nuxt-skew-protection 1.5.0 → 1.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/module.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "nuxt": ">=4.0.0"
5
5
  },
6
6
  "configKey": "skewProtection",
7
- "version": "1.5.0",
7
+ "version": "1.5.2",
8
8
  "builder": {
9
9
  "@nuxt/module-builder": "1.0.3",
10
10
  "unbuild": "3.6.1"
package/dist/module.mjs CHANGED
@@ -3,6 +3,7 @@ import { useLogger, useNuxt, defineNuxtModule, createResolver, hasNuxtModule, ad
3
3
  import { colors } from 'consola/utils';
4
4
  import { setupNitroRuntimeCompatibility, resolveNitroPreset, renderNitroTypeAugmentations, isNuxtGenerate } from 'nuxtseo-shared/kit';
5
5
  import { readPackageJSON } from 'pkg-types';
6
+ import { cachingRouteRules, skewCacheCeilingSeconds, htmlCacheCapability } from '../dist/runtime/server/utils/html-cache-policy.js';
6
7
  import { join } from 'node:path';
7
8
  import { spawn } from 'node:child_process';
8
9
  import { mkdtemp, writeFile, rm } from 'node:fs/promises';
@@ -10,7 +11,6 @@ import { tmpdir } from 'node:os';
10
11
  import { defineDriver, createStorage } from 'unstorage';
11
12
  import { isSkewAdapter } from '../dist/runtime/adapters/index.js';
12
13
  import '../dist/runtime/adapters/types.js';
13
- import { createHash } from 'node:crypto';
14
14
  import { join as join$1, dirname } from 'pathe';
15
15
 
16
16
  const logger = useLogger("nuxt-skew-protection");
@@ -393,12 +393,6 @@ function withCloudflareBuildAssetRouting(current, buildAssetsDir) {
393
393
 
394
394
  const RE_ENOTFOUND = /ENOTFOUND\s+(\S+)/;
395
395
  const RE_GETADDRINFO = /getaddrinfo\s+\S+\s+(\S+)/;
396
- const RE_SIZE_PROP = /(['"]?)size\1\s*:\s*\d+/;
397
- const RE_SIZE_PREFIX = /^(['"]?)size\1\s*:\s*/;
398
- const RE_ETAG_PROP = /(['"]?)etag\1\s*:\s*(['"])(?:[^\\]|\\.)*?\2/;
399
- const RE_ETAG_KEY_PREFIX = /^(['"]?)etag\1\s*:\s*/;
400
- const RE_ETAG_QUOTE = /:\s*(['"])/;
401
- const RE_ESCAPE_DOUBLE_QUOTE = /"/g;
402
396
  function formatStorageError(error, operation) {
403
397
  const cause = error instanceof Error ? error.cause : void 0;
404
398
  const message = error instanceof Error ? error.message : String(error);
@@ -513,7 +507,6 @@ function createAssetManager(options) {
513
507
  const retentionDays = options.retentionDays || 7;
514
508
  const maxNumberOfVersions = options.maxNumberOfVersions || 20;
515
509
  const buildAssetsDir = (options.buildAssetsDir || "/_nuxt/").replace(/^\/+|\/+$/g, "");
516
- const buildAssetsPath = `/${buildAssetsDir}`;
517
510
  const persistAssets = options.persistAssets !== false;
518
511
  async function getAssetsFromBuild(publicDir) {
519
512
  const startTime = Date.now();
@@ -813,7 +806,7 @@ function createAssetManager(options) {
813
806
  }
814
807
  logger.debug(`restoreOldAssetsToPublic: total ${formatDuration(Date.now() - startTime)}`);
815
808
  }
816
- async function augmentBuildMetadata(buildId, publicDir, serverDir) {
809
+ async function augmentBuildMetadata(buildId, publicDir) {
817
810
  const manifest = await getVersionManifest(storage);
818
811
  const latestPath = join$1(publicDir, buildAssetsDir, "builds", "latest.json");
819
812
  let newLatestContent;
@@ -852,66 +845,6 @@ function createAssetManager(options) {
852
845
  const message = error instanceof Error ? error.message : String(error);
853
846
  throw new Error(`Failed to augment builds/meta/${buildId}.json: ${message}`);
854
847
  }
855
- if (serverDir && newLatestContent) {
856
- await patchNitroManifest(serverDir, `${buildAssetsPath}/builds/latest.json`, newLatestContent);
857
- }
858
- }
859
- async function patchNitroManifest(serverDir, assetPath, newContent) {
860
- const nitroPath = join$1(serverDir, "chunks", "nitro", "nitro.mjs");
861
- let nitro = await promises.readFile(nitroPath, "utf-8").catch(() => {
862
- return null;
863
- });
864
- if (!nitro)
865
- return;
866
- const assetIdx = nitro.indexOf(`"${assetPath}":`);
867
- if (assetIdx === -1)
868
- return;
869
- const size = Buffer.byteLength(newContent, "utf-8");
870
- const hash = createHash("sha1").update(newContent).digest("base64").substring(0, 27);
871
- const newEtag = `"${size.toString(16)}-${hash}"`;
872
- const start = nitro.indexOf("{", assetIdx);
873
- if (start === -1)
874
- return;
875
- let depth = 0;
876
- let stringChar = null;
877
- let end = -1;
878
- for (let i = start; i < nitro.length; i++) {
879
- const char = nitro[i];
880
- if (stringChar) {
881
- if (char === "\\")
882
- i++;
883
- else if (char === stringChar)
884
- stringChar = null;
885
- } else {
886
- if (char === '"' || char === "'") {
887
- stringChar = char;
888
- } else if (char === "{") {
889
- depth++;
890
- } else if (char === "}") {
891
- depth--;
892
- if (depth === 0) {
893
- end = i;
894
- break;
895
- }
896
- }
897
- }
898
- }
899
- if (end === -1)
900
- return;
901
- let entryStr = nitro.substring(start, end + 1);
902
- entryStr = entryStr.replace(RE_SIZE_PROP, (match) => {
903
- const prefix = match.match(RE_SIZE_PREFIX)?.[0] || "size:";
904
- return `${prefix}${size}`;
905
- });
906
- entryStr = entryStr.replace(RE_ETAG_PROP, (match) => {
907
- const keyMatch = match.match(RE_ETAG_KEY_PREFIX);
908
- const prefix = keyMatch?.[0] || "etag:";
909
- const quoteChar = match.match(RE_ETAG_QUOTE)?.[1] || '"';
910
- const escapedEtag = quoteChar === "'" ? newEtag : newEtag.replace(RE_ESCAPE_DOUBLE_QUOTE, '\\"');
911
- return `${prefix}${quoteChar}${escapedEtag}${quoteChar}`;
912
- });
913
- nitro = nitro.substring(0, start) + entryStr + nitro.substring(end + 1);
914
- await promises.writeFile(nitroPath, nitro, "utf-8");
915
848
  }
916
849
  return {
917
850
  getAssetsFromBuild,
@@ -1182,6 +1115,50 @@ export {}
1182
1115
  const { setupDevToolsUI } = await import('./chunks/devtools.mjs');
1183
1116
  setupDevToolsUI(resolver.resolve, nuxt);
1184
1117
  }
1118
+ {
1119
+ const onVercel = resolveNitroPreset(nuxt.options.nitro)?.includes("vercel") || process.env.VERCEL_SKEW_PROTECTION_ENABLED === "1";
1120
+ const publicAssetBaseURLs = (nuxt.options.nitro.publicAssets ?? []).flatMap((asset) => asset && typeof asset.baseURL === "string" ? [asset.baseURL] : []);
1121
+ const caching = cachingRouteRules(nuxt.options.routeRules ?? {}, publicAssetBaseURLs);
1122
+ if (onVercel) {
1123
+ if (caching.length) {
1124
+ logger.warn(`${caching.length} route rule${caching.length > 1 ? "s" : ""} ask a shared cache to store HTML. That cannot work on Vercel. Vercel skew protection sets a \`__vdpl\` cookie on every document. Shared caches skip any response that sets a cookie.`);
1125
+ }
1126
+ } else {
1127
+ nuxt.options.nitro = nuxt.options.nitro || {};
1128
+ nuxt.options.nitro.plugins = nuxt.options.nitro.plugins || [];
1129
+ nuxt.options.nitro.plugins.push(resolver.resolve("./runtime/server/plugins/html-cache-headers"));
1130
+ if (caching.length) {
1131
+ const ceiling = skewCacheCeilingSeconds(options.retentionDays || 7);
1132
+ for (const { route, seconds, source, fromMaxAgeAlone } of caching) {
1133
+ if (seconds > ceiling)
1134
+ logger.warn(`routeRules['${route}'] (${source}) caches a document for ${seconds}s. Retention only keeps a build for ${ceiling}s. The cached document will outlive its chunks. Lower the window to ${ceiling}s or less.`);
1135
+ if (fromMaxAgeAlone)
1136
+ logger.warn(`routeRules['${route}'] caches documents with \`max-age\` and no \`s-maxage\`. The version cookie is dropped there, so \`isClientOutdated\` falls back to the build id. Use \`s-maxage\` for CDN caching, or \`private\` if you meant browser caching only.`);
1137
+ }
1138
+ }
1139
+ {
1140
+ const capability = htmlCacheCapability({
1141
+ retentionDays: options.retentionDays || 7,
1142
+ maxNumberOfVersions: options.maxNumberOfVersions ?? 10,
1143
+ // No preset gate. Retained chunks are restored before nitro seals
1144
+ // its public asset manifest (#48), so they resolve wherever the
1145
+ // build is served from. `bundleAssets: false` or no storage means
1146
+ // nothing was stored, and a retained-chunk promise would be a lie
1147
+ // however long the window.
1148
+ assetRecovery: Boolean(options.bundleAssets) && Boolean(options.storage)
1149
+ });
1150
+ if (capability) {
1151
+ const published = nuxt.options.runtimeConfig.htmlCacheCapabilities;
1152
+ nuxt.options.runtimeConfig.htmlCacheCapabilities = [
1153
+ ...Array.isArray(published) ? published : [],
1154
+ capability
1155
+ ];
1156
+ } else if (caching.length) {
1157
+ logger.warn("Route rules ask a shared cache to store HTML. This build keeps no previous assets. A cached document will 404 its chunks after the next deploy. Set `bundleAssets` and `storage` to keep them.");
1158
+ }
1159
+ }
1160
+ }
1161
+ }
1185
1162
  if (!nuxt.options.dev) {
1186
1163
  const isCloudflareRuntime = nitroPreset?.includes("cloudflare");
1187
1164
  const isVercel = nitroPreset?.includes("vercel") || process.env.VERCEL_SKEW_PROTECTION_ENABLED === "1";
@@ -1281,56 +1258,55 @@ export {}
1281
1258
  // Service workers should not be cached
1282
1259
  });
1283
1260
  if (options.storage) {
1284
- nuxt.hook("nitro:init", (nitro) => {
1285
- const buildId = nuxt.options.runtimeConfig.app.buildId ||= nuxt.options.buildId;
1286
- let assetManager;
1287
- nitro.hooks.hook("compiled", async () => {
1288
- const publicDir = nitro.options.output.publicDir;
1289
- assetManager = createAssetManager({
1290
- ...options,
1291
- buildAssetsDir: nuxt.options.app.buildAssetsDir,
1292
- persistAssets: options.bundleAssets !== false,
1293
- driver: await resolveBuildTimeDriver(options.storage)
1261
+ const buildId = nuxt.options.runtimeConfig.app.buildId ||= nuxt.options.buildId;
1262
+ let assetManager;
1263
+ nuxt.hook("nitro:build:public-assets", async (nitro) => {
1264
+ const publicDir = nitro.options.output.publicDir;
1265
+ assetManager = createAssetManager({
1266
+ ...options,
1267
+ buildAssetsDir: nuxt.options.app.buildAssetsDir,
1268
+ persistAssets: options.bundleAssets !== false,
1269
+ driver: await resolveBuildTimeDriver(options.storage)
1270
+ });
1271
+ const assets = await assetManager.getAssetsFromBuild(publicDir);
1272
+ const { isExistingVersion } = await assetManager.updateVersionsManifest(buildId, assets);
1273
+ if (options.bundleAssets) {
1274
+ const manifest = await assetManager.getManifest();
1275
+ const totalReleases = Object.keys(manifest.versions).length;
1276
+ const timestamps = Object.values(manifest.versions).map((v) => new Date(v.timestamp).getTime());
1277
+ const oldestTimestamp = Math.min(...timestamps);
1278
+ const daysSince = Math.floor((Date.now() - oldestTimestamp) / (1e3 * 60 * 60 * 24));
1279
+ const timeInfo = daysSince > 0 ? `${daysSince} day${daysSince > 1 ? "s" : ""} ago` : "today";
1280
+ const storageInfo = options.storage.base ? `${colors.green(options.storage.driver)} ${colors.gray(`(${options.storage.base})`)}` : colors.green(options.storage.driver);
1281
+ if (totalReleases === 1) {
1282
+ logger.warn(`No previous versions found in storage. This is either the first deployment or storage is misconfigured. https://nuxtseo.com/docs/skew-protection/storage-configuration`);
1283
+ } else {
1284
+ logger.log(`Storing ${colors.yellow(assets.length.toString())} assets for ${colors.cyan(buildId.slice(0, 8))} (${totalReleases} releases, oldest from ${timeInfo}) [${storageInfo}]`);
1285
+ }
1286
+ await assetManager.storeAssetsInStorage(buildId, publicDir, assets).catch((error) => {
1287
+ logger.error(`Failed to store assets:`, error instanceof Error ? error.message : error);
1288
+ throw error;
1294
1289
  });
1295
- const assets = await assetManager.getAssetsFromBuild(publicDir);
1296
- const { isExistingVersion } = await assetManager.updateVersionsManifest(buildId, assets);
1297
- if (options.bundleAssets) {
1298
- const manifest = await assetManager.getManifest();
1299
- const totalReleases = Object.keys(manifest.versions).length;
1300
- const timestamps = Object.values(manifest.versions).map((v) => new Date(v.timestamp).getTime());
1301
- const oldestTimestamp = Math.min(...timestamps);
1302
- const daysSince = Math.floor((Date.now() - oldestTimestamp) / (1e3 * 60 * 60 * 24));
1303
- const timeInfo = daysSince > 0 ? `${daysSince} day${daysSince > 1 ? "s" : ""} ago` : "today";
1304
- const storageInfo = options.storage.base ? `${colors.green(options.storage.driver)} ${colors.gray(`(${options.storage.base})`)}` : colors.green(options.storage.driver);
1305
- if (totalReleases === 1) {
1306
- logger.warn(`No previous versions found in storage. This is either the first deployment or storage is misconfigured. https://nuxtseo.com/docs/skew-protection/storage-configuration`);
1307
- } else {
1308
- logger.log(`Storing ${colors.yellow(assets.length.toString())} assets for ${colors.cyan(buildId.slice(0, 8))} (${totalReleases} releases, oldest from ${timeInfo}) [${storageInfo}]`);
1309
- }
1310
- await assetManager.storeAssetsInStorage(buildId, publicDir, assets).catch((error) => {
1311
- logger.error(`Failed to store assets:`, error instanceof Error ? error.message : error);
1312
- throw error;
1313
- });
1314
- const existingVersions = await assetManager.listExistingVersions();
1315
- const versionCount = existingVersions.filter((v) => v.id !== buildId).length;
1316
- logger.success(`Successfully stored ${assets.length} assets for latest release`);
1317
- if (versionCount > 0) {
1318
- const updatedManifest = await assetManager.getManifest();
1319
- let totalAssets = 0;
1320
- const versionSizes = [];
1321
- for (const [vId, vData] of Object.entries(updatedManifest.versions)) {
1322
- if (vId !== buildId) {
1323
- totalAssets += vData.assets.length;
1324
- versionSizes.push(`${vId.slice(0, 8)}:${vData.assets.length}`);
1325
- }
1290
+ const existingVersions = await assetManager.listExistingVersions();
1291
+ const versionCount = existingVersions.filter((v) => v.id !== buildId).length;
1292
+ logger.success(`Successfully stored ${assets.length} assets for latest release`);
1293
+ if (versionCount > 0) {
1294
+ const updatedManifest = await assetManager.getManifest();
1295
+ let totalAssets = 0;
1296
+ const versionSizes = [];
1297
+ for (const [vId, vData] of Object.entries(updatedManifest.versions)) {
1298
+ if (vId !== buildId) {
1299
+ totalAssets += vData.assets.length;
1300
+ versionSizes.push(`${vId.slice(0, 8)}:${vData.assets.length}`);
1326
1301
  }
1327
- logger.log(`Restoring build files from ${versionCount} release${versionCount > 1 ? "s" : ""} (${totalAssets} assets) [${versionSizes.join(", ")}]...`);
1328
1302
  }
1329
- await assetManager.restoreOldAssetsToPublic(buildId, publicDir, assets, isExistingVersion);
1303
+ logger.log(`Restoring build files from ${versionCount} release${versionCount > 1 ? "s" : ""} (${totalAssets} assets) [${versionSizes.join(", ")}]...`);
1330
1304
  }
1331
- const serverDir = nitro.options.output.serverDir;
1332
- await assetManager.augmentBuildMetadata(buildId, publicDir, serverDir);
1333
- });
1305
+ await assetManager.restoreOldAssetsToPublic(buildId, publicDir, assets, isExistingVersion);
1306
+ }
1307
+ await assetManager.augmentBuildMetadata(buildId, publicDir);
1308
+ });
1309
+ nuxt.hook("nitro:init", (nitro) => {
1334
1310
  nitro.hooks.hook("close", async () => {
1335
1311
  if (assetManager) {
1336
1312
  await assetManager.cleanupExpiredVersions().catch((error) => {
@@ -41,7 +41,7 @@ export default defineNuxtPlugin({
41
41
  return;
42
42
  const channel = new BroadcastChannel(CHANNEL_NAME);
43
43
  let receivedFromChannel = false;
44
- nuxtApp.hooks.hook("app:manifest:update", (manifest) => {
44
+ const stopBroadcasting = nuxtApp.hooks.hook("app:manifest:update", (manifest) => {
45
45
  if (receivedFromChannel) {
46
46
  receivedFromChannel = false;
47
47
  return;
@@ -57,6 +57,7 @@ export default defineNuxtPlugin({
57
57
  }
58
58
  };
59
59
  nuxtApp.hook("app:error", () => {
60
+ stopBroadcasting();
60
61
  channel.close();
61
62
  });
62
63
  }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Drops the version cookie from documents a shared cache was asked to keep.
3
+ *
4
+ * Runs on `beforeResponse` rather than as middleware, because the answer needs
5
+ * the response: the status decides whether the document is worth keeping, and
6
+ * the app's cache policy is the only signal that it wants one kept.
7
+ * Reading it here also means it does not matter how the app set it, route rule
8
+ * or plugin or handler.
9
+ *
10
+ * A route rule is caught at build time and named there. A cache header set by
11
+ * a handler or a nitro plugin is not, and gets no warning at all. There is
12
+ * nowhere to put one: the cookie middleware only registers outside dev
13
+ * (`module.ts`), so nothing is ever dropped while `nuxt dev` runs, and a
14
+ * per-route warning in production logs is noise for a header the author wrote
15
+ * on purpose.
16
+ */
17
+ declare const _default: any;
18
+ export default _default;
@@ -0,0 +1,37 @@
1
+ import { appendResponseHeader, getHeader, getResponseHeader, getResponseStatus, removeResponseHeader } from "#nuxtseo/h3";
2
+ import { defineNitroPlugin } from "#nuxtseo/nitro";
3
+ import { getSkewProtectionCookieName } from "../imports/cookie.js";
4
+ import {
5
+ htmlCacheRequestFromEvent,
6
+ readSetCookies,
7
+ resolveHtmlCachePolicy,
8
+ sharedCacheControlHeader,
9
+ withoutCookie
10
+ } from "../utils/html-cache-policy.js";
11
+ export default defineNitroPlugin((nitroApp) => {
12
+ nitroApp.hooks.hook("beforeResponse", (event) => {
13
+ const cacheControl = sharedCacheControlHeader((name2) => getResponseHeader(event, name2));
14
+ const decision = resolveHtmlCachePolicy(
15
+ htmlCacheRequestFromEvent(event, getHeader),
16
+ {
17
+ status: getResponseStatus(event),
18
+ cacheControl: cacheControl?.value
19
+ }
20
+ );
21
+ if (decision._tag !== "shared-cacheable")
22
+ return;
23
+ const name = getSkewProtectionCookieName();
24
+ if (!name)
25
+ return;
26
+ const cookies = readSetCookies(
27
+ event,
28
+ getResponseHeader(event, "set-cookie")
29
+ );
30
+ const remaining = withoutCookie(cookies, name);
31
+ if (remaining.length === cookies.length)
32
+ return;
33
+ removeResponseHeader(event, "set-cookie");
34
+ for (const cookie of remaining)
35
+ appendResponseHeader(event, "set-cookie", cookie);
36
+ });
37
+ });
@@ -0,0 +1,220 @@
1
+ /**
2
+ * Makes an app's own HTML caching survive skew protection.
3
+ *
4
+ * Freshness is not this module's decision. How often a page changes is the
5
+ * app's knowledge, it differs per route, and Nuxt already has a way to say it:
6
+ *
7
+ * ```ts
8
+ * routeRules: {
9
+ * '/gh/**': { headers: { 'cache-control': 'public, s-maxage=300' } },
10
+ * '/blog/**': { headers: { 'cache-control': 'public, s-maxage=3600' } },
11
+ * }
12
+ * ```
13
+ *
14
+ * What this module knows is different and singular: how long a document may
15
+ * outlive the build that rendered it, which falls out of `retentionDays` and
16
+ * `maxNumberOfVersions`. So it contributes two things and invents no config of
17
+ * its own.
18
+ *
19
+ * First, it gets out of the way. `set-skew-protection-cookie` puts `__nkpv` on
20
+ * every document, and shared caches will not store a response carrying
21
+ * Set-Cookie, so the rule above silently does nothing today. The version cookie
22
+ * is dropped from exactly the documents a shared cache was asked to keep.
23
+ *
24
+ * Second, it states the bound. Any route whose declared window exceeds what
25
+ * retention can promise is named at build time, because a document that
26
+ * outlives its chunks is the failure this module exists to prevent.
27
+ *
28
+ * There is no option to turn this on. Writing the route rule is the opt-in, and
29
+ * a flag would only mean the rule keeps silently doing nothing until the author
30
+ * finds a second thing to write. What the response asks for is the whole input,
31
+ * so a route that says nothing about caching is never touched.
32
+ */
33
+ export type HtmlCacheSkipReason = 'not-cacheable-method' | 'not-document' | 'request-has-cookie' | 'request-is-authenticated' | 'not-ok-status' | 'no-shared-cache-directive';
34
+ export type HtmlCacheDecision = {
35
+ _tag: 'shared-cacheable';
36
+ seconds: number;
37
+ } | {
38
+ _tag: 'skipped';
39
+ reason: HtmlCacheSkipReason;
40
+ };
41
+ export interface HtmlCacheRequest {
42
+ method: string;
43
+ secFetchDest: string | undefined;
44
+ accept: string | undefined;
45
+ cookie: string | undefined;
46
+ /** Any credential that personalises a document without being a cookie. */
47
+ authorization: string | undefined;
48
+ }
49
+ /**
50
+ * How long a shared cache may hold this response, in seconds.
51
+ *
52
+ * Returns null when the app did not ask for shared caching. `private` and
53
+ * `no-store` are refusals. `s-maxage` beats `max-age` because it is the one
54
+ * addressed to shared caches, which is what a stale document is served from.
55
+ */
56
+ export declare function sharedCacheSeconds(cacheControl: unknown): number | null;
57
+ /**
58
+ * Whether a shared-cache window came only from `max-age`.
59
+ *
60
+ * `s-maxage` is read by shared caches and ignored by browsers, so writing it is
61
+ * proof the author meant a CDN. `max-age` is also how you say "browser, hold
62
+ * this", and nothing in the header separates that intent from CDN intent. The
63
+ * response is storable by a shared cache either way, so this does not change
64
+ * what the policy decides. It exists so the build can name the routes where the
65
+ * author may not have meant it.
66
+ */
67
+ export declare function sharedWindowFromMaxAgeAlone(cacheControl: unknown): boolean;
68
+ /**
69
+ * Whether this response is one a shared cache was asked to keep.
70
+ *
71
+ * The app's `cache-control` is the whole input. However it got there, route
72
+ * rules, a nitro plugin, or a handler, the answer is the same, so an app with
73
+ * its own cache layer needs no special case.
74
+ */
75
+ export declare function resolveHtmlCachePolicy(request: HtmlCacheRequest, response: {
76
+ status: number;
77
+ cacheControl: unknown;
78
+ }): HtmlCacheDecision;
79
+ /**
80
+ * The same Set-Cookie header with one cookie removed.
81
+ *
82
+ * Only the version cookie goes. An app cookie set during render is not ours to
83
+ * drop, and a response still carrying one simply will not be stored, which is
84
+ * the correct outcome.
85
+ */
86
+ export declare function withoutCookie(setCookie: string | string[] | undefined, name: string): string[];
87
+ /**
88
+ * The longest a document may safely outlive the build that rendered it.
89
+ *
90
+ * This is the number to clamp a route rule against:
91
+ *
92
+ * ```ts
93
+ * const sMaxAge = Math.min(300, skewCacheCeilingSeconds(retentionDays))
94
+ * ```
95
+ *
96
+ * `retentionDays` is the only bound expressible without knowing the deploy
97
+ * rate. `maxNumberOfVersions` is the tighter one in practice and cannot be
98
+ * checked here, which is what the build-time guidance says out loud.
99
+ */
100
+ export declare function skewCacheCeilingSeconds(retentionDays: number): number;
101
+ /**
102
+ * A route rule as far as this check is concerned.
103
+ *
104
+ * Nitro accepts several spellings of "cache this", and they do not all end up
105
+ * in `headers`. `swr` and `isr` are normalised into `cache` during nitro's own
106
+ * config pass and only become a `cache-control` header at request time, so a
107
+ * check that reads `headers` alone sees nothing and stays silent on exactly the
108
+ * rules most likely to outlive retention: `swr: 31536000` is a year.
109
+ */
110
+ export interface InspectableRouteRule {
111
+ headers?: Record<string, string>;
112
+ cache?: unknown;
113
+ swr?: boolean | number;
114
+ isr?: unknown;
115
+ }
116
+ export interface OverlongRoute {
117
+ route: string;
118
+ seconds: number;
119
+ /** Which spelling declared it, so the warning names the line to edit. */
120
+ source: 'cache-control' | 'cache' | 'swr' | 'isr';
121
+ /** The window came from `max-age` alone, so CDN intent is a guess. */
122
+ fromMaxAgeAlone: boolean;
123
+ }
124
+ declare const SHARED_CACHE_CONTROL_HEADERS: readonly ["cloudflare-cdn-cache-control", "cdn-cache-control", "cache-control"];
125
+ interface SharedCacheControlHeader {
126
+ name: typeof SHARED_CACHE_CONTROL_HEADERS[number];
127
+ value: unknown;
128
+ }
129
+ /** The highest-precedence header that states a shared-cache policy. */
130
+ export declare function sharedCacheControlHeader(getHeader: (name: string) => unknown): SharedCacheControlHeader | null;
131
+ /**
132
+ * Route rules that ask a shared cache to keep a document.
133
+ *
134
+ * Reads the app's own `routeRules` rather than a second copy of them. Public
135
+ * asset prefixes are excluded because their cached responses are not HTML.
136
+ * Empty means the app never asked for shared HTML caching in its config.
137
+ */
138
+ export declare function cachingRouteRules(routeRules: Record<string, InspectableRouteRule | undefined>, publicAssetBaseURLs?: readonly string[]): OverlongRoute[];
139
+ /** Route rules whose declared window outlives the retained builds. */
140
+ export declare function overlongRouteRules(routeRules: Record<string, InspectableRouteRule | undefined>, ceilingSeconds: number, publicAssetBaseURLs?: readonly string[]): OverlongRoute[];
141
+ /**
142
+ * Reads the request fields the policy needs off an H3 event.
143
+ *
144
+ * Takes the header getter rather than importing one, so this module stays free
145
+ * of a runtime dependency and the policy is testable as plain data.
146
+ */
147
+ export declare function htmlCacheRequestFromEvent(event: {
148
+ method?: string;
149
+ node?: {
150
+ req?: {
151
+ method?: string;
152
+ };
153
+ };
154
+ }, getHeader: (event: never, name: string) => string | undefined): HtmlCacheRequest;
155
+ /**
156
+ * The response's `Set-Cookie` entries, one per cookie, across h3 majors.
157
+ *
158
+ * This cannot go through `getResponseHeader`. On h3 v2 the response headers are
159
+ * a `Headers` instance, and `Headers.get('set-cookie')` returns every cookie
160
+ * joined with `", "` as one string. Filtering that string treats two cookies as
161
+ * one value: measured on h3 2.0.1, a `__nkpv` set before an app's `session`
162
+ * cookie produced a single joined value beginning `__nkpv=`, so a prefix filter
163
+ * dropped both and deleted the app's cookie. `getSetCookie()` is the only
164
+ * accessor that separates them, and it exists solely on `Headers`.
165
+ *
166
+ * h3 v1 appends each cookie as its own header, so the array comes back from
167
+ * `getResponseHeader` directly. Feature detection rather than a version check,
168
+ * because the shape is what matters.
169
+ */
170
+ export declare function readSetCookies(event: {
171
+ res?: {
172
+ headers?: {
173
+ getSetCookie?: () => string[];
174
+ };
175
+ };
176
+ }, fallback: string | string[] | number | undefined): string[];
177
+ /**
178
+ * What this module can promise another module about cached documents.
179
+ *
180
+ * Duplicated verbatim in `@harlan-zw/nuxt-cloudflare`, which forces
181
+ * `private, no-store` on HTML because a cached document can name chunks a later
182
+ * deploy deleted. Retention is the answer to that, so this is how retention is
183
+ * stated in a form another module can act on.
184
+ *
185
+ * It states a bound and never an instruction. A module should not be able to
186
+ * tell another module to lower a safety rail; it can only supply the number the
187
+ * other module needs to make its own decision.
188
+ *
189
+ * Kept to a versioned, field-only interface so the two copies cannot drift in
190
+ * behaviour, only in whether they recognise a version. A consumer that reads an
191
+ * unknown `v` is expected to ignore it rather than guess.
192
+ */
193
+ export interface HtmlCacheCapability {
194
+ v: 1;
195
+ by: string;
196
+ /** Seconds a document may outlive its build and still resolve every chunk. */
197
+ documentTtlCeilingSeconds: number;
198
+ basis: 'observed-retained-builds' | 'retention-days' | 'none';
199
+ /** Requests for a retired build's chunks resolve instead of 404. */
200
+ assetRecovery: boolean;
201
+ }
202
+ /**
203
+ * The capability this configuration supports, or null when it supports none.
204
+ *
205
+ * `assetRecovery` is the load-bearing field, not the ceiling. Retaining old
206
+ * builds is what turns a stale document from a `ChunkLoadError` into a slow
207
+ * page, and a consumer is expected to refuse the whole handshake without it.
208
+ * It is true only when this module actually stores asset bytes: the preset
209
+ * says where old builds would be served from, `bundleAssets` and `storage`
210
+ * decide whether any were kept.
211
+ *
212
+ * The ceiling is the smaller of what time allows and what rank allows, because
213
+ * whichever binds first is the one that ends the guarantee.
214
+ */
215
+ export declare function htmlCacheCapability(input: {
216
+ retentionDays: number;
217
+ maxNumberOfVersions: number;
218
+ assetRecovery: boolean;
219
+ }): HtmlCacheCapability | null;
220
+ export {};
@@ -0,0 +1,172 @@
1
+ function isDocumentRequest(request) {
2
+ if (request.secFetchDest)
3
+ return request.secFetchDest === "document";
4
+ return request.accept?.includes("text/html") === true;
5
+ }
6
+ function directive(value, name) {
7
+ const match = value.match(new RegExp(`(?:^|[,\\s])${name}=(\\d+)`, "i"));
8
+ return match ? Number(match[1]) : void 0;
9
+ }
10
+ export function sharedCacheSeconds(cacheControl) {
11
+ const raw = Array.isArray(cacheControl) ? cacheControl.join(", ") : cacheControl;
12
+ if (typeof raw !== "string" || !raw)
13
+ return null;
14
+ const value = raw.toLowerCase();
15
+ if (value.includes("no-store") || value.includes("private"))
16
+ return null;
17
+ const shared = directive(value, "s-maxage") ?? directive(value, "max-age");
18
+ if (shared === void 0 || shared <= 0)
19
+ return null;
20
+ return shared + (directive(value, "stale-while-revalidate") ?? 0);
21
+ }
22
+ export function sharedWindowFromMaxAgeAlone(cacheControl) {
23
+ if (sharedCacheSeconds(cacheControl) === null)
24
+ return false;
25
+ const raw = Array.isArray(cacheControl) ? cacheControl.join(", ") : cacheControl;
26
+ if (typeof raw !== "string")
27
+ return false;
28
+ return directive(raw.toLowerCase(), "s-maxage") === void 0;
29
+ }
30
+ export function resolveHtmlCachePolicy(request, response) {
31
+ if (request.method !== "GET" && request.method !== "HEAD")
32
+ return { _tag: "skipped", reason: "not-cacheable-method" };
33
+ if (!isDocumentRequest(request))
34
+ return { _tag: "skipped", reason: "not-document" };
35
+ if (request.cookie)
36
+ return { _tag: "skipped", reason: "request-has-cookie" };
37
+ if (request.authorization)
38
+ return { _tag: "skipped", reason: "request-is-authenticated" };
39
+ if (response.status !== 200)
40
+ return { _tag: "skipped", reason: "not-ok-status" };
41
+ const seconds = sharedCacheSeconds(response.cacheControl);
42
+ if (seconds === null)
43
+ return { _tag: "skipped", reason: "no-shared-cache-directive" };
44
+ return { _tag: "shared-cacheable", seconds };
45
+ }
46
+ export function withoutCookie(setCookie, name) {
47
+ if (!setCookie)
48
+ return [];
49
+ const all = Array.isArray(setCookie) ? setCookie : [setCookie];
50
+ return all.filter((entry) => !entry.trimStart().toLowerCase().startsWith(`${name.toLowerCase()}=`));
51
+ }
52
+ export function skewCacheCeilingSeconds(retentionDays) {
53
+ if (!Number.isFinite(retentionDays))
54
+ return 0;
55
+ return Math.max(0, Math.floor(retentionDays * 24 * 60 * 60));
56
+ }
57
+ const SHARED_CACHE_CONTROL_HEADERS = [
58
+ "cloudflare-cdn-cache-control",
59
+ "cdn-cache-control",
60
+ "cache-control"
61
+ ];
62
+ const NON_HTML_ROUTE_PREFIXES = [
63
+ "/.well-known",
64
+ "/api",
65
+ "/assets",
66
+ "/fonts",
67
+ "/images",
68
+ "/mcp"
69
+ ];
70
+ const NON_HTML_EXTENSION_RE = /\.(?:avif|css|csv|gif|ico|jpe?g|js|json|map|md|mjs|pdf|png|svg|txt|webmanifest|webp|woff2?|xml)(?:$|[?*])/i;
71
+ const HTML_CONTENT_TYPE_RE = /^(?:application\/xhtml\+xml|text\/html)(?:\s*;|$)/i;
72
+ export function sharedCacheControlHeader(getHeader) {
73
+ for (const name of SHARED_CACHE_CONTROL_HEADERS) {
74
+ const value = getHeader(name);
75
+ if (value !== void 0)
76
+ return { name, value };
77
+ }
78
+ return null;
79
+ }
80
+ function isHtmlCapableRoute(route, rule, publicAssetPrefixes) {
81
+ const contentType = rule.headers && Object.entries(rule.headers).find(([name]) => name.toLowerCase() === "content-type")?.[1];
82
+ if (typeof contentType === "string")
83
+ return HTML_CONTENT_TYPE_RE.test(contentType);
84
+ if (route.startsWith("/_") || NON_HTML_EXTENSION_RE.test(route))
85
+ return false;
86
+ if (NON_HTML_ROUTE_PREFIXES.some((prefix) => route === prefix || route.startsWith(`${prefix}/`)))
87
+ return false;
88
+ return !publicAssetPrefixes.some((prefix) => route === prefix || route.startsWith(`${prefix}/`));
89
+ }
90
+ function ruleWindow(rule) {
91
+ const header = sharedCacheControlHeader((name) => rule.headers && Object.entries(rule.headers).find(([candidate]) => candidate.toLowerCase() === name)?.[1]);
92
+ const fromHeader = sharedCacheSeconds(header?.value);
93
+ if (fromHeader !== null) {
94
+ return {
95
+ seconds: fromHeader,
96
+ source: "cache-control",
97
+ fromMaxAgeAlone: header?.name === "cache-control" && sharedWindowFromMaxAgeAlone(header.value)
98
+ };
99
+ }
100
+ const cache = rule.cache;
101
+ if (cache && typeof cache === "object" && typeof cache.maxAge === "number") {
102
+ const stale = typeof cache.staleMaxAge === "number" ? cache.staleMaxAge : 0;
103
+ return { seconds: cache.maxAge + stale, source: "cache", fromMaxAgeAlone: false };
104
+ }
105
+ if (typeof rule.swr === "number")
106
+ return { seconds: rule.swr, source: "swr", fromMaxAgeAlone: false };
107
+ if (rule.swr === true)
108
+ return { seconds: Number.POSITIVE_INFINITY, source: "swr", fromMaxAgeAlone: false };
109
+ if (typeof rule.isr === "number")
110
+ return { seconds: rule.isr, source: "isr", fromMaxAgeAlone: false };
111
+ if (rule.isr === true)
112
+ return { seconds: Number.POSITIVE_INFINITY, source: "isr", fromMaxAgeAlone: false };
113
+ if (rule.isr && typeof rule.isr === "object") {
114
+ const expiration = rule.isr.expiration;
115
+ if (typeof expiration === "number")
116
+ return { seconds: expiration, source: "isr", fromMaxAgeAlone: false };
117
+ if (expiration === false)
118
+ return { seconds: Number.POSITIVE_INFINITY, source: "isr", fromMaxAgeAlone: false };
119
+ }
120
+ return null;
121
+ }
122
+ export function cachingRouteRules(routeRules, publicAssetBaseURLs = []) {
123
+ const caching = [];
124
+ const publicAssetPrefixes = publicAssetBaseURLs.map((baseURL) => `/${baseURL}`.replace(/^\/{2,}/, "/").replace(/\/+$/, "")).filter((prefix) => prefix !== "" && prefix !== "/");
125
+ for (const [route, rule] of Object.entries(routeRules ?? {})) {
126
+ if (!rule || typeof rule !== "object")
127
+ continue;
128
+ if (!isHtmlCapableRoute(route, rule, publicAssetPrefixes))
129
+ continue;
130
+ const window = ruleWindow(rule);
131
+ if (window)
132
+ caching.push({ route, seconds: window.seconds, source: window.source, fromMaxAgeAlone: window.fromMaxAgeAlone });
133
+ }
134
+ return caching;
135
+ }
136
+ export function overlongRouteRules(routeRules, ceilingSeconds, publicAssetBaseURLs = []) {
137
+ return cachingRouteRules(routeRules, publicAssetBaseURLs).filter((route) => route.seconds > ceilingSeconds);
138
+ }
139
+ export function htmlCacheRequestFromEvent(event, getHeader) {
140
+ return {
141
+ method: event.method ?? event.node?.req?.method ?? "GET",
142
+ secFetchDest: getHeader(event, "sec-fetch-dest"),
143
+ accept: getHeader(event, "accept"),
144
+ cookie: getHeader(event, "cookie"),
145
+ authorization: getHeader(event, "authorization") ?? getHeader(event, "proxy-authorization")
146
+ };
147
+ }
148
+ export function readSetCookies(event, fallback) {
149
+ const headers = event.res?.headers;
150
+ if (headers && typeof headers.getSetCookie === "function")
151
+ return headers.getSetCookie();
152
+ if (Array.isArray(fallback))
153
+ return fallback;
154
+ return fallback === void 0 || fallback === "" ? [] : [String(fallback)];
155
+ }
156
+ const ASSUMED_MIN_DEPLOY_INTERVAL_SECONDS = 60 * 60;
157
+ export function htmlCacheCapability(input) {
158
+ if (!input.assetRecovery)
159
+ return null;
160
+ const byTime = skewCacheCeilingSeconds(input.retentionDays);
161
+ const byRank = Math.max(0, Math.floor(input.maxNumberOfVersions)) * ASSUMED_MIN_DEPLOY_INTERVAL_SECONDS;
162
+ const ceiling = Math.min(byTime, byRank);
163
+ if (ceiling <= 0)
164
+ return null;
165
+ return {
166
+ v: 1,
167
+ by: "nuxt-skew-protection",
168
+ documentTtlCeilingSeconds: ceiling,
169
+ basis: "retention-days",
170
+ assetRecovery: true
171
+ };
172
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nuxt-skew-protection",
3
3
  "type": "module",
4
- "version": "1.5.0",
4
+ "version": "1.5.2",
5
5
  "description": "Solve Nuxt version skews with persistent assets and instant updates.",
6
6
  "author": {
7
7
  "name": "Harlan Wilton",
@@ -102,7 +102,7 @@
102
102
  "better-sqlite3": "^13.0.3",
103
103
  "bumpp": "^12.2.0",
104
104
  "eslint": "^10.8.1",
105
- "eslint-plugin-harlanzw": "^0.17.1",
105
+ "eslint-plugin-harlanzw": "^0.20.0",
106
106
  "eventsource": "^5.0.0",
107
107
  "happy-dom": "^20.11.2",
108
108
  "ioredis": "^6.0.0",