@manablox/auth 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,418 @@
1
+ import { rethrowUniqueViolation, schema } from "@manablox/db";
2
+ import { betterAuth } from "better-auth";
3
+ import { drizzleAdapter } from "better-auth/adapters/drizzle";
4
+ import { APIError } from "better-auth/api";
5
+ import { bearer } from "better-auth/plugins";
6
+ import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
7
+ import { ALL_PERMISSIONS, ALL_PERMISSIONS as ALL_PERMISSIONS$1, BUILT_IN_ROLES, CONTENT_ACTIONS, ManabloxError, PERMISSION_GROUPS, grantsCover, grantsCover as grantsCover$1, intersectGrants, intersectGrants as intersectGrants$1, isBuiltInRole, normaliseGrants, parseGrant, permissionsFor, permissionsFor as permissionsFor$1, typesCoveredBy, typesCoveredBy as typesCoveredBy$1 } from "@manablox/core";
8
+ import { and, eq, sql } from "drizzle-orm";
9
+ //#region src/password.ts
10
+ /**
11
+ * Argon2id, the current OWASP recommendation over bcrypt — which also silently truncates
12
+ * passwords at 72 bytes. One definition serves better-auth's own sign-in path and the
13
+ * accounts an administrator creates, so both write the same hash format.
14
+ */
15
+ async function hashPassword(password) {
16
+ const { hash } = await import("@node-rs/argon2");
17
+ return hash(password, {
18
+ memoryCost: 19456,
19
+ timeCost: 2,
20
+ parallelism: 1
21
+ });
22
+ }
23
+ async function verifyPassword(stored, password) {
24
+ const { verify } = await import("@node-rs/argon2");
25
+ return verify(stored, password);
26
+ }
27
+ /** Matches better-auth's `minPasswordLength`, so a password set here signs in there. */
28
+ const MIN_PASSWORD_LENGTH = 12;
29
+ //#endregion
30
+ //#region src/api-key.ts
31
+ const PREFIX = "mbx";
32
+ /**
33
+ * Takes a presented key apart. The secret is base64url and may itself contain `_`, so
34
+ * the key is not split on it: the prefix is a fixed twelve hex characters and the
35
+ * secret is whatever follows.
36
+ */
37
+ function parseApiKey(presented) {
38
+ const match = /^([a-z]+)_([0-9a-f]{12})_([A-Za-z0-9_-]+)$/.exec(presented);
39
+ if (!match || match[1] !== PREFIX) return null;
40
+ return {
41
+ prefix: match[2],
42
+ secret: match[3]
43
+ };
44
+ }
45
+ /**
46
+ * Long-lived credentials for headless consumers.
47
+ *
48
+ * Keys are stored as a SHA-256 digest, never in plaintext, and are looked up by an
49
+ * indexed non-secret prefix so verification is one indexed read plus one constant-time
50
+ * comparison — not a scan-and-compare over every row.
51
+ */
52
+ var ApiKeyService = class {
53
+ db;
54
+ repos;
55
+ constructor(db, repos) {
56
+ this.db = db;
57
+ this.repos = repos;
58
+ }
59
+ async issue(userId, name, options = {}) {
60
+ const secret = randomBytes(32).toString("base64url");
61
+ const prefix = randomBytes(6).toString("hex");
62
+ const key = `${PREFIX}_${prefix}_${secret}`;
63
+ const [row] = await this.db.insert(schema.apikeys).values({
64
+ userId,
65
+ name,
66
+ prefix,
67
+ start: key.slice(0, 12),
68
+ key: digest(secret),
69
+ expiresAt: options.expiresAt ?? null,
70
+ spaceIds: options.spaceIds?.length ? options.spaceIds : null,
71
+ permissions: options.permissions ?? null
72
+ }).returning();
73
+ if (!row) throw new ManabloxError("apiKey.create.failed");
74
+ return {
75
+ id: row.id,
76
+ name,
77
+ key,
78
+ prefix
79
+ };
80
+ }
81
+ /**
82
+ * Deletes the row rather than clearing `enabled`: a revoked key is never listed again
83
+ * or re-enabled, so a disabled row is only a secret digest left lying around.
84
+ */
85
+ async revoke(id) {
86
+ await this.db.delete(schema.apikeys).where(eq(schema.apikeys.id, id));
87
+ }
88
+ async list(userId) {
89
+ return this.db.select({
90
+ id: schema.apikeys.id,
91
+ name: schema.apikeys.name,
92
+ start: schema.apikeys.start,
93
+ enabled: schema.apikeys.enabled,
94
+ expiresAt: schema.apikeys.expiresAt,
95
+ lastRequest: schema.apikeys.lastRequest,
96
+ spaceIds: schema.apikeys.spaceIds,
97
+ permissions: schema.apikeys.permissions,
98
+ createdAt: schema.apikeys.createdAt
99
+ }).from(schema.apikeys).where(eq(schema.apikeys.userId, userId));
100
+ }
101
+ async resolve(presented) {
102
+ const parsed = parseApiKey(presented);
103
+ if (!parsed) return null;
104
+ const { prefix, secret } = parsed;
105
+ const row = (await this.db.select().from(schema.apikeys).where(and(eq(schema.apikeys.prefix, prefix), eq(schema.apikeys.enabled, true))).limit(1))[0];
106
+ if (!row) return null;
107
+ if (row.expiresAt && row.expiresAt.getTime() < Date.now()) return null;
108
+ const expected = Buffer.from(row.key, "hex");
109
+ const actual = Buffer.from(digest(secret), "hex");
110
+ if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) return null;
111
+ this.db.update(schema.apikeys).set({ lastRequest: /* @__PURE__ */ new Date() }).where(eq(schema.apikeys.id, row.id)).catch(() => void 0);
112
+ const user = await this.repos.users.findById(row.userId);
113
+ if (!user || user.banned) return null;
114
+ const resolved = await this.repos.users.principal(user.id);
115
+ if (!resolved) return null;
116
+ const allowed = row.spaceIds?.length ? new Set(row.spaceIds) : null;
117
+ const spaces = {};
118
+ const permissions = {};
119
+ for (const [spaceId, role] of Object.entries(resolved.spaces)) {
120
+ if (allowed && !allowed.has(spaceId)) continue;
121
+ spaces[spaceId] = role;
122
+ const grants = resolved.permissions[spaceId];
123
+ if (grants) permissions[spaceId] = grants;
124
+ }
125
+ return {
126
+ userId: user.id,
127
+ email: user.email,
128
+ role: user.role,
129
+ spaces,
130
+ permissions,
131
+ viaApiKey: true,
132
+ allowedSpaceIds: allowed ? [...allowed] : null,
133
+ allowedGrants: row.permissions
134
+ };
135
+ }
136
+ /** Removes expired keys; scheduled by the jobs package. */
137
+ async pruneExpired() {
138
+ return (await this.db.delete(schema.apikeys).where(sql`${schema.apikeys.expiresAt} is not null and ${schema.apikeys.expiresAt} < now()`).returning({ id: schema.apikeys.id })).length;
139
+ }
140
+ };
141
+ const digest = (secret) => createHash("sha256").update(secret).digest("hex");
142
+ //#endregion
143
+ //#region src/rbac.ts
144
+ /** The grants a principal's role gives in a space, whatever kind of role it is. */
145
+ function grantsIn(principal, spaceId) {
146
+ const role = principal.spaces[spaceId];
147
+ if (!role) return [];
148
+ return principal.permissions?.[spaceId] ?? permissionsFor$1(role);
149
+ }
150
+ /**
151
+ * What a principal can actually do in a space: the role's grants (everything, for a
152
+ * superadmin) narrowed by an API key's restriction, if the request came through one.
153
+ */
154
+ function effectiveGrants(principal, spaceId) {
155
+ if (principal.allowedSpaceIds && !principal.allowedSpaceIds.includes(spaceId)) return [];
156
+ const held = principal.role === "superadmin" ? ALL_PERMISSIONS$1 : grantsIn(principal, spaceId);
157
+ return principal.allowedGrants ? intersectGrants$1(held, principal.allowedGrants) : held;
158
+ }
159
+ function can(principal, spaceId, permission, typeId) {
160
+ if (!principal) return false;
161
+ if (principal.allowedSpaceIds && (!spaceId || !principal.allowedSpaceIds.includes(spaceId))) return false;
162
+ if (principal.allowedGrants && !grantsCover$1(principal.allowedGrants, permission, typeId)) return false;
163
+ if (principal.role === "superadmin") return true;
164
+ if (!spaceId) return false;
165
+ return grantsCover$1(grantsIn(principal, spaceId), permission, typeId);
166
+ }
167
+ function assertCan(principal, spaceId, permission, typeId) {
168
+ if (can(principal, spaceId, permission, typeId)) return;
169
+ if (!principal) throw ManabloxError.unauthorized();
170
+ throw ManabloxError.forbidden("auth.forbidden", {
171
+ permission,
172
+ spaceId,
173
+ ...typeId ? { typeId } : {}
174
+ });
175
+ }
176
+ /**
177
+ * The content types a principal may perform an action on in a space, or `null` for
178
+ * every type — what a listing narrows its filter to.
179
+ */
180
+ function allowedTypeIds(principal, spaceId, permission) {
181
+ if (!principal) return [];
182
+ if (principal.role === "superadmin" && !principal.allowedGrants) return null;
183
+ return typesCoveredBy$1(effectiveGrants(principal, spaceId), permission);
184
+ }
185
+ /** Roles used by field-level `readRoles`/`writeRoles` checks. */
186
+ function actorRoles(principal, spaceId) {
187
+ if (!principal) return [];
188
+ const roles = [principal.role];
189
+ if (spaceId && principal.spaces[spaceId]) roles.push(principal.spaces[spaceId]);
190
+ return roles;
191
+ }
192
+ //#endregion
193
+ //#region src/user.service.ts
194
+ /**
195
+ * `users_email_key` is enforced in the database, so a taken address arrives as a
196
+ * Postgres unique violation and would surface as an opaque 500.
197
+ */
198
+ const emailConflict = (email) => (error) => rethrowUniqueViolation(error, {
199
+ constraint: "email",
200
+ key: "user.email.taken",
201
+ path: ["email"],
202
+ params: { email: email ?? "" },
203
+ errorKey: "user.validation.failed"
204
+ });
205
+ /**
206
+ * Instance-wide user administration: the accounts, their instance role, and whether they
207
+ * may sign in at all. Space membership stays with `SpaceService`, because it is a
208
+ * property of the space.
209
+ *
210
+ * Every rule here exists to keep the instance reachable: an administrator cannot lock
211
+ * themself out, and the instance always keeps at least one superadmin.
212
+ */
213
+ var UserService = class {
214
+ repos;
215
+ constructor(repos) {
216
+ this.repos = repos;
217
+ }
218
+ async get(userId) {
219
+ const user = await this.repos.users.findById(userId);
220
+ if (!user) throw ManabloxError.notFound("user.notFound", { id: userId });
221
+ const memberships = await this.repos.users.membershipsWithSpaces(userId);
222
+ return {
223
+ ...summary(user),
224
+ memberships: memberships.map((row) => ({
225
+ spaceId: row.spaceId,
226
+ role: row.role,
227
+ space: row.space
228
+ }))
229
+ };
230
+ }
231
+ async list(pagination, search) {
232
+ const page = await this.repos.users.list(pagination, search);
233
+ return {
234
+ ...page,
235
+ items: page.items.map(summary)
236
+ };
237
+ }
238
+ async create(input) {
239
+ const email = normaliseEmail(input.email);
240
+ return summary(await this.repos.users.create({
241
+ name: input.name.trim(),
242
+ email,
243
+ role: input.role,
244
+ passwordHash: await hashPassword(input.password)
245
+ }).catch(emailConflict(email)));
246
+ }
247
+ async update(userId, input) {
248
+ const data = {};
249
+ if (input.name !== void 0) data.name = input.name.trim();
250
+ if (input.email !== void 0) data.email = normaliseEmail(input.email);
251
+ return summary(await this.repos.users.update(userId, data).catch(emailConflict(data.email)));
252
+ }
253
+ /** Changing the instance role; the last superadmin cannot step down. */
254
+ async setRole(userId, role) {
255
+ if (role !== "superadmin") await this.assertNotLastSuperadmin(userId);
256
+ return summary(await this.repos.users.setRole(userId, role));
257
+ }
258
+ /**
259
+ * A new password, and every session gone with the old one: whoever held the account
260
+ * before the reset does not keep it afterwards.
261
+ */
262
+ async setPassword(userId, password) {
263
+ await this.require(userId);
264
+ await this.repos.users.setPasswordHash(userId, await hashPassword(password));
265
+ await this.repos.users.revokeSessions(userId);
266
+ }
267
+ /** A banned user is signed out everywhere and refused on the next request. */
268
+ async ban(actorId, userId, reason) {
269
+ this.assertNotSelf(actorId, userId);
270
+ await this.assertNotLastSuperadmin(userId);
271
+ const user = await this.repos.users.setBanned(userId, true, reason);
272
+ await this.repos.users.revokeSessions(userId);
273
+ return summary(user);
274
+ }
275
+ async unban(userId) {
276
+ return summary(await this.repos.users.setBanned(userId, false, null));
277
+ }
278
+ async delete(actorId, userId) {
279
+ this.assertNotSelf(actorId, userId);
280
+ await this.require(userId);
281
+ await this.assertNotLastSuperadmin(userId);
282
+ await this.repos.users.delete(userId);
283
+ }
284
+ /** Signs the user out of every device without touching the account. */
285
+ async revokeSessions(userId) {
286
+ await this.require(userId);
287
+ await this.repos.users.revokeSessions(userId);
288
+ }
289
+ async require(userId) {
290
+ const user = await this.repos.users.findById(userId);
291
+ if (!user) throw ManabloxError.notFound("user.notFound", { id: userId });
292
+ return user;
293
+ }
294
+ assertNotSelf(actorId, userId) {
295
+ if (actorId === userId) throw ManabloxError.badRequest("user.self.protected", { id: userId });
296
+ }
297
+ /**
298
+ * Whatever happens to `userId`, one superadmin must remain — otherwise the instance
299
+ * has no one left who can create a space or manage users, and no way back.
300
+ */
301
+ async assertNotLastSuperadmin(userId) {
302
+ if ((await this.require(userId)).role !== "superadmin") return;
303
+ if (await this.repos.users.countByRole("superadmin") <= 1) throw ManabloxError.badRequest("user.lastSuperadmin", { id: userId });
304
+ }
305
+ };
306
+ function summary(user) {
307
+ return {
308
+ id: user.id,
309
+ name: user.name,
310
+ email: user.email,
311
+ image: user.image,
312
+ role: user.role,
313
+ banned: user.banned,
314
+ banReason: user.banReason,
315
+ createdAt: user.createdAt,
316
+ updatedAt: user.updatedAt
317
+ };
318
+ }
319
+ /** Lower-cased and trimmed, as better-auth stores it, so two spellings cannot coexist. */
320
+ function normaliseEmail(email) {
321
+ return email.trim().toLowerCase();
322
+ }
323
+ //#endregion
324
+ //#region src/index.ts
325
+ function createAuth(config, db, callbacks = {}) {
326
+ return betterAuth({
327
+ secret: config.secret,
328
+ ...config.baseUrl ? { baseURL: config.baseUrl } : {},
329
+ trustedOrigins: config.trustedOrigins ?? [],
330
+ database: drizzleAdapter(db, {
331
+ provider: "pg",
332
+ schema: {
333
+ user: schema.users,
334
+ session: schema.sessions,
335
+ account: schema.accounts,
336
+ verification: schema.verifications,
337
+ apikey: schema.apikeys
338
+ }
339
+ }),
340
+ emailAndPassword: {
341
+ enabled: config.emailAndPassword ?? true,
342
+ minPasswordLength: 12,
343
+ password: {
344
+ hash: hashPassword,
345
+ verify: ({ hash: stored, password }) => verifyPassword(stored, password)
346
+ }
347
+ },
348
+ session: {
349
+ expiresIn: config.sessionMaxAge ?? 604800,
350
+ updateAge: 86400,
351
+ cookieCache: {
352
+ enabled: true,
353
+ maxAge: 300
354
+ }
355
+ },
356
+ plugins: [bearer()],
357
+ databaseHooks: { user: { create: {
358
+ before: async (user) => {
359
+ if (!callbacks.allowSignUp || await callbacks.allowSignUp()) return { data: user };
360
+ throw new APIError("FORBIDDEN", { message: "auth.signUp.closed" });
361
+ },
362
+ after: async (user) => {
363
+ await callbacks.onUserCreated?.(user.id);
364
+ }
365
+ } } },
366
+ advanced: { database: { generateId: () => crypto.randomUUID() } }
367
+ });
368
+ }
369
+ /**
370
+ * Resolves a request's session into a `Principal`, including its space memberships.
371
+ * Returns `null` for anonymous requests rather than throwing — route guards decide.
372
+ */
373
+ async function resolvePrincipal(auth, repos, headers, apiKeys) {
374
+ const presented = headers.get("x-api-key");
375
+ if (presented && apiKeys) {
376
+ const principal = await apiKeys.resolve(presented);
377
+ if (principal) return principal;
378
+ }
379
+ const session = await auth.api.getSession({ headers });
380
+ if (!session?.user) return null;
381
+ const principal = await repos.users.principal(session.user.id);
382
+ if (!principal || principal.banned) return null;
383
+ return {
384
+ userId: session.user.id,
385
+ email: session.user.email,
386
+ role: principal.role,
387
+ spaces: principal.spaces,
388
+ permissions: principal.permissions
389
+ };
390
+ }
391
+ /**
392
+ * Promotes the very first account to `superadmin` and grants it ownership of every
393
+ * existing space, so a fresh install is reachable.
394
+ *
395
+ * Called from better-auth's user-create hook rather than at startup, so it fires for an
396
+ * account created after the server is already running.
397
+ */
398
+ async function promoteFirstUser(manablox, repos, userId) {
399
+ if (await repos.users.count() !== 1) return;
400
+ const user = await repos.users.findById(userId);
401
+ if (!user || user.role === "superadmin") return;
402
+ await repos.users.setRole(userId, "superadmin");
403
+ for (const space of await repos.spaces.all()) await repos.users.grant(userId, space.id, "owner");
404
+ manablox.logger.info({ email: user.email }, "first account promoted to superadmin");
405
+ }
406
+ /** Covers an instance whose first account predates this behaviour. */
407
+ function attachBootstrapOwner(manablox, repos) {
408
+ manablox.hooks.on("after:start", async () => {
409
+ const { items } = await repos.users.list({
410
+ limit: 1,
411
+ offset: 0
412
+ });
413
+ const first = items[0];
414
+ if (first && await repos.users.count() === 1) await promoteFirstUser(manablox, repos, first.id);
415
+ }, { source: "@manablox/auth" });
416
+ }
417
+ //#endregion
418
+ export { ALL_PERMISSIONS, ApiKeyService, BUILT_IN_ROLES, CONTENT_ACTIONS, MIN_PASSWORD_LENGTH, PERMISSION_GROUPS, UserService, actorRoles, allowedTypeIds, assertCan, attachBootstrapOwner, can, createAuth, effectiveGrants, grantsCover, grantsIn, hashPassword, intersectGrants, isBuiltInRole, normaliseGrants, parseApiKey, parseGrant, permissionsFor, promoteFirstUser, resolvePrincipal, typesCoveredBy, verifyPassword };
package/package.json CHANGED
@@ -1,18 +1,18 @@
1
1
  {
2
2
  "name": "@manablox/auth",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {
7
- "types": "./src/index.ts",
8
- "default": "./src/index.ts"
7
+ "types": "./dist/index.d.ts",
8
+ "default": "./dist/index.js"
9
9
  }
10
10
  },
11
- "main": "./src/index.ts",
12
- "types": "./src/index.ts",
11
+ "main": "./dist/index.js",
12
+ "types": "./dist/index.d.ts",
13
13
  "dependencies": {
14
- "@manablox/core": "0.2.0",
15
- "@manablox/db": "0.2.0",
14
+ "@manablox/core": "0.3.0",
15
+ "@manablox/db": "0.3.0",
16
16
  "better-auth": "^1.7.2",
17
17
  "drizzle-orm": "^0.45.2",
18
18
  "@node-rs/argon2": "^2.2.0"
@@ -20,10 +20,17 @@
20
20
  "devDependencies": {
21
21
  "@manablox/config-typescript": "0.0.0",
22
22
  "@types/node": "^26.4.1",
23
+ "tsdown": "^0.23.0",
23
24
  "typescript": "^7.0.2",
24
25
  "vitest": "^5.0.0"
25
26
  },
27
+ "files": [
28
+ "dist",
29
+ "!dist/**/*.map",
30
+ "README.md"
31
+ ],
26
32
  "scripts": {
33
+ "build": "tsdown",
27
34
  "typecheck": "tsc --noEmit",
28
35
  "test": "vitest run"
29
36
  }
package/src/api-key.ts DELETED
@@ -1,164 +0,0 @@
1
- import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
2
- import { ManabloxError } from '@manablox/core';
3
- import { type Database, type Repositories, schema } from '@manablox/db';
4
- import { and, eq, sql } from 'drizzle-orm';
5
- import type { Principal, SpaceRole } from './rbac.js';
6
-
7
- export interface IssuedApiKey {
8
- id: string;
9
- name: string;
10
- /** The full secret, shown once at creation and never recoverable afterwards. */
11
- key: string;
12
- prefix: string;
13
- }
14
-
15
- export interface IssueApiKeyOptions {
16
- expiresAt?: Date | undefined;
17
- /** Spaces the key may act in. `null`/omitted issues an unrestricted key. */
18
- spaceIds?: string[] | null | undefined;
19
- /** Grants the key may use. `null`/omitted leaves the owner's role as the limit. */
20
- permissions?: string[] | null | undefined;
21
- }
22
-
23
- const PREFIX = 'mbx';
24
-
25
- /**
26
- * Takes a presented key apart. The secret is base64url and may itself contain `_`, so
27
- * the key is not split on it: the prefix is a fixed twelve hex characters and the
28
- * secret is whatever follows.
29
- */
30
- export function parseApiKey(presented: string): { prefix: string; secret: string } | null {
31
- const match = /^([a-z]+)_([0-9a-f]{12})_([A-Za-z0-9_-]+)$/.exec(presented);
32
- if (!match || match[1] !== PREFIX) return null;
33
- return { prefix: match[2] as string, secret: match[3] as string };
34
- }
35
-
36
- /**
37
- * Long-lived credentials for headless consumers.
38
- *
39
- * Keys are stored as a SHA-256 digest, never in plaintext, and are looked up by an
40
- * indexed non-secret prefix so verification is one indexed read plus one constant-time
41
- * comparison — not a scan-and-compare over every row.
42
- */
43
- export class ApiKeyService {
44
- constructor(
45
- private readonly db: Database,
46
- private readonly repos: Repositories,
47
- ) {}
48
-
49
- async issue(
50
- userId: string,
51
- name: string,
52
- options: IssueApiKeyOptions = {},
53
- ): Promise<IssuedApiKey> {
54
- const secret = randomBytes(32).toString('base64url');
55
- const prefix = randomBytes(6).toString('hex');
56
- const key = `${PREFIX}_${prefix}_${secret}`;
57
-
58
- const [row] = await this.db
59
- .insert(schema.apikeys)
60
- .values({
61
- userId,
62
- name,
63
- prefix,
64
- start: key.slice(0, 12),
65
- key: digest(secret),
66
- expiresAt: options.expiresAt ?? null,
67
- spaceIds: options.spaceIds?.length ? options.spaceIds : null,
68
- permissions: options.permissions ?? null,
69
- })
70
- .returning();
71
-
72
- if (!row) throw new ManabloxError('apiKey.create.failed');
73
- return { id: row.id, name, key, prefix };
74
- }
75
-
76
- /**
77
- * Deletes the row rather than clearing `enabled`: a revoked key is never listed again
78
- * or re-enabled, so a disabled row is only a secret digest left lying around.
79
- */
80
- async revoke(id: string): Promise<void> {
81
- await this.db.delete(schema.apikeys).where(eq(schema.apikeys.id, id));
82
- }
83
-
84
- async list(userId: string) {
85
- return this.db
86
- .select({
87
- id: schema.apikeys.id,
88
- name: schema.apikeys.name,
89
- start: schema.apikeys.start,
90
- enabled: schema.apikeys.enabled,
91
- expiresAt: schema.apikeys.expiresAt,
92
- lastRequest: schema.apikeys.lastRequest,
93
- spaceIds: schema.apikeys.spaceIds,
94
- permissions: schema.apikeys.permissions,
95
- createdAt: schema.apikeys.createdAt,
96
- })
97
- .from(schema.apikeys)
98
- .where(eq(schema.apikeys.userId, userId));
99
- }
100
-
101
- async resolve(presented: string): Promise<Principal | null> {
102
- const parsed = parseApiKey(presented);
103
- if (!parsed) return null;
104
- const { prefix, secret } = parsed;
105
-
106
- const rows = await this.db
107
- .select()
108
- .from(schema.apikeys)
109
- .where(and(eq(schema.apikeys.prefix, prefix), eq(schema.apikeys.enabled, true)))
110
- .limit(1);
111
-
112
- const row = rows[0];
113
- if (!row) return null;
114
- if (row.expiresAt && row.expiresAt.getTime() < Date.now()) return null;
115
-
116
- const expected = Buffer.from(row.key, 'hex');
117
- const actual = Buffer.from(digest(secret), 'hex');
118
- if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) return null;
119
-
120
- // Best-effort touch; a failure here must never fail the request.
121
- void this.db
122
- .update(schema.apikeys)
123
- .set({ lastRequest: new Date() })
124
- .where(eq(schema.apikeys.id, row.id))
125
- .catch(() => undefined);
126
-
127
- const user = await this.repos.users.findById(row.userId);
128
- if (!user || user.banned) return null;
129
-
130
- const resolved = await this.repos.users.principal(user.id);
131
- if (!resolved) return null;
132
- const allowed = row.spaceIds?.length ? new Set(row.spaceIds) : null;
133
- const spaces: Record<string, SpaceRole> = {};
134
- const permissions: Record<string, string[]> = {};
135
- for (const [spaceId, role] of Object.entries(resolved.spaces)) {
136
- if (allowed && !allowed.has(spaceId)) continue;
137
- spaces[spaceId] = role;
138
- const grants = resolved.permissions[spaceId];
139
- if (grants) permissions[spaceId] = grants;
140
- }
141
-
142
- return {
143
- userId: user.id,
144
- email: user.email,
145
- role: user.role,
146
- spaces,
147
- permissions,
148
- viaApiKey: true,
149
- allowedSpaceIds: allowed ? [...allowed] : null,
150
- allowedGrants: row.permissions,
151
- };
152
- }
153
-
154
- /** Removes expired keys; scheduled by the jobs package. */
155
- async pruneExpired(): Promise<number> {
156
- const deleted = await this.db
157
- .delete(schema.apikeys)
158
- .where(sql`${schema.apikeys.expiresAt} is not null and ${schema.apikeys.expiresAt} < now()`)
159
- .returning({ id: schema.apikeys.id });
160
- return deleted.length;
161
- }
162
- }
163
-
164
- const digest = (secret: string): string => createHash('sha256').update(secret).digest('hex');