Files
clean-architecture-frontend…/src/adapters/web-push/notification-registry.ts
T
DongHyeonka c67edd2557 fix(web-push): 정상 알림 클릭이 router base path 아래 경로를 연다 (06-01)
문제: Web Push 정상 클릭은 registry path를 origin 기준으로 풀었다
(`new URL(path, origin)`). 거절된 클릭은 이미 앱 루트(=
registration.scope = router base path)를 쓴다(06-09). 그래서
VITE_ROUTER_BASE_PATH=/app/ 배포에서 열린 창이 없으면 정상 클릭이
https://host/inbox, 즉 앱 밖을 열었다. registry에 /app/inbox를 넣으면
openWindow는 맞지만 같은 값이 handoff path로 페이지에 가서 router
basename과 겹친다. 어떤 registry 값으로도 두 경로를 함께 맞출 수
없었다.

고른 방법: registry path를 "base path를 뺀 앱 기준 경로"로 정하고,
클릭 어댑터가 앱 루트의 pathname(끝 / 제외)을 앞에 붙여 openWindow
대상을 만든다. handoff path는 registry 값 그대로 둔다. same-origin·
userinfo·hash 검사(safeTarget)는 그대로 거친다. 규칙은
WebPushNotificationDefinition.path 주석, appRootUrl 주석, 설계 8.5절에
적었다. 앱 루트가 origin 루트(기본값)면 결과가 전과 같다.

버린 대안: 리뷰가 적은 `new URL(path.slice(1), appRootUrl)`. 앱 루트가
/로 끝나지 않으면(`https://host/app`) 마지막 segment가 사라지고,
`/a:b` 같은 경로는 `a:b`가 scheme으로 읽혀 거절된다. pathname을 앞에
붙이면 두 경우 모두 의도대로 된다.

위험·한계:
- realtime 레시피 번들(web-push 포함) 40,879 -> 40,897 / 40,900 gzip
  B(+18 B, 여유 3 B). 예산은 그대로다. 다음 realtime·web-push 변경은
  예산 인상과 함께 와야 한다.
- 페이지가 handoff path를 basename 기준으로 쓰는지는 제품 코드 몫이라
  확인하지 않았다(템플릿에는 handoff 소비자가 없다).
- 실제 브라우저·푸시 서비스에서는 실행하지 않았다.

검증:
- RED: 새 테스트 "opens an accepted click's route under the base
  path"가 수정 전 openWindow 인자 `https://app.example.test/inbox`
  (기대 `https://app.example.test/app/inbox`)로 실패(1 failed | 19
  passed).
- GREEN: 같은 테스트가 통과하고, 열린 창에는 handoff path `/inbox`가
  간다. `node scripts/run-vitest.ts run tests/unit/web-push
  tests/unit/sub-path-deployment.test.ts
  tests/unit/service-worker-web-push-remediation.test.ts` -> 8파일
  82건 통과(web-push-worker-runtime 20건 포함).
- `npx tsc` app·test·service-worker -> 오류 0.
- `npx eslint <바꾼 ts 3개> --max-warnings=0` -> 통과.
- `node scripts/check-realtime-boundaries.ts` -> PASS,
  `node scripts/check-optional-recipes.ts` -> PASS(realtime
  40897/40900), `node scripts/verify-documentation-readiness.ts` ->
  PASS_SCOPED.

Refs: docs/reviews/2026-11-01-maturity-review/06-adapters-service-worker-push.md 06-01
2026-11-01 22:49:38 +09:00

124 lines
3.7 KiB
TypeScript

import type {
NotificationClickDataV1,
NotificationRouteIntentId,
NotificationTypeId,
} from "../../contracts/web-push.ts";
export type SafeNotification = Readonly<{
title: string;
options: Readonly<{
body: string;
data: NotificationClickDataV1;
requireInteraction: false;
tag: string;
}>;
}>;
export type WebPushNotificationDefinition = Readonly<{
notificationType: NotificationTypeId;
routeIntent: NotificationRouteIntentId;
title: string;
body: string;
/** App path, without the router base path (`/inbox`, not `/app/inbox`). */
path: string;
}>;
export interface WebPushNotificationRegistry {
resolve(
notificationType: NotificationTypeId,
routeIntent: NotificationRouteIntentId,
): WebPushNotificationDefinition | null;
routePath(routeIntent: NotificationRouteIntentId): string | null;
}
const REGISTRY_ID = /^[A-Z][A-Z0-9_]{0,63}$/u;
export function createWebPushNotificationRegistry(
definitions: readonly WebPushNotificationDefinition[],
): WebPushNotificationRegistry {
if (
definitions.length === 0 ||
definitions.length > 32 ||
definitions.some(
(definition) =>
!REGISTRY_ID.test(definition.notificationType) ||
!REGISTRY_ID.test(definition.routeIntent) ||
definition.title.length < 1 ||
definition.title.length > 80 ||
definition.body.length < 1 ||
definition.body.length > 160 ||
!safePath(definition.path),
)
) {
throw new TypeError("Web Push notification registry is invalid.");
}
const byType = new Map<string, WebPushNotificationDefinition>();
const byRoute = new Map<string, string>();
for (const definition of definitions) {
if (
byType.has(definition.notificationType) ||
(byRoute.has(definition.routeIntent) &&
byRoute.get(definition.routeIntent) !== definition.path)
) {
throw new TypeError("Web Push notification registry is ambiguous.");
}
const snapshot = Object.freeze({ ...definition });
byType.set(definition.notificationType, snapshot);
byRoute.set(definition.routeIntent, definition.path);
}
const registry: WebPushNotificationRegistry = {
resolve(notificationType, routeIntent) {
const definition = byType.get(notificationType);
return definition && definition.routeIntent === routeIntent
? definition
: null;
},
routePath(routeIntent) {
return byRoute.get(routeIntent) ?? null;
},
};
return Object.freeze(registry);
}
export type AssociationNotificationTagDigest = (
algorithm: "SHA-256",
data: Uint8Array<ArrayBuffer>,
) => Promise<ArrayBuffer>;
export async function createAssociationNotificationTag(
associationEpoch: string,
notificationType: NotificationTypeId,
digest: AssociationNotificationTagDigest = (algorithm, data) =>
globalThis.crypto.subtle.digest(algorithm, data),
): Promise<string> {
const encoded = new TextEncoder().encode(
`PUSH_ASSOCIATION_TAG_V1\0${associationEpoch}`,
);
const hashed = new Uint8Array(await digest("SHA-256", encoded));
if (hashed.byteLength !== 32) {
throw new TypeError("Web Push notification tag digest is invalid.");
}
const prefix = [...hashed.subarray(0, 12)]
.map((value) => value.toString(16).padStart(2, "0"))
.join("");
return `ca-push-v1-${prefix}-${notificationType.toLowerCase()}`;
}
function safePath(path: string): boolean {
if (
!path.startsWith("/") ||
path.startsWith("//") ||
path.includes("\\") ||
path.includes("#") ||
path.length > 512
) {
return false;
}
try {
const parsed = new URL(path, "https://registry.invalid");
return parsed.origin === "https://registry.invalid";
} catch {
return false;
}
}