@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/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
package/dist/routes.js CHANGED
@@ -2,6 +2,7 @@ import { ctx, BasaltError } from '@basaltkit/core';
2
2
  import { route } from '@basaltkit/http';
3
3
  import { z } from 'zod';
4
4
  import { AUTH, CsrfRejectedError, isCsrfRejected } from './plugin.js';
5
+ import { RegistrationClosedError } from './auth.js';
5
6
  import { API_KEYS } from './apikeys-plugin.js';
6
7
  /**
7
8
  * Route meta shared by the account routes (sign-in, profile, MFA self-service):
@@ -44,19 +45,32 @@ export function authRoutes(options = {}) {
44
45
  // Every route here is about the caller's own account: exempt from the
45
46
  // tenant-membership guard (`account`) and reachable before MFA (`mfa: false`).
46
47
  const account = ACCOUNT_META;
48
+ const register = options.register;
47
49
  return [
48
- route({
49
- method: 'POST',
50
- url: '/auth/register',
51
- meta: { ...account, ...limit },
52
- body: credentials,
53
- // Enumeration-safe: the same 202 whether the email is new or already taken
54
- // (a collision is signalled out-of-band via auth:register_existing_email).
55
- async handler({ body, reply }) {
56
- await auth().registerSafely(body.email, body.password);
57
- return reply.code(202).send({ ok: true });
58
- },
59
- }),
50
+ register === 'closed'
51
+ ? // No body schema: every request gets the same 404, whatever it sends.
52
+ route({
53
+ method: 'POST',
54
+ url: '/auth/register',
55
+ meta: { ...account, ...limit },
56
+ handler() {
57
+ throw new RegistrationClosedError();
58
+ },
59
+ })
60
+ : route({
61
+ method: 'POST',
62
+ url: '/auth/register',
63
+ meta: { ...account, ...limit },
64
+ body: credentials,
65
+ // Enumeration-safe: the same 202 whether the email is new or already taken
66
+ // (a collision is signalled out-of-band via auth:register_existing_email),
67
+ // and whether a registration policy admitted it or not
68
+ // (auth:register_refused).
69
+ async handler({ body, reply }) {
70
+ await auth().registerSafely(body.email, body.password, register === undefined ? {} : { policy: register === 'open' ? null : register });
71
+ return reply.code(202).send({ ok: true });
72
+ },
73
+ }),
60
74
  route({
61
75
  method: 'POST',
62
76
  url: '/auth/login',
@@ -53,8 +53,7 @@ export interface SecretBoxOptions {
53
53
  * envelope and the threat model.
54
54
  */
55
55
  export declare class SecretBox {
56
- private readonly keys;
57
- private readonly activeId;
56
+ private readonly box;
58
57
  private readonly v1Keys;
59
58
  private readonly acceptPlaintext;
60
59
  constructor(options: SecretBoxOptions);
@@ -77,6 +76,5 @@ export declare class SecretBox {
77
76
  * write.
78
77
  */
79
78
  reseal(value: string, context: SecretContext): string | null;
80
- private openV2;
81
79
  private openV1;
82
80
  }
@@ -1,5 +1,6 @@
1
- import { createCipheriv, createDecipheriv, createHash, hkdfSync, randomBytes } from 'node:crypto';
1
+ import { createDecipheriv, createHash } from 'node:crypto';
2
2
  import { BasaltError } from '@basaltkit/core';
3
+ import { createSecretBox, SecretBoxError } from '@basaltkit/core/secret-box';
3
4
  /**
4
5
  * Authenticated encryption (AES-256-GCM) for secrets stored at rest — used to
5
6
  * encrypt TOTP secrets so a database leak doesn't hand the attacker every
@@ -27,13 +28,15 @@ import { BasaltError } from '@basaltkit/core';
27
28
  * Without the last point, anyone able to write the column could replace an
28
29
  * encrypted TOTP secret with a plaintext one they know (a downgrade), and the
29
30
  * box would hand it back as if it were genuine.
31
+ *
32
+ * The AEAD itself is the shared primitive in `@basaltkit/core/secret-box`
33
+ * (version `bka2`, two context fields); this class adds the auth contract on
34
+ * top — its errors, non-empty context fields, and the legacy read paths.
30
35
  */
31
36
  const VERSION = 'bka2';
32
37
  const LEGACY_PREFIX = 'v1:';
33
38
  /** Mixed into HKDF so key material reused elsewhere derives a different box key. */
34
39
  const HKDF_INFO = 'basalt:auth:secret-box:v2';
35
- const KEY_ID = /^[A-Za-z0-9_-]{1,64}$/;
36
- const MIN_KEY_BYTES = 32;
37
40
  /** GCM's full tag; anything shorter is refused (a short tag is cheaper to forge). */
38
41
  const TAG_BYTES = 16;
39
42
  /** A secret-box key or its value could not be used (configuration error). */
@@ -57,57 +60,61 @@ export class SecretUnreadableError extends BasaltError {
57
60
  }
58
61
  }
59
62
  const toBytes = (key) => (typeof key === 'string' ? Buffer.from(key, 'utf8') : Buffer.from(key));
60
- /** NUL-separated, so no field boundary can be shifted (`a|b`+`c` ≠ `a`+`b|c`). */
61
- function aad(keyId, context) {
62
- for (const field of [context.purpose, context.subject]) {
63
+ /**
64
+ * The context as the primitive's ordered fields. Auth also refuses empty
65
+ * fields: an empty subject would bind a secret to no record at all.
66
+ */
67
+ function fields(context) {
68
+ for (const field of [context?.purpose, context?.subject]) {
63
69
  if (typeof field !== 'string' || field.length === 0 || field.includes('\0')) {
64
70
  throw new SecretUnreadableError('the secret context must be non-empty strings without NUL characters.');
65
71
  }
66
72
  }
67
- return Buffer.from([VERSION, keyId, context.purpose, context.subject].join('\0'), 'utf8');
73
+ return [context.purpose, context.subject];
74
+ }
75
+ /** Maps a primitive failure onto the auth errors (one class per side of the contract). */
76
+ function translate(error) {
77
+ if (error instanceof SecretBoxError) {
78
+ if (error.failure === 'config')
79
+ throw new SecretBoxKeyError(error.detail);
80
+ if (error.failure === 'malformed')
81
+ throw new SecretUnreadableError('malformed envelope.');
82
+ throw new SecretUnreadableError(error.detail);
83
+ }
84
+ throw error;
68
85
  }
69
86
  /**
70
87
  * Seals and opens secrets against a key ring. See the module comment for the
71
88
  * envelope and the threat model.
72
89
  */
73
90
  export class SecretBox {
74
- keys = new Map();
75
- activeId;
91
+ box;
76
92
  v1Keys;
77
93
  acceptPlaintext;
78
94
  constructor(options) {
79
- const ring = options.keys;
80
- if (!Array.isArray(ring) || ring.length === 0)
81
- throw new SecretBoxKeyError('at least one key is required.');
82
- for (const entry of ring) {
83
- if (typeof entry?.id !== 'string' || !KEY_ID.test(entry.id)) {
84
- throw new SecretBoxKeyError(`key id ${JSON.stringify(entry?.id)} must match ${String(KEY_ID)}.`);
85
- }
86
- if (this.keys.has(entry.id))
87
- throw new SecretBoxKeyError(`duplicate key id "${entry.id}".`);
88
- const material = toBytes(entry.key);
89
- if (material.length < MIN_KEY_BYTES) {
90
- throw new SecretBoxKeyError(`key "${entry.id}" is ${material.length} bytes; at least ${MIN_KEY_BYTES} are required.`);
91
- }
92
- this.keys.set(entry.id, Buffer.from(hkdfSync('sha256', material, Buffer.alloc(0), HKDF_INFO, 32)));
95
+ try {
96
+ this.box = createSecretBox({ keys: options.keys, info: HKDF_INFO, version: VERSION, aadFields: 2 });
97
+ }
98
+ catch (error) {
99
+ translate(error);
93
100
  }
94
- this.activeId = ring[0].id;
95
101
  // The v1 format derived its key with a bare SHA-256; reproduced only to read old rows.
96
102
  this.v1Keys = (options.legacy?.v1Keys ?? []).map((k) => createHash('sha256').update(toBytes(k)).digest());
97
103
  this.acceptPlaintext = options.legacy?.plaintext === true;
98
104
  }
99
105
  /** The key id new ciphertexts are sealed with. */
100
106
  get activeKeyId() {
101
- return this.activeId;
107
+ return this.box.activeKeyId;
102
108
  }
103
109
  /** Encrypts `plaintext` under the active key, bound to `context`. */
104
110
  seal(plaintext, context) {
105
- const key = this.keys.get(this.activeId);
106
- const iv = randomBytes(12);
107
- const cipher = createCipheriv('aes-256-gcm', key, iv, { authTagLength: TAG_BYTES });
108
- cipher.setAAD(aad(this.activeId, context));
109
- const ciphertext = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
110
- return [VERSION, this.activeId, iv.toString('base64url'), cipher.getAuthTag().toString('base64url'), ciphertext.toString('base64url')].join('.');
111
+ const bound = fields(context);
112
+ try {
113
+ return this.box.seal(plaintext, bound);
114
+ }
115
+ catch (error) {
116
+ translate(error);
117
+ }
111
118
  }
112
119
  /**
113
120
  * Decrypts a value sealed for `context`. Throws {@link SecretUnreadableError}
@@ -117,8 +124,15 @@ export class SecretBox {
117
124
  open(value, context) {
118
125
  if (typeof value !== 'string')
119
126
  throw new SecretUnreadableError('not a string.');
120
- if (value.startsWith(`${VERSION}.`))
121
- return this.openV2(value, context);
127
+ if (value.startsWith(`${VERSION}.`)) {
128
+ const bound = fields(context);
129
+ try {
130
+ return this.box.open(value, bound);
131
+ }
132
+ catch (error) {
133
+ translate(error);
134
+ }
135
+ }
122
136
  if (value.startsWith(LEGACY_PREFIX))
123
137
  return this.openV1(value);
124
138
  if (this.acceptPlaintext)
@@ -127,8 +141,7 @@ export class SecretBox {
127
141
  }
128
142
  /** Whether `value` is already sealed with the active key (nothing to migrate). */
129
143
  isCurrent(value) {
130
- const parts = value.split('.');
131
- return parts.length === 5 && parts[0] === VERSION && parts[1] === this.activeId;
144
+ return this.box.isCurrent(value);
132
145
  }
133
146
  /**
134
147
  * Re-seals `value` under the active key — for rotation, and for migrating
@@ -143,28 +156,6 @@ export class SecretBox {
143
156
  }
144
157
  return this.seal(this.open(value, context), context);
145
158
  }
146
- openV2(value, context) {
147
- const parts = value.split('.');
148
- if (parts.length !== 5)
149
- throw new SecretUnreadableError('malformed envelope.');
150
- const [, keyId, ivB64, tagB64, ctB64] = parts;
151
- const key = this.keys.get(keyId);
152
- if (!key)
153
- throw new SecretUnreadableError(`unknown key id "${keyId}" (was it removed from the ring?).`);
154
- const additional = aad(keyId, context);
155
- try {
156
- const tag = Buffer.from(tagB64, 'base64url');
157
- if (tag.length !== TAG_BYTES)
158
- throw new Error('truncated tag');
159
- const decipher = createDecipheriv('aes-256-gcm', key, Buffer.from(ivB64, 'base64url'), { authTagLength: TAG_BYTES });
160
- decipher.setAAD(additional);
161
- decipher.setAuthTag(tag);
162
- return Buffer.concat([decipher.update(Buffer.from(ctB64, 'base64url')), decipher.final()]).toString('utf8');
163
- }
164
- catch {
165
- throw new SecretUnreadableError('authentication failed (wrong key, tampering, or a value from another record).');
166
- }
167
- }
168
159
  openV1(value) {
169
160
  if (this.v1Keys.length === 0)
170
161
  throw new SecretUnreadableError('a legacy v1 envelope, and no legacy v1 key is configured.');
package/dist/stores.d.ts CHANGED
@@ -14,13 +14,23 @@ export interface PublicUser {
14
14
  }
15
15
  /** Fields the email-verification / password-reset flows update on a user. */
16
16
  export type UserPatch = Partial<Pick<AuthUser, 'passwordHash' | 'emailVerified'>>;
17
+ /** What {@link UserSource.create} receives. */
18
+ export interface NewUser {
19
+ email: string;
20
+ passwordHash: string;
21
+ /** Create the account already verified. Default `false`. */
22
+ emailVerified?: boolean;
23
+ }
17
24
  export interface UserSource {
18
25
  findByEmail(email: string): Promise<AuthUser | null>;
19
26
  findById(id: string): Promise<AuthUser | null>;
20
- create(data: {
21
- email: string;
22
- passwordHash: string;
23
- }): Promise<AuthUser>;
27
+ /**
28
+ * Creates an account. `emailVerified` is set only by trusted server-side
29
+ * flows (`Auth.register(…, { emailVerified: true })`, a provider-verified
30
+ * social login) and must be persisted with the row; omitted means `false`.
31
+ * The public register route never passes it.
32
+ */
33
+ create(data: NewUser): Promise<AuthUser>;
24
34
  /** Required for email verification and password reset. Returns the updated user. */
25
35
  update?(id: string, patch: UserPatch): Promise<AuthUser | null>;
26
36
  /**
@@ -49,10 +59,7 @@ export declare class MemoryUserSource implements UserSource {
49
59
  findByEmail(email: string): Promise<AuthUser | null>;
50
60
  findById(id: string): Promise<AuthUser | null>;
51
61
  findByIds(ids: readonly string[]): Promise<PublicUser[]>;
52
- create(data: {
53
- email: string;
54
- passwordHash: string;
55
- }): Promise<AuthUser>;
62
+ create(data: NewUser): Promise<AuthUser>;
56
63
  update(id: string, patch: UserPatch): Promise<AuthUser | null>;
57
64
  }
58
65
  /**
@@ -233,6 +240,12 @@ export interface SessionRecord {
233
240
  id: string;
234
241
  userId: string;
235
242
  expiresAt: number;
243
+ /**
244
+ * Last time the session was used (ms), for the idle timeout
245
+ * (`AuthOptions.sessionIdleTtl`). Stores that implement `touch` set it at
246
+ * creation and return it from `find`; absent on rows written before.
247
+ */
248
+ lastSeenAt?: number;
236
249
  }
237
250
  export interface SessionStore {
238
251
  create(userId: string, ttlMs: number): Promise<SessionRecord>;
@@ -245,12 +258,19 @@ export interface SessionStore {
245
258
  * Optional so existing stores keep compiling; implement it to close the gap.
246
259
  */
247
260
  deleteAllForUser?(userId: string): Promise<void>;
261
+ /**
262
+ * Records activity on a session (`lastSeenAt = at`); `id` is the raw id, as
263
+ * for `find`. Required by `AuthOptions.sessionIdleTtl`, optional otherwise.
264
+ * Auth throttles the calls, so a store sees at most a few per idle window.
265
+ */
266
+ touch?(id: string, at: number): Promise<void>;
248
267
  }
249
268
  export declare class MemorySessionStore implements SessionStore {
250
269
  private readonly sessions;
251
270
  create(userId: string, ttlMs: number): Promise<SessionRecord>;
252
271
  find(id: string): Promise<SessionRecord | null>;
253
272
  delete(id: string): Promise<boolean>;
273
+ touch(id: string, at: number): Promise<void>;
254
274
  deleteAllForUser(userId: string): Promise<void>;
255
275
  }
256
276
  export interface RefreshRecord {
package/dist/stores.js CHANGED
@@ -41,7 +41,12 @@ export class MemoryUserSource {
41
41
  return out;
42
42
  }
43
43
  async create(data) {
44
- const user = { id: randomUUID(), emailVerified: false, ...data };
44
+ const user = {
45
+ id: randomUUID(),
46
+ email: data.email,
47
+ passwordHash: data.passwordHash,
48
+ emailVerified: data.emailVerified === true,
49
+ };
45
50
  this.users.set(user.id, user);
46
51
  return user;
47
52
  }
@@ -192,9 +197,10 @@ export class MemorySessionStore {
192
197
  // of the session table can't be replayed as a live session.
193
198
  const rawId = randomBytes(32).toString('base64url');
194
199
  const hashed = hashSessionId(rawId);
195
- const expiresAt = Date.now() + ttlMs;
196
- this.sessions.set(hashed, { id: hashed, userId, expiresAt });
197
- return { id: rawId, userId, expiresAt };
200
+ const now = Date.now();
201
+ const expiresAt = now + ttlMs;
202
+ this.sessions.set(hashed, { id: hashed, userId, expiresAt, lastSeenAt: now });
203
+ return { id: rawId, userId, expiresAt, lastSeenAt: now };
198
204
  }
199
205
  async find(id) {
200
206
  const hashed = hashSessionId(id);
@@ -206,11 +212,21 @@ export class MemorySessionStore {
206
212
  return null;
207
213
  }
208
214
  // Echo the id the caller queried with (never the stored hash).
209
- return { id, userId: record.userId, expiresAt: record.expiresAt };
215
+ return {
216
+ id,
217
+ userId: record.userId,
218
+ expiresAt: record.expiresAt,
219
+ ...(record.lastSeenAt !== undefined ? { lastSeenAt: record.lastSeenAt } : {}),
220
+ };
210
221
  }
211
222
  async delete(id) {
212
223
  return this.sessions.delete(hashSessionId(id));
213
224
  }
225
+ async touch(id, at) {
226
+ const record = this.sessions.get(hashSessionId(id));
227
+ if (record)
228
+ record.lastSeenAt = at;
229
+ }
214
230
  async deleteAllForUser(userId) {
215
231
  for (const [key, record] of this.sessions) {
216
232
  if (record.userId === userId)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@basaltkit/auth",
3
- "version": "4.1.0",
3
+ "version": "4.2.0",
4
4
  "engines": {
5
5
  "node": ">=22.5.0"
6
6
  },
@@ -18,8 +18,8 @@
18
18
  "dist"
19
19
  ],
20
20
  "dependencies": {
21
- "@basaltkit/core": "^1.5.0",
22
- "@basaltkit/http": "^2.7.0"
21
+ "@basaltkit/http": "^2.8.0",
22
+ "@basaltkit/core": "^1.6.0"
23
23
  },
24
24
  "peerDependencies": {
25
25
  "zod": "^4.0.0"
@@ -29,7 +29,7 @@
29
29
  "typescript": "^7.0.2",
30
30
  "vitest": "^5.0.1",
31
31
  "zod": "^4.6.5",
32
- "@basaltkit/fastify": "^2.5.0",
32
+ "@basaltkit/fastify": "^2.6.0",
33
33
  "@basaltkit/tsconfig": "^0.24.0"
34
34
  },
35
35
  "publishConfig": {