nuxt-skew-protection 0.7.2 → 0.7.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 CHANGED
@@ -9,7 +9,7 @@
9
9
  "version": ">=5.6.7"
10
10
  }
11
11
  },
12
- "version": "0.7.2",
12
+ "version": "0.7.4",
13
13
  "builder": {
14
14
  "@nuxt/module-builder": "1.0.2",
15
15
  "unbuild": "3.6.1"
package/dist/module.mjs CHANGED
@@ -10,10 +10,16 @@ import { join } from 'node:path';
10
10
  import { tmpdir } from 'node:os';
11
11
  import { x } from 'tinyexec';
12
12
  import { defineDriver, createStorage } from 'unstorage';
13
+ import { createHash } from 'node:crypto';
13
14
  import { join as join$1, dirname } from 'pathe';
14
15
 
15
16
  const logger = useLogger("nuxt-skew-protection");
16
17
 
18
+ function registerNuxtSeoProModule(registration) {
19
+ const nuxt = useNuxt();
20
+ nuxt._nuxtSeoProModules = nuxt._nuxtSeoProModules || [];
21
+ nuxt._nuxtSeoProModules.push(registration);
22
+ }
17
23
  function isStaticPreset(nuxt = useNuxt()) {
18
24
  return nuxt.options.nitro?.static || nuxt.options._generate || [
19
25
  "static",
@@ -52,7 +58,7 @@ function hookNuxtSeoProLicense() {
52
58
  const isBuild = !nuxt.options.dev && !nuxt.options._prepare;
53
59
  if (isBuild && !nuxt._isNuxtSeoProVerifying) {
54
60
  const license = nuxt.options.runtimeConfig.seoProKey || process.env.NUXT_SEO_PRO_KEY;
55
- if (isTest) {
61
+ if (isTest || process.env.VITEST) {
56
62
  return;
57
63
  }
58
64
  if (!isCI && !license) {
@@ -72,9 +78,15 @@ function hookNuxtSeoProLicense() {
72
78
  spinner.start("\u{1F511} Verifying Nuxt SEO Pro license...");
73
79
  const siteUrl = siteConfig.url?.startsWith("http") ? siteConfig.url : void 0;
74
80
  const siteName = siteConfig.name || void 0;
81
+ const modules = nuxt._nuxtSeoProModules?.length > 0 ? nuxt._nuxtSeoProModules : void 0;
75
82
  const res = await $fetch("https://nuxtseo.com/api/pro/verify", {
76
83
  method: "POST",
77
- body: { apiKey: license, siteUrl, siteName }
84
+ body: {
85
+ apiKey: license,
86
+ siteUrl,
87
+ siteName,
88
+ modules
89
+ }
78
90
  }).catch((err) => {
79
91
  if (err?.response?.status === 401) {
80
92
  spinner.stop("\u274C Invalid API key");
@@ -666,9 +678,10 @@ function createAssetManager(options) {
666
678
  }
667
679
  logger.debug(`restoreOldAssetsToPublic: total ${formatDuration(Date.now() - startTime)}`);
668
680
  }
669
- async function augmentBuildMetadata(buildId, publicDir) {
681
+ async function augmentBuildMetadata(buildId, publicDir, serverDir) {
670
682
  const manifest = await getVersionManifest(storage);
671
683
  const latestPath = join$1(publicDir, "_nuxt", "builds", "latest.json");
684
+ let newLatestContent;
672
685
  try {
673
686
  const latestData = await promises.readFile(latestPath, "utf-8");
674
687
  const latestJson = JSON.parse(latestData);
@@ -682,7 +695,8 @@ function createAssetManager(options) {
682
695
  latestJson.skewProtection = {
683
696
  versions: clientVersions
684
697
  };
685
- await promises.writeFile(latestPath, JSON.stringify(latestJson, null, 2), "utf-8");
698
+ newLatestContent = JSON.stringify(latestJson, null, 2);
699
+ await promises.writeFile(latestPath, newLatestContent, "utf-8");
686
700
  } catch (error) {
687
701
  if (options.debug) {
688
702
  logger.warn("Failed to augment builds/latest.json:", error);
@@ -705,6 +719,64 @@ function createAssetManager(options) {
705
719
  logger.warn(`Failed to augment builds/meta/${buildId}.json:`, error);
706
720
  }
707
721
  }
722
+ if (serverDir && newLatestContent) {
723
+ await patchNitroManifest(serverDir, "/_nuxt/builds/latest.json", newLatestContent);
724
+ }
725
+ }
726
+ async function patchNitroManifest(serverDir, assetPath, newContent) {
727
+ const nitroPath = join$1(serverDir, "chunks", "nitro", "nitro.mjs");
728
+ let nitro = await promises.readFile(nitroPath, "utf-8").catch(() => null);
729
+ if (!nitro)
730
+ return;
731
+ const assetIdx = nitro.indexOf(`"${assetPath}":`);
732
+ if (assetIdx === -1)
733
+ return;
734
+ const size = Buffer.byteLength(newContent, "utf-8");
735
+ const hash = createHash("sha1").update(newContent).digest("base64").substring(0, 27);
736
+ const newEtag = `"${size.toString(16)}-${hash}"`;
737
+ const start = nitro.indexOf("{", assetIdx);
738
+ if (start === -1)
739
+ return;
740
+ let depth = 0;
741
+ let stringChar = null;
742
+ let end = -1;
743
+ for (let i = start; i < nitro.length; i++) {
744
+ const char = nitro[i];
745
+ if (stringChar) {
746
+ if (char === "\\")
747
+ i++;
748
+ else if (char === stringChar)
749
+ stringChar = null;
750
+ } else {
751
+ if (char === '"' || char === "'") {
752
+ stringChar = char;
753
+ } else if (char === "{") {
754
+ depth++;
755
+ } else if (char === "}") {
756
+ depth--;
757
+ if (depth === 0) {
758
+ end = i;
759
+ break;
760
+ }
761
+ }
762
+ }
763
+ }
764
+ if (end === -1)
765
+ return;
766
+ let entryStr = nitro.substring(start, end + 1);
767
+ entryStr = entryStr.replace(/(['"]?)size\1\s*:\s*\d+/, (match) => {
768
+ const prefix = match.match(/^(['"]?)size\1\s*:\s*/)?.[0] || "size:";
769
+ return `${prefix}${size}`;
770
+ });
771
+ entryStr = entryStr.replace(/(['"]?)etag\1\s*:\s*(['"])(?:[^\\]|\\.)*?\2/, (match) => {
772
+ const keyMatch = match.match(/^(['"]?)etag\1\s*:\s*/);
773
+ const prefix = keyMatch?.[0] || "etag:";
774
+ const quoteChar = match.match(/:\s*(['"])/)?.[1] || '"';
775
+ const escapedEtag = quoteChar === "'" ? newEtag : newEtag.replace(/"/g, '\\"');
776
+ return `${prefix}${quoteChar}${escapedEtag}${quoteChar}`;
777
+ });
778
+ nitro = nitro.substring(0, start) + entryStr + nitro.substring(end + 1);
779
+ await promises.writeFile(nitroPath, nitro, "utf-8");
708
780
  }
709
781
  return {
710
782
  getAssetsFromBuild,
@@ -931,6 +1003,21 @@ export {}
931
1003
  logger.warn(`Strategy "${resolvedStrategy}" requires a server but static generation detected. Falling back to polling.`);
932
1004
  resolvedStrategy = "polling";
933
1005
  }
1006
+ const adapterName = isAdapter ? options.updateStrategy.name : void 0;
1007
+ registerNuxtSeoProModule({
1008
+ name: "nuxt-skew-protection",
1009
+ version,
1010
+ features: {
1011
+ updateStrategy: adapterName || resolvedStrategy,
1012
+ connectionTracking: !!options.connectionTracking,
1013
+ routeTracking: !!(options.connectionTracking && options.routeTracking),
1014
+ ipTracking: !!(options.connectionTracking && options.ipTracking),
1015
+ bundlePreviousDeploymentChunks: options.bundlePreviousDeploymentChunks !== false,
1016
+ storageDriver: options.storage?.driver || "none",
1017
+ preset: nitroPreset,
1018
+ isStatic
1019
+ }
1020
+ });
934
1021
  if (isVercel) {
935
1022
  addServerHandler({
936
1023
  handler: resolver.resolve("./runtime/server/middleware/vercel-skew"),
@@ -943,6 +1030,13 @@ export {}
943
1030
  middleware: true
944
1031
  });
945
1032
  }
1033
+ if (options.connectionTracking && !isStatic) {
1034
+ addServerHandler({
1035
+ route: "/_skew/admin/stats",
1036
+ method: "get",
1037
+ handler: resolver.resolve("./runtime/server/routes/_skew/admin/stats.get")
1038
+ });
1039
+ }
946
1040
  addPlugin({
947
1041
  src: resolver.resolve("./runtime/app/plugins/sw-track-user-modules.client"),
948
1042
  mode: "client"
@@ -1002,7 +1096,8 @@ export {}
1002
1096
  logger.log(`Restoring build files from ${versionCount} release${versionCount > 1 ? "s" : ""} (${totalAssets} assets) [${versionSizes.join(", ")}]...`);
1003
1097
  }
1004
1098
  await assetManager.restoreOldAssetsToPublic(buildId, publicDir, assets, isExistingVersion);
1005
- await assetManager.augmentBuildMetadata(buildId, publicDir);
1099
+ const serverDir = nitro.options.output.serverDir;
1100
+ await assetManager.augmentBuildMetadata(buildId, publicDir, serverDir);
1006
1101
  });
1007
1102
  nitro.hooks.hook("close", async () => {
1008
1103
  if (assetManager) {
@@ -1,4 +1,8 @@
1
1
  import type { SkewAdapterConfig } from '../types.js';
2
2
  export type { SkewAdapterConfig };
3
- declare const _default: import("nuxt/app").Plugin<Record<string, unknown>> & import("nuxt/app").ObjectPlugin<Record<string, unknown>>;
3
+ declare const _default: import("nuxt/app").Plugin<{
4
+ skewConnection: import("../utils/create-skew-connection.js").SkewConnection;
5
+ }> & import("nuxt/app").ObjectPlugin<{
6
+ skewConnection: import("../utils/create-skew-connection.js").SkewConnection;
7
+ }>;
4
8
  export default _default;
@@ -6,7 +6,7 @@ export default defineNuxtPlugin({
6
6
  name: "skew-protection:adapter-updates",
7
7
  async setup() {
8
8
  if (import.meta.prerender)
9
- return;
9
+ return {};
10
10
  const nuxtApp = useNuxtApp();
11
11
  const adapterName = useRuntimeConfig().public.skewProtection.adapterName;
12
12
  const config = {
@@ -1,4 +1,8 @@
1
1
  import type { SkewSSEConfig } from '../types.js';
2
2
  export type { SkewSSEConfig };
3
- declare const _default: import("nuxt/app").Plugin<Record<string, unknown>> & import("nuxt/app").ObjectPlugin<Record<string, unknown>>;
3
+ declare const _default: import("nuxt/app").Plugin<{
4
+ skewConnection: import("../utils/create-skew-connection.js").SkewConnection;
5
+ }> & import("nuxt/app").ObjectPlugin<{
6
+ skewConnection: import("../utils/create-skew-connection.js").SkewConnection;
7
+ }>;
4
8
  export default _default;
@@ -6,7 +6,7 @@ export default defineNuxtPlugin({
6
6
  name: "skew-protection:sse-updates",
7
7
  async setup() {
8
8
  if (import.meta.prerender)
9
- return;
9
+ return {};
10
10
  const nuxtApp = useNuxtApp();
11
11
  const router = useRouter();
12
12
  const runtimeConfig = useRuntimeConfig();
@@ -1,4 +1,8 @@
1
1
  import type { SkewWebSocketConfig } from '../types.js';
2
2
  export type { SkewWebSocketConfig };
3
- declare const _default: import("nuxt/app").Plugin<Record<string, unknown>> & import("nuxt/app").ObjectPlugin<Record<string, unknown>>;
3
+ declare const _default: import("nuxt/app").Plugin<{
4
+ skewConnection: import("../utils/create-skew-connection.js").SkewConnection;
5
+ }> & import("nuxt/app").ObjectPlugin<{
6
+ skewConnection: import("../utils/create-skew-connection.js").SkewConnection;
7
+ }>;
4
8
  export default _default;
@@ -7,7 +7,7 @@ export default defineNuxtPlugin({
7
7
  name: "skew-protection:ws-updates",
8
8
  async setup() {
9
9
  if (import.meta.prerender)
10
- return;
10
+ return {};
11
11
  const nuxtApp = useNuxtApp();
12
12
  const router = useRouter();
13
13
  const runtimeConfig = useRuntimeConfig();
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Admin endpoint for nuxtseo.com dashboard to query live connection stats.
3
+ * Requires Authorization header with SEO Pro key.
4
+ */
5
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<unknown>>;
6
+ export default _default;
@@ -0,0 +1,19 @@
1
+ import { createError, defineEventHandler, getHeader } from "h3";
2
+ import { useNitroApp, useRuntimeConfig } from "nitropack/runtime";
3
+ export default defineEventHandler(async (event) => {
4
+ const config = useRuntimeConfig(event);
5
+ const seoProKey = config.seoProKey || process.env.NUXT_SEO_PRO_KEY;
6
+ if (!seoProKey) {
7
+ throw createError({ statusCode: 503, message: "SEO Pro key not configured" });
8
+ }
9
+ const authHeader = getHeader(event, "authorization") || "";
10
+ const providedKey = authHeader.startsWith("Bearer ") ? authHeader.slice(7) : authHeader;
11
+ if (providedKey !== seoProKey) {
12
+ throw createError({ statusCode: 401, message: "Unauthorized" });
13
+ }
14
+ return new Promise((resolve) => {
15
+ useNitroApp().hooks.callHook("skew:stats", (stats) => {
16
+ resolve(stats);
17
+ });
18
+ });
19
+ });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nuxt-skew-protection",
3
3
  "type": "module",
4
- "version": "0.7.2",
4
+ "version": "0.7.4",
5
5
  "description": "Solve Nuxt version skews with persistent assets and instant updates.",
6
6
  "author": {
7
7
  "name": "Harlan Wilton",
@@ -55,20 +55,20 @@
55
55
  "consola": "^3.4.2",
56
56
  "cookie-es": "^2.0.0",
57
57
  "defu": "^6.1.4",
58
- "nuxt-site-config": "^3.2.14",
58
+ "nuxt-site-config": "^3.2.17",
59
59
  "ofetch": "^1.5.1",
60
60
  "pathe": "^2.0.3",
61
61
  "pkg-types": "^2.3.0",
62
62
  "std-env": "^3.10.0",
63
63
  "tinyexec": "^1.0.2",
64
- "ufo": "^1.6.2",
65
- "unstorage": "^1.17.3",
64
+ "ufo": "^1.6.3",
65
+ "unstorage": "^1.17.4",
66
66
  "zod": "^4.3.5"
67
67
  },
68
68
  "devDependencies": {
69
- "@antfu/eslint-config": "^6.7.3",
69
+ "@antfu/eslint-config": "^7.0.1",
70
70
  "@arethetypeswrong/cli": "^0.18.2",
71
- "@nuxt/content": "^3.10.0",
71
+ "@nuxt/content": "^3.11.0",
72
72
  "@nuxt/devtools-ui-kit": "^3.1.1",
73
73
  "@nuxt/module-builder": "^1.0.2",
74
74
  "@nuxt/test-utils": "^3.23.0",
@@ -84,27 +84,27 @@
84
84
  "@unocss/preset-uno": "66.5.12",
85
85
  "@unocss/runtime": "66.5.12",
86
86
  "@vueuse/nuxt": "^14.1.0",
87
- "ably": "^2.16.0",
88
- "better-sqlite3": "^12.5.0",
89
- "bumpp": "^10.3.2",
87
+ "ably": "^2.17.0",
88
+ "better-sqlite3": "^12.6.0",
89
+ "bumpp": "^10.4.0",
90
90
  "eslint": "^9.39.2",
91
91
  "eventsource": "^4.1.0",
92
92
  "execa": "^9.6.1",
93
- "firebase-functions": "^7.0.2",
94
- "happy-dom": "^20.0.11",
95
- "ioredis": "^5.9.0",
93
+ "firebase-functions": "^7.0.3",
94
+ "happy-dom": "^20.3.1",
95
+ "ioredis": "^5.9.2",
96
96
  "nuxt": "^4.2.2",
97
- "nuxt-auth-utils": "^0.5.26",
97
+ "nuxt-auth-utils": "^0.5.27",
98
98
  "playwright-core": "^1.57.0",
99
99
  "pusher-js": "^8.4.0",
100
100
  "tsx": "^4.21.0",
101
101
  "typescript": "^5.9.3",
102
102
  "unocss": "66.5.12",
103
- "vitest": "^4.0.16",
103
+ "vitest": "^4.0.17",
104
104
  "vue": "^3.5.26",
105
105
  "vue-router": "^4.6.4",
106
106
  "vue-tsc": "^3.2.2",
107
- "wrangler": "^4.54.0",
107
+ "wrangler": "^4.59.2",
108
108
  "ws": "^8.19.0"
109
109
  },
110
110
  "resolutions": {