@cossackframework/node-adapter 0.5.2 → 0.6.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/dist/index.js CHANGED
@@ -1,16 +1,10 @@
1
1
  import { WebSocket as e, WebSocketServer as t } from "ws";
2
- import { URL as n } from "url";
3
- //#region \0rolldown/runtime.js
4
- var r = Object.create, i = Object.defineProperty, a = Object.getOwnPropertyDescriptor, o = Object.getOwnPropertyNames, s = Object.getPrototypeOf, c = Object.prototype.hasOwnProperty, l = (e, t) => () => (t || (e((t = { exports: {} }).exports, t), e = null), t.exports), u = (e, t, n, r) => {
5
- if (t && typeof t == "object" || typeof t == "function") for (var s = o(t), l = 0, u = s.length, d; l < u; l++) d = s[l], !c.call(e, d) && d !== n && i(e, d, {
6
- get: ((e) => t[e]).bind(null, d),
7
- enumerable: !(r = a(t, d)) || r.enumerable
8
- });
9
- return e;
10
- }, d = (e, t, n) => (n = e == null ? {} : r(s(e)), u(t || !e || !e.__esModule ? i(n, "default", {
11
- value: e,
12
- enumerable: !0
13
- }) : n, e)), f = class {
2
+ import { createInstance as n, isOriginAllowed as r } from "@cossackframework/core";
3
+ import { URL as i } from "url";
4
+ import * as a from "fs";
5
+ import * as o from "path";
6
+ //#region src/runtime.ts
7
+ var s = class {
14
8
  component;
15
9
  clients = /* @__PURE__ */ new Set();
16
10
  constructor(e) {
@@ -20,15 +14,22 @@ var r = Object.create, i = Object.defineProperty, a = Object.getOwnPropertyDescr
20
14
  this.clients.add(e), e.user = t, e.on("close", () => {
21
15
  this.clients.delete(e);
22
16
  }), e.on("message", (t) => {
23
- this.onClientMessage(e, t.toString());
17
+ this.onClientMessage(e, t.toString()).catch((e) => {
18
+ console.error("[Cossack] Error handling Node WebSocket message:", e);
19
+ });
24
20
  });
25
21
  }
26
22
  async onClientMessage(e, t) {
27
- let n = e, r = JSON.parse(t);
28
- if (r.type === "action") {
29
- let t = n.user;
30
- await this.component.executeAction(r.action, r.payload, t, e);
23
+ let n = e, r;
24
+ try {
25
+ r = JSON.parse(t);
26
+ } catch (e) {
27
+ console.error("[Cossack] Ignoring malformed WebSocket message:", e);
28
+ return;
31
29
  }
30
+ if (!r || typeof r != "object" || r.type !== "action" || typeof r.action != "string" || !Array.isArray(r.payload)) return;
31
+ let i = n.user;
32
+ await this.component.executeAction(r.action, r.payload, i, e);
32
33
  }
33
34
  broadcastState(t) {
34
35
  let n = JSON.stringify({
@@ -54,43 +55,54 @@ var r = Object.create, i = Object.defineProperty, a = Object.getOwnPropertyDescr
54
55
  i.readyState === e.OPEN && i.send(a);
55
56
  }
56
57
  async persistState() {}
57
- }, p = /* @__PURE__ */ d((/* @__PURE__ */ l(((e, t) => {
58
- t.exports = {};
59
- })))(), 1);
60
- function m(e) {
58
+ };
59
+ //#endregion
60
+ //#region src/static-serve.ts
61
+ function c(e) {
61
62
  let t = e, n = t.indexOf("?");
62
63
  n !== -1 && (t = t.substring(0, n));
63
64
  let r = t.indexOf("#");
64
65
  return r !== -1 && (t = t.substring(0, r)), t.startsWith("/") || (t = "/" + t), t !== "/" && t.endsWith("/") && (t = t.slice(0, -1)), t;
65
66
  }
66
- function h(e) {
67
- let { root: t, prefix: n = "/", index: r = !0 } = e;
67
+ function l(e) {
68
+ let { root: t, prefix: n = "/", index: r = !0 } = e, i = o.resolve(t), s = i + o.sep, l = (e) => {
69
+ let t = o.resolve(e);
70
+ return t === i || t.startsWith(s);
71
+ };
68
72
  return async (e, i) => {
69
73
  if (e.req.method !== "GET" && e.req.method !== "HEAD") return i();
70
- let a = m(e.req.path);
71
- if (!a.startsWith(n)) return i();
72
- let o = a.substring(n.length);
73
- o === "" && (o = "/");
74
- let s;
75
- if (o === "/") s = p.join(t, "index.html");
76
- else if (s = p.join(t, o), r && !p.existsSync(s)) {
77
- let e = p.join(s, "index.html");
78
- p.existsSync(e) && (s = e);
74
+ let s = c(e.req.path);
75
+ if (!s.startsWith(n)) return i();
76
+ let d = s.substring(n.length);
77
+ d === "" && (d = "/");
78
+ let f;
79
+ if (d === "/") f = o.join(t, "index.html");
80
+ else if (f = o.join(t, d), r && !a.existsSync(f)) {
81
+ let e = o.join(f, "index.html");
82
+ a.existsSync(e) && (f = e);
79
83
  }
84
+ if (!l(f)) return i();
80
85
  try {
81
- if (p.statSync(s).isDirectory()) if (r) {
82
- let e = p.join(s, "index.html");
83
- if (p.existsSync(e)) s = e;
84
- else return i();
86
+ let e = await a.promises.stat(f);
87
+ if (e.isDirectory()) if (r) {
88
+ let t = o.join(f, "index.html");
89
+ try {
90
+ await a.promises.access(t), f = t, e = await a.promises.stat(f);
91
+ } catch {
92
+ return i();
93
+ }
85
94
  } else return i();
86
- let t = p.readFileSync(s, "utf-8");
87
- return g(s), e.html(t, 200);
95
+ let t = await a.promises.readFile(f), n = u(f);
96
+ return new Response(new Uint8Array(t), {
97
+ status: 200,
98
+ headers: { "Content-Type": n }
99
+ });
88
100
  } catch {
89
101
  return i();
90
102
  }
91
103
  };
92
104
  }
93
- function g(e) {
105
+ function u(e) {
94
106
  return {
95
107
  ".html": "text/html",
96
108
  ".css": "text/css",
@@ -110,64 +122,79 @@ function g(e) {
110
122
  ".eot": "application/vnd.ms-fontobject",
111
123
  ".pdf": "application/pdf",
112
124
  ".zip": "application/zip"
113
- }[p.extname(e).toLowerCase()] || "application/octet-stream";
125
+ }[o.extname(e).toLowerCase()] || "application/octet-stream";
114
126
  }
115
127
  //#endregion
116
128
  //#region src/index.ts
117
- var _ = class {
129
+ var d = class {
118
130
  wss;
119
131
  instances = /* @__PURE__ */ new Map();
120
132
  componentRegistry;
133
+ allowedOrigins;
134
+ authenticate;
135
+ defaultUser;
121
136
  constructor(e) {
122
- this.wss = new t({ noServer: !0 }), this.componentRegistry = e.componentRegistry, e.server.on("upgrade", (t, r, i) => {
123
- new n(t.url || "", `http://${t.headers.host}`).pathname.startsWith(e.path || "/ws") && this.handleUpgrade(t, r, i);
137
+ this.wss = new t({ noServer: !0 }), this.componentRegistry = e.componentRegistry, this.allowedOrigins = e.allowedOrigins, this.authenticate = e.authenticate, this.defaultUser = e.defaultUser ?? { id: "anonymous" }, e.server.on("upgrade", (t, n, r) => {
138
+ new i(t.url || "", `http://${t.headers.host}`).pathname.startsWith(e.path || "/ws") && this.handleUpgrade(t, n, r);
124
139
  });
125
140
  }
126
- handleUpgrade(e, t, r) {
127
- this.wss.handleUpgrade(e, t, r, async (t) => {
128
- let r = new n(e.url || "", `http://${e.headers.host}`), i = r.pathname.split("/"), a = i.pop(), o = i.pop(), s = r.searchParams, c = s.get("componentId");
129
- if (!a || !c) {
141
+ handleUpgrade(e, t, a) {
142
+ let o = new i(e.url || "", `http://${e.headers.host}`).toString(), c = e.headers.origin;
143
+ if (!r(c, o, this.allowedOrigins)) {
144
+ t.destroy();
145
+ return;
146
+ }
147
+ this.wss.handleUpgrade(e, t, a, async (t) => {
148
+ let r = new i(e.url || "", `http://${e.headers.host}`), a = r.pathname.split("/"), o = a.pop(), c = a.pop(), l = r.searchParams, u = l.get("componentId");
149
+ if (!o || !u) {
130
150
  t.close(1008, "Missing target or componentId");
131
151
  return;
132
152
  }
133
- let l = this.instances.get(a);
134
- if (!l) {
135
- let e = this.componentRegistry.get(c);
153
+ let d = this.instances.get(o);
154
+ if (!d) {
155
+ let e = this.componentRegistry.get(u);
136
156
  if (!e) {
137
157
  t.close(1008, "Component not found");
138
158
  return;
139
159
  }
140
- let n = new e(), r = s.get("pathname") || "/", i = { req: {
141
- path: r,
160
+ let r = n(e), i = l.get("pathname") || "/", a = { req: {
161
+ path: i,
142
162
  param: (e) => {
143
- if (e) return s.get(e);
163
+ if (e) return l.get(e);
144
164
  let t = {};
145
- return s.forEach((e, n) => {
165
+ return l.forEach((e, n) => {
146
166
  t[n] = e;
147
167
  }), t;
148
168
  },
149
169
  query: (e) => {
150
- if (e) return s.get(e);
170
+ if (e) return l.get(e);
151
171
  let t = {};
152
- return s.forEach((e, n) => {
172
+ return l.forEach((e, n) => {
153
173
  t[n] = e;
154
174
  }), t;
155
175
  }
156
176
  } };
157
- await n.bootstrap({
158
- context: i,
159
- page: r,
160
- providerName: o
161
- }), l = new f(n), this.instances.set(a, l);
177
+ await r.bootstrap({
178
+ context: a,
179
+ page: i,
180
+ providerName: c
181
+ }), d = new s(r), this.instances.set(o, d);
182
+ }
183
+ let f;
184
+ try {
185
+ f = this.authenticate ? await this.authenticate(e) : this.defaultUser;
186
+ } catch (e) {
187
+ console.error("[Cossack] Authentication failed, rejecting upgrade:", e), t.close(1008, "Authentication failed");
188
+ return;
162
189
  }
163
- l.addClient(t, { id: "guest" });
164
- let u = l.component.getInitialState();
190
+ d.addClient(t, f);
191
+ let p = d.component.getInitialState();
165
192
  t.send(JSON.stringify({
166
193
  type: "state-update",
167
- state: u
194
+ state: p
168
195
  }));
169
196
  });
170
197
  }
171
198
  };
172
199
  //#endregion
173
- export { _ as CossackNodeAdapter, f as NodeWebSocketRuntime, h as serveStatic };
200
+ export { d as CossackNodeAdapter, s as NodeWebSocketRuntime, l as serveStatic };
@@ -1,16 +1,36 @@
1
- import { Server } from 'http';
1
+ import { IncomingMessage, Server } from 'http';
2
2
  import { Cossack } from '@cossackframework/core';
3
3
 
4
4
  export * from './runtime';
5
5
  export { serveStatic, type StaticServeOptions } from './static-serve';
6
+ export interface CossackNodeAdapterOptions {
7
+ server: Server;
8
+ componentRegistry: Map<string, new () => Cossack>;
9
+ path?: string;
10
+ /**
11
+ * Allowed Origin values for WebSocket upgrades. Defaults to same-origin
12
+ * (the request's own origin). Missing Origin headers are rejected, which
13
+ * blocks cross-site WebSocket hijacking.
14
+ */
15
+ allowedOrigins?: string[];
16
+ /**
17
+ * Authenticate the WebSocket upgrade, returning the user object the
18
+ * component should run as (e.g. parsed from a cookie/JWT on `request`).
19
+ * Falls back to `defaultUser` then to `{ id: 'anonymous' }`. Provide this
20
+ * for any app with per-user state or authorization — otherwise every
21
+ * connection shares one anonymous identity.
22
+ */
23
+ authenticate?: (request: IncomingMessage) => Promise<unknown> | unknown;
24
+ /** User used when no `authenticate` hook is provided. Defaults to `{ id: 'anonymous' }`. */
25
+ defaultUser?: unknown;
26
+ }
6
27
  export declare class CossackNodeAdapter {
7
28
  private wss;
8
29
  private instances;
9
30
  private componentRegistry;
10
- constructor(options: {
11
- server: Server;
12
- componentRegistry: Map<string, new () => Cossack>;
13
- path?: string;
14
- });
31
+ private allowedOrigins?;
32
+ private authenticate?;
33
+ private defaultUser;
34
+ constructor(options: CossackNodeAdapterOptions);
15
35
  private handleUpgrade;
16
36
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cossackframework/node-adapter",
3
- "version": "0.5.2",
3
+ "version": "0.6.0",
4
4
  "type": "module",
5
5
  "description": "Node.js runtime adapter for the Cossack Framework",
6
6
  "license": "MIT",
@@ -25,7 +25,7 @@
25
25
  "dependencies": {
26
26
  "hono": "^4.12.25",
27
27
  "ws": ">=8.21.0",
28
- "@cossackframework/core": "0.5.2"
28
+ "@cossackframework/core": "0.6.0"
29
29
  },
30
30
  "devDependencies": {
31
31
  "@types/ws": "^8.18.0",