@bevel-software/platform-core-backend 0.31.0 → 0.32.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.
Files changed (76) hide show
  1. package/dist/core/create-core-services.d.ts +7 -0
  2. package/dist/core/create-core-services.d.ts.map +1 -1
  3. package/dist/core/create-core-services.js +12 -1
  4. package/dist/core/create-core-services.js.map +1 -1
  5. package/dist/index.d.ts +1 -0
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +1 -0
  8. package/dist/index.js.map +1 -1
  9. package/dist/modules/access-model/index.d.ts +14 -0
  10. package/dist/modules/access-model/index.d.ts.map +1 -0
  11. package/dist/modules/access-model/index.js +13 -0
  12. package/dist/modules/access-model/index.js.map +1 -0
  13. package/dist/modules/auth/account-hooks.d.ts +4 -6
  14. package/dist/modules/auth/account-hooks.d.ts.map +1 -1
  15. package/dist/modules/auth/account-hooks.js +7 -17
  16. package/dist/modules/auth/account-hooks.js.map +1 -1
  17. package/dist/modules/auth/auth.service.d.ts +9 -8
  18. package/dist/modules/auth/auth.service.d.ts.map +1 -1
  19. package/dist/modules/auth/auth.service.js +19 -18
  20. package/dist/modules/auth/auth.service.js.map +1 -1
  21. package/dist/modules/database/core-schema.d.ts +21 -1
  22. package/dist/modules/database/core-schema.d.ts.map +1 -1
  23. package/dist/modules/database/core-schema.js +16 -1
  24. package/dist/modules/database/core-schema.js.map +1 -1
  25. package/dist/modules/mcp/oauth/bevel-oauth-provider.d.ts +28 -0
  26. package/dist/modules/mcp/oauth/bevel-oauth-provider.d.ts.map +1 -1
  27. package/dist/modules/mcp/oauth/bevel-oauth-provider.js +166 -39
  28. package/dist/modules/mcp/oauth/bevel-oauth-provider.js.map +1 -1
  29. package/dist/modules/workflow/agent-tools/change-request-summary.d.ts +10 -1
  30. package/dist/modules/workflow/agent-tools/change-request-summary.d.ts.map +1 -1
  31. package/dist/modules/workflow/agent-tools/change-request-summary.js +2 -0
  32. package/dist/modules/workflow/agent-tools/change-request-summary.js.map +1 -1
  33. package/dist/modules/workflow/agent-tools/workflow.tools.d.ts.map +1 -1
  34. package/dist/modules/workflow/agent-tools/workflow.tools.js +5 -0
  35. package/dist/modules/workflow/agent-tools/workflow.tools.js.map +1 -1
  36. package/dist/modules/workflow/change-request-hooks.d.ts +78 -0
  37. package/dist/modules/workflow/change-request-hooks.d.ts.map +1 -0
  38. package/dist/modules/workflow/change-request-hooks.js +15 -0
  39. package/dist/modules/workflow/change-request-hooks.js.map +1 -0
  40. package/dist/modules/workflow/git/pull-request.service.d.ts +10 -0
  41. package/dist/modules/workflow/git/pull-request.service.d.ts.map +1 -1
  42. package/dist/modules/workflow/git/pull-request.service.js +9 -0
  43. package/dist/modules/workflow/git/pull-request.service.js.map +1 -1
  44. package/dist/modules/workflow/workflow.service.d.ts +75 -15
  45. package/dist/modules/workflow/workflow.service.d.ts.map +1 -1
  46. package/dist/modules/workflow/workflow.service.js +163 -32
  47. package/dist/modules/workflow/workflow.service.js.map +1 -1
  48. package/dist/shared/listener-seam.d.ts +34 -0
  49. package/dist/shared/listener-seam.d.ts.map +1 -0
  50. package/dist/shared/listener-seam.js +42 -0
  51. package/dist/shared/listener-seam.js.map +1 -0
  52. package/migrations/0019_oauth_token_rotated_at.sql +7 -0
  53. package/migrations/meta/0019_snapshot.json +2435 -0
  54. package/migrations/meta/_journal.json +7 -0
  55. package/package.json +3 -3
  56. package/src/core/create-core-services.ts +17 -0
  57. package/src/index.ts +7 -0
  58. package/src/modules/access-model/index.ts +13 -0
  59. package/src/modules/auth/__tests__/account-deactivation.test.ts +38 -2
  60. package/src/modules/auth/account-hooks.ts +13 -21
  61. package/src/modules/auth/auth.service.ts +19 -18
  62. package/src/modules/database/core-schema.ts +16 -1
  63. package/src/modules/mcp/__tests__/bevel-oauth-provider.pg.test.ts +279 -0
  64. package/src/modules/mcp/__tests__/bevel-oauth-provider.test.ts +190 -15
  65. package/src/modules/mcp/oauth/bevel-oauth-provider.ts +214 -48
  66. package/src/modules/workflow/__tests__/change-request-hooks.test.ts +62 -0
  67. package/src/modules/workflow/__tests__/workflow.routes.open-change-request.test.ts +79 -0
  68. package/src/modules/workflow/__tests__/workflow.service.delete-branch.test.ts +9 -1
  69. package/src/modules/workflow/__tests__/workflow.service.facade.test.ts +258 -1
  70. package/src/modules/workflow/agent-tools/__tests__/workflow.tools.test.ts +10 -0
  71. package/src/modules/workflow/agent-tools/change-request-summary.ts +10 -1
  72. package/src/modules/workflow/agent-tools/workflow.tools.ts +6 -0
  73. package/src/modules/workflow/change-request-hooks.ts +96 -0
  74. package/src/modules/workflow/git/pull-request.service.ts +10 -0
  75. package/src/modules/workflow/workflow.service.ts +188 -40
  76. package/src/shared/listener-seam.ts +52 -0
@@ -60,6 +60,10 @@ function makeFakeDb(queue: any[]) {
60
60
  // The mint-time prune of expired token rows; nothing here queues for it.
61
61
  delete: vi.fn(() => nextChain()),
62
62
  } as unknown as Database;
63
+ // A transaction is the same fake, so the queue is consumed in statement
64
+ // order whether or not a statement ran inside one; what ran inside one is
65
+ // pinned by the call count.
66
+ (db as unknown as { transaction: unknown }).transaction = vi.fn(async (fn: (tx: Database) => Promise<unknown>) => fn(db));
63
67
 
64
68
  return { db, captured };
65
69
  }
@@ -288,28 +292,39 @@ describe('BevelOAuthProvider', () => {
288
292
  ).rejects.toBeInstanceOf(InvalidGrantError);
289
293
  });
290
294
 
291
- it('exchangeRefreshToken rotates (revokes old row, mints new pair) and only narrows scope', async () => {
295
+ it('exchangeRefreshToken rotates (retires the old row, mints a new pair) and only narrows scope', async () => {
292
296
  const oldRow = {
293
297
  clientId: 'client-1', userId: 'user-1', connectionId: 'conn-1', scope: 'mcp extra', resource: null,
294
298
  refreshExpiresAt: new Date(Date.now() + 60_000),
295
299
  };
296
300
  const { provider, captured, db } = makeProvider([
297
- [oldRow] /* revoke.returning */,
301
+ [oldRow] /* the row behind the hash, for this client */,
298
302
  [{ id: 'conn-1' }] /* the token's connection, still live */,
299
- [] /* the (throttled) use stamp's first-use claim: stamped before */,
300
- undefined, undefined, /* prunes */
303
+ undefined, undefined, /* prunes — on the pool, before the transaction */
304
+ [oldRow] /* retire.returning — inside the transaction with the mint */,
301
305
  undefined /* token insert */,
306
+ [] /* the (throttled) use stamp's first-use claim, after the commit: stamped before */,
302
307
  undefined /* the ordinary use stamp */,
303
308
  ]);
304
309
  const tokens = await provider.exchangeRefreshToken(CLIENT, 'bevel-mcp_r_old', ['mcp']);
310
+ // The consume and the mint landed in one transaction.
311
+ expect((db as unknown as { transaction: ReturnType<typeof vi.fn> }).transaction).toHaveBeenCalledTimes(1);
305
312
  expect(tokens.scope).toBe('mcp');
313
+ // Read by hash AND client first, judged, and only then consumed.
314
+ expect(render(captured.where[0]).sql).toMatch(/"oauth_tokens"."refresh_token_hash" = .* and "oauth_tokens"."client_id" = /);
315
+ // The old row is RETIRED, not revoked: its access token keeps working for
316
+ // its own hour, so a runner still holding it is not cut off by a refresh
317
+ // another runner made. Only a fresh row is retired — one already rotated
318
+ // or revoked is the replay path's business.
319
+ expect(Object.keys(captured.set[0])).toEqual(['rotatedAt']);
320
+ expect(render(captured.where[4]).sql).toMatch(/"oauth_tokens"."revoked_at" is null and "oauth_tokens"."rotated_at" is null/);
306
321
  // A refresh STAYS on its token's connection: one connection spans every
307
322
  // token the agent holds, nothing is looked up by (user, agent) and no
308
323
  // second row is inserted for it.
309
324
  expect(captured.values).toHaveLength(1);
310
325
  expect(captured.values[0]).toMatchObject({ connectionId: 'conn-1' });
311
326
  // The liveness check is a read of THAT connection, live rows only…
312
- expect((db as any).select).toHaveBeenCalledTimes(1);
327
+ expect((db as any).select).toHaveBeenCalledTimes(2);
313
328
  expect(render(captured.where[1])).toMatchObject({ params: ['conn-1'] });
314
329
  expect(render(captured.where[1]).sql).toMatch(/"agent_connections"."revoked_at" is null/);
315
330
  // …and the use is stamped separately, off the refresh's own path: the
@@ -317,16 +332,170 @@ describe('BevelOAuthProvider', () => {
317
332
  await new Promise((r) => setTimeout(r, 0));
318
333
  expect(captured.updateTargets).toEqual([oauthTokens, agentConnections, agentConnections]);
319
334
  expect(Object.keys(captured.set[1])).toEqual(['lastUsedAt']);
335
+ // The refresh's prune — on the pool, before the transaction opened —
336
+ // keeps a retired row for its access hour plus the reuse grace (it can
337
+ // still verify and be replayed until then) and removes it after: the
338
+ // third term of the delete, cut off 61 minutes ago.
339
+ const prune = captured.where.map(render).find((w) => /"oauth_tokens"."rotated_at" < /.test(w.sql));
340
+ expect(prune, 'the refresh prunes retired rows').toBeDefined();
341
+ // Third statement: after the read and the liveness check, before the retire.
342
+ expect(render(captured.where[2]).sql).toMatch(/"oauth_tokens"."rotated_at" < /);
343
+ // The dialect renders a Date parameter as its ISO string.
344
+ const rotatedCutoff = new Date(prune!.params.at(-1) as string | Date);
345
+ expect(Date.now() - rotatedCutoff.getTime()).toBeGreaterThanOrEqual(61 * 60_000);
346
+ expect(Date.now() - rotatedCutoff.getTime()).toBeLessThan(61 * 60_000 + 5_000);
347
+
348
+ // Widening is refused — invalid_scope to the client, in the log like
349
+ // every other refusal, and BEFORE anything is consumed: the same token
350
+ // still refreshes with the scope it was granted.
351
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
352
+ try {
353
+ const widening = makeProvider([[oldRow]]);
354
+ await expect(
355
+ widening.provider.exchangeRefreshToken(CLIENT, 'bevel-mcp_r_old', ['mcp', 'admin']),
356
+ ).rejects.toBeInstanceOf(InvalidScopeError);
357
+ expect(warn).toHaveBeenCalledWith(expect.stringMatching(/refresh refused: requested scope exceeds the originally granted scope/), expect.anything());
358
+ expect(widening.captured.updateTargets).toEqual([]);
359
+ } finally {
360
+ warn.mockRestore();
361
+ }
362
+ });
320
363
 
321
- // Widening is refused.
322
- await expect(
323
- makeProvider([[oldRow]]).provider.exchangeRefreshToken(CLIENT, 'bevel-mcp_r_old', ['mcp', 'admin']),
324
- ).rejects.toBeInstanceOf(InvalidScopeError);
364
+ it('exchangeRefreshToken honours the loser of a rotation race once: read fresh, retired under it, replayed', async () => {
365
+ // Two refreshes of one fresh token at the same instant. Both read it
366
+ // fresh; one retire lands, the other matches nothing — and is then the
367
+ // loser of a double refresh, replayable within the grace like any other.
368
+ const oldRow = {
369
+ clientId: 'client-1', userId: 'user-1', connectionId: 'conn-1', scope: 'mcp', resource: null,
370
+ refreshExpiresAt: new Date(Date.now() + 60_000), revokedAt: null, rotatedAt: null,
371
+ };
372
+ const info = vi.spyOn(console, 'log').mockImplementation(() => undefined);
373
+ const { provider, captured } = makeProvider([
374
+ [oldRow] /* read fresh */,
375
+ [{ id: 'conn-1' }] /* its connection, live */,
376
+ undefined, undefined, /* prunes — before the transaction */
377
+ [] /* the retire matches nothing: rotated under this request */,
378
+ [{ ...oldRow, rotatedAt: new Date() }] /* the replay consumes it */,
379
+ undefined /* token insert */,
380
+ [] /* first-use claim, after the commit */,
381
+ undefined /* the ordinary use stamp */,
382
+ ]);
383
+ try {
384
+ const tokens = await provider.exchangeRefreshToken(CLIENT, 'bevel-mcp_r_old');
385
+ expect(tokens.refresh_token).toMatch(/^bevel-mcp_r_/);
386
+ expect(captured.values).toHaveLength(1);
387
+ expect(Object.keys(captured.set[0])).toEqual(['rotatedAt']);
388
+ expect(Object.keys(captured.set[1])).toEqual(['revokedAt']);
389
+ expect(info).toHaveBeenCalledWith(expect.stringMatching(/refresh replayed 0 s after its rotation/), expect.anything());
390
+ } finally {
391
+ info.mockRestore();
392
+ }
393
+ });
325
394
 
326
- // Unknown/already-rotated refresh token.
327
- await expect(
328
- makeProvider([[]]).provider.exchangeRefreshToken(CLIENT, 'bevel-mcp_r_gone'),
329
- ).rejects.toBeInstanceOf(InvalidGrantError);
395
+ it('a retired pair\'s access token verifies until its own expiry, and dies with a revoke like any other', async () => {
396
+ // Rotation sets `rotated_at` and leaves `revoked_at` null, and the
397
+ // verification predicate asks about `revoked_at` and `expires_at` only:
398
+ // so a runner still holding the old pair is served for the rest of its
399
+ // hour. The same predicate is what a revoke, a sign-out or a connection
400
+ // revoke then falsify, since all of those set `revoked_at` (or the
401
+ // connection's), none of which this change touched.
402
+ const row = {
403
+ id: 't-1', clientId: 'client-1', connectionId: 'conn-1', scope: 'mcp', resource: null,
404
+ expiresAt: new Date(Date.now() + 30 * 60_000), userId: 'user-1', userEmail: 'u@x.io',
405
+ };
406
+ const { provider, captured } = makeProvider([[row], undefined /* touch */, [] /* claim lost */, undefined /* stamp */]);
407
+ const info = await provider.verifyAccessToken('bevel-mcp_live');
408
+ expect(info.clientId).toBe('client-1');
409
+ const verify = render(captured.where[0]).sql;
410
+ expect(verify).toMatch(/"oauth_tokens"."revoked_at" is null/);
411
+ expect(verify).toMatch(/"oauth_tokens"."expires_at" > /);
412
+ expect(verify).toMatch(/"agent_connections"."revoked_at" is null/);
413
+ expect(verify).not.toMatch(/rotated_at/);
414
+ });
415
+
416
+ /** A row the rotation did not match, as the replay path then reads it. */
417
+ const rotatedRow = (ago: number) => ({
418
+ clientId: 'client-1', userId: 'user-1', connectionId: 'conn-1', scope: 'mcp', resource: null,
419
+ refreshExpiresAt: new Date(Date.now() + 60_000),
420
+ revokedAt: null,
421
+ rotatedAt: new Date(Date.now() - ago),
422
+ });
423
+
424
+ it('exchangeRefreshToken honours a refresh token rotated within the reuse grace once more — the loser of a double refresh gets a pair too', async () => {
425
+ // Claude's hosted apps refresh proactively and reactively, and a
426
+ // scheduled task refreshes beside the chat that shares its connector:
427
+ // the same token arrives twice. The second arrival, 10 s after the first
428
+ // rotated it, is answered with a fresh pair on the same connection rather
429
+ // than the invalid_grant a client reads as "re-authorize".
430
+ const info = vi.spyOn(console, 'log').mockImplementation(() => undefined);
431
+ const { provider, captured } = makeProvider([
432
+ [rotatedRow(10_000)] /* the row behind the hash: retired 10 s ago */,
433
+ [{ id: 'conn-1' }] /* its connection, live */,
434
+ undefined, undefined, /* prunes — before the transaction */
435
+ [rotatedRow(10_000)] /* the replay consumes it — inside the transaction with the mint */,
436
+ undefined /* token insert */,
437
+ [] /* first-use claim, after the commit */,
438
+ undefined /* the ordinary use stamp */,
439
+ ]);
440
+ try {
441
+ const tokens = await provider.exchangeRefreshToken(CLIENT, 'bevel-mcp_r_old');
442
+ expect(tokens.refresh_token).toMatch(/^bevel-mcp_r_/);
443
+ expect(captured.values).toHaveLength(1);
444
+ expect(captured.values[0]).toMatchObject({ connectionId: 'conn-1', userId: 'user-1' });
445
+ // Honoured ONCE: the replay revokes the retired row in the statement
446
+ // that admits it — by hash AND client, unrevoked, rotated within the
447
+ // grace — so a third presentation finds nothing, and another client's
448
+ // token is never honoured. Never retired again: no `rotatedAt` write.
449
+ expect(Object.keys(captured.set[0])).toEqual(['revokedAt']);
450
+ expect(captured.set.flatMap((s) => Object.keys(s))).not.toContain('rotatedAt');
451
+ expect(render(captured.where[4]).sql).toMatch(
452
+ /"oauth_tokens"."refresh_token_hash" = .* and "oauth_tokens"."client_id" = .* and "oauth_tokens"."revoked_at" is null and "oauth_tokens"."rotated_at" > /,
453
+ );
454
+ // Said once the pair is minted, not before the checks that could still refuse.
455
+ expect(info).toHaveBeenCalledWith(expect.stringMatching(/refresh replayed 10 s after its rotation, within the reuse grace; a fresh pair is minted/), expect.anything());
456
+ } finally {
457
+ info.mockRestore();
458
+ }
459
+ });
460
+
461
+ it.each([
462
+ ['unknown to this client', [[]], /refresh refused: unknown refresh token for this client/],
463
+ ['revoked', [[{ ...rotatedRow(10_000), rotatedAt: null, revokedAt: new Date() }]], /refresh refused: refresh token revoked/],
464
+ ['rotated past the grace', [[rotatedRow(120_000)]], /refresh refused: refresh token rotated 120 s ago, past the 60 s reuse grace/],
465
+ ['already replayed once', [[{ ...rotatedRow(10_000), revokedAt: new Date() }]], /refresh refused: refresh token rotated 10 s ago and already replayed once, or revoked since/],
466
+ [
467
+ 'rotated and replayed by concurrent requests between the read and the consume',
468
+ [[{ ...rotatedRow(0), rotatedAt: null }], [{ id: 'conn-1' }], undefined, undefined, /* prunes */ [] /* retire misses */, [] /* replay misses too */],
469
+ /refresh refused: refresh token rotated or revoked by a concurrent request/,
470
+ ],
471
+ ])('exchangeRefreshToken refuses a refresh token that is %s, mints nothing, and says why in the log', async (_what, queue, said) => {
472
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
473
+ try {
474
+ const { provider, captured } = makeProvider([...queue]);
475
+ await expect(provider.exchangeRefreshToken(CLIENT, 'bevel-mcp_r_old')).rejects.toBeInstanceOf(InvalidGrantError);
476
+ expect(captured.values).toHaveLength(0);
477
+ // The reason is in the log, never the token.
478
+ expect(warn).toHaveBeenCalledWith(expect.stringMatching(said), expect.anything());
479
+ expect(JSON.stringify(warn.mock.calls)).not.toContain('bevel-mcp_r_old');
480
+ } finally {
481
+ warn.mockRestore();
482
+ }
483
+ });
484
+
485
+ it('exchangeRefreshToken logs the two refusals that come after a token was accepted: expired, and its agent revoked', async () => {
486
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
487
+ try {
488
+ const expired = { ...rotatedRow(0), rotatedAt: null, refreshExpiresAt: new Date(Date.now() - 1_000) };
489
+ await expect(makeProvider([[expired]]).provider.exchangeRefreshToken(CLIENT, 'bevel-mcp_r_old')).rejects.toBeInstanceOf(InvalidGrantError);
490
+ expect(warn).toHaveBeenLastCalledWith(expect.stringMatching(/refresh refused: refresh token expired/), expect.anything());
491
+
492
+ const live = { ...rotatedRow(0), rotatedAt: null };
493
+ await expect(makeProvider([[live], [] /* its connection: revoked or gone */]).provider.exchangeRefreshToken(CLIENT, 'bevel-mcp_r_old')).rejects.toBeInstanceOf(InvalidGrantError);
494
+ expect(warn).toHaveBeenLastCalledWith(expect.stringMatching(/refresh refused: access for this agent was revoked/), expect.anything());
495
+ expect(JSON.stringify(warn.mock.calls)).not.toContain('bevel-mcp_r_old');
496
+ } finally {
497
+ warn.mockRestore();
498
+ }
330
499
  });
331
500
 
332
501
  it('exchangeRefreshToken refuses a token whose agent connection was revoked, minting nothing', async () => {
@@ -350,11 +519,13 @@ describe('BevelOAuthProvider', () => {
350
519
  refreshExpiresAt: new Date(Date.now() + 60_000),
351
520
  };
352
521
  const { provider, captured } = makeProvider([
353
- [oldRow],
354
- undefined, undefined, /* prunes */
522
+ [oldRow] /* the row behind the hash: no connection to check */,
523
+ // Placed under a connection BEFORE the transaction, as a first mint would place it.
355
524
  [{ clientName: 'Claude' }],
356
525
  [] /* no live connection */,
357
526
  [{ id: 'conn-new' }] /* connection insert.returning */,
527
+ undefined, undefined, /* prunes — before the transaction */
528
+ [oldRow] /* retire.returning */,
358
529
  undefined /* token insert */,
359
530
  ]);
360
531
  await provider.exchangeRefreshToken(CLIENT, 'bevel-mcp_r_old');
@@ -458,6 +629,10 @@ describe('BevelOAuthProvider', () => {
458
629
  ]);
459
630
  await provider.revokeToken(CLIENT, { token: 'bevel-mcp_r_old', token_type_hint: 'refresh_token' });
460
631
  expect(captured.updateTargets).toEqual([oauthTokens, agentConnections]);
632
+ // "Live" excludes a retired row: its successor is the live token, and a
633
+ // sign-out must not keep the connection open on a refresh token nobody
634
+ // can use any more.
635
+ expect(render(captured.where[1]).sql).toMatch(/"oauth_tokens"."revoked_at" is null and "oauth_tokens"."rotated_at" is null/);
461
636
  expect(captured.set[1]).toMatchObject({ revokedBy: 'owner' });
462
637
  expect(captured.set[1].revokedAt).toBeInstanceOf(Date);
463
638
  expect(render(captured.where[2])).toMatchObject({ params: ['conn-1'] });
@@ -32,9 +32,27 @@ import { signAuthRequest, type McpAuthRequestState } from './oauth-state.js';
32
32
  // (`<tenant>-int_`).
33
33
  const TOKEN_BYTES = 32;
34
34
 
35
+ /** A transaction's handle, for the statements a refresh must land together. */
36
+ type Tx = Parameters<Parameters<Database['transaction']>[0]>[0];
37
+
35
38
  const ACCESS_TTL_MS = 60 * 60_000; // 1 hour
36
39
  const REFRESH_TTL_MS = 30 * 24 * 60 * 60_000; // 30 days, rotated on use
37
40
  const CODE_TTL_MS = 60_000; // exchanged within seconds of Finish
41
+ /**
42
+ * How long a refresh token that was just rotated is honoured once more.
43
+ *
44
+ * Rotation makes a refresh token single-use, and a client that refreshes
45
+ * from two places at once — Claude's hosted apps refresh proactively before
46
+ * expiry AND reactively on a 401, and a scheduled task runs beside the chat
47
+ * that shares its connector — presents the same token twice. The second
48
+ * presentation used to be answered `invalid_grant`, which a client reads as
49
+ * "the credential is dead" and turns into a re-authorization prompt every
50
+ * day or two. Within this window the loser is answered as the winner was,
51
+ * with a fresh pair; past it, reuse is refused, which is what makes a stolen
52
+ * token's later replay fail. Sixty seconds is the window Okta allows at most
53
+ * and Auth0 recommends for exactly this case.
54
+ */
55
+ const REFRESH_REUSE_GRACE_MS = 60_000;
38
56
  /**
39
57
  * How often, at most, one process stamps an agent connection's `last_used_at`.
40
58
  * The Audit log shows the instant relatively ("4 minutes ago"), so a minute's
@@ -261,34 +279,54 @@ export class BevelOAuthProvider implements OAuthServerProvider {
261
279
  _resource?: URL,
262
280
  ): Promise<OAuthTokens> {
263
281
  const now = new Date();
264
- // Rotation: atomically revoke the presented refresh token; the winner of
265
- // a concurrent double-refresh gets the new pair, the loser a clean 400.
266
- // `clientId` is IN the predicate so a caller presenting a valid refresh
267
- // token under the WRONG client can't revoke (kill) another client's
268
- // session — the update matches nothing and their token stays live.
269
- const [row] = await this.deps.db
270
- .update(oauthTokens)
271
- .set({ revokedAt: now })
272
- .where(
273
- and(
274
- eq(oauthTokens.refreshTokenHash, hashToken(refreshToken)),
275
- eq(oauthTokens.clientId, client.client_id),
276
- isNull(oauthTokens.revokedAt),
277
- ),
278
- )
279
- .returning();
280
- if (!row) {
281
- throw new InvalidGrantError('Invalid or revoked refresh token');
282
+ const hash = hashToken(refreshToken);
283
+ const clientId = client.client_id;
284
+ // The row is READ first and judged whole, and consumed only once every
285
+ // check has passed: a refusal must leave a token the client could still
286
+ // use with a different request (a narrower scope) usable, and nothing
287
+ // may be minted or retired on a token that is expired, revoked, or
288
+ // bound to a revoked agent. Looked up by hash AND client, so a caller
289
+ // presenting a valid refresh token under the WRONG client learns
290
+ // nothing and changes nothing.
291
+ const [seen] = await this.deps.db
292
+ .select()
293
+ .from(oauthTokens)
294
+ .where(and(eq(oauthTokens.refreshTokenHash, hash), eq(oauthTokens.clientId, clientId)))
295
+ .limit(1);
296
+ if (!seen) return this.refuseRefresh('unknown refresh token for this client', 'Invalid or revoked refresh token', { clientId });
297
+ const rotatedAgoMs = seen.rotatedAt ? now.getTime() - seen.rotatedAt.getTime() : null;
298
+ const rotatedAgo = rotatedAgoMs === null ? null : `${Math.round(rotatedAgoMs / 1000)} s ago`;
299
+ if (seen.revokedAt) {
300
+ return this.refuseRefresh(
301
+ rotatedAgo ? `refresh token rotated ${rotatedAgo} and already replayed once, or revoked since` : 'refresh token revoked',
302
+ 'Invalid or revoked refresh token',
303
+ seen,
304
+ );
305
+ }
306
+ if (rotatedAgoMs !== null && rotatedAgoMs > REFRESH_REUSE_GRACE_MS) {
307
+ return this.refuseRefresh(
308
+ `refresh token rotated ${rotatedAgo}, past the ${REFRESH_REUSE_GRACE_MS / 1000} s reuse grace`,
309
+ 'Invalid or revoked refresh token',
310
+ seen,
311
+ );
282
312
  }
283
- if (row.refreshExpiresAt && row.refreshExpiresAt <= now) {
284
- throw new InvalidGrantError('Refresh token expired');
313
+ if (seen.refreshExpiresAt && seen.refreshExpiresAt <= now) {
314
+ return this.refuseRefresh('refresh token expired', 'Refresh token expired', seen);
285
315
  }
286
316
  // Scope may only narrow on refresh (RFC 6749 §6).
287
- let scope = row.scope;
317
+ let scope = seen.scope;
288
318
  if (scopes?.length) {
289
- const granted = new Set((row.scope ?? '').split(' ').filter(Boolean));
319
+ const granted = new Set((seen.scope ?? '').split(' ').filter(Boolean));
290
320
  if (!scopes.every((s) => granted.has(s))) {
291
- throw new InvalidScopeError('Requested scope exceeds the originally granted scope');
321
+ // `invalid_scope` to the client (RFC 6749 §5.2), since the token
322
+ // itself is fine — and untouched, so the same token refreshes with
323
+ // the scope it was granted.
324
+ return this.refuseRefresh(
325
+ 'requested scope exceeds the originally granted scope',
326
+ 'Requested scope exceeds the originally granted scope',
327
+ seen,
328
+ (message) => new InvalidScopeError(message),
329
+ );
292
330
  }
293
331
  scope = scopes.join(' ');
294
332
  }
@@ -299,13 +337,115 @@ export class BevelOAuthProvider implements OAuthServerProvider {
299
337
  // mint an unrevoked pair — the revoke undone by a millisecond. A token
300
338
  // from before connections existed has none to stay on and is placed
301
339
  // under one as a first mint would be.
302
- if (row.connectionId) {
303
- if (!(await this.isConnectionLive(row.connectionId))) {
304
- throw new InvalidGrantError('Access for this agent was revoked');
340
+ if (seen.connectionId && !(await this.isConnectionLive(seen.connectionId))) {
341
+ return this.refuseRefresh('access for this agent was revoked', 'Access for this agent was revoked', seen);
342
+ }
343
+
344
+ // Consume, with the state the row was judged in as the predicate, so two
345
+ // refreshes racing on one row have exactly one winner. A fresh token is
346
+ // RETIRED (`rotatedAt`), not revoked: its pair's access token stays good
347
+ // until its own expiry, an hour at most, so a runner still holding it is
348
+ // not cut off mid-task by a refresh another runner made, while a revoke
349
+ // or a sign-out still ends it at once. A token already retired within
350
+ // the reuse grace — the loser of a double refresh, which is what a client
351
+ // refreshing from two places at once produces — is honoured ONCE more,
352
+ // and the replay revokes the row in the same statement that admits it,
353
+ // so a third presentation, or two replays racing, find nothing. That does
354
+ // end the retired pair's access token: the runner that replayed holds the
355
+ // fresh pair from here, and the rotation's winner holds its own.
356
+ //
357
+ // The consume and the mint are ONE transaction: a token is retired or
358
+ // replayed only in the same commit that hands its holder the new pair, so
359
+ // a mint that fails leaves the token exactly as it was — never spent with
360
+ // nothing to show for it, which for a replayed token would be the lockout
361
+ // this whole path exists to prevent. A token from before connections
362
+ // existed is placed under one first, outside the transaction, as a first
363
+ // mint would place it: finding or making a connection is idempotent.
364
+ const connectionId = seen.connectionId ?? (await this.ensureConnection(seen.userId, seen.clientId));
365
+ // The opportunistic prune too runs BEFORE the transaction opens, on the
366
+ // pool: inside it, this request would hold a transaction's client while
367
+ // waiting for a second one, and a burst of refreshes the size of the pool
368
+ // would have every one of them wait out the connect timeout.
369
+ await this.pruneTokenTables(now.getTime());
370
+ const { consumed, tokens, replayed } = await this.deps.db.transaction(async (tx) => {
371
+ let row = rotatedAgoMs === null ? await this.retireFresh(tx, hash, clientId, now) : undefined;
372
+ let replayed = rotatedAgoMs !== null;
373
+ if (!row) {
374
+ // Either a retired token within the grace, or a fresh one that lost
375
+ // its rotation to a concurrent refresh between the read above and the
376
+ // retire — which makes it the loser of a double refresh, and so
377
+ // replayable now.
378
+ row = await this.replayRetired(tx, hash, clientId, now);
379
+ replayed = true;
380
+ }
381
+ if (!row) {
382
+ return this.refuseRefresh('refresh token rotated or revoked by a concurrent request', 'Invalid or revoked refresh token', seen);
305
383
  }
306
- this.noteConnectionUse(row.connectionId);
384
+ const tokens = await this.mintTokens(row.userId, row.clientId, scope, row.resource, connectionId, tx);
385
+ return { consumed: row, tokens, replayed };
386
+ });
387
+ if (replayed) {
388
+ log.info(
389
+ `refresh replayed ${Math.round((now.getTime() - consumed.rotatedAt!.getTime()) / 1000)} s after its rotation, within the reuse grace; a fresh pair is minted`,
390
+ { clientId, connectionId, userId: consumed.userId },
391
+ );
307
392
  }
308
- return this.mintTokens(row.userId, row.clientId, scope, row.resource, row.connectionId ?? undefined);
393
+ this.noteConnectionUse(connectionId);
394
+ return tokens;
395
+ }
396
+
397
+ /** Retire a fresh refresh token: the one statement that wins a rotation. */
398
+ private async retireFresh(tx: Tx, hash: string, clientId: string, now: Date) {
399
+ const [row] = await tx
400
+ .update(oauthTokens)
401
+ .set({ rotatedAt: now })
402
+ .where(
403
+ and(
404
+ eq(oauthTokens.refreshTokenHash, hash),
405
+ eq(oauthTokens.clientId, clientId),
406
+ isNull(oauthTokens.revokedAt),
407
+ isNull(oauthTokens.rotatedAt),
408
+ ),
409
+ )
410
+ .returning();
411
+ return row;
412
+ }
413
+
414
+ /** Consume a retired refresh token's one replay: revoked in the statement that admits it, within the grace only. */
415
+ private async replayRetired(tx: Tx, hash: string, clientId: string, now: Date) {
416
+ const since = new Date(now.getTime() - REFRESH_REUSE_GRACE_MS);
417
+ const [row] = await tx
418
+ .update(oauthTokens)
419
+ .set({ revokedAt: now })
420
+ .where(
421
+ and(
422
+ eq(oauthTokens.refreshTokenHash, hash),
423
+ eq(oauthTokens.clientId, clientId),
424
+ isNull(oauthTokens.revokedAt),
425
+ gt(oauthTokens.rotatedAt, since),
426
+ ),
427
+ )
428
+ .returning();
429
+ return row;
430
+ }
431
+
432
+ /**
433
+ * The one place a refresh is refused: logged with its reason, never the
434
+ * token, then the client's error — `invalid_grant` unless the caller says
435
+ * otherwise (a widened scope is `invalid_scope`).
436
+ */
437
+ private refuseRefresh(
438
+ reason: string,
439
+ clientMessage: string,
440
+ row: { clientId: string; connectionId?: string | null; userId?: string },
441
+ error: (message: string) => Error = (message) => new InvalidGrantError(message),
442
+ ): never {
443
+ log.warn(`refresh refused: ${reason}`, {
444
+ clientId: row.clientId,
445
+ connectionId: row.connectionId ?? null,
446
+ userId: row.userId ?? null,
447
+ });
448
+ throw error(clientMessage);
309
449
  }
310
450
 
311
451
  async verifyAccessToken(token: string): Promise<AuthInfo> {
@@ -413,10 +553,15 @@ export class BevelOAuthProvider implements OAuthServerProvider {
413
553
  // back to re-authorise into the same one.)
414
554
  const connectionId = revoked.find((r) => r.connectionId)?.connectionId;
415
555
  if (!connectionId) return;
556
+ // A rotated row is not a live token: its successor is the live one, and
557
+ // counting it would keep a connection open on a refresh token nobody can
558
+ // use any more.
416
559
  const [{ live }] = await this.deps.db
417
560
  .select({ live: count() })
418
561
  .from(oauthTokens)
419
- .where(and(eq(oauthTokens.connectionId, connectionId), isNull(oauthTokens.revokedAt)));
562
+ .where(
563
+ and(eq(oauthTokens.connectionId, connectionId), isNull(oauthTokens.revokedAt), isNull(oauthTokens.rotatedAt)),
564
+ );
420
565
  if (Number(live) > 0) return;
421
566
  await this.deps.db
422
567
  .update(agentConnections)
@@ -428,6 +573,12 @@ export class BevelOAuthProvider implements OAuthServerProvider {
428
573
  * @param connectionId The agent connection the pair belongs to, when the
429
574
  * caller already holds one (a refresh: the consumed token's). Absent on a
430
575
  * first mint, which finds or makes the live connection for (user, client).
576
+ * @param tx The transaction the insert belongs to, when the mint must land
577
+ * with the statement that consumed the token it replaces (a refresh).
578
+ * The prune is then the caller's, before the transaction opens: a
579
+ * best-effort statement that fails inside a transaction would abort the
580
+ * mint it is meant to spare, and one on the pool from inside it would
581
+ * hold this request's client while waiting for another.
431
582
  */
432
583
  private async mintTokens(
433
584
  userId: string,
@@ -435,30 +586,17 @@ export class BevelOAuthProvider implements OAuthServerProvider {
435
586
  scope: string | null,
436
587
  resource: string | null,
437
588
  connectionId?: string,
589
+ tx?: Tx,
438
590
  ): Promise<OAuthTokens> {
439
591
  const accessToken = this.deps.tokenPrefix + randomBytes(TOKEN_BYTES).toString('base64url');
440
592
  const refreshToken = this.refreshPrefix + randomBytes(TOKEN_BYTES).toString('base64url');
441
593
  const now = Date.now();
442
- // Opportunistic pruning, piggybacked on mint (one per sign-in / refresh —
443
- // no scheduler needed) so the oauth tables stay bounded: a token row whose
444
- // refresh window has closed can never authenticate again (revoked-but-live
445
- // rows are kept until then, so revocation stays observable), and an auth
446
- // code past its 60s TTL can never be exchanged. Best-effort — a cleanup
447
- // hiccup must not fail the token issuance itself.
448
- try {
449
- const cutoff = new Date(now);
450
- await this.deps.db.delete(oauthTokens).where(
451
- or(
452
- lt(oauthTokens.refreshExpiresAt, cutoff),
453
- and(isNull(oauthTokens.refreshExpiresAt), lt(oauthTokens.expiresAt, cutoff)),
454
- ),
455
- );
456
- await this.deps.db.delete(oauthAuthCodes).where(lt(oauthAuthCodes.expiresAt, cutoff));
457
- } catch (err) {
458
- log.warn('token-table prune failed (non-fatal):', { err });
459
- }
594
+ // A mint of its own (a sign-in) prunes here; a refresh pruned before its
595
+ // transaction opened.
596
+ if (!tx) await this.pruneTokenTables(now);
460
597
  const boundTo = connectionId ?? (await this.ensureConnection(userId, clientId));
461
- await this.deps.db.insert(oauthTokens).values({
598
+ const sink: Tx | Database = tx ?? this.deps.db;
599
+ await sink.insert(oauthTokens).values({
462
600
  accessTokenHash: hashToken(accessToken),
463
601
  refreshTokenHash: hashToken(refreshToken),
464
602
  clientId,
@@ -478,6 +616,34 @@ export class BevelOAuthProvider implements OAuthServerProvider {
478
616
  };
479
617
  }
480
618
 
619
+ /**
620
+ * Opportunistic pruning, piggybacked on every mint (one per sign-in /
621
+ * refresh — no scheduler needed) so the oauth tables stay bounded: a token
622
+ * row whose refresh window has closed can never authenticate again
623
+ * (revoked-but-live rows are kept until then, so revocation stays
624
+ * observable), a rotated row can authenticate for its access token's hour
625
+ * and be replayed for the reuse grace and past both is history only, and
626
+ * an auth code past its 60s TTL can never be exchanged. Best-effort, on the
627
+ * pool and never inside a transaction — a cleanup hiccup must not fail the
628
+ * token issuance itself.
629
+ */
630
+ private async pruneTokenTables(now: number): Promise<void> {
631
+ try {
632
+ const cutoff = new Date(now);
633
+ const rotatedCutoff = new Date(now - ACCESS_TTL_MS - REFRESH_REUSE_GRACE_MS);
634
+ await this.deps.db.delete(oauthTokens).where(
635
+ or(
636
+ lt(oauthTokens.refreshExpiresAt, cutoff),
637
+ and(isNull(oauthTokens.refreshExpiresAt), lt(oauthTokens.expiresAt, cutoff)),
638
+ lt(oauthTokens.rotatedAt, rotatedCutoff),
639
+ ),
640
+ );
641
+ await this.deps.db.delete(oauthAuthCodes).where(lt(oauthAuthCodes.expiresAt, cutoff));
642
+ } catch (err) {
643
+ log.warn('token-table prune failed (non-fatal):', { err });
644
+ }
645
+ }
646
+
481
647
  /**
482
648
  * The live `agent_connections` row for (user, client) — found, or made on
483
649
  * the first mint for the pair. A refresh finds the row the sign-in made, so
@@ -0,0 +1,62 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { ChangeRequestHooks, type ChangeRequestOpenedEvent } from '../change-request-hooks.js';
3
+
4
+ const EVENT: ChangeRequestOpenedEvent = {
5
+ number: 12,
6
+ title: 'Tidy the glossary',
7
+ sourceBranch: 'ali/x',
8
+ targetBranch: 'main',
9
+ openedBy: { id: 'u-ali', email: 'ali@acme.test', name: 'Ali' },
10
+ approvers: [{ id: 'u-dana', email: 'dana@acme.test', name: 'Dana' }],
11
+ unresolvedApprovers: 0,
12
+ pushPending: false,
13
+ };
14
+
15
+ describe('ChangeRequestHooks: a change request was opened', () => {
16
+ it('notifies nobody when nothing is registered, and says so', async () => {
17
+ expect(await new ChangeRequestHooks().runChangeRequestOpened(EVENT)).toEqual([]);
18
+ });
19
+
20
+ it('runs every listener in registration order, with the event, and collects the channels that reached the approvers', async () => {
21
+ const hooks = new ChangeRequestHooks();
22
+ const seen: string[] = [];
23
+ hooks.onChangeRequestOpened(async (event) => {
24
+ seen.push(`mail:#${event.number}:${event.approvers.map((a) => a.email).join(',')}`);
25
+ return 'email';
26
+ });
27
+ hooks.onChangeRequestOpened(async () => {
28
+ seen.push('chat');
29
+ return null;
30
+ });
31
+ hooks.onChangeRequestOpened(async () => {
32
+ seen.push('sms');
33
+ return 'sms';
34
+ });
35
+ expect(await hooks.runChangeRequestOpened(EVENT)).toEqual(['email', 'sms']);
36
+ expect(seen).toEqual(['mail:#12:dana@acme.test', 'chat', 'sms']);
37
+ });
38
+
39
+ it('a listener that throws counts as not having notified, and stops nothing', async () => {
40
+ const hooks = new ChangeRequestHooks();
41
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
42
+ try {
43
+ hooks.onChangeRequestOpened(async () => {
44
+ throw new Error('smtp down');
45
+ });
46
+ hooks.onChangeRequestOpened(async () => 'email');
47
+ expect(await hooks.runChangeRequestOpened(EVENT)).toEqual(['email']);
48
+ // Logged, so a failing mailer is diagnosable from the server's log.
49
+ expect(error).toHaveBeenCalledTimes(1);
50
+ expect(String(error.mock.calls[0]![0])).toContain('a change-request-opened listener failed');
51
+ } finally {
52
+ error.mockRestore();
53
+ }
54
+ });
55
+
56
+ it('an empty channel name is no channel: it counts as not having notified', async () => {
57
+ const hooks = new ChangeRequestHooks();
58
+ hooks.onChangeRequestOpened(async () => '');
59
+ hooks.onChangeRequestOpened(async () => 'email');
60
+ expect(await hooks.runChangeRequestOpened(EVENT)).toEqual(['email']);
61
+ });
62
+ });