nuxt-skew-protection 1.4.3 → 1.4.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/module.json +1 -1
- package/dist/module.mjs +38 -7
- package/dist/runtime/app/plugins/sw-track-user-modules.client.js +8 -1
- package/dist/runtime/server/utils/cloudflare-asset-fetch.d.ts +1 -1
- package/dist/runtime/server/utils/cloudflare-asset-fetch.js +38 -4
- package/dist/runtime/types.d.ts +9 -0
- package/dist/sw/_nuxt-skew-sw.js +1 -1
- package/package.json +1 -1
package/dist/module.json
CHANGED
package/dist/module.mjs
CHANGED
|
@@ -19,6 +19,10 @@ const DEFAULT_COOKIE_NAME = "__nkpv";
|
|
|
19
19
|
function trimSlashes(value) {
|
|
20
20
|
return value.replace(/^\/+|\/+$/g, "");
|
|
21
21
|
}
|
|
22
|
+
function resolveBuildAssetsPath(app = {}) {
|
|
23
|
+
const path = [app.baseURL, app.buildAssetsDir || "/_nuxt/"].map((value) => trimSlashes(value || "")).filter(Boolean).join("/");
|
|
24
|
+
return `/${path}/`;
|
|
25
|
+
}
|
|
22
26
|
function resolveBasePath(input = {}) {
|
|
23
27
|
if (input.basePath)
|
|
24
28
|
return `/${trimSlashes(input.basePath)}`;
|
|
@@ -195,15 +199,16 @@ const legacyCloudflareAdapterSuffixes = [
|
|
|
195
199
|
"/nitropack/dist/runtime/entries/cloudflare.mjs",
|
|
196
200
|
"/nitropack/dist/runtime/entries/cloudflare-pages.mjs"
|
|
197
201
|
];
|
|
198
|
-
const nitroPrerenderEntrySuffix = "/nitropack/dist/presets/_nitro/runtime/nitro-prerenderer
|
|
202
|
+
const nitroPrerenderEntrySuffix = "/nitropack/dist/presets/_nitro/runtime/nitro-prerenderer";
|
|
199
203
|
function isNitroPrerenderEntry(id) {
|
|
200
|
-
|
|
204
|
+
const normalizedId = id.split("?", 1)[0].replaceAll("\\", "/");
|
|
205
|
+
return normalizedId.endsWith(nitroPrerenderEntrySuffix) || normalizedId.endsWith(`${nitroPrerenderEntrySuffix}.mjs`);
|
|
201
206
|
}
|
|
202
207
|
function isLegacyCloudflareEntry(id) {
|
|
203
208
|
const normalizedId = id.split("?", 1)[0].replaceAll("\\", "/");
|
|
204
209
|
return legacyCloudflareAdapterSuffixes.some((suffix) => normalizedId.endsWith(suffix));
|
|
205
210
|
}
|
|
206
|
-
function
|
|
211
|
+
function normalizeBuildAssetsPath(value) {
|
|
207
212
|
const path = value.replace(/^\/+|\/+$/g, "");
|
|
208
213
|
return `/${path}/`;
|
|
209
214
|
}
|
|
@@ -217,7 +222,8 @@ function withoutCloudflareAssetProtectionPlugin(plugins) {
|
|
|
217
222
|
function renderCloudflareEntry(options) {
|
|
218
223
|
const nitroEntryId = JSON.stringify(options.nitroEntryId);
|
|
219
224
|
const runtimeHelperId = JSON.stringify(options.runtimeHelperId);
|
|
220
|
-
const
|
|
225
|
+
const buildAssetsPath = JSON.stringify(normalizeBuildAssetsPath(options.buildAssetsPath));
|
|
226
|
+
const recoveryPath = JSON.stringify(options.recoveryPath);
|
|
221
227
|
return `import nitroEntry from ${nitroEntryId};
|
|
222
228
|
import { fetchCloudflareBuildAsset } from ${runtimeHelperId};
|
|
223
229
|
export * from ${nitroEntryId};
|
|
@@ -229,7 +235,7 @@ if (!nitroEntry || typeof nitroEntry.fetch !== "function") {
|
|
|
229
235
|
export default {
|
|
230
236
|
...nitroEntry,
|
|
231
237
|
fetch(request, env, context) {
|
|
232
|
-
const assetResponse = fetchCloudflareBuildAsset(request, env.ASSETS, ${
|
|
238
|
+
const assetResponse = fetchCloudflareBuildAsset(request, env.ASSETS, ${buildAssetsPath}, ${recoveryPath});
|
|
233
239
|
return assetResponse ?? nitroEntry.fetch(request, env, context);
|
|
234
240
|
},
|
|
235
241
|
};`;
|
|
@@ -287,6 +293,15 @@ function createCloudflareAssetProtectionPlugin(options) {
|
|
|
287
293
|
};
|
|
288
294
|
}
|
|
289
295
|
|
|
296
|
+
function withCloudflareBuildAssetRouting(current, buildAssetsDir) {
|
|
297
|
+
if (current === true)
|
|
298
|
+
return true;
|
|
299
|
+
const prefix = `/${buildAssetsDir.replace(/^\/+|\/+$/g, "")}/`;
|
|
300
|
+
const pattern = `${prefix}*`;
|
|
301
|
+
const routes = Array.isArray(current) ? current.filter((route) => typeof route === "string") : [];
|
|
302
|
+
return routes.includes(pattern) ? routes : [...routes, pattern];
|
|
303
|
+
}
|
|
304
|
+
|
|
290
305
|
const RE_ENOTFOUND = /ENOTFOUND\s+(\S+)/;
|
|
291
306
|
const RE_GETADDRINFO = /getaddrinfo\s+\S+\s+(\S+)/;
|
|
292
307
|
const RE_SIZE_PROP = /(['"]?)size\1\s*:\s*\d+/;
|
|
@@ -913,8 +928,17 @@ const module$1 = defineNuxtModule({
|
|
|
913
928
|
if (options.ipTracking && !options.connectionTracking) {
|
|
914
929
|
logger.warn("`ipTracking` requires `connectionTracking: true`. IP tracking will be disabled.");
|
|
915
930
|
}
|
|
931
|
+
const nitroPreset = resolveNitroPreset(nuxt.options.nitro);
|
|
932
|
+
const usesCloudflareAssets = nitroPreset === "cloudflare-module" || nitroPreset === "cloudflare-durable";
|
|
933
|
+
const buildAssetsPath = resolveBuildAssetsPath(nuxt.options.app);
|
|
934
|
+
const recoveryPath = `${basePath}/asset`;
|
|
916
935
|
nuxt.options.runtimeConfig.public.skewProtection = {
|
|
917
936
|
basePath,
|
|
937
|
+
assetRecovery: usesCloudflareAssets ? {
|
|
938
|
+
_tag: "cloudflare",
|
|
939
|
+
buildAssetsPath,
|
|
940
|
+
recoveryPath
|
|
941
|
+
} : { _tag: "disabled" },
|
|
918
942
|
cookie: options.cookie,
|
|
919
943
|
debug: options.debug,
|
|
920
944
|
connectionTracking: options.connectionTracking,
|
|
@@ -924,7 +948,6 @@ const module$1 = defineNuxtModule({
|
|
|
924
948
|
multiTab: options.multiTab ?? true,
|
|
925
949
|
version
|
|
926
950
|
};
|
|
927
|
-
const nitroPreset = resolveNitroPreset(nuxt.options.nitro);
|
|
928
951
|
const isNuxtHub = hasNuxtModule("@nuxthub/core");
|
|
929
952
|
if (isNuxtHub && options.storage?.driver === "cloudflare-kv-binding" && !options.storage.namespaceId) {
|
|
930
953
|
logger.error("NuxtHub detected with cloudflare-kv-binding driver but no namespaceId configured.");
|
|
@@ -1080,12 +1103,20 @@ export {}
|
|
|
1080
1103
|
const isStatic = isNuxtGenerate(nuxt);
|
|
1081
1104
|
if (nitroPreset === "cloudflare-module" || nitroPreset === "cloudflare-durable") {
|
|
1082
1105
|
nuxt.hook("nitro:config", (nitroConfig) => {
|
|
1106
|
+
nitroConfig.cloudflare ||= {};
|
|
1107
|
+
nitroConfig.cloudflare.wrangler ||= {};
|
|
1108
|
+
nitroConfig.cloudflare.wrangler.assets ||= {};
|
|
1109
|
+
nitroConfig.cloudflare.wrangler.assets.run_worker_first = withCloudflareBuildAssetRouting(
|
|
1110
|
+
nitroConfig.cloudflare.wrangler.assets.run_worker_first,
|
|
1111
|
+
nuxt.options.app.buildAssetsDir
|
|
1112
|
+
);
|
|
1083
1113
|
nitroConfig.rollupConfig ||= {};
|
|
1084
1114
|
const existingPlugins = nitroConfig.rollupConfig.plugins;
|
|
1085
1115
|
nitroConfig.rollupConfig.plugins = [
|
|
1086
1116
|
...Array.isArray(existingPlugins) ? existingPlugins : existingPlugins ? [existingPlugins] : [],
|
|
1087
1117
|
createCloudflareAssetProtectionPlugin({
|
|
1088
|
-
|
|
1118
|
+
buildAssetsPath,
|
|
1119
|
+
recoveryPath,
|
|
1089
1120
|
runtimeHelperId: resolver.resolve("./runtime/server/utils/cloudflare-asset-fetch")
|
|
1090
1121
|
})
|
|
1091
1122
|
];
|
|
@@ -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
|
|
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;
|
|
@@ -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,
|
|
5
|
+
export declare function fetchCloudflareBuildAsset(request: Request, assets: CloudflareAssetBinding | undefined, buildAssetsPath: string, recoveryPath: string): Promise<Response> | undefined;
|
|
6
6
|
export {};
|
|
@@ -12,6 +12,36 @@ function disableCaching(response) {
|
|
|
12
12
|
function createRetryRequest(request) {
|
|
13
13
|
return new Request(request, { cache: "no-cache" });
|
|
14
14
|
}
|
|
15
|
+
function parseBuildAssetRequest(request, buildAssetsPath, recoveryPath) {
|
|
16
|
+
const requestUrl = new URL(request.url);
|
|
17
|
+
if (requestUrl.pathname.startsWith(buildAssetsPath)) {
|
|
18
|
+
return { _tag: "asset", request };
|
|
19
|
+
}
|
|
20
|
+
if (requestUrl.pathname !== recoveryPath) {
|
|
21
|
+
return { _tag: "unmatched" };
|
|
22
|
+
}
|
|
23
|
+
if (request.method !== "GET") {
|
|
24
|
+
return { _tag: "invalid-recovery" };
|
|
25
|
+
}
|
|
26
|
+
const target = requestUrl.searchParams.get("url");
|
|
27
|
+
if (!target) {
|
|
28
|
+
return { _tag: "invalid-recovery" };
|
|
29
|
+
}
|
|
30
|
+
if (!URL.canParse(target, requestUrl)) {
|
|
31
|
+
return { _tag: "invalid-recovery" };
|
|
32
|
+
}
|
|
33
|
+
const targetUrl = new URL(target, requestUrl);
|
|
34
|
+
if (targetUrl.origin !== requestUrl.origin || !targetUrl.pathname.startsWith(buildAssetsPath) || targetUrl.username || targetUrl.password) {
|
|
35
|
+
return { _tag: "invalid-recovery" };
|
|
36
|
+
}
|
|
37
|
+
return {
|
|
38
|
+
_tag: "asset",
|
|
39
|
+
request: new Request(targetUrl, {
|
|
40
|
+
cache: "no-cache",
|
|
41
|
+
headers: request.headers
|
|
42
|
+
})
|
|
43
|
+
};
|
|
44
|
+
}
|
|
15
45
|
export async function fetchCloudflareAsset(request, assets) {
|
|
16
46
|
const response = await assets.fetch(request);
|
|
17
47
|
if (response.status < 400) {
|
|
@@ -23,12 +53,16 @@ export async function fetchCloudflareAsset(request, assets) {
|
|
|
23
53
|
const retryResponse = await assets.fetch(createRetryRequest(request));
|
|
24
54
|
return retryResponse.status < 400 ? retryResponse : disableCaching(retryResponse);
|
|
25
55
|
}
|
|
26
|
-
export function fetchCloudflareBuildAsset(request, assets,
|
|
27
|
-
|
|
28
|
-
|
|
56
|
+
export function fetchCloudflareBuildAsset(request, assets, buildAssetsPath, recoveryPath) {
|
|
57
|
+
const parsed = parseBuildAssetRequest(request, buildAssetsPath, recoveryPath);
|
|
58
|
+
if (parsed._tag === "unmatched") {
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
if (parsed._tag === "invalid-recovery") {
|
|
62
|
+
return Promise.resolve(disableCaching(new Response(null, { status: 400 })));
|
|
29
63
|
}
|
|
30
64
|
if (!assets) {
|
|
31
65
|
return Promise.resolve(disableCaching(new Response(null, { status: 404 })));
|
|
32
66
|
}
|
|
33
|
-
return fetchCloudflareAsset(request, assets);
|
|
67
|
+
return fetchCloudflareAsset(parsed.request, assets);
|
|
34
68
|
}
|
package/dist/runtime/types.d.ts
CHANGED
|
@@ -1,4 +1,11 @@
|
|
|
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
|
+
};
|
|
2
9
|
export interface NuxtSkewProtectionRuntimeConfig {
|
|
3
10
|
/**
|
|
4
11
|
* Path prefix for the module's runtime endpoints (`/ws`, `/sse`, `/health`,
|
|
@@ -7,6 +14,7 @@ export interface NuxtSkewProtectionRuntimeConfig {
|
|
|
7
14
|
* that only owns part of the host, so the endpoints resolve to this app.
|
|
8
15
|
*/
|
|
9
16
|
basePath: string;
|
|
17
|
+
assetRecovery: AssetRecoveryConfig;
|
|
10
18
|
cookie: Omit<CookieSerializeOptions, 'encode'> & {
|
|
11
19
|
name?: string;
|
|
12
20
|
};
|
|
@@ -19,6 +27,7 @@ export interface NuxtSkewProtectionRuntimeConfig {
|
|
|
19
27
|
}
|
|
20
28
|
export interface SkewProtectionRuntimeConfig {
|
|
21
29
|
basePath: string;
|
|
30
|
+
assetRecovery: AssetRecoveryConfig;
|
|
22
31
|
cookie: Omit<CookieSerializeOptions, 'encode'> & {
|
|
23
32
|
name: string;
|
|
24
33
|
};
|
package/dist/sw/_nuxt-skew-sw.js
CHANGED
|
@@ -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)});
|