nuxt-skew-protection 0.1.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/LICENSE.md +51 -0
- package/README.md +88 -0
- package/dist/module.cjs +898 -0
- package/dist/module.d.cts +64 -0
- package/dist/module.d.mts +64 -0
- package/dist/module.d.ts +64 -0
- package/dist/module.json +12 -0
- package/dist/module.mjs +895 -0
- package/dist/runtime/app/components/SkewNotification.d.vue.ts +45 -0
- package/dist/runtime/app/components/SkewNotification.vue +62 -0
- package/dist/runtime/app/components/SkewNotification.vue.d.ts +45 -0
- package/dist/runtime/app/composables/useRuntimeConfigSkewProtection.d.ts +6 -0
- package/dist/runtime/app/composables/useRuntimeConfigSkewProtection.js +5 -0
- package/dist/runtime/app/composables/useSkewProtection.d.ts +12 -0
- package/dist/runtime/app/composables/useSkewProtection.js +48 -0
- package/dist/runtime/app/plugins/0.skew-protection.d.ts +27 -0
- package/dist/runtime/app/plugins/0.skew-protection.js +41 -0
- package/dist/runtime/app/plugins/check-updates-sse.client.d.ts +2 -0
- package/dist/runtime/app/plugins/check-updates-sse.client.js +36 -0
- package/dist/runtime/app/plugins/check-updates-websocket.client.d.ts +16 -0
- package/dist/runtime/app/plugins/check-updates-websocket.client.js +87 -0
- package/dist/runtime/app/plugins/sw-track-user-modules.client.d.ts +13 -0
- package/dist/runtime/app/plugins/sw-track-user-modules.client.js +102 -0
- package/dist/runtime/server/imports/cookie.d.ts +37 -0
- package/dist/runtime/server/imports/cookie.js +15 -0
- package/dist/runtime/server/imports/getRuntimeConfigSkewProtection.d.ts +7 -0
- package/dist/runtime/server/imports/getRuntimeConfigSkewProtection.js +5 -0
- package/dist/runtime/server/imports/utils.d.ts +6 -0
- package/dist/runtime/server/imports/utils.js +8 -0
- package/dist/runtime/server/index.d.ts +3 -0
- package/dist/runtime/server/index.js +3 -0
- package/dist/runtime/server/middleware/set-skew-protection-cookie.d.ts +6 -0
- package/dist/runtime/server/middleware/set-skew-protection-cookie.js +15 -0
- package/dist/runtime/server/middleware/vercel-skew.d.ts +2 -0
- package/dist/runtime/server/middleware/vercel-skew.js +17 -0
- package/dist/runtime/server/routes/_skew/sse.d.ts +2 -0
- package/dist/runtime/server/routes/_skew/sse.js +30 -0
- package/dist/runtime/server/routes/_skew/ws.d.ts +2 -0
- package/dist/runtime/server/routes/_skew/ws.js +17 -0
- package/dist/runtime/shared/logger.d.ts +1 -0
- package/dist/runtime/shared/logger.js +6 -0
- package/dist/runtime/types.d.ts +25 -0
- package/dist/runtime/types.js +0 -0
- package/dist/types.d.mts +9 -0
- package/package.json +116 -0
package/dist/module.cjs
ADDED
|
@@ -0,0 +1,898 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const node_fs = require('node:fs');
|
|
4
|
+
const kit = require('@nuxt/kit');
|
|
5
|
+
const stdEnv = require('std-env');
|
|
6
|
+
const node_path = require('node:path');
|
|
7
|
+
const node_os = require('node:os');
|
|
8
|
+
const tinyexec = require('tinyexec');
|
|
9
|
+
const unstorage = require('unstorage');
|
|
10
|
+
const utils = require('consola/utils');
|
|
11
|
+
const pathe = require('pathe');
|
|
12
|
+
|
|
13
|
+
var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
|
|
14
|
+
function isStaticPreset(nuxt = kit.useNuxt()) {
|
|
15
|
+
return nuxt.options.nitro.static || nuxt.options._generate || [
|
|
16
|
+
"static",
|
|
17
|
+
"github-pages"
|
|
18
|
+
].includes(resolveNitroPreset());
|
|
19
|
+
}
|
|
20
|
+
const autodetectableProviders = {
|
|
21
|
+
azure_static: "azure",
|
|
22
|
+
cloudflare_pages: "cloudflare-pages",
|
|
23
|
+
netlify: "netlify",
|
|
24
|
+
stormkit: "stormkit",
|
|
25
|
+
vercel: "vercel",
|
|
26
|
+
cleavr: "cleavr",
|
|
27
|
+
stackblitz: "stackblitz"
|
|
28
|
+
};
|
|
29
|
+
const autodetectableStaticProviders = {
|
|
30
|
+
netlify: "netlify-static",
|
|
31
|
+
vercel: "vercel-static"
|
|
32
|
+
};
|
|
33
|
+
function detectTarget(options = {}) {
|
|
34
|
+
return options?.static ? autodetectableStaticProviders[stdEnv.provider] : autodetectableProviders[stdEnv.provider];
|
|
35
|
+
}
|
|
36
|
+
function resolveNitroPreset(nitroConfig) {
|
|
37
|
+
nitroConfig = nitroConfig || kit.tryUseNuxt()?.options?.nitro;
|
|
38
|
+
if (stdEnv.provider === "stackblitz")
|
|
39
|
+
return "stackblitz";
|
|
40
|
+
let preset;
|
|
41
|
+
if (nitroConfig && nitroConfig?.preset)
|
|
42
|
+
preset = nitroConfig.preset;
|
|
43
|
+
if (!preset)
|
|
44
|
+
preset = stdEnv.env.NITRO_PRESET || stdEnv.env.SERVER_PRESET || detectTarget() || "node-server";
|
|
45
|
+
return preset.replace("_", "-");
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const logger = kit.useLogger("nuxt-skew-protection");
|
|
49
|
+
|
|
50
|
+
const awsS3CLIDriver = unstorage.defineDriver((opts) => {
|
|
51
|
+
const { bucket, prefix = "", region, profile } = opts;
|
|
52
|
+
if (!bucket) {
|
|
53
|
+
throw new Error("[aws-s3-cli] bucket is required");
|
|
54
|
+
}
|
|
55
|
+
function buildCommand(subcommand) {
|
|
56
|
+
const regionFlag = region ? `--region ${region}` : "";
|
|
57
|
+
const profileFlag = profile ? `--profile ${profile}` : "";
|
|
58
|
+
return `aws s3api ${subcommand} ${regionFlag} ${profileFlag}`.trim();
|
|
59
|
+
}
|
|
60
|
+
function getKey(key) {
|
|
61
|
+
return prefix ? `${prefix}${key}` : key;
|
|
62
|
+
}
|
|
63
|
+
async function execAWS(subcommand) {
|
|
64
|
+
const command = buildCommand(subcommand);
|
|
65
|
+
const result = await tinyexec.x("sh", ["-c", command], {
|
|
66
|
+
throwOnError: true
|
|
67
|
+
});
|
|
68
|
+
return result.stdout.trim();
|
|
69
|
+
}
|
|
70
|
+
const driver = {
|
|
71
|
+
name: "aws-s3-cli",
|
|
72
|
+
options: opts,
|
|
73
|
+
async hasItem(key) {
|
|
74
|
+
await execAWS(`head-object --bucket "${bucket}" --key "${getKey(key)}"`);
|
|
75
|
+
return true;
|
|
76
|
+
},
|
|
77
|
+
async getItem(key) {
|
|
78
|
+
const tmpFile = node_path.join(node_os.tmpdir(), `s3-get-${Date.now()}.json`);
|
|
79
|
+
await execAWS(`get-object --bucket "${bucket}" --key "${getKey(key)}" "${tmpFile}"`);
|
|
80
|
+
const content = node_fs.readFileSync(tmpFile, "utf-8");
|
|
81
|
+
const result = JSON.parse(content);
|
|
82
|
+
node_fs.unlinkSync(tmpFile);
|
|
83
|
+
return result;
|
|
84
|
+
},
|
|
85
|
+
async getItemRaw(key) {
|
|
86
|
+
const tmpFile = node_path.join(node_os.tmpdir(), `s3-get-${Date.now()}.bin`);
|
|
87
|
+
await execAWS(`get-object --bucket "${bucket}" --key "${getKey(key)}" "${tmpFile}"`);
|
|
88
|
+
const result = node_fs.readFileSync(tmpFile);
|
|
89
|
+
node_fs.unlinkSync(tmpFile);
|
|
90
|
+
return result;
|
|
91
|
+
},
|
|
92
|
+
async setItem(key, value) {
|
|
93
|
+
const tmpFile = node_path.join(node_os.tmpdir(), `s3-put-${Date.now()}.json`);
|
|
94
|
+
node_fs.writeFileSync(tmpFile, JSON.stringify(value));
|
|
95
|
+
await execAWS(`put-object --bucket "${bucket}" --key "${getKey(key)}" --body "${tmpFile}"`);
|
|
96
|
+
node_fs.unlinkSync(tmpFile);
|
|
97
|
+
},
|
|
98
|
+
async setItemRaw(key, value) {
|
|
99
|
+
const tmpFile = node_path.join(node_os.tmpdir(), `s3-put-${Date.now()}.bin`);
|
|
100
|
+
node_fs.writeFileSync(tmpFile, value);
|
|
101
|
+
await execAWS(`put-object --bucket "${bucket}" --key "${getKey(key)}" --body "${tmpFile}"`);
|
|
102
|
+
node_fs.unlinkSync(tmpFile);
|
|
103
|
+
},
|
|
104
|
+
async removeItem(key) {
|
|
105
|
+
await execAWS(`delete-object --bucket "${bucket}" --key "${getKey(key)}"`);
|
|
106
|
+
},
|
|
107
|
+
async getKeys(base) {
|
|
108
|
+
const searchPrefix = base ? getKey(base) : prefix;
|
|
109
|
+
const prefixFlag = searchPrefix ? `--prefix "${searchPrefix}"` : "";
|
|
110
|
+
const result = await execAWS(`list-objects-v2 --bucket "${bucket}" ${prefixFlag}`);
|
|
111
|
+
const data = JSON.parse(result);
|
|
112
|
+
if (!data.Contents || !Array.isArray(data.Contents)) {
|
|
113
|
+
return [];
|
|
114
|
+
}
|
|
115
|
+
return data.Contents.map((item) => {
|
|
116
|
+
let key = item.Key;
|
|
117
|
+
if (prefix && key.startsWith(prefix)) {
|
|
118
|
+
key = key.slice(prefix.length);
|
|
119
|
+
}
|
|
120
|
+
return key;
|
|
121
|
+
});
|
|
122
|
+
},
|
|
123
|
+
async clear(base) {
|
|
124
|
+
const keys = await driver.getKeys(base);
|
|
125
|
+
for (const key of keys) {
|
|
126
|
+
await driver.removeItem(key);
|
|
127
|
+
}
|
|
128
|
+
},
|
|
129
|
+
async dispose() {
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
return driver;
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
const cloudflareKVWranglerDriver = unstorage.defineDriver((opts) => {
|
|
136
|
+
const { namespaceId, local = false } = opts;
|
|
137
|
+
if (!namespaceId) {
|
|
138
|
+
throw new Error("[cloudflare-kv-wrangler] namespaceId is required");
|
|
139
|
+
}
|
|
140
|
+
const locationFlag = local ? "--local" : "--remote";
|
|
141
|
+
async function execWrangler(command, throwOnError = true) {
|
|
142
|
+
const result = await tinyexec.x("sh", ["-c", `npx ${command}`]);
|
|
143
|
+
if (throwOnError && result.exitCode !== 0) {
|
|
144
|
+
throw new Error(
|
|
145
|
+
`[cloudflare-kv-wrangler] Command failed with exit code ${result.exitCode}
|
|
146
|
+
Command: ${command}
|
|
147
|
+
stdout: ${result.stdout}
|
|
148
|
+
stderr: ${result.stderr}`
|
|
149
|
+
);
|
|
150
|
+
}
|
|
151
|
+
return { stdout: result.stdout.trim(), exitCode: result.exitCode || 0 };
|
|
152
|
+
}
|
|
153
|
+
const driver = {
|
|
154
|
+
name: "cloudflare-kv-wrangler",
|
|
155
|
+
options: opts,
|
|
156
|
+
async hasItem(key) {
|
|
157
|
+
const result = await execWrangler(`wrangler kv key get "${key}" --namespace-id="${namespaceId}" ${locationFlag}`, false);
|
|
158
|
+
return result.exitCode === 0;
|
|
159
|
+
},
|
|
160
|
+
async getItem(key) {
|
|
161
|
+
const result = await execWrangler(`wrangler kv key get "${key}" --namespace-id="${namespaceId}" ${locationFlag}`, false);
|
|
162
|
+
if (result.exitCode !== 0) {
|
|
163
|
+
return null;
|
|
164
|
+
}
|
|
165
|
+
return JSON.parse(result.stdout);
|
|
166
|
+
},
|
|
167
|
+
async getItemRaw(key) {
|
|
168
|
+
const result = await execWrangler(`wrangler kv key get "${key}" --namespace-id="${namespaceId}" ${locationFlag}`);
|
|
169
|
+
return Buffer.from(result.stdout, "utf-8");
|
|
170
|
+
},
|
|
171
|
+
async setItem(key, value) {
|
|
172
|
+
const tmpFile = node_path.join(node_os.tmpdir(), `kv-${Date.now()}-${Math.random().toString(36).substring(7)}.json`);
|
|
173
|
+
node_fs.writeFileSync(tmpFile, JSON.stringify(value));
|
|
174
|
+
try {
|
|
175
|
+
await execWrangler(`wrangler kv key put "${key}" --path="${tmpFile}" --namespace-id="${namespaceId}" ${locationFlag}`);
|
|
176
|
+
} finally {
|
|
177
|
+
node_fs.unlinkSync(tmpFile);
|
|
178
|
+
}
|
|
179
|
+
},
|
|
180
|
+
async setItemRaw(key, value) {
|
|
181
|
+
const tmpFile = node_path.join(node_os.tmpdir(), `kv-${Date.now()}.bin`);
|
|
182
|
+
node_fs.writeFileSync(tmpFile, value);
|
|
183
|
+
await execWrangler(`wrangler kv key put "${key}" --path="${tmpFile}" --namespace-id="${namespaceId}" ${locationFlag}`);
|
|
184
|
+
node_fs.unlinkSync(tmpFile);
|
|
185
|
+
},
|
|
186
|
+
async removeItem(key) {
|
|
187
|
+
await execWrangler(`wrangler kv key delete "${key}" --namespace-id="${namespaceId}" ${locationFlag}`);
|
|
188
|
+
},
|
|
189
|
+
async getKeys(base) {
|
|
190
|
+
const prefix = base ? `--prefix="${base}"` : "";
|
|
191
|
+
const result = await execWrangler(`wrangler kv key list ${prefix} --namespace-id="${namespaceId}" ${locationFlag}`);
|
|
192
|
+
const keys = JSON.parse(result.stdout);
|
|
193
|
+
return keys.map((k) => k.name);
|
|
194
|
+
},
|
|
195
|
+
async clear(base) {
|
|
196
|
+
const keys = await driver.getKeys(base);
|
|
197
|
+
for (const key of keys) {
|
|
198
|
+
await driver.removeItem(key);
|
|
199
|
+
}
|
|
200
|
+
},
|
|
201
|
+
async dispose() {
|
|
202
|
+
}
|
|
203
|
+
};
|
|
204
|
+
return driver;
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
const netlifyBlobsCLIDriver = unstorage.defineDriver((opts) => {
|
|
208
|
+
const { siteId, storeName = "production" } = opts;
|
|
209
|
+
function buildCommand(subcommand) {
|
|
210
|
+
const siteFlag = siteId ? `--site ${siteId}` : "";
|
|
211
|
+
return `netlify blobs:${subcommand} ${siteFlag}`.trim();
|
|
212
|
+
}
|
|
213
|
+
async function execNetlify(subcommand) {
|
|
214
|
+
const command = buildCommand(subcommand);
|
|
215
|
+
const result = await tinyexec.x("sh", ["-c", command], {
|
|
216
|
+
throwOnError: true
|
|
217
|
+
});
|
|
218
|
+
return result.stdout.trim();
|
|
219
|
+
}
|
|
220
|
+
const driver = {
|
|
221
|
+
name: "netlify-blobs-cli",
|
|
222
|
+
options: opts,
|
|
223
|
+
async hasItem(key) {
|
|
224
|
+
await execNetlify(`get "${key}" --store "${storeName}"`);
|
|
225
|
+
return true;
|
|
226
|
+
},
|
|
227
|
+
async getItem(key) {
|
|
228
|
+
const result = await execNetlify(`get "${key}" --store "${storeName}"`);
|
|
229
|
+
return JSON.parse(result);
|
|
230
|
+
},
|
|
231
|
+
async getItemRaw(key) {
|
|
232
|
+
const result = await execNetlify(`get "${key}" --store "${storeName}"`);
|
|
233
|
+
return Buffer.from(result, "utf-8");
|
|
234
|
+
},
|
|
235
|
+
async setItem(key, value) {
|
|
236
|
+
const tmpFile = node_path.join(node_os.tmpdir(), `netlify-blob-${Date.now()}.json`);
|
|
237
|
+
node_fs.writeFileSync(tmpFile, JSON.stringify(value));
|
|
238
|
+
await execNetlify(`set "${key}" "${tmpFile}" --store "${storeName}"`);
|
|
239
|
+
node_fs.unlinkSync(tmpFile);
|
|
240
|
+
},
|
|
241
|
+
async setItemRaw(key, value) {
|
|
242
|
+
const tmpFile = node_path.join(node_os.tmpdir(), `netlify-blob-${Date.now()}.bin`);
|
|
243
|
+
node_fs.writeFileSync(tmpFile, value);
|
|
244
|
+
await execNetlify(`set "${key}" "${tmpFile}" --store "${storeName}"`);
|
|
245
|
+
node_fs.unlinkSync(tmpFile);
|
|
246
|
+
},
|
|
247
|
+
async removeItem(key) {
|
|
248
|
+
await execNetlify(`delete "${key}" --store "${storeName}"`);
|
|
249
|
+
},
|
|
250
|
+
async getKeys(base) {
|
|
251
|
+
const prefix = base || "";
|
|
252
|
+
const result = await execNetlify(`list --store "${storeName}" --prefix "${prefix}" --json`);
|
|
253
|
+
const blobs = JSON.parse(result);
|
|
254
|
+
if (Array.isArray(blobs)) {
|
|
255
|
+
return blobs.map((blob) => blob.key || blob);
|
|
256
|
+
}
|
|
257
|
+
return [];
|
|
258
|
+
},
|
|
259
|
+
async clear(base) {
|
|
260
|
+
const keys = await driver.getKeys(base);
|
|
261
|
+
for (const key of keys) {
|
|
262
|
+
await driver.removeItem(key);
|
|
263
|
+
}
|
|
264
|
+
},
|
|
265
|
+
async dispose() {
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
return driver;
|
|
269
|
+
});
|
|
270
|
+
|
|
271
|
+
const vercelKVCLIDriver = unstorage.defineDriver((opts) => {
|
|
272
|
+
const { storeName, teamId } = opts;
|
|
273
|
+
if (!storeName) {
|
|
274
|
+
throw new Error("[vercel-kv-cli] storeName is required");
|
|
275
|
+
}
|
|
276
|
+
function buildCommand(subcommand) {
|
|
277
|
+
const teamFlag = teamId ? `--team ${teamId}` : "";
|
|
278
|
+
return `vercel kv ${subcommand} ${storeName} ${teamFlag}`.trim();
|
|
279
|
+
}
|
|
280
|
+
async function execVercelKV(subcommand) {
|
|
281
|
+
const command = buildCommand(subcommand);
|
|
282
|
+
const result = await tinyexec.x("sh", ["-c", command], {
|
|
283
|
+
throwOnError: true
|
|
284
|
+
});
|
|
285
|
+
return result.stdout.trim();
|
|
286
|
+
}
|
|
287
|
+
const driver = {
|
|
288
|
+
name: "vercel-kv-cli",
|
|
289
|
+
options: opts,
|
|
290
|
+
async hasItem(key) {
|
|
291
|
+
const result = await execVercelKV(`get "${key}"`);
|
|
292
|
+
return !!result;
|
|
293
|
+
},
|
|
294
|
+
async getItem(key) {
|
|
295
|
+
const result = await execVercelKV(`get "${key}"`);
|
|
296
|
+
return JSON.parse(result);
|
|
297
|
+
},
|
|
298
|
+
async getItemRaw(key) {
|
|
299
|
+
const result = await execVercelKV(`get "${key}"`);
|
|
300
|
+
return Buffer.from(result, "utf-8");
|
|
301
|
+
},
|
|
302
|
+
async setItem(key, value) {
|
|
303
|
+
const jsonValue = JSON.stringify(value);
|
|
304
|
+
const escapedValue = jsonValue.replace(/"/g, '\\"');
|
|
305
|
+
await execVercelKV(`set "${key}" "${escapedValue}"`);
|
|
306
|
+
},
|
|
307
|
+
async setItemRaw(key, value) {
|
|
308
|
+
const base64Value = Buffer.from(value).toString("base64");
|
|
309
|
+
const escapedValue = base64Value.replace(/"/g, '\\"');
|
|
310
|
+
await execVercelKV(`set "${key}" "${escapedValue}"`);
|
|
311
|
+
},
|
|
312
|
+
async removeItem(key) {
|
|
313
|
+
await execVercelKV(`del "${key}"`);
|
|
314
|
+
},
|
|
315
|
+
async getKeys(base) {
|
|
316
|
+
const pattern = base ? `"${base}*"` : '"*"';
|
|
317
|
+
const result = await execVercelKV(`keys ${pattern}`);
|
|
318
|
+
const keys = JSON.parse(result);
|
|
319
|
+
return Array.isArray(keys) ? keys : [];
|
|
320
|
+
},
|
|
321
|
+
async clear(base) {
|
|
322
|
+
const keys = await driver.getKeys(base);
|
|
323
|
+
for (const key of keys) {
|
|
324
|
+
await driver.removeItem(key);
|
|
325
|
+
}
|
|
326
|
+
},
|
|
327
|
+
async dispose() {
|
|
328
|
+
}
|
|
329
|
+
};
|
|
330
|
+
return driver;
|
|
331
|
+
});
|
|
332
|
+
|
|
333
|
+
async function detectCloudflareKVNamespace() {
|
|
334
|
+
const nuxt = kit.useNuxt();
|
|
335
|
+
const rootDir = nuxt.options.rootDir || process.cwd();
|
|
336
|
+
const wranglerPath = node_path.join(rootDir, "wrangler.toml");
|
|
337
|
+
if (!node_fs.existsSync(wranglerPath)) {
|
|
338
|
+
return null;
|
|
339
|
+
}
|
|
340
|
+
try {
|
|
341
|
+
const content = node_fs.readFileSync(wranglerPath, "utf-8");
|
|
342
|
+
const kvNamespaceMatch = content.match(/\[\[kv_namespaces\]\][^[]*?id\s*=\s*"([^"]+)"/);
|
|
343
|
+
if (kvNamespaceMatch?.[1]) {
|
|
344
|
+
return kvNamespaceMatch[1];
|
|
345
|
+
}
|
|
346
|
+
return null;
|
|
347
|
+
} catch {
|
|
348
|
+
return null;
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
async function resolveBuildTimeDriver(storage) {
|
|
352
|
+
const { driver, ...driverOptions } = storage;
|
|
353
|
+
switch (driver) {
|
|
354
|
+
case "cloudflare-kv-binding": {
|
|
355
|
+
let namespaceId = storage.namespaceId;
|
|
356
|
+
if (!namespaceId) {
|
|
357
|
+
namespaceId = await detectCloudflareKVNamespace();
|
|
358
|
+
}
|
|
359
|
+
return cloudflareKVWranglerDriver(driverOptions);
|
|
360
|
+
}
|
|
361
|
+
case "vercel-kv": {
|
|
362
|
+
return vercelKVCLIDriver(driverOptions);
|
|
363
|
+
}
|
|
364
|
+
case "s3":
|
|
365
|
+
case "aws-s3": {
|
|
366
|
+
return awsS3CLIDriver(driverOptions);
|
|
367
|
+
}
|
|
368
|
+
case "netlify-blobs": {
|
|
369
|
+
return netlifyBlobsCLIDriver(driverOptions);
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
const lazyDriver = await import(`unstorage/drivers/${storage.driver}`).then((m) => m.default);
|
|
373
|
+
return lazyDriver(driverOptions);
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
function extractFileId(assetPath) {
|
|
377
|
+
const filename = assetPath.split("/").pop();
|
|
378
|
+
if (!filename)
|
|
379
|
+
return null;
|
|
380
|
+
const match = filename.match(/^([^.]+\.\w+)/);
|
|
381
|
+
return match ? match[1] ?? null : null;
|
|
382
|
+
}
|
|
383
|
+
function calculateDeletedChunks(currentAssets, previousAssets) {
|
|
384
|
+
const currentSet = new Set(currentAssets);
|
|
385
|
+
return previousAssets.filter((asset) => !currentSet.has(asset));
|
|
386
|
+
}
|
|
387
|
+
function getPreviousVersion(manifest, currentVersionId) {
|
|
388
|
+
const sortedVersions = Object.entries(manifest.versions).map(([id, data]) => ({ id, timestamp: new Date(data.timestamp).getTime() })).sort((a, b) => b.timestamp - a.timestamp);
|
|
389
|
+
const currentIndex = sortedVersions.findIndex((v) => v.id === currentVersionId);
|
|
390
|
+
if (currentIndex === -1 || currentIndex === sortedVersions.length - 1) {
|
|
391
|
+
return null;
|
|
392
|
+
}
|
|
393
|
+
return sortedVersions[currentIndex + 1]?.id || null;
|
|
394
|
+
}
|
|
395
|
+
async function getFilesRecursively(dir) {
|
|
396
|
+
const files = [];
|
|
397
|
+
const items = await node_fs.promises.readdir(dir, { withFileTypes: true }).catch(() => []);
|
|
398
|
+
for (const item of items) {
|
|
399
|
+
const fullPath = pathe.join(dir, item.name);
|
|
400
|
+
if (item.isDirectory()) {
|
|
401
|
+
const subFiles = await getFilesRecursively(fullPath);
|
|
402
|
+
files.push(...subFiles);
|
|
403
|
+
} else {
|
|
404
|
+
files.push(fullPath);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
return files;
|
|
408
|
+
}
|
|
409
|
+
async function getVersionManifest(storage) {
|
|
410
|
+
try {
|
|
411
|
+
const manifest = await storage.getItem("version-manifest.json");
|
|
412
|
+
if (manifest && typeof manifest === "object" && "versions" in manifest) {
|
|
413
|
+
return manifest;
|
|
414
|
+
}
|
|
415
|
+
return {
|
|
416
|
+
current: "",
|
|
417
|
+
versions: {}
|
|
418
|
+
};
|
|
419
|
+
} catch {
|
|
420
|
+
return {
|
|
421
|
+
current: "",
|
|
422
|
+
versions: {}
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
async function setVersionManifest(manifest, storage) {
|
|
427
|
+
await storage.setItem("version-manifest.json", manifest);
|
|
428
|
+
}
|
|
429
|
+
function createAssetManager(options) {
|
|
430
|
+
const storage = unstorage.createStorage({
|
|
431
|
+
driver: options.driver
|
|
432
|
+
});
|
|
433
|
+
const retentionDays = options.retentionDays || 7;
|
|
434
|
+
const maxNumberOfVersions = options.maxNumberOfVersions || 20;
|
|
435
|
+
async function getAssetsFromBuild(outputDir) {
|
|
436
|
+
const nuxtDir = pathe.join(outputDir, "public", "_nuxt");
|
|
437
|
+
const assets = [];
|
|
438
|
+
const nuxtFiles = await getFilesRecursively(nuxtDir);
|
|
439
|
+
for (const file of nuxtFiles) {
|
|
440
|
+
const relativePath = file.replace(nuxtDir, "");
|
|
441
|
+
assets.push(`_nuxt${relativePath}`);
|
|
442
|
+
}
|
|
443
|
+
return assets;
|
|
444
|
+
}
|
|
445
|
+
async function updateVersionsManifest(buildId, assets) {
|
|
446
|
+
const now = /* @__PURE__ */ new Date();
|
|
447
|
+
const expires = new Date(now.getTime() + retentionDays * 24 * 60 * 60 * 1e3);
|
|
448
|
+
const manifest = await getVersionManifest(storage);
|
|
449
|
+
const isExistingVersion = !!manifest.versions[buildId];
|
|
450
|
+
manifest.current = buildId;
|
|
451
|
+
manifest.versions[buildId] = {
|
|
452
|
+
timestamp: now.toISOString(),
|
|
453
|
+
expires: expires.toISOString(),
|
|
454
|
+
assets,
|
|
455
|
+
// deletedChunks will be calculated after deduplication in storeAssetsInStorage
|
|
456
|
+
deletedChunks: []
|
|
457
|
+
};
|
|
458
|
+
await setVersionManifest(manifest, storage);
|
|
459
|
+
return { manifest, isExistingVersion };
|
|
460
|
+
}
|
|
461
|
+
async function cleanupExpiredVersions() {
|
|
462
|
+
const manifest = await getVersionManifest(storage);
|
|
463
|
+
if (!manifest || !manifest.versions) {
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
const now = /* @__PURE__ */ new Date();
|
|
467
|
+
const removedVersions = [];
|
|
468
|
+
const sortedVersions = Object.entries(manifest.versions).map(([id, data]) => ({ id, ...data, timestamp: new Date(data.timestamp).getTime() })).sort((a, b) => b.timestamp - a.timestamp);
|
|
469
|
+
const maxAge = retentionDays * 24 * 60 * 60 * 1e3;
|
|
470
|
+
for (let i = 0; i < sortedVersions.length; i++) {
|
|
471
|
+
const version = sortedVersions[i];
|
|
472
|
+
const isExpired = now.getTime() - version.timestamp > maxAge;
|
|
473
|
+
const exceedsCount = i >= maxNumberOfVersions;
|
|
474
|
+
const isCurrent = version.id === manifest.current;
|
|
475
|
+
if (isCurrent || i === 0 && sortedVersions.length === 1) {
|
|
476
|
+
continue;
|
|
477
|
+
}
|
|
478
|
+
if (isExpired || exceedsCount) {
|
|
479
|
+
const assetPromises = version.assets.map(
|
|
480
|
+
(asset) => storage.removeItem(`${version.id}/${asset}`).catch((error) => {
|
|
481
|
+
if (options.debug) {
|
|
482
|
+
logger.warn(`Failed to remove asset ${asset}:`, error);
|
|
483
|
+
}
|
|
484
|
+
})
|
|
485
|
+
);
|
|
486
|
+
await Promise.all(assetPromises);
|
|
487
|
+
delete manifest.versions[version.id];
|
|
488
|
+
if (manifest.fileIdToVersion) {
|
|
489
|
+
for (const [fileId, versionId] of Object.entries(manifest.fileIdToVersion)) {
|
|
490
|
+
if (versionId === version.id) {
|
|
491
|
+
delete manifest.fileIdToVersion[fileId];
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
removedVersions.push({
|
|
496
|
+
id: version.id,
|
|
497
|
+
reason: isExpired ? "expired" : "exceeded count limit",
|
|
498
|
+
assetCount: version.assets.length
|
|
499
|
+
});
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
if (removedVersions.length > 0) {
|
|
503
|
+
await setVersionManifest(manifest, storage);
|
|
504
|
+
logger.log(`Removing outdated build artifacts...`);
|
|
505
|
+
removedVersions.forEach((item, index) => {
|
|
506
|
+
const isLast = index === removedVersions.length - 1;
|
|
507
|
+
const prefix = isLast ? " \u2514\u2500" : " \u251C\u2500";
|
|
508
|
+
const versionInfo = `${item.id.slice(0, 8)}`;
|
|
509
|
+
const assetInfo = `(${item.assetCount} asset${item.assetCount > 1 ? "s" : ""})`;
|
|
510
|
+
const reasonInfo = `[${item.reason}]`;
|
|
511
|
+
logger.log(utils.colors.gray(`${prefix} ${versionInfo} ${assetInfo} ${reasonInfo}`));
|
|
512
|
+
});
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
async function storeAssetsInStorage(buildId, outputDir, assets) {
|
|
516
|
+
const publicDir = pathe.join(outputDir, "public");
|
|
517
|
+
const manifest = await getVersionManifest(storage);
|
|
518
|
+
if (!manifest.fileIdToVersion) {
|
|
519
|
+
manifest.fileIdToVersion = {};
|
|
520
|
+
}
|
|
521
|
+
const fileIdToVersion = manifest.fileIdToVersion;
|
|
522
|
+
const currentVersion = manifest.versions[buildId];
|
|
523
|
+
if (currentVersion) {
|
|
524
|
+
const previousVersionId = getPreviousVersion(manifest, buildId);
|
|
525
|
+
const previousAssets = previousVersionId ? manifest.versions[previousVersionId]?.assets || [] : [];
|
|
526
|
+
currentVersion.deletedChunks = calculateDeletedChunks(assets, previousAssets);
|
|
527
|
+
}
|
|
528
|
+
for (const asset of assets) {
|
|
529
|
+
const fileId = extractFileId(asset);
|
|
530
|
+
const assetPath = pathe.join(publicDir, asset);
|
|
531
|
+
const assetData = await node_fs.promises.readFile(assetPath).catch((error) => {
|
|
532
|
+
if (options.debug) {
|
|
533
|
+
logger.warn(`Failed to read ${assetPath}:`, error);
|
|
534
|
+
}
|
|
535
|
+
return null;
|
|
536
|
+
});
|
|
537
|
+
if (assetData) {
|
|
538
|
+
const storageKey = `${buildId}/${asset}`;
|
|
539
|
+
await storage.setItemRaw(storageKey, assetData).catch((error) => {
|
|
540
|
+
if (options.debug) {
|
|
541
|
+
logger.warn(`Failed to store ${storageKey}:`, error);
|
|
542
|
+
}
|
|
543
|
+
});
|
|
544
|
+
if (fileId && fileIdToVersion[fileId] && fileIdToVersion[fileId] !== buildId) {
|
|
545
|
+
const previousVersionId = fileIdToVersion[fileId];
|
|
546
|
+
if (manifest.versions[previousVersionId]) {
|
|
547
|
+
const previousAssets = manifest.versions[previousVersionId].assets;
|
|
548
|
+
const assetIndex = previousAssets.findIndex((a) => extractFileId(a) === fileId);
|
|
549
|
+
if (assetIndex !== -1) {
|
|
550
|
+
previousAssets.splice(assetIndex, 1);
|
|
551
|
+
const oldStorageKey = `${previousVersionId}/${asset}`;
|
|
552
|
+
await storage.removeItem(oldStorageKey).catch((error) => {
|
|
553
|
+
if (options.debug) {
|
|
554
|
+
logger.warn(`Failed to remove duplicate asset ${oldStorageKey}:`, error);
|
|
555
|
+
}
|
|
556
|
+
});
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
if (fileId) {
|
|
561
|
+
fileIdToVersion[fileId] = buildId;
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
await setVersionManifest(manifest, storage);
|
|
566
|
+
}
|
|
567
|
+
async function listExistingVersions() {
|
|
568
|
+
const manifest = await getVersionManifest(storage);
|
|
569
|
+
if (!manifest) {
|
|
570
|
+
return [];
|
|
571
|
+
}
|
|
572
|
+
return Object.entries(manifest.versions).map(([id, data]) => ({
|
|
573
|
+
id,
|
|
574
|
+
createdAt: new Date(data.timestamp).getTime()
|
|
575
|
+
}));
|
|
576
|
+
}
|
|
577
|
+
async function restoreOldAssetsToPublic(currentBuildId, outputDir, currentAssets = [], isExistingVersion = false) {
|
|
578
|
+
const manifest = await getVersionManifest(storage);
|
|
579
|
+
if (!manifest || !manifest.versions) {
|
|
580
|
+
return;
|
|
581
|
+
}
|
|
582
|
+
if (isExistingVersion) {
|
|
583
|
+
if (options.debug) {
|
|
584
|
+
logger.info(`Build ID ${currentBuildId} already exists, skipping restore`);
|
|
585
|
+
}
|
|
586
|
+
return;
|
|
587
|
+
}
|
|
588
|
+
const publicDir = pathe.join(outputDir, "public");
|
|
589
|
+
const restoredAssets = [];
|
|
590
|
+
const currentAssetsSet = new Set(currentAssets);
|
|
591
|
+
const currentFileIds = /* @__PURE__ */ new Set();
|
|
592
|
+
for (const asset of currentAssets) {
|
|
593
|
+
const fileId = extractFileId(asset);
|
|
594
|
+
if (fileId) {
|
|
595
|
+
currentFileIds.add(fileId);
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
const now = Date.now();
|
|
599
|
+
for (const [versionId, versionData] of Object.entries(manifest.versions)) {
|
|
600
|
+
if (versionId === currentBuildId) {
|
|
601
|
+
continue;
|
|
602
|
+
}
|
|
603
|
+
const assets = versionData.assets;
|
|
604
|
+
for (const asset of assets) {
|
|
605
|
+
if (currentAssetsSet.has(asset)) {
|
|
606
|
+
continue;
|
|
607
|
+
}
|
|
608
|
+
const fileId = extractFileId(asset);
|
|
609
|
+
if (fileId && currentFileIds.has(fileId)) {
|
|
610
|
+
continue;
|
|
611
|
+
}
|
|
612
|
+
const storageKey = `${versionId}/${asset}`;
|
|
613
|
+
await storage.getItemRaw(storageKey).then(async (assetData) => {
|
|
614
|
+
if (assetData) {
|
|
615
|
+
const targetPath = pathe.join(publicDir, asset);
|
|
616
|
+
await node_fs.promises.mkdir(pathe.dirname(targetPath), { recursive: true });
|
|
617
|
+
let dataToWrite;
|
|
618
|
+
if (Buffer.isBuffer(assetData)) {
|
|
619
|
+
dataToWrite = assetData;
|
|
620
|
+
} else if (typeof assetData === "object" && assetData.type === "Buffer" && Array.isArray(assetData.data)) {
|
|
621
|
+
dataToWrite = Buffer.from(assetData.data);
|
|
622
|
+
} else {
|
|
623
|
+
dataToWrite = Buffer.from(assetData);
|
|
624
|
+
}
|
|
625
|
+
await node_fs.promises.writeFile(targetPath, dataToWrite);
|
|
626
|
+
const versionTimestamp = new Date(versionData.timestamp).getTime();
|
|
627
|
+
const ageMs = now - versionTimestamp;
|
|
628
|
+
const ageMinutes = Math.floor(ageMs / 6e4);
|
|
629
|
+
const ageHours = Math.floor(ageMinutes / 60);
|
|
630
|
+
const ageDays = Math.floor(ageHours / 24);
|
|
631
|
+
let ageStr;
|
|
632
|
+
if (ageDays > 0) {
|
|
633
|
+
ageStr = `${ageDays}d ago`;
|
|
634
|
+
} else if (ageHours > 0) {
|
|
635
|
+
ageStr = `${ageHours}h ago`;
|
|
636
|
+
} else if (ageMinutes > 0) {
|
|
637
|
+
ageStr = `${ageMinutes}m ago`;
|
|
638
|
+
} else {
|
|
639
|
+
ageStr = "just now";
|
|
640
|
+
}
|
|
641
|
+
restoredAssets.push({
|
|
642
|
+
asset,
|
|
643
|
+
size: dataToWrite.byteLength,
|
|
644
|
+
versionId,
|
|
645
|
+
age: ageStr
|
|
646
|
+
});
|
|
647
|
+
}
|
|
648
|
+
}).catch((error) => {
|
|
649
|
+
if (options.debug) {
|
|
650
|
+
logger.warn(`Failed to restore asset ${asset} from version ${versionId}:`, error);
|
|
651
|
+
}
|
|
652
|
+
});
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
if (restoredAssets.length > 0) {
|
|
656
|
+
restoredAssets.forEach((item, index) => {
|
|
657
|
+
const isLast = index === restoredAssets.length - 1;
|
|
658
|
+
const prefix = isLast ? " \u2514\u2500" : " \u251C\u2500";
|
|
659
|
+
const sizeKB = (item.size / 1024).toFixed(2);
|
|
660
|
+
const displayPath = `public/${item.asset}`;
|
|
661
|
+
const sizeInfo = `(${sizeKB} kB)`;
|
|
662
|
+
const versionInfo = `[${item.versionId.slice(0, 8)}]`;
|
|
663
|
+
const ageInfo = `(${item.age})`;
|
|
664
|
+
logger.log(utils.colors.gray(`${prefix} ${displayPath} ${sizeInfo} ${versionInfo} ${ageInfo}`));
|
|
665
|
+
});
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
async function augmentBuildMetadata(buildId, outputDir) {
|
|
669
|
+
const manifest = await getVersionManifest(storage);
|
|
670
|
+
const latestPath = pathe.join(outputDir, "public", "_nuxt", "builds", "latest.json");
|
|
671
|
+
try {
|
|
672
|
+
const latestData = await node_fs.promises.readFile(latestPath, "utf-8");
|
|
673
|
+
const latestJson = JSON.parse(latestData);
|
|
674
|
+
latestJson.skewProtection = {
|
|
675
|
+
versions: manifest.versions
|
|
676
|
+
};
|
|
677
|
+
await node_fs.promises.writeFile(latestPath, JSON.stringify(latestJson, null, 2), "utf-8");
|
|
678
|
+
} catch (error) {
|
|
679
|
+
if (options.debug) {
|
|
680
|
+
logger.warn("Failed to augment builds/latest.json:", error);
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
const metaPath = pathe.join(outputDir, "public", "_nuxt", "builds", "meta", `${buildId}.json`);
|
|
684
|
+
try {
|
|
685
|
+
const metaData = await node_fs.promises.readFile(metaPath, "utf-8");
|
|
686
|
+
const metaJson = JSON.parse(metaData);
|
|
687
|
+
const versionData = manifest.versions[buildId];
|
|
688
|
+
if (versionData) {
|
|
689
|
+
metaJson.skewProtection = {
|
|
690
|
+
assets: versionData.assets,
|
|
691
|
+
deletedChunks: versionData.deletedChunks,
|
|
692
|
+
timestamp: versionData.timestamp,
|
|
693
|
+
expires: versionData.expires
|
|
694
|
+
};
|
|
695
|
+
}
|
|
696
|
+
await node_fs.promises.writeFile(metaPath, JSON.stringify(metaJson, null, 2), "utf-8");
|
|
697
|
+
} catch (error) {
|
|
698
|
+
if (options.debug) {
|
|
699
|
+
logger.warn(`Failed to augment builds/meta/${buildId}.json:`, error);
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
return {
|
|
704
|
+
getAssetsFromBuild,
|
|
705
|
+
updateVersionsManifest,
|
|
706
|
+
cleanupExpiredVersions,
|
|
707
|
+
storeAssetsInStorage,
|
|
708
|
+
listExistingVersions,
|
|
709
|
+
restoreOldAssetsToPublic,
|
|
710
|
+
augmentBuildMetadata
|
|
711
|
+
};
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
const module$1 = kit.defineNuxtModule({
|
|
715
|
+
meta: {
|
|
716
|
+
name: "nuxt-skew-protection",
|
|
717
|
+
compatibility: {
|
|
718
|
+
nuxt: ">=4.0.0"
|
|
719
|
+
},
|
|
720
|
+
configKey: "skewProtection"
|
|
721
|
+
},
|
|
722
|
+
defaults: {
|
|
723
|
+
retentionDays: 30,
|
|
724
|
+
maxNumberOfVersions: 10,
|
|
725
|
+
bundlePreviousDeploymentChunks: true,
|
|
726
|
+
cookie: {
|
|
727
|
+
name: "__nkpv",
|
|
728
|
+
path: "/",
|
|
729
|
+
sameSite: "strict",
|
|
730
|
+
maxAge: 60 * 60 * 24 * 60
|
|
731
|
+
// 60 days
|
|
732
|
+
},
|
|
733
|
+
storage: {
|
|
734
|
+
driver: "fs",
|
|
735
|
+
base: "node_modules/.cache/nuxt/skew-protection"
|
|
736
|
+
},
|
|
737
|
+
debug: false
|
|
738
|
+
},
|
|
739
|
+
async setup(options, nuxt) {
|
|
740
|
+
const resolver = kit.createResolver((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('module.cjs', document.baseURI).href)));
|
|
741
|
+
logger.level = options.debug || nuxt.options.debug ? 4 : 3;
|
|
742
|
+
if (options.enabled === false) {
|
|
743
|
+
logger.debug("The module is disabled, skipping setup.");
|
|
744
|
+
return;
|
|
745
|
+
}
|
|
746
|
+
nuxt.options.runtimeConfig.public = nuxt.options.runtimeConfig.public || {};
|
|
747
|
+
nuxt.options.runtimeConfig.public.skewProtection = {
|
|
748
|
+
cookie: options.cookie,
|
|
749
|
+
debug: options.debug
|
|
750
|
+
};
|
|
751
|
+
const nitroPreset = nuxt.options.nitro?.preset || resolveNitroPreset(nuxt);
|
|
752
|
+
kit.addTypeTemplate({
|
|
753
|
+
filename: "types/nuxt-skew-protection.d.ts",
|
|
754
|
+
getContents: () => {
|
|
755
|
+
return `// Generated by nuxt-skew-protection
|
|
756
|
+
declare module '#app' {
|
|
757
|
+
interface NuxtAppManifestMeta {
|
|
758
|
+
skewProtection?: {
|
|
759
|
+
versions?: Record<string, {
|
|
760
|
+
timestamp: string
|
|
761
|
+
expires: string
|
|
762
|
+
assets: string[]
|
|
763
|
+
deletedChunks?: string[]
|
|
764
|
+
}>
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
declare module 'nuxt/app' {
|
|
770
|
+
interface NuxtAppManifestMeta {
|
|
771
|
+
skewProtection?: {
|
|
772
|
+
versions?: Record<string, {
|
|
773
|
+
timestamp: string
|
|
774
|
+
expires: string
|
|
775
|
+
assets: string[]
|
|
776
|
+
deletedChunks?: string[]
|
|
777
|
+
}>
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
export {}
|
|
783
|
+
`;
|
|
784
|
+
}
|
|
785
|
+
}, {
|
|
786
|
+
nuxt: true
|
|
787
|
+
});
|
|
788
|
+
kit.addComponent({
|
|
789
|
+
name: "SkewNotification",
|
|
790
|
+
filePath: resolver.resolve(`./runtime/app/components/SkewNotification.vue`)
|
|
791
|
+
});
|
|
792
|
+
kit.addPlugin({
|
|
793
|
+
src: resolver.resolve("./runtime/app/plugins/0.skew-protection")
|
|
794
|
+
});
|
|
795
|
+
kit.addImports({
|
|
796
|
+
name: "useSkewProtection",
|
|
797
|
+
from: resolver.resolve("./runtime/app/composables/useSkewProtection")
|
|
798
|
+
});
|
|
799
|
+
kit.addImports({
|
|
800
|
+
name: "useSkewProtectionCookie",
|
|
801
|
+
from: resolver.resolve("./runtime/app/composables/useSkewProtectionCookie")
|
|
802
|
+
});
|
|
803
|
+
nuxt.options.alias["nuxt-skew-protection/server"] = resolver.resolve("./runtime/server");
|
|
804
|
+
if (options.storage?.driver) {
|
|
805
|
+
nuxt.options.nitro.storage = nuxt.options.nitro.storage || {};
|
|
806
|
+
nuxt.options.nitro.storage["skew-protection"] = options.storage;
|
|
807
|
+
}
|
|
808
|
+
if (!nuxt.options.dev) {
|
|
809
|
+
const isCloudflareRuntime = nitroPreset?.includes("cloudflare");
|
|
810
|
+
const isVercel = nitroPreset?.includes("vercel") || process.env.VERCEL_SKEW_PROTECTION_ENABLED === "1";
|
|
811
|
+
if (!options.checkForUpdateStrategy) {
|
|
812
|
+
options.checkForUpdateStrategy = isStaticPreset(nuxt) ? "polling" : isCloudflareRuntime ? "ws" : options.checkForUpdateStrategy || "sse";
|
|
813
|
+
}
|
|
814
|
+
if (isVercel) {
|
|
815
|
+
kit.addServerHandler({
|
|
816
|
+
handler: resolver.resolve("./runtime/server/middleware/vercel-skew"),
|
|
817
|
+
middleware: true
|
|
818
|
+
});
|
|
819
|
+
}
|
|
820
|
+
kit.addServerHandler({
|
|
821
|
+
handler: resolver.resolve("./runtime/server/middleware/set-skew-protection-cookie"),
|
|
822
|
+
middleware: true
|
|
823
|
+
});
|
|
824
|
+
kit.addPlugin({
|
|
825
|
+
src: resolver.resolve("./runtime/app/plugins/sw-track-user-modules.client"),
|
|
826
|
+
mode: "client"
|
|
827
|
+
});
|
|
828
|
+
let swPath = resolver.resolve("./sw");
|
|
829
|
+
if (!node_fs.existsSync(swPath)) {
|
|
830
|
+
swPath = resolver.resolve("../sw");
|
|
831
|
+
}
|
|
832
|
+
nuxt.options.nitro.publicAssets = nuxt.options.nitro.publicAssets || [];
|
|
833
|
+
nuxt.options.nitro.publicAssets.push({
|
|
834
|
+
dir: swPath,
|
|
835
|
+
maxAge: 0
|
|
836
|
+
// Service workers should not be cached
|
|
837
|
+
});
|
|
838
|
+
if (options.storage && options.bundlePreviousDeploymentChunks) {
|
|
839
|
+
nuxt.hook("nitro:build:public-assets", async (nitro) => {
|
|
840
|
+
const buildId = nuxt.options.runtimeConfig.app.buildId ||= nuxt.options.buildId;
|
|
841
|
+
const outputDir = nitro.options.output.dir;
|
|
842
|
+
const assetManager = createAssetManager({
|
|
843
|
+
...options,
|
|
844
|
+
driver: await resolveBuildTimeDriver(options.storage)
|
|
845
|
+
});
|
|
846
|
+
const assets = await assetManager.getAssetsFromBuild(outputDir);
|
|
847
|
+
const { isExistingVersion } = await assetManager.updateVersionsManifest(buildId, assets);
|
|
848
|
+
await assetManager.storeAssetsInStorage(buildId, outputDir, assets);
|
|
849
|
+
const existingVersions = await assetManager.listExistingVersions();
|
|
850
|
+
const versionCount = existingVersions.filter((v) => v.id !== buildId).length;
|
|
851
|
+
if (versionCount > 0) {
|
|
852
|
+
logger.log(`Restoring build files from the last ${versionCount} release${versionCount > 1 ? "s" : ""}...`);
|
|
853
|
+
}
|
|
854
|
+
await assetManager.restoreOldAssetsToPublic(buildId, outputDir, assets, isExistingVersion);
|
|
855
|
+
await assetManager.augmentBuildMetadata(buildId, outputDir);
|
|
856
|
+
await assetManager.cleanupExpiredVersions();
|
|
857
|
+
});
|
|
858
|
+
}
|
|
859
|
+
if (options.checkForUpdateStrategy === "ws") {
|
|
860
|
+
if (!nuxt.options.nitro.experimental?.websocket) {
|
|
861
|
+
logger.warn("You need to enable `experimental.websocket` in your Nitro config to use WebSockets. Falling back to polling.");
|
|
862
|
+
options.checkForUpdateStrategy = "polling";
|
|
863
|
+
} else if (isCloudflareRuntime && nitroPreset !== "cloudflare-durable") {
|
|
864
|
+
logger.warn("Websockets are only supported in Cloudflare using `cloudflare-durable` preset. Falling back to polling.");
|
|
865
|
+
options.checkForUpdateStrategy = "polling";
|
|
866
|
+
} else {
|
|
867
|
+
kit.addServerHandler({
|
|
868
|
+
route: "/_skew/ws",
|
|
869
|
+
handler: resolver.resolve(`./runtime/server/routes/_skew/ws`)
|
|
870
|
+
});
|
|
871
|
+
kit.addPlugin(resolver.resolve("./runtime/app/plugins/check-updates-websocket.client"));
|
|
872
|
+
}
|
|
873
|
+
} else if (options.checkForUpdateStrategy === "sse") {
|
|
874
|
+
if (isStaticPreset(nuxt) || isCloudflareRuntime) {
|
|
875
|
+
logger.warn("SSE not supported for static sites or Cloudflare Workers. Falling back to polling.");
|
|
876
|
+
options.checkForUpdateStrategy = "polling";
|
|
877
|
+
} else if (isCloudflareRuntime) {
|
|
878
|
+
logger.warn("SSE not supported on Cloudflare Workers (no persistent connections). Falling back to polling.");
|
|
879
|
+
options.checkForUpdateStrategy = "polling";
|
|
880
|
+
} else {
|
|
881
|
+
kit.addServerHandler({
|
|
882
|
+
route: "/_skew/sse",
|
|
883
|
+
handler: resolver.resolve("./runtime/server/routes/_skew/sse")
|
|
884
|
+
});
|
|
885
|
+
kit.addPlugin({
|
|
886
|
+
src: resolver.resolve("./runtime/app/plugins/check-updates-sse.client"),
|
|
887
|
+
mode: "client"
|
|
888
|
+
});
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
if (options.checkForUpdateStrategy === "polling") {
|
|
892
|
+
nuxt.options.experimental.checkOutdatedBuildInterval = 20;
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
});
|
|
897
|
+
|
|
898
|
+
module.exports = module$1;
|