@deque/axe-auth 1.1.0-next.6ad261c8 → 1.1.0-next.759bd5c5

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 (61) hide show
  1. package/README.md +64 -11
  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/authorizationURL.d.ts +29 -0
  28. package/dist/oauth/authorizationURL.js +52 -0
  29. package/dist/oauth/authorize.d.ts +84 -0
  30. package/dist/oauth/authorize.js +118 -0
  31. package/dist/oauth/discoverOIDC.d.ts +50 -0
  32. package/dist/oauth/discoverOIDC.js +143 -0
  33. package/dist/oauth/errors.d.ts +55 -2
  34. package/dist/oauth/errors.js +35 -1
  35. package/dist/oauth/getValidAccessToken.d.ts +89 -0
  36. package/dist/oauth/getValidAccessToken.js +139 -0
  37. package/dist/oauth/index.d.ts +14 -2
  38. package/dist/oauth/index.js +13 -1
  39. package/dist/oauth/issuerURL.d.ts +22 -0
  40. package/dist/oauth/issuerURL.js +38 -0
  41. package/dist/oauth/keyringBinding.d.ts +22 -0
  42. package/dist/oauth/keyringBinding.js +41 -0
  43. package/dist/oauth/openBrowser.d.ts +19 -0
  44. package/dist/oauth/openBrowser.js +78 -0
  45. package/dist/oauth/pkce.d.ts +17 -0
  46. package/dist/oauth/pkce.js +43 -0
  47. package/dist/oauth/predicates.d.ts +7 -0
  48. package/dist/oauth/predicates.js +15 -0
  49. package/dist/oauth/refreshTokens.d.ts +30 -0
  50. package/dist/oauth/refreshTokens.js +61 -0
  51. package/dist/oauth/revokeToken.d.ts +28 -0
  52. package/dist/oauth/revokeToken.js +59 -0
  53. package/dist/oauth/testUtils.d.ts +35 -0
  54. package/dist/oauth/testUtils.js +61 -0
  55. package/dist/oauth/tokenExchange.d.ts +26 -0
  56. package/dist/oauth/tokenExchange.js +42 -0
  57. package/dist/oauth/tokenResponse.d.ts +54 -0
  58. package/dist/oauth/tokenResponse.js +121 -0
  59. package/dist/oauth/tokenStore.d.ts +111 -0
  60. package/dist/oauth/tokenStore.js +198 -0
  61. package/package.json +11 -2
@@ -1,3 +1,4 @@
1
+ /** Error codes raised by the loopback callback server. */
1
2
  export type OAuthCallbackErrorCode =
2
3
  /** No callback arrived within `timeoutMs`; a retry is reasonable. */
3
4
  "TIMEOUT"
@@ -11,12 +12,64 @@ export type OAuthCallbackErrorCode =
11
12
  | "BIND_FAILED"
12
13
  /** Caller's `AbortSignal` fired. Expected; no user-facing message. */
13
14
  | "ABORTED";
14
- export type OAuthCallbackErrorOptions = {
15
+ /** Options for `OAuthCallbackError`. */
16
+ export interface OAuthCallbackErrorOptions {
17
+ /** Structured metadata for callers that want to surface specific fields. */
15
18
  details?: Record<string, string>;
19
+ /** Underlying error that triggered this failure. */
16
20
  cause?: unknown;
17
- };
21
+ }
22
+ /**
23
+ * Error raised by the loopback callback server when the authorization
24
+ * response cannot be consumed (timeout, state mismatch, provider error,
25
+ * malformed response, bind failure, or caller abort).
26
+ */
18
27
  export declare class OAuthCallbackError extends Error {
28
+ /** Discriminator for programmatic handling. */
19
29
  readonly code: OAuthCallbackErrorCode;
30
+ /** Structured metadata carried alongside the error, if any. */
20
31
  readonly details?: Record<string, string>;
21
32
  constructor(code: OAuthCallbackErrorCode, message: string, options?: OAuthCallbackErrorOptions);
22
33
  }
34
+ /** Error codes raised by the OAuth flow orchestrator and its helpers. */
35
+ export type OAuthFlowErrorCode =
36
+ /** OIDC discovery could not reach or parse the authorization server. No browser was opened. */
37
+ "DISCOVERY_FAILED"
38
+ /** Could not launch the system browser. User should be told to open the URL manually. */
39
+ | "BROWSER_LAUNCH_FAILED"
40
+ /** Authorization code → token exchange was rejected by the authorization server. */
41
+ | "TOKEN_EXCHANGE_FAILED"
42
+ /** System keychain is unavailable (e.g. no D-Bus secret service on Linux). */
43
+ | "KEYRING_UNAVAILABLE"
44
+ /** Authorization endpoint returned by discovery cannot be used (e.g. already carries an OAuth-required param). Server misconfiguration. */
45
+ | "INVALID_AUTHORIZATION_ENDPOINT"
46
+ /** No usable stored credentials; the user needs to run `login` to re-authenticate. Covers empty / corrupt / version-mismatched store and refresh tokens the authorization server has revoked. */
47
+ | "NOT_AUTHENTICATED";
48
+ /** Options for `OAuthFlowError`. */
49
+ export interface OAuthFlowErrorOptions {
50
+ /** Structured metadata for callers that want to surface specific fields. */
51
+ details?: Record<string, string>;
52
+ /** Underlying error that triggered this failure. */
53
+ cause?: unknown;
54
+ }
55
+ /**
56
+ * Error raised by anything in the OAuth flow outside the callback
57
+ * server itself: OIDC discovery, browser launch, token exchange, or
58
+ * keychain access.
59
+ *
60
+ * **Logging note.** For code `TOKEN_EXCHANGE_FAILED`, `message` may
61
+ * include the authorization server's `error_description`, which is
62
+ * free-form text the server controls and could plausibly contain
63
+ * user-identifying or otherwise sensitive information. Prefer
64
+ * structured logging via the discriminated `code` and the explicit
65
+ * `details` fields; avoid echoing the raw `message` (or the result
66
+ * of `console.error(err)`, which includes it) into shared log sinks
67
+ * without a redaction step.
68
+ */
69
+ export declare class OAuthFlowError extends Error {
70
+ /** Discriminator for programmatic handling. */
71
+ readonly code: OAuthFlowErrorCode;
72
+ /** Structured metadata carried alongside the error, if any. */
73
+ readonly details?: Record<string, string>;
74
+ constructor(code: OAuthFlowErrorCode, message: string, options?: OAuthFlowErrorOptions);
75
+ }
@@ -1,8 +1,15 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.OAuthCallbackError = void 0;
3
+ exports.OAuthFlowError = exports.OAuthCallbackError = void 0;
4
+ /**
5
+ * Error raised by the loopback callback server when the authorization
6
+ * response cannot be consumed (timeout, state mismatch, provider error,
7
+ * malformed response, bind failure, or caller abort).
8
+ */
4
9
  class OAuthCallbackError extends Error {
10
+ /** Discriminator for programmatic handling. */
5
11
  code;
12
+ /** Structured metadata carried alongside the error, if any. */
6
13
  details;
7
14
  constructor(code, message, options = {}) {
8
15
  super(message, { cause: options.cause });
@@ -12,3 +19,30 @@ class OAuthCallbackError extends Error {
12
19
  }
13
20
  }
14
21
  exports.OAuthCallbackError = OAuthCallbackError;
22
+ /**
23
+ * Error raised by anything in the OAuth flow outside the callback
24
+ * server itself: OIDC discovery, browser launch, token exchange, or
25
+ * keychain access.
26
+ *
27
+ * **Logging note.** For code `TOKEN_EXCHANGE_FAILED`, `message` may
28
+ * include the authorization server's `error_description`, which is
29
+ * free-form text the server controls and could plausibly contain
30
+ * user-identifying or otherwise sensitive information. Prefer
31
+ * structured logging via the discriminated `code` and the explicit
32
+ * `details` fields; avoid echoing the raw `message` (or the result
33
+ * of `console.error(err)`, which includes it) into shared log sinks
34
+ * without a redaction step.
35
+ */
36
+ class OAuthFlowError extends Error {
37
+ /** Discriminator for programmatic handling. */
38
+ code;
39
+ /** Structured metadata carried alongside the error, if any. */
40
+ details;
41
+ constructor(code, message, options = {}) {
42
+ super(message, { cause: options.cause });
43
+ this.name = "OAuthFlowError";
44
+ this.code = code;
45
+ this.details = options.details;
46
+ }
47
+ }
48
+ exports.OAuthFlowError = OAuthFlowError;
@@ -0,0 +1,89 @@
1
+ import { type LoadResult, type TokenStore } from "./tokenStore";
2
+ /** Options for `getValidAccessToken`. */
3
+ export interface GetValidAccessTokenOptions {
4
+ /**
5
+ * OIDC issuer URL (same value passed to `authorize`). Must match
6
+ * the stored entry's `issuerURL`; mismatch throws
7
+ * `OAuthFlowError("NOT_AUTHENTICATED", ...)` rather than refreshing
8
+ * the wrong issuer's tokens at the requested endpoint.
9
+ */
10
+ issuerURL: string;
11
+ /**
12
+ * OAuth client identifier. Must match the stored entry's
13
+ * `clientId`; see the note on `issuerURL` for the mismatch
14
+ * behavior.
15
+ */
16
+ clientId: string;
17
+ /**
18
+ * How close to expiry we start preemptively refreshing, in
19
+ * milliseconds. Defaults to 60_000 (60s). The buffer gives headroom
20
+ * between our "still fresh enough" check and the server's view of
21
+ * expiry (which may differ by a few seconds of clock skew) and
22
+ * prevents a token from expiring mid-request after we hand it out.
23
+ *
24
+ * Assumes the access-token TTL is much larger than the buffer. With
25
+ * TTLs ≤ `expiryBufferMs`, every call will trigger a refresh.
26
+ */
27
+ expiryBufferMs?: number;
28
+ /**
29
+ * Override for the token store. Defaults to a fresh
30
+ * `KeyringTokenStore()` (single keychain entry per machine).
31
+ */
32
+ tokenStore?: TokenStore;
33
+ /**
34
+ * Pre-loaded result of `tokenStore.load()`. When provided, the
35
+ * function skips its own keychain read and uses this value
36
+ * instead — lets a caller that already loaded the entry (the CLI
37
+ * dispatcher does, to derive `parseCommonArgs` defaults) avoid a
38
+ * redundant second read on the hot path. The same `tokenStore` is
39
+ * still used for the post-refresh `save()` and the
40
+ * `invalid_grant` `clear()`.
41
+ */
42
+ loadedEntry?: LoadResult;
43
+ /** Aborts discovery + the refresh POST when fired. */
44
+ signal?: AbortSignal;
45
+ /**
46
+ * Forwarded to discovery. Loopback issuers are always permitted
47
+ * over http; this flag is the opt-in for non-loopback http.
48
+ */
49
+ allowInsecureIssuer?: boolean;
50
+ /**
51
+ * Called for soft warnings that are not errors but warrant user
52
+ * attention (e.g. a fresh `TokenSet` could not be written to the
53
+ * keychain, stranding the rotated refresh token — see the hazard
54
+ * note in the body of `getValidAccessToken`). The default prints
55
+ * to stderr only when stderr is a TTY. Pass a custom handler to
56
+ * route warnings through your own UI, or `() => {}` to suppress.
57
+ */
58
+ onWarning?: (message: string) => void;
59
+ /** Source of `now`. Defaults to `Date.now`. Injected for test determinism. */
60
+ now?: () => number;
61
+ }
62
+ /**
63
+ * Returns a currently-valid access token string for the given issuer,
64
+ * refreshing via the stored refresh token if the cached access token
65
+ * is within `expiryBufferMs` of expiring (or already expired).
66
+ *
67
+ * Throws `OAuthFlowError("NOT_AUTHENTICATED", ...)` when the user
68
+ * must re-run `axe-auth login` — covers an empty / corrupt /
69
+ * version-mismatched store, an expired access token with no refresh
70
+ * token to rotate with, and a refresh attempt rejected with
71
+ * `invalid_grant` (which also clears the stored tokens).
72
+ *
73
+ * Throws `OAuthFlowError("TOKEN_EXCHANGE_FAILED", ...)` for transient
74
+ * failures during refresh (network errors, 5xx, malformed responses)
75
+ * and leaves the stored tokens intact so a retry is possible.
76
+ *
77
+ * Throws `OAuthFlowError("DISCOVERY_FAILED", ...)` when the issuer
78
+ * URL cannot be reached or parsed at refresh time.
79
+ *
80
+ * **Concurrency note.** Not safe against parallel invocations for
81
+ * the same issuer. Keycloak rotates refresh tokens by default; if
82
+ * two parallel calls both land on the refresh path, only one
83
+ * winner's rotated refresh token will be persisted and the loser's
84
+ * rotated token is stranded. The intended consumer is the
85
+ * `axe-auth token` CLI (a one-shot), so this is fine in context;
86
+ * per-request callers should wrap in an in-flight-Promise singleton
87
+ * keyed by issuer.
88
+ */
89
+ export declare function getValidAccessToken(options: GetValidAccessTokenOptions): Promise<string>;
@@ -0,0 +1,139 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getValidAccessToken = getValidAccessToken;
4
+ const discoverOIDC_1 = require("./discoverOIDC");
5
+ const errors_1 = require("./errors");
6
+ const refreshTokens_1 = require("./refreshTokens");
7
+ const tokenStore_1 = require("./tokenStore");
8
+ const DEFAULT_EXPIRY_BUFFER_MS = 60_000;
9
+ function defaultOnWarning(message) {
10
+ if (process.stderr.isTTY) {
11
+ console.error(`axe-auth: ${message}`);
12
+ }
13
+ }
14
+ function isInvalidGrant(err) {
15
+ return (err instanceof errors_1.OAuthFlowError &&
16
+ err.code === "TOKEN_EXCHANGE_FAILED" &&
17
+ err.details?.error === "invalid_grant");
18
+ }
19
+ function notAuthenticated(message, cause) {
20
+ return new errors_1.OAuthFlowError("NOT_AUTHENTICATED", message, cause === undefined ? undefined : { cause });
21
+ }
22
+ /**
23
+ * Returns a currently-valid access token string for the given issuer,
24
+ * refreshing via the stored refresh token if the cached access token
25
+ * is within `expiryBufferMs` of expiring (or already expired).
26
+ *
27
+ * Throws `OAuthFlowError("NOT_AUTHENTICATED", ...)` when the user
28
+ * must re-run `axe-auth login` — covers an empty / corrupt /
29
+ * version-mismatched store, an expired access token with no refresh
30
+ * token to rotate with, and a refresh attempt rejected with
31
+ * `invalid_grant` (which also clears the stored tokens).
32
+ *
33
+ * Throws `OAuthFlowError("TOKEN_EXCHANGE_FAILED", ...)` for transient
34
+ * failures during refresh (network errors, 5xx, malformed responses)
35
+ * and leaves the stored tokens intact so a retry is possible.
36
+ *
37
+ * Throws `OAuthFlowError("DISCOVERY_FAILED", ...)` when the issuer
38
+ * URL cannot be reached or parsed at refresh time.
39
+ *
40
+ * **Concurrency note.** Not safe against parallel invocations for
41
+ * the same issuer. Keycloak rotates refresh tokens by default; if
42
+ * two parallel calls both land on the refresh path, only one
43
+ * winner's rotated refresh token will be persisted and the loser's
44
+ * rotated token is stranded. The intended consumer is the
45
+ * `axe-auth token` CLI (a one-shot), so this is fine in context;
46
+ * per-request callers should wrap in an in-flight-Promise singleton
47
+ * keyed by issuer.
48
+ */
49
+ async function getValidAccessToken(options) {
50
+ const { issuerURL, clientId, expiryBufferMs = DEFAULT_EXPIRY_BUFFER_MS, tokenStore = new tokenStore_1.KeyringTokenStore(), loadedEntry, signal, allowInsecureIssuer, onWarning = defaultOnWarning, now = Date.now, } = options;
51
+ const loaded = loadedEntry ?? (await tokenStore.load());
52
+ if (!loaded.ok) {
53
+ switch (loaded.reason) {
54
+ case "empty":
55
+ throw notAuthenticated("No stored credentials. Run `axe-auth login` first.");
56
+ case "corrupt":
57
+ throw notAuthenticated("Stored credentials are unreadable. Run `axe-auth login` to re-authenticate.");
58
+ case "version-mismatch":
59
+ throw notAuthenticated(`Stored credentials are from an unsupported schema version (v:${loaded.storedVersion}). Run \`axe-auth login\` to re-authenticate.`);
60
+ }
61
+ }
62
+ // Guard against a mismatch between the requested issuer/client and
63
+ // the stored entry's. Under single-entry storage, the keychain
64
+ // holds one set of tokens minted against one (issuer, client)
65
+ // pair. Refreshing those tokens against a different
66
+ // discovery/token endpoint would land an unrelated refresh token
67
+ // at the wrong server and leak it. Refuse rather than silently
68
+ // proceed so direct library callers (the CLI's verbs warn + route
69
+ // before getting here) get a clear signal.
70
+ if (loaded.entry.issuerURL !== issuerURL ||
71
+ loaded.entry.clientId !== clientId) {
72
+ throw notAuthenticated(`Stored credentials are for issuer ${loaded.entry.issuerURL} (client ${loaded.entry.clientId}), but the requested issuer is ${issuerURL} (client ${clientId}). Run \`axe-auth login\` to re-authenticate.`);
73
+ }
74
+ const tokens = loaded.entry.tokens;
75
+ if (now() + expiryBufferMs < tokens.expiresAt) {
76
+ // Still fresh — no network call, no store write.
77
+ return tokens.accessToken;
78
+ }
79
+ if (!tokens.refreshToken) {
80
+ throw notAuthenticated("Access token has expired and no refresh token is available. Run `axe-auth login` to re-authenticate.");
81
+ }
82
+ const config = await (0, discoverOIDC_1.discoverOIDC)(issuerURL, {
83
+ signal,
84
+ allowInsecureIssuer,
85
+ });
86
+ let fresh;
87
+ try {
88
+ fresh = await (0, refreshTokens_1.refreshTokens)({
89
+ tokenEndpoint: config.tokenEndpoint,
90
+ clientId,
91
+ refreshToken: tokens.refreshToken,
92
+ now,
93
+ signal,
94
+ });
95
+ }
96
+ catch (err) {
97
+ if (isInvalidGrant(err)) {
98
+ // Refresh token revoked / expired server-side. Best-effort
99
+ // clear of the stored tokens so the next run starts clean —
100
+ // but if the clear itself fails (e.g. KEYRING_UNAVAILABLE),
101
+ // prefer surfacing NOT_AUTHENTICATED so the user still gets
102
+ // the actionable "please run login" signal. Note the clear
103
+ // failure via onWarning; the next run will see the stale
104
+ // tokens, try to refresh, and land back here.
105
+ try {
106
+ await tokenStore.clear();
107
+ }
108
+ catch (clearErr) {
109
+ onWarning(`Failed to clear stored tokens after refresh rejection: ${clearErr instanceof Error ? clearErr.message : String(clearErr)}. Next run may need to clear manually.`);
110
+ }
111
+ throw notAuthenticated("Your session has expired. Run `axe-auth login` to re-authenticate.", err);
112
+ }
113
+ // Transient failure — leave the store alone so the user can
114
+ // retry without re-logging-in.
115
+ throw err;
116
+ }
117
+ // HAZARD: Keycloak (and most rotating-refresh-token providers) have
118
+ // already consumed the old refresh token server-side by the time
119
+ // `refreshTokens` returns. If persisting the rotated set fails
120
+ // here, we hold a valid access token in memory but the stored
121
+ // refresh token is now stale — the next invocation will POST it,
122
+ // get `invalid_grant`, and prompt re-authentication.
123
+ //
124
+ // We still return the fresh access token so the current call is
125
+ // useful, and warn the caller so "why does the next run need me to
126
+ // log in again?" has a breadcrumb.
127
+ try {
128
+ await tokenStore.save({
129
+ tokens: fresh,
130
+ issuerURL: loaded.entry.issuerURL,
131
+ clientId: loaded.entry.clientId,
132
+ allowInsecureIssuer: loaded.entry.allowInsecureIssuer,
133
+ });
134
+ }
135
+ catch (err) {
136
+ onWarning(`Refreshed tokens could not be saved: ${err instanceof Error ? err.message : String(err)}. The current call will succeed, but the next invocation will require re-authentication.`);
137
+ }
138
+ return fresh.accessToken;
139
+ }
@@ -1,4 +1,16 @@
1
1
  export { startCallbackServer } from "./callbackServer";
2
2
  export type { CallbackServerOptions, CallbackServerHandle, CallbackResult, } from "./callbackServer";
3
- export { OAuthCallbackError } from "./errors";
4
- export type { OAuthCallbackErrorCode, OAuthCallbackErrorOptions, } from "./errors";
3
+ export { OAuthCallbackError, OAuthFlowError } from "./errors";
4
+ export type { OAuthCallbackErrorCode, OAuthCallbackErrorOptions, OAuthFlowErrorCode, OAuthFlowErrorOptions, } from "./errors";
5
+ export { authorize } from "./authorize";
6
+ export type { AuthorizeOptions } from "./authorize";
7
+ export { getValidAccessToken } from "./getValidAccessToken";
8
+ export type { GetValidAccessTokenOptions } from "./getValidAccessToken";
9
+ export { refreshTokens } from "./refreshTokens";
10
+ export type { RefreshTokensOptions } from "./refreshTokens";
11
+ export type { TokenSet } from "./tokenResponse";
12
+ export { KeyringTokenStore, STORED_BLOB_VERSION } from "./tokenStore";
13
+ export type { LoadResult, StoredEntry, TokenStore } from "./tokenStore";
14
+ export type { KeyringEntry, KeyringEntryFactory } from "./keyringBinding";
15
+ export { discoverOIDC } from "./discoverOIDC";
16
+ export type { OIDCConfiguration, DiscoverOIDCOptions } from "./discoverOIDC";
@@ -1,7 +1,19 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.OAuthCallbackError = exports.startCallbackServer = void 0;
3
+ exports.discoverOIDC = exports.STORED_BLOB_VERSION = exports.KeyringTokenStore = exports.refreshTokens = exports.getValidAccessToken = exports.authorize = exports.OAuthFlowError = exports.OAuthCallbackError = exports.startCallbackServer = void 0;
4
4
  var callbackServer_1 = require("./callbackServer");
5
5
  Object.defineProperty(exports, "startCallbackServer", { enumerable: true, get: function () { return callbackServer_1.startCallbackServer; } });
6
6
  var errors_1 = require("./errors");
7
7
  Object.defineProperty(exports, "OAuthCallbackError", { enumerable: true, get: function () { return errors_1.OAuthCallbackError; } });
8
+ Object.defineProperty(exports, "OAuthFlowError", { enumerable: true, get: function () { return errors_1.OAuthFlowError; } });
9
+ var authorize_1 = require("./authorize");
10
+ Object.defineProperty(exports, "authorize", { enumerable: true, get: function () { return authorize_1.authorize; } });
11
+ var getValidAccessToken_1 = require("./getValidAccessToken");
12
+ Object.defineProperty(exports, "getValidAccessToken", { enumerable: true, get: function () { return getValidAccessToken_1.getValidAccessToken; } });
13
+ var refreshTokens_1 = require("./refreshTokens");
14
+ Object.defineProperty(exports, "refreshTokens", { enumerable: true, get: function () { return refreshTokens_1.refreshTokens; } });
15
+ var tokenStore_1 = require("./tokenStore");
16
+ Object.defineProperty(exports, "KeyringTokenStore", { enumerable: true, get: function () { return tokenStore_1.KeyringTokenStore; } });
17
+ Object.defineProperty(exports, "STORED_BLOB_VERSION", { enumerable: true, get: function () { return tokenStore_1.STORED_BLOB_VERSION; } });
18
+ var discoverOIDC_1 = require("./discoverOIDC");
19
+ Object.defineProperty(exports, "discoverOIDC", { enumerable: true, get: function () { return discoverOIDC_1.discoverOIDC; } });
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Canonicalizes an OIDC issuer URL for equivalence comparison. Two URLs
3
+ * that normalize to the same string refer to the same issuer, which is
4
+ * what `discoverOIDC` uses to build discovery URLs and what
5
+ * `KeyringTokenStore` uses to key keychain entries.
6
+ *
7
+ * Rules (per RFC 3986 §6.2 URI comparison):
8
+ * - Trailing slashes stripped from the path.
9
+ * - Scheme and authority (host + optional port) lowercased — both are
10
+ * case-insensitive per the RFC.
11
+ * - Default ports (80 for http, 443 for https) collapsed via `URL.host`.
12
+ * - Path preserved case-sensitively.
13
+ * - Query string and fragment dropped: OIDC issuers are defined by
14
+ * scheme + authority + path, and carrying them through would break
15
+ * downstream path concatenation (e.g. appending
16
+ * `/.well-known/openid-configuration`).
17
+ *
18
+ * If the input is not a parseable URL, the function trims trailing
19
+ * slashes and returns — discovery will surface a clearer error than
20
+ * this function could.
21
+ */
22
+ export declare function normalizeIssuerURL(url: string): string;
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normalizeIssuerURL = normalizeIssuerURL;
4
+ /**
5
+ * Canonicalizes an OIDC issuer URL for equivalence comparison. Two URLs
6
+ * that normalize to the same string refer to the same issuer, which is
7
+ * what `discoverOIDC` uses to build discovery URLs and what
8
+ * `KeyringTokenStore` uses to key keychain entries.
9
+ *
10
+ * Rules (per RFC 3986 §6.2 URI comparison):
11
+ * - Trailing slashes stripped from the path.
12
+ * - Scheme and authority (host + optional port) lowercased — both are
13
+ * case-insensitive per the RFC.
14
+ * - Default ports (80 for http, 443 for https) collapsed via `URL.host`.
15
+ * - Path preserved case-sensitively.
16
+ * - Query string and fragment dropped: OIDC issuers are defined by
17
+ * scheme + authority + path, and carrying them through would break
18
+ * downstream path concatenation (e.g. appending
19
+ * `/.well-known/openid-configuration`).
20
+ *
21
+ * If the input is not a parseable URL, the function trims trailing
22
+ * slashes and returns — discovery will surface a clearer error than
23
+ * this function could.
24
+ */
25
+ function normalizeIssuerURL(url) {
26
+ let parsed;
27
+ try {
28
+ parsed = new URL(url);
29
+ }
30
+ catch {
31
+ return url.replace(/\/+$/, "");
32
+ }
33
+ // `URL.protocol` is already lowercased by the URL parser.
34
+ // `URL.host` retains input casing, so lowercase it explicitly.
35
+ const host = parsed.host.toLowerCase();
36
+ const pathname = parsed.pathname.replace(/\/+$/, "");
37
+ return `${parsed.protocol}//${host}${pathname}`;
38
+ }
@@ -0,0 +1,22 @@
1
+ /** Minimal keyring-entry surface consumed by the package's stores. */
2
+ export interface KeyringEntry {
3
+ /** Writes the password for this entry. */
4
+ setPassword(password: string): void;
5
+ /** Reads the current password, or returns `null` if none is set. */
6
+ getPassword(): string | null;
7
+ /** Deletes the password and returns `true` if one existed. */
8
+ deletePassword(): boolean;
9
+ }
10
+ /**
11
+ * Factory for `KeyringEntry` values. Injection seam for tests;
12
+ * production callers use the default that constructs
13
+ * `@napi-rs/keyring` entries lazily.
14
+ */
15
+ export type KeyringEntryFactory = (service: string, account: string) => KeyringEntry;
16
+ /**
17
+ * Default `KeyringEntryFactory`. Resolves `@napi-rs/keyring` lazily
18
+ * so platforms without a prebuilt binding only see a
19
+ * `KEYRING_UNAVAILABLE` on first store construction, not on module
20
+ * import.
21
+ */
22
+ export declare const defaultEntryFactory: KeyringEntryFactory;
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.defaultEntryFactory = void 0;
4
+ const node_module_1 = require("node:module");
5
+ const errors_1 = require("./errors");
6
+ const requireFromHere = (0, node_module_1.createRequire)(__filename);
7
+ // Lazy-resolved Entry constructor. Importing @napi-rs/keyring at the
8
+ // top of this module would run its native binding loader at
9
+ // module-load time, throwing before any of our OAuthFlowError code
10
+ // catches it and preventing the module from being imported at all on
11
+ // platforms without a prebuilt. We defer the require into
12
+ // `defaultEntryFactory`, which turns that import-time failure into a
13
+ // `KEYRING_UNAVAILABLE` surfaced on the first store construction —
14
+ // not on first save/load/clear, since callers construct stores
15
+ // eagerly as default-arg expressions. Runtime keychain errors
16
+ // (missing D-Bus Secret Service, macOS Keychain denial, etc.) are a
17
+ // separate concern and surface later, inside save/load/clear.
18
+ let cachedEntryCtor = null;
19
+ function resolveEntryCtor() {
20
+ if (cachedEntryCtor)
21
+ return cachedEntryCtor;
22
+ try {
23
+ const mod = requireFromHere("@napi-rs/keyring");
24
+ cachedEntryCtor = mod.Entry;
25
+ return cachedEntryCtor;
26
+ }
27
+ catch (cause) {
28
+ throw new errors_1.OAuthFlowError("KEYRING_UNAVAILABLE", `Could not load @napi-rs/keyring. A prebuilt native binding for this platform may be missing.`, { cause });
29
+ }
30
+ }
31
+ /**
32
+ * Default `KeyringEntryFactory`. Resolves `@napi-rs/keyring` lazily
33
+ * so platforms without a prebuilt binding only see a
34
+ * `KEYRING_UNAVAILABLE` on first store construction, not on module
35
+ * import.
36
+ */
37
+ const defaultEntryFactory = (service, account) => {
38
+ const Ctor = resolveEntryCtor();
39
+ return new Ctor(service, account);
40
+ };
41
+ exports.defaultEntryFactory = defaultEntryFactory;
@@ -0,0 +1,19 @@
1
+ import type { ChildProcess, SpawnOptions } from "node:child_process";
2
+ /** Injection seam for `child_process.spawn`. Used by tests. */
3
+ export type SpawnFn = (command: string, args: readonly string[], options: SpawnOptions) => ChildProcess;
4
+ /** Options for `openBrowser`. */
5
+ export interface OpenBrowserOptions {
6
+ /** Override for `process.platform`. Used by tests. */
7
+ platform?: NodeJS.Platform;
8
+ /** Override for `child_process.spawn`. Used by tests. */
9
+ spawnFn?: SpawnFn;
10
+ }
11
+ /**
12
+ * Launches the system browser at `url` in a detached child process.
13
+ * Returns synchronously once the child is spawned — completion of the
14
+ * browser load is intentionally not awaited.
15
+ *
16
+ * @param url Absolute URL to open.
17
+ * @param options Platform/spawn overrides; only exposed for tests.
18
+ */
19
+ export declare function openBrowser(url: string, options?: OpenBrowserOptions): void;
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.openBrowser = openBrowser;
4
+ const node_child_process_1 = require("node:child_process");
5
+ const errors_1 = require("./errors");
6
+ // On Windows `start` is a cmd.exe builtin, not a standalone binary.
7
+ // The empty `""` pair is a positional placeholder for the window
8
+ // title — without it `start` treats the URL as the title.
9
+ //
10
+ // The escape class covers:
11
+ // - `& | ^ < >` — cmd metacharacters that would otherwise split the
12
+ // command line.
13
+ // - `"` — would prematurely terminate the argument and break
14
+ // `start`'s quoting.
15
+ // - `%` — triggers cmd.exe environment-variable expansion (e.g.
16
+ // `%USERNAME%`), which could leak or alter the URL.
17
+ // - `\r \n` — embedded newlines let a crafted URL inject additional
18
+ // commands onto cmd.exe's line.
19
+ //
20
+ // URLs normally percent-encode most of these (so this is defense in
21
+ // depth), but we do not fully trust the authorization endpoint that
22
+ // came back from discovery.
23
+ function windowsCommand(url) {
24
+ return {
25
+ command: "cmd.exe",
26
+ args: ["/c", "start", '""', url.replace(/[&|^<>"%\r\n]/g, (c) => `^${c}`)],
27
+ };
28
+ }
29
+ function browserCommand(platform, url) {
30
+ switch (platform) {
31
+ case "darwin":
32
+ return { command: "open", args: [url] };
33
+ case "win32":
34
+ return windowsCommand(url);
35
+ default:
36
+ // linux / freebsd / openbsd — xdg-open is part of xdg-utils which
37
+ // is near-universal on desktop Linux. Environments without it
38
+ // (headless servers, containers) will report the missing binary
39
+ // via an asynchronous child-process `error` event, which this
40
+ // module deliberately swallows (see `child.once("error", ...)`
41
+ // below); `BROWSER_LAUNCH_FAILED` is only raised for synchronous
42
+ // `spawn()` throws. The caller's fallback is the URL already
43
+ // surfaced via `onAuthorizationUrl` so the user can finish the
44
+ // flow manually.
45
+ return { command: "xdg-open", args: [url] };
46
+ }
47
+ }
48
+ /**
49
+ * Launches the system browser at `url` in a detached child process.
50
+ * Returns synchronously once the child is spawned — completion of the
51
+ * browser load is intentionally not awaited.
52
+ *
53
+ * @param url Absolute URL to open.
54
+ * @param options Platform/spawn overrides; only exposed for tests.
55
+ */
56
+ function openBrowser(url, options = {}) {
57
+ const platform = options.platform ?? process.platform;
58
+ const spawnFn = options.spawnFn ?? node_child_process_1.spawn;
59
+ const { command, args } = browserCommand(platform, url);
60
+ let child;
61
+ try {
62
+ child = spawnFn(command, args, {
63
+ detached: true,
64
+ stdio: "ignore",
65
+ });
66
+ }
67
+ catch (cause) {
68
+ throw new errors_1.OAuthFlowError("BROWSER_LAUNCH_FAILED", `Failed to launch the system browser (${command}). Open this URL manually:\n${url}`, { cause });
69
+ }
70
+ // `spawn` itself can succeed (the parent fork was fine) and then emit
71
+ // `error` asynchronously if the binary isn't on PATH. We can't surface
72
+ // that synchronously, but attaching a handler prevents the default
73
+ // "unhandled error" crash. Callers get a benign no-op if the browser
74
+ // never opens; the authorize() orchestrator prints the URL alongside
75
+ // the launch so the user has a fallback.
76
+ child.once("error", () => { });
77
+ child.unref();
78
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Generates a cryptographically random PKCE `code_verifier` per RFC 7636
3
+ * §4.1. 43 base64url characters, 256 bits of entropy.
4
+ */
5
+ export declare function generateCodeVerifier(): string;
6
+ /**
7
+ * Derives the PKCE S256 `code_challenge` for the given verifier per
8
+ * RFC 7636 §4.2: `BASE64URL(SHA256(ASCII(verifier)))`.
9
+ *
10
+ * @param verifier The PKCE verifier produced by `generateCodeVerifier`.
11
+ */
12
+ export declare function deriveCodeChallenge(verifier: string): string;
13
+ /**
14
+ * Generates a cryptographically random OAuth `state` value for CSRF
15
+ * protection. 22 base64url characters, 128 bits of entropy.
16
+ */
17
+ export declare function generateState(): string;