문제
조립 루트는 응답이 있는 UNAUTHENTICATED면 프로필을 보지 않고
authSession.onUnauthenticated()를 불렀다. ANONYMOUS 요청은 세션을 묻지 않고
헤더 없이 나가는데도, 그 401이 로그인한 사용자를 로그아웃시키고 scope fence가
서버 상태 캐시를 모두 비웠다. 제품 credentialProviders가 자격 증명을 낸
요청의 401도 템플릿 세션을 로그아웃시켰다.
고른 방법
attachCredentials와 같은 순서로 401의 주인을 가른다(reportServerUnauthenticated).
- ANONYMOUS 프로필: 아무에게도 알리지 않는다.
- 제품 provider 프로필: 세션은 그대로 두고, ProductComposition의 선택 hook
onCredentialRejected({operationId, authProfileId})를 부른다. BFF 제품은
거기서 자기 owner에게 알린다. hook의 throw는 결과를 바꾸지 않는다.
- 나머지(템플릿 세션이 낸 자격 증명): 지금처럼 onUnauthenticated().
버린 대안: ANONYMOUS만 빼기(2줄)는 provider 경로의 과잉 로그아웃이 남는다.
owner가 401을 직접 판단하게 하면 owner 계약이 바뀌고 모든 owner가 판단
로직을 쓴다.
위험·한계
- 제품 provider가 템플릿 세션과 같은 세션의 자격 증명을 내는 경우, 제품이
hook을 쓰지 않으면 그 401은 세션을 바꾸지 않는다. 계약 주석과 매뉴얼 02
5절에 적었다.
- 401 도착과 계정 전환이 겹치는 경쟁은 여전히 확인하지 않았다.
검증
- RED: 새 테스트 3건(ANONYMOUS 401 demo·external, provider 401)이 수정 전
실패했다. bearer 대조군은 수정 전후 모두 통과.
- node scripts/run-vitest.ts run runtime-adapters-{auth-profile,credential-order},
runtime-adapters, product-composition-fixture, reference-runtime-composition
→ 5 files / 62 tests 통과. check:types 통과. eslint 통과.
Refs: docs/reviews/2026-11-03-maturity-review/09-app-core.md 09-01
704 lines
25 KiB
TypeScript
704 lines
25 KiB
TypeScript
import {
|
|
createDemoSessionAdapter,
|
|
createExternalAuthSessionAdapter,
|
|
createUnavailableSessionAdapter,
|
|
type ExternalSessionOwner,
|
|
} from "../adapters/auth/index.ts";
|
|
import { createDiagnosticsAdapter } from "../adapters/diagnostics/index.ts";
|
|
import {
|
|
createContractHttpExecutor,
|
|
type HttpExecutionObservation,
|
|
type InstalledHttpOperationExecutor,
|
|
} from "../adapters/http/index.ts";
|
|
import {
|
|
attemptBucket,
|
|
durationBucket,
|
|
statusGroup,
|
|
type DiagnosticRecordInput,
|
|
} from "../contracts/diagnostics.ts";
|
|
import type { TelemetryEventName } from "../contracts/telemetry.ts";
|
|
import {
|
|
createBrowserCrossContextInvalidationFromHost,
|
|
crossContextCacheEpochForRelease,
|
|
} from "../adapters/cross-context-invalidation/index.ts";
|
|
import {
|
|
createConditionalValidatorStore,
|
|
createQueryClient,
|
|
createServerStateScopeRuntime,
|
|
createTanStackCacheCoordinator,
|
|
} from "../adapters/query-cache/index.ts";
|
|
import { createBrowserStorageAdapter } from "../adapters/storage/index.ts";
|
|
import { createBrowserMutationIntentFactory } from "../adapters/platform/index.ts";
|
|
import {
|
|
createFeatureTelemetry,
|
|
createTelemetryAdapter,
|
|
createTelemetryCollector,
|
|
} from "../adapters/telemetry/index.ts";
|
|
import type { ReleaseInfo } from "../application/ports/release-info-port.ts";
|
|
import { INSTALLED_REST_AUTH_PROFILES } from "../contracts/rest-profiles.ts";
|
|
import { createInstalledFeatureLoaders } from "../features/installed-feature-adapters.ts";
|
|
import {
|
|
INVALIDATION_REGISTRY,
|
|
INVALIDATION_TOPIC_VERSIONS,
|
|
} from "../features/installed-feature-contracts.ts";
|
|
import { INSTALLED_RUNTIME_CAPABILITIES } from "../features/installed-runtime-capabilities.ts";
|
|
import {
|
|
COMPILED_PRODUCT_FEATURE_IDS,
|
|
INSTALLED_PRODUCT_FEATURE_IDS,
|
|
} from "../features/installed-product-manifest.ts";
|
|
import {
|
|
activeProductFeatureIds,
|
|
resolveProductFeatures,
|
|
unknownProductFeatureOverrides,
|
|
} from "../contracts/product-features.ts";
|
|
import { describeRuntimeCapabilities } from "../contracts/runtime-capabilities.ts";
|
|
import {
|
|
fetchReleaseManifest,
|
|
type ReleaseManifest,
|
|
} from "./load-release-manifest.ts";
|
|
import type { RuntimeConfigLoadResult } from "./load-runtime-config.ts";
|
|
import { createServerStateGenerationStore } from "./server-state-generation-store.ts";
|
|
import {
|
|
composeProduct,
|
|
composeProductSessionOwner,
|
|
} from "./product-composition.ts";
|
|
import type { ProductComposition } from "./product-composition-contract.ts";
|
|
import { createInstalledContractRegistry } from "../features/installed-contract-contributions.ts";
|
|
import {
|
|
indexInvalidationRegistry,
|
|
indexInvalidationTopicVersions,
|
|
} from "../contracts/query-invalidation.ts";
|
|
|
|
export type RuntimeAdaptersContext = Readonly<{
|
|
runtime: RuntimeConfigLoadResult;
|
|
release: Readonly<ReleaseManifest>;
|
|
host?: Record<string, unknown>;
|
|
fetcher?: typeof fetch;
|
|
}>;
|
|
|
|
/**
|
|
* §5.2. The composition root is where a manifest becomes release info. A V2
|
|
* manifest states contract identity as a verified contract set and a V1
|
|
* manifest as the legacy scalar; the application layer sees one shape and never
|
|
* branches on the schema version to find the identity.
|
|
*/
|
|
function toReleaseInfo(manifest: Readonly<ReleaseManifest>): ReleaseInfo {
|
|
const { contractSet, legacyApiContractVersion, ...rest } =
|
|
structuredClone(manifest);
|
|
return Object.freeze({
|
|
...rest,
|
|
...(legacyApiContractVersion === undefined
|
|
? {}
|
|
: { apiContractVersion: legacyApiContractVersion }),
|
|
...(contractSet === null
|
|
? {}
|
|
: { contractSetDigest: contractSet.setDigest }),
|
|
});
|
|
}
|
|
|
|
const EXTERNAL_OWNER_METHODS = Object.freeze([
|
|
"readState",
|
|
"readSubject",
|
|
"subscribe",
|
|
"beginSignIn",
|
|
"signOut",
|
|
"attachCredential",
|
|
"recoverSession",
|
|
"notifyUnauthenticated",
|
|
] as const);
|
|
|
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
return Boolean(value) && typeof value === "object";
|
|
}
|
|
|
|
function externalOwnerFrom(
|
|
host: Record<string, unknown>,
|
|
): ExternalSessionOwner | null {
|
|
const candidate = host.__CA_FRONTEND_AUTH_OWNER__;
|
|
if (!isRecord(candidate)) return null;
|
|
return EXTERNAL_OWNER_METHODS.every(
|
|
(name) => typeof candidate[name] === "function",
|
|
)
|
|
? (candidate as ExternalSessionOwner)
|
|
: null;
|
|
}
|
|
|
|
function hostValue(
|
|
host: Record<string, unknown>,
|
|
property: string,
|
|
): unknown {
|
|
try {
|
|
return Reflect.get(host, property);
|
|
} catch {
|
|
return undefined;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 09-02. The one host value a product credential reads: a double-submit CSRF
|
|
* cookie such as a BFF's `XSRF-TOKEN`. The host itself is not handed out.
|
|
*/
|
|
function hostCookie(
|
|
host: Record<string, unknown>,
|
|
name: string,
|
|
): string | undefined {
|
|
const page = hostValue(host, "document");
|
|
const cookie = isRecord(page) ? hostValue(page, "cookie") : undefined;
|
|
if (typeof cookie !== "string") return undefined;
|
|
const prefix = `${encodeURIComponent(name)}=`;
|
|
const entry = cookie
|
|
.split(";")
|
|
.map((part) => part.trim())
|
|
.find((part) => part.startsWith(prefix));
|
|
try {
|
|
return entry === undefined
|
|
? undefined
|
|
: decodeURIComponent(entry.slice(prefix.length));
|
|
} catch {
|
|
return undefined;
|
|
}
|
|
}
|
|
|
|
function storageOrUndefined(value: unknown): Storage | undefined {
|
|
if (!value || typeof value !== "object") return undefined;
|
|
const candidate = value as Record<string, unknown>;
|
|
try {
|
|
return ["getItem", "setItem", "removeItem"].every(
|
|
(method) => typeof Reflect.get(candidate, method) === "function",
|
|
)
|
|
? (value as Storage)
|
|
: undefined;
|
|
} catch {
|
|
return undefined;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* VD-07. Exactly one diagnostic per logical V3 execution and exactly one
|
|
* `api.request.failed` telemetry event per terminal non-abort failure.
|
|
*
|
|
* The projection is closed: only registered context keys and bucketed values
|
|
* reach the sinks, and neither sink can change the HTTP outcome, because the
|
|
* caller invokes this inside the executor's isolated observation boundary.
|
|
*/
|
|
export function createHttpObservationProjector(
|
|
sinks: Readonly<{
|
|
diagnostics: Readonly<{ record(input: DiagnosticRecordInput): void }>;
|
|
telemetry: Readonly<{
|
|
emit(
|
|
eventName: TelemetryEventName,
|
|
attributes: Record<string, unknown>,
|
|
): void;
|
|
}>;
|
|
}>,
|
|
): (observation: HttpExecutionObservation) => void {
|
|
return (observation) => {
|
|
const safeAttributes = {
|
|
route_id: observation.routeId,
|
|
operation_id: observation.operationId,
|
|
error_kind: observation.errorKind,
|
|
http_status_group: statusGroup(observation.status),
|
|
attempt_count_bucket: attemptBucket(observation.attemptCount),
|
|
duration_bucket: durationBucket(observation.durationMs),
|
|
};
|
|
try {
|
|
sinks.diagnostics.record({
|
|
level: observation.outcome === "SUCCESS" ? "info" : "warn",
|
|
eventId: "http.request.completed",
|
|
context: {
|
|
...safeAttributes,
|
|
operation: observation.diagnosticsOperation,
|
|
outcome: observation.outcome,
|
|
// 03-03. Request-scoped: diagnostics may carry it, telemetry never.
|
|
...(observation.correlationId === undefined
|
|
? {}
|
|
: { correlation_id: observation.correlationId }),
|
|
// 03-05. A closed client-defect code; diagnostics only.
|
|
...(observation.diagnosticReason === undefined
|
|
? {}
|
|
: { reason: observation.diagnosticReason }),
|
|
},
|
|
});
|
|
} catch {
|
|
// Diagnostics cannot change a contract execution outcome.
|
|
}
|
|
if (!isTerminalNonAbortFailure(observation)) return;
|
|
try {
|
|
sinks.telemetry.emit("api.request.failed", { ...safeAttributes });
|
|
} catch {
|
|
// Telemetry cannot change a contract execution outcome.
|
|
}
|
|
};
|
|
}
|
|
|
|
/**
|
|
* LIVE-05. Cancellation and scope fencing are caller- or generation-owned
|
|
* decisions, not API failures: they produce a diagnostic once and never
|
|
* `api.request.failed`.
|
|
*
|
|
* A `DEADLINE` owner is the opposite case. Nobody asked for it — the API did
|
|
* not answer inside the contract's own budget — so excluding it would hide
|
|
* exactly the outage this event exists to report.
|
|
*/
|
|
const CALLER_OWNED_CANCELLATION: ReadonlySet<string> = new Set([
|
|
"CALLER",
|
|
"ROUTE_TRANSITION",
|
|
"SCOPE_FENCE",
|
|
"APPLICATION_SHUTDOWN",
|
|
]);
|
|
|
|
function isTerminalNonAbortFailure(
|
|
observation: HttpExecutionObservation,
|
|
): boolean {
|
|
if (observation.outcome === "SUCCESS") return false;
|
|
if (observation.outcome === "CANCELLED") return false;
|
|
// 03-07. No credential, nothing sent: a client state, not an API failure.
|
|
if (
|
|
observation.outcome === "UNAUTHENTICATED" &&
|
|
observation.status === undefined
|
|
) {
|
|
return false;
|
|
}
|
|
if (
|
|
observation.cancellationOwner !== undefined &&
|
|
CALLER_OWNED_CANCELLATION.has(observation.cancellationOwner)
|
|
) {
|
|
return false;
|
|
}
|
|
return !(
|
|
observation.outcome === "CONTRACT_VIOLATION" &&
|
|
observation.errorKind === "SCOPE_FENCED"
|
|
);
|
|
}
|
|
|
|
export async function createRuntimeAdapters(
|
|
context: RuntimeAdaptersContext,
|
|
) {
|
|
const host =
|
|
context.host ?? (globalThis as unknown as Record<string, unknown>);
|
|
const config = context.runtime.config;
|
|
const mutationIntentFactory = createBrowserMutationIntentFactory();
|
|
// 09-02. A product that owns the session (a BFF's httpOnly cookie) returns
|
|
// its owner before anything resolves the session; the host global is the
|
|
// fallback. Demo mode keeps its own session and never asks.
|
|
const externalOwner =
|
|
config.AUTH_MODE === "demo"
|
|
? null
|
|
: (composeProductSessionOwner({
|
|
config,
|
|
...(context.fetcher === undefined ? {} : { fetcher: context.fetcher }),
|
|
}) ?? externalOwnerFrom(host));
|
|
const authSession =
|
|
config.AUTH_MODE === "demo"
|
|
? createDemoSessionAdapter()
|
|
: externalOwner
|
|
? createExternalAuthSessionAdapter(externalOwner)
|
|
: createUnavailableSessionAdapter();
|
|
const diagnostics = createDiagnosticsAdapter();
|
|
// Q-6.9-4. Both telemetry ports post through one collector transport: one
|
|
// send-rate window, one page-exit flush and one fetch policy per endpoint.
|
|
const telemetryCollector =
|
|
config.TELEMETRY_ENABLED && config.TELEMETRY_ENDPOINT
|
|
? createTelemetryCollector({
|
|
endpoint: config.TELEMETRY_ENDPOINT,
|
|
...(context.fetcher === undefined ? {} : { fetcher: context.fetcher }),
|
|
release: {
|
|
buildId: context.release.buildId,
|
|
releaseId: context.release.releaseId,
|
|
},
|
|
})
|
|
: undefined;
|
|
const telemetry = createTelemetryAdapter({
|
|
enabled: config.TELEMETRY_ENABLED,
|
|
endpoint: config.TELEMETRY_ENDPOINT,
|
|
fetcher: context.fetcher,
|
|
...(telemetryCollector === undefined ? {} : { collector: telemetryCollector }),
|
|
onDrop(event) {
|
|
const attributes =
|
|
event.attributes && typeof event.attributes === "object"
|
|
? event.attributes
|
|
: {};
|
|
diagnostics.record({
|
|
level: "warn",
|
|
eventId: "telemetry.delivery.dropped",
|
|
context: attributes,
|
|
});
|
|
},
|
|
});
|
|
const invalidationIndex = indexInvalidationRegistry(INVALIDATION_REGISTRY);
|
|
const invalidationTopicVersions = indexInvalidationTopicVersions(
|
|
INVALIDATION_REGISTRY,
|
|
INVALIDATION_TOPIC_VERSIONS,
|
|
);
|
|
const conditionalValidators = createConditionalValidatorStore();
|
|
const serverStateGeneration = createServerStateGenerationStore(() => {
|
|
const queryClient = createQueryClient({ diagnostics });
|
|
const crossContextInvalidation =
|
|
createBrowserCrossContextInvalidationFromHost({
|
|
...(context.host === undefined ? {} : { host: context.host }),
|
|
cacheEpoch: crossContextCacheEpochForRelease(
|
|
context.release.releaseId,
|
|
),
|
|
topics: [...invalidationTopicVersions].map(([topic, topicVersion]) =>
|
|
Object.freeze({
|
|
topic,
|
|
topicVersion,
|
|
}),
|
|
),
|
|
observe(observation) {
|
|
if (
|
|
observation.outcome !== "FAILED" &&
|
|
observation.outcome !== "DEGRADED"
|
|
) {
|
|
return;
|
|
}
|
|
diagnostics.record({
|
|
level: "warn",
|
|
eventId: "cache.operation.failed",
|
|
context: {
|
|
operation: observation.operation,
|
|
outcome: observation.outcome,
|
|
reason: observation.reason,
|
|
},
|
|
});
|
|
},
|
|
});
|
|
const queryInvalidation = createTanStackCacheCoordinator({
|
|
queryClient,
|
|
invalidationIndex,
|
|
topicVersions: invalidationTopicVersions,
|
|
crossContext: crossContextInvalidation,
|
|
diagnostics,
|
|
});
|
|
return Object.freeze({
|
|
queryClient,
|
|
queryInvalidation,
|
|
crossContextStatus: () =>
|
|
crossContextInvalidation?.getStatus() ?? "DEGRADED_LOCAL_ONLY",
|
|
});
|
|
});
|
|
const serverStateScope = createServerStateScopeRuntime({
|
|
session: authSession,
|
|
diagnostics,
|
|
queryInvalidation: {
|
|
resetLocal: () => serverStateGeneration.resetCurrent(),
|
|
},
|
|
participants: [
|
|
{
|
|
order: 4,
|
|
label: "conditional-validators",
|
|
close: () => conditionalValidators.clear(),
|
|
},
|
|
],
|
|
activateNextGeneration: () => serverStateGeneration.activateNext(),
|
|
});
|
|
const storage = createBrowserStorageAdapter({
|
|
localStorage: storageOrUndefined(hostValue(host, "localStorage")),
|
|
sessionStorage: storageOrUndefined(
|
|
hostValue(host, "sessionStorage"),
|
|
),
|
|
diagnostics,
|
|
});
|
|
const releaseInfo = Object.freeze({
|
|
async getCurrent() {
|
|
return toReleaseInfo(context.release);
|
|
},
|
|
async refresh() {
|
|
return toReleaseInfo(
|
|
await fetchReleaseManifest(config.RELEASE_MANIFEST_URL, {
|
|
fetcher: context.fetcher,
|
|
buildId: context.release.buildId,
|
|
releaseId: context.release.releaseId,
|
|
}),
|
|
);
|
|
},
|
|
});
|
|
const runtimeCapabilities = Object.freeze({
|
|
getSnapshot() {
|
|
return describeRuntimeCapabilities(
|
|
INSTALLED_RUNTIME_CAPABILITIES,
|
|
config.CAPABILITY_OVERRIDES,
|
|
);
|
|
},
|
|
});
|
|
/**
|
|
* §3.5. The two halves of the feature answer meet here and nowhere else: the
|
|
* manifest says what the build compiled in, the runtime document says what is
|
|
* switched off. Neither can add to the other.
|
|
*/
|
|
const productFeatureStatuses = resolveProductFeatures(
|
|
COMPILED_PRODUCT_FEATURE_IDS,
|
|
INSTALLED_PRODUCT_FEATURE_IDS,
|
|
config.FEATURE_OVERRIDES,
|
|
);
|
|
const activeFeatureIds = new Set(
|
|
activeProductFeatureIds(productFeatureStatuses),
|
|
);
|
|
for (const key of unknownProductFeatureOverrides(
|
|
COMPILED_PRODUCT_FEATURE_IDS,
|
|
config.FEATURE_OVERRIDES,
|
|
)) {
|
|
diagnostics.record({
|
|
level: "warn",
|
|
eventId: "feature.override.unknown",
|
|
context: { feature_override_key: key },
|
|
});
|
|
}
|
|
const productFeatures = Object.freeze({
|
|
getSnapshot() {
|
|
return productFeatureStatuses;
|
|
},
|
|
isActive(featureId: string) {
|
|
return activeFeatureIds.has(featureId);
|
|
},
|
|
});
|
|
const navigation = Object.freeze({
|
|
reload() {
|
|
const location = host.location;
|
|
if (!isRecord(location) || typeof location.reload !== "function") {
|
|
throw new Error("Browser reload is unavailable");
|
|
}
|
|
location.reload();
|
|
},
|
|
});
|
|
const observeHttpExecution = createHttpObservationProjector({
|
|
diagnostics,
|
|
telemetry,
|
|
});
|
|
const contractHttp = createContractHttpExecutor({
|
|
baseUrl: config.API_BASE_URL,
|
|
maxRetryAttempts: config.MAX_RETRY_ATTEMPTS,
|
|
// §6.1. `REQUEST_TIMEOUT_MS` was declared, validated and then dropped on the
|
|
// floor here: every V3 operation ran on its contract's own 10s deadline and
|
|
// the deployment dial did nothing. It is a ceiling, so it can tighten an
|
|
// operation but never loosen one.
|
|
requestDeadlineCeilingMs: config.REQUEST_TIMEOUT_MS,
|
|
fetcher: context.fetcher,
|
|
// §7.7. The installed registry owns Fetch credentials and the exact
|
|
// credential-header sets; this collaborator only supplies proof headers.
|
|
authProfiles: INSTALLED_REST_AUTH_PROFILES,
|
|
async attachCredentials(operation, authContext) {
|
|
if (serverStateScope.getPhase() !== "READY") {
|
|
return Object.freeze({ kind: "SCOPE_FENCED" as const });
|
|
}
|
|
// 09-01. The operation's installed profile decides first, the session
|
|
// second. An ANONYMOUS profile admits no credential header at all, so it
|
|
// goes out bare in every session state and never reaches the owner. Every
|
|
// other profile still needs a session and never downgrades to anonymous.
|
|
if (
|
|
INSTALLED_REST_AUTH_PROFILES.get(operation.authProfileId)?.transport ===
|
|
"ANONYMOUS"
|
|
) {
|
|
return Object.freeze({ kind: "READY" as const, headers: {} });
|
|
}
|
|
// 09-02. A product provider answers for its own profiles, between the
|
|
// checks above and the session. A throw is left to the executor, which
|
|
// closes it as CREDENTIAL_OWNER_FAILED. `productCredentialProviders` is
|
|
// set below, before any request can run.
|
|
if (Object.hasOwn(productCredentialProviders, operation.authProfileId)) {
|
|
const provider = productCredentialProviders[operation.authProfileId];
|
|
const answer = await provider(operation, authContext);
|
|
return serverStateScope.getPhase() === "READY"
|
|
? answer
|
|
: Object.freeze({ kind: "SCOPE_FENCED" as const });
|
|
}
|
|
const state = authSession.getState();
|
|
if (state === "integration-failed") {
|
|
return Object.freeze({ kind: "UNAVAILABLE" as const });
|
|
}
|
|
if (state !== "authenticated") {
|
|
return Object.freeze({ kind: "UNAUTHENTICATED" as const });
|
|
}
|
|
try {
|
|
const patch = await authSession.credentialPatch(
|
|
{
|
|
origin: new URL(config.API_BASE_URL).origin,
|
|
method: operation.method,
|
|
operationId: operation.operationId,
|
|
},
|
|
authContext,
|
|
);
|
|
if (serverStateScope.getPhase() !== "READY") {
|
|
return Object.freeze({ kind: "SCOPE_FENCED" as const });
|
|
}
|
|
return Object.freeze({
|
|
kind: "READY" as const,
|
|
headers: patch.headers,
|
|
});
|
|
} catch {
|
|
return Object.freeze({ kind: "UNAVAILABLE" as const });
|
|
}
|
|
},
|
|
observe: observeHttpExecution,
|
|
});
|
|
// 15-01. Filled one feature at a time as feature runtimes load; an
|
|
// operation of a feature that has not loaded resolves to nothing and is
|
|
// refused below, exactly like an operation no feature contributes.
|
|
const contractRegistry = createInstalledContractRegistry();
|
|
/**
|
|
* 1103/09-01. A 401 judges the credential the request carried, so it goes to
|
|
* whoever supplied it, decided in the same order as `attachCredentials`. An
|
|
* ANONYMOUS request carried none: nobody is told. A product provider's
|
|
* credential: the product is told, the session is not. Only the session's
|
|
* own credential signs the session out.
|
|
*/
|
|
function reportServerUnauthenticated(
|
|
authProfileId: string,
|
|
binding: Readonly<{ operationId: string; authProfileId: string }>,
|
|
): void {
|
|
if (INSTALLED_REST_AUTH_PROFILES.get(authProfileId)?.transport === "ANONYMOUS") {
|
|
return;
|
|
}
|
|
if (Object.hasOwn(productCredentialProviders, authProfileId)) {
|
|
try {
|
|
onProductCredentialRejected?.(Object.freeze(binding));
|
|
} catch {
|
|
// A product hook defect cannot change the contract execution outcome.
|
|
}
|
|
return;
|
|
}
|
|
authSession.onUnauthenticated();
|
|
}
|
|
const contractOperations: InstalledHttpOperationExecutor = Object.freeze({
|
|
async execute(operation, input, executionContext) {
|
|
const installed = contractRegistry.resolveHttp(
|
|
operation.contract.operationId,
|
|
);
|
|
if (!installed) {
|
|
// 03-02. Refused before the executor runs, so this path leaves the
|
|
// one diagnostic every V3 execution leaves itself, with the cause.
|
|
const refused = Object.freeze({
|
|
kind: "CONTRACT_VIOLATION" as const,
|
|
effect: "NOT_STARTED" as const,
|
|
violation: Object.freeze({
|
|
kind: "FINAL_REQUEST_INVARIANT_FAILED" as const,
|
|
operation: "REQUEST" as const,
|
|
reason: "CONTRACT_NOT_INSTALLED" as const,
|
|
}),
|
|
});
|
|
observeHttpExecution(
|
|
Object.freeze({
|
|
routeId: executionContext.routeId,
|
|
operationId: operation.contract.operationId,
|
|
diagnosticsOperation: operation.frontend.diagnosticsOperation,
|
|
outcome: refused.kind,
|
|
errorKind: refused.violation.kind,
|
|
attemptCount: 0,
|
|
durationMs: 0,
|
|
effect: refused.effect,
|
|
terminalReason: "NOT_STARTED",
|
|
diagnosticReason: refused.violation.reason,
|
|
}),
|
|
);
|
|
return refused;
|
|
}
|
|
// composeContractContributions deliberately snapshots every installed
|
|
// contract. Runtime authority is therefore the validated registry entry,
|
|
// not object identity with the feature-owned source declaration.
|
|
const executableContract = installed as typeof operation;
|
|
const outcome = await contractHttp.execute(executableContract, input, {
|
|
routeId: executionContext.routeId,
|
|
scope: serverStateScope.getSnapshot(),
|
|
...(executionContext.signal === undefined
|
|
? {}
|
|
: { signal: executionContext.signal }),
|
|
...(executionContext.intent === undefined
|
|
? {}
|
|
: { intent: executionContext.intent }),
|
|
...(executionContext.execution === undefined
|
|
? {}
|
|
: { execution: executionContext.execution }),
|
|
});
|
|
// R-3.2. Only a server 401 is a session verdict. A request refused before
|
|
// dispatch for lack of a credential carries no response metadata; telling
|
|
// the owner would overwrite a recovering session and re-fence the scope.
|
|
if (outcome.kind === "UNAUTHENTICATED" && outcome.metadata !== undefined) {
|
|
reportServerUnauthenticated(executableContract.frontend.authProfileId, {
|
|
operationId: executableContract.contract.operationId,
|
|
authProfileId: executableContract.frontend.authProfileId,
|
|
});
|
|
}
|
|
return outcome;
|
|
},
|
|
});
|
|
// scale-architecture.md §24–§27. Feature-owned events go through the bounded, fail-open
|
|
// pipeline behind the provider-neutral port; features never see the sink.
|
|
const featureTelemetry = createFeatureTelemetry({
|
|
enabled: config.TELEMETRY_ENABLED,
|
|
...(config.TELEMETRY_ENDPOINT === undefined
|
|
? {}
|
|
: { endpoint: config.TELEMETRY_ENDPOINT }),
|
|
...(context.fetcher === undefined ? {} : { fetcher: context.fetcher }),
|
|
...(telemetryCollector === undefined ? {} : { collector: telemetryCollector }),
|
|
});
|
|
// 09-02. The product half of the composition. It runs after `http` exists,
|
|
// so a provider can fetch its token through it, and before any feature loads.
|
|
const product = composeProduct({
|
|
config,
|
|
readCookie: (name) => hostCookie(host, name),
|
|
...(context.fetcher === undefined ? {} : { fetcher: context.fetcher }),
|
|
http: contractOperations,
|
|
isScopeReady: () => serverStateScope.getPhase() === "READY",
|
|
}) satisfies ProductComposition;
|
|
// Read through the contract type: the product's own return type omits the
|
|
// optional hook when the product does not use it.
|
|
const productContract: ProductComposition = product;
|
|
const productCredentialProviders = productContract.credentialProviders;
|
|
const onProductCredentialRejected = productContract.onCredentialRejected;
|
|
// Each installed contribution receives only the capabilities it declares.
|
|
// The template's own capabilities come last, so a product cannot replace
|
|
// them. 09-05. `indexedDb` is not built here: IndexedDB is an opt-in
|
|
// reference runtime (`productionComposition: false`). Installing a feature
|
|
// that needs it makes this object fail the app typecheck until the product
|
|
// returns `indexedDb` from product-composition.ts, built as in
|
|
// recipes/frontend-capabilities/indexeddb-feature-capability.ts.
|
|
const featureCapabilities = Object.freeze({
|
|
...product.capabilities,
|
|
http: contractOperations,
|
|
telemetry: featureTelemetry,
|
|
});
|
|
const featureLoaders = createInstalledFeatureLoaders(
|
|
featureCapabilities,
|
|
[...activeFeatureIds],
|
|
contractRegistry.install,
|
|
);
|
|
|
|
return Object.freeze({
|
|
outputPorts: Object.freeze({
|
|
session: authSession,
|
|
preferences: storage,
|
|
diagnostics,
|
|
telemetry,
|
|
releaseInfo,
|
|
runtimeCapabilities,
|
|
productFeatures,
|
|
navigation,
|
|
}),
|
|
infrastructure: Object.freeze({
|
|
get queryClient() {
|
|
return serverStateGeneration.getSnapshot().queryClient;
|
|
},
|
|
get queryInvalidation() {
|
|
return serverStateGeneration.getSnapshot().queryInvalidation;
|
|
},
|
|
serverStateGeneration,
|
|
serverStateScope,
|
|
mutationIntentFactory,
|
|
conditionalValidators,
|
|
crossContextInvalidationStatus: () =>
|
|
serverStateGeneration.getSnapshot().crossContextStatus(),
|
|
dispose() {
|
|
// N-04. Telemetry is torn down first: it must stop scheduling and
|
|
// delivering before the diagnostics and state dependencies it observes
|
|
// are destroyed.
|
|
telemetry.dispose();
|
|
featureTelemetry.dispose();
|
|
conditionalValidators.clear();
|
|
serverStateScope.dispose();
|
|
serverStateGeneration.dispose();
|
|
},
|
|
}),
|
|
featureLoaders,
|
|
});
|
|
}
|