@deque/axe-auth 1.1.0-next.40bb9b53 → 1.1.0-next.5c407e02
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.
- package/README.md +14 -8
- package/dist/oauth/authorizationURL.d.ts +29 -0
- package/dist/oauth/authorizationURL.js +52 -0
- package/dist/oauth/authorize.d.ts +83 -0
- package/dist/oauth/authorize.js +114 -0
- package/dist/oauth/discoverOIDC.d.ts +50 -0
- package/dist/oauth/discoverOIDC.js +143 -0
- package/dist/oauth/errors.d.ts +55 -2
- package/dist/oauth/errors.js +35 -1
- package/dist/oauth/getValidAccessToken.d.ts +70 -0
- package/dist/oauth/getValidAccessToken.js +122 -0
- package/dist/oauth/index.d.ts +13 -2
- package/dist/oauth/index.js +13 -1
- package/dist/oauth/issuerURL.d.ts +22 -0
- package/dist/oauth/issuerURL.js +38 -0
- package/dist/oauth/openBrowser.d.ts +19 -0
- package/dist/oauth/openBrowser.js +78 -0
- package/dist/oauth/pkce.d.ts +17 -0
- package/dist/oauth/pkce.js +43 -0
- package/dist/oauth/predicates.d.ts +7 -0
- package/dist/oauth/predicates.js +15 -0
- package/dist/oauth/refreshTokens.d.ts +30 -0
- package/dist/oauth/refreshTokens.js +61 -0
- package/dist/oauth/testUtils.d.ts +35 -0
- package/dist/oauth/testUtils.js +61 -0
- package/dist/oauth/tokenExchange.d.ts +26 -0
- package/dist/oauth/tokenExchange.js +42 -0
- package/dist/oauth/tokenResponse.d.ts +54 -0
- package/dist/oauth/tokenResponse.js +121 -0
- package/dist/oauth/tokenStore.d.ts +78 -0
- package/dist/oauth/tokenStore.js +176 -0
- package/package.json +10 -2
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Shared helpers for the oauth test files. Not a `.test.ts` itself so
|
|
3
|
+
// the test runner doesn't pick it up directly, and excluded from c8
|
|
4
|
+
// coverage in `.c8rc.json` since nothing in here is production code.
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.KEYCLOAK_ISSUER = exports.FIXED_NOW = void 0;
|
|
7
|
+
exports.withFetch = withFetch;
|
|
8
|
+
exports.jsonResponse = jsonResponse;
|
|
9
|
+
exports.tokenResponseBody = tokenResponseBody;
|
|
10
|
+
/**
|
|
11
|
+
* A fixed "now" timestamp used by token-endpoint tests that need
|
|
12
|
+
* determinism for `expiresAt` assertions. Any constant would do;
|
|
13
|
+
* choosing one value keeps the arithmetic trivial to eyeball
|
|
14
|
+
* (2023-11-14T22:13:20.000Z).
|
|
15
|
+
*/
|
|
16
|
+
exports.FIXED_NOW = 1_700_000_000_000;
|
|
17
|
+
/**
|
|
18
|
+
* Swaps `globalThis.fetch` for `mock` while `fn` runs, then restores.
|
|
19
|
+
* Use in tests that mock *every* fetch the subject under test makes.
|
|
20
|
+
* (Tests that want pass-through-on-miss behavior should keep their
|
|
21
|
+
* own router — see `authorize.test.ts`.)
|
|
22
|
+
*/
|
|
23
|
+
function withFetch(mock, fn) {
|
|
24
|
+
const original = globalThis.fetch;
|
|
25
|
+
globalThis.fetch = mock;
|
|
26
|
+
return fn().finally(() => {
|
|
27
|
+
globalThis.fetch = original;
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* JSON-serialized `Response` with `Content-Type: application/json`
|
|
32
|
+
* already set. Any headers in `init.headers` merge on top.
|
|
33
|
+
*/
|
|
34
|
+
function jsonResponse(body, init = { status: 200 }) {
|
|
35
|
+
return new Response(JSON.stringify(body), {
|
|
36
|
+
...init,
|
|
37
|
+
headers: { "Content-Type": "application/json", ...(init.headers ?? {}) },
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Canonical local Keycloak issuer URL used across tests — matches
|
|
42
|
+
* walnut's dev setup (`http://localhost:8080/auth/realms/local`).
|
|
43
|
+
* Use this anywhere a test needs "the Keycloak issuer" rather than
|
|
44
|
+
* a test-specific URL (e.g. `http://auth.test.invalid`).
|
|
45
|
+
*/
|
|
46
|
+
exports.KEYCLOAK_ISSUER = "http://localhost:8080/auth/realms/local";
|
|
47
|
+
/**
|
|
48
|
+
* Standard OAuth 2.0 token-endpoint success body. Returns a fresh
|
|
49
|
+
* plain object on each call so tests can safely mutate it after.
|
|
50
|
+
* Override any field via `overrides`; the happy-path defaults
|
|
51
|
+
* (Bearer, positive `expires_in`) are what most tests want.
|
|
52
|
+
*/
|
|
53
|
+
function tokenResponseBody(overrides = {}) {
|
|
54
|
+
return {
|
|
55
|
+
access_token: "at",
|
|
56
|
+
refresh_token: "rt",
|
|
57
|
+
expires_in: 300,
|
|
58
|
+
token_type: "Bearer",
|
|
59
|
+
...overrides,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { type TokenSet } from "./tokenResponse";
|
|
2
|
+
/** Options for `exchangeCodeForTokens`. */
|
|
3
|
+
export interface ExchangeCodeForTokensOptions {
|
|
4
|
+
/** Token endpoint resolved from OIDC discovery. */
|
|
5
|
+
tokenEndpoint: string;
|
|
6
|
+
/** OAuth client identifier. */
|
|
7
|
+
clientId: string;
|
|
8
|
+
/** Authorization code received via the loopback callback. */
|
|
9
|
+
code: string;
|
|
10
|
+
/** PKCE verifier paired with the `code_challenge` sent at auth time. */
|
|
11
|
+
codeVerifier: string;
|
|
12
|
+
/** Redirect URI originally sent to the authorization endpoint. */
|
|
13
|
+
redirectUri: string;
|
|
14
|
+
/** Source of `now`. Injected for test determinism; defaults to `Date.now`. */
|
|
15
|
+
now?: () => number;
|
|
16
|
+
/** Aborts the underlying fetch when fired. */
|
|
17
|
+
signal?: AbortSignal;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Exchanges an authorization code for a `TokenSet` via the
|
|
21
|
+
* authorization server's token endpoint (RFC 6749 §4.1.3 + RFC 7636
|
|
22
|
+
* §4.5). Rejects with `OAuthFlowError("TOKEN_EXCHANGE_FAILED", ...)`
|
|
23
|
+
* for any failure mode, surfacing the OAuth `error` /
|
|
24
|
+
* `error_description` when available.
|
|
25
|
+
*/
|
|
26
|
+
export declare function exchangeCodeForTokens(options: ExchangeCodeForTokensOptions): Promise<TokenSet>;
|
|
@@ -0,0 +1,42 @@
|
|
|
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
|
+
/**
|
|
7
|
+
* Exchanges an authorization code for a `TokenSet` via the
|
|
8
|
+
* authorization server's token endpoint (RFC 6749 §4.1.3 + RFC 7636
|
|
9
|
+
* §4.5). Rejects with `OAuthFlowError("TOKEN_EXCHANGE_FAILED", ...)`
|
|
10
|
+
* for any failure mode, surfacing the OAuth `error` /
|
|
11
|
+
* `error_description` when available.
|
|
12
|
+
*/
|
|
13
|
+
async function exchangeCodeForTokens(options) {
|
|
14
|
+
const now = options.now ?? Date.now;
|
|
15
|
+
const body = new URLSearchParams({
|
|
16
|
+
grant_type: "authorization_code",
|
|
17
|
+
client_id: options.clientId,
|
|
18
|
+
code: options.code,
|
|
19
|
+
code_verifier: options.codeVerifier,
|
|
20
|
+
redirect_uri: options.redirectUri,
|
|
21
|
+
});
|
|
22
|
+
const issuedAt = now();
|
|
23
|
+
let response;
|
|
24
|
+
try {
|
|
25
|
+
response = await fetch(options.tokenEndpoint, {
|
|
26
|
+
method: "POST",
|
|
27
|
+
headers: {
|
|
28
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
29
|
+
Accept: "application/json",
|
|
30
|
+
},
|
|
31
|
+
body,
|
|
32
|
+
signal: options.signal,
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
catch (cause) {
|
|
36
|
+
throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Could not reach the token endpoint at ${options.tokenEndpoint}. Check your network connection.`, { cause });
|
|
37
|
+
}
|
|
38
|
+
if (!response.ok) {
|
|
39
|
+
await (0, tokenResponse_1.throwTokenEndpointError)(response, "Token exchange");
|
|
40
|
+
}
|
|
41
|
+
return (0, tokenResponse_1.parseTokenResponse)(response, issuedAt, options.tokenEndpoint);
|
|
42
|
+
}
|
|
@@ -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,78 @@
|
|
|
1
|
+
import type { TokenSet } from "./tokenResponse";
|
|
2
|
+
/**
|
|
3
|
+
* Current on-disk blob schema version. Exported so consumers can
|
|
4
|
+
* display "stored v:N, expected v:M" diagnostics when `load()` returns
|
|
5
|
+
* a `version-mismatch` result.
|
|
6
|
+
*/
|
|
7
|
+
export declare const STORED_BLOB_VERSION = 1;
|
|
8
|
+
/**
|
|
9
|
+
* Outcome of a `TokenStore.load()` call.
|
|
10
|
+
*
|
|
11
|
+
* Note on downgrades: the migrator chain only walks *forward*. A user
|
|
12
|
+
* who downgrades `axe-auth` to a release that predates a schema bump
|
|
13
|
+
* will see `version-mismatch` on any blob written by the newer
|
|
14
|
+
* release, even if the change was strictly additive. That is the safe
|
|
15
|
+
* default for a credentials blob — the older version cannot vouch for
|
|
16
|
+
* the meaning of fields it has never seen. Callers hitting this case
|
|
17
|
+
* should treat it as "re-authenticate" rather than attempting to
|
|
18
|
+
* parse an unknown future shape.
|
|
19
|
+
*/
|
|
20
|
+
export type LoadResult = {
|
|
21
|
+
ok: true;
|
|
22
|
+
tokens: TokenSet;
|
|
23
|
+
} | {
|
|
24
|
+
ok: false;
|
|
25
|
+
reason: "empty";
|
|
26
|
+
} | {
|
|
27
|
+
ok: false;
|
|
28
|
+
reason: "corrupt";
|
|
29
|
+
} | {
|
|
30
|
+
ok: false;
|
|
31
|
+
reason: "version-mismatch";
|
|
32
|
+
storedVersion: number;
|
|
33
|
+
};
|
|
34
|
+
/** Persistence layer for an OAuth `TokenSet`. */
|
|
35
|
+
export interface TokenStore {
|
|
36
|
+
/** Write-through save. Replaces any previously stored tokens. */
|
|
37
|
+
save(tokens: TokenSet): Promise<void>;
|
|
38
|
+
/**
|
|
39
|
+
* Reads the stored tokens and returns a structured result.
|
|
40
|
+
*
|
|
41
|
+
* Callers should branch on `result.ok` first. When `ok` is `false`,
|
|
42
|
+
* `reason` tells them *why* there is no usable `TokenSet`: `empty`
|
|
43
|
+
* (nothing stored), `corrupt` (unparseable or shape-invalid), or
|
|
44
|
+
* `version-mismatch` (stored under a schema we cannot migrate from).
|
|
45
|
+
* The library does not emit output on these cases — surfacing them
|
|
46
|
+
* to the user is the caller's responsibility.
|
|
47
|
+
*/
|
|
48
|
+
load(): Promise<LoadResult>;
|
|
49
|
+
/** Removes any stored tokens. No-op if none are present. */
|
|
50
|
+
clear(): Promise<void>;
|
|
51
|
+
}
|
|
52
|
+
/** Minimal keyring-entry surface consumed by `KeyringTokenStore`. */
|
|
53
|
+
export interface KeyringEntry {
|
|
54
|
+
/** Writes the password for this entry. */
|
|
55
|
+
setPassword(password: string): void;
|
|
56
|
+
/** Reads the current password, or returns `null` if none is set. */
|
|
57
|
+
getPassword(): string | null;
|
|
58
|
+
/** Deletes the password and returns `true` if one existed. */
|
|
59
|
+
deletePassword(): boolean;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Factory for `KeyringEntry` values. Injection seam for tests;
|
|
63
|
+
* production callers use the default that constructs
|
|
64
|
+
* `@napi-rs/keyring` entries lazily.
|
|
65
|
+
*/
|
|
66
|
+
export type KeyringEntryFactory = (service: string, account: string) => KeyringEntry;
|
|
67
|
+
/**
|
|
68
|
+
* `TokenStore` backed by the operating system's native keychain via
|
|
69
|
+
* `@napi-rs/keyring` (macOS Keychain, Windows Credential Manager, Linux
|
|
70
|
+
* Secret Service). Account is keyed by the normalized issuer URL.
|
|
71
|
+
*/
|
|
72
|
+
export declare class KeyringTokenStore implements TokenStore {
|
|
73
|
+
#private;
|
|
74
|
+
constructor(issuerURL: string, entryFactory?: KeyringEntryFactory);
|
|
75
|
+
save(tokens: TokenSet): Promise<void>;
|
|
76
|
+
load(): Promise<LoadResult>;
|
|
77
|
+
clear(): Promise<void>;
|
|
78
|
+
}
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.KeyringTokenStore = exports.STORED_BLOB_VERSION = void 0;
|
|
4
|
+
const node_module_1 = require("node:module");
|
|
5
|
+
const errors_1 = require("./errors");
|
|
6
|
+
const issuerURL_1 = require("./issuerURL");
|
|
7
|
+
const requireFromHere = (0, node_module_1.createRequire)(__filename);
|
|
8
|
+
// On macOS: Keychain generic password item with the service name below.
|
|
9
|
+
// On Windows: Credential Manager entry. On Linux: Secret Service / libsecret.
|
|
10
|
+
// Exposed as a human-readable string because these all surface the service
|
|
11
|
+
// name in OS UIs (Keychain Access, credmgr.exe, seahorse).
|
|
12
|
+
const SERVICE_NAME = "axe-auth";
|
|
13
|
+
/**
|
|
14
|
+
* Current on-disk blob schema version. Exported so consumers can
|
|
15
|
+
* display "stored v:N, expected v:M" diagnostics when `load()` returns
|
|
16
|
+
* a `version-mismatch` result.
|
|
17
|
+
*/
|
|
18
|
+
exports.STORED_BLOB_VERSION = 1;
|
|
19
|
+
/**
|
|
20
|
+
* Migrators upgrade an older blob to the next version up. Walked by
|
|
21
|
+
* `load()` until the stored blob reaches `STORED_BLOB_VERSION`.
|
|
22
|
+
*
|
|
23
|
+
* A migrator returns `null` when the bump cannot be inferred from the
|
|
24
|
+
* old shape (e.g. a new required field with no derivable default); the
|
|
25
|
+
* caller then sees `{ ok: false, reason: "version-mismatch" }` and
|
|
26
|
+
* decides whether to re-auth, prompt, or preserve the old blob.
|
|
27
|
+
*
|
|
28
|
+
* Each migrator is responsible for taking `vN` → `vN+1`. To skip a
|
|
29
|
+
* version deliberately, register a migrator that returns `null` for
|
|
30
|
+
* that `fromVersion`.
|
|
31
|
+
*/
|
|
32
|
+
const MIGRATORS = new Map([
|
|
33
|
+
// [1, (v1) => migrateV1ToV2(v1 as StoredBlobV1)],
|
|
34
|
+
]);
|
|
35
|
+
// Lazy-resolved Entry constructor. Importing @napi-rs/keyring at the
|
|
36
|
+
// top of this module would run its native binding loader at
|
|
37
|
+
// module-load time, throwing before any of our OAuthFlowError code
|
|
38
|
+
// catches it and preventing the module from being imported at all on
|
|
39
|
+
// platforms without a prebuilt. We defer the require into
|
|
40
|
+
// `defaultEntryFactory`, which turns that import-time failure into a
|
|
41
|
+
// `KEYRING_UNAVAILABLE` surfaced on the first `new
|
|
42
|
+
// KeyringTokenStore(...)` call — not on first save/load/clear, since
|
|
43
|
+
// `authorize()` (and similar callers) construct the store eagerly as
|
|
44
|
+
// a default-arg expression. Runtime keychain errors (missing D-Bus
|
|
45
|
+
// Secret Service, macOS Keychain denial, etc.) are a separate
|
|
46
|
+
// concern and surface later, inside save/load/clear.
|
|
47
|
+
let cachedEntryCtor = null;
|
|
48
|
+
function resolveEntryCtor() {
|
|
49
|
+
if (cachedEntryCtor)
|
|
50
|
+
return cachedEntryCtor;
|
|
51
|
+
try {
|
|
52
|
+
const mod = requireFromHere("@napi-rs/keyring");
|
|
53
|
+
cachedEntryCtor = mod.Entry;
|
|
54
|
+
return cachedEntryCtor;
|
|
55
|
+
}
|
|
56
|
+
catch (cause) {
|
|
57
|
+
throw new errors_1.OAuthFlowError("KEYRING_UNAVAILABLE", `Could not load @napi-rs/keyring. A prebuilt native binding for this platform may be missing.`, { cause });
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
const defaultEntryFactory = (service, account) => {
|
|
61
|
+
const Ctor = resolveEntryCtor();
|
|
62
|
+
return new Ctor(service, account);
|
|
63
|
+
};
|
|
64
|
+
function getStoredVersion(blob) {
|
|
65
|
+
if (blob === null || typeof blob !== "object")
|
|
66
|
+
return null;
|
|
67
|
+
const v = blob.v;
|
|
68
|
+
return typeof v === "number" && Number.isInteger(v) && v > 0 ? v : null;
|
|
69
|
+
}
|
|
70
|
+
function isLatestBlob(blob) {
|
|
71
|
+
if (blob === null || typeof blob !== "object")
|
|
72
|
+
return false;
|
|
73
|
+
const b = blob;
|
|
74
|
+
return (b.v === exports.STORED_BLOB_VERSION &&
|
|
75
|
+
typeof b.accessToken === "string" &&
|
|
76
|
+
typeof b.expiresAt === "number" &&
|
|
77
|
+
(b.refreshToken === undefined || typeof b.refreshToken === "string"));
|
|
78
|
+
}
|
|
79
|
+
function blobToTokens(blob) {
|
|
80
|
+
const tokens = {
|
|
81
|
+
accessToken: blob.accessToken,
|
|
82
|
+
expiresAt: blob.expiresAt,
|
|
83
|
+
};
|
|
84
|
+
if (blob.refreshToken !== undefined)
|
|
85
|
+
tokens.refreshToken = blob.refreshToken;
|
|
86
|
+
return tokens;
|
|
87
|
+
}
|
|
88
|
+
function tokensToBlob(tokens) {
|
|
89
|
+
const blob = {
|
|
90
|
+
v: exports.STORED_BLOB_VERSION,
|
|
91
|
+
accessToken: tokens.accessToken,
|
|
92
|
+
expiresAt: tokens.expiresAt,
|
|
93
|
+
};
|
|
94
|
+
if (tokens.refreshToken !== undefined)
|
|
95
|
+
blob.refreshToken = tokens.refreshToken;
|
|
96
|
+
return blob;
|
|
97
|
+
}
|
|
98
|
+
function wrapKeyringError(op, cause) {
|
|
99
|
+
throw new errors_1.OAuthFlowError("KEYRING_UNAVAILABLE", `System keychain ${op} failed. On Linux this usually means no D-Bus Secret Service is running.`, { cause });
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* `TokenStore` backed by the operating system's native keychain via
|
|
103
|
+
* `@napi-rs/keyring` (macOS Keychain, Windows Credential Manager, Linux
|
|
104
|
+
* Secret Service). Account is keyed by the normalized issuer URL.
|
|
105
|
+
*/
|
|
106
|
+
class KeyringTokenStore {
|
|
107
|
+
#entry;
|
|
108
|
+
constructor(issuerURL, entryFactory = defaultEntryFactory) {
|
|
109
|
+
this.#entry = entryFactory(SERVICE_NAME, (0, issuerURL_1.normalizeIssuerURL)(issuerURL));
|
|
110
|
+
}
|
|
111
|
+
async save(tokens) {
|
|
112
|
+
try {
|
|
113
|
+
this.#entry.setPassword(JSON.stringify(tokensToBlob(tokens)));
|
|
114
|
+
}
|
|
115
|
+
catch (cause) {
|
|
116
|
+
wrapKeyringError("write", cause);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
async load() {
|
|
120
|
+
let raw;
|
|
121
|
+
try {
|
|
122
|
+
raw = this.#entry.getPassword();
|
|
123
|
+
}
|
|
124
|
+
catch (cause) {
|
|
125
|
+
wrapKeyringError("read", cause);
|
|
126
|
+
}
|
|
127
|
+
if (raw === null)
|
|
128
|
+
return { ok: false, reason: "empty" };
|
|
129
|
+
let parsed;
|
|
130
|
+
try {
|
|
131
|
+
parsed = JSON.parse(raw);
|
|
132
|
+
}
|
|
133
|
+
catch {
|
|
134
|
+
return { ok: false, reason: "corrupt" };
|
|
135
|
+
}
|
|
136
|
+
const storedVersion = getStoredVersion(parsed);
|
|
137
|
+
if (storedVersion === null)
|
|
138
|
+
return { ok: false, reason: "corrupt" };
|
|
139
|
+
// Walk the migrator chain until we reach the current version. A
|
|
140
|
+
// missing or null-returning migrator means the old blob cannot be
|
|
141
|
+
// upgraded; surface that so callers can prompt re-auth with a
|
|
142
|
+
// clear signal instead of silently returning `empty`.
|
|
143
|
+
let current = parsed;
|
|
144
|
+
let currentVersion = storedVersion;
|
|
145
|
+
while (currentVersion !== exports.STORED_BLOB_VERSION) {
|
|
146
|
+
const migrator = MIGRATORS.get(currentVersion);
|
|
147
|
+
if (!migrator) {
|
|
148
|
+
return { ok: false, reason: "version-mismatch", storedVersion };
|
|
149
|
+
}
|
|
150
|
+
const next = migrator(current);
|
|
151
|
+
if (next === null) {
|
|
152
|
+
return { ok: false, reason: "version-mismatch", storedVersion };
|
|
153
|
+
}
|
|
154
|
+
const nextVersion = getStoredVersion(next);
|
|
155
|
+
if (nextVersion === null || nextVersion <= currentVersion) {
|
|
156
|
+
// Migrator output is malformed or didn't advance. Treat the
|
|
157
|
+
// stored blob as un-migratable rather than loop forever.
|
|
158
|
+
return { ok: false, reason: "version-mismatch", storedVersion };
|
|
159
|
+
}
|
|
160
|
+
current = next;
|
|
161
|
+
currentVersion = nextVersion;
|
|
162
|
+
}
|
|
163
|
+
if (!isLatestBlob(current))
|
|
164
|
+
return { ok: false, reason: "corrupt" };
|
|
165
|
+
return { ok: true, tokens: blobToTokens(current) };
|
|
166
|
+
}
|
|
167
|
+
async clear() {
|
|
168
|
+
try {
|
|
169
|
+
this.#entry.deletePassword();
|
|
170
|
+
}
|
|
171
|
+
catch (cause) {
|
|
172
|
+
wrapKeyringError("delete", cause);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
exports.KeyringTokenStore = KeyringTokenStore;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@deque/axe-auth",
|
|
3
|
-
"version": "1.1.0-next.
|
|
3
|
+
"version": "1.1.0-next.5c407e02",
|
|
4
4
|
"description": "CLI authentication utility for Deque services",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE",
|
|
6
6
|
"type": "commonjs",
|
|
@@ -20,13 +20,21 @@
|
|
|
20
20
|
"engines": {
|
|
21
21
|
"node": ">=22.13.0"
|
|
22
22
|
},
|
|
23
|
+
"dependencies": {
|
|
24
|
+
"@napi-rs/keyring": "^1.2.0"
|
|
25
|
+
},
|
|
23
26
|
"devDependencies": {
|
|
24
27
|
"@types/node": "^22.13.10",
|
|
28
|
+
"c8": "^10.1.3",
|
|
25
29
|
"tsx": "^4.20.6",
|
|
26
30
|
"typescript": "^5.9.3"
|
|
27
31
|
},
|
|
28
32
|
"scripts": {
|
|
29
33
|
"build": "tsc",
|
|
30
|
-
"test": "tsx --test 'src/**/*.test.ts'"
|
|
34
|
+
"test": "tsx --test 'src/**/*.test.ts'",
|
|
35
|
+
"coverage": "c8 pnpm test",
|
|
36
|
+
"register-dev-client": "tsx scripts/registerDevClient.ts",
|
|
37
|
+
"smoke-authorize": "tsx scripts/smokeAuthorize.ts",
|
|
38
|
+
"manual-authorize": "tsx scripts/manualAuthorize.ts"
|
|
31
39
|
}
|
|
32
40
|
}
|