@basaltkit/auth 4.2.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 +7 -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 +7 -8
- package/dist/auth.js +20 -18
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/ip-allowlist.d.ts +22 -0
- package/dist/ip-allowlist.js +118 -0
- 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/package.json +3 -3
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)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@basaltkit/auth",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "5.0.0",
|
|
4
4
|
"engines": {
|
|
5
5
|
"node": ">=22.5.0"
|
|
6
6
|
},
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
"dist"
|
|
19
19
|
],
|
|
20
20
|
"dependencies": {
|
|
21
|
-
"@basaltkit/http": "^
|
|
21
|
+
"@basaltkit/http": "^3.0.0",
|
|
22
22
|
"@basaltkit/core": "^1.6.0"
|
|
23
23
|
},
|
|
24
24
|
"peerDependencies": {
|
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
"typescript": "^7.0.2",
|
|
30
30
|
"vitest": "^5.0.1",
|
|
31
31
|
"zod": "^4.6.5",
|
|
32
|
-
"@basaltkit/fastify": "^
|
|
32
|
+
"@basaltkit/fastify": "^3.0.0",
|
|
33
33
|
"@basaltkit/tsconfig": "^0.24.0"
|
|
34
34
|
},
|
|
35
35
|
"publishConfig": {
|