Realtime kept three DataSnapshot readers and about ten hand-written abort/timeout races, and two parsers had drifted copies in other adapters. Snapshot: reconnect-coordinator and bounded-poll now use result.ts captureRealtimeDataSnapshot (+ `source`, variadic hasExactSnapshotKeys). Kept the result.ts rules, the stricter ones: Object.hasOwn instead of `"value" in` (prototype pollution), enumerable fields only, keys read from one descriptor snapshot, frozen computed at snapshot time instead of a later Object.isFrozen. Poll therefore now rejects non-enumerable fields; it also accepts null-prototype records, which the other two copies already did (pure data, no inherited accessors). Characterization test added for both in bounded-poll-coordinator.test.ts. Race: one raceRealtimeTask(task, signal, deadline) in result.ts, built on kernel createAbortableOperation, replaces fetch-sse timed/cancelReader, reconnect race/drain (the drain keeps a host timer via timerDeadline, since the clock itself may hang), poll awaitTaskOrAbort/awaitWithinLease, live-poll checkpoint + two quiescence races (now one), stream-coordinator deadline/recovery-wait/close-drain, and the two WS inline races. Kept semantics: deadline armed first and wins a tie (poll lease), task still starts when the clock throws (reader cancel), collaborator rejections still reach stream-coordinator callers, scheduler install failure still fails closed as a timeout. Small change: nothing starts once the signal is already aborted (WS apply / SSE onEvent / reader.read could run just before being reported ABORTED). The mapping adds one microtask per race, so the reconnect test flush() helper gets 16 turns instead of 8. Kernel: parseRetryAfterDelay moves to platform/retry-after.ts (realtime re-exports it; http retry-policy parseRetryAfter now delegates, so it rejects "", " ", "1e3", "1.5", "0x10" and non-IMF dates it used to accept). json-member-scanner moves to platform/; web-push push-codec uses it instead of its top-level-only duplicate-key check, so nested duplicates are rejected too. INVENTORY 136 -> 137, detail tables updated. Tests: RED for http strict Retry-After, web-push nested duplicate, poll snapshot rules; new direct raceRealtimeTask tests. Gates: architecture, types app/test (+ service-worker/web-worker), lint, adapter-inventory (abort ratchet 21/21), test:unit, test:component, realtime-boundaries, integration/platform all pass. Realtime bundle 40346 -> 39433 gzip. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
419 lines
13 KiB
TypeScript
419 lines
13 KiB
TypeScript
import { describe, expect, it } from "vitest";
|
|
|
|
import {
|
|
WEB_PUSH_PROTOCOLS,
|
|
webPushSuccess,
|
|
} from "../../src/contracts/web-push.ts";
|
|
import {
|
|
clickDataFromHint,
|
|
decodeNotificationClickData,
|
|
decodeWebPushHint,
|
|
} from "../../src/adapters/web-push/push-codec.ts";
|
|
import {
|
|
createAssociationNotificationTag,
|
|
createWebPushNotificationRegistry,
|
|
} from "../../src/adapters/web-push/notification-registry.ts";
|
|
import {
|
|
WEB_PUSH_REGISTRATION_OPERATIONS,
|
|
createWebPushRegistrationGateway,
|
|
type WebPushRegistrationExecutor,
|
|
} from "../../src/adapters/web-push/push-registration-gateway.ts";
|
|
import { createPushAssociationFenceStore } from "../../src/adapters/web-push/push-association-fence-store.ts";
|
|
import { createWebPushSubscriptionAdapter } from "../../src/adapters/web-push/push-subscription-adapter.ts";
|
|
import { createFakePushControlStoreDependencies } from "../helpers/fake-push-control-repository.ts";
|
|
import {
|
|
base64UrlDecode,
|
|
base64UrlEncode,
|
|
} from "../../src/adapters/web-push/codec-primitives.ts";
|
|
|
|
const now = Date.parse("2026-07-28T00:00:00.000Z");
|
|
|
|
function hint(overrides: Readonly<Record<string, unknown>> = {}) {
|
|
return {
|
|
protocol: WEB_PUSH_PROTOCOLS.hint,
|
|
notificationType: "INBOX_ACTIVITY",
|
|
notificationId: "notification_01",
|
|
associationEpoch: "association_01",
|
|
releaseEpoch: "release_01",
|
|
issuedAt: "2026-07-27T23:59:00.000Z",
|
|
expiresAt: "2026-07-28T01:00:00.000Z",
|
|
routeIntent: "OPEN_INBOX",
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
function encoded(value: unknown): Uint8Array {
|
|
return new TextEncoder().encode(JSON.stringify(value));
|
|
}
|
|
|
|
describe("Web Push contracts", () => {
|
|
it("decodes an exact bounded hint and persists only typed click data", () => {
|
|
const decoded = decodeWebPushHint(encoded(hint()), now);
|
|
expect(decoded).toEqual({ ok: true, value: hint() });
|
|
if (!decoded.ok) throw new Error("expected a decoded hint");
|
|
|
|
const click = clickDataFromHint(decoded.value);
|
|
expect(decodeNotificationClickData(click, now)).toEqual({
|
|
ok: true,
|
|
value: click,
|
|
});
|
|
expect(click).not.toHaveProperty("notificationType");
|
|
expect(click).not.toHaveProperty("issuedAt");
|
|
});
|
|
|
|
it("fails closed for declarative, unknown, expired, and oversized payloads", () => {
|
|
expect(
|
|
decodeWebPushHint(encoded({ web_push: 8030 }), now),
|
|
).toMatchObject({
|
|
ok: false,
|
|
error: { code: "DECLARATIVE_PUSH_FORBIDDEN" },
|
|
});
|
|
expect(
|
|
decodeWebPushHint(encoded(hint({ unexpected: true })), now),
|
|
).toMatchObject({
|
|
ok: false,
|
|
error: { code: "CONTRACT_REJECTED" },
|
|
});
|
|
expect(
|
|
decodeWebPushHint(
|
|
encoded(
|
|
hint({
|
|
issuedAt: "2026-07-27T22:00:00.000Z",
|
|
expiresAt: "2026-07-27T23:00:00.000Z",
|
|
}),
|
|
),
|
|
now,
|
|
),
|
|
).toMatchObject({
|
|
ok: false,
|
|
error: { code: "EXPIRED" },
|
|
});
|
|
expect(
|
|
decodeWebPushHint(new Uint8Array(3 * 1024 + 1), now),
|
|
).toMatchObject({
|
|
ok: false,
|
|
error: { code: "LIMIT_EXCEEDED" },
|
|
});
|
|
expect(
|
|
decodeWebPushHint(
|
|
encoded(
|
|
hint({
|
|
issuedAt: "2026-07-28T00:06:00.000Z",
|
|
expiresAt: "2026-07-28T01:00:00.000Z",
|
|
}),
|
|
),
|
|
now,
|
|
),
|
|
).toMatchObject({
|
|
ok: false,
|
|
error: { code: "CONTRACT_REJECTED" },
|
|
});
|
|
expect(
|
|
decodeWebPushHint(
|
|
encoded(
|
|
hint({
|
|
issuedAt: "2026-07-28T00:00:00.000Z",
|
|
expiresAt: "2026-07-29T00:00:00.001Z",
|
|
}),
|
|
),
|
|
now,
|
|
),
|
|
).toMatchObject({
|
|
ok: false,
|
|
error: { code: "CONTRACT_REJECTED" },
|
|
});
|
|
const duplicateNotificationId = JSON.stringify(hint()).replace(
|
|
'"notificationId":"notification_01"',
|
|
'"notificationId":"notification_old","notificationId":"notification_01"',
|
|
);
|
|
expect(
|
|
decodeWebPushHint(
|
|
new TextEncoder().encode(duplicateNotificationId),
|
|
now,
|
|
),
|
|
).toMatchObject({
|
|
ok: false,
|
|
error: { code: "CONTRACT_REJECTED" },
|
|
});
|
|
});
|
|
|
|
it("rejects duplicate keys at any depth without a nesting budget", () => {
|
|
const deepDeclarative = {
|
|
web_push: 8030,
|
|
notification: { title: "t", data: { a: [[[[{ b: 1 }]]]] } },
|
|
};
|
|
expect(
|
|
decodeWebPushHint(encoded(deepDeclarative), now),
|
|
).toMatchObject({
|
|
ok: false,
|
|
error: { code: "DECLARATIVE_PUSH_FORBIDDEN" },
|
|
});
|
|
const nestedDuplicate = JSON.stringify(deepDeclarative).replace(
|
|
'"title":"t"',
|
|
'"title":"t","title":"u"',
|
|
);
|
|
expect(
|
|
decodeWebPushHint(new TextEncoder().encode(nestedDuplicate), now),
|
|
).toMatchObject({
|
|
ok: false,
|
|
error: { code: "CONTRACT_REJECTED" },
|
|
});
|
|
});
|
|
|
|
it("uses an injected closed notification and route registry", async () => {
|
|
const registry = createWebPushNotificationRegistry([
|
|
{
|
|
notificationType: "INBOX_ACTIVITY",
|
|
routeIntent: "OPEN_INBOX",
|
|
title: "새 알림이 있습니다",
|
|
body: "앱을 열어 최신 내용을 확인하세요.",
|
|
path: "/inbox",
|
|
},
|
|
]);
|
|
expect(
|
|
registry.resolve("INBOX_ACTIVITY", "OPEN_INBOX"),
|
|
).toMatchObject({ path: "/inbox" });
|
|
expect(registry.resolve("UNKNOWN", "OPEN_INBOX")).toBeNull();
|
|
expect(registry.routePath("OPEN_INBOX")).toBe("/inbox");
|
|
|
|
const tag = await createAssociationNotificationTag(
|
|
"association_01",
|
|
"INBOX_ACTIVITY",
|
|
async () => new Uint8Array(32).fill(7).buffer,
|
|
);
|
|
expect(tag).toMatch(/^ca-push-v1-[0-9a-f]{24}-inbox_activity$/u);
|
|
expect(tag).not.toContain("association_01");
|
|
});
|
|
|
|
it("binds backend calls to fixed operations and strict response codecs", async () => {
|
|
const calls: Array<Readonly<{ operationId: string; body: unknown }>> = [];
|
|
const executor: WebPushRegistrationExecutor = {
|
|
async execute(input) {
|
|
calls.push(input);
|
|
switch (input.operationId) {
|
|
case WEB_PUSH_REGISTRATION_OPERATIONS.register:
|
|
return webPushSuccess({
|
|
protocol: WEB_PUSH_PROTOCOLS.registration,
|
|
associationEpoch: "association_01",
|
|
sessionBindingEpoch: "session_01",
|
|
});
|
|
case WEB_PUSH_REGISTRATION_OPERATIONS.reconcile:
|
|
return webPushSuccess({
|
|
protocol: WEB_PUSH_PROTOCOLS.reconciliation,
|
|
state: "ABSENT",
|
|
});
|
|
case WEB_PUSH_REGISTRATION_OPERATIONS.revoke:
|
|
return webPushSuccess({
|
|
protocol: WEB_PUSH_PROTOCOLS.revoke,
|
|
state: "ALREADY_GONE",
|
|
});
|
|
}
|
|
},
|
|
};
|
|
const gateway = createWebPushRegistrationGateway(executor);
|
|
const p256dh = new Uint8Array(65);
|
|
p256dh[0] = 4;
|
|
const material = {
|
|
endpoint: "https://push.example.test/subscription/opaque",
|
|
p256dh: Buffer.from(p256dh).toString("base64url"),
|
|
auth: Buffer.from(new Uint8Array(16)).toString("base64url"),
|
|
expirationTime: null,
|
|
};
|
|
const authority = {
|
|
fenceGeneration: "fence_01",
|
|
sessionBindingEpoch: "session_01",
|
|
releaseEpoch: "release_01",
|
|
};
|
|
|
|
expect(
|
|
await gateway.register({
|
|
material,
|
|
authority,
|
|
idempotencyKey: "idempotency_01",
|
|
}),
|
|
).toEqual({
|
|
ok: true,
|
|
value: {
|
|
associationEpoch: "association_01",
|
|
sessionBindingEpoch: "session_01",
|
|
},
|
|
});
|
|
expect(await gateway.reconcile({ material, authority })).toEqual({
|
|
ok: true,
|
|
value: { state: "ABSENT" },
|
|
});
|
|
expect(
|
|
await gateway.revoke({ associationEpoch: "association_01" }),
|
|
).toEqual({
|
|
ok: true,
|
|
value: { state: "ALREADY_GONE" },
|
|
});
|
|
expect(calls.map((call) => call.operationId)).toEqual([
|
|
WEB_PUSH_REGISTRATION_OPERATIONS.register,
|
|
WEB_PUSH_REGISTRATION_OPERATIONS.reconcile,
|
|
WEB_PUSH_REGISTRATION_OPERATIONS.revoke,
|
|
]);
|
|
expect(
|
|
await gateway.register({
|
|
material: {
|
|
...material,
|
|
p256dh: Buffer.from(new Uint8Array(65)).toString(
|
|
"base64url",
|
|
),
|
|
},
|
|
authority,
|
|
idempotencyKey: "idempotency_02",
|
|
}),
|
|
).toMatchObject({
|
|
ok: false,
|
|
error: { code: "INVALID_INPUT" },
|
|
});
|
|
const throwing = createWebPushRegistrationGateway({
|
|
async execute() {
|
|
throw new Error("native transport detail must not escape");
|
|
},
|
|
});
|
|
expect(
|
|
await throwing.revoke({
|
|
associationEpoch: "association_01",
|
|
}),
|
|
).toMatchObject({
|
|
ok: false,
|
|
error: { code: "NATIVE_FAILURE" },
|
|
});
|
|
});
|
|
});
|
|
|
|
/**
|
|
* Q-6.6-12. The web-push files each carried their own base64url decoder,
|
|
* opaque-id pattern, authority check and exact-record check. These pin what
|
|
* every caller observes, so merging them into one module cannot loosen any.
|
|
*/
|
|
describe("web-push codec primitives as seen by their callers (Q-6.6-12)", () => {
|
|
const authority = {
|
|
fenceGeneration: "fence_01",
|
|
sessionBindingEpoch: "session_01",
|
|
releaseEpoch: "release_01",
|
|
};
|
|
const p256dhBytes = new Uint8Array(65);
|
|
p256dhBytes[0] = 4;
|
|
const material = {
|
|
endpoint: "https://push.example.test/subscription/opaque",
|
|
p256dh: Buffer.from(p256dhBytes).toString("base64url"),
|
|
auth: Buffer.from(new Uint8Array(16)).toString("base64url"),
|
|
expirationTime: null,
|
|
};
|
|
/** 87 chars carry 2 spare bits and 22 chars carry 4; they must be zero. */
|
|
const withSpareBitSet = (encoded: string) =>
|
|
`${encoded.slice(0, -1)}${encoded.endsWith("A") ? "B" : "A"}`;
|
|
const registered: WebPushRegistrationExecutor = {
|
|
async execute() {
|
|
return webPushSuccess({
|
|
protocol: WEB_PUSH_PROTOCOLS.registration,
|
|
associationEpoch: "association_01",
|
|
sessionBindingEpoch: "session_01",
|
|
});
|
|
},
|
|
};
|
|
|
|
it("rejects subscription keys whose spare base64url bits are set", async () => {
|
|
const gateway = createWebPushRegistrationGateway(registered);
|
|
for (const broken of [
|
|
{ ...material, p256dh: withSpareBitSet(material.p256dh) },
|
|
{ ...material, auth: withSpareBitSet(material.auth) },
|
|
]) {
|
|
expect(
|
|
await gateway.register({
|
|
material: broken,
|
|
authority,
|
|
idempotencyKey: "idempotency_01",
|
|
}),
|
|
).toMatchObject({ ok: false, error: { code: "INVALID_INPUT" } });
|
|
}
|
|
});
|
|
|
|
it("rejects a VAPID key whose spare base64url bits are set", () => {
|
|
const key = new Uint8Array(65);
|
|
key[0] = 4;
|
|
const valid = Buffer.from(key).toString("base64url");
|
|
expect(() =>
|
|
createWebPushSubscriptionAdapter({
|
|
vapidPublicKey: withSpareBitSet(valid),
|
|
} as never),
|
|
).toThrow(TypeError);
|
|
});
|
|
|
|
it("rejects a null authority as invalid input in the fence store", async () => {
|
|
const store = createPushAssociationFenceStore(
|
|
createFakePushControlStoreDependencies(),
|
|
);
|
|
expect(
|
|
await store.prepare({
|
|
authority: null as never,
|
|
updatedAt: "2026-07-28T00:00:00.000Z",
|
|
}),
|
|
).toMatchObject({ ok: false, error: { code: "INVALID_INPUT" } });
|
|
});
|
|
|
|
it("rejects a null authority as invalid input in the gateway", async () => {
|
|
const gateway = createWebPushRegistrationGateway(registered);
|
|
await expect(
|
|
gateway.register({
|
|
material,
|
|
authority: null as never,
|
|
idempotencyKey: "idempotency_01",
|
|
}),
|
|
).resolves.toMatchObject({ ok: false, error: { code: "INVALID_INPUT" } });
|
|
await expect(
|
|
gateway.reconcile({ material, authority: null as never }),
|
|
).resolves.toMatchObject({ ok: false, error: { code: "INVALID_INPUT" } });
|
|
});
|
|
|
|
it("rejects backend answers that are arrays or carry extra keys", async () => {
|
|
for (const answer of [
|
|
[WEB_PUSH_PROTOCOLS.revoke, "REVOKED"],
|
|
{ protocol: WEB_PUSH_PROTOCOLS.revoke, state: "REVOKED", extra: 1 },
|
|
]) {
|
|
const gateway = createWebPushRegistrationGateway({
|
|
execute: async () => webPushSuccess(answer),
|
|
});
|
|
expect(
|
|
await gateway.revoke({ associationEpoch: "association_01" }),
|
|
).toMatchObject({ ok: false, error: { code: "CONTRACT_REJECTED" } });
|
|
}
|
|
});
|
|
|
|
it("gives every accepted base64url string exactly one decoding", () => {
|
|
expect([...base64UrlDecode("AQID")!]).toEqual([1, 2, 3]);
|
|
expect([...base64UrlDecode("AQ")!]).toEqual([1]);
|
|
expect(base64UrlDecode("")?.byteLength).toBe(0);
|
|
// "AQIDA": a lone trailing character cannot finish a byte. The window
|
|
// adapter's old copy accepted it because its spare bits were zero.
|
|
for (const invalid of ["A", "AQIDA", "AR", "AQ==", "AQ+/", null, 7]) {
|
|
expect(base64UrlDecode(invalid), String(invalid)).toBeNull();
|
|
}
|
|
});
|
|
|
|
it("encodes base64url exactly like Node and round-trips through the decoder", () => {
|
|
for (let length = 0; length <= 66; length += 1) {
|
|
const bytes = Uint8Array.from({ length }, (_, index) => (index * 37 + 11) & 255);
|
|
const encoded = base64UrlEncode(bytes);
|
|
expect(encoded).toBe(Buffer.from(bytes).toString("base64url"));
|
|
expect([...base64UrlDecode(encoded)!]).toEqual([...bytes]);
|
|
}
|
|
});
|
|
|
|
it("rejects opaque ids outside the shared pattern", async () => {
|
|
const gateway = createWebPushRegistrationGateway(registered);
|
|
for (const associationEpoch of ["", "-leading", "a b", "a".repeat(129)]) {
|
|
expect(await gateway.revoke({ associationEpoch })).toMatchObject({
|
|
ok: false,
|
|
error: { code: "INVALID_INPUT" },
|
|
});
|
|
}
|
|
expect(
|
|
decodeWebPushHint(encoded(hint({ notificationId: "a b" })), now),
|
|
).toMatchObject({ ok: false });
|
|
});
|
|
});
|