nuxt-skew-protection 0.6.0 → 0.7.1

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.d.mts CHANGED
@@ -62,6 +62,19 @@ interface ModuleOptions {
62
62
  * @default false
63
63
  */
64
64
  connectionTracking?: boolean;
65
+ /**
66
+ * Track which routes users are currently viewing
67
+ * Requires connectionTracking to be enabled
68
+ * @default false
69
+ */
70
+ routeTracking?: boolean;
71
+ /**
72
+ * Track IP addresses of connected users
73
+ * Requires connectionTracking to be enabled
74
+ * Privacy note: IPs are only stored in memory and exposed via stats
75
+ * @default false
76
+ */
77
+ ipTracking?: boolean;
65
78
  }
66
79
  interface ModulePublicRuntimeConfig {
67
80
  skewProtection: NuxtSkewProtectionRuntimeConfig;
package/dist/module.json CHANGED
@@ -9,7 +9,7 @@
9
9
  "version": ">=5.6.7"
10
10
  }
11
11
  },
12
- "version": "0.6.0",
12
+ "version": "0.7.1",
13
13
  "builder": {
14
14
  "@nuxt/module-builder": "1.0.2",
15
15
  "unbuild": "3.6.1"
package/dist/module.mjs CHANGED
@@ -760,10 +760,18 @@ const module$1 = defineNuxtModule({
760
760
  await installNuxtSiteConfig();
761
761
  hookNuxtSeoProLicense();
762
762
  nuxt.options.runtimeConfig.public = nuxt.options.runtimeConfig.public || {};
763
+ if (options.routeTracking && !options.connectionTracking) {
764
+ logger.warn("`routeTracking` requires `connectionTracking: true`. Route tracking will be disabled.");
765
+ }
766
+ if (options.ipTracking && !options.connectionTracking) {
767
+ logger.warn("`ipTracking` requires `connectionTracking: true`. IP tracking will be disabled.");
768
+ }
763
769
  nuxt.options.runtimeConfig.public.skewProtection = {
764
770
  cookie: options.cookie,
765
771
  debug: options.debug,
766
772
  connectionTracking: options.connectionTracking,
773
+ routeTracking: options.connectionTracking && options.routeTracking,
774
+ ipTracking: options.connectionTracking && options.ipTracking,
767
775
  version
768
776
  };
769
777
  const nitroPreset = resolveNitroPreset(nuxt.options.nitro);
@@ -788,6 +796,7 @@ declare module '#app' {
788
796
  }
789
797
  interface NuxtApp {
790
798
  $skewConnection?: SkewConnection
799
+ _skewStatsSubscribed?: boolean
791
800
  }
792
801
  interface NuxtAppManifestMeta {
793
802
  skewProtection?: {
@@ -811,6 +820,7 @@ declare module 'nuxt/app' {
811
820
  }
812
821
  interface NuxtApp {
813
822
  $skewConnection?: SkewConnection
823
+ _skewStatsSubscribed?: boolean
814
824
  }
815
825
  interface NuxtAppManifestMeta {
816
826
  skewProtection?: {
@@ -830,14 +840,24 @@ export type { ChunksOutdatedPayload, SkewAdapterConfig, SkewConnection, SkewSSEC
830
840
  addTypeTemplate({
831
841
  filename: "types/nuxt-skew-protection-nitro.d.ts",
832
842
  getContents: () => `// Generated by nuxt-skew-protection
843
+ import type { H3Event } from 'h3'
844
+
833
845
  declare module 'nitropack/types' {
834
846
  interface NitroRuntimeHooks {
835
847
  'skew:connection:open': (payload: {
836
848
  id: string
837
849
  version: string
838
- send: (data: { type: string, total: number, versions: Record<string, number> }) => void
850
+ route?: string
851
+ ip?: string
852
+ send: (data: unknown) => void
839
853
  }) => void
854
+ 'skew:connection:route-update': (payload: { id: string, route: string }) => void
840
855
  'skew:connection:close': (payload: { id: string }) => void
856
+ // event is H3Event for SSE (via POST), { headers } for WebSocket (no H3Event available)
857
+ 'skew:subscribe-stats': (payload: { id: string, event?: H3Event | { headers?: Headers } }) => void
858
+ // event is H3Event for SSE (via POST), { headers } for WebSocket (no H3Event available)
859
+ 'skew:authorize-stats': (payload: { event?: H3Event | { headers?: Headers }, authorize: () => void }) => void
860
+ 'skew:stats': (callback: (stats: { total: number, versions: Record<string, number>, routes: Record<string, number> }) => void) => void
841
861
  }
842
862
  }
843
863
 
@@ -869,6 +889,29 @@ export {}
869
889
  nuxt.options.nitro.storage = nuxt.options.nitro.storage || {};
870
890
  nuxt.options.nitro.storage["skew-protection"] = options.storage;
871
891
  }
892
+ if (nuxt.options.dev && options.connectionTracking) {
893
+ if (nuxt.options.nitro?.experimental?.websocket) {
894
+ addServerHandler({
895
+ route: "/_skew/ws",
896
+ handler: resolver.resolve("./runtime/server/routes/_skew/ws")
897
+ });
898
+ addServerHandler({
899
+ route: "/_skew/subscribe-stats",
900
+ method: "post",
901
+ handler: resolver.resolve("./runtime/server/routes/_skew/subscribe-stats.post")
902
+ });
903
+ if (options.routeTracking) {
904
+ addServerHandler({
905
+ route: "/_skew/route",
906
+ method: "post",
907
+ handler: resolver.resolve("./runtime/server/routes/_skew/route.post")
908
+ });
909
+ }
910
+ addPlugin(resolver.resolve("./runtime/app/plugins/check-updates-websocket.client"));
911
+ } else {
912
+ logger.warn("connectionTracking in dev mode requires `nitro.experimental.websocket: true`");
913
+ }
914
+ }
872
915
  if (!nuxt.options.dev) {
873
916
  const isCloudflareRuntime = nitroPreset?.includes("cloudflare");
874
917
  const isVercel = nitroPreset?.includes("vercel") || process.env.VERCEL_SKEW_PROTECTION_ENABLED === "1";
@@ -1052,6 +1095,20 @@ export { subscribe }`
1052
1095
  route: "/_skew/sse",
1053
1096
  handler: resolver.resolve("./runtime/server/routes/_skew/sse")
1054
1097
  });
1098
+ if (options.connectionTracking) {
1099
+ addServerHandler({
1100
+ route: "/_skew/subscribe-stats",
1101
+ method: "post",
1102
+ handler: resolver.resolve("./runtime/server/routes/_skew/subscribe-stats.post")
1103
+ });
1104
+ if (options.routeTracking) {
1105
+ addServerHandler({
1106
+ route: "/_skew/route",
1107
+ method: "post",
1108
+ handler: resolver.resolve("./runtime/server/routes/_skew/route.post")
1109
+ });
1110
+ }
1111
+ }
1055
1112
  addPlugin({
1056
1113
  src: resolver.resolve("./runtime/app/plugins/check-updates-sse.client"),
1057
1114
  mode: "client"
@@ -5,15 +5,21 @@ interface Props {
5
5
  */
6
6
  forceOpen?: boolean;
7
7
  }
8
+ declare function handleDismiss(): void;
9
+ declare function handleReload(): Promise<void>;
8
10
  declare var __VLS_8: {
9
11
  version: any;
10
- isCurrentChunksOutdated: any;
11
- dismiss: any;
12
- reload: any;
13
- timeAgo: any;
14
- releaseDate: any;
15
- payload: any;
16
- isAppOutdated: any;
12
+ isCurrentChunksOutdated: boolean;
13
+ dismiss: typeof handleDismiss;
14
+ reload: typeof handleReload;
15
+ timeAgo: string;
16
+ releaseDate: Date;
17
+ payload: {
18
+ deletedChunks: string[];
19
+ invalidatedModules: string[];
20
+ passedReleases: string[];
21
+ } | null;
22
+ isAppOutdated: boolean;
17
23
  };
18
24
  type __VLS_Slots = {} & {
19
25
  default?: (props: typeof __VLS_8) => any;
@@ -5,15 +5,21 @@ interface Props {
5
5
  */
6
6
  forceOpen?: boolean;
7
7
  }
8
+ declare function handleDismiss(): void;
9
+ declare function handleReload(): Promise<void>;
8
10
  declare var __VLS_8: {
9
11
  version: any;
10
- isCurrentChunksOutdated: any;
11
- dismiss: any;
12
- reload: any;
13
- timeAgo: any;
14
- releaseDate: any;
15
- payload: any;
16
- isAppOutdated: any;
12
+ isCurrentChunksOutdated: boolean;
13
+ dismiss: typeof handleDismiss;
14
+ reload: typeof handleReload;
15
+ timeAgo: string;
16
+ releaseDate: Date;
17
+ payload: {
18
+ deletedChunks: string[];
19
+ invalidatedModules: string[];
20
+ passedReleases: string[];
21
+ } | null;
22
+ isAppOutdated: boolean;
17
23
  };
18
24
  type __VLS_Slots = {} & {
19
25
  default?: (props: typeof __VLS_8) => any;
@@ -1,8 +1,47 @@
1
+ export interface ConnectionInfo {
2
+ id: string;
3
+ version: string;
4
+ route: string;
5
+ ip?: string;
6
+ }
1
7
  export interface ConnectionStats {
2
8
  total: number;
3
9
  versions: Record<string, number>;
10
+ routes: Record<string, number>;
11
+ connections: ConnectionInfo[];
12
+ yourId?: string;
4
13
  }
14
+ /**
15
+ * Subscribe to real-time connection statistics.
16
+ *
17
+ * Requires:
18
+ * - `connectionTracking: true` in module config
19
+ * - Server-side `skew:authorize-stats` hook to authorize the subscription
20
+ *
21
+ * @example
22
+ * ```ts
23
+ * // server/plugins/stats-auth.ts
24
+ * export default defineNitroPlugin((nitroApp) => {
25
+ * nitroApp.hooks.hook('skew:authorize-stats', async ({ event, authorize }) => {
26
+ * const session = await getUserSession(event)
27
+ * if (session.user?.role === 'admin') {
28
+ * authorize()
29
+ * }
30
+ * })
31
+ * })
32
+ * ```
33
+ */
5
34
  export declare function useActiveConnections(): {
35
+ /** Whether the subscription is authorized (null while pending) */
36
+ authorized: import("vue").ComputedRef<boolean | null>;
37
+ /** Total active connections */
6
38
  total: import("vue").ComputedRef<number>;
39
+ /** Users per build version */
7
40
  versions: import("vue").ComputedRef<Record<string, number>>;
41
+ /** Users per route (requires routeTracking: true) */
42
+ routes: import("vue").ComputedRef<Record<string, number>>;
43
+ /** Individual connections with id, version, route */
44
+ connections: import("vue").ComputedRef<ConnectionInfo[]>;
45
+ /** Your connection ID (to identify yourself in the list) */
46
+ yourId: import("vue").ComputedRef<string | undefined>;
8
47
  };
@@ -1,21 +1,56 @@
1
- import { useNuxtApp, useRuntimeConfig } from "nuxt/app";
2
- import { computed, ref } from "vue";
3
- const stats = ref({ total: 0, versions: {} });
4
- let hooked = false;
1
+ import { useNuxtApp, useRuntimeConfig, useState } from "nuxt/app";
2
+ import { computed } from "vue";
5
3
  export function useActiveConnections() {
4
+ const nuxtApp = useNuxtApp();
6
5
  const config = useRuntimeConfig().public.skewProtection;
7
6
  if (!config?.connectionTracking) {
8
7
  throw new Error("[nuxt-skew-protection] useActiveConnections() requires `connectionTracking: true` in your module config.");
9
8
  }
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 };
9
+ const stats = useState("skew-stats", () => ({ total: 0, versions: {}, routes: {}, connections: [] }));
10
+ const authorized = useState("skew-authorized", () => null);
11
+ const subscribed = nuxtApp._skewStatsSubscribed;
12
+ if (!subscribed) {
13
+ nuxtApp._skewStatsSubscribed = true;
14
+ nuxtApp.hooks.hook("skew:message", (message) => {
15
+ if (message.type === "connected") {
16
+ nuxtApp.$skewConnection?.subscribeStats();
17
+ } else if (message.type === "stats") {
18
+ authorized.value = true;
19
+ stats.value = {
20
+ total: message.total,
21
+ versions: message.versions,
22
+ routes: message.routes || {},
23
+ connections: message.connections || [],
24
+ yourId: message.yourId
25
+ };
26
+ } else if (message.type === "stats-unauthorized") {
27
+ authorized.value = false;
28
+ }
15
29
  });
30
+ const startConnection = () => {
31
+ nuxtApp.$skewConnection?.connect();
32
+ nuxtApp.$skewConnection?.subscribeStats();
33
+ };
34
+ if (nuxtApp.$skewConnection) {
35
+ startConnection();
36
+ } else {
37
+ nuxtApp.hook("app:suspense:resolve", startConnection);
38
+ }
39
+ } else {
40
+ nuxtApp.$skewConnection?.subscribeStats();
16
41
  }
17
42
  return {
43
+ /** Whether the subscription is authorized (null while pending) */
44
+ authorized: computed(() => authorized.value),
45
+ /** Total active connections */
18
46
  total: computed(() => stats.value.total),
19
- versions: computed(() => stats.value.versions)
47
+ /** Users per build version */
48
+ versions: computed(() => stats.value.versions),
49
+ /** Users per route (requires routeTracking: true) */
50
+ routes: computed(() => stats.value.routes),
51
+ /** Individual connections with id, version, route */
52
+ connections: computed(() => stats.value.connections),
53
+ /** Your connection ID (to identify yourself in the list) */
54
+ yourId: computed(() => stats.value.yourId)
20
55
  };
21
56
  }
@@ -1,13 +1,17 @@
1
1
  import { useEventSource } from "@vueuse/core";
2
- import { defineNuxtPlugin, useNuxtApp } from "nuxt/app";
2
+ import { defineNuxtPlugin, useNuxtApp, useRouter, useRuntimeConfig } from "nuxt/app";
3
3
  import { watch } from "vue";
4
4
  import { createSkewConnection } from "../utils/create-skew-connection.js";
5
5
  export default defineNuxtPlugin({
6
6
  name: "skew-protection:sse-updates",
7
7
  async setup() {
8
8
  const nuxtApp = useNuxtApp();
9
+ const router = useRouter();
10
+ const runtimeConfig = useRuntimeConfig();
11
+ const routeTracking = runtimeConfig.public.skewProtection?.routeTracking;
12
+ const initialRoute = routeTracking ? `?route=${encodeURIComponent(router.currentRoute.value.path)}` : "";
9
13
  const config = {
10
- url: "/_skew/sse",
14
+ url: `/_skew/sse${initialRoute}`,
11
15
  options: {
12
16
  autoReconnect: { retries: 10, delay: 5e3 }
13
17
  }
@@ -22,9 +26,14 @@ export default defineNuxtPlugin({
22
26
  return;
23
27
  onMessage(JSON.parse(raw));
24
28
  });
25
- return sse.close;
29
+ return { cleanup: sse.close };
26
30
  }
27
31
  });
32
+ if (routeTracking) {
33
+ router.afterEach((to) => {
34
+ skewConnection.sendRoute(to.path);
35
+ });
36
+ }
28
37
  return { provide: { skewConnection } };
29
38
  }
30
39
  });
@@ -1,5 +1,5 @@
1
1
  import { useWebSocket } from "@vueuse/core";
2
- import { defineNuxtPlugin, useNuxtApp } from "nuxt/app";
2
+ import { defineNuxtPlugin, useNuxtApp, useRouter, useRuntimeConfig } from "nuxt/app";
3
3
  import { watch } from "vue";
4
4
  import { SKEW_MESSAGE_TYPE } from "../../const.js";
5
5
  import { createSkewConnection } from "../utils/create-skew-connection.js";
@@ -7,17 +7,18 @@ export default defineNuxtPlugin({
7
7
  name: "skew-protection:ws-updates",
8
8
  async setup() {
9
9
  const nuxtApp = useNuxtApp();
10
+ const router = useRouter();
11
+ const runtimeConfig = useRuntimeConfig();
12
+ const routeTracking = runtimeConfig.public.skewProtection?.routeTracking;
10
13
  const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
14
+ const initialRoute = routeTracking ? `?route=${encodeURIComponent(router.currentRoute.value.path)}` : "";
11
15
  const config = {
12
- url: `${protocol}//${window.location.host}/_skew/ws`,
16
+ url: `${protocol}//${window.location.host}/_skew/ws${initialRoute}`,
13
17
  options: {
14
18
  autoReconnect: { retries: 10, delay: 5e3 },
15
- heartbeat: {
16
- message: JSON.stringify({ type: SKEW_MESSAGE_TYPE.PING, timestamp: Date.now() }),
17
- interval: 3e4,
18
- pongTimeout: 1e4
19
- },
20
19
  immediate: false
20
+ // heartbeat disabled by default - saves server load and allows CF Durable Objects to hibernate
21
+ // enable via skew:ws:config hook if your infrastructure has aggressive idle timeouts
21
22
  }
22
23
  };
23
24
  await nuxtApp.callHook("skew:ws:config", config);
@@ -34,9 +35,17 @@ export default defineNuxtPlugin({
34
35
  onMessage(msg);
35
36
  });
36
37
  ws.open();
37
- return ws.close;
38
+ return {
39
+ cleanup: ws.close,
40
+ send: (data) => ws.send(JSON.stringify(data))
41
+ };
38
42
  }
39
43
  });
44
+ if (routeTracking) {
45
+ router.afterEach((to) => {
46
+ skewConnection.sendRoute(to.path);
47
+ });
48
+ }
40
49
  return { provide: { skewConnection } };
41
50
  }
42
51
  });
@@ -20,6 +20,9 @@ export interface ChunksOutdatedPayload {
20
20
  export interface SkewConnection {
21
21
  connect: () => void;
22
22
  disconnect: () => void;
23
+ send: (data: unknown) => void;
24
+ sendRoute: (route: string) => void;
25
+ subscribeStats: () => void;
23
26
  buildId: string;
24
27
  cookie: Ref<string | null | undefined>;
25
28
  }
@@ -2,15 +2,22 @@ import type { Ref } from 'vue';
2
2
  export interface SkewMessage {
3
3
  type: string;
4
4
  version?: string;
5
+ connectionId?: string;
5
6
  [key: string]: unknown;
6
7
  }
7
8
  export interface CreateSkewConnectionConfig {
8
9
  name: string;
9
- setup: (onMessage: (msg: SkewMessage) => void) => (() => void) | void;
10
+ setup: (onMessage: (msg: SkewMessage) => void) => {
11
+ cleanup?: () => void;
12
+ send?: (data: unknown) => void;
13
+ } | (() => void) | void;
10
14
  }
11
15
  export interface SkewConnection {
12
16
  connect: () => void;
13
17
  disconnect: () => void;
18
+ send: (data: unknown) => void;
19
+ sendRoute: (route: string) => void;
20
+ subscribeStats: () => void;
14
21
  buildId: string;
15
22
  cookie: Ref<string | null | undefined>;
16
23
  }
@@ -1,5 +1,6 @@
1
1
  import { useBotDetection } from "#imports";
2
2
  import { useCookie, useNuxtApp, useRuntimeConfig } from "nuxt/app";
3
+ import { SKEW_MESSAGE_TYPE } from "../../const.js";
3
4
  import { init, logger } from "../../shared/logger.js";
4
5
  export function createSkewConnection(config) {
5
6
  const { name, setup } = config;
@@ -15,15 +16,23 @@ export function createSkewConnection(config) {
15
16
  logger.debug(`[${name}] Skipping connection for bot`);
16
17
  return { connect: () => {
17
18
  }, disconnect: () => {
19
+ }, send: () => {
20
+ }, sendRoute: () => {
21
+ }, subscribeStats: () => {
18
22
  }, buildId, cookie };
19
23
  }
20
24
  if (import.meta.client && !cookie.value) {
21
25
  cookie.value = buildId;
22
26
  }
23
27
  let cleanup;
28
+ let sendFn;
24
29
  let isConnected = false;
30
+ let connectionId;
25
31
  const handleMessage = (msg) => {
26
32
  logger.debug(`[${name}] Received message:`, msg.type);
33
+ if (msg.connectionId) {
34
+ connectionId = msg.connectionId;
35
+ }
27
36
  nuxtApp.hooks.callHook("skew:message", msg);
28
37
  };
29
38
  const connect = () => {
@@ -31,7 +40,13 @@ export function createSkewConnection(config) {
31
40
  return;
32
41
  isConnected = true;
33
42
  logger.debug(`[${name}] Connecting`);
34
- cleanup = setup(handleMessage);
43
+ const result = setup(handleMessage);
44
+ if (result && typeof result === "object") {
45
+ cleanup = result.cleanup;
46
+ sendFn = result.send;
47
+ } else {
48
+ cleanup = result;
49
+ }
35
50
  };
36
51
  const disconnect = () => {
37
52
  if (!isConnected)
@@ -40,9 +55,43 @@ export function createSkewConnection(config) {
40
55
  logger.debug(`[${name}] Disconnecting`);
41
56
  cleanup?.();
42
57
  };
58
+ const send = (data) => {
59
+ if (!isConnected || !sendFn)
60
+ return;
61
+ sendFn(data);
62
+ };
63
+ const sendRoute = (route) => {
64
+ if (!isConnected)
65
+ return;
66
+ if (sendFn) {
67
+ sendFn({ type: "route-update", route });
68
+ } else if (connectionId) {
69
+ fetch("/_skew/route", {
70
+ method: "POST",
71
+ headers: { "Content-Type": "application/json" },
72
+ body: JSON.stringify({ connectionId, route })
73
+ }).catch(() => {
74
+ });
75
+ }
76
+ };
77
+ const subscribeStats = () => {
78
+ if (!isConnected || !connectionId)
79
+ return;
80
+ if (sendFn) {
81
+ sendFn({ type: SKEW_MESSAGE_TYPE.SUBSCRIBE_STATS });
82
+ } else {
83
+ fetch("/_skew/subscribe-stats", {
84
+ method: "POST",
85
+ headers: { "Content-Type": "application/json" },
86
+ credentials: "same-origin",
87
+ body: JSON.stringify({ connectionId })
88
+ }).catch(() => {
89
+ });
90
+ }
91
+ };
43
92
  nuxtApp.hook("app:error", disconnect);
44
93
  if (import.meta.client) {
45
94
  window.addEventListener("beforeunload", disconnect);
46
95
  }
47
- return { connect, disconnect, buildId, cookie };
96
+ return { connect, disconnect, send, sendRoute, subscribeStats, buildId, cookie };
48
97
  }
@@ -2,6 +2,8 @@ export declare const SKEW_MESSAGE_TYPE: {
2
2
  readonly VERSION: "version";
3
3
  readonly CONNECTED: "connected";
4
4
  readonly PING: "ping";
5
+ readonly ROUTE_UPDATE: "route-update";
6
+ readonly SUBSCRIBE_STATS: "subscribe-stats";
5
7
  };
6
8
  export type SkewMessageType = typeof SKEW_MESSAGE_TYPE[keyof typeof SKEW_MESSAGE_TYPE];
7
9
  export declare const SKEW_DEFAULT_CHANNEL = "skew-protection";
@@ -1,6 +1,8 @@
1
1
  export const SKEW_MESSAGE_TYPE = {
2
2
  VERSION: "version",
3
3
  CONNECTED: "connected",
4
- PING: "ping"
4
+ PING: "ping",
5
+ ROUTE_UPDATE: "route-update",
6
+ SUBSCRIBE_STATS: "subscribe-stats"
5
7
  };
6
8
  export const SKEW_DEFAULT_CHANNEL = "skew-protection";
@@ -2,33 +2,77 @@ import { defineNitroPlugin } from "nitropack/runtime";
2
2
  function getCtx(peer) {
3
3
  return peer?._internal?.durable?.ctx || null;
4
4
  }
5
- function getStats(ctx) {
5
+ function getStats(ctx, forId) {
6
6
  const websockets = ctx.getWebSockets();
7
7
  const versions = {};
8
+ const routes = {};
9
+ const connections = [];
8
10
  for (const ws of websockets) {
9
- const v = ws.deserializeAttachment?.()?.v || "unknown";
11
+ const attachment = ws.deserializeAttachment?.() || {};
12
+ const id = attachment.id || "unknown";
13
+ const v = attachment.v || "unknown";
14
+ const r = attachment.r || "/";
10
15
  versions[v] = (versions[v] || 0) + 1;
16
+ routes[r] = (routes[r] || 0) + 1;
17
+ connections.push({ id, version: v, route: r, ip: attachment.ip });
11
18
  }
12
- return { total: websockets.length, versions };
19
+ return { total: websockets.length, versions, routes, connections, yourId: forId };
13
20
  }
14
- function broadcast(ctx) {
15
- const stats = getStats(ctx);
16
- const msg = JSON.stringify({ type: "stats", ...stats });
17
- for (const ws of ctx.getWebSockets()) ws.send(msg);
21
+ function broadcastToSubscribers(ctx) {
22
+ const websockets = ctx.getWebSockets();
23
+ const subscribers = websockets.filter((ws) => {
24
+ const attachment = ws.deserializeAttachment?.() || {};
25
+ return attachment.s === true;
26
+ });
27
+ if (subscribers.length === 0)
28
+ return;
29
+ for (const ws of subscribers) {
30
+ const attachment = ws.deserializeAttachment?.() || {};
31
+ const stats = getStats(ctx, attachment.id);
32
+ ws.send(JSON.stringify({ type: "stats", ...stats }));
33
+ }
18
34
  }
19
35
  export default defineNitroPlugin((nitroApp) => {
20
- nitroApp.hooks.hook("skew:connection:open", ({ version, peer }) => {
36
+ nitroApp.hooks.hook("skew:connection:open", ({ id, version, route, ip, peer }) => {
21
37
  const ws = peer?._internal?.ws;
22
38
  if (ws?.serializeAttachment) {
23
- ws.serializeAttachment({ ...ws.deserializeAttachment?.() || {}, v: version });
39
+ ws.serializeAttachment({ ...ws.deserializeAttachment?.() || {}, id, v: version, r: route || "/", ip });
24
40
  }
25
41
  const ctx = getCtx(peer);
26
42
  if (ctx)
27
- broadcast(ctx);
43
+ broadcastToSubscribers(ctx);
44
+ });
45
+ nitroApp.hooks.hook("skew:connection:route-update", ({ route, peer }) => {
46
+ const ws = peer?._internal?.ws;
47
+ if (ws?.serializeAttachment) {
48
+ ws.serializeAttachment({ ...ws.deserializeAttachment?.() || {}, r: route });
49
+ }
50
+ const ctx = getCtx(peer);
51
+ if (ctx)
52
+ broadcastToSubscribers(ctx);
28
53
  });
29
54
  nitroApp.hooks.hook("skew:connection:close", ({ peer }) => {
30
55
  const ctx = getCtx(peer);
31
56
  if (ctx)
32
- broadcast(ctx);
57
+ broadcastToSubscribers(ctx);
58
+ });
59
+ nitroApp.hooks.hook("skew:subscribe-stats", async ({ id, event, peer }) => {
60
+ const ws = peer?._internal?.ws;
61
+ const ctx = getCtx(peer);
62
+ if (!ws || !ctx)
63
+ return;
64
+ let authorized = false;
65
+ await nitroApp.hooks.callHook("skew:authorize-stats", {
66
+ event,
67
+ authorize: () => {
68
+ authorized = true;
69
+ }
70
+ });
71
+ if (authorized) {
72
+ ws.serializeAttachment?.({ ...ws.deserializeAttachment?.() || {}, s: true });
73
+ ws.send(JSON.stringify({ type: "stats", ...getStats(ctx, id) }));
74
+ } else {
75
+ ws.send(JSON.stringify({ type: "stats-unauthorized" }));
76
+ }
33
77
  });
34
78
  });
@@ -1,25 +1,61 @@
1
1
  import { defineNitroPlugin } from "nitropack/runtime";
2
2
  export default defineNitroPlugin((nitroApp) => {
3
3
  const connections = /* @__PURE__ */ new Map();
4
- const getStats = () => {
4
+ const statsSubscribers = /* @__PURE__ */ new Set();
5
+ const getStats = (forId) => {
5
6
  const versions = {};
6
- for (const conn of connections.values()) {
7
+ const routes = {};
8
+ const connectionList = [];
9
+ for (const [id, conn] of connections.entries()) {
7
10
  versions[conn.version] = (versions[conn.version] || 0) + 1;
11
+ routes[conn.route] = (routes[conn.route] || 0) + 1;
12
+ connectionList.push({ id, version: conn.version, route: conn.route, ip: conn.ip });
8
13
  }
9
- return { total: connections.size, versions };
14
+ return { total: connections.size, versions, routes, connections: connectionList, yourId: forId };
10
15
  };
11
- const broadcast = () => {
12
- const stats = getStats();
13
- for (const conn of connections.values()) {
14
- conn.send({ type: "stats", ...stats });
16
+ const broadcastToSubscribers = () => {
17
+ if (statsSubscribers.size === 0)
18
+ return;
19
+ for (const id of statsSubscribers) {
20
+ const conn = connections.get(id);
21
+ conn?.send({ type: "stats", ...getStats(id) });
15
22
  }
16
23
  };
17
- nitroApp.hooks.hook("skew:connection:open", ({ id, version, send }) => {
18
- connections.set(id, { version, send });
19
- broadcast();
24
+ nitroApp.hooks.hook("skew:stats", (callback) => {
25
+ callback(getStats());
26
+ });
27
+ nitroApp.hooks.hook("skew:connection:open", ({ id, version, route, ip, send }) => {
28
+ connections.set(id, { version, route: route || "/", ip, send });
29
+ broadcastToSubscribers();
30
+ });
31
+ nitroApp.hooks.hook("skew:connection:route-update", ({ id, route }) => {
32
+ const conn = connections.get(id);
33
+ if (conn) {
34
+ conn.route = route;
35
+ broadcastToSubscribers();
36
+ }
20
37
  });
21
38
  nitroApp.hooks.hook("skew:connection:close", ({ id }) => {
22
39
  connections.delete(id);
23
- broadcast();
40
+ statsSubscribers.delete(id);
41
+ broadcastToSubscribers();
42
+ });
43
+ nitroApp.hooks.hook("skew:subscribe-stats", async ({ id, event }) => {
44
+ let authorized = false;
45
+ await nitroApp.hooks.callHook("skew:authorize-stats", {
46
+ id,
47
+ event,
48
+ authorize: () => {
49
+ authorized = true;
50
+ }
51
+ });
52
+ if (authorized) {
53
+ statsSubscribers.add(id);
54
+ const conn = connections.get(id);
55
+ conn?.send({ type: "stats", ...getStats(id) });
56
+ } else {
57
+ const conn = connections.get(id);
58
+ conn?.send({ type: "stats-unauthorized" });
59
+ }
24
60
  });
25
61
  });
@@ -0,0 +1,4 @@
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<{
2
+ ok: boolean;
3
+ }>>;
4
+ export default _default;
@@ -0,0 +1,13 @@
1
+ import { defineEventHandler, readBody } from "h3";
2
+ import { useNitroApp } from "nitropack/runtime";
3
+ export default defineEventHandler(async (event) => {
4
+ const body = await readBody(event);
5
+ if (!body?.connectionId || !body?.route) {
6
+ return { ok: false };
7
+ }
8
+ await useNitroApp().hooks.callHook("skew:connection:route-update", {
9
+ id: body.connectionId,
10
+ route: body.route
11
+ });
12
+ return { ok: true };
13
+ });
@@ -1,4 +1,4 @@
1
- import { createEventStream, defineEventHandler } from "h3";
1
+ import { createEventStream, defineEventHandler, getQuery, getRequestIP } from "h3";
2
2
  import { useNitroApp, useRuntimeConfig } from "nitropack/runtime";
3
3
  import { SKEW_MESSAGE_TYPE } from "../../../const.js";
4
4
  import { getSkewProtectionCookie } from "../../imports/cookie.js";
@@ -9,32 +9,43 @@ export default defineEventHandler(async (event) => {
9
9
  const send = (data) => {
10
10
  stream.push(JSON.stringify(data));
11
11
  };
12
+ const connectionId = crypto.randomUUID();
12
13
  send({
13
14
  type: SKEW_MESSAGE_TYPE.CONNECTED,
14
15
  version: serverVersion,
16
+ connectionId,
15
17
  timestamp: Date.now()
16
18
  });
17
- const connectionId = crypto.randomUUID();
18
19
  const clientVersion = getSkewProtectionCookie(event) || serverVersion;
20
+ const query = getQuery(event);
21
+ const initialRoute = query.route || "/";
22
+ const ip = getRequestIP(event, { xForwardedFor: true }) || void 0;
19
23
  await nitroApp.hooks.callHook("skew:connection:open", {
20
24
  id: connectionId,
21
25
  version: clientVersion,
26
+ route: initialRoute,
27
+ ip,
22
28
  send
23
29
  });
24
- const keepaliveInterval = setInterval(() => {
25
- send({ type: "keepalive", timestamp: Date.now() });
26
- }, 3e4);
30
+ let keepaliveTimeout;
31
+ const scheduleKeepalive = () => {
32
+ keepaliveTimeout = setTimeout(() => {
33
+ send({ type: "keepalive", timestamp: Date.now() });
34
+ scheduleKeepalive();
35
+ }, 3e4);
36
+ };
37
+ scheduleKeepalive();
27
38
  let cleanupDone = false;
28
39
  const close = async () => {
29
40
  if (cleanupDone)
30
41
  return;
31
42
  cleanupDone = true;
32
- clearInterval(keepaliveInterval);
43
+ clearTimeout(keepaliveTimeout);
44
+ process.off("SIGTERM", close);
33
45
  await nitroApp.hooks.callHook("skew:connection:close", { id: connectionId });
34
46
  await stream.close();
35
47
  };
36
48
  stream.onClosed(close);
37
- nitroApp.hooks.hook("close", close);
38
49
  process.on("SIGTERM", close);
39
50
  return stream.send();
40
51
  });
@@ -0,0 +1,8 @@
1
+ /**
2
+ * POST endpoint for SSE connections to request stats subscription.
3
+ * Since SSE is unidirectional, clients POST here to subscribe.
4
+ */
5
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<{
6
+ ok: boolean;
7
+ }>>;
8
+ export default _default;
@@ -0,0 +1,13 @@
1
+ import { createError, defineEventHandler, readBody } from "h3";
2
+ import { useNitroApp } from "nitropack/runtime";
3
+ export default defineEventHandler(async (event) => {
4
+ const body = await readBody(event);
5
+ if (!body.connectionId) {
6
+ throw createError({ statusCode: 400, message: "Missing connectionId" });
7
+ }
8
+ await useNitroApp().hooks.callHook("skew:subscribe-stats", {
9
+ id: body.connectionId,
10
+ event
11
+ });
12
+ return { ok: true };
13
+ });
@@ -10,21 +10,49 @@ export default defineWebSocketHandler({
10
10
  peer.send(JSON.stringify({
11
11
  type: SKEW_MESSAGE_TYPE.CONNECTED,
12
12
  version: serverVersion,
13
+ connectionId: peer.id,
13
14
  timestamp: Date.now()
14
15
  }));
15
16
  const cookieHeader = peer.request?.headers?.get("cookie") || "";
16
17
  const cookies = parseCookie(cookieHeader);
17
18
  const clientVersion = cookies[cookieName] || serverVersion;
19
+ const url = new URL(peer.request?.url || "", "http://localhost");
20
+ const initialRoute = url.searchParams.get("route") || "/";
21
+ const forwarded = peer.request?.headers?.get("x-forwarded-for");
22
+ const ip = peer.request?.headers?.get("cf-connecting-ip") || forwarded?.split(",")[0]?.trim() || peer.request?.headers?.get("x-real-ip") || void 0;
18
23
  useNitroApp().hooks.callHook("skew:connection:open", {
19
24
  id: peer.id,
20
25
  version: clientVersion,
26
+ route: initialRoute,
27
+ ip,
21
28
  send: (data) => peer.send(JSON.stringify(data)),
22
29
  peer
23
30
  });
24
31
  },
25
32
  message(peer, message) {
26
- if (message.text().includes("ping")) {
33
+ const text = message.text();
34
+ if (text.includes("ping")) {
27
35
  peer.send(JSON.stringify({ type: "pong" }));
36
+ return;
37
+ }
38
+ let data;
39
+ try {
40
+ data = JSON.parse(text);
41
+ } catch {
42
+ return;
43
+ }
44
+ if (data.type === SKEW_MESSAGE_TYPE.ROUTE_UPDATE && data.route) {
45
+ useNitroApp().hooks.callHook("skew:connection:route-update", {
46
+ id: peer.id,
47
+ route: data.route,
48
+ peer
49
+ });
50
+ } else if (data.type === SKEW_MESSAGE_TYPE.SUBSCRIBE_STATS) {
51
+ useNitroApp().hooks.callHook("skew:subscribe-stats", {
52
+ id: peer.id,
53
+ event: { headers: peer.request?.headers },
54
+ peer
55
+ });
28
56
  }
29
57
  },
30
58
  close(peer) {
@@ -7,6 +7,8 @@ export interface NuxtSkewProtectionRuntimeConfig {
7
7
  };
8
8
  debug: boolean;
9
9
  connectionTracking?: boolean;
10
+ routeTracking?: boolean;
11
+ ipTracking?: boolean;
10
12
  }
11
13
  export interface SkewProtectionRuntimeConfig {
12
14
  cookie: Omit<CookieSerializeOptions, 'encode'> & {
@@ -14,6 +16,8 @@ export interface SkewProtectionRuntimeConfig {
14
16
  };
15
17
  debug: boolean;
16
18
  connectionTracking?: boolean;
19
+ routeTracking?: boolean;
20
+ ipTracking?: boolean;
17
21
  }
18
22
  export interface ChunksOutdatedPayload {
19
23
  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.6.0",
4
+ "version": "0.7.1",
5
5
  "description": "Solve Nuxt version skews with persistent assets and instant updates.",
6
6
  "author": {
7
7
  "name": "Harlan Wilton",
@@ -63,48 +63,49 @@
63
63
  "tinyexec": "^1.0.2",
64
64
  "ufo": "^1.6.1",
65
65
  "unstorage": "^1.17.3",
66
- "zod": "^4.1.13"
66
+ "zod": "^4.3.5"
67
67
  },
68
68
  "devDependencies": {
69
- "@antfu/eslint-config": "^6.6.1",
69
+ "@antfu/eslint-config": "^6.7.3",
70
70
  "@arethetypeswrong/cli": "^0.18.2",
71
- "@nuxt/content": "^3.9.0",
71
+ "@nuxt/content": "^3.10.0",
72
72
  "@nuxt/devtools-ui-kit": "^3.1.1",
73
73
  "@nuxt/module-builder": "^1.0.2",
74
- "@nuxt/test-utils": "^3.21.0",
75
- "@nuxt/ui": "^4.2.1",
74
+ "@nuxt/test-utils": "^3.22.0",
75
+ "@nuxt/ui": "^4.3.0",
76
76
  "@nuxtjs/color-mode": "^4.0.0",
77
77
  "@nuxtjs/eslint-config-typescript": "^12.1.0",
78
78
  "@nuxtjs/i18n": "^10.2.1",
79
79
  "@nuxtjs/robots": "^5.6.7",
80
80
  "@types/ioredis": "^5.0.0",
81
81
  "@types/ws": "^8.18.1",
82
- "@unocss/nuxt": "66.5.10",
83
- "@unocss/preset-icons": "66.5.10",
84
- "@unocss/preset-uno": "66.5.10",
85
- "@unocss/runtime": "66.5.10",
82
+ "@unocss/nuxt": "66.5.12",
83
+ "@unocss/preset-icons": "66.5.12",
84
+ "@unocss/preset-uno": "66.5.12",
85
+ "@unocss/runtime": "66.5.12",
86
86
  "@vueuse/nuxt": "^14.1.0",
87
- "ably": "^2.15.0",
87
+ "ably": "^2.16.0",
88
88
  "better-sqlite3": "^12.5.0",
89
89
  "bumpp": "^10.3.2",
90
90
  "eslint": "^9.39.2",
91
91
  "eventsource": "^4.1.0",
92
92
  "execa": "^9.6.1",
93
- "firebase-functions": "^7.0.1",
93
+ "firebase-functions": "^7.0.2",
94
94
  "happy-dom": "^20.0.11",
95
- "ioredis": "^5.8.2",
95
+ "ioredis": "^5.9.0",
96
96
  "nuxt": "^4.2.2",
97
+ "nuxt-auth-utils": "^0.5.26",
97
98
  "playwright-core": "^1.57.0",
98
99
  "pusher-js": "^8.4.0",
99
100
  "tsx": "^4.21.0",
100
101
  "typescript": "^5.9.3",
101
- "unocss": "66.5.10",
102
- "vitest": "^4.0.15",
103
- "vue": "^3.5.25",
102
+ "unocss": "66.5.12",
103
+ "vitest": "^4.0.16",
104
+ "vue": "^3.5.26",
104
105
  "vue-router": "^4.6.4",
105
- "vue-tsc": "^3.1.8",
106
+ "vue-tsc": "^3.2.2",
106
107
  "wrangler": "^4.54.0",
107
- "ws": "^8.18.3"
108
+ "ws": "^8.19.0"
108
109
  },
109
110
  "resolutions": {
110
111
  "nuxt-skew-protection": "workspace:*",