nuxt-skew-protection 1.4.4 → 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.
- package/dist/module.d.mts +2 -2
- package/dist/module.json +1 -1
- package/dist/module.mjs +280 -187
- package/dist/runtime/adapters/ably/index.d.ts +2 -2
- package/dist/runtime/adapters/ably/index.js +7 -1
- package/dist/runtime/adapters/ably/node.d.ts +2 -0
- package/dist/runtime/adapters/ably/types.d.ts +3 -0
- package/dist/runtime/adapters/ably/types.js +2 -0
- package/dist/runtime/adapters/ably/web.d.ts +2 -5
- package/dist/runtime/adapters/ably/web.js +1 -1
- package/dist/runtime/adapters/index.js +1 -1
- package/dist/runtime/adapters/pusher/index.d.ts +2 -2
- package/dist/runtime/adapters/pusher/index.js +7 -1
- package/dist/runtime/adapters/pusher/types.d.ts +1 -0
- package/dist/runtime/adapters/pusher/web.d.ts +2 -8
- package/dist/runtime/adapters/types.d.ts +7 -5
- package/dist/runtime/adapters/types.js +1 -0
- package/dist/runtime/app/types.d.ts +1 -1
- package/dist/runtime/app/utils/create-skew-connection.js +5 -3
- package/dist/runtime/server/imports/cookie.d.ts +2 -2
- package/dist/runtime/server/imports/cookie.js +5 -1
- package/dist/runtime/server/middleware/vercel-skew.js +4 -1
- package/dist/runtime/server/routes/__skew/sse.js +0 -2
- package/dist/runtime/server/routes/__skew/ws.js +1 -1
- package/dist/runtime/server/utils/cloudflare-asset-fetch.js +5 -2
- package/dist/runtime/server/utils/vercel-cookie-path.d.ts +2 -0
- package/dist/runtime/server/utils/vercel-cookie-path.js +3 -0
- package/dist/runtime/types.d.ts +5 -2
- 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
package/dist/module.mjs
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
|
-
import {
|
|
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,6 +15,25 @@ 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) {
|
|
@@ -49,145 +69,214 @@ function resolveCookieName(explicitName, basePath) {
|
|
|
49
69
|
return slug ? `${DEFAULT_COOKIE_NAME}_${slug}` : DEFAULT_COOKIE_NAME;
|
|
50
70
|
}
|
|
51
71
|
|
|
52
|
-
const
|
|
53
|
-
const
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
}
|
|
57
|
-
const
|
|
58
|
-
const
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
stderr:
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
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 });
|
|
71
130
|
}
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
return null;
|
|
85
|
-
}
|
|
86
|
-
return JSON.parse(result.stdout);
|
|
87
|
-
},
|
|
88
|
-
async getItemRaw(key) {
|
|
89
|
-
const prefixedKey = prefixKey(key);
|
|
90
|
-
const result = await execWrangler(`wrangler kv key get "${prefixedKey}" --namespace-id="${namespaceId}" ${locationFlag}`);
|
|
91
|
-
return Buffer.from(result.stdout, "utf-8");
|
|
92
|
-
},
|
|
93
|
-
async setItem(key, value) {
|
|
94
|
-
const prefixedKey = prefixKey(key);
|
|
95
|
-
const tmpFile = join(tmpdir(), `kv-${Date.now()}-${Math.random().toString(36).substring(7)}.json`);
|
|
96
|
-
writeFileSync(tmpFile, JSON.stringify(value));
|
|
97
|
-
try {
|
|
98
|
-
await execWrangler(`wrangler kv key put "${prefixedKey}" --path="${tmpFile}" --namespace-id="${namespaceId}" ${locationFlag}`);
|
|
99
|
-
} finally {
|
|
100
|
-
unlinkSync(tmpFile);
|
|
101
|
-
}
|
|
102
|
-
},
|
|
103
|
-
async setItemRaw(key, value) {
|
|
104
|
-
const prefixedKey = prefixKey(key);
|
|
105
|
-
const tmpFile = join(tmpdir(), `kv-${Date.now()}.bin`);
|
|
106
|
-
writeFileSync(tmpFile, value);
|
|
107
|
-
try {
|
|
108
|
-
await execWrangler(`wrangler kv key put "${prefixedKey}" --path="${tmpFile}" --namespace-id="${namespaceId}" ${locationFlag}`);
|
|
109
|
-
} finally {
|
|
110
|
-
unlinkSync(tmpFile);
|
|
111
|
-
}
|
|
112
|
-
},
|
|
113
|
-
async removeItem(key) {
|
|
114
|
-
const prefixedKey = prefixKey(key);
|
|
115
|
-
await execWrangler(`wrangler kv key delete "${prefixedKey}" --namespace-id="${namespaceId}" ${locationFlag}`);
|
|
116
|
-
},
|
|
117
|
-
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) => {
|
|
118
143
|
const fullPrefix = base ? basePrefix ? `${base}${basePrefix}` : base : basePrefix;
|
|
119
|
-
const
|
|
120
|
-
const result = await
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
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() {
|
|
128
189
|
}
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
return driver;
|
|
134
|
-
});
|
|
190
|
+
};
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
const cloudflareKVWranglerDriver = createCloudflareKVWranglerDriver();
|
|
135
194
|
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
if (
|
|
147
|
-
|
|
148
|
-
}
|
|
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}.`);
|
|
149
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;
|
|
150
240
|
const rootDir = nuxt.options.rootDir || process.cwd();
|
|
151
|
-
const
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
if (skewMatch?.[1]) {
|
|
163
|
-
return skewMatch[1];
|
|
164
|
-
}
|
|
165
|
-
const kvNamespaceMatch = content.match(RE_KV_NAMESPACE);
|
|
166
|
-
if (kvNamespaceMatch?.[1]) {
|
|
167
|
-
return kvNamespaceMatch[1];
|
|
168
|
-
}
|
|
169
|
-
} 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;
|
|
170
252
|
}
|
|
171
253
|
}
|
|
172
254
|
return null;
|
|
173
255
|
}
|
|
174
256
|
async function resolveBuildTimeDriver(storage) {
|
|
175
|
-
const {
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
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
|
+
);
|
|
188
271
|
}
|
|
272
|
+
const kvBase = typeof base === "string" && !base.includes("/") ? base : "skew-protection:";
|
|
273
|
+
return cloudflareKVWranglerDriver({
|
|
274
|
+
...driverOptions,
|
|
275
|
+
namespaceId,
|
|
276
|
+
base: kvBase
|
|
277
|
+
});
|
|
189
278
|
}
|
|
190
|
-
const lazyDriver = await import(`unstorage/drivers/${
|
|
279
|
+
const lazyDriver = await import(`unstorage/drivers/${driver}`).then((module) => module.default);
|
|
191
280
|
return lazyDriver({ base, ...driverOptions });
|
|
192
281
|
}
|
|
193
282
|
|
|
@@ -425,6 +514,7 @@ function createAssetManager(options) {
|
|
|
425
514
|
const maxNumberOfVersions = options.maxNumberOfVersions || 20;
|
|
426
515
|
const buildAssetsDir = (options.buildAssetsDir || "/_nuxt/").replace(/^\/+|\/+$/g, "");
|
|
427
516
|
const buildAssetsPath = `/${buildAssetsDir}`;
|
|
517
|
+
const persistAssets = options.persistAssets !== false;
|
|
428
518
|
async function getAssetsFromBuild(publicDir) {
|
|
429
519
|
const startTime = Date.now();
|
|
430
520
|
const nuxtDir = join$1(publicDir, buildAssetsDir);
|
|
@@ -435,6 +525,9 @@ function createAssetManager(options) {
|
|
|
435
525
|
const relativePath = file.replace(nuxtDir, "");
|
|
436
526
|
assets.push(`${buildAssetsDir}${relativePath}`);
|
|
437
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
|
+
}
|
|
438
531
|
logger.debug(`Found ${assets.length} assets in ${formatDuration(Date.now() - startTime)}`);
|
|
439
532
|
return assets;
|
|
440
533
|
}
|
|
@@ -447,15 +540,17 @@ function createAssetManager(options) {
|
|
|
447
540
|
const manifest = await getVersionManifest(storage);
|
|
448
541
|
logger.debug(`updateVersionsManifest: loaded manifest in ${formatDuration(Date.now() - manifestStart)} (${Object.keys(manifest.versions).length} versions)`);
|
|
449
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 || [];
|
|
450
546
|
manifest.current = buildId;
|
|
451
547
|
manifest.versions[buildId] = {
|
|
452
548
|
timestamp: now.toISOString(),
|
|
453
549
|
expires: expires.toISOString(),
|
|
454
|
-
assets,
|
|
550
|
+
assets: persistAssets ? [...assets] : [],
|
|
455
551
|
// Store original assets for deletedChunks calculation (assets array gets modified by deduplication)
|
|
456
552
|
originalAssets: [...assets],
|
|
457
|
-
|
|
458
|
-
deletedChunks: []
|
|
553
|
+
deletedChunks: calculateDeletedChunks(assets, previousAssets)
|
|
459
554
|
};
|
|
460
555
|
const saveStart = Date.now();
|
|
461
556
|
await setVersionManifest(manifest, storage);
|
|
@@ -543,14 +638,6 @@ function createAssetManager(options) {
|
|
|
543
638
|
const fileIdToVersion = manifest.fileIdToVersion;
|
|
544
639
|
const existingFileIds = Object.keys(fileIdToVersion).length;
|
|
545
640
|
logger.debug(`storeAssetsInStorage: fileIdToVersion has ${existingFileIds} entries`);
|
|
546
|
-
const currentVersion = manifest.versions[buildId];
|
|
547
|
-
if (currentVersion) {
|
|
548
|
-
const previousVersionId = getPreviousVersion(manifest, buildId);
|
|
549
|
-
const previousVersion = previousVersionId ? manifest.versions[previousVersionId] : null;
|
|
550
|
-
const previousAssets = previousVersion?.originalAssets || previousVersion?.assets || [];
|
|
551
|
-
currentVersion.deletedChunks = calculateDeletedChunks(assets, previousAssets);
|
|
552
|
-
logger.debug(`storeAssetsInStorage: calculated ${currentVersion.deletedChunks.length} deleted chunks vs ${previousVersionId || "none"}`);
|
|
553
|
-
}
|
|
554
641
|
let storedCount = 0;
|
|
555
642
|
let deduplicatedCount = 0;
|
|
556
643
|
let totalBytes = 0;
|
|
@@ -570,9 +657,7 @@ function createAssetManager(options) {
|
|
|
570
657
|
if (assetData) {
|
|
571
658
|
totalBytes += assetData.byteLength;
|
|
572
659
|
const storageKey = `${buildId}/${asset}`;
|
|
573
|
-
await storage.setItemRaw(storageKey, assetData)
|
|
574
|
-
logger.error(`Failed to store ${storageKey}:`, error?.message || error);
|
|
575
|
-
});
|
|
660
|
+
await storage.setItemRaw(storageKey, assetData);
|
|
576
661
|
storedCount++;
|
|
577
662
|
if (fileId && fileIdToVersion[fileId] && fileIdToVersion[fileId] !== buildId) {
|
|
578
663
|
const previousVersionId = fileIdToVersion[fileId];
|
|
@@ -671,7 +756,6 @@ function createAssetManager(options) {
|
|
|
671
756
|
}
|
|
672
757
|
const restoreStart = Date.now();
|
|
673
758
|
let totalBytes = 0;
|
|
674
|
-
let failedCount = 0;
|
|
675
759
|
const createdDirs = /* @__PURE__ */ new Set();
|
|
676
760
|
const batchResults = await processBatch(assetTasks, 25, async ({ versionId, asset, versionData }) => {
|
|
677
761
|
const storageKey = `${versionId}/${asset}`;
|
|
@@ -701,17 +785,16 @@ function createAssetManager(options) {
|
|
|
701
785
|
age: formatAge(versionTimestamp, now)
|
|
702
786
|
};
|
|
703
787
|
}
|
|
704
|
-
|
|
788
|
+
throw new Error(`Stored asset ${storageKey} is missing.`);
|
|
705
789
|
}).catch((error) => {
|
|
706
|
-
if (error.code
|
|
707
|
-
|
|
708
|
-
logger.debug(`Failed to restore asset ${asset} from version ${versionId}: ${error}`);
|
|
790
|
+
if (error.code === "EEXIST") {
|
|
791
|
+
return null;
|
|
709
792
|
}
|
|
710
|
-
|
|
793
|
+
throw error;
|
|
711
794
|
});
|
|
712
795
|
});
|
|
713
796
|
restoredAssets.push(...batchResults.filter((r) => r !== null));
|
|
714
|
-
logger.debug(`restoreOldAssetsToPublic: restored ${restoredAssets.length} assets (${formatBytes(totalBytes)}) in ${formatDuration(Date.now() - restoreStart)}
|
|
797
|
+
logger.debug(`restoreOldAssetsToPublic: restored ${restoredAssets.length} assets (${formatBytes(totalBytes)}) in ${formatDuration(Date.now() - restoreStart)}`);
|
|
715
798
|
const restoredByVersion = /* @__PURE__ */ new Map();
|
|
716
799
|
for (const item of restoredAssets) {
|
|
717
800
|
restoredByVersion.set(item.versionId, (restoredByVersion.get(item.versionId) || 0) + 1);
|
|
@@ -750,9 +833,8 @@ function createAssetManager(options) {
|
|
|
750
833
|
newLatestContent = JSON.stringify(latestJson, null, 2);
|
|
751
834
|
await promises.writeFile(latestPath, newLatestContent, "utf-8");
|
|
752
835
|
} catch (error) {
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
}
|
|
836
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
837
|
+
throw new Error(`Failed to augment builds/latest.json: ${message}`);
|
|
756
838
|
}
|
|
757
839
|
const metaPath = join$1(publicDir, buildAssetsDir, "builds", "meta", `${buildId}.json`);
|
|
758
840
|
try {
|
|
@@ -767,9 +849,8 @@ function createAssetManager(options) {
|
|
|
767
849
|
}
|
|
768
850
|
await promises.writeFile(metaPath, JSON.stringify(metaJson, null, 2), "utf-8");
|
|
769
851
|
} catch (error) {
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
}
|
|
852
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
853
|
+
throw new Error(`Failed to augment builds/meta/${buildId}.json: ${message}`);
|
|
773
854
|
}
|
|
774
855
|
if (serverDir && newLatestContent) {
|
|
775
856
|
await patchNitroManifest(serverDir, `${buildAssetsPath}/builds/latest.json`, newLatestContent);
|
|
@@ -867,7 +948,6 @@ const module$1 = defineNuxtModule({
|
|
|
867
948
|
defaults: {
|
|
868
949
|
retentionDays: 30,
|
|
869
950
|
maxNumberOfVersions: 10,
|
|
870
|
-
bundleAssets: true,
|
|
871
951
|
cookie: {
|
|
872
952
|
// `name` intentionally omitted — derived from the mount point in setup
|
|
873
953
|
// (`resolveCookieName`) so path-routed apps get a distinct cookie. An
|
|
@@ -909,6 +989,11 @@ const module$1 = defineNuxtModule({
|
|
|
909
989
|
options.bundleAssets = rawOptions.bundlePreviousDeploymentChunks;
|
|
910
990
|
}
|
|
911
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
|
+
}
|
|
912
997
|
nuxt.hooks.hook("nuxt-seo-pro:modules", (modules) => {
|
|
913
998
|
const mod = modules.find((m) => m.name === "nuxt-skew-protection");
|
|
914
999
|
if (mod) {
|
|
@@ -1145,6 +1230,10 @@ export {}
|
|
|
1145
1230
|
resolvedStrategy = "polling";
|
|
1146
1231
|
}
|
|
1147
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
|
+
};
|
|
1148
1237
|
addServerHandler({
|
|
1149
1238
|
handler: resolver.resolve("./runtime/server/middleware/vercel-skew"),
|
|
1150
1239
|
middleware: true
|
|
@@ -1191,7 +1280,7 @@ export {}
|
|
|
1191
1280
|
maxAge: 0
|
|
1192
1281
|
// Service workers should not be cached
|
|
1193
1282
|
});
|
|
1194
|
-
if (options.storage
|
|
1283
|
+
if (options.storage) {
|
|
1195
1284
|
nuxt.hook("nitro:init", (nitro) => {
|
|
1196
1285
|
const buildId = nuxt.options.runtimeConfig.app.buildId ||= nuxt.options.buildId;
|
|
1197
1286
|
let assetManager;
|
|
@@ -1200,42 +1289,45 @@ export {}
|
|
|
1200
1289
|
assetManager = createAssetManager({
|
|
1201
1290
|
...options,
|
|
1202
1291
|
buildAssetsDir: nuxt.options.app.buildAssetsDir,
|
|
1292
|
+
persistAssets: options.bundleAssets !== false,
|
|
1203
1293
|
driver: await resolveBuildTimeDriver(options.storage)
|
|
1204
1294
|
});
|
|
1205
1295
|
const assets = await assetManager.getAssetsFromBuild(publicDir);
|
|
1206
1296
|
const { isExistingVersion } = await assetManager.updateVersionsManifest(buildId, assets);
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
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
|
+
}
|
|
1234
1326
|
}
|
|
1327
|
+
logger.log(`Restoring build files from ${versionCount} release${versionCount > 1 ? "s" : ""} (${totalAssets} assets) [${versionSizes.join(", ")}]...`);
|
|
1235
1328
|
}
|
|
1236
|
-
|
|
1329
|
+
await assetManager.restoreOldAssetsToPublic(buildId, publicDir, assets, isExistingVersion);
|
|
1237
1330
|
}
|
|
1238
|
-
await assetManager.restoreOldAssetsToPublic(buildId, publicDir, assets, isExistingVersion);
|
|
1239
1331
|
const serverDir = nitro.options.output.serverDir;
|
|
1240
1332
|
await assetManager.augmentBuildMetadata(buildId, publicDir, serverDir);
|
|
1241
1333
|
});
|
|
@@ -1257,6 +1349,7 @@ export {}
|
|
|
1257
1349
|
const errors = result.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join(", ");
|
|
1258
1350
|
throw new Error(`${adapter.name} adapter config invalid: ${errors}`);
|
|
1259
1351
|
}
|
|
1352
|
+
const publicAdapterConfig = adapter.toPublicConfig(result.data);
|
|
1260
1353
|
if (adapter.name === "pusher") {
|
|
1261
1354
|
if (!await tryResolveModule("pusher-js", nuxt.options.rootDir)) {
|
|
1262
1355
|
const msg = `The pusher adapter requires \`pusher-js\`. Install with: npx nypm add pusher-js`;
|
|
@@ -1279,7 +1372,7 @@ export {}
|
|
|
1279
1372
|
const template = addTemplate({
|
|
1280
1373
|
filename: "skew-adapter.mjs",
|
|
1281
1374
|
getContents: () => `import { subscribe } from 'nuxt-skew-protection/adapters/${adapter.name}/web'
|
|
1282
|
-
export const config = ${JSON.stringify(
|
|
1375
|
+
export const config = ${JSON.stringify(publicAdapterConfig)}
|
|
1283
1376
|
export { subscribe }`
|
|
1284
1377
|
});
|
|
1285
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,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
|
-
|
|
2
|
-
|
|
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({
|
|
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
|
-
|
|
2
|
-
|
|
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<
|
|
12
|
-
export interface DefineAdapterOptions<
|
|
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<
|
|
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<
|
|
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>;
|
|
@@ -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
|
|
15
|
-
|
|
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");
|
|
@@ -12,6 +12,9 @@ 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
|
+
}
|
|
15
18
|
function parseBuildAssetRequest(request, buildAssetsPath, recoveryPath) {
|
|
16
19
|
const requestUrl = new URL(request.url);
|
|
17
20
|
if (requestUrl.pathname.startsWith(buildAssetsPath)) {
|
|
@@ -45,13 +48,13 @@ function parseBuildAssetRequest(request, buildAssetsPath, recoveryPath) {
|
|
|
45
48
|
export async function fetchCloudflareAsset(request, assets) {
|
|
46
49
|
const response = await assets.fetch(request);
|
|
47
50
|
if (response.status < 400) {
|
|
48
|
-
return response;
|
|
51
|
+
return protectMutableAsset(request, response);
|
|
49
52
|
}
|
|
50
53
|
if (response.status !== 404) {
|
|
51
54
|
return disableCaching(response);
|
|
52
55
|
}
|
|
53
56
|
const retryResponse = await assets.fetch(createRetryRequest(request));
|
|
54
|
-
return retryResponse.status < 400 ? retryResponse : disableCaching(retryResponse);
|
|
57
|
+
return retryResponse.status < 400 ? protectMutableAsset(request, retryResponse) : disableCaching(retryResponse);
|
|
55
58
|
}
|
|
56
59
|
export function fetchCloudflareBuildAsset(request, assets, buildAssetsPath, recoveryPath) {
|
|
57
60
|
const parsed = parseBuildAssetRequest(request, buildAssetsPath, recoveryPath);
|
package/dist/runtime/types.d.ts
CHANGED
|
@@ -6,6 +6,9 @@ export type AssetRecoveryConfig = {
|
|
|
6
6
|
buildAssetsPath: string;
|
|
7
7
|
recoveryPath: string;
|
|
8
8
|
};
|
|
9
|
+
export interface NuxtSkewProtectionPrivateRuntimeConfig {
|
|
10
|
+
vercelCookiePath?: string;
|
|
11
|
+
}
|
|
9
12
|
export interface NuxtSkewProtectionRuntimeConfig {
|
|
10
13
|
/**
|
|
11
14
|
* Path prefix for the module's runtime endpoints (`/ws`, `/sse`, `/health`,
|
|
@@ -15,7 +18,7 @@ export interface NuxtSkewProtectionRuntimeConfig {
|
|
|
15
18
|
*/
|
|
16
19
|
basePath: string;
|
|
17
20
|
assetRecovery: AssetRecoveryConfig;
|
|
18
|
-
cookie: Omit<CookieSerializeOptions, 'encode'> & {
|
|
21
|
+
cookie: false | Omit<CookieSerializeOptions, 'encode'> & {
|
|
19
22
|
name?: string;
|
|
20
23
|
};
|
|
21
24
|
debug: boolean;
|
|
@@ -28,7 +31,7 @@ export interface NuxtSkewProtectionRuntimeConfig {
|
|
|
28
31
|
export interface SkewProtectionRuntimeConfig {
|
|
29
32
|
basePath: string;
|
|
30
33
|
assetRecovery: AssetRecoveryConfig;
|
|
31
|
-
cookie: Omit<CookieSerializeOptions, 'encode'> & {
|
|
34
|
+
cookie: false | Omit<CookieSerializeOptions, 'encode'> & {
|
|
32
35
|
name: string;
|
|
33
36
|
};
|
|
34
37
|
debug: boolean;
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nuxt-skew-protection",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "1.
|
|
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.
|
|
85
|
-
"nuxtseo-shared": "^5.3.
|
|
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.
|
|
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": "^
|
|
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.
|
|
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.
|
|
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.
|
|
122
|
+
"wrangler": "^4.121.0",
|
|
123
123
|
"ws": "^8.21.3"
|
|
124
124
|
},
|
|
125
125
|
"resolutions": {
|