@basaltkit/auth 4.1.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/auth.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
2
- import { BasaltError, isProductionEnvironment, parseDuration } from '@basaltkit/core';
2
+ import { BasaltError, isProductionEnvironment, parseDuration, tryCtx } from '@basaltkit/core';
3
3
  import { ScryptPasswordHasher } from './hashing.js';
4
4
  import { LoginThrottle } from './throttle.js';
5
5
  import { signJwt, verifyJwt } from './jwt.js';
@@ -151,6 +151,24 @@ const isLinkPart = (value) => typeof value === 'string' && value.length > 0 && v
151
151
  * `bob@acme.test` are one account.
152
152
  */
153
153
  export const canonicalEmail = (email) => email.trim().toLowerCase();
154
+ /**
155
+ * Account creation is not open here: the register route is configured
156
+ * `register: 'closed'`, or a {@link RegisterPolicy} refused a social / SSO
157
+ * login that would have created a new account. (A policy refusing the public
158
+ * register route never surfaces this — that route answers the same 202 as a
159
+ * success, so it cannot reveal who was invited.)
160
+ */
161
+ export class RegistrationClosedError extends BasaltError {
162
+ status = 404;
163
+ constructor() {
164
+ super('AUTH_REGISTRATION_CLOSED', 'Registration is not available here.');
165
+ }
166
+ }
167
+ /** The tenant id of the current request, read structurally (auth never imports tenancy). */
168
+ const currentTenantId = () => {
169
+ const id = tryCtx()?.tenant?.id;
170
+ return typeof id === 'string' && id !== '' ? id : undefined;
171
+ };
154
172
  /** An MFA action needed an enrollment that doesn't exist. */
155
173
  export class MfaNotEnrolledError extends BasaltError {
156
174
  status = 400;
@@ -165,6 +183,118 @@ export const isAmr = (value) => Array.isArray(value) &&
165
183
  value.length > 0 &&
166
184
  value.length <= 8 &&
167
185
  value.every((v) => typeof v === 'string' && AMR_VALUE.test(v));
186
+ /**
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
+ */
193
+ export class SessionCookieConfigError extends BasaltError {
194
+ status = 500;
195
+ constructor(message) {
196
+ super('AUTH_SESSION_COOKIE_INVALID', message);
197
+ }
198
+ }
199
+ /** `sessionIdleTtl` cannot be honoured as configured. */
200
+ export class SessionIdleConfigError extends BasaltError {
201
+ status = 500;
202
+ constructor(message) {
203
+ super('AUTH_SESSION_IDLE_CONFIG_INVALID', message);
204
+ }
205
+ }
206
+ /**
207
+ * Session cookie options already warned about. Keyed on the `sessionCookie`
208
+ * object, not on the `Auth` instance: `authPlugin` validates the options at
209
+ * registration and the `AUTH` singleton resolves them again with the same
210
+ * `sessionCookie` reference, so one configuration warns once. A refusal is
211
+ * never deduplicated: it throws on every resolution.
212
+ */
213
+ const warnedSessionCookies = new WeakSet();
214
+ /**
215
+ * Resolves the session cookie options against the cookie-prefix rules
216
+ * browsers apply (RFC 6265bis): `__Secure-` needs `Secure`; `__Host-` needs
217
+ * `Secure` and `Path=/` (and no `Domain`, which Basalt never sets). Prefixes
218
+ * match case-insensitively, as in current browsers. A violating cookie is not
219
+ * an error in the browser, it is silently dropped, so every login would
220
+ * "succeed" without a session.
221
+ *
222
+ * An unset `secure` on a prefixed name takes `true`. Contradicting values
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.
226
+ *
227
+ * Warnings are independent, each emitted once per `sessionCookie` object:
228
+ * - Secure is implied by the prefix where it was not before (outside
229
+ * production, so the emission differs from releases before auth 4.2);
230
+ * - `SameSite=None` without `Secure`, which browsers also drop.
231
+ */
232
+ function resolveSessionCookie(options) {
233
+ const name = options?.name ?? 'basalt_session';
234
+ const lowerName = name.toLowerCase();
235
+ const host = lowerName.startsWith('__host-');
236
+ const prefixed = host || lowerName.startsWith('__secure-');
237
+ const production = isProductionEnvironment();
238
+ const resolved = {
239
+ name,
240
+ path: options?.path ?? '/',
241
+ httpOnly: options?.httpOnly ?? true,
242
+ sameSite: options?.sameSite ?? 'Lax',
243
+ secure: options?.secure ?? (prefixed ? true : production),
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
+ }
254
+ if (options && !warnedSessionCookies.has(options)) {
255
+ const warnings = [];
256
+ if (prefixed && options.secure === undefined && !production) {
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).`);
258
+ }
259
+ if (!prefixed && resolved.sameSite === 'None' && !resolved.secure) {
260
+ warnings.push(`[basalt] sessionCookie "${name}": SameSite=None without Secure - browsers drop it; set secure: true or use SameSite "Lax".`);
261
+ }
262
+ if (warnings.length > 0) {
263
+ warnedSessionCookies.add(options);
264
+ for (const warning of warnings)
265
+ console.warn(warning);
266
+ }
267
+ }
268
+ return resolved;
269
+ }
270
+ /** Longest gap between two `touch` writes of one session: one minute. */
271
+ const MAX_SESSION_TOUCH_INTERVAL_MS = 60_000;
272
+ /**
273
+ * Resolves `sessionIdleTtl` to milliseconds, or undefined when unset. Fails
274
+ * when it is not a positive duration or the session store cannot record
275
+ * activity (`touch`). `sessions` undefined means the built-in memory store.
276
+ */
277
+ function resolveSessionIdle(idle, sessions) {
278
+ if (idle === undefined)
279
+ return undefined;
280
+ const idleMs = parseDuration(idle);
281
+ if (!Number.isFinite(idleMs) || idleMs <= 0) {
282
+ throw new SessionIdleConfigError('sessionIdleTtl must be a positive duration.');
283
+ }
284
+ if (sessions !== undefined && typeof sessions.touch !== 'function') {
285
+ throw new SessionIdleConfigError('sessionIdleTtl needs a session store that implements touch(id, at) — the built-in memory, auth-sqlite and auth-prisma (trackSessionActivity: true) stores do.');
286
+ }
287
+ return idleMs;
288
+ }
289
+ /**
290
+ * Validates the session options the way `new Auth()` does, without building
291
+ * it — so `authPlugin` refuses a bad configuration at registration rather
292
+ * than on the first request. Pure: no I/O.
293
+ */
294
+ export function assertSessionOptions(options) {
295
+ resolveSessionCookie(options.sessionCookie);
296
+ resolveSessionIdle(options.sessionIdleTtl, options.sessions);
297
+ }
168
298
  export const publicUser = (user) => ({
169
299
  id: user.id,
170
300
  email: user.email,
@@ -179,6 +309,8 @@ export class Auth {
179
309
  accessTtl;
180
310
  refreshTtl;
181
311
  sessionTtl;
312
+ sessionIdleMs;
313
+ sessionTouchEveryMs;
182
314
  sessionCookie;
183
315
  hooks;
184
316
  throttle;
@@ -193,6 +325,7 @@ export class Auth {
193
325
  mfaBox;
194
326
  tokenVersions;
195
327
  enumerationSafeRegister;
328
+ registerPolicy;
196
329
  constructor(options) {
197
330
  this.users = options.users;
198
331
  this.secret = options.secret;
@@ -210,13 +343,9 @@ export class Auth {
210
343
  this.accessTtl = options.accessTtl ?? '15m';
211
344
  this.refreshTtl = options.refreshTtl ?? '30d';
212
345
  this.sessionTtl = options.sessionTtl ?? '30d';
213
- this.sessionCookie = {
214
- name: options.sessionCookie?.name ?? 'basalt_session',
215
- path: options.sessionCookie?.path ?? '/',
216
- httpOnly: options.sessionCookie?.httpOnly ?? true,
217
- sameSite: options.sessionCookie?.sameSite ?? 'Lax',
218
- secure: options.sessionCookie?.secure ?? isProductionEnvironment(),
219
- };
346
+ this.sessionIdleMs = resolveSessionIdle(options.sessionIdleTtl, this.sessions);
347
+ this.sessionTouchEveryMs = Math.min(MAX_SESSION_TOUCH_INTERVAL_MS, (this.sessionIdleMs ?? 0) / 4);
348
+ this.sessionCookie = resolveSessionCookie(options.sessionCookie);
220
349
  this.hooks = options.hooks;
221
350
  const shared = options.throttleStore ? { store: options.throttleStore } : {};
222
351
  this.throttle =
@@ -249,18 +378,63 @@ export class Auth {
249
378
  : undefined;
250
379
  this.tokenVersions = options.tokenVersions;
251
380
  this.enumerationSafeRegister = options.enumerationSafeRegister ?? true;
381
+ this.registerPolicy = options.registerPolicy;
252
382
  }
253
- async register(rawEmail, password) {
383
+ /**
384
+ * Trusted, server-side account creation (seeding, a back-office, a flow that
385
+ * proved the address before creating the account). Throws
386
+ * {@link EmailTakenError} on a duplicate and is never gated by a
387
+ * {@link RegisterPolicy}. `emailVerified: true` creates the account already
388
+ * verified; `auth:registered` then carries the final state, so a mail hook
389
+ * can decide "unverified → send the verification link" on its own. Never
390
+ * forward this option from a request body.
391
+ *
392
+ * `emailVerified: true` needs a `UserSource` with `update()` — the same
393
+ * requirement as email verification. Without it this throws
394
+ * {@link UserUpdateUnsupportedError} **before** anything is written: whether
395
+ * `create()` persists the flag can only be learnt by writing the row, and a
396
+ * row that cannot be fixed afterwards would be a half-done registration
397
+ * (an unverified account that a retry reports as `EmailTakenError`).
398
+ */
399
+ async register(rawEmail, password, opts = {}) {
400
+ if (opts.emailVerified === true && typeof this.users.update !== 'function')
401
+ throw new UserUpdateUnsupportedError();
254
402
  const email = canonicalEmail(rawEmail);
255
403
  if (await this.users.findByEmail(email))
256
404
  throw new EmailTakenError();
257
- const user = await this.users.create({
258
- email,
259
- passwordHash: await this.hasher.hash(password),
260
- });
405
+ const user = await this.createUser(email, await this.hasher.hash(password), opts.emailVerified === true);
261
406
  await this.hooks?.emit('auth:registered', { user: publicUser(user) });
262
407
  return publicUser(user);
263
408
  }
409
+ /**
410
+ * Creates the row with the requested verification state. A custom
411
+ * `UserSource` written before `create()` took `emailVerified` may drop the
412
+ * flag: it is then set through `update()`.
413
+ *
414
+ * When the source can do neither (no `update()` and a `create()` that drops
415
+ * the flag), `onUnsupported` decides: `'throw'` fails loudly with
416
+ * {@link UserUpdateUnsupportedError} (trusted `register`, whose caller asked
417
+ * for a verified account and must hear it did not get one — `register`
418
+ * refuses a source without `update()` before calling this, so here it only
419
+ * fires for an `update()` that does not persist the flag); `'keep'` returns
420
+ * the row as it really is, unverified (social login — the row was just
421
+ * created by this call with an unusable password, so it is provably ours and
422
+ * must be linked and used, never left behind as an orphan that locks the
423
+ * provider account out on every later login).
424
+ */
425
+ async createUser(email, passwordHash, emailVerified, onUnsupported = 'throw') {
426
+ // Decided before anything is written, so the outcome never depends on
427
+ // how far a half-done create got.
428
+ const canPatch = typeof this.users.update === 'function';
429
+ let user = await this.users.create(emailVerified ? { email, passwordHash, emailVerified: true } : { email, passwordHash });
430
+ if (emailVerified && user.emailVerified !== true) {
431
+ if (canPatch)
432
+ user = (await this.users.update(user.id, { emailVerified: true })) ?? user;
433
+ if (user.emailVerified !== true && onUnsupported === 'throw')
434
+ throw new UserUpdateUnsupportedError();
435
+ }
436
+ return user;
437
+ }
264
438
  /**
265
439
  * Logs in an externally-authenticated user (e.g. from an OAuth provider) —
266
440
  * find-or-create. A new account is created **passwordless** (a random,
@@ -311,15 +485,22 @@ export class Auth {
311
485
  let user = await this.users.findByEmail(email);
312
486
  let created = false;
313
487
  if (!user) {
314
- user = await this.users.create({
315
- email,
316
- passwordHash: await this.hasher.hash(randomBytes(32).toString('hex')),
317
- });
488
+ // A social login is already an authenticated flow, so a refusal is said
489
+ // out loud (the provider vouched for the caller's address).
490
+ const tenantId = options.tenantId ?? currentTenantId();
491
+ if (this.registerPolicy && !(await this.registerPolicy(tenantId === undefined ? { email } : { email, tenantId }))) {
492
+ await this.hooks?.emit('auth:register_refused', { email, ...(tenantId !== undefined ? { tenantId } : {}), source: 'social' });
493
+ throw new RegistrationClosedError();
494
+ }
495
+ // Created with its final verification state, so `auth:registered`
496
+ // reports what the account really is. A source that cannot record the
497
+ // verification (no `update()`, a `create()` that drops the flag) keeps
498
+ // the account unverified rather than fail after the row exists: a
499
+ // half-done first login would leave an unlinked, unverified row that
500
+ // every later login refuses to adopt (`AUTH_SOCIAL_LINK_REFUSED`).
501
+ user = await this.createUser(email, await this.hasher.hash(randomBytes(32).toString('hex')), options.emailVerified === true, 'keep');
318
502
  created = true;
319
503
  await this.hooks?.emit('auth:registered', { user: publicUser(user) });
320
- if (options.emailVerified === true && this.users.update) {
321
- user = (await this.users.update(user.id, { emailVerified: true })) ?? user;
322
- }
323
504
  }
324
505
  else {
325
506
  if (options.emailVerified !== true)
@@ -401,9 +582,24 @@ export class Auth {
401
582
  *
402
583
  * With `enumerationSafeRegister: false` it throws {@link EmailTakenError} on a
403
584
  * duplicate instead (the classic, enumerable behavior).
585
+ *
586
+ * A {@link RegisterPolicy} (`opts.policy`, else `registerPolicy` of the
587
+ * options; `null` = open) is asked first. A refusal creates nothing, does the
588
+ * same hashing work and emits `auth:register_refused` — the caller sees the
589
+ * same outcome as a success, so the response never tells who was invited.
590
+ * Never creates a verified account.
404
591
  */
405
- async registerSafely(rawEmail, password) {
592
+ async registerSafely(rawEmail, password, opts = {}) {
406
593
  const email = canonicalEmail(rawEmail);
594
+ const policy = opts.policy === undefined ? this.registerPolicy : (opts.policy ?? undefined);
595
+ if (policy) {
596
+ const tenantId = opts.tenantId ?? currentTenantId();
597
+ if (!(await policy(tenantId === undefined ? { email } : { email, tenantId }))) {
598
+ await this.hasher.hash(password);
599
+ await this.hooks?.emit('auth:register_refused', { email, ...(tenantId !== undefined ? { tenantId } : {}), source: 'register' });
600
+ return;
601
+ }
602
+ }
407
603
  const existing = await this.users.findByEmail(email);
408
604
  if (existing) {
409
605
  if (!this.enumerationSafeRegister)
@@ -657,11 +853,33 @@ export class Auth {
657
853
  async sessionAuth(sessionId) {
658
854
  const { rawId, amr } = this.parseSessionId(sessionId);
659
855
  const session = await this.sessions.find(rawId);
856
+ if (session && !(await this.sessionStillActive(rawId, session)))
857
+ return null;
660
858
  const user = session ? await this.users.findById(session.userId) : null;
661
859
  if (!user)
662
860
  return null;
663
861
  return amr ? { user, amr } : { user };
664
862
  }
863
+ /**
864
+ * Applies the idle timeout: refuses (and deletes) a session idle for longer
865
+ * than `sessionIdleTtl`, otherwise records the activity, throttled. A no-op
866
+ * without `sessionIdleTtl`.
867
+ */
868
+ async sessionStillActive(rawId, session) {
869
+ const idleMs = this.sessionIdleMs;
870
+ if (idleMs === undefined)
871
+ return true;
872
+ const now = Date.now();
873
+ const lastSeenAt = session.lastSeenAt;
874
+ if (lastSeenAt !== undefined && now - lastSeenAt > idleMs) {
875
+ await this.sessions.delete(rawId);
876
+ return false;
877
+ }
878
+ if (lastSeenAt === undefined || now - lastSeenAt >= this.sessionTouchEveryMs) {
879
+ await this.sessions.touch?.(rawId, now);
880
+ }
881
+ return true;
882
+ }
665
883
  async logout(sessionId) {
666
884
  const { rawId } = this.parseSessionId(sessionId);
667
885
  const session = await this.sessions.find(rawId);
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 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. */
@@ -18,13 +18,13 @@ declare module '@basaltkit/http' {
18
18
  account?: boolean;
19
19
  }
20
20
  }
21
- export { Auth, publicUser, InvalidCredentialsError, EmailTakenError, WeakJwtSecretError, RefreshInvalidError, RefreshReusedError, AuthRequiredError, AuthTokenInvalidError, UserUpdateUnsupportedError, MfaRequiredError, MfaStepUpRequiredError, MfaEnrollmentRequiredError, MfaInvalidCodeError, MfaNotEnrolledError, MfaAlreadyEnabledError, SocialLinkRefusedError, AccountLinkConflictError, AccountEmailAmbiguousError, canonicalEmail, type AuthOptions, type SessionCookieOptions, type TokenPair, } from './auth.js';
21
+ export { Auth, publicUser, InvalidCredentialsError, EmailTakenError, WeakJwtSecretError, SessionCookieConfigError, SessionIdleConfigError, RefreshInvalidError, RefreshReusedError, AuthRequiredError, AuthTokenInvalidError, UserUpdateUnsupportedError, MfaRequiredError, MfaStepUpRequiredError, MfaEnrollmentRequiredError, MfaInvalidCodeError, MfaNotEnrolledError, MfaAlreadyEnabledError, SocialLinkRefusedError, AccountLinkConflictError, AccountEmailAmbiguousError, RegistrationClosedError, canonicalEmail, type AuthOptions, type RegisterPolicy, type SessionCookieOptions, type TokenPair, } from './auth.js';
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, ScopeRequiredError, scopesSatisfy, type ApiKeysOptions, type IssueApiKeyInput, type ApiKeyContext, } from './apikeys.js';
26
- export { apiKeysPlugin, API_KEYS, ApiKeyTenantMismatchError, ApiKeyNotAllowedError, ApiKeyAmbiguousError, type ApiKeysPluginOptions, } from './apikeys-plugin.js';
27
- export { authRoutes, apiKeyRoutes, mfaRoutes, DEFAULT_AUTH_RATE_LIMIT, ACCOUNT_META, MAX_EMAIL_LENGTH, MAX_PASSWORD_LENGTH, type AuthRoutesOptions, type PasswordPolicy, } from './routes.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
+ export { apiKeysPlugin, API_KEYS, ApiKeyTenantMismatchError, ApiKeyNotAllowedError, ApiKeyAmbiguousError, ApiKeyInvalidError, type ApiKeysPluginOptions, } from './apikeys-plugin.js';
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';
29
29
  export { oauthPlugin, oauthRoutes, OAUTH, type OAuthPluginOptions, type OAuthRoutesOptions, } from './oauth-plugin.js';
30
30
  export { LoginThrottle, MemoryThrottleStore, AccountLockedError, type LoginThrottleOptions, type MemoryThrottleStoreOptions, type ThrottleStore, type ThrottleWindow, } from './throttle.js';
package/dist/index.js CHANGED
@@ -1,12 +1,12 @@
1
1
  export { ScryptPasswordHasher } from './hashing.js';
2
2
  export { signJwt, verifyJwt, TokenInvalidError, TokenExpiredError, } from './jwt.js';
3
3
  export { MemoryUserSource, MemorySessionStore, MemoryRefreshTokenStore, MemoryAuthTokenStore, MemoryApiKeyStore, MemoryMfaStore, MemoryTokenVersionStore, MemoryAccountLinkStore, } from './stores.js';
4
- export { Auth, publicUser, InvalidCredentialsError, EmailTakenError, WeakJwtSecretError, RefreshInvalidError, RefreshReusedError, AuthRequiredError, AuthTokenInvalidError, UserUpdateUnsupportedError, MfaRequiredError, MfaStepUpRequiredError, MfaEnrollmentRequiredError, MfaInvalidCodeError, MfaNotEnrolledError, MfaAlreadyEnabledError, SocialLinkRefusedError, AccountLinkConflictError, AccountEmailAmbiguousError, canonicalEmail, } from './auth.js';
4
+ export { Auth, publicUser, InvalidCredentialsError, EmailTakenError, WeakJwtSecretError, SessionCookieConfigError, SessionIdleConfigError, RefreshInvalidError, RefreshReusedError, AuthRequiredError, AuthTokenInvalidError, UserUpdateUnsupportedError, MfaRequiredError, MfaStepUpRequiredError, MfaEnrollmentRequiredError, MfaInvalidCodeError, MfaNotEnrolledError, MfaAlreadyEnabledError, SocialLinkRefusedError, AccountLinkConflictError, AccountEmailAmbiguousError, RegistrationClosedError, canonicalEmail, } from './auth.js';
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, ScopeRequiredError, scopesSatisfy, } from './apikeys.js';
9
- export { apiKeysPlugin, API_KEYS, ApiKeyTenantMismatchError, ApiKeyNotAllowedError, ApiKeyAmbiguousError, } from './apikeys-plugin.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
+ 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';
12
12
  export { oauthPlugin, oauthRoutes, OAUTH, } from './oauth-plugin.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/plugin.d.ts CHANGED
@@ -25,6 +25,18 @@ declare module '@basaltkit/core' {
25
25
  'auth:register_existing_email': {
26
26
  email: string;
27
27
  };
28
+ /**
29
+ * A {@link RegisterPolicy} refused to create an account. Nothing was created.
30
+ * `source: 'register'` came through the public register route, which still
31
+ * answered its usual 202 (so the response reveals nothing); `'social'` was
32
+ * a social / SSO first login, refused with `AUTH_REGISTRATION_CLOSED`.
33
+ * `tenantId` is the tenant the attempt happened on (absent on the apex).
34
+ */
35
+ 'auth:register_refused': {
36
+ email: string;
37
+ tenantId?: string;
38
+ source: 'register' | 'social';
39
+ };
28
40
  'auth:login': {
29
41
  user: PublicUser;
30
42
  };
package/dist/plugin.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { BasaltError, createToken, definePlugin, ensureMetadata } from '@basaltkit/core';
2
2
  import { Auth, AuthRequiredError, isAmr, MfaEnrollmentRequiredError, MfaStepUpRequiredError, } from './auth.js';
3
- import { publicUser } from './auth.js';
3
+ import { assertSessionOptions, publicUser } from './auth.js';
4
4
  export const AUTH = createToken('auth');
5
5
  /** A cookie-authenticated, state-changing request came from another origin. */
6
6
  export class CsrfRejectedError extends BasaltError {
@@ -61,6 +61,9 @@ export function authPlugin(pluginOptions) {
61
61
  return definePlugin({
62
62
  name: 'basalt:auth',
63
63
  register({ container, hooks }) {
64
+ // Fail at boot, not on the first request, on a cookie the browser would
65
+ // drop or an idle timeout the store cannot enforce.
66
+ assertSessionOptions(options);
64
67
  container.singleton(AUTH, () => new Auth({ ...options, hooks }));
65
68
  const metadata = ensureMetadata(container);
66
69
  // Enricher: authenticates via Bearer JWT, session cookie, or x-session-id header.
@@ -143,6 +146,26 @@ export function authPlugin(pluginOptions) {
143
146
  throw (await c.get(AUTH).isMfaEnabled(user.id)) ? new MfaStepUpRequiredError() : new MfaEnrollmentRequiredError();
144
147
  };
145
148
  metadata.add('http:guards', mfaGuard);
149
+ // Visibility (e.g. MCP `tools/list`): hide a route the caller statically
150
+ // cannot pass the MFA guard on. Pure — it reads only ctx() (`user`, `amr`,
151
+ // `apiKey`): no MFA-store lookup, no hooks, no writes. A `requireMfa`
152
+ // FUNCTION policy is never called here (it is app code with no purity
153
+ // contract), so those routes stay listed and the guard decides on call.
154
+ const mfaVisibility = ({ route, context }) => {
155
+ const declared = route.meta?.['mfa'];
156
+ if (declared === false)
157
+ return true;
158
+ if (!context['user'])
159
+ return true; // meta.auth / the guard decide
160
+ let required = declared === true;
161
+ if (!required && requireMfa === true && context['apiKey'] === undefined)
162
+ required = true;
163
+ if (!required)
164
+ return true;
165
+ const amr = context['amr'];
166
+ return Array.isArray(amr) && amr.includes('mfa');
167
+ };
168
+ metadata.add('http:route-visibility', mfaVisibility);
146
169
  },
147
170
  });
148
171
  }
package/dist/routes.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { type BasaltRoute } from '@basaltkit/http';
2
2
  import { z } from 'zod';
3
+ import { type RegisterPolicy } from './auth.js';
3
4
  /**
4
5
  * How strong a password has to be.
5
6
  *
@@ -16,7 +17,24 @@ import { z } from 'zod';
16
17
  export interface PasswordPolicy {
17
18
  minLength?: number;
18
19
  }
20
+ /**
21
+ * Who may sign up through `POST /auth/register`:
22
+ * - `'open'`: anyone (ignores `registerPolicy` of the auth options);
23
+ * - `'closed'`: the route answers 404 `AUTH_REGISTRATION_CLOSED` to every
24
+ * request — a static answer that says nothing about any address;
25
+ * - a {@link RegisterPolicy}: asked per request with the canonical email and
26
+ * the request's tenant. A refusal answers the SAME 202 as a success, creates
27
+ * nothing and emits `auth:register_refused`, so the response cannot be used
28
+ * to learn who was invited.
29
+ */
30
+ export type RegisterOption = 'open' | 'closed' | RegisterPolicy;
19
31
  export interface AuthRoutesOptions {
32
+ /**
33
+ * Registration policy for `POST /auth/register`. Default: the
34
+ * `registerPolicy` given to `authPlugin()` (open when there is none). Use
35
+ * `@basaltkit/teams`' `teamsInviteGate(teams)` for invite-only tenant hosts.
36
+ */
37
+ register?: RegisterOption;
20
38
  /**
21
39
  * A minimum length, or the schema itself. Default: `min(8)`. Whatever the
22
40
  * policy, passwords are capped at {@link MAX_PASSWORD_LENGTH} characters
@@ -63,10 +81,23 @@ export declare const DEFAULT_AUTH_RATE_LIMIT: {
63
81
  */
64
82
  export declare function authRoutes(options?: AuthRoutesOptions): BasaltRoute[];
65
83
  /**
66
- * CRUD routes for API keys, all requiring a logged-in user (`meta.auth`). Keys
67
- * are scoped to the caller's tenant (`ctx().tenant`) and user; a caller only
68
- * ever sees or revokes keys within that scope. Register alongside
69
- * {@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`.
70
101
  */
71
102
  export declare function apiKeyRoutes(): BasaltRoute[];
72
103
  /**