# Image CDN 조립(composition) 이 adapter는 feature에게서 source URL이나 변환(transform) query를 받지 않는다. origin registry와 이름 붙은 preset은 제품 composition이 소유한다. 백엔드 gateway는 `runtime.assets`를 쓸 수 있다. presentation은 좁은 `runtime.presentation` facade와, registry가 발급한 asset·preset 참조만 받는다. ```ts import { ImageCdnPolicyRegistry, createBrowserImageProbe, createImageCdnRuntime, createP256ImageCapabilityVerifier, imageCdnPresetReference, } from "./index.ts"; const cardImage = imageCdnPresetReference( "product-card", "render-product-card-image", ); const policies = new ImageCdnPolicyRegistry({ applicationOrigin: "https://app.example.com", origins: [{ originKey: "product-images", origin: "https://images.example.com", assetPathPrefix: "/v1/assets/", minimumPublicMaxAgeSeconds: 31_536_000, }], presets: [{ reference: cardImage, bindingId: "product-card-v1", width: 640, height: 360, fit: "cover", dprs: [1, 2], responsiveWidths: [320, 640], quality: 80, formats: ["avif", "webp", "jpeg"], sizes: "(max-width: 640px) 100vw, 640px", loading: "eager", decoding: "async", fetchPriority: "high", referrerPolicy: "no-referrer", probeMode: "PRIMARY_REQUIRED", allowUpscale: false, maxTransformedPixels: 1_048_576, maxDecodedBytes: 4_194_304, maxEncodedBytes: 524_288, }], hardLimits: { maxIntrinsicWidth: 4_096, maxIntrinsicHeight: 4_096, maxSourcePixels: 16_777_216, maxCssDimension: 2_048, maxDpr: 2, maxQuality: 90, maxCandidateCount: 8, maxTransformedPixels: 1_048_576, maxDecodedBytes: 4_194_304, maxEncodedBytes: 524_288, maxUrlLength: 2_048, maxCapabilityLifetimeMs: 3_600_000, maxClockSkewMs: 60_000, minCapabilityRemainingMs: 30_000, maxPresetBindingsPerCapability: 8, maxConcurrentCapabilityVerifications: 8, allowedSourceMediaTypes: [ "image/avif", "image/jpeg", "image/png", "image/webp", ], formatQualityCeilings: { avif: 80, jpeg: 85, png: 90, webp: 85, }, }, capability: { issuer: "image-bff", acceptedKeyIds: [ "image-signing-2026-02", "image-signing-2026-01", ], }, }); const runtime = createImageCdnRuntime({ policies, subtle: crypto.subtle, capabilityVerifier: createP256ImageCapabilityVerifier({ subtle: crypto.subtle, publicKeys: [{ keyId: "image-signing-2026-02", key: currentImageCapabilityPublicKey, }, { keyId: "image-signing-2026-01", key: previousImageCapabilityPublicKey, }], }), capabilityVerificationTimeoutMs: 5_000, probe: createBrowserImageProbe(), observer: safeBrowserDataObserver, }); // `payload` is a strictly decoded BackendIssuedImageAsset from the BFF. const accepted = await runtime.assets.acceptBackendIssued(payload, { signal, }); if (!accepted.ok) return accepted; // Expose only this closure to the feature/presentation composition. const resolveCardImage = (signal: AbortSignal) => runtime.presentation.resolve({ asset: accepted.value, preset: cardImage, signal, }); // Application-scope teardown, logout, account/tenant partition change, or // replacement by a newly composed runtime. Never call this per render. const closeImageRuntime = (): void => runtime.close(); ``` 공개된 바뀌지 않는(public immutable) asset이면 신뢰하는 gateway가 `acceptPublicImmutable`을 부른다. 넘기는 것은 허용 목록에 있는 `originKey`, 불투명한(opaque) `assetId`와 `revision`, raster metadata, 원본 크기(intrinsic dimensions)뿐이다. `applicationOrigin`은 배포의 canonical HTTPS origin이어야 하고, 끝에 slash가 없어야 한다. 모든 CDN origin은 그것과 달라야 한다. `anonymous` 이미지 요청은 cross-origin일 때만 자격 증명을 빼기 때문이다. private descriptor는 백엔드가 서명해야 한다. 또 resolve할 때마다 설정된 최소 TTL보다 많이 남아 있어야 하고, eager이면서 낮은 우선순위가 아닌 `PRIMARY_REQUIRED` preset을 써야 한다. `PRIMARY_REQUIRED` preset의 `fit`은 `cover`, `contain`, `fill` 중 하나여야 한다. probe는 정확한 기본(primary) 픽셀 크기를 기대하는데, `inside`/`outside`는 원본 비율을 유지하기 때문이다. 그래서 registry는 composition 시점에 그 조합을 거부한다. digest 검증과 서명 검증은 composition이 소유한 마감 시간 하나를 함께 쓰고, 호출한 쪽의 abort signal과 경쟁한다. probe는 자격 증명을 보내지 않는다. 서명된 URL과 정확히 같지 않은 최종 URL은 모두 거부한다. private 응답에는 값 없는 지시어 `Cache-Control: no-store`가 선언돼 있어야 한다. native decode 전에 adapter는 크기 제한이 있는 PNG, JPEG, WebP, AVIF container를 파싱한다. animation은 거부하고, 픽셀 budget과 decode된 바이트 budget을 둘 다 강제한다. adapter가 소유한 시간 제한은 응답 header, stream 본문 읽기, decode를 모두 덮는다. abort 경로는 reader를 취소하고, 늦게 도착한 ImageBitmap까지 닫는다. 클라이언트는 CDN을 절대 purge하지 않는다. 공개 URL은 revision을 올려 앞으로 넘어가고, private 전달은 백엔드의 capability 폐기나 만료에 기댄다. composition이 주는 hard limit은 `IMAGE_CDN_IMPLEMENTATION_CEILINGS`를 더 조이기만 할 수 있다. 설정으로는 adapter가 소유한 상한을 올릴 수 없다: 원본 크기, source·output 픽셀, decode·encode 바이트, 후보 수, URL, capability 수명. private 검증은 추가로, 개수가 제한된 `maxConcurrentCapabilityVerifications` 슬롯 하나를 잡는다. 성공, 실패, abort, close 뒤에는 늘 그 슬롯을 돌려준다. `acceptedKeyIds`는 크기 제한이 있고 중복 없는 겹침(overlap) 집합이다. 지금 서명에 쓰는 키를 고르는 값이 아니다. verifier registry는 받아들이는 ID를 모두 덮어야 한다. 키를 교체할 때는 먼저 새 공개 키와 옛·새 겹침 집합을 배포하고, 그다음 백엔드 서명 주체(signer)를 바꾼다. 옛 키는 클라이언트 배포(rollout)에 걸리는 시간에 최소 `maxCapabilityLifetimeMs + maxClockSkewMs`를 더한 동안 남겨 둔다. 옛 클라이언트와 capability가 모두 사라진 뒤에만 지운다. 키가 유출됐다면 이 순서 대신 백엔드 폐기, `runtime.close()`, 다시 조립(recomposition), 강제 클라이언트 배포가 필요하다. `close()`는 끝 상태로 가고(terminal), 여러 번 불러도 결과가 같다(idempotent). 진행 중인 private 검증과 probe를 abort하고, runtime의 WeakMap capability registry를 새것으로 바꾼다. 그래서 발급한 참조를 강하게 붙잡지 않고도 모두 즉시 폐기한다. 그 뒤의 accept나 resolve는 모두 닫힘 상태의 `UNAVAILABLE`을 돌려준다. 다시 쓰려면 새로 조립한 runtime이 필요하다.