chore: sync the frontend template from ebea300 to af3d8e6

Carries 359 template commits, tag v0.2.0 plus one documentation commit: the
generator-built feature index with its app, bounded-context and feature
declarations, the src/platform kernel and scale tooling, the 2026-09-24 src
review fixes, and the 2026-09-25 maturity review round with its CHANGELOG
[보안]/[계약] rows. 691 of the 824 template paths are applied, 85 of them
merged with product changes; 127 are not carried.

Product identity is unchanged: name, version 0.1.0, routes, design and the
TechLog domain.

Three decisions worth naming. TechLog stays composed directly, as the last
two syncs recorded; its directory carries a NOT_INSTALLED marker that says so,
and every installed-* composer takes the template's projection with TechLog
added on top. The reference sample is no longer installed: the template now
installs a feature only through feature-module.ts and context-routes.ts,
which load the screens this product deleted, so its three operations, six
schemas and one topic leave the registries, recorded as registry change
evidence. And AppRouter mounts the platform and TechLog routes only; the
template's bounded-context route gateway waits for a generator-installed
feature.

Required fixes: readSubject on the BFF session owner (without it every HTTP
Studio session would close as integration-failed), zod through the facade in
nine TechLog files, noUnusedLocals, and public/config.json written out to
match the local profile. Derived baselines were recomputed after reproducing
both sides' values: CI contract 101 commands / 106 references / 141
artifacts, gate shape c9adcf85; registry approval 2dc6c3a3; the runtime
config schema baseline equals the schema at 8210d48.

Verified here: types, lint, architecture, adapter inventory, CI contract,
i18n, design system, diagnostics, browser security, dev release manifest,
TechLog contract and build pass; 220 component, 155 integration, 15
contract, 418 TechLog, 43 reference-feature, 18 recipe and 46
release-coherence tests pass, and 2381 of 2383 unit tests. Reproduced at
8210d48 first and unchanged: check:registries (byte-identical),
test:runtime-schema, verify:documentation. Brought by the template and
escalated rather than suppressed: check:request-fanout on TechLog's cursor
pagination, check:remediation-ledger (fails upstream too), the shared-chunk
hash test, and the registry-dependent sample removal and second-feature
tests. Playwright suites were not run.

Full record, the five open questions and the follow-ups in
docs/operations/template-sync-2026-09-29.md.

(cherry picked from commit b2170cf265dea45dc9cc05d3c61e627e97f31cdb)
This commit is contained in:
DongHyeonka
2026-11-12 08:28:54 +09:00
parent 585c62431a
commit c80320dfc7
738 changed files with 55027 additions and 13567 deletions
+101
View File
@@ -0,0 +1,101 @@
import type { PushAuthoritySnapshot } from "../../contracts/web-push.ts";
/**
* Q-6.6-12. The validation primitives every web-push codec shares. Each file
* used to carry its own copy, and the copies had drifted: one authority check
* threw on `null`, one base64url decoder accepted a lone trailing character.
* Where they differed, the stricter behavior is the one kept here.
*/
/** Opaque ids: bounded, ASCII, starting with an alphanumeric. */
export const OPAQUE_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
export function validOpaqueId(value: unknown): value is string {
return typeof value === "string" && OPAQUE_ID.test(value);
}
export function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
/** `expected` must be sorted; the record's own keys must equal it exactly. */
export function hasExactKeys(
value: Record<string, unknown>,
expected: readonly string[],
): boolean {
const actual = Object.keys(value).sort();
return (
actual.length === expected.length &&
actual.every((key, index) => key === expected[index])
);
}
export function exactRecord(
value: unknown,
expected: readonly string[],
): value is Record<string, unknown> {
return isRecord(value) && hasExactKeys(value, expected);
}
/** A missing or non-object authority is invalid input, never a TypeError. */
export function validAuthority(value: unknown): value is PushAuthoritySnapshot {
return (
isRecord(value) &&
validOpaqueId(value.fenceGeneration) &&
validOpaqueId(value.sessionBindingEpoch) &&
validOpaqueId(value.releaseEpoch)
);
}
const BASE64URL_ALPHABET =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
/**
* Unpadded base64url. Rejects non-strings, characters outside the alphabet,
* a lone trailing character (6 bits cannot finish a byte) and non-zero spare
* bits, so every accepted string has exactly one decoding.
*/
export function base64UrlDecode(value: unknown): Uint8Array<ArrayBuffer> | null {
if (typeof value !== "string") return null;
const output = new Uint8Array(
new ArrayBuffer(Math.floor((value.length * 6) / 8)),
);
let accumulator = 0;
let bitCount = 0;
let outputIndex = 0;
for (const character of value) {
const digit = BASE64URL_ALPHABET.indexOf(character);
if (digit < 0) return null;
accumulator = (accumulator << 6) | digit;
bitCount += 6;
if (bitCount >= 8) {
bitCount -= 8;
output[outputIndex] = (accumulator >>> bitCount) & 0xff;
outputIndex += 1;
}
}
return bitCount < 6 &&
outputIndex === output.length &&
(accumulator & ((1 << bitCount) - 1)) === 0
? output
: null;
}
/** Unpadded base64url with zero spare bits: the inverse of the decoder. */
export function base64UrlEncode(bytes: Uint8Array): string {
let output = "";
let accumulator = 0;
let bitCount = 0;
for (const byte of bytes) {
accumulator = (accumulator << 8) | byte;
bitCount += 8;
while (bitCount >= 6) {
bitCount -= 6;
output += BASE64URL_ALPHABET[(accumulator >>> bitCount) & 63];
}
}
if (bitCount > 0) {
output += BASE64URL_ALPHABET[(accumulator << (6 - bitCount)) & 63];
}
return output;
}
@@ -84,6 +84,11 @@ export function createNotificationClickAdapter(dependencies: Readonly<{
fenceStore: PushAssociationFenceStore;
clients: WorkerClientsFacade;
origin: string;
/**
* 06-09. Where a refused click opens: the registration scope, which is the
* router base path. Defaults to the origin root; must be same-origin.
*/
appRootUrl?: string;
now?: () => number;
handlerDeadlineMs?: number;
scheduler?: TimeoutScheduler;
@@ -104,6 +109,11 @@ export function createNotificationClickAdapter(dependencies: Readonly<{
throw new TypeError("Web Push click adapter configuration is invalid.");
}
const origin: string = parsedOrigin;
const parsedAppRootUrl = safeTarget(origin, dependencies.appRootUrl ?? "/");
if (!parsedAppRootUrl) {
throw new TypeError("Web Push click adapter configuration is invalid.");
}
const appRootUrl: string = parsedAppRootUrl;
return Object.freeze({
handle(event) {
@@ -125,7 +135,12 @@ export function createNotificationClickAdapter(dependencies: Readonly<{
tails: [],
};
const processing = withAbortableDeadline(
(signal) => process(event.notification.data, signal, effect),
async (signal) =>
openAppRootIfRejected(
await process(event.notification.data, signal, effect),
signal,
effect,
),
{
deadlineMs: handlerDeadlineMs,
operation: "NOTIFICATION_CLICK",
@@ -206,49 +221,6 @@ export function createNotificationClickAdapter(dependencies: Readonly<{
expiresAt: decoded.value.expiresAt,
path,
});
// WP-RR-01. `focus` and `openWindow` are user-visible native effects, so
// they carry the same certainty phase `showNotification` already does:
// NOT_APPLIED before the call, MAYBE_APPLIED while the promise is pending,
// CONFIRMED on fulfilment. An effect that lands after this handler's
// deadline is still observed exactly once — as evidence only, never as
// authorization to retry.
const observeLateEffect = (
pending: Promise<unknown>,
appliedWhen: (value: unknown) => boolean,
): void => {
let observed = false;
// WP-01. The tail is tracked so `waitUntil` owns it. Certainty is
// monotone: once the native call has been made the effect can only be
// confirmed or stay uncertain. A rejection says the call did not report
// success, not that it never happened, so downgrading it to NOT_APPLIED
// told operators the click had definitely not been applied.
effect.tails.push(
pending.then(
(value) => {
if (observed) return;
observed = true;
const applied = appliedWhen(value);
effect.certainty = applied ? "CONFIRMED" : "NOT_APPLIED";
observeWebPush(dependencies.observer, {
event: "web_push_click_dispatched",
outcome: applied ? "DEGRADED" : "FAILED",
reason: "ABORTED",
nativeEffect: effect.certainty,
});
},
() => {
if (observed) return;
observed = true;
observeWebPush(dependencies.observer, {
event: "web_push_click_dispatched",
outcome: "DEGRADED",
reason: "ABORTED",
nativeEffect: "MAYBE_APPLIED",
});
},
),
);
};
try {
if (signal.aborted) {
return webPushFailure("ABORTED", "NOTIFICATION_CLICK");
@@ -259,26 +231,16 @@ export function createNotificationClickAdapter(dependencies: Readonly<{
effect.certainty = "MAYBE_APPLIED";
const raced = await raceAbort(focused, signal);
if (raced === ABORT_OWNED) {
observeLateEffect(focused, () => true);
observeLateEffect(effect, focused, () => true);
return webPushFailure("ABORTED", "NOTIFICATION_CLICK");
}
effect.certainty = "CONFIRMED";
} else {
const opening = Promise.resolve(
dependencies.clients.openWindow(target),
);
effect.certainty = "MAYBE_APPLIED";
const raced = await raceAbort(opening, signal);
if (raced === ABORT_OWNED) {
observeLateEffect(opening, (value) => value !== null);
const opened = await openWindowBounded(target, signal, effect);
if (opened === ABORT_OWNED) {
return webPushFailure("ABORTED", "NOTIFICATION_CLICK");
}
if (!raced) {
// An explicit null is the one answer that confirms no window opened.
effect.certainty = "NOT_APPLIED";
return nativeFailure("NOTIFICATION_CLICK", true);
}
effect.certainty = "CONFIRMED";
if (!opened) return nativeFailure("NOTIFICATION_CLICK", true);
}
if (signal.aborted) {
return webPushFailure("ABORTED", "NOTIFICATION_CLICK");
@@ -291,6 +253,103 @@ export function createNotificationClickAdapter(dependencies: Readonly<{
return webPushSuccess(undefined);
}
/**
* Q-6.6-11 / D-14. A click whose data or authority was refused (expired,
* fence or release mismatch, unreadable fence, unknown route) still opens
* the app at its root (06-09: the router base path) with no handoff data,
* so the user's tap is never silently dropped. The refusal stays the
* result. Native failures (the browser refused a window) and aborts are not
* retried.
*/
async function openAppRootIfRejected(
result: WebPushResult<void>,
signal: AbortSignal,
effect: ClickEffectState,
): Promise<WebPushResult<void>> {
// Every failure after a native window call is ABORTED or NATIVE_FAILURE,
// so the rest are refusals made before any window was touched.
if (
result.ok ||
result.error.code === "NATIVE_FAILURE" ||
result.error.code === "ABORTED" ||
signal.aborted
) {
return result;
}
await openWindowBounded(appRootUrl, signal, effect).catch(() => {
// The native call threw: whether a window opened is unknown.
});
return result;
}
/**
* WP-RR-01. `openWindow` bounded by the handler signal: MAYBE_APPLIED while
* pending, then CONFIRMED, or NOT_APPLIED for an explicit null (the one
* answer that confirms no window opened). A late result is still observed.
*/
async function openWindowBounded(
url: string,
signal: AbortSignal,
effect: ClickEffectState,
): Promise<boolean | typeof ABORT_OWNED> {
const opening = Promise.resolve(dependencies.clients.openWindow(url));
effect.certainty = "MAYBE_APPLIED";
const raced = await raceAbort(opening, signal);
if (raced === ABORT_OWNED) {
observeLateEffect(effect, opening, (value) => value !== null);
return ABORT_OWNED;
}
effect.certainty = raced ? "CONFIRMED" : "NOT_APPLIED";
return raced !== null;
}
/**
* WP-RR-01. `focus` and `openWindow` are user-visible native effects, so
* they carry the same certainty phase `showNotification` already does:
* NOT_APPLIED before the call, MAYBE_APPLIED while the promise is pending,
* CONFIRMED on fulfilment. An effect that lands after this handler's
* deadline is still observed exactly once — as evidence only, never as
* authorization to retry.
*/
function observeLateEffect(
effect: ClickEffectState,
pending: Promise<unknown>,
appliedWhen: (value: unknown) => boolean,
): void {
let observed = false;
// WP-01. The tail is tracked so `waitUntil` owns it. Certainty is
// monotone: once the native call has been made the effect can only be
// confirmed or stay uncertain. A rejection says the call did not report
// success, not that it never happened, so downgrading it to NOT_APPLIED
// told operators the click had definitely not been applied.
effect.tails.push(
pending.then(
(value) => {
if (observed) return;
observed = true;
const applied = appliedWhen(value);
effect.certainty = applied ? "CONFIRMED" : "NOT_APPLIED";
observeWebPush(dependencies.observer, {
event: "web_push_click_dispatched",
outcome: applied ? "DEGRADED" : "FAILED",
reason: "ABORTED",
nativeEffect: effect.certainty,
});
},
() => {
if (observed) return;
observed = true;
observeWebPush(dependencies.observer, {
event: "web_push_click_dispatched",
outcome: "DEGRADED",
reason: "ABORTED",
nativeEffect: "MAYBE_APPLIED",
});
},
),
);
}
async function validateActiveFence(
associationEpoch: string,
releaseEpoch: string,
@@ -10,13 +10,27 @@ import {
type WebPushOperation,
type WebPushResult,
} from "../../contracts/web-push.ts";
import {
exactRecord,
hasExactKeys,
isRecord,
validAuthority,
validOpaqueId,
} from "./codec-primitives.ts";
import {
withAbortableDeadline,
type TimeoutScheduler,
} from "./runtime-support.ts";
const CONTROL_KEY = "push-control-v1";
const OPAQUE_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
const CONTROL_KEYS = Object.freeze([
"association",
"fenceGeneration",
"protocol",
"releaseEpoch",
"sessionBindingEpoch",
"updatedAt",
]);
const ISO_INSTANT =
/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/u;
@@ -621,13 +635,9 @@ function controlSnapshot(value: PushControlV1): PushControlV1 {
}
function decodeControl(value: unknown): PushControlV1 | null {
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
const record = value as Record<string, unknown>;
const keys = Object.keys(record).sort();
if (!exactRecord(value, CONTROL_KEYS)) return null;
const record = value;
if (
keys.length !== 6 ||
keys.join("|") !==
"association|fenceGeneration|protocol|releaseEpoch|sessionBindingEpoch|updatedAt" ||
record.protocol !== WEB_PUSH_PROTOCOLS.control ||
!validOpaqueId(record.fenceGeneration) ||
!validOpaqueId(record.sessionBindingEpoch) ||
@@ -650,29 +660,12 @@ function decodeControl(value: unknown): PushControlV1 | null {
function validAssociation(
value: unknown,
): value is PushControlAssociationV1 {
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
const record = value as Record<string, unknown>;
const keys = Object.keys(record).sort();
if (record.state === "UNASSOCIATED") {
return keys.length === 1 && keys[0] === "state";
}
if (!isRecord(value)) return false;
if (value.state === "UNASSOCIATED") return hasExactKeys(value, ["state"]);
return (
(record.state === "ACTIVE" || record.state === "REVOKED") &&
keys.length === 2 &&
keys[0] === "associationEpoch" &&
keys[1] === "state" &&
validOpaqueId(record.associationEpoch)
);
}
function validAuthority(
value: PushAuthoritySnapshot,
): value is PushAuthoritySnapshot {
return (
Boolean(value) &&
validOpaqueId(value.fenceGeneration) &&
validOpaqueId(value.sessionBindingEpoch) &&
validOpaqueId(value.releaseEpoch)
(value.state === "ACTIVE" || value.state === "REVOKED") &&
hasExactKeys(value, ["associationEpoch", "state"]) &&
validOpaqueId(value.associationEpoch)
);
}
@@ -720,10 +713,6 @@ function validIdempotencyKey(value: unknown): value is string {
);
}
function validOpaqueId(value: unknown): value is string {
return typeof value === "string" && OPAQUE_ID.test(value);
}
function validRevision(value: unknown): value is number {
return (
typeof value === "number" &&
+9 -119
View File
@@ -7,8 +7,9 @@ import {
type WebPushHintV1,
type WebPushResult,
} from "../../contracts/web-push.ts";
import { hasExactKeys, isRecord, validOpaqueId } from "./codec-primitives.ts";
import { hasDuplicateJsonMembers } from "../platform/json-member-scanner.ts";
const OPAQUE_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
const REGISTRY_ID = /^[A-Z][A-Z0-9_]{0,63}$/u;
const ISO_INSTANT =
/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/u;
@@ -31,25 +32,6 @@ const CLICK_KEYS = Object.freeze([
"routeIntent",
] as const);
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
function hasExactKeys(
value: Record<string, unknown>,
expected: readonly string[],
): boolean {
const actual = Object.keys(value).sort();
return (
actual.length === expected.length &&
actual.every((key, index) => key === expected[index])
);
}
function validOpaqueId(value: unknown): value is string {
return typeof value === "string" && OPAQUE_ID.test(value);
}
function instant(value: unknown): number | null {
if (typeof value !== "string" || !ISO_INSTANT.test(value)) return null;
const parsed = Date.parse(value);
@@ -90,7 +72,13 @@ export function decodeWebPushHint(
} catch {
return webPushFailure("CONTRACT_REJECTED", "PUSH_DECODE");
}
if (hasDuplicateTopLevelJsonKeys(decoded)) {
// The byte cap already bounds the scan, so the budget never trips first.
if (
hasDuplicateJsonMembers(decoded, {
maxDepth: WEB_PUSH_LIMITS.decodedHintBytes,
maxMembers: WEB_PUSH_LIMITS.decodedHintBytes,
})
) {
return webPushFailure("CONTRACT_REJECTED", "PUSH_DECODE");
}
if (isRecord(value) && Object.hasOwn(value, "web_push")) {
@@ -208,101 +196,3 @@ export function clickDataFromHint(
expiresAt: hint.expiresAt,
});
}
function hasDuplicateTopLevelJsonKeys(source: string): boolean {
let cursor = skipWhitespace(source, 0);
if (source[cursor] !== "{") return false;
cursor = skipWhitespace(source, cursor + 1);
const keys = new Set<string>();
while (cursor < source.length && source[cursor] !== "}") {
if (source[cursor] !== "\"") return false;
const keyEnd = jsonStringEnd(source, cursor);
if (keyEnd === null) return false;
let key: unknown;
try {
key = JSON.parse(source.slice(cursor, keyEnd));
} catch {
return false;
}
if (typeof key !== "string") return false;
if (keys.has(key)) return true;
keys.add(key);
cursor = skipWhitespace(source, keyEnd);
if (source[cursor] !== ":") return false;
const valueEnd = jsonValueEnd(source, cursor + 1);
if (valueEnd === null) return false;
cursor = skipWhitespace(source, valueEnd);
if (source[cursor] === ",") {
cursor = skipWhitespace(source, cursor + 1);
continue;
}
if (source[cursor] !== "}") return false;
}
return false;
}
function jsonStringEnd(
source: string,
start: number,
): number | null {
let escaped = false;
for (let cursor = start + 1; cursor < source.length; cursor += 1) {
const character = source[cursor];
if (escaped) {
escaped = false;
} else if (character === "\\") {
escaped = true;
} else if (character === "\"") {
return cursor + 1;
}
}
return null;
}
function jsonValueEnd(
source: string,
start: number,
): number | null {
let cursor = skipWhitespace(source, start);
let depth = 0;
let inString = false;
let escaped = false;
for (; cursor < source.length; cursor += 1) {
const character = source[cursor];
if (inString) {
if (escaped) {
escaped = false;
} else if (character === "\\") {
escaped = true;
} else if (character === "\"") {
inString = false;
}
continue;
}
if (character === "\"") {
inString = true;
} else if (character === "{" || character === "[") {
depth += 1;
} else if (character === "}" || character === "]") {
if (depth === 0) return cursor;
depth -= 1;
} else if (character === "," && depth === 0) {
return cursor;
}
}
return inString || depth !== 0 ? null : cursor;
}
function skipWhitespace(source: string, start: number): number {
let cursor = start;
while (
cursor < source.length &&
(source[cursor] === " " ||
source[cursor] === "\n" ||
source[cursor] === "\r" ||
source[cursor] === "\t")
) {
cursor += 1;
}
return cursor;
}
@@ -5,8 +5,12 @@ import {
type PushAuthoritySnapshot,
type WebPushResult,
} from "../../contracts/web-push.ts";
const OPAQUE_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
import {
base64UrlDecode,
exactRecord,
validAuthority,
validOpaqueId,
} from "./codec-primitives.ts";
export const WEB_PUSH_REGISTRATION_OPERATIONS = Object.freeze({
register: "REGISTER_WEB_PUSH_SUBSCRIPTION",
@@ -228,30 +232,6 @@ function decodeRevoke(
: null;
}
function exactRecord(
value: unknown,
keys: readonly string[],
): value is Record<string, unknown> {
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
const actual = Object.keys(value).sort();
return (
actual.length === keys.length &&
actual.every((key, index) => key === keys[index])
);
}
function validOpaqueId(value: unknown): value is string {
return typeof value === "string" && OPAQUE_ID.test(value);
}
function validAuthority(value: PushAuthoritySnapshot): boolean {
return (
validOpaqueId(value.fenceGeneration) &&
validOpaqueId(value.sessionBindingEpoch) &&
validOpaqueId(value.releaseEpoch)
);
}
function validMaterial(value: NativePushSubscriptionMaterial): boolean {
const p256dh = base64UrlDecode(value?.p256dh);
const auth = base64UrlDecode(value?.auth);
@@ -294,32 +274,3 @@ function snapshotMaterial(
expirationTime: value.expirationTime,
});
}
function base64UrlDecode(value: unknown): Uint8Array | null {
if (typeof value !== "string") return null;
const alphabet =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
const output = new Uint8Array(
new ArrayBuffer(Math.floor((value.length * 6) / 8)),
);
let accumulator = 0;
let bitCount = 0;
let outputIndex = 0;
for (const character of value) {
const digit = alphabet.indexOf(character);
if (digit < 0) return null;
accumulator = (accumulator << 6) | digit;
bitCount += 6;
if (bitCount >= 8) {
bitCount -= 8;
output[outputIndex] = (accumulator >> bitCount) & 0xff;
outputIndex += 1;
}
}
return bitCount < 6 &&
outputIndex === output.length &&
(bitCount === 0 ||
(accumulator & ((1 << bitCount) - 1)) === 0)
? output
: null;
}
+202 -138
View File
@@ -12,6 +12,7 @@ import {
type WebPushResult,
type WebPushUnavailableReason,
} from "../../contracts/web-push.ts";
import { base64UrlDecode, base64UrlEncode } from "./codec-primitives.ts";
import type {
PushAssociationFenceStore,
PushControlReceipt,
@@ -87,6 +88,13 @@ export function createWebPushSubscriptionAdapter(
backendOperationDeadlineMs?: number;
scheduler?: TimeoutScheduler;
observer?: WebPushObserver;
/**
* 06-02 (D-4). The composition passes `navigator.locks`. Every tab shares
* one native subscription and one origin fence, so enable, reconcile and
* revoke run under the origin-wide `web-push-control` lock. Without Web
* Locks the adapter reports `PUSH_UNSUPPORTED`.
*/
lockManager?: Pick<LockManager, "request">;
}>,
): WebPushControlPort {
const decodedVapidPublicKey = decodeVapidPublicKey(
@@ -118,6 +126,11 @@ export function createWebPushSubscriptionAdapter(
}
const idempotencyKeyFactory =
dependencies.idempotencyKeyFactory ?? (() => globalThis.crypto.randomUUID());
const lockManager = dependencies.lockManager;
const requestLock =
typeof lockManager?.request === "function"
? lockManager.request.bind(lockManager)
: null;
let closed = false;
let busy = false;
let lifecycleGeneration = 0;
@@ -130,33 +143,8 @@ export function createWebPushSubscriptionAdapter(
return exclusive(
"SUBSCRIPTION_INSPECT",
input.signal,
async (generation, operationSignal) => {
const supported = supportReadiness();
if (supported) return webPushSuccess(supported);
const permission = permissionReadiness();
if (permission) return webPushSuccess(permission);
const native = await getSubscription(operationSignal, generation);
if (!native.ok) return native;
if (!native.value) {
return webPushSuccess(
unavailable("NATIVE_SUBSCRIPTION_MISSING"),
);
}
if (!subscriptionUsesKey(native.value, vapidPublicKey)) {
return webPushSuccess(
unavailable("SUBSCRIPTION_KEY_MISMATCH"),
);
}
const control = await dependencies.fenceStore.read({
signal: operationSignal,
});
if (!control.ok) return control;
return webPushSuccess(
isActiveFor(control.value?.control ?? null, input.authority)
? readiness("PUSH_READY")
: unavailable("SESSION_AUTHORITY_CHANGED"),
);
},
(generation, operationSignal) =>
inspectReadiness(input.authority, generation, operationSignal),
);
},
@@ -343,6 +331,29 @@ export function createWebPushSubscriptionAdapter(
return webPushFailure("ABORTED", "SUBSCRIPTION_RECONCILE");
}
if (reconciled.value.state === "ABSENT") {
// R-6.7. Only a local ACTIVE association (the server lost it) is
// re-registered. A REVOKED or UNASSOCIATED fence with a leftover
// native subscription is a failed logout cleanup or an unfinished
// opt-in; registering it would sign the current account up without
// its own consent, so the native subscription is removed instead.
const association = prepared.value.control.association;
if (association.state !== "ACTIVE") {
const nativeClean = await cleanupNative(
association.state === "UNASSOCIATED"
? null
: association.associationEpoch,
generation,
Object.freeze({ captured: true, subscription: native.value }),
prepared.value,
);
return webPushSuccess(
unavailable(
nativeClean
? "BACKEND_ASSOCIATION_MISSING"
: "NATIVE_UNSUBSCRIBE_AMBIGUOUS",
),
);
}
return await registerAndActivate({
subscription: native.value,
prepared: prepared.value,
@@ -359,6 +370,7 @@ export function createWebPushSubscriptionAdapter(
commit: reconciled.value,
signal: operationSignal,
generation,
created: false,
});
},
);
@@ -384,62 +396,54 @@ export function createWebPushSubscriptionAdapter(
) {
return webPushSuccess(unavailable("LOCAL_FENCE_UNSAFE"));
}
const capturedNative = await captureNativeForCleanup(
return await revokeReceipt(
current.value,
input.previousAuthority,
input.nextAuthority,
generation,
operationSignal,
generation,
);
const previousAssociation =
current.value.control.association.state === "UNASSOCIATED"
? null
: current.value.control.association.associationEpoch;
const fenced = await dependencies.fenceStore.rotateAndRevoke({
expectedRevision: current.value.revision,
previousAuthority: input.previousAuthority,
nextAuthority: input.nextAuthority,
updatedAt: instantNow(),
signal: operationSignal,
});
if (!fenced.ok) {
if (previousAssociation) {
await boundedBackendRevoke(previousAssociation);
}
return webPushSuccess(unavailable("LOCAL_FENCE_UNSAFE"));
}
},
);
},
let revokeAmbiguous = false;
if (previousAssociation) {
const backend = await boundedBackendRevoke(
previousAssociation,
revokeForeign(input) {
return exclusive(
"SUBSCRIPTION_REVOKE",
input.signal,
async (generation, operationSignal) => {
const current = await dependencies.fenceStore.read({
signal: operationSignal,
});
if (!current.ok) {
return webPushSuccess(unavailable("LOCAL_FENCE_UNSAFE"));
}
// 06-06. Only another session generation's fence is foreign. The
// next authority's own fence (another tab of the same session opted
// in, or a new release of it) keeps its association.
if (
!current.value ||
current.value.control.fenceGeneration ===
input.nextAuthority.fenceGeneration
) {
return await inspectReadiness(
input.nextAuthority,
generation,
operationSignal,
);
}
const stored = current.value.control;
return await revokeReceipt(
current.value,
Object.freeze({
fenceGeneration: stored.fenceGeneration,
sessionBindingEpoch: stored.sessionBindingEpoch,
releaseEpoch: stored.releaseEpoch,
}),
input.nextAuthority,
generation,
operationSignal,
);
revokeAmbiguous = !backend.ok;
}
const nativeClean = await cleanupNative(
previousAssociation,
generation,
capturedNative,
fenced.value,
);
observeWebPush(dependencies.observer, {
event: "web_push_association_revoked",
outcome:
revokeAmbiguous || !nativeClean ? "DEGRADED" : "SUCCEEDED",
...(revokeAmbiguous
? { reason: "BACKEND_REVOKE_AMBIGUOUS" }
: !nativeClean
? { reason: "NATIVE_UNSUBSCRIBE_AMBIGUOUS" }
: {}),
});
if (revokeAmbiguous) {
return webPushSuccess(
unavailable("BACKEND_REVOKE_AMBIGUOUS"),
);
}
if (!nativeClean) {
return webPushSuccess(
unavailable("NATIVE_UNSUBSCRIBE_AMBIGUOUS"),
);
}
return webPushSuccess(unavailable("REVOKED"));
},
);
},
@@ -483,15 +487,22 @@ export function createWebPushSubscriptionAdapter(
const generation = lifecycleGeneration;
const operation = createLinkedAbortController(signal);
inFlight.add(operation);
const run = () => task(generation, operation.signal);
try {
try {
return await task(generation, operation.signal);
// 06-02 (D-4). Inspection only reads; mutations wait for other tabs.
return failureOperation === "SUBSCRIPTION_INSPECT" || !requestLock
? await run()
: await requestLock(
WEB_PUSH_CONTROL_LOCK,
{ signal: operation.signal },
run,
);
} catch {
return webPushFailure(
"NATIVE_FAILURE",
failureOperation,
true,
);
// An abort while waiting for the lock rejects the request.
return operation.signal.aborted
? webPushFailure("ABORTED", failureOperation)
: webPushFailure("NATIVE_FAILURE", failureOperation, true);
}
} finally {
operation.dispose();
@@ -500,8 +511,99 @@ export function createWebPushSubscriptionAdapter(
}
}
async function inspectReadiness(
authority: PushAuthoritySnapshot,
generation: number,
operationSignal: AbortSignal,
): Promise<WebPushResult<WebPushReadiness>> {
const supported = supportReadiness();
if (supported) return webPushSuccess(supported);
const permission = permissionReadiness();
if (permission) return webPushSuccess(permission);
const native = await getSubscription(operationSignal, generation);
if (!native.ok) return native;
if (!native.value) {
return webPushSuccess(unavailable("NATIVE_SUBSCRIPTION_MISSING"));
}
if (!subscriptionUsesKey(native.value, vapidPublicKey)) {
return webPushSuccess(unavailable("SUBSCRIPTION_KEY_MISMATCH"));
}
const control = await dependencies.fenceStore.read({
signal: operationSignal,
});
if (!control.ok) return control;
return webPushSuccess(
isActiveFor(control.value?.control ?? null, authority)
? readiness("PUSH_READY")
: unavailable("SESSION_AUTHORITY_CHANGED"),
);
}
/**
* Logout order: rotate the fence to REVOKED first, then revoke the captured
* association, unsubscribe the captured native subscription and close its
* notifications.
*/
async function revokeReceipt(
current: PushControlReceipt,
previousAuthority: PushAuthoritySnapshot,
nextAuthority: PushAuthoritySnapshot,
generation: number,
operationSignal: AbortSignal,
): Promise<WebPushResult<WebPushReadiness>> {
const capturedNative = await captureNativeForCleanup(
operationSignal,
generation,
);
const previousAssociation =
current.control.association.state === "UNASSOCIATED"
? null
: current.control.association.associationEpoch;
const fenced = await dependencies.fenceStore.rotateAndRevoke({
expectedRevision: current.revision,
previousAuthority,
nextAuthority,
updatedAt: instantNow(),
signal: operationSignal,
});
if (!fenced.ok) {
if (previousAssociation) {
await boundedBackendRevoke(previousAssociation);
}
return webPushSuccess(unavailable("LOCAL_FENCE_UNSAFE"));
}
let revokeAmbiguous = false;
if (previousAssociation) {
const backend = await boundedBackendRevoke(previousAssociation);
revokeAmbiguous = !backend.ok;
}
const nativeClean = await cleanupNative(
previousAssociation,
generation,
capturedNative,
fenced.value,
);
observeWebPush(dependencies.observer, {
event: "web_push_association_revoked",
outcome: revokeAmbiguous || !nativeClean ? "DEGRADED" : "SUCCEEDED",
...(revokeAmbiguous
? { reason: "BACKEND_REVOKE_AMBIGUOUS" }
: !nativeClean
? { reason: "NATIVE_UNSUBSCRIBE_AMBIGUOUS" }
: {}),
});
if (revokeAmbiguous) {
return webPushSuccess(unavailable("BACKEND_REVOKE_AMBIGUOUS"));
}
if (!nativeClean) {
return webPushSuccess(unavailable("NATIVE_UNSUBSCRIBE_AMBIGUOUS"));
}
return webPushSuccess(unavailable("REVOKED"));
}
function supportReadiness(): WebPushReadiness | null {
if (!dependencies.secureContext) {
if (!dependencies.secureContext || !requestLock) {
return readiness("PUSH_UNSUPPORTED");
}
if (!dependencies.registration.active) {
@@ -679,6 +781,7 @@ export function createWebPushSubscriptionAdapter(
commit: registered.value,
signal: input.signal,
generation: input.generation,
created: input.created,
});
}
@@ -689,13 +792,17 @@ export function createWebPushSubscriptionAdapter(
commit: WebPushRegistrationCommit;
signal: AbortSignal | undefined;
generation: number;
created: boolean;
}>): Promise<WebPushResult<WebPushReadiness>> {
// 06-02 (D-4). A subscription this call did not create may carry another
// tab's association, so compensation leaves it in place.
const createdSubscription = input.created ? input.subscription : null;
if (
input.commit.sessionBindingEpoch !==
input.authority.sessionBindingEpoch ||
stale(input.signal, input.generation)
) {
await compensate(input.subscription, input.commit.associationEpoch);
await compensate(createdSubscription, input.commit.associationEpoch);
return webPushSuccess(
unavailable("SESSION_AUTHORITY_CHANGED"),
);
@@ -708,21 +815,23 @@ export function createWebPushSubscriptionAdapter(
signal: input.signal,
});
if (!activated.ok) {
await compensate(input.subscription, input.commit.associationEpoch);
await compensate(createdSubscription, input.commit.associationEpoch);
return webPushSuccess(unavailable("LOCAL_FENCE_UNSAFE"));
}
return webPushSuccess(readiness("PUSH_READY"));
}
async function compensate(
subscription: WindowPushSubscriptionFacade,
createdSubscription: WindowPushSubscriptionFacade | null,
associationEpoch: string,
): Promise<void> {
await withAbortableDeadline(
async (signal) => {
await Promise.allSettled([
boundedBackendRevoke(associationEpoch, signal),
safeUnsubscribe(subscription),
createdSubscription
? safeUnsubscribe(createdSubscription)
: Promise.resolve(true),
]);
return webPushSuccess(undefined);
},
@@ -983,6 +1092,9 @@ export function createWebPushSubscriptionAdapter(
}
}
/** 06-02 (D-4). Origin-wide Web Lock name shared by every tab. */
const WEB_PUSH_CONTROL_LOCK = "web-push-control";
function readiness(
state: WebPushReadiness["state"],
): WebPushReadiness {
@@ -1089,51 +1201,3 @@ function decodeVapidPublicKey(
const decoded = base64UrlDecode(value);
return decoded?.byteLength === 65 && decoded[0] === 4 ? decoded : null;
}
function base64UrlDecode(value: string): Uint8Array<ArrayBuffer> | null {
const alphabet =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
const outputLength = Math.floor((value.length * 6) / 8);
const output = new Uint8Array(new ArrayBuffer(outputLength));
let accumulator = 0;
let bitCount = 0;
let outputIndex = 0;
for (const character of value) {
const digit = alphabet.indexOf(character);
if (digit < 0) return null;
accumulator = (accumulator << 6) | digit;
bitCount += 6;
if (bitCount >= 8) {
bitCount -= 8;
output[outputIndex] = (accumulator >>> bitCount) & 0xff;
outputIndex += 1;
}
}
if (
outputIndex !== outputLength ||
(bitCount > 0 && (accumulator & ((1 << bitCount) - 1)) !== 0)
) {
return null;
}
return output;
}
function base64UrlEncode(bytes: Uint8Array): string {
const alphabet =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
let output = "";
let accumulator = 0;
let bitCount = 0;
for (const byte of bytes) {
accumulator = (accumulator << 8) | byte;
bitCount += 8;
while (bitCount >= 6) {
bitCount -= 6;
output += alphabet[(accumulator >>> bitCount) & 63];
}
}
if (bitCount > 0) {
output += alphabet[(accumulator << (6 - bitCount)) & 63];
}
return output;
}
@@ -6,6 +6,7 @@ import {
webPushSuccess,
type WebPushObserver,
} from "../../contracts/web-push.ts";
import { isRecord } from "./codec-primitives.ts";
import type { PushAssociationFenceStore } from "./push-association-fence-store.ts";
import {
createPushEventAdapter,
@@ -59,6 +60,8 @@ type ServiceWorkerClientsFacade = Readonly<{
*/
export type ServiceWorkerEventHost = Readonly<{
origin: string;
/** 06-09. `registration.scope`, the app root a refused click opens. */
scope?: string;
registration: ServiceWorkerRegistrationFacade;
clients: ServiceWorkerClientsFacade;
addEventListener(type: string, listener: (event: unknown) => void): void;
@@ -117,6 +120,9 @@ export function createWebPushServiceWorkerRuntime(
},
},
origin: dependencies.host.origin,
...(dependencies.host.scope === undefined
? {}
: { appRootUrl: dependencies.host.scope }),
now: dependencies.now,
scheduler: dependencies.scheduler,
observer: dependencies.observer,
@@ -272,7 +278,9 @@ function notificationClickEventFacade(
typeof value.waitUntil !== "function" ||
!isRecord(value.notification) ||
typeof value.notification.close !== "function" ||
!Object.hasOwn(value.notification, "data")
// 06-01. `data` is a WebIDL getter on `Notification.prototype`, never an
// own property, so the check must follow the prototype chain.
!("data" in value.notification)
) {
return null;
}
@@ -290,7 +298,3 @@ function windowClientFacade(value: unknown): WindowClientFacade | null {
}
return value as WindowClientFacade;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
@@ -19,6 +19,7 @@ type MatchAllOptions = Parameters<
export type NativeWorkerScope = Readonly<{
location: Readonly<{ origin: string }>;
registration: Readonly<{
scope: string;
showNotification(title: string, options: unknown): Promise<void>;
}>;
clients: Readonly<{
@@ -36,6 +37,7 @@ export function createServiceWorkerScopeHost(
): ServiceWorkerEventHost {
return Object.freeze({
origin: scope.location.origin,
scope: scope.registration.scope,
registration: Object.freeze({
showNotification: (title: string, options: NotificationOptions) =>
scope.registration.showNotification(title, {