nuxt-skew-protection 0.4.3 → 0.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/README.md +1 -0
- package/dist/module.d.mts +6 -0
- package/dist/module.json +1 -1
- package/dist/module.mjs +86 -38
- package/dist/runtime/app/composables/useActiveConnections.d.ts +8 -0
- package/dist/runtime/app/composables/useActiveConnections.js +21 -0
- package/dist/runtime/app/plugins/check-updates-sse.client.js +1 -0
- package/dist/runtime/app/plugins/check-updates-websocket.client.d.ts +0 -14
- package/dist/runtime/app/plugins/check-updates-websocket.client.js +11 -18
- package/dist/runtime/server/plugins/connection-tracking.d.ts +2 -0
- package/dist/runtime/server/plugins/connection-tracking.js +25 -0
- package/dist/runtime/server/routes/_skew/sse.js +10 -4
- package/dist/runtime/server/routes/_skew/ws.js +17 -2
- package/dist/runtime/types.d.ts +2 -0
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -24,6 +24,7 @@ Nuxt Skew Protection solves this with proactive update prompts and persistent bu
|
|
|
24
24
|
- ⚡ **Instant Update Prompts** - Zero-config real-time notifications on deploy. Users adopt your latest build immediately.
|
|
25
25
|
- 🎯 **Chunk-Aware Targeting** - Notifications fire only when the user's loaded chunks are invalidated. No noise for unrelated updates.
|
|
26
26
|
- 🎨 **Headless UI** - Drop-in notification component with first-class Nuxt UI support.
|
|
27
|
+
- 📊 **Live Connection Monitoring** - Track active users and version distribution in real-time for admin dashboards and rollout progress.
|
|
27
28
|
- 🔌 **Third-Party Adapters** - Real-time updates on any platform (including static sites) via [Pusher](https://pusher.com) or [Ably](https://ably.com).
|
|
28
29
|
|
|
29
30
|
## Installation
|
package/dist/module.d.mts
CHANGED
|
@@ -56,6 +56,12 @@ interface ModuleOptions {
|
|
|
56
56
|
* @default false
|
|
57
57
|
*/
|
|
58
58
|
debug?: boolean;
|
|
59
|
+
/**
|
|
60
|
+
* Enable connection tracking to monitor active SSE/WebSocket connections
|
|
61
|
+
* Exposes useActiveConnections() composable with real-time stats
|
|
62
|
+
* @default false
|
|
63
|
+
*/
|
|
64
|
+
connectionTracking?: boolean;
|
|
59
65
|
}
|
|
60
66
|
interface ModulePublicRuntimeConfig {
|
|
61
67
|
skewProtection: NuxtSkewProtectionRuntimeConfig;
|
package/dist/module.json
CHANGED
package/dist/module.mjs
CHANGED
|
@@ -242,6 +242,29 @@ function isSkewAdapter(value) {
|
|
|
242
242
|
return typeof value === "object" && value !== null && "name" in value && "subscribe" in value && "broadcast" in value && typeof value.subscribe === "function" && typeof value.broadcast === "function";
|
|
243
243
|
}
|
|
244
244
|
|
|
245
|
+
function formatStorageError(error, operation) {
|
|
246
|
+
const cause = error instanceof Error ? error.cause : void 0;
|
|
247
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
248
|
+
const causeMessage = cause?.message || "";
|
|
249
|
+
if (causeMessage.includes("ENOTFOUND") || causeMessage.includes("getaddrinfo")) {
|
|
250
|
+
const hostMatch = causeMessage.match(/ENOTFOUND\s+(\S+)/) || causeMessage.match(/getaddrinfo\s+\S+\s+(\S+)/);
|
|
251
|
+
const host = hostMatch?.[1] || "unknown host";
|
|
252
|
+
return new Error(`Storage ${operation} failed: Could not resolve host '${host}'. Check your storage URL/credentials are correct.`);
|
|
253
|
+
}
|
|
254
|
+
if (causeMessage.includes("ECONNREFUSED") || message.includes("ECONNREFUSED")) {
|
|
255
|
+
return new Error(`Storage ${operation} failed: Connection refused. Is the storage server running and accessible?`);
|
|
256
|
+
}
|
|
257
|
+
if (message.includes("401") || message.includes("Unauthorized") || message.includes("WRONGPASS")) {
|
|
258
|
+
return new Error(`Storage ${operation} failed: Authentication failed. Check your storage credentials.`);
|
|
259
|
+
}
|
|
260
|
+
if (message.includes("timeout") || message.includes("ETIMEDOUT")) {
|
|
261
|
+
return new Error(`Storage ${operation} failed: Connection timed out. Check network connectivity to storage.`);
|
|
262
|
+
}
|
|
263
|
+
if (message === "fetch failed") {
|
|
264
|
+
return new Error(`Storage ${operation} failed: Network error. ${causeMessage || "Check your storage configuration."}`);
|
|
265
|
+
}
|
|
266
|
+
return new Error(`Storage ${operation} failed: ${message}`);
|
|
267
|
+
}
|
|
245
268
|
async function processBatch(items, batchSize, processor) {
|
|
246
269
|
const results = [];
|
|
247
270
|
for (let i = 0; i < items.length; i += batchSize) {
|
|
@@ -284,24 +307,23 @@ async function getFilesRecursively(dir) {
|
|
|
284
307
|
return files;
|
|
285
308
|
}
|
|
286
309
|
async function getVersionManifest(storage) {
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
if (manifest && typeof manifest === "object" && "versions" in manifest)
|
|
310
|
+
const emptyManifest = { current: "", versions: {} };
|
|
311
|
+
return storage.getItem("version-manifest.json").then((manifest) => {
|
|
312
|
+
if (manifest && typeof manifest === "object" && "versions" in manifest)
|
|
290
313
|
return manifest;
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
return
|
|
298
|
-
|
|
299
|
-
versions: {}
|
|
300
|
-
};
|
|
301
|
-
}
|
|
314
|
+
return emptyManifest;
|
|
315
|
+
}).catch((e) => {
|
|
316
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
317
|
+
const cause = e instanceof Error ? e.cause?.message || "" : "";
|
|
318
|
+
if (cause.includes("ENOTFOUND") || cause.includes("ECONNREFUSED") || message.includes("401") || message === "fetch failed")
|
|
319
|
+
throw formatStorageError(e, "read");
|
|
320
|
+
return emptyManifest;
|
|
321
|
+
});
|
|
302
322
|
}
|
|
303
323
|
async function setVersionManifest(manifest, storage) {
|
|
304
|
-
await storage.setItem("version-manifest.json", manifest)
|
|
324
|
+
await storage.setItem("version-manifest.json", manifest).catch((e) => {
|
|
325
|
+
throw formatStorageError(e, "write");
|
|
326
|
+
});
|
|
305
327
|
}
|
|
306
328
|
function formatBytes(bytes) {
|
|
307
329
|
if (bytes < 1024)
|
|
@@ -321,9 +343,9 @@ function createAssetManager(options) {
|
|
|
321
343
|
});
|
|
322
344
|
const retentionDays = options.retentionDays || 7;
|
|
323
345
|
const maxNumberOfVersions = options.maxNumberOfVersions || 20;
|
|
324
|
-
async function getAssetsFromBuild(
|
|
346
|
+
async function getAssetsFromBuild(publicDir) {
|
|
325
347
|
const startTime = Date.now();
|
|
326
|
-
const nuxtDir = join$1(
|
|
348
|
+
const nuxtDir = join$1(publicDir, "_nuxt");
|
|
327
349
|
logger.debug(`Scanning build assets from ${nuxtDir}`);
|
|
328
350
|
const assets = [];
|
|
329
351
|
const nuxtFiles = await getFilesRecursively(nuxtDir);
|
|
@@ -427,10 +449,9 @@ function createAssetManager(options) {
|
|
|
427
449
|
await setVersionManifest(manifest, storage);
|
|
428
450
|
}
|
|
429
451
|
}
|
|
430
|
-
async function storeAssetsInStorage(buildId,
|
|
452
|
+
async function storeAssetsInStorage(buildId, publicDir, assets) {
|
|
431
453
|
const startTime = Date.now();
|
|
432
454
|
logger.debug(`storeAssetsInStorage: starting for ${buildId} (${assets.length} assets)`);
|
|
433
|
-
const publicDir = join$1(outputDir, "public");
|
|
434
455
|
const manifestStart = Date.now();
|
|
435
456
|
const manifest = await getVersionManifest(storage);
|
|
436
457
|
logger.debug(`storeAssetsInStorage: loaded manifest in ${formatDuration(Date.now() - manifestStart)}`);
|
|
@@ -509,7 +530,7 @@ function createAssetManager(options) {
|
|
|
509
530
|
createdAt: new Date(data.timestamp).getTime()
|
|
510
531
|
}));
|
|
511
532
|
}
|
|
512
|
-
async function restoreOldAssetsToPublic(currentBuildId,
|
|
533
|
+
async function restoreOldAssetsToPublic(currentBuildId, publicDir, currentAssets = [], isExistingVersion = false) {
|
|
513
534
|
const startTime = Date.now();
|
|
514
535
|
logger.debug(`restoreOldAssetsToPublic: starting for ${currentBuildId}`);
|
|
515
536
|
const manifestStart = Date.now();
|
|
@@ -525,7 +546,6 @@ function createAssetManager(options) {
|
|
|
525
546
|
}
|
|
526
547
|
const versionCount = Object.keys(manifest.versions).length - 1;
|
|
527
548
|
logger.debug(`restoreOldAssetsToPublic: checking ${versionCount} previous versions`);
|
|
528
|
-
const publicDir = join$1(outputDir, "public");
|
|
529
549
|
const restoredAssets = [];
|
|
530
550
|
const currentAssetsSet = new Set(currentAssets);
|
|
531
551
|
const currentFileIds = /* @__PURE__ */ new Set();
|
|
@@ -646,9 +666,9 @@ function createAssetManager(options) {
|
|
|
646
666
|
}
|
|
647
667
|
logger.debug(`restoreOldAssetsToPublic: total ${formatDuration(Date.now() - startTime)}`);
|
|
648
668
|
}
|
|
649
|
-
async function augmentBuildMetadata(buildId,
|
|
669
|
+
async function augmentBuildMetadata(buildId, publicDir) {
|
|
650
670
|
const manifest = await getVersionManifest(storage);
|
|
651
|
-
const latestPath = join$1(
|
|
671
|
+
const latestPath = join$1(publicDir, "_nuxt", "builds", "latest.json");
|
|
652
672
|
try {
|
|
653
673
|
const latestData = await promises.readFile(latestPath, "utf-8");
|
|
654
674
|
const latestJson = JSON.parse(latestData);
|
|
@@ -668,7 +688,7 @@ function createAssetManager(options) {
|
|
|
668
688
|
logger.warn("Failed to augment builds/latest.json:", error);
|
|
669
689
|
}
|
|
670
690
|
}
|
|
671
|
-
const metaPath = join$1(
|
|
691
|
+
const metaPath = join$1(publicDir, "_nuxt", "builds", "meta", `${buildId}.json`);
|
|
672
692
|
try {
|
|
673
693
|
const metaData = await promises.readFile(metaPath, "utf-8");
|
|
674
694
|
const metaJson = JSON.parse(metaData);
|
|
@@ -694,7 +714,8 @@ function createAssetManager(options) {
|
|
|
694
714
|
listExistingVersions,
|
|
695
715
|
restoreOldAssetsToPublic,
|
|
696
716
|
augmentBuildMetadata,
|
|
697
|
-
getManifest: () => getVersionManifest(storage)
|
|
717
|
+
getManifest: () => getVersionManifest(storage),
|
|
718
|
+
dispose: () => storage.dispose()
|
|
698
719
|
};
|
|
699
720
|
}
|
|
700
721
|
|
|
@@ -737,6 +758,7 @@ const module$1 = defineNuxtModule({
|
|
|
737
758
|
nuxt.options.runtimeConfig.public.skewProtection = {
|
|
738
759
|
cookie: options.cookie,
|
|
739
760
|
debug: options.debug,
|
|
761
|
+
connectionTracking: options.connectionTracking,
|
|
740
762
|
version
|
|
741
763
|
};
|
|
742
764
|
const nitroPreset = resolveNitroPreset(nuxt.options.nitro);
|
|
@@ -748,11 +770,11 @@ const module$1 = defineNuxtModule({
|
|
|
748
770
|
}
|
|
749
771
|
addTypeTemplate({
|
|
750
772
|
filename: "types/nuxt-skew-protection.d.ts",
|
|
751
|
-
getContents: () =>
|
|
752
|
-
return `// Generated by nuxt-skew-protection
|
|
773
|
+
getContents: () => `// Generated by nuxt-skew-protection
|
|
753
774
|
declare module '#app' {
|
|
754
775
|
interface RuntimeNuxtHooks {
|
|
755
776
|
'skew-protection:chunks-outdated': (payload: ChunksOutdatedPayload) => void | Promise<void>
|
|
777
|
+
'skew:message': (message: { type: string, [key: string]: unknown }) => void | Promise<void>
|
|
756
778
|
}
|
|
757
779
|
interface NuxtApp {
|
|
758
780
|
$skewProtectionBuildId: Ref<string | undefined>
|
|
@@ -773,6 +795,7 @@ declare module '#app' {
|
|
|
773
795
|
declare module 'nuxt/app' {
|
|
774
796
|
interface RuntimeNuxtHooks {
|
|
775
797
|
'skew-protection:chunks-outdated': (payload: ChunksOutdatedPayload) => void | Promise<void>
|
|
798
|
+
'skew:message': (message: { type: string, [key: string]: unknown }) => void | Promise<void>
|
|
776
799
|
}
|
|
777
800
|
interface NuxtApp {
|
|
778
801
|
$skewProtectionBuildId: Ref<string | undefined>
|
|
@@ -791,11 +814,25 @@ declare module 'nuxt/app' {
|
|
|
791
814
|
}
|
|
792
815
|
|
|
793
816
|
export {}
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
817
|
+
`
|
|
818
|
+
}, { nuxt: true });
|
|
819
|
+
addTypeTemplate({
|
|
820
|
+
filename: "types/nuxt-skew-protection-nitro.d.ts",
|
|
821
|
+
getContents: () => `// Generated by nuxt-skew-protection
|
|
822
|
+
declare module 'nitropack/types' {
|
|
823
|
+
interface NitroRuntimeHooks {
|
|
824
|
+
'skew:connection:open': (payload: {
|
|
825
|
+
id: string
|
|
826
|
+
version: string
|
|
827
|
+
send: (data: { type: string, total: number, versions: Record<string, number> }) => void
|
|
828
|
+
}) => void
|
|
829
|
+
'skew:connection:close': (payload: { id: string }) => void
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
export {}
|
|
834
|
+
`
|
|
835
|
+
}, { nitro: true });
|
|
799
836
|
addComponent({
|
|
800
837
|
name: "SkewNotification",
|
|
801
838
|
filePath: resolver.resolve(`./runtime/app/components/SkewNotification.vue`)
|
|
@@ -804,6 +841,15 @@ export {}
|
|
|
804
841
|
name: "useSkewProtection",
|
|
805
842
|
from: resolver.resolve("./runtime/app/composables/useSkewProtection")
|
|
806
843
|
});
|
|
844
|
+
if (options.connectionTracking) {
|
|
845
|
+
addImports({
|
|
846
|
+
name: "useActiveConnections",
|
|
847
|
+
from: resolver.resolve("./runtime/app/composables/useActiveConnections")
|
|
848
|
+
});
|
|
849
|
+
nuxt.options.nitro = nuxt.options.nitro || {};
|
|
850
|
+
nuxt.options.nitro.plugins = nuxt.options.nitro.plugins || [];
|
|
851
|
+
nuxt.options.nitro.plugins.push(resolver.resolve("./runtime/server/plugins/connection-tracking"));
|
|
852
|
+
}
|
|
807
853
|
addPlugin({
|
|
808
854
|
src: resolver.resolve("./runtime/app/plugins/init-build-id")
|
|
809
855
|
});
|
|
@@ -864,12 +910,12 @@ export {}
|
|
|
864
910
|
const buildId = nuxt.options.runtimeConfig.app.buildId ||= nuxt.options.buildId;
|
|
865
911
|
let assetManager;
|
|
866
912
|
nitro.hooks.hook("compiled", async () => {
|
|
867
|
-
const
|
|
913
|
+
const publicDir = nitro.options.output.publicDir;
|
|
868
914
|
assetManager = createAssetManager({
|
|
869
915
|
...options,
|
|
870
916
|
driver: await resolveBuildTimeDriver(options.storage)
|
|
871
917
|
});
|
|
872
|
-
const assets = await assetManager.getAssetsFromBuild(
|
|
918
|
+
const assets = await assetManager.getAssetsFromBuild(publicDir);
|
|
873
919
|
const { isExistingVersion } = await assetManager.updateVersionsManifest(buildId, assets);
|
|
874
920
|
const manifest = await assetManager.getManifest();
|
|
875
921
|
const totalReleases = Object.keys(manifest.versions).length;
|
|
@@ -883,7 +929,7 @@ export {}
|
|
|
883
929
|
} else {
|
|
884
930
|
logger.log(`Storing ${colors.yellow(assets.length.toString())} assets for ${colors.cyan(buildId.slice(0, 8))} (${totalReleases} releases, oldest from ${timeInfo}) [${storageInfo}]`);
|
|
885
931
|
}
|
|
886
|
-
await assetManager.storeAssetsInStorage(buildId,
|
|
932
|
+
await assetManager.storeAssetsInStorage(buildId, publicDir, assets).catch((error) => {
|
|
887
933
|
logger.error(`Failed to store assets:`, error instanceof Error ? error.message : error);
|
|
888
934
|
throw error;
|
|
889
935
|
});
|
|
@@ -902,12 +948,14 @@ export {}
|
|
|
902
948
|
}
|
|
903
949
|
logger.log(`Restoring build files from ${versionCount} release${versionCount > 1 ? "s" : ""} (${totalAssets} assets) [${versionSizes.join(", ")}]...`);
|
|
904
950
|
}
|
|
905
|
-
await assetManager.restoreOldAssetsToPublic(buildId,
|
|
906
|
-
await assetManager.augmentBuildMetadata(buildId,
|
|
951
|
+
await assetManager.restoreOldAssetsToPublic(buildId, publicDir, assets, isExistingVersion);
|
|
952
|
+
await assetManager.augmentBuildMetadata(buildId, publicDir);
|
|
907
953
|
});
|
|
908
954
|
nitro.hooks.hook("close", async () => {
|
|
909
955
|
if (assetManager) {
|
|
910
|
-
await assetManager.cleanupExpiredVersions()
|
|
956
|
+
await assetManager.cleanupExpiredVersions().catch(() => {
|
|
957
|
+
});
|
|
958
|
+
await assetManager.dispose();
|
|
911
959
|
}
|
|
912
960
|
});
|
|
913
961
|
});
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { useNuxtApp, useRuntimeConfig } from "nuxt/app";
|
|
2
|
+
import { computed, ref } from "vue";
|
|
3
|
+
const stats = ref({ total: 0, versions: {} });
|
|
4
|
+
let hooked = false;
|
|
5
|
+
export function useActiveConnections() {
|
|
6
|
+
const config = useRuntimeConfig().public.skewProtection;
|
|
7
|
+
if (!config?.connectionTracking) {
|
|
8
|
+
throw new Error("[nuxt-skew-protection] useActiveConnections() requires `connectionTracking: true` in your module config.");
|
|
9
|
+
}
|
|
10
|
+
if (!hooked) {
|
|
11
|
+
hooked = true;
|
|
12
|
+
useNuxtApp().hooks.hook("skew:message", (message) => {
|
|
13
|
+
if (message.type === "stats")
|
|
14
|
+
stats.value = { total: message.total, versions: message.versions };
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
return {
|
|
18
|
+
total: computed(() => stats.value.total),
|
|
19
|
+
versions: computed(() => stats.value.versions)
|
|
20
|
+
};
|
|
21
|
+
}
|
|
@@ -32,6 +32,7 @@ export default defineNuxtPlugin({
|
|
|
32
32
|
logger.debug("[SSE] Message received:", message);
|
|
33
33
|
if (!message)
|
|
34
34
|
return;
|
|
35
|
+
nuxtApp.hooks.callHook("skew:message", message);
|
|
35
36
|
if (message.type === "connected" && message.version) {
|
|
36
37
|
const newVersion = message.version;
|
|
37
38
|
logger.debug(`[SSE] Server version: ${newVersion}, Client version: ${clientVersion}`);
|
|
@@ -1,16 +1,2 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* WebSocket Version Updates Plugin
|
|
3
|
-
*
|
|
4
|
-
* Similar to the SSE plugin, but uses WebSocket for real-time version notifications.
|
|
5
|
-
* Works with any WebSocket-capable backend (Cloudflare Durable Objects, custom WebSocket servers, etc.)
|
|
6
|
-
*
|
|
7
|
-
* Fires the same 'app:manifest:update' hook that Nuxt's chunk-reload plugin listens to.
|
|
8
|
-
* This allows our WebSocket updates to integrate seamlessly with Nuxt's existing reload logic.
|
|
9
|
-
*
|
|
10
|
-
* Can be used on:
|
|
11
|
-
* - Cloudflare Workers with Durable Objects
|
|
12
|
-
* - Custom WebSocket servers
|
|
13
|
-
* - Any platform that supports WebSocket connections
|
|
14
|
-
*/
|
|
15
1
|
declare const _default: import("nuxt/app").Plugin<Record<string, unknown>> & import("nuxt/app").ObjectPlugin<Record<string, unknown>>;
|
|
16
2
|
export default _default;
|
|
@@ -29,11 +29,9 @@ export default defineNuxtPlugin({
|
|
|
29
29
|
timestamp: Date.now()
|
|
30
30
|
}),
|
|
31
31
|
interval: 3e4,
|
|
32
|
-
// Every 30 seconds
|
|
33
32
|
pongTimeout: 1e4
|
|
34
33
|
},
|
|
35
34
|
immediate: false
|
|
36
|
-
// Don't connect immediately, wait for app:mounted
|
|
37
35
|
});
|
|
38
36
|
watch(status, (newStatus) => {
|
|
39
37
|
logger.debug(`[WS] Connection status changed: ${newStatus}`);
|
|
@@ -41,23 +39,18 @@ export default defineNuxtPlugin({
|
|
|
41
39
|
watch(data, (message) => {
|
|
42
40
|
if (!message)
|
|
43
41
|
return;
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
logger.debug(
|
|
54
|
-
|
|
55
|
-
logger.debug("[WS] Version mismatch detected, triggering update check");
|
|
56
|
-
nuxtApp.runWithContext(checkForUpdates);
|
|
57
|
-
}
|
|
42
|
+
const parsed = JSON.parse(message);
|
|
43
|
+
logger.debug("[WS] Message received:", parsed);
|
|
44
|
+
if (parsed.type === "ping")
|
|
45
|
+
return;
|
|
46
|
+
nuxtApp.hooks.callHook("skew:message", parsed);
|
|
47
|
+
if (parsed.version) {
|
|
48
|
+
const newVersion = parsed.version;
|
|
49
|
+
logger.debug(`[WS] Server version: ${newVersion}, Client version: ${clientVersion}`);
|
|
50
|
+
if (newVersion !== clientVersion) {
|
|
51
|
+
logger.debug("[WS] Version mismatch detected, triggering update check");
|
|
52
|
+
nuxtApp.runWithContext(checkForUpdates);
|
|
58
53
|
}
|
|
59
|
-
} catch (error) {
|
|
60
|
-
logger.error("[WS] Failed to parse WebSocket message:", error);
|
|
61
54
|
}
|
|
62
55
|
});
|
|
63
56
|
nuxtApp.hook("app:mounted", () => {
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { defineNitroPlugin } from "nitropack/runtime";
|
|
2
|
+
export default defineNitroPlugin((nitroApp) => {
|
|
3
|
+
const connections = /* @__PURE__ */ new Map();
|
|
4
|
+
const getStats = () => {
|
|
5
|
+
const versions = {};
|
|
6
|
+
for (const conn of connections.values()) {
|
|
7
|
+
versions[conn.version] = (versions[conn.version] || 0) + 1;
|
|
8
|
+
}
|
|
9
|
+
return { total: connections.size, versions };
|
|
10
|
+
};
|
|
11
|
+
const broadcast = () => {
|
|
12
|
+
const stats = getStats();
|
|
13
|
+
for (const conn of connections.values()) {
|
|
14
|
+
conn.send({ type: "stats", ...stats });
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
nitroApp.hooks.hook("skew:connection:open", ({ id, version, send }) => {
|
|
18
|
+
connections.set(id, { version, send });
|
|
19
|
+
broadcast();
|
|
20
|
+
});
|
|
21
|
+
nitroApp.hooks.hook("skew:connection:close", ({ id }) => {
|
|
22
|
+
connections.delete(id);
|
|
23
|
+
broadcast();
|
|
24
|
+
});
|
|
25
|
+
});
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createEventStream, defineEventHandler } from "h3";
|
|
2
2
|
import { useNitroApp, useRuntimeConfig } from "nitropack/runtime";
|
|
3
|
+
import { getSkewProtectionCookie } from "../../imports/cookie.js";
|
|
3
4
|
export default defineEventHandler(async (event) => {
|
|
4
5
|
const nitroApp = useNitroApp();
|
|
5
6
|
const stream = createEventStream(event);
|
|
@@ -13,11 +14,15 @@ export default defineEventHandler(async (event) => {
|
|
|
13
14
|
version: serverVersion,
|
|
14
15
|
timestamp: Date.now()
|
|
15
16
|
});
|
|
17
|
+
const connectionId = crypto.randomUUID();
|
|
18
|
+
const clientVersion = getSkewProtectionCookie(event) || serverVersion;
|
|
19
|
+
await nitroApp.hooks.callHook("skew:connection:open", {
|
|
20
|
+
id: connectionId,
|
|
21
|
+
version: clientVersion,
|
|
22
|
+
send
|
|
23
|
+
});
|
|
16
24
|
const keepaliveInterval = setInterval(() => {
|
|
17
|
-
send({
|
|
18
|
-
type: "keepalive",
|
|
19
|
-
timestamp: Date.now()
|
|
20
|
-
});
|
|
25
|
+
send({ type: "keepalive", timestamp: Date.now() });
|
|
21
26
|
}, 3e4);
|
|
22
27
|
let cleanupDone = false;
|
|
23
28
|
const close = async () => {
|
|
@@ -25,6 +30,7 @@ export default defineEventHandler(async (event) => {
|
|
|
25
30
|
return;
|
|
26
31
|
cleanupDone = true;
|
|
27
32
|
clearInterval(keepaliveInterval);
|
|
33
|
+
await nitroApp.hooks.callHook("skew:connection:close", { id: connectionId });
|
|
28
34
|
await stream.close();
|
|
29
35
|
};
|
|
30
36
|
stream.onClosed(close);
|
|
@@ -1,17 +1,32 @@
|
|
|
1
|
+
import { parse as parseCookie } from "cookie-es";
|
|
1
2
|
import { defineWebSocketHandler } from "h3";
|
|
2
|
-
import { useRuntimeConfig } from "nitropack/runtime";
|
|
3
|
+
import { useNitroApp, useRuntimeConfig } from "nitropack/runtime";
|
|
3
4
|
export default defineWebSocketHandler({
|
|
4
5
|
open(peer) {
|
|
5
6
|
const runtimeConfig = useRuntimeConfig();
|
|
7
|
+
const serverVersion = runtimeConfig.app?.buildId;
|
|
8
|
+
const skewConfig = runtimeConfig.public.skewProtection;
|
|
6
9
|
peer.send(JSON.stringify({
|
|
7
10
|
type: "connected",
|
|
8
|
-
version:
|
|
11
|
+
version: serverVersion,
|
|
9
12
|
timestamp: Date.now()
|
|
10
13
|
}));
|
|
14
|
+
const cookieHeader = peer.request?.headers?.get("cookie") || "";
|
|
15
|
+
const cookies = parseCookie(cookieHeader);
|
|
16
|
+
const cookieName = skewConfig?.cookie?.name || "__nkpv";
|
|
17
|
+
const clientVersion = cookies[cookieName] || serverVersion;
|
|
18
|
+
useNitroApp().hooks.callHook("skew:connection:open", {
|
|
19
|
+
id: peer.id,
|
|
20
|
+
version: clientVersion,
|
|
21
|
+
send: (data) => peer.send(JSON.stringify(data))
|
|
22
|
+
});
|
|
11
23
|
},
|
|
12
24
|
message(peer, message) {
|
|
13
25
|
if (message.text().includes("ping")) {
|
|
14
26
|
peer.send(JSON.stringify({ type: "pong" }));
|
|
15
27
|
}
|
|
28
|
+
},
|
|
29
|
+
close(peer) {
|
|
30
|
+
useNitroApp().hooks.callHook("skew:connection:close", { id: peer.id });
|
|
16
31
|
}
|
|
17
32
|
});
|
package/dist/runtime/types.d.ts
CHANGED
|
@@ -6,6 +6,7 @@ export interface NuxtSkewProtectionRuntimeConfig {
|
|
|
6
6
|
name?: string;
|
|
7
7
|
};
|
|
8
8
|
debug: boolean;
|
|
9
|
+
connectionTracking?: boolean;
|
|
9
10
|
}
|
|
10
11
|
export interface SkewProtectionRuntimeConfig {
|
|
11
12
|
cookie: Omit<CookieSerializeOptions, 'encode'> & {
|
|
@@ -13,6 +14,7 @@ export interface SkewProtectionRuntimeConfig {
|
|
|
13
14
|
};
|
|
14
15
|
buildId: string;
|
|
15
16
|
debug: boolean;
|
|
17
|
+
connectionTracking?: boolean;
|
|
16
18
|
}
|
|
17
19
|
export interface ChunksOutdatedPayload {
|
|
18
20
|
deletedChunks: string[];
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nuxt-skew-protection",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.5.0",
|
|
5
5
|
"description": "Solve Nuxt version skews with persistent assets and instant updates.",
|
|
6
6
|
"author": {
|
|
7
7
|
"name": "Harlan Wilton",
|
|
@@ -54,7 +54,7 @@
|
|
|
54
54
|
"consola": "^3.4.2",
|
|
55
55
|
"cookie-es": "^2.0.0",
|
|
56
56
|
"defu": "^6.1.4",
|
|
57
|
-
"nuxt-site-config": "^3.2.
|
|
57
|
+
"nuxt-site-config": "^3.2.13",
|
|
58
58
|
"ofetch": "^1.5.1",
|
|
59
59
|
"pathe": "^2.0.3",
|
|
60
60
|
"pkg-types": "^2.3.0",
|
|
@@ -85,7 +85,7 @@
|
|
|
85
85
|
"ably": "^2.15.0",
|
|
86
86
|
"better-sqlite3": "^12.5.0",
|
|
87
87
|
"bumpp": "^10.3.2",
|
|
88
|
-
"eslint": "^9.39.
|
|
88
|
+
"eslint": "^9.39.2",
|
|
89
89
|
"eventsource": "^4.1.0",
|
|
90
90
|
"execa": "^9.6.1",
|
|
91
91
|
"firebase-functions": "^7.0.1",
|