passport-bridge 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +115 -54
- package/dist/activeProfile.js +122 -0
- package/dist/boundedFile.js +46 -0
- package/dist/boundedMcpFetch.js +98 -0
- package/dist/boundedResponse.js +56 -0
- package/dist/bridge.js +427 -107
- package/dist/bridgeConfig.js +19 -0
- package/dist/bridgeShutdown.js +30 -0
- package/dist/cli.js +195 -37
- package/dist/cliArgs.js +8 -1
- package/dist/cliClient.js +24 -46
- package/dist/cliConnect.js +161 -0
- package/dist/cliDeadline.js +27 -0
- package/dist/cliLogin.js +175 -0
- package/dist/cliOffline.js +119 -0
- package/dist/cliOutput.js +116 -0
- package/dist/cliPagination.js +55 -0
- package/dist/cliResult.js +111 -0
- package/dist/cliSession.js +163 -0
- package/dist/cliSupport.js +232 -0
- package/dist/completion.js +25 -10
- package/dist/credentialStorage.js +293 -0
- package/dist/credentials.js +364 -108
- package/dist/discover.js +60 -34
- package/dist/doctor.js +126 -16
- package/dist/legacyCliSecurity.js +26 -0
- package/dist/passport.js +169 -584
- package/dist/privateStableFile.js +170 -0
- package/dist/recoveryCleanup.js +17 -0
- package/dist/recoveryIdentity.js +80 -0
- package/dist/tokenWorkspace.js +5 -0
- package/dist/version.js +1 -1
- package/npm-shrinkwrap.json +1740 -0
- package/package.json +21 -7
- package/dist/discover.test.js +0 -51
package/dist/credentials.js
CHANGED
|
@@ -1,156 +1,412 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { closeSync, constants, fchmodSync, fstatSync, lstatSync, openSync, readFileSync, unlinkSync } from "node:fs";
|
|
2
2
|
import { join } from "node:path";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
3
|
+
import { credentialDir, enforceOwner, ensurePrivateDirectory, isMissing, syncDirectory, withCredentialStoreWriteLock as withStoreWriteLock, withProfileLock as withProfileLockInternal, writePrivateAtomic } from "./credentialStorage.js";
|
|
4
|
+
import { activeProfilePath, clearActiveProfileAtomic, prepareActiveProfileForSelection, readActiveProfile as readActiveProfileFile, readActiveProfileDocument, writeActiveProfileAtomic } from "./activeProfile.js";
|
|
5
5
|
const PROFILE_NAME = /^[A-Za-z0-9][A-Za-z0-9._@-]{0,79}$/;
|
|
6
6
|
const UNSAFE_PROFILE_KEYS = new Set(["__proto__", "prototype", "constructor"]);
|
|
7
|
-
|
|
7
|
+
const MAX_CREDENTIAL_BYTES = 1024 * 1024;
|
|
8
|
+
const ROTATION_JOURNAL_VERSION = 1;
|
|
9
|
+
/** Profile names become both JSON keys and lock-file names. */
|
|
8
10
|
export function assertProfileName(name) {
|
|
9
11
|
if (!PROFILE_NAME.test(name) || UNSAFE_PROFILE_KEYS.has(name)) {
|
|
10
12
|
throw new Error("Profile names must be 1-80 letters, numbers, dots, underscores, @ signs, or hyphens, starting with a letter or number.");
|
|
11
13
|
}
|
|
12
14
|
}
|
|
13
15
|
function dir() {
|
|
14
|
-
return
|
|
16
|
+
return credentialDir();
|
|
15
17
|
}
|
|
16
18
|
function file() {
|
|
17
19
|
return join(dir(), "credentials.json");
|
|
18
20
|
}
|
|
21
|
+
export function profileRotationJournalPath(name) {
|
|
22
|
+
assertProfileName(name);
|
|
23
|
+
return join(dir(), `.${name}.rotation.json`);
|
|
24
|
+
}
|
|
25
|
+
function emptyCreds() {
|
|
26
|
+
return Object.create(null);
|
|
27
|
+
}
|
|
28
|
+
function validatedProfile(value) {
|
|
29
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
30
|
+
return undefined;
|
|
31
|
+
const profile = value;
|
|
32
|
+
if (typeof profile.refreshToken !== "string" ||
|
|
33
|
+
!profile.refreshToken ||
|
|
34
|
+
typeof profile.endpoint !== "string" ||
|
|
35
|
+
!profile.endpoint ||
|
|
36
|
+
(profile.instanceId !== undefined && typeof profile.instanceId !== "string") ||
|
|
37
|
+
(profile.client !== undefined &&
|
|
38
|
+
(typeof profile.client !== "string" ||
|
|
39
|
+
!profile.client ||
|
|
40
|
+
profile.client.length > 40 ||
|
|
41
|
+
/[\u0000-\u001f\u007f]/.test(profile.client))) ||
|
|
42
|
+
(profile.target !== undefined &&
|
|
43
|
+
(typeof profile.target !== "string" ||
|
|
44
|
+
!profile.target ||
|
|
45
|
+
profile.target.length > 160 ||
|
|
46
|
+
/[\u0000-\u001f\u007f]/.test(profile.target)))) {
|
|
47
|
+
return undefined;
|
|
48
|
+
}
|
|
49
|
+
return {
|
|
50
|
+
refreshToken: profile.refreshToken,
|
|
51
|
+
endpoint: profile.endpoint,
|
|
52
|
+
...(profile.instanceId === undefined ? {} : { instanceId: profile.instanceId }),
|
|
53
|
+
...(profile.client === undefined ? {} : { client: profile.client }),
|
|
54
|
+
...(profile.target === undefined ? {} : { target: profile.target })
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
function parseCreds(raw) {
|
|
58
|
+
if (!raw.trim())
|
|
59
|
+
return emptyCreds();
|
|
60
|
+
let parsed;
|
|
61
|
+
try {
|
|
62
|
+
parsed = JSON.parse(raw);
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
throw new Error("Passport credential store is malformed; refusing to overwrite it.");
|
|
66
|
+
}
|
|
67
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
68
|
+
throw new Error("Passport credential store has an invalid shape; refusing to overwrite it.");
|
|
69
|
+
}
|
|
70
|
+
const creds = emptyCreds();
|
|
71
|
+
for (const [name, value] of Object.entries(parsed)) {
|
|
72
|
+
try {
|
|
73
|
+
assertProfileName(name);
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
throw new Error("Passport credential store contains an invalid profile; refusing to overwrite it.");
|
|
77
|
+
}
|
|
78
|
+
const profile = validatedProfile(value);
|
|
79
|
+
if (!profile) {
|
|
80
|
+
throw new Error("Passport credential store contains an invalid profile; refusing to overwrite it.");
|
|
81
|
+
}
|
|
82
|
+
creds[name] = profile;
|
|
83
|
+
}
|
|
84
|
+
return creds;
|
|
85
|
+
}
|
|
86
|
+
/** Reads through a no-follow descriptor, then validates the opened inode. */
|
|
87
|
+
function readCredentialDocument() {
|
|
88
|
+
if (!ensurePrivateDirectory(false))
|
|
89
|
+
return { kind: "missing" };
|
|
90
|
+
let pathStat;
|
|
91
|
+
try {
|
|
92
|
+
pathStat = lstatSync(file());
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
if (isMissing(error))
|
|
96
|
+
return { kind: "missing" };
|
|
97
|
+
throw error;
|
|
98
|
+
}
|
|
99
|
+
if (pathStat.isSymbolicLink() || !pathStat.isFile()) {
|
|
100
|
+
throw new Error("Passport credential store must be a regular file, not a symlink.");
|
|
101
|
+
}
|
|
102
|
+
enforceOwner(pathStat, "credential store");
|
|
103
|
+
if (pathStat.size > MAX_CREDENTIAL_BYTES) {
|
|
104
|
+
throw new Error("Passport credential store is unexpectedly large; refusing to read it.");
|
|
105
|
+
}
|
|
106
|
+
let descriptor;
|
|
107
|
+
try {
|
|
108
|
+
descriptor = openSync(file(), constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
109
|
+
const stat = fstatSync(descriptor);
|
|
110
|
+
if (!stat.isFile())
|
|
111
|
+
throw new Error("Passport credential store must be a regular file, not a symlink.");
|
|
112
|
+
if (stat.dev !== pathStat.dev || stat.ino !== pathStat.ino) {
|
|
113
|
+
throw new Error("Passport credential store changed while it was being opened; refusing to read it.");
|
|
114
|
+
}
|
|
115
|
+
enforceOwner(stat, "credential store");
|
|
116
|
+
if (stat.size > MAX_CREDENTIAL_BYTES) {
|
|
117
|
+
throw new Error("Passport credential store is unexpectedly large; refusing to read it.");
|
|
118
|
+
}
|
|
119
|
+
if (process.platform !== "win32")
|
|
120
|
+
fchmodSync(descriptor, 0o600);
|
|
121
|
+
return { kind: "present", creds: parseCreds(readFileSync(descriptor, "utf8")) };
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
if (isMissing(error))
|
|
125
|
+
return { kind: "missing" };
|
|
126
|
+
throw error;
|
|
127
|
+
}
|
|
128
|
+
finally {
|
|
129
|
+
if (descriptor !== undefined)
|
|
130
|
+
closeSync(descriptor);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
function readRotationJournal(name) {
|
|
134
|
+
if (!ensurePrivateDirectory(false))
|
|
135
|
+
return undefined;
|
|
136
|
+
const path = profileRotationJournalPath(name);
|
|
137
|
+
let pathStat;
|
|
138
|
+
try {
|
|
139
|
+
pathStat = lstatSync(path);
|
|
140
|
+
}
|
|
141
|
+
catch (error) {
|
|
142
|
+
if (isMissing(error))
|
|
143
|
+
return undefined;
|
|
144
|
+
throw error;
|
|
145
|
+
}
|
|
146
|
+
if (pathStat.isSymbolicLink() || !pathStat.isFile()) {
|
|
147
|
+
throw new Error("Passport credential rotation journal must be a regular file, not a symlink.");
|
|
148
|
+
}
|
|
149
|
+
enforceOwner(pathStat, "credential rotation journal");
|
|
150
|
+
if (pathStat.size > MAX_CREDENTIAL_BYTES) {
|
|
151
|
+
throw new Error("Passport credential rotation journal is unexpectedly large.");
|
|
152
|
+
}
|
|
153
|
+
let descriptor;
|
|
154
|
+
try {
|
|
155
|
+
descriptor = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
156
|
+
const stat = fstatSync(descriptor);
|
|
157
|
+
if (!stat.isFile() || stat.dev !== pathStat.dev || stat.ino !== pathStat.ino) {
|
|
158
|
+
throw new Error("Passport credential rotation journal changed while it was being opened.");
|
|
159
|
+
}
|
|
160
|
+
enforceOwner(stat, "credential rotation journal");
|
|
161
|
+
if (process.platform !== "win32")
|
|
162
|
+
fchmodSync(descriptor, 0o600);
|
|
163
|
+
const value = JSON.parse(readFileSync(descriptor, "utf8"));
|
|
164
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
165
|
+
throw new Error("Passport credential rotation journal is invalid.");
|
|
166
|
+
}
|
|
167
|
+
const parsed = value;
|
|
168
|
+
const next = validatedProfile(parsed.next);
|
|
169
|
+
if (parsed.version !== ROTATION_JOURNAL_VERSION ||
|
|
170
|
+
typeof parsed.previousRefreshToken !== "string" ||
|
|
171
|
+
!parsed.previousRefreshToken ||
|
|
172
|
+
!next) {
|
|
173
|
+
throw new Error("Passport credential rotation journal is invalid.");
|
|
174
|
+
}
|
|
175
|
+
return { version: ROTATION_JOURNAL_VERSION, previousRefreshToken: parsed.previousRefreshToken, next };
|
|
176
|
+
}
|
|
177
|
+
catch (error) {
|
|
178
|
+
if (isMissing(error))
|
|
179
|
+
return undefined;
|
|
180
|
+
if (error instanceof SyntaxError)
|
|
181
|
+
throw new Error("Passport credential rotation journal is malformed.");
|
|
182
|
+
throw error;
|
|
183
|
+
}
|
|
184
|
+
finally {
|
|
185
|
+
if (descriptor !== undefined)
|
|
186
|
+
closeSync(descriptor);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
/** Best-effort reads preserve the historical offline UX. Mutations use the
|
|
190
|
+
* strict reader below and never turn corruption into an empty store. */
|
|
19
191
|
export function readCreds() {
|
|
20
192
|
try {
|
|
21
|
-
const
|
|
22
|
-
|
|
23
|
-
return Object.create(null);
|
|
24
|
-
// A null prototype makes even a hand-edited legacy `__proto__` slot inert.
|
|
25
|
-
return Object.assign(Object.create(null), parsed);
|
|
193
|
+
const result = readCredentialDocument();
|
|
194
|
+
return result.kind === "missing" ? emptyCreds() : result.creds;
|
|
26
195
|
}
|
|
27
196
|
catch {
|
|
28
|
-
return
|
|
197
|
+
return emptyCreds();
|
|
29
198
|
}
|
|
30
199
|
}
|
|
200
|
+
function readCredsForMutation() {
|
|
201
|
+
const result = readCredentialDocument();
|
|
202
|
+
return result.kind === "missing" ? emptyCreds() : result.creds;
|
|
203
|
+
}
|
|
31
204
|
export function getProfile(name) {
|
|
32
205
|
assertProfileName(name);
|
|
33
206
|
return readCreds()[name];
|
|
34
207
|
}
|
|
208
|
+
/** Security-sensitive flows use the strict view before minting or rotating a
|
|
209
|
+
* credential. Corruption and unreadable paths must fail before a remote token
|
|
210
|
+
* is changed, not after it becomes impossible to persist. */
|
|
211
|
+
export function getProfileStrict(name) {
|
|
212
|
+
assertProfileName(name);
|
|
213
|
+
return readCredsForMutation()[name];
|
|
214
|
+
}
|
|
215
|
+
export function assertCredentialStoreMutationReady() {
|
|
216
|
+
void readCredsForMutation();
|
|
217
|
+
}
|
|
218
|
+
/** Persist a minted refresh-token child before acknowledging its access token.
|
|
219
|
+
* The journal is fsynced first, so a failed credential replace or killed process
|
|
220
|
+
* can recover the child without replaying its now-stale parent. */
|
|
221
|
+
export function persistProfileRotation(name, previousRefreshToken, next) {
|
|
222
|
+
assertProfileName(name);
|
|
223
|
+
const validatedNext = validatedProfile(next);
|
|
224
|
+
if (!previousRefreshToken || !validatedNext || validatedNext.refreshToken === previousRefreshToken) {
|
|
225
|
+
throw new Error("Passport credential rotation is invalid.");
|
|
226
|
+
}
|
|
227
|
+
const current = getProfileStrict(name);
|
|
228
|
+
if (!current)
|
|
229
|
+
throw new Error("Passport profile is unavailable for credential rotation.");
|
|
230
|
+
const existingJournal = readRotationJournal(name);
|
|
231
|
+
if (existingJournal &&
|
|
232
|
+
(existingJournal.previousRefreshToken !== previousRefreshToken ||
|
|
233
|
+
existingJournal.next.refreshToken !== validatedNext.refreshToken)) {
|
|
234
|
+
throw new Error("Passport profile has a different pending credential rotation.");
|
|
235
|
+
}
|
|
236
|
+
if (current.refreshToken === validatedNext.refreshToken) {
|
|
237
|
+
clearRotationJournal(name);
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
if (current.refreshToken !== previousRefreshToken) {
|
|
241
|
+
throw new Error("Passport profile advanced before credential rotation could be persisted.");
|
|
242
|
+
}
|
|
243
|
+
writeRotationJournal(name, {
|
|
244
|
+
version: ROTATION_JOURNAL_VERSION,
|
|
245
|
+
previousRefreshToken,
|
|
246
|
+
next: { ...current, ...validatedNext }
|
|
247
|
+
});
|
|
248
|
+
withStoreWriteLock(() => {
|
|
249
|
+
const creds = readCredsForMutation();
|
|
250
|
+
const latest = creds[name];
|
|
251
|
+
if (!latest)
|
|
252
|
+
throw new Error("Passport profile is unavailable for credential rotation.");
|
|
253
|
+
if (latest.refreshToken === validatedNext.refreshToken) {
|
|
254
|
+
clearRotationJournal(name);
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
if (latest.refreshToken !== previousRefreshToken) {
|
|
258
|
+
throw new Error("Passport profile advanced before credential rotation could be persisted.");
|
|
259
|
+
}
|
|
260
|
+
creds[name] = { ...latest, ...validatedNext };
|
|
261
|
+
writeCredsAtomic(creds);
|
|
262
|
+
clearRotationJournal(name);
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
/** Persist a rotating child against the endpoint currently stored for this
|
|
266
|
+
* profile. Interactive recovery may have replaced that endpoint after the
|
|
267
|
+
* TokenManager was constructed, so a captured startup endpoint is only a
|
|
268
|
+
* fallback and must never overwrite newer durable state. */
|
|
269
|
+
export function persistCurrentProfileRotation(name, previousRefreshToken, nextRefreshToken, fallbackEndpoint) {
|
|
270
|
+
const currentEndpoint = getProfileStrict(name)?.endpoint ?? fallbackEndpoint;
|
|
271
|
+
persistProfileRotation(name, previousRefreshToken, {
|
|
272
|
+
refreshToken: nextRefreshToken,
|
|
273
|
+
endpoint: currentEndpoint
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
/** Complete an interrupted profile rotation while the caller owns its profile
|
|
277
|
+
* lock. Conflicting state fails closed rather than choosing a stale parent. */
|
|
278
|
+
export function recoverProfileRotation(name) {
|
|
279
|
+
assertProfileName(name);
|
|
280
|
+
if (!readRotationJournal(name))
|
|
281
|
+
return getProfileStrict(name);
|
|
282
|
+
return withStoreWriteLock(() => {
|
|
283
|
+
const creds = readCredsForMutation();
|
|
284
|
+
const journal = readRotationJournal(name);
|
|
285
|
+
if (!journal)
|
|
286
|
+
return creds[name];
|
|
287
|
+
const current = creds[name];
|
|
288
|
+
if (!current)
|
|
289
|
+
throw new Error("Passport profile is unavailable for credential rotation recovery.");
|
|
290
|
+
if (current.refreshToken === journal.previousRefreshToken) {
|
|
291
|
+
creds[name] = { ...current, ...journal.next };
|
|
292
|
+
writeCredsAtomic(creds);
|
|
293
|
+
}
|
|
294
|
+
else if (current.refreshToken !== journal.next.refreshToken) {
|
|
295
|
+
throw new Error("Passport profile conflicts with its credential rotation recovery journal.");
|
|
296
|
+
}
|
|
297
|
+
clearRotationJournal(name);
|
|
298
|
+
return creds[name];
|
|
299
|
+
});
|
|
300
|
+
}
|
|
35
301
|
export function writeProfile(name, profile) {
|
|
36
302
|
assertProfileName(name);
|
|
37
303
|
withStoreWriteLock(() => {
|
|
38
|
-
const creds =
|
|
39
|
-
//
|
|
40
|
-
// profile instance id so repeated CLI processes and re-logins remain one
|
|
41
|
-
// independently revocable connection instead of creating phantom devices.
|
|
304
|
+
const creds = readCredsForMutation();
|
|
305
|
+
// Preserve the installation id when rotating only the token.
|
|
42
306
|
creds[name] = { ...creds[name], ...profile };
|
|
43
307
|
writeCredsAtomic(creds);
|
|
308
|
+
clearRotationJournal(name);
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
/** Replace a profile only if the credential that started an interactive
|
|
312
|
+
* recovery is still the live slot value. A bridge may be waiting for browser
|
|
313
|
+
* approval while another process rotates or reconnects the same profile; in
|
|
314
|
+
* that race the newer durable slot wins and the recovery must not overwrite
|
|
315
|
+
* it. */
|
|
316
|
+
export function replaceProfileAfterRecovery(name, previousRefreshToken, profile) {
|
|
317
|
+
assertProfileName(name);
|
|
318
|
+
if (!previousRefreshToken)
|
|
319
|
+
throw new Error("Passport recovery has no previous credential.");
|
|
320
|
+
withStoreWriteLock(() => {
|
|
321
|
+
const creds = readCredsForMutation();
|
|
322
|
+
const current = creds[name];
|
|
323
|
+
if (!current || current.refreshToken !== previousRefreshToken) {
|
|
324
|
+
throw new Error("Passport profile changed while recovery was waiting; refusing to overwrite the newer credential.");
|
|
325
|
+
}
|
|
326
|
+
creds[name] = { ...current, ...profile };
|
|
327
|
+
writeCredsAtomic(creds);
|
|
328
|
+
clearRotationJournal(name);
|
|
44
329
|
});
|
|
45
330
|
}
|
|
46
331
|
export function removeProfile(name) {
|
|
47
332
|
assertProfileName(name);
|
|
48
333
|
return withStoreWriteLock(() => {
|
|
49
|
-
const creds =
|
|
334
|
+
const creds = readCredsForMutation();
|
|
50
335
|
const existing = creds[name];
|
|
336
|
+
const active = readActiveProfileDocument(assertProfileName);
|
|
51
337
|
delete creds[name];
|
|
52
338
|
writeCredsAtomic(creds);
|
|
339
|
+
clearRotationJournal(name);
|
|
340
|
+
if (active.kind === "present" && active.profile === name) {
|
|
341
|
+
const remaining = Object.keys(creds).sort();
|
|
342
|
+
if (remaining.length === 1)
|
|
343
|
+
writeActiveProfileAtomic(remaining[0], assertProfileName);
|
|
344
|
+
else
|
|
345
|
+
clearActiveProfileAtomic();
|
|
346
|
+
}
|
|
53
347
|
return existing;
|
|
54
348
|
});
|
|
55
349
|
}
|
|
350
|
+
export { activeProfilePath };
|
|
351
|
+
/** Serialize refresh-token exchange across processes. A heartbeat keeps a live
|
|
352
|
+
* owner fresh; the random token makes release ownership-safe after recovery. */
|
|
353
|
+
export async function withProfileLock(name, fn) {
|
|
354
|
+
assertProfileName(name);
|
|
355
|
+
return withProfileLockInternal(name, fn);
|
|
356
|
+
}
|
|
357
|
+
/** Best-effort read for command resolution. A stale or damaged pointer must
|
|
358
|
+
* never make the CLI guess a credential; callers can fall back to the normal
|
|
359
|
+
* sole-profile rule or report ambiguity. */
|
|
360
|
+
export function readActiveProfile() {
|
|
361
|
+
return readActiveProfileFile(assertProfileName);
|
|
362
|
+
}
|
|
363
|
+
/** Make a stored profile the local default for interactive CLI commands. The
|
|
364
|
+
* selected name is not a credential and is stored separately from secrets. */
|
|
365
|
+
export function setActiveProfile(name) {
|
|
366
|
+
assertProfileName(name);
|
|
367
|
+
withStoreWriteLock(() => {
|
|
368
|
+
const creds = readCredsForMutation();
|
|
369
|
+
if (!creds[name])
|
|
370
|
+
throw new Error(`Passport profile "${name}" does not exist.`);
|
|
371
|
+
prepareActiveProfileForSelection();
|
|
372
|
+
writeActiveProfileAtomic(name, assertProfileName);
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
/** Clear the local selection, optionally only when it points at `name`. */
|
|
376
|
+
export function clearActiveProfile(name) {
|
|
377
|
+
if (name !== undefined)
|
|
378
|
+
assertProfileName(name);
|
|
379
|
+
withStoreWriteLock(() => {
|
|
380
|
+
const active = readActiveProfileDocument(assertProfileName);
|
|
381
|
+
if (active.kind === "missing" || (name !== undefined && active.profile !== name))
|
|
382
|
+
return;
|
|
383
|
+
clearActiveProfileAtomic();
|
|
384
|
+
});
|
|
385
|
+
}
|
|
56
386
|
export function credsPath() {
|
|
57
387
|
return file();
|
|
58
388
|
}
|
|
59
|
-
/**
|
|
60
|
-
* Cross-process mutex for a profile's token exchange. The refresh token is
|
|
61
|
-
* single-use (it rotates on every exchange), and one profile can back several
|
|
62
|
-
* live bridge processes at once — Cursor spawns one MCP process per window —
|
|
63
|
-
* so exchanges must serialize ACROSS processes, not just within one. mkdir is
|
|
64
|
-
* atomic on every platform; a lock older than STALE_MS belongs to a dead
|
|
65
|
-
* process and is stolen. A caller that cannot acquire the lock within the
|
|
66
|
-
* patience window fails closed instead of risking refresh-token replay.
|
|
67
|
-
*/
|
|
68
|
-
const LOCK_STALE_MS = 30_000;
|
|
69
|
-
const LOCK_PATIENCE_MS = 15_000;
|
|
70
|
-
/** The JSON document is shared by every profile. This short global mutation
|
|
71
|
-
* lock prevents simultaneous rotations for different profiles from losing one
|
|
72
|
-
* another even though token exchanges use separate per-profile locks. */
|
|
73
|
-
function withStoreWriteLock(fn) {
|
|
74
|
-
const lockDir = join(dir(), ".credentials-write.lock");
|
|
75
|
-
mkdirSync(dir(), { recursive: true, mode: 0o700 });
|
|
76
|
-
const started = Date.now();
|
|
77
|
-
for (;;) {
|
|
78
|
-
try {
|
|
79
|
-
mkdirSync(lockDir);
|
|
80
|
-
break;
|
|
81
|
-
}
|
|
82
|
-
catch {
|
|
83
|
-
try {
|
|
84
|
-
if (Date.now() - statSync(lockDir).mtimeMs > LOCK_STALE_MS) {
|
|
85
|
-
rmSync(lockDir, { recursive: true, force: true });
|
|
86
|
-
continue;
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
catch {
|
|
90
|
-
continue;
|
|
91
|
-
}
|
|
92
|
-
if (Date.now() - started > LOCK_PATIENCE_MS)
|
|
93
|
-
throw new Error("Timed out waiting to update Passport credentials.");
|
|
94
|
-
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 25 + Math.floor(Math.random() * 25));
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
try {
|
|
98
|
-
return fn();
|
|
99
|
-
}
|
|
100
|
-
finally {
|
|
101
|
-
rmSync(lockDir, { recursive: true, force: true });
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
389
|
function writeCredsAtomic(creds) {
|
|
105
|
-
|
|
106
|
-
const tmp = join(dir(), `.credentials.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
|
|
107
|
-
try {
|
|
108
|
-
writeFileSync(tmp, JSON.stringify(creds, null, 2), { mode: 0o600 });
|
|
109
|
-
renameSync(tmp, file());
|
|
110
|
-
try {
|
|
111
|
-
chmodSync(file(), 0o600);
|
|
112
|
-
}
|
|
113
|
-
catch {
|
|
114
|
-
/* best effort on platforms without chmod */
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
finally {
|
|
118
|
-
rmSync(tmp, { force: true });
|
|
119
|
-
}
|
|
390
|
+
writePrivateAtomic(file(), ".credentials", JSON.stringify(creds, null, 2), "credential store");
|
|
120
391
|
}
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
const
|
|
126
|
-
let
|
|
127
|
-
for (;;) {
|
|
128
|
-
try {
|
|
129
|
-
mkdirSync(lockDir);
|
|
130
|
-
acquired = true;
|
|
131
|
-
break; // acquired
|
|
132
|
-
}
|
|
133
|
-
catch {
|
|
134
|
-
try {
|
|
135
|
-
const age = Date.now() - statSync(lockDir).mtimeMs;
|
|
136
|
-
if (age > LOCK_STALE_MS) {
|
|
137
|
-
rmSync(lockDir, { recursive: true, force: true });
|
|
138
|
-
continue;
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
catch {
|
|
142
|
-
continue; // lock vanished between attempts — retry immediately
|
|
143
|
-
}
|
|
144
|
-
if (Date.now() - started > LOCK_PATIENCE_MS)
|
|
145
|
-
throw new Error(`Timed out waiting for Passport profile "${name}".`);
|
|
146
|
-
await new Promise((r) => setTimeout(r, 100 + Math.floor(Math.random() * 100)));
|
|
147
|
-
}
|
|
148
|
-
}
|
|
392
|
+
function writeRotationJournal(name, journal) {
|
|
393
|
+
writePrivateAtomic(profileRotationJournalPath(name), `.${name}.rotation`, JSON.stringify(journal), "credential rotation journal");
|
|
394
|
+
}
|
|
395
|
+
function clearRotationJournal(name) {
|
|
396
|
+
const path = profileRotationJournalPath(name);
|
|
397
|
+
let stat;
|
|
149
398
|
try {
|
|
150
|
-
|
|
399
|
+
stat = lstatSync(path);
|
|
151
400
|
}
|
|
152
|
-
|
|
153
|
-
if (
|
|
154
|
-
|
|
401
|
+
catch (error) {
|
|
402
|
+
if (isMissing(error))
|
|
403
|
+
return;
|
|
404
|
+
throw error;
|
|
405
|
+
}
|
|
406
|
+
if (stat.isSymbolicLink() || !stat.isFile()) {
|
|
407
|
+
throw new Error("Passport credential rotation journal must be a regular file, not a symlink.");
|
|
155
408
|
}
|
|
409
|
+
enforceOwner(stat, "credential rotation journal");
|
|
410
|
+
unlinkSync(path);
|
|
411
|
+
syncDirectory();
|
|
156
412
|
}
|