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

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 +183 -0
  69. package/dist/oauth/tokenStore.js +560 -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 +20 -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,183 @@
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 because of
6
+ * Credential Manager's 2560 UTF-16 character per-entry cap. Exported
7
+ * (parameterized for tests) so the chunking path can be exercised
8
+ * deterministically.
9
+ */
10
+ export declare function shouldChunkForKeyring(platform?: NodeJS.Platform): boolean;
11
+ /**
12
+ * Current on-disk blob schema version. Exported so consumers can
13
+ * display "stored v:N, expected v:M" diagnostics when `load()` returns
14
+ * a `version-mismatch` result.
15
+ */
16
+ export declare const STORED_BLOB_VERSION = 1;
17
+ /**
18
+ * What `KeyringTokenStore` persists: the OAuth tokens plus the
19
+ * issuer/client coordinates they were minted against. Carrying the
20
+ * coordinates inside the entry means a verb can recover its full
21
+ * config from the keychain alone, with no separate "default issuer"
22
+ * pointer.
23
+ */
24
+ export interface StoredEntry {
25
+ tokens: TokenSet;
26
+ /** OIDC issuer URL the tokens were minted against. */
27
+ issuerURL: string;
28
+ /** OAuth client ID used at login. */
29
+ clientId: string;
30
+ /** Whether the original login allowed a non-loopback http issuer. */
31
+ allowInsecureIssuer: boolean;
32
+ /**
33
+ * Originating axe server (walnut) URL the user supplied (or the
34
+ * SaaS prod default) at login.
35
+ */
36
+ walnutURL: string;
37
+ }
38
+ /**
39
+ * Outcome of a `TokenStore.load()` call.
40
+ *
41
+ * Note on downgrades: the migrator chain only walks *forward*. A user
42
+ * who downgrades `axe-auth` to a release that predates a schema bump
43
+ * will see `version-mismatch` on any blob written by the newer
44
+ * release, even if the change was strictly additive. That is the safe
45
+ * default for a credentials blob — the older version cannot vouch for
46
+ * the meaning of fields it has never seen. Callers hitting this case
47
+ * should treat it as "re-authenticate" rather than attempting to
48
+ * parse an unknown future shape.
49
+ */
50
+ export type LoadResult = {
51
+ ok: true;
52
+ entry: StoredEntry;
53
+ } | {
54
+ ok: false;
55
+ reason: "empty";
56
+ } | {
57
+ ok: false;
58
+ reason: "corrupt";
59
+ } | {
60
+ ok: false;
61
+ reason: "version-mismatch";
62
+ storedVersion: number;
63
+ };
64
+ /** Persistence layer for an OAuth `StoredEntry`. */
65
+ export interface TokenStore {
66
+ /** Write-through save. Replaces any previously stored entry. */
67
+ save(entry: StoredEntry): Promise<void>;
68
+ /**
69
+ * Reads the stored entry and returns a structured result.
70
+ *
71
+ * Callers should branch on `result.ok` first. When `ok` is `false`,
72
+ * `reason` tells them *why* there is no usable entry: `empty`
73
+ * (nothing stored), `corrupt` (unparseable or shape-invalid), or
74
+ * `version-mismatch` (stored under a schema we cannot migrate from).
75
+ * The library does not emit output on these cases — surfacing them
76
+ * to the user is the caller's responsibility.
77
+ */
78
+ load(): Promise<LoadResult>;
79
+ /** Removes any stored entry. No-op if none is present. */
80
+ clear(): Promise<void>;
81
+ }
82
+ /**
83
+ * Outcome of `parseAndMigrateBlob`: same set of failure reasons as
84
+ * `LoadResult`, but on success carries the post-migration blob as an
85
+ * unknown payload. The caller is responsible for shape-validating
86
+ * that payload against the latest schema.
87
+ */
88
+ export type BlobChainResult = {
89
+ ok: true;
90
+ blob: unknown;
91
+ } | {
92
+ ok: false;
93
+ reason: "empty";
94
+ } | {
95
+ ok: false;
96
+ reason: "corrupt";
97
+ } | {
98
+ ok: false;
99
+ reason: "version-mismatch";
100
+ storedVersion: number;
101
+ };
102
+ /**
103
+ * JSON-parses the raw keychain password and walks the migrator chain
104
+ * until it reaches `expectedVersion`. Exported with `expectedVersion`
105
+ * and `migrators` parameters only for testing the chain mechanics
106
+ * against synthetic versions / migrators; production callers use
107
+ * `KeyringTokenStore.load()`, which feeds in `STORED_BLOB_VERSION`
108
+ * and `MIGRATORS` and applies the latest-shape check on top.
109
+ */
110
+ export declare function parseAndMigrateBlob(raw: string | null, expectedVersion?: number, migrators?: ReadonlyMap<number, (old: unknown) => unknown | null>): BlobChainResult;
111
+ /**
112
+ * Builds the user-facing keychain error message. Platform is a
113
+ * parameter (defaulting to `process.platform`) so tests can drive each
114
+ * branch without mocking the runtime; mirrors the pattern in
115
+ * `platformKeyringHint`.
116
+ *
117
+ * The Windows-specific size-limit message is only used when the
118
+ * underlying error matches the binding's "longer than the platform
119
+ * limit" wording AND the runtime is win32 — that combination is the
120
+ * only way the size cap actually manifests in practice. On other
121
+ * platforms (or for any other binding error) we fall back to the
122
+ * generic per-platform hint.
123
+ */
124
+ export declare function keyringErrorMessage(op: string, cause: unknown, platform?: NodeJS.Platform): string;
125
+ /**
126
+ * Detects the `@napi-rs/keyring` error string for "value too large".
127
+ * In practice only Windows Credential Manager triggers this — its
128
+ * stored values are capped at 2560 UTF-16 chars; macOS Keychain and
129
+ * Linux libsecret have no comparable limit. Exported (but not
130
+ * re-exported from the package index) so tests can exercise the
131
+ * detector independently of the wrap path.
132
+ */
133
+ export declare function isKeyringSizeError(cause: unknown): boolean;
134
+ /**
135
+ * Returns a per-platform hint appended to keychain error messages so
136
+ * users see actionable guidance for their OS instead of generic or
137
+ * Linux-only advice. Exported (but not re-exported from the package
138
+ * index) so tests can exercise each branch without mocking
139
+ * `process.platform`.
140
+ */
141
+ export declare function platformKeyringHint(platform?: NodeJS.Platform): string;
142
+ /**
143
+ * `TokenStore` backed by the operating system's native keychain via
144
+ * `@napi-rs/keyring` (macOS Keychain, Windows Credential Manager, Linux
145
+ * Secret Service). On macOS and Linux the blob lives in a single entry
146
+ * keyed by the fixed `credentials` account name. On Windows the blob
147
+ * is split across `credentials.0`, `credentials.1`, … entries to fit
148
+ * under Credential Manager's 2560 UTF-16 character per-entry cap; see
149
+ * `shouldChunkForKeyring`.
150
+ *
151
+ * The blob carries its own issuer/client coordinates so verbs can
152
+ * recover full config without per-issuer keying.
153
+ */
154
+ export declare class KeyringTokenStore implements TokenStore {
155
+ #private;
156
+ /**
157
+ * @param entryFactory Injection seam for `@napi-rs/keyring` entries.
158
+ * Defaults to the production lazy-resolved factory; tests pass a
159
+ * recording / faking variant.
160
+ */
161
+ constructor(entryFactory?: KeyringEntryFactory);
162
+ /**
163
+ * @internal Test seam. Constructs a store with an explicit chunking
164
+ * decision instead of the platform-determined default, so the
165
+ * chunked path can be exercised on macOS/Linux CI and the unchunked
166
+ * path on Windows CI. Production code must use the regular
167
+ * constructor and let `shouldChunkForKeyring()` decide — passing
168
+ * `chunked: true` on macOS would write data that the regular
169
+ * constructor wouldn't be able to read.
170
+ */
171
+ static forTesting(entryFactory: KeyringEntryFactory, chunked: boolean): KeyringTokenStore;
172
+ save(entry: StoredEntry): Promise<void>;
173
+ load(): Promise<LoadResult>;
174
+ clear(): Promise<void>;
175
+ }
176
+ /**
177
+ * Splits `blob` into the N parts that `KeyringTokenStore.#saveChunked`
178
+ * writes to `credentials.0..N-1`. Chunk 0 is prefixed with `<N>\n` so
179
+ * the reader can learn N from a single getPassword call. Each chunk
180
+ * stays under `CHUNK_LIMIT` UTF-16 characters; throws if the blob would
181
+ * require more than `MAX_CHUNKS` chunks. Exported for tests.
182
+ */
183
+ export declare function chunkBlobForKeyring(blob: string): string[];