The exact media-type regex lived in object-url-lease.ts, browser-file-policy-registry.ts and the download validation; safeOpaqueValue (vault) and safeGeneratedToken (download) were the same regex; and five modules each defined their own positive-safe-integer check (isPositiveByteLimit included). file-policy.ts now exports one copy of each: EXACT_MEDIA_TYPE, isSafeGeneratedToken, isPositiveSafeInteger. ObjectUrlLeaseRegistry.create also loses an inner revoke branch that could never run (it required a non-empty string inside a "not a non-empty string" guard). cache-storage/public-cache-policy.ts keeps its private positiveSafeInteger: adapters may not import another adapter's module. Verified: a characterization test (unsafe reference -> UNAVAILABLE, 128-char token accepted, empty object URL -> no revoke, fractional/zero limits and a wildcard download media type rejected) passes on the code before and after. Lane gates pass. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
523 lines
15 KiB
TypeScript
523 lines
15 KiB
TypeScript
import type {
|
|
DownloadStrategy,
|
|
FilePolicyReference,
|
|
FileSelectionLimitReduction,
|
|
} from "../../application/ports/browser-file-storage/file.ts";
|
|
import type {
|
|
BrowserDataOperation,
|
|
BrowserDataResult,
|
|
} from "../../application/ports/browser-file-storage/shared.ts";
|
|
import {
|
|
browserDataFailure,
|
|
browserDataSuccess,
|
|
} from "../browser-file-storage/result.ts";
|
|
import {
|
|
assertFileInspectionPolicy,
|
|
assertFileSelectionPolicy,
|
|
EXACT_MEDIA_TYPE,
|
|
isPositiveSafeInteger,
|
|
sanitizeSuggestedFileName,
|
|
type RegisteredFileInspectionPolicy,
|
|
type RegisteredFileSelectionPolicy,
|
|
} from "./file-policy.ts";
|
|
|
|
export type RegisteredPreviewPolicy = Readonly<{
|
|
allowedMediaTypes: readonly string[];
|
|
maxPreviewBytes: number;
|
|
}>;
|
|
|
|
export type RegisteredDownloadPolicy = Readonly<{
|
|
strategy: DownloadStrategy;
|
|
mediaType: string;
|
|
safeExtension: string;
|
|
maxTransferBytes: number;
|
|
maxBufferedBytes: number;
|
|
integrity: "OPTIONAL" | "REQUIRED";
|
|
}>;
|
|
|
|
export type BrowserFilePolicyProfile = Readonly<{
|
|
reference: FilePolicyReference;
|
|
selection?: RegisteredFileSelectionPolicy;
|
|
inspection?: RegisteredFileInspectionPolicy;
|
|
/**
|
|
* Preview is deliberately bound to the inspection policy in this profile.
|
|
* A verification receipt from another policy can never be replayed here.
|
|
*/
|
|
preview?: RegisteredPreviewPolicy;
|
|
download?: RegisteredDownloadPolicy;
|
|
}>;
|
|
|
|
export type BrowserFilePolicyRegistryOptions = Readonly<{
|
|
profiles: readonly BrowserFilePolicyProfile[];
|
|
hardLimits: Readonly<{
|
|
maxInspectionBytes: number;
|
|
maxRetainedFileBytes: number;
|
|
maxPreviewBytes: number;
|
|
maxObjectUrlBytes: number;
|
|
maxTransferBytes: number;
|
|
}>;
|
|
}>;
|
|
|
|
export type ResolvedPreviewPolicy = Readonly<{
|
|
verificationPolicyBindingId: string;
|
|
allowedMediaTypes: ReadonlySet<string>;
|
|
maxPreviewBytes: number;
|
|
}>;
|
|
|
|
export type ResolvedInspectionPolicy =
|
|
RegisteredFileInspectionPolicy &
|
|
Readonly<{ receiptBindingId: string }>;
|
|
|
|
export type ResolvedDownloadPolicy = RegisteredDownloadPolicy;
|
|
|
|
type SnapshotProfile = Readonly<{
|
|
receiptBindingId: string;
|
|
reference: FilePolicyReference;
|
|
selection?: RegisteredFileSelectionPolicy;
|
|
inspection?: RegisteredFileInspectionPolicy;
|
|
preview?: Readonly<{
|
|
allowedMediaTypes: ReadonlySet<string>;
|
|
maxPreviewBytes: number;
|
|
}>;
|
|
download?: RegisteredDownloadPolicy;
|
|
}>;
|
|
|
|
const POLICY_TOKEN = /^[a-z0-9][a-z0-9._:-]{0,127}$/i;
|
|
const ISSUED_POLICY_REFERENCES = new WeakSet<object>();
|
|
|
|
/**
|
|
* Creates the only policy reference accepted by the browser-file runtime.
|
|
* Product composition should inject the returned object into its narrow
|
|
* feature facade instead of exposing the whole registry to presentation.
|
|
*/
|
|
export function browserFilePolicyReference(
|
|
policyKey: string,
|
|
intention: string,
|
|
): FilePolicyReference {
|
|
if (!POLICY_TOKEN.test(policyKey) || !POLICY_TOKEN.test(intention)) {
|
|
throw new TypeError("Browser file policy reference is invalid.");
|
|
}
|
|
const reference = Object.freeze({
|
|
policyKey:
|
|
policyKey as FilePolicyReference["policyKey"],
|
|
intention:
|
|
intention as FilePolicyReference["intention"],
|
|
});
|
|
ISSUED_POLICY_REFERENCES.add(reference);
|
|
return reference;
|
|
}
|
|
|
|
/**
|
|
* Immutable composition-time registry. It retains no caller-owned object,
|
|
* array, Set or byte-pattern reference.
|
|
*/
|
|
export class BrowserFilePolicyRegistry {
|
|
readonly #profiles:
|
|
ReadonlyMap<FilePolicyReference, SnapshotProfile>;
|
|
|
|
constructor(options: BrowserFilePolicyRegistryOptions) {
|
|
assertHardLimits(options.hardLimits);
|
|
if (
|
|
!Array.isArray(options.profiles) ||
|
|
options.profiles.length < 1 ||
|
|
options.profiles.length > 128
|
|
) {
|
|
throw new TypeError("Browser file policy registry is invalid.");
|
|
}
|
|
const profiles =
|
|
new Map<FilePolicyReference, SnapshotProfile>();
|
|
const semanticKeys = new Set<string>();
|
|
for (const input of options.profiles) {
|
|
const profile = snapshotProfile(input, options.hardLimits);
|
|
const key = referenceKey(profile.reference);
|
|
if (semanticKeys.has(key)) {
|
|
throw new TypeError("Browser file policy reference is duplicated.");
|
|
}
|
|
semanticKeys.add(key);
|
|
profiles.set(profile.reference, profile);
|
|
}
|
|
this.#profiles = profiles;
|
|
}
|
|
|
|
resolveSelection(
|
|
reference: FilePolicyReference,
|
|
reduction?: FileSelectionLimitReduction,
|
|
): BrowserDataResult<RegisteredFileSelectionPolicy> {
|
|
const profile = this.#resolve(reference, "FILE_SELECT");
|
|
if (!profile.ok) return profile;
|
|
const policy = profile.value.selection;
|
|
if (!policy) {
|
|
return browserDataFailure("POLICY_REJECTED", "FILE_SELECT");
|
|
}
|
|
const maxCount = reducedLimit(
|
|
reduction?.maxCount,
|
|
policy.maxCount,
|
|
"FILE_SELECT",
|
|
);
|
|
if (!maxCount.ok) return maxCount;
|
|
const maxTotalBytes = reducedLimit(
|
|
reduction?.maxTotalBytes,
|
|
policy.maxTotalBytes,
|
|
"FILE_SELECT",
|
|
);
|
|
if (!maxTotalBytes.ok) return maxTotalBytes;
|
|
const maxFileBytes = reducedLimit(
|
|
reduction?.maxFileBytes,
|
|
Math.min(policy.maxFileBytes, maxTotalBytes.value),
|
|
"FILE_SELECT",
|
|
);
|
|
if (!maxFileBytes.ok) return maxFileBytes;
|
|
return browserDataSuccess(
|
|
Object.freeze({
|
|
...policy,
|
|
maxCount: maxCount.value,
|
|
maxFileBytes: maxFileBytes.value,
|
|
maxTotalBytes: maxTotalBytes.value,
|
|
}),
|
|
);
|
|
}
|
|
|
|
resolveInspection(
|
|
reference: FilePolicyReference,
|
|
maxInspectionBytes?: number,
|
|
): BrowserDataResult<ResolvedInspectionPolicy> {
|
|
const profile = this.#resolve(reference, "FILE_INSPECT");
|
|
if (!profile.ok) return profile;
|
|
const policy = profile.value.inspection;
|
|
if (!policy) {
|
|
return browserDataFailure("POLICY_REJECTED", "FILE_INSPECT");
|
|
}
|
|
const reduced = reducedLimit(
|
|
maxInspectionBytes,
|
|
policy.maxInspectionBytes,
|
|
"FILE_INSPECT",
|
|
);
|
|
if (!reduced.ok) return reduced;
|
|
return browserDataSuccess(
|
|
Object.freeze({
|
|
...policy,
|
|
maxInspectionBytes: reduced.value,
|
|
receiptBindingId: profile.value.receiptBindingId,
|
|
}),
|
|
);
|
|
}
|
|
|
|
resolvePreview(
|
|
reference: FilePolicyReference,
|
|
maxPreviewBytes?: number,
|
|
): BrowserDataResult<ResolvedPreviewPolicy> {
|
|
const profile = this.#resolve(reference, "PREVIEW");
|
|
if (!profile.ok) return profile;
|
|
if (!profile.value.preview || !profile.value.inspection) {
|
|
return browserDataFailure("POLICY_REJECTED", "PREVIEW");
|
|
}
|
|
const reduced = reducedLimit(
|
|
maxPreviewBytes,
|
|
profile.value.preview.maxPreviewBytes,
|
|
"PREVIEW",
|
|
);
|
|
if (!reduced.ok) return reduced;
|
|
return browserDataSuccess(
|
|
Object.freeze({
|
|
verificationPolicyBindingId:
|
|
profile.value.receiptBindingId,
|
|
allowedMediaTypes:
|
|
new Set(profile.value.preview.allowedMediaTypes),
|
|
maxPreviewBytes: reduced.value,
|
|
}),
|
|
);
|
|
}
|
|
|
|
resolveDownload(
|
|
reference: FilePolicyReference,
|
|
reductions: Readonly<{
|
|
maxTransferBytes?: number;
|
|
maxBufferedBytes?: number;
|
|
}>,
|
|
): BrowserDataResult<ResolvedDownloadPolicy> {
|
|
const profile = this.#resolve(reference, "DOWNLOAD");
|
|
if (!profile.ok) return profile;
|
|
const policy = profile.value.download;
|
|
if (!policy) {
|
|
return browserDataFailure("POLICY_REJECTED", "DOWNLOAD");
|
|
}
|
|
const maxTransferBytes = reducedLimit(
|
|
reductions.maxTransferBytes,
|
|
policy.maxTransferBytes,
|
|
"DOWNLOAD",
|
|
);
|
|
if (!maxTransferBytes.ok) return maxTransferBytes;
|
|
const maxBufferedBytes = reducedLimit(
|
|
reductions.maxBufferedBytes,
|
|
Math.min(policy.maxBufferedBytes, maxTransferBytes.value),
|
|
"DOWNLOAD",
|
|
);
|
|
if (!maxBufferedBytes.ok) return maxBufferedBytes;
|
|
return browserDataSuccess(
|
|
Object.freeze({
|
|
...policy,
|
|
maxTransferBytes: maxTransferBytes.value,
|
|
maxBufferedBytes: maxBufferedBytes.value,
|
|
}),
|
|
);
|
|
}
|
|
|
|
#resolve(
|
|
reference: FilePolicyReference,
|
|
operation: BrowserDataOperation,
|
|
): BrowserDataResult<SnapshotProfile> {
|
|
try {
|
|
if (
|
|
typeof reference !== "object" ||
|
|
reference === null ||
|
|
!ISSUED_POLICY_REFERENCES.has(reference)
|
|
) {
|
|
return browserDataFailure("POLICY_REJECTED", operation);
|
|
}
|
|
const profile = this.#profiles.get(reference);
|
|
return profile
|
|
? browserDataSuccess(profile)
|
|
: browserDataFailure("POLICY_REJECTED", operation);
|
|
} catch {
|
|
return browserDataFailure("POLICY_REJECTED", operation);
|
|
}
|
|
}
|
|
}
|
|
|
|
function snapshotProfile(
|
|
input: BrowserFilePolicyProfile,
|
|
hardLimits: BrowserFilePolicyRegistryOptions["hardLimits"],
|
|
): SnapshotProfile {
|
|
const reference = input.reference;
|
|
if (
|
|
typeof reference !== "object" ||
|
|
reference === null ||
|
|
!ISSUED_POLICY_REFERENCES.has(reference) ||
|
|
!Object.isFrozen(reference)
|
|
) {
|
|
throw new TypeError(
|
|
"Browser file policy reference was not issued by composition.",
|
|
);
|
|
}
|
|
referenceKey(reference);
|
|
if (
|
|
input.selection === undefined &&
|
|
input.inspection === undefined &&
|
|
input.preview === undefined &&
|
|
input.download === undefined
|
|
) {
|
|
throw new TypeError("Browser file policy profile is empty.");
|
|
}
|
|
|
|
const selection = input.selection
|
|
? snapshotSelection(input.selection)
|
|
: undefined;
|
|
if (
|
|
selection &&
|
|
(selection.maxFileBytes > hardLimits.maxRetainedFileBytes ||
|
|
selection.maxTotalBytes > hardLimits.maxRetainedFileBytes)
|
|
) {
|
|
throw new TypeError("File selection policy exceeds runtime limits.");
|
|
}
|
|
|
|
const inspection = input.inspection
|
|
? snapshotInspection(
|
|
input.inspection,
|
|
hardLimits.maxInspectionBytes,
|
|
)
|
|
: undefined;
|
|
if (input.preview && !inspection) {
|
|
throw new TypeError(
|
|
"Preview policy requires an inspection policy in the same profile.",
|
|
);
|
|
}
|
|
const preview = input.preview
|
|
? snapshotPreview(input.preview, hardLimits.maxPreviewBytes)
|
|
: undefined;
|
|
const download = input.download
|
|
? snapshotDownload(input.download, hardLimits)
|
|
: undefined;
|
|
|
|
return Object.freeze({
|
|
receiptBindingId: referenceKey(reference),
|
|
reference,
|
|
...(selection ? { selection } : {}),
|
|
...(inspection ? { inspection } : {}),
|
|
...(preview ? { preview } : {}),
|
|
...(download ? { download } : {}),
|
|
});
|
|
}
|
|
|
|
function snapshotSelection(
|
|
input: RegisteredFileSelectionPolicy,
|
|
): RegisteredFileSelectionPolicy {
|
|
const snapshot = Object.freeze({
|
|
policyId: input.policyId,
|
|
purpose: input.purpose,
|
|
classification: input.classification,
|
|
multiple: input.multiple,
|
|
maxCount: input.maxCount,
|
|
maxFileBytes: input.maxFileBytes,
|
|
maxTotalBytes: input.maxTotalBytes,
|
|
allowEmpty: input.allowEmpty,
|
|
accept: Object.freeze(
|
|
input.accept.map((rule) =>
|
|
Object.freeze({
|
|
mediaType: rule.mediaType.trim().toLowerCase(),
|
|
extensions: Object.freeze(
|
|
rule.extensions.map((extension) =>
|
|
extension.trim().toLowerCase(),
|
|
),
|
|
),
|
|
}),
|
|
),
|
|
),
|
|
});
|
|
assertFileSelectionPolicy(snapshot);
|
|
return snapshot;
|
|
}
|
|
|
|
function snapshotInspection(
|
|
input: RegisteredFileInspectionPolicy,
|
|
hardMaxInspectionBytes: number,
|
|
): RegisteredFileInspectionPolicy {
|
|
const snapshot = Object.freeze({
|
|
policyId: input.policyId,
|
|
maxInspectionBytes: input.maxInspectionBytes,
|
|
acceptedSignatures: Object.freeze(
|
|
input.acceptedSignatures.map((rule) =>
|
|
Object.freeze({
|
|
mediaType: rule.mediaType.trim().toLowerCase(),
|
|
extensions: Object.freeze(
|
|
rule.extensions.map((extension) =>
|
|
extension.trim().toLowerCase(),
|
|
),
|
|
),
|
|
patterns: Object.freeze(
|
|
rule.patterns.map((pattern) =>
|
|
Object.freeze({
|
|
offset: pattern.offset,
|
|
bytes: Object.freeze([...pattern.bytes]),
|
|
...(pattern.mask
|
|
? { mask: Object.freeze([...pattern.mask]) }
|
|
: {}),
|
|
}),
|
|
),
|
|
),
|
|
}),
|
|
),
|
|
),
|
|
});
|
|
assertFileInspectionPolicy(snapshot, hardMaxInspectionBytes);
|
|
return snapshot;
|
|
}
|
|
|
|
function snapshotPreview(
|
|
input: RegisteredPreviewPolicy,
|
|
hardMaxPreviewBytes: number,
|
|
): SnapshotProfile["preview"] {
|
|
if (
|
|
!isPositiveSafeInteger(input.maxPreviewBytes) ||
|
|
input.maxPreviewBytes > hardMaxPreviewBytes ||
|
|
!Array.isArray(input.allowedMediaTypes) ||
|
|
input.allowedMediaTypes.length < 1 ||
|
|
input.allowedMediaTypes.length > 64
|
|
) {
|
|
throw new TypeError("File preview policy is invalid.");
|
|
}
|
|
const allowedMediaTypes = new Set<string>();
|
|
for (const inputMediaType of input.allowedMediaTypes) {
|
|
const mediaType = inputMediaType.trim().toLowerCase();
|
|
if (!EXACT_MEDIA_TYPE.test(mediaType)) {
|
|
throw new TypeError("File preview media type is invalid.");
|
|
}
|
|
allowedMediaTypes.add(mediaType);
|
|
}
|
|
return Object.freeze({
|
|
allowedMediaTypes,
|
|
maxPreviewBytes: input.maxPreviewBytes,
|
|
});
|
|
}
|
|
|
|
function snapshotDownload(
|
|
input: RegisteredDownloadPolicy,
|
|
hardLimits: BrowserFilePolicyRegistryOptions["hardLimits"],
|
|
): RegisteredDownloadPolicy {
|
|
const mediaType = input.mediaType.trim().toLowerCase();
|
|
const safeExtension = input.safeExtension.trim().toLowerCase();
|
|
if (
|
|
![
|
|
"BROWSER_MANAGED",
|
|
"PROMPT_AND_STREAM",
|
|
"BOUNDED_OBJECT_URL",
|
|
].includes(input.strategy) ||
|
|
!EXACT_MEDIA_TYPE.test(mediaType) ||
|
|
!isPositiveSafeInteger(input.maxTransferBytes) ||
|
|
!isPositiveSafeInteger(input.maxBufferedBytes) ||
|
|
input.maxTransferBytes > hardLimits.maxTransferBytes ||
|
|
input.maxBufferedBytes > input.maxTransferBytes ||
|
|
(input.strategy === "BOUNDED_OBJECT_URL" &&
|
|
input.maxBufferedBytes > hardLimits.maxObjectUrlBytes) ||
|
|
!["OPTIONAL", "REQUIRED"].includes(input.integrity)
|
|
) {
|
|
throw new TypeError("File download policy is invalid.");
|
|
}
|
|
// Reuse the production filename extension validator.
|
|
sanitizeSuggestedFileName("download", { safeExtension });
|
|
return Object.freeze({
|
|
strategy: input.strategy,
|
|
mediaType,
|
|
safeExtension,
|
|
maxTransferBytes: input.maxTransferBytes,
|
|
maxBufferedBytes: input.maxBufferedBytes,
|
|
integrity: input.integrity,
|
|
});
|
|
}
|
|
|
|
function assertHardLimits(
|
|
input: BrowserFilePolicyRegistryOptions["hardLimits"],
|
|
): void {
|
|
if (
|
|
!isPositiveSafeInteger(input.maxInspectionBytes) ||
|
|
!isPositiveSafeInteger(input.maxRetainedFileBytes) ||
|
|
!isPositiveSafeInteger(input.maxPreviewBytes) ||
|
|
!isPositiveSafeInteger(input.maxObjectUrlBytes) ||
|
|
!isPositiveSafeInteger(input.maxTransferBytes) ||
|
|
input.maxObjectUrlBytes > input.maxTransferBytes
|
|
) {
|
|
throw new TypeError("Browser file policy hard limits are invalid.");
|
|
}
|
|
}
|
|
|
|
function reducedLimit(
|
|
requested: number | undefined,
|
|
configured: number,
|
|
operation: BrowserDataOperation,
|
|
): BrowserDataResult<number> {
|
|
if (requested === undefined) {
|
|
return browserDataSuccess(configured);
|
|
}
|
|
if (!isPositiveSafeInteger(requested)) {
|
|
return browserDataFailure("INVALID_INPUT", operation);
|
|
}
|
|
if (requested > configured) {
|
|
return browserDataFailure("LIMIT_EXCEEDED", operation);
|
|
}
|
|
return browserDataSuccess(requested);
|
|
}
|
|
|
|
function referenceKey(reference: FilePolicyReference): string {
|
|
if (
|
|
!reference ||
|
|
typeof reference !== "object" ||
|
|
!POLICY_TOKEN.test(reference.policyKey) ||
|
|
!POLICY_TOKEN.test(reference.intention)
|
|
) {
|
|
throw new TypeError("Browser file policy reference is invalid.");
|
|
}
|
|
return JSON.stringify([
|
|
reference.policyKey,
|
|
reference.intention,
|
|
]);
|
|
}
|