@basaltkit/auth 4.2.0 → 5.1.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 +23 -6
- package/dist/apikeys-plugin.d.ts +25 -5
- package/dist/apikeys-plugin.js +18 -3
- package/dist/apikeys.d.ts +138 -5
- package/dist/apikeys.js +272 -23
- package/dist/auth.d.ts +21 -8
- package/dist/auth.js +49 -24
- package/dist/index.d.ts +3 -2
- package/dist/index.js +2 -1
- package/dist/ip-allowlist.d.ts +22 -0
- package/dist/ip-allowlist.js +118 -0
- package/dist/plugin.d.ts +10 -0
- package/dist/plugin.js +6 -1
- package/dist/routes.d.ts +17 -4
- package/dist/routes.js +68 -17
- package/dist/stores.d.ts +70 -2
- package/dist/stores.js +48 -5
- package/dist/token-claims.d.ts +75 -0
- package/dist/token-claims.js +83 -0
- package/package.json +7 -7
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { BlockList, isIP } from 'node:net';
|
|
2
|
+
/** Maximum entries in one key's `allowedIps`. */
|
|
3
|
+
export const API_KEY_ALLOWED_IPS_MAX = 32;
|
|
4
|
+
/** Why an allowlist was refused; `ApiKeys` wraps it in `ApiKeyInputError`. */
|
|
5
|
+
export class AllowlistError extends Error {
|
|
6
|
+
}
|
|
7
|
+
const V4_MAPPED = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i;
|
|
8
|
+
/** IPv4-mapped IPv6 (`::ffff:a.b.c.d`) as plain IPv4; IPv6 lower-cased. Assumes a valid address. */
|
|
9
|
+
const canonicalAddress = (address) => {
|
|
10
|
+
const mapped = V4_MAPPED.exec(address);
|
|
11
|
+
if (mapped && isIP(mapped[1]) === 4)
|
|
12
|
+
return mapped[1];
|
|
13
|
+
return isIP(address) === 6 ? address.toLowerCase() : address;
|
|
14
|
+
};
|
|
15
|
+
/** The 128-bit (or 32-bit) value of an address. */
|
|
16
|
+
function toBigInt(address, family) {
|
|
17
|
+
if (family === 4)
|
|
18
|
+
return address.split('.').reduce((n, part) => (n << 8n) | BigInt(Number(part)), 0n);
|
|
19
|
+
// Expand `::` and an embedded dotted-quad tail.
|
|
20
|
+
let text = address;
|
|
21
|
+
const dotted = /(\d{1,3}(?:\.\d{1,3}){3})$/.exec(text);
|
|
22
|
+
if (dotted) {
|
|
23
|
+
const v4 = toBigInt(dotted[1], 4);
|
|
24
|
+
text = `${text.slice(0, -dotted[1].length)}${(v4 >> 16n).toString(16)}:${(v4 & 0xffffn).toString(16)}`;
|
|
25
|
+
}
|
|
26
|
+
const [head = '', tail] = text.split('::');
|
|
27
|
+
const left = head ? head.split(':') : [];
|
|
28
|
+
const right = tail !== undefined && tail !== '' ? tail.split(':') : [];
|
|
29
|
+
const groups = tail === undefined ? left : [...left, ...Array(8 - left.length - right.length).fill('0'), ...right];
|
|
30
|
+
return groups.reduce((n, group) => (n << 16n) | BigInt(parseInt(group, 16)), 0n);
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Validates and canonicalises one allowlist entry: an address or an
|
|
34
|
+
* `address/prefix` network. Zone ids are refused, and so is a CIDR whose
|
|
35
|
+
* address has host bits set (`10.0.0.5/8`) — a typo should surface, not be
|
|
36
|
+
* silently masked.
|
|
37
|
+
*/
|
|
38
|
+
function canonicalEntry(raw) {
|
|
39
|
+
if (typeof raw !== 'string' || raw.length === 0 || raw.length > 64)
|
|
40
|
+
throw new AllowlistError(`invalid entry ${JSON.stringify(raw)}`);
|
|
41
|
+
if (raw.includes('%'))
|
|
42
|
+
throw new AllowlistError(`zone ids are not allowed (${raw})`);
|
|
43
|
+
const slash = raw.indexOf('/');
|
|
44
|
+
const addressPart = slash === -1 ? raw : raw.slice(0, slash);
|
|
45
|
+
if (isIP(addressPart) === 0)
|
|
46
|
+
throw new AllowlistError(`not an IP address: ${raw}`);
|
|
47
|
+
const address = canonicalAddress(addressPart);
|
|
48
|
+
const family = isIP(address);
|
|
49
|
+
if (slash === -1)
|
|
50
|
+
return address;
|
|
51
|
+
const prefixText = raw.slice(slash + 1);
|
|
52
|
+
const bits = family === 4 ? 32 : 128;
|
|
53
|
+
// A mapped address keeps its IPv6 prefix length relative to 128 bits.
|
|
54
|
+
const mappedShift = family === 4 && isIP(addressPart) === 6 ? 96 : 0;
|
|
55
|
+
if (!/^\d{1,3}$/.test(prefixText))
|
|
56
|
+
throw new AllowlistError(`invalid prefix length: ${raw}`);
|
|
57
|
+
const rawPrefix = Number(prefixText);
|
|
58
|
+
const prefix = rawPrefix - mappedShift;
|
|
59
|
+
if (rawPrefix > (mappedShift ? 128 : bits) || prefix < 0)
|
|
60
|
+
throw new AllowlistError(`invalid prefix length: ${raw}`);
|
|
61
|
+
const hostBits = BigInt(bits - prefix);
|
|
62
|
+
if (hostBits > 0n && (toBigInt(address, family) & ((1n << hostBits) - 1n)) !== 0n) {
|
|
63
|
+
throw new AllowlistError(`${raw} is not a network address (host bits are set)`);
|
|
64
|
+
}
|
|
65
|
+
return `${address}/${prefix}`;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Validates and canonicalises a key's `allowedIps`. Duplicates are dropped.
|
|
69
|
+
* Throws {@link AllowlistError}.
|
|
70
|
+
*/
|
|
71
|
+
export function normalizeAllowedIps(entries) {
|
|
72
|
+
if (!Array.isArray(entries))
|
|
73
|
+
throw new AllowlistError('allowedIps must be an array');
|
|
74
|
+
if (entries.length > API_KEY_ALLOWED_IPS_MAX) {
|
|
75
|
+
throw new AllowlistError(`allowedIps holds at most ${API_KEY_ALLOWED_IPS_MAX} entries`);
|
|
76
|
+
}
|
|
77
|
+
return [...new Set(entries.map(canonicalEntry))];
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* A request address as an adapter reports it, normalised for a check: brackets
|
|
81
|
+
* and a `%zone` suffix stripped, IPv4-mapped IPv6 as IPv4. `undefined` when it
|
|
82
|
+
* is not an address at all.
|
|
83
|
+
*/
|
|
84
|
+
export function normalizeRequestIp(ip) {
|
|
85
|
+
if (typeof ip !== 'string' || ip.length === 0)
|
|
86
|
+
return undefined;
|
|
87
|
+
let text = ip.trim();
|
|
88
|
+
if (text.startsWith('[') && text.endsWith(']'))
|
|
89
|
+
text = text.slice(1, -1);
|
|
90
|
+
const zone = text.indexOf('%');
|
|
91
|
+
if (zone !== -1)
|
|
92
|
+
text = text.slice(0, zone);
|
|
93
|
+
return isIP(text) === 0 ? undefined : canonicalAddress(text);
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Whether `ip` is inside a (canonical) allowlist. An empty or absent list
|
|
97
|
+
* allows any address; a non-empty one refuses an unknown or unparseable
|
|
98
|
+
* address — it fails closed. Built per check: at most 32 entries, no cache.
|
|
99
|
+
*/
|
|
100
|
+
export function ipAllowed(allowedIps, ip) {
|
|
101
|
+
if (!allowedIps || allowedIps.length === 0)
|
|
102
|
+
return true;
|
|
103
|
+
const address = normalizeRequestIp(ip);
|
|
104
|
+
if (address === undefined)
|
|
105
|
+
return false;
|
|
106
|
+
const list = new BlockList();
|
|
107
|
+
for (const entry of allowedIps) {
|
|
108
|
+
const slash = entry.indexOf('/');
|
|
109
|
+
if (slash === -1) {
|
|
110
|
+
list.addAddress(entry, isIP(entry) === 6 ? 'ipv6' : 'ipv4');
|
|
111
|
+
}
|
|
112
|
+
else {
|
|
113
|
+
const network = entry.slice(0, slash);
|
|
114
|
+
list.addSubnet(network, Number(entry.slice(slash + 1)), isIP(network) === 6 ? 'ipv6' : 'ipv4');
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return list.check(address, isIP(address) === 6 ? 'ipv6' : 'ipv4');
|
|
118
|
+
}
|
package/dist/plugin.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { BasaltError, type RequestContext } from '@basaltkit/core';
|
|
2
2
|
import { Auth, type AuthOptions } from './auth.js';
|
|
3
3
|
import type { PublicUser } from './stores.js';
|
|
4
|
+
import { type VerifyClaimsFn } from './token-claims.js';
|
|
4
5
|
declare module '@basaltkit/core' {
|
|
5
6
|
interface RequestContext {
|
|
6
7
|
/** The authenticated user of the current request, set by auth. */
|
|
@@ -138,6 +139,15 @@ export interface AuthPluginOptions extends Omit<AuthOptions, 'hooks'> {
|
|
|
138
139
|
* requires MFA on a single route (step-up). Default: off.
|
|
139
140
|
*/
|
|
140
141
|
requireMfa?: boolean | ((user: PublicUser, context: RequestContext) => boolean | Promise<boolean>);
|
|
142
|
+
/**
|
|
143
|
+
* Checks the claims of every bearer access token on the request it
|
|
144
|
+
* authenticates, after the signature, expiry and token version passed and
|
|
145
|
+
* before the user is looked up. `false` refuses the request (a throw fails it):
|
|
146
|
+
* 401 `AUTH_TOKEN_CLAIMS_REJECTED`. Pair it with `tokenClaims`;
|
|
147
|
+
* `tenantBoundTokens()` gives both for a tenant binding. Sessions and API
|
|
148
|
+
* keys are not tokens and are not passed here. Default: none.
|
|
149
|
+
*/
|
|
150
|
+
verifyClaims?: VerifyClaimsFn;
|
|
141
151
|
}
|
|
142
152
|
/**
|
|
143
153
|
* Whether the request's session cookie failed the CSRF check (so it must not
|
package/dist/plugin.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { BasaltError, createToken, definePlugin, ensureMetadata } from '@basaltkit/core';
|
|
2
2
|
import { Auth, AuthRequiredError, isAmr, MfaEnrollmentRequiredError, MfaStepUpRequiredError, } from './auth.js';
|
|
3
3
|
import { assertSessionOptions, publicUser } from './auth.js';
|
|
4
|
+
import { TokenClaimsRejectedError } from './token-claims.js';
|
|
4
5
|
export const AUTH = createToken('auth');
|
|
5
6
|
/** A cookie-authenticated, state-changing request came from another origin. */
|
|
6
7
|
export class CsrfRejectedError extends BasaltError {
|
|
@@ -56,7 +57,7 @@ const csrfRejected = new WeakSet();
|
|
|
56
57
|
*/
|
|
57
58
|
export const isCsrfRejected = (context) => csrfRejected.has(context);
|
|
58
59
|
export function authPlugin(pluginOptions) {
|
|
59
|
-
const { csrf, requireMfa, ...options } = pluginOptions;
|
|
60
|
+
const { csrf, requireMfa, verifyClaims, ...options } = pluginOptions;
|
|
60
61
|
const trustedOrigins = new Set((csrf ? (csrf.trustedOrigins ?? []) : []).map((o) => originOf(o)).filter((o) => o !== null));
|
|
61
62
|
return definePlugin({
|
|
62
63
|
name: 'basalt:auth',
|
|
@@ -86,6 +87,10 @@ export function authPlugin(pluginOptions) {
|
|
|
86
87
|
// `mk_`-prefixed bearers are API keys — left to apiKeysPlugin.
|
|
87
88
|
if (bearer && !bearer.startsWith('mk_')) {
|
|
88
89
|
const claims = await auth.verifyAccessToken(bearer);
|
|
90
|
+
// Before the lookup: a token from another plane must not resolve
|
|
91
|
+
// whatever user happens to share its `sub` there.
|
|
92
|
+
if (verifyClaims && (await verifyClaims(claims, context)) !== true)
|
|
93
|
+
throw new TokenClaimsRejectedError();
|
|
89
94
|
const user = await auth.users.findById(claims.sub);
|
|
90
95
|
if (user) {
|
|
91
96
|
context.user = publicUser(user);
|
package/dist/routes.d.ts
CHANGED
|
@@ -81,10 +81,23 @@ export declare const DEFAULT_AUTH_RATE_LIMIT: {
|
|
|
81
81
|
*/
|
|
82
82
|
export declare function authRoutes(options?: AuthRoutesOptions): BasaltRoute[];
|
|
83
83
|
/**
|
|
84
|
-
*
|
|
85
|
-
*
|
|
86
|
-
*
|
|
87
|
-
*
|
|
84
|
+
* Self-service routes for API keys, all requiring a logged-in user
|
|
85
|
+
* (`meta.auth`) and refusing API keys (`meta.apiKey: false`, so a key can never
|
|
86
|
+
* mint, extend, rotate or unrestrict a key). Keys are scoped to the caller's
|
|
87
|
+
* tenant (`ctx().tenant`) and user; a caller only ever sees or changes keys
|
|
88
|
+
* within that scope, anything else is 404 `AUTH_APIKEY_NOT_FOUND`. Service keys
|
|
89
|
+
* (`serviceId`) have no user, so they are never reachable here: mint and manage
|
|
90
|
+
* them with `ApiKeys` behind the app's own permission check.
|
|
91
|
+
*
|
|
92
|
+
* - `POST /apikeys` issues a key (the plaintext `key` is returned once);
|
|
93
|
+
* - `GET /apikeys[?includeExpired=true]` lists live keys;
|
|
94
|
+
* - `PATCH /apikeys/:id` changes `name`, `scopes`, `expiresAt` (`null` = never),
|
|
95
|
+
* `allowedIps` and `meta` in one write;
|
|
96
|
+
* - `POST /apikeys/:id/rotate` replaces the secret (`graceMs` keeps the old one
|
|
97
|
+
* working that long) and returns the new `key` once;
|
|
98
|
+
* - `DELETE /apikeys/:id` revokes.
|
|
99
|
+
*
|
|
100
|
+
* Register alongside {@link authRoutes} and pair with `apiKeysPlugin`.
|
|
88
101
|
*/
|
|
89
102
|
export declare function apiKeyRoutes(): BasaltRoute[];
|
|
90
103
|
/**
|
package/dist/routes.js
CHANGED
|
@@ -4,6 +4,7 @@ import { z } from 'zod';
|
|
|
4
4
|
import { AUTH, CsrfRejectedError, isCsrfRejected } from './plugin.js';
|
|
5
5
|
import { RegistrationClosedError } from './auth.js';
|
|
6
6
|
import { API_KEYS } from './apikeys-plugin.js';
|
|
7
|
+
import { ApiKeyNotFoundError } from './apikeys.js';
|
|
7
8
|
/**
|
|
8
9
|
* Route meta shared by the account routes (sign-in, profile, MFA self-service):
|
|
9
10
|
* `account: true` exempts them from tenant-membership guards (they are about
|
|
@@ -180,17 +181,29 @@ export function authRoutes(options = {}) {
|
|
|
180
181
|
}),
|
|
181
182
|
];
|
|
182
183
|
}
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
}
|
|
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');
|
|
189
189
|
/**
|
|
190
|
-
*
|
|
191
|
-
*
|
|
192
|
-
*
|
|
193
|
-
*
|
|
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`.
|
|
194
207
|
*/
|
|
195
208
|
export function apiKeyRoutes() {
|
|
196
209
|
// `tenant` is set by @basaltkit/tenancy when present; read it without a hard
|
|
@@ -202,6 +215,15 @@ export function apiKeyRoutes() {
|
|
|
202
215
|
...(c.user ? { userId: c.user.id } : {}),
|
|
203
216
|
};
|
|
204
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());
|
|
205
227
|
return [
|
|
206
228
|
route({
|
|
207
229
|
method: 'POST',
|
|
@@ -213,6 +235,8 @@ export function apiKeyRoutes() {
|
|
|
213
235
|
name: z.string().min(1).max(100),
|
|
214
236
|
scopes: z.array(z.string().min(1)).optional(),
|
|
215
237
|
expiresAt: z.number().int().positive().optional(),
|
|
238
|
+
allowedIps: z.array(z.string()).optional(),
|
|
239
|
+
meta: meta.optional(),
|
|
216
240
|
}),
|
|
217
241
|
async handler({ body, reply }) {
|
|
218
242
|
const { record, key } = await apiKeys().issue({ ...body, ...scope() });
|
|
@@ -226,8 +250,39 @@ export function apiKeyRoutes() {
|
|
|
226
250
|
// Session-only: a key must never mint, list or revoke keys (a narrow or
|
|
227
251
|
// expiring key could otherwise mint a permanent '*' key).
|
|
228
252
|
meta: { auth: true, apiKey: false },
|
|
229
|
-
|
|
230
|
-
|
|
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 });
|
|
231
286
|
},
|
|
232
287
|
}),
|
|
233
288
|
route({
|
|
@@ -236,12 +291,8 @@ export function apiKeyRoutes() {
|
|
|
236
291
|
meta: { auth: true, apiKey: false },
|
|
237
292
|
params: z.object({ id: z.string() }),
|
|
238
293
|
async handler({ params, reply }) {
|
|
239
|
-
const record = await apiKeys().get(params.id);
|
|
240
|
-
const { tenantId, userId } = scope();
|
|
241
294
|
// Only expose/act on keys within the caller's scope; otherwise 404.
|
|
242
|
-
|
|
243
|
-
throw new ApiKeyForbiddenError();
|
|
244
|
-
}
|
|
295
|
+
await owned(params.id);
|
|
245
296
|
await apiKeys().revoke(params.id);
|
|
246
297
|
return reply.code(204).send();
|
|
247
298
|
},
|
package/dist/stores.d.ts
CHANGED
|
@@ -154,28 +154,96 @@ export interface ApiKeyRecord {
|
|
|
154
154
|
expiresAt?: number;
|
|
155
155
|
lastUsedAt?: number;
|
|
156
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>;
|
|
157
178
|
}
|
|
158
|
-
/** What a listing exposes — never
|
|
159
|
-
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
|
+
*/
|
|
160
185
|
export interface ApiKeyFilter {
|
|
161
186
|
tenantId?: string;
|
|
162
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;
|
|
163
212
|
}
|
|
164
213
|
export interface ApiKeyStore {
|
|
165
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
|
+
*/
|
|
166
220
|
findByHash(hash: string): Promise<ApiKeyRecord | null>;
|
|
167
221
|
findById(id: string): Promise<ApiKeyRecord | null>;
|
|
168
222
|
/** Active (non-revoked) keys matching the filter. */
|
|
169
223
|
list(filter: ApiKeyFilter): Promise<ApiKeyRecord[]>;
|
|
170
224
|
touch(id: string, at: number): Promise<void>;
|
|
171
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>;
|
|
172
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"];
|
|
173
240
|
export declare class MemoryApiKeyStore implements ApiKeyStore {
|
|
174
241
|
private readonly records;
|
|
175
242
|
create(record: ApiKeyRecord): Promise<void>;
|
|
176
243
|
findByHash(hash: string): Promise<ApiKeyRecord | null>;
|
|
177
244
|
findById(id: string): Promise<ApiKeyRecord | null>;
|
|
178
245
|
list(filter: ApiKeyFilter): Promise<ApiKeyRecord[]>;
|
|
246
|
+
update(id: string, patch: ApiKeyPatch, options?: ApiKeyUpdateOptions): Promise<ApiKeyRecord | null>;
|
|
179
247
|
touch(id: string, at: number): Promise<void>;
|
|
180
248
|
revoke(id: string, at: number): Promise<void>;
|
|
181
249
|
}
|
package/dist/stores.js
CHANGED
|
@@ -108,20 +108,41 @@ export class MemoryAuthTokenStore {
|
|
|
108
108
|
}
|
|
109
109
|
}
|
|
110
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
|
+
});
|
|
111
131
|
export class MemoryApiKeyStore {
|
|
112
132
|
records = new Map();
|
|
113
133
|
async create(record) {
|
|
114
|
-
this.records.set(record.id, record);
|
|
134
|
+
this.records.set(record.id, copyApiKey(record));
|
|
115
135
|
}
|
|
116
136
|
async findByHash(hash) {
|
|
117
137
|
for (const record of this.records.values()) {
|
|
118
|
-
if (record.hash === hash)
|
|
119
|
-
return record;
|
|
138
|
+
if (record.hash === hash || record.previousHash === hash)
|
|
139
|
+
return copyApiKey(record);
|
|
120
140
|
}
|
|
121
141
|
return null;
|
|
122
142
|
}
|
|
123
143
|
async findById(id) {
|
|
124
|
-
|
|
144
|
+
const record = this.records.get(id);
|
|
145
|
+
return record ? copyApiKey(record) : null;
|
|
125
146
|
}
|
|
126
147
|
async list(filter) {
|
|
127
148
|
const out = [];
|
|
@@ -132,10 +153,32 @@ export class MemoryApiKeyStore {
|
|
|
132
153
|
continue;
|
|
133
154
|
if (filter.userId !== undefined && record.userId !== filter.userId)
|
|
134
155
|
continue;
|
|
135
|
-
|
|
156
|
+
if (filter.serviceId !== undefined && record.serviceId !== filter.serviceId)
|
|
157
|
+
continue;
|
|
158
|
+
out.push(copyApiKey(record));
|
|
136
159
|
}
|
|
137
160
|
return out;
|
|
138
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
|
+
}
|
|
139
182
|
async touch(id, at) {
|
|
140
183
|
const record = this.records.get(id);
|
|
141
184
|
if (record)
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { BasaltError, type RequestContext } from '@basaltkit/core';
|
|
2
|
+
import type { JwtClaims } from './jwt.js';
|
|
3
|
+
import type { PublicUser } from './stores.js';
|
|
4
|
+
/**
|
|
5
|
+
* Claim names Basalt owns in an access token. A {@link TokenClaimsFn} that
|
|
6
|
+
* returns one of them fails the sign-in with {@link ReservedTokenClaimError}:
|
|
7
|
+
* a custom claim must never overwrite the subject, the expiry, the token
|
|
8
|
+
* version or the authentication methods.
|
|
9
|
+
*/
|
|
10
|
+
export declare const RESERVED_TOKEN_CLAIMS: readonly string[];
|
|
11
|
+
/** Why an access token is being signed. */
|
|
12
|
+
export type TokenClaimsReason = 'login' | 'social' | 'refresh';
|
|
13
|
+
export interface TokenClaimsContext {
|
|
14
|
+
/** `login` (password, with or without MFA), `social` (OAuth / SSO) or `refresh` (rotation). */
|
|
15
|
+
reason: TokenClaimsReason;
|
|
16
|
+
/** Authentication methods of the credential (`pwd`, `fed`, `mfa`), when known. */
|
|
17
|
+
amr?: string[];
|
|
18
|
+
/** The ambient context (`ctx()`), absent outside a request / `runWithContext`. */
|
|
19
|
+
request?: RequestContext;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Extra claims for every access token Auth signs — login, social login, MFA
|
|
23
|
+
* completion and every refresh. Called again on each refresh (the claims are
|
|
24
|
+
* re-derived, not copied), so a refreshed token carries the same claims as
|
|
25
|
+
* long as the inputs (the user, the context) are the same. Throwing fails the
|
|
26
|
+
* sign-in (fail closed). Returned values must be JSON-serialisable.
|
|
27
|
+
*/
|
|
28
|
+
export type TokenClaimsFn = (user: PublicUser, context: TokenClaimsContext) => Record<string, unknown> | Promise<Record<string, unknown>>;
|
|
29
|
+
/**
|
|
30
|
+
* Checks a verified access token's claims on the request it authenticates.
|
|
31
|
+
* `false` refuses the token with 401 {@link TokenClaimsRejectedError}.
|
|
32
|
+
* Runs before the user lookup, so a refused token never reads its `sub`.
|
|
33
|
+
*/
|
|
34
|
+
export type VerifyClaimsFn = (claims: JwtClaims, context: RequestContext) => boolean | Promise<boolean>;
|
|
35
|
+
/** A {@link TokenClaimsFn} returned a claim Basalt reserves (a bug in the app, 500). */
|
|
36
|
+
export declare class ReservedTokenClaimError extends BasaltError {
|
|
37
|
+
readonly status = 500;
|
|
38
|
+
constructor(claim: string);
|
|
39
|
+
}
|
|
40
|
+
/** A signed, unexpired access token whose claims `verifyClaims` refused. */
|
|
41
|
+
export declare class TokenClaimsRejectedError extends BasaltError {
|
|
42
|
+
readonly status = 401;
|
|
43
|
+
constructor();
|
|
44
|
+
}
|
|
45
|
+
/** Validates what a {@link TokenClaimsFn} returned. Internal to the package. */
|
|
46
|
+
export declare function checkCustomClaims(claims: unknown): Record<string, unknown>;
|
|
47
|
+
export interface TenantBoundTokensOptions {
|
|
48
|
+
/** The claim that carries the tenant id. Default `tid`. Must not be reserved. */
|
|
49
|
+
claim?: string;
|
|
50
|
+
/** More claims of the app's own, merged with the tenant claim. */
|
|
51
|
+
tokenClaims?: TokenClaimsFn;
|
|
52
|
+
/** A further check of the app's own, run after the tenant check passed. */
|
|
53
|
+
verifyClaims?: VerifyClaimsFn;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Binds access tokens to the plane they were issued on. Spread the result into
|
|
57
|
+
* `authPlugin({ ...tenantBoundTokens() })`:
|
|
58
|
+
*
|
|
59
|
+
* - every access token carries `tid` — the tenant of the context it was
|
|
60
|
+
* issued in (`ctx().tenant.id`, set by `@basaltkit/tenancy`), or `null` on
|
|
61
|
+
* the central plane;
|
|
62
|
+
* - a bearer token is accepted only where `tid` equals the tenant resolved for
|
|
63
|
+
* the request (`null` = no tenant). Anywhere else — another tenant, the apex,
|
|
64
|
+
* a token issued before the binding (no `tid`) — it is a 401
|
|
65
|
+
* `AUTH_TOKEN_CLAIMS_REJECTED`, whatever user ids the target plane holds.
|
|
66
|
+
*
|
|
67
|
+
* Works with any tenancy that puts `{ id }` on `ctx().tenant`; auth does not
|
|
68
|
+
* depend on `@basaltkit/tenancy`. Register `tenancyPlugin` before `authPlugin`
|
|
69
|
+
* so the tenant is resolved when the token is checked. Sessions and API keys
|
|
70
|
+
* are unaffected (they are looked up in the plane's own store).
|
|
71
|
+
*/
|
|
72
|
+
export declare function tenantBoundTokens(options?: TenantBoundTokensOptions): {
|
|
73
|
+
tokenClaims: TokenClaimsFn;
|
|
74
|
+
verifyClaims: VerifyClaimsFn;
|
|
75
|
+
};
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { BasaltError } from '@basaltkit/core';
|
|
2
|
+
/**
|
|
3
|
+
* Claim names Basalt owns in an access token. A {@link TokenClaimsFn} that
|
|
4
|
+
* returns one of them fails the sign-in with {@link ReservedTokenClaimError}:
|
|
5
|
+
* a custom claim must never overwrite the subject, the expiry, the token
|
|
6
|
+
* version or the authentication methods.
|
|
7
|
+
*/
|
|
8
|
+
export const RESERVED_TOKEN_CLAIMS = Object.freeze([
|
|
9
|
+
'sub',
|
|
10
|
+
'tv',
|
|
11
|
+
'amr',
|
|
12
|
+
'iat',
|
|
13
|
+
'exp',
|
|
14
|
+
'nbf',
|
|
15
|
+
'iss',
|
|
16
|
+
'aud',
|
|
17
|
+
'jti',
|
|
18
|
+
]);
|
|
19
|
+
/** A {@link TokenClaimsFn} returned a claim Basalt reserves (a bug in the app, 500). */
|
|
20
|
+
export class ReservedTokenClaimError extends BasaltError {
|
|
21
|
+
status = 500;
|
|
22
|
+
constructor(claim) {
|
|
23
|
+
super('AUTH_TOKEN_CLAIM_RESERVED', `The access-token claim "${claim}" is reserved and cannot be set by tokenClaims.`);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/** A signed, unexpired access token whose claims `verifyClaims` refused. */
|
|
27
|
+
export class TokenClaimsRejectedError extends BasaltError {
|
|
28
|
+
status = 401;
|
|
29
|
+
constructor() {
|
|
30
|
+
super('AUTH_TOKEN_CLAIMS_REJECTED', 'The token is not valid here.');
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/** Validates what a {@link TokenClaimsFn} returned. Internal to the package. */
|
|
34
|
+
export function checkCustomClaims(claims) {
|
|
35
|
+
if (claims === null || typeof claims !== 'object' || Array.isArray(claims)) {
|
|
36
|
+
throw new TypeError('tokenClaims must return a plain object of claims.');
|
|
37
|
+
}
|
|
38
|
+
for (const name of Object.keys(claims)) {
|
|
39
|
+
if (RESERVED_TOKEN_CLAIMS.includes(name))
|
|
40
|
+
throw new ReservedTokenClaimError(name);
|
|
41
|
+
}
|
|
42
|
+
return claims;
|
|
43
|
+
}
|
|
44
|
+
/** The tenant id of a context, read structurally (auth never imports tenancy). */
|
|
45
|
+
const tenantIdOf = (context) => {
|
|
46
|
+
const id = context?.tenant?.id;
|
|
47
|
+
return typeof id === 'string' && id !== '' ? id : null;
|
|
48
|
+
};
|
|
49
|
+
/**
|
|
50
|
+
* Binds access tokens to the plane they were issued on. Spread the result into
|
|
51
|
+
* `authPlugin({ ...tenantBoundTokens() })`:
|
|
52
|
+
*
|
|
53
|
+
* - every access token carries `tid` — the tenant of the context it was
|
|
54
|
+
* issued in (`ctx().tenant.id`, set by `@basaltkit/tenancy`), or `null` on
|
|
55
|
+
* the central plane;
|
|
56
|
+
* - a bearer token is accepted only where `tid` equals the tenant resolved for
|
|
57
|
+
* the request (`null` = no tenant). Anywhere else — another tenant, the apex,
|
|
58
|
+
* a token issued before the binding (no `tid`) — it is a 401
|
|
59
|
+
* `AUTH_TOKEN_CLAIMS_REJECTED`, whatever user ids the target plane holds.
|
|
60
|
+
*
|
|
61
|
+
* Works with any tenancy that puts `{ id }` on `ctx().tenant`; auth does not
|
|
62
|
+
* depend on `@basaltkit/tenancy`. Register `tenancyPlugin` before `authPlugin`
|
|
63
|
+
* so the tenant is resolved when the token is checked. Sessions and API keys
|
|
64
|
+
* are unaffected (they are looked up in the plane's own store).
|
|
65
|
+
*/
|
|
66
|
+
export function tenantBoundTokens(options = {}) {
|
|
67
|
+
const claim = options.claim ?? 'tid';
|
|
68
|
+
if (claim === '' || RESERVED_TOKEN_CLAIMS.includes(claim))
|
|
69
|
+
throw new ReservedTokenClaimError(claim);
|
|
70
|
+
const extra = options.tokenClaims;
|
|
71
|
+
const verify = options.verifyClaims;
|
|
72
|
+
return {
|
|
73
|
+
async tokenClaims(user, context) {
|
|
74
|
+
const own = extra ? checkCustomClaims(await extra(user, context)) : {};
|
|
75
|
+
return { ...own, [claim]: tenantIdOf(context.request) };
|
|
76
|
+
},
|
|
77
|
+
async verifyClaims(claims, context) {
|
|
78
|
+
if (claims[claim] !== tenantIdOf(context))
|
|
79
|
+
return false;
|
|
80
|
+
return verify ? (await verify(claims, context)) === true : true;
|
|
81
|
+
},
|
|
82
|
+
};
|
|
83
|
+
}
|