File size: 22,699 Bytes
97ee7cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
import { convexTest } from "convex-test";
import { expect, test, describe, beforeEach, afterEach, vi } from "vitest";
import schema from "../schema";
import { api, internal } from "../_generated/api";
import { getFeaturesForPlan } from "../lib/entitlements";

const modules = import.meta.glob("../**/*.ts");

// ---------------------------------------------------------------------------
// Helpers (mirrors convex/__tests__/apiKeys.test.ts)
// ---------------------------------------------------------------------------

const NOW = Date.now();
const FUTURE = NOW + 86400000 * 30; // 30 days
const PAST = NOW - 86400000; // 1 day ago

const API_USER = { subject: "user-api", tokenIdentifier: "clerk|user-api" };
const PRO_USER = { subject: "user-pro", tokenIdentifier: "clerk|user-pro" };
const FREE_USER = { subject: "user-free", tokenIdentifier: "clerk|user-free" };
const OTHER_USER = { subject: "user-other", tokenIdentifier: "clerk|user-other" };

const SHARED_SECRET = "test-shared-secret";

async function seedProEntitlement(
  t: ReturnType<typeof convexTest>,
  userId: string,
  opts: { validUntil?: number } = {},
) {
  await t.run(async (ctx) => {
    await ctx.db.insert("entitlements", {
      userId,
      planKey: "pro_monthly",
      features: getFeaturesForPlan("pro_monthly"),
      validUntil: opts.validUntil ?? FUTURE,
      updatedAt: NOW,
    });
  });
}

async function seedApiEntitlement(
  t: ReturnType<typeof convexTest>,
  userId: string,
  opts: { validUntil?: number } = {},
) {
  await t.run(async (ctx) => {
    await ctx.db.insert("entitlements", {
      userId,
      planKey: "api_starter",
      features: getFeaturesForPlan("api_starter"),
      validUntil: opts.validUntil ?? FUTURE,
      updatedAt: NOW,
    });
  });
}

// ---------------------------------------------------------------------------
// issueProMcpToken (internal)
// ---------------------------------------------------------------------------

describe("issueProMcpToken", () => {
  test("succeeds for tier-1 (Pro) user", async () => {
    const t = convexTest(schema, modules);
    await seedProEntitlement(t, "user-pro");

    const result = await t.mutation(internal.mcpProTokens.issueProMcpToken, {
      userId: "user-pro",
      clientId: "claude-desktop",
      name: "Connected via Claude Desktop",
    });

    expect(result.tokenId).toBeTruthy();

    // Verify row exists with revokedAt unset
    const row = await t.run(async (ctx) => ctx.db.get(result.tokenId));
    expect(row).toBeTruthy();
    expect(row?.userId).toBe("user-pro");
    expect(row?.clientId).toBe("claude-desktop");
    expect(row?.name).toBe("Connected via Claude Desktop");
    expect(row?.revokedAt).toBeUndefined();
    expect(row?.createdAt).toBeGreaterThan(0);
  });

  test("succeeds for tier-2 (API) user β€” Pro is the floor not exclusive", async () => {
    const t = convexTest(schema, modules);
    await seedApiEntitlement(t, "user-api");

    const result = await t.mutation(internal.mcpProTokens.issueProMcpToken, {
      userId: "user-api",
    });
    expect(result.tokenId).toBeTruthy();
  });

  test("rejects tier-0 (free) user with PRO_REQUIRED", async () => {
    const t = convexTest(schema, modules);

    await expect(
      t.mutation(internal.mcpProTokens.issueProMcpToken, { userId: "user-free" }),
    ).rejects.toThrow(/PRO_REQUIRED/);
  });

  test("rejects tier-1 user whose entitlement has lapsed", async () => {
    const t = convexTest(schema, modules);
    await seedProEntitlement(t, "user-pro", { validUntil: PAST });

    await expect(
      t.mutation(internal.mcpProTokens.issueProMcpToken, { userId: "user-pro" }),
    ).rejects.toThrow(/PRO_REQUIRED/);
  });

  test("F5 convergence: 6 actives (race-leftover) β†’ next issue trims to MAX", async () => {
    // Models the post-race state the F5 fix converges from: a brief
    // racing window left 6 active rows; the next issue call must trim
    // back to MAX (5) β€” that's the "eventually 5" guarantee.
    const t = convexTest(schema, modules);
    await seedProEntitlement(t, "user-pro");

    // Manually seed 6 active rows (simulates the race outcome).
    await t.run(async (ctx) => {
      const now = Date.now();
      for (let i = 0; i < 6; i++) {
        await ctx.db.insert("mcpProTokens", {
          userId: "user-pro",
          createdAt: now - (6 - i) * 1000, // oldest first
          name: `racing-slot-${i + 1}`,
        });
      }
    });

    // Next issue must converge: revoke 2 oldest, insert 1 new β†’ 5 active.
    const seventh = await t.mutation(internal.mcpProTokens.issueProMcpToken, {
      userId: "user-pro",
      name: "post-race",
    });
    expect(seventh.tokenId).toBeTruthy();

    const rows = await t
      .withIdentity(PRO_USER)
      .query(api.mcpProTokens.listProMcpTokens, {});
    const active = rows.filter((r: any) => !r.revokedAt);
    expect(active).toHaveLength(5);
  });

  test("6th issue rotates oldest β€” caps active rows at 5", async () => {
    const t = convexTest(schema, modules);
    await seedProEntitlement(t, "user-pro");

    const ids: string[] = [];
    for (let i = 1; i <= 5; i++) {
      const r = await t.mutation(internal.mcpProTokens.issueProMcpToken, {
        userId: "user-pro",
        name: `slot-${i}`,
      });
      ids.push(r.tokenId);
    }

    // Sixth issue should rotate the oldest (slot-1) and return a new id
    const sixth = await t.mutation(internal.mcpProTokens.issueProMcpToken, {
      userId: "user-pro",
      name: "slot-6",
    });
    expect(sixth.tokenId).toBeTruthy();
    expect(ids).not.toContain(sixth.tokenId);

    // The oldest row must be revoked, NOT deleted (audit trail)
    const oldestRow = await t.run(async (ctx) => ctx.db.get(ids[0] as any));
    expect(oldestRow).toBeTruthy();
    expect(oldestRow?.revokedAt).toBeGreaterThan(0);

    // Active count is exactly 5
    const allRows = await t.withIdentity(PRO_USER).query(api.mcpProTokens.listProMcpTokens, {});
    const active = allRows.filter((r: any) => !r.revokedAt);
    expect(active).toHaveLength(5);
  });
});

// ---------------------------------------------------------------------------
// validateProMcpToken (internal)
// ---------------------------------------------------------------------------

describe("validateProMcpToken", () => {
  test("returns {userId} for active row", async () => {
    const t = convexTest(schema, modules);
    await seedProEntitlement(t, "user-pro");

    const issued = await t.mutation(internal.mcpProTokens.issueProMcpToken, {
      userId: "user-pro",
    });

    const result = await t.query(internal.mcpProTokens.validateProMcpToken, {
      tokenId: issued.tokenId,
    });
    expect(result).toEqual({ userId: "user-pro" });
  });

  test("returns null for revoked row", async () => {
    const t = convexTest(schema, modules);
    await seedProEntitlement(t, "user-pro");

    const issued = await t.mutation(internal.mcpProTokens.issueProMcpToken, {
      userId: "user-pro",
    });
    await t.withIdentity(PRO_USER).mutation(api.mcpProTokens.revokeProMcpToken, {
      tokenId: issued.tokenId,
    });

    const result = await t.query(internal.mcpProTokens.validateProMcpToken, {
      tokenId: issued.tokenId,
    });
    expect(result).toBeNull();
  });

  test("returns null for non-existent tokenId (real-shape id)", async () => {
    const t = convexTest(schema, modules);
    await seedProEntitlement(t, "user-pro");

    // Issue then delete to obtain a syntactically valid but non-existent id
    const issued = await t.mutation(internal.mcpProTokens.issueProMcpToken, {
      userId: "user-pro",
    });
    await t.run(async (ctx) => ctx.db.delete(issued.tokenId));

    const result = await t.query(internal.mcpProTokens.validateProMcpToken, {
      tokenId: issued.tokenId,
    });
    expect(result).toBeNull();
  });
});

// ---------------------------------------------------------------------------
// revokeProMcpToken (public)
// ---------------------------------------------------------------------------

describe("revokeProMcpToken", () => {
  test("owner revoke sets revokedAt and subsequent validate returns null", async () => {
    const t = convexTest(schema, modules);
    await seedProEntitlement(t, "user-pro");

    const issued = await t.mutation(internal.mcpProTokens.issueProMcpToken, {
      userId: "user-pro",
    });

    const result = await t.withIdentity(PRO_USER).mutation(
      api.mcpProTokens.revokeProMcpToken,
      { tokenId: issued.tokenId },
    );
    expect(result).toEqual({ ok: true });

    const validated = await t.query(internal.mcpProTokens.validateProMcpToken, {
      tokenId: issued.tokenId,
    });
    expect(validated).toBeNull();
  });

  test("non-owner revoke throws NOT_FOUND (no leak)", async () => {
    const t = convexTest(schema, modules);
    await seedProEntitlement(t, "user-pro");

    const issued = await t.mutation(internal.mcpProTokens.issueProMcpToken, {
      userId: "user-pro",
    });

    await expect(
      t.withIdentity(OTHER_USER).mutation(api.mcpProTokens.revokeProMcpToken, {
        tokenId: issued.tokenId,
      }),
    ).rejects.toThrow(/NOT_FOUND/);
  });

  test("double revoke throws ALREADY_REVOKED", async () => {
    const t = convexTest(schema, modules);
    await seedProEntitlement(t, "user-pro");

    const issued = await t.mutation(internal.mcpProTokens.issueProMcpToken, {
      userId: "user-pro",
    });
    const asPro = t.withIdentity(PRO_USER);
    await asPro.mutation(api.mcpProTokens.revokeProMcpToken, {
      tokenId: issued.tokenId,
    });

    await expect(
      asPro.mutation(api.mcpProTokens.revokeProMcpToken, { tokenId: issued.tokenId }),
    ).rejects.toThrow(/ALREADY_REVOKED/);
  });
});

// ---------------------------------------------------------------------------
// listProMcpTokens (public)
// ---------------------------------------------------------------------------

describe("listProMcpTokens", () => {
  test("returns empty array for user with zero rows", async () => {
    const t = convexTest(schema, modules);
    const rows = await t.withIdentity(PRO_USER).query(api.mcpProTokens.listProMcpTokens, {});
    expect(rows).toEqual([]);
  });

  test("returns ALL rows (active + revoked) for transparency", async () => {
    const t = convexTest(schema, modules);
    await seedProEntitlement(t, "user-pro");

    const a = await t.mutation(internal.mcpProTokens.issueProMcpToken, {
      userId: "user-pro",
      name: "active-one",
    });
    const b = await t.mutation(internal.mcpProTokens.issueProMcpToken, {
      userId: "user-pro",
      name: "to-be-revoked",
    });
    await t.withIdentity(PRO_USER).mutation(api.mcpProTokens.revokeProMcpToken, {
      tokenId: b.tokenId,
    });

    const rows = await t.withIdentity(PRO_USER).query(api.mcpProTokens.listProMcpTokens, {});
    expect(rows).toHaveLength(2);
    expect(rows.find((r: any) => r.id === a.tokenId)?.revokedAt).toBeUndefined();
    expect(rows.find((r: any) => r.id === b.tokenId)?.revokedAt).toBeGreaterThan(0);
  });

  test("does not return other users' rows", async () => {
    const t = convexTest(schema, modules);
    await seedProEntitlement(t, "user-pro");

    await t.mutation(internal.mcpProTokens.issueProMcpToken, { userId: "user-pro" });

    const rows = await t.withIdentity(OTHER_USER).query(api.mcpProTokens.listProMcpTokens, {});
    expect(rows).toEqual([]);
  });

  test("returns empty array when called without auth identity (does not throw AUTH_REQUIRED)", async () => {
    // WORLDMONITOR-RD regression: this query is reactive (subscribed by
    // the settings UI), so it fires during transient unauth windows β€”
    // sign-out, initial page load before Clerk resolves, token-rotation
    // races. Throwing AUTH_REQUIRED from those races was paging via
    // Convex's server-side Sentry integration despite the
    // requireUserId() comment explicitly aiming to suppress N3-class
    // noise. Returning [] is observationally identical to "no tokens
    // yet" and removes the throw entirely.
    const t = convexTest(schema, modules);

    // Seed a token under a real user so we can prove the no-auth caller
    // gets empty (not the other user's row, not a throw).
    await seedProEntitlement(t, "user-pro");
    await t.mutation(internal.mcpProTokens.issueProMcpToken, { userId: "user-pro" });

    // No .withIdentity(...) β€” simulates the unauth race.
    const rows = await t.query(api.mcpProTokens.listProMcpTokens, {});
    expect(rows).toEqual([]);
  });
});

// ---------------------------------------------------------------------------
// touchProMcpTokenLastUsed (internal) β€” debounce
// ---------------------------------------------------------------------------

describe("touchProMcpTokenLastUsed", () => {
  test("sets lastUsedAt on first call", async () => {
    const t = convexTest(schema, modules);
    await seedProEntitlement(t, "user-pro");

    const issued = await t.mutation(internal.mcpProTokens.issueProMcpToken, {
      userId: "user-pro",
    });

    await t.mutation(internal.mcpProTokens.touchProMcpTokenLastUsed, {
      tokenId: issued.tokenId,
    });

    const rows = await t.withIdentity(PRO_USER).query(api.mcpProTokens.listProMcpTokens, {});
    const row = rows.find((r: any) => r.id === issued.tokenId);
    expect(row?.lastUsedAt).toBeGreaterThan(0);
  });

  test("debounces: second call within 5min does not bump lastUsedAt", async () => {
    const t = convexTest(schema, modules);
    await seedProEntitlement(t, "user-pro");

    const issued = await t.mutation(internal.mcpProTokens.issueProMcpToken, {
      userId: "user-pro",
    });

    await t.mutation(internal.mcpProTokens.touchProMcpTokenLastUsed, {
      tokenId: issued.tokenId,
    });
    const after1 = (await t.withIdentity(PRO_USER).query(api.mcpProTokens.listProMcpTokens, {}))
      .find((r: any) => r.id === issued.tokenId)?.lastUsedAt;

    // Immediate second call should be debounced
    await t.mutation(internal.mcpProTokens.touchProMcpTokenLastUsed, {
      tokenId: issued.tokenId,
    });
    const after2 = (await t.withIdentity(PRO_USER).query(api.mcpProTokens.listProMcpTokens, {}))
      .find((r: any) => r.id === issued.tokenId)?.lastUsedAt;

    expect(after1).toBe(after2);
  });

  test("no-op on revoked row (don't bump revoked tokens)", async () => {
    const t = convexTest(schema, modules);
    await seedProEntitlement(t, "user-pro");

    const issued = await t.mutation(internal.mcpProTokens.issueProMcpToken, {
      userId: "user-pro",
    });
    await t.withIdentity(PRO_USER).mutation(api.mcpProTokens.revokeProMcpToken, {
      tokenId: issued.tokenId,
    });

    // Should not throw and lastUsedAt must remain unset
    await t.mutation(internal.mcpProTokens.touchProMcpTokenLastUsed, {
      tokenId: issued.tokenId,
    });

    const rows = await t.withIdentity(PRO_USER).query(api.mcpProTokens.listProMcpTokens, {});
    const row = rows.find((r: any) => r.id === issued.tokenId);
    expect(row?.lastUsedAt).toBeUndefined();
  });
});

// ---------------------------------------------------------------------------
// HTTP routes (service-to-service via x-convex-shared-secret)
// ---------------------------------------------------------------------------

describe("HTTP route /api/internal-issue-pro-mcp-token", () => {
  beforeEach(() => {
    process.env.CONVEX_SERVER_SHARED_SECRET = SHARED_SECRET;
  });
  afterEach(() => {
    delete process.env.CONVEX_SERVER_SHARED_SECRET;
  });

  test("rejects missing shared-secret with 401", async () => {
    const t = convexTest(schema, modules);
    const res = await t.fetch("/api/internal-issue-pro-mcp-token", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ userId: "user-pro" }),
    });
    expect(res.status).toBe(401);
  });

  test("rejects wrong shared-secret with 401", async () => {
    const t = convexTest(schema, modules);
    const res = await t.fetch("/api/internal-issue-pro-mcp-token", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "x-convex-shared-secret": "wrong",
      },
      body: JSON.stringify({ userId: "user-pro" }),
    });
    expect(res.status).toBe(401);
  });

  test("happy path: tier-1 user β†’ 200 with tokenId", async () => {
    const t = convexTest(schema, modules);
    await seedProEntitlement(t, "user-pro");

    const res = await t.fetch("/api/internal-issue-pro-mcp-token", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "x-convex-shared-secret": SHARED_SECRET,
      },
      body: JSON.stringify({ userId: "user-pro", clientId: "cl", name: "n" }),
    });
    expect(res.status).toBe(200);
    const body = (await res.json()) as { tokenId?: string };
    expect(body.tokenId).toBeTruthy();
  });

  test("tier-0 β†’ 403 PRO_REQUIRED", async () => {
    const t = convexTest(schema, modules);

    const res = await t.fetch("/api/internal-issue-pro-mcp-token", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "x-convex-shared-secret": SHARED_SECRET,
      },
      body: JSON.stringify({ userId: "user-free" }),
    });
    expect(res.status).toBe(403);
    const body = (await res.json()) as { error?: string };
    expect(body.error).toBe("PRO_REQUIRED");
  });
});

describe("HTTP route /api/internal-validate-pro-mcp-token", () => {
  beforeEach(() => {
    process.env.CONVEX_SERVER_SHARED_SECRET = SHARED_SECRET;
  });
  afterEach(() => {
    delete process.env.CONVEX_SERVER_SHARED_SECRET;
  });

  test("rejects missing shared-secret with 401", async () => {
    const t = convexTest(schema, modules);
    const res = await t.fetch("/api/internal-validate-pro-mcp-token", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ tokenId: "anything" }),
    });
    expect(res.status).toBe(401);
  });

  test("happy path: active token β†’ {userId}", async () => {
    vi.useFakeTimers();
    const t = convexTest(schema, modules);
    await seedProEntitlement(t, "user-pro");

    const issued = await t.mutation(internal.mcpProTokens.issueProMcpToken, {
      userId: "user-pro",
    });

    const res = await t.fetch("/api/internal-validate-pro-mcp-token", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "x-convex-shared-secret": SHARED_SECRET,
      },
      body: JSON.stringify({ tokenId: issued.tokenId }),
    });
    expect(res.status).toBe(200);
    const body = (await res.json()) as { userId?: string } | null;
    expect(body).toEqual({ userId: "user-pro" });

    // The validate HTTP route schedules a fire-and-forget touch via
    // ctx.scheduler.runAfter(0, ...). Drain it deterministically with
    // fake timers so the lastUsedAt write doesn't escape the transaction
    // window and surface as an unhandled rejection during teardown.
    await t.finishAllScheduledFunctions(vi.runAllTimers);
    vi.useRealTimers();
  });

  test("revoked token β†’ null", async () => {
    vi.useFakeTimers();
    const t = convexTest(schema, modules);
    await seedProEntitlement(t, "user-pro");

    const issued = await t.mutation(internal.mcpProTokens.issueProMcpToken, {
      userId: "user-pro",
    });
    await t.withIdentity(PRO_USER).mutation(api.mcpProTokens.revokeProMcpToken, {
      tokenId: issued.tokenId,
    });

    const res = await t.fetch("/api/internal-validate-pro-mcp-token", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "x-convex-shared-secret": SHARED_SECRET,
      },
      body: JSON.stringify({ tokenId: issued.tokenId }),
    });
    expect(res.status).toBe(200);
    const body = await res.json();
    expect(body).toBeNull();

    // Defensive: revoked path returns null and skips scheduling, but
    // drain regardless to keep this test resilient to future edits.
    await t.finishAllScheduledFunctions(vi.runAllTimers);
    vi.useRealTimers();
  });
});

describe("HTTP route /api/internal-revoke-pro-mcp-token", () => {
  beforeEach(() => {
    process.env.CONVEX_SERVER_SHARED_SECRET = SHARED_SECRET;
  });
  afterEach(() => {
    delete process.env.CONVEX_SERVER_SHARED_SECRET;
  });

  test("rejects missing shared-secret with 401", async () => {
    const t = convexTest(schema, modules);
    const res = await t.fetch("/api/internal-revoke-pro-mcp-token", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ userId: "user-pro", tokenId: "x" }),
    });
    expect(res.status).toBe(401);
  });

  test("owner-matched revoke β†’ 200", async () => {
    const t = convexTest(schema, modules);
    await seedProEntitlement(t, "user-pro");
    const issued = await t.mutation(internal.mcpProTokens.issueProMcpToken, {
      userId: "user-pro",
    });

    const res = await t.fetch("/api/internal-revoke-pro-mcp-token", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "x-convex-shared-secret": SHARED_SECRET,
      },
      body: JSON.stringify({ userId: "user-pro", tokenId: issued.tokenId }),
    });
    expect(res.status).toBe(200);
  });

  test("non-owner userId mismatch β†’ 404 NOT_FOUND", async () => {
    const t = convexTest(schema, modules);
    await seedProEntitlement(t, "user-pro");
    const issued = await t.mutation(internal.mcpProTokens.issueProMcpToken, {
      userId: "user-pro",
    });

    const res = await t.fetch("/api/internal-revoke-pro-mcp-token", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "x-convex-shared-secret": SHARED_SECRET,
      },
      body: JSON.stringify({ userId: "user-other", tokenId: issued.tokenId }),
    });
    expect(res.status).toBe(404);
  });
});

// ---------------------------------------------------------------------------
// Integration: userApiKeys table is untouched
// ---------------------------------------------------------------------------

describe("integration: userApiKeys table untouched", () => {
  test("issuing a Pro MCP token does not create a userApiKeys row", async () => {
    const t = convexTest(schema, modules);
    await seedProEntitlement(t, "user-pro");

    await t.mutation(internal.mcpProTokens.issueProMcpToken, { userId: "user-pro" });

    // Inspect the underlying table directly
    const apiKeys = await t.run(async (ctx) =>
      ctx.db
        .query("userApiKeys")
        .withIndex("by_userId", (q) => q.eq("userId", "user-pro"))
        .collect(),
    );
    expect(apiKeys).toEqual([]);
  });
});