@deque/axe-auth 1.1.0-next.907ffbd7 → 1.1.0-next.ac35e028

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.
Files changed (51) hide show
  1. package/README.md +56 -9
  2. package/dist/cli/commonArgs.d.ts +66 -0
  3. package/dist/cli/commonArgs.help.d.ts +2 -0
  4. package/dist/cli/commonArgs.help.js +19 -0
  5. package/dist/cli/commonArgs.js +119 -0
  6. package/dist/cli/confirm.d.ts +17 -0
  7. package/dist/cli/confirm.js +56 -0
  8. package/dist/cli/errors.d.ts +30 -0
  9. package/dist/cli/errors.js +52 -0
  10. package/dist/cli/testUtils.d.ts +52 -0
  11. package/dist/cli/testUtils.js +100 -0
  12. package/dist/cli/types.d.ts +82 -0
  13. package/dist/cli/types.js +2 -0
  14. package/dist/commands/login.d.ts +41 -0
  15. package/dist/commands/login.help.d.ts +2 -0
  16. package/dist/commands/login.help.js +35 -0
  17. package/dist/commands/login.js +93 -0
  18. package/dist/commands/logout.d.ts +24 -0
  19. package/dist/commands/logout.help.d.ts +2 -0
  20. package/dist/commands/logout.help.js +37 -0
  21. package/dist/commands/logout.js +84 -0
  22. package/dist/commands/token.d.ts +26 -0
  23. package/dist/commands/token.help.d.ts +2 -0
  24. package/dist/commands/token.help.js +41 -0
  25. package/dist/commands/token.js +56 -0
  26. package/dist/index.js +142 -22
  27. package/dist/oauth/authorize.d.ts +4 -3
  28. package/dist/oauth/authorize.js +8 -4
  29. package/dist/oauth/discoverOIDC.js +5 -7
  30. package/dist/oauth/errors.d.ts +3 -1
  31. package/dist/oauth/getValidAccessToken.d.ts +89 -0
  32. package/dist/oauth/getValidAccessToken.js +139 -0
  33. package/dist/oauth/index.d.ts +7 -2
  34. package/dist/oauth/index.js +5 -1
  35. package/dist/oauth/keyringBinding.d.ts +22 -0
  36. package/dist/oauth/keyringBinding.js +41 -0
  37. package/dist/oauth/predicates.d.ts +7 -0
  38. package/dist/oauth/predicates.js +15 -0
  39. package/dist/oauth/refreshTokens.d.ts +30 -0
  40. package/dist/oauth/refreshTokens.js +61 -0
  41. package/dist/oauth/revokeToken.d.ts +28 -0
  42. package/dist/oauth/revokeToken.js +59 -0
  43. package/dist/oauth/testUtils.d.ts +35 -0
  44. package/dist/oauth/testUtils.js +61 -0
  45. package/dist/oauth/tokenExchange.d.ts +1 -24
  46. package/dist/oauth/tokenExchange.js +3 -97
  47. package/dist/oauth/tokenResponse.d.ts +54 -0
  48. package/dist/oauth/tokenResponse.js +121 -0
  49. package/dist/oauth/tokenStore.d.ts +57 -24
  50. package/dist/oauth/tokenStore.js +104 -82
  51. package/package.json +5 -2
@@ -1,10 +1,27 @@
1
- import type { TokenSet } from "./tokenExchange";
1
+ import { type KeyringEntryFactory } from "./keyringBinding";
2
+ import type { TokenSet } from "./tokenResponse";
2
3
  /**
3
4
  * Current on-disk blob schema version. Exported so consumers can
4
5
  * display "stored v:N, expected v:M" diagnostics when `load()` returns
5
6
  * a `version-mismatch` result.
6
7
  */
7
8
  export declare const STORED_BLOB_VERSION = 1;
9
+ /**
10
+ * What `KeyringTokenStore` persists: the OAuth tokens plus the
11
+ * issuer/client coordinates they were minted against. Carrying the
12
+ * coordinates inside the entry means a verb can recover its full
13
+ * config from the keychain alone, with no separate "default issuer"
14
+ * pointer.
15
+ */
16
+ export interface StoredEntry {
17
+ tokens: TokenSet;
18
+ /** OIDC issuer URL the tokens were minted against. */
19
+ issuerURL: string;
20
+ /** OAuth client ID used at login. */
21
+ clientId: string;
22
+ /** Whether the original login allowed a non-loopback http issuer. */
23
+ allowInsecureIssuer: boolean;
24
+ }
8
25
  /**
9
26
  * Outcome of a `TokenStore.load()` call.
10
27
  *
@@ -19,7 +36,7 @@ export declare const STORED_BLOB_VERSION = 1;
19
36
  */
20
37
  export type LoadResult = {
21
38
  ok: true;
22
- tokens: TokenSet;
39
+ entry: StoredEntry;
23
40
  } | {
24
41
  ok: false;
25
42
  reason: "empty";
@@ -31,48 +48,64 @@ export type LoadResult = {
31
48
  reason: "version-mismatch";
32
49
  storedVersion: number;
33
50
  };
34
- /** Persistence layer for an OAuth `TokenSet`. */
51
+ /** Persistence layer for an OAuth `StoredEntry`. */
35
52
  export interface TokenStore {
36
- /** Write-through save. Replaces any previously stored tokens. */
37
- save(tokens: TokenSet): Promise<void>;
53
+ /** Write-through save. Replaces any previously stored entry. */
54
+ save(entry: StoredEntry): Promise<void>;
38
55
  /**
39
- * Reads the stored tokens and returns a structured result.
56
+ * Reads the stored entry and returns a structured result.
40
57
  *
41
58
  * Callers should branch on `result.ok` first. When `ok` is `false`,
42
- * `reason` tells them *why* there is no usable `TokenSet`: `empty`
59
+ * `reason` tells them *why* there is no usable entry: `empty`
43
60
  * (nothing stored), `corrupt` (unparseable or shape-invalid), or
44
61
  * `version-mismatch` (stored under a schema we cannot migrate from).
45
62
  * The library does not emit output on these cases — surfacing them
46
63
  * to the user is the caller's responsibility.
47
64
  */
48
65
  load(): Promise<LoadResult>;
49
- /** Removes any stored tokens. No-op if none are present. */
66
+ /** Removes any stored entry. No-op if none is present. */
50
67
  clear(): Promise<void>;
51
68
  }
52
- /** Minimal keyring-entry surface consumed by `KeyringTokenStore`. */
53
- export interface KeyringEntry {
54
- /** Writes the password for this entry. */
55
- setPassword(password: string): void;
56
- /** Reads the current password, or returns `null` if none is set. */
57
- getPassword(): string | null;
58
- /** Deletes the password and returns `true` if one existed. */
59
- deletePassword(): boolean;
60
- }
61
69
  /**
62
- * Factory for `KeyringEntry` values. Injection seam for tests;
63
- * production callers use the default that constructs
64
- * `@napi-rs/keyring` entries lazily.
70
+ * Outcome of `parseAndMigrateBlob`: same set of failure reasons as
71
+ * `LoadResult`, but on success carries the post-migration blob as an
72
+ * unknown payload. The caller is responsible for shape-validating
73
+ * that payload against the latest schema.
74
+ */
75
+ export type BlobChainResult = {
76
+ ok: true;
77
+ blob: unknown;
78
+ } | {
79
+ ok: false;
80
+ reason: "empty";
81
+ } | {
82
+ ok: false;
83
+ reason: "corrupt";
84
+ } | {
85
+ ok: false;
86
+ reason: "version-mismatch";
87
+ storedVersion: number;
88
+ };
89
+ /**
90
+ * JSON-parses the raw keychain password and walks the migrator chain
91
+ * until it reaches `expectedVersion`. Exported with `expectedVersion`
92
+ * and `migrators` parameters only for testing the chain mechanics
93
+ * against synthetic versions / migrators; production callers use
94
+ * `KeyringTokenStore.load()`, which feeds in `STORED_BLOB_VERSION`
95
+ * and `MIGRATORS` and applies the latest-shape check on top.
65
96
  */
66
- export type KeyringEntryFactory = (service: string, account: string) => KeyringEntry;
97
+ export declare function parseAndMigrateBlob(raw: string | null, expectedVersion?: number, migrators?: ReadonlyMap<number, (old: unknown) => unknown | null>): BlobChainResult;
67
98
  /**
68
99
  * `TokenStore` backed by the operating system's native keychain via
69
100
  * `@napi-rs/keyring` (macOS Keychain, Windows Credential Manager, Linux
70
- * Secret Service). Account is keyed by the normalized issuer URL.
101
+ * Secret Service). One entry per machine, keyed by a fixed account
102
+ * name; the blob carries its own issuer/client coordinates so verbs
103
+ * can recover full config without per-issuer keying.
71
104
  */
72
105
  export declare class KeyringTokenStore implements TokenStore {
73
106
  #private;
74
- constructor(issuerURL: string, entryFactory?: KeyringEntryFactory);
75
- save(tokens: TokenSet): Promise<void>;
107
+ constructor(entryFactory?: KeyringEntryFactory);
108
+ save(entry: StoredEntry): Promise<void>;
76
109
  load(): Promise<LoadResult>;
77
110
  clear(): Promise<void>;
78
111
  }
@@ -1,15 +1,24 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.KeyringTokenStore = exports.STORED_BLOB_VERSION = void 0;
4
- const node_module_1 = require("node:module");
4
+ exports.parseAndMigrateBlob = parseAndMigrateBlob;
5
5
  const errors_1 = require("./errors");
6
- const issuerURL_1 = require("./issuerURL");
7
- const requireFromHere = (0, node_module_1.createRequire)(__filename);
6
+ const keyringBinding_1 = require("./keyringBinding");
8
7
  // On macOS: Keychain generic password item with the service name below.
9
8
  // On Windows: Credential Manager entry. On Linux: Secret Service / libsecret.
10
9
  // Exposed as a human-readable string because these all surface the service
11
10
  // name in OS UIs (Keychain Access, credmgr.exe, seahorse).
12
11
  const SERVICE_NAME = "axe-auth";
12
+ // Single keychain entry per machine. The blob it holds is fully
13
+ // self-describing (issuerURL, clientId, allowInsecureIssuer, plus the
14
+ // tokens), so verbs that don't pass `--server` / `--realm` /
15
+ // `--client-id` can resolve their config from the entry.
16
+ //
17
+ // Account name is human-readable so users investigating the entry in
18
+ // macOS Keychain Access (or `secret-tool` on Linux, credmgr on
19
+ // Windows) can tell what it is. Not versioned: the schema version
20
+ // lives inside the blob and migrators handle the upgrade path.
21
+ const ACCOUNT_NAME = "credentials";
13
22
  /**
14
23
  * Current on-disk blob schema version. Exported so consumers can
15
24
  * display "stored v:N, expected v:M" diagnostics when `load()` returns
@@ -32,35 +41,17 @@ exports.STORED_BLOB_VERSION = 1;
32
41
  const MIGRATORS = new Map([
33
42
  // [1, (v1) => migrateV1ToV2(v1 as StoredBlobV1)],
34
43
  ]);
35
- // Lazy-resolved Entry constructor. Importing @napi-rs/keyring at the
36
- // top of this module would run its native binding loader at
37
- // module-load time, throwing before any of our OAuthFlowError code
38
- // catches it and preventing the module from being imported at all on
39
- // platforms without a prebuilt. We defer the require into
40
- // `defaultEntryFactory`, which turns that import-time failure into a
41
- // `KEYRING_UNAVAILABLE` surfaced on the first `new
42
- // KeyringTokenStore(...)` call not on first save/load/clear, since
43
- // `authorize()` (and similar callers) construct the store eagerly as
44
- // a default-arg expression. Runtime keychain errors (missing D-Bus
45
- // Secret Service, macOS Keychain denial, etc.) are a separate
46
- // concern and surface later, inside save/load/clear.
47
- let cachedEntryCtor = null;
48
- function resolveEntryCtor() {
49
- if (cachedEntryCtor)
50
- return cachedEntryCtor;
51
- try {
52
- const mod = requireFromHere("@napi-rs/keyring");
53
- cachedEntryCtor = mod.Entry;
54
- return cachedEntryCtor;
55
- }
56
- catch (cause) {
57
- throw new errors_1.OAuthFlowError("KEYRING_UNAVAILABLE", `Could not load @napi-rs/keyring. A prebuilt native binding for this platform may be missing.`, { cause });
44
+ // Sanity-check the migrator map at module load. Every key must be
45
+ // strictly less than `STORED_BLOB_VERSION` the chain only walks
46
+ // forward, so a leftover migrator at the current (or future) version
47
+ // would either be unreachable or confuse the loop. Fail-fast so a
48
+ // dev forgetting to remove a stale entry during a version bump
49
+ // notices before shipping.
50
+ for (const fromVersion of MIGRATORS.keys()) {
51
+ if (fromVersion >= exports.STORED_BLOB_VERSION) {
52
+ throw new Error(`MIGRATORS contains a key (v${fromVersion}) that is not strictly less than STORED_BLOB_VERSION (${exports.STORED_BLOB_VERSION}). The chain only walks forward; remove stale migrators when bumping the schema version.`);
58
53
  }
59
54
  }
60
- const defaultEntryFactory = (service, account) => {
61
- const Ctor = resolveEntryCtor();
62
- return new Ctor(service, account);
63
- };
64
55
  function getStoredVersion(blob) {
65
56
  if (blob === null || typeof blob !== "object")
66
57
  return null;
@@ -72,45 +63,109 @@ function isLatestBlob(blob) {
72
63
  return false;
73
64
  const b = blob;
74
65
  return (b.v === exports.STORED_BLOB_VERSION &&
66
+ // Empty access token is treated as corrupt rather than a usable
67
+ // credential. `axe-auth token` printing an empty line and exiting
68
+ // 0 would look like success and silently break downstream.
75
69
  typeof b.accessToken === "string" &&
70
+ b.accessToken.length > 0 &&
76
71
  typeof b.expiresAt === "number" &&
77
- (b.refreshToken === undefined || typeof b.refreshToken === "string"));
72
+ (b.refreshToken === undefined || typeof b.refreshToken === "string") &&
73
+ typeof b.issuerURL === "string" &&
74
+ typeof b.clientId === "string" &&
75
+ typeof b.allowInsecureIssuer === "boolean");
78
76
  }
79
- function blobToTokens(blob) {
77
+ function blobToEntry(blob) {
80
78
  const tokens = {
81
79
  accessToken: blob.accessToken,
82
80
  expiresAt: blob.expiresAt,
83
81
  };
84
- if (blob.refreshToken !== undefined)
82
+ if (blob.refreshToken)
85
83
  tokens.refreshToken = blob.refreshToken;
86
- return tokens;
84
+ return {
85
+ tokens,
86
+ issuerURL: blob.issuerURL,
87
+ clientId: blob.clientId,
88
+ allowInsecureIssuer: blob.allowInsecureIssuer,
89
+ };
87
90
  }
88
- function tokensToBlob(tokens) {
91
+ function entryToBlob(entry) {
89
92
  const blob = {
90
93
  v: exports.STORED_BLOB_VERSION,
91
- accessToken: tokens.accessToken,
92
- expiresAt: tokens.expiresAt,
94
+ accessToken: entry.tokens.accessToken,
95
+ expiresAt: entry.tokens.expiresAt,
96
+ issuerURL: entry.issuerURL,
97
+ clientId: entry.clientId,
98
+ allowInsecureIssuer: entry.allowInsecureIssuer,
93
99
  };
94
- if (tokens.refreshToken !== undefined)
95
- blob.refreshToken = tokens.refreshToken;
100
+ if (entry.tokens.refreshToken)
101
+ blob.refreshToken = entry.tokens.refreshToken;
96
102
  return blob;
97
103
  }
104
+ /**
105
+ * JSON-parses the raw keychain password and walks the migrator chain
106
+ * until it reaches `expectedVersion`. Exported with `expectedVersion`
107
+ * and `migrators` parameters only for testing the chain mechanics
108
+ * against synthetic versions / migrators; production callers use
109
+ * `KeyringTokenStore.load()`, which feeds in `STORED_BLOB_VERSION`
110
+ * and `MIGRATORS` and applies the latest-shape check on top.
111
+ */
112
+ function parseAndMigrateBlob(raw, expectedVersion = exports.STORED_BLOB_VERSION, migrators = MIGRATORS) {
113
+ if (raw === null)
114
+ return { ok: false, reason: "empty" };
115
+ let parsed;
116
+ try {
117
+ parsed = JSON.parse(raw);
118
+ }
119
+ catch {
120
+ return { ok: false, reason: "corrupt" };
121
+ }
122
+ const storedVersion = getStoredVersion(parsed);
123
+ if (storedVersion === null)
124
+ return { ok: false, reason: "corrupt" };
125
+ // Walk the migrator chain until we reach the expected version. A
126
+ // missing or null-returning migrator means the old blob cannot be
127
+ // upgraded; surface that so callers can prompt re-auth with a
128
+ // clear signal instead of silently returning `empty`.
129
+ let current = parsed;
130
+ let currentVersion = storedVersion;
131
+ while (currentVersion !== expectedVersion) {
132
+ const migrator = migrators.get(currentVersion);
133
+ if (!migrator) {
134
+ return { ok: false, reason: "version-mismatch", storedVersion };
135
+ }
136
+ const next = migrator(current);
137
+ if (next === null) {
138
+ return { ok: false, reason: "version-mismatch", storedVersion };
139
+ }
140
+ const nextVersion = getStoredVersion(next);
141
+ if (nextVersion === null || nextVersion <= currentVersion) {
142
+ // Migrator output is malformed or didn't advance. Treat the
143
+ // stored blob as un-migratable rather than loop forever.
144
+ return { ok: false, reason: "version-mismatch", storedVersion };
145
+ }
146
+ current = next;
147
+ currentVersion = nextVersion;
148
+ }
149
+ return { ok: true, blob: current };
150
+ }
98
151
  function wrapKeyringError(op, cause) {
99
152
  throw new errors_1.OAuthFlowError("KEYRING_UNAVAILABLE", `System keychain ${op} failed. On Linux this usually means no D-Bus Secret Service is running.`, { cause });
100
153
  }
101
154
  /**
102
155
  * `TokenStore` backed by the operating system's native keychain via
103
156
  * `@napi-rs/keyring` (macOS Keychain, Windows Credential Manager, Linux
104
- * Secret Service). Account is keyed by the normalized issuer URL.
157
+ * Secret Service). One entry per machine, keyed by a fixed account
158
+ * name; the blob carries its own issuer/client coordinates so verbs
159
+ * can recover full config without per-issuer keying.
105
160
  */
106
161
  class KeyringTokenStore {
107
162
  #entry;
108
- constructor(issuerURL, entryFactory = defaultEntryFactory) {
109
- this.#entry = entryFactory(SERVICE_NAME, (0, issuerURL_1.normalizeIssuerURL)(issuerURL));
163
+ constructor(entryFactory = keyringBinding_1.defaultEntryFactory) {
164
+ this.#entry = entryFactory(SERVICE_NAME, ACCOUNT_NAME);
110
165
  }
111
- async save(tokens) {
166
+ async save(entry) {
112
167
  try {
113
- this.#entry.setPassword(JSON.stringify(tokensToBlob(tokens)));
168
+ this.#entry.setPassword(JSON.stringify(entryToBlob(entry)));
114
169
  }
115
170
  catch (cause) {
116
171
  wrapKeyringError("write", cause);
@@ -124,45 +179,12 @@ class KeyringTokenStore {
124
179
  catch (cause) {
125
180
  wrapKeyringError("read", cause);
126
181
  }
127
- if (raw === null)
128
- return { ok: false, reason: "empty" };
129
- let parsed;
130
- try {
131
- parsed = JSON.parse(raw);
132
- }
133
- catch {
134
- return { ok: false, reason: "corrupt" };
135
- }
136
- const storedVersion = getStoredVersion(parsed);
137
- if (storedVersion === null)
138
- return { ok: false, reason: "corrupt" };
139
- // Walk the migrator chain until we reach the current version. A
140
- // missing or null-returning migrator means the old blob cannot be
141
- // upgraded; surface that so callers can prompt re-auth with a
142
- // clear signal instead of silently returning `empty`.
143
- let current = parsed;
144
- let currentVersion = storedVersion;
145
- while (currentVersion !== exports.STORED_BLOB_VERSION) {
146
- const migrator = MIGRATORS.get(currentVersion);
147
- if (!migrator) {
148
- return { ok: false, reason: "version-mismatch", storedVersion };
149
- }
150
- const next = migrator(current);
151
- if (next === null) {
152
- return { ok: false, reason: "version-mismatch", storedVersion };
153
- }
154
- const nextVersion = getStoredVersion(next);
155
- if (nextVersion === null || nextVersion <= currentVersion) {
156
- // Migrator output is malformed or didn't advance. Treat the
157
- // stored blob as un-migratable rather than loop forever.
158
- return { ok: false, reason: "version-mismatch", storedVersion };
159
- }
160
- current = next;
161
- currentVersion = nextVersion;
162
- }
163
- if (!isLatestBlob(current))
182
+ const chain = parseAndMigrateBlob(raw);
183
+ if (!chain.ok)
184
+ return chain;
185
+ if (!isLatestBlob(chain.blob))
164
186
  return { ok: false, reason: "corrupt" };
165
- return { ok: true, tokens: blobToTokens(current) };
187
+ return { ok: true, entry: blobToEntry(chain.blob) };
166
188
  }
167
189
  async clear() {
168
190
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deque/axe-auth",
3
- "version": "1.1.0-next.907ffbd7",
3
+ "version": "1.1.0-next.ac35e028",
4
4
  "description": "CLI authentication utility for Deque services",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "type": "commonjs",
@@ -21,7 +21,9 @@
21
21
  "node": ">=22.13.0"
22
22
  },
23
23
  "dependencies": {
24
- "@napi-rs/keyring": "^1.2.0"
24
+ "@napi-rs/keyring": "^1.2.0",
25
+ "remove-trailing-slash": "^0.1.1",
26
+ "ts-dedent": "^2.2.0"
25
27
  },
26
28
  "devDependencies": {
27
29
  "@types/node": "^22.13.10",
@@ -35,6 +37,7 @@
35
37
  "coverage": "c8 pnpm test",
36
38
  "register-dev-client": "tsx scripts/registerDevClient.ts",
37
39
  "smoke-authorize": "tsx scripts/smokeAuthorize.ts",
40
+ "smoke-cli": "tsx scripts/smokeCLI.ts",
38
41
  "manual-authorize": "tsx scripts/manualAuthorize.ts"
39
42
  }
40
43
  }