diff --git a/docs/architecture/realtime-events-web-push-and-bounded-polling.md b/docs/architecture/realtime-events-web-push-and-bounded-polling.md index 27c735fb..1628f6f2 100644 --- a/docs/architecture/realtime-events-web-push-and-bounded-polling.md +++ b/docs/architecture/realtime-events-web-push-and-bounded-polling.md @@ -1411,6 +1411,20 @@ Service Worker는 언제든 종료될 수 있다. in-memory cursor, queue, auth timer를 authority로 사용하지 않는다. `waitUntil`도 무제한 lifetime을 보장하지 않으므로 large fetch, retry loop, data migration을 넣지 않는다. +**조용한 drop은 설계 의도다(D-14).** 검증에 실패한 push(EXPIRED, +RELEASE_MISMATCH, association mismatch, fence 읽기 실패, handler deadline 초과, +malformed/unknown)는 알림을 띄우지 않고 끝난다. 계정 정보가 없는 generic +알림으로 대신 띄우지 않는 이유는 logout·계정 전환 뒤에 도착한 push가 어떤 +형태로든 사용자에게 보이면 안 되기 때문이다. 대가는 두 가지다. + +- Chrome은 `userVisibleOnly` push가 알림 없이 끝나면 "This site has been updated + in the background" 같은 기본 알림을 대신 띄울 수 있다. +- Safari(WebKit)는 알림 없는 push가 반복되면 구독을 취소할 수 있다. + +그래서 drop은 드물어야 한다. backend는 ACTIVE association에만 보내고, 짧은 +server TTL을 쓰고, release를 바꾼 직후에는 이전 release epoch로 보내지 않는다. +drop은 `web_push_hint_processed`의 `FAILED` + reason으로 관측한다. + ### 8.5 Notification content와 click - title/body/icon/action은 closed notification registry가 만든다. @@ -1438,8 +1452,14 @@ type NotificationClickDataV1 = Readonly<{ worker가 종료·재시작된 뒤에도 click을 처리할 수 있도록 이 bounded, non-sensitive envelope만 `NotificationOptions.data`에 넣는다. click handler는 codec/size/expiry, -current local `ACTIVE` fence와 release epoch를 다시 검증한다. unknown/mismatch는 -route를 열지 않고 notification을 닫는다. 이미 표시된 notification은 logout 뒤 +current local `ACTIVE` fence와 release epoch를 다시 검증한다. unknown/mismatch +(만료, fence·release 불일치, fence 읽기 실패, 모르는 route)는 notification을 닫고 +요청한 route 대신 **앱 루트(`/`)를 handoff 데이터 없이 연다**(D-14). +사용자의 탭이 아무 반응 없이 사라지지 않게 하되, 거절된 click의 route와 +notification 정보는 페이지로 넘기지 않는다. 결과는 여전히 실패로 보고하고 +(`web_push_click_dispatched` `FAILED` + reason, `nativeEffect`는 루트 창의 +확실성), 브라우저가 창 열기를 거절한 native 실패나 deadline/abort 뒤에는 루트를 +다시 시도하지 않는다. 이미 표시된 notification은 logout 뒤 OS notification center에 남을 수 있으므로 copy는 항상 account-neutral하고 민감하지 않아야 하며, `getNotifications()` cleanup 성공을 privacy 보장으로 과장하지 않는다. diff --git a/src/adapters/web-push/inbound/notification-click-adapter.ts b/src/adapters/web-push/inbound/notification-click-adapter.ts index ec6d391a..b49fe4d1 100644 --- a/src/adapters/web-push/inbound/notification-click-adapter.ts +++ b/src/adapters/web-push/inbound/notification-click-adapter.ts @@ -125,7 +125,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 +211,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, - 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 +221,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 +243,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 the same-origin root and 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, + signal: AbortSignal, + effect: ClickEffectState, + ): Promise> { + // 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; + } + // `origin` is already a parsed origin, so this is its root URL. + await openWindowBounded(`${origin}/`, 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 { + 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, + 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, diff --git a/tests/unit/web-push-worker-runtime.test.ts b/tests/unit/web-push-worker-runtime.test.ts index 197bec38..ff9c8f58 100644 --- a/tests/unit/web-push-worker-runtime.test.ts +++ b/tests/unit/web-push-worker-runtime.test.ts @@ -346,6 +346,114 @@ describe("Web Push worker runtime", () => { expect(focus).not.toHaveBeenCalled(); }); + describe("a rejected click opens the app root (Q-6.6-11, D-14)", () => { + async function rejectedClick( + options: Readonly<{ at?: number; data?: unknown }>, + ) { + const store = await activeFence(); + const postMessage = vi.fn(); + const focus = vi.fn(async () => {}); + const openWindow = vi.fn(async (url: string) => ({ + url, + focus: async () => {}, + postMessage() {}, + })); + const observations: unknown[] = []; + const adapter = createNotificationClickAdapter({ + fenceStore: store, + registry, + origin: "https://app.example.test", + now: () => options.at ?? now, + observer: { + record(observation) { + observations.push(observation); + }, + }, + clients: { + async matchControlledWindowClients() { + return [ + { url: "https://app.example.test/current", focus, postMessage }, + ]; + }, + openWindow, + }, + }); + let waited: Promise | null = null; + const result = await adapter.handle({ + notification: { data: options.data ?? clickData(), close() {} }, + waitUntil(task) { + waited = task; + }, + }); + await waited; + return { result, openWindow, focus, postMessage, observations }; + } + + it("opens the root without handoff data for an expired click", async () => { + const click = await rejectedClick({ + at: Date.parse("2026-07-28T02:00:00.000Z"), + }); + + expect(click.result).toMatchObject({ + ok: false, + error: { code: "EXPIRED" }, + }); + expect(click.openWindow.mock.calls).toEqual([ + ["https://app.example.test/"], + ]); + expect(click.postMessage).not.toHaveBeenCalled(); + expect(click.focus).not.toHaveBeenCalled(); + expect(click.observations).toContainEqual({ + event: "web_push_click_dispatched", + outcome: "FAILED", + reason: "EXPIRED", + nativeEffect: "CONFIRMED", + }); + }); + + it("opens the root for a click from another release", async () => { + const click = await rejectedClick({ + data: { ...clickData(), releaseEpoch: "release_02" }, + }); + + expect(click.result).toMatchObject({ + ok: false, + error: { code: "RELEASE_MISMATCH" }, + }); + expect(click.openWindow.mock.calls).toEqual([ + ["https://app.example.test/"], + ]); + expect(click.postMessage).not.toHaveBeenCalled(); + }); + + it("does not retry the root after the browser refused the target window", async () => { + const store = await activeFence(); + const openWindow = vi.fn(async () => null); + const adapter = createNotificationClickAdapter({ + fenceStore: store, + registry, + origin: "https://app.example.test", + now: () => now, + clients: { + matchControlledWindowClients: async () => [], + openWindow, + }, + }); + + const result = await adapter.handle({ + notification: { data: clickData(), close() {} }, + waitUntil() {}, + }); + expect(result).toMatchObject({ + ok: false, + error: { code: "NATIVE_FAILURE" }, + }); + expect(openWindow.mock.calls).toEqual([ + ["https://app.example.test/inbox"], + ]); + }); + }); + it("aborts in-flight push work when the worker runtime is disposed", async () => { const store = await activeFence(); const listeners = new Map void>();