@basaltkit/auth 4.1.0 → 4.2.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.d.ts CHANGED
@@ -115,6 +115,28 @@ export declare class AccountEmailAmbiguousError extends BasaltError {
115
115
  * `bob@acme.test` are one account.
116
116
  */
117
117
  export declare const canonicalEmail: (email: string) => string;
118
+ /**
119
+ * Account creation is not open here: the register route is configured
120
+ * `register: 'closed'`, or a {@link RegisterPolicy} refused a social / SSO
121
+ * login that would have created a new account. (A policy refusing the public
122
+ * register route never surfaces this — that route answers the same 202 as a
123
+ * success, so it cannot reveal who was invited.)
124
+ */
125
+ export declare class RegistrationClosedError extends BasaltError {
126
+ readonly status = 404;
127
+ constructor();
128
+ }
129
+ /**
130
+ * Decides whether a NEW account may be created for this address. `tenantId`
131
+ * is the tenant resolved for the request (`ctx().tenant?.id`), `undefined` on
132
+ * the apex / central plane. Return `false` to refuse. Throwing fails the
133
+ * request (fail closed). `@basaltkit/teams`' `teamsInviteGate(teams)` is the
134
+ * ready-made "invite-only on tenant hosts" policy.
135
+ */
136
+ export type RegisterPolicy = (input: {
137
+ email: string;
138
+ tenantId?: string;
139
+ }) => boolean | Promise<boolean>;
118
140
  /** An MFA action needed an enrollment that doesn't exist. */
119
141
  export declare class MfaNotEnrolledError extends BasaltError {
120
142
  readonly status = 400;
@@ -138,9 +160,37 @@ export interface SessionCookieOptions {
138
160
  /**
139
161
  * Whether to require HTTPS. Defaults to true unless `NODE_ENV` is explicitly
140
162
  * `development` or `test` (an unset NODE_ENV counts as production).
163
+ *
164
+ * A `__Host-` or `__Secure-` name (matched case-insensitively) implies
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.
141
169
  */
142
170
  secure?: boolean;
143
171
  }
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`.
178
+ */
179
+ export declare class SessionCookieConfigError extends BasaltError {
180
+ readonly status = 500;
181
+ constructor(message: string);
182
+ }
183
+ /** `sessionIdleTtl` cannot be honoured as configured. */
184
+ export declare class SessionIdleConfigError extends BasaltError {
185
+ readonly status = 500;
186
+ constructor(message: string);
187
+ }
188
+ /**
189
+ * Validates the session options the way `new Auth()` does, without building
190
+ * it — so `authPlugin` refuses a bad configuration at registration rather
191
+ * than on the first request. Pure: no I/O.
192
+ */
193
+ export declare function assertSessionOptions(options: Pick<AuthOptions, 'sessionCookie' | 'sessionIdleTtl' | 'sessions'>): void;
144
194
  export interface AuthOptions {
145
195
  users: UserSource;
146
196
  secret: string;
@@ -149,7 +199,21 @@ export interface AuthOptions {
149
199
  refreshTokens?: RefreshTokenStore;
150
200
  accessTtl?: DurationInput;
151
201
  refreshTtl?: DurationInput;
202
+ /** Absolute lifetime of a server-side session. Default `30d`. */
152
203
  sessionTtl?: DurationInput;
204
+ /**
205
+ * Idle timeout: a session unused for longer than this is refused and
206
+ * deleted, whatever its absolute `sessionTtl`. Activity is recorded with the
207
+ * store's `touch` at most once per `min(60s, sessionIdleTtl / 4)`, so the
208
+ * effective idle limit can be that much longer. Requires a session store
209
+ * that implements `touch` (memory, auth-sqlite, auth-prisma with
210
+ * `trackSessionActivity`); construction fails otherwise. A session with no
211
+ * `lastSeenAt` (a legacy row) starts its idle clock on its next use; one
212
+ * that has it is measured from it, and nothing touches it while this option
213
+ * is off, so enabling it signs out sessions created longer ago than the
214
+ * window once. Default: no idle timeout.
215
+ */
216
+ sessionIdleTtl?: DurationInput;
153
217
  sessionCookie?: SessionCookieOptions;
154
218
  hooks?: HookBus;
155
219
  /** Brute-force lockout (per email). Enabled by default; pass `false` to disable. */
@@ -186,6 +250,14 @@ export interface AuthOptions {
186
250
  * lower-level {@link Auth.register} always throws on a duplicate. Default true.
187
251
  */
188
252
  enumerationSafeRegister?: boolean;
253
+ /**
254
+ * Who may create a NEW account through the self-service paths: the public
255
+ * register route ({@link Auth.registerSafely}, unless `authRoutes({ register })`
256
+ * overrides it) and the create branch of {@link Auth.socialLogin}. Logins into
257
+ * existing accounts and the trusted {@link Auth.register} are never gated.
258
+ * Default: open.
259
+ */
260
+ registerPolicy?: RegisterPolicy;
189
261
  /** Store for verification/reset tokens. Default: in-memory. */
190
262
  tokens?: AuthTokenStore;
191
263
  /** Email-verification link lifetime. Default 24h. */
@@ -243,6 +315,8 @@ export declare class Auth {
243
315
  private readonly accessTtl;
244
316
  private readonly refreshTtl;
245
317
  private readonly sessionTtl;
318
+ private readonly sessionIdleMs;
319
+ private readonly sessionTouchEveryMs;
246
320
  private readonly sessionCookie;
247
321
  private readonly hooks;
248
322
  private readonly throttle;
@@ -257,8 +331,44 @@ export declare class Auth {
257
331
  private readonly mfaBox;
258
332
  private readonly tokenVersions;
259
333
  private readonly enumerationSafeRegister;
334
+ private readonly registerPolicy;
260
335
  constructor(options: AuthOptions);
261
- register(rawEmail: string, password: string): Promise<PublicUser>;
336
+ /**
337
+ * Trusted, server-side account creation (seeding, a back-office, a flow that
338
+ * proved the address before creating the account). Throws
339
+ * {@link EmailTakenError} on a duplicate and is never gated by a
340
+ * {@link RegisterPolicy}. `emailVerified: true` creates the account already
341
+ * verified; `auth:registered` then carries the final state, so a mail hook
342
+ * can decide "unverified → send the verification link" on its own. Never
343
+ * forward this option from a request body.
344
+ *
345
+ * `emailVerified: true` needs a `UserSource` with `update()` — the same
346
+ * requirement as email verification. Without it this throws
347
+ * {@link UserUpdateUnsupportedError} **before** anything is written: whether
348
+ * `create()` persists the flag can only be learnt by writing the row, and a
349
+ * row that cannot be fixed afterwards would be a half-done registration
350
+ * (an unverified account that a retry reports as `EmailTakenError`).
351
+ */
352
+ register(rawEmail: string, password: string, opts?: {
353
+ emailVerified?: boolean;
354
+ }): Promise<PublicUser>;
355
+ /**
356
+ * Creates the row with the requested verification state. A custom
357
+ * `UserSource` written before `create()` took `emailVerified` may drop the
358
+ * flag: it is then set through `update()`.
359
+ *
360
+ * When the source can do neither (no `update()` and a `create()` that drops
361
+ * the flag), `onUnsupported` decides: `'throw'` fails loudly with
362
+ * {@link UserUpdateUnsupportedError} (trusted `register`, whose caller asked
363
+ * for a verified account and must hear it did not get one — `register`
364
+ * refuses a source without `update()` before calling this, so here it only
365
+ * fires for an `update()` that does not persist the flag); `'keep'` returns
366
+ * the row as it really is, unverified (social login — the row was just
367
+ * created by this call with an unusable password, so it is provably ours and
368
+ * must be linked and used, never left behind as an orphan that locks the
369
+ * provider account out on every later login).
370
+ */
371
+ private createUser;
262
372
  /**
263
373
  * Logs in an externally-authenticated user (e.g. from an OAuth provider) —
264
374
  * find-or-create. A new account is created **passwordless** (a random,
@@ -299,6 +409,11 @@ export declare class Auth {
299
409
  * that legitimately re-issues subjects (a directory migration).
300
410
  */
301
411
  subjectConflict?: 'refuse' | 'link';
412
+ /**
413
+ * The tenant this login happens on, for the {@link RegisterPolicy}.
414
+ * Default: the current request's `ctx().tenant?.id`.
415
+ */
416
+ tenantId?: string;
302
417
  }): Promise<{
303
418
  user: PublicUser;
304
419
  tokens: TokenPair;
@@ -325,8 +440,17 @@ export declare class Auth {
325
440
  *
326
441
  * With `enumerationSafeRegister: false` it throws {@link EmailTakenError} on a
327
442
  * duplicate instead (the classic, enumerable behavior).
443
+ *
444
+ * A {@link RegisterPolicy} (`opts.policy`, else `registerPolicy` of the
445
+ * options; `null` = open) is asked first. A refusal creates nothing, does the
446
+ * same hashing work and emits `auth:register_refused` — the caller sees the
447
+ * same outcome as a success, so the response never tells who was invited.
448
+ * Never creates a verified account.
328
449
  */
329
- registerSafely(rawEmail: string, password: string): Promise<void>;
450
+ registerSafely(rawEmail: string, password: string, opts?: {
451
+ policy?: RegisterPolicy | null;
452
+ tenantId?: string;
453
+ }): Promise<void>;
330
454
  /** Verifies credentials without side effects. Null on failure. */
331
455
  attempt(email: string, password: string): Promise<AuthUser | null>;
332
456
  private dummyHashPromise?;
@@ -407,6 +531,12 @@ export declare class Auth {
407
531
  user: AuthUser;
408
532
  amr?: string[];
409
533
  } | null>;
534
+ /**
535
+ * Applies the idle timeout: refuses (and deletes) a session idle for longer
536
+ * than `sessionIdleTtl`, otherwise records the activity, throttled. A no-op
537
+ * without `sessionIdleTtl`.
538
+ */
539
+ private sessionStillActive;
410
540
  logout(sessionId: string): Promise<void>;
411
541
  /**
412
542
  * Starts email verification: mints a single-use token and emits
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,116 @@ 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
+ *
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`.
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.
211
+ */
212
+ const warnedSessionCookies = new WeakSet();
213
+ /**
214
+ * Resolves the session cookie options against the cookie-prefix rules
215
+ * browsers apply (RFC 6265bis): `__Secure-` needs `Secure`; `__Host-` needs
216
+ * `Secure` and `Path=/` (and no `Domain`, which Basalt never sets). Prefixes
217
+ * match case-insensitively, as in current browsers. A violating cookie is not
218
+ * an error in the browser, it is silently dropped, so every login would
219
+ * "succeed" without a session.
220
+ *
221
+ * 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
+ *
225
+ * Warnings are independent, each emitted once per `sessionCookie` object:
226
+ * - the cookie is dropped by browsers because of its prefix (refused next major);
227
+ * - Secure is implied by the prefix where it was not before (outside
228
+ * production, so the emission differs from earlier versions);
229
+ * - `SameSite=None` without `Secure`, which browsers also drop.
230
+ */
231
+ function resolveSessionCookie(options) {
232
+ const name = options?.name ?? 'basalt_session';
233
+ const lowerName = name.toLowerCase();
234
+ const host = lowerName.startsWith('__host-');
235
+ const prefixed = host || lowerName.startsWith('__secure-');
236
+ const production = isProductionEnvironment();
237
+ const resolved = {
238
+ name,
239
+ path: options?.path ?? '/',
240
+ httpOnly: options?.httpOnly ?? true,
241
+ sameSite: options?.sameSite ?? 'Lax',
242
+ secure: options?.secure ?? (prefixed ? true : production),
243
+ };
244
+ if (options && !warnedSessionCookies.has(options)) {
245
+ 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
+ if (prefixed && options.secure === undefined && !production) {
255
+ 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
+ }
257
+ if (!prefixed && resolved.sameSite === 'None' && !resolved.secure) {
258
+ warnings.push(`[basalt] sessionCookie "${name}": SameSite=None without Secure - browsers drop it; set secure: true or use SameSite "Lax".`);
259
+ }
260
+ if (warnings.length > 0) {
261
+ warnedSessionCookies.add(options);
262
+ for (const warning of warnings)
263
+ console.warn(warning);
264
+ }
265
+ }
266
+ return resolved;
267
+ }
268
+ /** Longest gap between two `touch` writes of one session: one minute. */
269
+ const MAX_SESSION_TOUCH_INTERVAL_MS = 60_000;
270
+ /**
271
+ * Resolves `sessionIdleTtl` to milliseconds, or undefined when unset. Fails
272
+ * when it is not a positive duration or the session store cannot record
273
+ * activity (`touch`). `sessions` undefined means the built-in memory store.
274
+ */
275
+ function resolveSessionIdle(idle, sessions) {
276
+ if (idle === undefined)
277
+ return undefined;
278
+ const idleMs = parseDuration(idle);
279
+ if (!Number.isFinite(idleMs) || idleMs <= 0) {
280
+ throw new SessionIdleConfigError('sessionIdleTtl must be a positive duration.');
281
+ }
282
+ if (sessions !== undefined && typeof sessions.touch !== 'function') {
283
+ 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.');
284
+ }
285
+ return idleMs;
286
+ }
287
+ /**
288
+ * Validates the session options the way `new Auth()` does, without building
289
+ * it — so `authPlugin` refuses a bad configuration at registration rather
290
+ * than on the first request. Pure: no I/O.
291
+ */
292
+ export function assertSessionOptions(options) {
293
+ resolveSessionCookie(options.sessionCookie);
294
+ resolveSessionIdle(options.sessionIdleTtl, options.sessions);
295
+ }
168
296
  export const publicUser = (user) => ({
169
297
  id: user.id,
170
298
  email: user.email,
@@ -179,6 +307,8 @@ export class Auth {
179
307
  accessTtl;
180
308
  refreshTtl;
181
309
  sessionTtl;
310
+ sessionIdleMs;
311
+ sessionTouchEveryMs;
182
312
  sessionCookie;
183
313
  hooks;
184
314
  throttle;
@@ -193,6 +323,7 @@ export class Auth {
193
323
  mfaBox;
194
324
  tokenVersions;
195
325
  enumerationSafeRegister;
326
+ registerPolicy;
196
327
  constructor(options) {
197
328
  this.users = options.users;
198
329
  this.secret = options.secret;
@@ -210,13 +341,9 @@ export class Auth {
210
341
  this.accessTtl = options.accessTtl ?? '15m';
211
342
  this.refreshTtl = options.refreshTtl ?? '30d';
212
343
  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
- };
344
+ this.sessionIdleMs = resolveSessionIdle(options.sessionIdleTtl, this.sessions);
345
+ this.sessionTouchEveryMs = Math.min(MAX_SESSION_TOUCH_INTERVAL_MS, (this.sessionIdleMs ?? 0) / 4);
346
+ this.sessionCookie = resolveSessionCookie(options.sessionCookie);
220
347
  this.hooks = options.hooks;
221
348
  const shared = options.throttleStore ? { store: options.throttleStore } : {};
222
349
  this.throttle =
@@ -249,18 +376,63 @@ export class Auth {
249
376
  : undefined;
250
377
  this.tokenVersions = options.tokenVersions;
251
378
  this.enumerationSafeRegister = options.enumerationSafeRegister ?? true;
379
+ this.registerPolicy = options.registerPolicy;
252
380
  }
253
- async register(rawEmail, password) {
381
+ /**
382
+ * Trusted, server-side account creation (seeding, a back-office, a flow that
383
+ * proved the address before creating the account). Throws
384
+ * {@link EmailTakenError} on a duplicate and is never gated by a
385
+ * {@link RegisterPolicy}. `emailVerified: true` creates the account already
386
+ * verified; `auth:registered` then carries the final state, so a mail hook
387
+ * can decide "unverified → send the verification link" on its own. Never
388
+ * forward this option from a request body.
389
+ *
390
+ * `emailVerified: true` needs a `UserSource` with `update()` — the same
391
+ * requirement as email verification. Without it this throws
392
+ * {@link UserUpdateUnsupportedError} **before** anything is written: whether
393
+ * `create()` persists the flag can only be learnt by writing the row, and a
394
+ * row that cannot be fixed afterwards would be a half-done registration
395
+ * (an unverified account that a retry reports as `EmailTakenError`).
396
+ */
397
+ async register(rawEmail, password, opts = {}) {
398
+ if (opts.emailVerified === true && typeof this.users.update !== 'function')
399
+ throw new UserUpdateUnsupportedError();
254
400
  const email = canonicalEmail(rawEmail);
255
401
  if (await this.users.findByEmail(email))
256
402
  throw new EmailTakenError();
257
- const user = await this.users.create({
258
- email,
259
- passwordHash: await this.hasher.hash(password),
260
- });
403
+ const user = await this.createUser(email, await this.hasher.hash(password), opts.emailVerified === true);
261
404
  await this.hooks?.emit('auth:registered', { user: publicUser(user) });
262
405
  return publicUser(user);
263
406
  }
407
+ /**
408
+ * Creates the row with the requested verification state. A custom
409
+ * `UserSource` written before `create()` took `emailVerified` may drop the
410
+ * flag: it is then set through `update()`.
411
+ *
412
+ * When the source can do neither (no `update()` and a `create()` that drops
413
+ * the flag), `onUnsupported` decides: `'throw'` fails loudly with
414
+ * {@link UserUpdateUnsupportedError} (trusted `register`, whose caller asked
415
+ * for a verified account and must hear it did not get one — `register`
416
+ * refuses a source without `update()` before calling this, so here it only
417
+ * fires for an `update()` that does not persist the flag); `'keep'` returns
418
+ * the row as it really is, unverified (social login — the row was just
419
+ * created by this call with an unusable password, so it is provably ours and
420
+ * must be linked and used, never left behind as an orphan that locks the
421
+ * provider account out on every later login).
422
+ */
423
+ async createUser(email, passwordHash, emailVerified, onUnsupported = 'throw') {
424
+ // Decided before anything is written, so the outcome never depends on
425
+ // how far a half-done create got.
426
+ const canPatch = typeof this.users.update === 'function';
427
+ let user = await this.users.create(emailVerified ? { email, passwordHash, emailVerified: true } : { email, passwordHash });
428
+ if (emailVerified && user.emailVerified !== true) {
429
+ if (canPatch)
430
+ user = (await this.users.update(user.id, { emailVerified: true })) ?? user;
431
+ if (user.emailVerified !== true && onUnsupported === 'throw')
432
+ throw new UserUpdateUnsupportedError();
433
+ }
434
+ return user;
435
+ }
264
436
  /**
265
437
  * Logs in an externally-authenticated user (e.g. from an OAuth provider) —
266
438
  * find-or-create. A new account is created **passwordless** (a random,
@@ -311,15 +483,22 @@ export class Auth {
311
483
  let user = await this.users.findByEmail(email);
312
484
  let created = false;
313
485
  if (!user) {
314
- user = await this.users.create({
315
- email,
316
- passwordHash: await this.hasher.hash(randomBytes(32).toString('hex')),
317
- });
486
+ // A social login is already an authenticated flow, so a refusal is said
487
+ // out loud (the provider vouched for the caller's address).
488
+ const tenantId = options.tenantId ?? currentTenantId();
489
+ if (this.registerPolicy && !(await this.registerPolicy(tenantId === undefined ? { email } : { email, tenantId }))) {
490
+ await this.hooks?.emit('auth:register_refused', { email, ...(tenantId !== undefined ? { tenantId } : {}), source: 'social' });
491
+ throw new RegistrationClosedError();
492
+ }
493
+ // Created with its final verification state, so `auth:registered`
494
+ // reports what the account really is. A source that cannot record the
495
+ // verification (no `update()`, a `create()` that drops the flag) keeps
496
+ // the account unverified rather than fail after the row exists: a
497
+ // half-done first login would leave an unlinked, unverified row that
498
+ // every later login refuses to adopt (`AUTH_SOCIAL_LINK_REFUSED`).
499
+ user = await this.createUser(email, await this.hasher.hash(randomBytes(32).toString('hex')), options.emailVerified === true, 'keep');
318
500
  created = true;
319
501
  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
502
  }
324
503
  else {
325
504
  if (options.emailVerified !== true)
@@ -401,9 +580,24 @@ export class Auth {
401
580
  *
402
581
  * With `enumerationSafeRegister: false` it throws {@link EmailTakenError} on a
403
582
  * duplicate instead (the classic, enumerable behavior).
583
+ *
584
+ * A {@link RegisterPolicy} (`opts.policy`, else `registerPolicy` of the
585
+ * options; `null` = open) is asked first. A refusal creates nothing, does the
586
+ * same hashing work and emits `auth:register_refused` — the caller sees the
587
+ * same outcome as a success, so the response never tells who was invited.
588
+ * Never creates a verified account.
404
589
  */
405
- async registerSafely(rawEmail, password) {
590
+ async registerSafely(rawEmail, password, opts = {}) {
406
591
  const email = canonicalEmail(rawEmail);
592
+ const policy = opts.policy === undefined ? this.registerPolicy : (opts.policy ?? undefined);
593
+ if (policy) {
594
+ const tenantId = opts.tenantId ?? currentTenantId();
595
+ if (!(await policy(tenantId === undefined ? { email } : { email, tenantId }))) {
596
+ await this.hasher.hash(password);
597
+ await this.hooks?.emit('auth:register_refused', { email, ...(tenantId !== undefined ? { tenantId } : {}), source: 'register' });
598
+ return;
599
+ }
600
+ }
407
601
  const existing = await this.users.findByEmail(email);
408
602
  if (existing) {
409
603
  if (!this.enumerationSafeRegister)
@@ -657,11 +851,33 @@ export class Auth {
657
851
  async sessionAuth(sessionId) {
658
852
  const { rawId, amr } = this.parseSessionId(sessionId);
659
853
  const session = await this.sessions.find(rawId);
854
+ if (session && !(await this.sessionStillActive(rawId, session)))
855
+ return null;
660
856
  const user = session ? await this.users.findById(session.userId) : null;
661
857
  if (!user)
662
858
  return null;
663
859
  return amr ? { user, amr } : { user };
664
860
  }
861
+ /**
862
+ * Applies the idle timeout: refuses (and deletes) a session idle for longer
863
+ * than `sessionIdleTtl`, otherwise records the activity, throttled. A no-op
864
+ * without `sessionIdleTtl`.
865
+ */
866
+ async sessionStillActive(rawId, session) {
867
+ const idleMs = this.sessionIdleMs;
868
+ if (idleMs === undefined)
869
+ return true;
870
+ const now = Date.now();
871
+ const lastSeenAt = session.lastSeenAt;
872
+ if (lastSeenAt !== undefined && now - lastSeenAt > idleMs) {
873
+ await this.sessions.delete(rawId);
874
+ return false;
875
+ }
876
+ if (lastSeenAt === undefined || now - lastSeenAt >= this.sessionTouchEveryMs) {
877
+ await this.sessions.touch?.(rawId, now);
878
+ }
879
+ return true;
880
+ }
665
881
  async logout(sessionId) {
666
882
  const { rawId } = this.parseSessionId(sessionId);
667
883
  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 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, DEFAULT_API_KEY_TOUCH_EVERY_MS, ScopeRequiredError, scopesSatisfy, type ApiKeysOptions, type IssueApiKeyInput, 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, DEFAULT_API_KEY_TOUCH_EVERY_MS, 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';
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
  }