@open-wa/api 5.4.0 → 5.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dashboard-neo/dist/assets/{AgentScalarDrawer.vue-Cly13x9l.js → AgentScalarDrawer.vue-COZ7xmHy.js} +4 -4
- package/dashboard-neo/dist/assets/{browser-J5x-7eFP.js → browser-Dw3rJib4.js} +4 -4
- package/dashboard-neo/dist/assets/hls-D9b4QHpD.js +42 -0
- package/dashboard-neo/dist/assets/{index-CP58_PDI.css → index-DvjbsVtZ.css} +1 -1
- package/dashboard-neo/dist/assets/index-ehunMaG7.js +2185 -0
- package/dashboard-neo/dist/assets/modal-BVMhooSt.js +5 -0
- package/dashboard-neo/dist/assets/{parse-html-description-DHRmA6ou.js → parse-html-description-XSND5qRr.js} +1 -1
- package/dashboard-neo/dist/assets/request-example-ChGpFMrb.js +16 -0
- package/dashboard-neo/dist/assets/workspace-events-tr7bC8Vy.js +100 -0
- package/dashboard-neo/dist/calling/greeting.wav +0 -0
- package/dashboard-neo/dist/index.html +4 -4
- package/dist/index.cjs +5088 -27
- package/dist/index.d.cts +3 -1
- package/dist/index.d.cts.map +1 -1
- package/package.json +4 -4
- package/src/createApiMiddleware.ts +1 -0
- package/src/createApiServer.ts +22 -2
- package/src/dashboard/middleware.ts +2 -1
- package/src/events/EventBroadcaster.ts +6 -0
- package/src/health/HealthStore.ts +43 -18
- package/src/routes/calls.ts +94 -0
- package/src/routes/session-refresh.ts +32 -0
- package/dashboard-neo/dist/assets/index-Dl0sJuu6.js +0 -2162
- package/dashboard-neo/dist/assets/modal-BTlJ4pQT.js +0 -5
- package/dashboard-neo/dist/assets/preload-helper-CJLUz7BA.js +0 -16
- package/dashboard-neo/dist/assets/workspace-events-eIuzLwDq.js +0 -100
package/dist/index.d.cts
CHANGED
|
@@ -30,6 +30,7 @@ export declare class EventBroadcaster {
|
|
|
30
30
|
private nextSubscriberId;
|
|
31
31
|
private subscribers;
|
|
32
32
|
constructor(sessionId?: string);
|
|
33
|
+
close(): void;
|
|
33
34
|
broadcast(event: string, payload: unknown): SseEventEnvelope;
|
|
34
35
|
createStream(options?: EventStreamOptions): ReadableStream<Uint8Array>;
|
|
35
36
|
getSubscriberCount(): number;
|
|
@@ -97,6 +98,7 @@ export declare class ApiServer {
|
|
|
97
98
|
private latestQR;
|
|
98
99
|
private screencastManager;
|
|
99
100
|
private server?;
|
|
101
|
+
private dashboardDevServer?;
|
|
100
102
|
private isDashboardActive;
|
|
101
103
|
private pluginHost?;
|
|
102
104
|
private healthStore;
|
|
@@ -118,7 +120,7 @@ export declare class ApiServer {
|
|
|
118
120
|
} | undefined) | undefined): void;
|
|
119
121
|
setPage(page: IScreencastPage): Promise<void>;
|
|
120
122
|
clearPage(): Promise<void>;
|
|
121
|
-
setQR(qr: string): void;
|
|
123
|
+
setQR(qr: string | null): void;
|
|
122
124
|
getApp(): Hono<import("hono/types").BlankEnv, import("hono/types").BlankSchema, "/">;
|
|
123
125
|
getEventBroadcaster(): EventBroadcaster;
|
|
124
126
|
mountPlugins(pluginHost: PluginHost): void;
|
package/dist/index.d.cts.map
CHANGED
|
@@ -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;;
|
|
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;;;;qBCyBG;UACH;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;EAWR,YAAY,SAAS;EAoCd,UAAU,QAAQ;EAIlB,eAAe,QAAQ;EAiBvB,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;EAoBV;UAIC;UAeA;UAwCA;;wBAsKM,gBAAgB,QAAQ,SAAM;;;wBCxa9B,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"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-wa/api",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.5.0",
|
|
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.
|
|
23
|
-
"@open-wa/schema": "5.
|
|
24
|
-
"@open-wa/screencaster": "5.
|
|
22
|
+
"@open-wa/mcp": "5.5.0",
|
|
23
|
+
"@open-wa/schema": "5.5.0",
|
|
24
|
+
"@open-wa/screencaster": "5.5.0",
|
|
25
25
|
"hono": "^4.13.9",
|
|
26
26
|
"tree-kill": "^1.2.2",
|
|
27
27
|
"ws": "^8.22.0"
|
|
@@ -119,6 +119,7 @@ export function createApiMiddleware(clientSource: ClientSource, options: ApiMidd
|
|
|
119
119
|
if (result.success) {
|
|
120
120
|
return c.json({ success: true, data: result.data });
|
|
121
121
|
}
|
|
122
|
+
if (result.status === 503) c.header('Retry-After', '2');
|
|
122
123
|
|
|
123
124
|
return c.json(
|
|
124
125
|
{
|
package/src/createApiServer.ts
CHANGED
|
@@ -14,6 +14,8 @@ import { createApiMiddleware } from './createApiMiddleware';
|
|
|
14
14
|
import { createHonoMcpAdapter } from '@open-wa/mcp';
|
|
15
15
|
import { registerMetaRoutes } from './routes/meta';
|
|
16
16
|
import { registerDebugRoutes } from './routes/debug';
|
|
17
|
+
import { registerCallingRoutes } from './routes/calls';
|
|
18
|
+
import { registerSessionRefreshRoutes } from './routes/session-refresh';
|
|
17
19
|
import { registerAgentDiscoveryRoutes } from './routes/agent-discovery';
|
|
18
20
|
import { type EventBridge } from './events/EventBridge';
|
|
19
21
|
import { HealthStore } from './health/HealthStore';
|
|
@@ -53,6 +55,7 @@ export class ApiServer {
|
|
|
53
55
|
private latestQR: string | null = null;
|
|
54
56
|
private screencastManager: ScreencastManager;
|
|
55
57
|
private server?: Server;
|
|
58
|
+
private dashboardDevServer?: { close(): Promise<void> };
|
|
56
59
|
private isDashboardActive: boolean = false;
|
|
57
60
|
private pluginHost?: PluginHost;
|
|
58
61
|
private healthStore: HealthStore = new HealthStore();
|
|
@@ -97,6 +100,7 @@ export class ApiServer {
|
|
|
97
100
|
}
|
|
98
101
|
|
|
99
102
|
this.setupMiddleware();
|
|
103
|
+
registerCallingRoutes(this.app, { config: this.config, upgrade: upgradeWebSocket, getService: () => this.client?.getCallingService?.() });
|
|
100
104
|
this.registerRoutes();
|
|
101
105
|
|
|
102
106
|
// Register screencast WebSocket route
|
|
@@ -149,6 +153,10 @@ export class ApiServer {
|
|
|
149
153
|
* Call this once the browser page is ready.
|
|
150
154
|
*/
|
|
151
155
|
public async setPage(page: IScreencastPage): Promise<void> {
|
|
156
|
+
if (this.config.useLightpanda) {
|
|
157
|
+
await this.screencastManager.clearPage();
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
152
160
|
await this.screencastManager.setPage(page);
|
|
153
161
|
}
|
|
154
162
|
|
|
@@ -159,7 +167,7 @@ export class ApiServer {
|
|
|
159
167
|
await this.screencastManager.clearPage();
|
|
160
168
|
}
|
|
161
169
|
|
|
162
|
-
public setQR(qr: string) {
|
|
170
|
+
public setQR(qr: string | null) {
|
|
163
171
|
this.latestQR = qr;
|
|
164
172
|
}
|
|
165
173
|
|
|
@@ -188,6 +196,7 @@ export class ApiServer {
|
|
|
188
196
|
let viteDevServer: any = null;
|
|
189
197
|
if (this.config.dashboard) {
|
|
190
198
|
viteDevServer = await setupViteDevServer();
|
|
199
|
+
this.dashboardDevServer = viteDevServer ?? undefined;
|
|
191
200
|
if (!viteDevServer) {
|
|
192
201
|
this.isDashboardActive = await mountDashboardProduction(this.app);
|
|
193
202
|
} else {
|
|
@@ -234,14 +243,20 @@ export class ApiServer {
|
|
|
234
243
|
}
|
|
235
244
|
|
|
236
245
|
public async stop() {
|
|
246
|
+
await this.dashboardDevServer?.close();
|
|
247
|
+
this.dashboardDevServer = undefined;
|
|
237
248
|
const server = this.server;
|
|
238
249
|
this.server = undefined;
|
|
250
|
+
await this.screencastManager.destroy();
|
|
251
|
+
this.eventBroadcaster.close();
|
|
239
252
|
if (server?.listening) {
|
|
240
253
|
await new Promise<void>((resolve, reject) => {
|
|
241
254
|
server.close((error) => (error ? reject(error) : resolve()));
|
|
255
|
+
// Dashboard SSE responses remain open by design. Once admission has
|
|
256
|
+
// stopped, close them so shutdown can release the listening socket.
|
|
257
|
+
server.closeAllConnections();
|
|
242
258
|
});
|
|
243
259
|
}
|
|
244
|
-
await this.screencastManager.destroy();
|
|
245
260
|
if (this.elasticEmitter) {
|
|
246
261
|
await this.elasticEmitter.stop();
|
|
247
262
|
}
|
|
@@ -307,6 +322,7 @@ export class ApiServer {
|
|
|
307
322
|
}
|
|
308
323
|
|
|
309
324
|
private registerRoutes() {
|
|
325
|
+
registerSessionRefreshRoutes(this.app, this.config, () => this.client);
|
|
310
326
|
const methodDefinitions = getHttpMethodDefinitions();
|
|
311
327
|
registerAgentDiscoveryRoutes(this.app, {
|
|
312
328
|
config: this.config,
|
|
@@ -337,6 +353,10 @@ export class ApiServer {
|
|
|
337
353
|
},
|
|
338
354
|
},
|
|
339
355
|
capabilities: {
|
|
356
|
+
livePortalAvailable: !this.config.useLightpanda,
|
|
357
|
+
livePortalUnavailableReason: this.config.useLightpanda
|
|
358
|
+
? 'Lightpanda does not render a visual feed. Use Chrome or Chromium for Live Portal.'
|
|
359
|
+
: undefined,
|
|
340
360
|
apiKeyConfigured: Boolean(this.config.apiKey),
|
|
341
361
|
mcpEnabled: Boolean(this.config.mcp?.enabled),
|
|
342
362
|
mcpAvailable: Boolean(this.config.apiKey && this.config.mcp?.enabled),
|
|
@@ -44,7 +44,8 @@ export async function setupViteDevServer(): Promise<any | null> {
|
|
|
44
44
|
const vite = await import('vite');
|
|
45
45
|
const viteServer = await vite.createServer({
|
|
46
46
|
root: dashboardDir,
|
|
47
|
-
|
|
47
|
+
configLoader: process.versions.bun ? 'native' : 'bundle',
|
|
48
|
+
server: { middlewareMode: true, hmr: false },
|
|
48
49
|
appType: 'spa',
|
|
49
50
|
base: '/dashboard/',
|
|
50
51
|
});
|
|
@@ -9,6 +9,7 @@ export interface SseEventEnvelope {
|
|
|
9
9
|
interface EventSubscriber {
|
|
10
10
|
topics: Set<string> | null;
|
|
11
11
|
push: (chunk: string) => void;
|
|
12
|
+
close: () => void;
|
|
12
13
|
}
|
|
13
14
|
|
|
14
15
|
export interface EventStreamOptions {
|
|
@@ -42,6 +43,10 @@ export class EventBroadcaster {
|
|
|
42
43
|
this.sessionId = sessionId ?? '';
|
|
43
44
|
}
|
|
44
45
|
|
|
46
|
+
public close(): void {
|
|
47
|
+
for (const subscriber of this.subscribers.values()) subscriber.close();
|
|
48
|
+
}
|
|
49
|
+
|
|
45
50
|
public broadcast(event: string, payload: unknown): SseEventEnvelope {
|
|
46
51
|
const envelope: SseEventEnvelope = {
|
|
47
52
|
id: String(++this.nextEventId),
|
|
@@ -109,6 +114,7 @@ export class EventBroadcaster {
|
|
|
109
114
|
this.subscribers.set(subscriberId, {
|
|
110
115
|
topics,
|
|
111
116
|
push,
|
|
117
|
+
close: () => { cleanup(); controller.close(); },
|
|
112
118
|
});
|
|
113
119
|
|
|
114
120
|
options.signal?.addEventListener('abort', cleanup, { once: true });
|
|
@@ -10,6 +10,8 @@
|
|
|
10
10
|
* only stores small summaries — no message payloads.
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
|
+
import type { SessionRefreshSnapshot } from '@open-wa/schema';
|
|
14
|
+
|
|
13
15
|
const MAX_RECONNECTIONS = 100;
|
|
14
16
|
const MAX_TIMELINE_STEPS = 50;
|
|
15
17
|
|
|
@@ -43,6 +45,7 @@ export interface ReconnectionEntry {
|
|
|
43
45
|
}
|
|
44
46
|
|
|
45
47
|
export interface HealthSnapshot {
|
|
48
|
+
refresh: SessionRefreshSnapshot | null;
|
|
46
49
|
launchTimeline: TimelineStep[];
|
|
47
50
|
patches: PatchInfo[];
|
|
48
51
|
license: LicenseInfo | null;
|
|
@@ -52,6 +55,9 @@ export interface HealthSnapshot {
|
|
|
52
55
|
}
|
|
53
56
|
|
|
54
57
|
export class HealthStore {
|
|
58
|
+
private refresh: SessionRefreshSnapshot | null = null;
|
|
59
|
+
private stagedPatches: PatchInfo[] = [];
|
|
60
|
+
private stagedLicense: LicenseInfo | null = null;
|
|
55
61
|
private timeline: TimelineStep[] = [];
|
|
56
62
|
private patches: PatchInfo[] = [];
|
|
57
63
|
private license: LicenseInfo | null = null;
|
|
@@ -71,6 +77,35 @@ export class HealthStore {
|
|
|
71
77
|
const ts = Date.now();
|
|
72
78
|
this.lastEventAt = ts;
|
|
73
79
|
|
|
80
|
+
if (event === 'session.refresh.progress' && data?.refresh) {
|
|
81
|
+
this.refresh = data.refresh as SessionRefreshSnapshot;
|
|
82
|
+
if (this.refresh.phase === 'reloading') {
|
|
83
|
+
this.patches = []; this.license = null;
|
|
84
|
+
this.stagedPatches = []; this.stagedLicense = null;
|
|
85
|
+
}
|
|
86
|
+
if (!this.refresh.running && (this.refresh.phase === 'ready' || this.refresh.restored)) {
|
|
87
|
+
this.patches = [...this.stagedPatches];
|
|
88
|
+
this.license = this.stagedLicense ?? { status: 'missing', source: 'none', keyType: 'none', detail: 'No license is applied.' };
|
|
89
|
+
}
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
if (this.refresh?.running || this.refresh?.phase === 'needs_auth') {
|
|
93
|
+
if (event === 'patch.apply.after') this.stagedPatches.push(...this.readAppliedPatches(data?.details as Record<string, unknown> | undefined));
|
|
94
|
+
if (event === 'license.inject.after' && data?.details) {
|
|
95
|
+
const current = this.license;
|
|
96
|
+
this.captureLicenseInfo(data.details as Record<string, unknown>);
|
|
97
|
+
this.stagedLicense = this.license; this.license = current;
|
|
98
|
+
}
|
|
99
|
+
return; // Candidate preparation/install events do not rewrite the launch timeline or installed status.
|
|
100
|
+
}
|
|
101
|
+
if (event === 'patch.apply.after') {
|
|
102
|
+
const results = this.readAppliedPatches(data?.details as Record<string, unknown> | undefined);
|
|
103
|
+
for (const result of results) {
|
|
104
|
+
this.patches = [...this.patches.filter(patch => patch.patchId !== result.patchId), result];
|
|
105
|
+
}
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
|
|
74
109
|
// ── Launch timeline ──
|
|
75
110
|
if (event.startsWith('launch.') && event.endsWith('.before')) {
|
|
76
111
|
const step = event.replace('.before', '');
|
|
@@ -97,13 +132,8 @@ export class HealthStore {
|
|
|
97
132
|
timestamp: ts,
|
|
98
133
|
});
|
|
99
134
|
|
|
100
|
-
// Special: capture patch info from launch.patch.init.after
|
|
101
|
-
if (step === 'launch.patch.init') {
|
|
102
|
-
this.capturePatchInfo(details);
|
|
103
|
-
}
|
|
104
|
-
|
|
105
135
|
// Special: capture license info from launch.license.preload.after or launch.license.check.after
|
|
106
|
-
if (step === 'launch.license.
|
|
136
|
+
if (step === 'launch.license.check' && details?.status === 'missing') {
|
|
107
137
|
this.captureLicenseInfo(details);
|
|
108
138
|
}
|
|
109
139
|
return;
|
|
@@ -194,6 +224,7 @@ export class HealthStore {
|
|
|
194
224
|
*/
|
|
195
225
|
getSnapshot(): HealthSnapshot {
|
|
196
226
|
return {
|
|
227
|
+
refresh: this.refresh && { ...this.refresh },
|
|
197
228
|
launchTimeline: [...this.timeline],
|
|
198
229
|
patches: [...this.patches],
|
|
199
230
|
license: this.license ? { ...this.license } : null,
|
|
@@ -210,18 +241,12 @@ export class HealthStore {
|
|
|
210
241
|
}
|
|
211
242
|
}
|
|
212
243
|
|
|
213
|
-
private
|
|
214
|
-
if (!details) return;
|
|
215
|
-
const
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
this.patches = available.map((id) => ({
|
|
220
|
-
patchId: id,
|
|
221
|
-
description: `Patch ${id}`,
|
|
222
|
-
required: true,
|
|
223
|
-
outcome: applied.includes(id) ? 'applied' as const : (outcome === 'none' ? 'not_applicable' as const : 'failed' as const),
|
|
224
|
-
}));
|
|
244
|
+
private readAppliedPatches(details?: Record<string, unknown>): PatchInfo[] {
|
|
245
|
+
if (!details) return [];
|
|
246
|
+
const results = Array.isArray(details.results) ? details.results
|
|
247
|
+
: typeof details.patchId === 'string' ? [details] : [];
|
|
248
|
+
return results.map(result => ({ patchId: String(result.patchId), description: String(result.description ?? `Patch ${result.patchId}`),
|
|
249
|
+
required: Boolean(result.required), outcome: result.outcome as PatchInfo['outcome'] }));
|
|
225
250
|
}
|
|
226
251
|
|
|
227
252
|
private captureLicenseInfo(details?: Record<string, unknown>) {
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import type { Hono } from 'hono';
|
|
2
|
+
import type { Config } from '@open-wa/schema';
|
|
3
|
+
import type { CallingService } from '@open-wa/core';
|
|
4
|
+
import type { upgradeWebSocket } from '@hono/node-server';
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
import { getConnInfo } from '@hono/node-server/conninfo';
|
|
7
|
+
import { encodeAudioPacket } from '@open-wa/schema';
|
|
8
|
+
|
|
9
|
+
const requestSchema = z.object({
|
|
10
|
+
call: z.object({ id: z.string(), sessionId: z.string(), generation: z.string() }).optional(),
|
|
11
|
+
to: z.string().optional(), mode: z.enum(['accept', 'start', 'replace', 'observe']), microphone: z.boolean(), speaker: z.boolean(),
|
|
12
|
+
replacesId: z.string().optional(),
|
|
13
|
+
onMediaFailure: z.enum(['end', 'keep-open']).optional(),
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
export function registerCallingRoutes(app: Hono, options: {
|
|
17
|
+
config: Config; getService: () => CallingService | undefined; upgrade: typeof upgradeWebSocket;
|
|
18
|
+
}) {
|
|
19
|
+
const authorized = (c: Parameters<typeof getConnInfo>[0], key?: string) => {
|
|
20
|
+
if (options.config.apiKey) return key === options.config.apiKey;
|
|
21
|
+
const address = getConnInfo(c).remote.address;
|
|
22
|
+
return address === '::1' || address === '127.0.0.1' || address === '::ffff:127.0.0.1';
|
|
23
|
+
};
|
|
24
|
+
app.post('/api/calls/media', async c => {
|
|
25
|
+
if (!authorized(c, c.req.header('X-API-Key'))) return c.json({ error: 'Calling media requires configured API authentication for remote clients.' }, 401);
|
|
26
|
+
const parsed = requestSchema.safeParse(await c.req.json().catch(() => undefined));
|
|
27
|
+
if (!parsed.success) return c.json({ error: 'Invalid call media request' }, 400);
|
|
28
|
+
const service = options.getService();
|
|
29
|
+
if (!service) return c.json({ ok: false, status: 'unavailable', reason: { code: 'CALLING_UNAVAILABLE', message: 'The calling session is not ready.', status: 503 } });
|
|
30
|
+
return c.json(await service.admitRemote(parsed.data));
|
|
31
|
+
});
|
|
32
|
+
app.get('/api/calls/media/ws', options.upgrade(c => {
|
|
33
|
+
const origin = c.req.header('Origin');
|
|
34
|
+
const requestOrigin = new URL(c.req.url).origin;
|
|
35
|
+
const configured = Array.isArray(options.config.cors) ? options.config.cors : String(options.config.cors).split(',').map(item => item.trim());
|
|
36
|
+
const originAllowed = !origin || origin === requestOrigin || (Boolean(options.config.apiKey) && (configured.includes('*') || configured.includes(origin)));
|
|
37
|
+
let remote: ReturnType<CallingService['connectRemote']> | undefined;
|
|
38
|
+
let service: CallingService | undefined;
|
|
39
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
40
|
+
let ticket = '';
|
|
41
|
+
let failure: string | undefined;
|
|
42
|
+
let sequence = 0, audioTimeMs = 0, lastDropNoticeAt = 0, droppedMs = 0;
|
|
43
|
+
return {
|
|
44
|
+
onOpen(_event, ws) {
|
|
45
|
+
if (!originAllowed) { ws.close(1008, 'Origin is not allowed'); return; }
|
|
46
|
+
timer = setTimeout(() => ws.close(1008, 'Call media handshake timed out'), 10_000);
|
|
47
|
+
timer.unref?.();
|
|
48
|
+
},
|
|
49
|
+
onMessage(event, ws) {
|
|
50
|
+
try {
|
|
51
|
+
if (!remote) {
|
|
52
|
+
if (typeof event.data !== 'string' || event.data.length > 16_384) throw new Error('Expected call media handshake');
|
|
53
|
+
const handshake = JSON.parse(event.data);
|
|
54
|
+
if (!authorized(c, handshake.apiKey) || handshake.version !== 1 || handshake.type !== 'start' || typeof handshake.ticket !== 'string') throw new Error('Unauthorized call media');
|
|
55
|
+
service = options.getService();
|
|
56
|
+
if (!service) throw new Error('Calling session unavailable');
|
|
57
|
+
ticket = handshake.ticket;
|
|
58
|
+
remote = service.connectRemote(ticket, {
|
|
59
|
+
async send(bytes, timestampMs) {
|
|
60
|
+
if (ws.readyState !== 1) throw new Error('Call media disconnected');
|
|
61
|
+
const time = timestampMs ?? audioTimeMs; audioTimeMs = time + bytes.length / 32;
|
|
62
|
+
const frameSequence = sequence++;
|
|
63
|
+
if (((ws.raw as { bufferedAmount?: number })?.bufferedAmount ?? 0) > 16_000) {
|
|
64
|
+
droppedMs += bytes.length / 32;
|
|
65
|
+
if (Date.now() - lastDropNoticeAt >= 5000) { console.warn('Calling playback transport dropped audio while the client caught up; the call remains open.', { discardedMs: droppedMs }); droppedMs = 0; lastDropNoticeAt = Date.now(); }
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
ws.send(encodeAudioPacket(bytes, frameSequence, time));
|
|
69
|
+
},
|
|
70
|
+
activate(callId) { ws.send(JSON.stringify({ type: 'active', callId })); },
|
|
71
|
+
close() { ws.close(1000, 'Call ended'); },
|
|
72
|
+
});
|
|
73
|
+
clearTimeout(timer);
|
|
74
|
+
ws.send(JSON.stringify({ type: 'ready', version: 1, format: { encoding: 'pcm16le', sampleRate: 16_000, channels: 1 } }));
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
if (typeof event.data === 'string') {
|
|
78
|
+
if (event.data.length > 4096) throw new Error('Oversized call media message');
|
|
79
|
+
const message = JSON.parse(event.data);
|
|
80
|
+
if (message.type === 'end') ws.close(1000, 'Media client ended');
|
|
81
|
+
else if (message.type === 'input-error' && typeof message.message === 'string') void service?.remoteInputFailed(ticket, message.message.slice(0, 512)).catch(error => console.warn('Calling microphone recovery failed:', String(error)));
|
|
82
|
+
else if (message.type === 'error' && typeof message.message === 'string') { failure = message.message.slice(0, 512).trim() || 'The dashboard media source failed.'; ws.close(1011, 'Media source failed'); }
|
|
83
|
+
} else remote.push(new Uint8Array(event.data as ArrayBuffer));
|
|
84
|
+
} catch (error) {
|
|
85
|
+
failure = remote && error instanceof Error ? error.message : 'Invalid or unavailable call media';
|
|
86
|
+
if (remote) ws.send(JSON.stringify({ type: 'error', message: failure }));
|
|
87
|
+
ws.close(1008, 'Invalid or unavailable call media');
|
|
88
|
+
}
|
|
89
|
+
},
|
|
90
|
+
onClose(event) { clearTimeout(timer); if (ticket) void service?.remoteDisconnected(ticket, failure ?? `Call media connection closed (WebSocket ${event.code}${event.reason ? `: ${event.reason}` : ''}).`); },
|
|
91
|
+
onError() { clearTimeout(timer); if (ticket) void service?.remoteDisconnected(ticket, failure ?? 'The call media WebSocket connection failed.'); },
|
|
92
|
+
};
|
|
93
|
+
}));
|
|
94
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { Hono } from 'hono';
|
|
2
|
+
import type { Config } from '@open-wa/schema';
|
|
3
|
+
import type { ClientMethodMap } from '../types';
|
|
4
|
+
import { apiKeyMiddleware } from '../auth/api-key';
|
|
5
|
+
import { rateLimitMiddleware } from '../middleware/rate-limit';
|
|
6
|
+
|
|
7
|
+
/** Host controls stay available while document-owned WAPI calls are interrupted. */
|
|
8
|
+
export function registerSessionRefreshRoutes(app: Hono, config: Config, getClient: () => ClientMethodMap | undefined) {
|
|
9
|
+
const controls = new Hono();
|
|
10
|
+
controls.use('*', rateLimitMiddleware(100, 60_000));
|
|
11
|
+
if (config.apiKey) controls.use('*', apiKeyMiddleware(config.apiKey));
|
|
12
|
+
controls.get('/', async c => {
|
|
13
|
+
c.header('Cache-Control', 'no-store');
|
|
14
|
+
const client = getClient();
|
|
15
|
+
if (!client?.getRefreshStatus) return c.json({ error: 'Session controls are unavailable.' }, 503);
|
|
16
|
+
return c.json(await client.getRefreshStatus());
|
|
17
|
+
});
|
|
18
|
+
controls.post('/', async c => {
|
|
19
|
+
const client = getClient();
|
|
20
|
+
if (!client?.requestRefresh) return c.json({ error: 'Session controls are unavailable.' }, 503);
|
|
21
|
+
let body: unknown;
|
|
22
|
+
try { body = await c.req.json(); } catch { return c.json({ error: 'Invalid refresh request.' }, 400); }
|
|
23
|
+
try { return c.json(client.requestRefresh(body), 202); }
|
|
24
|
+
catch (error) {
|
|
25
|
+
const status = error instanceof Error && 'status' in error && error.status === 400 ? 400
|
|
26
|
+
: error instanceof Error && 'status' in error && error.status === 409 ? 409 : 503;
|
|
27
|
+
return c.json({ error: status === 400 ? 'Provide a non-empty license key or omit it.'
|
|
28
|
+
: status === 409 ? 'The session is busy or is not available for refresh.' : 'Session controls are unavailable.' }, status);
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
app.route('/api/session/refresh', controls);
|
|
32
|
+
}
|