@vllnt/convex-api-keys 0.1.0 → 0.1.1-canary.61796d1

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.
Files changed (67) hide show
  1. package/README.md +44 -55
  2. package/dist/client/_generated/_ignore.d.ts +1 -0
  3. package/dist/client/_generated/_ignore.d.ts.map +1 -0
  4. package/dist/client/_generated/_ignore.js +3 -0
  5. package/dist/client/_generated/_ignore.js.map +1 -0
  6. package/dist/client/index.d.ts +69 -0
  7. package/dist/client/index.d.ts.map +1 -0
  8. package/dist/client/index.js +82 -0
  9. package/dist/client/index.js.map +1 -0
  10. package/dist/client/types.d.ts +59 -0
  11. package/dist/client/types.d.ts.map +1 -0
  12. package/dist/client/types.js +2 -0
  13. package/dist/client/types.js.map +1 -0
  14. package/dist/component/_generated/api.d.ts +38 -0
  15. package/dist/component/_generated/api.d.ts.map +1 -0
  16. package/dist/component/_generated/api.js +31 -0
  17. package/dist/component/_generated/api.js.map +1 -0
  18. package/dist/component/_generated/component.d.ts +141 -0
  19. package/dist/component/_generated/component.d.ts.map +1 -0
  20. package/dist/component/_generated/component.js +11 -0
  21. package/dist/component/_generated/component.js.map +1 -0
  22. package/dist/component/_generated/dataModel.d.ts +46 -0
  23. package/dist/component/_generated/dataModel.d.ts.map +1 -0
  24. package/dist/component/_generated/dataModel.js +11 -0
  25. package/dist/component/_generated/dataModel.js.map +1 -0
  26. package/dist/component/_generated/server.d.ts +121 -0
  27. package/dist/component/_generated/server.d.ts.map +1 -0
  28. package/dist/component/_generated/server.js +78 -0
  29. package/dist/component/_generated/server.js.map +1 -0
  30. package/dist/component/convex.config.d.ts +3 -0
  31. package/dist/component/convex.config.d.ts.map +1 -0
  32. package/dist/component/convex.config.js +6 -0
  33. package/dist/component/convex.config.js.map +1 -0
  34. package/dist/component/mutations.d.ts +80 -0
  35. package/dist/component/mutations.d.ts.map +1 -0
  36. package/dist/component/mutations.js +422 -0
  37. package/dist/component/mutations.js.map +1 -0
  38. package/dist/component/queries.d.ts +47 -0
  39. package/dist/component/queries.d.ts.map +1 -0
  40. package/dist/component/queries.js +117 -0
  41. package/dist/component/queries.js.map +1 -0
  42. package/dist/component/schema.d.ts +52 -0
  43. package/dist/component/schema.d.ts.map +1 -0
  44. package/dist/component/schema.js +33 -0
  45. package/dist/component/schema.js.map +1 -0
  46. package/dist/component/validators.d.ts +3 -0
  47. package/dist/component/validators.d.ts.map +1 -0
  48. package/dist/component/validators.js +4 -0
  49. package/dist/component/validators.js.map +1 -0
  50. package/dist/log.d.ts +11 -0
  51. package/dist/log.d.ts.map +1 -0
  52. package/dist/log.js +15 -0
  53. package/dist/log.js.map +1 -0
  54. package/dist/shared.d.ts +38 -0
  55. package/dist/shared.d.ts.map +1 -0
  56. package/dist/shared.js +98 -0
  57. package/dist/shared.js.map +1 -0
  58. package/package.json +21 -23
  59. package/src/client/index.ts +23 -38
  60. package/src/client/types.ts +2 -12
  61. package/src/component/_generated/api.ts +0 -3
  62. package/src/component/_generated/component.ts +8 -11
  63. package/src/component/convex.config.ts +0 -6
  64. package/src/component/mutations.ts +130 -154
  65. package/src/component/queries.ts +56 -91
  66. package/src/component/schema.ts +0 -11
  67. package/src/shared.ts +53 -25
@@ -1,16 +1,17 @@
1
1
  import { v } from "convex/values";
2
2
  import { mutation } from "./_generated/server.js";
3
3
  import { components } from "./_generated/api.js";
4
- import { RateLimiter, MINUTE, HOUR } from "@convex-dev/rate-limiter";
5
4
  import { ShardedCounter } from "@convex-dev/sharded-counter";
6
5
  import {
7
- KEY_STATUS,
8
6
  KEY_TYPE,
9
7
  TERMINAL_STATUSES,
10
8
  parseKeyString,
11
9
  timingSafeEqual,
12
10
  sha256Hex,
13
11
  validateTags,
12
+ validateKeyPrefix,
13
+ validateEnv,
14
+ validateSizeLimits,
14
15
  KEY_PREFIX_SEPARATOR,
15
16
  } from "../shared.js";
16
17
  import { createLogger } from "../log.js";
@@ -19,13 +20,16 @@ import type { KeyStatus } from "../shared.js";
19
20
 
20
21
  const log = createLogger("api-keys");
21
22
 
22
- const rateLimiter = new RateLimiter(components.rateLimiter, {
23
- createKey: { kind: "fixed window", rate: 100, period: HOUR },
24
- validateKey: { kind: "token bucket", rate: 1000, period: MINUTE },
25
- });
26
-
27
23
  const counter = new ShardedCounter(components.shardedCounter);
28
24
 
25
+ function generateRandomHex(length: number): string {
26
+ const bytes = new Uint8Array(length / 2);
27
+ crypto.getRandomValues(bytes);
28
+ return Array.from(bytes)
29
+ .map((b) => b.toString(16).padStart(2, "0"))
30
+ .join("");
31
+ }
32
+
29
33
  export const create = mutation({
30
34
  args: {
31
35
  name: v.string(),
@@ -38,9 +42,6 @@ export const create = mutation({
38
42
  remaining: v.optional(v.number()),
39
43
  expiresAt: v.optional(v.number()),
40
44
  keyPrefix: v.optional(v.string()),
41
- lookupPrefix: v.string(),
42
- secretHex: v.string(),
43
- hash: v.string(),
44
45
  },
45
46
  returns: v.object({
46
47
  keyId: v.id("apiKeys"),
@@ -57,19 +58,25 @@ export const create = mutation({
57
58
  validateTags(args.tags);
58
59
  }
59
60
 
60
- await rateLimiter.limit(ctx, "createKey", {
61
- key: args.ownerId,
62
- throws: true,
63
- });
61
+ const prefix = args.keyPrefix ?? "vk";
62
+ validateKeyPrefix(prefix);
63
+ const env = args.env ?? "live";
64
+ validateEnv(env);
65
+ validateSizeLimits({ metadata: args.metadata, scopes: args.scopes, tags: args.tags, name: args.name });
64
66
 
65
67
  const type = args.type ?? "secret";
66
- const env = args.env ?? "live";
67
- const prefix = args.keyPrefix ?? "vk";
68
68
  const typeShort = type === "publishable" ? "pub" : "secret";
69
69
 
70
+ const lookupPrefix = generateRandomHex(8);
71
+ const secretHex = generateRandomHex(64);
72
+ const rawKey = [prefix, typeShort, env, lookupPrefix, secretHex].join(
73
+ KEY_PREFIX_SEPARATOR,
74
+ );
75
+ const hash = await sha256Hex(rawKey);
76
+
70
77
  const keyId = await ctx.db.insert("apiKeys", {
71
- hash: args.hash,
72
- lookupPrefix: args.lookupPrefix,
78
+ hash,
79
+ lookupPrefix,
73
80
  keyPrefix: prefix,
74
81
  type,
75
82
  env,
@@ -83,22 +90,13 @@ export const create = mutation({
83
90
  expiresAt: args.expiresAt,
84
91
  });
85
92
 
86
- await ctx.db.insert("apiKeyEvents", {
87
- keyId,
88
- ownerId: args.ownerId,
89
- eventType: "key.created",
90
- timestamp: Date.now(),
91
- });
92
-
93
- const rawKey = [prefix, typeShort, env, args.lookupPrefix, args.secretHex].join(
94
- KEY_PREFIX_SEPARATOR,
95
- );
96
-
97
- log.info("key created", { keyId, ownerId: args.ownerId, type, env });
93
+ log.info("key.created", { keyId, ownerId: args.ownerId, type, env });
98
94
  return { keyId, key: rawKey };
99
95
  },
100
96
  });
101
97
 
98
+ const LAST_USED_AT_THROTTLE_MS = 60_000;
99
+
102
100
  export const validate = mutation({
103
101
  args: {
104
102
  key: v.string(),
@@ -118,12 +116,12 @@ export const validate = mutation({
118
116
  v.object({
119
117
  valid: v.literal(false),
120
118
  reason: v.string(),
121
- retryAfter: v.optional(v.number()),
122
119
  }),
123
120
  ),
124
121
  handler: async (ctx, { key }) => {
125
122
  const parsed = parseKeyString(key);
126
123
  if (!parsed.valid) {
124
+ log.info("key.validate_failed", { reason: "malformed" });
127
125
  return { valid: false as const, reason: "malformed" };
128
126
  }
129
127
 
@@ -133,6 +131,7 @@ export const validate = mutation({
133
131
  .collect();
134
132
 
135
133
  if (candidates.length === 0) {
134
+ log.info("key.validate_failed", { reason: "not_found", lookupPrefix: parsed.lookupPrefix });
136
135
  return { valid: false as const, reason: "not_found" };
137
136
  }
138
137
 
@@ -147,45 +146,30 @@ export const validate = mutation({
147
146
  }
148
147
 
149
148
  if (!matchedKey) {
149
+ log.info("key.validate_failed", { reason: "not_found", lookupPrefix: parsed.lookupPrefix });
150
150
  return { valid: false as const, reason: "not_found" };
151
151
  }
152
152
 
153
153
  const now = Date.now();
154
154
 
155
155
  if (matchedKey.status === "revoked") {
156
- await ctx.db.insert("apiKeyEvents", {
157
- keyId: matchedKey._id,
158
- ownerId: matchedKey.ownerId,
159
- eventType: "key.validate_failed",
160
- reason: "revoked",
161
- timestamp: now,
162
- });
156
+ log.info("key.validate_failed", { keyId: matchedKey._id, reason: "revoked" });
163
157
  return { valid: false as const, reason: "revoked" };
164
158
  }
165
159
 
166
160
  if (matchedKey.status === "disabled") {
167
- await ctx.db.insert("apiKeyEvents", {
168
- keyId: matchedKey._id,
169
- ownerId: matchedKey.ownerId,
170
- eventType: "key.validate_failed",
171
- reason: "disabled",
172
- timestamp: now,
173
- });
161
+ log.info("key.validate_failed", { keyId: matchedKey._id, reason: "disabled" });
174
162
  return { valid: false as const, reason: "disabled" };
175
163
  }
176
164
 
177
165
  if (matchedKey.status === "exhausted") {
166
+ log.info("key.validate_failed", { keyId: matchedKey._id, reason: "exhausted" });
178
167
  return { valid: false as const, reason: "exhausted" };
179
168
  }
180
169
 
181
170
  if (matchedKey.expiresAt && matchedKey.expiresAt <= now) {
182
171
  await ctx.db.patch(matchedKey._id, { status: "expired" });
183
- await ctx.db.insert("apiKeyEvents", {
184
- keyId: matchedKey._id,
185
- ownerId: matchedKey.ownerId,
186
- eventType: "key.expired",
187
- timestamp: now,
188
- });
172
+ log.info("key.expired", { keyId: matchedKey._id });
189
173
  return { valid: false as const, reason: "expired" };
190
174
  }
191
175
 
@@ -195,13 +179,7 @@ export const validate = mutation({
195
179
  matchedKey.gracePeriodEnd <= now
196
180
  ) {
197
181
  await ctx.db.patch(matchedKey._id, { status: "expired" });
198
- await ctx.db.insert("apiKeyEvents", {
199
- keyId: matchedKey._id,
200
- ownerId: matchedKey.ownerId,
201
- eventType: "key.expired",
202
- reason: "grace_period_ended",
203
- timestamp: now,
204
- });
182
+ log.info("key.expired", { keyId: matchedKey._id, reason: "grace_period_ended" });
205
183
  return { valid: false as const, reason: "expired" };
206
184
  }
207
185
 
@@ -209,58 +187,35 @@ export const validate = mutation({
209
187
  if (matchedKey.remaining !== undefined) {
210
188
  if (matchedKey.remaining <= 0) {
211
189
  await ctx.db.patch(matchedKey._id, { status: "exhausted" });
212
- await ctx.db.insert("apiKeyEvents", {
213
- keyId: matchedKey._id,
214
- ownerId: matchedKey.ownerId,
215
- eventType: "key.exhausted",
216
- timestamp: now,
217
- });
190
+ log.info("key.exhausted", { keyId: matchedKey._id });
218
191
  return { valid: false as const, reason: "exhausted" };
219
192
  }
220
193
  newRemaining = matchedKey.remaining - 1;
221
- const updates: Record<string, unknown> = {
222
- remaining: newRemaining,
223
- lastUsedAt: now,
224
- };
225
- if (newRemaining === 0) {
226
- updates.status = "exhausted";
227
- }
228
- await ctx.db.patch(matchedKey._id, updates);
194
+ }
229
195
 
196
+ const shouldUpdateLastUsed =
197
+ !matchedKey.lastUsedAt || now - matchedKey.lastUsedAt >= LAST_USED_AT_THROTTLE_MS;
198
+
199
+ const patch: Record<string, unknown> = {};
200
+ if (newRemaining !== matchedKey.remaining) {
201
+ patch.remaining = newRemaining;
230
202
  if (newRemaining === 0) {
231
- await ctx.db.insert("apiKeyEvents", {
232
- keyId: matchedKey._id,
233
- ownerId: matchedKey.ownerId,
234
- eventType: "key.exhausted",
235
- timestamp: now,
236
- });
203
+ patch.status = "exhausted";
237
204
  }
238
- } else {
239
- await ctx.db.patch(matchedKey._id, { lastUsedAt: now });
240
205
  }
241
-
242
- const { ok, retryAfter } = await rateLimiter.limit(ctx, "validateKey", {
243
- key: matchedKey._id,
244
- throws: false,
245
- });
246
- if (!ok) {
247
- await ctx.db.insert("apiKeyEvents", {
248
- keyId: matchedKey._id,
249
- ownerId: matchedKey.ownerId,
250
- eventType: "key.rate_limited",
251
- timestamp: now,
252
- });
253
- return { valid: false as const, reason: "rate_limited", retryAfter };
206
+ if (shouldUpdateLastUsed) {
207
+ patch.lastUsedAt = now;
208
+ }
209
+ if (Object.keys(patch).length > 0) {
210
+ await ctx.db.patch(matchedKey._id, patch);
211
+ }
212
+ if (newRemaining === 0) {
213
+ log.info("key.exhausted", { keyId: matchedKey._id });
254
214
  }
255
215
 
256
216
  await counter.add(ctx, matchedKey._id, 1);
257
217
 
258
- await ctx.db.insert("apiKeyEvents", {
259
- keyId: matchedKey._id,
260
- ownerId: matchedKey.ownerId,
261
- eventType: "key.validated",
262
- timestamp: now,
263
- });
218
+ log.info("key.validated", { keyId: matchedKey._id, ownerId: matchedKey.ownerId });
264
219
 
265
220
  return {
266
221
  valid: true as const,
@@ -279,24 +234,22 @@ export const validate = mutation({
279
234
  export const revoke = mutation({
280
235
  args: {
281
236
  keyId: v.id("apiKeys"),
237
+ ownerId: v.string(),
282
238
  },
283
239
  returns: v.null(),
284
- handler: async (ctx, { keyId }) => {
240
+ handler: async (ctx, { keyId, ownerId }) => {
285
241
  const key = await ctx.db.get(keyId);
286
242
  if (!key) {
287
243
  throw new Error("key not found");
288
244
  }
245
+ if (key.ownerId !== ownerId) {
246
+ throw new Error("unauthorized: key does not belong to owner");
247
+ }
289
248
  if (key.status === "revoked") {
290
249
  return null;
291
250
  }
292
251
  await ctx.db.patch(keyId, { status: "revoked", revokedAt: Date.now() });
293
- await ctx.db.insert("apiKeyEvents", {
294
- keyId,
295
- ownerId: key.ownerId,
296
- eventType: "key.revoked",
297
- timestamp: Date.now(),
298
- });
299
- log.info("key revoked", { keyId, ownerId: key.ownerId });
252
+ log.info("key.revoked", { keyId, ownerId });
300
253
  return null;
301
254
  },
302
255
  });
@@ -308,36 +261,41 @@ export const revokeByTag = mutation({
308
261
  },
309
262
  returns: v.object({ revokedCount: v.number() }),
310
263
  handler: async (ctx, { ownerId, tag }) => {
311
- const keys = await ctx.db
264
+ const activeKeys = await ctx.db
312
265
  .query("apiKeys")
313
266
  .withIndex("by_owner_status", (q) => q.eq("ownerId", ownerId).eq("status", "active"))
314
267
  .collect();
268
+ const rotatingKeys = await ctx.db
269
+ .query("apiKeys")
270
+ .withIndex("by_owner_status", (q) => q.eq("ownerId", ownerId).eq("status", "rotating"))
271
+ .collect();
272
+ const disabledKeys = await ctx.db
273
+ .query("apiKeys")
274
+ .withIndex("by_owner_status", (q) => q.eq("ownerId", ownerId).eq("status", "disabled"))
275
+ .collect();
315
276
 
277
+ const allKeys = [...activeKeys, ...rotatingKeys, ...disabledKeys];
316
278
  let revokedCount = 0;
317
279
  const now = Date.now();
318
- for (const key of keys) {
280
+ for (const key of allKeys) {
319
281
  if (key.tags.includes(tag)) {
320
282
  await ctx.db.patch(key._id, { status: "revoked", revokedAt: now });
321
- await ctx.db.insert("apiKeyEvents", {
322
- keyId: key._id,
323
- ownerId,
324
- eventType: "key.revoked",
325
- reason: `bulk_revoke_by_tag:${tag}`,
326
- timestamp: now,
327
- });
328
283
  revokedCount++;
329
284
  }
330
285
  }
286
+ log.info("key.bulk_revoked", { ownerId, tag, revokedCount });
331
287
  return { revokedCount };
332
288
  },
333
289
  });
334
290
 
291
+ const MIN_GRACE_PERIOD_MS = 60_000;
292
+ const MAX_GRACE_PERIOD_MS = 30 * 24 * 60 * 60 * 1000;
293
+
335
294
  export const rotate = mutation({
336
295
  args: {
337
296
  keyId: v.id("apiKeys"),
297
+ ownerId: v.string(),
338
298
  gracePeriodMs: v.optional(v.number()),
339
- lookupPrefix: v.string(),
340
- secretHex: v.string(),
341
299
  },
342
300
  returns: v.object({
343
301
  newKeyId: v.id("apiKeys"),
@@ -349,12 +307,21 @@ export const rotate = mutation({
349
307
  if (!oldKey) {
350
308
  throw new Error("key not found");
351
309
  }
310
+ if (oldKey.ownerId !== args.ownerId) {
311
+ throw new Error("unauthorized: key does not belong to owner");
312
+ }
352
313
  if (TERMINAL_STATUSES.has(oldKey.status as KeyStatus)) {
353
314
  throw new Error("cannot rotate a terminal key");
354
315
  }
355
316
 
356
- const now = Date.now();
357
317
  const gracePeriodMs = args.gracePeriodMs ?? 3600000;
318
+ if (gracePeriodMs < MIN_GRACE_PERIOD_MS || gracePeriodMs > MAX_GRACE_PERIOD_MS) {
319
+ throw new Error(
320
+ `gracePeriodMs must be between ${MIN_GRACE_PERIOD_MS} (60s) and ${MAX_GRACE_PERIOD_MS} (30 days)`,
321
+ );
322
+ }
323
+
324
+ const now = Date.now();
358
325
  const gracePeriodEnd = now + gracePeriodMs;
359
326
 
360
327
  await ctx.db.patch(args.keyId, {
@@ -363,18 +330,20 @@ export const rotate = mutation({
363
330
  });
364
331
 
365
332
  const typeShort = oldKey.type === "publishable" ? "pub" : "secret";
333
+ const lookupPrefix = generateRandomHex(8);
334
+ const secretHex = generateRandomHex(64);
366
335
  const rawKey = [
367
336
  oldKey.keyPrefix,
368
337
  typeShort,
369
338
  oldKey.env,
370
- args.lookupPrefix,
371
- args.secretHex,
339
+ lookupPrefix,
340
+ secretHex,
372
341
  ].join(KEY_PREFIX_SEPARATOR);
373
342
  const hash = await sha256Hex(rawKey);
374
343
 
375
344
  const newKeyId = await ctx.db.insert("apiKeys", {
376
345
  hash,
377
- lookupPrefix: args.lookupPrefix,
346
+ lookupPrefix,
378
347
  keyPrefix: oldKey.keyPrefix,
379
348
  type: oldKey.type,
380
349
  env: oldKey.env,
@@ -389,14 +358,7 @@ export const rotate = mutation({
389
358
  rotatedFromId: args.keyId,
390
359
  });
391
360
 
392
- await ctx.db.insert("apiKeyEvents", {
393
- keyId: args.keyId,
394
- ownerId: oldKey.ownerId,
395
- eventType: "key.rotated",
396
- metadata: { newKeyId },
397
- timestamp: now,
398
- });
399
-
361
+ log.info("key.rotated", { keyId: args.keyId, newKeyId, ownerId: oldKey.ownerId });
400
362
  return { newKeyId, newKey: rawKey, oldKeyExpiresAt: gracePeriodEnd };
401
363
  },
402
364
  });
@@ -404,23 +366,28 @@ export const rotate = mutation({
404
366
  export const update = mutation({
405
367
  args: {
406
368
  keyId: v.id("apiKeys"),
369
+ ownerId: v.string(),
407
370
  name: v.optional(v.string()),
408
371
  scopes: v.optional(v.array(v.string())),
409
372
  tags: v.optional(v.array(v.string())),
410
373
  metadata: v.optional(jsonValue),
411
374
  },
412
375
  returns: v.null(),
413
- handler: async (ctx, { keyId, ...updates }) => {
376
+ handler: async (ctx, { keyId, ownerId, ...updates }) => {
414
377
  const key = await ctx.db.get(keyId);
415
378
  if (!key) {
416
379
  throw new Error("key not found");
417
380
  }
381
+ if (key.ownerId !== ownerId) {
382
+ throw new Error("unauthorized: key does not belong to owner");
383
+ }
418
384
  if (TERMINAL_STATUSES.has(key.status as KeyStatus)) {
419
385
  throw new Error("cannot update terminal key");
420
386
  }
421
387
  if (updates.tags) {
422
388
  validateTags(updates.tags);
423
389
  }
390
+ validateSizeLimits({ metadata: updates.metadata, scopes: updates.scopes, tags: updates.tags, name: updates.name });
424
391
 
425
392
  const patch: Record<string, unknown> = {};
426
393
  if (updates.name !== undefined) patch.name = updates.name;
@@ -430,13 +397,7 @@ export const update = mutation({
430
397
 
431
398
  if (Object.keys(patch).length > 0) {
432
399
  await ctx.db.patch(keyId, patch);
433
- await ctx.db.insert("apiKeyEvents", {
434
- keyId,
435
- ownerId: key.ownerId,
436
- eventType: "key.updated",
437
- metadata: { fields: Object.keys(patch) },
438
- timestamp: Date.now(),
439
- });
400
+ log.info("key.updated", { keyId, ownerId, fields: Object.keys(patch) });
440
401
  }
441
402
 
442
403
  return null;
@@ -444,13 +405,19 @@ export const update = mutation({
444
405
  });
445
406
 
446
407
  export const disable = mutation({
447
- args: { keyId: v.id("apiKeys") },
408
+ args: {
409
+ keyId: v.id("apiKeys"),
410
+ ownerId: v.string(),
411
+ },
448
412
  returns: v.null(),
449
- handler: async (ctx, { keyId }) => {
413
+ handler: async (ctx, { keyId, ownerId }) => {
450
414
  const key = await ctx.db.get(keyId);
451
415
  if (!key) {
452
416
  throw new Error("key not found");
453
417
  }
418
+ if (key.ownerId !== ownerId) {
419
+ throw new Error("unauthorized: key does not belong to owner");
420
+ }
454
421
  if (key.status === "disabled") {
455
422
  return null;
456
423
  }
@@ -458,24 +425,25 @@ export const disable = mutation({
458
425
  throw new Error("can only disable active keys");
459
426
  }
460
427
  await ctx.db.patch(keyId, { status: "disabled" });
461
- await ctx.db.insert("apiKeyEvents", {
462
- keyId,
463
- ownerId: key.ownerId,
464
- eventType: "key.disabled",
465
- timestamp: Date.now(),
466
- });
428
+ log.info("key.disabled", { keyId, ownerId });
467
429
  return null;
468
430
  },
469
431
  });
470
432
 
471
433
  export const enable = mutation({
472
- args: { keyId: v.id("apiKeys") },
434
+ args: {
435
+ keyId: v.id("apiKeys"),
436
+ ownerId: v.string(),
437
+ },
473
438
  returns: v.null(),
474
- handler: async (ctx, { keyId }) => {
439
+ handler: async (ctx, { keyId, ownerId }) => {
475
440
  const key = await ctx.db.get(keyId);
476
441
  if (!key) {
477
442
  throw new Error("key not found");
478
443
  }
444
+ if (key.ownerId !== ownerId) {
445
+ throw new Error("unauthorized: key does not belong to owner");
446
+ }
479
447
  if (key.status === "active") {
480
448
  return null;
481
449
  }
@@ -483,12 +451,7 @@ export const enable = mutation({
483
451
  throw new Error("can only enable disabled keys");
484
452
  }
485
453
  await ctx.db.patch(keyId, { status: "active" });
486
- await ctx.db.insert("apiKeyEvents", {
487
- keyId,
488
- ownerId: key.ownerId,
489
- eventType: "key.enabled",
490
- timestamp: Date.now(),
491
- });
454
+ log.info("key.enabled", { keyId, ownerId });
492
455
  return null;
493
456
  },
494
457
  });
@@ -500,12 +463,25 @@ export const configure = mutation({
500
463
  },
501
464
  returns: v.null(),
502
465
  handler: async (ctx, args) => {
466
+ if (args.cleanupIntervalMs !== undefined && args.cleanupIntervalMs <= 0) {
467
+ throw new Error("cleanupIntervalMs must be > 0");
468
+ }
469
+ if (args.defaultExpiryMs !== undefined && args.defaultExpiryMs <= 0) {
470
+ throw new Error("defaultExpiryMs must be > 0");
471
+ }
472
+
503
473
  const existing = await ctx.db.query("config").first();
474
+ const oldValues = existing
475
+ ? { cleanupIntervalMs: existing.cleanupIntervalMs, defaultExpiryMs: existing.defaultExpiryMs }
476
+ : {};
477
+
504
478
  if (existing) {
505
479
  await ctx.db.patch(existing._id, args);
506
480
  } else {
507
481
  await ctx.db.insert("config", args);
508
482
  }
483
+
484
+ log.info("config.updated", { old: oldValues, new: args });
509
485
  return null;
510
486
  },
511
487
  });