Skip to content

A one-of-a-kind resume builder that keeps your privacy in mind. Completely secure, customizable, portable, open-source and free forever. Try it out today!

fix: read batch account bindings case-insensitively

Amruth Pillaic6dfdaa53bda
diff --git a/apps/server/src/rpc/account-header.test.ts b/apps/server/src/rpc/account-header.test.ts
new file mode 100644
index 000000000..5989bde9b
--- /dev/null
+++ b/apps/server/src/rpc/account-header.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from "vite-plus/test";
+import { readAccountBinding } from "./account-header";
+
+describe("readAccountBinding", () => {
+ it.each(["x-account-id", "X-Account-Id", "X-ACCOUNT-ID", "X-Account-ID"])(
+ "reads the binding regardless of header casing (%s)",
+ (headerName) => {
+ expect(readAccountBinding({ [headerName]: "bob" })).toBe("bob");
+ },
+ );
+
+ it("treats repeated equal values as one binding", () => {
+ expect(readAccountBinding({ "x-account-id": ["bob", "bob"] })).toBe("bob");
+ expect(readAccountBinding({ "x-account-id": "bob", "X-Account-Id": "bob" })).toBe("bob");
+ });
+
+ it("keeps conflicting values from matching an account", () => {
+ expect(readAccountBinding({ "x-account-id": ["alice", "bob"] })).toBe("alice, bob");
+ expect(readAccountBinding({ "x-account-id": "alice", "X-Account-Id": "bob" })).toBe("alice, bob");
+ });
+
+ it.each([undefined, "", " "])("treats an absent or empty binding as legacy (%j)", (value) => {
+ expect(readAccountBinding(value === undefined ? {} : { "x-account-id": value })).toBeUndefined();
+ });
+
+ it("ignores headers that are not the binding", () => {
+ expect(readAccountBinding({ cookie: "session=1", authorization: "Bearer token" })).toBeUndefined();
+ });
+
+ it("ignores malformed header names without losing a valid binding", () => {
+ expect(readAccountBinding({ "bad header": "value", "x-account-id": "bob" })).toBe("bob");
+ });
+});
diff --git a/apps/server/src/rpc/account-header.ts b/apps/server/src/rpc/account-header.ts
new file mode 100644
index 000000000..10bc73902
--- /dev/null
+++ b/apps/server/src/rpc/account-header.ts
@@ -0,0 +1,29 @@
+/**
+ * Batch items keep the wire casing of their header names, so an item may spell the binding `X-Account-Id`. Read it
+ * through the platform's case-insensitive Headers view instead of matching a raw JSON key: `X-Account-Id` and
+ * `x-account-id` are the same binding, duplicate values collapse when they agree, and conflicting duplicates stay a
+ * value that cannot match an account id (the every-known-binding check then fails closed). Only this header is read
+ * here; cookies and tokens never contribute to the binding.
+ */
+export function readAccountBinding(headers: Record<string, string | string[] | undefined>) {
+ const view = new Headers();
+ for (const [name, value] of Object.entries(headers)) {
+ if (value === undefined) continue;
+ for (const entry of Array.isArray(value) ? value : [value]) {
+ try {
+ view.append(name, entry);
+ } catch {
+ // Ignore malformed header names; they cannot be the account binding.
+ }
+ }
+ }
+ const raw = view.get("x-account-id");
+ if (raw === null) return undefined;
+ const values = raw
+ .split(",")
+ .map((value) => value.trim())
+ .filter(Boolean);
+ const [first] = values;
+ if (!first) return undefined;
+ return values.every((value) => value === first) ? first : raw;
+}
diff --git a/apps/server/src/rpc/handler.ts b/apps/server/src/rpc/handler.ts
index 4edfc6219..f25362c54 100644
--- a/apps/server/src/rpc/handler.ts
+++ b/apps/server/src/rpc/handler.ts
@@ -3,6 +3,7 @@ import { RPCHandler } from "@orpc/server/fetch";
import { BatchHandlerPlugin, RequestHeadersPlugin, StrictGetMethodPlugin } from "@orpc/server/plugins";
import router from "@reactive-resume/api/routers";
import { mergeResponseHeaders } from "../http/headers";
+import { readAccountBinding } from "./account-header";
import { getRequestLocale } from "./locale";
const rpcHandler = new RPCHandler(router, {
@@ -11,8 +12,7 @@ const rpcHandler = new RPCHandler(router, {
// carry its own account expectation; authentication keeps using the envelope, so an item cannot swap the cookie.
rootInterceptors: [
(interceptorOptions) => {
- const header = interceptorOptions.request.headers["x-account-id"];
- const accountId = Array.isArray(header) ? header[0] : header;
+ const accountId = readAccountBinding(interceptorOptions.request.headers);
return interceptorOptions.next({
...interceptorOptions,
context: {
diff --git a/apps/web/src/libs/orpc/account-binding.integration.test.ts b/apps/web/src/libs/orpc/account-binding.integration.test.ts
index 870bae7be..5eff479fc 100644
--- a/apps/web/src/libs/orpc/account-binding.integration.test.ts
+++ b/apps/web/src/libs/orpc/account-binding.integration.test.ts
@@ -1,9 +1,9 @@
-import { afterAll, beforeAll, describe, expect, it, vi } from "vite-plus/test";
// @vitest-environment node
+import { afterAll, beforeAll, describe, expect, it, vi } from "vite-plus/test";
/**
* Real transport + real HTTP regression for account-bound writes. Runs only when RX106_BINDING_APP_URL points at a
- * disposable server whose database is DATABASE_URL; every account is synthetic and deleted afterwards.
+ * disposable server; every account is synthetic and deleted afterwards.
*/
const appUrl = process.env.RX106_BINDING_APP_URL;
@@ -235,6 +235,168 @@ describe.skipIf(!appUrl)("account binding over the real transport", () => {
}
}, 60_000);
+ it("reads item bindings case-insensitively in streaming and buffered batches", async () => {
+ type Mode = "streaming" | "buffered";
+ const item = (
+ accountId: string | null,
+ payload: Record<string, unknown>,
+ headerName = "x-account-id",
+ extraHeaders: Record<string, string> = {},
+ ) => ({
+ url: `${appUrl}/api/rpc/career/saveProfile`,
+ headers: {
+ "content-type": "application/json",
+ ...(accountId ? { [headerName]: accountId } : {}),
+ ...extraHeaders,
+ },
+ body: { json: payload },
+ });
+ const runBatch = async (mode: Mode, envelope: string | null, items: ReturnType<typeof item>[]) => {
+ const response = await realFetch(`${appUrl}/api/rpc/__batch__`, {
+ method: "POST",
+ headers: {
+ origin: appUrl ?? "",
+ "content-type": "application/json",
+ "x-orpc-batch": mode,
+ cookie: bob.cookie,
+ ...(envelope ? { "x-account-id": envelope } : {}),
+ },
+ body: JSON.stringify(items),
+ });
+ if (mode === "buffered") {
+ const body = (await response.json()) as Array<{ index: number; status?: number }>;
+ const statuses = body.sort((left, right) => left.index - right.index).map((entry) => entry.status ?? 207);
+ return { status: response.status, statuses };
+ }
+ const text = await response.text();
+ const statuses = [...text.matchAll(/data: (\{.*\})/g)]
+ .map((match) => JSON.parse(match[1] as string) as { index: number; status: number })
+ .sort((left, right) => left.index - right.index)
+ .map((entry) => entry.status);
+ return { status: response.status, statuses };
+ };
+ const baseline = async () => {
+ const response = await realFetch(`${appUrl}/api/openapi/career/profile`, {
+ method: "PUT",
+ headers: { cookie: bob.cookie, "content-type": "application/json" },
+ body: JSON.stringify({ ...bobPayload, priorities: "baseline" }),
+ });
+ expect(response.ok).toBe(true);
+ };
+
+ const bobWrite = { ...bobPayload, priorities: "case-bob" };
+ const aliceWrite = { ...alicePayload, priorities: "case-alice" };
+ const cases: Array<{
+ name: string;
+ mode: Mode;
+ envelope: string | null;
+ items: ReturnType<typeof item>[];
+ statuses: number[];
+ stored: string;
+ }> = [];
+ for (const mode of ["streaming", "buffered"] as const) {
+ cases.push(
+ {
+ name: `${mode}: uppercase stale item`,
+ mode,
+ envelope: bob.id,
+ items: [item(alice.id, aliceWrite, "X-Account-Id")],
+ statuses: [409],
+ stored: "baseline",
+ },
+ {
+ name: `${mode}: mixed-case stale item`,
+ mode,
+ envelope: bob.id,
+ items: [item(alice.id, aliceWrite, "X-Account-ID")],
+ statuses: [409],
+ stored: "baseline",
+ },
+ {
+ name: `${mode}: uppercase matching item`,
+ mode,
+ envelope: bob.id,
+ items: [item(bob.id, bobWrite, "X-Account-Id")],
+ statuses: [200],
+ stored: "case-bob",
+ },
+ {
+ name: `${mode}: conflicting envelope and mixed-case item`,
+ mode,
+ envelope: alice.id,
+ items: [item(bob.id, bobWrite, "X-Account-ID")],
+ statuses: [409],
+ stored: "baseline",
+ },
+ {
+ name: `${mode}: headerless legacy item`,
+ mode,
+ envelope: null,
+ items: [item(null, bobWrite)],
+ statuses: [200],
+ stored: "case-bob",
+ },
+ );
+ }
+ for (const entry of cases) {
+ await baseline();
+ const result = await runBatch(entry.mode, entry.envelope, entry.items);
+ expect(result.status, entry.name).toBe(207);
+ expect(result.statuses, entry.name).toEqual(entry.statuses);
+ expect((await profile(bob.cookie)).priorities, entry.name).toBe(entry.stored);
+ expect((await profile(alice.cookie)).priorities, entry.name).toBe("Alice private priorities");
+ }
+ }, 60_000);
+
+ it("keeps authentication envelope-bound when an item carries its own cookie or bearer", async () => {
+ const item = (payload: Record<string, unknown>, extraHeaders: Record<string, string>) => ({
+ url: `${appUrl}/api/rpc/career/saveProfile`,
+ headers: { "content-type": "application/json", "x-account-id": bob.id, ...extraHeaders },
+ body: { json: payload },
+ });
+ const runBatch = async (items: ReturnType<typeof item>[]) => {
+ const response = await realFetch(`${appUrl}/api/rpc/__batch__`, {
+ method: "POST",
+ headers: {
+ origin: appUrl ?? "",
+ "content-type": "application/json",
+ "x-orpc-batch": "streaming",
+ cookie: bob.cookie,
+ "x-account-id": bob.id,
+ },
+ body: JSON.stringify(items),
+ });
+ const text = await response.text();
+ const statuses = [...text.matchAll(/data: (\{.*\})/g)]
+ .map((match) => JSON.parse(match[1] as string) as { index: number; status: number })
+ .sort((left, right) => left.index - right.index)
+ .map((entry) => entry.status);
+ return { status: response.status, statuses };
+ };
+ const baseline = async () => {
+ const response = await realFetch(`${appUrl}/api/openapi/career/profile`, {
+ method: "PUT",
+ headers: { cookie: bob.cookie, "content-type": "application/json" },
+ body: JSON.stringify({ ...bobPayload, priorities: "baseline" }),
+ });
+ expect(response.ok).toBe(true);
+ };
+
+ await baseline();
+ const withCookie = await runBatch([item({ ...bobPayload, priorities: "item-cookie" }, { cookie: alice.cookie })]);
+ expect(withCookie.statuses).toEqual([200]);
+ expect((await profile(bob.cookie)).priorities).toBe("item-cookie");
+ expect((await profile(alice.cookie)).priorities).toBe("Alice private priorities");
+
+ await baseline();
+ const withBearer = await runBatch([
+ item({ ...bobPayload, priorities: "item-bearer" }, { authorization: "Bearer garbage" }),
+ ]);
+ expect(withBearer.statuses).toEqual([200]);
+ expect((await profile(bob.cookie)).priorities).toBe("item-bearer");
+ expect((await profile(alice.cookie)).priorities).toBe("Alice private priorities");
+ }, 60_000);
+
it("allows a call bound to the signed-in account", async () => {
const { setAccountScope } = await import("@/libs/auth/account-scope");
const { client } = await import("./client");
diff --git a/apps/web/src/libs/orpc/fetch.test.ts b/apps/web/src/libs/orpc/fetch.test.ts
index 59de41576..53f63bcfc 100644
--- a/apps/web/src/libs/orpc/fetch.test.ts
+++ b/apps/web/src/libs/orpc/fetch.test.ts
@@ -32,6 +32,8 @@ describe("RPC fetch", () => {
it("uploads large wire bytes to Blob, then sends a tiny reference to the original RPC", async () => {
queueStaging();
+ const { setAccountScope } = await import("@/libs/auth/account-scope");
+ setAccountScope("alice");
const { rpcFetch } = await import("./fetch");
const result = await rpcFetch(
new Request(rpcUrl, {
@@ -62,6 +64,7 @@ describe("RPC fetch", () => {
expect(headers.get("content-type")).toBe(contentType);
expect(headers.get("x-example")).toBe("preserved");
expect(headers.get("x-client-timezone")).toBe(Intl.DateTimeFormat().resolvedOptions().timeZone);
+ expect(headers.get("x-account-id")).toBe("alice");
});
it("sends large requests directly once staging is unavailable on Docker", async () => {