@deque/axe-auth 1.1.0-next.97bcb8e6 → 1.1.0-next.f7b98204
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 +19 -3
- package/dist/index.js +32 -25
- 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/callbackServer.d.ts +23 -0
- package/dist/oauth/callbackServer.js +234 -0
- package/dist/oauth/discoverOIDC.d.ts +50 -0
- package/dist/oauth/discoverOIDC.js +145 -0
- package/dist/oauth/errors.d.ts +73 -0
- package/dist/oauth/errors.js +48 -0
- package/dist/oauth/index.d.ts +11 -0
- package/dist/oauth/index.js +15 -0
- package/dist/oauth/issuerURL.d.ts +22 -0
- package/dist/oauth/issuerURL.js +38 -0
- package/dist/oauth/logo.generated.d.ts +1 -0
- package/dist/oauth/logo.generated.js +7 -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/renderHtml.d.ts +9 -0
- package/dist/oauth/renderHtml.js +60 -0
- package/dist/oauth/tokenExchange.d.ts +49 -0
- package/dist/oauth/tokenExchange.js +136 -0
- package/dist/oauth/tokenStore.d.ts +78 -0
- package/dist/oauth/tokenStore.js +176 -0
- package/package.json +10 -2
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.renderHtml = exports.CSP_HEADER = void 0;
|
|
4
|
+
const node_crypto_1 = require("node:crypto");
|
|
5
|
+
const logo_generated_1 = require("./logo.generated");
|
|
6
|
+
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}
|
|
7
|
+
html{box-sizing:border-box}
|
|
8
|
+
*,*::before,*::after{box-sizing:inherit}
|
|
9
|
+
*:focus{outline:2px solid var(--pink);outline-offset:2px}
|
|
10
|
+
body{margin:0;padding:0;width:100%;height:100%;font-family:Roboto,Helvetica,Arial,sans-serif;font-style:normal;font-weight:400;color:var(--off-black);background-color:var(--off-white);font-size:15px}
|
|
11
|
+
h1{padding:0;margin:0;font-size:34px;font-weight:700}
|
|
12
|
+
main{margin:var(--space-huge) auto;padding-left:var(--space-medium);padding-right:var(--space-medium);max-width:400px;text-align:center}
|
|
13
|
+
.hero{margin-bottom:var(--space-medium)}
|
|
14
|
+
.hero img{width:180px;max-width:100%;margin-bottom:var(--space-medium)}
|
|
15
|
+
.reason{margin-top:var(--space-medium);font-weight:500}
|
|
16
|
+
.description{margin-top:var(--space-small);font-size:13px}
|
|
17
|
+
.close{margin-top:var(--space-large)}`;
|
|
18
|
+
// CSP uses a SHA-256 hash of the <style> block contents instead of
|
|
19
|
+
// 'unsafe-inline'. Any drift between this digest and the rendered <style> tag
|
|
20
|
+
// causes the browser to refuse the stylesheet — see docs/callback-page.md.
|
|
21
|
+
const STYLE_HASH = (0, node_crypto_1.createHash)("sha256").update(CSS, "utf8").digest("base64");
|
|
22
|
+
exports.CSP_HEADER = `default-src 'none'; img-src data:; style-src 'sha256-${STYLE_HASH}'; frame-ancestors 'none'`;
|
|
23
|
+
// OWASP-recommended 5-character set for HTML body/attribute contexts;
|
|
24
|
+
// & must come first to avoid double-escaping. Not safe for JS/CSS/URL contexts.
|
|
25
|
+
// 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, "&")
|
|
28
|
+
.replace(/</g, "<")
|
|
29
|
+
.replace(/>/g, ">")
|
|
30
|
+
.replace(/"/g, """)
|
|
31
|
+
.replace(/'/g, "'");
|
|
32
|
+
const page = (title, body) => `<!doctype html>
|
|
33
|
+
<html lang="en">
|
|
34
|
+
<head>
|
|
35
|
+
<meta charset="UTF-8">
|
|
36
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
37
|
+
<title>${escape(title)}</title>
|
|
38
|
+
<style>${CSS}</style>
|
|
39
|
+
</head>
|
|
40
|
+
<body>
|
|
41
|
+
<main>
|
|
42
|
+
<div class="hero"><img src="data:image/png;base64,${logo_generated_1.LOGO_PNG_BASE64}" alt="Deque"></div>
|
|
43
|
+
${body}
|
|
44
|
+
</main>
|
|
45
|
+
</body>
|
|
46
|
+
</html>`;
|
|
47
|
+
const renderHtml = (input) => {
|
|
48
|
+
if (input.kind === "success") {
|
|
49
|
+
return page("Authenticated", `<h1>Authenticated</h1>
|
|
50
|
+
<p class="close">You can close this tab and return to your terminal.</p>`);
|
|
51
|
+
}
|
|
52
|
+
const descriptionBlock = input.description
|
|
53
|
+
? `<p class="description">${escape(input.description)}</p>`
|
|
54
|
+
: "";
|
|
55
|
+
return page("Authentication failed", `<h1>Authentication failed</h1>
|
|
56
|
+
<p class="reason">${escape(input.reason)}</p>
|
|
57
|
+
${descriptionBlock}
|
|
58
|
+
<p class="close">You can close this tab and return to your terminal.</p>`);
|
|
59
|
+
};
|
|
60
|
+
exports.renderHtml = renderHtml;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tokens returned by a successful authorization-code exchange.
|
|
3
|
+
*
|
|
4
|
+
* `refreshToken` is optional because not all flows return one —
|
|
5
|
+
* callers that did not request `offline_access` (or the provider
|
|
6
|
+
* equivalent) will receive only an access token. Refresh logic (issue
|
|
7
|
+
* #422) must handle this case.
|
|
8
|
+
*
|
|
9
|
+
* `grantedScope` reflects the authorization server's `scope` response
|
|
10
|
+
* field when present (RFC 6749 §5.1 says `scope` is required when the
|
|
11
|
+
* granted set differs from the requested set; optional otherwise).
|
|
12
|
+
* Callers comparing granted vs requested to surface diagnostics should
|
|
13
|
+
* read this field.
|
|
14
|
+
*/
|
|
15
|
+
export interface TokenSet {
|
|
16
|
+
/** Access token for authenticated API calls. */
|
|
17
|
+
accessToken: string;
|
|
18
|
+
/** Long-lived token used to mint new access tokens without re-auth. Absent if the flow did not request it. */
|
|
19
|
+
refreshToken?: string;
|
|
20
|
+
/** Absolute timestamp (ms since epoch) when the access token expires. */
|
|
21
|
+
expiresAt: number;
|
|
22
|
+
/** Space-delimited scopes the server actually granted, if reported. */
|
|
23
|
+
grantedScope?: string;
|
|
24
|
+
}
|
|
25
|
+
/** Options for `exchangeCodeForTokens`. */
|
|
26
|
+
export interface ExchangeCodeForTokensOptions {
|
|
27
|
+
/** Token endpoint resolved from OIDC discovery. */
|
|
28
|
+
tokenEndpoint: string;
|
|
29
|
+
/** OAuth client identifier. */
|
|
30
|
+
clientId: string;
|
|
31
|
+
/** Authorization code received via the loopback callback. */
|
|
32
|
+
code: string;
|
|
33
|
+
/** PKCE verifier paired with the `code_challenge` sent at auth time. */
|
|
34
|
+
codeVerifier: string;
|
|
35
|
+
/** Redirect URI originally sent to the authorization endpoint. */
|
|
36
|
+
redirectUri: string;
|
|
37
|
+
/** Source of `now`. Injected for test determinism; defaults to `Date.now`. */
|
|
38
|
+
now?: () => number;
|
|
39
|
+
/** Aborts the underlying fetch when fired. */
|
|
40
|
+
signal?: AbortSignal;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Exchanges an authorization code for a `TokenSet` via the
|
|
44
|
+
* authorization server's token endpoint (RFC 6749 §4.1.3 + RFC 7636
|
|
45
|
+
* §4.5). Rejects with `OAuthFlowError("TOKEN_EXCHANGE_FAILED", ...)`
|
|
46
|
+
* for any failure mode, surfacing the OAuth `error` /
|
|
47
|
+
* `error_description` when available.
|
|
48
|
+
*/
|
|
49
|
+
export declare function exchangeCodeForTokens(options: ExchangeCodeForTokensOptions): Promise<TokenSet>;
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.exchangeCodeForTokens = exchangeCodeForTokens;
|
|
4
|
+
const errors_1 = require("./errors");
|
|
5
|
+
function isNonEmptyString(v) {
|
|
6
|
+
return typeof v === "string" && v.length > 0;
|
|
7
|
+
}
|
|
8
|
+
// RFC 6749 §5.1 describes `expires_in` as "the lifetime in seconds"
|
|
9
|
+
// without pinning the JSON type, and some providers historically send
|
|
10
|
+
// numeric strings. Accept both; reject anything non-positive or
|
|
11
|
+
// non-finite.
|
|
12
|
+
function parseExpiresIn(v) {
|
|
13
|
+
if (typeof v === "number" && Number.isFinite(v) && v > 0)
|
|
14
|
+
return v;
|
|
15
|
+
if (typeof v === "string") {
|
|
16
|
+
const n = Number(v);
|
|
17
|
+
if (Number.isFinite(n) && n > 0)
|
|
18
|
+
return n;
|
|
19
|
+
}
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
function parseErrorBody(body) {
|
|
23
|
+
let parsed;
|
|
24
|
+
try {
|
|
25
|
+
parsed = JSON.parse(body);
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return {};
|
|
29
|
+
}
|
|
30
|
+
if (parsed === null || typeof parsed !== "object")
|
|
31
|
+
return {};
|
|
32
|
+
const raw = parsed;
|
|
33
|
+
return {
|
|
34
|
+
error: isNonEmptyString(raw.error) ? raw.error : undefined,
|
|
35
|
+
description: isNonEmptyString(raw.error_description)
|
|
36
|
+
? raw.error_description
|
|
37
|
+
: undefined,
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
function throwFromErrorResponse(status, body) {
|
|
41
|
+
const { error, description } = parseErrorBody(body);
|
|
42
|
+
const suffix = error
|
|
43
|
+
? description
|
|
44
|
+
? `: ${error}: ${description}`
|
|
45
|
+
: `: ${error}`
|
|
46
|
+
: "";
|
|
47
|
+
const details = {};
|
|
48
|
+
if (error)
|
|
49
|
+
details.error = error;
|
|
50
|
+
if (description)
|
|
51
|
+
details.error_description = description;
|
|
52
|
+
throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token exchange failed with HTTP ${status}${suffix}`, Object.keys(details).length > 0 ? { details } : undefined);
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Exchanges an authorization code for a `TokenSet` via the
|
|
56
|
+
* authorization server's token endpoint (RFC 6749 §4.1.3 + RFC 7636
|
|
57
|
+
* §4.5). Rejects with `OAuthFlowError("TOKEN_EXCHANGE_FAILED", ...)`
|
|
58
|
+
* for any failure mode, surfacing the OAuth `error` /
|
|
59
|
+
* `error_description` when available.
|
|
60
|
+
*/
|
|
61
|
+
async function exchangeCodeForTokens(options) {
|
|
62
|
+
const now = options.now ?? Date.now;
|
|
63
|
+
const body = new URLSearchParams({
|
|
64
|
+
grant_type: "authorization_code",
|
|
65
|
+
client_id: options.clientId,
|
|
66
|
+
code: options.code,
|
|
67
|
+
code_verifier: options.codeVerifier,
|
|
68
|
+
redirect_uri: options.redirectUri,
|
|
69
|
+
});
|
|
70
|
+
// Capture `issuedAt` before the network call so we don't drift past
|
|
71
|
+
// expiry just because the network was slow. Slightly conservative —
|
|
72
|
+
// the token actually expires `expires_in` seconds from when the
|
|
73
|
+
// server issued it, so the effective usable window is `expires_in -
|
|
74
|
+
// RTT`, which errs toward "expires sooner" rather than "expires
|
|
75
|
+
// later." That's the safer direction for any consumer doing
|
|
76
|
+
// pre-expiry checks.
|
|
77
|
+
const issuedAt = now();
|
|
78
|
+
let response;
|
|
79
|
+
try {
|
|
80
|
+
response = await fetch(options.tokenEndpoint, {
|
|
81
|
+
method: "POST",
|
|
82
|
+
headers: {
|
|
83
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
84
|
+
Accept: "application/json",
|
|
85
|
+
},
|
|
86
|
+
body,
|
|
87
|
+
signal: options.signal,
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
catch (cause) {
|
|
91
|
+
throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Could not reach the token endpoint at ${options.tokenEndpoint}. Check your network connection.`, { cause });
|
|
92
|
+
}
|
|
93
|
+
if (!response.ok) {
|
|
94
|
+
const text = await response.text().catch(() => "");
|
|
95
|
+
throwFromErrorResponse(response.status, text);
|
|
96
|
+
}
|
|
97
|
+
let parsed;
|
|
98
|
+
try {
|
|
99
|
+
parsed = await response.json();
|
|
100
|
+
}
|
|
101
|
+
catch (cause) {
|
|
102
|
+
throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token endpoint at ${options.tokenEndpoint} returned a non-JSON response`, { cause });
|
|
103
|
+
}
|
|
104
|
+
if (parsed === null || typeof parsed !== "object") {
|
|
105
|
+
throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token endpoint at ${options.tokenEndpoint} returned a non-object response`);
|
|
106
|
+
}
|
|
107
|
+
const raw = parsed;
|
|
108
|
+
if (!isNonEmptyString(raw.access_token)) {
|
|
109
|
+
throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token response missing 'access_token'`);
|
|
110
|
+
}
|
|
111
|
+
const expiresIn = parseExpiresIn(raw.expires_in);
|
|
112
|
+
if (expiresIn === null) {
|
|
113
|
+
throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token response missing or has invalid 'expires_in'`);
|
|
114
|
+
}
|
|
115
|
+
// RFC 6749 §5.1: token_type is REQUIRED. We only speak Bearer;
|
|
116
|
+
// DPoP / MAC / other proof-of-possession types need request-side
|
|
117
|
+
// support we don't implement, and silently treating them as Bearer
|
|
118
|
+
// would send tokens in the wrong header with unclear semantics.
|
|
119
|
+
if (!isNonEmptyString(raw.token_type)) {
|
|
120
|
+
throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token response missing required 'token_type'`);
|
|
121
|
+
}
|
|
122
|
+
if (raw.token_type.toLowerCase() !== "bearer") {
|
|
123
|
+
throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Unsupported token_type '${raw.token_type}'; this library only handles Bearer.`);
|
|
124
|
+
}
|
|
125
|
+
const tokens = {
|
|
126
|
+
accessToken: raw.access_token,
|
|
127
|
+
expiresAt: issuedAt + expiresIn * 1000,
|
|
128
|
+
};
|
|
129
|
+
if (isNonEmptyString(raw.refresh_token)) {
|
|
130
|
+
tokens.refreshToken = raw.refresh_token;
|
|
131
|
+
}
|
|
132
|
+
if (isNonEmptyString(raw.scope)) {
|
|
133
|
+
tokens.grantedScope = raw.scope;
|
|
134
|
+
}
|
|
135
|
+
return tokens;
|
|
136
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import type { TokenSet } from "./tokenExchange";
|
|
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.f7b98204",
|
|
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
|
}
|