Repository navigation
Expand file tree
/
Copy pathauthBootstrap.test.ts
More file actions
398 lines (361 loc) · 13.9 KB
/
Copy pathauthBootstrap.test.ts
File metadata and controls
398 lines (361 loc) · 13.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
import {
EnvironmentAuthInvalidError,
type AuthBrowserSessionResult,
type AuthCreatePairingCredentialInput,
type AuthSessionState,
type DesktopBridge,
} from "@t3tools/contracts";
import { createBrowserHistory } from "@tanstack/react-router";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import { installEnvironmentHttpTest } from "../test/environmentHttpTest";
import { __setPrimaryHttpRunnerForTests } from "./lib/runtime";
type TestWindow = {
location: URL;
history: {
state: unknown;
replaceState: (_data: unknown, _unused: string, url?: string) => void;
};
desktopBridge?: DesktopBridge;
};
const LOOPBACK_AUTH = {
policy: "loopback-browser",
bootstrapMethods: ["one-time-token"],
sessionMethods: ["browser-session-cookie"],
sessionCookieName: "t3_session",
} as const;
const DESKTOP_AUTH = {
policy: "desktop-managed-local",
bootstrapMethods: ["desktop-bootstrap"],
sessionMethods: ["browser-session-cookie"],
sessionCookieName: "t3_session",
} as const;
const SESSION_EXPIRES_AT = DateTime.makeUnsafe("2026-04-05T00:00:00.000Z");
const unauthenticatedSession = (auth: AuthSessionState["auth"]): AuthSessionState => ({
authenticated: false,
auth,
});
const authenticatedSession = (auth: AuthSessionState["auth"]): AuthSessionState => ({
authenticated: true,
auth,
sessionMethod: "browser-session-cookie",
expiresAt: SESSION_EXPIRES_AT,
});
const browserSession = (scopes: AuthBrowserSessionResult["scopes"]): AuthBrowserSessionResult => ({
authenticated: true,
scopes,
sessionMethod: "browser-session-cookie",
expiresAt: SESSION_EXPIRES_AT,
});
function installTestBrowser(url: string) {
const testWindow: TestWindow = {
location: new URL(url),
history: {
state: null,
replaceState: (data, _unused, nextUrl) => {
testWindow.history.state = data;
if (nextUrl !== undefined) {
testWindow.location = new URL(nextUrl, testWindow.location.href);
}
},
},
};
vi.stubGlobal("window", testWindow);
vi.stubGlobal("document", { title: "T3 Code" });
return testWindow;
}
function sequence<A>(...values: ReadonlyArray<A>) {
let index = 0;
return () => values[Math.min(index++, values.length - 1)]!;
}
function createSignal() {
let resolve = () => {};
const promise = new Promise<void>((resolvePromise) => {
resolve = resolvePromise;
});
return { promise, resolve };
}
let disposeHttpTest: (() => Promise<void>) | undefined;
async function installAuthApi(input: {
readonly session?: () => AuthSessionState;
readonly browserSession?: (
credential: string,
) => Effect.Effect<AuthBrowserSessionResult, EnvironmentAuthInvalidError>;
readonly pairingCredential?: (payload: AuthCreatePairingCredentialInput) => Effect.Effect<{
readonly id: string;
readonly credential: string;
readonly label?: string;
readonly expiresAt: DateTime.Utc;
}>;
}) {
const testApi = await installEnvironmentHttpTest({
...(input.session ? { session: () => Effect.succeed(input.session!()) } : {}),
...(input.browserSession
? { browserSession: (payload) => input.browserSession!(payload.credential) }
: {}),
...(input.pairingCredential
? { pairingCredential: (payload) => input.pairingCredential!(payload) }
: {}),
});
disposeHttpTest = testApi.dispose;
return testApi;
}
describe("resolveInitialServerAuthGateState", () => {
beforeEach(() => {
vi.restoreAllMocks();
vi.useRealTimers();
installTestBrowser("http://localhost/");
});
afterEach(async () => {
await disposeHttpTest?.();
disposeHttpTest = undefined;
const { __resetServerAuthBootstrapForTests } = await import("./environments/primary");
__resetServerAuthBootstrapForTests();
__setPrimaryHttpRunnerForTests();
vi.unstubAllEnvs();
vi.useRealTimers();
vi.restoreAllMocks();
});
it("reuses an in-flight silent bootstrap attempt", async () => {
const nextSession = sequence(
unauthenticatedSession(DESKTOP_AUTH),
authenticatedSession(DESKTOP_AUTH),
);
const testApi = await installAuthApi({
session: nextSession,
browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])),
});
const testWindow = installTestBrowser("http://localhost/");
testWindow.desktopBridge = {
getLocalEnvironmentBootstraps: () => [
{
id: "primary",
label: "Windows",
httpBaseUrl: "http://localhost:3773",
wsBaseUrl: "ws://localhost:3773",
bootstrapToken: "desktop-bootstrap-token",
},
],
} as unknown as DesktopBridge;
const { resolveInitialServerAuthGateState } = await import("./environments/primary");
await Promise.all([resolveInitialServerAuthGateState(), resolveInitialServerAuthGateState()]);
expect(testApi.calls.session).toBe(2);
expect(testApi.calls.browserSession).toEqual([{ credential: "desktop-bootstrap-token" }]);
});
it("takes a pairing token from the location hash and strips it immediately", async () => {
const testWindow = installTestBrowser("http://localhost/#token=pairing-token");
const { takePairingTokenFromUrl } = await import("./environments/primary");
expect(takePairingTokenFromUrl()).toBe("pairing-token");
expect(testWindow.location.hash).toBe("");
expect(testWindow.location.searchParams.get("token")).toBeNull();
});
it.each([
{ suffix: "#token=replacement-token", cached: false },
{ suffix: "#token=replacement-token", cached: true },
{ suffix: "?token=replacement-token", cached: true },
{ suffix: "/#token=replacement-token", cached: true },
])(
"re-pairs an authenticated browser with $suffix when cached=$cached",
async ({ suffix, cached }) => {
let scopes: AuthBrowserSessionResult["scopes"] = ["orchestration:read"];
const testApi = await installAuthApi({
session: () => ({ ...authenticatedSession(LOOPBACK_AUTH), scopes }),
browserSession: () =>
Effect.sync(() => {
scopes = ["orchestration:read", "orchestration:operate"];
return browserSession(scopes);
}),
});
const testWindow = installTestBrowser("http://localhost/");
const {
resolveInitialServerAuthGateState,
submitServerAuthCredential,
takePairingTokenFromUrl,
} = await import("./environments/primary");
const { fetchSessionState } = await import("./environments/primary/auth");
if (cached) {
await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
status: "authenticated",
});
}
testWindow.location = new URL(`http://localhost/pair${suffix}`);
await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
status: "requires-auth",
auth: LOOPBACK_AUTH,
});
expect(testApi.calls.browserSession).toEqual([]);
const token = takePairingTokenFromUrl();
expect(token).toBe("replacement-token");
await submitServerAuthCredential(token!);
expect(testApi.calls.browserSession).toEqual([{ credential: "replacement-token" }]);
await expect(fetchSessionState()).resolves.toMatchObject({
authenticated: true,
scopes: ["orchestration:read", "orchestration:operate"],
});
await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
status: "authenticated",
});
},
);
it.each([false, true])(
"keeps rejected replacement pairing open when cached=%s",
async (cached) => {
const existingSession = {
...authenticatedSession(LOOPBACK_AUTH),
scopes: ["orchestration:read"] as const,
};
const exchangeStarted = createSignal();
const finishExchange = createSignal();
const testApi = await installAuthApi({
session: () => existingSession,
browserSession: () =>
Effect.gen(function* () {
exchangeStarted.resolve();
yield* Effect.promise(() => finishExchange.promise);
return yield* new EnvironmentAuthInvalidError({
code: "auth_invalid",
reason: "invalid_credential",
traceId: "trace-invalid-replacement",
});
}),
});
const testWindow = installTestBrowser("http://localhost/");
const {
resolveInitialServerAuthGateState,
submitServerAuthCredential,
takePairingTokenFromUrl,
} = await import("./environments/primary");
const { fetchSessionState } = await import("./environments/primary/auth");
if (cached) {
await resolveInitialServerAuthGateState();
}
testWindow.location = new URL("http://localhost/pair#token=invalid-replacement");
const history = createBrowserHistory({
window: {
get location() {
return testWindow.location;
},
history: testWindow.history,
addEventListener() {},
removeEventListener() {},
},
});
const gateLoads: Array<ReturnType<typeof resolveInitialServerAuthGateState>> = [];
const unsubscribe = history.subscribe(() => {
gateLoads.push(resolveInitialServerAuthGateState());
});
try {
const requiresAuth = { status: "requires-auth", auth: LOOPBACK_AUTH };
await expect(resolveInitialServerAuthGateState()).resolves.toEqual(requiresAuth);
// Token removal synchronously reloads the TanStack auth gate via replaceState.
const token = takePairingTokenFromUrl();
expect(gateLoads).toHaveLength(1);
await expect(gateLoads[0]).resolves.toEqual(requiresAuth);
const rejected = expect(submitServerAuthCredential(token!)).rejects.toMatchObject({
_tag: "PrimaryEnvironmentPairingCredentialRejectedError",
message: "Invalid pairing token. Check the token and try again.",
});
await exchangeStarted.promise;
await expect(resolveInitialServerAuthGateState()).resolves.toEqual(requiresAuth);
finishExchange.resolve();
await rejected;
await expect(resolveInitialServerAuthGateState()).resolves.toEqual(requiresAuth);
expect(testApi.calls.browserSession).toEqual([{ credential: "invalid-replacement" }]);
await expect(fetchSessionState()).resolves.toEqual(existingSession);
testWindow.history.replaceState({}, "", "/");
await expect(gateLoads[1]).resolves.toEqual({ status: "authenticated" });
testWindow.history.replaceState({}, "", "/pair");
await expect(gateLoads[2]).resolves.toEqual({ status: "authenticated" });
} finally {
finishExchange.resolve();
unsubscribe();
history.destroy();
}
},
);
it("makes later callers wait for a URL token that arrives during bootstrap", async () => {
let releaseExchange!: () => void;
const exchangeRelease = new Promise<void>((resolve) => {
releaseExchange = resolve;
});
let markExchangeStarted!: () => void;
const exchangeStarted = new Promise<void>((resolve) => {
markExchangeStarted = resolve;
});
const nextSession = sequence(
authenticatedSession(LOOPBACK_AUTH),
authenticatedSession(LOOPBACK_AUTH),
);
const testApi = await installAuthApi({
session: nextSession,
browserSession: () => {
markExchangeStarted();
return Effect.promise(() => exchangeRelease).pipe(
Effect.andThen(
Effect.fail(
new EnvironmentAuthInvalidError({
code: "auth_invalid",
reason: "invalid_credential",
traceId: "trace-rejected-queued-credential",
}),
),
),
);
},
});
const testWindow = installTestBrowser("http://localhost/");
const { resolveInitialServerAuthGateState } = await import("./environments/primary");
const initialBootstrap = resolveInitialServerAuthGateState();
testWindow.location = new URL("http://localhost/#token=reusable-token");
const explicitPairing = resolveInitialServerAuthGateState();
const laterCaller = resolveInitialServerAuthGateState();
let laterCallerSettled = false;
void laterCaller.then(() => {
laterCallerSettled = true;
});
try {
await expect(initialBootstrap).resolves.toEqual({ status: "authenticated" });
await exchangeStarted;
expect(laterCallerSettled).toBe(false);
} finally {
releaseExchange();
}
const rejectedState = {
status: "requires-auth",
auth: LOOPBACK_AUTH,
errorMessage: "Invalid pairing token. Check the token and try again.",
} as const;
await expect(explicitPairing).resolves.toEqual(rejectedState);
await expect(laterCaller).resolves.toEqual(rejectedState);
expect(testApi.calls.browserSession).toEqual([{ credential: "reusable-token" }]);
expect(testApi.calls.session).toBe(2);
});
it("reports a rejected URL token without caching false success", async () => {
const cause = new EnvironmentAuthInvalidError({
code: "auth_invalid",
reason: "invalid_credential",
traceId: "trace-invalid-url-credential",
});
const nextSession = sequence(
authenticatedSession(LOOPBACK_AUTH),
unauthenticatedSession(LOOPBACK_AUTH),
);
const testApi = await installAuthApi({
session: nextSession,
browserSession: () => Effect.fail(cause),
});
installTestBrowser("http://localhost/#token=rejected-token");
const { resolveInitialServerAuthGateState } = await import("./environments/primary");
await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
status: "requires-auth",
auth: LOOPBACK_AUTH,
errorMessage: "Invalid pairing token. Check the token and try again.",
});
await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
status: "requires-auth",
auth: LOOPBACK_AUTH,
});
expect(testApi.calls.browserSession).toEqual([{ credential: "rejected-token" }]);
});
});