@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/apikeys.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { createHash, randomBytes, randomUUID } from 'node:crypto';
|
|
2
2
|
import { BasaltError } from '@basaltkit/core';
|
|
3
|
+
import { AllowlistError, API_KEY_ALLOWED_IPS_MAX, ipAllowed, normalizeAllowedIps } from './ip-allowlist.js';
|
|
3
4
|
import { MemoryApiKeyStore, } from './stores.js';
|
|
5
|
+
export { API_KEY_ALLOWED_IPS_MAX };
|
|
4
6
|
/** A route required a scope the presented key does not hold. */
|
|
5
7
|
export class ScopeRequiredError extends BasaltError {
|
|
6
8
|
status = 403;
|
|
@@ -14,71 +16,332 @@ export class ApiKeyExpirationError extends BasaltError {
|
|
|
14
16
|
super('AUTH_APIKEY_EXPIRATION_INVALID', 'API key expiration must be a future timestamp.');
|
|
15
17
|
}
|
|
16
18
|
}
|
|
19
|
+
/** No key with this id in scope, or it is revoked or expired (an expired key is dead: issue a new one). */
|
|
20
|
+
export class ApiKeyNotFoundError extends BasaltError {
|
|
21
|
+
status = 404;
|
|
22
|
+
constructor() {
|
|
23
|
+
super('AUTH_APIKEY_NOT_FOUND', 'API key not found.');
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Invalid input to an API key operation: a bad `allowedIps` entry, `meta` over
|
|
28
|
+
* its limits, `userId` together with `serviceId`, a malformed `serviceId` or
|
|
29
|
+
* `scopes`, or a rotation `graceMs` out of range.
|
|
30
|
+
*/
|
|
31
|
+
export class ApiKeyInputError extends BasaltError {
|
|
32
|
+
status = 400;
|
|
33
|
+
constructor(message) {
|
|
34
|
+
super('AUTH_APIKEY_INPUT_INVALID', message);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/** A concurrent rotation or revocation changed the key first; re-read it and retry. */
|
|
38
|
+
export class ApiKeyConflictError extends BasaltError {
|
|
39
|
+
status = 409;
|
|
40
|
+
constructor() {
|
|
41
|
+
super('AUTH_APIKEY_CONFLICT', 'The API key was changed concurrently; retry.');
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/** The configured `ApiKeyStore` does not implement `update`, which lifecycle operations need. */
|
|
45
|
+
export class ApiKeyStoreUnsupportedError extends BasaltError {
|
|
46
|
+
status = 501;
|
|
47
|
+
constructor(operation) {
|
|
48
|
+
super('AUTH_APIKEY_STORE_UNSUPPORTED', `The API key store does not support "${operation}": it does not implement ApiKeyStore.update.`);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/** The key is valid, but the request comes from an address outside its `allowedIps`. */
|
|
52
|
+
export class ApiKeyIpNotAllowedError extends BasaltError {
|
|
53
|
+
status = 403;
|
|
54
|
+
constructor() {
|
|
55
|
+
super('AUTH_APIKEY_IP_NOT_ALLOWED', 'This API key is not allowed from this address.');
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
/** Longest rotation grace window {@link ApiKeys.rotate} accepts: 30 days (the webhooks secret-rotation cap). */
|
|
59
|
+
export const MAX_API_KEY_ROTATION_GRACE_MS = 30 * 24 * 60 * 60 * 1000;
|
|
60
|
+
/** Limits on a key's `meta`: number of entries, key length, value length. */
|
|
61
|
+
export const API_KEY_META_LIMITS = { keys: 20, keyLength: 40, valueLength: 500 };
|
|
62
|
+
const META_KEY = /^[A-Za-z0-9_.-]+$/;
|
|
63
|
+
const FORBIDDEN_META_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
|
|
64
|
+
/** Printable ASCII without spaces, 1..128 characters. */
|
|
65
|
+
const SERVICE_ID = /^[\x21-\x7E]{1,128}$/;
|
|
66
|
+
/** Validates a key's `meta`; returns a fresh copy. Throws {@link ApiKeyInputError}. */
|
|
67
|
+
function normalizeMeta(meta) {
|
|
68
|
+
if (typeof meta !== 'object' || meta === null || Array.isArray(meta)) {
|
|
69
|
+
throw new ApiKeyInputError('meta must be an object of string values.');
|
|
70
|
+
}
|
|
71
|
+
const entries = Object.entries(meta);
|
|
72
|
+
if (entries.length > API_KEY_META_LIMITS.keys) {
|
|
73
|
+
throw new ApiKeyInputError(`meta holds at most ${API_KEY_META_LIMITS.keys} entries.`);
|
|
74
|
+
}
|
|
75
|
+
const out = {};
|
|
76
|
+
for (const [key, value] of entries) {
|
|
77
|
+
if (FORBIDDEN_META_KEYS.has(key) || !META_KEY.test(key) || key.length > API_KEY_META_LIMITS.keyLength) {
|
|
78
|
+
throw new ApiKeyInputError(`meta key ${JSON.stringify(key)} is invalid: 1-${API_KEY_META_LIMITS.keyLength} characters of A-Z, a-z, 0-9, "_", "." or "-" (not __proto__, constructor or prototype).`);
|
|
79
|
+
}
|
|
80
|
+
if (typeof value !== 'string' || value.length > API_KEY_META_LIMITS.valueLength) {
|
|
81
|
+
throw new ApiKeyInputError(`meta value of ${JSON.stringify(key)} must be a string of at most ${API_KEY_META_LIMITS.valueLength} characters.`);
|
|
82
|
+
}
|
|
83
|
+
out[key] = value;
|
|
84
|
+
}
|
|
85
|
+
return out;
|
|
86
|
+
}
|
|
87
|
+
/** Validates and canonicalises `allowedIps`. Throws {@link ApiKeyInputError}. */
|
|
88
|
+
function allowedIpsOf(value) {
|
|
89
|
+
try {
|
|
90
|
+
return normalizeAllowedIps(value);
|
|
91
|
+
}
|
|
92
|
+
catch (err) {
|
|
93
|
+
if (err instanceof AllowlistError)
|
|
94
|
+
throw new ApiKeyInputError(`allowedIps: ${err.message}.`);
|
|
95
|
+
throw err;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
function assertScopes(scopes) {
|
|
99
|
+
if (!Array.isArray(scopes) || !scopes.every((scope) => typeof scope === 'string' && scope.length > 0)) {
|
|
100
|
+
throw new ApiKeyInputError('scopes must be an array of non-empty strings.');
|
|
101
|
+
}
|
|
102
|
+
}
|
|
17
103
|
/** The prefix on every key. `mk` = Basalt key, `live` = environment. */
|
|
18
104
|
const KEY_PREFIX = 'mk_live_';
|
|
105
|
+
/** Secret characters kept in the display prefix (`ApiKeyRecord.prefix`). */
|
|
106
|
+
const DISPLAY_SECRET_CHARS = 6;
|
|
107
|
+
/**
|
|
108
|
+
* The display prefix of a presented key (`mk_live_` plus the first six secret
|
|
109
|
+
* characters), the same value `ApiKeyRecord.prefix` stores and listings show.
|
|
110
|
+
* Undefined for anything that is not shaped like a Basalt key, so an unrelated
|
|
111
|
+
* secret sent by mistake is never echoed into a hook payload or a log.
|
|
112
|
+
*/
|
|
113
|
+
export const apiKeyDisplayPrefix = (presented) => presented.startsWith(KEY_PREFIX) && presented.length >= KEY_PREFIX.length + DISPLAY_SECRET_CHARS
|
|
114
|
+
? presented.slice(0, KEY_PREFIX.length + DISPLAY_SECRET_CHARS)
|
|
115
|
+
: undefined;
|
|
19
116
|
/** SHA-256 is safe here: API keys are high-entropy, so no slow hash is needed. */
|
|
20
117
|
const hashKey = (key) => createHash('sha256').update(key).digest('hex');
|
|
118
|
+
/** A fresh secret: the plaintext key, its hash and its display prefix. */
|
|
119
|
+
const mintSecret = () => {
|
|
120
|
+
const secret = randomBytes(24).toString('base64url');
|
|
121
|
+
const key = `${KEY_PREFIX}${secret}`;
|
|
122
|
+
return { key, hash: hashKey(key), prefix: `${KEY_PREFIX}${secret.slice(0, DISPLAY_SECRET_CHARS)}` };
|
|
123
|
+
};
|
|
124
|
+
/** The public view of a record: never a hash, current or previous. */
|
|
21
125
|
const strip = (record) => {
|
|
22
|
-
const { hash: _hash, ...info } = record;
|
|
126
|
+
const { hash: _hash, previousHash: _previousHash, ...info } = record;
|
|
23
127
|
return info;
|
|
24
128
|
};
|
|
129
|
+
const isExpired = (record, now) => record.expiresAt !== undefined && record.expiresAt <= now;
|
|
25
130
|
/** True when `granted` covers `required` (an exact match or the `*` wildcard). */
|
|
26
131
|
export const scopesSatisfy = (granted, required) => granted.includes('*') || required.every((scope) => granted.includes(scope));
|
|
132
|
+
export class ApiKeyOptionsError extends BasaltError {
|
|
133
|
+
status = 500;
|
|
134
|
+
constructor(message) {
|
|
135
|
+
super('AUTH_APIKEY_OPTIONS_INVALID', message);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
/** Default `touchEveryMs`: one `lastUsedAt` write per key per minute. */
|
|
139
|
+
export const DEFAULT_API_KEY_TOUCH_EVERY_MS = 60_000;
|
|
140
|
+
/** Resolves and validates `touchEveryMs`; throws {@link ApiKeyOptionsError}. */
|
|
141
|
+
export function resolveTouchEveryMs(value) {
|
|
142
|
+
const touchEveryMs = value ?? DEFAULT_API_KEY_TOUCH_EVERY_MS;
|
|
143
|
+
if (typeof touchEveryMs !== 'number' || !Number.isFinite(touchEveryMs) || touchEveryMs < 0) {
|
|
144
|
+
throw new ApiKeyOptionsError(`apiKeys: touchEveryMs must be a finite number >= 0 (got ${String(touchEveryMs)}).`);
|
|
145
|
+
}
|
|
146
|
+
return touchEveryMs;
|
|
147
|
+
}
|
|
27
148
|
/**
|
|
28
149
|
* Issues and verifies API keys. The plaintext key is returned exactly once by
|
|
29
|
-
* {@link issue}; only its SHA-256 hash is stored, so a
|
|
30
|
-
* yields usable keys.
|
|
150
|
+
* {@link issue} (and {@link rotate}); only its SHA-256 hash is stored, so a
|
|
151
|
+
* leaked database never yields usable keys.
|
|
31
152
|
*/
|
|
32
153
|
export class ApiKeys {
|
|
33
154
|
store;
|
|
34
155
|
hooks;
|
|
35
156
|
now;
|
|
157
|
+
touchEveryMs;
|
|
36
158
|
constructor(options = {}) {
|
|
37
159
|
this.store = options.store ?? new MemoryApiKeyStore();
|
|
38
160
|
this.hooks = options.hooks;
|
|
39
161
|
this.now = options.now ?? Date.now;
|
|
162
|
+
this.touchEveryMs = resolveTouchEveryMs(options.touchEveryMs);
|
|
40
163
|
}
|
|
41
164
|
/** Mints a key. Returns the record plus the plaintext `key` (shown once). */
|
|
42
165
|
async issue(input) {
|
|
43
166
|
if (input.expiresAt !== undefined && (!Number.isInteger(input.expiresAt) || input.expiresAt <= this.now())) {
|
|
44
167
|
throw new ApiKeyExpirationError();
|
|
45
168
|
}
|
|
46
|
-
|
|
47
|
-
|
|
169
|
+
if (input.serviceId !== undefined) {
|
|
170
|
+
if (input.userId !== undefined) {
|
|
171
|
+
throw new ApiKeyInputError('A key acts as a user or as a service, not both: pass userId or serviceId.');
|
|
172
|
+
}
|
|
173
|
+
if (typeof input.serviceId !== 'string' || !SERVICE_ID.test(input.serviceId)) {
|
|
174
|
+
throw new ApiKeyInputError('serviceId must be 1-128 printable characters without spaces.');
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
if (input.scopes !== undefined)
|
|
178
|
+
assertScopes(input.scopes);
|
|
179
|
+
const allowedIps = input.allowedIps !== undefined ? allowedIpsOf(input.allowedIps) : [];
|
|
180
|
+
const meta = input.meta !== undefined ? normalizeMeta(input.meta) : {};
|
|
181
|
+
const { key, hash, prefix } = mintSecret();
|
|
48
182
|
const record = {
|
|
49
183
|
id: randomUUID(),
|
|
50
184
|
name: input.name,
|
|
51
|
-
prefix
|
|
52
|
-
hash
|
|
185
|
+
prefix,
|
|
186
|
+
hash,
|
|
53
187
|
scopes: input.scopes ?? ['*'],
|
|
54
188
|
createdAt: this.now(),
|
|
55
189
|
...(input.expiresAt !== undefined ? { expiresAt: input.expiresAt } : {}),
|
|
56
190
|
...(input.tenantId !== undefined ? { tenantId: input.tenantId } : {}),
|
|
57
191
|
...(input.userId !== undefined ? { userId: input.userId } : {}),
|
|
192
|
+
...(input.serviceId !== undefined ? { serviceId: input.serviceId } : {}),
|
|
193
|
+
...(allowedIps.length > 0 ? { allowedIps } : {}),
|
|
194
|
+
...(Object.keys(meta).length > 0 ? { meta } : {}),
|
|
58
195
|
};
|
|
59
196
|
await this.store.create(record);
|
|
60
|
-
await this.hooks?.emit('auth:apikey_issued', {
|
|
61
|
-
id: record.id,
|
|
62
|
-
...(record.tenantId !== undefined ? { tenantId: record.tenantId } : {}),
|
|
63
|
-
...(record.userId !== undefined ? { userId: record.userId } : {}),
|
|
64
|
-
});
|
|
197
|
+
await this.hooks?.emit('auth:apikey_issued', { id: record.id, ...ownerOf(record) });
|
|
65
198
|
return { record: strip(record), key };
|
|
66
199
|
}
|
|
67
200
|
/**
|
|
68
|
-
*
|
|
69
|
-
*
|
|
201
|
+
* Authenticates a presented key. Malformed, unknown, revoked and expired keys
|
|
202
|
+
* are `invalid`; a key whose `allowedIps` does not cover `options.ip` (or
|
|
203
|
+
* that has an allowlist and no ip to check) is `ip_not_allowed`. After a
|
|
204
|
+
* rotation the previous secret is accepted only until
|
|
205
|
+
* `previousHashExpiresAt`, re-checked here and never trusted to the store.
|
|
206
|
+
* Updates `lastUsedAt` on success only, at most once per `touchEveryMs`.
|
|
70
207
|
*/
|
|
71
|
-
async
|
|
208
|
+
async authenticate(presented, options = {}) {
|
|
72
209
|
if (!presented.startsWith(KEY_PREFIX))
|
|
73
|
-
return
|
|
74
|
-
const
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
210
|
+
return { ok: false, reason: 'invalid' };
|
|
211
|
+
const hash = hashKey(presented);
|
|
212
|
+
const record = await this.store.findByHash(hash);
|
|
213
|
+
if (!record)
|
|
214
|
+
return { ok: false, reason: 'invalid' };
|
|
215
|
+
const now = this.now();
|
|
216
|
+
if (record.hash !== hash) {
|
|
217
|
+
const inGrace = record.previousHash === hash && record.previousHashExpiresAt !== undefined && record.previousHashExpiresAt > now;
|
|
218
|
+
if (!inGrace)
|
|
219
|
+
return { ok: false, reason: 'invalid' };
|
|
220
|
+
}
|
|
221
|
+
if (record.revokedAt !== undefined || isExpired(record, now))
|
|
222
|
+
return { ok: false, reason: 'invalid' };
|
|
223
|
+
if (!ipAllowed(record.allowedIps, options.ip))
|
|
224
|
+
return { ok: false, reason: 'ip_not_allowed', record };
|
|
225
|
+
if (record.lastUsedAt === undefined || now - record.lastUsedAt >= this.touchEveryMs) {
|
|
226
|
+
await this.store.touch(record.id, now);
|
|
227
|
+
record.lastUsedAt = now;
|
|
228
|
+
}
|
|
229
|
+
return { ok: true, record };
|
|
79
230
|
}
|
|
80
|
-
|
|
81
|
-
|
|
231
|
+
/**
|
|
232
|
+
* Resolves a presented key to its record, or null if it's malformed,
|
|
233
|
+
* unknown, revoked, expired, or used from an address outside its
|
|
234
|
+
* `allowedIps`. Updates `lastUsedAt` on a hit, at most once per
|
|
235
|
+
* `touchEveryMs` per key.
|
|
236
|
+
*/
|
|
237
|
+
async verify(presented, options = {}) {
|
|
238
|
+
const result = await this.authenticate(presented, options);
|
|
239
|
+
return result.ok ? result.record : null;
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* Live keys matching the filter, without hashes. The filter is re-applied
|
|
243
|
+
* here, so a store that ignores one of its fields never widens the result.
|
|
244
|
+
* Expired keys are listed only with `includeExpired`; revoked ones never.
|
|
245
|
+
*/
|
|
246
|
+
async list(options) {
|
|
247
|
+
const { includeExpired = false, ...filter } = options;
|
|
248
|
+
const now = this.now();
|
|
249
|
+
return (await this.store.list(filter))
|
|
250
|
+
.filter((record) => record.revokedAt === undefined &&
|
|
251
|
+
(filter.tenantId === undefined || record.tenantId === filter.tenantId) &&
|
|
252
|
+
(filter.userId === undefined || record.userId === filter.userId) &&
|
|
253
|
+
(filter.serviceId === undefined || record.serviceId === filter.serviceId) &&
|
|
254
|
+
(includeExpired || !isExpired(record, now)))
|
|
255
|
+
.map(strip);
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* Changes a key's mutable fields in ONE store write; all input is validated
|
|
259
|
+
* first. An unknown, revoked or expired key is {@link ApiKeyNotFoundError}:
|
|
260
|
+
* an expired key cannot be renewed, issue a new one. Emits
|
|
261
|
+
* `auth:apikey_updated` with the changed field names (never the values).
|
|
262
|
+
*/
|
|
263
|
+
async update(id, input) {
|
|
264
|
+
const patch = {};
|
|
265
|
+
const changes = [];
|
|
266
|
+
if (input.name !== undefined) {
|
|
267
|
+
if (typeof input.name !== 'string' || input.name.length === 0)
|
|
268
|
+
throw new ApiKeyInputError('name must be a non-empty string.');
|
|
269
|
+
patch.name = input.name;
|
|
270
|
+
changes.push('name');
|
|
271
|
+
}
|
|
272
|
+
if (input.scopes !== undefined) {
|
|
273
|
+
assertScopes(input.scopes);
|
|
274
|
+
patch.scopes = [...input.scopes];
|
|
275
|
+
changes.push('scopes');
|
|
276
|
+
}
|
|
277
|
+
if (input.expiresAt !== undefined) {
|
|
278
|
+
if (input.expiresAt !== null && (!Number.isInteger(input.expiresAt) || input.expiresAt <= this.now())) {
|
|
279
|
+
throw new ApiKeyExpirationError();
|
|
280
|
+
}
|
|
281
|
+
patch.expiresAt = input.expiresAt;
|
|
282
|
+
changes.push('expiresAt');
|
|
283
|
+
}
|
|
284
|
+
if (input.allowedIps !== undefined) {
|
|
285
|
+
const allowedIps = input.allowedIps === null ? [] : allowedIpsOf(input.allowedIps);
|
|
286
|
+
patch.allowedIps = allowedIps.length > 0 ? allowedIps : null;
|
|
287
|
+
changes.push('allowedIps');
|
|
288
|
+
}
|
|
289
|
+
if (input.meta !== undefined) {
|
|
290
|
+
const meta = input.meta === null ? {} : normalizeMeta(input.meta);
|
|
291
|
+
patch.meta = Object.keys(meta).length > 0 ? meta : null;
|
|
292
|
+
changes.push('meta');
|
|
293
|
+
}
|
|
294
|
+
const update = this.requireUpdate('update');
|
|
295
|
+
const current = await this.live(id);
|
|
296
|
+
if (changes.length === 0)
|
|
297
|
+
return strip(current);
|
|
298
|
+
const updated = await update(id, patch);
|
|
299
|
+
// Revoked between the read and the write.
|
|
300
|
+
if (!updated)
|
|
301
|
+
throw new ApiKeyNotFoundError();
|
|
302
|
+
await this.hooks?.emit('auth:apikey_updated', { id, ...ownerOf(updated), changes });
|
|
303
|
+
return strip(updated);
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Sets when a key expires: a future timestamp (ms), or `null` for never. A
|
|
307
|
+
* thin wrapper over {@link update}; the same "expired is dead" rule applies.
|
|
308
|
+
*/
|
|
309
|
+
async setExpiry(id, expiresAt) {
|
|
310
|
+
return this.update(id, { expiresAt });
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* Replaces a key's secret, keeping its id (so its owner, scopes and audit
|
|
314
|
+
* trail stay). With `graceMs` the replaced secret keeps working that long —
|
|
315
|
+
* never past the key's own expiry or revocation; at most two secrets are ever
|
|
316
|
+
* live, so rotating during a grace window drops the oldest. Compare-and-set:
|
|
317
|
+
* when a concurrent rotation or revocation wins, this one throws
|
|
318
|
+
* {@link ApiKeyConflictError}. Returns the new plaintext `key` (shown once).
|
|
319
|
+
*/
|
|
320
|
+
async rotate(id, options = {}) {
|
|
321
|
+
const graceMs = options.graceMs ?? 0;
|
|
322
|
+
if (!Number.isInteger(graceMs) || graceMs < 0 || graceMs > MAX_API_KEY_ROTATION_GRACE_MS) {
|
|
323
|
+
throw new ApiKeyInputError(`graceMs must be an integer between 0 and ${MAX_API_KEY_ROTATION_GRACE_MS} (30 days).`);
|
|
324
|
+
}
|
|
325
|
+
const update = this.requireUpdate('rotate');
|
|
326
|
+
const current = await this.live(id);
|
|
327
|
+
const now = this.now();
|
|
328
|
+
const { key, hash, prefix } = mintSecret();
|
|
329
|
+
const graceUntil = graceMs > 0 ? Math.min(now + graceMs, current.expiresAt ?? Number.POSITIVE_INFINITY) : undefined;
|
|
330
|
+
const rotated = await update(id, {
|
|
331
|
+
hash,
|
|
332
|
+
prefix,
|
|
333
|
+
previousHash: graceUntil !== undefined ? current.hash : null,
|
|
334
|
+
previousHashExpiresAt: graceUntil ?? null,
|
|
335
|
+
rotatedAt: now,
|
|
336
|
+
}, { ifHash: current.hash });
|
|
337
|
+
if (!rotated)
|
|
338
|
+
throw new ApiKeyConflictError();
|
|
339
|
+
await this.hooks?.emit('auth:apikey_rotated', {
|
|
340
|
+
id,
|
|
341
|
+
...ownerOf(rotated),
|
|
342
|
+
...(graceUntil !== undefined ? { graceUntil } : {}),
|
|
343
|
+
});
|
|
344
|
+
return { record: strip(rotated), key };
|
|
82
345
|
}
|
|
83
346
|
/** Revokes a key by id. No-op if unknown or already revoked. */
|
|
84
347
|
async revoke(id) {
|
|
@@ -103,4 +366,23 @@ export class ApiKeys {
|
|
|
103
366
|
const record = await this.store.findById(id);
|
|
104
367
|
return record ? strip(record) : null;
|
|
105
368
|
}
|
|
369
|
+
requireUpdate(operation) {
|
|
370
|
+
const update = this.store.update;
|
|
371
|
+
if (typeof update !== 'function')
|
|
372
|
+
throw new ApiKeyStoreUnsupportedError(operation);
|
|
373
|
+
return update.bind(this.store);
|
|
374
|
+
}
|
|
375
|
+
/** The record behind a lifecycle operation: unknown, revoked and expired keys are all "not found". */
|
|
376
|
+
async live(id) {
|
|
377
|
+
const record = await this.store.findById(id);
|
|
378
|
+
if (!record || record.revokedAt !== undefined || isExpired(record, this.now()))
|
|
379
|
+
throw new ApiKeyNotFoundError();
|
|
380
|
+
return record;
|
|
381
|
+
}
|
|
106
382
|
}
|
|
383
|
+
/** The owner fields every lifecycle hook carries. */
|
|
384
|
+
const ownerOf = (record) => ({
|
|
385
|
+
...(record.tenantId !== undefined ? { tenantId: record.tenantId } : {}),
|
|
386
|
+
...(record.userId !== undefined ? { userId: record.userId } : {}),
|
|
387
|
+
...(record.serviceId !== undefined ? { serviceId: record.serviceId } : {}),
|
|
388
|
+
});
|
package/dist/auth.d.ts
CHANGED
|
@@ -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,36 @@ 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 explicit `false` on such a name refuses the
|
|
167
|
+
* boot with `AUTH_SESSION_COOKIE_INVALID` ({@link SessionCookieConfigError}).
|
|
141
168
|
*/
|
|
142
169
|
secure?: boolean;
|
|
143
170
|
}
|
|
171
|
+
/**
|
|
172
|
+
* The session cookie options violate the rules of the cookie name's prefix
|
|
173
|
+
* (`__Secure-` without `Secure`, `__Host-` without `Secure` or with a path
|
|
174
|
+
* other than `/`). Browsers drop such a cookie, so every login would
|
|
175
|
+
* "succeed" without a session; thrown at boot with code
|
|
176
|
+
* `AUTH_SESSION_COOKIE_INVALID`.
|
|
177
|
+
*/
|
|
178
|
+
export declare class SessionCookieConfigError extends BasaltError {
|
|
179
|
+
readonly status = 500;
|
|
180
|
+
constructor(message: string);
|
|
181
|
+
}
|
|
182
|
+
/** `sessionIdleTtl` cannot be honoured as configured. */
|
|
183
|
+
export declare class SessionIdleConfigError extends BasaltError {
|
|
184
|
+
readonly status = 500;
|
|
185
|
+
constructor(message: string);
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Validates the session options the way `new Auth()` does, without building
|
|
189
|
+
* it — so `authPlugin` refuses a bad configuration at registration rather
|
|
190
|
+
* than on the first request. Pure: no I/O.
|
|
191
|
+
*/
|
|
192
|
+
export declare function assertSessionOptions(options: Pick<AuthOptions, 'sessionCookie' | 'sessionIdleTtl' | 'sessions'>): void;
|
|
144
193
|
export interface AuthOptions {
|
|
145
194
|
users: UserSource;
|
|
146
195
|
secret: string;
|
|
@@ -149,7 +198,21 @@ export interface AuthOptions {
|
|
|
149
198
|
refreshTokens?: RefreshTokenStore;
|
|
150
199
|
accessTtl?: DurationInput;
|
|
151
200
|
refreshTtl?: DurationInput;
|
|
201
|
+
/** Absolute lifetime of a server-side session. Default `30d`. */
|
|
152
202
|
sessionTtl?: DurationInput;
|
|
203
|
+
/**
|
|
204
|
+
* Idle timeout: a session unused for longer than this is refused and
|
|
205
|
+
* deleted, whatever its absolute `sessionTtl`. Activity is recorded with the
|
|
206
|
+
* store's `touch` at most once per `min(60s, sessionIdleTtl / 4)`, so the
|
|
207
|
+
* effective idle limit can be that much longer. Requires a session store
|
|
208
|
+
* that implements `touch` (memory, auth-sqlite, auth-prisma with
|
|
209
|
+
* `trackSessionActivity`); construction fails otherwise. A session with no
|
|
210
|
+
* `lastSeenAt` (a legacy row) starts its idle clock on its next use; one
|
|
211
|
+
* that has it is measured from it, and nothing touches it while this option
|
|
212
|
+
* is off, so enabling it signs out sessions created longer ago than the
|
|
213
|
+
* window once. Default: no idle timeout.
|
|
214
|
+
*/
|
|
215
|
+
sessionIdleTtl?: DurationInput;
|
|
153
216
|
sessionCookie?: SessionCookieOptions;
|
|
154
217
|
hooks?: HookBus;
|
|
155
218
|
/** Brute-force lockout (per email). Enabled by default; pass `false` to disable. */
|
|
@@ -186,6 +249,14 @@ export interface AuthOptions {
|
|
|
186
249
|
* lower-level {@link Auth.register} always throws on a duplicate. Default true.
|
|
187
250
|
*/
|
|
188
251
|
enumerationSafeRegister?: boolean;
|
|
252
|
+
/**
|
|
253
|
+
* Who may create a NEW account through the self-service paths: the public
|
|
254
|
+
* register route ({@link Auth.registerSafely}, unless `authRoutes({ register })`
|
|
255
|
+
* overrides it) and the create branch of {@link Auth.socialLogin}. Logins into
|
|
256
|
+
* existing accounts and the trusted {@link Auth.register} are never gated.
|
|
257
|
+
* Default: open.
|
|
258
|
+
*/
|
|
259
|
+
registerPolicy?: RegisterPolicy;
|
|
189
260
|
/** Store for verification/reset tokens. Default: in-memory. */
|
|
190
261
|
tokens?: AuthTokenStore;
|
|
191
262
|
/** Email-verification link lifetime. Default 24h. */
|
|
@@ -243,6 +314,8 @@ export declare class Auth {
|
|
|
243
314
|
private readonly accessTtl;
|
|
244
315
|
private readonly refreshTtl;
|
|
245
316
|
private readonly sessionTtl;
|
|
317
|
+
private readonly sessionIdleMs;
|
|
318
|
+
private readonly sessionTouchEveryMs;
|
|
246
319
|
private readonly sessionCookie;
|
|
247
320
|
private readonly hooks;
|
|
248
321
|
private readonly throttle;
|
|
@@ -257,8 +330,44 @@ export declare class Auth {
|
|
|
257
330
|
private readonly mfaBox;
|
|
258
331
|
private readonly tokenVersions;
|
|
259
332
|
private readonly enumerationSafeRegister;
|
|
333
|
+
private readonly registerPolicy;
|
|
260
334
|
constructor(options: AuthOptions);
|
|
261
|
-
|
|
335
|
+
/**
|
|
336
|
+
* Trusted, server-side account creation (seeding, a back-office, a flow that
|
|
337
|
+
* proved the address before creating the account). Throws
|
|
338
|
+
* {@link EmailTakenError} on a duplicate and is never gated by a
|
|
339
|
+
* {@link RegisterPolicy}. `emailVerified: true` creates the account already
|
|
340
|
+
* verified; `auth:registered` then carries the final state, so a mail hook
|
|
341
|
+
* can decide "unverified → send the verification link" on its own. Never
|
|
342
|
+
* forward this option from a request body.
|
|
343
|
+
*
|
|
344
|
+
* `emailVerified: true` needs a `UserSource` with `update()` — the same
|
|
345
|
+
* requirement as email verification. Without it this throws
|
|
346
|
+
* {@link UserUpdateUnsupportedError} **before** anything is written: whether
|
|
347
|
+
* `create()` persists the flag can only be learnt by writing the row, and a
|
|
348
|
+
* row that cannot be fixed afterwards would be a half-done registration
|
|
349
|
+
* (an unverified account that a retry reports as `EmailTakenError`).
|
|
350
|
+
*/
|
|
351
|
+
register(rawEmail: string, password: string, opts?: {
|
|
352
|
+
emailVerified?: boolean;
|
|
353
|
+
}): Promise<PublicUser>;
|
|
354
|
+
/**
|
|
355
|
+
* Creates the row with the requested verification state. A custom
|
|
356
|
+
* `UserSource` written before `create()` took `emailVerified` may drop the
|
|
357
|
+
* flag: it is then set through `update()`.
|
|
358
|
+
*
|
|
359
|
+
* When the source can do neither (no `update()` and a `create()` that drops
|
|
360
|
+
* the flag), `onUnsupported` decides: `'throw'` fails loudly with
|
|
361
|
+
* {@link UserUpdateUnsupportedError} (trusted `register`, whose caller asked
|
|
362
|
+
* for a verified account and must hear it did not get one — `register`
|
|
363
|
+
* refuses a source without `update()` before calling this, so here it only
|
|
364
|
+
* fires for an `update()` that does not persist the flag); `'keep'` returns
|
|
365
|
+
* the row as it really is, unverified (social login — the row was just
|
|
366
|
+
* created by this call with an unusable password, so it is provably ours and
|
|
367
|
+
* must be linked and used, never left behind as an orphan that locks the
|
|
368
|
+
* provider account out on every later login).
|
|
369
|
+
*/
|
|
370
|
+
private createUser;
|
|
262
371
|
/**
|
|
263
372
|
* Logs in an externally-authenticated user (e.g. from an OAuth provider) —
|
|
264
373
|
* find-or-create. A new account is created **passwordless** (a random,
|
|
@@ -299,6 +408,11 @@ export declare class Auth {
|
|
|
299
408
|
* that legitimately re-issues subjects (a directory migration).
|
|
300
409
|
*/
|
|
301
410
|
subjectConflict?: 'refuse' | 'link';
|
|
411
|
+
/**
|
|
412
|
+
* The tenant this login happens on, for the {@link RegisterPolicy}.
|
|
413
|
+
* Default: the current request's `ctx().tenant?.id`.
|
|
414
|
+
*/
|
|
415
|
+
tenantId?: string;
|
|
302
416
|
}): Promise<{
|
|
303
417
|
user: PublicUser;
|
|
304
418
|
tokens: TokenPair;
|
|
@@ -325,8 +439,17 @@ export declare class Auth {
|
|
|
325
439
|
*
|
|
326
440
|
* With `enumerationSafeRegister: false` it throws {@link EmailTakenError} on a
|
|
327
441
|
* duplicate instead (the classic, enumerable behavior).
|
|
442
|
+
*
|
|
443
|
+
* A {@link RegisterPolicy} (`opts.policy`, else `registerPolicy` of the
|
|
444
|
+
* options; `null` = open) is asked first. A refusal creates nothing, does the
|
|
445
|
+
* same hashing work and emits `auth:register_refused` — the caller sees the
|
|
446
|
+
* same outcome as a success, so the response never tells who was invited.
|
|
447
|
+
* Never creates a verified account.
|
|
328
448
|
*/
|
|
329
|
-
registerSafely(rawEmail: string, password: string
|
|
449
|
+
registerSafely(rawEmail: string, password: string, opts?: {
|
|
450
|
+
policy?: RegisterPolicy | null;
|
|
451
|
+
tenantId?: string;
|
|
452
|
+
}): Promise<void>;
|
|
330
453
|
/** Verifies credentials without side effects. Null on failure. */
|
|
331
454
|
attempt(email: string, password: string): Promise<AuthUser | null>;
|
|
332
455
|
private dummyHashPromise?;
|
|
@@ -407,6 +530,12 @@ export declare class Auth {
|
|
|
407
530
|
user: AuthUser;
|
|
408
531
|
amr?: string[];
|
|
409
532
|
} | null>;
|
|
533
|
+
/**
|
|
534
|
+
* Applies the idle timeout: refuses (and deletes) a session idle for longer
|
|
535
|
+
* than `sessionIdleTtl`, otherwise records the activity, throttled. A no-op
|
|
536
|
+
* without `sessionIdleTtl`.
|
|
537
|
+
*/
|
|
538
|
+
private sessionStillActive;
|
|
410
539
|
logout(sessionId: string): Promise<void>;
|
|
411
540
|
/**
|
|
412
541
|
* Starts email verification: mints a single-use token and emits
|