@basaltkit/auth 3.1.0 → 4.0.0
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 +159 -24
- package/dist/apikeys-plugin.d.ts +11 -1
- package/dist/apikeys-plugin.js +22 -2
- package/dist/auth.d.ts +108 -20
- package/dist/auth.js +170 -41
- package/dist/hashing.d.ts +3 -1
- package/dist/hashing.js +29 -7
- package/dist/index.d.ts +6 -5
- package/dist/index.js +6 -5
- package/dist/jwt.js +13 -1
- package/dist/oauth-plugin.d.ts +12 -1
- package/dist/oauth-plugin.js +6 -5
- package/dist/oauth.d.ts +81 -2
- package/dist/oauth.js +221 -40
- package/dist/plugin.d.ts +6 -1
- package/dist/secret-box.d.ts +80 -8
- package/dist/secret-box.js +178 -27
- package/dist/stores.d.ts +60 -0
- package/dist/stores.js +52 -0
- package/dist/throttle.d.ts +12 -4
- package/dist/throttle.js +16 -4
- package/dist/webauthn-plugin.js +1 -1
- package/dist/webauthn.d.ts +49 -8
- package/dist/webauthn.js +70 -11
- package/package.json +4 -4
package/dist/oauth.d.ts
CHANGED
|
@@ -13,6 +13,17 @@ export declare class OAuthStateInvalidError extends BasaltError {
|
|
|
13
13
|
}
|
|
14
14
|
export declare class OAuthExchangeError extends BasaltError {
|
|
15
15
|
readonly status = 502;
|
|
16
|
+
/**
|
|
17
|
+
* The message quotes the provider's reply (`error_description`, an HTTP
|
|
18
|
+
* status, a discovery URL): diagnostic for the log, not for the client, who
|
|
19
|
+
* only gets the code and a neutral message.
|
|
20
|
+
*/
|
|
21
|
+
readonly expose = false;
|
|
22
|
+
constructor(detail: string);
|
|
23
|
+
}
|
|
24
|
+
/** Thrown when the OAuth provider configuration is unsafe (see {@link OAuthProvider.allowedEmailDomains}). */
|
|
25
|
+
export declare class OAuthProviderConfigError extends BasaltError {
|
|
26
|
+
readonly status = 500;
|
|
16
27
|
constructor(detail: string);
|
|
17
28
|
}
|
|
18
29
|
/** The normalized profile a provider returns after a successful login. */
|
|
@@ -32,6 +43,32 @@ export interface OAuthProvider {
|
|
|
32
43
|
scopes: string[];
|
|
33
44
|
/** Fetches and normalizes the user profile from an access token. */
|
|
34
45
|
fetchProfile(accessToken: string, doFetch: typeof fetch): Promise<OAuthProfile>;
|
|
46
|
+
/**
|
|
47
|
+
* Expected `iss` of the `id_token` (OpenID Connect). When set, an `id_token`
|
|
48
|
+
* issued by anyone else is refused.
|
|
49
|
+
*/
|
|
50
|
+
issuer?: string | string[];
|
|
51
|
+
/**
|
|
52
|
+
* Email domains this provider is trusted to assert (exact, case-insensitive
|
|
53
|
+
* match on the part after `@`; list subdomains explicitly). A login for any
|
|
54
|
+
* other domain is refused with `AUTH_OAUTH_EXCHANGE_FAILED` before any account
|
|
55
|
+
* is looked up.
|
|
56
|
+
*/
|
|
57
|
+
allowedEmailDomains?: string[];
|
|
58
|
+
/**
|
|
59
|
+
* Explicit opt-out of {@link allowedEmailDomains} for an {@link enterprise}
|
|
60
|
+
* provider when several providers are configured: this IdP may assert **any**
|
|
61
|
+
* email. Only for an IdP you fully control.
|
|
62
|
+
*/
|
|
63
|
+
allowAnyEmailDomain?: true;
|
|
64
|
+
/**
|
|
65
|
+
* The provider is an enterprise IdP administered by someone else — typically a
|
|
66
|
+
* customer's Okta / Entra / Keycloak ({@link oidcProvider} sets it). Its admin
|
|
67
|
+
* decides which emails it asserts as verified, so when more than one provider
|
|
68
|
+
* is configured it must declare {@link allowedEmailDomains} (or
|
|
69
|
+
* {@link allowAnyEmailDomain}) or the {@link OAuth} service refuses to start.
|
|
70
|
+
*/
|
|
71
|
+
enterprise?: boolean;
|
|
35
72
|
}
|
|
36
73
|
interface ProviderKeys {
|
|
37
74
|
clientId: string;
|
|
@@ -48,6 +85,12 @@ interface OidcConfig extends ProviderKeys {
|
|
|
48
85
|
authorizeUrl: string;
|
|
49
86
|
tokenUrl: string;
|
|
50
87
|
userInfoUrl: string;
|
|
88
|
+
/** The IdP issuer; when set, the `id_token`'s `iss` must match it. */
|
|
89
|
+
issuer?: string;
|
|
90
|
+
/** See {@link OAuthProvider.allowedEmailDomains}. */
|
|
91
|
+
allowedEmailDomains?: string[];
|
|
92
|
+
/** See {@link OAuthProvider.allowAnyEmailDomain}. */
|
|
93
|
+
allowAnyEmailDomain?: true;
|
|
51
94
|
}
|
|
52
95
|
/**
|
|
53
96
|
* A generic **OIDC** provider — enterprise SSO for any OpenID Connect IdP
|
|
@@ -55,11 +98,20 @@ interface OidcConfig extends ProviderKeys {
|
|
|
55
98
|
* three endpoints from the IdP's `.well-known/openid-configuration`, or use
|
|
56
99
|
* {@link discoverOidcProvider} to fetch them for you. Maps the standard OIDC
|
|
57
100
|
* `userinfo` claims (`sub`, `email`, `email_verified`, `name`).
|
|
101
|
+
*
|
|
102
|
+
* The IdP's admin decides which emails it asserts as verified: restrict each
|
|
103
|
+
* customer's IdP to that customer's domains with `allowedEmailDomains` —
|
|
104
|
+
* required as soon as more than one provider is configured (see
|
|
105
|
+
* {@link OAuthProvider.enterprise}).
|
|
58
106
|
*/
|
|
59
107
|
export declare function oidcProvider(config: OidcConfig): OAuthProvider;
|
|
60
108
|
/**
|
|
61
109
|
* Builds an {@link oidcProvider} by fetching the IdP's OIDC discovery document
|
|
62
110
|
* (`${issuer}/.well-known/openid-configuration`). Await it at startup.
|
|
111
|
+
*
|
|
112
|
+
* Per OpenID Connect Discovery §4.3 the document's `issuer` must equal the
|
|
113
|
+
* configured one (trailing slashes aside), and every endpoint must be `https:`
|
|
114
|
+
* (plain `http:` only to a loopback host), or discovery fails.
|
|
63
115
|
*/
|
|
64
116
|
export declare function discoverOidcProvider(config: {
|
|
65
117
|
name?: string;
|
|
@@ -68,7 +120,13 @@ export declare function discoverOidcProvider(config: {
|
|
|
68
120
|
clientId: string;
|
|
69
121
|
clientSecret: string;
|
|
70
122
|
scopes?: string[];
|
|
123
|
+
/** See {@link OAuthProvider.allowedEmailDomains}. */
|
|
124
|
+
allowedEmailDomains?: string[];
|
|
125
|
+
/** See {@link OAuthProvider.allowAnyEmailDomain}. */
|
|
126
|
+
allowAnyEmailDomain?: true;
|
|
71
127
|
fetch?: typeof fetch;
|
|
128
|
+
/** Timeout for the discovery request, ms. Default 10 s. */
|
|
129
|
+
timeoutMs?: number;
|
|
72
130
|
}): Promise<OAuthProvider>;
|
|
73
131
|
export interface OAuthOptions {
|
|
74
132
|
/** Secret used to sign the CSRF `state` (typically your APP_SECRET). */
|
|
@@ -86,6 +144,21 @@ export interface OAuthOptions {
|
|
|
86
144
|
* only for an IdP that enforces MFA.
|
|
87
145
|
*/
|
|
88
146
|
mfa?: 'required' | 'skip';
|
|
147
|
+
/**
|
|
148
|
+
* Timeout for every request to a provider (token endpoint, userinfo, …), ms.
|
|
149
|
+
* Default 10 s; a provider that hangs fails the login with
|
|
150
|
+
* `AUTH_OAUTH_EXCHANGE_FAILED` instead of holding the request open.
|
|
151
|
+
*/
|
|
152
|
+
timeoutMs?: number;
|
|
153
|
+
/**
|
|
154
|
+
* An account already linked to one subject of a provider, and a login from a
|
|
155
|
+
* **different** subject of that provider asserting the same email: `'refuse'`
|
|
156
|
+
* (default, `AUTH_ACCOUNT_LINK_CONFLICT`) or `'link'` the new subject too.
|
|
157
|
+
* Choose `'link'` only for an IdP that re-issues subjects (a directory
|
|
158
|
+
* migration) — otherwise it lets a second IdP account take the first one's
|
|
159
|
+
* place by email.
|
|
160
|
+
*/
|
|
161
|
+
subjectConflict?: 'refuse' | 'link';
|
|
89
162
|
}
|
|
90
163
|
/**
|
|
91
164
|
* OAuth 2.0 authorization-code login. Server-side (confidential-client) flow:
|
|
@@ -103,6 +176,7 @@ export declare class OAuth {
|
|
|
103
176
|
private readonly auth;
|
|
104
177
|
private readonly options;
|
|
105
178
|
private readonly providers;
|
|
179
|
+
private readonly allowedDomains;
|
|
106
180
|
private readonly doFetch;
|
|
107
181
|
private readonly now;
|
|
108
182
|
private readonly stateTtl;
|
|
@@ -143,8 +217,13 @@ export declare class OAuth {
|
|
|
143
217
|
/** Single-use: a state nonce is remembered until it expires. */
|
|
144
218
|
private readonly consumed;
|
|
145
219
|
private consumeState;
|
|
146
|
-
/**
|
|
147
|
-
|
|
220
|
+
/**
|
|
221
|
+
* The id_token is received directly from the token endpoint over TLS, so its
|
|
222
|
+
* signature is not re-verified (OIDC Core §3.1.3.7 item 6), but its claims
|
|
223
|
+
* must still be for THIS flow: our nonce, our client as audience, not
|
|
224
|
+
* expired, and — when the provider declares one — the expected issuer.
|
|
225
|
+
*/
|
|
226
|
+
private checkIdToken;
|
|
148
227
|
private exchangeCode;
|
|
149
228
|
private signState;
|
|
150
229
|
private verifyState;
|
package/dist/oauth.js
CHANGED
|
@@ -21,10 +21,42 @@ export class OAuthStateInvalidError extends BasaltError {
|
|
|
21
21
|
}
|
|
22
22
|
export class OAuthExchangeError extends BasaltError {
|
|
23
23
|
status = 502;
|
|
24
|
+
/**
|
|
25
|
+
* The message quotes the provider's reply (`error_description`, an HTTP
|
|
26
|
+
* status, a discovery URL): diagnostic for the log, not for the client, who
|
|
27
|
+
* only gets the code and a neutral message.
|
|
28
|
+
*/
|
|
29
|
+
expose = false;
|
|
24
30
|
constructor(detail) {
|
|
25
31
|
super('AUTH_OAUTH_EXCHANGE_FAILED', `OAuth token/profile exchange failed: ${detail}`);
|
|
26
32
|
}
|
|
27
33
|
}
|
|
34
|
+
/** Thrown when the OAuth provider configuration is unsafe (see {@link OAuthProvider.allowedEmailDomains}). */
|
|
35
|
+
export class OAuthProviderConfigError extends BasaltError {
|
|
36
|
+
status = 500;
|
|
37
|
+
constructor(detail) {
|
|
38
|
+
super('AUTH_OAUTH_PROVIDER_CONFIG', `Unsafe OAuth configuration: ${detail}.`);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/** Default deadline for a request to a provider, ms. */
|
|
42
|
+
const DEFAULT_TIMEOUT_MS = 10_000;
|
|
43
|
+
/** A provider claim that must be a non-empty string; otherwise the login fails closed. */
|
|
44
|
+
function claim(value, what) {
|
|
45
|
+
if (typeof value === 'string' && value.length > 0)
|
|
46
|
+
return value;
|
|
47
|
+
if (typeof value === 'number' && Number.isSafeInteger(value))
|
|
48
|
+
return String(value);
|
|
49
|
+
throw new OAuthExchangeError(`provider returned no ${what}`);
|
|
50
|
+
}
|
|
51
|
+
/** Parses a provider response body as JSON, turning an HTML/garbage reply into an exchange error. */
|
|
52
|
+
async function readJson(res, what) {
|
|
53
|
+
try {
|
|
54
|
+
return (await res.json());
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
throw new OAuthExchangeError(`${what} did not return JSON`);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
28
60
|
/** Google (OpenID Connect). Default scopes: `openid email profile`. */
|
|
29
61
|
export function googleProvider(keys) {
|
|
30
62
|
return {
|
|
@@ -34,16 +66,17 @@ export function googleProvider(keys) {
|
|
|
34
66
|
clientId: keys.clientId,
|
|
35
67
|
clientSecret: keys.clientSecret,
|
|
36
68
|
scopes: keys.scopes ?? ['openid', 'email', 'profile'],
|
|
69
|
+
issuer: ['https://accounts.google.com', 'accounts.google.com'],
|
|
37
70
|
async fetchProfile(accessToken, doFetch) {
|
|
38
71
|
const res = await doFetch('https://openidconnect.googleapis.com/v1/userinfo', {
|
|
39
72
|
headers: { authorization: `Bearer ${accessToken}` },
|
|
40
73
|
});
|
|
41
74
|
if (!res.ok)
|
|
42
75
|
throw new OAuthExchangeError(`google userinfo HTTP ${res.status}`);
|
|
43
|
-
const p =
|
|
76
|
+
const p = await readJson(res, 'google userinfo');
|
|
44
77
|
return {
|
|
45
|
-
subject:
|
|
46
|
-
email:
|
|
78
|
+
subject: claim(p.sub, 'subject'),
|
|
79
|
+
email: claim(p.email, 'email'),
|
|
47
80
|
emailVerified: p.email_verified === true,
|
|
48
81
|
...(p.name ? { name: p.name } : {}),
|
|
49
82
|
};
|
|
@@ -64,22 +97,24 @@ export function githubProvider(keys) {
|
|
|
64
97
|
const userRes = await doFetch('https://api.github.com/user', { headers });
|
|
65
98
|
if (!userRes.ok)
|
|
66
99
|
throw new OAuthExchangeError(`github user HTTP ${userRes.status}`);
|
|
67
|
-
const user =
|
|
100
|
+
const user = await readJson(userRes, 'github user');
|
|
101
|
+
const subject = claim(user.id, 'subject');
|
|
68
102
|
// GitHub often hides the email on /user; the primary verified one comes from /user/emails.
|
|
69
103
|
let email = user.email ?? undefined;
|
|
70
104
|
let emailVerified = false;
|
|
71
105
|
const emailsRes = await doFetch('https://api.github.com/user/emails', { headers });
|
|
72
106
|
if (emailsRes.ok) {
|
|
73
|
-
const emails =
|
|
74
|
-
const
|
|
107
|
+
const emails = await readJson(emailsRes, 'github emails');
|
|
108
|
+
const list = Array.isArray(emails) ? emails : [];
|
|
109
|
+
const primary = list.find((e) => e.primary && e.verified) ?? list.find((e) => e.verified);
|
|
75
110
|
if (primary) {
|
|
76
111
|
email = primary.email;
|
|
77
112
|
emailVerified = true;
|
|
78
113
|
}
|
|
79
114
|
}
|
|
80
|
-
if (!email)
|
|
115
|
+
if (typeof email !== 'string' || !email)
|
|
81
116
|
throw new OAuthExchangeError('github returned no usable email');
|
|
82
|
-
return { subject
|
|
117
|
+
return { subject, email, emailVerified, ...(user.name ? { name: user.name } : {}) };
|
|
83
118
|
},
|
|
84
119
|
};
|
|
85
120
|
}
|
|
@@ -89,6 +124,11 @@ export function githubProvider(keys) {
|
|
|
89
124
|
* three endpoints from the IdP's `.well-known/openid-configuration`, or use
|
|
90
125
|
* {@link discoverOidcProvider} to fetch them for you. Maps the standard OIDC
|
|
91
126
|
* `userinfo` claims (`sub`, `email`, `email_verified`, `name`).
|
|
127
|
+
*
|
|
128
|
+
* The IdP's admin decides which emails it asserts as verified: restrict each
|
|
129
|
+
* customer's IdP to that customer's domains with `allowedEmailDomains` —
|
|
130
|
+
* required as soon as more than one provider is configured (see
|
|
131
|
+
* {@link OAuthProvider.enterprise}).
|
|
92
132
|
*/
|
|
93
133
|
export function oidcProvider(config) {
|
|
94
134
|
return {
|
|
@@ -98,44 +138,110 @@ export function oidcProvider(config) {
|
|
|
98
138
|
clientId: config.clientId,
|
|
99
139
|
clientSecret: config.clientSecret,
|
|
100
140
|
scopes: config.scopes ?? ['openid', 'email', 'profile'],
|
|
141
|
+
enterprise: true,
|
|
142
|
+
...(config.issuer !== undefined ? { issuer: config.issuer } : {}),
|
|
143
|
+
...(config.allowedEmailDomains !== undefined ? { allowedEmailDomains: config.allowedEmailDomains } : {}),
|
|
144
|
+
...(config.allowAnyEmailDomain === true ? { allowAnyEmailDomain: true } : {}),
|
|
101
145
|
async fetchProfile(accessToken, doFetch) {
|
|
102
146
|
const res = await doFetch(config.userInfoUrl, { headers: { authorization: `Bearer ${accessToken}` } });
|
|
103
147
|
if (!res.ok)
|
|
104
148
|
throw new OAuthExchangeError(`oidc userinfo HTTP ${res.status}`);
|
|
105
|
-
const p =
|
|
149
|
+
const p = await readJson(res, 'oidc userinfo');
|
|
106
150
|
return {
|
|
107
|
-
subject:
|
|
108
|
-
email:
|
|
151
|
+
subject: claim(p.sub, 'subject'),
|
|
152
|
+
email: claim(p.email, 'email'),
|
|
109
153
|
emailVerified: p.email_verified === true,
|
|
110
154
|
...(p.name ? { name: p.name } : {}),
|
|
111
155
|
};
|
|
112
156
|
},
|
|
113
157
|
};
|
|
114
158
|
}
|
|
159
|
+
/** `https:` — or plain `http:` to a loopback host (a local IdP in development). */
|
|
160
|
+
function isSecureEndpoint(value) {
|
|
161
|
+
if (typeof value !== 'string')
|
|
162
|
+
return false;
|
|
163
|
+
let url;
|
|
164
|
+
try {
|
|
165
|
+
url = new URL(value);
|
|
166
|
+
}
|
|
167
|
+
catch {
|
|
168
|
+
return false;
|
|
169
|
+
}
|
|
170
|
+
if (url.protocol === 'https:')
|
|
171
|
+
return true;
|
|
172
|
+
return url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
|
|
173
|
+
}
|
|
115
174
|
/**
|
|
116
175
|
* Builds an {@link oidcProvider} by fetching the IdP's OIDC discovery document
|
|
117
176
|
* (`${issuer}/.well-known/openid-configuration`). Await it at startup.
|
|
177
|
+
*
|
|
178
|
+
* Per OpenID Connect Discovery §4.3 the document's `issuer` must equal the
|
|
179
|
+
* configured one (trailing slashes aside), and every endpoint must be `https:`
|
|
180
|
+
* (plain `http:` only to a loopback host), or discovery fails.
|
|
118
181
|
*/
|
|
119
182
|
export async function discoverOidcProvider(config) {
|
|
120
183
|
const doFetch = config.fetch ?? globalThis.fetch;
|
|
121
184
|
const url = `${stripTrailingSlashes(config.issuer)}/.well-known/openid-configuration`;
|
|
122
|
-
|
|
185
|
+
let res;
|
|
186
|
+
try {
|
|
187
|
+
res = await doFetch(url, { signal: AbortSignal.timeout(config.timeoutMs ?? DEFAULT_TIMEOUT_MS) });
|
|
188
|
+
}
|
|
189
|
+
catch {
|
|
190
|
+
throw new OAuthExchangeError(`OIDC discovery request failed for ${url}`);
|
|
191
|
+
}
|
|
123
192
|
if (!res.ok)
|
|
124
193
|
throw new OAuthExchangeError(`OIDC discovery HTTP ${res.status} for ${url}`);
|
|
125
|
-
const meta =
|
|
194
|
+
const meta = await readJson(res, 'OIDC discovery');
|
|
126
195
|
if (!meta.authorization_endpoint || !meta.token_endpoint || !meta.userinfo_endpoint) {
|
|
127
196
|
throw new OAuthExchangeError('OIDC discovery document is missing required endpoints');
|
|
128
197
|
}
|
|
198
|
+
if (typeof meta.issuer !== 'string' || stripTrailingSlashes(meta.issuer) !== stripTrailingSlashes(config.issuer)) {
|
|
199
|
+
throw new OAuthExchangeError(`OIDC discovery document is for another issuer (${String(meta.issuer)})`);
|
|
200
|
+
}
|
|
201
|
+
if (!isSecureEndpoint(meta.authorization_endpoint) ||
|
|
202
|
+
!isSecureEndpoint(meta.token_endpoint) ||
|
|
203
|
+
!isSecureEndpoint(meta.userinfo_endpoint)) {
|
|
204
|
+
throw new OAuthExchangeError('OIDC discovery document lists a non-https endpoint');
|
|
205
|
+
}
|
|
129
206
|
return oidcProvider({
|
|
130
207
|
...(config.name ? { name: config.name } : {}),
|
|
131
208
|
authorizeUrl: meta.authorization_endpoint,
|
|
132
209
|
tokenUrl: meta.token_endpoint,
|
|
133
210
|
userInfoUrl: meta.userinfo_endpoint,
|
|
211
|
+
issuer: meta.issuer,
|
|
134
212
|
clientId: config.clientId,
|
|
135
213
|
clientSecret: config.clientSecret,
|
|
136
214
|
...(config.scopes ? { scopes: config.scopes } : {}),
|
|
215
|
+
...(config.allowedEmailDomains !== undefined ? { allowedEmailDomains: config.allowedEmailDomains } : {}),
|
|
216
|
+
...(config.allowAnyEmailDomain === true ? { allowAnyEmailDomain: true } : {}),
|
|
137
217
|
});
|
|
138
218
|
}
|
|
219
|
+
const DOMAIN_RE = /^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/;
|
|
220
|
+
function normalizeAllowedDomains(p) {
|
|
221
|
+
if (p.allowedEmailDomains === undefined)
|
|
222
|
+
return undefined;
|
|
223
|
+
if (!Array.isArray(p.allowedEmailDomains) || p.allowedEmailDomains.length === 0) {
|
|
224
|
+
throw new OAuthProviderConfigError(`provider "${p.name}" has an empty allowedEmailDomains list`);
|
|
225
|
+
}
|
|
226
|
+
const out = new Set();
|
|
227
|
+
for (const d of p.allowedEmailDomains) {
|
|
228
|
+
const n = typeof d === 'string' ? d.toLowerCase() : '';
|
|
229
|
+
if (!DOMAIN_RE.test(n)) {
|
|
230
|
+
throw new OAuthProviderConfigError(`provider "${p.name}" has an invalid allowedEmailDomains entry ${JSON.stringify(d)}`);
|
|
231
|
+
}
|
|
232
|
+
out.add(n);
|
|
233
|
+
}
|
|
234
|
+
return out;
|
|
235
|
+
}
|
|
236
|
+
/** The domain of a single-`@`, whitespace/control-free email, lowercased; otherwise `undefined`. */
|
|
237
|
+
function emailDomain(email) {
|
|
238
|
+
if (/[\s\p{Cc}\p{Cf}]/u.test(email))
|
|
239
|
+
return undefined;
|
|
240
|
+
const at = email.indexOf('@');
|
|
241
|
+
if (at <= 0 || at !== email.lastIndexOf('@') || at === email.length - 1)
|
|
242
|
+
return undefined;
|
|
243
|
+
return email.slice(at + 1).toLowerCase();
|
|
244
|
+
}
|
|
139
245
|
const sha256 = (value) => createHash('sha256').update(value).digest('base64url');
|
|
140
246
|
const safeEqual = (a, b) => {
|
|
141
247
|
const x = Buffer.from(a);
|
|
@@ -160,14 +266,32 @@ export class OAuth {
|
|
|
160
266
|
auth;
|
|
161
267
|
options;
|
|
162
268
|
providers;
|
|
269
|
+
allowedDomains = new Map();
|
|
163
270
|
doFetch;
|
|
164
271
|
now;
|
|
165
272
|
stateTtl;
|
|
166
273
|
constructor(auth, providers, options) {
|
|
167
274
|
this.auth = auth;
|
|
168
275
|
this.options = options;
|
|
276
|
+
const seen = new Set();
|
|
277
|
+
for (const p of providers) {
|
|
278
|
+
// A duplicate name would silently pair one entry's IdP with another's allowlist.
|
|
279
|
+
if (seen.has(p.name))
|
|
280
|
+
throw new OAuthProviderConfigError(`provider "${p.name}" is configured more than once`);
|
|
281
|
+
seen.add(p.name);
|
|
282
|
+
const domains = normalizeAllowedDomains(p);
|
|
283
|
+
if (domains)
|
|
284
|
+
this.allowedDomains.set(p.name, domains);
|
|
285
|
+
else if (p.enterprise === true && providers.length > 1 && p.allowAnyEmailDomain !== true) {
|
|
286
|
+
throw new OAuthProviderConfigError(`provider "${p.name}" is an enterprise IdP with no allowedEmailDomains; with several providers each ` +
|
|
287
|
+
"customer's IdP must be restricted to its own email domains (or set allowAnyEmailDomain: true for an IdP you fully control)");
|
|
288
|
+
}
|
|
289
|
+
}
|
|
169
290
|
this.providers = new Map(providers.map((p) => [p.name, p]));
|
|
170
|
-
|
|
291
|
+
const base = options.fetch ?? globalThis.fetch;
|
|
292
|
+
const timeout = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
293
|
+
// Every provider call gets a deadline unless the caller passed its own signal.
|
|
294
|
+
this.doFetch = ((input, init) => base(input, { ...init, signal: init?.signal ?? AbortSignal.timeout(timeout) }));
|
|
171
295
|
this.now = options.now ?? Date.now;
|
|
172
296
|
this.stateTtl = options.stateTtlMs ?? 10 * 60_000;
|
|
173
297
|
}
|
|
@@ -231,14 +355,39 @@ export class OAuth {
|
|
|
231
355
|
this.consumeState(payload);
|
|
232
356
|
const p = this.provider(name);
|
|
233
357
|
const { accessToken, idToken } = await this.exchangeCode(p, input.code, input.redirectUri, this.derive('pkce', input.binding));
|
|
234
|
-
if (p.scopes.includes('openid')
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
358
|
+
if (p.scopes.includes('openid')) {
|
|
359
|
+
// OIDC Core §3.1.3.3: the token response of an `openid` flow carries an id_token.
|
|
360
|
+
if (idToken === undefined)
|
|
361
|
+
throw new OAuthExchangeError('the token response has no id_token');
|
|
362
|
+
this.checkIdToken(p, idToken, this.derive('nonce', input.binding));
|
|
363
|
+
}
|
|
364
|
+
let profile;
|
|
365
|
+
try {
|
|
366
|
+
profile = await p.fetchProfile(accessToken, this.doFetch);
|
|
367
|
+
}
|
|
368
|
+
catch (err) {
|
|
369
|
+
if (err instanceof BasaltError)
|
|
370
|
+
throw err;
|
|
371
|
+
throw new OAuthExchangeError(`${name} profile request failed`);
|
|
372
|
+
}
|
|
373
|
+
const email = typeof profile.email === 'string' ? profile.email : '';
|
|
374
|
+
const domain = emailDomain(email);
|
|
375
|
+
if (!domain)
|
|
376
|
+
throw new OAuthExchangeError('provider returned no usable email');
|
|
377
|
+
const allowed = this.allowedDomains.get(p.name);
|
|
378
|
+
if (allowed && !allowed.has(domain)) {
|
|
379
|
+
throw new OAuthExchangeError(`provider "${p.name}" is not trusted for the email domain "${domain}"`);
|
|
380
|
+
}
|
|
381
|
+
// The provider's stable subject decides which account this is once linked;
|
|
382
|
+
// the email only matters for the first login (see Auth.socialLogin).
|
|
383
|
+
const subject = typeof profile.subject === 'string' ? profile.subject : '';
|
|
384
|
+
if (!subject)
|
|
385
|
+
throw new OAuthExchangeError('provider returned no subject');
|
|
386
|
+
return this.auth.socialLogin(email, {
|
|
240
387
|
emailVerified: profile.emailVerified === true,
|
|
388
|
+
identity: { provider: p.name, subject },
|
|
241
389
|
...(this.options.mfa ? { mfa: this.options.mfa } : {}),
|
|
390
|
+
...(this.options.subjectConflict ? { subjectConflict: this.options.subjectConflict } : {}),
|
|
242
391
|
});
|
|
243
392
|
}
|
|
244
393
|
/** A per-flow secret derived from the binding (PKCE verifier, OIDC nonce): 43 url-safe chars. */
|
|
@@ -263,8 +412,13 @@ export class OAuth {
|
|
|
263
412
|
throw new OAuthStateInvalidError();
|
|
264
413
|
this.consumed.set(payload.n, payload.e);
|
|
265
414
|
}
|
|
266
|
-
/**
|
|
267
|
-
|
|
415
|
+
/**
|
|
416
|
+
* The id_token is received directly from the token endpoint over TLS, so its
|
|
417
|
+
* signature is not re-verified (OIDC Core §3.1.3.7 item 6), but its claims
|
|
418
|
+
* must still be for THIS flow: our nonce, our client as audience, not
|
|
419
|
+
* expired, and — when the provider declares one — the expected issuer.
|
|
420
|
+
*/
|
|
421
|
+
checkIdToken(p, idToken, expectedNonce) {
|
|
268
422
|
let claims;
|
|
269
423
|
try {
|
|
270
424
|
claims = JSON.parse(Buffer.from(idToken.split('.')[1] ?? '', 'base64url').toString('utf8'));
|
|
@@ -272,29 +426,56 @@ export class OAuth {
|
|
|
272
426
|
catch {
|
|
273
427
|
throw new OAuthExchangeError('malformed id_token');
|
|
274
428
|
}
|
|
275
|
-
if (typeof claims
|
|
429
|
+
if (claims === null || typeof claims !== 'object')
|
|
430
|
+
throw new OAuthExchangeError('malformed id_token');
|
|
431
|
+
if (typeof claims.nonce !== 'string' || !safeEqual(claims.nonce, expectedNonce)) {
|
|
276
432
|
throw new OAuthExchangeError('id_token nonce mismatch');
|
|
277
433
|
}
|
|
434
|
+
const audiences = Array.isArray(claims.aud) ? claims.aud : [claims.aud];
|
|
435
|
+
if (!audiences.includes(p.clientId))
|
|
436
|
+
throw new OAuthExchangeError('id_token audience mismatch');
|
|
437
|
+
if (typeof claims.exp !== 'number' || claims.exp * 1000 <= this.now()) {
|
|
438
|
+
throw new OAuthExchangeError('id_token expired');
|
|
439
|
+
}
|
|
440
|
+
if (p.issuer !== undefined) {
|
|
441
|
+
const issuers = Array.isArray(p.issuer) ? p.issuer : [p.issuer];
|
|
442
|
+
if (typeof claims.iss !== 'string' || !issuers.some((i) => stripTrailingSlashes(i) === stripTrailingSlashes(claims.iss))) {
|
|
443
|
+
throw new OAuthExchangeError('id_token issuer mismatch');
|
|
444
|
+
}
|
|
445
|
+
}
|
|
278
446
|
}
|
|
279
447
|
async exchangeCode(p, code, redirectUri, codeVerifier) {
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
448
|
+
let res;
|
|
449
|
+
try {
|
|
450
|
+
res = await this.doFetch(p.tokenUrl, {
|
|
451
|
+
method: 'POST',
|
|
452
|
+
headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },
|
|
453
|
+
body: new URLSearchParams({
|
|
454
|
+
grant_type: 'authorization_code',
|
|
455
|
+
code,
|
|
456
|
+
redirect_uri: redirectUri,
|
|
457
|
+
client_id: p.clientId,
|
|
458
|
+
client_secret: p.clientSecret,
|
|
459
|
+
code_verifier: codeVerifier,
|
|
460
|
+
}).toString(),
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
catch {
|
|
464
|
+
throw new OAuthExchangeError(`${p.name} token endpoint request failed`);
|
|
465
|
+
}
|
|
292
466
|
const text = await res.text();
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
: {};
|
|
296
|
-
|
|
297
|
-
|
|
467
|
+
let json = {};
|
|
468
|
+
try {
|
|
469
|
+
json = text ? JSON.parse(text) : {};
|
|
470
|
+
}
|
|
471
|
+
catch {
|
|
472
|
+
throw new OAuthExchangeError(`token endpoint HTTP ${res.status} did not return JSON`);
|
|
473
|
+
}
|
|
474
|
+
if (json === null || typeof json !== 'object')
|
|
475
|
+
json = {};
|
|
476
|
+
if (!res.ok || typeof json.access_token !== 'string' || !json.access_token) {
|
|
477
|
+
const reason = typeof json.error_description === 'string' ? json.error_description : typeof json.error === 'string' ? json.error : undefined;
|
|
478
|
+
throw new OAuthExchangeError(reason ?? `token endpoint HTTP ${res.status}`);
|
|
298
479
|
}
|
|
299
480
|
return { accessToken: json.access_token, ...(typeof json.id_token === 'string' ? { idToken: json.id_token } : {}) };
|
|
300
481
|
}
|
package/dist/plugin.d.ts
CHANGED
|
@@ -73,11 +73,16 @@ declare module '@basaltkit/core' {
|
|
|
73
73
|
/**
|
|
74
74
|
* A provider-verified social login took over an account whose email had
|
|
75
75
|
* never been verified; its previous password, sessions, refresh tokens and
|
|
76
|
-
* MFA were revoked.
|
|
76
|
+
* MFA and account links were revoked.
|
|
77
77
|
*/
|
|
78
78
|
'auth:social_account_adopted': {
|
|
79
79
|
user: PublicUser;
|
|
80
80
|
};
|
|
81
|
+
/** A provider account (its stable subject) was linked to this account on its first social login. */
|
|
82
|
+
'auth:account_linked': {
|
|
83
|
+
user: PublicUser;
|
|
84
|
+
provider: string;
|
|
85
|
+
};
|
|
81
86
|
}
|
|
82
87
|
}
|
|
83
88
|
export declare const AUTH: import("@basaltkit/core").Token<Auth>;
|
package/dist/secret-box.d.ts
CHANGED
|
@@ -1,10 +1,82 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
1
|
+
import { BasaltError } from '@basaltkit/core';
|
|
2
|
+
/** A secret-box key or its value could not be used (configuration error). */
|
|
3
|
+
export declare class SecretBoxKeyError extends BasaltError {
|
|
4
|
+
readonly status = 500;
|
|
5
|
+
readonly expose = false;
|
|
6
|
+
constructor(detail: string);
|
|
7
|
+
}
|
|
5
8
|
/**
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
+
* A stored secret could not be opened: not an envelope (and no legacy opt-in),
|
|
10
|
+
* an unknown key id, tampering, or a blob that belongs to another record. One
|
|
11
|
+
* error for every case, so a caller cannot tell them apart.
|
|
9
12
|
*/
|
|
10
|
-
export declare
|
|
13
|
+
export declare class SecretUnreadableError extends BasaltError {
|
|
14
|
+
readonly status = 500;
|
|
15
|
+
readonly expose = false;
|
|
16
|
+
constructor(detail: string);
|
|
17
|
+
}
|
|
18
|
+
/** One entry of the key ring. */
|
|
19
|
+
export interface SecretBoxKey {
|
|
20
|
+
/**
|
|
21
|
+
* Stable identifier stored with every ciphertext (`[A-Za-z0-9_-]{1,64}`).
|
|
22
|
+
* Keep it in the ring as long as any row was sealed with it.
|
|
23
|
+
*/
|
|
24
|
+
id: string;
|
|
25
|
+
/** Key material, at least 32 bytes. Never used raw: the AES key is derived with HKDF. */
|
|
26
|
+
key: string | Uint8Array;
|
|
27
|
+
}
|
|
28
|
+
/** What a ciphertext is bound to. Changing either field makes it undecryptable. */
|
|
29
|
+
export interface SecretContext {
|
|
30
|
+
/** What the secret is for, e.g. `'totp'`. */
|
|
31
|
+
purpose: string;
|
|
32
|
+
/** Whose secret it is, e.g. the user id. */
|
|
33
|
+
subject: string;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Read-only compatibility with values written before the `bka2` envelope.
|
|
37
|
+
* Accepting them re-opens the downgrade the envelope closes, so enable it only
|
|
38
|
+
* while migrating ({@link SecretBox.reseal}) and remove it afterwards.
|
|
39
|
+
*/
|
|
40
|
+
export interface SecretBoxLegacyOptions {
|
|
41
|
+
/** Keys of the old `v1:` envelopes (the former `mfaEncryptionKey`). */
|
|
42
|
+
v1Keys?: ReadonlyArray<string | Uint8Array>;
|
|
43
|
+
/** Accept a value with no envelope at all as plaintext. */
|
|
44
|
+
plaintext?: boolean;
|
|
45
|
+
}
|
|
46
|
+
export interface SecretBoxOptions {
|
|
47
|
+
/** The key ring; the first key seals everything new. */
|
|
48
|
+
keys: readonly SecretBoxKey[];
|
|
49
|
+
legacy?: SecretBoxLegacyOptions;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Seals and opens secrets against a key ring. See the module comment for the
|
|
53
|
+
* envelope and the threat model.
|
|
54
|
+
*/
|
|
55
|
+
export declare class SecretBox {
|
|
56
|
+
private readonly keys;
|
|
57
|
+
private readonly activeId;
|
|
58
|
+
private readonly v1Keys;
|
|
59
|
+
private readonly acceptPlaintext;
|
|
60
|
+
constructor(options: SecretBoxOptions);
|
|
61
|
+
/** The key id new ciphertexts are sealed with. */
|
|
62
|
+
get activeKeyId(): string;
|
|
63
|
+
/** Encrypts `plaintext` under the active key, bound to `context`. */
|
|
64
|
+
seal(plaintext: string, context: SecretContext): string;
|
|
65
|
+
/**
|
|
66
|
+
* Decrypts a value sealed for `context`. Throws {@link SecretUnreadableError}
|
|
67
|
+
* for anything else — including plaintext and `v1:` values unless the
|
|
68
|
+
* matching legacy opt-in is set.
|
|
69
|
+
*/
|
|
70
|
+
open(value: string, context: SecretContext): string;
|
|
71
|
+
/** Whether `value` is already sealed with the active key (nothing to migrate). */
|
|
72
|
+
isCurrent(value: string): boolean;
|
|
73
|
+
/**
|
|
74
|
+
* Re-seals `value` under the active key — for rotation, and for migrating
|
|
75
|
+
* `v1:` / plaintext values (which requires the legacy opt-in to read them).
|
|
76
|
+
* Returns `null` when the value is already current, so a caller can skip the
|
|
77
|
+
* write.
|
|
78
|
+
*/
|
|
79
|
+
reseal(value: string, context: SecretContext): string | null;
|
|
80
|
+
private openV2;
|
|
81
|
+
private openV1;
|
|
82
|
+
}
|