Support If-Match and If-Unmodified-Since preconditions
Co-authored-by: Theo Browne <[email protected]>
This commit is contained in:
1 parent
3e109a88e6
commit
8aa5ed80f5
3 files changed
+157
-17
No files matched your search
@@ -249,6 +249,12 @@ async function main() {
|
||||
if (!assetLastModified || assetLastModified.length === 0) {
|
||||
throw new Error("Smoke test failed: expected Last-Modified on built asset response.");
|
||||
}
|
||||
const parsedLastModifiedMs = Date.parse(assetLastModified);
|
||||
if (!Number.isFinite(parsedLastModifiedMs)) {
|
||||
throw new Error(
|
||||
`Smoke test failed: expected parseable last-modified date, got ${assetLastModified}.`,
|
||||
);
|
||||
}
|
||||
const assetContentLength = Number(assetResponse.headers.get("content-length") ?? "0");
|
||||
if (!Number.isFinite(assetContentLength) || assetContentLength <= 0) {
|
||||
throw new Error(
|
||||
@@ -336,6 +342,37 @@ async function main() {
|
||||
`Smoke test failed: expected If-None-Match precedence status 200, received ${precedenceAsset.status}.`,
|
||||
);
|
||||
}
|
||||
const ifMatchMismatchAsset = await fetch(assetUrl, {
|
||||
headers: {
|
||||
"If-Match": "\"definitely-different-etag\"",
|
||||
},
|
||||
});
|
||||
if (ifMatchMismatchAsset.status !== 412) {
|
||||
throw new Error(
|
||||
`Smoke test failed: expected If-Match mismatch status 412, received ${ifMatchMismatchAsset.status}.`,
|
||||
);
|
||||
}
|
||||
const staleUnmodifiedSince = new Date(parsedLastModifiedMs - 1_000).toUTCString();
|
||||
const ifUnmodifiedSinceStaleAsset = await fetch(assetUrl, {
|
||||
headers: {
|
||||
"If-Unmodified-Since": staleUnmodifiedSince,
|
||||
},
|
||||
});
|
||||
if (ifUnmodifiedSinceStaleAsset.status !== 412) {
|
||||
throw new Error(
|
||||
`Smoke test failed: expected stale If-Unmodified-Since status 412, received ${ifUnmodifiedSinceStaleAsset.status}.`,
|
||||
);
|
||||
}
|
||||
const ifUnmodifiedSinceCurrentAsset = await fetch(assetUrl, {
|
||||
headers: {
|
||||
"If-Unmodified-Since": assetLastModified,
|
||||
},
|
||||
});
|
||||
if (ifUnmodifiedSinceCurrentAsset.status !== 200) {
|
||||
throw new Error(
|
||||
`Smoke test failed: expected current If-Unmodified-Since status 200, received ${ifUnmodifiedSinceCurrentAsset.status}.`,
|
||||
);
|
||||
}
|
||||
const conditionalHeadAsset = await fetch(assetUrl, {
|
||||
method: "HEAD",
|
||||
headers: {
|
||||
@@ -407,6 +444,17 @@ async function main() {
|
||||
`Smoke test failed: expected If-Modified-Since HEAD asset status 304, received ${modifiedSinceHeadAsset.status}.`,
|
||||
);
|
||||
}
|
||||
const ifMatchMismatchHeadAsset = await fetch(assetUrl, {
|
||||
method: "HEAD",
|
||||
headers: {
|
||||
"If-Match": "\"definitely-different-etag\"",
|
||||
},
|
||||
});
|
||||
if (ifMatchMismatchHeadAsset.status !== 412) {
|
||||
throw new Error(
|
||||
`Smoke test failed: expected HEAD If-Match mismatch status 412, received ${ifMatchMismatchHeadAsset.status}.`,
|
||||
);
|
||||
}
|
||||
const rangeEnd = Math.min(15, assetContentLength - 1);
|
||||
const rangedAsset = await fetch(assetUrl, {
|
||||
headers: {
|
||||
@@ -478,12 +526,6 @@ async function main() {
|
||||
`Smoke test failed: expected If-Range(date) asset status 206, received ${ifRangeDateAsset.status}.`,
|
||||
);
|
||||
}
|
||||
const parsedLastModifiedMs = Date.parse(assetLastModified);
|
||||
if (!Number.isFinite(parsedLastModifiedMs)) {
|
||||
throw new Error(
|
||||
`Smoke test failed: expected parseable last-modified date, got ${assetLastModified}.`,
|
||||
);
|
||||
}
|
||||
const staleIfRangeDate = new Date(parsedLastModifiedMs - 1_000).toUTCString();
|
||||
const ifRangeStaleDateAsset = await fetch(assetUrl, {
|
||||
headers: {
|
||||
|
||||
@@ -5,9 +5,11 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
formatStartupError,
|
||||
ifMatchSatisfied,
|
||||
ifModifiedSinceSatisfied,
|
||||
ifNoneMatchSatisfied,
|
||||
ifRangeSatisfied,
|
||||
ifUnmodifiedSinceSatisfied,
|
||||
parseByteRangeHeader,
|
||||
parseCliOptions,
|
||||
readCliVersion,
|
||||
@@ -975,6 +977,26 @@ describe("ifNoneMatchSatisfied", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("ifMatchSatisfied", () => {
|
||||
it("defaults to true when header is missing", () => {
|
||||
expect(ifMatchSatisfied(undefined, "\"abc\"")).toBe(true);
|
||||
});
|
||||
|
||||
it("supports wildcard and exact strong matches", () => {
|
||||
expect(ifMatchSatisfied("*", "\"abc\"")).toBe(true);
|
||||
expect(ifMatchSatisfied("\"abc\"", "\"abc\"")).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects weak validators and mismatches", () => {
|
||||
expect(ifMatchSatisfied("W/\"abc\"", "\"abc\"")).toBe(false);
|
||||
expect(ifMatchSatisfied("\"xyz\"", "\"abc\"")).toBe(false);
|
||||
});
|
||||
|
||||
it("supports array-valued headers", () => {
|
||||
expect(ifMatchSatisfied(["\"foo\"", "\"abc\""], "\"abc\"")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ifModifiedSinceSatisfied", () => {
|
||||
it("returns false for missing or invalid dates", () => {
|
||||
expect(ifModifiedSinceSatisfied(undefined, Date.now())).toBe(false);
|
||||
@@ -997,6 +1019,23 @@ describe("ifModifiedSinceSatisfied", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("ifUnmodifiedSinceSatisfied", () => {
|
||||
it("defaults to true for missing and invalid values", () => {
|
||||
expect(ifUnmodifiedSinceSatisfied(undefined, Date.now())).toBe(true);
|
||||
expect(ifUnmodifiedSinceSatisfied("not-a-date", Date.now())).toBe(true);
|
||||
});
|
||||
|
||||
it("returns true when resource has not changed since timestamp", () => {
|
||||
const modifiedAt = Date.parse("2026-01-01T12:00:00.100Z");
|
||||
expect(ifUnmodifiedSinceSatisfied("Thu, 01 Jan 2026 12:00:00 GMT", modifiedAt)).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false when resource changed after timestamp", () => {
|
||||
const modifiedAt = Date.parse("2026-01-01T12:00:01.000Z");
|
||||
expect(ifUnmodifiedSinceSatisfied("Thu, 01 Jan 2026 12:00:00 GMT", modifiedAt)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ifRangeSatisfied", () => {
|
||||
it("returns true when header is missing", () => {
|
||||
expect(ifRangeSatisfied(undefined, "\"abc\"", Date.now())).toBe(true);
|
||||
|
||||
+70
-11
@@ -521,21 +521,23 @@ function normalizeWeakEtag(etag: string): string {
|
||||
return trimmed.startsWith("W/") ? trimmed.slice(2).trim() : trimmed;
|
||||
}
|
||||
|
||||
function normalizeEtagHeaderValue(value: string | string[] | undefined): string[] {
|
||||
if (!value) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const rawHeaderValue = Array.isArray(value) ? value.join(",") : value;
|
||||
return rawHeaderValue
|
||||
.split(",")
|
||||
.map((token) => token.trim())
|
||||
.filter((token) => token.length > 0);
|
||||
}
|
||||
|
||||
export function ifNoneMatchSatisfied(
|
||||
ifNoneMatchHeader: string | string[] | undefined,
|
||||
etag: string,
|
||||
): boolean {
|
||||
if (!ifNoneMatchHeader) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const rawHeaderValue = Array.isArray(ifNoneMatchHeader)
|
||||
? ifNoneMatchHeader.join(",")
|
||||
: ifNoneMatchHeader;
|
||||
const candidates = rawHeaderValue
|
||||
.split(",")
|
||||
.map((token) => token.trim())
|
||||
.filter((token) => token.length > 0);
|
||||
const candidates = normalizeEtagHeaderValue(ifNoneMatchHeader);
|
||||
if (candidates.length === 0) {
|
||||
return false;
|
||||
}
|
||||
@@ -548,6 +550,31 @@ export function ifNoneMatchSatisfied(
|
||||
return candidates.some((candidate) => normalizeWeakEtag(candidate) === normalizedEtag);
|
||||
}
|
||||
|
||||
export function ifMatchSatisfied(ifMatchHeader: string | string[] | undefined, etag: string): boolean {
|
||||
const candidates = normalizeEtagHeaderValue(ifMatchHeader);
|
||||
if (candidates.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (candidates.includes("*")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const normalizedCurrentTag = etag.trim();
|
||||
if (normalizedCurrentTag.startsWith("W/")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return candidates.some((candidate) => {
|
||||
const normalizedCandidate = candidate.trim();
|
||||
if (normalizedCandidate.startsWith("W/")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return normalizedCandidate === normalizedCurrentTag;
|
||||
});
|
||||
}
|
||||
|
||||
export function ifModifiedSinceSatisfied(
|
||||
ifModifiedSinceHeader: string | string[] | undefined,
|
||||
modifiedAtMs: number,
|
||||
@@ -571,6 +598,29 @@ export function ifModifiedSinceSatisfied(
|
||||
return Math.floor(modifiedAtMs / 1_000) <= Math.floor(parsedTimestamp / 1_000);
|
||||
}
|
||||
|
||||
export function ifUnmodifiedSinceSatisfied(
|
||||
ifUnmodifiedSinceHeader: string | string[] | undefined,
|
||||
modifiedAtMs: number,
|
||||
): boolean {
|
||||
if (!ifUnmodifiedSinceHeader) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const rawHeaderValue = Array.isArray(ifUnmodifiedSinceHeader)
|
||||
? ifUnmodifiedSinceHeader[0]
|
||||
: ifUnmodifiedSinceHeader;
|
||||
if (!rawHeaderValue) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const parsedTimestamp = Date.parse(rawHeaderValue);
|
||||
if (!Number.isFinite(parsedTimestamp)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return Math.floor(modifiedAtMs / 1_000) <= Math.floor(parsedTimestamp / 1_000);
|
||||
}
|
||||
|
||||
export function ifRangeSatisfied(
|
||||
ifRangeHeader: string | string[] | undefined,
|
||||
etag: string,
|
||||
@@ -842,11 +892,20 @@ function startStaticWebServer(distRoot: string, port: number) {
|
||||
|
||||
const etag = staticEtagFor(stats);
|
||||
const lastModified = stats.mtime.toUTCString();
|
||||
const hasIfMatchHeader = request.headers["if-match"] !== undefined;
|
||||
const ifMatchMatches = ifMatchSatisfied(request.headers["if-match"], etag);
|
||||
const ifUnmodifiedSinceMatches = hasIfMatchHeader
|
||||
? true
|
||||
: ifUnmodifiedSinceSatisfied(request.headers["if-unmodified-since"], stats.mtimeMs);
|
||||
const hasIfNoneMatchHeader = request.headers["if-none-match"] !== undefined;
|
||||
const ifNoneMatchMatches = ifNoneMatchSatisfied(request.headers["if-none-match"], etag);
|
||||
const ifModifiedSinceMatches = hasIfNoneMatchHeader
|
||||
? false
|
||||
: ifModifiedSinceSatisfied(request.headers["if-modified-since"], stats.mtimeMs);
|
||||
if (!ifMatchMatches || !ifUnmodifiedSinceMatches) {
|
||||
respondText(412, "Precondition Failed");
|
||||
return;
|
||||
}
|
||||
const shouldReturnNotModified = ifNoneMatchMatches || ifModifiedSinceMatches;
|
||||
|
||||
if (shouldReturnNotModified) {
|
||||
|
||||
Reference in new issue
Block a user