Files
clean-architecture-frontend…/src/adapters/web-push/push-registration-gateway.ts
T
DongHyeonkaandClaude Opus 5.5 ec71b0b0a2 refactor(web-push): merge codec primitives into one module and inject the page document (Q-6.6-12)
web-push/codec-primitives.ts now owns OPAQUE_ID/validOpaqueId, isRecord,
hasExactKeys, exactRecord, validAuthority, base64UrlDecode and (to share the
alphabet) base64UrlEncode. push-codec,
push-registration-gateway, push-association-fence-store,
push-subscription-adapter and service-worker-runtime import them instead of
carrying their own copies (the fence store's control/association key checks
now use exactRecord/hasExactKeys with the same key lists). The duplicate-key
JSON scan in push-codec.ts is untouched (realtime lane, T76).

Where the copies differed, the stricter validated behavior is kept:
- validAuthority: the fence store's null guard. The gateway's copy threw a
  TypeError for a null authority, so register()/reconcile() rejected instead
  of returning INVALID_INPUT; they now return INVALID_INPUT (the only change a
  caller can observe; characterization test was RED before the merge).
  Non-record values (arrays) are also refused.
- base64UrlDecode: the gateway's decoder, which refuses a lone trailing
  character (length % 4 == 1). The window adapter's copy accepted it when the
  spare bits were zero; its only caller pre-checks an 87-char VAPID key, so
  that difference was not reachable. `>>` vs `>>>` gave identical bytes.
- OPAQUE_ID, isRecord/hasExactKeys/exactRecord were already identical.

Page controller: PageControllerDependencies gains optional `document`; the
6-hour update check reads it (falling back to the global document), and
bootstrap/register-service-worker.ts now passes host.document through.

New adapter file: INVENTORY.md row 126 + renumber, total 137/137; detail row in
docs/reviews/adapters/05-service-worker-and-web-push.md.

Verified: characterization tests pinned the caller-visible behavior of every
copy before the merge (spare-bit keys, VAPID key, null authority in fence
store and gateway, array/extra-key backend answers, opaque ids); all pass
after, plus direct base64UrlDecode tests and an encode round-trip against
Node's base64url for lengths 0..66. Document injection test was RED
(update() ran while the injected document was hidden), green after. Gates:
check:architecture, types app/test/service-worker, lint, test:unit (only
pre-existing removal-fixture failure), test:component,
check:realtime-boundaries, check:adapter-inventory.
Realtime reference bundle (check:optional-recipes:source, already over budget
at b953142): 40139 -> 40097 gzip bytes after T89+T90.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 13:37:56 +09:00

277 lines
7.8 KiB
TypeScript

import {
WEB_PUSH_PROTOCOLS,
webPushFailure,
webPushSuccess,
type PushAuthoritySnapshot,
type WebPushResult,
} from "../../contracts/web-push.ts";
import {
base64UrlDecode,
exactRecord,
validAuthority,
validOpaqueId,
} from "./codec-primitives.ts";
export const WEB_PUSH_REGISTRATION_OPERATIONS = Object.freeze({
register: "REGISTER_WEB_PUSH_SUBSCRIPTION",
reconcile: "RECONCILE_WEB_PUSH_SUBSCRIPTION",
revoke: "REVOKE_WEB_PUSH_ASSOCIATION",
} as const);
export type NativePushSubscriptionMaterial = Readonly<{
endpoint: string;
p256dh: string;
auth: string;
expirationTime: number | null;
}>;
export type WebPushRegistrationExecutor = Readonly<{
execute(input: Readonly<{
operationId:
(typeof WEB_PUSH_REGISTRATION_OPERATIONS)[keyof typeof WEB_PUSH_REGISTRATION_OPERATIONS];
body: unknown;
idempotencyKey?: string;
signal?: AbortSignal;
}>): Promise<WebPushResult<unknown>>;
}>;
export type WebPushRegistrationCommit = Readonly<{
associationEpoch: string;
sessionBindingEpoch: string;
}>;
export type WebPushReconciliation =
| Readonly<{ state: "ABSENT" }>
| Readonly<{
state: "ACTIVE";
associationEpoch: string;
sessionBindingEpoch: string;
}>;
export interface WebPushRegistrationGateway {
register(input: Readonly<{
material: NativePushSubscriptionMaterial;
authority: PushAuthoritySnapshot;
idempotencyKey: string;
signal?: AbortSignal;
}>): Promise<WebPushResult<WebPushRegistrationCommit>>;
reconcile(input: Readonly<{
material: NativePushSubscriptionMaterial;
authority: PushAuthoritySnapshot;
signal?: AbortSignal;
}>): Promise<WebPushResult<WebPushReconciliation>>;
revoke(input: Readonly<{
associationEpoch: string;
signal?: AbortSignal;
}>): Promise<WebPushResult<Readonly<{
state: "REVOKED" | "ALREADY_GONE";
}>>>;
}
export function createWebPushRegistrationGateway(
executor: WebPushRegistrationExecutor,
): WebPushRegistrationGateway {
const gateway: WebPushRegistrationGateway = {
async register(input) {
if (
!validMaterial(input.material) ||
!validAuthority(input.authority) ||
!validOpaqueId(input.idempotencyKey)
) {
return webPushFailure("INVALID_INPUT", "SUBSCRIPTION_CREATE");
}
const response = await execute(
{
operationId: WEB_PUSH_REGISTRATION_OPERATIONS.register,
body: Object.freeze({
protocol: "WEB_PUSH_REGISTER_COMMAND_V1",
subscription: snapshotMaterial(input.material),
fenceGeneration: input.authority.fenceGeneration,
sessionBindingEpoch: input.authority.sessionBindingEpoch,
releaseEpoch: input.authority.releaseEpoch,
}),
idempotencyKey: input.idempotencyKey,
signal: input.signal,
},
"SUBSCRIPTION_CREATE",
);
if (!response.ok) return response;
const decoded = decodeRegistration(response.value);
return decoded
? webPushSuccess(decoded)
: webPushFailure("CONTRACT_REJECTED", "SUBSCRIPTION_CREATE");
},
async reconcile(input) {
if (
!validMaterial(input.material) ||
!validAuthority(input.authority)
) {
return webPushFailure("INVALID_INPUT", "SUBSCRIPTION_RECONCILE");
}
const response = await execute(
{
operationId: WEB_PUSH_REGISTRATION_OPERATIONS.reconcile,
body: Object.freeze({
protocol: "WEB_PUSH_RECONCILE_COMMAND_V1",
subscription: snapshotMaterial(input.material),
fenceGeneration: input.authority.fenceGeneration,
sessionBindingEpoch: input.authority.sessionBindingEpoch,
releaseEpoch: input.authority.releaseEpoch,
}),
signal: input.signal,
},
"SUBSCRIPTION_RECONCILE",
);
if (!response.ok) return response;
const decoded = decodeReconciliation(response.value);
return decoded
? webPushSuccess(decoded)
: webPushFailure("CONTRACT_REJECTED", "SUBSCRIPTION_RECONCILE");
},
async revoke(input) {
if (!validOpaqueId(input.associationEpoch)) {
return webPushFailure("INVALID_INPUT", "SUBSCRIPTION_REVOKE");
}
const response = await execute(
{
operationId: WEB_PUSH_REGISTRATION_OPERATIONS.revoke,
body: Object.freeze({
protocol: "WEB_PUSH_REVOKE_COMMAND_V1",
associationEpoch: input.associationEpoch,
}),
signal: input.signal,
},
"SUBSCRIPTION_REVOKE",
);
if (!response.ok) return response;
const decoded = decodeRevoke(response.value);
return decoded
? webPushSuccess(decoded)
: webPushFailure("CONTRACT_REJECTED", "SUBSCRIPTION_REVOKE");
},
};
return Object.freeze(gateway);
async function execute(
input: Parameters<WebPushRegistrationExecutor["execute"]>[0],
operation:
| "SUBSCRIPTION_CREATE"
| "SUBSCRIPTION_RECONCILE"
| "SUBSCRIPTION_REVOKE",
): Promise<WebPushResult<unknown>> {
try {
return await executor.execute(input);
} catch {
return webPushFailure("NATIVE_FAILURE", operation, true);
}
}
}
function decodeRegistration(
value: unknown,
): WebPushRegistrationCommit | null {
if (!exactRecord(value, [
"associationEpoch",
"protocol",
"sessionBindingEpoch",
])) {
return null;
}
return value.protocol === WEB_PUSH_PROTOCOLS.registration &&
validOpaqueId(value.associationEpoch) &&
validOpaqueId(value.sessionBindingEpoch)
? Object.freeze({
associationEpoch: value.associationEpoch,
sessionBindingEpoch: value.sessionBindingEpoch,
})
: null;
}
function decodeReconciliation(
value: unknown,
): WebPushReconciliation | null {
if (
exactRecord(value, ["protocol", "state"]) &&
value.protocol === WEB_PUSH_PROTOCOLS.reconciliation &&
value.state === "ABSENT"
) {
return Object.freeze({ state: "ABSENT" });
}
if (
!exactRecord(value, [
"associationEpoch",
"protocol",
"sessionBindingEpoch",
"state",
]) ||
value.protocol !== WEB_PUSH_PROTOCOLS.reconciliation ||
value.state !== "ACTIVE" ||
!validOpaqueId(value.associationEpoch) ||
!validOpaqueId(value.sessionBindingEpoch)
) {
return null;
}
return Object.freeze({
state: "ACTIVE",
associationEpoch: value.associationEpoch,
sessionBindingEpoch: value.sessionBindingEpoch,
});
}
function decodeRevoke(
value: unknown,
): Readonly<{ state: "REVOKED" | "ALREADY_GONE" }> | null {
return exactRecord(value, ["protocol", "state"]) &&
value.protocol === WEB_PUSH_PROTOCOLS.revoke &&
(value.state === "REVOKED" || value.state === "ALREADY_GONE")
? Object.freeze({ state: value.state })
: null;
}
function validMaterial(value: NativePushSubscriptionMaterial): boolean {
const p256dh = base64UrlDecode(value?.p256dh);
const auth = base64UrlDecode(value?.auth);
if (
!value ||
typeof value !== "object" ||
typeof value.endpoint !== "string" ||
value.endpoint.length > 4_096 ||
!/^[A-Za-z0-9_-]{87}$/u.test(value.p256dh) ||
!/^[A-Za-z0-9_-]{22}$/u.test(value.auth) ||
p256dh?.byteLength !== 65 ||
p256dh[0] !== 4 ||
auth?.byteLength !== 16 ||
(value.expirationTime !== null &&
(!Number.isFinite(value.expirationTime) ||
value.expirationTime <= 0))
) {
return false;
}
try {
const endpoint = new URL(value.endpoint);
return (
endpoint.protocol === "https:" &&
!endpoint.username &&
!endpoint.password &&
!endpoint.hash
);
} catch {
return false;
}
}
function snapshotMaterial(
value: NativePushSubscriptionMaterial,
): NativePushSubscriptionMaterial {
return Object.freeze({
endpoint: value.endpoint,
p256dh: value.p256dh,
auth: value.auth,
expirationTime: value.expirationTime,
});
}