Files
clean-architecture-frontend…/src/contracts/storage-keys.ts
T
DongHyeonka dc7c95b005 fix(recipes): OIDC PKCE 레시피가 sessionStorage 키를 registry에서 가져온다
문제: OIDC PKCE session owner 레시피가 sign-in transaction의
sessionStorage 키를 글자 그대로 적는다
(`"ca-frontend:auth:v1:oidc-pkce-transaction"`). 주석은
`buildPhysicalKey(...)`라고 하지만 함수를 부르지 않는다. 템플릿의 다른
Web Storage 키는 모두 `src/contracts/storage-keys.ts` registry가
`APP_NAMESPACE`로 만들고, 어댑터가 직접 쓰는 키도 `backend: "external"`
행으로 둔다. 그래서 제품이 `APP_NAMESPACE`를 바꾸면(memento 설계가
예정한 일) 이 키만 `ca-frontend:`로 남고, registry는 앱이 쓰는 Web
Storage 키 목록이 아니게 된다. registry로 로그아웃 때 지울 키를 정하는
제품은 버려진 sign-in의 verifier·state·nonce·돌아갈 경로를 지우지 못한다.

고른 방법:
- registry에 `AUTH_REDIRECT_TRANSACTION` 행을 둔다. `scope: "auth"`,
  `name: "oidc-pkce-transaction"`, `backend: "external"`(pulse 키와 같은
  모양, StoragePort는 거절), `ttl: "session"`. 물리 키는 지금 글자와 같다
  (`ca-frontend:auth:v1:oidc-pkce-transaction`)라서 진행 중인 sign-in을
  잃지 않는다.
- 레시피의 `OIDC_PKCE_TRANSACTION_KEY`는 그 행의 `physicalKey`다.
  매뉴얼의 복사 규칙(`../../src/` → `../`)이 새 import에도 그대로 맞는다.
- 분류는 `opaque-cache`다. `sensitive-forbidden`은 "저장하지 않는다"는
  뜻이고 backend가 disabled·forbidden이어야 해서 맞지 않는다. 이 값은
  리다이렉트 한 번 동안 저장하는 것이 설계다.
- FE-REG-STORAGE의 `orphanExemptRows`에 이 행을 더한다
  (`config/contracts/registry-governance.json`). 이 행을 쓰는 곳은 레시피
  하나뿐이고, 레시피는 제품이 지울 수 있다(test:optional-recipe-removal).
  행은 registry로 지울 키를 정하는 제품을 위해 남는다. `AUTH_TOKEN`처럼
  사용처 없이 선언만 하는 행이다. 빼지 않으면 `src`만 복사해
  check:registries를 돌리는 `tests/unit/second-api-feature-registries.test.ts`가
  "has no executable consumer"로 실패한다.
  버린 대안: consumer 폴더에 `recipes`를 더하기. 레시피를 지운 사본(FE-GATE-020)
  에서 다시 사용처가 사라진다.

버린 대안: registry에 새 분류(예: `session-transaction`)를 더하기. 계약
타입의 union과 registry 기준선의 허용 값이 함께 바뀌는데, 분류가 코드
동작을 바꾸는 곳은 `sensitive-forbidden` 검사뿐이라 얻는 것이 없다.

위험·한계:
- `src/contracts/storage-keys.ts`에 행 하나가 더해진다(FE-REG-STORAGE
  additive). CHANGELOG [계약] 행이 필요하다.
- 이미 레시피를 복사한 제품은 자기 복사본을 같은 diff로 고쳐야 키가
  namespace를 따른다.
- orphan 검사가 이 행을 보지 않는다. 레시피가 키를 registry에서 가져오는지는
  `tests/recipes/oidc-pkce-session-owner.test.ts`가 본다.

검증: desktop batch에서 확인
- node scripts/run-vitest.ts run tests/unit/storage-registry.test.ts
  tests/recipes/oidc-pkce-session-owner.test.ts
- corepack pnpm check:registries (additive 행)
- node scripts/run-vitest.ts run tests/unit/second-api-feature-registries.test.ts
- corepack pnpm test:optional-recipe-removal

Refs: 1105/05-01
2026-11-06 02:07:47 +09:00

241 lines
7.2 KiB
TypeScript

const APP_NAMESPACE = "ca-frontend";
export type StorageBackend =
| "memory"
| "sessionStorage"
| "localStorage"
| "disabled"
| "forbidden"
/**
* Another adapter owns the value format and writes the physical key itself.
* The registry only owns the name, so StoragePort refuses the key.
*/
| "external";
export type StorageValueCodec =
| "color-scheme-v1"
| "opaque-string-v1"
| "none";
export type StorageKeyInput = Readonly<{
logicalName: string;
scope: string;
name: string;
backend: StorageBackend;
classification:
| "public-preference"
| "opaque-cache"
| "sensitive-forbidden";
schemaVersion: number;
valueCodec: StorageValueCodec;
ttl: number | "session" | null;
migration: "discard";
quotaFallback: "memory" | "no-persist" | "feature-disable";
}>;
export type StorageDefinition = Readonly<
StorageKeyInput & { physicalKey: string }
>;
export const STORAGE_REGISTRY = Object.freeze({
COLOR_SCHEME: defineStorageKey({
logicalName: "COLOR_SCHEME",
scope: "preference",
name: "color-scheme",
backend: "localStorage",
classification: "public-preference",
schemaVersion: 1,
valueCodec: "color-scheme-v1",
ttl: null,
migration: "discard",
quotaFallback: "memory",
}),
/** The chosen UI locale. Presentation normalizes whatever it reads back. */
LOCALE: defineStorageKey({
logicalName: "LOCALE",
scope: "preference",
name: "locale",
backend: "localStorage",
classification: "public-preference",
schemaVersion: 1,
valueCodec: "opaque-string-v1",
ttl: null,
migration: "discard",
quotaFallback: "memory",
}),
CHUNK_RELOAD_GUARD: defineStorageKey({
logicalName: "CHUNK_RELOAD_GUARD",
scope: "release",
name: "chunk-reload-guard",
backend: "sessionStorage",
classification: "opaque-cache",
schemaVersion: 1,
valueCodec: "opaque-string-v1",
ttl: "session",
migration: "discard",
quotaFallback: "no-persist",
}),
/**
* scale-architecture.md §45 / release-coherence plan Task 6. One reload-once marker per boot
* release-mismatch key, so a mixed rolling release can recover with one
* fresh HTML fetch but can never reload-loop.
*/
RELEASE_MISMATCH_RECOVERY: defineStorageKey({
logicalName: "RELEASE_MISMATCH_RECOVERY",
scope: "release",
name: "boot-mismatch-recovery",
backend: "sessionStorage",
classification: "opaque-cache",
schemaVersion: 1,
valueCodec: "opaque-string-v1",
ttl: "session",
migration: "discard",
quotaFallback: "no-persist",
}),
QUERY_PERSISTENCE: defineStorageKey({
logicalName: "QUERY_PERSISTENCE",
scope: "cache",
name: "query-persistence",
backend: "disabled",
classification: "sensitive-forbidden",
schemaVersion: 1,
valueCodec: "none",
ttl: null,
migration: "discard",
quotaFallback: "feature-disable",
}),
/**
* 05-01. The cross-context invalidation adapter writes raw wire JSON to this
* localStorage key with no envelope. Only the physical key name lives here.
* The key string is a channel between deployed tabs and must not change.
*/
CACHE_INVALIDATION_PULSE: defineStorageKey({
logicalName: "CACHE_INVALIDATION_PULSE",
scope: "cache-invalidation",
name: "pulse",
backend: "external",
classification: "opaque-cache",
schemaVersion: 1,
valueCodec: "none",
ttl: null,
migration: "discard",
quotaFallback: "no-persist",
}),
AUTH_TOKEN: defineStorageKey({
logicalName: "AUTH_TOKEN",
scope: "auth",
name: "auth-token",
backend: "forbidden",
classification: "sensitive-forbidden",
schemaVersion: 1,
valueCodec: "none",
ttl: null,
migration: "discard",
quotaFallback: "feature-disable",
}),
/**
* 1105/05-01. The OIDC PKCE session owner recipe
* (`recipes/session-owners/oidc-pkce-session-owner.ts`) keeps one sign-in
* transaction here in sessionStorage: the PKCE verifier, `state`, `nonce`
* and the return path, never a token, for at most ten minutes, and the
* callback deletes it first. The recipe owns the value format, so only the
* name lives here and StoragePort refuses the key. It is not
* `sensitive-forbidden`, which means "never stored"; this one is stored by
* design for one redirect.
*/
AUTH_REDIRECT_TRANSACTION: defineStorageKey({
logicalName: "AUTH_REDIRECT_TRANSACTION",
scope: "auth",
name: "oidc-pkce-transaction",
backend: "external",
classification: "opaque-cache",
schemaVersion: 1,
valueCodec: "none",
ttl: "session",
migration: "discard",
quotaFallback: "no-persist",
}),
});
export function defineStorageKey<Definition extends StorageKeyInput>(
definition: Definition,
): Readonly<Definition & { physicalKey: string }> {
if (
!["color-scheme-v1", "opaque-string-v1", "none"].includes(
definition.valueCodec,
)
) {
throw new Error("Unknown client storage value codec");
}
if (definition.migration !== "discard") {
throw new Error("Unsupported client storage migration policy");
}
if (definition.classification === "sensitive-forbidden") {
if (!["disabled", "forbidden"].includes(definition.backend)) {
throw new Error("Sensitive client storage registration is forbidden");
}
if (definition.valueCodec !== "none") {
throw new Error("Sensitive client storage codec is forbidden");
}
} else if (definition.backend === "external") {
if (definition.valueCodec !== "none") {
throw new Error("Externally owned storage keys have no StoragePort codec");
}
} else if (definition.valueCodec === "none") {
throw new Error("Persisted storage keys require a value codec");
}
if (!Number.isInteger(definition.schemaVersion) || definition.schemaVersion < 1) {
throw new Error("Storage schemaVersion must be a positive integer");
}
return Object.freeze({
...definition,
physicalKey: buildPhysicalKey(
definition.scope,
definition.schemaVersion,
definition.name,
),
});
}
export function buildPhysicalKey(
scope: string,
schemaVersion: number,
name: string,
): string {
return `${APP_NAMESPACE}:${scope}:v${schemaVersion}:${name}`;
}
export function getStorageDefinition(logicalName: string): StorageDefinition {
const registry: Readonly<Record<string, StorageDefinition>> = STORAGE_REGISTRY;
const definition = Object.hasOwn(registry, logicalName)
? registry[logicalName]
: undefined;
if (!definition) throw new Error(`Unregistered storage key: ${logicalName}`);
if (definition.classification === "sensitive-forbidden") {
throw new Error(`Forbidden storage key: ${logicalName}`);
}
if (definition.backend === "external") {
throw new Error(`Externally owned storage key: ${logicalName}`);
}
return definition;
}
export function isStorageValueAllowed(
definition: StorageDefinition,
value: unknown,
): boolean {
switch (definition.valueCodec) {
case "color-scheme-v1":
return value === "light" || value === "dark" || value === "system";
case "opaque-string-v1":
return (
typeof value === "string" &&
value.length >= 1 &&
value.length <= 2_048
);
default:
return false;
}
}