@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/README.md +45 -14
- package/dist/apikeys-plugin.d.ts +65 -3
- package/dist/apikeys-plugin.js +81 -9
- package/dist/apikeys.d.ts +163 -5
- package/dist/apikeys.js +305 -23
- package/dist/auth.d.ts +131 -2
- package/dist/auth.js +239 -21
- package/dist/index.d.ts +5 -5
- package/dist/index.js +3 -3
- package/dist/ip-allowlist.d.ts +22 -0
- package/dist/ip-allowlist.js +118 -0
- package/dist/plugin.d.ts +12 -0
- package/dist/plugin.js +24 -1
- package/dist/routes.d.ts +35 -4
- package/dist/routes.js +94 -29
- package/dist/secret-box.d.ts +1 -3
- package/dist/secret-box.js +48 -57
- package/dist/stores.d.ts +98 -10
- package/dist/stores.js +69 -10
- package/package.json +4 -4
package/dist/routes.js
CHANGED
|
@@ -2,7 +2,9 @@ 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';
|
|
7
|
+
import { ApiKeyNotFoundError } from './apikeys.js';
|
|
6
8
|
/**
|
|
7
9
|
* Route meta shared by the account routes (sign-in, profile, MFA self-service):
|
|
8
10
|
* `account: true` exempts them from tenant-membership guards (they are about
|
|
@@ -44,19 +46,32 @@ export function authRoutes(options = {}) {
|
|
|
44
46
|
// Every route here is about the caller's own account: exempt from the
|
|
45
47
|
// tenant-membership guard (`account`) and reachable before MFA (`mfa: false`).
|
|
46
48
|
const account = ACCOUNT_META;
|
|
49
|
+
const register = options.register;
|
|
47
50
|
return [
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
51
|
+
register === 'closed'
|
|
52
|
+
? // No body schema: every request gets the same 404, whatever it sends.
|
|
53
|
+
route({
|
|
54
|
+
method: 'POST',
|
|
55
|
+
url: '/auth/register',
|
|
56
|
+
meta: { ...account, ...limit },
|
|
57
|
+
handler() {
|
|
58
|
+
throw new RegistrationClosedError();
|
|
59
|
+
},
|
|
60
|
+
})
|
|
61
|
+
: route({
|
|
62
|
+
method: 'POST',
|
|
63
|
+
url: '/auth/register',
|
|
64
|
+
meta: { ...account, ...limit },
|
|
65
|
+
body: credentials,
|
|
66
|
+
// Enumeration-safe: the same 202 whether the email is new or already taken
|
|
67
|
+
// (a collision is signalled out-of-band via auth:register_existing_email),
|
|
68
|
+
// and whether a registration policy admitted it or not
|
|
69
|
+
// (auth:register_refused).
|
|
70
|
+
async handler({ body, reply }) {
|
|
71
|
+
await auth().registerSafely(body.email, body.password, register === undefined ? {} : { policy: register === 'open' ? null : register });
|
|
72
|
+
return reply.code(202).send({ ok: true });
|
|
73
|
+
},
|
|
74
|
+
}),
|
|
60
75
|
route({
|
|
61
76
|
method: 'POST',
|
|
62
77
|
url: '/auth/login',
|
|
@@ -166,17 +181,29 @@ export function authRoutes(options = {}) {
|
|
|
166
181
|
}),
|
|
167
182
|
];
|
|
168
183
|
}
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
}
|
|
184
|
+
/** `?includeExpired=true|false` — a query string is text, so coerce it explicitly. */
|
|
185
|
+
const queryBoolean = z
|
|
186
|
+
.enum(['true', 'false'])
|
|
187
|
+
.optional()
|
|
188
|
+
.transform((value) => value === 'true');
|
|
175
189
|
/**
|
|
176
|
-
*
|
|
177
|
-
*
|
|
178
|
-
*
|
|
179
|
-
*
|
|
190
|
+
* Self-service routes for API keys, all requiring a logged-in user
|
|
191
|
+
* (`meta.auth`) and refusing API keys (`meta.apiKey: false`, so a key can never
|
|
192
|
+
* mint, extend, rotate or unrestrict a key). Keys are scoped to the caller's
|
|
193
|
+
* tenant (`ctx().tenant`) and user; a caller only ever sees or changes keys
|
|
194
|
+
* within that scope, anything else is 404 `AUTH_APIKEY_NOT_FOUND`. Service keys
|
|
195
|
+
* (`serviceId`) have no user, so they are never reachable here: mint and manage
|
|
196
|
+
* them with `ApiKeys` behind the app's own permission check.
|
|
197
|
+
*
|
|
198
|
+
* - `POST /apikeys` issues a key (the plaintext `key` is returned once);
|
|
199
|
+
* - `GET /apikeys[?includeExpired=true]` lists live keys;
|
|
200
|
+
* - `PATCH /apikeys/:id` changes `name`, `scopes`, `expiresAt` (`null` = never),
|
|
201
|
+
* `allowedIps` and `meta` in one write;
|
|
202
|
+
* - `POST /apikeys/:id/rotate` replaces the secret (`graceMs` keeps the old one
|
|
203
|
+
* working that long) and returns the new `key` once;
|
|
204
|
+
* - `DELETE /apikeys/:id` revokes.
|
|
205
|
+
*
|
|
206
|
+
* Register alongside {@link authRoutes} and pair with `apiKeysPlugin`.
|
|
180
207
|
*/
|
|
181
208
|
export function apiKeyRoutes() {
|
|
182
209
|
// `tenant` is set by @basaltkit/tenancy when present; read it without a hard
|
|
@@ -188,6 +215,15 @@ export function apiKeyRoutes() {
|
|
|
188
215
|
...(c.user ? { userId: c.user.id } : {}),
|
|
189
216
|
};
|
|
190
217
|
};
|
|
218
|
+
/** The key, when it is within the caller's scope; otherwise 404. */
|
|
219
|
+
const owned = async (id) => {
|
|
220
|
+
const record = await apiKeys().get(id);
|
|
221
|
+
const { tenantId, userId } = scope();
|
|
222
|
+
if (!record || record.tenantId !== tenantId || record.userId !== userId)
|
|
223
|
+
throw new ApiKeyNotFoundError();
|
|
224
|
+
return record;
|
|
225
|
+
};
|
|
226
|
+
const meta = z.record(z.string(), z.string());
|
|
191
227
|
return [
|
|
192
228
|
route({
|
|
193
229
|
method: 'POST',
|
|
@@ -199,6 +235,8 @@ export function apiKeyRoutes() {
|
|
|
199
235
|
name: z.string().min(1).max(100),
|
|
200
236
|
scopes: z.array(z.string().min(1)).optional(),
|
|
201
237
|
expiresAt: z.number().int().positive().optional(),
|
|
238
|
+
allowedIps: z.array(z.string()).optional(),
|
|
239
|
+
meta: meta.optional(),
|
|
202
240
|
}),
|
|
203
241
|
async handler({ body, reply }) {
|
|
204
242
|
const { record, key } = await apiKeys().issue({ ...body, ...scope() });
|
|
@@ -212,8 +250,39 @@ export function apiKeyRoutes() {
|
|
|
212
250
|
// Session-only: a key must never mint, list or revoke keys (a narrow or
|
|
213
251
|
// expiring key could otherwise mint a permanent '*' key).
|
|
214
252
|
meta: { auth: true, apiKey: false },
|
|
215
|
-
|
|
216
|
-
|
|
253
|
+
query: z.object({ includeExpired: queryBoolean }),
|
|
254
|
+
async handler({ query }) {
|
|
255
|
+
return apiKeys().list({ ...scope(), includeExpired: query.includeExpired });
|
|
256
|
+
},
|
|
257
|
+
}),
|
|
258
|
+
route({
|
|
259
|
+
method: 'PATCH',
|
|
260
|
+
url: '/apikeys/:id',
|
|
261
|
+
meta: { auth: true, apiKey: false },
|
|
262
|
+
params: z.object({ id: z.string() }),
|
|
263
|
+
body: z.object({
|
|
264
|
+
name: z.string().min(1).max(100).optional(),
|
|
265
|
+
scopes: z.array(z.string().min(1)).optional(),
|
|
266
|
+
expiresAt: z.number().int().positive().nullable().optional(),
|
|
267
|
+
allowedIps: z.array(z.string()).nullable().optional(),
|
|
268
|
+
meta: meta.nullable().optional(),
|
|
269
|
+
}),
|
|
270
|
+
async handler({ params, body }) {
|
|
271
|
+
await owned(params.id);
|
|
272
|
+
return apiKeys().update(params.id, body);
|
|
273
|
+
},
|
|
274
|
+
}),
|
|
275
|
+
route({
|
|
276
|
+
method: 'POST',
|
|
277
|
+
url: '/apikeys/:id/rotate',
|
|
278
|
+
meta: { auth: true, apiKey: false },
|
|
279
|
+
params: z.object({ id: z.string() }),
|
|
280
|
+
body: z.object({ graceMs: z.number().int().min(0).optional() }).optional(),
|
|
281
|
+
async handler({ params, body, reply }) {
|
|
282
|
+
await owned(params.id);
|
|
283
|
+
const { record, key } = await apiKeys().rotate(params.id, { graceMs: body?.graceMs });
|
|
284
|
+
// The new `key` is returned exactly once.
|
|
285
|
+
return reply.code(201).send({ ...record, key });
|
|
217
286
|
},
|
|
218
287
|
}),
|
|
219
288
|
route({
|
|
@@ -222,12 +291,8 @@ export function apiKeyRoutes() {
|
|
|
222
291
|
meta: { auth: true, apiKey: false },
|
|
223
292
|
params: z.object({ id: z.string() }),
|
|
224
293
|
async handler({ params, reply }) {
|
|
225
|
-
const record = await apiKeys().get(params.id);
|
|
226
|
-
const { tenantId, userId } = scope();
|
|
227
294
|
// Only expose/act on keys within the caller's scope; otherwise 404.
|
|
228
|
-
|
|
229
|
-
throw new ApiKeyForbiddenError();
|
|
230
|
-
}
|
|
295
|
+
await owned(params.id);
|
|
231
296
|
await apiKeys().revoke(params.id);
|
|
232
297
|
return reply.code(204).send();
|
|
233
298
|
},
|
package/dist/secret-box.d.ts
CHANGED
|
@@ -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
|
|
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
|
}
|
package/dist/secret-box.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import {
|
|
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
|
-
/**
|
|
61
|
-
|
|
62
|
-
|
|
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
|
|
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
|
-
|
|
75
|
-
activeId;
|
|
91
|
+
box;
|
|
76
92
|
v1Keys;
|
|
77
93
|
acceptPlaintext;
|
|
78
94
|
constructor(options) {
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
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.
|
|
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
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
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
|
/**
|
|
@@ -147,28 +154,96 @@ export interface ApiKeyRecord {
|
|
|
147
154
|
expiresAt?: number;
|
|
148
155
|
lastUsedAt?: number;
|
|
149
156
|
revokedAt?: number;
|
|
157
|
+
/**
|
|
158
|
+
* The non-human actor this key acts as (opaque and app-defined, e.g.
|
|
159
|
+
* `erp-sync`). Mutually exclusive with `userId`; immutable once issued.
|
|
160
|
+
*/
|
|
161
|
+
serviceId?: string;
|
|
162
|
+
/**
|
|
163
|
+
* SHA-256 of the secret the last rotation replaced. It keeps verifying until
|
|
164
|
+
* `previousHashExpiresAt`. Never exposed in {@link ApiKeyInfo}.
|
|
165
|
+
*/
|
|
166
|
+
previousHash?: string;
|
|
167
|
+
/** When the pre-rotation secret stops verifying (ms). Absent: it already does not. */
|
|
168
|
+
previousHashExpiresAt?: number;
|
|
169
|
+
/** Time of the last rotation (ms). */
|
|
170
|
+
rotatedAt?: number;
|
|
171
|
+
/**
|
|
172
|
+
* Client addresses allowed to use the key: canonical IPv4/IPv6 addresses or
|
|
173
|
+
* CIDR networks. Absent or empty means any address.
|
|
174
|
+
*/
|
|
175
|
+
allowedIps?: string[];
|
|
176
|
+
/** Flat app metadata (who requested the key, a ticket, a label). Never used for authorization. */
|
|
177
|
+
meta?: Record<string, string>;
|
|
150
178
|
}
|
|
151
|
-
/** What a listing exposes — never
|
|
152
|
-
export type ApiKeyInfo = Omit<ApiKeyRecord, 'hash'>;
|
|
179
|
+
/** What a listing exposes — never a hash, current or previous. */
|
|
180
|
+
export type ApiKeyInfo = Omit<ApiKeyRecord, 'hash' | 'previousHash'>;
|
|
181
|
+
/**
|
|
182
|
+
* Narrows a listing. A store may use it to filter early, but `ApiKeys.list`
|
|
183
|
+
* re-applies every field itself: a store that ignores one never widens a result.
|
|
184
|
+
*/
|
|
153
185
|
export interface ApiKeyFilter {
|
|
154
186
|
tenantId?: string;
|
|
155
187
|
userId?: string;
|
|
188
|
+
serviceId?: string;
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* The mutable fields of a key, as `ApiKeyStore.update` receives them. `null`
|
|
192
|
+
* clears a field. Identity (`id`, `tenantId`, `userId`, `serviceId`,
|
|
193
|
+
* `createdAt`) is not part of it, and drivers ignore it at runtime too: moving
|
|
194
|
+
* a key to another owner would be a privilege transfer.
|
|
195
|
+
*/
|
|
196
|
+
export interface ApiKeyPatch {
|
|
197
|
+
name?: string;
|
|
198
|
+
scopes?: string[];
|
|
199
|
+
expiresAt?: number | null;
|
|
200
|
+
hash?: string;
|
|
201
|
+
prefix?: string;
|
|
202
|
+
previousHash?: string | null;
|
|
203
|
+
previousHashExpiresAt?: number | null;
|
|
204
|
+
rotatedAt?: number;
|
|
205
|
+
allowedIps?: string[] | null;
|
|
206
|
+
meta?: Record<string, string> | null;
|
|
207
|
+
}
|
|
208
|
+
/** Options of {@link ApiKeyStore.update}. */
|
|
209
|
+
export interface ApiKeyUpdateOptions {
|
|
210
|
+
/** Compare-and-set: apply only while the record's current `hash` still equals this value. */
|
|
211
|
+
ifHash?: string;
|
|
156
212
|
}
|
|
157
213
|
export interface ApiKeyStore {
|
|
158
214
|
create(record: ApiKeyRecord): Promise<void>;
|
|
215
|
+
/**
|
|
216
|
+
* The record whose `hash` equals `hash`. A store that implements
|
|
217
|
+
* {@link update} MUST also return the record whose `previousHash` equals it
|
|
218
|
+
* (rotation grace); `ApiKeys` re-checks the grace window itself.
|
|
219
|
+
*/
|
|
159
220
|
findByHash(hash: string): Promise<ApiKeyRecord | null>;
|
|
160
221
|
findById(id: string): Promise<ApiKeyRecord | null>;
|
|
161
222
|
/** Active (non-revoked) keys matching the filter. */
|
|
162
223
|
list(filter: ApiKeyFilter): Promise<ApiKeyRecord[]>;
|
|
163
224
|
touch(id: string, at: number): Promise<void>;
|
|
164
225
|
revoke(id: string, at: number): Promise<void>;
|
|
226
|
+
/**
|
|
227
|
+
* Applies `patch` atomically to a NON-revoked record — with `ifHash`, only
|
|
228
|
+
* while its current hash still equals it. Returns the updated record, or
|
|
229
|
+
* `null` when nothing matched (unknown, revoked, or the precondition failed).
|
|
230
|
+
*
|
|
231
|
+
* Optional, so stores written before it keep compiling; without it
|
|
232
|
+
* `ApiKeys.update`/`setExpiry`/`rotate` throw 501
|
|
233
|
+
* `AUTH_APIKEY_STORE_UNSUPPORTED`. Implementing it commits the store to the
|
|
234
|
+
* `previousHash` lookup in {@link findByHash}.
|
|
235
|
+
*/
|
|
236
|
+
update?(id: string, patch: ApiKeyPatch, options?: ApiKeyUpdateOptions): Promise<ApiKeyRecord | null>;
|
|
165
237
|
}
|
|
238
|
+
/** The fields an {@link ApiKeyPatch} may change — drivers apply nothing else. */
|
|
239
|
+
export declare const API_KEY_PATCH_FIELDS: readonly ["name", "scopes", "expiresAt", "hash", "prefix", "previousHash", "previousHashExpiresAt", "rotatedAt", "allowedIps", "meta"];
|
|
166
240
|
export declare class MemoryApiKeyStore implements ApiKeyStore {
|
|
167
241
|
private readonly records;
|
|
168
242
|
create(record: ApiKeyRecord): Promise<void>;
|
|
169
243
|
findByHash(hash: string): Promise<ApiKeyRecord | null>;
|
|
170
244
|
findById(id: string): Promise<ApiKeyRecord | null>;
|
|
171
245
|
list(filter: ApiKeyFilter): Promise<ApiKeyRecord[]>;
|
|
246
|
+
update(id: string, patch: ApiKeyPatch, options?: ApiKeyUpdateOptions): Promise<ApiKeyRecord | null>;
|
|
172
247
|
touch(id: string, at: number): Promise<void>;
|
|
173
248
|
revoke(id: string, at: number): Promise<void>;
|
|
174
249
|
}
|
|
@@ -233,6 +308,12 @@ export interface SessionRecord {
|
|
|
233
308
|
id: string;
|
|
234
309
|
userId: string;
|
|
235
310
|
expiresAt: number;
|
|
311
|
+
/**
|
|
312
|
+
* Last time the session was used (ms), for the idle timeout
|
|
313
|
+
* (`AuthOptions.sessionIdleTtl`). Stores that implement `touch` set it at
|
|
314
|
+
* creation and return it from `find`; absent on rows written before.
|
|
315
|
+
*/
|
|
316
|
+
lastSeenAt?: number;
|
|
236
317
|
}
|
|
237
318
|
export interface SessionStore {
|
|
238
319
|
create(userId: string, ttlMs: number): Promise<SessionRecord>;
|
|
@@ -245,12 +326,19 @@ export interface SessionStore {
|
|
|
245
326
|
* Optional so existing stores keep compiling; implement it to close the gap.
|
|
246
327
|
*/
|
|
247
328
|
deleteAllForUser?(userId: string): Promise<void>;
|
|
329
|
+
/**
|
|
330
|
+
* Records activity on a session (`lastSeenAt = at`); `id` is the raw id, as
|
|
331
|
+
* for `find`. Required by `AuthOptions.sessionIdleTtl`, optional otherwise.
|
|
332
|
+
* Auth throttles the calls, so a store sees at most a few per idle window.
|
|
333
|
+
*/
|
|
334
|
+
touch?(id: string, at: number): Promise<void>;
|
|
248
335
|
}
|
|
249
336
|
export declare class MemorySessionStore implements SessionStore {
|
|
250
337
|
private readonly sessions;
|
|
251
338
|
create(userId: string, ttlMs: number): Promise<SessionRecord>;
|
|
252
339
|
find(id: string): Promise<SessionRecord | null>;
|
|
253
340
|
delete(id: string): Promise<boolean>;
|
|
341
|
+
touch(id: string, at: number): Promise<void>;
|
|
254
342
|
deleteAllForUser(userId: string): Promise<void>;
|
|
255
343
|
}
|
|
256
344
|
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 = {
|
|
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
|
}
|
|
@@ -103,20 +108,41 @@ export class MemoryAuthTokenStore {
|
|
|
103
108
|
}
|
|
104
109
|
}
|
|
105
110
|
}
|
|
111
|
+
/** The fields an {@link ApiKeyPatch} may change — drivers apply nothing else. */
|
|
112
|
+
export const API_KEY_PATCH_FIELDS = [
|
|
113
|
+
'name',
|
|
114
|
+
'scopes',
|
|
115
|
+
'expiresAt',
|
|
116
|
+
'hash',
|
|
117
|
+
'prefix',
|
|
118
|
+
'previousHash',
|
|
119
|
+
'previousHashExpiresAt',
|
|
120
|
+
'rotatedAt',
|
|
121
|
+
'allowedIps',
|
|
122
|
+
'meta',
|
|
123
|
+
];
|
|
124
|
+
/** A detached copy, as a database returns: callers never alias the stored row. */
|
|
125
|
+
const copyApiKey = (record) => ({
|
|
126
|
+
...record,
|
|
127
|
+
scopes: [...record.scopes],
|
|
128
|
+
...(record.allowedIps !== undefined ? { allowedIps: [...record.allowedIps] } : {}),
|
|
129
|
+
...(record.meta !== undefined ? { meta: { ...record.meta } } : {}),
|
|
130
|
+
});
|
|
106
131
|
export class MemoryApiKeyStore {
|
|
107
132
|
records = new Map();
|
|
108
133
|
async create(record) {
|
|
109
|
-
this.records.set(record.id, record);
|
|
134
|
+
this.records.set(record.id, copyApiKey(record));
|
|
110
135
|
}
|
|
111
136
|
async findByHash(hash) {
|
|
112
137
|
for (const record of this.records.values()) {
|
|
113
|
-
if (record.hash === hash)
|
|
114
|
-
return record;
|
|
138
|
+
if (record.hash === hash || record.previousHash === hash)
|
|
139
|
+
return copyApiKey(record);
|
|
115
140
|
}
|
|
116
141
|
return null;
|
|
117
142
|
}
|
|
118
143
|
async findById(id) {
|
|
119
|
-
|
|
144
|
+
const record = this.records.get(id);
|
|
145
|
+
return record ? copyApiKey(record) : null;
|
|
120
146
|
}
|
|
121
147
|
async list(filter) {
|
|
122
148
|
const out = [];
|
|
@@ -127,10 +153,32 @@ export class MemoryApiKeyStore {
|
|
|
127
153
|
continue;
|
|
128
154
|
if (filter.userId !== undefined && record.userId !== filter.userId)
|
|
129
155
|
continue;
|
|
130
|
-
|
|
156
|
+
if (filter.serviceId !== undefined && record.serviceId !== filter.serviceId)
|
|
157
|
+
continue;
|
|
158
|
+
out.push(copyApiKey(record));
|
|
131
159
|
}
|
|
132
160
|
return out;
|
|
133
161
|
}
|
|
162
|
+
async update(id, patch, options = {}) {
|
|
163
|
+
const record = this.records.get(id);
|
|
164
|
+
if (!record || record.revokedAt !== undefined)
|
|
165
|
+
return null;
|
|
166
|
+
if (options.ifHash !== undefined && record.hash !== options.ifHash)
|
|
167
|
+
return null;
|
|
168
|
+
const target = record;
|
|
169
|
+
for (const field of API_KEY_PATCH_FIELDS) {
|
|
170
|
+
if (!Object.hasOwn(patch, field))
|
|
171
|
+
continue;
|
|
172
|
+
const value = patch[field];
|
|
173
|
+
if (value === undefined)
|
|
174
|
+
continue;
|
|
175
|
+
if (value === null)
|
|
176
|
+
delete target[field];
|
|
177
|
+
else
|
|
178
|
+
target[field] = Array.isArray(value) ? [...value] : typeof value === 'object' ? { ...value } : value;
|
|
179
|
+
}
|
|
180
|
+
return copyApiKey(record);
|
|
181
|
+
}
|
|
134
182
|
async touch(id, at) {
|
|
135
183
|
const record = this.records.get(id);
|
|
136
184
|
if (record)
|
|
@@ -192,9 +240,10 @@ export class MemorySessionStore {
|
|
|
192
240
|
// of the session table can't be replayed as a live session.
|
|
193
241
|
const rawId = randomBytes(32).toString('base64url');
|
|
194
242
|
const hashed = hashSessionId(rawId);
|
|
195
|
-
const
|
|
196
|
-
|
|
197
|
-
|
|
243
|
+
const now = Date.now();
|
|
244
|
+
const expiresAt = now + ttlMs;
|
|
245
|
+
this.sessions.set(hashed, { id: hashed, userId, expiresAt, lastSeenAt: now });
|
|
246
|
+
return { id: rawId, userId, expiresAt, lastSeenAt: now };
|
|
198
247
|
}
|
|
199
248
|
async find(id) {
|
|
200
249
|
const hashed = hashSessionId(id);
|
|
@@ -206,11 +255,21 @@ export class MemorySessionStore {
|
|
|
206
255
|
return null;
|
|
207
256
|
}
|
|
208
257
|
// Echo the id the caller queried with (never the stored hash).
|
|
209
|
-
return {
|
|
258
|
+
return {
|
|
259
|
+
id,
|
|
260
|
+
userId: record.userId,
|
|
261
|
+
expiresAt: record.expiresAt,
|
|
262
|
+
...(record.lastSeenAt !== undefined ? { lastSeenAt: record.lastSeenAt } : {}),
|
|
263
|
+
};
|
|
210
264
|
}
|
|
211
265
|
async delete(id) {
|
|
212
266
|
return this.sessions.delete(hashSessionId(id));
|
|
213
267
|
}
|
|
268
|
+
async touch(id, at) {
|
|
269
|
+
const record = this.sessions.get(hashSessionId(id));
|
|
270
|
+
if (record)
|
|
271
|
+
record.lastSeenAt = at;
|
|
272
|
+
}
|
|
214
273
|
async deleteAllForUser(userId) {
|
|
215
274
|
for (const [key, record] of this.sessions) {
|
|
216
275
|
if (record.userId === userId)
|