passport-bridge 0.7.0 → 0.7.1
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 +80 -48
- package/dist/boundedFile.js +46 -0
- package/dist/boundedMcpFetch.js +98 -0
- package/dist/boundedResponse.js +56 -0
- package/dist/bridge.js +426 -99
- package/dist/bridgeConfig.js +19 -0
- package/dist/bridgeShutdown.js +30 -0
- package/dist/cli.js +193 -37
- package/dist/cliArgs.js +2 -0
- package/dist/cliClient.js +24 -46
- package/dist/cliDeadline.js +27 -0
- package/dist/cliLogin.js +103 -0
- package/dist/cliOffline.js +53 -0
- package/dist/cliOutput.js +106 -0
- package/dist/cliPagination.js +55 -0
- package/dist/cliResult.js +87 -0
- package/dist/cliSession.js +163 -0
- package/dist/cliSupport.js +191 -0
- package/dist/completion.js +22 -9
- package/dist/credentials.js +584 -83
- package/dist/discover.js +60 -34
- package/dist/doctor.js +56 -13
- package/dist/legacyCliSecurity.js +26 -0
- package/dist/passport.js +87 -469
- package/dist/privateStableFile.js +170 -0
- package/dist/recoveryCleanup.js +17 -0
- package/dist/recoveryIdentity.js +80 -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,10 +1,15 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { chmodSync, closeSync, constants, fchmodSync, fstatSync, fsyncSync, lstatSync, linkSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, utimesSync, writeFileSync } from "node:fs";
|
|
1
3
|
import { homedir } from "node:os";
|
|
2
4
|
import { join } from "node:path";
|
|
3
|
-
import { mkdirSync, readFileSync, writeFileSync, chmodSync, rmSync, statSync, renameSync } from "node:fs";
|
|
4
|
-
import { randomBytes } from "node:crypto";
|
|
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 LOCK_STALE_MS = 30_000;
|
|
9
|
+
const LOCK_PATIENCE_MS = LOCK_STALE_MS + 5_000;
|
|
10
|
+
const LOCK_HEARTBEAT_MS = 5_000;
|
|
11
|
+
const ROTATION_JOURNAL_VERSION = 1;
|
|
12
|
+
/** Profile names become both JSON keys and lock-file names. */
|
|
8
13
|
export function assertProfileName(name) {
|
|
9
14
|
if (!PROFILE_NAME.test(name) || UNSAFE_PROFILE_KEYS.has(name)) {
|
|
10
15
|
throw new Error("Profile names must be 1-80 letters, numbers, dots, underscores, @ signs, or hyphens, starting with a letter or number.");
|
|
@@ -16,141 +21,637 @@ function dir() {
|
|
|
16
21
|
function file() {
|
|
17
22
|
return join(dir(), "credentials.json");
|
|
18
23
|
}
|
|
24
|
+
export function profileRotationJournalPath(name) {
|
|
25
|
+
assertProfileName(name);
|
|
26
|
+
return join(dir(), `.${name}.rotation.json`);
|
|
27
|
+
}
|
|
28
|
+
function emptyCreds() {
|
|
29
|
+
return Object.create(null);
|
|
30
|
+
}
|
|
31
|
+
function isMissing(error) {
|
|
32
|
+
return error.code === "ENOENT";
|
|
33
|
+
}
|
|
34
|
+
function enforceOwner(stat, label) {
|
|
35
|
+
if (typeof process.getuid === "function" && stat.uid !== process.getuid()) {
|
|
36
|
+
throw new Error(`Passport ${label} is owned by another account.`);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
function validatedProfile(value) {
|
|
40
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
41
|
+
return undefined;
|
|
42
|
+
const profile = value;
|
|
43
|
+
if (typeof profile.refreshToken !== "string" ||
|
|
44
|
+
!profile.refreshToken ||
|
|
45
|
+
typeof profile.endpoint !== "string" ||
|
|
46
|
+
!profile.endpoint ||
|
|
47
|
+
(profile.instanceId !== undefined && typeof profile.instanceId !== "string") ||
|
|
48
|
+
(profile.client !== undefined &&
|
|
49
|
+
(typeof profile.client !== "string" ||
|
|
50
|
+
!profile.client ||
|
|
51
|
+
profile.client.length > 40 ||
|
|
52
|
+
/[\u0000-\u001f\u007f]/.test(profile.client))) ||
|
|
53
|
+
(profile.target !== undefined &&
|
|
54
|
+
(typeof profile.target !== "string" ||
|
|
55
|
+
!profile.target ||
|
|
56
|
+
profile.target.length > 160 ||
|
|
57
|
+
/[\u0000-\u001f\u007f]/.test(profile.target)))) {
|
|
58
|
+
return undefined;
|
|
59
|
+
}
|
|
60
|
+
return {
|
|
61
|
+
refreshToken: profile.refreshToken,
|
|
62
|
+
endpoint: profile.endpoint,
|
|
63
|
+
...(profile.instanceId === undefined ? {} : { instanceId: profile.instanceId }),
|
|
64
|
+
...(profile.client === undefined ? {} : { client: profile.client }),
|
|
65
|
+
...(profile.target === undefined ? {} : { target: profile.target })
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
/** Create or repair the owner-only credential directory without following a
|
|
69
|
+
* symlink at the security boundary. */
|
|
70
|
+
function ensurePrivateDirectory(create) {
|
|
71
|
+
try {
|
|
72
|
+
const stat = lstatSync(dir());
|
|
73
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) {
|
|
74
|
+
throw new Error("Passport credential directory must be a regular directory, not a symlink.");
|
|
75
|
+
}
|
|
76
|
+
enforceOwner(stat, "credential directory");
|
|
77
|
+
if (process.platform !== "win32")
|
|
78
|
+
chmodSync(dir(), 0o700);
|
|
79
|
+
return true;
|
|
80
|
+
}
|
|
81
|
+
catch (error) {
|
|
82
|
+
if (!isMissing(error))
|
|
83
|
+
throw error;
|
|
84
|
+
if (!create)
|
|
85
|
+
return false;
|
|
86
|
+
mkdirSync(dir(), { recursive: true, mode: 0o700 });
|
|
87
|
+
const stat = lstatSync(dir());
|
|
88
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) {
|
|
89
|
+
throw new Error("Passport credential directory must be a regular directory, not a symlink.");
|
|
90
|
+
}
|
|
91
|
+
enforceOwner(stat, "credential directory");
|
|
92
|
+
if (process.platform !== "win32")
|
|
93
|
+
chmodSync(dir(), 0o700);
|
|
94
|
+
return true;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
function parseCreds(raw) {
|
|
98
|
+
if (!raw.trim())
|
|
99
|
+
return emptyCreds();
|
|
100
|
+
let parsed;
|
|
101
|
+
try {
|
|
102
|
+
parsed = JSON.parse(raw);
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
throw new Error("Passport credential store is malformed; refusing to overwrite it.");
|
|
106
|
+
}
|
|
107
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
108
|
+
throw new Error("Passport credential store has an invalid shape; refusing to overwrite it.");
|
|
109
|
+
}
|
|
110
|
+
const creds = emptyCreds();
|
|
111
|
+
for (const [name, value] of Object.entries(parsed)) {
|
|
112
|
+
try {
|
|
113
|
+
assertProfileName(name);
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
throw new Error("Passport credential store contains an invalid profile; refusing to overwrite it.");
|
|
117
|
+
}
|
|
118
|
+
const profile = validatedProfile(value);
|
|
119
|
+
if (!profile) {
|
|
120
|
+
throw new Error("Passport credential store contains an invalid profile; refusing to overwrite it.");
|
|
121
|
+
}
|
|
122
|
+
creds[name] = profile;
|
|
123
|
+
}
|
|
124
|
+
return creds;
|
|
125
|
+
}
|
|
126
|
+
/** Reads through a no-follow descriptor, then validates the opened inode. */
|
|
127
|
+
function readCredentialDocument() {
|
|
128
|
+
if (!ensurePrivateDirectory(false))
|
|
129
|
+
return { kind: "missing" };
|
|
130
|
+
let pathStat;
|
|
131
|
+
try {
|
|
132
|
+
pathStat = lstatSync(file());
|
|
133
|
+
}
|
|
134
|
+
catch (error) {
|
|
135
|
+
if (isMissing(error))
|
|
136
|
+
return { kind: "missing" };
|
|
137
|
+
throw error;
|
|
138
|
+
}
|
|
139
|
+
if (pathStat.isSymbolicLink() || !pathStat.isFile()) {
|
|
140
|
+
throw new Error("Passport credential store must be a regular file, not a symlink.");
|
|
141
|
+
}
|
|
142
|
+
enforceOwner(pathStat, "credential store");
|
|
143
|
+
if (pathStat.size > MAX_CREDENTIAL_BYTES) {
|
|
144
|
+
throw new Error("Passport credential store is unexpectedly large; refusing to read it.");
|
|
145
|
+
}
|
|
146
|
+
let descriptor;
|
|
147
|
+
try {
|
|
148
|
+
descriptor = openSync(file(), constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
149
|
+
const stat = fstatSync(descriptor);
|
|
150
|
+
if (!stat.isFile())
|
|
151
|
+
throw new Error("Passport credential store must be a regular file, not a symlink.");
|
|
152
|
+
if (stat.dev !== pathStat.dev || stat.ino !== pathStat.ino) {
|
|
153
|
+
throw new Error("Passport credential store changed while it was being opened; refusing to read it.");
|
|
154
|
+
}
|
|
155
|
+
enforceOwner(stat, "credential store");
|
|
156
|
+
if (stat.size > MAX_CREDENTIAL_BYTES) {
|
|
157
|
+
throw new Error("Passport credential store is unexpectedly large; refusing to read it.");
|
|
158
|
+
}
|
|
159
|
+
if (process.platform !== "win32")
|
|
160
|
+
fchmodSync(descriptor, 0o600);
|
|
161
|
+
return { kind: "present", creds: parseCreds(readFileSync(descriptor, "utf8")) };
|
|
162
|
+
}
|
|
163
|
+
catch (error) {
|
|
164
|
+
if (isMissing(error))
|
|
165
|
+
return { kind: "missing" };
|
|
166
|
+
throw error;
|
|
167
|
+
}
|
|
168
|
+
finally {
|
|
169
|
+
if (descriptor !== undefined)
|
|
170
|
+
closeSync(descriptor);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
function readRotationJournal(name) {
|
|
174
|
+
if (!ensurePrivateDirectory(false))
|
|
175
|
+
return undefined;
|
|
176
|
+
const path = profileRotationJournalPath(name);
|
|
177
|
+
let pathStat;
|
|
178
|
+
try {
|
|
179
|
+
pathStat = lstatSync(path);
|
|
180
|
+
}
|
|
181
|
+
catch (error) {
|
|
182
|
+
if (isMissing(error))
|
|
183
|
+
return undefined;
|
|
184
|
+
throw error;
|
|
185
|
+
}
|
|
186
|
+
if (pathStat.isSymbolicLink() || !pathStat.isFile()) {
|
|
187
|
+
throw new Error("Passport credential rotation journal must be a regular file, not a symlink.");
|
|
188
|
+
}
|
|
189
|
+
enforceOwner(pathStat, "credential rotation journal");
|
|
190
|
+
if (pathStat.size > MAX_CREDENTIAL_BYTES) {
|
|
191
|
+
throw new Error("Passport credential rotation journal is unexpectedly large.");
|
|
192
|
+
}
|
|
193
|
+
let descriptor;
|
|
194
|
+
try {
|
|
195
|
+
descriptor = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
196
|
+
const stat = fstatSync(descriptor);
|
|
197
|
+
if (!stat.isFile() || stat.dev !== pathStat.dev || stat.ino !== pathStat.ino) {
|
|
198
|
+
throw new Error("Passport credential rotation journal changed while it was being opened.");
|
|
199
|
+
}
|
|
200
|
+
enforceOwner(stat, "credential rotation journal");
|
|
201
|
+
if (process.platform !== "win32")
|
|
202
|
+
fchmodSync(descriptor, 0o600);
|
|
203
|
+
const value = JSON.parse(readFileSync(descriptor, "utf8"));
|
|
204
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
205
|
+
throw new Error("Passport credential rotation journal is invalid.");
|
|
206
|
+
}
|
|
207
|
+
const parsed = value;
|
|
208
|
+
const next = validatedProfile(parsed.next);
|
|
209
|
+
if (parsed.version !== ROTATION_JOURNAL_VERSION ||
|
|
210
|
+
typeof parsed.previousRefreshToken !== "string" ||
|
|
211
|
+
!parsed.previousRefreshToken ||
|
|
212
|
+
!next) {
|
|
213
|
+
throw new Error("Passport credential rotation journal is invalid.");
|
|
214
|
+
}
|
|
215
|
+
return { version: ROTATION_JOURNAL_VERSION, previousRefreshToken: parsed.previousRefreshToken, next };
|
|
216
|
+
}
|
|
217
|
+
catch (error) {
|
|
218
|
+
if (isMissing(error))
|
|
219
|
+
return undefined;
|
|
220
|
+
if (error instanceof SyntaxError)
|
|
221
|
+
throw new Error("Passport credential rotation journal is malformed.");
|
|
222
|
+
throw error;
|
|
223
|
+
}
|
|
224
|
+
finally {
|
|
225
|
+
if (descriptor !== undefined)
|
|
226
|
+
closeSync(descriptor);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
/** Best-effort reads preserve the historical offline UX. Mutations use the
|
|
230
|
+
* strict reader below and never turn corruption into an empty store. */
|
|
19
231
|
export function readCreds() {
|
|
20
232
|
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);
|
|
233
|
+
const result = readCredentialDocument();
|
|
234
|
+
return result.kind === "missing" ? emptyCreds() : result.creds;
|
|
26
235
|
}
|
|
27
236
|
catch {
|
|
28
|
-
return
|
|
237
|
+
return emptyCreds();
|
|
29
238
|
}
|
|
30
239
|
}
|
|
240
|
+
function readCredsForMutation() {
|
|
241
|
+
const result = readCredentialDocument();
|
|
242
|
+
return result.kind === "missing" ? emptyCreds() : result.creds;
|
|
243
|
+
}
|
|
31
244
|
export function getProfile(name) {
|
|
32
245
|
assertProfileName(name);
|
|
33
246
|
return readCreds()[name];
|
|
34
247
|
}
|
|
248
|
+
/** Security-sensitive flows use the strict view before minting or rotating a
|
|
249
|
+
* credential. Corruption and unreadable paths must fail before a remote token
|
|
250
|
+
* is changed, not after it becomes impossible to persist. */
|
|
251
|
+
export function getProfileStrict(name) {
|
|
252
|
+
assertProfileName(name);
|
|
253
|
+
return readCredsForMutation()[name];
|
|
254
|
+
}
|
|
255
|
+
export function assertCredentialStoreMutationReady() {
|
|
256
|
+
void readCredsForMutation();
|
|
257
|
+
}
|
|
258
|
+
/** Persist a minted refresh-token child before acknowledging its access token.
|
|
259
|
+
* The journal is fsynced first, so a failed credential replace or killed process
|
|
260
|
+
* can recover the child without replaying its now-stale parent. */
|
|
261
|
+
export function persistProfileRotation(name, previousRefreshToken, next) {
|
|
262
|
+
assertProfileName(name);
|
|
263
|
+
const validatedNext = validatedProfile(next);
|
|
264
|
+
if (!previousRefreshToken || !validatedNext || validatedNext.refreshToken === previousRefreshToken) {
|
|
265
|
+
throw new Error("Passport credential rotation is invalid.");
|
|
266
|
+
}
|
|
267
|
+
const current = getProfileStrict(name);
|
|
268
|
+
if (!current)
|
|
269
|
+
throw new Error("Passport profile is unavailable for credential rotation.");
|
|
270
|
+
const existingJournal = readRotationJournal(name);
|
|
271
|
+
if (existingJournal &&
|
|
272
|
+
(existingJournal.previousRefreshToken !== previousRefreshToken ||
|
|
273
|
+
existingJournal.next.refreshToken !== validatedNext.refreshToken)) {
|
|
274
|
+
throw new Error("Passport profile has a different pending credential rotation.");
|
|
275
|
+
}
|
|
276
|
+
if (current.refreshToken === validatedNext.refreshToken) {
|
|
277
|
+
clearRotationJournal(name);
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
if (current.refreshToken !== previousRefreshToken) {
|
|
281
|
+
throw new Error("Passport profile advanced before credential rotation could be persisted.");
|
|
282
|
+
}
|
|
283
|
+
writeRotationJournal(name, {
|
|
284
|
+
version: ROTATION_JOURNAL_VERSION,
|
|
285
|
+
previousRefreshToken,
|
|
286
|
+
next: { ...current, ...validatedNext }
|
|
287
|
+
});
|
|
288
|
+
withStoreWriteLock(() => {
|
|
289
|
+
const creds = readCredsForMutation();
|
|
290
|
+
const latest = creds[name];
|
|
291
|
+
if (!latest)
|
|
292
|
+
throw new Error("Passport profile is unavailable for credential rotation.");
|
|
293
|
+
if (latest.refreshToken === validatedNext.refreshToken) {
|
|
294
|
+
clearRotationJournal(name);
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
if (latest.refreshToken !== previousRefreshToken) {
|
|
298
|
+
throw new Error("Passport profile advanced before credential rotation could be persisted.");
|
|
299
|
+
}
|
|
300
|
+
creds[name] = { ...latest, ...validatedNext };
|
|
301
|
+
writeCredsAtomic(creds);
|
|
302
|
+
clearRotationJournal(name);
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
/** Persist a rotating child against the endpoint currently stored for this
|
|
306
|
+
* profile. Interactive recovery may have replaced that endpoint after the
|
|
307
|
+
* TokenManager was constructed, so a captured startup endpoint is only a
|
|
308
|
+
* fallback and must never overwrite newer durable state. */
|
|
309
|
+
export function persistCurrentProfileRotation(name, previousRefreshToken, nextRefreshToken, fallbackEndpoint) {
|
|
310
|
+
const currentEndpoint = getProfileStrict(name)?.endpoint ?? fallbackEndpoint;
|
|
311
|
+
persistProfileRotation(name, previousRefreshToken, {
|
|
312
|
+
refreshToken: nextRefreshToken,
|
|
313
|
+
endpoint: currentEndpoint
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
/** Complete an interrupted profile rotation while the caller owns its profile
|
|
317
|
+
* lock. Conflicting state fails closed rather than choosing a stale parent. */
|
|
318
|
+
export function recoverProfileRotation(name) {
|
|
319
|
+
assertProfileName(name);
|
|
320
|
+
if (!readRotationJournal(name))
|
|
321
|
+
return getProfileStrict(name);
|
|
322
|
+
return withStoreWriteLock(() => {
|
|
323
|
+
const creds = readCredsForMutation();
|
|
324
|
+
const journal = readRotationJournal(name);
|
|
325
|
+
if (!journal)
|
|
326
|
+
return creds[name];
|
|
327
|
+
const current = creds[name];
|
|
328
|
+
if (!current)
|
|
329
|
+
throw new Error("Passport profile is unavailable for credential rotation recovery.");
|
|
330
|
+
if (current.refreshToken === journal.previousRefreshToken) {
|
|
331
|
+
creds[name] = { ...current, ...journal.next };
|
|
332
|
+
writeCredsAtomic(creds);
|
|
333
|
+
}
|
|
334
|
+
else if (current.refreshToken !== journal.next.refreshToken) {
|
|
335
|
+
throw new Error("Passport profile conflicts with its credential rotation recovery journal.");
|
|
336
|
+
}
|
|
337
|
+
clearRotationJournal(name);
|
|
338
|
+
return creds[name];
|
|
339
|
+
});
|
|
340
|
+
}
|
|
35
341
|
export function writeProfile(name, profile) {
|
|
36
342
|
assertProfileName(name);
|
|
37
343
|
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.
|
|
344
|
+
const creds = readCredsForMutation();
|
|
345
|
+
// Preserve the installation id when rotating only the token.
|
|
42
346
|
creds[name] = { ...creds[name], ...profile };
|
|
43
347
|
writeCredsAtomic(creds);
|
|
348
|
+
clearRotationJournal(name);
|
|
349
|
+
});
|
|
350
|
+
}
|
|
351
|
+
/** Replace a profile only if the credential that started an interactive
|
|
352
|
+
* recovery is still the live slot value. A bridge may be waiting for browser
|
|
353
|
+
* approval while another process rotates or reconnects the same profile; in
|
|
354
|
+
* that race the newer durable slot wins and the recovery must not overwrite
|
|
355
|
+
* it. */
|
|
356
|
+
export function replaceProfileAfterRecovery(name, previousRefreshToken, profile) {
|
|
357
|
+
assertProfileName(name);
|
|
358
|
+
if (!previousRefreshToken)
|
|
359
|
+
throw new Error("Passport recovery has no previous credential.");
|
|
360
|
+
withStoreWriteLock(() => {
|
|
361
|
+
const creds = readCredsForMutation();
|
|
362
|
+
const current = creds[name];
|
|
363
|
+
if (!current || current.refreshToken !== previousRefreshToken) {
|
|
364
|
+
throw new Error("Passport profile changed while recovery was waiting; refusing to overwrite the newer credential.");
|
|
365
|
+
}
|
|
366
|
+
creds[name] = { ...current, ...profile };
|
|
367
|
+
writeCredsAtomic(creds);
|
|
368
|
+
clearRotationJournal(name);
|
|
44
369
|
});
|
|
45
370
|
}
|
|
46
371
|
export function removeProfile(name) {
|
|
47
372
|
assertProfileName(name);
|
|
48
373
|
return withStoreWriteLock(() => {
|
|
49
|
-
const creds =
|
|
374
|
+
const creds = readCredsForMutation();
|
|
50
375
|
const existing = creds[name];
|
|
51
376
|
delete creds[name];
|
|
52
377
|
writeCredsAtomic(creds);
|
|
378
|
+
clearRotationJournal(name);
|
|
53
379
|
return existing;
|
|
54
380
|
});
|
|
55
381
|
}
|
|
56
382
|
export function credsPath() {
|
|
57
383
|
return file();
|
|
58
384
|
}
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
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
|
-
}
|
|
385
|
+
function lockContents(path) {
|
|
386
|
+
try {
|
|
387
|
+
const stat = lstatSync(path);
|
|
388
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 256)
|
|
389
|
+
return undefined;
|
|
390
|
+
return readFileSync(path, "utf8");
|
|
391
|
+
}
|
|
392
|
+
catch {
|
|
393
|
+
return undefined;
|
|
96
394
|
}
|
|
395
|
+
}
|
|
396
|
+
function lockOwnerIsDead(path) {
|
|
397
|
+
const owner = lockContents(path)?.match(/^(\d+):[a-f0-9]{32}$/i);
|
|
398
|
+
if (!owner)
|
|
399
|
+
return false;
|
|
400
|
+
const pid = Number(owner[1]);
|
|
401
|
+
if (!Number.isSafeInteger(pid) || pid <= 0 || pid === process.pid)
|
|
402
|
+
return false;
|
|
97
403
|
try {
|
|
98
|
-
|
|
404
|
+
process.kill(pid, 0);
|
|
405
|
+
return false;
|
|
406
|
+
}
|
|
407
|
+
catch (error) {
|
|
408
|
+
return error.code === "ESRCH";
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
function tryAcquireLease(path) {
|
|
412
|
+
const token = `${process.pid}:${randomBytes(16).toString("hex")}`;
|
|
413
|
+
let descriptor;
|
|
414
|
+
try {
|
|
415
|
+
descriptor = openSync(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
|
416
|
+
if (process.platform !== "win32")
|
|
417
|
+
fchmodSync(descriptor, 0o600);
|
|
418
|
+
writeFileSync(descriptor, token, "utf8");
|
|
419
|
+
fsyncSync(descriptor);
|
|
420
|
+
return { path, token };
|
|
421
|
+
}
|
|
422
|
+
catch (error) {
|
|
423
|
+
if (error.code === "EEXIST")
|
|
424
|
+
return undefined;
|
|
425
|
+
throw error;
|
|
99
426
|
}
|
|
100
427
|
finally {
|
|
101
|
-
|
|
428
|
+
if (descriptor !== undefined)
|
|
429
|
+
closeSync(descriptor);
|
|
102
430
|
}
|
|
103
431
|
}
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
432
|
+
/** Move a stale or dead-owner inode out of the lock pathname before deleting
|
|
433
|
+
* it. An old owner can therefore never unlink a successor's lease. */
|
|
434
|
+
function stealRecoverableLease(path) {
|
|
435
|
+
let stat;
|
|
107
436
|
try {
|
|
108
|
-
|
|
109
|
-
|
|
437
|
+
stat = lstatSync(path);
|
|
438
|
+
}
|
|
439
|
+
catch (error) {
|
|
440
|
+
return isMissing(error);
|
|
441
|
+
}
|
|
442
|
+
if (stat.isSymbolicLink() || !stat.isFile())
|
|
443
|
+
return false;
|
|
444
|
+
if (Date.now() - stat.mtimeMs <= LOCK_STALE_MS && !lockOwnerIsDead(path))
|
|
445
|
+
return false;
|
|
446
|
+
const expected = lockContents(path);
|
|
447
|
+
const quarantine = `${path}.stale.${process.pid}.${randomBytes(6).toString("hex")}`;
|
|
448
|
+
try {
|
|
449
|
+
renameSync(path, quarantine);
|
|
450
|
+
}
|
|
451
|
+
catch (error) {
|
|
452
|
+
if (isMissing(error))
|
|
453
|
+
return true;
|
|
454
|
+
return false;
|
|
455
|
+
}
|
|
456
|
+
// A second contender may have won the race and installed a fresh lease.
|
|
457
|
+
// Never delete a quarantined inode unless it is the one we inspected.
|
|
458
|
+
let quarantined;
|
|
459
|
+
try {
|
|
460
|
+
quarantined = lstatSync(quarantine);
|
|
461
|
+
}
|
|
462
|
+
catch {
|
|
463
|
+
return false;
|
|
464
|
+
}
|
|
465
|
+
if (quarantined.dev !== stat.dev ||
|
|
466
|
+
quarantined.ino !== stat.ino ||
|
|
467
|
+
(expected !== undefined && lockContents(quarantine) !== expected)) {
|
|
110
468
|
try {
|
|
111
|
-
|
|
469
|
+
linkSync(quarantine, path);
|
|
470
|
+
unlinkSync(quarantine);
|
|
112
471
|
}
|
|
113
472
|
catch {
|
|
114
|
-
/*
|
|
473
|
+
/* Preserve the unexpected inode for manual inspection. */
|
|
115
474
|
}
|
|
475
|
+
return false;
|
|
116
476
|
}
|
|
117
|
-
|
|
118
|
-
|
|
477
|
+
unlinkSync(quarantine);
|
|
478
|
+
return true;
|
|
479
|
+
}
|
|
480
|
+
function acquireLease(path, timeoutMessage) {
|
|
481
|
+
ensurePrivateDirectory(true);
|
|
482
|
+
const started = Date.now();
|
|
483
|
+
for (;;) {
|
|
484
|
+
const lease = tryAcquireLease(path);
|
|
485
|
+
if (lease)
|
|
486
|
+
return lease;
|
|
487
|
+
if (stealRecoverableLease(path))
|
|
488
|
+
continue;
|
|
489
|
+
if (Date.now() - started > LOCK_PATIENCE_MS)
|
|
490
|
+
throw new Error(timeoutMessage);
|
|
491
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 25 + Math.floor(Math.random() * 25));
|
|
119
492
|
}
|
|
120
493
|
}
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
const lockDir = join(dir(), `${name}.lock`);
|
|
124
|
-
mkdirSync(dir(), { recursive: true });
|
|
494
|
+
async function acquireLeaseAsync(path, timeoutMessage) {
|
|
495
|
+
ensurePrivateDirectory(true);
|
|
125
496
|
const started = Date.now();
|
|
126
|
-
let acquired = false;
|
|
127
497
|
for (;;) {
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
498
|
+
const lease = tryAcquireLease(path);
|
|
499
|
+
if (lease)
|
|
500
|
+
return lease;
|
|
501
|
+
if (stealRecoverableLease(path))
|
|
502
|
+
continue;
|
|
503
|
+
if (Date.now() - started > LOCK_PATIENCE_MS)
|
|
504
|
+
throw new Error(timeoutMessage);
|
|
505
|
+
await new Promise((resolve) => setTimeout(resolve, 50 + Math.floor(Math.random() * 50)));
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
function leaseOwned(lease) {
|
|
509
|
+
return lockContents(lease.path) === lease.token;
|
|
510
|
+
}
|
|
511
|
+
function renewLease(lease) {
|
|
512
|
+
if (!leaseOwned(lease))
|
|
513
|
+
return;
|
|
514
|
+
const now = new Date();
|
|
515
|
+
try {
|
|
516
|
+
utimesSync(lease.path, now, now);
|
|
517
|
+
}
|
|
518
|
+
catch {
|
|
519
|
+
/* A stolen or released lease cannot be renewed. */
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
function releaseLease(lease) {
|
|
523
|
+
if (!leaseOwned(lease))
|
|
524
|
+
return;
|
|
525
|
+
try {
|
|
526
|
+
unlinkSync(lease.path);
|
|
527
|
+
}
|
|
528
|
+
catch (error) {
|
|
529
|
+
if (!isMissing(error))
|
|
530
|
+
throw error;
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
/** The JSON document is shared by every profile. */
|
|
534
|
+
function withStoreWriteLock(fn) {
|
|
535
|
+
const lease = acquireLease(join(dir(), ".credentials-write.lock"), "Timed out waiting to update Passport credentials.");
|
|
536
|
+
try {
|
|
537
|
+
return fn();
|
|
538
|
+
}
|
|
539
|
+
finally {
|
|
540
|
+
releaseLease(lease);
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
function assertSafePrivateTarget(path, label) {
|
|
544
|
+
try {
|
|
545
|
+
const stat = lstatSync(path);
|
|
546
|
+
if (stat.isSymbolicLink() || !stat.isFile()) {
|
|
547
|
+
throw new Error(`Passport ${label} must be a regular file, not a symlink.`);
|
|
132
548
|
}
|
|
133
|
-
|
|
549
|
+
enforceOwner(stat, label);
|
|
550
|
+
}
|
|
551
|
+
catch (error) {
|
|
552
|
+
if (!isMissing(error))
|
|
553
|
+
throw error;
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
function syncDirectory() {
|
|
557
|
+
if (process.platform === "win32")
|
|
558
|
+
return;
|
|
559
|
+
const descriptor = openSync(dir(), constants.O_RDONLY);
|
|
560
|
+
try {
|
|
561
|
+
fsyncSync(descriptor);
|
|
562
|
+
}
|
|
563
|
+
finally {
|
|
564
|
+
closeSync(descriptor);
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
function writePrivateAtomic(target, temporaryPrefix, contents, label) {
|
|
568
|
+
ensurePrivateDirectory(true);
|
|
569
|
+
assertSafePrivateTarget(target, label);
|
|
570
|
+
const tmp = join(dir(), `${temporaryPrefix}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
|
|
571
|
+
let descriptor;
|
|
572
|
+
let failed = false;
|
|
573
|
+
let failure;
|
|
574
|
+
try {
|
|
575
|
+
descriptor = openSync(tmp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
|
576
|
+
if (process.platform !== "win32")
|
|
577
|
+
fchmodSync(descriptor, 0o600);
|
|
578
|
+
writeFileSync(descriptor, contents, "utf8");
|
|
579
|
+
fsyncSync(descriptor);
|
|
580
|
+
closeSync(descriptor);
|
|
581
|
+
descriptor = undefined;
|
|
582
|
+
// Recheck after the strict mutation read so a swapped symlink or directory
|
|
583
|
+
// is rejected rather than silently replaced.
|
|
584
|
+
assertSafePrivateTarget(target, label);
|
|
585
|
+
renameSync(tmp, target);
|
|
586
|
+
if (process.platform !== "win32")
|
|
587
|
+
chmodSync(target, 0o600);
|
|
588
|
+
syncDirectory();
|
|
589
|
+
}
|
|
590
|
+
catch (error) {
|
|
591
|
+
failed = true;
|
|
592
|
+
failure = error;
|
|
593
|
+
}
|
|
594
|
+
finally {
|
|
595
|
+
if (descriptor !== undefined) {
|
|
134
596
|
try {
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
597
|
+
closeSync(descriptor);
|
|
598
|
+
}
|
|
599
|
+
catch (error) {
|
|
600
|
+
if (!failed) {
|
|
601
|
+
failed = true;
|
|
602
|
+
failure = error;
|
|
139
603
|
}
|
|
140
604
|
}
|
|
141
|
-
|
|
142
|
-
|
|
605
|
+
}
|
|
606
|
+
try {
|
|
607
|
+
unlinkSync(tmp);
|
|
608
|
+
}
|
|
609
|
+
catch (error) {
|
|
610
|
+
if (!isMissing(error) && !failed) {
|
|
611
|
+
failed = true;
|
|
612
|
+
failure = error;
|
|
143
613
|
}
|
|
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
614
|
}
|
|
148
615
|
}
|
|
616
|
+
if (failed)
|
|
617
|
+
throw failure;
|
|
618
|
+
}
|
|
619
|
+
function writeCredsAtomic(creds) {
|
|
620
|
+
writePrivateAtomic(file(), ".credentials", JSON.stringify(creds, null, 2), "credential store");
|
|
621
|
+
}
|
|
622
|
+
function writeRotationJournal(name, journal) {
|
|
623
|
+
writePrivateAtomic(profileRotationJournalPath(name), `.${name}.rotation`, JSON.stringify(journal), "credential rotation journal");
|
|
624
|
+
}
|
|
625
|
+
function clearRotationJournal(name) {
|
|
626
|
+
const path = profileRotationJournalPath(name);
|
|
627
|
+
let stat;
|
|
628
|
+
try {
|
|
629
|
+
stat = lstatSync(path);
|
|
630
|
+
}
|
|
631
|
+
catch (error) {
|
|
632
|
+
if (isMissing(error))
|
|
633
|
+
return;
|
|
634
|
+
throw error;
|
|
635
|
+
}
|
|
636
|
+
if (stat.isSymbolicLink() || !stat.isFile()) {
|
|
637
|
+
throw new Error("Passport credential rotation journal must be a regular file, not a symlink.");
|
|
638
|
+
}
|
|
639
|
+
enforceOwner(stat, "credential rotation journal");
|
|
640
|
+
unlinkSync(path);
|
|
641
|
+
syncDirectory();
|
|
642
|
+
}
|
|
643
|
+
/** Serialize refresh-token exchange across processes. A heartbeat keeps a live
|
|
644
|
+
* owner fresh; the random token makes release ownership-safe after recovery. */
|
|
645
|
+
export async function withProfileLock(name, fn) {
|
|
646
|
+
assertProfileName(name);
|
|
647
|
+
const lease = await acquireLeaseAsync(join(dir(), `${name}.lock`), `Timed out waiting for Passport profile "${name}".`);
|
|
648
|
+
const heartbeat = setInterval(() => renewLease(lease), LOCK_HEARTBEAT_MS);
|
|
649
|
+
heartbeat.unref?.();
|
|
149
650
|
try {
|
|
150
651
|
return await fn();
|
|
151
652
|
}
|
|
152
653
|
finally {
|
|
153
|
-
|
|
154
|
-
|
|
654
|
+
clearInterval(heartbeat);
|
|
655
|
+
releaseLease(lease);
|
|
155
656
|
}
|
|
156
657
|
}
|