@deque/axe-auth 1.1.0-next.d59ba863 → 1.1.0-next.d5a755f8

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 (44) hide show
  1. package/credits.json +11 -0
  2. package/dist/cli/commonArgs.d.ts +11 -58
  3. package/dist/cli/commonArgs.js +8 -35
  4. package/dist/cli/confirm.js +0 -3
  5. package/dist/cli/errors.d.ts +2 -9
  6. package/dist/cli/errors.js +2 -9
  7. package/dist/cli/safeExit.d.ts +8 -0
  8. package/dist/cli/safeExit.js +16 -0
  9. package/dist/cli/types.d.ts +10 -50
  10. package/dist/commands/login.d.ts +1 -4
  11. package/dist/commands/login.js +5 -14
  12. package/dist/commands/logout.js +0 -2
  13. package/dist/commands/token.js +0 -4
  14. package/dist/index.js +8 -14
  15. package/dist/oauth/authorizationURL.d.ts +2 -7
  16. package/dist/oauth/authorizationURL.js +3 -7
  17. package/dist/oauth/authorize.d.ts +13 -51
  18. package/dist/oauth/authorize.js +8 -10
  19. package/dist/oauth/callbackServer.d.ts +20 -9
  20. package/dist/oauth/callbackServer.js +33 -27
  21. package/dist/oauth/discoverOIDC.d.ts +10 -27
  22. package/dist/oauth/discoverOIDC.js +17 -46
  23. package/dist/oauth/discoverSSOConfig.d.ts +2 -12
  24. package/dist/oauth/errors.d.ts +2 -0
  25. package/dist/oauth/getValidAccessToken.d.ts +9 -44
  26. package/dist/oauth/getValidAccessToken.js +7 -16
  27. package/dist/oauth/openBrowser.d.ts +14 -3
  28. package/dist/oauth/openBrowser.js +23 -6
  29. package/dist/oauth/refreshTokens.js +3 -5
  30. package/dist/oauth/renderHTML.d.ts +12 -0
  31. package/dist/oauth/{renderHtml.js → renderHTML.js} +17 -11
  32. package/dist/oauth/retry.d.ts +2 -0
  33. package/dist/oauth/retry.js +50 -0
  34. package/dist/oauth/revokeToken.js +3 -2
  35. package/dist/oauth/tokenExchange.d.ts +1 -1
  36. package/dist/oauth/tokenExchange.js +4 -3
  37. package/dist/oauth/tokenResponse.d.ts +6 -38
  38. package/dist/oauth/tokenResponse.js +7 -27
  39. package/dist/oauth/tokenStore.d.ts +58 -3
  40. package/dist/oauth/tokenStore.js +374 -31
  41. package/docs/callback-page.md +2 -2
  42. package/docs/callback-server.md +1 -1
  43. package/package.json +16 -5
  44. package/dist/oauth/renderHtml.d.ts +0 -9
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.refreshTokens = refreshTokens;
4
4
  const errors_1 = require("./errors");
5
+ const retry_1 = require("./retry");
5
6
  const tokenResponse_1 = require("./tokenResponse");
6
7
  const userAgent_1 = require("../userAgent");
7
8
  /**
@@ -31,11 +32,11 @@ async function refreshTokens(options) {
31
32
  grant_type: "refresh_token",
32
33
  client_id: options.clientId,
33
34
  refresh_token: options.refreshToken,
34
- });
35
+ }).toString();
35
36
  const issuedAt = now();
36
37
  let response;
37
38
  try {
38
- response = await fetch(options.tokenEndpoint, {
39
+ response = await (0, retry_1.fetchWithRetry)(options.tokenEndpoint, {
39
40
  method: "POST",
40
41
  headers: {
41
42
  "Content-Type": "application/x-www-form-urlencoded",
@@ -53,9 +54,6 @@ async function refreshTokens(options) {
53
54
  await (0, tokenResponse_1.throwTokenEndpointError)(response, "Token refresh");
54
55
  }
55
56
  const fresh = await (0, tokenResponse_1.parseTokenResponse)(response, issuedAt, options.tokenEndpoint);
56
- // Preserve the input refresh token if the server didn't rotate.
57
- // Keycloak rotates by default; others (e.g. Okta with some
58
- // configs) don't.
59
57
  return {
60
58
  ...fresh,
61
59
  refreshToken: fresh.refreshToken ?? options.refreshToken,
@@ -0,0 +1,12 @@
1
+ /** Discriminates the success vs. error variant of the callback page. */
2
+ export type HTMLInput = {
3
+ kind: "success";
4
+ } | {
5
+ kind: "error";
6
+ reason: string;
7
+ description?: string;
8
+ };
9
+ /** Content-Security-Policy header value sent with every callback page. */
10
+ export declare const CSP_HEADER: string;
11
+ /** Renders the loopback callback page shown in the user's browser. */
12
+ export declare function renderHTML(input: HTMLInput): string;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.renderHtml = exports.CSP_HEADER = void 0;
3
+ exports.CSP_HEADER = void 0;
4
+ exports.renderHTML = renderHTML;
4
5
  const node_crypto_1 = require("node:crypto");
5
6
  const logo_generated_1 = require("./logo.generated");
6
7
  const CSS = `:root{--off-black:#666;--off-white:#fdfdfe;--white:#fff;--pink:#d71ef7;--blue:#3c7aae;--space-small:12px;--space-medium:24px;--space-large:36px;--space-huge:48px;--border-radius:3px}
@@ -19,17 +20,21 @@ main{margin:var(--space-huge) auto;padding-left:var(--space-medium);padding-righ
19
20
  // 'unsafe-inline'. Any drift between this digest and the rendered <style> tag
20
21
  // causes the browser to refuse the stylesheet — see docs/callback-page.md.
21
22
  const STYLE_HASH = (0, node_crypto_1.createHash)("sha256").update(CSS, "utf8").digest("base64");
23
+ /** Content-Security-Policy header value sent with every callback page. */
22
24
  exports.CSP_HEADER = `default-src 'none'; img-src data:; style-src 'sha256-${STYLE_HASH}'; frame-ancestors 'none'`;
23
25
  // OWASP-recommended 5-character set for HTML body/attribute contexts;
24
26
  // & must come first to avoid double-escaping. Not safe for JS/CSS/URL contexts.
25
27
  // https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html#output-encoding-for-html-contexts
26
- const escape = (s) => s
27
- .replace(/&/g, "&amp;")
28
- .replace(/</g, "&lt;")
29
- .replace(/>/g, "&gt;")
30
- .replace(/"/g, "&quot;")
31
- .replace(/'/g, "&#39;");
32
- const page = (title, body) => `<!doctype html>
28
+ function escape(s) {
29
+ return s
30
+ .replace(/&/g, "&amp;")
31
+ .replace(/</g, "&lt;")
32
+ .replace(/>/g, "&gt;")
33
+ .replace(/"/g, "&quot;")
34
+ .replace(/'/g, "&#39;");
35
+ }
36
+ function page(title, body) {
37
+ return `<!doctype html>
33
38
  <html lang="en">
34
39
  <head>
35
40
  <meta charset="UTF-8">
@@ -44,7 +49,9 @@ ${body}
44
49
  </main>
45
50
  </body>
46
51
  </html>`;
47
- const renderHtml = (input) => {
52
+ }
53
+ /** Renders the loopback callback page shown in the user's browser. */
54
+ function renderHTML(input) {
48
55
  if (input.kind === "success") {
49
56
  return page("Authenticated", `<h1>Authenticated</h1>
50
57
  <p class="close">You can close this tab and return to your terminal.</p>`);
@@ -56,5 +63,4 @@ const renderHtml = (input) => {
56
63
  <p class="reason">${escape(input.reason)}</p>
57
64
  ${descriptionBlock}
58
65
  <p class="close">You can close this tab and return to your terminal.</p>`);
59
- };
60
- exports.renderHtml = renderHtml;
66
+ }
@@ -0,0 +1,2 @@
1
+ /** Wraps `fetch` with bounded retries on transient connection errors. */
2
+ export declare function fetchWithRetry(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ // undici's `RetryAgent` cannot retry POSTs through `fetch()` — its retry
3
+ // handler aborts once the fetch ReadableStream body is consumed. Re-invoking
4
+ // `fetch()` per attempt with a string body sidesteps that. POST replay is
5
+ // safe for our OAuth endpoints by spec: single-use codes (RFC 6749 §4.1.2),
6
+ // refresh requests that never reached the server (§6), no-op revocation
7
+ // (RFC 7009 §2.2).
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.fetchWithRetry = fetchWithRetry;
10
+ const promises_1 = require("node:timers/promises");
11
+ const MAX_RETRIES = 3;
12
+ const CONNECTION_ERROR_CODES = new Set([
13
+ "ECONNRESET",
14
+ "ECONNREFUSED",
15
+ "ENOTFOUND",
16
+ "ENETDOWN",
17
+ "ENETUNREACH",
18
+ "EHOSTDOWN",
19
+ "UND_ERR_SOCKET",
20
+ ]);
21
+ function isConnectionError(err) {
22
+ const seen = new Set();
23
+ let current = err;
24
+ while (current && typeof current === "object" && !seen.has(current)) {
25
+ seen.add(current);
26
+ const e = current;
27
+ if (typeof e.code === "string" && CONNECTION_ERROR_CODES.has(e.code)) {
28
+ return true;
29
+ }
30
+ current = e.cause;
31
+ }
32
+ return false;
33
+ }
34
+ /** Wraps `fetch` with bounded retries on transient connection errors. */
35
+ async function fetchWithRetry(input, init) {
36
+ for (let attempt = 0;; attempt++) {
37
+ try {
38
+ return await fetch(input, init);
39
+ }
40
+ catch (err) {
41
+ if (attempt >= MAX_RETRIES || !isConnectionError(err)) {
42
+ throw err;
43
+ }
44
+ // Exponential backoff: 500ms, 1s, 2s, capped at 30s.
45
+ // `sleep` honors `init.signal` so an aborted request interrupts the wait.
46
+ const delay = Math.min(500 * Math.pow(2, attempt), 30_000);
47
+ await (0, promises_1.setTimeout)(delay, undefined, { signal: init?.signal ?? undefined });
48
+ }
49
+ }
50
+ }
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.revokeRefreshToken = revokeRefreshToken;
4
+ const retry_1 = require("./retry");
4
5
  const userAgent_1 = require("../userAgent");
5
6
  /**
6
7
  * Revokes a refresh token via RFC 7009. Servers SHOULD return 200
@@ -23,10 +24,10 @@ async function revokeRefreshToken(options) {
23
24
  token: options.refreshToken,
24
25
  token_type_hint: "refresh_token",
25
26
  client_id: options.clientId,
26
- });
27
+ }).toString();
27
28
  let response;
28
29
  try {
29
- response = await fetch(options.revocationEndpoint, {
30
+ response = await (0, retry_1.fetchWithRetry)(options.revocationEndpoint, {
30
31
  method: "POST",
31
32
  headers: {
32
33
  "Content-Type": "application/x-www-form-urlencoded",
@@ -10,7 +10,7 @@ export interface ExchangeCodeForTokensOptions {
10
10
  /** PKCE verifier paired with the `code_challenge` sent at auth time. */
11
11
  codeVerifier: string;
12
12
  /** Redirect URI originally sent to the authorization endpoint. */
13
- redirectUri: string;
13
+ redirectURI: string;
14
14
  /** Source of `now`. Injected for test determinism; defaults to `Date.now`. */
15
15
  now?: () => number;
16
16
  /** Aborts the underlying fetch when fired. */
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.exchangeCodeForTokens = exchangeCodeForTokens;
4
4
  const errors_1 = require("./errors");
5
+ const retry_1 = require("./retry");
5
6
  const tokenResponse_1 = require("./tokenResponse");
6
7
  const userAgent_1 = require("../userAgent");
7
8
  /**
@@ -18,12 +19,12 @@ async function exchangeCodeForTokens(options) {
18
19
  client_id: options.clientId,
19
20
  code: options.code,
20
21
  code_verifier: options.codeVerifier,
21
- redirect_uri: options.redirectUri,
22
- });
22
+ redirect_uri: options.redirectURI,
23
+ }).toString();
23
24
  const issuedAt = now();
24
25
  let response;
25
26
  try {
26
- response = await fetch(options.tokenEndpoint, {
27
+ response = await (0, retry_1.fetchWithRetry)(options.tokenEndpoint, {
27
28
  method: "POST",
28
29
  headers: {
29
30
  "Content-Type": "application/x-www-form-urlencoded",
@@ -1,18 +1,4 @@
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
- */
1
+ /** Tokens returned by a successful token-endpoint call. */
16
2
  export interface TokenSet {
17
3
  /** Access token for authenticated API calls. */
18
4
  accessToken: string;
@@ -24,31 +10,13 @@ export interface TokenSet {
24
10
  grantedScope?: string;
25
11
  }
26
12
  /**
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.
13
+ * Reads a non-2xx response body and throws `TOKEN_EXCHANGE_FAILED`
14
+ * with the OAuth `error` / `error_description` surfaced when present.
36
15
  */
37
16
  export declare function throwTokenEndpointError(response: Response, context: string): Promise<never>;
38
17
  /**
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.
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.
53
21
  */
54
22
  export declare function parseTokenResponse(response: Response, issuedAt: number, endpointURL: string): Promise<TokenSet>;
@@ -4,10 +4,8 @@ exports.throwTokenEndpointError = throwTokenEndpointError;
4
4
  exports.parseTokenResponse = parseTokenResponse;
5
5
  const errors_1 = require("./errors");
6
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.
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.
11
9
  function parseExpiresIn(v) {
12
10
  if (typeof v === "number" && Number.isFinite(v) && v > 0)
13
11
  return v;
@@ -37,15 +35,8 @@ function parseErrorBody(body) {
37
35
  };
38
36
  }
39
37
  /**
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.
38
+ * Reads a non-2xx response body and throws `TOKEN_EXCHANGE_FAILED`
39
+ * with the OAuth `error` / `error_description` surfaced when present.
49
40
  */
50
41
  async function throwTokenEndpointError(response, context) {
51
42
  const body = await response.text().catch(() => "");
@@ -63,20 +54,9 @@ async function throwTokenEndpointError(response, context) {
63
54
  throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `${context} failed with HTTP ${response.status}${suffix}`, Object.keys(details).length > 0 ? { details } : undefined);
64
55
  }
65
56
  /**
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.
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.
80
60
  */
81
61
  async function parseTokenResponse(response, issuedAt, endpointURL) {
82
62
  let parsed;
@@ -1,5 +1,16 @@
1
1
  import { type KeyringEntryFactory } from "./keyringBinding";
2
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;
3
14
  /**
4
15
  * Current on-disk blob schema version. Exported so consumers can
5
16
  * display "stored v:N, expected v:M" diagnostics when `load()` returns
@@ -100,17 +111,61 @@ export type BlobChainResult = {
100
111
  * and `MIGRATORS` and applies the latest-shape check on top.
101
112
  */
102
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;
103
130
  /**
104
131
  * `TokenStore` backed by the operating system's native keychain via
105
132
  * `@napi-rs/keyring` (macOS Keychain, Windows Credential Manager, Linux
106
- * Secret Service). One entry per machine, keyed by a fixed account
107
- * name; the blob carries its own issuer/client coordinates so verbs
108
- * can recover full config without per-issuer keying.
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.
109
141
  */
110
142
  export declare class KeyringTokenStore implements TokenStore {
111
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
+ */
112
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;
113
160
  save(entry: StoredEntry): Promise<void>;
114
161
  load(): Promise<LoadResult>;
115
162
  clear(): Promise<void>;
116
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[];