nuxt-skew-protection 1.4.2 → 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 +54 -8
- 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)}`;
|
|
@@ -188,28 +192,38 @@ async function resolveBuildTimeDriver(storage) {
|
|
|
188
192
|
}
|
|
189
193
|
|
|
190
194
|
const virtualEntryId = "virtual:nuxt-skew-protection/cloudflare-entry";
|
|
195
|
+
const cloudflareAssetProtectionPluginName = "nuxt-skew-protection:cloudflare-asset-fetch";
|
|
191
196
|
const resolvedVirtualEntryId = `\0${virtualEntryId}`;
|
|
192
197
|
const legacyCloudflareAdapterSuffixes = [
|
|
193
198
|
"/nitropack/dist/runtime/entries/cloudflare-module.mjs",
|
|
194
199
|
"/nitropack/dist/runtime/entries/cloudflare.mjs",
|
|
195
200
|
"/nitropack/dist/runtime/entries/cloudflare-pages.mjs"
|
|
196
201
|
];
|
|
197
|
-
const nitroPrerenderEntrySuffix = "/nitropack/dist/presets/_nitro/runtime/nitro-prerenderer
|
|
202
|
+
const nitroPrerenderEntrySuffix = "/nitropack/dist/presets/_nitro/runtime/nitro-prerenderer";
|
|
198
203
|
function isNitroPrerenderEntry(id) {
|
|
199
|
-
|
|
204
|
+
const normalizedId = id.split("?", 1)[0].replaceAll("\\", "/");
|
|
205
|
+
return normalizedId.endsWith(nitroPrerenderEntrySuffix) || normalizedId.endsWith(`${nitroPrerenderEntrySuffix}.mjs`);
|
|
200
206
|
}
|
|
201
207
|
function isLegacyCloudflareEntry(id) {
|
|
202
208
|
const normalizedId = id.split("?", 1)[0].replaceAll("\\", "/");
|
|
203
209
|
return legacyCloudflareAdapterSuffixes.some((suffix) => normalizedId.endsWith(suffix));
|
|
204
210
|
}
|
|
205
|
-
function
|
|
211
|
+
function normalizeBuildAssetsPath(value) {
|
|
206
212
|
const path = value.replace(/^\/+|\/+$/g, "");
|
|
207
213
|
return `/${path}/`;
|
|
208
214
|
}
|
|
215
|
+
function withoutCloudflareAssetProtectionPlugin(plugins) {
|
|
216
|
+
return plugins.filter((plugin) => {
|
|
217
|
+
if (!plugin || typeof plugin !== "object" || !("name" in plugin))
|
|
218
|
+
return true;
|
|
219
|
+
return plugin.name !== cloudflareAssetProtectionPluginName;
|
|
220
|
+
});
|
|
221
|
+
}
|
|
209
222
|
function renderCloudflareEntry(options) {
|
|
210
223
|
const nitroEntryId = JSON.stringify(options.nitroEntryId);
|
|
211
224
|
const runtimeHelperId = JSON.stringify(options.runtimeHelperId);
|
|
212
|
-
const
|
|
225
|
+
const buildAssetsPath = JSON.stringify(normalizeBuildAssetsPath(options.buildAssetsPath));
|
|
226
|
+
const recoveryPath = JSON.stringify(options.recoveryPath);
|
|
213
227
|
return `import nitroEntry from ${nitroEntryId};
|
|
214
228
|
import { fetchCloudflareBuildAsset } from ${runtimeHelperId};
|
|
215
229
|
export * from ${nitroEntryId};
|
|
@@ -221,7 +235,7 @@ if (!nitroEntry || typeof nitroEntry.fetch !== "function") {
|
|
|
221
235
|
export default {
|
|
222
236
|
...nitroEntry,
|
|
223
237
|
fetch(request, env, context) {
|
|
224
|
-
const assetResponse = fetchCloudflareBuildAsset(request, env.ASSETS, ${
|
|
238
|
+
const assetResponse = fetchCloudflareBuildAsset(request, env.ASSETS, ${buildAssetsPath}, ${recoveryPath});
|
|
225
239
|
return assetResponse ?? nitroEntry.fetch(request, env, context);
|
|
226
240
|
},
|
|
227
241
|
};`;
|
|
@@ -231,7 +245,7 @@ function createCloudflareAssetProtectionPlugin(options) {
|
|
|
231
245
|
let wrapperLoaded = false;
|
|
232
246
|
let shouldWrapEntry = true;
|
|
233
247
|
return {
|
|
234
|
-
name:
|
|
248
|
+
name: cloudflareAssetProtectionPluginName,
|
|
235
249
|
options(inputOptions) {
|
|
236
250
|
nitroEntryId = void 0;
|
|
237
251
|
wrapperLoaded = false;
|
|
@@ -279,6 +293,15 @@ function createCloudflareAssetProtectionPlugin(options) {
|
|
|
279
293
|
};
|
|
280
294
|
}
|
|
281
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
|
+
|
|
282
305
|
const RE_ENOTFOUND = /ENOTFOUND\s+(\S+)/;
|
|
283
306
|
const RE_GETADDRINFO = /getaddrinfo\s+\S+\s+(\S+)/;
|
|
284
307
|
const RE_SIZE_PROP = /(['"]?)size\1\s*:\s*\d+/;
|
|
@@ -905,8 +928,17 @@ const module$1 = defineNuxtModule({
|
|
|
905
928
|
if (options.ipTracking && !options.connectionTracking) {
|
|
906
929
|
logger.warn("`ipTracking` requires `connectionTracking: true`. IP tracking will be disabled.");
|
|
907
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`;
|
|
908
935
|
nuxt.options.runtimeConfig.public.skewProtection = {
|
|
909
936
|
basePath,
|
|
937
|
+
assetRecovery: usesCloudflareAssets ? {
|
|
938
|
+
_tag: "cloudflare",
|
|
939
|
+
buildAssetsPath,
|
|
940
|
+
recoveryPath
|
|
941
|
+
} : { _tag: "disabled" },
|
|
910
942
|
cookie: options.cookie,
|
|
911
943
|
debug: options.debug,
|
|
912
944
|
connectionTracking: options.connectionTracking,
|
|
@@ -916,7 +948,6 @@ const module$1 = defineNuxtModule({
|
|
|
916
948
|
multiTab: options.multiTab ?? true,
|
|
917
949
|
version
|
|
918
950
|
};
|
|
919
|
-
const nitroPreset = resolveNitroPreset(nuxt.options.nitro);
|
|
920
951
|
const isNuxtHub = hasNuxtModule("@nuxthub/core");
|
|
921
952
|
if (isNuxtHub && options.storage?.driver === "cloudflare-kv-binding" && !options.storage.namespaceId) {
|
|
922
953
|
logger.error("NuxtHub detected with cloudflare-kv-binding driver but no namespaceId configured.");
|
|
@@ -1072,16 +1103,31 @@ export {}
|
|
|
1072
1103
|
const isStatic = isNuxtGenerate(nuxt);
|
|
1073
1104
|
if (nitroPreset === "cloudflare-module" || nitroPreset === "cloudflare-durable") {
|
|
1074
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
|
+
);
|
|
1075
1113
|
nitroConfig.rollupConfig ||= {};
|
|
1076
1114
|
const existingPlugins = nitroConfig.rollupConfig.plugins;
|
|
1077
1115
|
nitroConfig.rollupConfig.plugins = [
|
|
1078
1116
|
...Array.isArray(existingPlugins) ? existingPlugins : existingPlugins ? [existingPlugins] : [],
|
|
1079
1117
|
createCloudflareAssetProtectionPlugin({
|
|
1080
|
-
|
|
1118
|
+
buildAssetsPath,
|
|
1119
|
+
recoveryPath,
|
|
1081
1120
|
runtimeHelperId: resolver.resolve("./runtime/server/utils/cloudflare-asset-fetch")
|
|
1082
1121
|
})
|
|
1083
1122
|
];
|
|
1084
1123
|
});
|
|
1124
|
+
nuxt.hook("nitro:init", (nitro) => {
|
|
1125
|
+
nitro.hooks.hook("prerender:config", (prerenderConfig) => {
|
|
1126
|
+
const plugins = prerenderConfig.rollupConfig?.plugins;
|
|
1127
|
+
if (Array.isArray(plugins))
|
|
1128
|
+
prerenderConfig.rollupConfig.plugins = withoutCloudflareAssetProtectionPlugin(plugins);
|
|
1129
|
+
});
|
|
1130
|
+
});
|
|
1085
1131
|
}
|
|
1086
1132
|
const isAdapter = isSkewAdapter(options.updateStrategy);
|
|
1087
1133
|
let resolvedStrategy = "polling";
|
|
@@ -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)});
|