@deque/axe-auth 0.0.1-skeleton → 1.1.0-next.009d3665

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 (78) hide show
  1. package/LICENSE +7 -0
  2. package/README.md +85 -1
  3. package/credits.json +53 -0
  4. package/dist/cli/commonArgs.d.ts +82 -0
  5. package/dist/cli/commonArgs.help.d.ts +2 -0
  6. package/dist/cli/commonArgs.help.js +20 -0
  7. package/dist/cli/commonArgs.js +90 -0
  8. package/dist/cli/confirm.d.ts +17 -0
  9. package/dist/cli/confirm.js +56 -0
  10. package/dist/cli/errors.d.ts +20 -0
  11. package/dist/cli/errors.js +37 -0
  12. package/dist/cli/testUtils.d.ts +52 -0
  13. package/dist/cli/testUtils.js +100 -0
  14. package/dist/cli/types.d.ts +79 -0
  15. package/dist/cli/types.js +2 -0
  16. package/dist/commands/login.d.ts +44 -0
  17. package/dist/commands/login.help.d.ts +2 -0
  18. package/dist/commands/login.help.js +41 -0
  19. package/dist/commands/login.js +117 -0
  20. package/dist/commands/logout.d.ts +24 -0
  21. package/dist/commands/logout.help.d.ts +2 -0
  22. package/dist/commands/logout.help.js +38 -0
  23. package/dist/commands/logout.js +70 -0
  24. package/dist/commands/token.d.ts +21 -0
  25. package/dist/commands/token.help.d.ts +2 -0
  26. package/dist/commands/token.help.js +41 -0
  27. package/dist/commands/token.js +44 -0
  28. package/dist/index.d.ts +2 -0
  29. package/dist/index.js +139 -0
  30. package/dist/oauth/authorizationURL.d.ts +29 -0
  31. package/dist/oauth/authorizationURL.js +52 -0
  32. package/dist/oauth/authorize.d.ts +91 -0
  33. package/dist/oauth/authorize.js +119 -0
  34. package/dist/oauth/callbackServer.d.ts +23 -0
  35. package/dist/oauth/callbackServer.js +234 -0
  36. package/dist/oauth/discoverOIDC.d.ts +50 -0
  37. package/dist/oauth/discoverOIDC.js +173 -0
  38. package/dist/oauth/discoverSSOConfig.d.ts +47 -0
  39. package/dist/oauth/discoverSSOConfig.js +105 -0
  40. package/dist/oauth/errors.d.ts +77 -0
  41. package/dist/oauth/errors.js +48 -0
  42. package/dist/oauth/getValidAccessToken.d.ts +89 -0
  43. package/dist/oauth/getValidAccessToken.js +140 -0
  44. package/dist/oauth/index.d.ts +16 -0
  45. package/dist/oauth/index.js +19 -0
  46. package/dist/oauth/issuerURL.d.ts +22 -0
  47. package/dist/oauth/issuerURL.js +38 -0
  48. package/dist/oauth/keyringBinding.d.ts +22 -0
  49. package/dist/oauth/keyringBinding.js +41 -0
  50. package/dist/oauth/logo.generated.d.ts +1 -0
  51. package/dist/oauth/logo.generated.js +7 -0
  52. package/dist/oauth/openBrowser.d.ts +30 -0
  53. package/dist/oauth/openBrowser.js +95 -0
  54. package/dist/oauth/pkce.d.ts +17 -0
  55. package/dist/oauth/pkce.js +43 -0
  56. package/dist/oauth/predicates.d.ts +7 -0
  57. package/dist/oauth/predicates.js +15 -0
  58. package/dist/oauth/refreshTokens.d.ts +30 -0
  59. package/dist/oauth/refreshTokens.js +63 -0
  60. package/dist/oauth/renderHtml.d.ts +9 -0
  61. package/dist/oauth/renderHtml.js +60 -0
  62. package/dist/oauth/revokeToken.d.ts +28 -0
  63. package/dist/oauth/revokeToken.js +63 -0
  64. package/dist/oauth/testUtils.d.ts +35 -0
  65. package/dist/oauth/testUtils.js +61 -0
  66. package/dist/oauth/tokenExchange.d.ts +26 -0
  67. package/dist/oauth/tokenExchange.js +44 -0
  68. package/dist/oauth/tokenResponse.d.ts +54 -0
  69. package/dist/oauth/tokenResponse.js +121 -0
  70. package/dist/oauth/tokenStore.d.ts +160 -0
  71. package/dist/oauth/tokenStore.js +549 -0
  72. package/dist/userAgent.d.ts +12 -0
  73. package/dist/userAgent.js +18 -0
  74. package/docs/architecture.md +201 -0
  75. package/docs/callback-page.md +24 -0
  76. package/docs/callback-server.md +21 -0
  77. package/docs/oauth-flow.md +15 -0
  78. package/package.json +41 -5
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Tokens returned by a successful token-endpoint call (authorization
3
+ * code exchange, refresh-token grant, etc.).
4
+ *
5
+ * `refreshToken` is optional because not all flows return one. On
6
+ * authorization-code exchange it's absent if the caller did not
7
+ * request `offline_access` (or the provider equivalent); on refresh
8
+ * some providers rotate tokens (return a new one) while others don't
9
+ * (the caller should keep the existing refresh token).
10
+ *
11
+ * `grantedScope` reflects the authorization server's `scope` response
12
+ * field when present. RFC 6749 §5.1 says `scope` is required in the
13
+ * response when the granted set differs from the requested set; many
14
+ * servers send it unconditionally.
15
+ */
16
+ export interface TokenSet {
17
+ /** Access token for authenticated API calls. */
18
+ accessToken: string;
19
+ /** Long-lived token used to mint new access tokens without re-auth. Absent if the flow did not return one. */
20
+ refreshToken?: string;
21
+ /** Absolute timestamp (ms since epoch) when the access token expires. */
22
+ expiresAt: number;
23
+ /** Space-delimited scopes the server actually granted, if reported. */
24
+ grantedScope?: string;
25
+ }
26
+ /**
27
+ * Reads a non-2xx response body and throws
28
+ * `OAuthFlowError("TOKEN_EXCHANGE_FAILED", …)` with the OAuth
29
+ * `error` / `error_description` surfaced in both message and details
30
+ * when present. Shared by both the authorization-code exchange and
31
+ * refresh-token paths since the error contract is identical.
32
+ *
33
+ * @param context Short human-readable description of which call
34
+ * failed ("Token exchange", "Token refresh", etc.). Appears in the
35
+ * error message.
36
+ */
37
+ export declare function throwTokenEndpointError(response: Response, context: string): Promise<never>;
38
+ /**
39
+ * Parses a 2xx response body from an RFC 6749 §5.1 token endpoint
40
+ * (authorization-code exchange, refresh-token grant, etc.) into a
41
+ * `TokenSet`. Validates the required shape (`access_token`,
42
+ * `expires_in`, Bearer `token_type`) and converts the relative
43
+ * `expires_in` into an absolute `expiresAt` using `issuedAt`.
44
+ *
45
+ * @param response The HTTP response (must be 2xx; caller handles
46
+ * error statuses via `throwTokenEndpointError`).
47
+ * @param issuedAt The timestamp captured just before the network
48
+ * call. Slightly conservative — the token actually expires
49
+ * `expires_in` seconds from when the server issued it, so the
50
+ * effective usable window is `expires_in - RTT`, which errs toward
51
+ * "expires sooner" rather than "expires later."
52
+ * @param endpointURL URL used for error messages.
53
+ */
54
+ export declare function parseTokenResponse(response: Response, issuedAt: number, endpointURL: string): Promise<TokenSet>;
@@ -0,0 +1,121 @@
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 describes `expires_in` as "the lifetime in seconds"
8
+ // without pinning the JSON type, and some providers historically send
9
+ // numeric strings. Accept both; reject anything non-positive or
10
+ // non-finite.
11
+ function parseExpiresIn(v) {
12
+ if (typeof v === "number" && Number.isFinite(v) && v > 0)
13
+ return v;
14
+ if (typeof v === "string") {
15
+ const n = Number(v);
16
+ if (Number.isFinite(n) && n > 0)
17
+ return n;
18
+ }
19
+ return null;
20
+ }
21
+ function parseErrorBody(body) {
22
+ let parsed;
23
+ try {
24
+ parsed = JSON.parse(body);
25
+ }
26
+ catch {
27
+ return {};
28
+ }
29
+ if (parsed === null || typeof parsed !== "object")
30
+ return {};
31
+ const raw = parsed;
32
+ return {
33
+ error: (0, predicates_1.isNonEmptyString)(raw.error) ? raw.error : undefined,
34
+ description: (0, predicates_1.isNonEmptyString)(raw.error_description)
35
+ ? raw.error_description
36
+ : undefined,
37
+ };
38
+ }
39
+ /**
40
+ * Reads a non-2xx response body and throws
41
+ * `OAuthFlowError("TOKEN_EXCHANGE_FAILED", …)` with the OAuth
42
+ * `error` / `error_description` surfaced in both message and details
43
+ * when present. Shared by both the authorization-code exchange and
44
+ * refresh-token paths since the error contract is identical.
45
+ *
46
+ * @param context Short human-readable description of which call
47
+ * failed ("Token exchange", "Token refresh", etc.). Appears in the
48
+ * error message.
49
+ */
50
+ async function throwTokenEndpointError(response, context) {
51
+ const body = await response.text().catch(() => "");
52
+ const { error, description } = parseErrorBody(body);
53
+ const suffix = error
54
+ ? description
55
+ ? `: ${error}: ${description}`
56
+ : `: ${error}`
57
+ : "";
58
+ const details = {};
59
+ if (error)
60
+ details.error = error;
61
+ if (description)
62
+ details.error_description = description;
63
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `${context} failed with HTTP ${response.status}${suffix}`, Object.keys(details).length > 0 ? { details } : undefined);
64
+ }
65
+ /**
66
+ * Parses a 2xx response body from an RFC 6749 §5.1 token endpoint
67
+ * (authorization-code exchange, refresh-token grant, etc.) into a
68
+ * `TokenSet`. Validates the required shape (`access_token`,
69
+ * `expires_in`, Bearer `token_type`) and converts the relative
70
+ * `expires_in` into an absolute `expiresAt` using `issuedAt`.
71
+ *
72
+ * @param response The HTTP response (must be 2xx; caller handles
73
+ * error statuses via `throwTokenEndpointError`).
74
+ * @param issuedAt The timestamp captured just before the network
75
+ * call. Slightly conservative — the token actually expires
76
+ * `expires_in` seconds from when the server issued it, so the
77
+ * effective usable window is `expires_in - RTT`, which errs toward
78
+ * "expires sooner" rather than "expires later."
79
+ * @param endpointURL URL used for error messages.
80
+ */
81
+ async function parseTokenResponse(response, issuedAt, endpointURL) {
82
+ let parsed;
83
+ try {
84
+ parsed = await response.json();
85
+ }
86
+ catch (cause) {
87
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token endpoint at ${endpointURL} returned a non-JSON response`, { cause });
88
+ }
89
+ if (parsed === null || typeof parsed !== "object") {
90
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token endpoint at ${endpointURL} returned a non-object response`);
91
+ }
92
+ const raw = parsed;
93
+ if (!(0, predicates_1.isNonEmptyString)(raw.access_token)) {
94
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token response missing 'access_token'`);
95
+ }
96
+ const expiresIn = parseExpiresIn(raw.expires_in);
97
+ if (expiresIn === null) {
98
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token response missing or has invalid 'expires_in'`);
99
+ }
100
+ // RFC 6749 §5.1: token_type is REQUIRED. We only speak Bearer;
101
+ // DPoP / MAC / other proof-of-possession types need request-side
102
+ // support we don't implement, and silently treating them as Bearer
103
+ // would send tokens in the wrong header with unclear semantics.
104
+ if (!(0, predicates_1.isNonEmptyString)(raw.token_type)) {
105
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token response missing required 'token_type'`);
106
+ }
107
+ if (raw.token_type.toLowerCase() !== "bearer") {
108
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Unsupported token_type '${raw.token_type}'; this library only handles Bearer.`);
109
+ }
110
+ const tokens = {
111
+ accessToken: raw.access_token,
112
+ expiresAt: issuedAt + expiresIn * 1000,
113
+ };
114
+ if ((0, predicates_1.isNonEmptyString)(raw.refresh_token)) {
115
+ tokens.refreshToken = raw.refresh_token;
116
+ }
117
+ if ((0, predicates_1.isNonEmptyString)(raw.scope)) {
118
+ tokens.grantedScope = raw.scope;
119
+ }
120
+ return tokens;
121
+ }
@@ -0,0 +1,160 @@
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
+ * Returns a per-platform hint appended to keychain error messages so
113
+ * users see actionable guidance for their OS instead of generic or
114
+ * Linux-only advice. Exported (but not re-exported from the package
115
+ * index) so tests can exercise each branch without mocking
116
+ * `process.platform`.
117
+ */
118
+ export declare function platformKeyringHint(platform?: NodeJS.Platform): string;
119
+ /**
120
+ * `TokenStore` backed by the operating system's native keychain via
121
+ * `@napi-rs/keyring` (macOS Keychain, Windows Credential Manager, Linux
122
+ * Secret Service). On macOS and Linux the blob lives in a single entry
123
+ * keyed by the fixed `credentials` account name. On Windows the blob
124
+ * is split across `credentials.0`, `credentials.1`, … entries to fit
125
+ * under Credential Manager's 2560 UTF-16 character per-entry cap; see
126
+ * `shouldChunkForKeyring`.
127
+ *
128
+ * The blob carries its own issuer/client coordinates so verbs can
129
+ * recover full config without per-issuer keying.
130
+ */
131
+ export declare class KeyringTokenStore implements TokenStore {
132
+ #private;
133
+ /**
134
+ * @param entryFactory Injection seam for `@napi-rs/keyring` entries.
135
+ * Defaults to the production lazy-resolved factory; tests pass a
136
+ * recording / faking variant.
137
+ */
138
+ constructor(entryFactory?: KeyringEntryFactory);
139
+ /**
140
+ * @internal Test seam. Constructs a store with an explicit chunking
141
+ * decision instead of the platform-determined default, so the
142
+ * chunked path can be exercised on macOS/Linux CI and the unchunked
143
+ * path on Windows CI. Production code must use the regular
144
+ * constructor and let `shouldChunkForKeyring()` decide — passing
145
+ * `chunked: true` on macOS would write data that the regular
146
+ * constructor wouldn't be able to read.
147
+ */
148
+ static forTesting(entryFactory: KeyringEntryFactory, chunked: boolean): KeyringTokenStore;
149
+ save(entry: StoredEntry): Promise<void>;
150
+ load(): Promise<LoadResult>;
151
+ clear(): Promise<void>;
152
+ }
153
+ /**
154
+ * Splits `blob` into the N parts that `KeyringTokenStore.#saveChunked`
155
+ * writes to `credentials.0..N-1`. Chunk 0 is prefixed with `<N>\n` so
156
+ * the reader can learn N from a single getPassword call. Each chunk
157
+ * stays under `CHUNK_LIMIT` UTF-16 characters; throws if the blob would
158
+ * require more than `MAX_CHUNKS` chunks. Exported for tests.
159
+ */
160
+ export declare function chunkBlobForKeyring(blob: string): string[];