-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathextension.ts
More file actions
290 lines (257 loc) · 9.76 KB
/
Copy pathextension.ts
File metadata and controls
290 lines (257 loc) · 9.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
/**
* Git ID Switcher - VS Code Extension Entry Point
* @author Null;Variant
* @license MIT
*/
import * as vscode from 'vscode';
import { Identity, getIdentitiesWithValidation, invalidateIdentityCache } from '../identity/identity';
import { createStatusBar, IdentityStatusBar } from '../ui/identityStatusBar';
import { showDocumentation } from '../ui/documentationPublic';
import { securityLogger } from '../security/securityLogger';
import { getUserSafeMessage, isFatalError } from './errors';
import { initializeWorkspaceTrust } from './workspaceTrust';
import { tryRestoreSavedIdentity, tryDetectFromGit, tryDetectFromSsh, applyDetectedIdentity } from '../services/detection';
import { selectIdentityCommand, showCurrentIdentityCommand, showWelcomeNotification, handleDeleteIdentity, resolveSyncMismatchCommand } from '../commands/handlers';
import { checkSync } from './syncChecker';
import { extensionLogger } from '../logging/extensionLogger';
// Global state
let statusBar: IdentityStatusBar;
let currentIdentity: Identity | undefined;
let initializeCancellation: vscode.CancellationTokenSource | undefined;
let syncCheckDebounceTimer: ReturnType<typeof setTimeout> | undefined;
/** Debounce delay for sync check on focus return (ms) */
const SYNC_CHECK_DEBOUNCE_MS = 500;
// State accessors for dependency injection
const getCurrentIdentity = (): Identity | undefined => currentIdentity;
const setCurrentIdentity = (identity: Identity): void => { currentIdentity = identity; };
/**
* Extension activation
*/
export async function activate(context: vscode.ExtensionContext): Promise<void> {
extensionLogger.info('Activating...');
// SECURITY: Log files written only to extension's secure storage
securityLogger.initializeWithContext(context.globalStorageUri.fsPath);
securityLogger.logActivation();
statusBar = createStatusBar();
context.subscriptions.push(statusBar);
const selectCommand = vscode.commands.registerCommand(
'git-id-switcher.selectIdentity',
() => selectIdentityCommand(context, statusBar, getCurrentIdentity, setCurrentIdentity)
);
const showCurrentCommand = vscode.commands.registerCommand(
'git-id-switcher.showCurrentIdentity',
() => showCurrentIdentityCommand(getCurrentIdentity)
);
const showDocsCommand = vscode.commands.registerCommand(
'git-id-switcher.showDocumentation',
() => showDocumentation(context)
);
const deleteCommand = vscode.commands.registerCommand(
'git-id-switcher.deleteIdentity',
() => handleDeleteIdentity(context, statusBar)
);
const resolveSyncCommand = vscode.commands.registerCommand(
'git-id-switcher.resolveSyncMismatch',
() => resolveSyncMismatchCommand(context, statusBar, getCurrentIdentity, setCurrentIdentity)
);
context.subscriptions.push(selectCommand, showCurrentCommand, showDocsCommand, deleteCommand, resolveSyncCommand);
// SECURITY: Check workspace trust before initializing sensitive operations
const isTrusted = initializeWorkspaceTrust(context, async () => {
await performTrustedInitialization(context);
});
if (isTrusted) {
await performTrustedInitialization(context);
} else {
statusBar.setNoIdentity();
extensionLogger.info('Activated in restricted mode (untrusted workspace)');
return;
}
extensionLogger.info('Activated');
}
/**
* Run sync check for the current identity and update the status bar.
*
* Reads `syncCheck.enabled` from configuration. When disabled, restores
* the status bar to normal (synced) state to clear any lingering warning.
*
* @sideeffect Executes `git config --local` via checkSync()
*/
async function performSyncCheck(): Promise<void> {
if (!currentIdentity) {
return;
}
const config = vscode.workspace.getConfiguration('gitIdSwitcher');
if (!config.get<boolean>('syncCheck.enabled', true)) {
// Clear any existing warning when sync check is disabled
statusBar.setSyncState({ state: 'synced', mismatches: [] });
return;
}
try {
const result = await checkSync(currentIdentity);
statusBar.setSyncState(result);
} catch {
// Non-fatal: sync check failure should not disrupt the extension
extensionLogger.debug('Sync check failed silently');
}
}
/**
* Debounced sync check for focus-return events.
* Prevents multiple rapid invocations when the window focus changes quickly.
*/
function debouncedSyncCheck(): void {
if (syncCheckDebounceTimer !== undefined) {
clearTimeout(syncCheckDebounceTimer);
}
syncCheckDebounceTimer = setTimeout(() => {
syncCheckDebounceTimer = undefined;
performSyncCheck().catch(error => {
const safeMessage = getUserSafeMessage(error);
extensionLogger.debug(`Debounced sync check failed: ${safeMessage}`);
});
}, SYNC_CHECK_DEBOUNCE_MS);
}
/**
* Perform initialization that requires workspace trust.
* SECURITY: Only call after confirming workspace is trusted.
*/
async function performTrustedInitialization(context: vscode.ExtensionContext): Promise<void> {
await initializeState(context);
// Run initial sync check after state is loaded
await performSyncCheck();
securityLogger.storeConfigSnapshot();
context.subscriptions.push(
vscode.workspace.onDidChangeWorkspaceFolders(() => {
initializeState(context)
.then(() => performSyncCheck())
.catch(error => {
const safeMessage = getUserSafeMessage(error);
extensionLogger.error(`Failed to initialize after workspace change: ${safeMessage}`);
if (isFatalError(error)) {
vscode.window.showErrorMessage(
vscode.l10n.t('Failed to initialize Git ID Switcher: {0}', safeMessage)
);
}
});
}),
vscode.workspace.onDidChangeConfiguration((e: vscode.ConfigurationChangeEvent) => {
if (!e.affectsConfiguration('gitIdSwitcher')) {
return;
}
try {
const newSnapshot = securityLogger.createConfigSnapshot();
const changes = securityLogger.detectConfigChanges(newSnapshot);
if (changes.length > 0) {
securityLogger.logConfigChanges(changes);
}
securityLogger.storeConfigSnapshot();
} catch (error) {
extensionLogger.error(`Error handling config change: ${getUserSafeMessage(error)}`);
try {
securityLogger.storeConfigSnapshot();
} catch (snapshotError) {
extensionLogger.error(`Error storing config snapshot: ${getUserSafeMessage(snapshotError)}`);
}
}
invalidateIdentityCache();
initializeState(context)
.then(() => performSyncCheck())
.catch(error => {
const safeMessage = getUserSafeMessage(error);
extensionLogger.error(`Failed to initialize after config change: ${safeMessage}`);
if (isFatalError(error)) {
vscode.window.showErrorMessage(
vscode.l10n.t('Failed to initialize Git ID Switcher: {0}', safeMessage)
);
}
});
}),
// Sync check on window focus return
vscode.window.onDidChangeWindowState((state: vscode.WindowState) => {
if (!state.focused) {
return;
}
const config = vscode.workspace.getConfiguration('gitIdSwitcher');
if (!config.get<boolean>('syncCheck.onFocusReturn', true)) {
return;
}
debouncedSyncCheck();
}),
);
}
/**
* Extension deactivation
*/
export function deactivate(): void {
if (syncCheckDebounceTimer !== undefined) {
clearTimeout(syncCheckDebounceTimer);
syncCheckDebounceTimer = undefined;
}
if (initializeCancellation) {
initializeCancellation.cancel();
initializeCancellation.dispose();
initializeCancellation = undefined;
}
securityLogger.logDeactivation();
securityLogger.dispose();
extensionLogger.info('Deactivated');
extensionLogger.dispose();
}
/**
* Initialize state from saved settings and current Git config
*/
async function initializeState(context: vscode.ExtensionContext): Promise<void> {
if (initializeCancellation) {
initializeCancellation.cancel();
initializeCancellation.dispose();
}
const tokenSource = new vscode.CancellationTokenSource();
initializeCancellation = tokenSource;
const token = tokenSource.token;
try {
const identities = getIdentitiesWithValidation();
if (identities.length === 0) {
statusBar.setNoIdentity();
return;
}
// First-run welcome notification
const hasShownWelcome = context.globalState.get<boolean>('hasShownWelcome', false);
if (!hasShownWelcome && identities.length === 1 && identities[0].id === 'example') {
void showWelcomeNotification();
await context.globalState.update('hasShownWelcome', true);
}
const savedResult = tryRestoreSavedIdentity(context);
if (savedResult.found) {
await applyDetectedIdentity(savedResult.identity, context, false, statusBar, setCurrentIdentity);
return;
}
const gitResult = await tryDetectFromGit(token);
if (gitResult === 'cancelled') return;
if (gitResult.found) {
await applyDetectedIdentity(gitResult.identity, context, true, statusBar, setCurrentIdentity);
return;
}
const sshResult = await tryDetectFromSsh(token);
if (sshResult === 'cancelled') return;
if (sshResult.found) {
await applyDetectedIdentity(sshResult.identity, context, true, statusBar, setCurrentIdentity);
return;
}
statusBar.setNoIdentity();
} catch (error) {
if (token.isCancellationRequested) {
extensionLogger.debug('Initialization cancelled (caught in error handler)');
return;
}
const safeMessage = getUserSafeMessage(error);
extensionLogger.error(`Failed to initialize: ${safeMessage}`);
statusBar.setNoIdentity();
if (isFatalError(error)) {
throw error;
}
} finally {
if (initializeCancellation === tokenSource) {
initializeCancellation = undefined;
}
tokenSource.dispose();
}
}