@deque/axe-auth 1.1.0-next.97bcb8e6 → 1.1.0-next.9c8d8c98

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 (76) hide show
  1. package/README.md +64 -7
  2. package/credits.json +53 -0
  3. package/dist/cli/commonArgs.d.ts +35 -0
  4. package/dist/cli/commonArgs.help.d.ts +2 -0
  5. package/dist/cli/commonArgs.help.js +20 -0
  6. package/dist/cli/commonArgs.js +63 -0
  7. package/dist/cli/confirm.d.ts +17 -0
  8. package/dist/cli/confirm.js +53 -0
  9. package/dist/cli/errors.d.ts +13 -0
  10. package/dist/cli/errors.js +30 -0
  11. package/dist/cli/testUtils.d.ts +52 -0
  12. package/dist/cli/testUtils.js +100 -0
  13. package/dist/cli/types.d.ts +39 -0
  14. package/dist/cli/types.js +2 -0
  15. package/dist/commands/login.d.ts +41 -0
  16. package/dist/commands/login.help.d.ts +2 -0
  17. package/dist/commands/login.help.js +41 -0
  18. package/dist/commands/login.js +108 -0
  19. package/dist/commands/logout.d.ts +24 -0
  20. package/dist/commands/logout.help.d.ts +2 -0
  21. package/dist/commands/logout.help.js +38 -0
  22. package/dist/commands/logout.js +68 -0
  23. package/dist/commands/token.d.ts +21 -0
  24. package/dist/commands/token.help.d.ts +2 -0
  25. package/dist/commands/token.help.js +41 -0
  26. package/dist/commands/token.js +40 -0
  27. package/dist/index.js +119 -27
  28. package/dist/oauth/authorizationURL.d.ts +24 -0
  29. package/dist/oauth/authorizationURL.js +48 -0
  30. package/dist/oauth/authorize.d.ts +53 -0
  31. package/dist/oauth/authorize.js +117 -0
  32. package/dist/oauth/callbackServer.d.ts +23 -0
  33. package/dist/oauth/callbackServer.js +234 -0
  34. package/dist/oauth/discoverOIDC.d.ts +33 -0
  35. package/dist/oauth/discoverOIDC.js +144 -0
  36. package/dist/oauth/discoverSSOConfig.d.ts +37 -0
  37. package/dist/oauth/discoverSSOConfig.js +105 -0
  38. package/dist/oauth/errors.d.ts +77 -0
  39. package/dist/oauth/errors.js +48 -0
  40. package/dist/oauth/getValidAccessToken.d.ts +54 -0
  41. package/dist/oauth/getValidAccessToken.js +131 -0
  42. package/dist/oauth/index.d.ts +16 -0
  43. package/dist/oauth/index.js +19 -0
  44. package/dist/oauth/issuerURL.d.ts +22 -0
  45. package/dist/oauth/issuerURL.js +38 -0
  46. package/dist/oauth/keyringBinding.d.ts +22 -0
  47. package/dist/oauth/keyringBinding.js +41 -0
  48. package/dist/oauth/logo.generated.d.ts +1 -0
  49. package/dist/oauth/logo.generated.js +7 -0
  50. package/dist/oauth/openBrowser.d.ts +30 -0
  51. package/dist/oauth/openBrowser.js +95 -0
  52. package/dist/oauth/pkce.d.ts +17 -0
  53. package/dist/oauth/pkce.js +43 -0
  54. package/dist/oauth/predicates.d.ts +7 -0
  55. package/dist/oauth/predicates.js +15 -0
  56. package/dist/oauth/refreshTokens.d.ts +30 -0
  57. package/dist/oauth/refreshTokens.js +60 -0
  58. package/dist/oauth/renderHtml.d.ts +9 -0
  59. package/dist/oauth/renderHtml.js +60 -0
  60. package/dist/oauth/revokeToken.d.ts +28 -0
  61. package/dist/oauth/revokeToken.js +63 -0
  62. package/dist/oauth/testUtils.d.ts +35 -0
  63. package/dist/oauth/testUtils.js +61 -0
  64. package/dist/oauth/tokenExchange.d.ts +26 -0
  65. package/dist/oauth/tokenExchange.js +44 -0
  66. package/dist/oauth/tokenResponse.d.ts +22 -0
  67. package/dist/oauth/tokenResponse.js +101 -0
  68. package/dist/oauth/tokenStore.d.ts +171 -0
  69. package/dist/oauth/tokenStore.js +545 -0
  70. package/dist/userAgent.d.ts +12 -0
  71. package/dist/userAgent.js +18 -0
  72. package/docs/architecture.md +201 -0
  73. package/docs/callback-page.md +24 -0
  74. package/docs/callback-server.md +21 -0
  75. package/docs/oauth-flow.md +15 -0
  76. package/package.json +21 -4
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.exchangeCodeForTokens = exchangeCodeForTokens;
4
+ const errors_1 = require("./errors");
5
+ const tokenResponse_1 = require("./tokenResponse");
6
+ const userAgent_1 = require("../userAgent");
7
+ /**
8
+ * Exchanges an authorization code for a `TokenSet` via the
9
+ * authorization server's token endpoint (RFC 6749 §4.1.3 + RFC 7636
10
+ * §4.5). Rejects with `OAuthFlowError("TOKEN_EXCHANGE_FAILED", ...)`
11
+ * for any failure mode, surfacing the OAuth `error` /
12
+ * `error_description` when available.
13
+ */
14
+ async function exchangeCodeForTokens(options) {
15
+ const now = options.now ?? Date.now;
16
+ const body = new URLSearchParams({
17
+ grant_type: "authorization_code",
18
+ client_id: options.clientId,
19
+ code: options.code,
20
+ code_verifier: options.codeVerifier,
21
+ redirect_uri: options.redirectUri,
22
+ });
23
+ const issuedAt = now();
24
+ let response;
25
+ try {
26
+ response = await fetch(options.tokenEndpoint, {
27
+ method: "POST",
28
+ headers: {
29
+ "Content-Type": "application/x-www-form-urlencoded",
30
+ Accept: "application/json",
31
+ "User-Agent": userAgent_1.USER_AGENT,
32
+ },
33
+ body,
34
+ signal: options.signal,
35
+ });
36
+ }
37
+ catch (cause) {
38
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Could not reach the token endpoint at ${options.tokenEndpoint}. Check your network connection.`, { cause });
39
+ }
40
+ if (!response.ok) {
41
+ await (0, tokenResponse_1.throwTokenEndpointError)(response, "Token exchange");
42
+ }
43
+ return (0, tokenResponse_1.parseTokenResponse)(response, issuedAt, options.tokenEndpoint);
44
+ }
@@ -0,0 +1,22 @@
1
+ /** Tokens returned by a successful token-endpoint call. */
2
+ export interface TokenSet {
3
+ /** Access token for authenticated API calls. */
4
+ accessToken: string;
5
+ /** Long-lived token used to mint new access tokens without re-auth. Absent if the flow did not return one. */
6
+ refreshToken?: string;
7
+ /** Absolute timestamp (ms since epoch) when the access token expires. */
8
+ expiresAt: number;
9
+ /** Space-delimited scopes the server actually granted, if reported. */
10
+ grantedScope?: string;
11
+ }
12
+ /**
13
+ * Reads a non-2xx response body and throws `TOKEN_EXCHANGE_FAILED`
14
+ * with the OAuth `error` / `error_description` surfaced when present.
15
+ */
16
+ export declare function throwTokenEndpointError(response: Response, context: string): Promise<never>;
17
+ /**
18
+ * Parses a 2xx response from an RFC 6749 §5.1 token endpoint into a
19
+ * `TokenSet`. `issuedAt` is the timestamp captured just before the
20
+ * network call; the resulting `expiresAt` is conservative by ~RTT.
21
+ */
22
+ export declare function parseTokenResponse(response: Response, issuedAt: number, endpointURL: string): Promise<TokenSet>;
@@ -0,0 +1,101 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.throwTokenEndpointError = throwTokenEndpointError;
4
+ exports.parseTokenResponse = parseTokenResponse;
5
+ const errors_1 = require("./errors");
6
+ const predicates_1 = require("./predicates");
7
+ // RFC 6749 §5.1 doesn't pin the JSON type and some providers send
8
+ // numeric strings; accept both, reject non-positive or non-finite.
9
+ function parseExpiresIn(v) {
10
+ if (typeof v === "number" && Number.isFinite(v) && v > 0)
11
+ return v;
12
+ if (typeof v === "string") {
13
+ const n = Number(v);
14
+ if (Number.isFinite(n) && n > 0)
15
+ return n;
16
+ }
17
+ return null;
18
+ }
19
+ function parseErrorBody(body) {
20
+ let parsed;
21
+ try {
22
+ parsed = JSON.parse(body);
23
+ }
24
+ catch {
25
+ return {};
26
+ }
27
+ if (parsed === null || typeof parsed !== "object")
28
+ return {};
29
+ const raw = parsed;
30
+ return {
31
+ error: (0, predicates_1.isNonEmptyString)(raw.error) ? raw.error : undefined,
32
+ description: (0, predicates_1.isNonEmptyString)(raw.error_description)
33
+ ? raw.error_description
34
+ : undefined,
35
+ };
36
+ }
37
+ /**
38
+ * Reads a non-2xx response body and throws `TOKEN_EXCHANGE_FAILED`
39
+ * with the OAuth `error` / `error_description` surfaced when present.
40
+ */
41
+ async function throwTokenEndpointError(response, context) {
42
+ const body = await response.text().catch(() => "");
43
+ const { error, description } = parseErrorBody(body);
44
+ const suffix = error
45
+ ? description
46
+ ? `: ${error}: ${description}`
47
+ : `: ${error}`
48
+ : "";
49
+ const details = {};
50
+ if (error)
51
+ details.error = error;
52
+ if (description)
53
+ details.error_description = description;
54
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `${context} failed with HTTP ${response.status}${suffix}`, Object.keys(details).length > 0 ? { details } : undefined);
55
+ }
56
+ /**
57
+ * Parses a 2xx response from an RFC 6749 §5.1 token endpoint into a
58
+ * `TokenSet`. `issuedAt` is the timestamp captured just before the
59
+ * network call; the resulting `expiresAt` is conservative by ~RTT.
60
+ */
61
+ async function parseTokenResponse(response, issuedAt, endpointURL) {
62
+ let parsed;
63
+ try {
64
+ parsed = await response.json();
65
+ }
66
+ catch (cause) {
67
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token endpoint at ${endpointURL} returned a non-JSON response`, { cause });
68
+ }
69
+ if (parsed === null || typeof parsed !== "object") {
70
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token endpoint at ${endpointURL} returned a non-object response`);
71
+ }
72
+ const raw = parsed;
73
+ if (!(0, predicates_1.isNonEmptyString)(raw.access_token)) {
74
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token response missing 'access_token'`);
75
+ }
76
+ const expiresIn = parseExpiresIn(raw.expires_in);
77
+ if (expiresIn === null) {
78
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token response missing or has invalid 'expires_in'`);
79
+ }
80
+ // RFC 6749 §5.1: token_type is REQUIRED. We only speak Bearer;
81
+ // DPoP / MAC / other proof-of-possession types need request-side
82
+ // support we don't implement, and silently treating them as Bearer
83
+ // would send tokens in the wrong header with unclear semantics.
84
+ if (!(0, predicates_1.isNonEmptyString)(raw.token_type)) {
85
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token response missing required 'token_type'`);
86
+ }
87
+ if (raw.token_type.toLowerCase() !== "bearer") {
88
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Unsupported token_type '${raw.token_type}'; this library only handles Bearer.`);
89
+ }
90
+ const tokens = {
91
+ accessToken: raw.access_token,
92
+ expiresAt: issuedAt + expiresIn * 1000,
93
+ };
94
+ if ((0, predicates_1.isNonEmptyString)(raw.refresh_token)) {
95
+ tokens.refreshToken = raw.refresh_token;
96
+ }
97
+ if ((0, predicates_1.isNonEmptyString)(raw.scope)) {
98
+ tokens.grantedScope = raw.scope;
99
+ }
100
+ return tokens;
101
+ }
@@ -0,0 +1,171 @@
1
+ import { type KeyringEntryFactory } from "./keyringBinding";
2
+ import type { TokenSet } from "./tokenResponse";
3
+ /**
4
+ * Whether `KeyringTokenStore` should split the stored blob across
5
+ * multiple keychain entries on this platform. Windows-only: Credential
6
+ * Manager has a 2560-byte per-entry cap that large OAuth tokens
7
+ * routinely exceed. macOS Keychain and Linux libsecret have no
8
+ * comparable limit, and on macOS each entry is independently lockable
9
+ * (chunking there would multiply per-entry ACL prompts). Exported
10
+ * (parameterized for tests) so the chunking path can be exercised
11
+ * deterministically.
12
+ */
13
+ export declare function shouldChunkForKeyring(platform?: NodeJS.Platform): boolean;
14
+ /**
15
+ * Current on-disk blob schema version. Exported so consumers can
16
+ * display "stored v:N, expected v:M" diagnostics when `load()` returns
17
+ * a `version-mismatch` result.
18
+ */
19
+ export declare const STORED_BLOB_VERSION = 1;
20
+ /**
21
+ * What `KeyringTokenStore` persists: the OAuth tokens plus the
22
+ * issuer/client coordinates they were minted against. Carrying the
23
+ * coordinates inside the entry means a verb can recover its full
24
+ * config from the keychain alone, with no separate "default issuer"
25
+ * pointer.
26
+ */
27
+ export interface StoredEntry {
28
+ tokens: TokenSet;
29
+ /** OIDC issuer URL the tokens were minted against. */
30
+ issuerURL: string;
31
+ /** OAuth client ID used at login. */
32
+ clientId: string;
33
+ /** Whether the original login allowed a non-loopback http issuer. */
34
+ allowInsecureIssuer: boolean;
35
+ /**
36
+ * Originating axe server (walnut) URL the user supplied (or the
37
+ * SaaS prod default) at login.
38
+ */
39
+ walnutURL: string;
40
+ }
41
+ /**
42
+ * Outcome of a `TokenStore.load()` call.
43
+ *
44
+ * Note on downgrades: the migrator chain only walks *forward*. A user
45
+ * who downgrades `axe-auth` to a release that predates a schema bump
46
+ * will see `version-mismatch` on any blob written by the newer
47
+ * release, even if the change was strictly additive. That is the safe
48
+ * default for a credentials blob — the older version cannot vouch for
49
+ * the meaning of fields it has never seen. Callers hitting this case
50
+ * should treat it as "re-authenticate" rather than attempting to
51
+ * parse an unknown future shape.
52
+ */
53
+ export type LoadResult = {
54
+ ok: true;
55
+ entry: StoredEntry;
56
+ } | {
57
+ ok: false;
58
+ reason: "empty";
59
+ } | {
60
+ ok: false;
61
+ reason: "corrupt";
62
+ } | {
63
+ ok: false;
64
+ reason: "version-mismatch";
65
+ storedVersion: number;
66
+ };
67
+ /** Persistence layer for an OAuth `StoredEntry`. */
68
+ export interface TokenStore {
69
+ /** Write-through save. Replaces any previously stored entry. */
70
+ save(entry: StoredEntry): Promise<void>;
71
+ /**
72
+ * Reads the stored entry and returns a structured result.
73
+ *
74
+ * Callers should branch on `result.ok` first. When `ok` is `false`,
75
+ * `reason` tells them *why* there is no usable entry: `empty`
76
+ * (nothing stored), `corrupt` (unparseable or shape-invalid), or
77
+ * `version-mismatch` (stored under a schema we cannot migrate from).
78
+ * The library does not emit output on these cases — surfacing them
79
+ * to the user is the caller's responsibility.
80
+ */
81
+ load(): Promise<LoadResult>;
82
+ /** Removes any stored entry. No-op if none is present. */
83
+ clear(): Promise<void>;
84
+ }
85
+ /**
86
+ * Outcome of `parseAndMigrateBlob`: same set of failure reasons as
87
+ * `LoadResult`, but on success carries the post-migration blob as an
88
+ * unknown payload. The caller is responsible for shape-validating
89
+ * that payload against the latest schema.
90
+ */
91
+ export type BlobChainResult = {
92
+ ok: true;
93
+ blob: unknown;
94
+ } | {
95
+ ok: false;
96
+ reason: "empty";
97
+ } | {
98
+ ok: false;
99
+ reason: "corrupt";
100
+ } | {
101
+ ok: false;
102
+ reason: "version-mismatch";
103
+ storedVersion: number;
104
+ };
105
+ /**
106
+ * JSON-parses the raw keychain password and walks the migrator chain
107
+ * until it reaches `expectedVersion`. Exported with `expectedVersion`
108
+ * and `migrators` parameters only for testing the chain mechanics
109
+ * against synthetic versions / migrators; production callers use
110
+ * `KeyringTokenStore.load()`, which feeds in `STORED_BLOB_VERSION`
111
+ * and `MIGRATORS` and applies the latest-shape check on top.
112
+ */
113
+ export declare function parseAndMigrateBlob(raw: string | null, expectedVersion?: number, migrators?: ReadonlyMap<number, (old: unknown) => unknown | null>): BlobChainResult;
114
+ /**
115
+ * Builds the user-facing keychain error message: the underlying
116
+ * cause's text plus a per-platform hint. Platform is a parameter
117
+ * (defaulting to `process.platform`) so tests can drive each branch
118
+ * without mocking the runtime; mirrors the pattern in
119
+ * `platformKeyringHint`.
120
+ */
121
+ export declare function keyringErrorMessage(op: string, cause: unknown, platform?: NodeJS.Platform): string;
122
+ /**
123
+ * Returns a per-platform hint appended to keychain error messages so
124
+ * users see actionable guidance for their OS instead of generic or
125
+ * Linux-only advice. Exported (but not re-exported from the package
126
+ * index) so tests can exercise each branch without mocking
127
+ * `process.platform`.
128
+ */
129
+ export declare function platformKeyringHint(platform?: NodeJS.Platform): string;
130
+ /**
131
+ * `TokenStore` backed by the operating system's native keychain via
132
+ * `@napi-rs/keyring` (macOS Keychain, Windows Credential Manager, Linux
133
+ * Secret Service). On macOS and Linux the blob lives in a single entry
134
+ * keyed by the fixed `credentials` account name. On Windows the blob
135
+ * is split across `credentials.0`, `credentials.1`, … entries to fit
136
+ * under Credential Manager's 2560-byte (1280 UTF-16 char) per-entry
137
+ * cap; see `shouldChunkForKeyring`.
138
+ *
139
+ * The blob carries its own issuer/client coordinates so verbs can
140
+ * recover full config without per-issuer keying.
141
+ */
142
+ export declare class KeyringTokenStore implements TokenStore {
143
+ #private;
144
+ /**
145
+ * @param entryFactory Injection seam for `@napi-rs/keyring` entries.
146
+ * Defaults to the production lazy-resolved factory; tests pass a
147
+ * recording / faking variant.
148
+ */
149
+ constructor(entryFactory?: KeyringEntryFactory);
150
+ /**
151
+ * @internal Test seam. Constructs a store with an explicit chunking
152
+ * decision instead of the platform-determined default, so the
153
+ * chunked path can be exercised on macOS/Linux CI and the unchunked
154
+ * path on Windows CI. Production code must use the regular
155
+ * constructor and let `shouldChunkForKeyring()` decide — passing
156
+ * `chunked: true` on macOS would write data that the regular
157
+ * constructor wouldn't be able to read.
158
+ */
159
+ static forTesting(entryFactory: KeyringEntryFactory, chunked: boolean): KeyringTokenStore;
160
+ save(entry: StoredEntry): Promise<void>;
161
+ load(): Promise<LoadResult>;
162
+ clear(): Promise<void>;
163
+ }
164
+ /**
165
+ * Splits `blob` into the N parts that `KeyringTokenStore.#saveChunked`
166
+ * writes to `credentials.0..N-1`. Chunk 0 is prefixed with `<N>\n` so
167
+ * the reader can learn N from a single getPassword call. Each chunk
168
+ * stays under `CHUNK_LIMIT` UTF-16 characters; throws if the blob would
169
+ * require more than `MAX_CHUNKS` chunks. Exported for tests.
170
+ */
171
+ export declare function chunkBlobForKeyring(blob: string): string[];