Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 34 additions & 9 deletions http/unstable_cache_control.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,8 +147,24 @@ const MAX_DELTA_SECONDS = 2_147_483_648; // 2^31

const DIGITS_REGEXP = /^\d+$/;

/** RFC 9110 §5.6.2 tchar; used to validate HTTP token grammar (e.g. field
* names that appear inside `no-cache` / `private` arguments). */
const TCHAR_REGEXP = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;

/** Resolve a directive argument that may be either a token or a quoted-string
* (RFC 9111 §5.2). When the value is a quoted-string, surrounding double
* quotes are stripped and quoted-pair sequences (`\\X`) are unescaped per
* RFC 9110 §5.6.4. */
function unquoteArgument(value: string): string {
const t = value.trim();
if (t.length >= 2 && t.startsWith('"') && t.endsWith('"')) {
return t.slice(1, -1).replace(/\\(.)/g, "$1");
}
return t;
}

function parseNonNegativeInt(value: string, directive: string): number {
const trimmed = value.trim();
const trimmed = unquoteArgument(value);
if (!DIGITS_REGEXP.test(trimmed)) {
throw new SyntaxError(
`Cache-Control: invalid value for ${directive}: "${value}"`,
Expand Down Expand Up @@ -183,14 +199,14 @@ function splitDirectives(value: string): string[] {
}

/** Parse a comma-separated list of HTTP field names from a directive argument.
* Strips surrounding double quotes if present and unescapes `\"` sequences.
* Returns an array of trimmed, non-empty field names. */
* Strips surrounding double quotes if present and unescapes any quoted-pair
* sequence (RFC 9110 §5.6.4). Returns an array of trimmed, non-empty field
* names. */
function parseFieldNames(value: string): string[] {
const t = value.trim();
const parsed = t.length >= 2 && t.startsWith('"') && t.endsWith('"')
? t.slice(1, -1).replace(/\\"/g, '"')
: t;
return parsed.split(",").map((s) => s.trim()).filter(Boolean);
return unquoteArgument(value)
.split(",")
.map((s) => s.trim())
.filter(Boolean);
}

/**
Expand Down Expand Up @@ -351,7 +367,7 @@ function append(
if (typeof value === "number") {
if (!Number.isInteger(value) || value < 0) {
throw new RangeError(
`Cache-Control: ${directive} must be a non-negative integer, got ${value}`,
`Cache-Control: ${directive} must be a non-negative integer: current value is ${value}`,
Comment thread
tomas-zijdemans marked this conversation as resolved.
Outdated
);
}
// Clamp to MAX_DELTA_SECONDS to match parser behavior (RFC 9111 §1.2.2).
Expand All @@ -362,6 +378,13 @@ function append(
out.push(directive);
return;
}
for (const name of value) {
if (!TCHAR_REGEXP.test(name)) {
throw new TypeError(
`Cache-Control: invalid field name in ${directive}: "${name}"`,
);
}
}
out.push(`${directive}="${value.join(", ")}"`);
}

Expand All @@ -385,6 +408,8 @@ function append(
*
* @throws {RangeError} If a numeric directive value is not a non-negative
* integer (e.g. `NaN`, `Infinity`, `-1`, or `3.14`).
* @throws {TypeError} If a field name in `noCache` or `private` is not a
* valid HTTP token (RFC 9110 §5.6.2).
*/
export function formatCacheControl(cc: CacheControl): string {
const d: CacheControl = cc;
Expand Down
42 changes: 42 additions & 0 deletions http/unstable_cache_control_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -381,3 +381,45 @@ Deno.test("formatCacheControl() accepts RequestCacheControl and ResponseCacheCon
>
>(true);
});

Deno.test("parseCacheControl() accepts quoted-string form for numeric arguments", () => {
assertEquals(parseCacheControl('max-age="60"'), { maxAge: 60 });
assertEquals(parseCacheControl('s-maxage="0"'), { sMaxage: 0 });
assertEquals(parseCacheControl('stale-while-revalidate="30"'), {
staleWhileRevalidate: 30,
});
assertEquals(parseCacheControl('max-stale="120"'), { maxStale: 120 });
});

Deno.test("parseCacheControl() rejects quoted-string with non-digit content", () => {
assertThrows(
() => parseCacheControl('max-age="abc"'),
SyntaxError,
"invalid value",
);
});

Deno.test("parseCacheControl() unescapes backslash quoted-pairs in field names", () => {
assertEquals(
parseCacheControl('no-cache="x-\\\\header"'),
{ noCache: ["x-\\header"] },
);
});

Deno.test("formatCacheControl() throws on invalid field-name characters", () => {
assertThrows(
() => formatCacheControl({ noCache: ['has"quote'] }),
TypeError,
"invalid field name",
);
assertThrows(
() => formatCacheControl({ private: ["has space"] }),
TypeError,
"invalid field name",
);
assertThrows(
() => formatCacheControl({ noCache: [""] }),
TypeError,
"invalid field name",
);
});
Loading