@open-wa/api 5.6.7 → 5.9.7

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.cjs CHANGED
@@ -3,13 +3,13 @@ let hono = require("hono");
3
3
  let hono_cors = require("hono/cors");
4
4
  let hono_logger = require("hono/logger");
5
5
  let _hono_node_server = require("@hono/node-server");
6
+ let _hono_node_server_conninfo = require("@hono/node-server/conninfo");
6
7
  let node_http = require("node:http");
7
8
  let ws = require("ws");
8
9
  let _open_wa_schema = require("@open-wa/schema");
9
10
  let _open_wa_screencaster_server = require("@open-wa/screencaster/server");
10
11
  require("@open-wa/schema/methods");
11
12
  let _open_wa_mcp = require("@open-wa/mcp");
12
- let _hono_node_server_conninfo = require("@hono/node-server/conninfo");
13
13
  let _elastic_elasticsearch = require("@elastic/elasticsearch");
14
14
  let path = require("path");
15
15
  let fs = require("fs");
@@ -52,13 +52,13 @@ function apiKeyMiddleware(apiKey) {
52
52
  }
53
53
  //#endregion
54
54
  //#region src/middleware/rate-limit.ts
55
- const requests = /* @__PURE__ */ new Map();
56
55
  function getRequestKey(c) {
57
56
  const forwarded = c.req.header("x-forwarded-for");
58
57
  if (forwarded) return forwarded.split(",")[0].trim();
59
58
  return c.req.header("x-real-ip") || "unknown";
60
59
  }
61
60
  function rateLimitMiddleware(maxRequests = 100, windowMs = 6e4) {
61
+ const requests = /* @__PURE__ */ new Map();
62
62
  return async (c, next) => {
63
63
  const requestKey = getRequestKey(c);
64
64
  const now = Date.now();
@@ -104,6 +104,21 @@ function readQueryParams(c) {
104
104
  const url = new URL(c.req.url);
105
105
  return Object.fromEntries(url.searchParams.entries());
106
106
  }
107
+ async function decodeQueryParams(definition, query) {
108
+ const values = (0, _open_wa_mcp.normalizeMethodPayload)(definition, query);
109
+ if (!(definition.inputSchema instanceof _open_wa_schema.z.ZodObject)) return values;
110
+ for (const [key, field] of Object.entries(definition.inputSchema.shape)) {
111
+ const value = values[key];
112
+ if (typeof value !== "string") continue;
113
+ const schema = field;
114
+ if ((await schema.safeParseAsync(value)).success) continue;
115
+ try {
116
+ const decoded = JSON.parse(value);
117
+ if ((await schema.safeParseAsync(decoded)).success) values[key] = decoded;
118
+ } catch {}
119
+ }
120
+ return values;
121
+ }
107
122
  function toLocalPath(path, basePath) {
108
123
  const normalizedBase = basePath === "/" ? "" : basePath.replace(/\/+$/, "");
109
124
  if (!normalizedBase) return path || "/";
@@ -137,8 +152,9 @@ function createApiMiddleware(clientSource, options) {
137
152
  const sessionCheck = assertSessionPath(options.config.sessionId, routeSessionId, useSessionIdInPath);
138
153
  if (!sessionCheck.ok) return c.json({ error: sessionCheck.error }, sessionCheck.status);
139
154
  const query = readQueryParams(c);
155
+ const body = c.req.method === "GET" || c.req.method === "DELETE" ? {} : await readRequestBody(c);
140
156
  const payload = {
141
- ...c.req.method === "GET" || c.req.method === "DELETE" ? {} : await readRequestBody(c),
157
+ ...body,
142
158
  ...query
143
159
  };
144
160
  const methodName = routeMethod || routeDefinition?.functionName || (typeof payload.method === "string" ? payload.method : void 0);
@@ -148,7 +164,10 @@ function createApiMiddleware(clientSource, options) {
148
164
  const result = await (0, _open_wa_mcp.executeCapability)({
149
165
  client: resolveClient(clientSource),
150
166
  definition,
151
- payload,
167
+ payload: {
168
+ ...body,
169
+ ...await decodeQueryParams(definition, query)
170
+ },
152
171
  elasticEmitter: options.elasticEmitter,
153
172
  sessionId: options.config.sessionId
154
173
  });
@@ -198,7 +217,7 @@ function createApiMiddleware(clientSource, options) {
198
217
  //#endregion
199
218
  //#region src/version.ts
200
219
  /** Version of the API package running the Easy API server. */
201
- const API_VERSION = "5.6.7";
220
+ const API_VERSION = "5.9.7";
202
221
  //#endregion
203
222
  //#region src/docs/openapi.ts
204
223
  function schemaToOpenApi(schema) {
@@ -829,7 +848,8 @@ function registerDebugRoutes(app, options) {
829
848
  "sessionData",
830
849
  "sessionDataBucketAuth",
831
850
  "sessionDataEncryptionKey",
832
- "sessionDataEncryptionKeyFile"
851
+ "sessionDataEncryptionKeyFile",
852
+ "pluginConfig"
833
853
  ]) if (redacted[key]) redacted[key] = "***REDACTED***";
834
854
  if (redacted.proxyServerCredentials) redacted.proxyServerCredentials = {
835
855
  ...redacted.proxyServerCredentials,
@@ -5754,6 +5774,7 @@ const requestSchema = object({
5754
5774
  microphone: boolean(),
5755
5775
  speaker: boolean(),
5756
5776
  replacesId: string().optional(),
5777
+ takeover: boolean().optional(),
5757
5778
  onMediaFailure: _enum(["end", "keep-open"]).optional()
5758
5779
  });
5759
5780
  function registerCallingRoutes(app, options) {
@@ -6504,6 +6525,7 @@ var ApiServer = class {
6504
6525
  constructor(options) {
6505
6526
  this.latestQR = null;
6506
6527
  this.isDashboardActive = false;
6528
+ this.pluginApp = new hono.Hono();
6507
6529
  this.healthStore = new HealthStore();
6508
6530
  this.diagnosticStore = new DiagnosticStore();
6509
6531
  this.config = options.config;
@@ -6578,7 +6600,26 @@ var ApiServer = class {
6578
6600
  */
6579
6601
  mountPlugins(pluginHost) {
6580
6602
  this.pluginHost = pluginHost;
6581
- for (const { name, router } of pluginHost.getRoutes()) this.app.route(`/plugins/${name}`, router);
6603
+ const pluginApp = new hono.Hono();
6604
+ for (const { name, router, routeAuth } of pluginHost.getRoutes()) {
6605
+ if (routeAuth === "host") pluginApp.use(`/plugins/${name}/*`, async (c, next) => {
6606
+ if (this.config.apiKey) {
6607
+ if (c.req.header("X-API-Key") !== this.config.apiKey) return c.json({ error: "Invalid or missing API key." }, 401);
6608
+ } else {
6609
+ const address = (0, _hono_node_server_conninfo.getConnInfo)(c).remote.address;
6610
+ if (![
6611
+ "127.0.0.1",
6612
+ "::1",
6613
+ "::ffff:127.0.0.1"
6614
+ ].includes(address ?? "")) return c.json({ error: "Configure an Easy API key for remote plugin access." }, 401);
6615
+ const origin = c.req.header("Origin");
6616
+ if (origin && origin !== new URL(c.req.url).origin) return c.json({ error: "Cross-origin plugin access requires an API key." }, 403);
6617
+ }
6618
+ await next();
6619
+ });
6620
+ pluginApp.route(`/plugins/${name}`, router);
6621
+ }
6622
+ this.pluginApp = pluginApp;
6582
6623
  }
6583
6624
  async start() {
6584
6625
  let viteDevServer = null;
@@ -6670,6 +6711,7 @@ var ApiServer = class {
6670
6711
  methodDefinitions
6671
6712
  });
6672
6713
  this.app.get("/plugins/manifest", (c) => c.json(this.pluginHost?.getManifest() ?? { plugins: [] }));
6714
+ this.app.all("/plugins/*", (c) => this.pluginApp.fetch(c.req.raw, c.env));
6673
6715
  this.app.get("/health", (c) => {
6674
6716
  const healthSnapshot = this.healthStore.getSnapshot();
6675
6717
  return c.json({
package/dist/index.d.cts CHANGED
@@ -102,6 +102,7 @@ export declare class ApiServer {
102
102
  private dashboardDevServer?;
103
103
  private isDashboardActive;
104
104
  private pluginHost?;
105
+ private pluginApp;
105
106
  private healthStore;
106
107
  private diagnosticStore;
107
108
  private eventBroadcaster;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","names":[],"sources":["../src/events/EventBridge.ts","../src/events/EventBroadcaster.ts","../src/monitoring/elastic.ts","../src/types.ts","../src/createApiServer.ts","../src/createApiMiddleware.ts","../src/auth/api-key.ts","../src/middleware/rate-limit.ts"],"mappings":";;;;;;;UAAiB;EACf,MAAM,WAAW,eAAe;EAChC,OAAO,WAAW,eAAe;;;;UCFlB;EACf;EACA;EACA;EACA;EACA;;UASe;EACf;EACA,SAAS;EACT;;qBAiBW;mBACM;mBACA;UACT;UACA;UACA;EAER,YAAY;EAIL;EAIA,UAAU,eAAe,mBAAmB;EAsB5C,aAAa,UAAS,qBAA0B,eAAe;EAyD/D;;;;UC9HQ;EACf;EACA;EACA;EACA;EACA;EACA;;UAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;GACC;;qBAGU;UACH;UACA;UACA;UACA;EAER,YAAY,QAAQ;EAsBP,SAAS;EAOf,IAAI,UAAU,KAAK;EAYb,SAAS;EAmBT,QAAQ;;;;KC1FX,kBAAkB,mBAAmB,gBAAgB;KACrD,eAAe,qCAAqC;UAE/C;EACf,QAAQ;EACR;EACA;EACA,oBAAoB;EACpB,iBAAiB;EACjB;;UASe;EACf,QAAQ;EACR;;;;qBCwBW;UACH;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;EAWR,YAAY,SAAS;EAoCd,UAAU,QAAQ;EAIlB,eAAe,QAAQ;EAkBvB,qBACL;IAGU;IACA;IACA;IACA;IACA;IACA;;EAYC,QAAQ,MAAM,kBAAkB;EAWhC,aAAa;EAInB,MAAM;EAIN,UAAM,0BAAA,+BAAA;EAIN,uBAAmB;EAQnB,aAAa,YAAY;EASnB,SAAK;EAkDL,QAAI;EAuBV;UAIC;UAeA;UAwCA;;wBAsKM,gBAAgB,QAAQ,SAAM;;;wBC7a9B,oBAAoB,cAAc,cAAc,SAAS,uBAAoB,0BAAA,+BAAA;;;wBC9D7E,iBAAiB,kBAAc,GAC5B,SAAO,MAAQ,SAAI,gBAAA,0BAAA;;;;;;wBCUtB,oBAAoB,sBAAmB,qBAAgB,GACpD,SAAO,MAAQ,SAAI,gBAAA,0BAAA"}
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../src/events/EventBridge.ts","../src/events/EventBroadcaster.ts","../src/monitoring/elastic.ts","../src/types.ts","../src/createApiServer.ts","../src/createApiMiddleware.ts","../src/auth/api-key.ts","../src/middleware/rate-limit.ts"],"mappings":";;;;;;;UAAiB;EACf,MAAM,WAAW,eAAe;EAChC,OAAO,WAAW,eAAe;;;;UCFlB;EACf;EACA;EACA;EACA;EACA;;UASe;EACf;EACA,SAAS;EACT;;qBAiBW;mBACM;mBACA;UACT;UACA;UACA;EAER,YAAY;EAIL;EAIA,UAAU,eAAe,mBAAmB;EAsB5C,aAAa,UAAS,qBAA0B,eAAe;EAyD/D;;;;UC9HQ;EACf;EACA;EACA;EACA;EACA;EACA;;UAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;GACC;;qBAGU;UACH;UACA;UACA;UACA;EAER,YAAY,QAAQ;EAsBP,SAAS;EAOf,IAAI,UAAU,KAAK;EAYb,SAAS;EAmBT,QAAQ;;;;KC1FX,kBAAkB,mBAAmB,gBAAgB;KACrD,eAAe,qCAAqC;UAE/C;EACf,QAAQ;EACR;EACA;EACA,oBAAoB;EACpB,iBAAiB;EACjB;;UASe;EACf,QAAQ;EACR;;;;qBCyBW;UACH;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;EAWR,YAAY,SAAS;EAoCd,UAAU,QAAQ;EAIlB,eAAe,QAAQ;EAkBvB,qBACL;IAGU;IACA;IACA;IACA;IACA;IACA;;EAYC,QAAQ,MAAM,kBAAkB;EAWhC,aAAa;EAInB,MAAM;EAIN,UAAM,0BAAA,+BAAA;EAIN,uBAAmB;EAQnB,aAAa,YAAY;EA0BnB,SAAK;EAkDL,QAAI;EAuBV;UAIC;UAeA;UAwCA;;wBAyKM,gBAAgB,QAAQ,SAAM;;;wBClb9B,oBAAoB,cAAc,cAAc,SAAS,uBAAoB,0BAAA,+BAAA;;;wBC/E7E,iBAAiB,kBAAc,GAC5B,SAAO,MAAQ,SAAI,gBAAA,0BAAA;;;;;;wBCQtB,oBAAoB,sBAAmB,qBAAgB,GAEpD,SAAO,MAAQ,SAAI,gBAAA,0BAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-wa/api",
3
- "version": "5.6.7",
3
+ "version": "5.9.7",
4
4
  "description": "Reusable Easy API transport and runtime explorer layer for open-wa",
5
5
  "main": "./dist/index.cjs",
6
6
  "types": "./dist/index.d.cts",
@@ -19,9 +19,9 @@
19
19
  "dependencies": {
20
20
  "@elastic/elasticsearch": "^9.5.1",
21
21
  "@hono/node-server": "^2.1.1",
22
- "@open-wa/mcp": "5.6.7",
23
- "@open-wa/schema": "5.6.7",
24
- "@open-wa/screencaster": "5.6.7",
22
+ "@open-wa/mcp": "5.9.7",
23
+ "@open-wa/schema": "5.9.7",
24
+ "@open-wa/screencaster": "5.9.7",
25
25
  "hono": "^4.13.9",
26
26
  "tree-kill": "^1.2.2",
27
27
  "ws": "^8.22.0"
@@ -1,5 +1,5 @@
1
1
  import { Hono } from 'hono';
2
- import { getHttpMethodDefinitions, type HttpMethodDefinition } from '@open-wa/schema';
2
+ import { getHttpMethodDefinitions, z, type HttpMethodDefinition } from '@open-wa/schema';
3
3
  import '@open-wa/schema/methods';
4
4
  import { apiKeyMiddleware } from './auth/api-key';
5
5
  import { rateLimitMiddleware } from './middleware/rate-limit';
@@ -26,6 +26,23 @@ function readQueryParams(c: any): Record<string, unknown> {
26
26
  return Object.fromEntries(url.searchParams.entries());
27
27
  }
28
28
 
29
+ async function decodeQueryParams(definition: HttpMethodDefinition, query: Record<string, unknown>) {
30
+ const values = normalizeMethodPayload(definition, query);
31
+ if (!(definition.inputSchema instanceof z.ZodObject)) return values;
32
+ for (const [key, field] of Object.entries(definition.inputSchema.shape)) {
33
+ const value = values[key];
34
+ if (typeof value !== 'string') continue;
35
+ const schema = field as z.ZodType;
36
+ // Preserve strings, including identifiers and text such as "false".
37
+ if ((await schema.safeParseAsync(value)).success) continue;
38
+ try {
39
+ const decoded = JSON.parse(value);
40
+ if ((await schema.safeParseAsync(decoded)).success) values[key] = decoded;
41
+ } catch { /* Leave invalid text for the normal input validation response. */ }
42
+ }
43
+ return values;
44
+ }
45
+
29
46
  function toLocalPath(path: string, basePath: string): string {
30
47
  const normalizedBase = basePath === '/' ? '' : basePath.replace(/\/+$/, '');
31
48
  if (!normalizedBase) {
@@ -111,7 +128,7 @@ export function createApiMiddleware(clientSource: ClientSource, options: ApiMidd
111
128
  const result = await executeCapability({
112
129
  client: resolveClient(clientSource),
113
130
  definition,
114
- payload,
131
+ payload: { ...body, ...await decodeQueryParams(definition, query) },
115
132
  elasticEmitter: options.elasticEmitter,
116
133
  sessionId: options.config.sessionId,
117
134
  });
@@ -2,6 +2,7 @@ import { Hono } from 'hono';
2
2
  import { cors } from 'hono/cors';
3
3
  import { logger } from 'hono/logger';
4
4
  import { createAdaptorServer, upgradeWebSocket } from '@hono/node-server';
5
+ import { getConnInfo } from '@hono/node-server/conninfo';
5
6
  import { createServer, type Server } from 'node:http';
6
7
  import { WebSocketServer } from 'ws';
7
8
  import { getHttpMethodDefinitions, type Config } from '@open-wa/schema';
@@ -58,6 +59,7 @@ export class ApiServer {
58
59
  private dashboardDevServer?: { close(): Promise<void> };
59
60
  private isDashboardActive: boolean = false;
60
61
  private pluginHost?: PluginHost;
62
+ private pluginApp = new Hono();
61
63
  private healthStore: HealthStore = new HealthStore();
62
64
  private diagnosticStore: DiagnosticStore = new DiagnosticStore();
63
65
  private eventBroadcaster: EventBroadcaster;
@@ -187,11 +189,28 @@ export class ApiServer {
187
189
  */
188
190
  public mountPlugins(pluginHost: PluginHost): void {
189
191
  this.pluginHost = pluginHost;
192
+ const pluginApp = new Hono();
190
193
 
191
194
  // Mount each plugin's routes at /plugins/<name>/
192
- for (const { name, router } of pluginHost.getRoutes()) {
193
- this.app.route(`/plugins/${name}`, router);
195
+ for (const { name, router, routeAuth } of pluginHost.getRoutes()) {
196
+ if (routeAuth === 'host') {
197
+ pluginApp.use(`/plugins/${name}/*`, async (c, next) => {
198
+ if (this.config.apiKey) {
199
+ if (c.req.header('X-API-Key') !== this.config.apiKey) return c.json({ error: 'Invalid or missing API key.' }, 401);
200
+ } else {
201
+ const address = getConnInfo(c).remote.address;
202
+ if (!['127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(address ?? '')) {
203
+ return c.json({ error: 'Configure an Easy API key for remote plugin access.' }, 401);
204
+ }
205
+ const origin = c.req.header('Origin');
206
+ if (origin && origin !== new URL(c.req.url).origin) return c.json({ error: 'Cross-origin plugin access requires an API key.' }, 403);
207
+ }
208
+ await next();
209
+ });
210
+ }
211
+ pluginApp.route(`/plugins/${name}`, router);
194
212
  }
213
+ this.pluginApp = pluginApp;
195
214
  }
196
215
 
197
216
  public async start() {
@@ -337,6 +356,9 @@ export class ApiServer {
337
356
  this.app.get('/plugins/manifest', (c) =>
338
357
  c.json(this.pluginHost?.getManifest() ?? { plugins: [] }),
339
358
  );
359
+ // The host router can already be serving health/dashboard requests while
360
+ // plugins initialize. Swap the delegate instead of mutating its matcher.
361
+ this.app.all('/plugins/*', (c) => this.pluginApp.fetch(c.req.raw, c.env));
340
362
 
341
363
  this.app.get('/health', (c) => {
342
364
  const healthSnapshot = this.healthStore.getSnapshot();
@@ -1,7 +1,5 @@
1
1
  import type { Context, Next } from 'hono';
2
2
 
3
- const requests = new Map<string, number[]>();
4
-
5
3
  function getRequestKey(c: Context): string {
6
4
  const forwarded = c.req.header('x-forwarded-for');
7
5
 
@@ -13,6 +11,7 @@ function getRequestKey(c: Context): string {
13
11
  }
14
12
 
15
13
  export function rateLimitMiddleware(maxRequests = 100, windowMs = 60000) {
14
+ const requests = new Map<string, number[]>();
16
15
  return async (c: Context, next: Next) => {
17
16
  const requestKey = getRequestKey(c);
18
17
  const now = Date.now();
@@ -10,6 +10,7 @@ const requestSchema = z.object({
10
10
  call: z.object({ id: z.string(), sessionId: z.string(), generation: z.string() }).optional(),
11
11
  to: z.string().optional(), mode: z.enum(['accept', 'start', 'replace', 'observe']), microphone: z.boolean(), speaker: z.boolean(),
12
12
  replacesId: z.string().optional(),
13
+ takeover: z.boolean().optional(),
13
14
  onMediaFailure: z.enum(['end', 'keep-open']).optional(),
14
15
  });
15
16
 
@@ -48,7 +48,7 @@ export function registerDebugRoutes(
48
48
  // Redact sensitive fields
49
49
  const redacted = { ...config } as Record<string, unknown>;
50
50
  const sensitiveKeys = ['apiKey', 'licenseKey', 'elasticPassword', 'elasticUsername', 'sessionData', 'sessionDataBucketAuth',
51
- 'sessionDataEncryptionKey', 'sessionDataEncryptionKeyFile'];
51
+ 'sessionDataEncryptionKey', 'sessionDataEncryptionKeyFile', 'pluginConfig'];
52
52
  for (const key of sensitiveKeys) {
53
53
  if (redacted[key]) {
54
54
  redacted[key] = '***REDACTED***';