@basaltkit/auth 4.2.0 → 5.1.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/dist/apikeys.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import { createHash, randomBytes, randomUUID } from 'node:crypto';
2
2
  import { BasaltError } from '@basaltkit/core';
3
+ import { AllowlistError, API_KEY_ALLOWED_IPS_MAX, ipAllowed, normalizeAllowedIps } from './ip-allowlist.js';
3
4
  import { MemoryApiKeyStore, } from './stores.js';
5
+ export { API_KEY_ALLOWED_IPS_MAX };
4
6
  /** A route required a scope the presented key does not hold. */
5
7
  export class ScopeRequiredError extends BasaltError {
6
8
  status = 403;
@@ -14,6 +16,90 @@ export class ApiKeyExpirationError extends BasaltError {
14
16
  super('AUTH_APIKEY_EXPIRATION_INVALID', 'API key expiration must be a future timestamp.');
15
17
  }
16
18
  }
19
+ /** No key with this id in scope, or it is revoked or expired (an expired key is dead: issue a new one). */
20
+ export class ApiKeyNotFoundError extends BasaltError {
21
+ status = 404;
22
+ constructor() {
23
+ super('AUTH_APIKEY_NOT_FOUND', 'API key not found.');
24
+ }
25
+ }
26
+ /**
27
+ * Invalid input to an API key operation: a bad `allowedIps` entry, `meta` over
28
+ * its limits, `userId` together with `serviceId`, a malformed `serviceId` or
29
+ * `scopes`, or a rotation `graceMs` out of range.
30
+ */
31
+ export class ApiKeyInputError extends BasaltError {
32
+ status = 400;
33
+ constructor(message) {
34
+ super('AUTH_APIKEY_INPUT_INVALID', message);
35
+ }
36
+ }
37
+ /** A concurrent rotation or revocation changed the key first; re-read it and retry. */
38
+ export class ApiKeyConflictError extends BasaltError {
39
+ status = 409;
40
+ constructor() {
41
+ super('AUTH_APIKEY_CONFLICT', 'The API key was changed concurrently; retry.');
42
+ }
43
+ }
44
+ /** The configured `ApiKeyStore` does not implement `update`, which lifecycle operations need. */
45
+ export class ApiKeyStoreUnsupportedError extends BasaltError {
46
+ status = 501;
47
+ constructor(operation) {
48
+ super('AUTH_APIKEY_STORE_UNSUPPORTED', `The API key store does not support "${operation}": it does not implement ApiKeyStore.update.`);
49
+ }
50
+ }
51
+ /** The key is valid, but the request comes from an address outside its `allowedIps`. */
52
+ export class ApiKeyIpNotAllowedError extends BasaltError {
53
+ status = 403;
54
+ constructor() {
55
+ super('AUTH_APIKEY_IP_NOT_ALLOWED', 'This API key is not allowed from this address.');
56
+ }
57
+ }
58
+ /** Longest rotation grace window {@link ApiKeys.rotate} accepts: 30 days (the webhooks secret-rotation cap). */
59
+ export const MAX_API_KEY_ROTATION_GRACE_MS = 30 * 24 * 60 * 60 * 1000;
60
+ /** Limits on a key's `meta`: number of entries, key length, value length. */
61
+ export const API_KEY_META_LIMITS = { keys: 20, keyLength: 40, valueLength: 500 };
62
+ const META_KEY = /^[A-Za-z0-9_.-]+$/;
63
+ const FORBIDDEN_META_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
64
+ /** Printable ASCII without spaces, 1..128 characters. */
65
+ const SERVICE_ID = /^[\x21-\x7E]{1,128}$/;
66
+ /** Validates a key's `meta`; returns a fresh copy. Throws {@link ApiKeyInputError}. */
67
+ function normalizeMeta(meta) {
68
+ if (typeof meta !== 'object' || meta === null || Array.isArray(meta)) {
69
+ throw new ApiKeyInputError('meta must be an object of string values.');
70
+ }
71
+ const entries = Object.entries(meta);
72
+ if (entries.length > API_KEY_META_LIMITS.keys) {
73
+ throw new ApiKeyInputError(`meta holds at most ${API_KEY_META_LIMITS.keys} entries.`);
74
+ }
75
+ const out = {};
76
+ for (const [key, value] of entries) {
77
+ if (FORBIDDEN_META_KEYS.has(key) || !META_KEY.test(key) || key.length > API_KEY_META_LIMITS.keyLength) {
78
+ throw new ApiKeyInputError(`meta key ${JSON.stringify(key)} is invalid: 1-${API_KEY_META_LIMITS.keyLength} characters of A-Z, a-z, 0-9, "_", "." or "-" (not __proto__, constructor or prototype).`);
79
+ }
80
+ if (typeof value !== 'string' || value.length > API_KEY_META_LIMITS.valueLength) {
81
+ throw new ApiKeyInputError(`meta value of ${JSON.stringify(key)} must be a string of at most ${API_KEY_META_LIMITS.valueLength} characters.`);
82
+ }
83
+ out[key] = value;
84
+ }
85
+ return out;
86
+ }
87
+ /** Validates and canonicalises `allowedIps`. Throws {@link ApiKeyInputError}. */
88
+ function allowedIpsOf(value) {
89
+ try {
90
+ return normalizeAllowedIps(value);
91
+ }
92
+ catch (err) {
93
+ if (err instanceof AllowlistError)
94
+ throw new ApiKeyInputError(`allowedIps: ${err.message}.`);
95
+ throw err;
96
+ }
97
+ }
98
+ function assertScopes(scopes) {
99
+ if (!Array.isArray(scopes) || !scopes.every((scope) => typeof scope === 'string' && scope.length > 0)) {
100
+ throw new ApiKeyInputError('scopes must be an array of non-empty strings.');
101
+ }
102
+ }
17
103
  /** The prefix on every key. `mk` = Basalt key, `live` = environment. */
18
104
  const KEY_PREFIX = 'mk_live_';
19
105
  /** Secret characters kept in the display prefix (`ApiKeyRecord.prefix`). */
@@ -29,10 +115,18 @@ export const apiKeyDisplayPrefix = (presented) => presented.startsWith(KEY_PREFI
29
115
  : undefined;
30
116
  /** SHA-256 is safe here: API keys are high-entropy, so no slow hash is needed. */
31
117
  const hashKey = (key) => createHash('sha256').update(key).digest('hex');
118
+ /** A fresh secret: the plaintext key, its hash and its display prefix. */
119
+ const mintSecret = () => {
120
+ const secret = randomBytes(24).toString('base64url');
121
+ const key = `${KEY_PREFIX}${secret}`;
122
+ return { key, hash: hashKey(key), prefix: `${KEY_PREFIX}${secret.slice(0, DISPLAY_SECRET_CHARS)}` };
123
+ };
124
+ /** The public view of a record: never a hash, current or previous. */
32
125
  const strip = (record) => {
33
- const { hash: _hash, ...info } = record;
126
+ const { hash: _hash, previousHash: _previousHash, ...info } = record;
34
127
  return info;
35
128
  };
129
+ const isExpired = (record, now) => record.expiresAt !== undefined && record.expiresAt <= now;
36
130
  /** True when `granted` covers `required` (an exact match or the `*` wildcard). */
37
131
  export const scopesSatisfy = (granted, required) => granted.includes('*') || required.every((scope) => granted.includes(scope));
38
132
  export class ApiKeyOptionsError extends BasaltError {
@@ -53,8 +147,8 @@ export function resolveTouchEveryMs(value) {
53
147
  }
54
148
  /**
55
149
  * Issues and verifies API keys. The plaintext key is returned exactly once by
56
- * {@link issue}; only its SHA-256 hash is stored, so a leaked database never
57
- * yields usable keys.
150
+ * {@link issue} (and {@link rotate}); only its SHA-256 hash is stored, so a
151
+ * leaked database never yields usable keys.
58
152
  */
59
153
  export class ApiKeys {
60
154
  store;
@@ -72,46 +166,182 @@ export class ApiKeys {
72
166
  if (input.expiresAt !== undefined && (!Number.isInteger(input.expiresAt) || input.expiresAt <= this.now())) {
73
167
  throw new ApiKeyExpirationError();
74
168
  }
75
- const secret = randomBytes(24).toString('base64url');
76
- const key = `${KEY_PREFIX}${secret}`;
169
+ if (input.serviceId !== undefined) {
170
+ if (input.userId !== undefined) {
171
+ throw new ApiKeyInputError('A key acts as a user or as a service, not both: pass userId or serviceId.');
172
+ }
173
+ if (typeof input.serviceId !== 'string' || !SERVICE_ID.test(input.serviceId)) {
174
+ throw new ApiKeyInputError('serviceId must be 1-128 printable characters without spaces.');
175
+ }
176
+ }
177
+ if (input.scopes !== undefined)
178
+ assertScopes(input.scopes);
179
+ const allowedIps = input.allowedIps !== undefined ? allowedIpsOf(input.allowedIps) : [];
180
+ const meta = input.meta !== undefined ? normalizeMeta(input.meta) : {};
181
+ const { key, hash, prefix } = mintSecret();
77
182
  const record = {
78
183
  id: randomUUID(),
79
184
  name: input.name,
80
- prefix: `${KEY_PREFIX}${secret.slice(0, DISPLAY_SECRET_CHARS)}`,
81
- hash: hashKey(key),
185
+ prefix,
186
+ hash,
82
187
  scopes: input.scopes ?? ['*'],
83
188
  createdAt: this.now(),
84
189
  ...(input.expiresAt !== undefined ? { expiresAt: input.expiresAt } : {}),
85
190
  ...(input.tenantId !== undefined ? { tenantId: input.tenantId } : {}),
86
191
  ...(input.userId !== undefined ? { userId: input.userId } : {}),
192
+ ...(input.serviceId !== undefined ? { serviceId: input.serviceId } : {}),
193
+ ...(allowedIps.length > 0 ? { allowedIps } : {}),
194
+ ...(Object.keys(meta).length > 0 ? { meta } : {}),
87
195
  };
88
196
  await this.store.create(record);
89
- await this.hooks?.emit('auth:apikey_issued', {
90
- id: record.id,
91
- ...(record.tenantId !== undefined ? { tenantId: record.tenantId } : {}),
92
- ...(record.userId !== undefined ? { userId: record.userId } : {}),
93
- });
197
+ await this.hooks?.emit('auth:apikey_issued', { id: record.id, ...ownerOf(record) });
94
198
  return { record: strip(record), key };
95
199
  }
96
200
  /**
97
- * Resolves a presented key to its record, or null if it's malformed,
98
- * unknown, or revoked. Updates `lastUsedAt` on a hit, at most once per
99
- * `touchEveryMs` per key.
201
+ * Authenticates a presented key. Malformed, unknown, revoked and expired keys
202
+ * are `invalid`; a key whose `allowedIps` does not cover `options.ip` (or
203
+ * that has an allowlist and no ip to check) is `ip_not_allowed`. After a
204
+ * rotation the previous secret is accepted only until
205
+ * `previousHashExpiresAt`, re-checked here and never trusted to the store.
206
+ * Updates `lastUsedAt` on success only, at most once per `touchEveryMs`.
100
207
  */
101
- async verify(presented) {
208
+ async authenticate(presented, options = {}) {
102
209
  if (!presented.startsWith(KEY_PREFIX))
103
- return null;
104
- const record = await this.store.findByHash(hashKey(presented));
210
+ return { ok: false, reason: 'invalid' };
211
+ const hash = hashKey(presented);
212
+ const record = await this.store.findByHash(hash);
213
+ if (!record)
214
+ return { ok: false, reason: 'invalid' };
105
215
  const now = this.now();
106
- if (!record || record.revokedAt !== undefined || (record.expiresAt !== undefined && record.expiresAt <= now))
107
- return null;
216
+ if (record.hash !== hash) {
217
+ const inGrace = record.previousHash === hash && record.previousHashExpiresAt !== undefined && record.previousHashExpiresAt > now;
218
+ if (!inGrace)
219
+ return { ok: false, reason: 'invalid' };
220
+ }
221
+ if (record.revokedAt !== undefined || isExpired(record, now))
222
+ return { ok: false, reason: 'invalid' };
223
+ if (!ipAllowed(record.allowedIps, options.ip))
224
+ return { ok: false, reason: 'ip_not_allowed', record };
108
225
  if (record.lastUsedAt === undefined || now - record.lastUsedAt >= this.touchEveryMs) {
109
226
  await this.store.touch(record.id, now);
227
+ record.lastUsedAt = now;
110
228
  }
111
- return record;
229
+ return { ok: true, record };
230
+ }
231
+ /**
232
+ * Resolves a presented key to its record, or null if it's malformed,
233
+ * unknown, revoked, expired, or used from an address outside its
234
+ * `allowedIps`. Updates `lastUsedAt` on a hit, at most once per
235
+ * `touchEveryMs` per key.
236
+ */
237
+ async verify(presented, options = {}) {
238
+ const result = await this.authenticate(presented, options);
239
+ return result.ok ? result.record : null;
240
+ }
241
+ /**
242
+ * Live keys matching the filter, without hashes. The filter is re-applied
243
+ * here, so a store that ignores one of its fields never widens the result.
244
+ * Expired keys are listed only with `includeExpired`; revoked ones never.
245
+ */
246
+ async list(options) {
247
+ const { includeExpired = false, ...filter } = options;
248
+ const now = this.now();
249
+ return (await this.store.list(filter))
250
+ .filter((record) => record.revokedAt === undefined &&
251
+ (filter.tenantId === undefined || record.tenantId === filter.tenantId) &&
252
+ (filter.userId === undefined || record.userId === filter.userId) &&
253
+ (filter.serviceId === undefined || record.serviceId === filter.serviceId) &&
254
+ (includeExpired || !isExpired(record, now)))
255
+ .map(strip);
256
+ }
257
+ /**
258
+ * Changes a key's mutable fields in ONE store write; all input is validated
259
+ * first. An unknown, revoked or expired key is {@link ApiKeyNotFoundError}:
260
+ * an expired key cannot be renewed, issue a new one. Emits
261
+ * `auth:apikey_updated` with the changed field names (never the values).
262
+ */
263
+ async update(id, input) {
264
+ const patch = {};
265
+ const changes = [];
266
+ if (input.name !== undefined) {
267
+ if (typeof input.name !== 'string' || input.name.length === 0)
268
+ throw new ApiKeyInputError('name must be a non-empty string.');
269
+ patch.name = input.name;
270
+ changes.push('name');
271
+ }
272
+ if (input.scopes !== undefined) {
273
+ assertScopes(input.scopes);
274
+ patch.scopes = [...input.scopes];
275
+ changes.push('scopes');
276
+ }
277
+ if (input.expiresAt !== undefined) {
278
+ if (input.expiresAt !== null && (!Number.isInteger(input.expiresAt) || input.expiresAt <= this.now())) {
279
+ throw new ApiKeyExpirationError();
280
+ }
281
+ patch.expiresAt = input.expiresAt;
282
+ changes.push('expiresAt');
283
+ }
284
+ if (input.allowedIps !== undefined) {
285
+ const allowedIps = input.allowedIps === null ? [] : allowedIpsOf(input.allowedIps);
286
+ patch.allowedIps = allowedIps.length > 0 ? allowedIps : null;
287
+ changes.push('allowedIps');
288
+ }
289
+ if (input.meta !== undefined) {
290
+ const meta = input.meta === null ? {} : normalizeMeta(input.meta);
291
+ patch.meta = Object.keys(meta).length > 0 ? meta : null;
292
+ changes.push('meta');
293
+ }
294
+ const update = this.requireUpdate('update');
295
+ const current = await this.live(id);
296
+ if (changes.length === 0)
297
+ return strip(current);
298
+ const updated = await update(id, patch);
299
+ // Revoked between the read and the write.
300
+ if (!updated)
301
+ throw new ApiKeyNotFoundError();
302
+ await this.hooks?.emit('auth:apikey_updated', { id, ...ownerOf(updated), changes });
303
+ return strip(updated);
112
304
  }
113
- async list(filter) {
114
- return (await this.store.list(filter)).filter((record) => record.expiresAt === undefined || record.expiresAt > this.now()).map(strip);
305
+ /**
306
+ * Sets when a key expires: a future timestamp (ms), or `null` for never. A
307
+ * thin wrapper over {@link update}; the same "expired is dead" rule applies.
308
+ */
309
+ async setExpiry(id, expiresAt) {
310
+ return this.update(id, { expiresAt });
311
+ }
312
+ /**
313
+ * Replaces a key's secret, keeping its id (so its owner, scopes and audit
314
+ * trail stay). With `graceMs` the replaced secret keeps working that long —
315
+ * never past the key's own expiry or revocation; at most two secrets are ever
316
+ * live, so rotating during a grace window drops the oldest. Compare-and-set:
317
+ * when a concurrent rotation or revocation wins, this one throws
318
+ * {@link ApiKeyConflictError}. Returns the new plaintext `key` (shown once).
319
+ */
320
+ async rotate(id, options = {}) {
321
+ const graceMs = options.graceMs ?? 0;
322
+ if (!Number.isInteger(graceMs) || graceMs < 0 || graceMs > MAX_API_KEY_ROTATION_GRACE_MS) {
323
+ throw new ApiKeyInputError(`graceMs must be an integer between 0 and ${MAX_API_KEY_ROTATION_GRACE_MS} (30 days).`);
324
+ }
325
+ const update = this.requireUpdate('rotate');
326
+ const current = await this.live(id);
327
+ const now = this.now();
328
+ const { key, hash, prefix } = mintSecret();
329
+ const graceUntil = graceMs > 0 ? Math.min(now + graceMs, current.expiresAt ?? Number.POSITIVE_INFINITY) : undefined;
330
+ const rotated = await update(id, {
331
+ hash,
332
+ prefix,
333
+ previousHash: graceUntil !== undefined ? current.hash : null,
334
+ previousHashExpiresAt: graceUntil ?? null,
335
+ rotatedAt: now,
336
+ }, { ifHash: current.hash });
337
+ if (!rotated)
338
+ throw new ApiKeyConflictError();
339
+ await this.hooks?.emit('auth:apikey_rotated', {
340
+ id,
341
+ ...ownerOf(rotated),
342
+ ...(graceUntil !== undefined ? { graceUntil } : {}),
343
+ });
344
+ return { record: strip(rotated), key };
115
345
  }
116
346
  /** Revokes a key by id. No-op if unknown or already revoked. */
117
347
  async revoke(id) {
@@ -136,4 +366,23 @@ export class ApiKeys {
136
366
  const record = await this.store.findById(id);
137
367
  return record ? strip(record) : null;
138
368
  }
369
+ requireUpdate(operation) {
370
+ const update = this.store.update;
371
+ if (typeof update !== 'function')
372
+ throw new ApiKeyStoreUnsupportedError(operation);
373
+ return update.bind(this.store);
374
+ }
375
+ /** The record behind a lifecycle operation: unknown, revoked and expired keys are all "not found". */
376
+ async live(id) {
377
+ const record = await this.store.findById(id);
378
+ if (!record || record.revokedAt !== undefined || isExpired(record, this.now()))
379
+ throw new ApiKeyNotFoundError();
380
+ return record;
381
+ }
139
382
  }
383
+ /** The owner fields every lifecycle hook carries. */
384
+ const ownerOf = (record) => ({
385
+ ...(record.tenantId !== undefined ? { tenantId: record.tenantId } : {}),
386
+ ...(record.userId !== undefined ? { userId: record.userId } : {}),
387
+ ...(record.serviceId !== undefined ? { serviceId: record.serviceId } : {}),
388
+ });
package/dist/auth.d.ts CHANGED
@@ -2,6 +2,7 @@ import { BasaltError, type DurationInput, type HookBus } from '@basaltkit/core';
2
2
  import { type PasswordHasher } from './hashing.js';
3
3
  import { LoginThrottle, type ThrottleStore } from './throttle.js';
4
4
  import { type JwtClaims } from './jwt.js';
5
+ import { type TokenClaimsFn } from './token-claims.js';
5
6
  import { type SecretBoxKey, type SecretBoxLegacyOptions } from './secret-box.js';
6
7
  import { type AccountLinkStore, type AuthTokenStore, type AuthUser, type MfaStore, type PublicUser, type RefreshTokenStore, type SessionRecord, type SessionStore, type TokenVersionStore, type UserSource } from './stores.js';
7
8
  export declare class InvalidCredentialsError extends BasaltError {
@@ -163,18 +164,17 @@ export interface SessionCookieOptions {
163
164
  *
164
165
  * A `__Host-` or `__Secure-` name (matched case-insensitively) implies
165
166
  * `true` when unset (in every environment): browsers silently drop such a
166
- * cookie without `Secure`. An
167
- * explicit `false` is kept as given but warns at boot; it is refused from
168
- * the next major.
167
+ * cookie without `Secure`. An explicit `false` on such a name refuses the
168
+ * boot with `AUTH_SESSION_COOKIE_INVALID` ({@link SessionCookieConfigError}).
169
169
  */
170
170
  secure?: boolean;
171
171
  }
172
172
  /**
173
- * The session cookie options violate the rules of the cookie name's prefix.
174
- *
175
- * Exported ahead of time: today such a configuration only warns at boot (the
176
- * cookie is emitted as configured, as before); from the next major it is
177
- * thrown with code `AUTH_SESSION_COOKIE_INVALID`.
173
+ * The session cookie options violate the rules of the cookie name's prefix
174
+ * (`__Secure-` without `Secure`, `__Host-` without `Secure` or with a path
175
+ * other than `/`). Browsers drop such a cookie, so every login would
176
+ * "succeed" without a session; thrown at boot with code
177
+ * `AUTH_SESSION_COOKIE_INVALID`.
178
178
  */
179
179
  export declare class SessionCookieConfigError extends BasaltError {
180
180
  readonly status = 500;
@@ -304,6 +304,16 @@ export interface AuthOptions {
304
304
  mfaEncryptionKey?: string | Buffer;
305
305
  /** Issuer name shown in authenticator apps. Default 'Basalt'. */
306
306
  mfaIssuer?: string;
307
+ /**
308
+ * Extra claims for every access token: login, MFA completion (login /
309
+ * social login with a code), social login and every refresh — re-derived on
310
+ * each refresh, so a rotated token keeps them. Reserved names
311
+ * ({@link RESERVED_TOKEN_CLAIMS}: `sub`, `tv`, `amr`, `exp`, `iat`, …) throw
312
+ * `AUTH_TOKEN_CLAIM_RESERVED`. Check them on the request path with
313
+ * `authPlugin({ verifyClaims })`; `tenantBoundTokens()` is the ready-made
314
+ * tenant binding. Default: none (tokens carry only `sub`, `tv`, `amr`).
315
+ */
316
+ tokenClaims?: TokenClaimsFn;
307
317
  }
308
318
  export declare const publicUser: (user: AuthUser) => PublicUser;
309
319
  export declare class Auth {
@@ -332,6 +342,7 @@ export declare class Auth {
332
342
  private readonly tokenVersions;
333
343
  private readonly enumerationSafeRegister;
334
344
  private readonly registerPolicy;
345
+ private readonly tokenClaims;
335
346
  constructor(options: AuthOptions);
336
347
  /**
337
348
  * Trusted, server-side account creation (seeding, a back-office, a flow that
@@ -620,5 +631,7 @@ export declare class Auth {
620
631
  private issueOneTimeToken;
621
632
  private consumeToken;
622
633
  private updateUser;
634
+ /** The app's {@link AuthOptions.tokenClaims} for this sign-in, validated. */
635
+ private customClaims;
623
636
  private issueTokens;
624
637
  }
package/dist/auth.js CHANGED
@@ -3,6 +3,7 @@ import { BasaltError, isProductionEnvironment, parseDuration, tryCtx } from '@ba
3
3
  import { ScryptPasswordHasher } from './hashing.js';
4
4
  import { LoginThrottle } from './throttle.js';
5
5
  import { signJwt, verifyJwt } from './jwt.js';
6
+ import { checkCustomClaims } from './token-claims.js';
6
7
  import { generateTotpSecret, matchTotpStep, otpauthUri } from './totp.js';
7
8
  import { SecretBox, SecretBoxKeyError } from './secret-box.js';
8
9
  import { MemoryAccountLinkStore, MemoryAuthTokenStore, MemoryMfaStore, MemoryRefreshTokenStore, MemorySessionStore, } from './stores.js';
@@ -184,11 +185,11 @@ export const isAmr = (value) => Array.isArray(value) &&
184
185
  value.length <= 8 &&
185
186
  value.every((v) => typeof v === 'string' && AMR_VALUE.test(v));
186
187
  /**
187
- * The session cookie options violate the rules of the cookie name's prefix.
188
- *
189
- * Exported ahead of time: today such a configuration only warns at boot (the
190
- * cookie is emitted as configured, as before); from the next major it is
191
- * thrown with code `AUTH_SESSION_COOKIE_INVALID`.
188
+ * The session cookie options violate the rules of the cookie name's prefix
189
+ * (`__Secure-` without `Secure`, `__Host-` without `Secure` or with a path
190
+ * other than `/`). Browsers drop such a cookie, so every login would
191
+ * "succeed" without a session; thrown at boot with code
192
+ * `AUTH_SESSION_COOKIE_INVALID`.
192
193
  */
193
194
  export class SessionCookieConfigError extends BasaltError {
194
195
  status = 500;
@@ -207,7 +208,8 @@ export class SessionIdleConfigError extends BasaltError {
207
208
  * Session cookie options already warned about. Keyed on the `sessionCookie`
208
209
  * object, not on the `Auth` instance: `authPlugin` validates the options at
209
210
  * registration and the `AUTH` singleton resolves them again with the same
210
- * `sessionCookie` reference, so one configuration warns once.
211
+ * `sessionCookie` reference, so one configuration warns once. A refusal is
212
+ * never deduplicated: it throws on every resolution.
211
213
  */
212
214
  const warnedSessionCookies = new WeakSet();
213
215
  /**
@@ -219,13 +221,13 @@ const warnedSessionCookies = new WeakSet();
219
221
  * "succeed" without a session.
220
222
  *
221
223
  * An unset `secure` on a prefixed name takes `true`. Contradicting values
222
- * (`secure: false`, a `__Host-` path other than `/`) are emitted as given and
223
- * warn once at boot; they are refused from the next major.
224
+ * (`secure: false`, a `__Host-` path other than `/`) throw
225
+ * {@link SessionCookieConfigError}: a cookie the browser drops is a broken
226
+ * login, so it fails closed at boot rather than at the first sign-in.
224
227
  *
225
228
  * Warnings are independent, each emitted once per `sessionCookie` object:
226
- * - the cookie is dropped by browsers because of its prefix (refused next major);
227
229
  * - Secure is implied by the prefix where it was not before (outside
228
- * production, so the emission differs from earlier versions);
230
+ * production, so the emission differs from releases before auth 4.2);
229
231
  * - `SameSite=None` without `Secure`, which browsers also drop.
230
232
  */
231
233
  function resolveSessionCookie(options) {
@@ -241,16 +243,17 @@ function resolveSessionCookie(options) {
241
243
  sameSite: options?.sameSite ?? 'Lax',
242
244
  secure: options?.secure ?? (prefixed ? true : production),
243
245
  };
246
+ const problems = [];
247
+ if (prefixed && !resolved.secure)
248
+ problems.push('secure: true');
249
+ if (host && resolved.path !== '/')
250
+ problems.push('path "/"');
251
+ if (problems.length > 0) {
252
+ throw new SessionCookieConfigError(`sessionCookie "${name}" requires ${problems.join(' and ')}: browsers drop a ${host ? '__Host-' : '__Secure-'} cookie without it. ` +
253
+ `Drop the contradicting option, or use an unprefixed name outside production (name: isProd ? '__Host-sid' : 'sid').`);
254
+ }
244
255
  if (options && !warnedSessionCookies.has(options)) {
245
256
  const warnings = [];
246
- const problems = [];
247
- if (prefixed && !resolved.secure)
248
- problems.push('secure: true');
249
- if (host && resolved.path !== '/')
250
- problems.push('path "/"');
251
- if (problems.length > 0) {
252
- warnings.push(`[basalt] sessionCookie: "${name}" requires ${problems.join(' / ')} - browsers drop it; this will refuse to boot in the next major.`);
253
- }
254
257
  if (prefixed && options.secure === undefined && !production) {
255
258
  warnings.push(`[basalt] sessionCookie "${name}": Secure is implied by the prefix (it was not before outside production). Test clients over plain http will not send it back; use an unprefixed name outside production, or set secure explicitly (secure: true silences this).`);
256
259
  }
@@ -324,6 +327,7 @@ export class Auth {
324
327
  tokenVersions;
325
328
  enumerationSafeRegister;
326
329
  registerPolicy;
330
+ tokenClaims;
327
331
  constructor(options) {
328
332
  this.users = options.users;
329
333
  this.secret = options.secret;
@@ -377,6 +381,7 @@ export class Auth {
377
381
  this.tokenVersions = options.tokenVersions;
378
382
  this.enumerationSafeRegister = options.enumerationSafeRegister ?? true;
379
383
  this.registerPolicy = options.registerPolicy;
384
+ this.tokenClaims = options.tokenClaims;
380
385
  }
381
386
  /**
382
387
  * Trusted, server-side account creation (seeding, a back-office, a flow that
@@ -546,7 +551,8 @@ export class Auth {
546
551
  amr.push('mfa');
547
552
  }
548
553
  async finishSocialLogin(user, created, amr) {
549
- const tokens = await this.issueTokens(user.id, undefined, amr);
554
+ const claims = await this.customClaims(user, 'social', amr);
555
+ const tokens = await this.issueTokens(user.id, undefined, amr, claims);
550
556
  await this.hooks?.emit('auth:login', { user: publicUser(user) });
551
557
  return { user: publicUser(user), tokens, created, amr };
552
558
  }
@@ -692,10 +698,12 @@ export class Auth {
692
698
  }
693
699
  amr.push('mfa');
694
700
  }
701
+ // Before the throttle is reset: a throwing tokenClaims fails the login closed.
702
+ const claims = await this.customClaims(user, 'login', amr);
695
703
  await this.throttle?.reset(key);
696
704
  if (ipKey)
697
705
  await this.ipThrottle?.release(ipKey);
698
- const tokens = await this.issueTokens(user.id, undefined, amr);
706
+ const tokens = await this.issueTokens(user.id, undefined, amr, claims);
699
707
  await this.hooks?.emit('auth:login', { user: publicUser(user) });
700
708
  return { user: publicUser(user), tokens, amr };
701
709
  }
@@ -714,16 +722,21 @@ export class Auth {
714
722
  if (Date.now() >= record.expiresAt)
715
723
  throw new RefreshInvalidError();
716
724
  // A deleted account must not keep minting tokens from a leftover refresh token.
717
- if (!(await this.users.findById(record.userId))) {
725
+ const user = await this.users.findById(record.userId);
726
+ if (!user) {
718
727
  await this.refreshTokens.revokeFamily(record.familyId);
719
728
  throw new RefreshInvalidError();
720
729
  }
730
+ const amr = amrOfFamily(record.familyId);
731
+ // Re-derived before the token is consumed: a throwing tokenClaims leaves
732
+ // the refresh token usable rather than burning the client's session.
733
+ const claims = await this.customClaims(user, 'refresh', amr);
721
734
  // Compare-and-swap: `false` means another caller consumed this exact token
722
735
  // between our read and this write — the very race reuse detection exists for.
723
736
  if ((await this.refreshTokens.markUsed(hashed)) === false) {
724
737
  return this.reuseDetected(record.userId, record.familyId);
725
738
  }
726
- const pair = await this.issueTokens(record.userId, record.familyId, amrOfFamily(record.familyId));
739
+ const pair = await this.issueTokens(record.userId, record.familyId, amr, claims);
727
740
  // The consumed token is the witness that the family is still alive:
728
741
  // revokeFamily/revokeAllForUser delete every row of it. If a concurrent
729
742
  // revocation (a reuse loser, a logout, a logout-everywhere) ran between our
@@ -1129,7 +1142,19 @@ export class Auth {
1129
1142
  throw new AuthTokenInvalidError(); // user vanished between issue and consume
1130
1143
  return user;
1131
1144
  }
1132
- async issueTokens(userId, family, amr) {
1145
+ /** The app's {@link AuthOptions.tokenClaims} for this sign-in, validated. */
1146
+ async customClaims(user, reason, amr) {
1147
+ if (!this.tokenClaims)
1148
+ return {};
1149
+ const request = tryCtx();
1150
+ const claims = await this.tokenClaims(publicUser(user), {
1151
+ reason,
1152
+ ...(amr && isAmr(amr) ? { amr: [...amr] } : {}),
1153
+ ...(request !== undefined ? { request } : {}),
1154
+ });
1155
+ return checkCustomClaims(claims);
1156
+ }
1157
+ async issueTokens(userId, family, amr, claims = {}) {
1133
1158
  // A new family records the login's authentication methods in its id, so
1134
1159
  // every rotation carries them forward without a store schema change.
1135
1160
  const familyId = family ?? (amr && isAmr(amr) ? `${randomUUID()}.${amr.join('+')}` : randomUUID());
@@ -1143,7 +1168,7 @@ export class Auth {
1143
1168
  });
1144
1169
  const tv = this.tokenVersions ? await this.tokenVersions.get(userId) : undefined;
1145
1170
  return {
1146
- accessToken: signJwt({ sub: userId, ...(tv !== undefined ? { tv } : {}), ...(amr && isAmr(amr) ? { amr } : {}) }, { secret: this.secret, expiresIn: this.accessTtl }),
1171
+ accessToken: signJwt({ ...claims, sub: userId, ...(tv !== undefined ? { tv } : {}), ...(amr && isAmr(amr) ? { amr } : {}) }, { secret: this.secret, expiresIn: this.accessTtl }),
1147
1172
  refreshToken,
1148
1173
  };
1149
1174
  }
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export { ScryptPasswordHasher, type PasswordHasher } from './hashing.js';
2
2
  export { signJwt, verifyJwt, TokenInvalidError, TokenExpiredError, type JwtClaims, } from './jwt.js';
3
- export { MemoryUserSource, MemorySessionStore, MemoryRefreshTokenStore, MemoryAuthTokenStore, MemoryApiKeyStore, MemoryMfaStore, MemoryTokenVersionStore, MemoryAccountLinkStore, type AccountLink, type AccountLinkStore, type TokenVersionStore, type AuthUser, type PublicUser, type UserSource, type UserPatch, type NewUser, type SessionStore, type SessionRecord, type RefreshTokenStore, type RefreshRecord, type AuthTokenStore, type AuthTokenRecord, type AuthTokenPurpose, type ApiKeyStore, type ApiKeyRecord, type ApiKeyInfo, type ApiKeyFilter, type MfaStore, type MfaRecord, } from './stores.js';
3
+ export { MemoryUserSource, MemorySessionStore, MemoryRefreshTokenStore, MemoryAuthTokenStore, MemoryApiKeyStore, MemoryMfaStore, MemoryTokenVersionStore, MemoryAccountLinkStore, type AccountLink, type AccountLinkStore, type TokenVersionStore, type AuthUser, type PublicUser, type UserSource, type UserPatch, type NewUser, type SessionStore, type SessionRecord, type RefreshTokenStore, type RefreshRecord, type AuthTokenStore, type AuthTokenRecord, type AuthTokenPurpose, type ApiKeyStore, type ApiKeyRecord, type ApiKeyInfo, type ApiKeyFilter, type ApiKeyPatch, type ApiKeyUpdateOptions, type MfaStore, type MfaRecord, } from './stores.js';
4
4
  declare module '@basaltkit/http' {
5
5
  interface RouteMeta {
6
6
  /** `true` requires a session; `false` opts a route out. */
@@ -22,7 +22,8 @@ export { Auth, publicUser, InvalidCredentialsError, EmailTakenError, WeakJwtSecr
22
22
  export { base32Encode, base32Decode, generateTotpSecret, totp, verifyTotp, matchTotpStep, otpauthUri, type TotpOptions, type VerifyTotpOptions, type OtpauthUriInput, } from './totp.js';
23
23
  export { SecretBox, SecretBoxKeyError, SecretUnreadableError, type SecretBoxKey, type SecretBoxOptions, type SecretBoxLegacyOptions, type SecretContext, } from './secret-box.js';
24
24
  export { authPlugin, AUTH, CsrfRejectedError, type AuthPluginOptions, type CsrfOptions } from './plugin.js';
25
- export { ApiKeys, ApiKeyExpirationError, ApiKeyOptionsError, DEFAULT_API_KEY_TOUCH_EVERY_MS, ScopeRequiredError, scopesSatisfy, type ApiKeysOptions, type IssueApiKeyInput, type ApiKeyContext, } from './apikeys.js';
25
+ export { tenantBoundTokens, RESERVED_TOKEN_CLAIMS, ReservedTokenClaimError, TokenClaimsRejectedError, type TenantBoundTokensOptions, type TokenClaimsContext, type TokenClaimsFn, type TokenClaimsReason, type VerifyClaimsFn, } from './token-claims.js';
26
+ export { ApiKeys, ApiKeyExpirationError, ApiKeyOptionsError, ApiKeyNotFoundError, ApiKeyInputError, ApiKeyConflictError, ApiKeyStoreUnsupportedError, ApiKeyIpNotAllowedError, DEFAULT_API_KEY_TOUCH_EVERY_MS, MAX_API_KEY_ROTATION_GRACE_MS, API_KEY_ALLOWED_IPS_MAX, API_KEY_META_LIMITS, ScopeRequiredError, scopesSatisfy, type ApiKeysOptions, type IssueApiKeyInput, type UpdateApiKeyInput, type RotateApiKeyOptions, type ListApiKeysOptions, type AuthenticateApiKeyOptions, type ApiKeyAuthResult, type ApiKeyUpdatedField, type ApiKeyContext, } from './apikeys.js';
26
27
  export { apiKeysPlugin, API_KEYS, ApiKeyTenantMismatchError, ApiKeyNotAllowedError, ApiKeyAmbiguousError, ApiKeyInvalidError, type ApiKeysPluginOptions, } from './apikeys-plugin.js';
27
28
  export { authRoutes, apiKeyRoutes, mfaRoutes, DEFAULT_AUTH_RATE_LIMIT, ACCOUNT_META, MAX_EMAIL_LENGTH, MAX_PASSWORD_LENGTH, type AuthRoutesOptions, type PasswordPolicy, type RegisterOption, } from './routes.js';
28
29
  export { OAuth, googleProvider, githubProvider, oidcProvider, discoverOidcProvider, stripTrailingSlashes, OAuthProviderUnknownError, OAuthStateInvalidError, OAuthExchangeError, OAuthProviderConfigError, type OAuthProvider, type OAuthProfile, type OAuthOptions, } from './oauth.js';
package/dist/index.js CHANGED
@@ -5,7 +5,8 @@ export { Auth, publicUser, InvalidCredentialsError, EmailTakenError, WeakJwtSecr
5
5
  export { base32Encode, base32Decode, generateTotpSecret, totp, verifyTotp, matchTotpStep, otpauthUri, } from './totp.js';
6
6
  export { SecretBox, SecretBoxKeyError, SecretUnreadableError, } from './secret-box.js';
7
7
  export { authPlugin, AUTH, CsrfRejectedError } from './plugin.js';
8
- export { ApiKeys, ApiKeyExpirationError, ApiKeyOptionsError, DEFAULT_API_KEY_TOUCH_EVERY_MS, ScopeRequiredError, scopesSatisfy, } from './apikeys.js';
8
+ export { tenantBoundTokens, RESERVED_TOKEN_CLAIMS, ReservedTokenClaimError, TokenClaimsRejectedError, } from './token-claims.js';
9
+ export { ApiKeys, ApiKeyExpirationError, ApiKeyOptionsError, ApiKeyNotFoundError, ApiKeyInputError, ApiKeyConflictError, ApiKeyStoreUnsupportedError, ApiKeyIpNotAllowedError, DEFAULT_API_KEY_TOUCH_EVERY_MS, MAX_API_KEY_ROTATION_GRACE_MS, API_KEY_ALLOWED_IPS_MAX, API_KEY_META_LIMITS, ScopeRequiredError, scopesSatisfy, } from './apikeys.js';
9
10
  export { apiKeysPlugin, API_KEYS, ApiKeyTenantMismatchError, ApiKeyNotAllowedError, ApiKeyAmbiguousError, ApiKeyInvalidError, } from './apikeys-plugin.js';
10
11
  export { authRoutes, apiKeyRoutes, mfaRoutes, DEFAULT_AUTH_RATE_LIMIT, ACCOUNT_META, MAX_EMAIL_LENGTH, MAX_PASSWORD_LENGTH, } from './routes.js';
11
12
  export { OAuth, googleProvider, githubProvider, oidcProvider, discoverOidcProvider, stripTrailingSlashes, OAuthProviderUnknownError, OAuthStateInvalidError, OAuthExchangeError, OAuthProviderConfigError, } from './oauth.js';
@@ -0,0 +1,22 @@
1
+ /** Maximum entries in one key's `allowedIps`. */
2
+ export declare const API_KEY_ALLOWED_IPS_MAX = 32;
3
+ /** Why an allowlist was refused; `ApiKeys` wraps it in `ApiKeyInputError`. */
4
+ export declare class AllowlistError extends Error {
5
+ }
6
+ /**
7
+ * Validates and canonicalises a key's `allowedIps`. Duplicates are dropped.
8
+ * Throws {@link AllowlistError}.
9
+ */
10
+ export declare function normalizeAllowedIps(entries: unknown): string[];
11
+ /**
12
+ * A request address as an adapter reports it, normalised for a check: brackets
13
+ * and a `%zone` suffix stripped, IPv4-mapped IPv6 as IPv4. `undefined` when it
14
+ * is not an address at all.
15
+ */
16
+ export declare function normalizeRequestIp(ip: string | undefined): string | undefined;
17
+ /**
18
+ * Whether `ip` is inside a (canonical) allowlist. An empty or absent list
19
+ * allows any address; a non-empty one refuses an unknown or unparseable
20
+ * address — it fails closed. Built per check: at most 32 entries, no cache.
21
+ */
22
+ export declare function ipAllowed(allowedIps: readonly string[] | undefined, ip: string | undefined): boolean;