Files
clean-architecture-frontend…/src/adapters/browser-transfer/image-cdn
donghyeon-kaandClaude Opus 5.5 49413af045 fix(types): turn on noUnusedLocals and drop the unused declarations (12-12)
VD-01 decision 3 hands unused diagnostics to tsc and turns off ESLint's
no-unused-vars for TS files, but tsconfig.base.json never enabled the
tsc check (D-19). The flag found 46 unused imports, types and helpers
across 22 files; none of them were read, so removing them changes no
behaviour.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 13:32:33 +09:00
..
2026-07-30 15:58:20 +09:00

Image CDN composition

This adapter accepts no source URL or transform query from a feature. Product composition owns the origin registry and named presets. A backend gateway may use runtime.assets; presentation receives only the narrow runtime.presentation facade plus registry-issued asset and preset references.

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();

For a public immutable asset, the trusted gateway calls acceptPublicImmutable with only an allowlisted originKey, opaque assetId and revision, raster metadata and intrinsic dimensions. applicationOrigin must be the deployment's canonical HTTPS origin, without a trailing slash, and every CDN origin must differ from it. This is required because an anonymous image request omits credentials only when it is cross-origin. Private descriptors must be backend-signed, remain above the configured minimum TTL at every resolve, and use an eager, non-low-priority PRIMARY_REQUIRED preset. A PRIMARY_REQUIRED preset must use fit cover, contain or fill: the probe expects the exact primary pixel size, and inside/outside keep the source ratio, so the registry rejects that combination at composition time. Digest and signature verification share one composition-owned deadline and race the caller's abort signal. The probe sends no credentials, rejects any final URL other than the exact signed URL, and requires the private response to declare the flag-only directive Cache-Control: no-store. Before native decode, the adapter parses the bounded PNG, JPEG, WebP or AVIF container, rejects animation and enforces both pixel and decoded-byte budgets. Its adapter-owned timeout covers response headers, streamed body consumption and decode; abort paths cancel the reader and close even a late ImageBitmap. The client never purges a CDN: public URLs roll forward by revision, while private delivery relies on backend capability revocation or expiry.

Composition-supplied hard limits may only tighten IMAGE_CDN_IMPLEMENTATION_CEILINGS; configuration cannot raise intrinsic, source/output pixel, decoded/encoded byte, candidate, URL or capability lifetime ceilings owned by the adapter. Private verification additionally reserves one of the bounded maxConcurrentCapabilityVerifications slots and always releases it after success, failure, abort or close.

acceptedKeyIds is a bounded, unique overlap set, not the active signing-key selector. The verifier registry must cover every accepted ID. Rotate by first deploying the new public key and an old/new overlap set, then switch the backend signer. Retain the old key for client rollout plus at least maxCapabilityLifetimeMs + maxClockSkewMs; remove it only after old clients and capabilities are exhausted. A compromised key instead requires backend revocation, runtime.close(), recomposition and a forced client rollout.

close() is terminal and idempotent. It aborts in-flight private verification and probing and replaces the runtime's WeakMap capability registry, immediately revoking every issued reference without retaining them strongly. Every later accept or resolve returns closed UNAVAILABLE; resuming requires a newly composed runtime.