passwd-sso-cli 0.4.76 → 0.5.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.
@@ -9,6 +9,7 @@
9
9
  import { apiRequest } from "../lib/api-client.js";
10
10
  import { readMainApiErrorBody } from "../lib/api-error-body.js";
11
11
  import * as output from "../lib/output.js";
12
+ import { MS_PER_DAY } from "../lib/time.js";
12
13
  export async function apiKeyListCommand(options = {}) {
13
14
  const res = await apiRequest("/api/api-keys");
14
15
  if (!res.ok) {
@@ -63,8 +64,9 @@ export async function apiKeyListCommand(options = {}) {
63
64
  output.table(["ID", "Name", "Prefix", "Scopes", "Status", "Expires", "Last Used"], rows);
64
65
  }
65
66
  export async function apiKeyCreateCommand(opts) {
66
- const expiresAt = new Date();
67
- expiresAt.setDate(expiresAt.getDate() + opts.days);
67
+ // Elapsed days, as the server bounds it: a local calendar step would land an
68
+ // hour past the bound across a DST fall-back.
69
+ const expiresAt = new Date(Date.now() + opts.days * MS_PER_DAY);
68
70
  const res = await apiRequest("/api/api-keys", {
69
71
  method: "POST",
70
72
  body: {
@@ -4,6 +4,8 @@
4
4
  * Validates the EdDSA signature, optionally checks tenant coverage,
5
5
  * and optionally checks chain-sequence regression against a prior manifest.
6
6
  */
7
+ /** How long a manifest or public-key fetch may take, headers and body together. */
8
+ export declare const AUDIT_VERIFY_FETCH_TIMEOUT_MS = 30000;
7
9
  export declare class InvalidAlgorithmError extends Error {
8
10
  constructor(alg: unknown);
9
11
  }
@@ -19,6 +21,19 @@ export declare class InvalidTenantIdFormatError extends Error {
19
21
  export declare class InvalidKidError extends Error {
20
22
  constructor(kid: unknown);
21
23
  }
24
+ /** The header names a key other than the one the signature was checked under. */
25
+ export declare class KidMismatchError extends Error {
26
+ constructor(headerKid: string, keyKid: string);
27
+ }
28
+ export declare class InvalidPublicKeyError extends Error {
29
+ constructor();
30
+ }
31
+ export declare class InsecureUrlError extends Error {
32
+ constructor(what: string);
33
+ }
34
+ export declare class PriorPublicKeyRequiredError extends Error {
35
+ constructor(priorKid: string);
36
+ }
22
37
  export declare class ManifestSchemaValidationError extends Error {
23
38
  constructor(detail: string);
24
39
  }
@@ -31,6 +46,10 @@ export declare class TenantNotInManifestError extends Error {
31
46
  export declare class ChainBreakError extends Error {
32
47
  constructor(expected: string, got: string);
33
48
  }
49
+ /** The prior and the current manifest are not of one chain location. */
50
+ export declare class ChainLocationMismatchError extends Error {
51
+ constructor(prior: string, current: string);
52
+ }
34
53
  export declare class ChainSeqRegressionError extends Error {
35
54
  constructor(tenantTag: string, prior: string, current: string);
36
55
  }
@@ -52,6 +71,10 @@ export declare class ManifestFetchError extends Error {
52
71
  readonly status: number;
53
72
  constructor(status: number);
54
73
  }
74
+ /** A fetched manifest or public key larger than any anchor artifact. */
75
+ export declare class ResponseTooLargeError extends Error {
76
+ constructor();
77
+ }
55
78
  export declare function computeTenantTag(tenantId: string, tagSecret: Buffer): string;
56
79
  export type AuditVerifyArgs = {
57
80
  manifest: string;
@@ -60,6 +83,7 @@ export type AuditVerifyArgs = {
60
83
  tagSecret?: string;
61
84
  tagSecretFile?: string;
62
85
  priorManifest?: string;
86
+ priorPublicKey?: string;
63
87
  archiveUrl?: string;
64
88
  };
65
89
  export declare function auditVerifyCommand(args: AuditVerifyArgs): Promise<void>;
@@ -7,19 +7,21 @@
7
7
  import { readFileSync, openSync, fstatSync, readSync, closeSync } from "node:fs";
8
8
  import { createHash, createHmac, createPublicKey, verify as nodeVerify } from "node:crypto";
9
9
  import { z } from "zod";
10
- import { AUDIT_ANCHOR_KID_PREFIX, AUDIT_ANCHOR_TYP } from "../constants/audit-anchor.js";
10
+ import { AUDIT_ANCHOR_ARTIFACT_MAX_BYTES, AUDIT_ANCHOR_KID_HEX_CHARS, AUDIT_ANCHOR_KID_PREFIX, AUDIT_ANCHOR_TYP, } from "../constants/audit-anchor.js";
11
11
  // --- Constants ---
12
12
  const AUDIT_ANCHOR_TAG_DOMAIN = "audit-anchor-tag-v1";
13
+ /** How long a manifest or public-key fetch may take, headers and body together. */
14
+ export const AUDIT_VERIFY_FETCH_TIMEOUT_MS = 30_000;
13
15
  // --- Typed errors ---
14
16
  export class InvalidAlgorithmError extends Error {
15
17
  constructor(alg) {
16
- super(`Invalid JWS alg: ${alg}; expected EdDSA`);
18
+ super(`Invalid JWS alg: ${JSON.stringify(alg)}; expected EdDSA`);
17
19
  this.name = "InvalidAlgorithmError";
18
20
  }
19
21
  }
20
22
  export class InvalidTypError extends Error {
21
23
  constructor(typ) {
22
- super(`Invalid JWS typ: ${typ}; expected ${AUDIT_ANCHOR_TYP}`);
24
+ super(`Invalid JWS typ: ${JSON.stringify(typ)}; expected ${AUDIT_ANCHOR_TYP}`);
23
25
  this.name = "InvalidTypError";
24
26
  }
25
27
  }
@@ -37,10 +39,35 @@ export class InvalidTenantIdFormatError extends Error {
37
39
  }
38
40
  export class InvalidKidError extends Error {
39
41
  constructor(kid) {
40
- super(`Invalid kid format; expected ${AUDIT_ANCHOR_KID_PREFIX}<8-32 char> (no path separators): got ${kid}`);
42
+ super(`Invalid kid format; expected ${AUDIT_ANCHOR_KID_PREFIX}<${AUDIT_ANCHOR_KID_HEX_CHARS} lower-case hex chars>: got ${JSON.stringify(kid)}`);
41
43
  this.name = "InvalidKidError";
42
44
  }
43
45
  }
46
+ /** The header names a key other than the one the signature was checked under. */
47
+ export class KidMismatchError extends Error {
48
+ constructor(headerKid, keyKid) {
49
+ super(`JWS kid ${headerKid} does not name the supplied public key (${keyKid})`);
50
+ this.name = "KidMismatchError";
51
+ }
52
+ }
53
+ export class InvalidPublicKeyError extends Error {
54
+ constructor() {
55
+ super("Invalid Ed25519 public key; expected 64 lower-case hex chars (32 bytes)");
56
+ this.name = "InvalidPublicKeyError";
57
+ }
58
+ }
59
+ export class InsecureUrlError extends Error {
60
+ constructor(what) {
61
+ super(`${what} must be an https:// URL (http:// is accepted for localhost, 127.0.0.1 and [::1] only)`);
62
+ this.name = "InsecureUrlError";
63
+ }
64
+ }
65
+ export class PriorPublicKeyRequiredError extends Error {
66
+ constructor(priorKid) {
67
+ super(`The prior manifest is signed under another key (${priorKid}); pass its public key with --prior-public-key`);
68
+ this.name = "PriorPublicKeyRequiredError";
69
+ }
70
+ }
44
71
  export class ManifestSchemaValidationError extends Error {
45
72
  constructor(detail) {
46
73
  super(detail);
@@ -65,6 +92,13 @@ export class ChainBreakError extends Error {
65
92
  this.name = "ChainBreakError";
66
93
  }
67
94
  }
95
+ /** The prior and the current manifest are not of one chain location. */
96
+ export class ChainLocationMismatchError extends Error {
97
+ constructor(prior, current) {
98
+ super(`Prior and current manifest are bound to different chain locations; prior=${prior}, current=${current}`);
99
+ this.name = "ChainLocationMismatchError";
100
+ }
101
+ }
68
102
  export class ChainSeqRegressionError extends Error {
69
103
  constructor(tenantTag, prior, current) {
70
104
  super(`CHAIN_SEQ_REGRESSION at tenantTag=${tenantTag}: prior=${prior}, current=${current}`);
@@ -107,21 +141,41 @@ export class ManifestFetchError extends Error {
107
141
  this.status = status;
108
142
  }
109
143
  }
144
+ /** A fetched manifest or public key larger than any anchor artifact. */
145
+ export class ResponseTooLargeError extends Error {
146
+ constructor() {
147
+ super(`Fetched response is larger than ${AUDIT_ANCHOR_ARTIFACT_MAX_BYTES} bytes`);
148
+ this.name = "ResponseTooLargeError";
149
+ }
150
+ }
110
151
  const tenantEntrySchema = z.object({
111
152
  tenantTag: z.string().regex(/^[0-9a-f]{64}$/),
112
153
  chainSeq: z.string().regex(/^(0|[1-9][0-9]*)$/),
113
154
  prevHash: z.string().regex(/^([0-9a-f]{64}|[0-9a-f]{2})$/),
114
155
  epoch: z.number().int().min(1),
115
156
  });
116
- const manifestSchema = z.object({
157
+ /** `value` is exactly what `Date.prototype.toISOString` writes for its instant. */
158
+ function isIsoTimestamp(value) {
159
+ if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value))
160
+ return false;
161
+ const ms = Date.parse(value);
162
+ return Number.isFinite(ms) && new Date(ms).toISOString() === value;
163
+ }
164
+ const manifestBodyShape = {
117
165
  $schema: z.string(),
118
- version: z.literal(1),
119
166
  issuer: z.literal("passwd-sso"),
120
167
  deploymentId: z.string(),
121
- anchoredAt: z.string(),
168
+ anchoredAt: z.string().refine(isIsoTimestamp),
122
169
  previousManifest: z.object({ uri: z.string(), sha256: z.string() }).nullable(),
123
170
  tenants: z.array(tenantEntrySchema),
124
- });
171
+ };
172
+ // A version 1 payload that carries a chainLocation parses without it, and
173
+ // verifyJws then refuses it: the payload is not the canonical form of what
174
+ // was parsed.
175
+ const manifestSchema = z.discriminatedUnion("version", [
176
+ z.object({ ...manifestBodyShape, version: z.literal(1) }),
177
+ z.object({ ...manifestBodyShape, version: z.literal(2), chainLocation: z.string().regex(/^[0-9a-f]{64}$/) }),
178
+ ]);
125
179
  // --- SubjectPublicKeyInfo prefix for Ed25519 (RFC 8410) ---
126
180
  const ED25519_SPKI_PREFIX = Buffer.from("302a300506032b6570032100", "hex");
127
181
  // --- Helpers ---
@@ -169,11 +223,7 @@ function validateManifest(value) {
169
223
  function canonicalize(manifest) {
170
224
  return Buffer.from(jcsCanonical(manifest), "utf-8");
171
225
  }
172
- function verifyJws(jws, publicKey) {
173
- const parts = jws.split(".");
174
- if (parts.length !== 3)
175
- throw new InvalidSignatureError();
176
- const [headerB64, payloadB64, sigB64] = parts;
226
+ function decodeHeader(headerB64) {
177
227
  let header;
178
228
  try {
179
229
  header = JSON.parse(b64urlDecode(headerB64).toString("utf-8"));
@@ -181,10 +231,27 @@ function verifyJws(jws, publicKey) {
181
231
  catch {
182
232
  throw new InvalidSignatureError();
183
233
  }
234
+ if (typeof header !== "object" || header === null)
235
+ throw new InvalidSignatureError();
236
+ return header;
237
+ }
238
+ function verifyJws(jws, publicKey) {
239
+ const parts = jws.split(".");
240
+ if (parts.length !== 3)
241
+ throw new InvalidSignatureError();
242
+ const [headerB64, payloadB64, sigB64] = parts;
243
+ const header = decodeHeader(headerB64);
184
244
  if (header.alg !== "EdDSA")
185
245
  throw new InvalidAlgorithmError(header.alg);
186
246
  if (header.typ !== AUDIT_ANCHOR_TYP)
187
247
  throw new InvalidTypError(header.typ);
248
+ // A signature is accepted only under the key its kid names, and the kid is
249
+ // checked before the signature.
250
+ if (typeof header.kid !== "string" || !KID_PATTERN.test(header.kid))
251
+ throw new InvalidKidError(header.kid);
252
+ const keyKid = kidForPublicKey(publicKey);
253
+ if (header.kid !== keyKid)
254
+ throw new KidMismatchError(header.kid, keyKid);
188
255
  const keyObject = createPublicKey({
189
256
  key: Buffer.concat([ED25519_SPKI_PREFIX, publicKey]),
190
257
  format: "der",
@@ -231,21 +298,110 @@ function extractKidFromJws(jws) {
231
298
  if (dot === -1)
232
299
  throw new InvalidSignatureError();
233
300
  const headerB64 = jws.slice(0, dot);
234
- let header;
301
+ const header = decodeHeader(headerB64);
302
+ return typeof header.kid === "string" ? header.kid : "";
303
+ }
304
+ // The only shape a public key derives: no path separators, percent-encoding, etc.
305
+ const KID_PATTERN = new RegExp(`^${AUDIT_ANCHOR_KID_PREFIX}[0-9a-f]{${AUDIT_ANCHOR_KID_HEX_CHARS}}$`);
306
+ function validateKid(kid) {
307
+ if (!KID_PATTERN.test(kid)) {
308
+ throw new InvalidKidError(kid);
309
+ }
310
+ }
311
+ /** The kid of a raw Ed25519 public key: the prefix plus its first 8 bytes in hex. */
312
+ function kidForPublicKey(publicKey) {
313
+ return `${AUDIT_ANCHOR_KID_PREFIX}${publicKey.subarray(0, AUDIT_ANCHOR_KID_HEX_CHARS / 2).toString("hex")}`;
314
+ }
315
+ /**
316
+ * A raw public key from its text: exactly 64 lower-case hex chars once
317
+ * surrounding whitespace is trimmed. `Buffer.from(text, "hex")` is not used
318
+ * alone: it stops at the first non-hex char and returns what it had.
319
+ */
320
+ function parsePublicKeyHex(text) {
321
+ const hex = text.trim();
322
+ if (!/^[0-9a-f]{64}$/.test(hex))
323
+ throw new InvalidPublicKeyError();
324
+ return Buffer.from(hex, "hex");
325
+ }
326
+ const HTTP_LOOPBACK_HOSTNAMES = new Set(["localhost", "127.0.0.1", "[::1]"]);
327
+ function looksLikeUrl(value) {
328
+ return /^[a-z][a-z0-9+.-]*:\/\//i.test(value);
329
+ }
330
+ /**
331
+ * `raw` as a URL the verifier may fetch: `https://`, or `http://` to a
332
+ * loopback host. The scheme is matched on the text as given, and the host on
333
+ * the parsed URL — a prefix test alone passes `http://127.0.0.1@example.com/`.
334
+ */
335
+ function fetchableUrl(raw, what) {
336
+ let url;
235
337
  try {
236
- header = JSON.parse(b64urlDecode(headerB64).toString("utf-8"));
338
+ url = new URL(raw);
237
339
  }
238
340
  catch {
239
- throw new InvalidSignatureError();
341
+ throw new InsecureUrlError(what);
240
342
  }
241
- return typeof header.kid === "string" ? header.kid : "";
343
+ if (raw.startsWith("https://"))
344
+ return url;
345
+ if (raw.startsWith("http://") && HTTP_LOOPBACK_HOSTNAMES.has(url.hostname))
346
+ return url;
347
+ throw new InsecureUrlError(what);
242
348
  }
243
- function validateKid(kid) {
244
- // Strict regex: only alphanumeric + hyphen + underscore — no path separators, percent-encoding, etc.
245
- const kidPattern = new RegExp(`^${AUDIT_ANCHOR_KID_PREFIX}[a-zA-Z0-9_-]{8,32}$`);
246
- if (!kidPattern.test(kid)) {
247
- throw new InvalidKidError(kid);
349
+ /**
350
+ * The body of a 200 answer from `url`, as text. Redirects are not followed;
351
+ * the request is bounded in time and the body in size, counted as it is read
352
+ * (a `Content-Length` may be absent or understated), so the server decides
353
+ * neither how long the verifier waits nor how much it buffers.
354
+ */
355
+ async function fetchBoundedText(url, failure) {
356
+ const resp = await fetch(url, { redirect: "manual", signal: AbortSignal.timeout(AUDIT_VERIFY_FETCH_TIMEOUT_MS) });
357
+ if (resp.status !== 200) {
358
+ await resp.body?.cancel();
359
+ throw failure(resp.status);
360
+ }
361
+ if (Number(resp.headers.get("content-length")) > AUDIT_ANCHOR_ARTIFACT_MAX_BYTES) {
362
+ await resp.body?.cancel();
363
+ throw new ResponseTooLargeError();
364
+ }
365
+ const reader = resp.body?.getReader();
366
+ const chunks = [];
367
+ let total = 0;
368
+ while (reader) {
369
+ const { done, value } = await reader.read();
370
+ if (done)
371
+ break;
372
+ total += value.byteLength;
373
+ if (total > AUDIT_ANCHOR_ARTIFACT_MAX_BYTES) {
374
+ await reader.cancel();
375
+ throw new ResponseTooLargeError();
376
+ }
377
+ chunks.push(value);
248
378
  }
379
+ return Buffer.concat(chunks, total).toString("utf-8");
380
+ }
381
+ /** The public key of `kid` from the archive at `archiveBase`. */
382
+ async function fetchArchivedPublicKey(archiveBase, kid) {
383
+ // Three layers of defense for the file-data → outbound-fetch flow:
384
+ // 1. validateKid() restricts kid to ^audit-anchor-[0-9a-f]{16}$
385
+ // (no ".", "/", "%", or other path-special characters).
386
+ // 2. encodeURIComponent on kid — recognized by CodeQL as a sanitizer for
387
+ // URL-path-segment construction. At runtime this is a no-op because
388
+ // validateKid already restricted kid to characters that
389
+ // encodeURIComponent does not encode, but the call breaks the
390
+ // taint-flow CodeQL detects (see PR #419 review #4209883677).
391
+ // 3. URL constructor with archiveBaseUrl as base — resolution semantics
392
+ // pin the host to archiveBase's origin; combined with the explicit
393
+ // origin equality check below, kid cannot escape the archive origin.
394
+ validateKid(kid);
395
+ const archiveBaseUrl = fetchableUrl(archiveBase, "The public key archive URL");
396
+ const archivePath = archiveBaseUrl.pathname.replace(/\/$/, "");
397
+ const safeKid = encodeURIComponent(kid);
398
+ const pubUrlObj = new URL(`${archivePath}/${safeKid}.pub`, archiveBaseUrl);
399
+ if (pubUrlObj.origin !== archiveBaseUrl.origin) {
400
+ // Defense in depth: should be impossible given validateKid + URL semantics,
401
+ // but explicit reject if URL resolution somehow crosses origins.
402
+ throw new PublicKeyFetchError(0, pubUrlObj.href);
403
+ }
404
+ return parsePublicKeyHex(await fetchBoundedText(pubUrlObj.href, (status) => new PublicKeyFetchError(status, pubUrlObj.href)));
249
405
  }
250
406
  function sha256Hex(buf) {
251
407
  return createHash("sha256").update(buf).digest("hex");
@@ -310,12 +466,9 @@ export async function auditVerifyCommand(args) {
310
466
  const print = makeRedactedPrint(tagSecretHex);
311
467
  // Fetch or read manifest JWS
312
468
  let jws;
313
- if (args.manifest.startsWith("http://") || args.manifest.startsWith("https://")) {
314
- const resp = await fetch(args.manifest, { redirect: "manual" });
315
- if (resp.status !== 200) {
316
- throw new ManifestFetchError(resp.status);
317
- }
318
- jws = (await resp.text()).trim();
469
+ if (looksLikeUrl(args.manifest)) {
470
+ const manifestUrl = fetchableUrl(args.manifest, "The manifest URL");
471
+ jws = (await fetchBoundedText(manifestUrl.href, (status) => new ManifestFetchError(status))).trim();
319
472
  }
320
473
  else {
321
474
  jws = readFileSync(args.manifest, "utf-8").trim();
@@ -324,42 +477,16 @@ export async function auditVerifyCommand(args) {
324
477
  const kid = extractKidFromJws(jws);
325
478
  validateKid(kid); // throws InvalidKidError if invalid
326
479
  // Resolve public key
480
+ const archiveBase = args.archiveUrl ?? process.env["AUDIT_ANCHOR_PUBLIC_KEY_ARCHIVE_URL"];
327
481
  let publicKeyBytes;
328
482
  if (args.publicKey) {
329
- const raw = readFileSync(args.publicKey, "utf-8").trim();
330
- publicKeyBytes = Buffer.from(raw, "hex");
483
+ publicKeyBytes = parsePublicKeyHex(readFileSync(args.publicKey, "utf-8"));
331
484
  }
332
485
  else {
333
- const archiveBase = args.archiveUrl ?? process.env["AUDIT_ANCHOR_PUBLIC_KEY_ARCHIVE_URL"];
334
486
  if (!archiveBase) {
335
487
  throw new PublicKeyArchiveUrlMissingError();
336
488
  }
337
- // Three layers of defense for the file-data → outbound-fetch flow:
338
- // 1. validateKid() above restricts kid to ^audit-anchor-[a-zA-Z0-9_-]{8,32}$
339
- // (no ".", "/", "%", or other path-special characters).
340
- // 2. encodeURIComponent on kid — recognized by CodeQL as a sanitizer for
341
- // URL-path-segment construction. At runtime this is a no-op because
342
- // validateKid already restricted kid to characters that
343
- // encodeURIComponent does not encode, but the call breaks the
344
- // taint-flow CodeQL detects (see PR #419 review #4209883677).
345
- // 3. URL constructor with archiveBaseUrl as base — resolution semantics
346
- // pin the host to archiveBase's origin; combined with the explicit
347
- // origin equality check below, kid cannot escape the archive origin.
348
- const archiveBaseUrl = new URL(archiveBase);
349
- const archivePath = archiveBaseUrl.pathname.replace(/\/$/, "");
350
- const safeKid = encodeURIComponent(kid);
351
- const pubUrlObj = new URL(`${archivePath}/${safeKid}.pub`, archiveBaseUrl);
352
- if (pubUrlObj.origin !== archiveBaseUrl.origin) {
353
- // Defense in depth: should be impossible given validateKid + URL semantics,
354
- // but explicit reject if URL resolution somehow crosses origins.
355
- throw new PublicKeyFetchError(0, pubUrlObj.href);
356
- }
357
- const resp = await fetch(pubUrlObj.href, { redirect: "manual" });
358
- if (resp.status !== 200) {
359
- throw new PublicKeyFetchError(resp.status, pubUrlObj.href);
360
- }
361
- const raw = (await resp.text()).trim();
362
- publicKeyBytes = Buffer.from(raw, "hex");
489
+ publicKeyBytes = await fetchArchivedPublicKey(archiveBase, kid);
363
490
  }
364
491
  // Verify JWS signature — throws typed errors on failure
365
492
  const manifest = verifyJws(jws, publicKeyBytes);
@@ -386,8 +513,34 @@ export async function auditVerifyCommand(args) {
386
513
  process.stderr.write("WARN: current manifest claims genesis (no previousManifest) but --prior-manifest was supplied; chain link cannot be verified\n");
387
514
  }
388
515
  const priorJws = readFileSync(args.priorManifest, "utf-8").trim();
516
+ // The prior manifest's key. Across a rotation it is not the current one,
517
+ // and it is taken from the archive only when the current key was too: a
518
+ // key the caller handed over says nothing about what the archive serves.
519
+ const priorKid = extractKidFromJws(priorJws);
520
+ validateKid(priorKid);
521
+ let priorKeyBytes;
522
+ if (priorKid === kid) {
523
+ priorKeyBytes = publicKeyBytes;
524
+ }
525
+ else if (args.priorPublicKey) {
526
+ priorKeyBytes = parsePublicKeyHex(readFileSync(args.priorPublicKey, "utf-8"));
527
+ }
528
+ else if (!args.publicKey && archiveBase) {
529
+ priorKeyBytes = await fetchArchivedPublicKey(archiveBase, priorKid);
530
+ }
531
+ else {
532
+ throw new PriorPublicKeyRequiredError(priorKid);
533
+ }
389
534
  // Verify prior manifest signature too
390
- const priorManifest = verifyJws(priorJws, publicKeyBytes);
535
+ const priorManifest = verifyJws(priorJws, priorKeyBytes);
536
+ // One chain lives at one location. A version 1 prior under a version 2
537
+ // current is the upgrade; the reverse is a downgrade no publisher makes.
538
+ if (priorManifest.version === 2) {
539
+ const currentLocation = manifest.version === 2 ? manifest.chainLocation : "none (version 1)";
540
+ if (currentLocation !== priorManifest.chainLocation) {
541
+ throw new ChainLocationMismatchError(priorManifest.chainLocation, currentLocation);
542
+ }
543
+ }
391
544
  // Check prior hash reference
392
545
  const priorCanon = canonicalize(priorManifest);
393
546
  const priorSha256 = sha256Hex(priorCanon);
@@ -401,6 +554,11 @@ export async function auditVerifyCommand(args) {
401
554
  continue;
402
555
  const priorSeq = BigInt(priorTenant.chainSeq);
403
556
  const currentSeq = BigInt(currentTenant.chainSeq);
557
+ // A chainSeq is comparable within one epoch only, so a changed epoch
558
+ // leaves the regression check below with nothing to say: say that.
559
+ if (priorTenant.epoch !== currentTenant.epoch) {
560
+ process.stderr.write(`WARN: epoch changed for tenantTag=${priorTenant.tenantTag}: prior=${priorTenant.epoch}, current=${currentTenant.epoch}; chainSeq regression was not checked for this tenant\n`);
561
+ }
404
562
  if (priorTenant.epoch === currentTenant.epoch && currentSeq < priorSeq) {
405
563
  throw new ChainSeqRegressionError(priorTenant.tenantTag, priorTenant.chainSeq, currentTenant.chainSeq);
406
564
  }
@@ -10,12 +10,14 @@
10
10
  import { loadSecretsConfig, getPasswordPath, getSecretsServerUrl } from "../lib/secrets-config.js";
11
11
  import { getEncryptionKey, getUserId } from "../lib/vault-state.js";
12
12
  import { autoUnlockIfNeeded } from "./unlock.js";
13
- import { getToken } from "../lib/api-client.js";
13
+ import { getToken, getTokenServerUrl } from "../lib/api-client.js";
14
14
  import { decryptData } from "../lib/crypto.js";
15
15
  import { buildPersonalEntryAAD, VAULT_TYPE } from "../lib/crypto-aad.js";
16
+ import { describeEntryFetchFailure } from "../lib/v1-entry-failure.js";
16
17
  import { BLOCKED_KEYS } from "../lib/blocked-keys.js";
17
18
  import { shellQuote } from "../lib/shell-quote.js";
18
19
  import * as output from "../lib/output.js";
20
+ import { onRedirectRefused } from "../lib/redirect-refusal.js";
19
21
  export async function envCommand(opts) {
20
22
  let config;
21
23
  try {
@@ -46,6 +48,8 @@ export async function envCommand(opts) {
46
48
  process.exit(1);
47
49
  }
48
50
  authHeader = `Bearer ${token}`;
51
+ // A login token goes only to the server that issued it.
52
+ baseUrl = getTokenServerUrl();
49
53
  }
50
54
  // Auto-unlock with PSSO_PASSPHRASE if needed
51
55
  if (!await autoUnlockIfNeeded()) {
@@ -65,9 +69,11 @@ export async function envCommand(opts) {
65
69
  const url = `${baseUrl}${path}`;
66
70
  const res = await fetch(url, {
67
71
  headers: { Authorization: authHeader },
68
- });
72
+ // Never let a redirect carry the bearer token to another host.
73
+ redirect: "error",
74
+ }).catch(onRedirectRefused(url));
69
75
  if (!res.ok) {
70
- output.error(`Failed to fetch entry ${mapping.entry}: HTTP ${res.status}`);
76
+ output.error(await describeEntryFetchFailure(res, mapping.entry));
71
77
  process.exit(1);
72
78
  }
73
79
  const data = (await res.json());
@@ -36,7 +36,7 @@ export async function loginCommand(opts = {}) {
36
36
  }
37
37
  saveConfig(config);
38
38
  // Revoke previous session before starting new login
39
- await revokeExistingSession(config.serverUrl);
39
+ await revokeExistingSession();
40
40
  if (opts.useToken) {
41
41
  // Manual token paste fallback (CI / headless without callback)
42
42
  await manualTokenLogin(config.serverUrl);
@@ -46,14 +46,18 @@ export async function loginCommand(opts = {}) {
46
46
  await oauthLogin(config.serverUrl);
47
47
  }
48
48
  }
49
- /** Best-effort revocation of the previous session's tokens. */
50
- async function revokeExistingSession(serverUrl) {
49
+ /**
50
+ * Best-effort revocation of the previous session's tokens, at the server that
51
+ * issued them — never the server being logged in to now, which may be another
52
+ * instance and must not receive this one's refresh token.
53
+ */
54
+ async function revokeExistingSession() {
51
55
  const creds = loadCredentials();
52
56
  if (!creds || !creds.refreshToken || !creds.clientId)
53
57
  return;
54
58
  try {
55
59
  // Revoking the refresh token also revokes all access tokens in the family
56
- await revokeTokenRequest(serverUrl, creds.refreshToken, creds.clientId, "refresh_token");
60
+ await revokeTokenRequest(creds.serverUrl, creds.refreshToken, creds.clientId, "refresh_token");
57
61
  }
58
62
  catch {
59
63
  // Best-effort — failure here should not block login
@@ -68,8 +72,9 @@ async function oauthLogin(serverUrl) {
68
72
  refreshToken: result.refreshToken,
69
73
  clientId: result.clientId,
70
74
  expiresAt,
75
+ serverUrl,
71
76
  });
72
- setTokenCache(result.accessToken, expiresAt, result.refreshToken, result.clientId);
77
+ setTokenCache(result.accessToken, serverUrl, expiresAt, result.refreshToken, result.clientId);
73
78
  output.success(`Logged in to ${serverUrl}`);
74
79
  }
75
80
  catch (err) {
@@ -92,8 +97,9 @@ async function manualTokenLogin(serverUrl) {
92
97
  refreshToken: "",
93
98
  clientId: "",
94
99
  expiresAt,
100
+ serverUrl,
95
101
  });
96
- setTokenCache(token, expiresAt);
102
+ setTokenCache(token, serverUrl, expiresAt);
97
103
  output.warn("Manual token will not auto-refresh. Use `passwd-sso login` for persistent sessions.");
98
104
  output.success(`Logged in to ${serverUrl}`);
99
105
  }
@@ -8,11 +8,13 @@ import { spawn } from "node:child_process";
8
8
  import { loadSecretsConfig, getPasswordPath, getSecretsServerUrl } from "../lib/secrets-config.js";
9
9
  import { getEncryptionKey, getUserId } from "../lib/vault-state.js";
10
10
  import { autoUnlockIfNeeded } from "./unlock.js";
11
- import { getToken } from "../lib/api-client.js";
11
+ import { getToken, getTokenServerUrl } from "../lib/api-client.js";
12
12
  import { decryptData } from "../lib/crypto.js";
13
13
  import { buildPersonalEntryAAD, VAULT_TYPE } from "../lib/crypto-aad.js";
14
+ import { describeEntryFetchFailure } from "../lib/v1-entry-failure.js";
14
15
  import * as output from "../lib/output.js";
15
16
  import { BLOCKED_KEYS } from "../lib/blocked-keys.js";
17
+ import { onRedirectRefused } from "../lib/redirect-refusal.js";
16
18
  export async function runCommand(opts) {
17
19
  if (opts.command.length === 0) {
18
20
  output.error("No command specified. Usage: passwd-sso run -- <command>");
@@ -46,6 +48,8 @@ export async function runCommand(opts) {
46
48
  process.exit(1);
47
49
  }
48
50
  authHeader = `Bearer ${token}`;
51
+ // A login token goes only to the server that issued it.
52
+ baseUrl = getTokenServerUrl();
49
53
  }
50
54
  if (!await autoUnlockIfNeeded()) {
51
55
  output.error("Vault is not unlocked. Run `passwd-sso unlock` first, or set PSSO_PASSPHRASE.");
@@ -66,9 +70,11 @@ export async function runCommand(opts) {
66
70
  const url = `${baseUrl}${path}`;
67
71
  const res = await fetch(url, {
68
72
  headers: { Authorization: authHeader },
69
- });
73
+ // Never let a redirect carry the bearer token to another host.
74
+ redirect: "error",
75
+ }).catch(onRedirectRefused(url));
70
76
  if (!res.ok) {
71
- output.error(`Failed to fetch entry ${mapping.entry}: HTTP ${res.status}`);
77
+ output.error(await describeEntryFetchFailure(res, mapping.entry));
72
78
  process.exit(1);
73
79
  }
74
80
  const data = (await res.json());
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * `passwd-sso status` — Show connection and vault status.
3
3
  */
4
- import { apiRequest } from "../lib/api-client.js";
4
+ import { apiRequest, getTokenServerUrl } from "../lib/api-client.js";
5
5
  import { isUnlocked } from "../lib/vault-state.js";
6
6
  import { loadConfig } from "../lib/config.js";
7
7
  import * as output from "../lib/output.js";
@@ -18,20 +18,29 @@ export async function statusCommand(options = {}) {
18
18
  }
19
19
  return;
20
20
  }
21
+ // Requests go to the server that issued the stored tokens, which can differ
22
+ // from the configured one; report the one actually contacted.
23
+ let server = config.serverUrl;
24
+ try {
25
+ server = getTokenServerUrl();
26
+ }
27
+ catch {
28
+ // not logged in — apiRequest below reports it
29
+ }
21
30
  try {
22
31
  const res = await apiRequest("/api/vault/status");
23
32
  if (res.ok) {
24
33
  const vaultSetup = res.data.setupRequired === false;
25
34
  if (options.json) {
26
35
  output.json({
27
- server: config.serverUrl,
36
+ server,
28
37
  vault: unlocked ? "unlocked" : "locked",
29
38
  setup: vaultSetup ? "complete" : "required",
30
39
  connected: true,
31
40
  });
32
41
  }
33
42
  else {
34
- console.log(`Server: ${config.serverUrl}`);
43
+ console.log(`Server: ${server}`);
35
44
  console.log(`Vault: ${unlocked ? "Unlocked" : "Locked"}`);
36
45
  console.log(`Setup: ${vaultSetup ? "Complete" : "Required"}`);
37
46
  output.success("Connected");
@@ -39,10 +48,10 @@ export async function statusCommand(options = {}) {
39
48
  }
40
49
  else {
41
50
  if (options.json) {
42
- output.json({ server: config.serverUrl, vault: unlocked ? "unlocked" : "locked", connected: false, error: `HTTP ${res.status}` });
51
+ output.json({ server, vault: unlocked ? "unlocked" : "locked", connected: false, error: `HTTP ${res.status}` });
43
52
  }
44
53
  else {
45
- console.log(`Server: ${config.serverUrl}`);
54
+ console.log(`Server: ${server}`);
46
55
  console.log(`Vault: ${unlocked ? "Unlocked" : "Locked"}`);
47
56
  output.error(`Server returned ${res.status}`);
48
57
  }
@@ -50,10 +59,10 @@ export async function statusCommand(options = {}) {
50
59
  }
51
60
  catch (err) {
52
61
  if (options.json) {
53
- output.json({ server: config.serverUrl, vault: unlocked ? "unlocked" : "locked", connected: false, error: err instanceof Error ? err.message : "unknown error" });
62
+ output.json({ server, vault: unlocked ? "unlocked" : "locked", connected: false, error: err instanceof Error ? err.message : "unknown error" });
54
63
  }
55
64
  else {
56
- console.log(`Server: ${config.serverUrl}`);
65
+ console.log(`Server: ${server}`);
57
66
  console.log(`Vault: ${unlocked ? "Unlocked" : "Locked"}`);
58
67
  output.error(`Connection failed: ${err instanceof Error ? err.message : "unknown error"}`);
59
68
  }
@@ -1,2 +1,4 @@
1
1
  export declare const AUDIT_ANCHOR_KID_PREFIX = "audit-anchor-";
2
+ export declare const AUDIT_ANCHOR_KID_HEX_CHARS = 16;
2
3
  export declare const AUDIT_ANCHOR_TYP = "passwd-sso.audit-anchor.v1";
4
+ export declare const AUDIT_ANCHOR_ARTIFACT_MAX_BYTES: number;
@@ -1,4 +1,6 @@
1
1
  // Mirrors src/lib/constants/audit/audit.ts — drift caught by parity test.
2
2
  export const AUDIT_ANCHOR_KID_PREFIX = "audit-anchor-";
3
+ export const AUDIT_ANCHOR_KID_HEX_CHARS = 16;
3
4
  export const AUDIT_ANCHOR_TYP = "passwd-sso.audit-anchor.v1";
5
+ export const AUDIT_ANCHOR_ARTIFACT_MAX_BYTES = 8 * 1024 * 1024;
4
6
  //# sourceMappingURL=audit-anchor.js.map
package/dist/index.js CHANGED
@@ -21,7 +21,7 @@ import { runCommand } from "./commands/run.js";
21
21
  import { apiKeyListCommand, apiKeyCreateCommand, apiKeyRevokeCommand } from "./commands/api-key.js";
22
22
  import { agentCommand } from "./commands/agent.js";
23
23
  import { decryptCommand } from "./commands/decrypt.js";
24
- import { auditVerifyCommand, InvalidAlgorithmError, InvalidTypError, InvalidSignatureError, ManifestSchemaValidationError, InvalidTenantIdFormatError, TenantNotInManifestError, ChainBreakError, ChainSeqRegressionError, InvalidTagSecretLengthError, } from "./commands/audit-verify.js";
24
+ import { auditVerifyCommand, InvalidAlgorithmError, InvalidTypError, InvalidSignatureError, ManifestSchemaValidationError, InvalidTenantIdFormatError, TenantNotInManifestError, ChainBreakError, ChainSeqRegressionError, InvalidTagSecretLengthError, KidMismatchError, ChainLocationMismatchError, } from "./commands/audit-verify.js";
25
25
  import { isUnlocked, lockVault } from "./lib/vault-state.js";
26
26
  import { clearPendingClipboard } from "./lib/clipboard.js";
27
27
  import { setInsecure, clearTokenCache, startBackgroundRefresh, stopBackgroundRefresh } from "./lib/api-client.js";
@@ -137,6 +137,7 @@ program
137
137
  .option("--tag-secret-file <path>", "Path to file containing hex tag secret (recommended; must be mode 0600)")
138
138
  .option("--tag-secret <hex>", "Hex tag secret on the CLI (discouraged — recorded in shell history)")
139
139
  .option("--prior-manifest <path>", "Prior manifest JWS file for regression check")
140
+ .option("--prior-public-key <path>", "Path to the prior manifest's .pub file, when it was signed under another key")
140
141
  .option("--archive-url <url>", "Override AUDIT_ANCHOR_PUBLIC_KEY_ARCHIVE_URL for public key fetch")
141
142
  .action(async (opts) => {
142
143
  try {
@@ -147,6 +148,7 @@ program
147
148
  tagSecret: opts.tagSecret,
148
149
  tagSecretFile: opts.tagSecretFile,
149
150
  priorManifest: opts.priorManifest,
151
+ priorPublicKey: opts.priorPublicKey,
150
152
  archiveUrl: opts.archiveUrl,
151
153
  });
152
154
  }
@@ -171,6 +173,10 @@ program
171
173
  process.exit(17);
172
174
  else if (err instanceof InvalidTagSecretLengthError)
173
175
  process.exit(18);
176
+ else if (err instanceof KidMismatchError)
177
+ process.exit(19);
178
+ else if (err instanceof ChainLocationMismatchError)
179
+ process.exit(20);
174
180
  else
175
181
  process.exit(1);
176
182
  }
@@ -6,9 +6,15 @@
6
6
  */
7
7
  export declare function setInsecure(enabled: boolean): void;
8
8
  export declare function getToken(): string | null;
9
- export declare function setTokenCache(token: string, expiresAt?: string, refreshToken?: string, clientId?: string): void;
9
+ export declare function setTokenCache(token: string, serverUrl: string, expiresAt?: string, refreshToken?: string, clientId?: string): void;
10
10
  export declare function clearTokenCache(): void;
11
11
  export declare function assertLoggedIn(): void;
12
+ /**
13
+ * The server that issued the cached tokens. Tokens are only ever sent there:
14
+ * the configured serverUrl can point elsewhere (a later `login` to another
15
+ * server, a hand-edited config) and must not receive this server's tokens.
16
+ */
17
+ export declare function getTokenServerUrl(): string;
12
18
  export interface ApiResponse<T = unknown> {
13
19
  ok: boolean;
14
20
  status: number;
@@ -4,13 +4,15 @@
4
4
  * Uses native Node.js fetch with Bearer token authentication.
5
5
  * Automatically refreshes expired tokens via OAuth 2.1 refresh_token grant.
6
6
  */
7
- import { loadCredentials, saveCredentials, loadConfig } from "./config.js";
7
+ import { loadCredentials, saveCredentials } from "./config.js";
8
8
  import { refreshTokenGrant } from "./oauth.js";
9
9
  import { MS_PER_MINUTE, MS_PER_SECOND } from "./time.js";
10
+ import { onRedirectRefused } from "./redirect-refusal.js";
10
11
  let cachedToken = null;
11
12
  let cachedExpiresAt = null;
12
13
  let cachedRefreshToken = null;
13
14
  let cachedClientId = null;
15
+ let cachedServerUrl = null;
14
16
  export function setInsecure(enabled) {
15
17
  if (enabled) {
16
18
  process.stderr.write("WARNING: TLS certificate verification is disabled. Your credentials may be intercepted.\n");
@@ -27,10 +29,12 @@ export function getToken() {
27
29
  cachedExpiresAt = new Date(creds.expiresAt).getTime();
28
30
  cachedRefreshToken = creds.refreshToken || null;
29
31
  cachedClientId = creds.clientId || null;
32
+ cachedServerUrl = creds.serverUrl;
30
33
  return cachedToken;
31
34
  }
32
- export function setTokenCache(token, expiresAt, refreshToken, clientId) {
35
+ export function setTokenCache(token, serverUrl, expiresAt, refreshToken, clientId) {
33
36
  cachedToken = token;
37
+ cachedServerUrl = serverUrl;
34
38
  if (expiresAt) {
35
39
  cachedExpiresAt = new Date(expiresAt).getTime();
36
40
  }
@@ -46,18 +50,23 @@ export function clearTokenCache() {
46
50
  cachedExpiresAt = null;
47
51
  cachedRefreshToken = null;
48
52
  cachedClientId = null;
53
+ cachedServerUrl = null;
49
54
  }
50
55
  export function assertLoggedIn() {
51
56
  if (!getToken()) {
52
57
  throw new Error("Not logged in. Run `passwd-sso login` first.");
53
58
  }
54
59
  }
55
- function getBaseUrl() {
56
- const config = loadConfig();
57
- if (!config.serverUrl) {
58
- throw new Error("Server URL not configured. Run `passwd-sso login` first.");
60
+ /**
61
+ * The server that issued the cached tokens. Tokens are only ever sent there:
62
+ * the configured serverUrl can point elsewhere (a later `login` to another
63
+ * server, a hand-edited config) and must not receive this server's tokens.
64
+ */
65
+ export function getTokenServerUrl() {
66
+ if (!getToken() || !cachedServerUrl) {
67
+ throw new Error("Not logged in. Run `passwd-sso login` first.");
59
68
  }
60
- return config.serverUrl.replace(/\/$/, "");
69
+ return cachedServerUrl;
61
70
  }
62
71
  const REFRESH_BUFFER_MS = 2 * MS_PER_MINUTE;
63
72
  function isTokenExpiringSoon() {
@@ -68,7 +77,7 @@ function isTokenExpiringSoon() {
68
77
  async function refreshToken() {
69
78
  if (!cachedRefreshToken || !cachedClientId)
70
79
  return false;
71
- const baseUrl = getBaseUrl();
80
+ const baseUrl = getTokenServerUrl();
72
81
  try {
73
82
  const result = await refreshTokenGrant(baseUrl, cachedRefreshToken, cachedClientId);
74
83
  if (!result || !result.refreshToken)
@@ -79,8 +88,9 @@ async function refreshToken() {
79
88
  refreshToken: result.refreshToken,
80
89
  clientId: cachedClientId,
81
90
  expiresAt,
91
+ serverUrl: baseUrl,
82
92
  });
83
- setTokenCache(result.accessToken, expiresAt, result.refreshToken, cachedClientId);
93
+ setTokenCache(result.accessToken, baseUrl, expiresAt, result.refreshToken, cachedClientId);
84
94
  return true;
85
95
  }
86
96
  catch {
@@ -96,11 +106,14 @@ export async function apiRequest(path, options = {}) {
96
106
  token = getToken();
97
107
  }
98
108
  }
99
- const baseUrl = getBaseUrl();
109
+ const baseUrl = getTokenServerUrl();
100
110
  const url = `${baseUrl}${path}`;
101
111
  const { method = "GET", body, headers = {} } = options;
102
112
  const fetchOpts = {
103
113
  method,
114
+ // The bearer token and body go to the issuing server only; it never
115
+ // legitimately redirects these requests.
116
+ redirect: "error",
104
117
  headers: {
105
118
  Authorization: `Bearer ${token}`,
106
119
  ...(body !== undefined ? { "Content-Type": "application/json" } : {}),
@@ -110,7 +123,7 @@ export async function apiRequest(path, options = {}) {
110
123
  if (body !== undefined) {
111
124
  fetchOpts.body = JSON.stringify(body);
112
125
  }
113
- let res = await fetch(url, fetchOpts);
126
+ let res = await fetch(url, fetchOpts).catch(onRedirectRefused(url));
114
127
  if (res.status === 401) {
115
128
  const refreshed = await refreshToken();
116
129
  if (refreshed) {
@@ -119,7 +132,7 @@ export async function apiRequest(path, options = {}) {
119
132
  ...fetchOpts.headers,
120
133
  Authorization: `Bearer ${newToken}`,
121
134
  };
122
- res = await fetch(url, fetchOpts);
135
+ res = await fetch(url, fetchOpts).catch(onRedirectRefused(url));
123
136
  }
124
137
  }
125
138
  const data = (await res.json().catch(() => ({})));
@@ -22,6 +22,13 @@ export type MainApiErrorBody = {
22
22
  readonly lockedUntil?: string | null;
23
23
  readonly currentKeyVersion?: number;
24
24
  };
25
+ /**
26
+ * Parse `res`'s JSON body once per `Response`; later calls return the same
27
+ * parse. A body can be read only once, so without this a second reader of an
28
+ * error response gets `null`. Never rejects: an unparseable body is `null`.
29
+ * Only for error-path readers — success paths read their body themselves.
30
+ */
31
+ export declare function parseJsonBodyOnce(res: Response): Promise<unknown>;
25
32
  export declare function readApiErrorBody(res: Response): Promise<MainApiErrorBody | null>;
26
33
  /**
27
34
  * Read `details.message` from an already-parsed error body.
@@ -16,10 +16,26 @@
16
16
  * those endpoints belong in `cli/src/lib/oauth.ts` and are intentionally not
17
17
  * migrated here.
18
18
  */
19
+ /**
20
+ * Parse `res`'s JSON body once per `Response`; later calls return the same
21
+ * parse. A body can be read only once, so without this a second reader of an
22
+ * error response gets `null`. Never rejects: an unparseable body is `null`.
23
+ * Only for error-path readers — success paths read their body themselves.
24
+ */
25
+ export function parseJsonBodyOnce(res) {
26
+ let parse = jsonBodyParses.get(res);
27
+ if (!parse) {
28
+ parse = res.json().catch(() => null);
29
+ jsonBodyParses.set(res, parse);
30
+ }
31
+ return parse;
32
+ }
33
+ // Keyed weakly: an entry lives only as long as its Response.
34
+ const jsonBodyParses = new WeakMap();
19
35
  export async function readApiErrorBody(res) {
20
36
  if (res.ok)
21
37
  return null;
22
- const json = await res.json().catch(() => null);
38
+ const json = await parseJsonBodyOnce(res);
23
39
  if (!json ||
24
40
  typeof json !== "object" ||
25
41
  typeof json.error !== "string") {
@@ -17,6 +17,12 @@ export interface StoredCredentials {
17
17
  refreshToken: string;
18
18
  clientId: string;
19
19
  expiresAt: string;
20
+ /**
21
+ * The server that issued these tokens (normalised, no trailing slash). Every
22
+ * request carrying them goes here, never to the configured serverUrl, which
23
+ * `login` rewrites before the old tokens are revoked.
24
+ */
25
+ serverUrl: string;
20
26
  }
21
27
  /**
22
28
  * Write credentials to the data directory using O_NOFOLLOW to prevent
@@ -26,7 +32,9 @@ export declare function saveCredentials(creds: StoredCredentials): void;
26
32
  /**
27
33
  * Load stored credentials. Returns null if the file does not exist,
28
34
  * cannot be parsed as JSON, or is missing required fields (e.g. legacy
29
- * plaintext token format written by older CLI versions).
35
+ * plaintext token format written by older CLI versions, or credentials
36
+ * saved before the issuing serverUrl was recorded — those must re-login
37
+ * rather than have their tokens sent to whatever server is configured now).
30
38
  */
31
39
  export declare function loadCredentials(): StoredCredentials | null;
32
40
  /** Remove the stored credentials file. Silently ignores missing-file errors. */
@@ -6,25 +6,34 @@
6
6
  *
7
7
  * Legacy ~/.passwd-sso/ is auto-migrated on first access.
8
8
  */
9
- import { existsSync, mkdirSync, readFileSync, writeFileSync, lstatSync, unlinkSync, } from "node:fs";
9
+ import { chmodSync, existsSync, mkdirSync, readFileSync, lstatSync, unlinkSync, } from "node:fs";
10
10
  import { getConfigDir, getDataDir, getConfigFilePath, getCredentialsFilePath, } from "./paths.js";
11
11
  import { writeSecretFile, readSecretFile } from "./secure-file.js";
12
12
  import { migrateIfNeeded } from "./migrate.js";
13
+ import { validateServerUrl } from "./oauth.js";
13
14
  const DEFAULT_CONFIG = {
14
15
  serverUrl: "",
15
16
  locale: "en",
16
17
  };
17
- function ensureConfigDir() {
18
- const dir = getConfigDir();
18
+ /**
19
+ * Create `dir` 0700, or tighten it to 0700 if it already exists: mkdirSync's
20
+ * mode applies only to a freshly created directory. A symlink is left alone
21
+ * (callers refuse to write through one).
22
+ */
23
+ function ensurePrivateDir(dir) {
19
24
  if (!existsSync(dir)) {
20
25
  mkdirSync(dir, { mode: 0o700, recursive: true });
26
+ return;
27
+ }
28
+ if (!lstatSync(dir).isSymbolicLink()) {
29
+ chmodSync(dir, 0o700);
21
30
  }
22
31
  }
32
+ function ensureConfigDir() {
33
+ ensurePrivateDir(getConfigDir());
34
+ }
23
35
  function ensureDataDir() {
24
- const dir = getDataDir();
25
- if (!existsSync(dir)) {
26
- mkdirSync(dir, { mode: 0o700, recursive: true });
27
- }
36
+ ensurePrivateDir(getDataDir());
28
37
  }
29
38
  export function loadConfig() {
30
39
  migrateIfNeeded();
@@ -39,9 +48,7 @@ export function loadConfig() {
39
48
  }
40
49
  export function saveConfig(config) {
41
50
  ensureConfigDir();
42
- writeFileSync(getConfigFilePath(), JSON.stringify(config, null, 2), {
43
- mode: 0o600,
44
- });
51
+ writeSecretFile(getConfigFilePath(), JSON.stringify(config, null, 2));
45
52
  }
46
53
  /**
47
54
  * Write credentials to the data directory using O_NOFOLLOW to prevent
@@ -58,7 +65,9 @@ export function saveCredentials(creds) {
58
65
  /**
59
66
  * Load stored credentials. Returns null if the file does not exist,
60
67
  * cannot be parsed as JSON, or is missing required fields (e.g. legacy
61
- * plaintext token format written by older CLI versions).
68
+ * plaintext token format written by older CLI versions, or credentials
69
+ * saved before the issuing serverUrl was recorded — those must re-login
70
+ * rather than have their tokens sent to whatever server is configured now).
62
71
  */
63
72
  export function loadCredentials() {
64
73
  migrateIfNeeded();
@@ -88,14 +97,22 @@ export function loadCredentials() {
88
97
  if (typeof obj.accessToken !== "string" ||
89
98
  typeof obj.refreshToken !== "string" ||
90
99
  typeof obj.clientId !== "string" ||
91
- typeof obj.expiresAt !== "string") {
100
+ typeof obj.expiresAt !== "string" ||
101
+ typeof obj.serverUrl !== "string" ||
102
+ obj.serverUrl === "") {
92
103
  return null;
93
104
  }
105
+ // The tokens are sent to this URL; a hand-edited file must not redirect
106
+ // them to a non-https or credential-bearing URL.
107
+ validateServerUrl(obj.serverUrl);
94
108
  return {
95
109
  accessToken: obj.accessToken,
96
110
  refreshToken: obj.refreshToken,
97
111
  clientId: obj.clientId,
98
112
  expiresAt: obj.expiresAt,
113
+ // Callers append `/api/...`; `login` writes it without the slash, but a
114
+ // hand-edited file may carry one.
115
+ serverUrl: obj.serverUrl.replace(/\/$/, ""),
99
116
  };
100
117
  }
101
118
  catch {
@@ -3,10 +3,27 @@
3
3
  *
4
4
  * Called once on first access. Idempotent — safe to call multiple times.
5
5
  */
6
- import { copyFileSync, chmodSync, existsSync, lstatSync, mkdirSync, readdirSync, renameSync, rmSync, unlinkSync, } from "node:fs";
6
+ import { closeSync, constants as fsConstants, copyFileSync, chmodSync, existsSync, fchmodSync, fstatSync, lstatSync, mkdirSync, openSync, readdirSync, renameSync, rmSync, unlinkSync, } from "node:fs";
7
7
  import { join } from "node:path";
8
8
  import { getLegacyDir, getConfigDir, getDataDir } from "./paths.js";
9
9
  let migrationDone = false;
10
+ /**
11
+ * chmod 0600 through an O_NOFOLLOW descriptor, refusing anything but a regular
12
+ * file: a path-based chmod would follow a symlinked legacy file and change the
13
+ * mode of whatever it points at.
14
+ */
15
+ function tightenRegularFile(path) {
16
+ const fd = openSync(path, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0));
17
+ try {
18
+ if (!fstatSync(fd).isFile()) {
19
+ throw new Error(`Refusing to migrate ${path}: not a regular file`);
20
+ }
21
+ fchmodSync(fd, 0o600);
22
+ }
23
+ finally {
24
+ closeSync(fd);
25
+ }
26
+ }
10
27
  /**
11
28
  * Move a single file from `src` to `dest`, creating `destDir` if needed.
12
29
  * Handles cross-device moves (EXDEV) by falling back to copy + delete.
@@ -14,6 +31,10 @@ let migrationDone = false;
14
31
  function moveFile(src, dest, destDir) {
15
32
  try {
16
33
  mkdirSync(destDir, { mode: 0o700, recursive: true });
34
+ // rename (and copyFile below) keep the legacy file's mode, which may be
35
+ // group/other-readable. Tighten the source first: if that fails nothing has
36
+ // moved, and a moved file is never left at the old mode.
37
+ tightenRegularFile(src);
17
38
  renameSync(src, dest);
18
39
  return true;
19
40
  }
package/dist/lib/oauth.js CHANGED
@@ -8,6 +8,7 @@ import { randomBytes, createHash, timingSafeEqual } from "node:crypto";
8
8
  import { createServer, } from "node:http";
9
9
  import { spawn } from "node:child_process";
10
10
  import { MS_PER_MINUTE, MS_PER_SECOND, SEC_PER_HOUR } from "./time.js";
11
+ import { onRedirectRefused } from "./redirect-refusal.js";
11
12
  const CALLBACK_TIMEOUT_MS = 2 * MS_PER_MINUTE;
12
13
  const CLI_CLIENT_NAME = "passwd-sso-cli";
13
14
  const CLI_SCOPES = "credentials:list credentials:use vault:status vault:unlock-data passwords:read passwords:write ssh:sign";
@@ -136,6 +137,7 @@ export async function startCallbackServer(expectedState) {
136
137
  export async function registerClient(serverUrl, redirectUri) {
137
138
  const response = await fetch(`${serverUrl}${MCP_REGISTER_ENDPOINT}`, {
138
139
  method: "POST",
140
+ redirect: "error",
139
141
  headers: { "Content-Type": "application/json" },
140
142
  body: JSON.stringify({
141
143
  client_name: CLI_CLIENT_NAME,
@@ -145,7 +147,7 @@ export async function registerClient(serverUrl, redirectUri) {
145
147
  token_endpoint_auth_method: "none",
146
148
  scope: CLI_SCOPES,
147
149
  }),
148
- });
150
+ }).catch(onRedirectRefused(serverUrl));
149
151
  if (!response.ok) {
150
152
  const text = await response.text().catch(() => "");
151
153
  throw new Error(`DCR registration failed (${response.status}): ${text}`);
@@ -185,6 +187,9 @@ function parseTokenResponse(data) {
185
187
  export async function exchangeCode(serverUrl, params) {
186
188
  const response = await fetch(`${serverUrl}${MCP_TOKEN_ENDPOINT}`, {
187
189
  method: "POST",
190
+ // A 307/308 would resend this body — the code and verifier — to wherever
191
+ // the redirect points; the token endpoint never legitimately redirects.
192
+ redirect: "error",
188
193
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
189
194
  body: new URLSearchParams({
190
195
  grant_type: "authorization_code",
@@ -193,7 +198,7 @@ export async function exchangeCode(serverUrl, params) {
193
198
  client_id: params.clientId,
194
199
  code_verifier: params.codeVerifier,
195
200
  }).toString(),
196
- });
201
+ }).catch(onRedirectRefused(serverUrl));
197
202
  if (!response.ok) {
198
203
  const text = await response.text().catch(() => "");
199
204
  throw new Error(`Token exchange failed (${response.status}): ${text}`);
@@ -206,13 +211,15 @@ export async function exchangeCode(serverUrl, params) {
206
211
  export async function refreshTokenGrant(serverUrl, refreshToken, clientId) {
207
212
  const response = await fetch(`${serverUrl}${MCP_TOKEN_ENDPOINT}`, {
208
213
  method: "POST",
214
+ // Never let a redirect carry the refresh token to another host.
215
+ redirect: "error",
209
216
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
210
217
  body: new URLSearchParams({
211
218
  grant_type: "refresh_token",
212
219
  refresh_token: refreshToken,
213
220
  client_id: clientId,
214
221
  }).toString(),
215
- });
222
+ }).catch(onRedirectRefused(serverUrl));
216
223
  if (!response.ok)
217
224
  return null;
218
225
  const data = (await response.json());
@@ -227,6 +234,8 @@ export async function revokeTokenRequest(serverUrl, token, clientId, tokenTypeHi
227
234
  try {
228
235
  await fetch(`${serverUrl}${MCP_REVOKE_ENDPOINT}`, {
229
236
  method: "POST",
237
+ // Never let a redirect carry the token to another host.
238
+ redirect: "error",
230
239
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
231
240
  body: new URLSearchParams(params).toString(),
232
241
  });
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Credential-bearing requests use `redirect: "error"`, so a server that
3
+ * redirects (http→https, apex→www, a canonicalising proxy) makes fetch reject
4
+ * with undici's bare "fetch failed". Rethrow that one case with the fix the
5
+ * user needs; every other error passes through unchanged.
6
+ *
7
+ * Usage: `await fetch(url, init).catch(onRedirectRefused(url))`
8
+ */
9
+ export declare function onRedirectRefused(url: string): (err: unknown) => never;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Credential-bearing requests use `redirect: "error"`, so a server that
3
+ * redirects (http→https, apex→www, a canonicalising proxy) makes fetch reject
4
+ * with undici's bare "fetch failed". Rethrow that one case with the fix the
5
+ * user needs; every other error passes through unchanged.
6
+ *
7
+ * Usage: `await fetch(url, init).catch(onRedirectRefused(url))`
8
+ */
9
+ export function onRedirectRefused(url) {
10
+ return (err) => {
11
+ if (err instanceof TypeError &&
12
+ err.cause instanceof Error &&
13
+ err.cause.message === "unexpected redirect") {
14
+ throw new Error(`The server at ${new URL(url).origin} redirected the request, and requests carrying credentials do not follow redirects. ` +
15
+ "Set the server URL to its final address: passwd-sso login --server <url>", { cause: err });
16
+ }
17
+ throw err;
18
+ };
19
+ }
20
+ //# sourceMappingURL=redirect-refusal.js.map
@@ -89,7 +89,9 @@ export function getSecretsServerUrl() {
89
89
  * If apiKey is configured, use the public /api/v1/ path.
90
90
  */
91
91
  export function getPasswordPath(entryId, useV1) {
92
- if (/[\/\\]/.test(entryId)) {
92
+ // "." and ".." survive encodeURIComponent and are dot segments to the URL
93
+ // parser, so they would turn the request into the list or /api/ route.
94
+ if (/[\/\\]/.test(entryId) || entryId === "." || entryId === "..") {
93
95
  throw new Error(`Invalid entry ID: "${entryId}"`);
94
96
  }
95
97
  return useV1
@@ -10,7 +10,7 @@
10
10
  * module). Keep the O_NOFOLLOW semantics in sync. This copy adds an `encoding`
11
11
  * param + codeql annotation the e2e copy intentionally omits.
12
12
  */
13
- import { openSync, writeSync, closeSync, readFileSync, constants as fsConstants, } from "node:fs";
13
+ import { openSync, fchmodSync, writeSync, closeSync, readFileSync, constants as fsConstants, } from "node:fs";
14
14
  /** Write `data` to `path` with O_NOFOLLOW + the given mode (default 0600). */
15
15
  export function writeSecretFile(path, data, mode = 0o600) {
16
16
  const fd = openSync(path, fsConstants.O_WRONLY |
@@ -18,6 +18,10 @@ export function writeSecretFile(path, data, mode = 0o600) {
18
18
  fsConstants.O_TRUNC |
19
19
  (fsConstants.O_NOFOLLOW ?? 0), mode);
20
20
  try {
21
+ // open()'s mode applies only when the file is created; an existing file
22
+ // keeps its old mode (e.g. 0644), so set it on the descriptor before the
23
+ // secret is written.
24
+ fchmodSync(fd, mode);
21
25
  // Intentional persistence of the caller's own secrets (OAuth tokens /
22
26
  // decrypted export) to a 0600 O_NOFOLLOW file. CodeQL js/http-to-file-access
23
27
  // is excluded for this in .github/codeql/codeql-config.yml (inline
@@ -0,0 +1,2 @@
1
+ /** The message `env` and `run` print when a v1 entry fetch is refused. */
2
+ export declare function describeEntryFetchFailure(res: Response, entry: string): Promise<string>;
@@ -0,0 +1,10 @@
1
+ import { readApiErrorBody } from "./api-error-body.js";
2
+ /** The message `env` and `run` print when a v1 entry fetch is refused. */
3
+ export async function describeEntryFetchFailure(res, entry) {
4
+ const errorBody = await readApiErrorBody(res);
5
+ if (errorBody?.error === "PASSKEY_REQUIRED") {
6
+ return "This tenant requires a passkey to be registered in the browser.";
7
+ }
8
+ return `Failed to fetch entry ${entry}: HTTP ${res.status}`;
9
+ }
10
+ //# sourceMappingURL=v1-entry-failure.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "passwd-sso-cli",
3
- "version": "0.4.76",
3
+ "version": "0.5.0",
4
4
  "description": "CLI for passwd-sso password manager",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -42,7 +42,7 @@
42
42
  "chalk": "^6.0.0",
43
43
  "cli-table3": "^0.6.5",
44
44
  "clipboardy": "^5.3.1",
45
- "commander": "^15.0.0",
45
+ "commander": "^15.1.0",
46
46
  "inquirer": "^14.0.2",
47
47
  "otpauth": "^9.4.0",
48
48
  "zod": "^4.3.6"