zitejs 0.10.0-start.21 → 0.10.0-start.22

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 (112) hide show
  1. package/dist/cjs/auth/client.d.ts +2 -2
  2. package/dist/cjs/check/start/sourceRules.js +3 -0
  3. package/dist/cjs/cli.js +6 -0
  4. package/dist/cjs/dev/index.js +15 -0
  5. package/dist/cjs/dev/signin.d.ts +16 -0
  6. package/dist/cjs/dev/signin.js +76 -0
  7. package/dist/cjs/internal/appMode.d.ts +11 -0
  8. package/dist/cjs/internal/appMode.js +4 -1
  9. package/dist/cjs/internal/appToken.d.ts +17 -0
  10. package/dist/cjs/internal/appToken.js +26 -0
  11. package/dist/cjs/internal/platformFetch.d.ts +2 -0
  12. package/dist/cjs/internal/platformFetch.js +13 -0
  13. package/dist/cjs/internal/serviceUrls.d.ts +7 -0
  14. package/dist/cjs/internal/serviceUrls.js +16 -0
  15. package/dist/cjs/runtime/index.d.ts +1 -1
  16. package/dist/cjs/start/aiUsage.d.ts +23 -0
  17. package/dist/cjs/start/aiUsage.js +151 -0
  18. package/dist/cjs/start/devApp.d.ts +1 -0
  19. package/dist/cjs/start/devApp.js +6 -0
  20. package/dist/cjs/start/entries.js +4 -0
  21. package/dist/cjs/start/provider.d.ts +24 -0
  22. package/dist/cjs/start/provider.js +159 -0
  23. package/dist/cjs/start/types.d.ts +320 -0
  24. package/dist/cjs/start/types.js +2 -0
  25. package/dist/cjs/upload/index.js +73 -22
  26. package/dist/cjs/upload/index.test.js +35 -2
  27. package/dist/esm/auth/client.d.ts +2 -2
  28. package/dist/esm/check/start/sourceRules.js +3 -0
  29. package/dist/esm/cli.js +6 -0
  30. package/dist/esm/dev/index.js +15 -0
  31. package/dist/esm/dev/signin.d.ts +16 -0
  32. package/dist/esm/dev/signin.js +72 -0
  33. package/dist/esm/internal/appMode.d.ts +11 -0
  34. package/dist/esm/internal/appMode.js +2 -0
  35. package/dist/esm/internal/appToken.d.ts +17 -0
  36. package/dist/esm/internal/appToken.js +22 -0
  37. package/dist/esm/internal/platformFetch.d.ts +2 -0
  38. package/dist/esm/internal/platformFetch.js +8 -0
  39. package/dist/esm/internal/serviceUrls.d.ts +7 -0
  40. package/dist/esm/internal/serviceUrls.js +12 -0
  41. package/dist/esm/runtime/index.d.ts +1 -1
  42. package/dist/esm/signin/conformance.d.ts +100 -0
  43. package/dist/esm/signin/conformance.js +471 -0
  44. package/dist/esm/signin/cookies.d.ts +28 -0
  45. package/dist/esm/signin/cookies.js +59 -0
  46. package/dist/esm/signin/encoding.d.ts +9 -0
  47. package/dist/esm/signin/encoding.js +39 -0
  48. package/dist/esm/signin/endpoints.d.ts +12 -0
  49. package/dist/esm/signin/endpoints.js +29 -0
  50. package/dist/esm/signin/http.d.ts +25 -0
  51. package/dist/esm/signin/http.js +69 -0
  52. package/dist/esm/signin/index.d.ts +8 -0
  53. package/dist/esm/signin/index.js +9 -0
  54. package/dist/esm/signin/keys.d.ts +39 -0
  55. package/dist/esm/signin/keys.js +80 -0
  56. package/dist/esm/signin/paths.d.ts +2 -0
  57. package/dist/esm/signin/paths.js +2 -0
  58. package/dist/esm/signin/seal.d.ts +8 -0
  59. package/dist/esm/signin/seal.js +35 -0
  60. package/dist/esm/signin/signin.d.ts +60 -0
  61. package/dist/esm/signin/signin.js +340 -0
  62. package/dist/esm/signin/transport.d.ts +111 -0
  63. package/dist/esm/signin/transport.js +1 -0
  64. package/dist/esm/signin/verify.d.ts +77 -0
  65. package/dist/esm/signin/verify.js +155 -0
  66. package/dist/esm/start/airtable/index.d.ts +1 -1
  67. package/dist/esm/start/analytics.d.ts +5 -0
  68. package/dist/esm/start/analytics.js +77 -0
  69. package/dist/esm/start/data/index.d.ts +3 -3
  70. package/dist/esm/start/data/index.js +1 -1
  71. package/dist/esm/start/devApp.d.ts +1 -0
  72. package/dist/esm/start/devApp.js +3 -0
  73. package/dist/esm/start/devSignIn.d.ts +1 -0
  74. package/dist/esm/start/devSignIn.js +3 -0
  75. package/dist/esm/start/direct.d.ts +40 -0
  76. package/dist/esm/start/direct.js +313 -0
  77. package/dist/esm/start/entries.js +4 -0
  78. package/dist/esm/start/fetch.d.ts +1 -0
  79. package/dist/esm/start/fetch.js +4 -0
  80. package/dist/esm/start/instance.js +6 -2
  81. package/dist/esm/start/localSignIn.d.ts +18 -0
  82. package/dist/esm/start/localSignIn.js +73 -0
  83. package/dist/esm/start/outbound.d.ts +10 -1
  84. package/dist/esm/start/outbound.js +132 -22
  85. package/dist/esm/start/pageHead.d.ts +36 -0
  86. package/dist/esm/start/pageHead.js +178 -0
  87. package/dist/esm/start/provider.d.ts +24 -0
  88. package/dist/esm/start/provider.js +150 -0
  89. package/dist/esm/start/router.d.ts +6 -2
  90. package/dist/esm/start/router.js +41 -2
  91. package/dist/esm/start/server.d.ts +13 -6
  92. package/dist/esm/start/server.js +173 -42
  93. package/dist/esm/start/telemetry.d.ts +10 -0
  94. package/dist/esm/start/telemetry.js +74 -0
  95. package/dist/esm/start/types.d.ts +117 -2
  96. package/dist/esm/start/uploads.d.ts +2 -0
  97. package/dist/esm/start/uploads.js +52 -0
  98. package/dist/esm/start/version.d.ts +1 -1
  99. package/dist/esm/start/version.js +1 -1
  100. package/dist/esm/start/vite.d.ts +12 -1
  101. package/dist/esm/start/vite.js +116 -4
  102. package/dist/esm/start/workspaceSchema.d.ts +1 -0
  103. package/dist/esm/start/workspaceSchema.js +3 -0
  104. package/dist/esm/upload/index.js +74 -23
  105. package/dist/esm/upload/index.test.js +35 -2
  106. package/package.json +21 -11
  107. package/dist/cjs/auth-server/index.d.ts +0 -369
  108. package/dist/cjs/auth-server/index.js +0 -119
  109. package/dist/esm/auth-server/index.d.ts +0 -369
  110. package/dist/esm/auth-server/index.js +0 -116
  111. package/dist/esm/start/problems.d.ts +0 -19
  112. package/dist/esm/start/problems.js +0 -8
@@ -0,0 +1,471 @@
1
+ // `zitejs/signin/conformance`: the sign-in scenarios (T5 design §9), for tests only. One list drives two runners:
2
+ // zitejs's, with the module mounted in the Node fixture against a fake issuer, and restly's, with the dispatcher and
3
+ // the real identity Worker. No dependencies, so either can import it.
4
+ /** A cookie jar per host and manual redirects: enough of a browser for sign-in's cross-origin hops. */
5
+ export class Browser {
6
+ target;
7
+ jars = new Map();
8
+ seenSetCookies = [];
9
+ constructor(target) {
10
+ this.target = target;
11
+ }
12
+ jar(host) {
13
+ let jar = this.jars.get(host);
14
+ if (!jar)
15
+ this.jars.set(host, (jar = new Map()));
16
+ return jar;
17
+ }
18
+ /** The cookies a request to `url` carries, as a Cookie header. */
19
+ cookieHeader(url) {
20
+ const jar = this.jar(new URL(url).host);
21
+ const now = Date.now();
22
+ for (const [name, { expiresAt }] of jar)
23
+ if (expiresAt !== undefined && expiresAt <= now)
24
+ jar.delete(name);
25
+ return jar.size ? [...jar].map(([name, { value }]) => `${name}=${value}`).join("; ") : null;
26
+ }
27
+ get(url, name) {
28
+ this.cookieHeader(url);
29
+ return this.jar(new URL(url).host).get(name);
30
+ }
31
+ set(url, name, value) {
32
+ this.jar(new URL(url).host).set(name, { value, attributes: "" });
33
+ }
34
+ /** Every cookie this browser holds for `url`'s host, to copy into another browser. */
35
+ copyFrom(other, url) {
36
+ other.cookieHeader(url);
37
+ for (const [name, stored] of other.jar(new URL(url).host))
38
+ this.jar(new URL(url).host).set(name, { ...stored });
39
+ }
40
+ store(host, cookie) {
41
+ this.seenSetCookies.push({ host, cookie });
42
+ const [pair = "", ...rest] = cookie.split(";");
43
+ const eq = pair.indexOf("=");
44
+ const name = pair.slice(0, eq).trim();
45
+ const value = pair.slice(eq + 1).trim();
46
+ const attributes = rest.join(";");
47
+ const maxAge = /max-age=(-?\d+)/i.exec(attributes)?.[1];
48
+ if ((maxAge !== undefined && Number(maxAge) <= 0) || (!value && maxAge === undefined)) {
49
+ this.jar(host).delete(name);
50
+ return;
51
+ }
52
+ this.jar(host).set(name, { value, attributes, ...(maxAge !== undefined && { expiresAt: Date.now() + Number(maxAge) * 1000 }) });
53
+ }
54
+ /** One request with this browser's cookies; stores what it sets. */
55
+ async request(url, init = {}) {
56
+ const headers = new Headers(init.headers);
57
+ const cookie = this.cookieHeader(url);
58
+ if (cookie && !headers.has("cookie"))
59
+ headers.set("cookie", cookie);
60
+ const response = await this.target.fetch(new Request(url, { ...init, headers, redirect: "manual" }));
61
+ for (const set of response.headers.getSetCookie())
62
+ this.store(new URL(url).host, set);
63
+ return response;
64
+ }
65
+ /** A top-level navigation, following redirects. */
66
+ async navigate(url, init = {}) {
67
+ let at = url;
68
+ let response = await this.request(at, { ...init, headers: { accept: "text/html", ...init.headers } });
69
+ for (let hops = 0; response.status >= 300 && response.status < 400 && hops < 20; hops++) {
70
+ at = new URL(response.headers.get("location") ?? "", at).href;
71
+ response = await this.request(at, { headers: { accept: "text/html" } });
72
+ }
73
+ return { url: at, response };
74
+ }
75
+ }
76
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
77
+ const MODULE_COOKIE = /^(?:__host-)?zite_(?:id|signin|session)$/i;
78
+ const PLATFORM_COOKIE = /^(?:__(?:secure|host)-)?(?:better-auth\.|zite_)/i;
79
+ const cookieNames = (target) => {
80
+ const secure = new URL(target.appOrigin).protocol === "https:";
81
+ const name = (base) => (secure ? `__Host-${base}` : base);
82
+ return { secure, identity: name("zite_id"), flow: name("zite_signin"), session: name("zite_session") };
83
+ };
84
+ const modeOf = (target) => target.clientId.split(":")[1] ?? "";
85
+ const echo = async (target, browser, headers = {}) => {
86
+ const response = await browser.request(`${target.appOrigin}${target.echoPath}`, { headers: { accept: "application/json", ...headers } });
87
+ const text = await response.text();
88
+ try {
89
+ return { echo: JSON.parse(text), text, response };
90
+ }
91
+ catch {
92
+ throw new Error(`the echo path answered ${response.status}: ${text.slice(0, 300)}`);
93
+ }
94
+ };
95
+ /** Signs `email` in through the whole flow; answers where the browser ended up. */
96
+ const signIn = async (target, browser, email, returnTo = "/") => {
97
+ const login = `${target.appOrigin}/auth/login?redirectUrl=${encodeURIComponent(new URL(returnTo, target.appOrigin).href)}`;
98
+ const page = await browser.navigate(login);
99
+ if (new URL(page.url).origin === target.appOrigin && !page.url.includes("/auth/sign-in"))
100
+ return page.url;
101
+ const next = await target.completeSignIn(browser, page.url, email);
102
+ return (await browser.navigate(next)).url;
103
+ };
104
+ const baseClaims = (target, overrides = {}) => {
105
+ const now = Math.floor(Date.now() / 1000);
106
+ return {
107
+ iss: target.issuer,
108
+ sub: "u_forged",
109
+ aud: target.clientId,
110
+ iat: now,
111
+ exp: now + target.identityLifetimeS,
112
+ email: "forged@x.co",
113
+ name: "Forged",
114
+ roles: [],
115
+ isInternal: false,
116
+ mode: modeOf(target),
117
+ ver: target.ver ?? null,
118
+ ...overrides,
119
+ };
120
+ };
121
+ const attributesOf = (cookie) => cookie
122
+ .split(";")
123
+ .slice(1)
124
+ .map((a) => a.trim().toLowerCase());
125
+ const waitOutIdentity = (target) => sleep((target.identityLifetimeS + 1) * 1000);
126
+ const sameOrigin = (target) => ({ origin: target.appOrigin, "sec-fetch-site": "same-origin" });
127
+ export const scenarios = [
128
+ {
129
+ id: "S1",
130
+ title: "an anonymous visitor reaches a page, signed out, with no sign-in cookies set",
131
+ runners: ["zite", "local"],
132
+ async run({ target, browser, check }) {
133
+ const visitor = browser();
134
+ const page = await visitor.navigate(`${target.appOrigin}/`);
135
+ check(target.appAnswered(page.response) && page.url === `${target.appOrigin}/`, "app code answers the page, in place", page.url);
136
+ const { echo: seen } = await echo(target, visitor);
137
+ check(seen.user === null, "app code sees nobody", seen);
138
+ check(!visitor.seenSetCookies.some(({ cookie }) => MODULE_COOKIE.test(cookie.split("=")[0])), "no module cookie is set", visitor.seenSetCookies);
139
+ },
140
+ },
141
+ {
142
+ id: "S2",
143
+ title: "/auth/login sets the flow cookie and redirects to authorize with PKCE, state and nonce",
144
+ runners: ["zite", "local"],
145
+ async run({ target, browser, check }) {
146
+ const visitor = browser();
147
+ const response = await visitor.request(`${target.appOrigin}/auth/login`);
148
+ const location = new URL(response.headers.get("location") ?? "", target.appOrigin);
149
+ const query = Object.fromEntries(location.searchParams);
150
+ check(response.status === 302 && location.pathname.endsWith("/api/auth/oauth2/authorize"), "302 to the authorize endpoint", location.href);
151
+ check(query.response_type === "code" &&
152
+ query.client_id === target.clientId &&
153
+ query.redirect_uri === `${target.appOrigin}/auth/callback` &&
154
+ query.code_challenge_method === "S256" &&
155
+ !!query.code_challenge &&
156
+ !!query.state &&
157
+ !!query.nonce, "the authorization request names the client, the callback and PKCE", query);
158
+ const scopes = (query.scope ?? "").split(" ");
159
+ check(scopes.includes("openid") && scopes.includes("offline_access") === (target.runner === "local"), "offline_access only off Zite", query.scope);
160
+ const names = cookieNames(target);
161
+ const flow = visitor.seenSetCookies.find(({ cookie }) => cookie.startsWith(`${names.flow}=`))?.cookie ?? "";
162
+ const attributes = attributesOf(flow);
163
+ check(attributes.includes("httponly") && attributes.includes("path=/") && attributes.includes("max-age=600") && !attributes.some((a) => a.startsWith("domain")) && attributes.includes("secure") === names.secure, "the flow cookie is HttpOnly, host-only, 600 s", flow);
164
+ },
165
+ },
166
+ {
167
+ id: "S3",
168
+ title: "email sign-in end to end sets the identity cookie, clears the flow, and returns same-origin only",
169
+ runners: ["zite", "local"],
170
+ async run({ target, browser, check }) {
171
+ const email = await target.createUser();
172
+ const visitor = browser();
173
+ const landed = await signIn(target, visitor, email, "/about?tab=2");
174
+ check(landed === `${target.appOrigin}/about?tab=2`, "back where sign-in started", landed);
175
+ const names = cookieNames(target);
176
+ const identity = [...visitor.seenSetCookies].reverse().find(({ cookie }) => cookie.startsWith(`${names.identity}=`))?.cookie ?? "";
177
+ const attributes = attributesOf(identity);
178
+ const maxAge = Number(attributes.find((a) => a.startsWith("max-age="))?.slice(8));
179
+ check(attributes.includes("httponly") && attributes.includes("path=/") && attributes.includes("samesite=lax") && maxAge > 0 && maxAge <= 300 && !attributes.some((a) => a.startsWith("domain")), "the identity cookie is HttpOnly, Lax, host-only and short", identity);
180
+ check(!visitor.get(target.appOrigin, names.flow), "the flow cookie is gone", visitor.cookieHeader(target.appOrigin));
181
+ const elsewhere = await signIn(target, browser(), email, "https://evil.example/steal");
182
+ check(elsewhere === `${target.appOrigin}/`, "a foreign return address lands on the app's root", elsewhere);
183
+ },
184
+ },
185
+ {
186
+ id: "S4",
187
+ title: "the user reaches app code, and an x-zite-user header from the browser is ignored",
188
+ runners: ["zite", "local"],
189
+ async run({ target, browser, check }) {
190
+ const email = await target.createUser();
191
+ const visitor = browser();
192
+ await signIn(target, visitor, email);
193
+ const forged = btoa(JSON.stringify({ id: "u_mallory", email: "m@x.co", name: "M", roles: [], isInternal: true })).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
194
+ const { echo: seen } = await echo(target, visitor, { "x-zite-user": forged });
195
+ check(seen.user?.email === email, "app code sees the signed-in user, not the header's", seen);
196
+ const { echo: anonymous } = await echo(target, browser(), { "x-zite-user": forged });
197
+ check(anonymous.user === null, "nor does a header sign anyone in", anonymous);
198
+ const posted = await visitor.request(`${target.appOrigin}${target.echoPath}`, {
199
+ method: "POST",
200
+ headers: { ...sameOrigin(target), "content-type": "application/json" },
201
+ body: JSON.stringify({ hello: "world" }),
202
+ });
203
+ const postedEcho = (await posted.json().catch(() => null));
204
+ check(posted.status === 200 && postedEcho?.user?.email === email, "a same-origin POST with a body reaches app code as the user", postedEcho);
205
+ },
206
+ },
207
+ {
208
+ id: "S5",
209
+ title: "an expired identity is renewed from the long-lived credential",
210
+ runners: ["zite", "local"],
211
+ async run({ target, browser, check }) {
212
+ const email = await target.createUser();
213
+ const visitor = browser();
214
+ await signIn(target, visitor, email);
215
+ const names = cookieNames(target);
216
+ const first = visitor.get(target.appOrigin, names.identity)?.value;
217
+ await waitOutIdentity(target);
218
+ const { echo: seen } = await echo(target, visitor);
219
+ const renewed = visitor.get(target.appOrigin, names.identity)?.value;
220
+ check(seen.user?.email === email, "still signed in after the identity lapsed", seen);
221
+ check(!!renewed && renewed !== first, "a new identity cookie", { first, renewed });
222
+ },
223
+ },
224
+ { id: "S6", title: "an internal app refuses a page, a server function and a call without a session, before app code", runners: ["zite"] },
225
+ {
226
+ id: "S7",
227
+ title: "forged identity cookies are refused and cleared",
228
+ runners: ["zite", "local"],
229
+ async run({ target, browser, check }) {
230
+ const names = cookieNames(target);
231
+ const [app] = target.clientId.split(":");
232
+ const otherMode = modeOf(target) === "live" ? "preview" : "live";
233
+ const appToken = await target.mint({
234
+ claims: { iss: "zite-host", aud: ["backend"], iat: baseClaims(target).iat, exp: baseClaims(target).exp, app, mode: "live", user: "u_forged" },
235
+ header: { typ: "JWT" },
236
+ key: "app-token",
237
+ });
238
+ const cases = [
239
+ ["signed with another key", target.mint({ claims: baseClaims(target), key: "stranger" })],
240
+ ["alg none", target.mint({ claims: baseClaims(target), header: { alg: "none" } })],
241
+ ["HS256", target.mint({ claims: baseClaims(target), header: { alg: "HS256" } })],
242
+ ["typ JWT", target.mint({ claims: baseClaims(target), header: { typ: "JWT" } })],
243
+ ["another app's audience", target.mint({ claims: baseClaims(target, { aud: `other-app:${modeOf(target)}` }) })],
244
+ [`a ${otherMode} identity`, target.mint({ claims: baseClaims(target, { aud: `${app}:${otherMode}`, mode: otherMode, ...(otherMode === "preview" && { preview: { build: 1, editor: "e" } }) }) })],
245
+ ["another host's issuer", target.mint({ claims: baseClaims(target, { iss: "https://other.zite.so/auth" }) })],
246
+ ["an app token in the slot", `zite_app_v1.${appToken}`],
247
+ ["an app token's JWS in the slot", appToken],
248
+ ...(typeof target.ver === "number" ? [["a stale version", target.mint({ claims: baseClaims(target, { ver: target.ver - 1 }) })]] : []),
249
+ ];
250
+ for (const [name, token] of cases) {
251
+ const visitor = browser();
252
+ visitor.set(target.appOrigin, names.identity, await token);
253
+ const { echo: seen } = await echo(target, visitor);
254
+ check(seen.user === null, `${name}: nobody signed in`, seen);
255
+ check(!visitor.get(target.appOrigin, names.identity), `${name}: the cookie is cleared`, visitor.seenSetCookies);
256
+ }
257
+ },
258
+ },
259
+ {
260
+ id: "S8",
261
+ title: "a role change shows at the next renewal, and a removed user is refused there",
262
+ runners: ["zite", "local"],
263
+ async run({ target, browser, check }) {
264
+ const email = await target.createUser(["viewer"]);
265
+ const visitor = browser();
266
+ await signIn(target, visitor, email);
267
+ await target.setRoles(email, ["manager"]);
268
+ await waitOutIdentity(target);
269
+ const { echo: changed } = await echo(target, visitor);
270
+ check(changed.user?.roles?.map((role) => role.id).join() === "manager", "the new role", changed);
271
+ await target.removeUser(email);
272
+ await waitOutIdentity(target);
273
+ const { echo: removed } = await echo(target, visitor);
274
+ check(removed.user === null, "the removed user is signed out", removed);
275
+ const names = cookieNames(target);
276
+ check(!visitor.get(target.appOrigin, names.identity), "and holds no identity", visitor.cookieHeader(target.appOrigin));
277
+ },
278
+ },
279
+ {
280
+ id: "S9",
281
+ title: "sign-out, new and legacy, ends this browser's session; a copied identity dies with its lifetime",
282
+ runners: ["zite", "local"],
283
+ async run({ target, browser, check }) {
284
+ const names = cookieNames(target);
285
+ for (const path of ["/auth/logout", "/api/auth/sign-out"]) {
286
+ const email = await target.createUser();
287
+ const visitor = browser();
288
+ await signIn(target, visitor, email);
289
+ const copy = browser();
290
+ copy.copyFrom(visitor, target.appOrigin);
291
+ const response = await visitor.request(`${target.appOrigin}${path}`, { method: "POST", headers: sameOrigin(target) });
292
+ check(response.status === 200 && JSON.stringify(await response.json()) === '{"success":true}', `${path} answers better-auth's shape`, response.status);
293
+ const held = visitor.cookieHeader(target.appOrigin) ?? "";
294
+ check(!held.split("; ").some((pair) => PLATFORM_COOKIE.test(pair.split("=")[0])), `${path} clears every sign-in cookie`, held);
295
+ check((await echo(target, visitor)).echo.user === null, `${path}: signed out`);
296
+ check((await echo(target, copy)).echo.user?.email === email, `${path}: a copied identity holds until it lapses`);
297
+ await waitOutIdentity(target);
298
+ check((await echo(target, copy)).echo.user === null, `${path}: then the copy can't renew`);
299
+ }
300
+ },
301
+ },
302
+ { id: "S10", title: "update-user changes the two name fields only, and re-issues the identity", runners: ["zite"] },
303
+ {
304
+ id: "S11",
305
+ title: "a cross-site POST with the cookies is refused; same-origin is accepted",
306
+ runners: ["zite", "local"],
307
+ async run({ target, browser, check }) {
308
+ const email = await target.createUser();
309
+ const visitor = browser();
310
+ await signIn(target, visitor, email);
311
+ const crossSite = { origin: "https://evil.example", "sec-fetch-site": "cross-site" };
312
+ for (const path of ["/auth/logout", "/api/auth/sign-out"]) {
313
+ const response = await visitor.request(`${target.appOrigin}${path}`, { method: "POST", headers: crossSite });
314
+ check(response.status === 403, `${path} cross-site: 403`, response.status);
315
+ }
316
+ const update = await visitor.request(`${target.appOrigin}/api/auth/update-user`, {
317
+ method: "POST",
318
+ headers: { ...crossSite, "content-type": "application/json" },
319
+ body: JSON.stringify({ firstName: "Mallory" }),
320
+ });
321
+ check(update.status === 403, "update-user cross-site: 403", update.status);
322
+ check((await echo(target, visitor)).echo.user?.email === email, "still signed in");
323
+ const response = await visitor.request(`${target.appOrigin}/auth/logout`, { method: "POST", headers: sameOrigin(target) });
324
+ check(response.status === 200, "same-origin sign-out: 200", response.status);
325
+ },
326
+ },
327
+ {
328
+ id: "S12",
329
+ title: "nothing under /auth or /api/auth reaches the app",
330
+ runners: ["zite", "local"],
331
+ async run({ target, browser, check }) {
332
+ const visitor = browser();
333
+ for (const path of ["/auth/anything", "/api/auth/anything", "/auth", "/api/auth/oauth2/introspect", "/api/auth/list-sessions"]) {
334
+ const response = await visitor.request(`${target.appOrigin}${path}`);
335
+ check(!target.appAnswered(response) && response.status >= 400, `${path} isn't the app's`, response.status);
336
+ }
337
+ },
338
+ },
339
+ { id: "S12b", title: "the token endpoint refuses a browser redeeming a :live or :preview code: invalid_client", runners: ["zite"] },
340
+ { id: "S13", title: "preview entry: the preview claim, Partitioned cookies, URL and header forms, the re-enter signal", runners: ["zite"] },
341
+ { id: "S14", title: "demo: the picker, the demo token, a removed demo user refused", runners: ["zite"] },
342
+ {
343
+ id: "S15",
344
+ title: "old builds' shapes: loginHref's /auth/login and get-session's JSON",
345
+ runners: ["zite", "local"],
346
+ async run({ target, browser, check }) {
347
+ const visitor = browser();
348
+ const login = await visitor.request(`${target.appOrigin}/auth/login?redirectUrl=${encodeURIComponent(`${target.appOrigin}/orders`)}`);
349
+ check(login.status === 302, "loginHref's URL starts a sign-in", login.status);
350
+ const anonymous = await visitor.request(`${target.appOrigin}/api/auth/get-session`);
351
+ check((await anonymous.text()) === "null", "get-session answers null signed out");
352
+ const email = await target.createUser();
353
+ await signIn(target, visitor, email);
354
+ const session = (await (await visitor.request(`${target.appOrigin}/api/auth/get-session`)).json());
355
+ check(session.user?.email === email && !!session.user.id && session.session?.userId === session.user.id, "get-session answers better-auth's shape", session);
356
+ },
357
+ },
358
+ {
359
+ id: "S16",
360
+ title: "cookie hygiene: no Domain, a duplicated identity dropped, an unprefixed one ignored over https, none in app code",
361
+ runners: ["zite", "local"],
362
+ async run({ target, browser, check }) {
363
+ const names = cookieNames(target);
364
+ const email = await target.createUser();
365
+ const visitor = browser();
366
+ await signIn(target, visitor, email);
367
+ const appHost = new URL(target.appOrigin).host;
368
+ const ours = visitor.seenSetCookies.filter(({ host }) => host === appHost).map(({ cookie }) => cookie);
369
+ check(ours.length > 0 && ours.every((cookie) => !attributesOf(cookie).some((a) => a.startsWith("domain"))), "no Set-Cookie names a Domain", ours);
370
+ const identity = visitor.get(target.appOrigin, names.identity)?.value ?? "";
371
+ const duplicated = await echo(target, browser(), { cookie: `${names.identity}=${identity}; ${names.identity}=${identity}` });
372
+ check(duplicated.echo.user === null, "an identity sent twice counts for nothing", duplicated.echo);
373
+ if (names.secure) {
374
+ const unprefixed = await echo(target, browser(), { cookie: `zite_id=${identity}` });
375
+ check(unprefixed.echo.user === null, "an unprefixed zite_id counts for nothing over https", unprefixed.echo);
376
+ }
377
+ const { echo: seen } = await echo(target, visitor);
378
+ const appCookies = (seen.cookie ?? "").split("; ").filter(Boolean).map((pair) => pair.split("=")[0]);
379
+ check(!appCookies.some((name) => PLATFORM_COOKIE.test(name)), "app code sees no sign-in cookie", seen.cookie);
380
+ },
381
+ },
382
+ {
383
+ id: "S17",
384
+ title: "nothing long-lived reaches app code, before or after a renewal",
385
+ runners: ["zite", "local"],
386
+ async run({ target, browser, check }) {
387
+ const email = await target.createUser();
388
+ const visitor = browser();
389
+ visitor.set(target.appOrigin, "theme", "dark");
390
+ await signIn(target, visitor, email);
391
+ const secrets = () => (visitor.cookieHeader(target.appOrigin) ?? "")
392
+ .split("; ")
393
+ .filter((pair) => PLATFORM_COOKIE.test(pair.split("=")[0]))
394
+ .map((pair) => pair.slice(pair.indexOf("=") + 1))
395
+ .filter((value) => value.length >= 16);
396
+ const before = secrets();
397
+ const first = await echo(target, visitor);
398
+ check(first.echo.cookie === "theme=dark", "app code gets its own cookies only", first.echo.cookie);
399
+ check(before.length > 0 && before.every((value) => !first.text.includes(value)), "no sign-in cookie's value in what app code saw");
400
+ await waitOutIdentity(target);
401
+ const second = await echo(target, visitor);
402
+ const after = [...before, ...secrets()];
403
+ check(second.echo.user?.email === email && after.every((value) => !second.text.includes(value)), "nor after a renewal", second.echo);
404
+ },
405
+ },
406
+ {
407
+ id: "S18",
408
+ title: "two parallel renewals on one refresh token both succeed, and the session goes on",
409
+ runners: ["local"],
410
+ async run({ target, browser, check }) {
411
+ const email = await target.createUser();
412
+ const visitor = browser();
413
+ await signIn(target, visitor, email);
414
+ await waitOutIdentity(target);
415
+ const [a, b] = await Promise.all([echo(target, visitor), echo(target, visitor)]);
416
+ check(a.echo.user?.email === email && b.echo.user?.email === email, "both renew", [a.echo, b.echo]);
417
+ await waitOutIdentity(target);
418
+ check((await echo(target, visitor)).echo.user?.email === email, "and the next renewal still works");
419
+ },
420
+ },
421
+ {
422
+ id: "S19",
423
+ title: "ZITE_DEV_USER's stand-in bypasses the module, with no call to the identity server",
424
+ runners: ["local"],
425
+ async run({ target, browser, check }) {
426
+ if (!target.withDevUser)
427
+ throw new Error("the target can't set ZITE_DEV_USER");
428
+ const before = target.identityServerCalls();
429
+ await target.withDevUser({ id: "u_stand_in", email: "stand-in@x.co" }, async () => {
430
+ const visitor = browser();
431
+ const { echo: seen } = await echo(target, visitor);
432
+ check(seen.user?.email === "stand-in@x.co", "app code sees the stand-in", seen);
433
+ const login = await visitor.request(`${target.appOrigin}/auth/login`);
434
+ check(login.status !== 302, "the module doesn't answer /auth/login", login.status);
435
+ });
436
+ check(target.identityServerCalls() === before, "the identity server heard nothing", target.identityServerCalls() - before);
437
+ },
438
+ },
439
+ ];
440
+ /** Runs every scenario this runner can, in order. Scenarios for the other runner are reported skipped. */
441
+ export const runConformance = async (target, options = {}) => {
442
+ const results = [];
443
+ for (const scenario of scenarios) {
444
+ if (options.only && !options.only.includes(scenario.id))
445
+ continue;
446
+ const { id, title } = scenario;
447
+ let result;
448
+ if (!scenario.run || !scenario.runners.includes(target.runner)) {
449
+ result = { id, title, status: "skipped", detail: scenario.runners.includes(target.runner) ? "not implemented here" : `the ${scenario.runners.join(" and ")} runner's` };
450
+ }
451
+ else {
452
+ try {
453
+ await scenario.run({
454
+ target,
455
+ browser: () => new Browser(target),
456
+ check(ok, what, seen) {
457
+ if (!ok)
458
+ throw new Error(`${what}${seen === undefined ? "" : `: ${JSON.stringify(seen)?.slice(0, 400)}`}`);
459
+ },
460
+ });
461
+ result = { id, title, status: "pass" };
462
+ }
463
+ catch (error) {
464
+ result = { id, title, status: "fail", detail: error instanceof Error ? error.message : String(error) };
465
+ }
466
+ }
467
+ results.push(result);
468
+ options.onResult?.(result);
469
+ }
470
+ return results;
471
+ };
@@ -0,0 +1,28 @@
1
+ /** Where a cookie has to work: over https, and inside the editor's frame. */
2
+ export type CookieContext = {
3
+ secure: boolean;
4
+ framed: boolean;
5
+ };
6
+ export declare const MODULE_COOKIES: {
7
+ /** The identity token. */
8
+ readonly identity: "zite_id";
9
+ /** One sign-in's state, PKCE verifier, nonce and return path. */
10
+ readonly flow: "zite_signin";
11
+ /** Off Zite only: the sealed refresh token. */
12
+ readonly session: "zite_session";
13
+ };
14
+ export type ModuleCookie = keyof typeof MODULE_COOKIES;
15
+ /** `__Host-` over https, so no sibling host can set or shadow it; plain on http://localhost, which can't hold one. */
16
+ export declare const cookieName: (cookie: ModuleCookie, secure: boolean) => string;
17
+ export declare const isModuleCookie: (name: string) => boolean;
18
+ export declare const setCookie: (cookie: ModuleCookie, value: string, context: CookieContext, maxAgeS: number) => string;
19
+ export declare const clearCookie: (cookie: ModuleCookie, context: CookieContext) => string;
20
+ /**
21
+ * The cookies sent once. A name sent twice is dropped: which copy wins differs between parsers, and that difference
22
+ * is how one cookie shadows another.
23
+ */
24
+ export declare const readCookies: (header: string | null) => Map<string, string>;
25
+ /** The pairs of `header` whose names match, sent once each, as a Cookie header; null for none. */
26
+ export declare const cookiePairs: (header: string | null, names: RegExp) => string | null;
27
+ /** `header` without the pairs `drop` names; null when nothing is left. */
28
+ export declare const withoutCookies: (header: string | null, drop: (name: string) => boolean) => string | null;
@@ -0,0 +1,59 @@
1
+ // The module's cookies (T5 design §3.2). Byte-exact: names and values are never URL-decoded.
2
+ export const MODULE_COOKIES = {
3
+ /** The identity token. */
4
+ identity: "zite_id",
5
+ /** One sign-in's state, PKCE verifier, nonce and return path. */
6
+ flow: "zite_signin",
7
+ /** Off Zite only: the sealed refresh token. */
8
+ session: "zite_session",
9
+ };
10
+ /** `__Host-` over https, so no sibling host can set or shadow it; plain on http://localhost, which can't hold one. */
11
+ export const cookieName = (cookie, secure) => secure ? `__Host-${MODULE_COOKIES[cookie]}` : MODULE_COOKIES[cookie];
12
+ const MODULE_COOKIE_NAME = /^(?:__host-)?zite_(?:id|signin|session)$/i;
13
+ export const isModuleCookie = (name) => MODULE_COOKIE_NAME.test(name);
14
+ // A framed preview is cross-site to the editor around it, so its cookies are SameSite=None and Partitioned to survive
15
+ // there. Lax everywhere else: the return leg through Google and the backend is a cross-site redirect chain, where
16
+ // Strict isn't sent.
17
+ const attributes = ({ secure, framed }, maxAge) => {
18
+ const crossSite = framed && secure;
19
+ return [
20
+ "Path=/",
21
+ `Max-Age=${Math.max(Math.floor(maxAge), 0)}`,
22
+ "HttpOnly",
23
+ crossSite ? "SameSite=None" : "SameSite=Lax",
24
+ ...(secure ? ["Secure"] : []),
25
+ ...(crossSite ? ["Partitioned"] : []),
26
+ ].join("; ");
27
+ };
28
+ export const setCookie = (cookie, value, context, maxAgeS) => `${cookieName(cookie, context.secure)}=${value}; ${attributes(context, maxAgeS)}`;
29
+ export const clearCookie = (cookie, context) => `${cookieName(cookie, context.secure)}=; ${attributes(context, 0)}`;
30
+ const pairsOf = (header) => (header ?? "")
31
+ .split(";")
32
+ .map((pair) => pair.trim())
33
+ .filter(Boolean)
34
+ .map((pair) => {
35
+ const eq = pair.indexOf("=");
36
+ return { name: (eq === -1 ? pair : pair.slice(0, eq)).trim(), value: eq === -1 ? "" : pair.slice(eq + 1).trim(), pair };
37
+ });
38
+ /**
39
+ * The cookies sent once. A name sent twice is dropped: which copy wins differs between parsers, and that difference
40
+ * is how one cookie shadows another.
41
+ */
42
+ export const readCookies = (header) => {
43
+ const pairs = pairsOf(header);
44
+ const counts = new Map();
45
+ for (const { name } of pairs)
46
+ counts.set(name, (counts.get(name) ?? 0) + 1);
47
+ return new Map(pairs.filter(({ name }) => counts.get(name) === 1).map(({ name, value }) => [name, value]));
48
+ };
49
+ /** The pairs of `header` whose names match, sent once each, as a Cookie header; null for none. */
50
+ export const cookiePairs = (header, names) => {
51
+ const sent = readCookies(header);
52
+ const kept = [...sent].filter(([name]) => names.test(name)).map(([name, value]) => `${name}=${value}`);
53
+ return kept.length > 0 ? kept.join("; ") : null;
54
+ };
55
+ /** `header` without the pairs `drop` names; null when nothing is left. */
56
+ export const withoutCookies = (header, drop) => {
57
+ const kept = pairsOf(header).filter(({ name }) => !drop(name));
58
+ return kept.length > 0 ? kept.map(({ pair }) => pair).join("; ") : null;
59
+ };
@@ -0,0 +1,9 @@
1
+ export declare const utf8: (text: string) => Uint8Array<ArrayBuffer>;
2
+ export declare const fromUtf8: (bytes: Uint8Array) => string;
3
+ export declare const toBase64Url: (bytes: Uint8Array) => string;
4
+ export declare const fromBase64Url: (value: string) => Uint8Array<ArrayBuffer> | undefined;
5
+ export declare const jsonOf: (bytes: Uint8Array | undefined) => unknown;
6
+ export declare const isRecord: (value: unknown) => value is Record<string, unknown>;
7
+ export declare const randomToken: (bytes?: number) => string;
8
+ /** RFC 7636's S256 challenge for a verifier. */
9
+ export declare const s256: (verifier: string) => Promise<string>;
@@ -0,0 +1,39 @@
1
+ const encoder = new TextEncoder();
2
+ const decoder = new TextDecoder();
3
+ export const utf8 = (text) => encoder.encode(text);
4
+ export const fromUtf8 = (bytes) => decoder.decode(bytes);
5
+ export const toBase64Url = (bytes) => {
6
+ let binary = "";
7
+ for (const byte of bytes)
8
+ binary += String.fromCharCode(byte);
9
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
10
+ };
11
+ // Canonical encodings only: atob ignores a last character's unused bits, so without the round trip one signature
12
+ // would have several spellings.
13
+ export const fromBase64Url = (value) => {
14
+ if (!/^[A-Za-z0-9_-]*$/.test(value))
15
+ return undefined;
16
+ const padded = value.replace(/-/g, "+").replace(/_/g, "/");
17
+ let bytes;
18
+ try {
19
+ bytes = Uint8Array.from(atob(padded + "=".repeat((4 - (padded.length % 4)) % 4)), (char) => char.charCodeAt(0));
20
+ }
21
+ catch {
22
+ return undefined;
23
+ }
24
+ return toBase64Url(bytes) === value ? bytes : undefined;
25
+ };
26
+ export const jsonOf = (bytes) => {
27
+ if (!bytes)
28
+ return undefined;
29
+ try {
30
+ return JSON.parse(fromUtf8(bytes));
31
+ }
32
+ catch {
33
+ return undefined;
34
+ }
35
+ };
36
+ export const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
37
+ export const randomToken = (bytes = 32) => toBase64Url(crypto.getRandomValues(new Uint8Array(bytes)));
38
+ /** RFC 7636's S256 challenge for a verifier. */
39
+ export const s256 = async (verifier) => toBase64Url(new Uint8Array(await crypto.subtle.digest("SHA-256", utf8(verifier))));
@@ -0,0 +1,12 @@
1
+ /** https, or plain http on a loopback host (a local stack, or a test's issuer). */
2
+ export declare const isServedUrl: (url: URL) => boolean;
3
+ /** The issuer's origin; throws for anything that isn't `https://<host>/auth`. */
4
+ export declare const issuerOrigin: (issuer: string) => string;
5
+ /** Where Zite's identity server answers for an issuer: better-auth's base path stays `/api/auth` (T5 design §2). */
6
+ export declare const ziteEndpoints: (issuer: string) => {
7
+ authorize: string;
8
+ token: string;
9
+ endSession: string;
10
+ revocation: string;
11
+ signInPage: string;
12
+ };
@@ -0,0 +1,29 @@
1
+ // `.localhost` names are loopback (RFC 6761): a local stack serves each app on its own `<app>.localhost`.
2
+ const LOOPBACK = /^(?:(?:[a-z0-9-]+\.)*localhost|127\.0\.0\.1|\[::1\])$/i;
3
+ /** https, or plain http on a loopback host (a local stack, or a test's issuer). */
4
+ export const isServedUrl = (url) => !url.username && !url.password && (url.protocol === "https:" || (url.protocol === "http:" && LOOPBACK.test(url.hostname)));
5
+ /** The issuer's origin; throws for anything that isn't `https://<host>/auth`. */
6
+ export const issuerOrigin = (issuer) => {
7
+ let url;
8
+ try {
9
+ url = new URL(issuer);
10
+ }
11
+ catch {
12
+ throw new Error(`The sign-in issuer ${issuer} isn't a URL`);
13
+ }
14
+ if (!isServedUrl(url) || url.pathname !== "/auth" || url.search || url.hash) {
15
+ throw new Error(`The sign-in issuer must be https://<host>/auth, not ${issuer}`);
16
+ }
17
+ return url.origin;
18
+ };
19
+ /** Where Zite's identity server answers for an issuer: better-auth's base path stays `/api/auth` (T5 design §2). */
20
+ export const ziteEndpoints = (issuer) => {
21
+ const origin = issuerOrigin(issuer);
22
+ return {
23
+ authorize: `${origin}/api/auth/oauth2/authorize`,
24
+ token: `${origin}/api/auth/oauth2/token`,
25
+ endSession: `${origin}/api/auth/oauth2/end-session`,
26
+ revocation: `${origin}/api/auth/oauth2/revoke`,
27
+ signInPage: `${origin}/auth/sign-in`,
28
+ };
29
+ };