feat(bootstrap): 세션 owner context에 시간 제한 있는 fetch와 페이지를 준다

문제: composeProductSessionOwner는 config와 raw fetcher만 받는다. owner는
http보다 먼저 만들어져 세션 조회·토큰 호출을 직접 해야 하는데, 응답하지
않는 호출 하나가 세션을 recovery-pending에 영원히 둔다. 픽스처의 쿠키
owner 스케치가 바로 그렇게 쓴다. 로그인 리다이렉트에 필요한 페이지
(location·history)와 sessionStorage도 bootstrap lint가 전역 접근을 막아
제품 파일에서 얻을 길이 없다.

고른 방법: ProductSessionOwnerContext에 넷을 더한다.
- fetch: 헤더와 본문 전체에 마감 하나(REQUEST_TIMEOUT_MS가 상한, 호출이
  줄일 수만 있다). 본문은 64 KiB까지 메모리로 읽어 새 Response로 준다.
  redirect는 항상 error. fetcher가 signal을 무시해도 경합으로 끝난다.
- readCookie: composeProduct와 같은 host cookie 읽기.
- page: href·replaceUrl·assign. host에 없으면 throw로 닫힌다.
  replaceUrl은 라우터의 history state를 그대로 둔다.
- redirectStorage: host sessionStorage. 토큰이 아니라 리다이렉트 한 번
  동안의 상태만 둔다고 계약에 적었다.
조립은 새 파일 product-session-owner-context.ts에 두고
runtime-adapters.ts는 호출 한 곳만 바꿨다. fetch 구현
(session-owner-fetch.ts)은 처음 쓸 때 동적 import로 읽는다. 초기 번들
여유가 3 KB 남짓이라 demo 모드나 owner 없는 제품이 이 코드를 내려받지
않게 했다.
버린 대안:
- platform 커널 createAbortableOperation 사용. 커널이 boot가 이미 읽는
  배럴과 같은 청크로 묶여 지연 청크로 빼도 초기 번들에 남았다(빌드로
  확인). 그래서 read-bounded-boot-json.ts와 같은 마감 방식을 쓴다.
- 마감만 주고 본문은 owner가 읽게 두기. 본문이 멈추면 다시 무한 대기다.

위험·한계: fetch는 필수 필드라 ProductSessionOwnerContext를 직접 만드는
제품 테스트는 컴파일이 깨진다. 기존 fetcher는 그대로 둔다. 지연 청크
적재 시간은 마감에 들어가지 않는다(라우트 청크와 같다).

검증: tests/unit/product-session-owner-context.test.ts 12건(구현 전 모듈
없음으로 실패 확인), product-composition-fixture·runtime-adapters 테스트
통과, check:types, eslint 통과. build + check:bundle: initial JS
202,242 / 204,800 B gzip(09-11 포함, 기준 201,848), 지연 청크
session-owner-fetch 0.81 kB gzip.

Refs: docs/reviews/2026-11-03-maturity-review/09-app-core.md 09-03
This commit is contained in:
DongHyeonka
2026-11-04 20:46:40 +09:00
parent d7c6cb4fd2
commit d02efe7bc9
5 changed files with 553 additions and 4 deletions
@@ -12,6 +12,28 @@ import type { RuntimeConfig } from "./runtime-config-schema.ts";
* profiles and runtime-config keys) and never edits `runtime-adapters.ts`.
*/
/**
* 1103/09-03. A fetch with one deadline over the whole exchange (at most
* `REQUEST_TIMEOUT_MS`; `timeoutMs` may shorten it) and the body read into
* memory, at most 64 KiB. Rejects with a `TimeoutError` or `AbortError`
* DOMException, or a `RangeError` for a larger body. Redirects are refused.
*/
export type SessionOwnerFetch = (
input: string | URL,
init?: Omit<RequestInit, "signal" | "redirect"> &
Readonly<{ signal?: AbortSignal; timeoutMs?: number }>,
) => Promise<Response>;
/** The page a sign-in redirect leaves and returns to. Each throws without one. */
export type ProductSessionOwnerPage = Readonly<{
/** The current URL. */
href(): string;
/** Replaces the current entry without loading, e.g. to drop a sign-in callback query. */
replaceUrl(url: string): void;
/** Loads another page: the identity provider's sign-in or sign-out. */
assign(url: string): void;
}>;
/**
* What a product session owner is built from. It is asked first, before
* `http` exists (`http` needs the session), so it gets no capability.
@@ -19,7 +41,19 @@ import type { RuntimeConfig } from "./runtime-config-schema.ts";
export type ProductSessionOwnerContext = Readonly<{
/** Validated runtime config, product keys included. */
config: RuntimeConfig;
/** Unbounded; prefer `fetch`. */
fetcher?: typeof fetch;
/** 1103/09-03. Use this one: a probe or token call cannot hang the session. */
fetch: SessionOwnerFetch;
/** A cookie of the page (double-submit CSRF), read when called. */
readCookie(name: string): string | undefined;
page: ProductSessionOwnerPage;
/**
* The page's session storage, when there is one: what must survive a
* sign-in redirect and nothing longer. Never a token (`AUTH_TOKEN` is
* `forbidden` in `src/contracts/storage-keys.ts`).
*/
redirectStorage?: Pick<Storage, "getItem" | "setItem" | "removeItem">;
}>;
/**
@@ -0,0 +1,102 @@
import type {
ProductSessionOwnerContext,
ProductSessionOwnerPage,
SessionOwnerFetch,
} from "./product-composition-contract.ts";
import type { RuntimeConfig } from "./runtime-config-schema.ts";
/**
* 1103/09-03. What the composition root hands a product session owner. The
* owner is asked at boot, before `http` exists, so it talks to its session
* endpoint or identity provider itself; these are the host facilities it needs
* for that, each bounded or fail-closed.
*/
/**
* `session-owner-fetch.ts` on first use. The initial bundle has no headroom
* for code only an external-mode product owner runs; the chunk is the size of
* a route chunk and loads the same way.
*/
function lazySessionOwnerFetch(
options: Readonly<{ fetcher?: typeof fetch; timeoutMs: number }>,
): SessionOwnerFetch {
let loaded: Promise<SessionOwnerFetch> | null = null;
return (input, init) => {
loaded ??= import("./session-owner-fetch.ts").then(
({ createSessionOwnerFetch }) => createSessionOwnerFetch(options),
(error: unknown) => {
loaded = null;
throw error;
},
);
return loaded.then((bounded) => bounded(input, init));
};
}
function hostMember(target: unknown, name: string): unknown {
if (!target || typeof target !== "object") return undefined;
try {
return Reflect.get(target, name);
} catch {
return undefined;
}
}
/**
* The page, read from the host when called. A host without `location` or
* `history` (a worker, a test) throws, so an owner that needs the page fails
* closed instead of signing in somewhere else.
*/
function hostPage(host: Record<string, unknown>): ProductSessionOwnerPage {
const unavailable = (): never => {
throw new TypeError("The page is unavailable to the session owner.");
};
const location = () => hostMember(host, "location");
return Object.freeze({
href() {
const href = hostMember(location(), "href");
return typeof href === "string" ? href : unavailable();
},
replaceUrl(url: string) {
const history = hostMember(host, "history");
const replaceState = hostMember(history, "replaceState");
if (typeof replaceState !== "function") unavailable();
// The router keeps its own entry state; replacing it would lose its index.
Reflect.apply(replaceState as (...args: unknown[]) => void, history, [
hostMember(history, "state") ?? null,
"",
url,
]);
},
assign(url: string) {
const page = location();
const assign = hostMember(page, "assign");
if (typeof assign !== "function") unavailable();
Reflect.apply(assign as (url: string) => void, page, [url]);
},
});
}
export function createProductSessionOwnerContext(
host: Record<string, unknown>,
input: Readonly<{
config: RuntimeConfig;
fetcher?: typeof fetch;
readCookie(name: string): string | undefined;
redirectStorage?: Storage;
}>,
): ProductSessionOwnerContext {
return Object.freeze({
config: input.config,
...(input.fetcher === undefined ? {} : { fetcher: input.fetcher }),
fetch: lazySessionOwnerFetch({
...(input.fetcher === undefined ? {} : { fetcher: input.fetcher }),
timeoutMs: input.config.REQUEST_TIMEOUT_MS,
}),
readCookie: input.readCookie,
page: hostPage(host),
...(input.redirectStorage === undefined
? {}
: { redirectStorage: input.redirectStorage }),
});
}
+10 -4
View File
@@ -63,6 +63,7 @@ import {
composeProductSessionOwner,
} from "./product-composition.ts";
import type { ProductComposition } from "./product-composition-contract.ts";
import { createProductSessionOwnerContext } from "./product-session-owner-context.ts";
import { createInstalledContractRegistry } from "../features/installed-contract-contributions.ts";
import {
indexInvalidationRegistry,
@@ -284,10 +285,15 @@ export async function createRuntimeAdapters(
const externalOwner =
config.AUTH_MODE === "demo"
? null
: (composeProductSessionOwner({
config,
...(context.fetcher === undefined ? {} : { fetcher: context.fetcher }),
}) ?? externalOwnerFrom(host));
: (composeProductSessionOwner(
// 1103/09-03. A bounded fetch, the page and its cookies.
createProductSessionOwnerContext(host, {
config,
...(context.fetcher === undefined ? {} : { fetcher: context.fetcher }),
readCookie: (name) => hostCookie(host, name),
redirectStorage: storageOrUndefined(hostValue(host, "sessionStorage")),
}),
) ?? externalOwnerFrom(host));
const authSession =
config.AUTH_MODE === "demo"
? createDemoSessionAdapter()
+134
View File
@@ -0,0 +1,134 @@
import type { SessionOwnerFetch } from "./product-composition-contract.ts";
/**
* 1103/09-03. The fetch a product session owner gets. Loaded on first use,
* from `product-session-owner-context.ts`, so it costs the initial bundle
* nothing in demo mode or without a product owner. It does not use the
* platform kernel's `createAbortableOperation`: the kernel shares a chunk
* with the barrel boot already imports, so it would land in the initial
* bundle after all. The deadline is the one `read-bounded-boot-json.ts` uses.
*/
/** A session or token response is a few KiB; this is the most an owner buffers. */
export const SESSION_OWNER_FETCH_MAXIMUM_BYTES = 65_536;
/** Statuses whose `Response` cannot carry a body. */
const NULL_BODY_STATUSES: ReadonlySet<number> = new Set([101, 103, 204, 205, 304]);
/**
* One deadline over the whole exchange, headers and body. The body is read
* into memory up to `maximumBytes` and handed back as a fresh `Response`, so
* the owner reads it without a second, unbounded wait. `timeoutMs` is a
* ceiling: a call may shorten it, never extend it. Redirects are refused: a
* session endpoint that redirects to a sign-in page must not read as an
* answer.
*/
export function createSessionOwnerFetch(
options: Readonly<{
fetcher?: typeof fetch;
timeoutMs: number;
maximumBytes?: number;
}>,
): SessionOwnerFetch {
const fetcher = options.fetcher ?? fetch;
const maximumBytes = options.maximumBytes ?? SESSION_OWNER_FETCH_MAXIMUM_BYTES;
return async (input, init = {}) => {
const { signal, timeoutMs, ...request } = init;
const controller = new AbortController();
let timedOut = false;
const timer = setTimeout(
() => {
timedOut = true;
controller.abort();
},
Math.min(timeoutMs ?? options.timeoutMs, options.timeoutMs),
);
const forwardAbort = () => controller.abort();
if (signal?.aborted) controller.abort();
else signal?.addEventListener("abort", forwardAbort, { once: true });
// Raced, not only signalled: a fetcher that ignores the signal is still
// bounded, and so is a body stream that stops sending.
const stopped = new Promise<never>((_, reject) => {
const stop = () =>
reject(
timedOut
? new DOMException("The session owner request timed out.", "TimeoutError")
: new DOMException("The session owner request was aborted.", "AbortError"),
);
if (controller.signal.aborted) stop();
else controller.signal.addEventListener("abort", stop, { once: true });
});
stopped.catch(() => undefined);
const sending = Promise.resolve().then(() =>
fetcher(input, {
cache: "no-store",
...request,
redirect: "error",
signal: controller.signal,
}),
);
// A response that lands after the deadline is released, not left open.
void sending.then(
(late) => {
if (controller.signal.aborted) void late.body?.cancel().catch(() => undefined);
},
() => undefined,
);
try {
const response = await Promise.race([sending, stopped]);
const reading = readBody(response, maximumBytes, controller.signal);
reading.catch(() => undefined);
const bytes = await Promise.race([reading, stopped]);
return new Response(NULL_BODY_STATUSES.has(response.status) ? null : bytes, {
status: response.status,
statusText: response.statusText,
headers: response.headers,
});
} finally {
clearTimeout(timer);
signal?.removeEventListener("abort", forwardAbort);
}
};
}
async function readBody(
response: Response,
maximumBytes: number,
signal: AbortSignal,
): Promise<Uint8Array<ArrayBuffer>> {
const declared = Number(response.headers.get("content-length"));
if (Number.isFinite(declared) && declared > maximumBytes) {
void response.body?.cancel().catch(() => undefined);
throw new RangeError("The session owner response is too large.");
}
const body = response.body;
if (!body) return new Uint8Array(0);
const reader = body.getReader();
// The deadline releases the stream even when the fetcher ignored the signal.
signal.addEventListener("abort", () => void reader.cancel().catch(() => undefined), {
once: true,
});
const chunks: Uint8Array[] = [];
let total = 0;
try {
for (;;) {
const { done, value } = await reader.read();
if (done) break;
total += value.byteLength;
if (total > maximumBytes) {
throw new RangeError("The session owner response is too large.");
}
chunks.push(value);
}
} catch (error) {
void reader.cancel().catch(() => undefined);
throw error;
}
const bytes = new Uint8Array(total);
let offset = 0;
for (const chunk of chunks) {
bytes.set(chunk, offset);
offset += chunk.byteLength;
}
return bytes;
}
@@ -0,0 +1,273 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import type { ProductSessionOwnerContext } from "../../src/bootstrap/product-composition-contract.ts";
import {
createSessionOwnerFetch,
SESSION_OWNER_FETCH_MAXIMUM_BYTES,
} from "../../src/bootstrap/session-owner-fetch.ts";
import { createRuntimeAdapters } from "../../src/bootstrap/runtime-adapters.ts";
import { validateRuntimeConfig } from "../../src/bootstrap/runtime-config-schema.ts";
/**
* 1103/09-03. A session owner is asked for at boot, before `http` exists, and
* the shipped context gave it a raw `fetcher`: a session probe or a token call
* that never answered left the session `recovery-pending` for good. The
* context now carries a fetch with one deadline over the whole exchange.
*/
const fixture = vi.hoisted(() => ({
context: undefined as ProductSessionOwnerContext | undefined,
}));
vi.mock("../../src/bootstrap/product-composition.ts", () => ({
composeProductSessionOwner(context: ProductSessionOwnerContext) {
fixture.context = context;
return null;
},
composeProduct: () => ({ capabilities: {}, credentialProviders: {} }),
}));
const never = () => new Promise<Response>(() => {});
/** A body that sends one chunk and then nothing. */
function stalledBody(): ReadableStream<Uint8Array> {
return new ReadableStream({
start(controller) {
controller.enqueue(new TextEncoder().encode("{"));
},
});
}
describe("createSessionOwnerFetch", () => {
it("answers with the whole body read, status and headers kept", async () => {
const fetcher = vi.fn(async () =>
Response.json({ sub: "user-1" }, { status: 201, headers: { "x-extra": "1" } }),
);
const bounded = createSessionOwnerFetch({ fetcher, timeoutMs: 1_000 });
const response = await bounded("https://idp.example/token", {
method: "POST",
credentials: "omit",
});
expect(response.status).toBe(201);
expect(response.headers.get("x-extra")).toBe("1");
await expect(response.json()).resolves.toEqual({ sub: "user-1" });
const [, init] = fetcher.mock.calls[0] as unknown as [string, RequestInit];
expect(init).toMatchObject({
method: "POST",
credentials: "omit",
cache: "no-store",
redirect: "error",
});
expect(init.signal).toBeInstanceOf(AbortSignal);
});
it("refuses to follow a redirect even when asked", async () => {
const fetcher = vi.fn(async () => new Response("{}"));
const bounded = createSessionOwnerFetch({ fetcher, timeoutMs: 1_000 });
await bounded("https://api.example/session", {
redirect: "follow",
} as unknown as Parameters<typeof bounded>[1]);
expect((fetcher.mock.calls[0] as unknown as [string, RequestInit])[1].redirect).toBe("error");
});
it("times out a request that never answers", async () => {
const bounded = createSessionOwnerFetch({ fetcher: never, timeoutMs: 20 });
await expect(bounded("https://api.example/session")).rejects.toMatchObject({
name: "TimeoutError",
});
});
it("times out a body that stops arriving: the deadline covers the body", async () => {
const bounded = createSessionOwnerFetch({
fetcher: async () => new Response(stalledBody()),
timeoutMs: 20,
});
await expect(bounded("https://api.example/session")).rejects.toMatchObject({
name: "TimeoutError",
});
});
it("lets one call shorten the deadline but never extend it", async () => {
const shorter = createSessionOwnerFetch({ fetcher: never, timeoutMs: 10_000 });
const started = Date.now();
await expect(
shorter("https://api.example/session", { timeoutMs: 20 }),
).rejects.toMatchObject({ name: "TimeoutError" });
expect(Date.now() - started).toBeLessThan(5_000);
const capped = createSessionOwnerFetch({ fetcher: never, timeoutMs: 20 });
await expect(
capped("https://api.example/session", { timeoutMs: 60_000 }),
).rejects.toMatchObject({ name: "TimeoutError" });
});
it("stops when the caller aborts", async () => {
const bounded = createSessionOwnerFetch({ fetcher: never, timeoutMs: 10_000 });
const caller = new AbortController();
const pending = bounded("https://api.example/session", { signal: caller.signal });
caller.abort();
await expect(pending).rejects.toMatchObject({ name: "AbortError" });
});
it("refuses a body over the cap and cancels it", async () => {
const cancel = vi.fn();
const chunk = new Uint8Array(SESSION_OWNER_FETCH_MAXIMUM_BYTES);
const body = new ReadableStream<Uint8Array>({
pull(controller) {
controller.enqueue(chunk);
},
cancel,
});
const bounded = createSessionOwnerFetch({
fetcher: async () => new Response(body),
timeoutMs: 1_000,
});
await expect(bounded("https://api.example/session")).rejects.toBeInstanceOf(RangeError);
expect(cancel).toHaveBeenCalled();
});
it("passes the fetcher's own rejection through", async () => {
const bounded = createSessionOwnerFetch({
fetcher: async () => {
throw new TypeError("Failed to fetch");
},
timeoutMs: 1_000,
});
await expect(bounded("https://api.example/session")).rejects.toThrow("Failed to fetch");
});
it("answers a body-less status without a body", async () => {
const bounded = createSessionOwnerFetch({
fetcher: async () => new Response(null, { status: 204 }),
timeoutMs: 1_000,
});
const response = await bounded("https://api.example/sign-out", { method: "POST" });
expect(response.status).toBe(204);
expect(response.body).toBeNull();
});
});
const CONFIG = {
APP_ENV: "local",
API_BASE_URL: "http://localhost:8080",
REQUEST_TIMEOUT_MS: 150,
TELEMETRY_ENABLED: false,
AUTH_MODE: "external",
CONFIG_SCHEMA_VERSION: "2.0",
RELEASE_MANIFEST_URL: "/release-manifest.json",
CAPABILITY_OVERRIDES: {
REALTIME: "DEFAULT",
WEB_WORKER: "DEFAULT",
SERVICE_WORKER: "DEFAULT",
OFFLINE_COMMANDS: "DEFAULT",
},
FEATURE_OVERRIDES: {},
} as const;
describe("the session owner context the composition root builds", () => {
let dispose: (() => void) | undefined;
afterEach(() => {
dispose?.();
dispose = undefined;
fixture.context = undefined;
});
async function compose(host: Record<string, unknown>, fetcher: typeof fetch) {
const validated = validateRuntimeConfig(CONFIG);
if (!validated.success) throw new Error(JSON.stringify(validated.issues));
const adapters = await createRuntimeAdapters({
runtime: {
config: validated.data,
configSchema: "V2",
build: {
buildId: "build-a",
commitSha: "abc123",
routerBasePath: "/",
runtimeConfigUrl: "/config.json",
},
validationDurationMs: 0,
},
release: {
schemaVersion: 2,
appVersion: "0.1.0",
buildId: "build-a",
commitSha: "abc123",
configSchemaVersion: "2.0",
contractSet: {
setAlgorithm: "CA_CONTRACT_SET_V1",
setDigest: `sha256:${"0".repeat(64)}`,
packages: [],
},
assetManifestHash: "hash-a",
releaseId: "release-a",
builtAt: "2026-07-25T00:00:00Z",
routeChunks: { "route-home": "assets/home.js" },
},
host,
fetcher,
});
dispose = () => adapters.infrastructure.dispose();
const context = fixture.context;
if (!context) throw new Error("the session owner was not asked");
return context;
}
it("bounds the owner's fetch by REQUEST_TIMEOUT_MS", async () => {
const context = await compose({}, never as unknown as typeof fetch);
await expect(context.fetch("http://localhost:8080/session")).rejects.toMatchObject({
name: "TimeoutError",
});
});
it("reads the page, its session storage and its cookies through the host", async () => {
const replaceState = vi.fn();
const assign = vi.fn();
const storage = new Map<string, string>();
const sessionStorage = {
getItem: (key: string) => storage.get(key) ?? null,
setItem: (key: string, value: string) => void storage.set(key, value),
removeItem: (key: string) => void storage.delete(key),
};
const context = await compose(
{
location: { href: "http://localhost:5173/callback?code=c&state=s", assign },
history: { state: { idx: 3 }, replaceState },
sessionStorage,
document: { cookie: "theme=dark; XSRF-TOKEN=xsrf-1" },
},
(async () => new Response("{}")) as unknown as typeof fetch,
);
expect(context.page.href()).toBe("http://localhost:5173/callback?code=c&state=s");
context.page.replaceUrl("/items?limit=1");
// The router's own history state is kept, so its index survives.
expect(replaceState).toHaveBeenCalledWith({ idx: 3 }, "", "/items?limit=1");
context.page.assign("https://idp.example/auth");
expect(assign).toHaveBeenCalledWith("https://idp.example/auth");
context.redirectStorage?.setItem("k", "v");
expect(storage.get("k")).toBe("v");
expect(context.readCookie("XSRF-TOKEN")).toBe("xsrf-1");
});
it("fails closed when the host has no page", async () => {
const context = await compose({}, (async () => new Response("{}")) as unknown as typeof fetch);
expect(context.redirectStorage).toBeUndefined();
expect(() => context.page.href()).toThrow("page is unavailable");
expect(() => context.page.assign("https://idp.example/auth")).toThrow("page is unavailable");
expect(context.readCookie("XSRF-TOKEN")).toBeUndefined();
});
});