Skip to content

Commit 39137f6

Browse files
committed
fix(web): key broadcast reads by query, keep no-JS envelope cookies
1 parent 50dec1b commit 39137f6

5 files changed

Lines changed: 235 additions & 10 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@solidjs/web": patch
3+
---
4+
5+
A broadcast live read with a plain form query (`?room=a`, no `?args=`) is now keyed by that query, so viewers of different queries no longer share one source.
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@solidjs/web": patch
3+
---
4+
5+
A no-JS form post answered by `respond(value, { headers })`, returned or thrown, now keeps the envelope's `Set-Cookie` headers on the redirect.

‎packages/web/server-functions/src/server.ts‎

Lines changed: 27 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1714,9 +1714,9 @@ export function broadcast(fn) {
17141714
// a BigInt throws), so two callers with different arguments would share one
17151715
// render. Encodings that differ for equal values only cost sharing. A POST
17161716
// body is keyed with its content type; one this dispatch didn't buffer has no
1717-
// key, and the call is served per connection.
1718-
function encodedArguments(request, argsEncoding, argumentBytes) {
1719-
if (request.method !== "POST") return argsEncoding || "";
1717+
// key, and the call is served per connection. A read without args is keyed by its form query.
1718+
function encodedArguments(request, url, argsEncoding, argumentBytes) {
1719+
if (request.method !== "POST") return argsEncoding || url.search;
17201720
if (!argumentBytes) return undefined;
17211721
return (
17221722
(request.headers.get("content-type") || "") +
@@ -4880,7 +4880,7 @@ export async function handleServerFunctionRequest(request, options = {}) {
48804880
id: functionId,
48814881
live: !!live,
48824882
broadcast: shared || undefined,
4883-
shareKey: shared ? encodedArguments(request, argsEncoding, argumentBytes) : undefined
4883+
shareKey: shared ? encodedArguments(request, url, argsEncoding, argumentBytes) : undefined
48844884
});
48854885
const run = () => serverFunction(...parsed);
48864886
// Same observation as the direct leg (see `observeInvocation`): the
@@ -4986,11 +4986,8 @@ export async function handleServerFunctionRequest(request, options = {}) {
49864986
// to prefer, a returned `null` passes through as the outcome it is
49874987
// rather than eroding to `undefined` on the way to the flash (#3248).
49884988
if (handleNoJS) {
4989-
return handleNoJS(
4990-
result == null && metadata !== undefined ? metadata : result,
4991-
request,
4992-
parsed
4993-
);
4989+
const outcome = result == null && metadata !== undefined ? metadata : result;
4990+
return withEnvelopeCookies(await handleNoJS(outcome, request, parsed), outcome, metadata);
49944991
}
49954992
if (result instanceof Response) return result;
49964993
// the envelope's status forwards for unscripted callers too — this
@@ -5141,7 +5138,14 @@ export async function handleServerFunctionRequest(request, options = {}) {
51415138
// `x` was nulled when the thrown Response had no body, but the no-JS
51425139
// handler reads redirect metadata off the result — hand it the
51435140
// original Response, matching what the returned path passes.
5144-
if (handleNoJS) return handleNoJS(x ?? metadata, request, parsed, true);
5141+
if (handleNoJS) {
5142+
const outcome = x ?? metadata;
5143+
return withEnvelopeCookies(
5144+
await handleNoJS(outcome, request, parsed, true),
5145+
outcome,
5146+
metadata
5147+
);
5148+
}
51455149
if (x instanceof Response) return x;
51465150
}
51475151
if (scripted && status === 304) warnScripted304(functionId);
@@ -5249,6 +5253,19 @@ function withholdTrace(event) {
52495253
traceForEvent(event).emit = false;
52505254
}
52515255

5256+
// The no-JS handler sees only an envelope's value, so carry its cookies.
5257+
function withEnvelopeCookies(response, outcome, metadata) {
5258+
if (outcome === metadata || !metadata || !metadata.headers || !(response instanceof Response)) {
5259+
return response;
5260+
}
5261+
const cookies = metadata.headers.getSetCookie ? metadata.headers.getSetCookie() : [];
5262+
if (!cookies.length) return response;
5263+
const owned = ownResponse(response);
5264+
if (owned === response) return response;
5265+
for (const cookie of cookies) owned.headers.append("Set-Cookie", cookie);
5266+
return owned;
5267+
}
5268+
52525269
// A fresh Response around the same body: status, statusText and headers are
52535270
// copied (Response doubles as its own ResponseInit), so the copy's headers
52545271
// are mutable even when the source's were immutable (Response.redirect, a
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
/**
2+
* A read whose query is not an `?args=` encoding reaches the function as a
3+
* lone URLSearchParams (parseArguments). A broadcast's share key ignores
4+
* that query, so two viewers of different queries share one source.
5+
*/
6+
import { AsyncLocalStorage } from "node:async_hooks";
7+
import { afterAll, beforeAll, describe, expect, it } from "vitest";
8+
import {
9+
broadcast,
10+
createServerReference,
11+
handleServerFunctionRequest,
12+
registerServerReference
13+
} from "../../server-functions/src/server.js";
14+
import { createJSONDeserializer } from "../../serialization/src/serializer-decode.js";
15+
16+
const RequestContext = Symbol.for("solid.RequestContext");
17+
beforeAll(() => {
18+
(globalThis as any)[RequestContext] = new AsyncLocalStorage();
19+
});
20+
afterAll(() => {
21+
delete (globalThis as any)[RequestContext];
22+
});
23+
24+
const tick = (ms = 10) => new Promise<void>(r => setTimeout(r, ms));
25+
26+
function tap(response: Response) {
27+
const values: any[] = [];
28+
const reader = response.body!.getReader();
29+
const decoder = new TextDecoder();
30+
const decode = createJSONDeserializer();
31+
let buffer = "";
32+
let first = true;
33+
(async () => {
34+
for (;;) {
35+
const { done, value } = await reader.read().catch(() => ({ done: true, value: undefined }));
36+
if (done) return;
37+
buffer += decoder.decode(value, { stream: true });
38+
let end;
39+
while ((end = buffer.indexOf("\n\n")) >= 0) {
40+
const lines = buffer.slice(0, end).split("\n");
41+
buffer = buffer.slice(end + 2);
42+
const data = lines
43+
.filter(l => l.startsWith("data: "))
44+
.map(l => l.slice(6))
45+
.join("\n");
46+
if (!data) continue;
47+
const decoded: any = decode(JSON.parse(data));
48+
if (first) {
49+
first = false;
50+
(async () => {
51+
for await (const v of decoded) values.push(v);
52+
})().catch(() => {});
53+
}
54+
}
55+
}
56+
})();
57+
return { values, cancel: () => reader.cancel() };
58+
}
59+
60+
describe("broadcast share key and form-query reads", () => {
61+
it("viewers of different query parameters get their own source", async () => {
62+
broadcast(
63+
createServerReference(
64+
registerServerReference("broadcast-form-query-room", async (params: URLSearchParams) => {
65+
const room = params.get("room");
66+
return (async function* () {
67+
yield `room ${room}`;
68+
await new Promise(() => {});
69+
})();
70+
})
71+
)
72+
);
73+
const a = tap(
74+
await handleServerFunctionRequest(
75+
new Request("http://localhost/_server/live/broadcast-form-query-room?room=a", {
76+
method: "GET"
77+
})
78+
)
79+
);
80+
await tick();
81+
const b = tap(
82+
await handleServerFunctionRequest(
83+
new Request("http://localhost/_server/live/broadcast-form-query-room?room=b", {
84+
method: "GET"
85+
})
86+
)
87+
);
88+
await tick(30);
89+
expect(a.values).toEqual(["room a"]);
90+
expect(b.values).toEqual(["room b"]);
91+
a.cancel();
92+
b.cancel();
93+
await tick();
94+
});
95+
it("viewers of the same args share one source whatever else rides the query", async () => {
96+
let runs = 0;
97+
broadcast(
98+
createServerReference(
99+
registerServerReference("broadcast-form-query-args", async (room: string) => {
100+
const run = ++runs;
101+
return (async function* () {
102+
yield `room ${room} #${run}`;
103+
await new Promise(() => {});
104+
})();
105+
})
106+
)
107+
);
108+
const address = "http://localhost/_server/live/broadcast-form-query-args?args=%5B%22a%22%5D";
109+
const a = tap(await handleServerFunctionRequest(new Request(`${address}&x=1`)));
110+
await tick();
111+
const b = tap(await handleServerFunctionRequest(new Request(`${address}&x=2`)));
112+
await tick(30);
113+
expect(a.values).toEqual(["room a #1"]);
114+
expect(b.values).toEqual(["room a #1"]);
115+
a.cancel();
116+
b.cancel();
117+
await tick();
118+
});
119+
});
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
/**
2+
* A no-JS form post to a function answering `respond(value, { headers })`:
3+
* the dispatch unwraps the envelope and hands the no-JS handler only the
4+
* value, so the envelope's Set-Cookie (a session the mutation established)
5+
* never reaches the 303. A scripted call, an unscripted call and a
6+
* `respond(undefined, …)` form post all deliver it.
7+
*/
8+
import { AsyncLocalStorage } from "node:async_hooks";
9+
import { afterAll, beforeAll, describe, expect, it } from "vitest";
10+
import { respond } from "@solidjs/web";
11+
import {
12+
handleServerFunctionRequest,
13+
registerServerFunction
14+
} from "@solidjs/web/server-functions/server";
15+
16+
const RequestContext = Symbol.for("solid.RequestContext");
17+
beforeAll(() => {
18+
(globalThis as any)[RequestContext] = new AsyncLocalStorage();
19+
(globalThis as any).__SOLID_SECRET__ = "nojs-envelope-cookie";
20+
});
21+
afterAll(() => {
22+
delete (globalThis as any)[RequestContext];
23+
delete (globalThis as any).__SOLID_SECRET__;
24+
});
25+
26+
const formPost = (id: string) =>
27+
new Request(`https://app.example/_server/${id}`, {
28+
method: "POST",
29+
headers: {
30+
"Sec-Fetch-Site": "same-origin",
31+
"Content-Type": "application/x-www-form-urlencoded",
32+
Referer: "https://app.example/login"
33+
},
34+
body: "user=a"
35+
});
36+
37+
const sessions = (response: Response) =>
38+
response.headers.getSetCookie().filter(c => c.startsWith("session="));
39+
40+
describe("no-JS form post and a respond() envelope's cookies", () => {
41+
it("a returned envelope with a value keeps its Set-Cookie", async () => {
42+
registerServerFunction("nojs-envelope-cookie-return", async () =>
43+
respond({ ok: true }, { headers: { "Set-Cookie": "session=abc; Path=/" } })
44+
);
45+
const response = await handleServerFunctionRequest(formPost("nojs-envelope-cookie-return"));
46+
expect(response.status).toBe(303);
47+
expect(sessions(response)).toEqual(["session=abc; Path=/"]);
48+
});
49+
50+
it("a thrown envelope with a value keeps its Set-Cookie", async () => {
51+
registerServerFunction("nojs-envelope-cookie-throw", async () => {
52+
throw respond(
53+
{ error: "bad" },
54+
{ status: 400, headers: { "Set-Cookie": "session=abc; Path=/" } }
55+
);
56+
});
57+
const response = await handleServerFunctionRequest(formPost("nojs-envelope-cookie-throw"));
58+
expect(sessions(response)).toEqual(["session=abc; Path=/"]);
59+
});
60+
61+
it("a custom handleNoJS answer also keeps the envelope's Set-Cookie", async () => {
62+
registerServerFunction("nojs-envelope-cookie-custom", async () =>
63+
respond({ ok: true }, { headers: { "Set-Cookie": "session=abc; Path=/" } })
64+
);
65+
const response = await handleServerFunctionRequest(formPost("nojs-envelope-cookie-custom"), {
66+
handleNoJS: async () => Response.redirect("https://app.example/done", 303)
67+
});
68+
expect(response.headers.get("Location")).toBe("https://app.example/done");
69+
expect(sessions(response)).toEqual(["session=abc; Path=/"]);
70+
});
71+
72+
it("control: a void envelope already keeps it", async () => {
73+
registerServerFunction("nojs-envelope-cookie-void", async () =>
74+
respond(undefined, { headers: { "Set-Cookie": "session=abc; Path=/" } })
75+
);
76+
const response = await handleServerFunctionRequest(formPost("nojs-envelope-cookie-void"));
77+
expect(sessions(response)).toEqual(["session=abc; Path=/"]);
78+
});
79+
});

0 commit comments

Comments
 (0)