@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
@@ -0,0 +1,946 @@
1
+ import {afterAll, beforeAll, beforeEach, describe, expect, it} from "bun:test";
2
+ import {once} from "node:events";
3
+ import type {Server} from "node:http";
4
+ import type {AddressInfo} from "node:net";
5
+ import type {BetterAuthPlugin} from "better-auth";
6
+ import {createAuthMiddleware} from "better-auth/api";
7
+ import {genericOAuth} from "better-auth/plugins";
8
+ import express from "express";
9
+ import {DateTime} from "luxon";
10
+ import mongoose from "mongoose";
11
+ import supertest from "supertest";
12
+ import type {BetterAuthConfig} from "./betterAuth";
13
+ import {
14
+ type BetterAuthInstance,
15
+ createBetterAuth,
16
+ getMongoClientFromMongoose,
17
+ mountBetterAuthRoutes,
18
+ } from "./betterAuthSetup";
19
+
20
+ const API_ORIGIN = "http://localhost:3000";
21
+ const WEB_ORIGIN = "https://web.example.com";
22
+ const PROVIDER_ID = "mock-oidc";
23
+ const MOCK_CODE = "mock-authorization-code";
24
+ const MOCK_ACCESS_TOKEN = "mock-access-token";
25
+ const SECRET = "test-secret-at-least-32-characters-long";
26
+
27
+ interface MockOidcUser {
28
+ email: string;
29
+ id: string;
30
+ name: string;
31
+ }
32
+
33
+ interface MockOidcProvider {
34
+ close: () => Promise<void>;
35
+ issuer: string;
36
+ /** The user the next sign-in authenticates as. */
37
+ setUser: (user: MockOidcUser) => void;
38
+ }
39
+
40
+ // A minimal OIDC provider: discovery, an authorize step that approves at once, a token
41
+ // endpoint, and userinfo. Real enough for Better Auth's generic OAuth code flow with PKCE.
42
+ const startMockOidcProvider = async (): Promise<MockOidcProvider> => {
43
+ let issuer = "";
44
+ let user: MockOidcUser = {email: "oidc@example.com", id: "oidc-user", name: "OIDC User"};
45
+ const app = express();
46
+ app.use(express.urlencoded({extended: false}));
47
+ app.get("/.well-known/openid-configuration", (_req, res) => {
48
+ res.json({
49
+ authorization_endpoint: `${issuer}/authorize`,
50
+ issuer,
51
+ response_types_supported: ["code"],
52
+ token_endpoint: `${issuer}/token`,
53
+ userinfo_endpoint: `${issuer}/userinfo`,
54
+ });
55
+ });
56
+ app.get("/authorize", (req, res) => {
57
+ const redirect = new URL(String(req.query.redirect_uri));
58
+ redirect.searchParams.set("code", MOCK_CODE);
59
+ redirect.searchParams.set("state", String(req.query.state));
60
+ res.redirect(redirect.toString());
61
+ });
62
+ app.post("/token", (req, res) => {
63
+ if (req.body.code !== MOCK_CODE) {
64
+ res.status(400).json({error: "invalid_grant"});
65
+ return;
66
+ }
67
+ res.json({access_token: MOCK_ACCESS_TOKEN, expires_in: 3600, token_type: "Bearer"});
68
+ });
69
+ app.get("/userinfo", (req, res) => {
70
+ if (req.headers.authorization !== `Bearer ${MOCK_ACCESS_TOKEN}`) {
71
+ res.status(401).json({error: "invalid_token"});
72
+ return;
73
+ }
74
+ res.json({...user, email_verified: true, sub: user.id});
75
+ });
76
+ const server: Server = app.listen(0, "127.0.0.1");
77
+ await once(server, "listening");
78
+ issuer = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
79
+ return {
80
+ close: async (): Promise<void> => {
81
+ server.close();
82
+ await once(server, "close");
83
+ },
84
+ issuer,
85
+ setUser: (next: MockOidcUser): void => {
86
+ user = next;
87
+ },
88
+ };
89
+ };
90
+
91
+ // Lets a case replace what Better Auth put on the callback response before the handoff hook
92
+ // reads it, to probe the hook with redirects Better Auth's own origin check would refuse.
93
+ interface CallbackOverride {
94
+ location?: string;
95
+ replaceResponse?: boolean;
96
+ }
97
+
98
+ let callbackOverride: CallbackOverride = {};
99
+
100
+ const callbackOverridePlugin = {
101
+ hooks: {
102
+ after: [
103
+ {
104
+ handler: createAuthMiddleware(async (ctx): Promise<void> => {
105
+ if (callbackOverride.location !== undefined) {
106
+ ctx.setHeader("location", callbackOverride.location);
107
+ }
108
+ if (callbackOverride.replaceResponse) {
109
+ (ctx.context as {returned?: unknown}).returned = new Response("replaced", {
110
+ status: 200,
111
+ });
112
+ }
113
+ }),
114
+ matcher: (context: {path?: string}): boolean =>
115
+ Boolean(context.path?.startsWith("/callback/")),
116
+ },
117
+ ],
118
+ },
119
+ id: "terreno-test-callback-override",
120
+ } satisfies BetterAuthPlugin;
121
+
122
+ let provider: MockOidcProvider;
123
+
124
+ interface HandoffApp {
125
+ app: express.Application;
126
+ auth: BetterAuthInstance;
127
+ }
128
+
129
+ const buildApp = (overrides: Partial<BetterAuthConfig> = {}): HandoffApp => {
130
+ const config: BetterAuthConfig = {
131
+ baseURL: API_ORIGIN,
132
+ enabled: true,
133
+ oauthHandoff: {callbackPaths: ["/", "/after"], webOrigins: [WEB_ORIGIN]},
134
+ // Better Auth skips origin checks when NODE_ENV is "test"; turn them back on so the
135
+ // callbackURLs below pass or fail the same check they would in production.
136
+ options: {advanced: {disableOriginCheck: false}},
137
+ plugins: [
138
+ genericOAuth({
139
+ config: [
140
+ {
141
+ clientId: "mock-client",
142
+ clientSecret: "mock-secret",
143
+ discoveryUrl: `${provider.issuer}/.well-known/openid-configuration`,
144
+ providerId: PROVIDER_ID,
145
+ },
146
+ // Registered without an authorization URL, so starting a sign-in with it fails.
147
+ {clientId: "broken-client", clientSecret: "broken-secret", providerId: "broken"},
148
+ ],
149
+ }),
150
+ callbackOverridePlugin,
151
+ ],
152
+ secret: SECRET,
153
+ trustedOrigins: [
154
+ WEB_ORIGIN,
155
+ "http://web.example.com",
156
+ "https://other.example.com",
157
+ "https://*.preview.example.com",
158
+ "exp://",
159
+ "terreno://",
160
+ ],
161
+ ...overrides,
162
+ };
163
+ const auth = createBetterAuth({config, mongoClient: getMongoClientFromMongoose()});
164
+ const app = express();
165
+ mountBetterAuthRoutes(app, auth);
166
+ return {app, auth};
167
+ };
168
+
169
+ // `name=value` pairs from a response's set-cookie headers, ready for a cookie request header.
170
+ const cookieHeaderFrom = (res: supertest.Response): string => {
171
+ const raw = res.headers["set-cookie"] as unknown as string[] | undefined;
172
+ return (raw ?? []).map((cookie) => cookie.split(";")[0]).join("; ");
173
+ };
174
+
175
+ interface StartedSignIn {
176
+ callbackPath: string;
177
+ cookie: string;
178
+ }
179
+
180
+ // The web app's cross-site `signIn.social` call, then the provider's approval redirect.
181
+ const startSignIn = async (
182
+ app: express.Application,
183
+ body: Record<string, string>
184
+ ): Promise<StartedSignIn> => {
185
+ const start = await supertest(app)
186
+ .post("/api/auth/sign-in/social")
187
+ .set("origin", WEB_ORIGIN)
188
+ .set("sec-fetch-site", "cross-site")
189
+ .set("sec-fetch-mode", "cors")
190
+ .set("content-type", "application/json")
191
+ .send({provider: PROVIDER_ID, ...body});
192
+ expect(start.status).toBe(200);
193
+ expect(start.body.url).toStartWith(`${provider.issuer}/authorize`);
194
+
195
+ const approval = await fetch(start.body.url, {redirect: "manual"});
196
+ const callback = new URL(approval.headers.get("location") ?? "");
197
+ expect(callback.origin).toBe(API_ORIGIN);
198
+ expect(callback.pathname).toBe(`/api/auth/callback/${PROVIDER_ID}`);
199
+ // The callback needs the OAuth state cookie the sign-in response set. Carrying it by hand
200
+ // stands in for however the browser keeps it; how a cross-site app keeps it is T13/T14's call.
201
+ return {callbackPath: `${callback.pathname}${callback.search}`, cookie: cookieHeaderFrom(start)};
202
+ };
203
+
204
+ // Completes the provider's redirect back to the API's callback (a top-level navigation).
205
+ const completeSignIn = async (
206
+ app: express.Application,
207
+ body: Record<string, string>
208
+ ): Promise<supertest.Response> => {
209
+ const {callbackPath, cookie} = await startSignIn(app, body);
210
+ return supertest(app).get(callbackPath).set("cookie", cookie);
211
+ };
212
+
213
+ const fragmentParams = (location: string): URLSearchParams =>
214
+ new URLSearchParams(new URL(location).hash.slice(1));
215
+
216
+ const HANDOFF_TOKEN_ROWS = {identifier: {$regex: /^one-time-token:/}};
217
+
218
+ // Better Auth's verification collection on the default connection.
219
+ const verificationRows = (): ReturnType<mongoose.mongo.Db["collection"]> => {
220
+ const db = mongoose.connection.db;
221
+ if (!db) {
222
+ throw new Error("The test database is not connected");
223
+ }
224
+ return db.collection("verification");
225
+ };
226
+
227
+ const verify = (app: express.Application, token: string): supertest.Test =>
228
+ supertest(app)
229
+ .post("/api/auth/one-time-token/verify")
230
+ .set("origin", WEB_ORIGIN)
231
+ .set("sec-fetch-site", "cross-site")
232
+ .set("sec-fetch-mode", "cors")
233
+ .set("content-type", "application/json")
234
+ .send({token});
235
+
236
+ beforeAll(async () => {
237
+ provider = await startMockOidcProvider();
238
+ });
239
+
240
+ afterAll(async () => {
241
+ await provider?.close();
242
+ });
243
+
244
+ beforeEach(async () => {
245
+ callbackOverride = {};
246
+ provider.setUser({
247
+ email: `oidc-${Math.random().toString(36).slice(2)}@example.com`,
248
+ id: `oidc-${Math.random().toString(36).slice(2)}`,
249
+ name: "OIDC User",
250
+ });
251
+ for (const collection of ["user", "session", "account", "verification"]) {
252
+ await mongoose.connection.db?.collection(collection).deleteMany({});
253
+ }
254
+ });
255
+
256
+ describe("oauthHandoff on a listed web origin", () => {
257
+ it("redirects with #ott, which verifies once into a bearer session", async () => {
258
+ const {app} = buildApp();
259
+
260
+ const callback = await completeSignIn(app, {callbackURL: `${WEB_ORIGIN}/after?tab=1`});
261
+
262
+ expect(callback.status).toBe(302);
263
+ const location = callback.headers.location as string;
264
+ expect(location).toStartWith(`${WEB_ORIGIN}/after?tab=1#ott=`);
265
+ // The handed-off redirect leaves no session behind on the API's origin: no session cookie
266
+ // and no raw token header, while the state cookie is still cleared.
267
+ const callbackCookies = (callback.headers["set-cookie"] as unknown as string[]) ?? [];
268
+ expect(callbackCookies.some((cookie) => cookie.includes("session_token="))).toBe(false);
269
+ expect(callbackCookies.some((cookie) => cookie.includes("session_data="))).toBe(false);
270
+ expect(callbackCookies.some((cookie) => cookie.includes(".state="))).toBe(true);
271
+ expect(callback.headers["set-auth-token"]).toBeUndefined();
272
+ const ott = fragmentParams(location).get("ott") ?? "";
273
+ expect(ott.length).toBeGreaterThan(20);
274
+ // The token travels only in the fragment, never in the path or query the server sees.
275
+ expect(new URL(location).search).toBe("?tab=1");
276
+
277
+ const first = await verify(app, ott);
278
+ expect(first.status).toBe(200);
279
+ const bearer = first.headers["set-auth-token"] as string;
280
+ expect(bearer).toBeTruthy();
281
+ expect(first.headers["set-ott"]).toBeUndefined();
282
+ // Bearer mode needs no API-origin session cookie.
283
+ expect(first.headers["set-cookie"]).toBeUndefined();
284
+ const exposed = String(first.headers["access-control-expose-headers"] ?? "").toLowerCase();
285
+ expect(exposed).toContain("set-auth-token");
286
+ expect(first.body.user.email).toStartWith("oidc-");
287
+
288
+ const session = await supertest(app)
289
+ .get("/api/auth/get-session")
290
+ .set("authorization", `Bearer ${bearer}`);
291
+ expect(session.status).toBe(200);
292
+ expect(session.body.user.email).toBe(first.body.user.email);
293
+
294
+ const second = await verify(app, ott);
295
+ expect(second.status).toBe(400);
296
+ expect(second.headers["set-auth-token"]).toBeUndefined();
297
+ });
298
+
299
+ it("lets only one of two concurrent verifies use the token", async () => {
300
+ const {app} = buildApp();
301
+ const callback = await completeSignIn(app, {callbackURL: `${WEB_ORIGIN}/after`});
302
+ const ott = fragmentParams(callback.headers.location as string).get("ott") ?? "";
303
+
304
+ const results = await Promise.all([verify(app, ott), verify(app, ott)]);
305
+
306
+ expect(results.map((res) => res.status).sort()).toEqual([200, 400]);
307
+ });
308
+
309
+ it("stores the token hashed, expiring in three minutes", async () => {
310
+ const {app} = buildApp();
311
+ const callback = await completeSignIn(app, {callbackURL: `${WEB_ORIGIN}/`});
312
+ const ott = fragmentParams(callback.headers.location as string).get("ott") ?? "";
313
+
314
+ const rows = await verificationRows().find(HANDOFF_TOKEN_ROWS).toArray();
315
+
316
+ expect(rows).toHaveLength(1);
317
+ expect(rows[0].identifier).not.toContain(ott);
318
+ const minutes = DateTime.fromJSDate(rows[0].expiresAt).diffNow("minutes").minutes;
319
+ expect(minutes).toBeGreaterThan(2.5);
320
+ expect(minutes).toBeLessThanOrEqual(3);
321
+ });
322
+
323
+ it("keeps an existing fragment and replaces an ott already in it", async () => {
324
+ const {app} = buildApp();
325
+
326
+ const callback = await completeSignIn(app, {
327
+ callbackURL: `${WEB_ORIGIN}/after#section=2&ott=planted&o%74t=planted2`,
328
+ });
329
+
330
+ const location = callback.headers.location as string;
331
+ expect(location).toStartWith(`${WEB_ORIGIN}/after#section=2&ott=`);
332
+ const params = fragmentParams(location);
333
+ expect(params.getAll("ott")).toHaveLength(1);
334
+ expect(params.get("ott")).not.toBe("planted");
335
+ expect(params.get("section")).toBe("2");
336
+ expect((await verify(app, params.get("ott") ?? "")).status).toBe(200);
337
+ });
338
+
339
+ it("keeps a fragment part it cannot decode", async () => {
340
+ const {app} = buildApp();
341
+
342
+ const callback = await completeSignIn(app, {callbackURL: `${WEB_ORIGIN}/after#%zz=1`});
343
+
344
+ expect(callback.headers.location).toStartWith(`${WEB_ORIGIN}/after#%zz=1&ott=`);
345
+ });
346
+
347
+ it("gives no token when a new user is sent to an unlisted newUserCallbackURL", async () => {
348
+ const {app} = buildApp();
349
+
350
+ const callback = await completeSignIn(app, {
351
+ callbackURL: `${WEB_ORIGIN}/after`,
352
+ newUserCallbackURL: "https://other.example.com/welcome",
353
+ });
354
+
355
+ expect(callback.status).toBe(302);
356
+ expect(callback.headers.location).toBe("https://other.example.com/welcome");
357
+ });
358
+
359
+ it("gives no token when the callback links an account to a signed-in user", async () => {
360
+ const {app} = buildApp();
361
+ const email = `linker-${Math.random().toString(36).slice(2)}@example.com`;
362
+ provider.setUser({email, id: `oidc-${Math.random().toString(36).slice(2)}`, name: "Linker"});
363
+ const signUp = await supertest(app)
364
+ .post("/api/auth/sign-up/email")
365
+ .set("origin", WEB_ORIGIN)
366
+ .set("content-type", "application/json")
367
+ .send({email, name: "Linker", password: "password-123456"});
368
+ expect(signUp.status).toBe(200);
369
+ const sessionCookie = cookieHeaderFrom(signUp);
370
+
371
+ const link = await supertest(app)
372
+ .post("/api/auth/link-social")
373
+ .set("origin", WEB_ORIGIN)
374
+ .set("cookie", sessionCookie)
375
+ .set("content-type", "application/json")
376
+ .send({callbackURL: `${WEB_ORIGIN}/after`, provider: PROVIDER_ID});
377
+ expect(link.status).toBe(200);
378
+ const approval = await fetch(link.body.url, {redirect: "manual"});
379
+ const callback = new URL(approval.headers.get("location") ?? "");
380
+
381
+ const returned = await supertest(app)
382
+ .get(`${callback.pathname}${callback.search}`)
383
+ .set("cookie", `${sessionCookie}; ${cookieHeaderFrom(link)}`);
384
+
385
+ expect(returned.status).toBe(302);
386
+ expect(returned.headers.location).toBe(`${WEB_ORIGIN}/after`);
387
+ expect(await verificationRows().countDocuments(HANDOFF_TOKEN_ROWS)).toBe(0);
388
+ const accounts = await mongoose.connection.db
389
+ ?.collection("account")
390
+ .countDocuments({providerId: PROVIDER_ID});
391
+ expect(accounts).toBe(1);
392
+ });
393
+
394
+ it("gives no token to a failed sign-in that redirects to a listed web origin", async () => {
395
+ const {app} = buildApp();
396
+ const {callbackPath, cookie} = await startSignIn(app, {
397
+ callbackURL: `${WEB_ORIGIN}/after`,
398
+ errorCallbackURL: `${WEB_ORIGIN}/error`,
399
+ });
400
+ const state = new URL(callbackPath, API_ORIGIN).searchParams.get("state") ?? "";
401
+
402
+ const callback = await supertest(app)
403
+ .get(`/api/auth/callback/${PROVIDER_ID}?error=access_denied&state=${state}`)
404
+ .set("cookie", cookie);
405
+
406
+ expect(callback.status).toBe(302);
407
+ expect(callback.headers.location).toStartWith(`${WEB_ORIGIN}/error?error=access_denied`);
408
+ expect(callback.headers.location).not.toContain("ott=");
409
+ });
410
+
411
+ it("leaves a callback response another plugin replaced untouched", async () => {
412
+ const {app} = buildApp();
413
+ callbackOverride = {replaceResponse: true};
414
+
415
+ const callback = await completeSignIn(app, {callbackURL: `${WEB_ORIGIN}/after`});
416
+
417
+ expect(callback.status).toBe(200);
418
+ expect(callback.text).toBe("replaced");
419
+ expect(String(callback.headers.location ?? "")).not.toContain("ott=");
420
+ });
421
+
422
+ it("keeps the redirect without a token when minting fails", async () => {
423
+ const {app} = buildApp({
424
+ options: {
425
+ advanced: {disableOriginCheck: false},
426
+ databaseHooks: {
427
+ verification: {
428
+ create: {
429
+ before: async (verification: {identifier: string}): Promise<void> => {
430
+ if (verification.identifier.startsWith("one-time-token:")) {
431
+ throw new Error("verification store unavailable");
432
+ }
433
+ },
434
+ },
435
+ },
436
+ },
437
+ },
438
+ });
439
+
440
+ const callback = await completeSignIn(app, {callbackURL: `${WEB_ORIGIN}/after`});
441
+
442
+ expect(callback.status).toBe(302);
443
+ expect(callback.headers.location).toBe(`${WEB_ORIGIN}/after`);
444
+ });
445
+ });
446
+
447
+ describe("oauthHandoff on a callbackURL that is not a listed web origin", () => {
448
+ const unlisted: {callbackURL: string; name: string}[] = [
449
+ {callbackURL: "exp://127.0.0.1:8081/--/home", name: "an exp:// app scheme"},
450
+ {callbackURL: "terreno://home", name: "a terreno:// app scheme"},
451
+ {callbackURL: "/dashboard", name: "a relative path"},
452
+ {callbackURL: `${API_ORIGIN}/welcome`, name: "the API's own origin"},
453
+ {callbackURL: "http://web.example.com/after", name: "the web host over http"},
454
+ {callbackURL: "https://other.example.com/after", name: "another trusted origin"},
455
+ {callbackURL: "https://pr-7.preview.example.com/after", name: "a wildcard-trusted origin"},
456
+ ];
457
+
458
+ for (const {name, callbackURL} of unlisted) {
459
+ it(`passes the origin check but gets no ott for ${name}`, async () => {
460
+ const {app} = buildApp();
461
+
462
+ const callback = await completeSignIn(app, {callbackURL});
463
+
464
+ expect(callback.status).toBe(302);
465
+ expect(callback.headers.location).toBe(callbackURL);
466
+ const rows = await verificationRows().countDocuments(HANDOFF_TOKEN_ROWS);
467
+ expect(rows).toBe(0);
468
+ });
469
+ }
470
+
471
+ it("rejects a callbackURL outside trustedOrigins before any redirect", async () => {
472
+ const {app} = buildApp();
473
+
474
+ const start = await supertest(app)
475
+ .post("/api/auth/sign-in/social")
476
+ .set("origin", WEB_ORIGIN)
477
+ .set("content-type", "application/json")
478
+ .send({callbackURL: "https://evil.example/after", provider: PROVIDER_ID});
479
+
480
+ expect(start.status).toBe(403);
481
+ expect(start.body.code).toBe("INVALID_CALLBACK_URL");
482
+ });
483
+
484
+ // Redirects Better Auth itself would refuse, injected after its check, to prove the hook's
485
+ // own origin comparison is exact.
486
+ const injected: {location: string; name: string; ott: boolean}[] = [
487
+ {
488
+ location: `${WEB_ORIGIN}@evil.example/after`,
489
+ name: "userinfo before another host",
490
+ ott: false,
491
+ },
492
+ {location: "https://web.example.com.evil.example/", name: "a suffix host", ott: false},
493
+ {location: "https://web.example.com:8443/", name: "another port", ott: false},
494
+ {location: "//web.example.com/after", name: "a scheme-relative URL", ott: false},
495
+ {location: "https:web.example.com/after", name: "a scheme without slashes", ott: false},
496
+ {location: "javascript://web.example.com/%0aalert(1)", name: "a javascript: URL", ott: false},
497
+ {location: "https://[web.example.com/after", name: "an unparseable URL", ott: false},
498
+ // Only the normal form the URL parser would print gets a token, so browsers that parse a
499
+ // little differently cannot be steered elsewhere.
500
+ {
501
+ location: "HTTPS://WEB.EXAMPLE.COM/after",
502
+ name: "the listed origin in upper case",
503
+ ott: false,
504
+ },
505
+ {
506
+ location: "https://web.example.com:443/after",
507
+ name: "the listed origin's default port",
508
+ ott: false,
509
+ },
510
+ {location: "https://web.example.com\\after", name: "a backslash for the slash", ott: false},
511
+ ];
512
+
513
+ for (const {location, name, ott} of injected) {
514
+ it(`${ott ? "hands" : "gives no"} ott to ${name}`, async () => {
515
+ const {app} = buildApp();
516
+ callbackOverride = {location};
517
+
518
+ const callback = await completeSignIn(app, {callbackURL: `${WEB_ORIGIN}/after`});
519
+
520
+ expect(callback.status).toBe(302);
521
+ if (ott) {
522
+ expect(callback.headers.location).toStartWith(`${location}#ott=`);
523
+ } else {
524
+ expect(callback.headers.location).toBe(location);
525
+ }
526
+ });
527
+ }
528
+ });
529
+
530
+ describe("oauthHandoff minting is server-only", () => {
531
+ const signUpAndSignIn = async (app: express.Application): Promise<supertest.Response> => {
532
+ const email = `email-${Math.random().toString(36).slice(2)}@example.com`;
533
+ const signUp = await supertest(app)
534
+ .post("/api/auth/sign-up/email")
535
+ .set("origin", WEB_ORIGIN)
536
+ .set("content-type", "application/json")
537
+ .send({email, name: "Email User", password: "password-123456"});
538
+ expect(signUp.status).toBe(200);
539
+ expect(signUp.headers["set-ott"]).toBeUndefined();
540
+ return supertest(app)
541
+ .post("/api/auth/sign-in/email")
542
+ .set("origin", WEB_ORIGIN)
543
+ .set("content-type", "application/json")
544
+ .send({email, password: "password-123456"});
545
+ };
546
+
547
+ it("refuses the client route GET /one-time-token/generate", async () => {
548
+ const {app} = buildApp();
549
+ const signIn = await signUpAndSignIn(app);
550
+ const bearer = signIn.headers["set-auth-token"] as string;
551
+ expect(bearer).toBeTruthy();
552
+
553
+ const res = await supertest(app)
554
+ .get("/api/auth/one-time-token/generate")
555
+ .set("origin", WEB_ORIGIN)
556
+ .set("authorization", `Bearer ${bearer}`);
557
+
558
+ expect(res.status).toBe(400);
559
+ expect(res.body.token).toBeUndefined();
560
+ });
561
+
562
+ it("sends no set-ott header on email sign-in", async () => {
563
+ const {app} = buildApp();
564
+
565
+ const signIn = await signUpAndSignIn(app);
566
+
567
+ expect(signIn.status).toBe(200);
568
+ expect(signIn.headers["set-ott"]).toBeUndefined();
569
+ expect(String(signIn.headers["access-control-expose-headers"] ?? "")).not.toContain("set-ott");
570
+ });
571
+
572
+ it("has no /one-time-token routes when oauthHandoff is unset", async () => {
573
+ const {app} = buildApp({oauthHandoff: undefined});
574
+
575
+ const verifyRes = await verify(app, "anything");
576
+ const generateRes = await supertest(app).get("/api/auth/one-time-token/generate");
577
+
578
+ expect(verifyRes.status).toBe(404);
579
+ expect(generateRes.status).toBe(404);
580
+ });
581
+
582
+ it("puts no ott on the callback redirect when oauthHandoff is unset", async () => {
583
+ const {app} = buildApp({oauthHandoff: undefined});
584
+
585
+ const callback = await completeSignIn(app, {callbackURL: `${WEB_ORIGIN}/after`});
586
+
587
+ expect(callback.status).toBe(302);
588
+ expect(callback.headers.location).toBe(`${WEB_ORIGIN}/after`);
589
+ });
590
+ });
591
+
592
+ describe("oauthHandoff configuration", () => {
593
+ const invalid = [
594
+ "web.example.com",
595
+ "https://*.example.com",
596
+ "exp://",
597
+ "https://web.example.com/app",
598
+ "https://web.example.com?x=1",
599
+ "https://user@web.example.com",
600
+ ];
601
+
602
+ for (const entry of invalid) {
603
+ it(`refuses "${entry}" as a web origin`, () => {
604
+ expect(() => buildApp({oauthHandoff: {webOrigins: [entry]}})).toThrow(
605
+ "oauthHandoff.webOrigins must list exact http(s) origins"
606
+ );
607
+ });
608
+ }
609
+
610
+ it("refuses an empty webOrigins list", () => {
611
+ expect(() => buildApp({oauthHandoff: {webOrigins: []}})).toThrow(
612
+ "oauthHandoff.webOrigins must list exact http(s) origins"
613
+ );
614
+ });
615
+
616
+ for (const baseURL of ["localhost:3000", "not a url"]) {
617
+ it(`refuses "${baseURL}" as the baseURL`, () => {
618
+ expect(() => buildApp({baseURL})).toThrow("BETTER_AUTH_URL must be an absolute URL");
619
+ });
620
+ }
621
+
622
+ it("accepts an origin with a trailing slash", async () => {
623
+ const {app} = buildApp({
624
+ oauthHandoff: {callbackPaths: ["/after"], webOrigins: [`${WEB_ORIGIN}/`]},
625
+ });
626
+
627
+ const callback = await completeSignIn(app, {callbackURL: `${WEB_ORIGIN}/after`});
628
+
629
+ expect(callback.headers.location).toStartWith(`${WEB_ORIGIN}/after#ott=`);
630
+ });
631
+
632
+ it("never hands a token to the API origin, even when listed", async () => {
633
+ const {app} = buildApp({oauthHandoff: {webOrigins: [WEB_ORIGIN, API_ORIGIN]}});
634
+
635
+ const callback = await completeSignIn(app, {callbackURL: `${API_ORIGIN}/welcome`});
636
+
637
+ expect(callback.headers.location).toBe(`${API_ORIGIN}/welcome`);
638
+ });
639
+ });
640
+
641
+ describe("GET /oauth-handoff/start", () => {
642
+ // A top-level navigation from the web app to the API: no cookie, no Origin header.
643
+ const start = (app: express.Application, query: Record<string, string>): supertest.Test =>
644
+ supertest(app)
645
+ .get(`/api/auth/oauth-handoff/start?${new URLSearchParams(query).toString()}`)
646
+ .set("sec-fetch-site", "cross-site")
647
+ .set("sec-fetch-mode", "navigate");
648
+
649
+ const setCookies = (res: supertest.Response): string[] =>
650
+ (res.headers["set-cookie"] as unknown as string[] | undefined) ?? [];
651
+
652
+ it("starts the flow with a first-party state cookie and ends on the web origin with #ott", async () => {
653
+ const {app} = buildApp();
654
+ const callbackURL = `${WEB_ORIGIN}/after?handoff=nonce-123&tab=1`;
655
+
656
+ const started = await start(app, {callbackURL, provider: PROVIDER_ID});
657
+
658
+ expect(started.status).toBe(302);
659
+ expect(started.headers.location).toStartWith(`${provider.issuer}/authorize?`);
660
+ const stateCookie = setCookies(started).find((cookie) => cookie.includes(".state="));
661
+ expect(stateCookie).toBeTruthy();
662
+ // Lax comes back on the provider's top-level redirect to the callback.
663
+ expect(stateCookie?.toLowerCase()).toContain("samesite=lax");
664
+ expect(stateCookie?.toLowerCase()).toContain("httponly");
665
+
666
+ const approval = await fetch(started.headers.location as string, {redirect: "manual"});
667
+ const callback = new URL(approval.headers.get("location") ?? "");
668
+ expect(callback.origin).toBe(API_ORIGIN);
669
+ const returned = await supertest(app)
670
+ .get(`${callback.pathname}${callback.search}`)
671
+ .set("cookie", cookieHeaderFrom(started));
672
+
673
+ expect(returned.status).toBe(302);
674
+ const location = returned.headers.location as string;
675
+ expect(location).toStartWith(`${callbackURL}#ott=`);
676
+ const verified = await verify(app, fragmentParams(location).get("ott") ?? "");
677
+ expect(verified.status).toBe(200);
678
+ expect(verified.headers["set-auth-token"]).toBeTruthy();
679
+ });
680
+
681
+ it("sends a failed sign-in to a listed errorCallbackURL without a token", async () => {
682
+ const {app} = buildApp();
683
+ const started = await start(app, {
684
+ callbackURL: `${WEB_ORIGIN}/after`,
685
+ errorCallbackURL: `${WEB_ORIGIN}/sign-in-error`,
686
+ provider: PROVIDER_ID,
687
+ });
688
+ const state = new URL(started.headers.location as string).searchParams.get("state") ?? "";
689
+
690
+ const returned = await supertest(app)
691
+ .get(`/api/auth/callback/${PROVIDER_ID}?error=access_denied&state=${state}`)
692
+ .set("cookie", cookieHeaderFrom(started));
693
+
694
+ expect(returned.status).toBe(302);
695
+ expect(returned.headers.location).toStartWith(
696
+ `${WEB_ORIGIN}/sign-in-error?error=access_denied`
697
+ );
698
+ expect(returned.headers.location).not.toContain("ott=");
699
+ });
700
+
701
+ it("fails the callback when the start's state cookie does not come back", async () => {
702
+ const {app} = buildApp();
703
+ const started = await start(app, {callbackURL: `${WEB_ORIGIN}/after`, provider: PROVIDER_ID});
704
+ const approval = await fetch(started.headers.location as string, {redirect: "manual"});
705
+ const callback = new URL(approval.headers.get("location") ?? "");
706
+
707
+ const returned = await supertest(app).get(`${callback.pathname}${callback.search}`);
708
+
709
+ expect(returned.status).toBe(302);
710
+ expect(returned.headers.location).not.toContain("ott=");
711
+ expect(returned.headers.location).toContain("error=state_mismatch");
712
+ });
713
+
714
+ const refused: {name: string; query: Record<string, string>}[] = [
715
+ {name: "an exp:// app scheme", query: {callbackURL: "exp://127.0.0.1:8081/--/home"}},
716
+ {name: "a relative path", query: {callbackURL: "/dashboard"}},
717
+ {name: "a scheme-relative URL", query: {callbackURL: "//web.example.com/after"}},
718
+ {name: "the API's own origin", query: {callbackURL: `${API_ORIGIN}/welcome`}},
719
+ {name: "a trusted but unlisted origin", query: {callbackURL: "https://other.example.com/"}},
720
+ {name: "an untrusted origin", query: {callbackURL: "https://evil.example/after"}},
721
+ {name: "userinfo before another host", query: {callbackURL: `${WEB_ORIGIN}@evil.example/`}},
722
+ {name: "the web host over http", query: {callbackURL: "http://web.example.com/after"}},
723
+ {
724
+ name: "an unlisted errorCallbackURL",
725
+ query: {callbackURL: `${WEB_ORIGIN}/after`, errorCallbackURL: "https://evil.example/error"},
726
+ },
727
+ {name: "a missing callbackURL", query: {}},
728
+ ];
729
+
730
+ for (const {name, query} of refused) {
731
+ it(`refuses ${name} with 400 and no redirect`, async () => {
732
+ const {app} = buildApp();
733
+
734
+ const res = await start(app, {provider: PROVIDER_ID, ...query});
735
+
736
+ expect(res.status).toBe(400);
737
+ expect(res.headers.location).toBeUndefined();
738
+ expect(setCookies(res)).toEqual([]);
739
+ });
740
+ }
741
+
742
+ it("sends an unknown provider back to the web app with an error", async () => {
743
+ const {app} = buildApp();
744
+
745
+ const res = await start(app, {callbackURL: `${WEB_ORIGIN}/after?handoff=n`, provider: "nope"});
746
+
747
+ expect(res.status).toBe(302);
748
+ expect(res.headers.location).toBe(`${WEB_ORIGIN}/after?handoff=n&error=provider_not_found`);
749
+ expect(setCookies(res)).toEqual([]);
750
+ });
751
+
752
+ it("sends a provider that cannot start to the errorCallbackURL", async () => {
753
+ const {app} = buildApp();
754
+
755
+ const res = await start(app, {
756
+ callbackURL: `${WEB_ORIGIN}/after`,
757
+ errorCallbackURL: `${WEB_ORIGIN}/sign-in-error`,
758
+ provider: "broken",
759
+ });
760
+
761
+ expect(res.status).toBe(302);
762
+ expect(res.headers.location).toBe(`${WEB_ORIGIN}/sign-in-error?error=sign_in_failed`);
763
+ });
764
+
765
+ it("refuses a listed web origin that is not in trustedOrigins", async () => {
766
+ const listedOnly = "https://listed-only.example.com";
767
+ const {app} = buildApp({oauthHandoff: {webOrigins: [WEB_ORIGIN, listedOnly]}});
768
+
769
+ const res = await start(app, {callbackURL: `${listedOnly}/after`, provider: PROVIDER_ID});
770
+
771
+ expect(res.status).toBe(400);
772
+ expect(res.headers.location).toBeUndefined();
773
+ });
774
+
775
+ it("refuses a request that is not a page navigation", async () => {
776
+ const {app} = buildApp();
777
+
778
+ const res = await start(app, {callbackURL: `${WEB_ORIGIN}/after`, provider: PROVIDER_ID}).set(
779
+ "sec-fetch-dest",
780
+ "image"
781
+ );
782
+
783
+ expect(res.status).toBe(400);
784
+ expect(res.headers.location).toBeUndefined();
785
+ expect(setCookies(res)).toEqual([]);
786
+ });
787
+
788
+ it("limits starts to three per ten seconds when Better Auth's limiter is on", async () => {
789
+ const {app} = buildApp({
790
+ options: {advanced: {disableOriginCheck: false}, rateLimit: {enabled: true}},
791
+ });
792
+ const query = {callbackURL: `${WEB_ORIGIN}/after`, provider: PROVIDER_ID};
793
+
794
+ const statuses: number[] = [];
795
+ for (let attempt = 0; attempt < 4; attempt += 1) {
796
+ statuses.push((await start(app, query).set("x-forwarded-for", "203.0.113.9")).status);
797
+ }
798
+
799
+ expect(statuses).toEqual([302, 302, 302, 429]);
800
+ });
801
+
802
+ it("starts a built-in social provider", async () => {
803
+ const {app} = buildApp({googleOAuth: {clientId: "google-id", clientSecret: "google-secret"}});
804
+
805
+ const res = await start(app, {callbackURL: `${WEB_ORIGIN}/after`, provider: "google"});
806
+
807
+ expect(res.status).toBe(302);
808
+ const authorize = new URL(res.headers.location as string);
809
+ expect(authorize.origin).toBe("https://accounts.google.com");
810
+ expect(authorize.searchParams.get("redirect_uri")).toBe(
811
+ `${API_ORIGIN}/api/auth/callback/google`
812
+ );
813
+ expect(res.headers["cache-control"]).toBe("no-store");
814
+ expect(setCookies(res).some((cookie) => cookie.includes(".state="))).toBe(true);
815
+ });
816
+
817
+ it("sets a SameSite=None; Secure state cookie with crossDomainCookies", async () => {
818
+ const {app} = buildApp({crossDomainCookies: true});
819
+
820
+ const res = await start(app, {callbackURL: `${WEB_ORIGIN}/after`, provider: PROVIDER_ID});
821
+
822
+ expect(res.status).toBe(302);
823
+ const stateCookie = setCookies(res).find((cookie) => cookie.includes(".state="));
824
+ expect(stateCookie?.toLowerCase()).toContain("samesite=none");
825
+ expect(stateCookie?.toLowerCase()).toContain("secure");
826
+ });
827
+
828
+ it("does not exist when oauthHandoff is unset", async () => {
829
+ const {app} = buildApp({oauthHandoff: undefined});
830
+
831
+ const res = await start(app, {callbackURL: `${WEB_ORIGIN}/after`, provider: PROVIDER_ID});
832
+
833
+ expect(res.status).toBe(404);
834
+ expect(res.headers.location).toBeUndefined();
835
+ });
836
+ });
837
+
838
+ describe("oauthHandoff callbackPaths", () => {
839
+ const startFor = (app: express.Application, callbackURL: string): supertest.Test =>
840
+ supertest(app)
841
+ .get(
842
+ `/api/auth/oauth-handoff/start?${new URLSearchParams({callbackURL, provider: PROVIDER_ID})}`
843
+ )
844
+ .set("sec-fetch-mode", "navigate");
845
+
846
+ it("defaults to the web origin's root path", async () => {
847
+ const {app} = buildApp({oauthHandoff: {webOrigins: [WEB_ORIGIN]}});
848
+
849
+ const root = await completeSignIn(app, {callbackURL: `${WEB_ORIGIN}/?handoff=n`});
850
+ const other = await completeSignIn(app, {callbackURL: `${WEB_ORIGIN}/after`});
851
+ const startOther = await startFor(app, `${WEB_ORIGIN}/after`);
852
+
853
+ expect(root.headers.location).toStartWith(`${WEB_ORIGIN}/?handoff=n#ott=`);
854
+ expect(other.headers.location).toBe(`${WEB_ORIGIN}/after`);
855
+ expect(startOther.status).toBe(400);
856
+ expect(startOther.headers.location).toBeUndefined();
857
+ });
858
+
859
+ it("hands a token only to the listed paths", async () => {
860
+ const {app} = buildApp({
861
+ oauthHandoff: {callbackPaths: ["/auth/return"], webOrigins: [WEB_ORIGIN]},
862
+ });
863
+
864
+ const listed = await completeSignIn(app, {callbackURL: `${WEB_ORIGIN}/auth/return?handoff=n`});
865
+ const root = await completeSignIn(app, {callbackURL: `${WEB_ORIGIN}/`});
866
+ const startListed = await startFor(app, `${WEB_ORIGIN}/auth/return?handoff=n`);
867
+ const startRoot = await startFor(app, `${WEB_ORIGIN}/`);
868
+
869
+ expect(listed.headers.location).toStartWith(`${WEB_ORIGIN}/auth/return?handoff=n#ott=`);
870
+ expect(root.headers.location).toBe(`${WEB_ORIGIN}/`);
871
+ expect(startListed.status).toBe(302);
872
+ expect(startRoot.status).toBe(400);
873
+ });
874
+
875
+ it("checks only the origin of errorCallbackURL, which never carries a token", async () => {
876
+ const {app} = buildApp();
877
+
878
+ const res = await supertest(app)
879
+ .get(
880
+ `/api/auth/oauth-handoff/start?${new URLSearchParams({
881
+ callbackURL: `${WEB_ORIGIN}/after`,
882
+ errorCallbackURL: `${WEB_ORIGIN}/any/error/page`,
883
+ provider: PROVIDER_ID,
884
+ })}`
885
+ )
886
+ .set("sec-fetch-mode", "navigate");
887
+
888
+ expect(res.status).toBe(302);
889
+ });
890
+
891
+ // The redirect must already be in the URL parser's normal form, and its path must then
892
+ // match byte for byte; only the query and fragment are free.
893
+ const pathCases: {location: string; name: string; ott: boolean}[] = [
894
+ {location: `${WEB_ORIGIN}/after/`, name: "a trailing slash", ott: false},
895
+ {location: `${WEB_ORIGIN}/AFTER`, name: "a different case", ott: false},
896
+ {location: `${WEB_ORIGIN}//after`, name: "a doubled slash", ott: false},
897
+ {location: `${WEB_ORIGIN}/x%2Fafter`, name: "an encoded slash", ott: false},
898
+ {location: `${WEB_ORIGIN}/after%2F`, name: "a trailing encoded slash", ott: false},
899
+ {location: `${WEB_ORIGIN}/after;x`, name: "a path parameter", ott: false},
900
+ {location: `${WEB_ORIGIN}/x/%2e%2e/after`, name: "encoded dot segments", ott: false},
901
+ {location: `${WEB_ORIGIN}/x/../after`, name: "dot segments", ott: false},
902
+ {location: `${WEB_ORIGIN}/after?next=1`, name: "a listed path with a query", ott: true},
903
+ {location: `${WEB_ORIGIN}/after#keep`, name: "a listed path with a fragment", ott: true},
904
+ ];
905
+
906
+ for (const {location, name, ott} of pathCases) {
907
+ it(`${ott ? "hands" : "gives no"} ott to ${name}`, async () => {
908
+ const {app} = buildApp();
909
+ callbackOverride = {location};
910
+
911
+ const callback = await completeSignIn(app, {callbackURL: `${WEB_ORIGIN}/after`});
912
+ const started = await startFor(app, location);
913
+
914
+ if (ott) {
915
+ expect(callback.headers.location).toContain("ott=");
916
+ expect(started.status).toBe(302);
917
+ } else {
918
+ expect(callback.headers.location).toBe(location);
919
+ expect(started.status).toBe(400);
920
+ }
921
+ });
922
+ }
923
+
924
+ const invalidPaths: string[][] = [
925
+ [],
926
+ ["after"],
927
+ ["//after"],
928
+ ["/a/../b"],
929
+ ["/%2e%2e/"],
930
+ ["/a/./b"],
931
+ ["/a%2Fb"],
932
+ ["/a%5Cb"],
933
+ ["/a\\b"],
934
+ ["/a?x=1"],
935
+ ["/a#x"],
936
+ ["/a b"],
937
+ ];
938
+
939
+ for (const callbackPaths of invalidPaths) {
940
+ it(`refuses callbackPaths ${JSON.stringify(callbackPaths)}`, () => {
941
+ expect(() => buildApp({oauthHandoff: {callbackPaths, webOrigins: [WEB_ORIGIN]}})).toThrow(
942
+ "oauthHandoff.callbackPaths must list exact absolute paths"
943
+ );
944
+ });
945
+ }
946
+ });