@terreno/syncdb 58.0.6 → 58.1.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 (50) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/dist/auth/TerrenoOAuthConsentScreen.d.ts +65 -0
  3. package/dist/auth/TerrenoOAuthConsentScreen.d.ts.map +1 -0
  4. package/dist/auth/TerrenoOAuthConsentScreen.js +119 -0
  5. package/dist/auth/TerrenoOAuthConsentScreen.js.map +1 -0
  6. package/dist/auth/auth.d.ts +2 -0
  7. package/dist/auth/auth.d.ts.map +1 -1
  8. package/dist/auth/auth.js +2 -0
  9. package/dist/auth/auth.js.map +1 -1
  10. package/dist/auth/useLoginController.d.ts +23 -1
  11. package/dist/auth/useLoginController.d.ts.map +1 -1
  12. package/dist/auth/useLoginController.js +14 -4
  13. package/dist/auth/useLoginController.js.map +1 -1
  14. package/dist/auth/useMcpOAuthConsent.d.ts +65 -0
  15. package/dist/auth/useMcpOAuthConsent.d.ts.map +1 -0
  16. package/dist/auth/useMcpOAuthConsent.js +133 -0
  17. package/dist/auth/useMcpOAuthConsent.js.map +1 -0
  18. package/dist/codegen/discoverOperations.test.d.ts +2 -0
  19. package/dist/codegen/discoverOperations.test.d.ts.map +1 -0
  20. package/dist/codegen/discoverOperations.test.js +66 -0
  21. package/dist/codegen/discoverOperations.test.js.map +1 -0
  22. package/dist/devMcpRegistry.d.ts.map +1 -1
  23. package/dist/devMcpRegistry.isolated.js +6 -0
  24. package/dist/devMcpRegistry.isolated.js.map +1 -1
  25. package/dist/devMcpRegistry.js +3 -1
  26. package/dist/devMcpRegistry.js.map +1 -1
  27. package/dist/isolated/TerrenoLoginScreen.isolated.js +59 -0
  28. package/dist/isolated/TerrenoLoginScreen.isolated.js.map +1 -1
  29. package/dist/isolated/TerrenoOAuthConsentScreen.isolated.d.ts +2 -0
  30. package/dist/isolated/TerrenoOAuthConsentScreen.isolated.d.ts.map +1 -0
  31. package/dist/isolated/TerrenoOAuthConsentScreen.isolated.js +532 -0
  32. package/dist/isolated/TerrenoOAuthConsentScreen.isolated.js.map +1 -0
  33. package/dist/isolated/useLoginController.isolated.js +94 -0
  34. package/dist/isolated/useLoginController.isolated.js.map +1 -1
  35. package/dist/isolated/useMcpOAuthConsent.isolated.d.ts +2 -0
  36. package/dist/isolated/useMcpOAuthConsent.isolated.d.ts.map +1 -0
  37. package/dist/isolated/useMcpOAuthConsent.isolated.js +273 -0
  38. package/dist/isolated/useMcpOAuthConsent.isolated.js.map +1 -0
  39. package/package.json +4 -4
  40. package/src/auth/TerrenoOAuthConsentScreen.tsx +365 -0
  41. package/src/auth/auth.ts +2 -0
  42. package/src/auth/useLoginController.ts +47 -3
  43. package/src/auth/useMcpOAuthConsent.ts +242 -0
  44. package/src/codegen/discoverOperations.test.ts +69 -0
  45. package/src/devMcpRegistry.isolated.ts +6 -0
  46. package/src/devMcpRegistry.ts +3 -1
  47. package/src/isolated/TerrenoLoginScreen.isolated.tsx +93 -0
  48. package/src/isolated/TerrenoOAuthConsentScreen.isolated.tsx +637 -0
  49. package/src/isolated/useLoginController.isolated.ts +109 -0
  50. package/src/isolated/useMcpOAuthConsent.isolated.ts +330 -0
@@ -0,0 +1,637 @@
1
+ /**
2
+ * Isolated tests for TerrenoOAuthConsentScreen. `@terreno/ui` cannot render under the test
3
+ * preload's react-native stub, so it is replaced with components that render a host element
4
+ * carrying their props (so test ids, labels, `disabled`, and handlers are observable) and, for the
5
+ * login steps, recorders like TerrenoLoginScreen.isolated.tsx. The session is a real
6
+ * `SessionProvider` over a controllable source, and the consent endpoints are stubbed at the fetch
7
+ * boundary of a real request client mounted through `ApiClientProvider`.
8
+ */
9
+ import {afterEach, beforeEach, describe, expect, it, mock} from "bun:test";
10
+ import {createElement, type ReactElement, type ReactNode} from "react";
11
+ import {act, create, type ReactTestInstance, type ReactTestRenderer} from "react-test-renderer";
12
+
13
+ import {createApiClient, type FetchLike} from "../api/client";
14
+ import type {BetterAuthUser} from "../auth/betterAuthTypes";
15
+ import type {BetterAuthMethods} from "../auth/useAuthMethods";
16
+ import type {LoginControllerClient, LoginUser} from "../auth/useLoginController";
17
+ import {ApiClientProvider} from "../react/apiHooks";
18
+
19
+ // Tells React this process drives updates through act(), as @testing-library does.
20
+ (globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT = true;
21
+
22
+ mock.module("../auth/platform", () => ({IsWeb: true}));
23
+ mock.module("@better-auth/expo/client", () => ({
24
+ expoClient: () => ({id: "expo", name: "expo-plugin"}),
25
+ }));
26
+
27
+ const rendered: Array<{name: string; props: Record<string, unknown>}> = [];
28
+ const recorder =
29
+ (name: string) =>
30
+ (props: Record<string, unknown>): null => {
31
+ rendered.push({name, props});
32
+ return null;
33
+ };
34
+
35
+ // Renders a host element with every prop, and the text-bearing props as children, so the text a
36
+ // screen shows through `text`, `title`, or `children` is readable from the tree.
37
+ const hostFake =
38
+ (name: string) =>
39
+ (props: Record<string, unknown>): ReactElement => {
40
+ const {children, text, title, ...rest} = props;
41
+ const parts = [title, text, children].filter(
42
+ (part) => part !== undefined && part !== null && part !== false
43
+ ) as ReactNode[];
44
+ return createElement(name, rest, ...parts);
45
+ };
46
+
47
+ // Like the real Box: a clickable Box renders its pressable as `${testID}-clickable`, so a test id
48
+ // promised on a clickable Box fails here the way it would in the app.
49
+ const boxFake = (props: Record<string, unknown>): ReactElement => {
50
+ const {onClick, testID} = props;
51
+ const resolved =
52
+ onClick !== undefined && typeof testID === "string"
53
+ ? {...props, testID: `${testID}-clickable`}
54
+ : props;
55
+ return hostFake("Box")(resolved);
56
+ };
57
+
58
+ // The preload's react-native stub has no Pressable; add one that renders a host element.
59
+ mock.module("react-native", () => ({
60
+ AppState: {
61
+ addEventListener: (): {remove: () => void} => ({remove: (): void => {}}),
62
+ currentState: "active",
63
+ },
64
+ Linking: {openURL: async (): Promise<boolean> => true},
65
+ Platform: {OS: "web"},
66
+ Pressable: hostFake("Pressable"),
67
+ StyleSheet: {create: (styles: unknown): unknown => styles},
68
+ }));
69
+
70
+ mock.module("@terreno/ui", () => ({
71
+ Badge: hostFake("Badge"),
72
+ Banner: hostFake("Banner"),
73
+ BooleanField: hostFake("BooleanField"),
74
+ Box: boxFake,
75
+ Button: hostFake("Button"),
76
+ Card: hostFake("Card"),
77
+ CheckBox: hostFake("CheckBox"),
78
+ ErrorPage: hostFake("ErrorPage"),
79
+ Heading: hostFake("Heading"),
80
+ Icon: hostFake("Icon"),
81
+ IconButton: hostFake("IconButton"),
82
+ Link: hostFake("Link"),
83
+ LoginScreen: recorder("LoginScreen"),
84
+ Page: hostFake("Page"),
85
+ Spinner: hostFake("Spinner"),
86
+ Text: hostFake("Text"),
87
+ TwoFactorChallengeScreen: recorder("TwoFactorChallengeScreen"),
88
+ }));
89
+
90
+ const {createBetterAuthClient} = await import("../auth/betterAuthClient");
91
+ const {createRememberedAccountsStore} = await import("../auth/rememberedAccounts");
92
+ const {createSessionStore} = await import("../auth/session");
93
+ const {SessionProvider} = await import("../auth/SessionProvider");
94
+ const {MCP_OAUTH_CONSENT_ERROR_COPY, TerrenoOAuthConsentScreen} = await import(
95
+ "../auth/TerrenoOAuthConsentScreen"
96
+ );
97
+
98
+ const HREF = "https://app.test/oauth/consent?request=abc";
99
+ const REQUEST_PATH = "/oauth/authorize/abc";
100
+ const REDIRECT_URL = "https://claude.ai/callback?code=granted";
101
+ const DENY_URL = "https://claude.ai/callback?error=access_denied";
102
+
103
+ const METHODS: BetterAuthMethods = {
104
+ accountLinking: {mode: "verified-email"},
105
+ emailPassword: true,
106
+ multiSession: false,
107
+ passkey: false,
108
+ providers: ["google", "github"],
109
+ signUp: true,
110
+ twoFactor: true,
111
+ };
112
+
113
+ const JANE: LoginUser = {email: "jane@example.com", id: "u1", name: "Jane"};
114
+ const JANE_SESSION = {user: JANE as unknown as BetterAuthUser, userId: "u1"};
115
+
116
+ const CONSENT = {
117
+ clientId: "client-1",
118
+ clientName: "Claude" as string | null,
119
+ expiresAt: "2026-11-16T12:00:00.000Z",
120
+ grants: [
121
+ {access: "read" as const, description: "See your todos", label: "Read", scope: "mcp:read"},
122
+ {access: "write" as const, description: null, label: "Write", scope: "mcp:write"},
123
+ ],
124
+ redirectHost: "claude.ai",
125
+ redirectUri: "https://claude.ai/callback",
126
+ requestId: "abc",
127
+ resource: "https://api.test/mcp",
128
+ scope: "mcp:read mcp:write",
129
+ };
130
+
131
+ interface Calls {
132
+ fetches: Array<{body: unknown; method: string; path: string}>;
133
+ redirects: string[];
134
+ refresh: ReturnType<typeof mock>;
135
+ social: Array<Record<string, unknown>>;
136
+ assign: ReturnType<typeof mock>;
137
+ }
138
+
139
+ interface Setup {
140
+ consent?: typeof CONSENT;
141
+ getStatus?: number;
142
+ signedIn?: boolean;
143
+ requestId?: string;
144
+ search?: string;
145
+ testID?: string;
146
+ grantLabels?: Record<string, {label: string; description?: string}>;
147
+ loginProps?: Record<string, unknown>;
148
+ webAuth?: "cookie" | "bearer";
149
+ client?: LoginControllerClient;
150
+ methods?: BetterAuthMethods;
151
+ }
152
+
153
+ const json = (status: number, body: unknown): Response =>
154
+ new Response(JSON.stringify(body), {
155
+ headers: {"Content-Type": "application/json"},
156
+ status,
157
+ });
158
+
159
+ const memoryStorage = (): Record<string, unknown> => {
160
+ const values = new Map<string, string>();
161
+ return {
162
+ getItem: (key: string): string | null => values.get(key) ?? null,
163
+ removeItem: (key: string): void => {
164
+ values.delete(key);
165
+ },
166
+ setItem: (key: string, value: string): void => {
167
+ values.set(key, value);
168
+ },
169
+ };
170
+ };
171
+
172
+ const memoryRemembered = (): ReturnType<typeof createRememberedAccountsStore> =>
173
+ createRememberedAccountsStore({
174
+ rememberIdentity: false,
175
+ storage: memoryStorage() as never,
176
+ });
177
+
178
+ const globalWithWindow = globalThis as unknown as {window?: unknown};
179
+ const originalFetch = globalThis.fetch;
180
+
181
+ const leaves = (node: ReactTestInstance): string[] =>
182
+ node.children.flatMap((child) => (typeof child === "string" ? [child] : leaves(child)));
183
+
184
+ describe("TerrenoOAuthConsentScreen", () => {
185
+ let renderer: ReactTestRenderer | undefined;
186
+ let calls: Calls;
187
+ // Whether the fake auth server holds a session; sign-in calls flip it.
188
+ let isSignedInOnServer = false;
189
+
190
+ const hostsWithTestId = (id: string): ReactTestInstance[] =>
191
+ renderer?.root.findAll((node) => typeof node.type === "string" && node.props.testID === id) ??
192
+ [];
193
+ const byId = (id: string): ReactTestInstance => {
194
+ const [node] = hostsWithTestId(id);
195
+ if (!node) {
196
+ throw new Error(`No element with testID ${id}`);
197
+ }
198
+ return node;
199
+ };
200
+ const hasId = (id: string): boolean => hostsWithTestId(id).length > 0;
201
+ const family = (node: ReactTestInstance): ReactTestInstance[] => [
202
+ node,
203
+ ...node.findAll((child) => typeof child.type === "string" && child !== node),
204
+ ];
205
+ const checkedOf = (node: ReactTestInstance): boolean | undefined => {
206
+ for (const member of family(node)) {
207
+ for (const key of ["selected", "value", "checked", "isChecked", "isSelected"]) {
208
+ if (typeof member.props[key] === "boolean") {
209
+ return member.props[key] as boolean;
210
+ }
211
+ }
212
+ }
213
+ return undefined;
214
+ };
215
+ const isDisabled = (node: ReactTestInstance): boolean =>
216
+ family(node).some((member) => member.props.disabled === true);
217
+ const handlerOf = (node: ReactTestInstance): ((...args: unknown[]) => unknown) => {
218
+ for (const member of family(node)) {
219
+ for (const key of ["onClick", "onPress", "onChange", "onValueChange"]) {
220
+ if (typeof member.props[key] === "function") {
221
+ return member.props[key] as (...args: unknown[]) => unknown;
222
+ }
223
+ }
224
+ }
225
+ throw new Error("Element has no press handler");
226
+ };
227
+ const press = async (id: string, ...args: unknown[]): Promise<void> => {
228
+ const node = byId(id);
229
+ const checked = checkedOf(node);
230
+ await act(async () => {
231
+ await handlerOf(node)(
232
+ ...(args.length ? args : [checked === undefined ? undefined : !checked])
233
+ );
234
+ });
235
+ await flush();
236
+ };
237
+ const lastRecorded = (name: string): Record<string, unknown> => {
238
+ const props = rendered.filter((entry) => entry.name === name).at(-1)?.props;
239
+ if (!props) {
240
+ throw new Error(`${name} never rendered`);
241
+ }
242
+ return props;
243
+ };
244
+ const flush = async (): Promise<void> => {
245
+ for (let index = 0; index < 10; index += 1) {
246
+ await act(async () => {
247
+ await Promise.resolve();
248
+ });
249
+ }
250
+ };
251
+
252
+ const fakeClient = (methods: BetterAuthMethods): LoginControllerClient => ({
253
+ $fetch: async () => ({data: methods, error: null}),
254
+ getSession: async () =>
255
+ isSignedInOnServer
256
+ ? ({data: {session: {}, user: JANE}, error: null} as never)
257
+ : {data: null, error: null},
258
+ signIn: {
259
+ email: async () => {
260
+ isSignedInOnServer = true;
261
+ return {data: {user: JANE}, error: null} as never;
262
+ },
263
+ passkey: async () => ({data: null, error: null}),
264
+ social: async (options) => {
265
+ calls.social.push(options as Record<string, unknown>);
266
+ return {data: {redirect: false}, error: null} as never;
267
+ },
268
+ },
269
+ twoFactor: {
270
+ verifyBackupCode: async () => ({data: {user: JANE}, error: null}),
271
+ verifyTotp: async () => {
272
+ isSignedInOnServer = true;
273
+ return {data: {user: JANE}, error: null} as never;
274
+ },
275
+ },
276
+ });
277
+
278
+ const mount = async (setup: Setup = {}): Promise<void> => {
279
+ const consent = setup.consent ?? CONSENT;
280
+ const fetchImpl: FetchLike = async (input, init) => {
281
+ const method = init?.method ?? "GET";
282
+ const path = new URL(input).pathname;
283
+ calls.fetches.push({
284
+ body: init?.body ? JSON.parse(String(init.body)) : undefined,
285
+ method,
286
+ path,
287
+ });
288
+ if (method === "GET") {
289
+ const status = setup.getStatus ?? 200;
290
+ return status === 200 ? json(200, {data: consent}) : json(status, {title: "failed"});
291
+ }
292
+ if (path.endsWith("/approve")) {
293
+ return json(200, {data: {redirectUrl: REDIRECT_URL}});
294
+ }
295
+ return json(200, {data: {redirectUrl: DENY_URL}});
296
+ };
297
+ const apiClient = createApiClient({baseUrl: "http://api.test", fetchImpl});
298
+ isSignedInOnServer = Boolean(setup.signedIn);
299
+ const store = createSessionStore({
300
+ initialSession: setup.signedIn ? JANE_SESSION : null,
301
+ pollIntervalMs: 0,
302
+ source: {
303
+ getSession: async () => (isSignedInOnServer ? JANE_SESSION : null),
304
+ signOut: async () => {},
305
+ },
306
+ });
307
+ const realRefresh = store.refresh;
308
+ calls.refresh = mock(() => realRefresh());
309
+ store.refresh = calls.refresh as never;
310
+
311
+ const loginProps = {
312
+ client: setup.client ?? fakeClient(setup.methods ?? METHODS),
313
+ rememberedAccounts: memoryRemembered(),
314
+ webAuth: setup.webAuth ?? "cookie",
315
+ ...setup.loginProps,
316
+ };
317
+ await act(async () => {
318
+ renderer = create(
319
+ <SessionProvider store={store}>
320
+ <ApiClientProvider client={apiClient}>
321
+ <TerrenoOAuthConsentScreen
322
+ grantLabels={setup.grantLabels}
323
+ loginProps={loginProps as never}
324
+ onRedirect={(url: string) => calls.redirects.push(url)}
325
+ requestId={setup.requestId}
326
+ testID={setup.testID}
327
+ />
328
+ </ApiClientProvider>
329
+ </SessionProvider>
330
+ );
331
+ });
332
+ await flush();
333
+ };
334
+
335
+ beforeEach(() => {
336
+ rendered.length = 0;
337
+ calls = {
338
+ assign: mock((_url: string) => {}),
339
+ fetches: [],
340
+ redirects: [],
341
+ refresh: mock(() => Promise.resolve()),
342
+ social: [],
343
+ };
344
+ globalWithWindow.window = {
345
+ localStorage: memoryStorage(),
346
+ location: {assign: calls.assign, href: HREF, search: "?request=abc"},
347
+ sessionStorage: memoryStorage(),
348
+ };
349
+ });
350
+
351
+ afterEach(() => {
352
+ act(() => renderer?.unmount());
353
+ renderer = undefined;
354
+ globalThis.fetch = originalFetch;
355
+ delete globalWithWindow.window;
356
+ });
357
+
358
+ describe("MCP_OAUTH_CONSENT_ERROR_COPY", () => {
359
+ it("holds the exact title and message for all six error kinds", () => {
360
+ expect(MCP_OAUTH_CONSENT_ERROR_COPY).toEqual({
361
+ decided: {
362
+ message:
363
+ "This request was already approved or denied. Start the connection again from your app.",
364
+ title: "Request already decided",
365
+ },
366
+ expired: {
367
+ message: "Authorization requests expire after a few minutes. Start the connection again.",
368
+ title: "Request expired",
369
+ },
370
+ missingRequest: {
371
+ message:
372
+ "This link has no authorization request. Start the connection again from your app.",
373
+ title: "Missing authorization request",
374
+ },
375
+ notFound: {
376
+ message: "This authorization request does not exist. Check the link or start again.",
377
+ title: "Request not found",
378
+ },
379
+ signedOut: {
380
+ message: "Your session ended, or this browser cannot decide this request. Sign in again.",
381
+ title: "Sign in required",
382
+ },
383
+ unknown: {
384
+ message: "Something went wrong loading or deciding this request. Try again.",
385
+ title: "Could not complete the request",
386
+ },
387
+ });
388
+ });
389
+ });
390
+
391
+ describe("signed out", () => {
392
+ it("renders the login screen with loginProps.methods applied and no consent card", async () => {
393
+ await mount({
394
+ loginProps: {methods: {providers: ["google"]}},
395
+ methods: {...METHODS, providers: ["google", "github", "apple"]},
396
+ });
397
+ const login = lastRecorded("LoginScreen");
398
+ expect(
399
+ (login.oauthProviders as Array<{provider: string}>).map(({provider}) => provider)
400
+ ).toEqual(["google"]);
401
+ expect(hasId("oauth-consent-client-name")).toBe(false);
402
+ expect(hasId("oauth-consent-approve-button")).toBe(false);
403
+ expect(calls.fetches).toEqual([]);
404
+ });
405
+
406
+ it("passes loginProps title through to the login screen", async () => {
407
+ await mount({loginProps: {title: "Sign in to connect"}});
408
+ expect(lastRecorded("LoginScreen").title).toBe("Sign in to connect");
409
+ });
410
+
411
+ it("signs in inline: refresh once, then the consent card renders", async () => {
412
+ await mount();
413
+ const login = lastRecorded("LoginScreen");
414
+ await act(async () => {
415
+ await (login.onSubmit as (values: Record<string, string>) => Promise<void>)({
416
+ email: "jane@example.com",
417
+ password: "pw",
418
+ });
419
+ });
420
+ await flush();
421
+ expect(calls.refresh).toHaveBeenCalledTimes(1);
422
+ expect(hasId("oauth-consent-client-name")).toBe(true);
423
+ expect(leaves(byId("oauth-consent-client-name"))).toContain("Claude");
424
+ expect(calls.assign).not.toHaveBeenCalled();
425
+ expect(calls.redirects).toEqual([]);
426
+ });
427
+
428
+ it("shows the two-factor challenge inline, then the consent card, with no navigation", async () => {
429
+ const client = fakeClient(METHODS);
430
+ client.signIn.email = (async () => ({
431
+ data: {twoFactorMethods: ["totp"], twoFactorRedirect: true},
432
+ error: null,
433
+ })) as never;
434
+ await mount({client});
435
+ const login = lastRecorded("LoginScreen");
436
+ await act(async () => {
437
+ await (login.onSubmit as (values: Record<string, string>) => Promise<void>)({
438
+ email: "jane@example.com",
439
+ password: "pw",
440
+ });
441
+ });
442
+ await flush();
443
+ const challenge = lastRecorded("TwoFactorChallengeScreen");
444
+ expect(hasId("oauth-consent-client-name")).toBe(false);
445
+
446
+ await act(async () => {
447
+ await (challenge.onSubmit as (values: unknown) => Promise<void>)({
448
+ code: "123456",
449
+ kind: "totp",
450
+ trustDevice: false,
451
+ });
452
+ });
453
+ await flush();
454
+ expect(calls.refresh).toHaveBeenCalledTimes(1);
455
+ expect(hasId("oauth-consent-client-name")).toBe(true);
456
+ expect(calls.assign).not.toHaveBeenCalled();
457
+ expect(calls.redirects).toEqual([]);
458
+ });
459
+
460
+ it("defaults the social callbackURL to the current href including ?request=abc", async () => {
461
+ await mount();
462
+ const login = lastRecorded("LoginScreen");
463
+ await act(async () => {
464
+ await (login.oauthProviders as Array<{onPress: () => Promise<void>}>)[0].onPress();
465
+ });
466
+ expect(calls.social).toHaveLength(1);
467
+ expect(calls.social[0].callbackURL).toBe(HREF);
468
+ });
469
+
470
+ it("defaults the callbackURL to the href in bearer mode too", async () => {
471
+ globalThis.fetch = (async (input: string | URL | Request): Promise<Response> => {
472
+ const url = input instanceof Request ? input.url : String(input);
473
+ return url.includes("/terreno/methods") ? Response.json(METHODS) : Response.json(null);
474
+ }) as typeof fetch;
475
+ const client = createBetterAuthClient({
476
+ baseURL: "http://api.test",
477
+ features: {twoFactor: true},
478
+ scheme: "terreno",
479
+ webAuth: "bearer",
480
+ });
481
+ await mount({client: client as never, webAuth: "bearer"});
482
+ const login = lastRecorded("LoginScreen");
483
+ await act(async () => {
484
+ await (login.oauthProviders as Array<{onPress: () => Promise<void>}>)[0].onPress();
485
+ });
486
+ const started = new URL(calls.assign.mock.calls[0][0] as string);
487
+ expect(started.pathname).toBe("/api/auth/oauth-handoff/start");
488
+ const callback = new URL(started.searchParams.get("callbackURL") ?? "");
489
+ expect(callback.pathname).toBe("/oauth/consent");
490
+ // The handoff adds its own `handoff` nonce; `request` must survive.
491
+ expect(callback.searchParams.get("request")).toBe("abc");
492
+ });
493
+
494
+ it("passes loginProps.callbackURL through unchanged", async () => {
495
+ await mount({loginProps: {callbackURL: "/custom/return?x=1"}});
496
+ const login = lastRecorded("LoginScreen");
497
+ await act(async () => {
498
+ await (login.oauthProviders as Array<{onPress: () => Promise<void>}>)[0].onPress();
499
+ });
500
+ expect(calls.social[0].callbackURL).toBe("/custom/return?x=1");
501
+ });
502
+ });
503
+
504
+ describe("signed in", () => {
505
+ it("shows the screen root, client name, redirect host, signed-in email, and both buttons", async () => {
506
+ await mount({signedIn: true});
507
+ expect(hasId("oauth-consent-screen")).toBe(true);
508
+ expect(leaves(byId("oauth-consent-client-name"))).toContain("Claude");
509
+ expect(leaves(byId("oauth-consent-screen")).join(" ")).toContain("claude.ai");
510
+ expect(leaves(byId("oauth-consent-signed-in-as")).join(" ")).toContain("jane@example.com");
511
+ expect(hasId("oauth-consent-approve-button")).toBe(true);
512
+ expect(hasId("oauth-consent-deny-button")).toBe(true);
513
+ expect(hasId("oauth-consent-error")).toBe(false);
514
+ expect(calls.fetches[0]).toMatchObject({method: "GET", path: REQUEST_PATH});
515
+ });
516
+
517
+ it("shows 2 checked checkboxes with the server labels", async () => {
518
+ await mount({signedIn: true});
519
+ const read = byId("oauth-consent-grant-mcp:read");
520
+ const write = byId("oauth-consent-grant-mcp:write");
521
+ expect(checkedOf(read)).toBe(true);
522
+ expect(checkedOf(write)).toBe(true);
523
+ expect(leaves(read)).toContain("Read");
524
+ expect(leaves(read)).toContain("See your todos");
525
+ expect(leaves(write)).toContain("Write");
526
+ });
527
+
528
+ it("shows the grantLabels override instead of the server label", async () => {
529
+ await mount({
530
+ grantLabels: {"mcp:read": {description: "Look at todos", label: "View todos"}},
531
+ signedIn: true,
532
+ });
533
+ const read = leaves(byId("oauth-consent-grant-mcp:read"));
534
+ expect(read).toContain("View todos");
535
+ expect(read).toContain("Look at todos");
536
+ expect(read).not.toContain("Read");
537
+ expect(leaves(byId("oauth-consent-grant-mcp:write"))).toContain("Write");
538
+ });
539
+
540
+ it("disables Approve when both grants are unchecked", async () => {
541
+ await mount({signedIn: true});
542
+ expect(isDisabled(byId("oauth-consent-approve-button"))).toBe(false);
543
+ await press("oauth-consent-grant-mcp:read");
544
+ await press("oauth-consent-grant-mcp:write");
545
+ expect(checkedOf(byId("oauth-consent-grant-mcp:read"))).toBe(false);
546
+ expect(checkedOf(byId("oauth-consent-grant-mcp:write"))).toBe(false);
547
+ expect(isDisabled(byId("oauth-consent-approve-button"))).toBe(true);
548
+ });
549
+
550
+ it("Approve calls onRedirect with the server URL", async () => {
551
+ await mount({signedIn: true});
552
+ await press("oauth-consent-approve-button");
553
+ expect(calls.redirects).toEqual([REDIRECT_URL]);
554
+ expect(calls.fetches.find((call) => call.method === "POST")).toMatchObject({
555
+ body: {scope: "mcp:read mcp:write"},
556
+ path: `${REQUEST_PATH}/approve`,
557
+ });
558
+ });
559
+
560
+ it("Approve after unchecking one grant narrows the approved scope", async () => {
561
+ await mount({signedIn: true});
562
+ await press("oauth-consent-grant-mcp:write");
563
+ await press("oauth-consent-approve-button");
564
+ expect(calls.fetches.find((call) => call.method === "POST")?.body).toEqual({
565
+ scope: "mcp:read",
566
+ });
567
+ expect(calls.redirects).toEqual([REDIRECT_URL]);
568
+ });
569
+
570
+ it("Deny calls onRedirect with the deny URL", async () => {
571
+ await mount({signedIn: true});
572
+ await press("oauth-consent-deny-button");
573
+ expect(calls.redirects).toEqual([DENY_URL]);
574
+ expect(calls.fetches.find((call) => call.method === "POST")?.path).toBe(
575
+ `${REQUEST_PATH}/deny`
576
+ );
577
+ });
578
+
579
+ it("shows 'An unnamed MCP client' when clientName is null", async () => {
580
+ await mount({consent: {...CONSENT, clientName: null}, signedIn: true});
581
+ expect(leaves(byId("oauth-consent-client-name"))).toContain("An unnamed MCP client");
582
+ });
583
+
584
+ it("uses an explicit requestId prop over the URL", async () => {
585
+ await mount({requestId: "other", signedIn: true});
586
+ expect(calls.fetches[0].path).toBe("/oauth/authorize/other");
587
+ });
588
+
589
+ it("prefixes every test id with a custom testID", async () => {
590
+ await mount({signedIn: true, testID: "connect"});
591
+ for (const id of [
592
+ "connect-screen",
593
+ "connect-client-name",
594
+ "connect-grant-mcp:read",
595
+ "connect-approve-button",
596
+ "connect-deny-button",
597
+ "connect-signed-in-as",
598
+ ]) {
599
+ expect(hasId(id)).toBe(true);
600
+ }
601
+ });
602
+ });
603
+
604
+ describe("errors", () => {
605
+ const cases: Array<{kind: keyof typeof MCP_OAUTH_CONSENT_ERROR_COPY; setup: Setup}> = [
606
+ {kind: "missingRequest", setup: {}},
607
+ {kind: "notFound", setup: {getStatus: 404}},
608
+ {kind: "decided", setup: {getStatus: 409}},
609
+ {kind: "expired", setup: {getStatus: 400}},
610
+ {kind: "signedOut", setup: {getStatus: 401}},
611
+ {kind: "unknown", setup: {getStatus: 500}},
612
+ ];
613
+
614
+ for (const {kind, setup} of cases) {
615
+ it(`${kind} shows its exact title and message in oauth-consent-error`, async () => {
616
+ if (kind === "missingRequest") {
617
+ // No ?request= in the URL and no requestId prop.
618
+ (globalWithWindow.window as {location: {href: string; search: string}}).location.href =
619
+ "https://app.test/oauth/consent";
620
+ (globalWithWindow.window as {location: {search: string}}).location.search = "";
621
+ }
622
+ await mount({...setup, signedIn: true});
623
+ const copy = MCP_OAUTH_CONSENT_ERROR_COPY[kind];
624
+ const shown = leaves(byId("oauth-consent-error"));
625
+ expect(shown).toContain(copy.title);
626
+ expect(shown).toContain(copy.message);
627
+ expect(hasId("oauth-consent-approve-button")).toBe(false);
628
+ });
629
+ }
630
+
631
+ it("missingRequest makes no consent request", async () => {
632
+ (globalWithWindow.window as {location: {search: string}}).location.search = "";
633
+ await mount({signedIn: true});
634
+ expect(calls.fetches).toEqual([]);
635
+ });
636
+ });
637
+ });