@arcblock/event-hub 1.30.24 → 1.30.25

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/esm/index.mjs CHANGED
@@ -2,11 +2,14 @@ import client_default from "./client.mjs";
2
2
  import { Client } from "./single.mjs";
3
3
 
4
4
  //#region src/index.ts
5
- const port = Number(process.env.ABT_NODE_EVENT_PORT);
6
- const hostname = process.env.ABT_NODE_EVENT_HOSTNAME || "127.0.0.1";
5
+ const port = Number(process.env.CHAIN_EVENT_PORT || process.env.ABT_NODE_EVENT_PORT);
6
+ const hostname = process.env.CHAIN_EVENT_HOSTNAME || process.env.ABT_NODE_EVENT_HOSTNAME || "127.0.0.1";
7
7
  let did;
8
8
  let sk;
9
- if (process.env.BLOCKLET_APP_SK && process.env.BLOCKLET_APP_ID) {
9
+ if (process.env.CHAIN_SK && process.env.CHAIN_DID) {
10
+ sk = process.env.CHAIN_SK;
11
+ did = process.env.CHAIN_DID;
12
+ } else if (process.env.BLOCKLET_APP_SK && process.env.BLOCKLET_APP_ID) {
10
13
  sk = process.env.BLOCKLET_APP_SK;
11
14
  did = process.env.BLOCKLET_APP_ID;
12
15
  } else if (process.env.ABT_NODE_SK && process.env.ABT_NODE_DID) {
@@ -1,6 +1,8 @@
1
1
  import Server from "./server.mjs";
2
2
 
3
3
  //#region src/server-abtnode.d.ts
4
+ declare function isLoopbackHostname(hostname: string): boolean;
5
+ declare function resolveLoopbackHostname(rawHostname?: string | undefined, allowNonLoopback?: boolean): string;
4
6
  declare const server: Server;
5
7
  //#endregion
6
- export { server as default };
8
+ export { server as default, isLoopbackHostname, resolveLoopbackHostname };
@@ -1,11 +1,23 @@
1
1
  import server_default from "./server.mjs";
2
2
 
3
3
  //#region src/server-abtnode.ts
4
+ const LOOPBACK_IPV4_RE = /^127\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;
5
+ function isLoopbackHostname(hostname) {
6
+ const normalized = hostname.trim().toLowerCase();
7
+ return normalized === "localhost" || normalized === "::1" || normalized === "[::1]" || LOOPBACK_IPV4_RE.test(normalized);
8
+ }
9
+ function resolveLoopbackHostname(rawHostname = process.env.ABT_NODE_EVENT_HOSTNAME, allowNonLoopback = process.env.EVENT_HUB_ALLOW_NON_LOOPBACK === "1" || process.env.EVENT_HUB_ALLOW_NON_LOOPBACK === "true") {
10
+ const hostname = typeof rawHostname === "string" && rawHostname.trim() ? rawHostname.trim() : "127.0.0.1";
11
+ if (!allowNonLoopback && !isLoopbackHostname(hostname)) throw new Error(`Refusing to bind event-hub server to non-loopback hostname: "${hostname}"`);
12
+ return hostname;
13
+ }
4
14
  const port = Number(process.env.ABT_NODE_EVENT_PORT);
5
- const hostname = Number(process.env.ABT_NODE_EVENT_HOSTNAME) || "127.0.0.1";
6
15
  const server = new server_default();
7
- server.bind(port, hostname);
16
+ if (Number.isInteger(port) && port > 0) {
17
+ const hostname = resolveLoopbackHostname(process.env.ABT_NODE_EVENT_HOSTNAME);
18
+ server.bind(port, hostname);
19
+ }
8
20
  var server_abtnode_default = server;
9
21
 
10
22
  //#endregion
11
- export { server_abtnode_default as default };
23
+ export { server_abtnode_default as default, isLoopbackHostname, resolveLoopbackHostname };
package/esm/server.d.mts CHANGED
@@ -5,15 +5,47 @@ interface JwtLike {
5
5
  verify(token: string, pk: string): Promise<boolean>;
6
6
  decode(token: string): {
7
7
  iss: string;
8
+ exp?: number;
8
9
  };
9
10
  }
11
+ interface RouteContext {
12
+ sock: SocketWithChannel;
13
+ channel?: string;
14
+ event: string;
15
+ server: Server;
16
+ }
17
+ type AuthorizePredicate = (did: string | undefined, ctx: RouteContext) => boolean | Promise<boolean>;
10
18
  interface ServerOptions {
11
19
  jwt?: JwtLike;
20
+ maxAuthAttempts?: number;
21
+ authWindowMs?: number;
22
+ allowedDids?: Iterable<string>;
23
+ authorize?: AuthorizePredicate;
24
+ sanitizeErrors?: boolean;
25
+ }
26
+ interface RegisterOptions {
27
+ /**
28
+ * Whether the caller socket must have completed EVENT_AUTH (proving DID key ownership).
29
+ * Defaults to true. To restrict *which* authenticated DIDs can call the route, also
30
+ * pass `allowedDids` or `authorize`.
31
+ */
32
+ authRequired?: boolean;
33
+ /** Optional allowlist of DIDs permitted to invoke this route. */
34
+ allowedDids?: Iterable<string>;
35
+ /** Optional custom authorization predicate `(did, ctx) => boolean | Promise<boolean>`. */
36
+ authorize?: AuthorizePredicate;
37
+ /** Always replace thrown handler errors with a generic message. */
38
+ sanitizeErrors?: boolean;
12
39
  }
13
40
  interface SocketWithChannel {
14
41
  channel?: string;
42
+ channelExp?: number;
43
+ authFailures?: number;
44
+ authWindowStart?: number;
15
45
  writable: boolean;
16
46
  write(buf: Buffer): void;
47
+ destroy?: () => void;
48
+ end?: () => void;
17
49
  _peername?: {
18
50
  family: string;
19
51
  address: string;
@@ -21,35 +53,35 @@ interface SocketWithChannel {
21
53
  };
22
54
  }
23
55
  interface RouteHandler {
24
- fn: (payload: unknown, ctx: {
25
- sock: SocketWithChannel;
26
- channel?: string;
27
- event: string;
28
- server: Server;
29
- }) => unknown | Promise<unknown>;
56
+ fn: (payload: unknown, ctx: RouteContext) => unknown | Promise<unknown>;
30
57
  authRequired: boolean;
58
+ allowedDids?: Set<string>;
59
+ authorize?: AuthorizePredicate;
60
+ sanitizeErrors?: boolean;
31
61
  }
62
+ declare function sanitizeErrorMessage(err: unknown, fallback?: string, sanitizeAll?: boolean): string;
32
63
  declare class Server extends axon.Socket {
33
64
  jwt: JwtLike;
34
65
  handlers: Map<string, RouteHandler>;
66
+ maxAuthAttempts: number;
67
+ authWindowMs: number;
68
+ allowedDids?: Set<string>;
69
+ authorize?: AuthorizePredicate;
70
+ sanitizeErrors: boolean;
35
71
  socks: SocketWithChannel[];
36
72
  constructor(opts?: ServerOptions);
73
+ _recordAuthFailure(sock: SocketWithChannel, msg: string): void;
37
74
  onmessage(sock: SocketWithChannel): (buf: Buffer) => void;
38
75
  send(event: string, data: unknown, channel: string): this;
39
76
  /**
40
77
  * 注册路由
78
+ * Note: `authRequired: true` (default) verifies that the caller owns a valid DID keypair.
79
+ * For privileged routes, pass `allowedDids` or `authorize(did, ctx)` to restrict which DIDs may call the route.
41
80
  * @param {string} event
42
- * @param {(payload:any, ctx:{sock:any, channel?:string, event:string, server:Server})=>any|Promise<any>} handler
43
- * @param {{authRequired?: boolean}} [opts] - 默认 true;设为 false 则该事件免鉴权
81
+ * @param {(payload:any, ctx:RouteContext)=>any|Promise<any>} handler
82
+ * @param {RegisterOptions} [opts]
44
83
  */
45
- register(event: string, handler: (payload: unknown, ctx: {
46
- sock: SocketWithChannel;
47
- channel?: string;
48
- event: string;
49
- server: Server;
50
- }) => unknown | Promise<unknown>, opts?: {
51
- authRequired?: boolean;
52
- }): this;
84
+ register(event: string, handler: (payload: unknown, ctx: RouteContext) => unknown | Promise<unknown>, opts?: RegisterOptions): this;
53
85
  }
54
86
  //#endregion
55
- export { Server as default };
87
+ export { AuthorizePredicate, RegisterOptions, RouteContext, ServerOptions, Server as default, sanitizeErrorMessage };
package/esm/server.mjs CHANGED
@@ -4,7 +4,29 @@ import Message from "amp-message";
4
4
  import * as JWT from "@arcblock/jwt";
5
5
 
6
6
  //#region src/server.ts
7
- const getDid = (jwt) => jwt.iss.replace(/^did:abt:/, "");
7
+ const DEFAULT_MAX_AUTH_ATTEMPTS = 5;
8
+ const DEFAULT_AUTH_WINDOW_MS = 60 * 1e3;
9
+ const normalizeDid = (did) => typeof did === "string" ? did.trim().replace(/^did:[a-z0-9]+:/i, "") : "";
10
+ const getDid = (jwt) => normalizeDid(jwt?.iss);
11
+ const toDidSet = (dids) => {
12
+ if (!dids) return void 0;
13
+ const set = /* @__PURE__ */ new Set();
14
+ for (const d of dids) {
15
+ const normalized = normalizeDid(d);
16
+ if (normalized) set.add(normalized);
17
+ }
18
+ return set;
19
+ };
20
+ const INTERNAL_ERROR_RE = /\b(?:EACCES|EADDRINUSE|ECONNREFUSED|ENOENT|EPERM|ETIMEDOUT|SQLITE_\w+|ER_[A-Z_]+|TypeError|ReferenceError|SyntaxError|RangeError)\b/;
21
+ const FILE_PATH_RE = /(?:\/[\w.-]+){2,}|[A-Za-z]:\\[\w.\\-]+/;
22
+ function sanitizeErrorMessage(err, fallback = "Internal server error", sanitizeAll = false) {
23
+ if (sanitizeAll) return fallback;
24
+ if (err instanceof TypeError || err instanceof ReferenceError || err instanceof SyntaxError || err instanceof RangeError) return fallback;
25
+ if (err && typeof err === "object" && ("syscall" in err || "path" in err || "sql" in err)) return fallback;
26
+ const msg = err?.message || String(err ?? "");
27
+ if (!msg || msg.includes("\n") || INTERNAL_ERROR_RE.test(msg) || FILE_PATH_RE.test(msg)) return fallback;
28
+ return msg;
29
+ }
8
30
  function normalizeReq(input) {
9
31
  if (input && typeof input === "object" && ("payload" in input || "reqId" in input)) {
10
32
  const { reqId, payload } = input;
@@ -29,47 +51,87 @@ var Server = class extends axon.Socket {
29
51
  constructor(opts = {}) {
30
52
  super();
31
53
  this.jwt = opts?.jwt || JWT;
54
+ this.maxAuthAttempts = opts.maxAuthAttempts ?? DEFAULT_MAX_AUTH_ATTEMPTS;
55
+ this.authWindowMs = opts.authWindowMs ?? DEFAULT_AUTH_WINDOW_MS;
56
+ this.allowedDids = toDidSet(opts.allowedDids);
57
+ this.authorize = opts.authorize;
58
+ this.sanitizeErrors = opts.sanitizeErrors ?? false;
32
59
  this.handlers = /* @__PURE__ */ new Map();
33
60
  this.on("message", async (event, data, sock) => {
61
+ if (sock.channelExp && Date.now() >= sock.channelExp) {
62
+ sock.channel = void 0;
63
+ sock.channelExp = void 0;
64
+ }
34
65
  const route = this.handlers.get(event);
35
66
  if (route) {
36
- const { fn, authRequired } = route;
67
+ const { fn, authRequired, allowedDids, authorize, sanitizeErrors } = route;
68
+ const { reqId, payload } = normalizeReq(data);
69
+ const replyEvent = `${event}:res`;
70
+ const sendReply = (resObj) => {
71
+ if (sock.channel) this.send(replyEvent, resObj, sock.channel);
72
+ else if (sock.writable) {
73
+ const buf = this.pack([replyEvent, resObj]);
74
+ sock.write(buf);
75
+ }
76
+ };
37
77
  if (authRequired && !sock.channel) {
38
78
  console.error(`unauthenticated socket blocked for event "${event}"`);
79
+ if (reqId) sendReply({
80
+ reqId,
81
+ ok: false,
82
+ error: "unauthorized"
83
+ });
39
84
  return;
40
85
  }
41
- const { reqId, payload } = normalizeReq(data);
42
- try {
43
- const res = normalizeRes(await fn(payload, {
44
- sock,
45
- channel: sock.channel,
46
- event,
47
- server: this
48
- }));
49
- const replyEvent = `${event}:res`;
50
- if (sock.channel) this.send(replyEvent, {
86
+ const ctx = {
87
+ sock,
88
+ channel: sock.channel,
89
+ event,
90
+ server: this
91
+ };
92
+ const callerDid = normalizeDid(sock.channel);
93
+ const effectiveAllowedDids = allowedDids ?? this.allowedDids;
94
+ if (effectiveAllowedDids && (!callerDid || !effectiveAllowedDids.has(callerDid))) {
95
+ console.error(`unauthorized DID "${callerDid}" blocked for event "${event}"`);
96
+ sendReply({
51
97
  reqId,
52
- ...res
53
- }, sock.channel);
54
- else {
55
- const buf = this.pack([replyEvent, {
98
+ ok: false,
99
+ error: "forbidden"
100
+ });
101
+ return;
102
+ }
103
+ const effectiveAuthorize = authorize ?? this.authorize;
104
+ if (effectiveAuthorize) try {
105
+ if (!await effectiveAuthorize(callerDid || void 0, ctx)) {
106
+ console.error(`unauthorized DID "${callerDid}" blocked by authorize predicate for event "${event}"`);
107
+ sendReply({
56
108
  reqId,
57
- ...res
58
- }]);
59
- if (sock.writable) sock.write(buf);
109
+ ok: false,
110
+ error: "forbidden"
111
+ });
112
+ return;
60
113
  }
114
+ } catch (authErr) {
115
+ console.error(authErr);
116
+ sendReply({
117
+ reqId,
118
+ ok: false,
119
+ error: "forbidden"
120
+ });
121
+ return;
122
+ }
123
+ try {
124
+ sendReply({
125
+ reqId,
126
+ ...normalizeRes(await fn(payload, ctx))
127
+ });
61
128
  } catch (err) {
62
- const replyEvent = `${event}:res`;
63
- const payloadErr = {
129
+ console.error(err);
130
+ sendReply({
64
131
  reqId,
65
132
  ok: false,
66
- error: err?.message || String(err)
67
- };
68
- if (sock.channel) this.send(replyEvent, payloadErr, sock.channel);
69
- else {
70
- const buf = this.pack([replyEvent, payloadErr]);
71
- if (sock.writable) sock.write(buf);
72
- }
133
+ error: sanitizeErrorMessage(err, "Internal server error", sanitizeErrors ?? this.sanitizeErrors)
134
+ });
73
135
  }
74
136
  return;
75
137
  }
@@ -95,20 +157,67 @@ var Server = class extends axon.Socket {
95
157
  console.log("event-hub server error", err);
96
158
  });
97
159
  }
160
+ _recordAuthFailure(sock, msg) {
161
+ const now = Date.now();
162
+ if (!sock.authWindowStart || now - sock.authWindowStart > this.authWindowMs) {
163
+ sock.authWindowStart = now;
164
+ sock.authFailures = 0;
165
+ }
166
+ sock.authFailures = (sock.authFailures || 0) + 1;
167
+ const resBuf = this.pack([EVENT_AUTH_FAIL, { msg }]);
168
+ if (sock.writable !== false) sock.write(resBuf);
169
+ if (this.maxAuthAttempts > 0 && sock.authFailures >= this.maxAuthAttempts) {
170
+ sock.writable = false;
171
+ if (typeof sock.destroy === "function") sock.destroy();
172
+ else if (typeof sock.end === "function") sock.end();
173
+ }
174
+ }
98
175
  onmessage(sock) {
99
176
  return (buf) => {
100
- const [event, data] = new Message(buf).args;
177
+ let event;
178
+ let data;
179
+ try {
180
+ const msg = new Message(buf);
181
+ [event, data] = msg.args;
182
+ } catch (err) {
183
+ console.error("event-hub message decode error", err);
184
+ return;
185
+ }
101
186
  if (event === EVENT_AUTH) {
187
+ const now = Date.now();
188
+ if (sock.authWindowStart && now - sock.authWindowStart > this.authWindowMs) {
189
+ sock.authWindowStart = now;
190
+ sock.authFailures = 0;
191
+ }
192
+ if (this.maxAuthAttempts > 0 && (sock.authFailures || 0) >= this.maxAuthAttempts) {
193
+ this._recordAuthFailure(sock, "too many auth attempts");
194
+ return;
195
+ }
196
+ if (!data || typeof data !== "object") {
197
+ this._recordAuthFailure(sock, "invalid auth payload");
198
+ return;
199
+ }
102
200
  const { pk, token } = data;
103
- this.jwt.verify(token, pk).then((valid) => {
201
+ Promise.resolve().then(() => {
202
+ if (!token || !pk) throw new Error("token verify failed");
203
+ return this.jwt.verify(token, pk);
204
+ }).then((valid) => {
104
205
  if (!valid) throw new Error("token verify failed");
105
- sock.channel = getDid(this.jwt.decode(token));
206
+ const decoded = this.jwt.decode(token);
207
+ const did = getDid(decoded);
208
+ if (!did) throw new Error("token verify failed");
209
+ if (typeof decoded?.exp === "number" && Number.isFinite(decoded.exp)) {
210
+ const expMs = decoded.exp < 0xe8d4a51000 ? decoded.exp * 1e3 : decoded.exp;
211
+ if (Date.now() >= expMs) throw new Error("token verify failed");
212
+ sock.channelExp = expMs;
213
+ }
214
+ sock.authFailures = 0;
215
+ sock.channel = did;
106
216
  const successBuf = this.pack([EVENT_AUTH_SUCCESS, {}]);
107
- sock.write(successBuf);
217
+ if (sock.writable !== false) sock.write(successBuf);
108
218
  }).catch((err) => {
109
219
  console.error(err);
110
- const resBuf = this.pack([EVENT_AUTH_FAIL, { msg: err.message }]);
111
- sock.write(resBuf);
220
+ this._recordAuthFailure(sock, "token verify failed");
112
221
  });
113
222
  return;
114
223
  }
@@ -123,15 +232,20 @@ var Server = class extends axon.Socket {
123
232
  }
124
233
  /**
125
234
  * 注册路由
235
+ * Note: `authRequired: true` (default) verifies that the caller owns a valid DID keypair.
236
+ * For privileged routes, pass `allowedDids` or `authorize(did, ctx)` to restrict which DIDs may call the route.
126
237
  * @param {string} event
127
- * @param {(payload:any, ctx:{sock:any, channel?:string, event:string, server:Server})=>any|Promise<any>} handler
128
- * @param {{authRequired?: boolean}} [opts] - 默认 true;设为 false 则该事件免鉴权
238
+ * @param {(payload:any, ctx:RouteContext)=>any|Promise<any>} handler
239
+ * @param {RegisterOptions} [opts]
129
240
  */
130
241
  register(event, handler, opts = {}) {
131
242
  const authRequired = opts.authRequired !== false;
132
243
  this.handlers.set(event, {
133
244
  fn: handler,
134
- authRequired
245
+ authRequired,
246
+ allowedDids: toDidSet(opts.allowedDids),
247
+ authorize: opts.authorize,
248
+ sanitizeErrors: opts.sanitizeErrors
135
249
  });
136
250
  return this;
137
251
  }
@@ -139,4 +253,4 @@ var Server = class extends axon.Socket {
139
253
  var server_default = Server;
140
254
 
141
255
  //#endregion
142
- export { server_default as default };
256
+ export { server_default as default, sanitizeErrorMessage };
package/lib/index.cjs CHANGED
@@ -3,11 +3,14 @@ const require_client = require('./client.cjs');
3
3
  const require_single = require('./single.cjs');
4
4
 
5
5
  //#region src/index.ts
6
- const port = Number(process.env.ABT_NODE_EVENT_PORT);
7
- const hostname = process.env.ABT_NODE_EVENT_HOSTNAME || "127.0.0.1";
6
+ const port = Number(process.env.CHAIN_EVENT_PORT || process.env.ABT_NODE_EVENT_PORT);
7
+ const hostname = process.env.CHAIN_EVENT_HOSTNAME || process.env.ABT_NODE_EVENT_HOSTNAME || "127.0.0.1";
8
8
  let did;
9
9
  let sk;
10
- if (process.env.BLOCKLET_APP_SK && process.env.BLOCKLET_APP_ID) {
10
+ if (process.env.CHAIN_SK && process.env.CHAIN_DID) {
11
+ sk = process.env.CHAIN_SK;
12
+ did = process.env.CHAIN_DID;
13
+ } else if (process.env.BLOCKLET_APP_SK && process.env.BLOCKLET_APP_ID) {
11
14
  sk = process.env.BLOCKLET_APP_SK;
12
15
  did = process.env.BLOCKLET_APP_ID;
13
16
  } else if (process.env.ABT_NODE_SK && process.env.ABT_NODE_DID) {
@@ -2,11 +2,25 @@ Object.defineProperty(exports, '__esModule', { value: true });
2
2
  const require_server = require('./server.cjs');
3
3
 
4
4
  //#region src/server-abtnode.ts
5
+ const LOOPBACK_IPV4_RE = /^127\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;
6
+ function isLoopbackHostname(hostname) {
7
+ const normalized = hostname.trim().toLowerCase();
8
+ return normalized === "localhost" || normalized === "::1" || normalized === "[::1]" || LOOPBACK_IPV4_RE.test(normalized);
9
+ }
10
+ function resolveLoopbackHostname(rawHostname = process.env.ABT_NODE_EVENT_HOSTNAME, allowNonLoopback = process.env.EVENT_HUB_ALLOW_NON_LOOPBACK === "1" || process.env.EVENT_HUB_ALLOW_NON_LOOPBACK === "true") {
11
+ const hostname = typeof rawHostname === "string" && rawHostname.trim() ? rawHostname.trim() : "127.0.0.1";
12
+ if (!allowNonLoopback && !isLoopbackHostname(hostname)) throw new Error(`Refusing to bind event-hub server to non-loopback hostname: "${hostname}"`);
13
+ return hostname;
14
+ }
5
15
  const port = Number(process.env.ABT_NODE_EVENT_PORT);
6
- const hostname = Number(process.env.ABT_NODE_EVENT_HOSTNAME) || "127.0.0.1";
7
16
  const server = new require_server.default();
8
- server.bind(port, hostname);
17
+ if (Number.isInteger(port) && port > 0) {
18
+ const hostname = resolveLoopbackHostname(process.env.ABT_NODE_EVENT_HOSTNAME);
19
+ server.bind(port, hostname);
20
+ }
9
21
  var server_abtnode_default = server;
10
22
 
11
23
  //#endregion
12
- exports.default = server_abtnode_default;
24
+ exports.default = server_abtnode_default;
25
+ exports.isLoopbackHostname = isLoopbackHostname;
26
+ exports.resolveLoopbackHostname = resolveLoopbackHostname;
@@ -1,6 +1,8 @@
1
1
  import Server from "./server.cjs";
2
2
 
3
3
  //#region src/server-abtnode.d.ts
4
+ declare function isLoopbackHostname(hostname: string): boolean;
5
+ declare function resolveLoopbackHostname(rawHostname?: string | undefined, allowNonLoopback?: boolean): string;
4
6
  declare const server: Server;
5
7
  //#endregion
6
- export { server as default };
8
+ export { server as default, isLoopbackHostname, resolveLoopbackHostname };
package/lib/server.cjs CHANGED
@@ -9,7 +9,29 @@ let _arcblock_jwt = require("@arcblock/jwt");
9
9
  _arcblock_jwt = require_rolldown_runtime.__toESM(_arcblock_jwt);
10
10
 
11
11
  //#region src/server.ts
12
- const getDid = (jwt) => jwt.iss.replace(/^did:abt:/, "");
12
+ const DEFAULT_MAX_AUTH_ATTEMPTS = 5;
13
+ const DEFAULT_AUTH_WINDOW_MS = 60 * 1e3;
14
+ const normalizeDid = (did) => typeof did === "string" ? did.trim().replace(/^did:[a-z0-9]+:/i, "") : "";
15
+ const getDid = (jwt) => normalizeDid(jwt?.iss);
16
+ const toDidSet = (dids) => {
17
+ if (!dids) return void 0;
18
+ const set = /* @__PURE__ */ new Set();
19
+ for (const d of dids) {
20
+ const normalized = normalizeDid(d);
21
+ if (normalized) set.add(normalized);
22
+ }
23
+ return set;
24
+ };
25
+ const INTERNAL_ERROR_RE = /\b(?:EACCES|EADDRINUSE|ECONNREFUSED|ENOENT|EPERM|ETIMEDOUT|SQLITE_\w+|ER_[A-Z_]+|TypeError|ReferenceError|SyntaxError|RangeError)\b/;
26
+ const FILE_PATH_RE = /(?:\/[\w.-]+){2,}|[A-Za-z]:\\[\w.\\-]+/;
27
+ function sanitizeErrorMessage(err, fallback = "Internal server error", sanitizeAll = false) {
28
+ if (sanitizeAll) return fallback;
29
+ if (err instanceof TypeError || err instanceof ReferenceError || err instanceof SyntaxError || err instanceof RangeError) return fallback;
30
+ if (err && typeof err === "object" && ("syscall" in err || "path" in err || "sql" in err)) return fallback;
31
+ const msg = err?.message || String(err ?? "");
32
+ if (!msg || msg.includes("\n") || INTERNAL_ERROR_RE.test(msg) || FILE_PATH_RE.test(msg)) return fallback;
33
+ return msg;
34
+ }
13
35
  function normalizeReq(input) {
14
36
  if (input && typeof input === "object" && ("payload" in input || "reqId" in input)) {
15
37
  const { reqId, payload } = input;
@@ -34,47 +56,87 @@ var Server = class extends axon.default.Socket {
34
56
  constructor(opts = {}) {
35
57
  super();
36
58
  this.jwt = opts?.jwt || _arcblock_jwt;
59
+ this.maxAuthAttempts = opts.maxAuthAttempts ?? DEFAULT_MAX_AUTH_ATTEMPTS;
60
+ this.authWindowMs = opts.authWindowMs ?? DEFAULT_AUTH_WINDOW_MS;
61
+ this.allowedDids = toDidSet(opts.allowedDids);
62
+ this.authorize = opts.authorize;
63
+ this.sanitizeErrors = opts.sanitizeErrors ?? false;
37
64
  this.handlers = /* @__PURE__ */ new Map();
38
65
  this.on("message", async (event, data, sock) => {
66
+ if (sock.channelExp && Date.now() >= sock.channelExp) {
67
+ sock.channel = void 0;
68
+ sock.channelExp = void 0;
69
+ }
39
70
  const route = this.handlers.get(event);
40
71
  if (route) {
41
- const { fn, authRequired } = route;
72
+ const { fn, authRequired, allowedDids, authorize, sanitizeErrors } = route;
73
+ const { reqId, payload } = normalizeReq(data);
74
+ const replyEvent = `${event}:res`;
75
+ const sendReply = (resObj) => {
76
+ if (sock.channel) this.send(replyEvent, resObj, sock.channel);
77
+ else if (sock.writable) {
78
+ const buf = this.pack([replyEvent, resObj]);
79
+ sock.write(buf);
80
+ }
81
+ };
42
82
  if (authRequired && !sock.channel) {
43
83
  console.error(`unauthenticated socket blocked for event "${event}"`);
84
+ if (reqId) sendReply({
85
+ reqId,
86
+ ok: false,
87
+ error: "unauthorized"
88
+ });
44
89
  return;
45
90
  }
46
- const { reqId, payload } = normalizeReq(data);
47
- try {
48
- const res = normalizeRes(await fn(payload, {
49
- sock,
50
- channel: sock.channel,
51
- event,
52
- server: this
53
- }));
54
- const replyEvent = `${event}:res`;
55
- if (sock.channel) this.send(replyEvent, {
91
+ const ctx = {
92
+ sock,
93
+ channel: sock.channel,
94
+ event,
95
+ server: this
96
+ };
97
+ const callerDid = normalizeDid(sock.channel);
98
+ const effectiveAllowedDids = allowedDids ?? this.allowedDids;
99
+ if (effectiveAllowedDids && (!callerDid || !effectiveAllowedDids.has(callerDid))) {
100
+ console.error(`unauthorized DID "${callerDid}" blocked for event "${event}"`);
101
+ sendReply({
56
102
  reqId,
57
- ...res
58
- }, sock.channel);
59
- else {
60
- const buf = this.pack([replyEvent, {
103
+ ok: false,
104
+ error: "forbidden"
105
+ });
106
+ return;
107
+ }
108
+ const effectiveAuthorize = authorize ?? this.authorize;
109
+ if (effectiveAuthorize) try {
110
+ if (!await effectiveAuthorize(callerDid || void 0, ctx)) {
111
+ console.error(`unauthorized DID "${callerDid}" blocked by authorize predicate for event "${event}"`);
112
+ sendReply({
61
113
  reqId,
62
- ...res
63
- }]);
64
- if (sock.writable) sock.write(buf);
114
+ ok: false,
115
+ error: "forbidden"
116
+ });
117
+ return;
65
118
  }
119
+ } catch (authErr) {
120
+ console.error(authErr);
121
+ sendReply({
122
+ reqId,
123
+ ok: false,
124
+ error: "forbidden"
125
+ });
126
+ return;
127
+ }
128
+ try {
129
+ sendReply({
130
+ reqId,
131
+ ...normalizeRes(await fn(payload, ctx))
132
+ });
66
133
  } catch (err) {
67
- const replyEvent = `${event}:res`;
68
- const payloadErr = {
134
+ console.error(err);
135
+ sendReply({
69
136
  reqId,
70
137
  ok: false,
71
- error: err?.message || String(err)
72
- };
73
- if (sock.channel) this.send(replyEvent, payloadErr, sock.channel);
74
- else {
75
- const buf = this.pack([replyEvent, payloadErr]);
76
- if (sock.writable) sock.write(buf);
77
- }
138
+ error: sanitizeErrorMessage(err, "Internal server error", sanitizeErrors ?? this.sanitizeErrors)
139
+ });
78
140
  }
79
141
  return;
80
142
  }
@@ -100,20 +162,67 @@ var Server = class extends axon.default.Socket {
100
162
  console.log("event-hub server error", err);
101
163
  });
102
164
  }
165
+ _recordAuthFailure(sock, msg) {
166
+ const now = Date.now();
167
+ if (!sock.authWindowStart || now - sock.authWindowStart > this.authWindowMs) {
168
+ sock.authWindowStart = now;
169
+ sock.authFailures = 0;
170
+ }
171
+ sock.authFailures = (sock.authFailures || 0) + 1;
172
+ const resBuf = this.pack([require_constant.EVENT_AUTH_FAIL, { msg }]);
173
+ if (sock.writable !== false) sock.write(resBuf);
174
+ if (this.maxAuthAttempts > 0 && sock.authFailures >= this.maxAuthAttempts) {
175
+ sock.writable = false;
176
+ if (typeof sock.destroy === "function") sock.destroy();
177
+ else if (typeof sock.end === "function") sock.end();
178
+ }
179
+ }
103
180
  onmessage(sock) {
104
181
  return (buf) => {
105
- const [event, data] = new amp_message.default(buf).args;
182
+ let event;
183
+ let data;
184
+ try {
185
+ const msg = new amp_message.default(buf);
186
+ [event, data] = msg.args;
187
+ } catch (err) {
188
+ console.error("event-hub message decode error", err);
189
+ return;
190
+ }
106
191
  if (event === require_constant.EVENT_AUTH) {
192
+ const now = Date.now();
193
+ if (sock.authWindowStart && now - sock.authWindowStart > this.authWindowMs) {
194
+ sock.authWindowStart = now;
195
+ sock.authFailures = 0;
196
+ }
197
+ if (this.maxAuthAttempts > 0 && (sock.authFailures || 0) >= this.maxAuthAttempts) {
198
+ this._recordAuthFailure(sock, "too many auth attempts");
199
+ return;
200
+ }
201
+ if (!data || typeof data !== "object") {
202
+ this._recordAuthFailure(sock, "invalid auth payload");
203
+ return;
204
+ }
107
205
  const { pk, token } = data;
108
- this.jwt.verify(token, pk).then((valid) => {
206
+ Promise.resolve().then(() => {
207
+ if (!token || !pk) throw new Error("token verify failed");
208
+ return this.jwt.verify(token, pk);
209
+ }).then((valid) => {
109
210
  if (!valid) throw new Error("token verify failed");
110
- sock.channel = getDid(this.jwt.decode(token));
211
+ const decoded = this.jwt.decode(token);
212
+ const did = getDid(decoded);
213
+ if (!did) throw new Error("token verify failed");
214
+ if (typeof decoded?.exp === "number" && Number.isFinite(decoded.exp)) {
215
+ const expMs = decoded.exp < 0xe8d4a51000 ? decoded.exp * 1e3 : decoded.exp;
216
+ if (Date.now() >= expMs) throw new Error("token verify failed");
217
+ sock.channelExp = expMs;
218
+ }
219
+ sock.authFailures = 0;
220
+ sock.channel = did;
111
221
  const successBuf = this.pack([require_constant.EVENT_AUTH_SUCCESS, {}]);
112
- sock.write(successBuf);
222
+ if (sock.writable !== false) sock.write(successBuf);
113
223
  }).catch((err) => {
114
224
  console.error(err);
115
- const resBuf = this.pack([require_constant.EVENT_AUTH_FAIL, { msg: err.message }]);
116
- sock.write(resBuf);
225
+ this._recordAuthFailure(sock, "token verify failed");
117
226
  });
118
227
  return;
119
228
  }
@@ -128,15 +237,20 @@ var Server = class extends axon.default.Socket {
128
237
  }
129
238
  /**
130
239
  * 注册路由
240
+ * Note: `authRequired: true` (default) verifies that the caller owns a valid DID keypair.
241
+ * For privileged routes, pass `allowedDids` or `authorize(did, ctx)` to restrict which DIDs may call the route.
131
242
  * @param {string} event
132
- * @param {(payload:any, ctx:{sock:any, channel?:string, event:string, server:Server})=>any|Promise<any>} handler
133
- * @param {{authRequired?: boolean}} [opts] - 默认 true;设为 false 则该事件免鉴权
243
+ * @param {(payload:any, ctx:RouteContext)=>any|Promise<any>} handler
244
+ * @param {RegisterOptions} [opts]
134
245
  */
135
246
  register(event, handler, opts = {}) {
136
247
  const authRequired = opts.authRequired !== false;
137
248
  this.handlers.set(event, {
138
249
  fn: handler,
139
- authRequired
250
+ authRequired,
251
+ allowedDids: toDidSet(opts.allowedDids),
252
+ authorize: opts.authorize,
253
+ sanitizeErrors: opts.sanitizeErrors
140
254
  });
141
255
  return this;
142
256
  }
@@ -144,4 +258,5 @@ var Server = class extends axon.default.Socket {
144
258
  var server_default = Server;
145
259
 
146
260
  //#endregion
147
- exports.default = server_default;
261
+ exports.default = server_default;
262
+ exports.sanitizeErrorMessage = sanitizeErrorMessage;
package/lib/server.d.cts CHANGED
@@ -5,15 +5,47 @@ interface JwtLike {
5
5
  verify(token: string, pk: string): Promise<boolean>;
6
6
  decode(token: string): {
7
7
  iss: string;
8
+ exp?: number;
8
9
  };
9
10
  }
11
+ interface RouteContext {
12
+ sock: SocketWithChannel;
13
+ channel?: string;
14
+ event: string;
15
+ server: Server;
16
+ }
17
+ type AuthorizePredicate = (did: string | undefined, ctx: RouteContext) => boolean | Promise<boolean>;
10
18
  interface ServerOptions {
11
19
  jwt?: JwtLike;
20
+ maxAuthAttempts?: number;
21
+ authWindowMs?: number;
22
+ allowedDids?: Iterable<string>;
23
+ authorize?: AuthorizePredicate;
24
+ sanitizeErrors?: boolean;
25
+ }
26
+ interface RegisterOptions {
27
+ /**
28
+ * Whether the caller socket must have completed EVENT_AUTH (proving DID key ownership).
29
+ * Defaults to true. To restrict *which* authenticated DIDs can call the route, also
30
+ * pass `allowedDids` or `authorize`.
31
+ */
32
+ authRequired?: boolean;
33
+ /** Optional allowlist of DIDs permitted to invoke this route. */
34
+ allowedDids?: Iterable<string>;
35
+ /** Optional custom authorization predicate `(did, ctx) => boolean | Promise<boolean>`. */
36
+ authorize?: AuthorizePredicate;
37
+ /** Always replace thrown handler errors with a generic message. */
38
+ sanitizeErrors?: boolean;
12
39
  }
13
40
  interface SocketWithChannel {
14
41
  channel?: string;
42
+ channelExp?: number;
43
+ authFailures?: number;
44
+ authWindowStart?: number;
15
45
  writable: boolean;
16
46
  write(buf: Buffer): void;
47
+ destroy?: () => void;
48
+ end?: () => void;
17
49
  _peername?: {
18
50
  family: string;
19
51
  address: string;
@@ -21,35 +53,35 @@ interface SocketWithChannel {
21
53
  };
22
54
  }
23
55
  interface RouteHandler {
24
- fn: (payload: unknown, ctx: {
25
- sock: SocketWithChannel;
26
- channel?: string;
27
- event: string;
28
- server: Server;
29
- }) => unknown | Promise<unknown>;
56
+ fn: (payload: unknown, ctx: RouteContext) => unknown | Promise<unknown>;
30
57
  authRequired: boolean;
58
+ allowedDids?: Set<string>;
59
+ authorize?: AuthorizePredicate;
60
+ sanitizeErrors?: boolean;
31
61
  }
62
+ declare function sanitizeErrorMessage(err: unknown, fallback?: string, sanitizeAll?: boolean): string;
32
63
  declare class Server extends axon.Socket {
33
64
  jwt: JwtLike;
34
65
  handlers: Map<string, RouteHandler>;
66
+ maxAuthAttempts: number;
67
+ authWindowMs: number;
68
+ allowedDids?: Set<string>;
69
+ authorize?: AuthorizePredicate;
70
+ sanitizeErrors: boolean;
35
71
  socks: SocketWithChannel[];
36
72
  constructor(opts?: ServerOptions);
73
+ _recordAuthFailure(sock: SocketWithChannel, msg: string): void;
37
74
  onmessage(sock: SocketWithChannel): (buf: Buffer) => void;
38
75
  send(event: string, data: unknown, channel: string): this;
39
76
  /**
40
77
  * 注册路由
78
+ * Note: `authRequired: true` (default) verifies that the caller owns a valid DID keypair.
79
+ * For privileged routes, pass `allowedDids` or `authorize(did, ctx)` to restrict which DIDs may call the route.
41
80
  * @param {string} event
42
- * @param {(payload:any, ctx:{sock:any, channel?:string, event:string, server:Server})=>any|Promise<any>} handler
43
- * @param {{authRequired?: boolean}} [opts] - 默认 true;设为 false 则该事件免鉴权
81
+ * @param {(payload:any, ctx:RouteContext)=>any|Promise<any>} handler
82
+ * @param {RegisterOptions} [opts]
44
83
  */
45
- register(event: string, handler: (payload: unknown, ctx: {
46
- sock: SocketWithChannel;
47
- channel?: string;
48
- event: string;
49
- server: Server;
50
- }) => unknown | Promise<unknown>, opts?: {
51
- authRequired?: boolean;
52
- }): this;
84
+ register(event: string, handler: (payload: unknown, ctx: RouteContext) => unknown | Promise<unknown>, opts?: RegisterOptions): this;
53
85
  }
54
86
  //#endregion
55
- export { Server as default };
87
+ export { AuthorizePredicate, RegisterOptions, RouteContext, ServerOptions, Server as default, sanitizeErrorMessage };
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "1.30.24",
6
+ "version": "1.30.25",
7
7
  "description": "A nodejs module for local and remote Inter Process Event",
8
8
  "type": "module",
9
9
  "main": "./lib/index.cjs",
@@ -51,9 +51,9 @@
51
51
  ],
52
52
  "license": "MIT",
53
53
  "dependencies": {
54
- "@arcblock/did": "1.30.24",
55
- "@arcblock/jwt": "1.30.24",
56
- "@ocap/wallet": "1.30.24",
54
+ "@arcblock/did": "1.30.25",
55
+ "@arcblock/jwt": "1.30.25",
56
+ "@ocap/wallet": "1.30.25",
57
57
  "amp-message": "~0.1.2",
58
58
  "axon": "^2.0.3"
59
59
  },