@terreno/api 57.16.2 → 57.17.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 (184) hide show
  1. package/dist/actions.d.ts +26 -3
  2. package/dist/actions.js +102 -16
  3. package/dist/api.d.ts +7 -0
  4. package/dist/api.js +59 -3
  5. package/dist/auth.d.ts +28 -4
  6. package/dist/auth.js +140 -15
  7. package/dist/authRecovery.d.ts +31 -0
  8. package/dist/authRecovery.js +86 -6
  9. package/dist/betterAuth.d.ts +86 -0
  10. package/dist/betterAuthApp.d.ts +17 -0
  11. package/dist/betterAuthApp.js +12 -1
  12. package/dist/betterAuthOAuthHandoff.d.ts +24 -0
  13. package/dist/betterAuthOAuthHandoff.js +305 -0
  14. package/dist/betterAuthSetup.d.ts +37 -2
  15. package/dist/betterAuthSetup.js +304 -24
  16. package/dist/expressServer.d.ts +16 -0
  17. package/dist/expressServer.js +61 -14
  18. package/dist/githubAuth.d.ts +9 -0
  19. package/dist/githubAuth.js +230 -31
  20. package/dist/index.d.ts +9 -1
  21. package/dist/index.js +27 -3
  22. package/dist/mcp/actionTools.d.ts +4 -0
  23. package/dist/mcp/actionTools.js +158 -0
  24. package/dist/mcp/auth.d.ts +30 -0
  25. package/dist/mcp/auth.js +83 -28
  26. package/dist/mcp/createMCPRequest.d.ts +5 -1
  27. package/dist/mcp/createMCPRequest.js +3 -3
  28. package/dist/mcp/handlers.d.ts +3 -0
  29. package/dist/mcp/handlers.js +43 -27
  30. package/dist/mcp/oauth.d.ts +14 -0
  31. package/dist/mcp/oauth.js +618 -0
  32. package/dist/mcp/oauthMetadata.d.ts +89 -0
  33. package/dist/mcp/oauthMetadata.js +137 -0
  34. package/dist/mcp/registry.d.ts +5 -0
  35. package/dist/mcp/registry.js +9 -1
  36. package/dist/mcp/server.d.ts +6 -0
  37. package/dist/mcp/server.js +44 -7
  38. package/dist/mcp/serviceTokens.js +12 -2
  39. package/dist/mcp/toolExecution.d.ts +12 -0
  40. package/dist/mcp/toolExecution.js +60 -0
  41. package/dist/mcp/toolGenerator.d.ts +4 -1
  42. package/dist/mcp/toolGenerator.js +26 -60
  43. package/dist/mcp/types.d.ts +4 -4
  44. package/dist/models/mcpOAuthAuthorization.d.ts +2 -0
  45. package/dist/models/mcpOAuthAuthorization.js +86 -0
  46. package/dist/models/mcpOAuthClient.d.ts +2 -0
  47. package/dist/models/mcpOAuthClient.js +42 -0
  48. package/dist/models/mcpOAuthRevokedFamily.d.ts +2 -0
  49. package/dist/models/mcpOAuthRevokedFamily.js +36 -0
  50. package/dist/models/mcpOAuthToken.d.ts +12 -0
  51. package/dist/models/mcpOAuthToken.js +159 -0
  52. package/dist/models/mcpServiceToken.d.ts +1 -0
  53. package/dist/models/mcpServiceToken.js +21 -4
  54. package/dist/permissions.d.ts +7 -0
  55. package/dist/permissions.js +18 -1
  56. package/dist/rateLimit/policies.d.ts +4 -0
  57. package/dist/rateLimit/policies.js +46 -7
  58. package/dist/rbac/access.js +1 -0
  59. package/dist/rbac/membershipOrgAdminSource.d.ts +4 -0
  60. package/dist/rbac/membershipOrgAdminSource.js +5 -0
  61. package/dist/rbac/modelRouterAccess.d.ts +7 -1
  62. package/dist/rbac/modelRouterAccess.js +37 -24
  63. package/dist/rbac/realtimeAccess.js +17 -3
  64. package/dist/rbac/resolve.js +66 -9
  65. package/dist/rbac/roleManager.js +60 -5
  66. package/dist/rbac/roleModel.js +1 -1
  67. package/dist/rbac/statements.d.ts +1 -1
  68. package/dist/rbac/statements.js +13 -1
  69. package/dist/rbac/types.d.ts +12 -0
  70. package/dist/rbac/userWriteGuards.d.ts +50 -0
  71. package/dist/rbac/userWriteGuards.js +156 -0
  72. package/dist/realtime/changeStreamWatcher.d.ts +4 -1
  73. package/dist/realtime/changeStreamWatcher.js +157 -73
  74. package/dist/realtime/queryMatcher.d.ts +3 -0
  75. package/dist/realtime/queryMatcher.js +25 -10
  76. package/dist/realtime/realtimeApp.d.ts +16 -1
  77. package/dist/realtime/realtimeApp.js +76 -8
  78. package/dist/realtime/socketAuth.d.ts +17 -6
  79. package/dist/realtime/socketAuth.js +77 -16
  80. package/dist/realtime/types.d.ts +8 -5
  81. package/dist/requestContext.d.ts +22 -0
  82. package/dist/requestContext.js +22 -1
  83. package/dist/seedRunner.js +3 -1
  84. package/dist/sortFields.d.ts +33 -0
  85. package/dist/sortFields.js +55 -0
  86. package/dist/sync/executors.js +140 -2
  87. package/dist/sync/models.d.ts +2 -0
  88. package/dist/sync/models.js +5 -0
  89. package/dist/sync/mutationHandler.js +70 -7
  90. package/dist/sync/routes.js +4 -2
  91. package/dist/sync/syncSeqPlugin.js +6 -5
  92. package/dist/terrenoApp.d.ts +14 -0
  93. package/dist/terrenoApp.js +21 -6
  94. package/dist/types/mcpOAuth.d.ts +101 -0
  95. package/dist/types/mcpOAuth.js +2 -0
  96. package/dist/types/mcpServiceToken.d.ts +8 -0
  97. package/package.json +3 -3
  98. package/src/actions.test.ts +118 -0
  99. package/src/actions.ts +139 -17
  100. package/src/api.arrayOperations.test.ts +78 -0
  101. package/src/api.test.ts +36 -0
  102. package/src/api.ts +76 -4
  103. package/src/auth.test.ts +521 -3
  104. package/src/auth.ts +171 -17
  105. package/src/authRecovery.test.ts +99 -0
  106. package/src/authRecovery.ts +117 -5
  107. package/src/authVerification.test.ts +3 -3
  108. package/src/betterAuth.ts +104 -1
  109. package/src/betterAuthApp.test.ts +634 -1
  110. package/src/betterAuthApp.ts +28 -0
  111. package/src/betterAuthOAuthHandoff.test.ts +946 -0
  112. package/src/betterAuthOAuthHandoff.ts +375 -0
  113. package/src/betterAuthSetup.test.ts +393 -4
  114. package/src/betterAuthSetup.ts +402 -29
  115. package/src/expressServer.test.ts +93 -0
  116. package/src/expressServer.ts +81 -14
  117. package/src/githubAuth.test.ts +448 -6
  118. package/src/githubAuth.ts +276 -34
  119. package/src/index.ts +35 -1
  120. package/src/mcp/actionTools.test.ts +498 -0
  121. package/src/mcp/actionTools.ts +220 -0
  122. package/src/mcp/auth.test.ts +114 -1
  123. package/src/mcp/auth.ts +122 -35
  124. package/src/mcp/createMCPRequest.ts +8 -2
  125. package/src/mcp/handlers.test.ts +27 -0
  126. package/src/mcp/handlers.ts +21 -6
  127. package/src/mcp/oauth.test.ts +1026 -0
  128. package/src/mcp/oauth.ts +798 -0
  129. package/src/mcp/oauthMetadata.ts +234 -0
  130. package/src/mcp/registry.ts +11 -0
  131. package/src/mcp/server.ts +54 -14
  132. package/src/mcp/serviceTokens.ts +16 -3
  133. package/src/mcp/toolExecution.ts +67 -0
  134. package/src/mcp/toolGenerator.ts +27 -83
  135. package/src/mcp/types.ts +4 -4
  136. package/src/models/mcpOAuthAuthorization.ts +97 -0
  137. package/src/models/mcpOAuthClient.ts +49 -0
  138. package/src/models/mcpOAuthRevokedFamily.ts +47 -0
  139. package/src/models/mcpOAuthToken.test.ts +82 -0
  140. package/src/models/mcpOAuthToken.ts +195 -0
  141. package/src/models/mcpServiceToken.ts +26 -2
  142. package/src/permissions.ts +17 -0
  143. package/src/rateLimit/policies.ts +54 -10
  144. package/src/rateLimit/rateLimit.test.ts +41 -0
  145. package/src/rbac/access.ts +1 -0
  146. package/src/rbac/membershipOrgAdminSource.ts +5 -0
  147. package/src/rbac/modelRouterAccess.ts +40 -23
  148. package/src/rbac/realtimeAccess.test.ts +43 -0
  149. package/src/rbac/realtimeAccess.ts +23 -3
  150. package/src/rbac/resolve.test.ts +179 -1
  151. package/src/rbac/resolve.ts +78 -9
  152. package/src/rbac/roleManager.test.ts +132 -0
  153. package/src/rbac/roleManager.ts +69 -5
  154. package/src/rbac/roleModel.ts +1 -1
  155. package/src/rbac/statements.ts +14 -1
  156. package/src/rbac/types.ts +12 -0
  157. package/src/rbac/userWriteGuards.test.ts +407 -0
  158. package/src/rbac/userWriteGuards.ts +185 -0
  159. package/src/realtime/changeStreamWatcher.ts +203 -75
  160. package/src/realtime/queryMatcher.ts +30 -13
  161. package/src/realtime/realtime.test.ts +132 -0
  162. package/src/realtime/realtimeApp.ts +94 -10
  163. package/src/realtime/realtimeAppSetup.test.ts +282 -1
  164. package/src/realtime/socketAuth.test.ts +140 -8
  165. package/src/realtime/socketAuth.ts +90 -19
  166. package/src/realtime/types.ts +8 -5
  167. package/src/requestContext.ts +52 -1
  168. package/src/requestCredential.test.ts +89 -0
  169. package/src/seedRunner.test.ts +21 -0
  170. package/src/seedRunner.ts +3 -1
  171. package/src/sortFields.ts +69 -0
  172. package/src/sync/executors.test.ts +382 -3
  173. package/src/sync/executors.ts +179 -4
  174. package/src/sync/models.ts +8 -0
  175. package/src/sync/mutationHandler.test.ts +166 -2
  176. package/src/sync/mutationHandler.ts +97 -5
  177. package/src/sync/routes.ts +4 -2
  178. package/src/sync/syncFrontier.test.ts +11 -0
  179. package/src/sync/syncPhaseC.test.ts +18 -0
  180. package/src/sync/syncSeqPlugin.ts +6 -5
  181. package/src/sync/syncSocket.test.ts +92 -0
  182. package/src/terrenoApp.ts +36 -21
  183. package/src/types/mcpOAuth.ts +129 -0
  184. package/src/types/mcpServiceToken.ts +6 -1
@@ -3,7 +3,6 @@ import * as Sentry from "@sentry/bun";
3
3
  import cron from "cron";
4
4
  import express, {type Router} from "express";
5
5
  import type jwt from "jsonwebtoken";
6
- import cloneDeep from "lodash/cloneDeep";
7
6
  import onFinished from "on-finished";
8
7
  import passport from "passport";
9
8
  import type {ModelRouterOptions} from "./api";
@@ -15,25 +14,76 @@ import {sendToSlack} from "./notifiers/slackNotifier";
15
14
  const SLOW_READ_MAX = 200;
16
15
  const SLOW_WRITE_MAX = 500;
17
16
  const IS_JEST = process.env.JEST_WORKER_ID !== undefined;
18
- const SENSITIVE_REQUEST_BODY_KEYS = [
19
- "newPassword",
20
- "oldPassword",
17
+ const REDACTED = "<REDACTED>";
18
+ // Stop at a depth no real request body reaches, so a self-referencing body cannot loop.
19
+ const MAX_REDACTION_DEPTH = 32;
20
+
21
+ // Matched anywhere in a key after lowercasing and removing separators, e.g. currentPassword,
22
+ // refresh_token, client_secret, code_verifier, x-api-key.
23
+ const SENSITIVE_KEY_FRAGMENTS = [
24
+ "apikey",
25
+ "authorization",
26
+ "credential",
27
+ "passcode",
28
+ "passphrase",
29
+ "passwd",
21
30
  "password",
22
- "refreshToken",
31
+ "privatekey",
32
+ "secret",
33
+ "signature",
23
34
  "token",
35
+ "verifier",
24
36
  ] as const;
25
37
 
26
- const redactSensitiveRequestBody = (body: Record<string, unknown>): Record<string, unknown> => {
27
- const bodyCopy = cloneDeep(body);
28
- for (const key of SENSITIVE_REQUEST_BODY_KEYS) {
29
- if (key in bodyCopy && bodyCopy[key] !== undefined) {
30
- bodyCopy[key] = "<REDACTED>";
38
+ // Matched as whole words of a key, so `code` covers OAuth and verification codes without
39
+ // matching unrelated words that merely contain the letters.
40
+ const SENSITIVE_KEY_WORDS = new Set<string>(["code", "otp", "pin"]);
41
+
42
+ const keyWords = (key: string): string[] => {
43
+ return key
44
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
45
+ .toLowerCase()
46
+ .split(/[^a-z0-9]+/)
47
+ .filter(Boolean);
48
+ };
49
+
50
+ /** Whether a request body or query key names credential material that must not be logged. */
51
+ const isSensitiveRequestKey = (key: string): boolean => {
52
+ const normalized = key.toLowerCase().replace(/[^a-z0-9]/g, "");
53
+ if (SENSITIVE_KEY_FRAGMENTS.some((fragment) => normalized.includes(fragment))) {
54
+ return true;
55
+ }
56
+ return keyWords(key).some((word) => SENSITIVE_KEY_WORDS.has(word));
57
+ };
58
+
59
+ const redactSensitiveValue = (value: unknown, depth: number): unknown => {
60
+ if (value === null || typeof value !== "object") {
61
+ return value;
62
+ }
63
+ if (depth >= MAX_REDACTION_DEPTH) {
64
+ return REDACTED;
65
+ }
66
+ if (Array.isArray(value)) {
67
+ return value.map((item) => redactSensitiveValue(item, depth + 1));
68
+ }
69
+ const prototype = Object.getPrototypeOf(value);
70
+ if (prototype !== Object.prototype && prototype !== null) {
71
+ return value;
72
+ }
73
+ const redacted: Record<string, unknown> = {};
74
+ for (const [key, child] of Object.entries(value as Record<string, unknown>)) {
75
+ if (child !== undefined && isSensitiveRequestKey(key)) {
76
+ redacted[key] = REDACTED;
77
+ } else {
78
+ redacted[key] = redactSensitiveValue(child, depth + 1);
31
79
  }
32
80
  }
33
- return bodyCopy;
81
+ return redacted;
34
82
  };
35
83
 
36
- const sensitiveQueryKeySet = new Set<string>(SENSITIVE_REQUEST_BODY_KEYS);
84
+ const redactSensitiveRequestBody = (body: Record<string, unknown>): unknown => {
85
+ return redactSensitiveValue(body, 0);
86
+ };
37
87
 
38
88
  export const redactSensitiveRequestUrl = (url: string | undefined): string => {
39
89
  if (!url) {
@@ -43,8 +93,8 @@ export const redactSensitiveRequestUrl = (url: string | undefined): string => {
43
93
  const parsed = new URL(url, "http://terreno.invalid");
44
94
  let didRedact = false;
45
95
  for (const key of parsed.searchParams.keys()) {
46
- if (sensitiveQueryKeySet.has(key)) {
47
- parsed.searchParams.set(key, "<REDACTED>");
96
+ if (isSensitiveRequestKey(key)) {
97
+ parsed.searchParams.set(key, REDACTED);
48
98
  didRedact = true;
49
99
  }
50
100
  }
@@ -210,6 +260,11 @@ export const createRouterWithAuth = (
210
260
 
211
261
  export interface AuthRecoveryMail {
212
262
  html?: string;
263
+ /**
264
+ * True on Terreno's recovery mail: it carries a one-time secret link. Mail transports should
265
+ * not store its content; `@terreno/comms` keeps no payload for it in the message log.
266
+ */
267
+ sensitive?: boolean;
213
268
  subject: string;
214
269
  text: string;
215
270
  to: string;
@@ -244,8 +299,20 @@ export interface AuthOptions {
244
299
  * BetterAuthApp is registered.
245
300
  */
246
301
  syncPasswordResetToBetterAuth?: (user: User, password: string) => Promise<void>;
302
+ /**
303
+ * Check a password against the user's Better Auth credential account. `PATCH /auth/me` uses it
304
+ * to confirm an email change for a user with no passport password. TerrenoApp wires this when
305
+ * BetterAuthApp is registered.
306
+ */
307
+ verifyBetterAuthPassword?: (user: User, password: string) => Promise<BetterAuthPasswordCheck>;
247
308
  }
248
309
 
310
+ /**
311
+ * Result of {@link AuthOptions.verifyBetterAuthPassword}: the password matched, did not match, or
312
+ * the user has no Better Auth credential password to check.
313
+ */
314
+ export type BetterAuthPasswordCheck = "verified" | "wrong" | "no-password";
315
+
249
316
  export const cronjob = (
250
317
  name: string,
251
318
  schedule: "hourly" | "minutely" | string,
@@ -320,6 +320,45 @@ const invokeGitHubVerify = (
320
320
  });
321
321
  };
322
322
 
323
+ type StateStoreCallback = (err: unknown, ok?: unknown) => void;
324
+
325
+ interface StateStoreLike {
326
+ store: (req: unknown, state: unknown, meta: unknown, callback: StateStoreCallback) => void;
327
+ verify: (req: unknown, state: unknown, meta: unknown, callback: StateStoreCallback) => void;
328
+ }
329
+
330
+ // Build a callback request whose link target was bound by the strategy's own state store, the
331
+ // way /auth/github/link binds it.
332
+ const linkRequestFor = async (userId: unknown): Promise<Record<string, unknown>> => {
333
+ const strategy = (
334
+ passport as unknown as {_strategies: Record<string, {_stateStore: StateStoreLike}>}
335
+ )._strategies.github;
336
+ let cookieValue = "";
337
+ const startReq = {
338
+ headers: {},
339
+ res: {
340
+ cookie: (_name: string, value: string): void => {
341
+ cookieValue = value;
342
+ },
343
+ },
344
+ };
345
+ const state = await new Promise<unknown>((resolve, reject) => {
346
+ strategy._stateStore.store(startReq, {linkUserId: String(userId)}, {}, (err, nonce) =>
347
+ err ? reject(err) : resolve(nonce)
348
+ );
349
+ });
350
+ const callbackReq = {
351
+ headers: {cookie: `terreno_github_oauth_state=${encodeURIComponent(cookieValue)}`},
352
+ res: {clearCookie: (): void => {}},
353
+ };
354
+ await new Promise<void>((resolve, reject) => {
355
+ strategy._stateStore.verify(callbackReq, state, {}, (err, ok) =>
356
+ err || !ok ? reject(err ?? new Error("state not verified")) : resolve()
357
+ );
358
+ });
359
+ return callbackReq;
360
+ };
361
+
323
362
  describe("GitHub strategy verify callback", () => {
324
363
  const testApp = {get: () => {}, use: () => {}} as unknown as express.Application;
325
364
 
@@ -400,7 +439,7 @@ describe("GitHub strategy verify callback", () => {
400
439
  clientSecret: "secret",
401
440
  });
402
441
 
403
- const req = {user: existingUser};
442
+ const req = await linkRequestFor(existingUser._id);
404
443
  const result = await invokeGitHubVerify(req, "access", "refresh", {
405
444
  id: "gh-link-1",
406
445
  photos: [{value: "http://avatar"}],
@@ -408,10 +447,49 @@ describe("GitHub strategy verify callback", () => {
408
447
  username: "linkedghuser",
409
448
  });
410
449
  expect(result.err).toBeNull();
450
+ expect(result.user._id.toString()).toBe(existingUser._id.toString());
411
451
  expect(result.user.githubId).toBe("gh-link-1");
412
452
  expect(result.user.githubUsername).toBe("linkedghuser");
413
453
  });
414
454
 
455
+ it("does not treat an ambient req.user as a link target", async () => {
456
+ const ambientUser = await GitHubTestUserModel.create({email: "ambient@example.com"});
457
+
458
+ setupGitHubAuth(testApp, GitHubTestUserModel as unknown as UserModel, {
459
+ allowAccountLinking: true,
460
+ callbackURL: "http://localhost:9000/auth/github/callback",
461
+ clientId: "id",
462
+ clientSecret: "secret",
463
+ });
464
+
465
+ const result = await invokeGitHubVerify({user: ambientUser}, "access", "refresh", {
466
+ emails: [{value: "ambient-gh@example.com"}],
467
+ id: "gh-ambient-1",
468
+ });
469
+ expect(result.err).toBeNull();
470
+ expect(result.user._id.toString()).not.toBe(ambientUser._id.toString());
471
+ const ambientRow = await GitHubTestUserModel.findById(ambientUser._id);
472
+ expect(ambientRow?.githubId).toBeUndefined();
473
+ });
474
+
475
+ it("passes the bound link user to a custom findOrCreateUser", async () => {
476
+ const linkUser = await GitHubTestUserModel.create({email: "customlink@example.com"});
477
+ let received: unknown;
478
+ setupGitHubAuth(testApp, GitHubTestUserModel as unknown as UserModel, {
479
+ callbackURL: "http://localhost:9000/auth/github/callback",
480
+ clientId: "id",
481
+ clientSecret: "secret",
482
+ findOrCreateUser: async (_profile, _access, _refresh, existingUser) => {
483
+ received = existingUser;
484
+ return existingUser;
485
+ },
486
+ });
487
+
488
+ const req = await linkRequestFor(linkUser._id);
489
+ await invokeGitHubVerify(req, "access", "refresh", {id: "gh-custom-link-1"});
490
+ expect(String((received as {_id: unknown})._id)).toBe(String(linkUser._id));
491
+ });
492
+
415
493
  it("rejects linking when allowAccountLinking=false", async () => {
416
494
  const existingUser = await GitHubTestUserModel.create({
417
495
  email: "nolink@example.com",
@@ -424,7 +502,7 @@ describe("GitHub strategy verify callback", () => {
424
502
  clientSecret: "secret",
425
503
  });
426
504
 
427
- const req = {user: existingUser};
505
+ const req = await linkRequestFor(existingUser._id);
428
506
  const result = await invokeGitHubVerify(req, "access", "refresh", {id: "gh-nolink-1"});
429
507
  expect(result.err).toBeDefined();
430
508
  expect(result.err?.status).toBe(400);
@@ -446,7 +524,7 @@ describe("GitHub strategy verify callback", () => {
446
524
  clientSecret: "secret",
447
525
  });
448
526
 
449
- const req = {user: userA};
527
+ const req = await linkRequestFor(userA._id);
450
528
  const result = await invokeGitHubVerify(req, "access", "refresh", {id: "gh-other-1"});
451
529
  expect(result.err).toBeDefined();
452
530
  expect(result.err?.status).toBe(400);
@@ -608,6 +686,7 @@ describe("GitHub callback handler (fake strategy)", () => {
608
686
  configureApp: addRoutes,
609
687
  githubAuth: {
610
688
  allowAccountLinking: true,
689
+ allowedReturnTo: ["https://example.com"],
611
690
  callbackURL: "http://localhost:9000/auth/github/callback",
612
691
  clientId: "test-client-id",
613
692
  clientSecret: "test-client-secret",
@@ -640,7 +719,7 @@ describe("GitHub callback handler (fake strategy)", () => {
640
719
  expect(res.body.data.userId).toBeDefined();
641
720
  });
642
721
 
643
- it("GET /auth/github/callback redirects to returnTo with tokens when session.returnTo is set", async () => {
722
+ it("GET /auth/github/callback redirects to an allowlisted returnTo with tokens in the fragment", async () => {
644
723
  const user = await GitHubTestUserModel.create({
645
724
  email: "cb2@example.com",
646
725
  githubId: "cb-gh-2",
@@ -652,10 +731,29 @@ describe("GitHub callback handler (fake strategy)", () => {
652
731
  .get("/auth/github/callback")
653
732
  .set("x-mock-return-to", "https://example.com/cb")
654
733
  .expect(302);
655
- expect(res.headers.location).toContain("https://example.com/cb");
734
+ expect(res.headers.location).toContain("https://example.com/cb#");
656
735
  expect(res.headers.location).toContain("token=");
657
736
  expect(res.headers.location).toContain("refreshToken=");
658
737
  expect(res.headers.location).toContain("userId=");
738
+ expect(new URL(res.headers.location).search).toBe("");
739
+ });
740
+
741
+ it("GET /auth/github/callback refuses to issue tokens to a disabled user", async () => {
742
+ const user = await GitHubTestUserModel.create({
743
+ disabled: true,
744
+ email: "cb-disabled@example.com",
745
+ githubId: "cb-gh-disabled",
746
+ name: "CB Disabled",
747
+ } as unknown as TestUser);
748
+
749
+ fakeGithubOutcome = {type: "success", user};
750
+
751
+ const res = await agent
752
+ .get("/auth/github/callback")
753
+ .set("x-mock-return-to", "https://example.com/cb")
754
+ .expect(401);
755
+ expect(res.headers.location).toBeUndefined();
756
+ expect(res.body.data?.token).toBeUndefined();
659
757
  });
660
758
 
661
759
  it("GET /auth/github/callback redirects on failure", async () => {
@@ -849,10 +947,11 @@ describe("GitHub strategy verify callback edge cases", () => {
849
947
  clientSecret: "secret",
850
948
  });
851
949
 
950
+ const req = await linkRequestFor((existingUser as unknown as {_id: unknown})._id);
951
+
852
952
  // Delete user before verify runs to hit the 404 path.
853
953
  await GitHubTestUserModel.deleteOne({_id: (existingUser as unknown as {_id: unknown})._id});
854
954
 
855
- const req = {user: existingUser};
856
955
  const result = await invokeGitHubVerify(req, "access", "refresh", {
857
956
  id: "gh-missing-1",
858
957
  username: "missing",
@@ -861,3 +960,346 @@ describe("GitHub strategy verify callback edge cases", () => {
861
960
  expect(result.err?.status).toBe(404);
862
961
  });
863
962
  });
963
+
964
+ interface OAuth2Stub {
965
+ getOAuthAccessToken: (
966
+ code: string,
967
+ params: Record<string, unknown>,
968
+ callback: (err: unknown, accessToken?: string, refreshToken?: string, params?: unknown) => void
969
+ ) => void;
970
+ }
971
+
972
+ interface StubbableGitHubStrategy {
973
+ _oauth2: OAuth2Stub;
974
+ userProfile: (accessToken: string, done: (err: unknown, profile?: unknown) => void) => void;
975
+ }
976
+
977
+ // Replace only the GitHub HTTP exchange: the code maps to a dummy profile with the same id.
978
+ const stubGitHubExchange = (): void => {
979
+ const strategy = (passport as unknown as {_strategies: Record<string, unknown>})._strategies
980
+ .github as StubbableGitHubStrategy;
981
+ strategy._oauth2.getOAuthAccessToken = (code, _params, callback): void => {
982
+ callback(null, `access-${code}`, undefined, {});
983
+ };
984
+ strategy.userProfile = (accessToken, done): void => {
985
+ const id = accessToken.replace(/^access-/, "");
986
+ done(null, {
987
+ emails: [{value: `${id}@github.example`}],
988
+ id,
989
+ photos: [],
990
+ profileUrl: `https://github.example/${id}`,
991
+ provider: "github",
992
+ username: `gh-${id}`,
993
+ });
994
+ };
995
+ };
996
+
997
+ const stateFromLocation = (location: string | undefined): string | null => {
998
+ if (!location) {
999
+ return null;
1000
+ }
1001
+ return new URL(location).searchParams.get("state");
1002
+ };
1003
+
1004
+ describe("GitHub OAuth state binding", () => {
1005
+ let app: express.Application;
1006
+
1007
+ beforeEach(async () => {
1008
+ setSystemTime();
1009
+ await connectDb();
1010
+ await GitHubTestUserModel.deleteMany({});
1011
+
1012
+ app = new TerrenoApp({
1013
+ beforeJsonSetup: (a) => {
1014
+ // Stand-in for an ambient cookie session (such as Better Auth) that sets req.user on
1015
+ // every request the browser makes, including the GitHub callback.
1016
+ a.use(async (req, _res, next) => {
1017
+ const ambientUserId = req.headers["x-ambient-session-user"];
1018
+ if (typeof ambientUserId === "string") {
1019
+ const ambientUser = await GitHubTestUserModel.findById(ambientUserId);
1020
+ req.user = ambientUser as unknown as express.Request["user"];
1021
+ }
1022
+ next();
1023
+ });
1024
+ },
1025
+ githubAuth: {
1026
+ allowAccountLinking: true,
1027
+ callbackURL: "http://localhost:9000/auth/github/callback",
1028
+ clientId: "test-client-id",
1029
+ clientSecret: "test-client-secret",
1030
+ },
1031
+ skipListen: true,
1032
+ userModel: GitHubTestUserModel as unknown as UserModel,
1033
+ }).build();
1034
+ stubGitHubExchange();
1035
+ });
1036
+
1037
+ afterEach(() => {
1038
+ setSystemTime();
1039
+ });
1040
+
1041
+ it("GET /auth/github sends a state parameter and sets an HttpOnly state cookie", async () => {
1042
+ const res = await supertest(app).get("/auth/github").expect(302);
1043
+ expect(stateFromLocation(res.headers.location)).toBeTruthy();
1044
+ const setCookie = String(res.headers["set-cookie"] ?? "");
1045
+ expect(setCookie).toContain("HttpOnly");
1046
+ expect(setCookie.toLowerCase()).toContain("samesite=lax");
1047
+ });
1048
+
1049
+ it("callback without state does not link GitHub to an ambient session user", async () => {
1050
+ const victim = await GitHubTestUserModel.create({email: "victim@example.test"});
1051
+
1052
+ await supertest(app)
1053
+ .get("/auth/github/callback?code=attacker-gh-1")
1054
+ .set("x-ambient-session-user", String(victim._id))
1055
+ .expect(302);
1056
+
1057
+ const victimRow = await GitHubTestUserModel.findById(victim._id);
1058
+ expect(victimRow?.githubId).toBeUndefined();
1059
+ });
1060
+
1061
+ it("callback with another browser's state is rejected", async () => {
1062
+ const attacker = supertest.agent(app);
1063
+ const start = await attacker.get("/auth/github").expect(302);
1064
+ const attackerState = stateFromLocation(start.headers.location);
1065
+
1066
+ const victim = await GitHubTestUserModel.create({email: "victim2@example.test"});
1067
+ const res = await supertest(app)
1068
+ .get(`/auth/github/callback?code=attacker-gh-2&state=${attackerState}`)
1069
+ .set("x-ambient-session-user", String(victim._id))
1070
+ .expect(302);
1071
+ expect(res.headers.location).toContain("/auth/github/failure");
1072
+
1073
+ const victimRow = await GitHubTestUserModel.findById(victim._id);
1074
+ expect(victimRow?.githubId).toBeUndefined();
1075
+ expect(await GitHubTestUserModel.countDocuments({githubId: "attacker-gh-2"})).toBe(0);
1076
+ });
1077
+
1078
+ it("login flow with valid state ignores the ambient session user", async () => {
1079
+ const victim = await GitHubTestUserModel.create({email: "victim3@example.test"});
1080
+ const browser = supertest.agent(app);
1081
+ const start = await browser.get("/auth/github").expect(302);
1082
+ const state = stateFromLocation(start.headers.location);
1083
+
1084
+ const res = await browser
1085
+ .get(`/auth/github/callback?code=gh-login-3&state=${state}`)
1086
+ .set("x-ambient-session-user", String(victim._id))
1087
+ .expect(200);
1088
+
1089
+ const victimRow = await GitHubTestUserModel.findById(victim._id);
1090
+ expect(victimRow?.githubId).toBeUndefined();
1091
+ expect(String(res.body.data.userId)).not.toBe(String(victim._id));
1092
+ });
1093
+
1094
+ it("state is single use", async () => {
1095
+ const browser = supertest.agent(app);
1096
+ const start = await browser.get("/auth/github").expect(302);
1097
+ const state = stateFromLocation(start.headers.location);
1098
+
1099
+ await browser.get(`/auth/github/callback?code=gh-once-1&state=${state}`).expect(200);
1100
+ const replay = await browser
1101
+ .get(`/auth/github/callback?code=gh-once-2&state=${state}`)
1102
+ .expect(302);
1103
+ expect(replay.headers.location).toContain("/auth/github/failure");
1104
+ });
1105
+
1106
+ it("link flow links GitHub to the user who started /auth/github/link", async () => {
1107
+ const user = await GitHubTestUserModel.create({email: "linker@example.test"});
1108
+ const {token} = await generateTokens({_id: user._id});
1109
+ const browser = supertest.agent(app);
1110
+
1111
+ const start = await browser
1112
+ .get("/auth/github/link")
1113
+ .set("authorization", `Bearer ${token}`)
1114
+ .expect(302);
1115
+ const state = stateFromLocation(start.headers.location);
1116
+ expect(state).toBeTruthy();
1117
+
1118
+ const res = await browser
1119
+ .get(`/auth/github/callback?code=gh-link-4&state=${state}`)
1120
+ .expect(200);
1121
+ expect(String(res.body.data.userId)).toBe(String(user._id));
1122
+
1123
+ const linked = await GitHubTestUserModel.findById(user._id);
1124
+ expect(linked?.githubId).toBe("gh-link-4");
1125
+ expect(linked?.githubUsername).toBe("gh-gh-link-4");
1126
+ });
1127
+
1128
+ it("an expired state cookie is rejected", async () => {
1129
+ const browser = supertest.agent(app);
1130
+ const start = await browser.get("/auth/github").expect(302);
1131
+ const state = stateFromLocation(start.headers.location);
1132
+
1133
+ setSystemTime(new Date(Date.now() + 11 * 60 * 1000));
1134
+ const res = await browser
1135
+ .get(`/auth/github/callback?code=gh-late-1&state=${state}`)
1136
+ .expect(302);
1137
+ expect(res.headers.location).toContain("/auth/github/failure");
1138
+ });
1139
+
1140
+ it("a tampered state cookie is rejected", async () => {
1141
+ const victim = await GitHubTestUserModel.create({email: "victim5@example.test"});
1142
+ const browser = supertest.agent(app);
1143
+ const start = await browser.get("/auth/github").expect(302);
1144
+ const state = stateFromLocation(start.headers.location);
1145
+ const setCookie = String(start.headers["set-cookie"]);
1146
+ const cookieValue = setCookie.split(";")[0].split("=").slice(1).join("=");
1147
+ const [, signature] = decodeURIComponent(cookieValue).split(".");
1148
+ const forgedPayload = Buffer.from(
1149
+ JSON.stringify({expiresAt: Date.now() + 60_000, linkUserId: String(victim._id), nonce: state})
1150
+ ).toString("base64url");
1151
+
1152
+ const res = await supertest(app)
1153
+ .get(`/auth/github/callback?code=gh-forged-1&state=${state}`)
1154
+ .set("cookie", `terreno_github_oauth_state=${forgedPayload}.${signature}`)
1155
+ .expect(302);
1156
+ expect(res.headers.location).toContain("/auth/github/failure");
1157
+ const victimRow = await GitHubTestUserModel.findById(victim._id);
1158
+ expect(victimRow?.githubId).toBeUndefined();
1159
+ });
1160
+ });
1161
+
1162
+ describe("GitHub OAuth returnTo allowlist", () => {
1163
+ const buildApp = (allowedReturnTo?: string[]): express.Application => {
1164
+ const sessions = new Map<string, Record<string, unknown>>();
1165
+ let nextSessionId = 0;
1166
+ const built = new TerrenoApp({
1167
+ beforeJsonSetup: (a) => {
1168
+ // Minimal cookie-keyed session store standing in for express-session.
1169
+ a.use((req, res, next) => {
1170
+ const match = /(?:^|;\s*)sid=([^;]+)/.exec(req.headers.cookie ?? "");
1171
+ let sessionId = match?.[1];
1172
+ if (!sessionId || !sessions.has(sessionId)) {
1173
+ nextSessionId += 1;
1174
+ sessionId = `session-${nextSessionId}`;
1175
+ sessions.set(sessionId, {});
1176
+ res.cookie("sid", sessionId, {httpOnly: true, path: "/"});
1177
+ }
1178
+ const session = sessions.get(sessionId) as Record<string, unknown>;
1179
+ const planted = req.headers["x-plant-return-to"];
1180
+ if (typeof planted === "string") {
1181
+ session.returnTo = planted;
1182
+ }
1183
+ (req as unknown as {session: Record<string, unknown>}).session = session;
1184
+ next();
1185
+ });
1186
+ },
1187
+ githubAuth: {
1188
+ allowedReturnTo,
1189
+ callbackURL: "http://localhost:9000/auth/github/callback",
1190
+ clientId: "test-client-id",
1191
+ clientSecret: "test-client-secret",
1192
+ },
1193
+ skipListen: true,
1194
+ userModel: GitHubTestUserModel as unknown as UserModel,
1195
+ }).build();
1196
+ installFakeGithubStrategy();
1197
+ return built;
1198
+ };
1199
+
1200
+ beforeEach(async () => {
1201
+ setSystemTime();
1202
+ await connectDb();
1203
+ await GitHubTestUserModel.deleteMany({});
1204
+ });
1205
+
1206
+ afterEach(() => {
1207
+ setSystemTime();
1208
+ fakeGithubOutcome = {type: "redirect", url: "http://github.com/mock"};
1209
+ });
1210
+
1211
+ const createGitHubUser = async (suffix: string): Promise<unknown> => {
1212
+ return GitHubTestUserModel.create({
1213
+ email: `returnto-${suffix}@example.test`,
1214
+ githubId: `returnto-gh-${suffix}`,
1215
+ } as unknown as TestUser);
1216
+ };
1217
+
1218
+ it("rejects a returnTo outside the allowlist and sends no tokens there", async () => {
1219
+ const app = buildApp(["https://app.example.test", "myapp://auth"]);
1220
+ const browser = supertest.agent(app);
1221
+ await browser.get("/auth/github?returnTo=https://attacker.example/steal").expect(400);
1222
+
1223
+ fakeGithubOutcome = {type: "success", user: await createGitHubUser("a")};
1224
+ const res = await browser.get("/auth/github/callback").expect(200);
1225
+ expect(res.headers.location).toBeUndefined();
1226
+ });
1227
+
1228
+ it("rejects look-alike and non-http returnTo values", async () => {
1229
+ const app = buildApp(["https://app.example.test", "myapp://auth"]);
1230
+ const targets = [
1231
+ "https://app.example.test.attacker.example/cb",
1232
+ "https://app.example.test@attacker.example/cb",
1233
+ "http://app.example.test/cb",
1234
+ "javascript:alert(1)",
1235
+ "myapp://other/cb",
1236
+ "/relative/path",
1237
+ ];
1238
+ for (const target of targets) {
1239
+ await supertest(app)
1240
+ .get(`/auth/github?returnTo=${encodeURIComponent(target)}`)
1241
+ .expect(400);
1242
+ }
1243
+ await supertest(app).get("/auth/github?returnTo=a&returnTo=b").expect(400);
1244
+ });
1245
+
1246
+ it("redirects an allowlisted returnTo with tokens in the fragment, not the query", async () => {
1247
+ const app = buildApp(["https://app.example.test"]);
1248
+ const browser = supertest.agent(app);
1249
+ await browser
1250
+ .get(`/auth/github?returnTo=${encodeURIComponent("https://app.example.test/auth/callback")}`)
1251
+ .expect(302);
1252
+
1253
+ const user = await createGitHubUser("b");
1254
+ fakeGithubOutcome = {type: "success", user};
1255
+ const res = await browser.get("/auth/github/callback").expect(302);
1256
+ const location = new URL(res.headers.location);
1257
+ expect(location.origin).toBe("https://app.example.test");
1258
+ expect(location.pathname).toBe("/auth/callback");
1259
+ expect(location.search).toBe("");
1260
+ const fragment = new URLSearchParams(location.hash.slice(1));
1261
+ expect(fragment.get("token")).toBeTruthy();
1262
+ expect(fragment.get("refreshToken")).toBeTruthy();
1263
+ expect(fragment.get("userId")).toBe(String((user as {_id: unknown})._id));
1264
+
1265
+ // The stored target is used once.
1266
+ const again = await browser.get("/auth/github/callback").expect(200);
1267
+ expect(again.headers.location).toBeUndefined();
1268
+ });
1269
+
1270
+ it("accepts an allowlisted custom-scheme authority", async () => {
1271
+ const app = buildApp(["myapp://auth"]);
1272
+ const browser = supertest.agent(app);
1273
+ await browser
1274
+ .get(`/auth/github?returnTo=${encodeURIComponent("myapp://auth/github")}`)
1275
+ .expect(302);
1276
+
1277
+ fakeGithubOutcome = {type: "success", user: await createGitHubUser("c")};
1278
+ const res = await browser.get("/auth/github/callback").expect(302);
1279
+ expect(res.headers.location.startsWith("myapp://auth/github#token=")).toBe(true);
1280
+ });
1281
+
1282
+ it("ignores returnTo when no allowlist is configured", async () => {
1283
+ const app = buildApp();
1284
+ const browser = supertest.agent(app);
1285
+ await browser.get("/auth/github?returnTo=https://attacker.example/steal").expect(302);
1286
+
1287
+ fakeGithubOutcome = {type: "success", user: await createGitHubUser("d")};
1288
+ const res = await browser.get("/auth/github/callback").expect(200);
1289
+ expect(res.headers.location).toBeUndefined();
1290
+ expect(res.body.data.token).toBeDefined();
1291
+ });
1292
+
1293
+ it("re-checks a stored returnTo before redirecting", async () => {
1294
+ const app = buildApp(["https://app.example.test"]);
1295
+ const browser = supertest.agent(app);
1296
+ // Prime a session, then plant a target that did not pass the start-time check.
1297
+ await browser.get("/auth/github").expect(302);
1298
+ fakeGithubOutcome = {type: "success", user: await createGitHubUser("e")};
1299
+ const res = await browser
1300
+ .get("/auth/github/callback")
1301
+ .set("x-plant-return-to", "https://attacker.example/steal")
1302
+ .expect(200);
1303
+ expect(res.headers.location).toBeUndefined();
1304
+ });
1305
+ });