Files
clean-architecture-frontend…/src/adapters/browser-transfer/image-cdn
DongHyeonkaandClaude Opus 5 cc4e875c2d fix: bound browser transfer leases and effect reporting
BT-X-01: add the shared abortable-operation utility with golden tests for first
terminal owner, idempotent close, listener and timer cleanup under a throwing
scheduler, observed late rejection and late-handle compensation. It carries no
subsystem result taxonomy.

BT-PRE-01: make the presigned download lease lazy and single-start. open() now
validates, claims and consumes the capability without any network I/O; the
fetch, the transfer deadline and the expiry recheck happen at first stream
consumption. The source gained close(), which discards an unused lease with no
I/O and otherwise cancels the body and releases the scope exactly once.

BT-UP-01: require removeEventListener in the AbortSignal structural guard and
isolate release cleanup so a hostile facade cannot replace a typed terminal
result with a rejection.

BT-UP-03: deleteDatabase cannot be cancelled after dispatch, so a blocked
deadline now returns PENDING with effect UNKNOWN instead of a failure that reads
as NOT_APPLIED. A realm-scoped (factory, databaseName) registry prevents
recreating the partition until the native request settles.

BT-UP-04: reject non-finite and negative upload clocks as a dependency failure
instead of letting them bypass every capability expiry comparison.

BT-IMG-02: replace the naive Cache-Control quote stripping with a quote- and
escape-aware tokenizer, so max-age="60 or 60" is no longer read as 60 and a
comma inside a quoted extension is not a directive boundary.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-14 00:13:54 +09:00
..
2026-07-30 15:58:20 +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. 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.