@basaltkit/auth 4.2.0 → 5.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/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
@@ -163,18 +163,17 @@ export interface SessionCookieOptions {
163
163
  *
164
164
  * A `__Host-` or `__Secure-` name (matched case-insensitively) implies
165
165
  * `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.
166
+ * cookie without `Secure`. An explicit `false` on such a name refuses the
167
+ * boot with `AUTH_SESSION_COOKIE_INVALID` ({@link SessionCookieConfigError}).
169
168
  */
170
169
  secure?: boolean;
171
170
  }
172
171
  /**
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`.
172
+ * The session cookie options violate the rules of the cookie name's prefix
173
+ * (`__Secure-` without `Secure`, `__Host-` without `Secure` or with a path
174
+ * other than `/`). Browsers drop such a cookie, so every login would
175
+ * "succeed" without a session; thrown at boot with code
176
+ * `AUTH_SESSION_COOKIE_INVALID`.
178
177
  */
179
178
  export declare class SessionCookieConfigError extends BasaltError {
180
179
  readonly status = 500;
package/dist/auth.js CHANGED
@@ -184,11 +184,11 @@ export const isAmr = (value) => Array.isArray(value) &&
184
184
  value.length <= 8 &&
185
185
  value.every((v) => typeof v === 'string' && AMR_VALUE.test(v));
186
186
  /**
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`.
187
+ * The session cookie options violate the rules of the cookie name's prefix
188
+ * (`__Secure-` without `Secure`, `__Host-` without `Secure` or with a path
189
+ * other than `/`). Browsers drop such a cookie, so every login would
190
+ * "succeed" without a session; thrown at boot with code
191
+ * `AUTH_SESSION_COOKIE_INVALID`.
192
192
  */
193
193
  export class SessionCookieConfigError extends BasaltError {
194
194
  status = 500;
@@ -207,7 +207,8 @@ export class SessionIdleConfigError extends BasaltError {
207
207
  * Session cookie options already warned about. Keyed on the `sessionCookie`
208
208
  * object, not on the `Auth` instance: `authPlugin` validates the options at
209
209
  * registration and the `AUTH` singleton resolves them again with the same
210
- * `sessionCookie` reference, so one configuration warns once.
210
+ * `sessionCookie` reference, so one configuration warns once. A refusal is
211
+ * never deduplicated: it throws on every resolution.
211
212
  */
212
213
  const warnedSessionCookies = new WeakSet();
213
214
  /**
@@ -219,13 +220,13 @@ const warnedSessionCookies = new WeakSet();
219
220
  * "succeed" without a session.
220
221
  *
221
222
  * 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.
223
+ * (`secure: false`, a `__Host-` path other than `/`) throw
224
+ * {@link SessionCookieConfigError}: a cookie the browser drops is a broken
225
+ * login, so it fails closed at boot rather than at the first sign-in.
224
226
  *
225
227
  * Warnings are independent, each emitted once per `sessionCookie` object:
226
- * - the cookie is dropped by browsers because of its prefix (refused next major);
227
228
  * - Secure is implied by the prefix where it was not before (outside
228
- * production, so the emission differs from earlier versions);
229
+ * production, so the emission differs from releases before auth 4.2);
229
230
  * - `SameSite=None` without `Secure`, which browsers also drop.
230
231
  */
231
232
  function resolveSessionCookie(options) {
@@ -241,16 +242,17 @@ function resolveSessionCookie(options) {
241
242
  sameSite: options?.sameSite ?? 'Lax',
242
243
  secure: options?.secure ?? (prefixed ? true : production),
243
244
  };
245
+ const problems = [];
246
+ if (prefixed && !resolved.secure)
247
+ problems.push('secure: true');
248
+ if (host && resolved.path !== '/')
249
+ problems.push('path "/"');
250
+ if (problems.length > 0) {
251
+ throw new SessionCookieConfigError(`sessionCookie "${name}" requires ${problems.join(' and ')}: browsers drop a ${host ? '__Host-' : '__Secure-'} cookie without it. ` +
252
+ `Drop the contradicting option, or use an unprefixed name outside production (name: isProd ? '__Host-sid' : 'sid').`);
253
+ }
244
254
  if (options && !warnedSessionCookies.has(options)) {
245
255
  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
256
  if (prefixed && options.secure === undefined && !production) {
255
257
  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
258
  }
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,7 @@ 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 { 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
26
  export { apiKeysPlugin, API_KEYS, ApiKeyTenantMismatchError, ApiKeyNotAllowedError, ApiKeyAmbiguousError, ApiKeyInvalidError, type ApiKeysPluginOptions, } from './apikeys-plugin.js';
27
27
  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
28
  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,7 @@ 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 { 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
9
  export { apiKeysPlugin, API_KEYS, ApiKeyTenantMismatchError, ApiKeyNotAllowedError, ApiKeyAmbiguousError, ApiKeyInvalidError, } from './apikeys-plugin.js';
10
10
  export { authRoutes, apiKeyRoutes, mfaRoutes, DEFAULT_AUTH_RATE_LIMIT, ACCOUNT_META, MAX_EMAIL_LENGTH, MAX_PASSWORD_LENGTH, } from './routes.js';
11
11
  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;
@@ -0,0 +1,118 @@
1
+ import { BlockList, isIP } from 'node:net';
2
+ /** Maximum entries in one key's `allowedIps`. */
3
+ export const API_KEY_ALLOWED_IPS_MAX = 32;
4
+ /** Why an allowlist was refused; `ApiKeys` wraps it in `ApiKeyInputError`. */
5
+ export class AllowlistError extends Error {
6
+ }
7
+ const V4_MAPPED = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i;
8
+ /** IPv4-mapped IPv6 (`::ffff:a.b.c.d`) as plain IPv4; IPv6 lower-cased. Assumes a valid address. */
9
+ const canonicalAddress = (address) => {
10
+ const mapped = V4_MAPPED.exec(address);
11
+ if (mapped && isIP(mapped[1]) === 4)
12
+ return mapped[1];
13
+ return isIP(address) === 6 ? address.toLowerCase() : address;
14
+ };
15
+ /** The 128-bit (or 32-bit) value of an address. */
16
+ function toBigInt(address, family) {
17
+ if (family === 4)
18
+ return address.split('.').reduce((n, part) => (n << 8n) | BigInt(Number(part)), 0n);
19
+ // Expand `::` and an embedded dotted-quad tail.
20
+ let text = address;
21
+ const dotted = /(\d{1,3}(?:\.\d{1,3}){3})$/.exec(text);
22
+ if (dotted) {
23
+ const v4 = toBigInt(dotted[1], 4);
24
+ text = `${text.slice(0, -dotted[1].length)}${(v4 >> 16n).toString(16)}:${(v4 & 0xffffn).toString(16)}`;
25
+ }
26
+ const [head = '', tail] = text.split('::');
27
+ const left = head ? head.split(':') : [];
28
+ const right = tail !== undefined && tail !== '' ? tail.split(':') : [];
29
+ const groups = tail === undefined ? left : [...left, ...Array(8 - left.length - right.length).fill('0'), ...right];
30
+ return groups.reduce((n, group) => (n << 16n) | BigInt(parseInt(group, 16)), 0n);
31
+ }
32
+ /**
33
+ * Validates and canonicalises one allowlist entry: an address or an
34
+ * `address/prefix` network. Zone ids are refused, and so is a CIDR whose
35
+ * address has host bits set (`10.0.0.5/8`) — a typo should surface, not be
36
+ * silently masked.
37
+ */
38
+ function canonicalEntry(raw) {
39
+ if (typeof raw !== 'string' || raw.length === 0 || raw.length > 64)
40
+ throw new AllowlistError(`invalid entry ${JSON.stringify(raw)}`);
41
+ if (raw.includes('%'))
42
+ throw new AllowlistError(`zone ids are not allowed (${raw})`);
43
+ const slash = raw.indexOf('/');
44
+ const addressPart = slash === -1 ? raw : raw.slice(0, slash);
45
+ if (isIP(addressPart) === 0)
46
+ throw new AllowlistError(`not an IP address: ${raw}`);
47
+ const address = canonicalAddress(addressPart);
48
+ const family = isIP(address);
49
+ if (slash === -1)
50
+ return address;
51
+ const prefixText = raw.slice(slash + 1);
52
+ const bits = family === 4 ? 32 : 128;
53
+ // A mapped address keeps its IPv6 prefix length relative to 128 bits.
54
+ const mappedShift = family === 4 && isIP(addressPart) === 6 ? 96 : 0;
55
+ if (!/^\d{1,3}$/.test(prefixText))
56
+ throw new AllowlistError(`invalid prefix length: ${raw}`);
57
+ const rawPrefix = Number(prefixText);
58
+ const prefix = rawPrefix - mappedShift;
59
+ if (rawPrefix > (mappedShift ? 128 : bits) || prefix < 0)
60
+ throw new AllowlistError(`invalid prefix length: ${raw}`);
61
+ const hostBits = BigInt(bits - prefix);
62
+ if (hostBits > 0n && (toBigInt(address, family) & ((1n << hostBits) - 1n)) !== 0n) {
63
+ throw new AllowlistError(`${raw} is not a network address (host bits are set)`);
64
+ }
65
+ return `${address}/${prefix}`;
66
+ }
67
+ /**
68
+ * Validates and canonicalises a key's `allowedIps`. Duplicates are dropped.
69
+ * Throws {@link AllowlistError}.
70
+ */
71
+ export function normalizeAllowedIps(entries) {
72
+ if (!Array.isArray(entries))
73
+ throw new AllowlistError('allowedIps must be an array');
74
+ if (entries.length > API_KEY_ALLOWED_IPS_MAX) {
75
+ throw new AllowlistError(`allowedIps holds at most ${API_KEY_ALLOWED_IPS_MAX} entries`);
76
+ }
77
+ return [...new Set(entries.map(canonicalEntry))];
78
+ }
79
+ /**
80
+ * A request address as an adapter reports it, normalised for a check: brackets
81
+ * and a `%zone` suffix stripped, IPv4-mapped IPv6 as IPv4. `undefined` when it
82
+ * is not an address at all.
83
+ */
84
+ export function normalizeRequestIp(ip) {
85
+ if (typeof ip !== 'string' || ip.length === 0)
86
+ return undefined;
87
+ let text = ip.trim();
88
+ if (text.startsWith('[') && text.endsWith(']'))
89
+ text = text.slice(1, -1);
90
+ const zone = text.indexOf('%');
91
+ if (zone !== -1)
92
+ text = text.slice(0, zone);
93
+ return isIP(text) === 0 ? undefined : canonicalAddress(text);
94
+ }
95
+ /**
96
+ * Whether `ip` is inside a (canonical) allowlist. An empty or absent list
97
+ * allows any address; a non-empty one refuses an unknown or unparseable
98
+ * address — it fails closed. Built per check: at most 32 entries, no cache.
99
+ */
100
+ export function ipAllowed(allowedIps, ip) {
101
+ if (!allowedIps || allowedIps.length === 0)
102
+ return true;
103
+ const address = normalizeRequestIp(ip);
104
+ if (address === undefined)
105
+ return false;
106
+ const list = new BlockList();
107
+ for (const entry of allowedIps) {
108
+ const slash = entry.indexOf('/');
109
+ if (slash === -1) {
110
+ list.addAddress(entry, isIP(entry) === 6 ? 'ipv6' : 'ipv4');
111
+ }
112
+ else {
113
+ const network = entry.slice(0, slash);
114
+ list.addSubnet(network, Number(entry.slice(slash + 1)), isIP(network) === 6 ? 'ipv6' : 'ipv4');
115
+ }
116
+ }
117
+ return list.check(address, isIP(address) === 6 ? 'ipv6' : 'ipv4');
118
+ }
package/dist/routes.d.ts CHANGED
@@ -81,10 +81,23 @@ export declare const DEFAULT_AUTH_RATE_LIMIT: {
81
81
  */
82
82
  export declare function authRoutes(options?: AuthRoutesOptions): BasaltRoute[];
83
83
  /**
84
- * CRUD routes for API keys, all requiring a logged-in user (`meta.auth`). Keys
85
- * are scoped to the caller's tenant (`ctx().tenant`) and user; a caller only
86
- * ever sees or revokes keys within that scope. Register alongside
87
- * {@link authRoutes} and pair with `apiKeysPlugin`.
84
+ * Self-service routes for API keys, all requiring a logged-in user
85
+ * (`meta.auth`) and refusing API keys (`meta.apiKey: false`, so a key can never
86
+ * mint, extend, rotate or unrestrict a key). Keys are scoped to the caller's
87
+ * tenant (`ctx().tenant`) and user; a caller only ever sees or changes keys
88
+ * within that scope, anything else is 404 `AUTH_APIKEY_NOT_FOUND`. Service keys
89
+ * (`serviceId`) have no user, so they are never reachable here: mint and manage
90
+ * them with `ApiKeys` behind the app's own permission check.
91
+ *
92
+ * - `POST /apikeys` issues a key (the plaintext `key` is returned once);
93
+ * - `GET /apikeys[?includeExpired=true]` lists live keys;
94
+ * - `PATCH /apikeys/:id` changes `name`, `scopes`, `expiresAt` (`null` = never),
95
+ * `allowedIps` and `meta` in one write;
96
+ * - `POST /apikeys/:id/rotate` replaces the secret (`graceMs` keeps the old one
97
+ * working that long) and returns the new `key` once;
98
+ * - `DELETE /apikeys/:id` revokes.
99
+ *
100
+ * Register alongside {@link authRoutes} and pair with `apiKeysPlugin`.
88
101
  */
89
102
  export declare function apiKeyRoutes(): BasaltRoute[];
90
103
  /**