nuxt-skew-protection 1.4.3 → 1.5.0

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.
Files changed (32) hide show
  1. package/dist/module.d.mts +2 -2
  2. package/dist/module.json +1 -1
  3. package/dist/module.mjs +318 -194
  4. package/dist/runtime/adapters/ably/index.d.ts +2 -2
  5. package/dist/runtime/adapters/ably/index.js +7 -1
  6. package/dist/runtime/adapters/ably/node.d.ts +2 -0
  7. package/dist/runtime/adapters/ably/types.d.ts +3 -0
  8. package/dist/runtime/adapters/ably/types.js +2 -0
  9. package/dist/runtime/adapters/ably/web.d.ts +2 -5
  10. package/dist/runtime/adapters/ably/web.js +1 -1
  11. package/dist/runtime/adapters/index.js +1 -1
  12. package/dist/runtime/adapters/pusher/index.d.ts +2 -2
  13. package/dist/runtime/adapters/pusher/index.js +7 -1
  14. package/dist/runtime/adapters/pusher/types.d.ts +1 -0
  15. package/dist/runtime/adapters/pusher/web.d.ts +2 -8
  16. package/dist/runtime/adapters/types.d.ts +7 -5
  17. package/dist/runtime/adapters/types.js +1 -0
  18. package/dist/runtime/app/plugins/sw-track-user-modules.client.js +8 -1
  19. package/dist/runtime/app/types.d.ts +1 -1
  20. package/dist/runtime/app/utils/create-skew-connection.js +5 -3
  21. package/dist/runtime/server/imports/cookie.d.ts +2 -2
  22. package/dist/runtime/server/imports/cookie.js +5 -1
  23. package/dist/runtime/server/middleware/vercel-skew.js +4 -1
  24. package/dist/runtime/server/routes/__skew/sse.js +0 -2
  25. package/dist/runtime/server/routes/__skew/ws.js +1 -1
  26. package/dist/runtime/server/utils/cloudflare-asset-fetch.d.ts +1 -1
  27. package/dist/runtime/server/utils/cloudflare-asset-fetch.js +43 -6
  28. package/dist/runtime/server/utils/vercel-cookie-path.d.ts +2 -0
  29. package/dist/runtime/server/utils/vercel-cookie-path.js +3 -0
  30. package/dist/runtime/types.d.ts +14 -2
  31. package/dist/sw/_nuxt-skew-sw.js +1 -1
  32. package/package.json +8 -8
package/dist/module.d.mts CHANGED
@@ -58,8 +58,8 @@ interface ModuleOptions {
58
58
  /**
59
59
  * Bundle old deployment assets to support users on previous versions.
60
60
  * When enabled, old build assets are stored and served to users who haven't refreshed.
61
- * @default true
62
- * @note Automatically disabled when using CDN URL
61
+ * @default true, or false when native Vercel Skew Protection is active
62
+ * @note Automatically disabled when using a CDN URL or native Vercel Skew Protection
63
63
  */
64
64
  bundleAssets?: boolean;
65
65
  /**
package/dist/module.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "nuxt": ">=4.0.0"
5
5
  },
6
6
  "configKey": "skewProtection",
7
- "version": "1.4.3",
7
+ "version": "1.5.0",
8
8
  "builder": {
9
9
  "@nuxt/module-builder": "1.0.3",
10
10
  "unbuild": "3.6.1"
package/dist/module.mjs CHANGED
@@ -1,11 +1,12 @@
1
- import { writeFileSync, unlinkSync, existsSync, readFileSync, promises } from 'node:fs';
1
+ import { existsSync, promises } from 'node:fs';
2
2
  import { useLogger, useNuxt, defineNuxtModule, createResolver, hasNuxtModule, addTypeTemplate, addComponent, addImports, addServerHandler, addPlugin, tryResolveModule, addTemplate } from '@nuxt/kit';
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
6
  import { join } from 'node:path';
7
+ import { spawn } from 'node:child_process';
8
+ import { mkdtemp, writeFile, rm } from 'node:fs/promises';
7
9
  import { tmpdir } from 'node:os';
8
- import { x } from 'tinyexec';
9
10
  import { defineDriver, createStorage } from 'unstorage';
10
11
  import { isSkewAdapter } from '../dist/runtime/adapters/index.js';
11
12
  import '../dist/runtime/adapters/types.js';
@@ -14,11 +15,34 @@ import { join as join$1, dirname } from 'pathe';
14
15
 
15
16
  const logger = useLogger("nuxt-skew-protection");
16
17
 
18
+ function resolveBundleAssets(options, env = process.env) {
19
+ if (typeof options.bundleAssets === "boolean") {
20
+ return {
21
+ _tag: "configured",
22
+ bundleAssets: options.bundleAssets
23
+ };
24
+ }
25
+ if (env.VERCEL_SKEW_PROTECTION_ENABLED === "1" && env.VERCEL_DEPLOYMENT_ID) {
26
+ return {
27
+ _tag: "vercel-native",
28
+ bundleAssets: false
29
+ };
30
+ }
31
+ return {
32
+ _tag: "default",
33
+ bundleAssets: true
34
+ };
35
+ }
36
+
17
37
  const SKEW_SEGMENT = "__skew";
18
38
  const DEFAULT_COOKIE_NAME = "__nkpv";
19
39
  function trimSlashes(value) {
20
40
  return value.replace(/^\/+|\/+$/g, "");
21
41
  }
42
+ function resolveBuildAssetsPath(app = {}) {
43
+ const path = [app.baseURL, app.buildAssetsDir || "/_nuxt/"].map((value) => trimSlashes(value || "")).filter(Boolean).join("/");
44
+ return `/${path}/`;
45
+ }
22
46
  function resolveBasePath(input = {}) {
23
47
  if (input.basePath)
24
48
  return `/${trimSlashes(input.basePath)}`;
@@ -45,145 +69,214 @@ function resolveCookieName(explicitName, basePath) {
45
69
  return slug ? `${DEFAULT_COOKIE_NAME}_${slug}` : DEFAULT_COOKIE_NAME;
46
70
  }
47
71
 
48
- const cloudflareKVWranglerDriver = defineDriver((opts) => {
49
- const { namespaceId, local = false, base = "" } = opts;
50
- if (!namespaceId) {
51
- throw new Error("[cloudflare-kv-wrangler] namespaceId is required");
52
- }
53
- const locationFlag = local ? "--local" : "--remote";
54
- const prefixKey = (key) => base ? `${base}${key}` : key;
55
- const unprefixKey = (key) => base && key.startsWith(base) ? key.slice(base.length) : key;
56
- async function execWrangler(command, throwOnError = true) {
57
- const result = await x("sh", ["-c", `npx ${command}`]);
58
- if (throwOnError && result.exitCode !== 0) {
59
- throw new Error(
60
- `[cloudflare-kv-wrangler] Command failed with exit code ${result.exitCode}
61
- Command: ${command}
62
- stdout: ${result.stdout}
63
- stderr: ${result.stderr}`
64
- );
65
- }
66
- return { stdout: result.stdout.trim(), exitCode: result.exitCode || 0 };
72
+ const executeWrangler = (args) => new Promise((resolve, reject) => {
73
+ const child = spawn("wrangler", [...args], {
74
+ shell: false,
75
+ windowsHide: true
76
+ });
77
+ const stdout = [];
78
+ const stderr = [];
79
+ child.stdout.on("data", (chunk) => stdout.push(Buffer.from(chunk)));
80
+ child.stderr.on("data", (chunk) => stderr.push(Buffer.from(chunk)));
81
+ child.once("error", (error) => reject(new Error(
82
+ "[cloudflare-kv-wrangler] Unable to run Wrangler. Install Wrangler v4 in the project and authenticate the build environment.",
83
+ { cause: error }
84
+ )));
85
+ child.once("close", (code) => resolve({
86
+ exitCode: code ?? 1,
87
+ stderr: Buffer.concat(stderr),
88
+ stdout: Buffer.concat(stdout)
89
+ }));
90
+ });
91
+ function assertSuccess(result, args) {
92
+ if (result.exitCode === 0)
93
+ return result;
94
+ const stderr = result.stderr.toString("utf8").trim();
95
+ throw new Error([
96
+ `[cloudflare-kv-wrangler] Wrangler exited with status ${result.exitCode}.`,
97
+ `Command: wrangler ${args.map((arg) => JSON.stringify(arg)).join(" ")}`,
98
+ stderr ? `stderr: ${stderr}` : "Wrangler did not provide an error message."
99
+ ].join("\n"));
100
+ }
101
+ function parseListedKeys(stdout) {
102
+ const parsed = JSON.parse(stdout.toString("utf8"));
103
+ if (!Array.isArray(parsed))
104
+ throw new TypeError("[cloudflare-kv-wrangler] Wrangler returned an invalid key list.");
105
+ return parsed.map((entry, index) => {
106
+ if (!entry || typeof entry !== "object" || !("name" in entry) || typeof entry.name !== "string")
107
+ throw new TypeError(`[cloudflare-kv-wrangler] Wrangler returned an invalid key at index ${index}.`);
108
+ return entry.name;
109
+ });
110
+ }
111
+ function toRawBuffer(value) {
112
+ if (Buffer.isBuffer(value))
113
+ return value;
114
+ if (value instanceof Uint8Array)
115
+ return Buffer.from(value);
116
+ if (value instanceof ArrayBuffer)
117
+ return Buffer.from(value);
118
+ if (typeof value === "string")
119
+ return Buffer.from(value);
120
+ throw new TypeError("[cloudflare-kv-wrangler] Raw values must be a string, Buffer, Uint8Array, or ArrayBuffer.");
121
+ }
122
+ async function withTemporaryFile(suffix, value, task) {
123
+ const directory = await mkdtemp(join(tmpdir(), "nuxt-skew-protection-kv-"));
124
+ const path = join(directory, `value${suffix}`);
125
+ await writeFile(path, value);
126
+ try {
127
+ return await task(path);
128
+ } finally {
129
+ await rm(directory, { recursive: true, force: true });
67
130
  }
68
- const driver = {
69
- name: "cloudflare-kv-wrangler",
70
- options: opts,
71
- async hasItem(key) {
72
- const prefixedKey = prefixKey(key);
73
- const result = await execWrangler(`wrangler kv key get "${prefixedKey}" --namespace-id="${namespaceId}" ${locationFlag}`, false);
74
- return result.exitCode === 0;
75
- },
76
- async getItem(key) {
77
- const prefixedKey = prefixKey(key);
78
- const result = await execWrangler(`wrangler kv key get "${prefixedKey}" --namespace-id="${namespaceId}" ${locationFlag}`, false);
79
- if (result.exitCode !== 0) {
80
- return null;
81
- }
82
- return JSON.parse(result.stdout);
83
- },
84
- async getItemRaw(key) {
85
- const prefixedKey = prefixKey(key);
86
- const result = await execWrangler(`wrangler kv key get "${prefixedKey}" --namespace-id="${namespaceId}" ${locationFlag}`);
87
- return Buffer.from(result.stdout, "utf-8");
88
- },
89
- async setItem(key, value) {
90
- const prefixedKey = prefixKey(key);
91
- const tmpFile = join(tmpdir(), `kv-${Date.now()}-${Math.random().toString(36).substring(7)}.json`);
92
- writeFileSync(tmpFile, JSON.stringify(value));
93
- try {
94
- await execWrangler(`wrangler kv key put "${prefixedKey}" --path="${tmpFile}" --namespace-id="${namespaceId}" ${locationFlag}`);
95
- } finally {
96
- unlinkSync(tmpFile);
97
- }
98
- },
99
- async setItemRaw(key, value) {
100
- const prefixedKey = prefixKey(key);
101
- const tmpFile = join(tmpdir(), `kv-${Date.now()}.bin`);
102
- writeFileSync(tmpFile, value);
103
- try {
104
- await execWrangler(`wrangler kv key put "${prefixedKey}" --path="${tmpFile}" --namespace-id="${namespaceId}" ${locationFlag}`);
105
- } finally {
106
- unlinkSync(tmpFile);
107
- }
108
- },
109
- async removeItem(key) {
110
- const prefixedKey = prefixKey(key);
111
- await execWrangler(`wrangler kv key delete "${prefixedKey}" --namespace-id="${namespaceId}" ${locationFlag}`);
112
- },
113
- async getKeys(basePrefix) {
131
+ }
132
+ function createCloudflareKVWranglerDriver(run = executeWrangler) {
133
+ return defineDriver((opts) => {
134
+ const { namespaceId, local = false, base = "" } = opts;
135
+ if (!namespaceId)
136
+ throw new Error("[cloudflare-kv-wrangler] namespaceId is required");
137
+ const locationFlag = local ? "--local" : "--remote";
138
+ const namespaceArgs = ["--namespace-id", namespaceId, locationFlag];
139
+ const prefixKey = (key) => base ? `${base}${key}` : key;
140
+ const unprefixKey = (key) => base && key.startsWith(base) ? key.slice(base.length) : key;
141
+ const command = async (args) => assertSuccess(await run(args), args);
142
+ const listKeys = async (basePrefix) => {
114
143
  const fullPrefix = base ? basePrefix ? `${base}${basePrefix}` : base : basePrefix;
115
- const prefix = fullPrefix ? `--prefix="${fullPrefix}"` : "";
116
- const result = await execWrangler(`wrangler kv key list ${prefix} --namespace-id="${namespaceId}" ${locationFlag}`);
117
- const keys = JSON.parse(result.stdout);
118
- return keys.map((k) => unprefixKey(k.name));
119
- },
120
- async clear(basePrefix) {
121
- const keys = await driver.getKeys(basePrefix);
122
- for (const key of keys) {
123
- await driver.removeItem(key);
144
+ const prefixArgs = fullPrefix ? ["--prefix", fullPrefix] : [];
145
+ const result = await command(["kv", "key", "list", ...prefixArgs, ...namespaceArgs]);
146
+ return parseListedKeys(result.stdout).map(unprefixKey);
147
+ };
148
+ const hasItem = async (key) => {
149
+ const keys = await listKeys(key);
150
+ return keys.includes(key);
151
+ };
152
+ return {
153
+ name: "cloudflare-kv-wrangler",
154
+ options: opts,
155
+ hasItem,
156
+ async getItem(key) {
157
+ const result = await command(["kv", "key", "get", prefixKey(key), ...namespaceArgs, "--text"]);
158
+ const value = result.stdout.toString("utf8").trim();
159
+ if (value === "Value not found")
160
+ return null;
161
+ return JSON.parse(value);
162
+ },
163
+ async getItemRaw(key) {
164
+ if (!await hasItem(key))
165
+ return null;
166
+ const result = await command(["kv", "key", "get", prefixKey(key), ...namespaceArgs]);
167
+ return result.stdout;
168
+ },
169
+ async setItem(key, value) {
170
+ await withTemporaryFile(".json", Buffer.from(JSON.stringify(value)), async (path) => {
171
+ await command(["kv", "key", "put", prefixKey(key), "--path", path, ...namespaceArgs]);
172
+ });
173
+ },
174
+ async setItemRaw(key, value) {
175
+ await withTemporaryFile(".bin", toRawBuffer(value), async (path) => {
176
+ await command(["kv", "key", "put", prefixKey(key), "--path", path, ...namespaceArgs]);
177
+ });
178
+ },
179
+ async removeItem(key) {
180
+ await command(["kv", "key", "delete", prefixKey(key), ...namespaceArgs]);
181
+ },
182
+ getKeys: listKeys,
183
+ async clear(basePrefix) {
184
+ const keys = await listKeys(basePrefix);
185
+ for (const key of keys)
186
+ await command(["kv", "key", "delete", prefixKey(key), ...namespaceArgs]);
187
+ },
188
+ async dispose() {
124
189
  }
125
- },
126
- async dispose() {
127
- }
128
- };
129
- return driver;
130
- });
190
+ };
191
+ });
192
+ }
193
+ const cloudflareKVWranglerDriver = createCloudflareKVWranglerDriver();
131
194
 
132
- const RE_KV_SKEW_PROTECTION = /\[\[kv_namespaces\]\][^[]*?binding\s*=\s*"SKEW_PROTECTION"[^[]*?id\s*=\s*"([^"]+)"/;
133
- const RE_KV_NAMESPACE = /\[\[kv_namespaces\]\][^[]*?id\s*=\s*"([^"]+)"/;
134
- async function detectCloudflareKVNamespace() {
135
- const nuxt = useNuxt();
136
- const kvNamespaces = nuxt.options.nitro?.cloudflare?.wrangler?.kv_namespaces;
137
- if (kvNamespaces?.length) {
138
- const skewNamespace = kvNamespaces.find((ns) => ns?.binding === "SKEW_PROTECTION");
139
- if (skewNamespace?.id) {
140
- return skewNamespace.id;
141
- }
142
- if (kvNamespaces[0]?.id) {
143
- return kvNamespaces[0].id;
144
- }
195
+ function parseWranglerKVNamespaces(value, source) {
196
+ if (value === void 0)
197
+ return [];
198
+ if (!Array.isArray(value))
199
+ throw new TypeError(`[nuxt-skew-protection] ${source} has an invalid kv_namespaces value.`);
200
+ return value.map((entry, index) => {
201
+ if (!entry || typeof entry !== "object")
202
+ throw new TypeError(`[nuxt-skew-protection] ${source} has an invalid kv_namespaces entry at index ${index}.`);
203
+ const binding = "binding" in entry ? entry.binding : void 0;
204
+ const id = "id" in entry ? entry.id : void 0;
205
+ if (typeof binding !== "string" || id !== void 0 && typeof id !== "string")
206
+ throw new TypeError(`[nuxt-skew-protection] ${source} has invalid binding or id values for kv_namespaces entry ${index}.`);
207
+ return { binding, id };
208
+ });
209
+ }
210
+ function selectCloudflareKVNamespace(namespaces, binding) {
211
+ if (namespaces.length === 0)
212
+ return null;
213
+ const matches = namespaces.filter((namespace) => namespace.binding === binding);
214
+ if (matches.length === 0) {
215
+ const available = namespaces.map((namespace) => namespace.binding).join(", ");
216
+ throw new Error(`[nuxt-skew-protection] Cloudflare KV binding ${binding} was not found. Available bindings: ${available}.`);
145
217
  }
218
+ if (matches.length > 1)
219
+ throw new Error(`[nuxt-skew-protection] Found multiple Cloudflare KV bindings named ${binding}.`);
220
+ const match = matches[0];
221
+ if (!match?.id)
222
+ throw new Error(`[nuxt-skew-protection] Cloudflare KV binding ${binding} does not have a namespace id.`);
223
+ return match.id;
224
+ }
225
+ async function readWranglerKVNamespaces(path) {
226
+ const wranglerModule = "wrangler";
227
+ const { unstable_readConfig } = await import(wranglerModule);
228
+ const config = unstable_readConfig({ config: path }, { hideWarnings: true });
229
+ return parseWranglerKVNamespaces(config.kv_namespaces, path);
230
+ }
231
+ async function detectCloudflareKVNamespace(binding) {
232
+ const nuxt = useNuxt();
233
+ const nitroNamespaces = parseWranglerKVNamespaces(
234
+ nuxt.options.nitro?.cloudflare?.wrangler?.kv_namespaces,
235
+ "nitro.cloudflare.wrangler.kv_namespaces"
236
+ );
237
+ const nitroNamespaceId = selectCloudflareKVNamespace(nitroNamespaces, binding);
238
+ if (nitroNamespaceId)
239
+ return nitroNamespaceId;
146
240
  const rootDir = nuxt.options.rootDir || process.cwd();
147
- const possiblePaths = [
148
- join(rootDir, "wrangler.toml"),
149
- join(rootDir, "app", "wrangler.toml")
150
- ];
151
- for (const wranglerPath of possiblePaths) {
152
- if (!existsSync(wranglerPath)) {
153
- continue;
154
- }
155
- try {
156
- const content = readFileSync(wranglerPath, "utf-8");
157
- const skewMatch = content.match(RE_KV_SKEW_PROTECTION);
158
- if (skewMatch?.[1]) {
159
- return skewMatch[1];
160
- }
161
- const kvNamespaceMatch = content.match(RE_KV_NAMESPACE);
162
- if (kvNamespaceMatch?.[1]) {
163
- return kvNamespaceMatch[1];
164
- }
165
- } catch {
241
+ const configNames = ["wrangler.json", "wrangler.jsonc", "wrangler.toml"];
242
+ const configDirectories = [rootDir, join(rootDir, "app")];
243
+ for (const directory of configDirectories) {
244
+ for (const configName of configNames) {
245
+ const path = join(directory, configName);
246
+ if (!existsSync(path))
247
+ continue;
248
+ const namespaces = await readWranglerKVNamespaces(path);
249
+ const namespaceId = selectCloudflareKVNamespace(namespaces, binding);
250
+ if (namespaceId)
251
+ return namespaceId;
166
252
  }
167
253
  }
168
254
  return null;
169
255
  }
170
256
  async function resolveBuildTimeDriver(storage) {
171
- const { driver, base, ...driverOptions } = storage;
172
- switch (driver) {
173
- case "cloudflare-kv-binding": {
174
- let namespaceId = storage.namespaceId;
175
- if (!namespaceId) {
176
- namespaceId = await detectCloudflareKVNamespace();
177
- }
178
- const kvBase = base?.includes("/") ? "skew-protection:" : base || "skew-protection:";
179
- return cloudflareKVWranglerDriver({
180
- namespaceId,
181
- base: kvBase,
182
- ...driverOptions
183
- });
257
+ const {
258
+ driver,
259
+ base,
260
+ binding: configuredBinding,
261
+ namespaceId: configuredNamespaceId,
262
+ ...driverOptions
263
+ } = storage;
264
+ if (driver === "cloudflare-kv-binding") {
265
+ const binding = typeof configuredBinding === "string" ? configuredBinding : "SKEW_PROTECTION";
266
+ const namespaceId = typeof configuredNamespaceId === "string" ? configuredNamespaceId : await detectCloudflareKVNamespace(binding);
267
+ if (!namespaceId) {
268
+ throw new Error(
269
+ `[nuxt-skew-protection] Unable to resolve Cloudflare KV binding ${binding}. Configure storage.namespaceId or add the binding to wrangler.jsonc.`
270
+ );
184
271
  }
272
+ const kvBase = typeof base === "string" && !base.includes("/") ? base : "skew-protection:";
273
+ return cloudflareKVWranglerDriver({
274
+ ...driverOptions,
275
+ namespaceId,
276
+ base: kvBase
277
+ });
185
278
  }
186
- const lazyDriver = await import(`unstorage/drivers/${storage.driver}`).then((m) => m.default);
279
+ const lazyDriver = await import(`unstorage/drivers/${driver}`).then((module) => module.default);
187
280
  return lazyDriver({ base, ...driverOptions });
188
281
  }
189
282
 
@@ -195,15 +288,16 @@ const legacyCloudflareAdapterSuffixes = [
195
288
  "/nitropack/dist/runtime/entries/cloudflare.mjs",
196
289
  "/nitropack/dist/runtime/entries/cloudflare-pages.mjs"
197
290
  ];
198
- const nitroPrerenderEntrySuffix = "/nitropack/dist/presets/_nitro/runtime/nitro-prerenderer.mjs";
291
+ const nitroPrerenderEntrySuffix = "/nitropack/dist/presets/_nitro/runtime/nitro-prerenderer";
199
292
  function isNitroPrerenderEntry(id) {
200
- return id.split("?", 1)[0].endsWith(nitroPrerenderEntrySuffix);
293
+ const normalizedId = id.split("?", 1)[0].replaceAll("\\", "/");
294
+ return normalizedId.endsWith(nitroPrerenderEntrySuffix) || normalizedId.endsWith(`${nitroPrerenderEntrySuffix}.mjs`);
201
295
  }
202
296
  function isLegacyCloudflareEntry(id) {
203
297
  const normalizedId = id.split("?", 1)[0].replaceAll("\\", "/");
204
298
  return legacyCloudflareAdapterSuffixes.some((suffix) => normalizedId.endsWith(suffix));
205
299
  }
206
- function normalizeBuildAssetsDir(value) {
300
+ function normalizeBuildAssetsPath(value) {
207
301
  const path = value.replace(/^\/+|\/+$/g, "");
208
302
  return `/${path}/`;
209
303
  }
@@ -217,7 +311,8 @@ function withoutCloudflareAssetProtectionPlugin(plugins) {
217
311
  function renderCloudflareEntry(options) {
218
312
  const nitroEntryId = JSON.stringify(options.nitroEntryId);
219
313
  const runtimeHelperId = JSON.stringify(options.runtimeHelperId);
220
- const buildAssetsDir = JSON.stringify(normalizeBuildAssetsDir(options.buildAssetsDir));
314
+ const buildAssetsPath = JSON.stringify(normalizeBuildAssetsPath(options.buildAssetsPath));
315
+ const recoveryPath = JSON.stringify(options.recoveryPath);
221
316
  return `import nitroEntry from ${nitroEntryId};
222
317
  import { fetchCloudflareBuildAsset } from ${runtimeHelperId};
223
318
  export * from ${nitroEntryId};
@@ -229,7 +324,7 @@ if (!nitroEntry || typeof nitroEntry.fetch !== "function") {
229
324
  export default {
230
325
  ...nitroEntry,
231
326
  fetch(request, env, context) {
232
- const assetResponse = fetchCloudflareBuildAsset(request, env.ASSETS, ${buildAssetsDir});
327
+ const assetResponse = fetchCloudflareBuildAsset(request, env.ASSETS, ${buildAssetsPath}, ${recoveryPath});
233
328
  return assetResponse ?? nitroEntry.fetch(request, env, context);
234
329
  },
235
330
  };`;
@@ -287,6 +382,15 @@ function createCloudflareAssetProtectionPlugin(options) {
287
382
  };
288
383
  }
289
384
 
385
+ function withCloudflareBuildAssetRouting(current, buildAssetsDir) {
386
+ if (current === true)
387
+ return true;
388
+ const prefix = `/${buildAssetsDir.replace(/^\/+|\/+$/g, "")}/`;
389
+ const pattern = `${prefix}*`;
390
+ const routes = Array.isArray(current) ? current.filter((route) => typeof route === "string") : [];
391
+ return routes.includes(pattern) ? routes : [...routes, pattern];
392
+ }
393
+
290
394
  const RE_ENOTFOUND = /ENOTFOUND\s+(\S+)/;
291
395
  const RE_GETADDRINFO = /getaddrinfo\s+\S+\s+(\S+)/;
292
396
  const RE_SIZE_PROP = /(['"]?)size\1\s*:\s*\d+/;
@@ -410,6 +514,7 @@ function createAssetManager(options) {
410
514
  const maxNumberOfVersions = options.maxNumberOfVersions || 20;
411
515
  const buildAssetsDir = (options.buildAssetsDir || "/_nuxt/").replace(/^\/+|\/+$/g, "");
412
516
  const buildAssetsPath = `/${buildAssetsDir}`;
517
+ const persistAssets = options.persistAssets !== false;
413
518
  async function getAssetsFromBuild(publicDir) {
414
519
  const startTime = Date.now();
415
520
  const nuxtDir = join$1(publicDir, buildAssetsDir);
@@ -420,6 +525,9 @@ function createAssetManager(options) {
420
525
  const relativePath = file.replace(nuxtDir, "");
421
526
  assets.push(`${buildAssetsDir}${relativePath}`);
422
527
  }
528
+ if (assets.length === 0) {
529
+ throw new Error(`No build assets found in ${nuxtDir}. Check that app.buildAssetsDir matches the generated output.`);
530
+ }
423
531
  logger.debug(`Found ${assets.length} assets in ${formatDuration(Date.now() - startTime)}`);
424
532
  return assets;
425
533
  }
@@ -432,15 +540,17 @@ function createAssetManager(options) {
432
540
  const manifest = await getVersionManifest(storage);
433
541
  logger.debug(`updateVersionsManifest: loaded manifest in ${formatDuration(Date.now() - manifestStart)} (${Object.keys(manifest.versions).length} versions)`);
434
542
  const isExistingVersion = !!manifest.versions[buildId];
543
+ const previousVersionId = manifest.current && manifest.current !== buildId ? manifest.current : getPreviousVersion(manifest, buildId);
544
+ const previousVersion = previousVersionId ? manifest.versions[previousVersionId] : void 0;
545
+ const previousAssets = previousVersion?.originalAssets || previousVersion?.assets || [];
435
546
  manifest.current = buildId;
436
547
  manifest.versions[buildId] = {
437
548
  timestamp: now.toISOString(),
438
549
  expires: expires.toISOString(),
439
- assets,
550
+ assets: persistAssets ? [...assets] : [],
440
551
  // Store original assets for deletedChunks calculation (assets array gets modified by deduplication)
441
552
  originalAssets: [...assets],
442
- // deletedChunks will be calculated in storeAssetsInStorage
443
- deletedChunks: []
553
+ deletedChunks: calculateDeletedChunks(assets, previousAssets)
444
554
  };
445
555
  const saveStart = Date.now();
446
556
  await setVersionManifest(manifest, storage);
@@ -528,14 +638,6 @@ function createAssetManager(options) {
528
638
  const fileIdToVersion = manifest.fileIdToVersion;
529
639
  const existingFileIds = Object.keys(fileIdToVersion).length;
530
640
  logger.debug(`storeAssetsInStorage: fileIdToVersion has ${existingFileIds} entries`);
531
- const currentVersion = manifest.versions[buildId];
532
- if (currentVersion) {
533
- const previousVersionId = getPreviousVersion(manifest, buildId);
534
- const previousVersion = previousVersionId ? manifest.versions[previousVersionId] : null;
535
- const previousAssets = previousVersion?.originalAssets || previousVersion?.assets || [];
536
- currentVersion.deletedChunks = calculateDeletedChunks(assets, previousAssets);
537
- logger.debug(`storeAssetsInStorage: calculated ${currentVersion.deletedChunks.length} deleted chunks vs ${previousVersionId || "none"}`);
538
- }
539
641
  let storedCount = 0;
540
642
  let deduplicatedCount = 0;
541
643
  let totalBytes = 0;
@@ -555,9 +657,7 @@ function createAssetManager(options) {
555
657
  if (assetData) {
556
658
  totalBytes += assetData.byteLength;
557
659
  const storageKey = `${buildId}/${asset}`;
558
- await storage.setItemRaw(storageKey, assetData).catch((error) => {
559
- logger.error(`Failed to store ${storageKey}:`, error?.message || error);
560
- });
660
+ await storage.setItemRaw(storageKey, assetData);
561
661
  storedCount++;
562
662
  if (fileId && fileIdToVersion[fileId] && fileIdToVersion[fileId] !== buildId) {
563
663
  const previousVersionId = fileIdToVersion[fileId];
@@ -656,7 +756,6 @@ function createAssetManager(options) {
656
756
  }
657
757
  const restoreStart = Date.now();
658
758
  let totalBytes = 0;
659
- let failedCount = 0;
660
759
  const createdDirs = /* @__PURE__ */ new Set();
661
760
  const batchResults = await processBatch(assetTasks, 25, async ({ versionId, asset, versionData }) => {
662
761
  const storageKey = `${versionId}/${asset}`;
@@ -686,17 +785,16 @@ function createAssetManager(options) {
686
785
  age: formatAge(versionTimestamp, now)
687
786
  };
688
787
  }
689
- return null;
788
+ throw new Error(`Stored asset ${storageKey} is missing.`);
690
789
  }).catch((error) => {
691
- if (error.code !== "EEXIST") {
692
- failedCount++;
693
- logger.debug(`Failed to restore asset ${asset} from version ${versionId}: ${error}`);
790
+ if (error.code === "EEXIST") {
791
+ return null;
694
792
  }
695
- return null;
793
+ throw error;
696
794
  });
697
795
  });
698
796
  restoredAssets.push(...batchResults.filter((r) => r !== null));
699
- logger.debug(`restoreOldAssetsToPublic: restored ${restoredAssets.length} assets (${formatBytes(totalBytes)}) in ${formatDuration(Date.now() - restoreStart)}${failedCount > 0 ? `, ${failedCount} failed` : ""}`);
797
+ logger.debug(`restoreOldAssetsToPublic: restored ${restoredAssets.length} assets (${formatBytes(totalBytes)}) in ${formatDuration(Date.now() - restoreStart)}`);
700
798
  const restoredByVersion = /* @__PURE__ */ new Map();
701
799
  for (const item of restoredAssets) {
702
800
  restoredByVersion.set(item.versionId, (restoredByVersion.get(item.versionId) || 0) + 1);
@@ -735,9 +833,8 @@ function createAssetManager(options) {
735
833
  newLatestContent = JSON.stringify(latestJson, null, 2);
736
834
  await promises.writeFile(latestPath, newLatestContent, "utf-8");
737
835
  } catch (error) {
738
- if (options.debug) {
739
- logger.warn("Failed to augment builds/latest.json:", error);
740
- }
836
+ const message = error instanceof Error ? error.message : String(error);
837
+ throw new Error(`Failed to augment builds/latest.json: ${message}`);
741
838
  }
742
839
  const metaPath = join$1(publicDir, buildAssetsDir, "builds", "meta", `${buildId}.json`);
743
840
  try {
@@ -752,9 +849,8 @@ function createAssetManager(options) {
752
849
  }
753
850
  await promises.writeFile(metaPath, JSON.stringify(metaJson, null, 2), "utf-8");
754
851
  } catch (error) {
755
- if (options.debug) {
756
- logger.warn(`Failed to augment builds/meta/${buildId}.json:`, error);
757
- }
852
+ const message = error instanceof Error ? error.message : String(error);
853
+ throw new Error(`Failed to augment builds/meta/${buildId}.json: ${message}`);
758
854
  }
759
855
  if (serverDir && newLatestContent) {
760
856
  await patchNitroManifest(serverDir, `${buildAssetsPath}/builds/latest.json`, newLatestContent);
@@ -852,7 +948,6 @@ const module$1 = defineNuxtModule({
852
948
  defaults: {
853
949
  retentionDays: 30,
854
950
  maxNumberOfVersions: 10,
855
- bundleAssets: true,
856
951
  cookie: {
857
952
  // `name` intentionally omitted — derived from the mount point in setup
858
953
  // (`resolveCookieName`) so path-routed apps get a distinct cookie. An
@@ -894,6 +989,11 @@ const module$1 = defineNuxtModule({
894
989
  options.bundleAssets = rawOptions.bundlePreviousDeploymentChunks;
895
990
  }
896
991
  }
992
+ const bundleAssetsResolution = resolveBundleAssets(options);
993
+ options.bundleAssets = bundleAssetsResolution.bundleAssets;
994
+ if (bundleAssetsResolution._tag === "vercel-native") {
995
+ logger.info("Vercel Skew Protection detected. Persistent asset storage is disabled. Build metadata tracking remains enabled. Set `bundleAssets: true` to override.");
996
+ }
897
997
  nuxt.hooks.hook("nuxt-seo-pro:modules", (modules) => {
898
998
  const mod = modules.find((m) => m.name === "nuxt-skew-protection");
899
999
  if (mod) {
@@ -913,8 +1013,17 @@ const module$1 = defineNuxtModule({
913
1013
  if (options.ipTracking && !options.connectionTracking) {
914
1014
  logger.warn("`ipTracking` requires `connectionTracking: true`. IP tracking will be disabled.");
915
1015
  }
1016
+ const nitroPreset = resolveNitroPreset(nuxt.options.nitro);
1017
+ const usesCloudflareAssets = nitroPreset === "cloudflare-module" || nitroPreset === "cloudflare-durable";
1018
+ const buildAssetsPath = resolveBuildAssetsPath(nuxt.options.app);
1019
+ const recoveryPath = `${basePath}/asset`;
916
1020
  nuxt.options.runtimeConfig.public.skewProtection = {
917
1021
  basePath,
1022
+ assetRecovery: usesCloudflareAssets ? {
1023
+ _tag: "cloudflare",
1024
+ buildAssetsPath,
1025
+ recoveryPath
1026
+ } : { _tag: "disabled" },
918
1027
  cookie: options.cookie,
919
1028
  debug: options.debug,
920
1029
  connectionTracking: options.connectionTracking,
@@ -924,7 +1033,6 @@ const module$1 = defineNuxtModule({
924
1033
  multiTab: options.multiTab ?? true,
925
1034
  version
926
1035
  };
927
- const nitroPreset = resolveNitroPreset(nuxt.options.nitro);
928
1036
  const isNuxtHub = hasNuxtModule("@nuxthub/core");
929
1037
  if (isNuxtHub && options.storage?.driver === "cloudflare-kv-binding" && !options.storage.namespaceId) {
930
1038
  logger.error("NuxtHub detected with cloudflare-kv-binding driver but no namespaceId configured.");
@@ -1080,12 +1188,20 @@ export {}
1080
1188
  const isStatic = isNuxtGenerate(nuxt);
1081
1189
  if (nitroPreset === "cloudflare-module" || nitroPreset === "cloudflare-durable") {
1082
1190
  nuxt.hook("nitro:config", (nitroConfig) => {
1191
+ nitroConfig.cloudflare ||= {};
1192
+ nitroConfig.cloudflare.wrangler ||= {};
1193
+ nitroConfig.cloudflare.wrangler.assets ||= {};
1194
+ nitroConfig.cloudflare.wrangler.assets.run_worker_first = withCloudflareBuildAssetRouting(
1195
+ nitroConfig.cloudflare.wrangler.assets.run_worker_first,
1196
+ nuxt.options.app.buildAssetsDir
1197
+ );
1083
1198
  nitroConfig.rollupConfig ||= {};
1084
1199
  const existingPlugins = nitroConfig.rollupConfig.plugins;
1085
1200
  nitroConfig.rollupConfig.plugins = [
1086
1201
  ...Array.isArray(existingPlugins) ? existingPlugins : existingPlugins ? [existingPlugins] : [],
1087
1202
  createCloudflareAssetProtectionPlugin({
1088
- buildAssetsDir: nuxt.options.app.buildAssetsDir,
1203
+ buildAssetsPath,
1204
+ recoveryPath,
1089
1205
  runtimeHelperId: resolver.resolve("./runtime/server/utils/cloudflare-asset-fetch")
1090
1206
  })
1091
1207
  ];
@@ -1114,6 +1230,10 @@ export {}
1114
1230
  resolvedStrategy = "polling";
1115
1231
  }
1116
1232
  if (isVercel) {
1233
+ nuxt.options.runtimeConfig.skewProtection = {
1234
+ ...typeof nuxt.options.runtimeConfig.skewProtection === "object" ? nuxt.options.runtimeConfig.skewProtection : {},
1235
+ vercelCookiePath: nuxt.options.app.baseURL
1236
+ };
1117
1237
  addServerHandler({
1118
1238
  handler: resolver.resolve("./runtime/server/middleware/vercel-skew"),
1119
1239
  middleware: true
@@ -1160,7 +1280,7 @@ export {}
1160
1280
  maxAge: 0
1161
1281
  // Service workers should not be cached
1162
1282
  });
1163
- if (options.storage && options.bundleAssets) {
1283
+ if (options.storage) {
1164
1284
  nuxt.hook("nitro:init", (nitro) => {
1165
1285
  const buildId = nuxt.options.runtimeConfig.app.buildId ||= nuxt.options.buildId;
1166
1286
  let assetManager;
@@ -1169,42 +1289,45 @@ export {}
1169
1289
  assetManager = createAssetManager({
1170
1290
  ...options,
1171
1291
  buildAssetsDir: nuxt.options.app.buildAssetsDir,
1292
+ persistAssets: options.bundleAssets !== false,
1172
1293
  driver: await resolveBuildTimeDriver(options.storage)
1173
1294
  });
1174
1295
  const assets = await assetManager.getAssetsFromBuild(publicDir);
1175
1296
  const { isExistingVersion } = await assetManager.updateVersionsManifest(buildId, assets);
1176
- const manifest = await assetManager.getManifest();
1177
- const totalReleases = Object.keys(manifest.versions).length;
1178
- const timestamps = Object.values(manifest.versions).map((v) => new Date(v.timestamp).getTime());
1179
- const oldestTimestamp = Math.min(...timestamps);
1180
- const daysSince = Math.floor((Date.now() - oldestTimestamp) / (1e3 * 60 * 60 * 24));
1181
- const timeInfo = daysSince > 0 ? `${daysSince} day${daysSince > 1 ? "s" : ""} ago` : "today";
1182
- const storageInfo = options.storage.base ? `${colors.green(options.storage.driver)} ${colors.gray(`(${options.storage.base})`)}` : colors.green(options.storage.driver);
1183
- if (totalReleases === 1) {
1184
- 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`);
1185
- } else {
1186
- logger.log(`Storing ${colors.yellow(assets.length.toString())} assets for ${colors.cyan(buildId.slice(0, 8))} (${totalReleases} releases, oldest from ${timeInfo}) [${storageInfo}]`);
1187
- }
1188
- await assetManager.storeAssetsInStorage(buildId, publicDir, assets).catch((error) => {
1189
- logger.error(`Failed to store assets:`, error instanceof Error ? error.message : error);
1190
- throw error;
1191
- });
1192
- const existingVersions = await assetManager.listExistingVersions();
1193
- const versionCount = existingVersions.filter((v) => v.id !== buildId).length;
1194
- logger.success(`Successfully stored ${assets.length} assets for latest release`);
1195
- if (versionCount > 0) {
1196
- const updatedManifest = await assetManager.getManifest();
1197
- let totalAssets = 0;
1198
- const versionSizes = [];
1199
- for (const [vId, vData] of Object.entries(updatedManifest.versions)) {
1200
- if (vId !== buildId) {
1201
- totalAssets += vData.assets.length;
1202
- versionSizes.push(`${vId.slice(0, 8)}:${vData.assets.length}`);
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
+ }
1203
1326
  }
1327
+ logger.log(`Restoring build files from ${versionCount} release${versionCount > 1 ? "s" : ""} (${totalAssets} assets) [${versionSizes.join(", ")}]...`);
1204
1328
  }
1205
- logger.log(`Restoring build files from ${versionCount} release${versionCount > 1 ? "s" : ""} (${totalAssets} assets) [${versionSizes.join(", ")}]...`);
1329
+ await assetManager.restoreOldAssetsToPublic(buildId, publicDir, assets, isExistingVersion);
1206
1330
  }
1207
- await assetManager.restoreOldAssetsToPublic(buildId, publicDir, assets, isExistingVersion);
1208
1331
  const serverDir = nitro.options.output.serverDir;
1209
1332
  await assetManager.augmentBuildMetadata(buildId, publicDir, serverDir);
1210
1333
  });
@@ -1226,6 +1349,7 @@ export {}
1226
1349
  const errors = result.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join(", ");
1227
1350
  throw new Error(`${adapter.name} adapter config invalid: ${errors}`);
1228
1351
  }
1352
+ const publicAdapterConfig = adapter.toPublicConfig(result.data);
1229
1353
  if (adapter.name === "pusher") {
1230
1354
  if (!await tryResolveModule("pusher-js", nuxt.options.rootDir)) {
1231
1355
  const msg = `The pusher adapter requires \`pusher-js\`. Install with: npx nypm add pusher-js`;
@@ -1248,7 +1372,7 @@ export {}
1248
1372
  const template = addTemplate({
1249
1373
  filename: "skew-adapter.mjs",
1250
1374
  getContents: () => `import { subscribe } from 'nuxt-skew-protection/adapters/${adapter.name}/web'
1251
- export const config = ${JSON.stringify(adapter.config)}
1375
+ export const config = ${JSON.stringify(publicAdapterConfig)}
1252
1376
  export { subscribe }`
1253
1377
  });
1254
1378
  nuxt.options.alias["#skew-adapter"] = template.dst;
@@ -1,5 +1,5 @@
1
1
  import type { SkewAdapterFactory } from '../types.js';
2
- import type { AblyAdapterConfig } from './types.js';
2
+ import type { AblyAdapterConfig, AblyClientConfig } from './types.js';
3
3
  export type { AblyAdapterConfig } from './types.js';
4
4
  export { ablyConfigSchema } from './types.js';
5
- export declare const ablyAdapter: SkewAdapterFactory<AblyAdapterConfig>;
5
+ export declare const ablyAdapter: SkewAdapterFactory<AblyAdapterConfig, AblyClientConfig>;
@@ -3,5 +3,11 @@ import { ablyConfigSchema } from "./types.js";
3
3
  export { ablyConfigSchema } from "./types.js";
4
4
  export const ablyAdapter = defineAdapter({
5
5
  name: "ably",
6
- schema: ablyConfigSchema
6
+ schema: ablyConfigSchema,
7
+ toPublicConfig: ({ authUrl, clientId, channel, event }) => ({
8
+ authUrl,
9
+ ...clientId ? { clientId } : {},
10
+ ...channel ? { channel } : {},
11
+ ...event ? { event } : {}
12
+ })
7
13
  });
@@ -1,5 +1,7 @@
1
1
  export declare const broadcast: import("../types.js").BroadcastFn<{
2
2
  key: string;
3
+ authUrl: string;
4
+ clientId?: string | undefined;
3
5
  channel?: string | undefined;
4
6
  event?: string | undefined;
5
7
  }>;
@@ -1,7 +1,10 @@
1
1
  import { z } from 'zod';
2
2
  export declare const ablyConfigSchema: z.ZodObject<{
3
3
  key: z.ZodString;
4
+ authUrl: z.ZodString;
5
+ clientId: z.ZodOptional<z.ZodString>;
4
6
  channel: z.ZodOptional<z.ZodString>;
5
7
  event: z.ZodOptional<z.ZodString>;
6
8
  }, z.core.$strip>;
7
9
  export type AblyAdapterConfig = z.infer<typeof ablyConfigSchema>;
10
+ export type AblyClientConfig = Pick<AblyAdapterConfig, 'authUrl' | 'clientId' | 'channel' | 'event'>;
@@ -1,6 +1,8 @@
1
1
  import { z } from "zod";
2
2
  export const ablyConfigSchema = z.object({
3
3
  key: z.string().min(1, "Ably key is required"),
4
+ authUrl: z.string().min(1, "Ably authUrl is required"),
5
+ clientId: z.string().optional(),
4
6
  channel: z.string().optional(),
5
7
  event: z.string().optional()
6
8
  });
@@ -1,5 +1,2 @@
1
- export declare const subscribe: import("../types.js").SubscribeFn<{
2
- key: string;
3
- channel?: string | undefined;
4
- event?: string | undefined;
5
- }>;
1
+ import type { AblyClientConfig } from './types.js';
2
+ export declare const subscribe: import("../types.js").SubscribeFn<AblyClientConfig>;
@@ -5,7 +5,7 @@ export const subscribe = defineWebSubscribe((config, onMessage) => {
5
5
  let cleanup;
6
6
  onNuxtReady(async () => {
7
7
  const { Realtime } = await import("ably");
8
- const ably = new Realtime({ key: config.key });
8
+ const ably = new Realtime({ authUrl: config.authUrl, clientId: config.clientId });
9
9
  const channelName = config.channel || SKEW_DEFAULT_CHANNEL;
10
10
  const eventName = config.event || SKEW_MESSAGE_TYPE.VERSION;
11
11
  const channel = ably.channels.get(channelName);
@@ -1,3 +1,3 @@
1
1
  export function isSkewAdapter(value) {
2
- return typeof value === "object" && value !== null && "name" in value && "subscribe" in value && "broadcast" in value && typeof value.subscribe === "function" && typeof value.broadcast === "function";
2
+ return typeof value === "object" && value !== null && "name" in value && "toPublicConfig" in value && "subscribe" in value && "broadcast" in value && typeof value.toPublicConfig === "function" && typeof value.subscribe === "function" && typeof value.broadcast === "function";
3
3
  }
@@ -1,5 +1,5 @@
1
1
  import type { SkewAdapterFactory } from '../types.js';
2
- import type { PusherAdapterConfig } from './types.js';
2
+ import type { PusherAdapterConfig, PusherClientConfig } from './types.js';
3
3
  export type { PusherAdapterConfig } from './types.js';
4
4
  export { pusherConfigSchema } from './types.js';
5
- export declare const pusherAdapter: SkewAdapterFactory<PusherAdapterConfig>;
5
+ export declare const pusherAdapter: SkewAdapterFactory<PusherAdapterConfig, PusherClientConfig>;
@@ -3,5 +3,11 @@ import { pusherConfigSchema } from "./types.js";
3
3
  export { pusherConfigSchema } from "./types.js";
4
4
  export const pusherAdapter = defineAdapter({
5
5
  name: "pusher",
6
- schema: pusherConfigSchema
6
+ schema: pusherConfigSchema,
7
+ toPublicConfig: ({ key, cluster, channel, event }) => ({
8
+ key,
9
+ cluster,
10
+ ...channel ? { channel } : {},
11
+ ...event ? { event } : {}
12
+ })
7
13
  });
@@ -8,3 +8,4 @@ export declare const pusherConfigSchema: z.ZodObject<{
8
8
  event: z.ZodOptional<z.ZodString>;
9
9
  }, z.core.$strip>;
10
10
  export type PusherAdapterConfig = z.infer<typeof pusherConfigSchema>;
11
+ export type PusherClientConfig = Pick<PusherAdapterConfig, 'key' | 'cluster' | 'channel' | 'event'>;
@@ -1,8 +1,2 @@
1
- export declare const subscribe: import("../types.js").SubscribeFn<{
2
- key: string;
3
- cluster: string;
4
- appId: string;
5
- secret: string;
6
- channel?: string | undefined;
7
- event?: string | undefined;
8
- }>;
1
+ import type { PusherClientConfig } from './types.js';
2
+ export declare const subscribe: import("../types.js").SubscribeFn<PusherClientConfig>;
@@ -1,22 +1,24 @@
1
1
  import type { z } from 'zod';
2
- export interface SkewAdapter<TConfig = unknown> {
2
+ export interface SkewAdapter<TConfig = unknown, TPublicConfig extends Record<string, unknown> = Record<string, unknown>> {
3
3
  name: string;
4
4
  config: TConfig;
5
5
  schema: z.ZodType<TConfig>;
6
+ toPublicConfig: (config: TConfig) => TPublicConfig;
6
7
  subscribe: (onMessage: (msg: {
7
8
  version: string;
8
9
  }) => void) => () => void;
9
10
  broadcast: (version: string) => Promise<void>;
10
11
  }
11
- export type SkewAdapterFactory<T> = (config: T) => SkewAdapter<T>;
12
- export interface DefineAdapterOptions<T> {
12
+ export type SkewAdapterFactory<TConfig, TPublicConfig extends Record<string, unknown> = Record<string, unknown>> = (config: TConfig) => SkewAdapter<TConfig, TPublicConfig>;
13
+ export interface DefineAdapterOptions<TConfig, TPublicConfig extends Record<string, unknown>> {
13
14
  name: string;
14
- schema: z.ZodType<T>;
15
+ schema: z.ZodType<TConfig>;
16
+ toPublicConfig: (config: TConfig) => TPublicConfig;
15
17
  }
16
18
  export type BroadcastFn<T> = (config: T, version: string) => Promise<void>;
17
19
  export type SubscribeFn<T> = (config: T, onMessage: (msg: {
18
20
  version: string;
19
21
  }) => void) => () => void;
20
- export declare function defineAdapter<T>(options: DefineAdapterOptions<T>): SkewAdapterFactory<T>;
22
+ export declare function defineAdapter<TConfig, TPublicConfig extends Record<string, unknown>>(options: DefineAdapterOptions<TConfig, TPublicConfig>): SkewAdapterFactory<TConfig, TPublicConfig>;
21
23
  export declare const defineNodeBroadcast: <T>(broadcast: BroadcastFn<T>) => BroadcastFn<T>;
22
24
  export declare const defineWebSubscribe: <T>(subscribe: SubscribeFn<T>) => SubscribeFn<T>;
@@ -3,6 +3,7 @@ export function defineAdapter(options) {
3
3
  name: options.name,
4
4
  config,
5
5
  schema: options.schema,
6
+ toPublicConfig: options.toPublicConfig,
6
7
  subscribe: () => {
7
8
  throw new Error(`${options.name}.subscribe() - use web build`);
8
9
  },
@@ -1,5 +1,6 @@
1
1
  import { defineNuxtPlugin } from "nuxt/app";
2
2
  import { logger } from "../../shared/logger.js";
3
+ import { useRuntimeConfigSkewProtection } from "../composables/useRuntimeConfigSkewProtection.js";
3
4
  import { useSkewProtection } from "../composables/useSkewProtection.js";
4
5
  const RE_LEADING_SLASH = /^\//;
5
6
  function normalizePath(pathOrUrl) {
@@ -19,9 +20,15 @@ export default defineNuxtPlugin({
19
20
  logger.debug("[SW] Service Worker not supported in this browser");
20
21
  return;
21
22
  }
23
+ const { assetRecovery } = useRuntimeConfigSkewProtection();
22
24
  const { clientVersion, onAppOutdated } = useSkewProtection();
23
25
  logger.debug("[SW] Initializing service worker tracking");
24
- const swRegistration = navigator.serviceWorker.register("/_nuxt-skew-sw.js");
26
+ const serviceWorkerUrl = new URL("/_nuxt-skew-sw.js", window.location.origin);
27
+ if (assetRecovery._tag === "cloudflare") {
28
+ serviceWorkerUrl.searchParams.set("buildAssetsPath", assetRecovery.buildAssetsPath);
29
+ serviceWorkerUrl.searchParams.set("recoveryPath", assetRecovery.recoveryPath);
30
+ }
31
+ const swRegistration = navigator.serviceWorker.register(serviceWorkerUrl.href);
25
32
  swRegistration.then((registration) => {
26
33
  logger.debug("[SW] Service worker registered successfully");
27
34
  const sw = registration.active || registration.installing || registration.waiting;
@@ -24,5 +24,5 @@ export interface SkewConnection {
24
24
  sendRoute: (route: string) => void;
25
25
  subscribeStats: () => void;
26
26
  buildId: string;
27
- cookie: Ref<string | null | undefined>;
27
+ cookie?: Ref<string | null | undefined>;
28
28
  }
@@ -11,8 +11,10 @@ export function createSkewConnection(config) {
11
11
  const { isBot } = useBotDetection();
12
12
  const basePath = runtimeConfig.public.skewProtection.basePath || "/__skew";
13
13
  const cookieConfig = runtimeConfig.public.skewProtection.cookie;
14
- const { name: cookieName, ...cookieOpts } = cookieConfig;
15
- const cookie = useCookie(cookieName, { ...cookieOpts, readonly: false });
14
+ const cookie = cookieConfig === false ? void 0 : (() => {
15
+ const { name: cookieName, ...cookieOpts } = cookieConfig;
16
+ return useCookie(cookieName, { ...cookieOpts, readonly: false });
17
+ })();
16
18
  if (isBot.value) {
17
19
  logger.debug(`[${name}] Skipping connection for bot`);
18
20
  return { connect: () => {
@@ -22,7 +24,7 @@ export function createSkewConnection(config) {
22
24
  }, subscribeStats: () => {
23
25
  }, buildId, cookie };
24
26
  }
25
- if (import.meta.client && !cookie.value) {
27
+ if (import.meta.client && cookie && !cookie.value) {
26
28
  cookie.value = buildId;
27
29
  }
28
30
  let cleanup;
@@ -3,9 +3,9 @@ import type { SkewProtectionEvent } from './getRuntimeConfigSkewProtection.js';
3
3
  * Get the skew protection version cookie name from runtime config
4
4
  *
5
5
  * @param event - H3 event (optional, for better type safety)
6
- * @returns The configured cookie name
6
+ * @returns The configured cookie name, or undefined when cookies are disabled
7
7
  */
8
- export declare function getSkewProtectionCookieName(event?: SkewProtectionEvent): string;
8
+ export declare function getSkewProtectionCookieName(event?: SkewProtectionEvent): string | undefined;
9
9
  /**
10
10
  * Get the skew protection version cookie value
11
11
  *
@@ -2,14 +2,18 @@ import { getCookie, setCookie } from "#nuxtseo/h3";
2
2
  import { getRuntimeConfigSkewProtection } from "./getRuntimeConfigSkewProtection.js";
3
3
  export function getSkewProtectionCookieName(event) {
4
4
  const { cookie } = getRuntimeConfigSkewProtection(event);
5
- return cookie.name;
5
+ return cookie === false ? void 0 : cookie.name;
6
6
  }
7
7
  export function getSkewProtectionCookie(event) {
8
8
  const cookieName = getSkewProtectionCookieName(event);
9
+ if (!cookieName)
10
+ return void 0;
9
11
  return getCookie(event, cookieName);
10
12
  }
11
13
  export function setSkewProtectionCookie(event, value) {
12
14
  const { cookie: cookieConfig } = getRuntimeConfigSkewProtection(event);
15
+ if (cookieConfig === false)
16
+ return;
13
17
  const { name: cookieName, ...cookieOptions } = cookieConfig;
14
18
  setCookie(event, cookieName, value, cookieOptions);
15
19
  }
@@ -1,4 +1,6 @@
1
1
  import { defineEventHandler, getHeader, setCookie } from "#nuxtseo/h3";
2
+ import { useRuntimeConfig } from "#nuxtseo/nitro";
3
+ import { resolveVercelCookiePath } from "../utils/vercel-cookie-path.js";
2
4
  export default defineEventHandler(async (event) => {
3
5
  const secFetchDest = getHeader(event, "sec-fetch-dest");
4
6
  if (secFetchDest !== "document") {
@@ -8,8 +10,9 @@ export default defineEventHandler(async (event) => {
8
10
  if (!deploymentId) {
9
11
  return;
10
12
  }
13
+ const { skewProtection } = useRuntimeConfig(event);
11
14
  setCookie(event, "__vdpl", deploymentId, {
12
- path: "/",
15
+ path: resolveVercelCookiePath(skewProtection),
13
16
  sameSite: "lax",
14
17
  secure: true,
15
18
  httpOnly: true
@@ -41,11 +41,9 @@ export default defineEventHandler(async (event) => {
41
41
  return;
42
42
  cleanupDone = true;
43
43
  clearTimeout(keepaliveTimeout);
44
- process.off("SIGTERM", close);
45
44
  await nitroApp.hooks.callHook("skew:connection:close", { id: connectionId });
46
45
  await stream.close();
47
46
  };
48
47
  stream.onClosed(close);
49
- process.on("SIGTERM", close);
50
48
  return stream.send();
51
49
  });
@@ -15,7 +15,7 @@ export default defineWebSocketHandler({
15
15
  }));
16
16
  const cookieHeader = peer.request?.headers?.get("cookie") || "";
17
17
  const cookies = parseCookie(cookieHeader);
18
- const clientVersion = cookies[cookieName] || serverVersion;
18
+ const clientVersion = (cookieName ? cookies[cookieName] : void 0) || serverVersion;
19
19
  const url = new URL(peer.request?.url || "", "http://localhost");
20
20
  const initialRoute = url.searchParams.get("route") || "/";
21
21
  const forwarded = peer.request?.headers?.get("x-forwarded-for");
@@ -2,5 +2,5 @@ interface CloudflareAssetBinding {
2
2
  fetch: (request: Request) => Promise<Response>;
3
3
  }
4
4
  export declare function fetchCloudflareAsset(request: Request, assets: CloudflareAssetBinding): Promise<Response>;
5
- export declare function fetchCloudflareBuildAsset(request: Request, assets: CloudflareAssetBinding | undefined, buildAssetsDir: string): Promise<Response> | undefined;
5
+ export declare function fetchCloudflareBuildAsset(request: Request, assets: CloudflareAssetBinding | undefined, buildAssetsPath: string, recoveryPath: string): Promise<Response> | undefined;
6
6
  export {};
@@ -12,23 +12,60 @@ function disableCaching(response) {
12
12
  function createRetryRequest(request) {
13
13
  return new Request(request, { cache: "no-cache" });
14
14
  }
15
+ function protectMutableAsset(request, response) {
16
+ return new URL(request.url).pathname.endsWith("/builds/latest.json") ? disableCaching(response) : response;
17
+ }
18
+ function parseBuildAssetRequest(request, buildAssetsPath, recoveryPath) {
19
+ const requestUrl = new URL(request.url);
20
+ if (requestUrl.pathname.startsWith(buildAssetsPath)) {
21
+ return { _tag: "asset", request };
22
+ }
23
+ if (requestUrl.pathname !== recoveryPath) {
24
+ return { _tag: "unmatched" };
25
+ }
26
+ if (request.method !== "GET") {
27
+ return { _tag: "invalid-recovery" };
28
+ }
29
+ const target = requestUrl.searchParams.get("url");
30
+ if (!target) {
31
+ return { _tag: "invalid-recovery" };
32
+ }
33
+ if (!URL.canParse(target, requestUrl)) {
34
+ return { _tag: "invalid-recovery" };
35
+ }
36
+ const targetUrl = new URL(target, requestUrl);
37
+ if (targetUrl.origin !== requestUrl.origin || !targetUrl.pathname.startsWith(buildAssetsPath) || targetUrl.username || targetUrl.password) {
38
+ return { _tag: "invalid-recovery" };
39
+ }
40
+ return {
41
+ _tag: "asset",
42
+ request: new Request(targetUrl, {
43
+ cache: "no-cache",
44
+ headers: request.headers
45
+ })
46
+ };
47
+ }
15
48
  export async function fetchCloudflareAsset(request, assets) {
16
49
  const response = await assets.fetch(request);
17
50
  if (response.status < 400) {
18
- return response;
51
+ return protectMutableAsset(request, response);
19
52
  }
20
53
  if (response.status !== 404) {
21
54
  return disableCaching(response);
22
55
  }
23
56
  const retryResponse = await assets.fetch(createRetryRequest(request));
24
- return retryResponse.status < 400 ? retryResponse : disableCaching(retryResponse);
57
+ return retryResponse.status < 400 ? protectMutableAsset(request, retryResponse) : disableCaching(retryResponse);
25
58
  }
26
- export function fetchCloudflareBuildAsset(request, assets, buildAssetsDir) {
27
- if (!new URL(request.url).pathname.startsWith(buildAssetsDir)) {
28
- return void 0;
59
+ export function fetchCloudflareBuildAsset(request, assets, buildAssetsPath, recoveryPath) {
60
+ const parsed = parseBuildAssetRequest(request, buildAssetsPath, recoveryPath);
61
+ if (parsed._tag === "unmatched") {
62
+ return;
63
+ }
64
+ if (parsed._tag === "invalid-recovery") {
65
+ return Promise.resolve(disableCaching(new Response(null, { status: 400 })));
29
66
  }
30
67
  if (!assets) {
31
68
  return Promise.resolve(disableCaching(new Response(null, { status: 404 })));
32
69
  }
33
- return fetchCloudflareAsset(request, assets);
70
+ return fetchCloudflareAsset(parsed.request, assets);
34
71
  }
@@ -0,0 +1,2 @@
1
+ import type { NuxtSkewProtectionPrivateRuntimeConfig } from '../../types.js';
2
+ export declare function resolveVercelCookiePath(config?: NuxtSkewProtectionPrivateRuntimeConfig): string;
@@ -0,0 +1,3 @@
1
+ export function resolveVercelCookiePath(config) {
2
+ return config?.vercelCookiePath || "/";
3
+ }
@@ -1,4 +1,14 @@
1
1
  import type { CookieSerializeOptions } from 'cookie-es';
2
+ export type AssetRecoveryConfig = {
3
+ _tag: 'disabled';
4
+ } | {
5
+ _tag: 'cloudflare';
6
+ buildAssetsPath: string;
7
+ recoveryPath: string;
8
+ };
9
+ export interface NuxtSkewProtectionPrivateRuntimeConfig {
10
+ vercelCookiePath?: string;
11
+ }
2
12
  export interface NuxtSkewProtectionRuntimeConfig {
3
13
  /**
4
14
  * Path prefix for the module's runtime endpoints (`/ws`, `/sse`, `/health`,
@@ -7,7 +17,8 @@ export interface NuxtSkewProtectionRuntimeConfig {
7
17
  * that only owns part of the host, so the endpoints resolve to this app.
8
18
  */
9
19
  basePath: string;
10
- cookie: Omit<CookieSerializeOptions, 'encode'> & {
20
+ assetRecovery: AssetRecoveryConfig;
21
+ cookie: false | Omit<CookieSerializeOptions, 'encode'> & {
11
22
  name?: string;
12
23
  };
13
24
  debug: boolean;
@@ -19,7 +30,8 @@ export interface NuxtSkewProtectionRuntimeConfig {
19
30
  }
20
31
  export interface SkewProtectionRuntimeConfig {
21
32
  basePath: string;
22
- cookie: Omit<CookieSerializeOptions, 'encode'> & {
33
+ assetRecovery: AssetRecoveryConfig;
34
+ cookie: false | Omit<CookieSerializeOptions, 'encode'> & {
23
35
  name: string;
24
36
  };
25
37
  debug: boolean;
@@ -1 +1 @@
1
- const loadedModules=new Set;self.addEventListener("activate",e=>{e.waitUntil(self.clients.claim())}),self.addEventListener("fetch",e=>{const t=e.request.url;(e.request.destination==="script"||t.endsWith(".js"))&&(loadedModules.add(t),e.waitUntil(self.clients.matchAll().then(a=>{a.forEach(s=>{s.postMessage({type:"MODULE_LOADED",url:t,modules:Array.from(loadedModules)})})})))}),self.addEventListener("message",e=>{if(e.data.type==="GET_MODULES"){const t=Array.from(loadedModules);e.source.postMessage({type:"MODULES_LIST",modules:t})}if(e.data.type==="CHECK_MODULE"){const t=loadedModules.has(e.data.url);e.source.postMessage({type:"MODULE_STATUS",url:e.data.url,loaded:t})}e.data.type==="RESET_MODULES"&&(loadedModules.clear(),e.source.postMessage({type:"MODULES_RESET",success:!0})),e.data.type==="ADD_MODULE"&&loadedModules.add(e.data.url)});
1
+ const loadedModules=new Set,serviceWorkerUrl=new URL(globalThis.location.href),buildAssetsPath=serviceWorkerUrl.searchParams.get("buildAssetsPath"),recoveryPath=serviceWorkerUrl.searchParams.get("recoveryPath");function isRecoverableBuildAsset(e){if(!buildAssetsPath||!recoveryPath||e.method!=="GET")return!1;const t=new URL(e.url);return t.origin===globalThis.location.origin&&t.pathname.startsWith(buildAssetsPath)}function withoutResponseUrl(e){return new Response(e.body,{status:e.status,statusText:e.statusText,headers:e.headers})}async function fetchBuildAsset(e){const t=await fetch(e);if(t.status!==404)return t;const a=new URL(recoveryPath,e.url);a.searchParams.set("url",e.url);const s=new Request(a,{cache:"no-cache",headers:e.headers});return withoutResponseUrl(await fetch(s))}self.addEventListener("activate",e=>{e.waitUntil(self.clients.claim())}),self.addEventListener("fetch",e=>{const t=e.request.url;isRecoverableBuildAsset(e.request)&&e.respondWith(fetchBuildAsset(e.request)),(e.request.destination==="script"||t.endsWith(".js"))&&(loadedModules.add(t),e.waitUntil(self.clients.matchAll().then(a=>{a.forEach(s=>{s.postMessage({type:"MODULE_LOADED",url:t,modules:Array.from(loadedModules)})})})))}),self.addEventListener("message",e=>{if(e.data.type==="GET_MODULES"){const t=Array.from(loadedModules);e.source.postMessage({type:"MODULES_LIST",modules:t})}if(e.data.type==="CHECK_MODULE"){const t=loadedModules.has(e.data.url);e.source.postMessage({type:"MODULE_STATUS",url:e.data.url,loaded:t})}e.data.type==="RESET_MODULES"&&(loadedModules.clear(),e.source.postMessage({type:"MODULES_RESET",success:!0})),e.data.type==="ADD_MODULE"&&loadedModules.add(e.data.url)});
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nuxt-skew-protection",
3
3
  "type": "module",
4
- "version": "1.4.3",
4
+ "version": "1.5.0",
5
5
  "description": "Solve Nuxt version skews with persistent assets and instant updates.",
6
6
  "author": {
7
7
  "name": "Harlan Wilton",
@@ -81,8 +81,8 @@
81
81
  "@vueuse/core": "^14.4.0",
82
82
  "consola": "^3.4.2",
83
83
  "cookie-es": "^3.1.1",
84
- "nuxt-site-config": "^4.2.0",
85
- "nuxtseo-shared": "^5.3.11",
84
+ "nuxt-site-config": "^4.2.2",
85
+ "nuxtseo-shared": "^5.3.12",
86
86
  "ofetch": "^1.5.1",
87
87
  "pathe": "^2.0.3",
88
88
  "pkg-types": "^2.3.1",
@@ -98,28 +98,28 @@
98
98
  "@nuxt/ui": "^4.10.0",
99
99
  "@nuxtjs/robots": "^6.1.4",
100
100
  "@types/ws": "^8.18.1",
101
- "ably": "^2.26.0",
101
+ "ably": "^2.27.0",
102
102
  "better-sqlite3": "^13.0.3",
103
103
  "bumpp": "^12.2.0",
104
104
  "eslint": "^10.8.1",
105
105
  "eslint-plugin-harlanzw": "^0.17.1",
106
- "eventsource": "^4.1.1",
106
+ "eventsource": "^5.0.0",
107
107
  "happy-dom": "^20.11.2",
108
108
  "ioredis": "^6.0.0",
109
109
  "nuxt": "^4.5.2",
110
110
  "nuxt-auth-utils": "^0.5.30",
111
- "nuxtseo-layer-devtools": "^5.3.10",
111
+ "nuxtseo-layer-devtools": "^5.3.12",
112
112
  "playwright-core": "^1.62.1",
113
113
  "pusher-js": "^8.6.0",
114
114
  "std-env": "^4.2.0",
115
- "tsx": "^4.23.11",
115
+ "tsx": "^4.23.12",
116
116
  "typescript": "6.0.3",
117
117
  "unbuild": "^3.6.1",
118
118
  "vitest": "^4.1.10",
119
119
  "vue": "^3.5.41",
120
120
  "vue-router": "^5.2.0",
121
121
  "vue-tsc": "^3.3.9",
122
- "wrangler": "^4.120.0",
122
+ "wrangler": "^4.121.0",
123
123
  "ws": "^8.21.3"
124
124
  },
125
125
  "resolutions": {