refactor(browser-files): share the media-type, token and limit checks (Q-6.2-12)
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>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
4093ee8fc2
commit
042427c887
@@ -14,6 +14,8 @@ import {
|
||||
import {
|
||||
assertFileInspectionPolicy,
|
||||
assertFileSelectionPolicy,
|
||||
EXACT_MEDIA_TYPE,
|
||||
isPositiveSafeInteger,
|
||||
sanitizeSuggestedFileName,
|
||||
type RegisteredFileInspectionPolicy,
|
||||
type RegisteredFileSelectionPolicy,
|
||||
@@ -81,8 +83,6 @@ type SnapshotProfile = Readonly<{
|
||||
}>;
|
||||
|
||||
const POLICY_TOKEN = /^[a-z0-9][a-z0-9._:-]{0,127}$/i;
|
||||
const MEDIA_TYPE =
|
||||
/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/i;
|
||||
const ISSUED_POLICY_REFERENCES = new WeakSet<object>();
|
||||
|
||||
/**
|
||||
@@ -417,7 +417,7 @@ function snapshotPreview(
|
||||
hardMaxPreviewBytes: number,
|
||||
): SnapshotProfile["preview"] {
|
||||
if (
|
||||
!positiveSafeInteger(input.maxPreviewBytes) ||
|
||||
!isPositiveSafeInteger(input.maxPreviewBytes) ||
|
||||
input.maxPreviewBytes > hardMaxPreviewBytes ||
|
||||
!Array.isArray(input.allowedMediaTypes) ||
|
||||
input.allowedMediaTypes.length < 1 ||
|
||||
@@ -428,7 +428,7 @@ function snapshotPreview(
|
||||
const allowedMediaTypes = new Set<string>();
|
||||
for (const inputMediaType of input.allowedMediaTypes) {
|
||||
const mediaType = inputMediaType.trim().toLowerCase();
|
||||
if (!MEDIA_TYPE.test(mediaType)) {
|
||||
if (!EXACT_MEDIA_TYPE.test(mediaType)) {
|
||||
throw new TypeError("File preview media type is invalid.");
|
||||
}
|
||||
allowedMediaTypes.add(mediaType);
|
||||
@@ -451,9 +451,9 @@ function snapshotDownload(
|
||||
"PROMPT_AND_STREAM",
|
||||
"BOUNDED_OBJECT_URL",
|
||||
].includes(input.strategy) ||
|
||||
!MEDIA_TYPE.test(mediaType) ||
|
||||
!positiveSafeInteger(input.maxTransferBytes) ||
|
||||
!positiveSafeInteger(input.maxBufferedBytes) ||
|
||||
!EXACT_MEDIA_TYPE.test(mediaType) ||
|
||||
!isPositiveSafeInteger(input.maxTransferBytes) ||
|
||||
!isPositiveSafeInteger(input.maxBufferedBytes) ||
|
||||
input.maxTransferBytes > hardLimits.maxTransferBytes ||
|
||||
input.maxBufferedBytes > input.maxTransferBytes ||
|
||||
(input.strategy === "BOUNDED_OBJECT_URL" &&
|
||||
@@ -478,11 +478,11 @@ function assertHardLimits(
|
||||
input: BrowserFilePolicyRegistryOptions["hardLimits"],
|
||||
): void {
|
||||
if (
|
||||
!positiveSafeInteger(input.maxInspectionBytes) ||
|
||||
!positiveSafeInteger(input.maxRetainedFileBytes) ||
|
||||
!positiveSafeInteger(input.maxPreviewBytes) ||
|
||||
!positiveSafeInteger(input.maxObjectUrlBytes) ||
|
||||
!positiveSafeInteger(input.maxTransferBytes) ||
|
||||
!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.");
|
||||
@@ -497,7 +497,7 @@ function reducedLimit(
|
||||
if (requested === undefined) {
|
||||
return browserDataSuccess(configured);
|
||||
}
|
||||
if (!positiveSafeInteger(requested)) {
|
||||
if (!isPositiveSafeInteger(requested)) {
|
||||
return browserDataFailure("INVALID_INPUT", operation);
|
||||
}
|
||||
if (requested > configured) {
|
||||
@@ -520,7 +520,3 @@ function referenceKey(reference: FilePolicyReference): string {
|
||||
reference.intention,
|
||||
]);
|
||||
}
|
||||
|
||||
function positiveSafeInteger(value: number): boolean {
|
||||
return Number.isSafeInteger(value) && value > 0;
|
||||
}
|
||||
|
||||
@@ -27,6 +27,8 @@ import {
|
||||
assertFileInspectionPolicy,
|
||||
assertFileSelectionPolicy,
|
||||
findMatchingSignature,
|
||||
isPositiveSafeInteger,
|
||||
isSafeGeneratedToken,
|
||||
matchesSelectionHint,
|
||||
normalizedExtension,
|
||||
signatureMetadataMatches,
|
||||
@@ -685,7 +687,7 @@ export class BrowserFileVault
|
||||
return browserDataFailure("LIMIT_EXCEEDED", "FILE_SELECT");
|
||||
}
|
||||
const refValue = this.#createReference();
|
||||
if (!safeOpaqueValue(refValue)) {
|
||||
if (!isSafeGeneratedToken(refValue)) {
|
||||
return browserDataFailure("UNAVAILABLE", "FILE_SELECT");
|
||||
}
|
||||
const ref = refValue as LocalFileRef;
|
||||
@@ -720,7 +722,7 @@ export class BrowserFileVault
|
||||
#issueVerification(record: VerificationRecord):
|
||||
BrowserDataResult<FileVerificationReceipt> {
|
||||
const receiptValue = this.#createVerificationReceipt();
|
||||
if (!safeOpaqueValue(receiptValue)) {
|
||||
if (!isSafeGeneratedToken(receiptValue)) {
|
||||
return browserDataFailure("UNAVAILABLE", "FILE_INSPECT");
|
||||
}
|
||||
const receipt = receiptValue as FileVerificationReceipt;
|
||||
@@ -868,14 +870,6 @@ function normalizedMediaType(value: string): string | null {
|
||||
return normalized.length > 0 ? normalized : null;
|
||||
}
|
||||
|
||||
function isPositiveSafeInteger(value: number): boolean {
|
||||
return Number.isSafeInteger(value) && value > 0;
|
||||
}
|
||||
|
||||
function safeOpaqueValue(value: string): boolean {
|
||||
return /^[a-z0-9][a-z0-9:_-]{0,127}$/i.test(value);
|
||||
}
|
||||
|
||||
function abortException(): DOMException {
|
||||
return new DOMException("Operation aborted", "AbortError");
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
type DownloadDeliveryAdapterOptions,
|
||||
} from "./download-delivery-adapter.ts";
|
||||
import type { BrowserFileObserver } from "./file-observer.ts";
|
||||
import { isPositiveSafeInteger } from "./file-policy.ts";
|
||||
import {
|
||||
BrowserTransientPreview,
|
||||
ObjectUrlLeaseRegistry,
|
||||
@@ -239,7 +240,3 @@ function resolveRuntimeLimits(
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
function isPositiveSafeInteger(value: number): boolean {
|
||||
return Number.isSafeInteger(value) && value > 0;
|
||||
}
|
||||
|
||||
@@ -34,11 +34,10 @@ import {
|
||||
type ObjectUrlLease,
|
||||
} from "./object-url-lease.ts";
|
||||
import { BrowserFilePolicyRegistry } from "./browser-file-policy-registry.ts";
|
||||
import { isPositiveSafeInteger, isSafeGeneratedToken } from "./file-policy.ts";
|
||||
import {
|
||||
activeDeliveryInput,
|
||||
isPositiveByteLimit,
|
||||
resolveBrowserManagedTarget,
|
||||
safeGeneratedToken,
|
||||
validByteSource,
|
||||
validPresignedByteSource,
|
||||
validateBrowserManagedCapability,
|
||||
@@ -183,8 +182,8 @@ export function createDownloadDeliveryAdapter(
|
||||
progressMinIntervalMs < 0 ||
|
||||
!Number.isSafeInteger(releaseDelayMs) ||
|
||||
releaseDelayMs < 0 ||
|
||||
!isPositiveByteLimit(options.hardMaxObjectUrlBytes) ||
|
||||
!isPositiveByteLimit(options.hardMaxTransferBytes) ||
|
||||
!isPositiveSafeInteger(options.hardMaxObjectUrlBytes) ||
|
||||
!isPositiveSafeInteger(options.hardMaxTransferBytes) ||
|
||||
options.hardMaxObjectUrlBytes > options.hardMaxTransferBytes ||
|
||||
typeof options.host?.handoff !== "function" ||
|
||||
typeof options.policies?.resolveDownload !== "function" ||
|
||||
@@ -335,7 +334,7 @@ export function createDownloadDeliveryAdapter(
|
||||
dependencies.observer,
|
||||
);
|
||||
}
|
||||
if (!safeGeneratedToken(transferId)) {
|
||||
if (!isSafeGeneratedToken(transferId)) {
|
||||
return observeResult(
|
||||
browserDataFailure("UNAVAILABLE", "DOWNLOAD"),
|
||||
dependencies.observer,
|
||||
|
||||
@@ -15,6 +15,8 @@ import {
|
||||
browserDataSuccess,
|
||||
} from "../browser-file-storage/result.ts";
|
||||
import {
|
||||
EXACT_MEDIA_TYPE,
|
||||
isPositiveSafeInteger,
|
||||
sanitizeSuggestedFileName,
|
||||
type SuggestedFileNamePolicy,
|
||||
} from "./file-policy.ts";
|
||||
@@ -36,7 +38,6 @@ export type DownloadInputValidationOptions = Readonly<{
|
||||
now?: () => number;
|
||||
}>;
|
||||
|
||||
export const MEDIA_TYPE = /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/i;
|
||||
export const SHA256 = /^[a-f0-9]{64}$/i;
|
||||
|
||||
export type DeliveryRequest =
|
||||
@@ -119,7 +120,7 @@ export function validateDownloadInput(
|
||||
if (
|
||||
input.signal.aborted ||
|
||||
input.suggestedFileName.length === 0 ||
|
||||
!MEDIA_TYPE.test(input.mediaType) ||
|
||||
!EXACT_MEDIA_TYPE.test(input.mediaType) ||
|
||||
!isValidByteLength(input.maxTransferBytes) ||
|
||||
input.maxTransferBytes === 0 ||
|
||||
!isValidByteLength(input.maxBufferedBytes) ||
|
||||
@@ -246,7 +247,7 @@ export function validPresignedCapabilityForInput(
|
||||
capability.binding.resourceId === resourceId &&
|
||||
capability.mediaType === mediaType &&
|
||||
isValidByteLength(capability.byteLength) &&
|
||||
isPositiveByteLimit(capability.maxBytes) &&
|
||||
isPositiveSafeInteger(capability.maxBytes) &&
|
||||
capability.byteLength <= capability.maxBytes &&
|
||||
capability.maxBytes <= maxTransferBytes &&
|
||||
SHA256.test(capability.expectedSha256) &&
|
||||
@@ -277,7 +278,7 @@ export function validateBrowserManagedCapability(
|
||||
input.mediaType ||
|
||||
capability.safeExtension.trim().toLowerCase() !==
|
||||
input.safeExtension ||
|
||||
!isPositiveByteLimit(capability.maxBytes) ||
|
||||
!isPositiveSafeInteger(capability.maxBytes) ||
|
||||
capability.maxBytes > input.maxTransferBytes ||
|
||||
!Number.isSafeInteger(capability.expiresAtEpochMs) ||
|
||||
!Number.isSafeInteger(nowEpochMs) ||
|
||||
@@ -364,11 +365,3 @@ export function safeOpaqueId(value: unknown): value is string {
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function safeGeneratedToken(value: string): boolean {
|
||||
return /^[a-z0-9][a-z0-9:_-]{0,127}$/i.test(value);
|
||||
}
|
||||
|
||||
export function isPositiveByteLimit(value: number): boolean {
|
||||
return isValidByteLength(value) && value > 0;
|
||||
}
|
||||
|
||||
@@ -40,6 +40,21 @@ export type RegisteredFileInspectionPolicy = Readonly<{
|
||||
}>;
|
||||
|
||||
const MEDIA_TYPE = /^[a-z0-9!#$&^_.+-]+\/(?:[a-z0-9!#$&^_.+-]+|\*)$/i;
|
||||
/**
|
||||
* Q-6.2-12. The shared browser-file copies of three checks that used to be
|
||||
* redefined per module: an exact `type/subtype` media type (no wildcard), a
|
||||
* generated opaque token (file reference, receipt or transfer ID) and a
|
||||
* positive safe integer limit.
|
||||
*/
|
||||
export const EXACT_MEDIA_TYPE = /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/i;
|
||||
|
||||
export function isSafeGeneratedToken(value: string): boolean {
|
||||
return /^[a-z0-9][a-z0-9:_-]{0,127}$/i.test(value);
|
||||
}
|
||||
|
||||
export function isPositiveSafeInteger(value: number): boolean {
|
||||
return Number.isSafeInteger(value) && value > 0;
|
||||
}
|
||||
const EXTENSION =
|
||||
/^\.[a-z0-9][a-z0-9+_-]{0,15}(?:\.[a-z0-9][a-z0-9+_-]{0,15})?$/i;
|
||||
const POLICY_TOKEN = /^[a-z0-9][a-z0-9._:-]{0,127}$/i;
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
type BrowserFileObserver,
|
||||
} from "./file-observer.ts";
|
||||
import { BrowserFilePolicyRegistry } from "./browser-file-policy-registry.ts";
|
||||
import { EXACT_MEDIA_TYPE, isPositiveSafeInteger } from "./file-policy.ts";
|
||||
|
||||
export type ObjectUrlApi = Readonly<{
|
||||
createObjectURL(blob: Blob): string;
|
||||
@@ -109,13 +110,6 @@ export class ObjectUrlLeaseRegistry {
|
||||
}
|
||||
const url = this.#createObjectURL(blob);
|
||||
if (typeof url !== "string" || url.length === 0) {
|
||||
if (typeof url === "string" && url.length > 0) {
|
||||
try {
|
||||
this.#revokeObjectURL(url);
|
||||
} catch {
|
||||
// The invalid lease is rejected regardless of cleanup support.
|
||||
}
|
||||
}
|
||||
throw new DOMException(
|
||||
"Object URL allocation failed",
|
||||
"InvalidStateError",
|
||||
@@ -184,7 +178,6 @@ const DEFAULT_ACTIVE_CONTENT = new Set([
|
||||
"text/html",
|
||||
"text/xml",
|
||||
]);
|
||||
const MEDIA_TYPE = /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/i;
|
||||
|
||||
export class BrowserTransientPreview implements TransientPreviewPort {
|
||||
readonly #resolveVerifiedFile:
|
||||
@@ -269,7 +262,7 @@ export class BrowserTransientPreview implements TransientPreviewPort {
|
||||
}
|
||||
const mediaType = resolved.value.mediaType.trim().toLowerCase();
|
||||
if (
|
||||
!MEDIA_TYPE.test(mediaType) ||
|
||||
!EXACT_MEDIA_TYPE.test(mediaType) ||
|
||||
!policy.allowedMediaTypes.has(mediaType) ||
|
||||
this.#hardForbiddenMediaTypes.has(mediaType)
|
||||
) {
|
||||
@@ -333,7 +326,3 @@ export class BrowserTransientPreview implements TransientPreviewPort {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
function isPositiveSafeInteger(value: number): boolean {
|
||||
return Number.isSafeInteger(value) && value > 0;
|
||||
}
|
||||
|
||||
@@ -781,6 +781,74 @@ describe("browser file content policy", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps the shared token, limit and media-type checks (Q-6.2-12 characterization)", () => {
|
||||
const policies = pngPolicies();
|
||||
const file = new File([new Uint8Array([1])], "a.png", {
|
||||
type: "image/png",
|
||||
lastModified: 1,
|
||||
});
|
||||
expect(
|
||||
new BrowserFileVault({
|
||||
policies,
|
||||
createReference: () => "file with space",
|
||||
}).captureFiles([file], pngSelectionPolicy),
|
||||
).toMatchObject({ ok: false, error: { code: "UNAVAILABLE" } });
|
||||
expect(
|
||||
new BrowserFileVault({
|
||||
policies,
|
||||
createReference: () => `file:${"x".repeat(123)}`,
|
||||
}).captureFiles([file], pngSelectionPolicy),
|
||||
).toMatchObject({ ok: true });
|
||||
expect(
|
||||
() => new BrowserFileVault({ policies, hardMaxRangeBytes: 0 }),
|
||||
).toThrow(TypeError);
|
||||
|
||||
const revoked: string[] = [];
|
||||
const registry = new ObjectUrlLeaseRegistry({
|
||||
createObjectURL: () => "",
|
||||
revokeObjectURL: (url) => revoked.push(url),
|
||||
});
|
||||
expect(() => registry.create(new Blob([new Uint8Array([1])]))).toThrow(
|
||||
"Object URL allocation failed",
|
||||
);
|
||||
expect(revoked).toEqual([]);
|
||||
expect(
|
||||
() =>
|
||||
new ObjectUrlLeaseRegistry(URL, {
|
||||
hardMaxActiveLeases: 1.5,
|
||||
hardMaxSingleLeaseBytes: 1,
|
||||
hardMaxAggregateLeaseBytes: 1,
|
||||
}),
|
||||
).toThrow(TypeError);
|
||||
|
||||
const download = (mediaType: string, maxTransferBytes = 8) =>
|
||||
new BrowserFilePolicyRegistry({
|
||||
profiles: [
|
||||
{
|
||||
reference: browserFilePolicyReference("files", "download"),
|
||||
download: {
|
||||
strategy: "BOUNDED_OBJECT_URL",
|
||||
mediaType,
|
||||
safeExtension: ".bin",
|
||||
maxTransferBytes,
|
||||
maxBufferedBytes: 8,
|
||||
integrity: "OPTIONAL",
|
||||
},
|
||||
},
|
||||
],
|
||||
hardLimits: {
|
||||
maxInspectionBytes: 64,
|
||||
maxRetainedFileBytes: 64,
|
||||
maxPreviewBytes: 64,
|
||||
maxObjectUrlBytes: 64,
|
||||
maxTransferBytes: 64,
|
||||
},
|
||||
});
|
||||
expect(() => download("application/octet-stream")).not.toThrow();
|
||||
expect(() => download("application/*")).toThrow(TypeError);
|
||||
expect(() => download("application/octet-stream", 0)).toThrow(TypeError);
|
||||
});
|
||||
|
||||
it("ends a pending native read on caller abort and on vault dispose", async () => {
|
||||
const pendingStream = () => {
|
||||
const state = { cancelled: 0 };
|
||||
|
||||
Reference in New Issue
Block a user