passport-bridge 0.7.1 → 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.
@@ -1,13 +1,10 @@
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";
3
- import { homedir } from "node:os";
1
+ import { closeSync, constants, fchmodSync, fstatSync, lstatSync, openSync, readFileSync, unlinkSync } from "node:fs";
4
2
  import { join } from "node:path";
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 LOCK_STALE_MS = 30_000;
9
- const LOCK_PATIENCE_MS = LOCK_STALE_MS + 5_000;
10
- const LOCK_HEARTBEAT_MS = 5_000;
11
8
  const ROTATION_JOURNAL_VERSION = 1;
12
9
  /** Profile names become both JSON keys and lock-file names. */
13
10
  export function assertProfileName(name) {
@@ -16,7 +13,7 @@ export function assertProfileName(name) {
16
13
  }
17
14
  }
18
15
  function dir() {
19
- return process.env.PASSPORT_HOME || join(homedir(), ".passport");
16
+ return credentialDir();
20
17
  }
21
18
  function file() {
22
19
  return join(dir(), "credentials.json");
@@ -28,14 +25,6 @@ export function profileRotationJournalPath(name) {
28
25
  function emptyCreds() {
29
26
  return Object.create(null);
30
27
  }
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
28
  function validatedProfile(value) {
40
29
  if (!value || typeof value !== "object" || Array.isArray(value))
41
30
  return undefined;
@@ -65,35 +54,6 @@ function validatedProfile(value) {
65
54
  ...(profile.target === undefined ? {} : { target: profile.target })
66
55
  };
67
56
  }
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
57
  function parseCreds(raw) {
98
58
  if (!raw.trim())
99
59
  return emptyCreds();
@@ -373,248 +333,58 @@ export function removeProfile(name) {
373
333
  return withStoreWriteLock(() => {
374
334
  const creds = readCredsForMutation();
375
335
  const existing = creds[name];
336
+ const active = readActiveProfileDocument(assertProfileName);
376
337
  delete creds[name];
377
338
  writeCredsAtomic(creds);
378
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
+ }
379
347
  return existing;
380
348
  });
381
349
  }
382
- export function credsPath() {
383
- return file();
384
- }
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;
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;
403
- try {
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;
426
- }
427
- finally {
428
- if (descriptor !== undefined)
429
- closeSync(descriptor);
430
- }
431
- }
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;
436
- try {
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)) {
468
- try {
469
- linkSync(quarantine, path);
470
- unlinkSync(quarantine);
471
- }
472
- catch {
473
- /* Preserve the unexpected inode for manual inspection. */
474
- }
475
- return false;
476
- }
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));
492
- }
493
- }
494
- async function acquireLeaseAsync(path, timeoutMessage) {
495
- ensurePrivateDirectory(true);
496
- const started = Date.now();
497
- for (;;) {
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
- }
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);
532
356
  }
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
- }
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);
542
362
  }
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.`);
548
- }
549
- enforceOwner(stat, label);
550
- }
551
- catch (error) {
552
- if (!isMissing(error))
553
- throw error;
554
- }
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
+ });
555
374
  }
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
- }
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
+ });
566
385
  }
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) {
596
- try {
597
- closeSync(descriptor);
598
- }
599
- catch (error) {
600
- if (!failed) {
601
- failed = true;
602
- failure = error;
603
- }
604
- }
605
- }
606
- try {
607
- unlinkSync(tmp);
608
- }
609
- catch (error) {
610
- if (!isMissing(error) && !failed) {
611
- failed = true;
612
- failure = error;
613
- }
614
- }
615
- }
616
- if (failed)
617
- throw failure;
386
+ export function credsPath() {
387
+ return file();
618
388
  }
619
389
  function writeCredsAtomic(creds) {
620
390
  writePrivateAtomic(file(), ".credentials", JSON.stringify(creds, null, 2), "credential store");
@@ -640,18 +410,3 @@ function clearRotationJournal(name) {
640
410
  unlinkSync(path);
641
411
  syncDirectory();
642
412
  }
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?.();
650
- try {
651
- return await fn();
652
- }
653
- finally {
654
- clearInterval(heartbeat);
655
- releaseLease(lease);
656
- }
657
- }
package/dist/doctor.js CHANGED
@@ -1,13 +1,22 @@
1
1
  import { lstatSync } from "node:fs";
2
2
  import { readBoundedUtf8File } from "./boundedFile.js";
3
3
  import { CliGateway, CLI_PROTOCOL_TOOLS, MIN_CLI_SERVER_VERSION } from "./cliClient.js";
4
- import { assertProfileName, credsPath } from "./credentials.js";
4
+ import { activeProfilePath, assertProfileName, credsPath } from "./credentials.js";
5
+ import { ensurePrivateDirectory } from "./credentialStorage.js";
5
6
  const DOCTOR_CREDENTIAL_MAX_BYTES = 1024 * 1024;
7
+ const DOCTOR_ACTIVE_PROFILE_MAX_BYTES = 512;
6
8
  function check(checks, id, status, summary, action) {
7
9
  checks.push({ id, status, summary, ...(action ? { action } : {}) });
8
10
  }
9
11
  function inspectStore(checks, agentMode) {
10
12
  const empty = Object.create(null);
13
+ try {
14
+ ensurePrivateDirectory(false);
15
+ }
16
+ catch {
17
+ check(checks, "credential_store", "fail", "The Passport credential directory is not an owner-controlled regular directory.", "Replace it with a regular directory owned by this account.");
18
+ return { profiles: empty, count: 0 };
19
+ }
11
20
  let stat;
12
21
  try {
13
22
  stat = lstatSync(credsPath());
@@ -18,7 +27,7 @@ function inspectStore(checks, agentMode) {
18
27
  ? agentMode
19
28
  ? "No local credential store is needed in agent-key mode."
20
29
  : "No local credential store exists."
21
- : "The credential store could not be inspected.", missing && !agentMode ? "Run `passport login --cloud <origin> --workspace <id>`." : undefined);
30
+ : "The credential store could not be inspected.", missing && !agentMode ? "Run `passport login --workspace <workspace-id>`." : undefined);
22
31
  return { profiles: empty, count: 0 };
23
32
  }
24
33
  if (stat.isSymbolicLink() || !stat.isFile()) {
@@ -82,6 +91,48 @@ function inspectStore(checks, agentMode) {
82
91
  }
83
92
  return { profiles, count };
84
93
  }
94
+ function inspectActiveProfile(checks, store) {
95
+ try {
96
+ if (!ensurePrivateDirectory(false))
97
+ return undefined;
98
+ }
99
+ catch {
100
+ return undefined;
101
+ }
102
+ let stat;
103
+ try {
104
+ stat = lstatSync(activeProfilePath());
105
+ }
106
+ catch (error) {
107
+ if (error.code === "ENOENT")
108
+ return undefined;
109
+ check(checks, "active_profile", "fail", "The active-profile selection could not be inspected.", "Run `passport use <name>` to repair it.");
110
+ return undefined;
111
+ }
112
+ if (stat.isSymbolicLink() || !stat.isFile()) {
113
+ check(checks, "active_profile", "fail", "The active-profile selection is not a regular file.", "Run `passport use <name>` to repair it safely.");
114
+ return undefined;
115
+ }
116
+ if (typeof process.getuid === "function" && stat.uid !== process.getuid()) {
117
+ check(checks, "active_profile", "fail", "The active-profile selection is owned by another account.", "Remove it, then run `passport use <name>`.");
118
+ return undefined;
119
+ }
120
+ let active = "";
121
+ try {
122
+ active = readBoundedUtf8File(activeProfilePath(), DOCTOR_ACTIVE_PROFILE_MAX_BYTES).trim();
123
+ assertProfileName(active);
124
+ }
125
+ catch {
126
+ check(checks, "active_profile", "fail", "The active-profile selection is invalid.", "Run `passport use <name>` to repair it.");
127
+ return undefined;
128
+ }
129
+ if (!store.profiles[active]) {
130
+ check(checks, "active_profile", "fail", `The active profile "${active}" is not stored.`, "Run `passport profiles`, then `passport use <name>`.");
131
+ return undefined;
132
+ }
133
+ check(checks, "active_profile", "pass", `Active profile is "${active}".`);
134
+ return active;
135
+ }
85
136
  function errorText(error, redact) {
86
137
  return redact(error instanceof Error ? error.message : String(error)) || "Unknown failure.";
87
138
  }
@@ -96,13 +147,29 @@ function inspectRuntime(checks) {
96
147
  const supported = nodeRuntimeSupported(process.versions.node);
97
148
  check(checks, "runtime", supported ? "pass" : "fail", `Node.js ${process.versions.node}${supported ? " satisfies" : " does not satisfy"} the >=22.23.2 requirement.`, supported ? undefined : "Install Node.js 22.23.2 or newer.");
98
149
  }
150
+ function selectedProfileCandidate(options, store, active) {
151
+ if (options.profile !== undefined)
152
+ return options.profile;
153
+ if (options.env.PASSPORT_PROFILE !== undefined)
154
+ return options.env.PASSPORT_PROFILE;
155
+ if (active && store.profiles[active])
156
+ return active;
157
+ const names = Object.keys(store.profiles);
158
+ return names.length === 1 ? names[0] : undefined;
159
+ }
99
160
  export async function runDoctor(options) {
100
161
  const checks = [];
101
162
  inspectRuntime(checks);
102
163
  const hasAgentKey = Boolean(options.env.PASSPORT_AGENT_KEY);
103
164
  const hasAgentEndpoint = Boolean(options.env.PASSPORT_ENDPOINT);
104
165
  const agentMode = hasAgentKey && hasAgentEndpoint;
105
- const store = inspectStore(checks, agentMode);
166
+ const store = agentMode
167
+ ? (() => {
168
+ check(checks, "credential_store", "skip", "Local profiles are not inspected in agent-key mode.");
169
+ return { profiles: Object.create(null), count: 0 };
170
+ })()
171
+ : inspectStore(checks, false);
172
+ const active = agentMode ? undefined : inspectActiveProfile(checks, store);
106
173
  let auth;
107
174
  let selectedProfile;
108
175
  if (hasAgentKey !== hasAgentEndpoint) {
@@ -125,13 +192,13 @@ export async function runDoctor(options) {
125
192
  }
126
193
  else {
127
194
  const names = Object.keys(store.profiles).sort();
128
- const candidate = options.profile ?? options.env.PASSPORT_PROFILE ?? (names.length === 1 ? names[0] : undefined);
195
+ const candidate = selectedProfileCandidate(options, store, active);
129
196
  if (!candidate) {
130
197
  check(checks, "auth_config", "fail", names.length > 1
131
198
  ? `No profile was selected from ${names.length} stored profiles.`
132
199
  : "No usable profile is configured.", names.length > 1
133
- ? "Run `passport doctor --profile <name>`."
134
- : "Run `passport login --cloud <origin> --workspace <id>`.");
200
+ ? "Run `passport profiles`, then `passport use <name>` or retry with `--profile <name>`."
201
+ : "Run `passport login --workspace <workspace-id>`.");
135
202
  }
136
203
  else {
137
204
  try {