@agentapps/station 0.0.0-stage → 0.2.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.
Files changed (75) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +58 -2
  3. package/dist/api-key-store.d.ts +46 -0
  4. package/dist/api-key-store.d.ts.map +1 -0
  5. package/dist/api-key-store.js +84 -0
  6. package/dist/api-key-store.js.map +1 -0
  7. package/dist/app-station.d.ts +129 -0
  8. package/dist/app-station.d.ts.map +1 -0
  9. package/dist/app-station.js +706 -0
  10. package/dist/app-station.js.map +1 -0
  11. package/dist/approval-manager.d.ts +75 -0
  12. package/dist/approval-manager.d.ts.map +1 -0
  13. package/dist/approval-manager.js +96 -0
  14. package/dist/approval-manager.js.map +1 -0
  15. package/dist/document-store.d.ts +86 -0
  16. package/dist/document-store.d.ts.map +1 -0
  17. package/dist/document-store.js +230 -0
  18. package/dist/document-store.js.map +1 -0
  19. package/dist/file-handlers/object-store.d.ts +113 -0
  20. package/dist/file-handlers/object-store.d.ts.map +1 -0
  21. package/dist/file-handlers/object-store.js +273 -0
  22. package/dist/file-handlers/object-store.js.map +1 -0
  23. package/dist/file-handlers/signed-url.d.ts +44 -0
  24. package/dist/file-handlers/signed-url.d.ts.map +1 -0
  25. package/dist/file-handlers/signed-url.js +68 -0
  26. package/dist/file-handlers/signed-url.js.map +1 -0
  27. package/dist/file-handlers/volume-handlers.d.ts +136 -0
  28. package/dist/file-handlers/volume-handlers.d.ts.map +1 -0
  29. package/dist/file-handlers/volume-handlers.js +426 -0
  30. package/dist/file-handlers/volume-handlers.js.map +1 -0
  31. package/dist/in-process-runtime.d.ts +49 -0
  32. package/dist/in-process-runtime.d.ts.map +1 -0
  33. package/dist/in-process-runtime.js +50 -0
  34. package/dist/in-process-runtime.js.map +1 -0
  35. package/dist/index.d.ts +27 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +34 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/local-process-runtime.d.ts +28 -0
  40. package/dist/local-process-runtime.d.ts.map +1 -0
  41. package/dist/local-process-runtime.js +134 -0
  42. package/dist/local-process-runtime.js.map +1 -0
  43. package/dist/oauth-manager.d.ts +90 -0
  44. package/dist/oauth-manager.d.ts.map +1 -0
  45. package/dist/oauth-manager.js +148 -0
  46. package/dist/oauth-manager.js.map +1 -0
  47. package/dist/oauth-pages.d.ts +9 -0
  48. package/dist/oauth-pages.d.ts.map +1 -0
  49. package/dist/oauth-pages.js +59 -0
  50. package/dist/oauth-pages.js.map +1 -0
  51. package/dist/permission-enforcer.d.ts +52 -0
  52. package/dist/permission-enforcer.d.ts.map +1 -0
  53. package/dist/permission-enforcer.js +144 -0
  54. package/dist/permission-enforcer.js.map +1 -0
  55. package/dist/policy-store.d.ts +34 -0
  56. package/dist/policy-store.d.ts.map +1 -0
  57. package/dist/policy-store.js +35 -0
  58. package/dist/policy-store.js.map +1 -0
  59. package/dist/secrets-manager.d.ts +32 -0
  60. package/dist/secrets-manager.d.ts.map +1 -0
  61. package/dist/secrets-manager.js +12 -0
  62. package/dist/secrets-manager.js.map +1 -0
  63. package/dist/server.d.ts +368 -0
  64. package/dist/server.d.ts.map +1 -0
  65. package/dist/server.js +1954 -0
  66. package/dist/server.js.map +1 -0
  67. package/dist/telemetry.d.ts +9 -0
  68. package/dist/telemetry.d.ts.map +1 -0
  69. package/dist/telemetry.js +9 -0
  70. package/dist/telemetry.js.map +1 -0
  71. package/dist/types.d.ts +47 -0
  72. package/dist/types.d.ts.map +1 -0
  73. package/dist/types.js +9 -0
  74. package/dist/types.js.map +1 -0
  75. package/package.json +40 -3
package/dist/server.js ADDED
@@ -0,0 +1,1954 @@
1
+ /**
2
+ * Station Server
3
+ *
4
+ * Production HTTP server that wraps one or more AppStation instances and
5
+ * serves the Agent Apps v2.0 protocol over POST /messages.
6
+ *
7
+ * Usage:
8
+ * import { StationServer, serve } from '@agentapps/station';
9
+ *
10
+ * const server = await serve({
11
+ * port: 4100,
12
+ * apps: [{ id: 'app.hello', version: '1.0.0', factory }],
13
+ * });
14
+ */
15
+ import { createReadStream, existsSync, statSync } from 'node:fs';
16
+ import { createServer } from 'node:http';
17
+ import { hostname } from 'node:os';
18
+ import { join, normalize, relative, resolve, sep } from 'node:path';
19
+ import { ADMIN_PRINCIPAL_ID, createInProcessTransportPair, ErrorCode, OBJECT_REQUEST_TYPES, STORAGE_REQUEST_TYPES, } from '@agentapps/protocol';
20
+ import { hashApiKey } from './api-key-store.js';
21
+ import { AppStation } from './app-station.js';
22
+ import { ApprovalManager } from './approval-manager.js';
23
+ import { handleStorageRequest, InMemoryDocumentStore, } from './document-store.js';
24
+ import { handleObjectRequest, ObjectStore } from './file-handlers/object-store.js';
25
+ import { getStationSecret } from './file-handlers/signed-url.js';
26
+ import { getVolumesBasePath, handleVolumeRequest, resolveMountPath, VOLUME_REQUEST_TYPES, } from './file-handlers/volume-handlers.js';
27
+ import { InProcessRuntime } from './in-process-runtime.js';
28
+ import { OAuthManager } from './oauth-manager.js';
29
+ import { errorPage, successPage } from './oauth-pages.js';
30
+ import { appVisible, evaluatePolicy, toolVisible } from './permission-enforcer.js';
31
+ import { policyFor } from './policy-store.js';
32
+ const SERVER_VERSION = '1.0.0';
33
+ /** Instance→host secret requests the server can answer via a SecretsManager. */
34
+ const SECRET_CALLBACK_TYPES = new Set([
35
+ 'get_system_secrets',
36
+ 'get_installation_secrets',
37
+ 'update_installation_secrets',
38
+ ]);
39
+ let idCounter = 0;
40
+ function readBody(req) {
41
+ const chunks = [];
42
+ return new Promise((resolve, reject) => {
43
+ req.on('data', (chunk) => chunks.push(chunk));
44
+ req.on('end', () => resolve(Buffer.concat(chunks).toString()));
45
+ req.on('error', reject);
46
+ });
47
+ }
48
+ function json(res, status, data) {
49
+ res.writeHead(status, { 'Content-Type': 'application/json' });
50
+ res.end(JSON.stringify(data));
51
+ }
52
+ // ---------------------------------------------------------------------------
53
+ // StationServer
54
+ // ---------------------------------------------------------------------------
55
+ export class StationServer {
56
+ managedApps = new Map();
57
+ sessionIndex = new Map();
58
+ /** Parked calls per Session (POLICY-REQ-13). */
59
+ parkedCalls = new Map();
60
+ /** `session_close` messages held back until their Session's parked calls end (POLICY-REQ-13). */
61
+ heldCloses = new Map();
62
+ httpServer = null;
63
+ _info = null;
64
+ stationId;
65
+ token;
66
+ idleTimeoutMs;
67
+ defaultPort;
68
+ defaultHost;
69
+ stations;
70
+ secrets;
71
+ documentStore;
72
+ resolveInstallation;
73
+ installations;
74
+ oauth = new OAuthManager();
75
+ publicUrl;
76
+ apiKeyStore;
77
+ policyStore;
78
+ approvalManager;
79
+ adminToken;
80
+ adminRoutes;
81
+ enableManagementApi;
82
+ volumesBasePath;
83
+ stationSecret;
84
+ /** Objects: immutable blobs per Installation, served at GET /objects/{id}. */
85
+ objectStore;
86
+ /** Installation and Workspace of each open session, for scoping object Requests. */
87
+ sessionScopes = new Map();
88
+ /** Cached tool definitions per app for annotation lookups. */
89
+ toolsCache = new Map();
90
+ constructor(options = {}) {
91
+ this.documentStore = options.documentStore ?? new InMemoryDocumentStore();
92
+ this.stationId = options.stationId ?? `station-${hostname()}-${options.port ?? 4100}`;
93
+ this.token = options.token;
94
+ this.idleTimeoutMs = options.idleTimeoutMs ?? 10 * 60 * 1000;
95
+ this.defaultPort = options.port ?? 4100;
96
+ this.defaultHost = options.host ?? '0.0.0.0';
97
+ this.stations = options.stations ?? [];
98
+ this.secrets = options.secrets;
99
+ this.resolveInstallation = options.resolveInstallation;
100
+ this.installations = options.installations;
101
+ this.publicUrl = options.publicUrl;
102
+ this.apiKeyStore = options.apiKeys;
103
+ this.policyStore = options.policies;
104
+ this.approvalManager = options.policies
105
+ ? new ApprovalManager({ timeoutMs: options.askTimeoutMs })
106
+ : undefined;
107
+ this.adminToken = options.adminToken;
108
+ this.adminRoutes = options.adminRoutes ?? {};
109
+ this.enableManagementApi = options.enableManagementApi ?? false;
110
+ this.volumesBasePath = getVolumesBasePath(options.volumesBasePath);
111
+ this.stationSecret = getStationSecret();
112
+ this.objectStore = options.objectStore ?? null;
113
+ for (const app of options.apps ?? []) {
114
+ this.addApp(app);
115
+ }
116
+ }
117
+ // -------------------------------------------------------------------------
118
+ // App management
119
+ // -------------------------------------------------------------------------
120
+ addApp(entry) {
121
+ if (this.managedApps.has(entry.id)) {
122
+ throw new Error(`App ${entry.id} already registered`);
123
+ }
124
+ const runtime = new InProcessRuntime(entry.factory);
125
+ const mountVolume = entry.manifest?.runtime
126
+ ?.mountVolume;
127
+ const appStation = new AppStation({
128
+ appId: entry.id,
129
+ appVersion: entry.version,
130
+ runtime,
131
+ idleTimeoutMs: this.idleTimeoutMs,
132
+ resolveMountPath: (open) => resolveMountPath({
133
+ mountVolume,
134
+ permissions: open.effectivePermissions?.permissions,
135
+ volumesBasePath: this.volumesBasePath,
136
+ workspaceId: open.tenant.workspaceId ?? 'default',
137
+ }),
138
+ });
139
+ const [hostSide, ctrlSide] = createInProcessTransportPair();
140
+ appStation.accept(ctrlSide);
141
+ const managed = {
142
+ entry,
143
+ appStation,
144
+ hostSide,
145
+ initialized: false,
146
+ pending: new Map(),
147
+ };
148
+ hostSide.onMessage((msg) => {
149
+ if (msg.type === 'session_opened' &&
150
+ typeof msg.sessionId === 'string') {
151
+ this.sessionIndex.set(msg.sessionId, entry.id);
152
+ }
153
+ if (msg.type === 'session_closed' &&
154
+ typeof msg.sessionId === 'string') {
155
+ this.sessionIndex.delete(msg.sessionId);
156
+ this.sessionScopes.delete(msg.sessionId);
157
+ }
158
+ if (SECRET_CALLBACK_TYPES.has(msg.type)) {
159
+ void this.handleSecretsCallback(managed, msg);
160
+ return;
161
+ }
162
+ if (STORAGE_REQUEST_TYPES.has(msg.type)) {
163
+ void this.handleStorageCallback(managed, msg);
164
+ return;
165
+ }
166
+ if (VOLUME_REQUEST_TYPES.has(msg.type)) {
167
+ void this.handleVolumeRequest(managed, msg);
168
+ return;
169
+ }
170
+ if (OBJECT_REQUEST_TYPES.has(msg.type)) {
171
+ void this.handleObjectCallback(managed, msg);
172
+ return;
173
+ }
174
+ const req = managed.pending.get(msg.id);
175
+ if (req) {
176
+ clearTimeout(req.timer);
177
+ managed.pending.delete(msg.id);
178
+ req.resolve(msg);
179
+ }
180
+ });
181
+ this.managedApps.set(entry.id, managed);
182
+ }
183
+ async removeApp(appId) {
184
+ const managed = this.managedApps.get(appId);
185
+ if (!managed)
186
+ return;
187
+ for (const [sid, id] of this.sessionIndex) {
188
+ if (id === appId)
189
+ this.sessionIndex.delete(sid);
190
+ }
191
+ for (const { timer } of managed.pending.values())
192
+ clearTimeout(timer);
193
+ managed.pending.clear();
194
+ await managed.appStation.shutdown();
195
+ await managed.hostSide.close();
196
+ this.managedApps.delete(appId);
197
+ }
198
+ // -------------------------------------------------------------------------
199
+ // Lifecycle
200
+ // -------------------------------------------------------------------------
201
+ async start(port, host) {
202
+ const p = port ?? this.defaultPort;
203
+ const h = host ?? this.defaultHost;
204
+ await Promise.allSettled([...this.managedApps.values()].map((m) => this.autoInitialize(m)));
205
+ this.httpServer = createServer((req, res) => {
206
+ this.handleRequest(req, res).catch(() => {
207
+ if (!res.headersSent)
208
+ json(res, 500, { error: 'Internal server error' });
209
+ });
210
+ });
211
+ const info = await new Promise((resolve, reject) => {
212
+ this.httpServer?.listen(p, h, () => {
213
+ const addr = this.httpServer?.address();
214
+ const localUrl = `http://${h === '0.0.0.0' ? 'localhost' : h}:${addr.port}`;
215
+ this._info = {
216
+ port: addr.port,
217
+ host: h,
218
+ url: localUrl,
219
+ stationId: this.stationId,
220
+ apps: [...this.managedApps.keys()],
221
+ oauthCallbackUrl: this.getOAuthRedirectUri(),
222
+ };
223
+ resolve(this._info);
224
+ });
225
+ this.httpServer?.on('error', reject);
226
+ });
227
+ // Announce to stations (fire-and-forget)
228
+ if (this.stations.length > 0) {
229
+ this.announceToStations().catch(() => { });
230
+ }
231
+ return info;
232
+ }
233
+ async stop() {
234
+ await Promise.allSettled([...this.managedApps.values()].map(async (m) => {
235
+ for (const { timer } of m.pending.values())
236
+ clearTimeout(timer);
237
+ m.pending.clear();
238
+ await m.appStation.shutdown();
239
+ await m.hostSide.close();
240
+ }));
241
+ this.managedApps.clear();
242
+ this.sessionIndex.clear();
243
+ this.oauth.dispose();
244
+ if (this.httpServer) {
245
+ await new Promise((r) => this.httpServer?.close(() => r()));
246
+ this.httpServer = null;
247
+ }
248
+ this._info = null;
249
+ }
250
+ get info() {
251
+ return this._info;
252
+ }
253
+ get appIds() {
254
+ return [...this.managedApps.keys()];
255
+ }
256
+ // -------------------------------------------------------------------------
257
+ // Transport helpers
258
+ // -------------------------------------------------------------------------
259
+ sendAndWait(managed, message, timeoutMs = 30_000) {
260
+ return new Promise((resolve, reject) => {
261
+ const timer = setTimeout(() => {
262
+ managed.pending.delete(message.id);
263
+ reject(new Error(`Timeout after ${timeoutMs}ms waiting for ${message.type} response`));
264
+ }, timeoutMs);
265
+ managed.pending.set(message.id, { resolve, timer });
266
+ managed.hostSide.send(message);
267
+ });
268
+ }
269
+ /**
270
+ * Relay a `session_close`. A Session with parked calls is answered
271
+ * `session_closed` at once and ends after its last parked call.
272
+ *
273
+ * @spec POLICY-REQ-13
274
+ */
275
+ closeSession(managed, message, timeoutMs) {
276
+ const sessionId = message.sessionId;
277
+ if (typeof sessionId === 'string' && this.parkedCalls.has(sessionId)) {
278
+ this.heldCloses.set(sessionId, { managed, message });
279
+ return Promise.resolve({
280
+ id: message.id,
281
+ type: 'session_closed',
282
+ timestamp: new Date().toISOString(),
283
+ version: '2.0',
284
+ sessionId,
285
+ });
286
+ }
287
+ return this.sendAndWait(managed, message, timeoutMs);
288
+ }
289
+ /** A call parked on `sessionId` (POLICY-REQ-13). */
290
+ holdSession(sessionId) {
291
+ this.parkedCalls.set(sessionId, (this.parkedCalls.get(sessionId) ?? 0) + 1);
292
+ }
293
+ /** A parked call on `sessionId` was decided and answered: end the Session if a close was held. */
294
+ releaseSession(sessionId) {
295
+ const left = (this.parkedCalls.get(sessionId) ?? 1) - 1;
296
+ if (left > 0) {
297
+ this.parkedCalls.set(sessionId, left);
298
+ return;
299
+ }
300
+ this.parkedCalls.delete(sessionId);
301
+ const held = this.heldCloses.get(sessionId);
302
+ if (!held)
303
+ return;
304
+ this.heldCloses.delete(sessionId);
305
+ this.sendAndWait(held.managed, held.message, 5_000).catch(() => { });
306
+ }
307
+ async autoInitialize(managed) {
308
+ if (managed.initialized)
309
+ return;
310
+ const msg = {
311
+ id: `auto-init-${++idCounter}`,
312
+ type: 'initialize',
313
+ timestamp: new Date().toISOString(),
314
+ version: '2.0',
315
+ supportedVersions: ['2.0'],
316
+ host: { name: 'station-server', version: SERVER_VERSION },
317
+ // HOSTCAP-REQ-1: the server answers these Requests itself and serves many users.
318
+ capabilities: {
319
+ directConnection: false,
320
+ multiUser: true,
321
+ push: true,
322
+ storage: true,
323
+ objects: true,
324
+ volume: true,
325
+ },
326
+ };
327
+ const resp = await this.sendAndWait(managed, msg, 10_000);
328
+ managed.initialized = resp.type === 'initialized';
329
+ }
330
+ /**
331
+ * Answer an instance→host secret request using the configured SecretsManager.
332
+ *
333
+ * Replies mirror the AgentAppHost wire format: `system_secrets` /
334
+ * `installation_secrets` / `update_installation_secrets_response` on success, and a
335
+ * `prompt_result` with `success: false` on failure — so the app's
336
+ * `ctx.systemSecret()` / `ctx.installationSecret()` resolve instead of timing out.
337
+ */
338
+ async handleSecretsCallback(managed, msg) {
339
+ const sessionId = msg.sessionId;
340
+ const requestId = msg.requestId;
341
+ const reply = (type, fields) => {
342
+ managed.hostSide.send({
343
+ id: `secrets-${++idCounter}`,
344
+ type,
345
+ timestamp: new Date().toISOString(),
346
+ version: '2.0',
347
+ sessionId,
348
+ requestId,
349
+ ...fields,
350
+ });
351
+ };
352
+ const fail = (error) => {
353
+ reply('prompt_result', { success: false, error });
354
+ };
355
+ if (!this.secrets) {
356
+ fail(`No secrets manager configured on this server (${msg.type})`);
357
+ return;
358
+ }
359
+ const installationId = msg.installationId ?? managed.entry.id;
360
+ const ctx = {
361
+ installationId,
362
+ tenant: { userId: 'station-server', workspaceId: 'local' },
363
+ sessionId,
364
+ };
365
+ try {
366
+ switch (msg.type) {
367
+ case 'get_system_secrets': {
368
+ const secrets = await this.secrets.getSystemSecrets(ctx);
369
+ reply('system_secrets', { secrets });
370
+ return;
371
+ }
372
+ case 'get_installation_secrets': {
373
+ const secrets = await this.secrets.getInstallationSecrets(ctx);
374
+ reply('installation_secrets', { secrets });
375
+ return;
376
+ }
377
+ case 'update_installation_secrets': {
378
+ const handler = this.secrets.updateInstallationSecrets?.bind(this.secrets);
379
+ if (!handler) {
380
+ fail('Secrets manager does not support updates');
381
+ return;
382
+ }
383
+ const success = await handler(ctx, msg.secrets);
384
+ reply('update_installation_secrets_response', { success });
385
+ return;
386
+ }
387
+ }
388
+ }
389
+ catch (err) {
390
+ fail(err instanceof Error ? err.message : String(err));
391
+ }
392
+ }
393
+ findInstallation(installationId) {
394
+ return this.installations?.().find((i) => i.installationId === installationId);
395
+ }
396
+ /**
397
+ * `GET /installations`: the Installations the caller's Principal may use.
398
+ * Needs a credential even when the Station is otherwise open.
399
+ *
400
+ * @spec POLICY-REQ-10
401
+ * @spec POLICY-REQ-12
402
+ */
403
+ async handleInstallations(req, res) {
404
+ const principalId = await this.identifyCredential(req);
405
+ if (!principalId) {
406
+ json(res, 401, { error: 'Unauthorized: GET /installations needs an API key' });
407
+ return;
408
+ }
409
+ const policy = this.policyStore ? await policyFor(this.policyStore, principalId) : undefined;
410
+ const installations = (this.installations?.() ?? [])
411
+ .filter((i) => this.managedApps.has(i.appId))
412
+ .filter((i) => !policy || appVisible(policy, i.appId))
413
+ .map((i) => ({
414
+ installationId: i.installationId,
415
+ alias: i.alias,
416
+ appId: i.appId,
417
+ name: this.managedApps.get(i.appId)?.entry.name ?? i.appId,
418
+ }));
419
+ json(res, 200, { installations });
420
+ }
421
+ /** The Principal a request's bearer credential names, checked even on an open Station. */
422
+ async identifyCredential(req) {
423
+ const header = req.headers.authorization;
424
+ const bearer = header?.startsWith('Bearer ') ? header.slice(7) : undefined;
425
+ if (!bearer)
426
+ return undefined;
427
+ if (this.apiKeyStore && bearer.startsWith('aak_')) {
428
+ const record = await this.apiKeyStore.getByHash(hashApiKey(bearer));
429
+ return record?.principalId;
430
+ }
431
+ if (this.adminToken && bearer === this.adminToken)
432
+ return ADMIN_PRINCIPAL_ID;
433
+ if (this.token && bearer === this.token)
434
+ return ADMIN_PRINCIPAL_ID;
435
+ return undefined;
436
+ }
437
+ resolveApp(message) {
438
+ if (typeof message.installationId === 'string') {
439
+ const m = this.managedApps.get(message.installationId);
440
+ if (m)
441
+ return m;
442
+ const installation = this.findInstallation(message.installationId);
443
+ if (installation)
444
+ return this.managedApps.get(installation.appId);
445
+ }
446
+ if (typeof message.sessionId === 'string') {
447
+ const appId = this.sessionIndex.get(message.sessionId);
448
+ if (appId)
449
+ return this.managedApps.get(appId);
450
+ }
451
+ if (typeof message.appId === 'string') {
452
+ const m = this.managedApps.get(message.appId);
453
+ if (m)
454
+ return m;
455
+ }
456
+ return this.managedApps.values().next().value;
457
+ }
458
+ // -------------------------------------------------------------------------
459
+ // Storage requests (in-memory, for standalone/dev mode)
460
+ // -------------------------------------------------------------------------
461
+ /**
462
+ * Answer an instance→host Storage request with the configured document
463
+ * store (in memory by default), scoped by installationId.
464
+ */
465
+ async handleStorageCallback(managed, msg) {
466
+ const sessionId = msg.sessionId;
467
+ const requestId = msg.requestId;
468
+ const installationId = this.sessionScopes.get(sessionId)?.installationId ??
469
+ msg.installationId ??
470
+ managed.entry.id;
471
+ const reply = (type, fields) => {
472
+ managed.hostSide.send({
473
+ id: `storage-${++idCounter}`,
474
+ type,
475
+ timestamp: new Date().toISOString(),
476
+ version: '2.0',
477
+ sessionId,
478
+ requestId,
479
+ ...fields,
480
+ });
481
+ };
482
+ try {
483
+ const response = await handleStorageRequest(this.documentStore, installationId, msg);
484
+ reply(response.type, response.fields);
485
+ }
486
+ catch (err) {
487
+ const error = err instanceof Error ? err.message : 'Storage error';
488
+ reply(`${msg.type}_response`, { success: false, error });
489
+ }
490
+ }
491
+ // -------------------------------------------------------------------------
492
+ // Volume storage requests (file_volume_*)
493
+ // -------------------------------------------------------------------------
494
+ /**
495
+ * Answer an instance→host volume storage request.
496
+ *
497
+ * Resolves the workspaceId + installationId from the message (or falls
498
+ * back to the managed app's id), then delegates to the volume handlers
499
+ * which operate on the physical `workspace/` directory.
500
+ */
501
+ async handleVolumeRequest(managed, msg) {
502
+ const sessionId = msg.sessionId;
503
+ const requestId = msg.requestId;
504
+ // VOL-REQ-1 / VOL-REQ-2: the Workspace and the Effective Permissions come
505
+ // from the session_open this server relayed.
506
+ const scope = this.sessionScopes.get(sessionId);
507
+ const ctx = {
508
+ volumesBasePath: this.volumesBasePath,
509
+ workspaceId: scope?.workspaceId ?? 'default',
510
+ sessionId,
511
+ permissions: scope?.permissions,
512
+ };
513
+ try {
514
+ const response = await handleVolumeRequest(ctx, msg);
515
+ if (response) {
516
+ managed.hostSide.send(response);
517
+ }
518
+ else {
519
+ // Unknown request type — send error result
520
+ managed.hostSide.send({
521
+ id: `vol-err-${++idCounter}`,
522
+ type: `${msg.type}_result`,
523
+ timestamp: new Date().toISOString(),
524
+ version: '2.0',
525
+ sessionId,
526
+ requestId,
527
+ success: false,
528
+ error: `Unknown volume request: ${msg.type}`,
529
+ });
530
+ }
531
+ }
532
+ catch (err) {
533
+ managed.hostSide.send({
534
+ id: `vol-err-${++idCounter}`,
535
+ type: `${msg.type}_result`,
536
+ timestamp: new Date().toISOString(),
537
+ version: '2.0',
538
+ sessionId,
539
+ requestId,
540
+ success: false,
541
+ error: err instanceof Error ? err.message : String(err),
542
+ });
543
+ }
544
+ }
545
+ // -------------------------------------------------------------------------
546
+ // Object Requests (object_put, object_get, object_delete, object_list, object_link)
547
+ // -------------------------------------------------------------------------
548
+ /** The object store, built lazily once the server knows its URL. */
549
+ objects() {
550
+ if (!this.objectStore) {
551
+ this.objectStore = new ObjectStore({
552
+ volumesBasePath: this.volumesBasePath,
553
+ stationSecret: this.stationSecret,
554
+ publicUrl: this.publicUrl ?? this._info?.url ?? `http://localhost:${this.defaultPort}`,
555
+ });
556
+ }
557
+ return this.objectStore;
558
+ }
559
+ /**
560
+ * Answer an instance→host object Request. The Installation and Workspace
561
+ * come from the session that was opened over `/messages`; a session the
562
+ * server did not open itself falls back to the app id and `default`.
563
+ */
564
+ async handleObjectCallback(managed, msg) {
565
+ const sessionId = msg.sessionId;
566
+ const requestId = msg.requestId;
567
+ const scope = this.sessionScopes.get(sessionId) ?? {
568
+ installationId: managed.entry.id,
569
+ workspaceId: 'default',
570
+ };
571
+ try {
572
+ const response = await handleObjectRequest(this.objects(), scope, msg);
573
+ managed.hostSide.send((response ?? {
574
+ id: `obj-err-${++idCounter}`,
575
+ type: 'prompt_result',
576
+ timestamp: new Date().toISOString(),
577
+ version: '2.0',
578
+ sessionId,
579
+ requestId,
580
+ success: false,
581
+ error: `Unknown object request: ${msg.type}`,
582
+ }));
583
+ }
584
+ catch (err) {
585
+ managed.hostSide.send({
586
+ id: `obj-err-${++idCounter}`,
587
+ type: 'prompt_result',
588
+ timestamp: new Date().toISOString(),
589
+ version: '2.0',
590
+ sessionId,
591
+ requestId,
592
+ success: false,
593
+ error: err instanceof Error ? err.message : String(err),
594
+ });
595
+ }
596
+ }
597
+ // -------------------------------------------------------------------------
598
+ // Station announce
599
+ // -------------------------------------------------------------------------
600
+ /**
601
+ * Announce all apps to registered stations.
602
+ *
603
+ * Opens a temporary session per app to discover its tools, then POSTs
604
+ * the catalog to each station's announce endpoint. Stations use this
605
+ * to register the app station and its apps automatically.
606
+ */
607
+ async announceToStations() {
608
+ if (this.stations.length === 0)
609
+ return;
610
+ const apps = await this.buildAnnounceCatalog();
611
+ if (apps.length === 0)
612
+ return;
613
+ const stationUrl = this._info?.url;
614
+ if (!stationUrl)
615
+ return;
616
+ const payload = {
617
+ stationId: this.stationId,
618
+ stationUrl,
619
+ apps,
620
+ };
621
+ await Promise.allSettled(this.stations.map((station) => this.postAnnounce(station, payload)));
622
+ }
623
+ async buildAnnounceCatalog() {
624
+ const result = [];
625
+ for (const [appId, managed] of this.managedApps) {
626
+ try {
627
+ if (!managed.initialized)
628
+ await this.autoInitialize(managed);
629
+ // Open temporary session to list tools
630
+ const openMsg = {
631
+ id: `announce-open-${++idCounter}`,
632
+ type: 'session_open',
633
+ timestamp: new Date().toISOString(),
634
+ version: '2.0',
635
+ installationId: appId,
636
+ tenant: { userId: 'system', workspaceId: 'system' },
637
+ };
638
+ const openResp = await this.sendAndWait(managed, openMsg, 10_000);
639
+ if (openResp.type !== 'session_opened')
640
+ continue;
641
+ const sessionId = openResp.sessionId;
642
+ // List tools
643
+ const toolsMsg = {
644
+ id: `announce-tools-${++idCounter}`,
645
+ type: 'list_tools',
646
+ timestamp: new Date().toISOString(),
647
+ version: '2.0',
648
+ sessionId,
649
+ };
650
+ const toolsResp = await this.sendAndWait(managed, toolsMsg, 10_000);
651
+ const tools = toolsResp.tools ?? [];
652
+ // Close temporary session (best-effort)
653
+ const closeMsg = {
654
+ id: `announce-close-${++idCounter}`,
655
+ type: 'session_close',
656
+ timestamp: new Date().toISOString(),
657
+ version: '2.0',
658
+ sessionId,
659
+ reason: 'announce-complete',
660
+ };
661
+ this.closeSession(managed, closeMsg, 5_000).catch(() => { });
662
+ // Cache tool annotations for permission enforcement
663
+ this.cacheTools(appId, tools.map((t) => ({
664
+ name: t.name,
665
+ annotations: t.annotations,
666
+ })));
667
+ result.push({
668
+ appId,
669
+ name: managed.entry.name ?? appId.replace(/^app\./, ''),
670
+ version: managed.entry.version,
671
+ description: managed.entry.description,
672
+ tools: tools.map((t) => ({
673
+ name: t.name,
674
+ description: t.description,
675
+ parameters: t.parameters,
676
+ annotations: t.annotations,
677
+ })),
678
+ });
679
+ }
680
+ catch {
681
+ // Skip apps that fail to list tools
682
+ }
683
+ }
684
+ return result;
685
+ }
686
+ async postAnnounce(station, payload) {
687
+ const headers = { 'Content-Type': 'application/json' };
688
+ if (station.token)
689
+ headers.Authorization = `Bearer ${station.token}`;
690
+ const response = await fetch(station.url, {
691
+ method: 'POST',
692
+ headers,
693
+ body: JSON.stringify(payload),
694
+ signal: AbortSignal.timeout(10_000),
695
+ });
696
+ if (!response.ok) {
697
+ const body = await response.text().catch(() => '');
698
+ throw new Error(`Station ${station.url} responded ${response.status}: ${body}`);
699
+ }
700
+ }
701
+ // -------------------------------------------------------------------------
702
+ // HTTP
703
+ // -------------------------------------------------------------------------
704
+ async handleRequest(req, res) {
705
+ const url = req.url ?? '/';
706
+ res.setHeader('Access-Control-Allow-Origin', '*');
707
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
708
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
709
+ if (req.method === 'OPTIONS') {
710
+ res.writeHead(204);
711
+ res.end();
712
+ return;
713
+ }
714
+ // Authentication: API keys or legacy bearer token.
715
+ const authResult = await this.authenticateRequest(req, url);
716
+ if (authResult === false) {
717
+ json(res, 401, { error: 'Unauthorized' });
718
+ return;
719
+ }
720
+ // @spec POLICY-REQ-10
721
+ // @spec POLICY-REQ-12
722
+ if (url === '/installations' && req.method === 'GET') {
723
+ await this.handleInstallations(req, res);
724
+ return;
725
+ }
726
+ if (url === '/health' && req.method === 'GET') {
727
+ json(res, 200, {
728
+ status: 'ok',
729
+ stationId: this.stationId,
730
+ version: SERVER_VERSION,
731
+ apps: [...this.managedApps.entries()].map(([id, m]) => ({
732
+ id,
733
+ version: m.entry.version,
734
+ name: m.entry.name,
735
+ initialized: m.initialized,
736
+ sessions: m.appStation.sessionCount,
737
+ instances: m.appStation.instanceCount,
738
+ })),
739
+ });
740
+ return;
741
+ }
742
+ if (url === '/messages' && req.method === 'POST') {
743
+ await this.handleMessages(req, res, authResult || undefined);
744
+ return;
745
+ }
746
+ // OAuth routes — start and callback
747
+ if (req.method === 'GET' && url.startsWith('/auth/start')) {
748
+ await this.handleAuthStart(req, res);
749
+ return;
750
+ }
751
+ if (req.method === 'GET' && url.startsWith('/auth/callback')) {
752
+ await this.handleAuthCallback(req, res);
753
+ return;
754
+ }
755
+ if (req.method === 'GET' && url.startsWith('/auth/status')) {
756
+ await this.handleAuthStatus(req, res);
757
+ return;
758
+ }
759
+ // @spec HOOK-REQ-26
760
+ const adminRoute = req.method === 'POST' ? this.adminRoutes[url] : undefined;
761
+ if (adminRoute) {
762
+ if (((authResult || undefined)?.principalId ?? ADMIN_PRINCIPAL_ID) !== ADMIN_PRINCIPAL_ID) {
763
+ json(res, 403, { error: 'Only the admin may call this route' });
764
+ return;
765
+ }
766
+ let body;
767
+ try {
768
+ body = JSON.parse((await readBody(req)) || '{}');
769
+ }
770
+ catch {
771
+ json(res, 400, { error: 'Body is not JSON' });
772
+ return;
773
+ }
774
+ json(res, 200, (await adminRoute(body)) ?? {});
775
+ return;
776
+ }
777
+ // Management API (permissions, keys, approvals)
778
+ // @spec POLICY-REQ-7
779
+ if (url === '/approvals' || url.startsWith('/approvals/')) {
780
+ await this.handleApprovals(req, res, url, authResult || undefined);
781
+ return;
782
+ }
783
+ if (this.enableManagementApi && url.startsWith('/api/')) {
784
+ await this.handleManagementApi(req, res, url, authResult || undefined);
785
+ return;
786
+ }
787
+ // App discovery & static serving routes
788
+ if (req.method === 'GET' && (url === '/apps' || url === '/apps/')) {
789
+ this.handleAppCatalog(res);
790
+ return;
791
+ }
792
+ const manifestMatch = url.match(/^\/apps\/([^/]+)\/manifest$/);
793
+ if (req.method === 'GET' && manifestMatch) {
794
+ this.handleAppManifest(res, manifestMatch[1]);
795
+ return;
796
+ }
797
+ if (req.method === 'GET' && (url === '/launcher' || url === '/launcher/')) {
798
+ this.handleLauncher(res, req);
799
+ return;
800
+ }
801
+ const bundleMatch = url.match(/^\/apps\/([^/]+)\/bundles\/(.+)$/);
802
+ if (req.method === 'GET' && bundleMatch) {
803
+ this.handleStaticBundle(res, bundleMatch[1], bundleMatch[2]);
804
+ return;
805
+ }
806
+ // Objects: public ones to anyone, private ones with a signed link token
807
+ const objectMatch = url.match(/^\/objects\/([^?/]+)(?:\?(.*))?$/);
808
+ if (objectMatch && req.method === 'GET') {
809
+ const token = new URLSearchParams(objectMatch[2] ?? '').get('token') ?? undefined;
810
+ await this.handleObjectRequest(res, objectMatch[1], token);
811
+ return;
812
+ }
813
+ json(res, 404, { error: `Not found: ${req.method} ${url}` });
814
+ }
815
+ // -------------------------------------------------------------------------
816
+ // OAuth helpers
817
+ // -------------------------------------------------------------------------
818
+ /**
819
+ * Resolve the OAuth redirect URI for the app station.
820
+ *
821
+ * Priority: explicit `publicUrl` option → auto-detect from request headers
822
+ * (supports X-Forwarded-Proto/Host behind a reverse proxy) → fallback to
823
+ * the server's own info.
824
+ */
825
+ getOAuthRedirectUri(req) {
826
+ if (this.publicUrl) {
827
+ const base = this.publicUrl.replace(/\/+$/, '');
828
+ return `${base}/auth/callback`;
829
+ }
830
+ if (req) {
831
+ const proto = req.headers['x-forwarded-proto'] ?? 'http';
832
+ const host = req.headers['x-forwarded-host'] ?? req.headers.host;
833
+ if (host)
834
+ return `${proto}://${host}/auth/callback`;
835
+ }
836
+ const port = this._info?.port ?? this.defaultPort;
837
+ return `http://localhost:${port}/auth/callback`;
838
+ }
839
+ // -------------------------------------------------------------------------
840
+ // OAuth handlers
841
+ // -------------------------------------------------------------------------
842
+ /**
843
+ * GET /auth/start?installationId=X[&userId=Z&workspaceId=W]
844
+ *
845
+ * Initiates an OAuth flow. Resolves the installationId to an appId, reads
846
+ * the app's auth config and system secrets, builds the authorize URL, and
847
+ * either redirects the browser (302) or returns JSON with the URL.
848
+ */
849
+ async handleAuthStart(req, res) {
850
+ const parsed = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`);
851
+ const installationId = parsed.searchParams.get('installationId');
852
+ const userId = parsed.searchParams.get('userId') ?? 'anonymous';
853
+ const workspaceId = parsed.searchParams.get('workspaceId') ?? 'local';
854
+ if (!installationId) {
855
+ json(res, 400, { error: 'Missing required query parameter: installationId' });
856
+ return;
857
+ }
858
+ // Resolve installationId → appId
859
+ if (!this.resolveInstallation) {
860
+ json(res, 500, {
861
+ error: 'No installation resolver configured — cannot map installationId to app',
862
+ });
863
+ return;
864
+ }
865
+ const resolved = this.resolveInstallation(installationId);
866
+ if (!resolved) {
867
+ json(res, 404, { error: `Unknown installationId: ${installationId}` });
868
+ return;
869
+ }
870
+ const { appId } = resolved;
871
+ const managed = this.managedApps.get(appId);
872
+ if (!managed) {
873
+ json(res, 404, { error: `App not found: ${appId}` });
874
+ return;
875
+ }
876
+ const authConfig = managed.entry.auth;
877
+ if (!authConfig?.authorizeUrl || !authConfig?.tokenUrl) {
878
+ json(res, 400, { error: `App ${appId} does not support OAuth (missing auth config)` });
879
+ return;
880
+ }
881
+ // Resolve system secrets for client credentials
882
+ if (!this.secrets) {
883
+ json(res, 500, { error: 'No secrets manager configured — cannot read OAuth credentials' });
884
+ return;
885
+ }
886
+ const ctx = {
887
+ installationId,
888
+ tenant: { userId, workspaceId },
889
+ };
890
+ let systemSecrets;
891
+ try {
892
+ systemSecrets = (await this.secrets.getSystemSecrets(ctx)) ?? {};
893
+ }
894
+ catch {
895
+ json(res, 500, { error: 'Failed to read system secrets' });
896
+ return;
897
+ }
898
+ const clientId = systemSecrets.CLIENT_ID;
899
+ const clientSecret = systemSecrets.CLIENT_SECRET;
900
+ if (!clientId || !clientSecret) {
901
+ json(res, 500, { error: `Missing CLIENT_ID or CLIENT_SECRET for ${appId}` });
902
+ return;
903
+ }
904
+ // Build the request URI from the app station's public URL — this is
905
+ // infrastructure-level, not per-app. All OAuth apps share the same
906
+ // request endpoint.
907
+ const redirectUri = this.getOAuthRedirectUri(req);
908
+ const params = {
909
+ installationId,
910
+ appId,
911
+ tenant: { userId, workspaceId },
912
+ provider: authConfig.provider ?? 'oauth2',
913
+ authorizeUrl: authConfig.authorizeUrl,
914
+ tokenUrl: authConfig.tokenUrl,
915
+ clientId,
916
+ clientSecret,
917
+ redirectUri,
918
+ scopes: authConfig.scopes,
919
+ };
920
+ const { url, state } = this.oauth.startAuth(params);
921
+ // If the browser wants HTML, redirect directly. Otherwise return JSON.
922
+ const accept = req.headers.accept ?? '';
923
+ if (accept.includes('text/html')) {
924
+ res.writeHead(302, { Location: url });
925
+ res.end();
926
+ }
927
+ else {
928
+ json(res, 200, { url, state });
929
+ }
930
+ }
931
+ /**
932
+ * GET /auth/callback?code=X&state=Y
933
+ *
934
+ * Receives the OAuth provider's redirect. Exchanges the code for tokens,
935
+ * persists them via the SecretsManager, and shows a success/error page.
936
+ */
937
+ async handleAuthCallback(_req, res) {
938
+ const parsed = new URL(_req.url ?? '/', `http://${_req.headers.host ?? 'localhost'}`);
939
+ const code = parsed.searchParams.get('code');
940
+ const state = parsed.searchParams.get('state');
941
+ const providerError = parsed.searchParams.get('error');
942
+ const errorDescription = parsed.searchParams.get('error_description');
943
+ const html = (status, body) => {
944
+ res.writeHead(status, { 'Content-Type': 'text/html; charset=utf-8' });
945
+ res.end(body);
946
+ };
947
+ // Provider returned an error (e.g. user denied consent)
948
+ if (providerError) {
949
+ html(400, errorPage('Authentication denied', errorDescription ?? providerError));
950
+ return;
951
+ }
952
+ if (!code || !state) {
953
+ html(400, errorPage('Missing parameters', 'The request is missing code or state.'));
954
+ return;
955
+ }
956
+ if (!this.oauth.hasPending(state)) {
957
+ html(400, errorPage('Session expired', 'This authentication link has expired. Please start again.'));
958
+ return;
959
+ }
960
+ try {
961
+ const result = await this.oauth.handleCallback(state, code);
962
+ // Persist tokens via the SecretsManager
963
+ if (this.secrets?.updateInstallationSecrets) {
964
+ const ctx = {
965
+ installationId: result.installationId,
966
+ tenant: result.tenant ?? { userId: 'anonymous', workspaceId: 'local' },
967
+ };
968
+ await this.secrets.updateInstallationSecrets(ctx, result.tokens);
969
+ }
970
+ const appName = this.managedApps.get(result.appId)?.entry.name ?? result.installationId;
971
+ html(200, successPage(appName));
972
+ }
973
+ catch (err) {
974
+ const message = err instanceof Error ? err.message : String(err);
975
+ html(500, errorPage('Authentication failed', message));
976
+ }
977
+ }
978
+ /**
979
+ * GET /auth/status?installationId=X
980
+ *
981
+ * Returns the current authentication status for an installation.
982
+ * Used by the CLI to poll for completion after delegating OAuth
983
+ * to the station via /auth/start.
984
+ */
985
+ async handleAuthStatus(req, res) {
986
+ const parsed = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`);
987
+ const installationId = parsed.searchParams.get('installationId');
988
+ if (!installationId) {
989
+ json(res, 400, { error: 'Missing required query parameter: installationId' });
990
+ return;
991
+ }
992
+ if (!this.secrets) {
993
+ json(res, 500, { error: 'No secrets manager configured' });
994
+ return;
995
+ }
996
+ const ctx = {
997
+ installationId,
998
+ tenant: { userId: 'anonymous', workspaceId: 'local' },
999
+ };
1000
+ try {
1001
+ const installationSecrets = (await this.secrets.getInstallationSecrets(ctx)) ?? {};
1002
+ const authenticated = !!(installationSecrets.ACCESS_TOKEN || installationSecrets.REFRESH_TOKEN);
1003
+ json(res, 200, { authenticated });
1004
+ }
1005
+ catch {
1006
+ json(res, 500, { error: 'Failed to read auth status' });
1007
+ }
1008
+ }
1009
+ // -------------------------------------------------------------------------
1010
+ // Messages handler
1011
+ // -------------------------------------------------------------------------
1012
+ async handleMessages(req, res, authResult) {
1013
+ let body;
1014
+ try {
1015
+ body = await readBody(req);
1016
+ }
1017
+ catch {
1018
+ json(res, 400, { error: 'Failed to read request body' });
1019
+ return;
1020
+ }
1021
+ let message;
1022
+ try {
1023
+ message = JSON.parse(body);
1024
+ }
1025
+ catch {
1026
+ json(res, 400, { error: 'Invalid JSON' });
1027
+ return;
1028
+ }
1029
+ // POLICY-REQ-10: a session opened as a known Installation gets that
1030
+ // Installation's Effective Permissions from the Station's record, not
1031
+ // from what the caller claims.
1032
+ if (message.type === 'session_open') {
1033
+ const open = message;
1034
+ const installation = typeof open.installationId === 'string'
1035
+ ? this.findInstallation(open.installationId)
1036
+ : undefined;
1037
+ if (installation) {
1038
+ open.effectivePermissions = { permissions: installation.permissions ?? {} };
1039
+ }
1040
+ }
1041
+ const managed = this.resolveApp(message);
1042
+ if (!managed) {
1043
+ json(res, 404, { error: 'No matching app found' });
1044
+ return;
1045
+ }
1046
+ if (!managed.initialized && message.type !== 'initialize') {
1047
+ try {
1048
+ await this.autoInitialize(managed);
1049
+ }
1050
+ catch {
1051
+ // AppStation will reject with "not initialized"
1052
+ }
1053
+ }
1054
+ // The Approval this call was parked on and approved by, if any (POLICY-REQ-14).
1055
+ let approved;
1056
+ // The Session this call held while parked (POLICY-REQ-13).
1057
+ let heldSessionId;
1058
+ // POLICY-REQ-5: evaluate the Principal's Policy before relaying a tool call.
1059
+ // An open station (no credential configured) serves only its local admin.
1060
+ if (message.type === 'tool_call' && this.policyStore) {
1061
+ const msg = message;
1062
+ const toolName = msg.tool ?? '';
1063
+ const args = msg.arguments ?? {};
1064
+ const principalId = authResult?.principalId ?? ADMIN_PRINCIPAL_ID;
1065
+ const policy = await policyFor(this.policyStore, principalId);
1066
+ const decision = evaluatePolicy(policy, {
1067
+ app: managed.entry.id,
1068
+ tool: toolName,
1069
+ args,
1070
+ annotations: this.getToolAnnotations(managed.entry.id, toolName),
1071
+ });
1072
+ let outcome = decision.effect === 'deny' ? 'deny' : 'allow';
1073
+ if (decision.effect === 'ask' && this.approvalManager) {
1074
+ const approvals = this.approvalManager;
1075
+ const call = { principalId, app: managed.entry.id, tool: toolName };
1076
+ // POLICY-REQ-13: the Session stays able to relay this call while it is parked.
1077
+ const sessionId = message.sessionId;
1078
+ if (typeof sessionId === 'string') {
1079
+ heldSessionId = sessionId;
1080
+ this.holdSession(sessionId);
1081
+ }
1082
+ // POLICY-REQ-14: a caller that goes away cancels its Approval.
1083
+ let approvalId;
1084
+ const onCallerGone = () => {
1085
+ if (approvalId)
1086
+ approvals.cancel(approvalId);
1087
+ };
1088
+ res.once('close', onCallerGone);
1089
+ // POLICY-REQ-6: park until the Approver decides or the Approval expires.
1090
+ const answer = await approvals.park({ ...call, args, rule: decision.rule }, (info) => {
1091
+ approvalId = info.id;
1092
+ if (res.destroyed)
1093
+ approvals.cancel(info.id);
1094
+ });
1095
+ res.off('close', onCallerGone);
1096
+ outcome = answer === 'approve' ? 'allow' : answer;
1097
+ if (answer === 'approve' && approvalId)
1098
+ approved = { id: approvalId, ...call };
1099
+ }
1100
+ if (outcome === 'cancelled') {
1101
+ // Nobody is left to answer; the cancellation is already logged.
1102
+ if (heldSessionId)
1103
+ this.releaseSession(heldSessionId);
1104
+ return;
1105
+ }
1106
+ if (outcome !== 'allow') {
1107
+ const reason = outcome === 'timeout'
1108
+ ? `Tool '${toolName}' was not approved before the Approval expired`
1109
+ : `Tool '${toolName}' is denied by rule '${decision.rule}' of ${principalId}'s Policy`;
1110
+ // POLICY-NFR-1: every deny is audited.
1111
+ // eslint-disable-next-line no-console
1112
+ console.error(`[policy] ${outcome}: principal=${principalId} app=${managed.entry.id} tool=${toolName} rule=${decision.rule} at=${new Date().toISOString()}`);
1113
+ json(res, 403, {
1114
+ id: message.id,
1115
+ type: 'error',
1116
+ timestamp: new Date().toISOString(),
1117
+ version: '2.0',
1118
+ error: {
1119
+ code: outcome === 'timeout' ? ErrorCode.APPROVAL_TIMEOUT : ErrorCode.PERMISSION_DENIED,
1120
+ message: reason,
1121
+ details: { layer: 'policy', rule: decision.rule, reason },
1122
+ },
1123
+ });
1124
+ if (heldSessionId)
1125
+ this.releaseSession(heldSessionId);
1126
+ return;
1127
+ }
1128
+ }
1129
+ try {
1130
+ const response = message.type === 'session_close'
1131
+ ? await this.closeSession(managed, message)
1132
+ : await this.sendAndWait(managed, message);
1133
+ // POLICY-REQ-14: an approved call that the Instance answers with an error is logged.
1134
+ if (approved && response.type === 'error') {
1135
+ const code = response.error?.code ?? 'UNKNOWN';
1136
+ this.approvalManager?.logApprovedCallFailed(approved.id, approved, code);
1137
+ }
1138
+ if (message.type === 'session_open' && response.type === 'session_opened') {
1139
+ const open = message;
1140
+ const tenant = open.tenant;
1141
+ this.sessionScopes.set(response.sessionId, {
1142
+ installationId: open.installationId ?? managed.entry.id,
1143
+ workspaceId: tenant?.workspaceId ?? 'default',
1144
+ permissions: open.effectivePermissions
1145
+ ?.permissions,
1146
+ });
1147
+ }
1148
+ // POLICY-REQ-4: Rules on Annotations need the tools' Annotations.
1149
+ if (message.type === 'list_tools') {
1150
+ const tools = response.tools;
1151
+ if (tools) {
1152
+ this.cacheTools(managed.entry.id, tools);
1153
+ // POLICY-REQ-11: drop the tools this Principal's Policy always denies.
1154
+ if (this.policyStore) {
1155
+ const policy = await policyFor(this.policyStore, authResult?.principalId ?? ADMIN_PRINCIPAL_ID);
1156
+ response.tools = tools.filter((t) => toolVisible(policy, managed.entry.id, t.name, t.annotations));
1157
+ }
1158
+ }
1159
+ }
1160
+ json(res, 200, response);
1161
+ }
1162
+ catch (err) {
1163
+ const errMsg = err instanceof Error ? err.message : 'Unknown error';
1164
+ // POLICY-REQ-14: an approved call that could not be relayed is logged.
1165
+ if (approved) {
1166
+ this.approvalManager?.logApprovedCallFailed(approved.id, approved, ErrorCode.TIMEOUT);
1167
+ }
1168
+ json(res, 504, { error: errMsg });
1169
+ }
1170
+ finally {
1171
+ if (heldSessionId)
1172
+ this.releaseSession(heldSessionId);
1173
+ }
1174
+ }
1175
+ // -------------------------------------------------------------------------
1176
+ // Authentication
1177
+ // -------------------------------------------------------------------------
1178
+ /**
1179
+ * Authenticate an incoming request.
1180
+ *
1181
+ * Returns:
1182
+ * - `null` when no auth is configured (pass-through)
1183
+ * - `false` when auth is required but the request is invalid
1184
+ * - `{ identity, policyId }` on success
1185
+ */
1186
+ async authenticateRequest(req, url) {
1187
+ const needsAuth = url.startsWith('/messages') ||
1188
+ url.startsWith('/api/') ||
1189
+ url.startsWith('/approvals') ||
1190
+ url in this.adminRoutes;
1191
+ if (!needsAuth)
1192
+ return null;
1193
+ // Auth is enforced once a legacy token is configured or at least one
1194
+ // active API key exists. An empty (or fully revoked/expired) key store
1195
+ // keeps the station open — creating the first key switches auth on.
1196
+ if (!this.token) {
1197
+ if (!this.apiKeyStore)
1198
+ return null;
1199
+ const keys = await this.apiKeyStore.list();
1200
+ const now = new Date();
1201
+ const hasActiveKey = keys.some((k) => !k.revokedAt && (!k.expiresAt || new Date(k.expiresAt) > now));
1202
+ if (!hasActiveKey)
1203
+ return null;
1204
+ }
1205
+ const authHeader = req.headers.authorization;
1206
+ if (!authHeader)
1207
+ return false;
1208
+ const bearer = authHeader.startsWith('Bearer ') ? authHeader.slice(7) : null;
1209
+ if (!bearer)
1210
+ return false;
1211
+ // API key auth (aak_ prefix)
1212
+ if (this.apiKeyStore && bearer.startsWith('aak_')) {
1213
+ const hash = hashApiKey(bearer);
1214
+ const record = await this.apiKeyStore.getByHash(hash);
1215
+ if (!record)
1216
+ return false;
1217
+ return { identity: record.identity, principalId: record.principalId };
1218
+ }
1219
+ // Legacy single-token auth
1220
+ if (this.token && bearer === this.token) {
1221
+ return { identity: { userId: 'local' }, principalId: ADMIN_PRINCIPAL_ID };
1222
+ }
1223
+ // The local admin credential handed to the CLI that launched the station.
1224
+ if (this.adminToken && bearer === this.adminToken) {
1225
+ return { identity: { userId: ADMIN_PRINCIPAL_ID }, principalId: ADMIN_PRINCIPAL_ID };
1226
+ }
1227
+ return false;
1228
+ }
1229
+ // -------------------------------------------------------------------------
1230
+ // Tool annotations cache
1231
+ // -------------------------------------------------------------------------
1232
+ /** Look up cached tool annotations for permission enforcement. */
1233
+ getToolAnnotations(appId, toolName) {
1234
+ const tools = this.toolsCache.get(appId);
1235
+ if (!tools)
1236
+ return undefined;
1237
+ const tool = tools.find((t) => t.name === toolName);
1238
+ return tool?.annotations;
1239
+ }
1240
+ /** Populate tool cache for an app (called after auto-init or announce). */
1241
+ cacheTools(appId, tools) {
1242
+ this.toolsCache.set(appId, tools);
1243
+ }
1244
+ // -------------------------------------------------------------------------
1245
+ // App discovery & static serving
1246
+ // -------------------------------------------------------------------------
1247
+ /**
1248
+ * GET /apps — JSON catalog of all registered apps.
1249
+ *
1250
+ * Returns a lightweight listing (id, version, name, description) suitable
1251
+ * for registries and launchers to discover what's running on this station.
1252
+ */
1253
+ handleAppCatalog(res) {
1254
+ const apps = [...this.managedApps.entries()].map(([id, m]) => ({
1255
+ id,
1256
+ version: m.entry.version,
1257
+ name: m.entry.name ?? id,
1258
+ description: m.entry.description,
1259
+ manifestUrl: `/apps/${id}/manifest`,
1260
+ ...(m.entry.sourcePath ? { bundlesUrl: `/apps/${id}/bundles` } : {}),
1261
+ }));
1262
+ json(res, 200, {
1263
+ stationId: this.stationId,
1264
+ apps,
1265
+ });
1266
+ }
1267
+ /**
1268
+ * GET /apps/:appId/manifest — full manifest JSON for an app.
1269
+ *
1270
+ * Serves the `agentapp.json` content (or the manifest passed via `AppEntry.manifest`).
1271
+ * Returns 404 if the app is not registered, and 404 with a helpful message
1272
+ * if the app was registered without a manifest.
1273
+ */
1274
+ handleAppManifest(res, appId) {
1275
+ const managed = this.managedApps.get(appId);
1276
+ if (!managed) {
1277
+ json(res, 404, { error: `App not found: ${appId}` });
1278
+ return;
1279
+ }
1280
+ if (!managed.entry.manifest) {
1281
+ json(res, 404, { error: `No manifest available for app: ${appId}` });
1282
+ return;
1283
+ }
1284
+ json(res, 200, managed.entry.manifest);
1285
+ }
1286
+ /**
1287
+ * GET /launcher — generic HTML launcher page.
1288
+ *
1289
+ * Renders an HTML page that reads each app's manifest, evaluates screen
1290
+ * conditions, and auto-opens the first eligible screen in an iframe.
1291
+ *
1292
+ * The page embeds manifest data as JSON so client-side JS can:
1293
+ * - Evaluate `condition` predicates on screens (e.g. 'authenticated', '!authenticated')
1294
+ * - Show/hide screens based on the current auth state
1295
+ * - Auto-open the first visible launcher screen
1296
+ * - Navigate between screens without a full page reload
1297
+ *
1298
+ * Screens without a `bundleUrl` are listed but not openable in the iframe.
1299
+ */
1300
+ handleLauncher(res, req) {
1301
+ const baseUrl = this.getBaseUrl(req);
1302
+ // Build a serializable catalog: one entry per app with its launcher screens
1303
+ const catalog = [...this.managedApps.values()].map((m) => {
1304
+ const manifest = m.entry.manifest;
1305
+ const appId = m.entry.id;
1306
+ const name = m.entry.name ?? appId;
1307
+ const description = m.entry.description ?? '';
1308
+ const screens = manifest?.screens ?? [];
1309
+ const launcherScreens = screens
1310
+ .filter((s) => s.launcher === true)
1311
+ .map((s) => {
1312
+ const bundleUrl = s.bundleUrl;
1313
+ const resolvedUrl = bundleUrl ? resolveBundleLink(bundleUrl, appId, baseUrl) : null;
1314
+ return {
1315
+ name: String(s.name ?? ''),
1316
+ title: String(s.title ?? s.name ?? ''),
1317
+ description: s.description != null ? String(s.description) : undefined,
1318
+ icon: s.icon != null ? String(s.icon) : undefined,
1319
+ condition: s.condition != null ? String(s.condition) : undefined,
1320
+ bundleUrl: resolvedUrl,
1321
+ manifestUrl: `${baseUrl}/apps/${encodeURIComponent(appId)}/manifest`,
1322
+ };
1323
+ });
1324
+ return {
1325
+ id: appId,
1326
+ name,
1327
+ description,
1328
+ manifestUrl: `${baseUrl}/apps/${encodeURIComponent(appId)}/manifest`,
1329
+ screens: launcherScreens,
1330
+ };
1331
+ });
1332
+ // Pre-render the app cards for no-JS fallback and SEO
1333
+ const cardsHtml = catalog.length > 0
1334
+ ? catalog
1335
+ .map((app) => {
1336
+ if (app.screens.length === 0) {
1337
+ return ` <div class="app-card" data-app-id="${escapeHtml(app.id)}">
1338
+ <h3>${escapeHtml(app.name)}</h3>
1339
+ <p class="desc">${escapeHtml(app.description)}</p>
1340
+ <a href="${escapeHtml(app.manifestUrl)}" class="btn">Manifest</a>
1341
+ </div>`;
1342
+ }
1343
+ const screenButtons = app.screens
1344
+ .map((s) => {
1345
+ const condAttr = s.condition
1346
+ ? ` data-condition="${escapeHtml(s.condition)}"`
1347
+ : '';
1348
+ const urlAttr = s.bundleUrl
1349
+ ? ` data-bundle-url="${escapeHtml(s.bundleUrl)}"`
1350
+ : '';
1351
+ return ` <a href="${s.bundleUrl ?? '#'}" class="btn screen-btn" data-screen="${escapeHtml(s.name)}"${condAttr}${urlAttr}>${escapeHtml(s.title)}</a>`;
1352
+ })
1353
+ .join('\n');
1354
+ return ` <div class="app-card" data-app-id="${escapeHtml(app.id)}">
1355
+ <h3>${escapeHtml(app.name)}</h3>
1356
+ <p class="desc">${escapeHtml(app.description)}</p>
1357
+ <div class="screens">
1358
+ ${screenButtons}
1359
+ </div>
1360
+ <a href="${escapeHtml(app.manifestUrl)}" class="btn secondary">Manifest</a>
1361
+ </div>`;
1362
+ })
1363
+ .join('\n')
1364
+ : ' <p class="empty">No apps registered on this station.</p>';
1365
+ const catalogJson = JSON.stringify(catalog).replace(/</g, '\\u003c');
1366
+ const html = `<!DOCTYPE html>
1367
+ <html lang="en">
1368
+ <head>
1369
+ <meta charset="UTF-8">
1370
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1371
+ <title>Agent Apps Station — Launcher</title>
1372
+ <style>
1373
+ * { margin: 0; padding: 0; box-sizing: border-box; }
1374
+ body {
1375
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
1376
+ background: #0a0a0f;
1377
+ color: #fafafa;
1378
+ min-height: 100vh;
1379
+ display: flex;
1380
+ flex-direction: column;
1381
+ }
1382
+ .header {
1383
+ padding: 1rem 2rem;
1384
+ border-bottom: 1px solid #27272a;
1385
+ display: flex;
1386
+ align-items: center;
1387
+ justify-content: space-between;
1388
+ flex-wrap: wrap;
1389
+ gap: 0.5rem;
1390
+ }
1391
+ .header h1 { font-size: 1.3rem; }
1392
+ .subtitle { color: #a1a1aa; font-size: 0.8rem; }
1393
+ .toolbar { display: flex; align-items: center; gap: 0.75rem; }
1394
+ .auth-toggle {
1395
+ display: flex;
1396
+ align-items: center;
1397
+ gap: 0.4rem;
1398
+ font-size: 0.8rem;
1399
+ color: #a1a1aa;
1400
+ cursor: pointer;
1401
+ user-select: none;
1402
+ }
1403
+ .auth-toggle input { cursor: pointer; }
1404
+ .main {
1405
+ display: flex;
1406
+ flex: 1;
1407
+ overflow: hidden;
1408
+ }
1409
+ .sidebar {
1410
+ width: 320px;
1411
+ min-width: 280px;
1412
+ max-width: 400px;
1413
+ border-right: 1px solid #27272a;
1414
+ padding: 1.5rem;
1415
+ overflow-y: auto;
1416
+ }
1417
+ .sidebar h2 { font-size: 0.9rem; color: #a1a1aa; margin-bottom: 1rem; text-transform: uppercase; letter-spacing: 0.05em; }
1418
+ .grid {
1419
+ display: flex;
1420
+ flex-direction: column;
1421
+ gap: 1rem;
1422
+ }
1423
+ .app-card {
1424
+ background: #18181b;
1425
+ border: 1px solid #27272a;
1426
+ border-radius: 12px;
1427
+ padding: 1.25rem;
1428
+ }
1429
+ .app-card h3 { font-size: 1.1rem; margin-bottom: 0.5rem; }
1430
+ .desc { color: #a1a1aa; font-size: 0.85rem; margin-bottom: 1rem; line-height: 1.4; }
1431
+ .screens { display: flex; flex-direction: column; gap: 0.5rem; margin-bottom: 0.75rem; }
1432
+ .btn {
1433
+ display: inline-block;
1434
+ padding: 0.5rem 1rem;
1435
+ border-radius: 8px;
1436
+ font-size: 0.85rem;
1437
+ text-decoration: none;
1438
+ transition: background 0.15s, opacity 0.15s;
1439
+ cursor: pointer;
1440
+ border: none;
1441
+ }
1442
+ .btn:link, .btn:visited { color: #fafafa; }
1443
+ .btn { background: #5e6ad2; }
1444
+ .btn:hover { background: #4f5ab8; }
1445
+ .btn.secondary { background: #27272a; }
1446
+ .btn.secondary:hover { background: #3f3f46; }
1447
+ .btn.screen-btn { width: 100%; text-align: center; }
1448
+ .btn.screen-btn.active { background: #4f5ab8; box-shadow: 0 0 0 2px #5e6ad2; }
1449
+ .btn.screen-btn.hidden { display: none; }
1450
+ .btn.screen-btn.disabled { opacity: 0.4; cursor: default; pointer-events: none; }
1451
+ .empty { color: #a1a1aa; font-style: italic; }
1452
+ .content {
1453
+ flex: 1;
1454
+ position: relative;
1455
+ background: #18181b;
1456
+ }
1457
+ .content iframe {
1458
+ width: 100%;
1459
+ height: 100%;
1460
+ border: none;
1461
+ }
1462
+ .placeholder {
1463
+ position: absolute;
1464
+ inset: 0;
1465
+ display: flex;
1466
+ align-items: center;
1467
+ justify-content: center;
1468
+ color: #52525b;
1469
+ font-size: 1rem;
1470
+ text-align: center;
1471
+ padding: 2rem;
1472
+ }
1473
+ .placeholder.hidden { display: none; }
1474
+ .screen-header {
1475
+ padding: 0.75rem 1.5rem;
1476
+ border-bottom: 1px solid #27272a;
1477
+ font-size: 0.85rem;
1478
+ color: #a1a1aa;
1479
+ display: flex;
1480
+ align-items: center;
1481
+ justify-content: space-between;
1482
+ }
1483
+ .screen-header .screen-title { color: #fafafa; font-weight: 600; }
1484
+ .screen-header a { color: #5e6ad2; text-decoration: none; font-size: 0.8rem; }
1485
+ .screen-header a:hover { text-decoration: underline; }
1486
+ @media (max-width: 768px) {
1487
+ .main { flex-direction: column; }
1488
+ .sidebar { width: 100%; max-width: none; border-right: none; border-bottom: 1px solid #27272a; max-height: 40vh; }
1489
+ }
1490
+ </style>
1491
+ </head>
1492
+ <body>
1493
+ <div class="header">
1494
+ <div>
1495
+ <h1>\u{1F680} Agent Apps Station</h1>
1496
+ <p class="subtitle">Station ID: ${escapeHtml(this.stationId)}</p>
1497
+ </div>
1498
+ <div class="toolbar">
1499
+ <label class="auth-toggle">
1500
+ <input type="checkbox" id="auth-state" />
1501
+ Authenticated
1502
+ </label>
1503
+ </div>
1504
+ </div>
1505
+ <div class="main">
1506
+ <div class="sidebar">
1507
+ <h2>Apps &amp; Screens</h2>
1508
+ <div class="grid" id="app-grid">
1509
+ ${cardsHtml}
1510
+ </div>
1511
+ </div>
1512
+ <div class="content">
1513
+ <div class="screen-header" id="screen-header" style="display:none;">
1514
+ <span class="screen-title" id="screen-title"></span>
1515
+ <a href="#" id="screen-manifest-link" target="_blank">View manifest</a>
1516
+ </div>
1517
+ <div class="placeholder" id="placeholder">
1518
+ Select a screen to open it, or the first eligible screen will open automatically.
1519
+ </div>
1520
+ <iframe id="screen-frame" sandbox="allow-scripts allow-same-origin allow-forms allow-popups" style="display:none;"></iframe>
1521
+ </div>
1522
+ </div>
1523
+ <script id="catalog-data" type="application/json">${catalogJson}</script>
1524
+ <script>
1525
+ (function() {
1526
+ var catalog = JSON.parse(document.getElementById('catalog-data').textContent);
1527
+ var authCheckbox = document.getElementById('auth-state');
1528
+ var screenFrame = document.getElementById('screen-frame');
1529
+ var placeholder = document.getElementById('placeholder');
1530
+ var screenHeader = document.getElementById('screen-header');
1531
+ var screenTitle = document.getElementById('screen-title');
1532
+ var screenManifestLink = document.getElementById('screen-manifest-link');
1533
+ var currentScreen = null;
1534
+
1535
+ // --- Condition evaluation ---
1536
+ // Supports simple predicates: 'authenticated', '!authenticated'
1537
+ // Negation is indicated by a leading '!'.
1538
+ function evaluateCondition(condition, context) {
1539
+ if (!condition) return true;
1540
+ var negated = condition.charAt(0) === '!';
1541
+ var key = negated ? condition.slice(1) : condition;
1542
+ var value = context[key] || false;
1543
+ return negated ? !value : value;
1544
+ }
1545
+
1546
+ function getAuthContext() {
1547
+ return { authenticated: authCheckbox.checked };
1548
+ }
1549
+
1550
+ // --- Screen visibility ---
1551
+ function updateScreenVisibility() {
1552
+ var ctx = getAuthContext();
1553
+ var buttons = document.querySelectorAll('.screen-btn');
1554
+ for (var i = 0; i < buttons.length; i++) {
1555
+ var btn = buttons[i];
1556
+ var condition = btn.getAttribute('data-condition');
1557
+ var visible = evaluateCondition(condition, ctx);
1558
+ if (visible) {
1559
+ btn.classList.remove('hidden');
1560
+ } else {
1561
+ btn.classList.add('hidden');
1562
+ btn.classList.remove('active');
1563
+ }
1564
+ }
1565
+ // If the currently displayed screen is now hidden, close it
1566
+ if (currentScreen && currentScreen.condition) {
1567
+ if (!evaluateCondition(currentScreen.condition, ctx)) {
1568
+ closeScreen();
1569
+ }
1570
+ }
1571
+ // Auto-open the first visible screen if nothing is open
1572
+ if (!currentScreen) {
1573
+ autoOpenFirstScreen();
1574
+ }
1575
+ }
1576
+
1577
+ // --- Screen opening ---
1578
+ function openScreen(app, screen) {
1579
+ if (!screen.bundleUrl) return;
1580
+ currentScreen = screen;
1581
+ screenFrame.src = screen.bundleUrl;
1582
+ screenFrame.style.display = 'block';
1583
+ placeholder.classList.add('hidden');
1584
+ screenHeader.style.display = 'flex';
1585
+ screenTitle.textContent = app.name + ' / ' + screen.title;
1586
+ screenManifestLink.href = app.manifestUrl;
1587
+ // Mark active button
1588
+ var buttons = document.querySelectorAll('.screen-btn');
1589
+ for (var i = 0; i < buttons.length; i++) {
1590
+ buttons[i].classList.remove('active');
1591
+ }
1592
+ var activeBtn = document.querySelector('.screen-btn[data-screen="' + cssEscape(screen.name) + '"]');
1593
+ if (activeBtn) activeBtn.classList.add('active');
1594
+ }
1595
+
1596
+ function closeScreen() {
1597
+ currentScreen = null;
1598
+ screenFrame.src = 'about:blank';
1599
+ screenFrame.style.display = 'none';
1600
+ placeholder.classList.remove('hidden');
1601
+ screenHeader.style.display = 'none';
1602
+ var buttons = document.querySelectorAll('.screen-btn');
1603
+ for (var i = 0; i < buttons.length; i++) {
1604
+ buttons[i].classList.remove('active');
1605
+ }
1606
+ }
1607
+
1608
+ function autoOpenFirstScreen() {
1609
+ var ctx = getAuthContext();
1610
+ for (var i = 0; i < catalog.length; i++) {
1611
+ var app = catalog[i];
1612
+ for (var j = 0; j < app.screens.length; j++) {
1613
+ var screen = app.screens[j];
1614
+ if (screen.bundleUrl && evaluateCondition(screen.condition, ctx)) {
1615
+ openScreen(app, screen);
1616
+ return;
1617
+ }
1618
+ }
1619
+ }
1620
+ }
1621
+
1622
+ // --- CSS escape for attribute selectors ---
1623
+ function cssEscape(str) {
1624
+ return str.replace(/["\\\\]/g, '\\\\$&');
1625
+ }
1626
+
1627
+ // --- Event wiring ---
1628
+ // Click handler for screen buttons
1629
+ document.addEventListener('click', function(e) {
1630
+ var btn = e.target.closest('.screen-btn');
1631
+ if (!btn) return;
1632
+ e.preventDefault();
1633
+ var screenName = btn.getAttribute('data-screen');
1634
+ var bundleUrl = btn.getAttribute('data-bundle-url');
1635
+ if (!bundleUrl || bundleUrl === '#') return;
1636
+ // Find the screen in the catalog
1637
+ for (var i = 0; i < catalog.length; i++) {
1638
+ var app = catalog[i];
1639
+ for (var j = 0; j < app.screens.length; j++) {
1640
+ if (app.screens[j].name === screenName) {
1641
+ openScreen(app, app.screens[j]);
1642
+ return;
1643
+ }
1644
+ }
1645
+ }
1646
+ });
1647
+
1648
+ // Auth state toggle
1649
+ authCheckbox.addEventListener('change', updateScreenVisibility);
1650
+
1651
+ // --- Initial render ---
1652
+ // Mark buttons without bundleUrl as disabled
1653
+ var buttons = document.querySelectorAll('.screen-btn');
1654
+ for (var i = 0; i < buttons.length; i++) {
1655
+ var url = buttons[i].getAttribute('data-bundle-url');
1656
+ if (!url || url === '#') {
1657
+ buttons[i].classList.add('disabled');
1658
+ }
1659
+ }
1660
+ updateScreenVisibility();
1661
+ })();
1662
+ </script>
1663
+ </body>
1664
+ </html>`;
1665
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
1666
+ res.end(html);
1667
+ }
1668
+ /**
1669
+ * GET /apps/:appId/bundles/* — serve static files from the app's source directory.
1670
+ *
1671
+ * The path after `/bundles/` is resolved relative to the app's `sourcePath`.
1672
+ * Path traversal is prevented by normalizing and checking the resolved path
1673
+ * stays within the source directory.
1674
+ */
1675
+ handleStaticBundle(res, appId, relativePath) {
1676
+ const managed = this.managedApps.get(appId);
1677
+ if (!managed) {
1678
+ json(res, 404, { error: `App not found: ${appId}` });
1679
+ return;
1680
+ }
1681
+ const sourcePath = managed.entry.sourcePath;
1682
+ if (!sourcePath) {
1683
+ json(res, 404, { error: `No source path configured for app: ${appId}` });
1684
+ return;
1685
+ }
1686
+ // Decode URL-encoded path and normalize
1687
+ const decoded = decodeURIComponent(relativePath);
1688
+ const safePath = this.resolveSafePath(sourcePath, decoded);
1689
+ if (!safePath) {
1690
+ json(res, 403, { error: 'Path traversal denied' });
1691
+ return;
1692
+ }
1693
+ if (!existsSync(safePath) || !statSync(safePath).isFile()) {
1694
+ json(res, 404, { error: `File not found: ${decoded}` });
1695
+ return;
1696
+ }
1697
+ const mimeType = getMimeType(safePath);
1698
+ const stat = statSync(safePath);
1699
+ res.writeHead(200, {
1700
+ 'Content-Type': mimeType,
1701
+ 'Content-Length': stat.size,
1702
+ 'Cache-Control': 'no-cache',
1703
+ });
1704
+ createReadStream(safePath).pipe(res);
1705
+ }
1706
+ /**
1707
+ * GET /objects/{id}[?token=…]
1708
+ *
1709
+ * - Public object → 200, permanent.
1710
+ * - Private object with a valid signed link token for that id → 200.
1711
+ * - Private object without a valid token → 401.
1712
+ * - Unknown id → 404.
1713
+ * Cache-Control: no-cache, so an expired link is not served from a cache.
1714
+ */
1715
+ async handleObjectRequest(res, objectId, token) {
1716
+ const outcome = await this.objects().resolveForServing(objectId, token);
1717
+ if (outcome.status !== 200) {
1718
+ json(res, outcome.status, { error: outcome.error });
1719
+ return;
1720
+ }
1721
+ if (!existsSync(outcome.path) || !statSync(outcome.path).isFile()) {
1722
+ json(res, 404, { error: 'Object not found' });
1723
+ return;
1724
+ }
1725
+ const headers = {
1726
+ 'Content-Type': outcome.meta.contentType,
1727
+ 'Content-Length': statSync(outcome.path).size,
1728
+ 'Cache-Control': 'no-cache',
1729
+ };
1730
+ if (outcome.meta.filename) {
1731
+ headers['Content-Disposition'] =
1732
+ `inline; filename="${outcome.meta.filename.replace(/["\\]/g, '')}"`;
1733
+ }
1734
+ res.writeHead(200, headers);
1735
+ createReadStream(outcome.path).pipe(res);
1736
+ }
1737
+ /**
1738
+ * Resolve a relative path against a base directory, ensuring the result
1739
+ * stays within the base. Returns null if the path escapes the base.
1740
+ */
1741
+ resolveSafePath(baseDir, relPath) {
1742
+ const base = resolve(baseDir);
1743
+ const normalized = normalize(relPath);
1744
+ // Reject absolute paths and parent traversal attempts
1745
+ if (normalized.startsWith('..') || normalized.startsWith(`${sep}..`)) {
1746
+ return null;
1747
+ }
1748
+ const target = join(base, normalized);
1749
+ const rel = relative(base, target);
1750
+ // If the relative path starts with '..', the target is outside base
1751
+ if (rel.startsWith('..') || rel === '') {
1752
+ // rel === '' means the target IS the base dir itself — allow only if it's a file
1753
+ if (rel === '' && existsSync(target) && statSync(target).isFile()) {
1754
+ return target;
1755
+ }
1756
+ if (rel.startsWith('..'))
1757
+ return null;
1758
+ }
1759
+ return target;
1760
+ }
1761
+ /**
1762
+ * Determine the base URL for building absolute links in the launcher.
1763
+ * Uses `publicUrl` if configured, otherwise falls back to request headers.
1764
+ */
1765
+ getBaseUrl(req) {
1766
+ if (this.publicUrl) {
1767
+ return this.publicUrl.replace(/\/+$/, '');
1768
+ }
1769
+ const proto = req.headers['x-forwarded-proto'] ?? 'http';
1770
+ const host = req.headers['x-forwarded-host'] ?? req.headers.host;
1771
+ if (host)
1772
+ return `${proto}://${host}`;
1773
+ const port = this._info?.port ?? this.defaultPort;
1774
+ return `http://localhost:${port}`;
1775
+ }
1776
+ // -------------------------------------------------------------------------
1777
+ // Management API
1778
+ // -------------------------------------------------------------------------
1779
+ /**
1780
+ * Pending Approvals for the Approver (POLICY-REQ-7): `GET /approvals` lists
1781
+ * them and `POST /approvals/{id}` with `{ decision: 'approve' | 'deny' }`
1782
+ * decides one. Only the `admin` Principal may answer; an open station has
1783
+ * no other caller.
1784
+ *
1785
+ * @spec POLICY-REQ-7
1786
+ */
1787
+ async handleApprovals(req, res, url, authResult) {
1788
+ const principalId = authResult?.principalId ?? ADMIN_PRINCIPAL_ID;
1789
+ if (principalId !== ADMIN_PRINCIPAL_ID) {
1790
+ json(res, 403, { error: 'Only the Approver can answer approvals' });
1791
+ return;
1792
+ }
1793
+ if (!this.approvalManager) {
1794
+ json(res, 404, { error: 'Approvals not configured' });
1795
+ return;
1796
+ }
1797
+ const method = req.method ?? 'GET';
1798
+ // @spec POLICY-REQ-7
1799
+ if (url === '/approvals' && method === 'GET') {
1800
+ json(res, 200, { approvals: this.approvalManager.listPending() });
1801
+ return;
1802
+ }
1803
+ const match = url.match(/^\/approvals\/([^/]+)$/);
1804
+ if (match && method === 'POST') {
1805
+ const body = JSON.parse(await readBody(req));
1806
+ if (body.decision !== 'approve' && body.decision !== 'deny') {
1807
+ json(res, 400, { error: "Field 'decision' must be 'approve' or 'deny'" });
1808
+ return;
1809
+ }
1810
+ if (!this.approvalManager.decide(match[1], body.decision, principalId)) {
1811
+ json(res, 404, { error: 'Approval not found, already decided or expired' });
1812
+ return;
1813
+ }
1814
+ json(res, 200, { decided: true, decision: body.decision });
1815
+ return;
1816
+ }
1817
+ json(res, 404, { error: `Not found: ${method} ${url}` });
1818
+ }
1819
+ async handleManagementApi(req, res, url, _authResult) {
1820
+ const method = req.method ?? 'GET';
1821
+ // --- API Keys CRUD ---
1822
+ if (url === '/api/keys' && method === 'GET') {
1823
+ if (!this.apiKeyStore) {
1824
+ json(res, 404, { error: 'API keys not configured' });
1825
+ return;
1826
+ }
1827
+ const keys = await this.apiKeyStore.list();
1828
+ json(res, 200, { keys });
1829
+ return;
1830
+ }
1831
+ if (url === '/api/keys' && method === 'POST') {
1832
+ if (!this.apiKeyStore) {
1833
+ json(res, 404, { error: 'API keys not configured' });
1834
+ return;
1835
+ }
1836
+ const body = JSON.parse(await readBody(req));
1837
+ const { raw, hash, prefix } = generateApiKeyPair();
1838
+ const now = new Date().toISOString();
1839
+ const id = `ak_${randomId()}`;
1840
+ const record = {
1841
+ id,
1842
+ name: body.name,
1843
+ keyHash: hash,
1844
+ prefix,
1845
+ identity: body.identity ?? { userId: body.userId ?? 'anonymous' },
1846
+ // POLICY-REQ-1: each key is its own Principal unless it names one.
1847
+ principalId: body.principalId ?? id,
1848
+ createdAt: now,
1849
+ updatedAt: now,
1850
+ expiresAt: body.expiresAt,
1851
+ };
1852
+ await this.apiKeyStore.create(record);
1853
+ // Return raw key exactly once
1854
+ json(res, 201, { ...record, key: raw });
1855
+ return;
1856
+ }
1857
+ const keyMatch = url.match(/^\/api\/keys\/([^/]+)$/);
1858
+ if (keyMatch && method === 'DELETE') {
1859
+ if (!this.apiKeyStore) {
1860
+ json(res, 404, { error: 'API keys not configured' });
1861
+ return;
1862
+ }
1863
+ const revoked = await this.apiKeyStore.revoke(keyMatch[1]);
1864
+ if (!revoked) {
1865
+ json(res, 404, { error: 'Key not found' });
1866
+ return;
1867
+ }
1868
+ json(res, 200, { revoked: true });
1869
+ return;
1870
+ }
1871
+ json(res, 404, { error: `Not found: ${method} ${url}` });
1872
+ }
1873
+ }
1874
+ // ---------------------------------------------------------------------------
1875
+ // Helpers
1876
+ // ---------------------------------------------------------------------------
1877
+ function randomId() {
1878
+ const bytes = new Uint8Array(8);
1879
+ crypto.getRandomValues(bytes);
1880
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
1881
+ }
1882
+ function generateApiKeyPair() {
1883
+ const bytes = new Uint8Array(16);
1884
+ crypto.getRandomValues(bytes);
1885
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
1886
+ const raw = `aak_${hex}`;
1887
+ const hash = hashApiKey(raw);
1888
+ return { raw, hash, prefix: raw.slice(0, 12) };
1889
+ }
1890
+ // ---------------------------------------------------------------------------
1891
+ // Static serving helpers
1892
+ // ---------------------------------------------------------------------------
1893
+ /** Escape HTML special characters to prevent injection in the launcher page. */
1894
+ function escapeHtml(str) {
1895
+ return str
1896
+ .replace(/&/g, '&amp;')
1897
+ .replace(/</g, '&lt;')
1898
+ .replace(/>/g, '&gt;')
1899
+ .replace(/"/g, '&quot;')
1900
+ .replace(/'/g, '&#39;');
1901
+ }
1902
+ /** MIME type lookup for common static file extensions. */
1903
+ function getMimeType(filePath) {
1904
+ const ext = filePath.slice(filePath.lastIndexOf('.') + 1).toLowerCase();
1905
+ const types = {
1906
+ html: 'text/html; charset=utf-8',
1907
+ htm: 'text/html; charset=utf-8',
1908
+ js: 'application/javascript; charset=utf-8',
1909
+ mjs: 'application/javascript; charset=utf-8',
1910
+ css: 'text/css; charset=utf-8',
1911
+ json: 'application/json; charset=utf-8',
1912
+ svg: 'image/svg+xml',
1913
+ png: 'image/png',
1914
+ jpg: 'image/jpeg',
1915
+ jpeg: 'image/jpeg',
1916
+ gif: 'image/gif',
1917
+ webp: 'image/webp',
1918
+ ico: 'image/x-icon',
1919
+ woff: 'font/woff',
1920
+ woff2: 'font/woff2',
1921
+ ttf: 'font/ttf',
1922
+ otf: 'font/otf',
1923
+ map: 'application/json; charset=utf-8',
1924
+ txt: 'text/plain; charset=utf-8',
1925
+ wasm: 'application/wasm',
1926
+ pdf: 'application/pdf',
1927
+ };
1928
+ return types[ext] ?? 'application/octet-stream';
1929
+ }
1930
+ /**
1931
+ * Resolve a screen's `bundleUrl` into a link the launcher can use.
1932
+ *
1933
+ * If the bundleUrl is a relative path (e.g. `dist/screen.js`), it's served
1934
+ * through the station's `/apps/:appId/bundles/` route. If it's an absolute
1935
+ * URL (http/https), it's used as-is.
1936
+ */
1937
+ function resolveBundleLink(bundleUrl, appId, baseUrl) {
1938
+ // Absolute URLs are used directly
1939
+ if (bundleUrl.startsWith('http://') || bundleUrl.startsWith('https://')) {
1940
+ return bundleUrl;
1941
+ }
1942
+ // Relative paths are served through the station's bundle route
1943
+ const cleanPath = bundleUrl.replace(/^\.?\//, '');
1944
+ return `${baseUrl}/apps/${encodeURIComponent(appId)}/bundles/${cleanPath}`;
1945
+ }
1946
+ // ---------------------------------------------------------------------------
1947
+ // Convenience
1948
+ // ---------------------------------------------------------------------------
1949
+ export async function serve(options) {
1950
+ const server = new StationServer(options);
1951
+ await server.start();
1952
+ return server;
1953
+ }
1954
+ //# sourceMappingURL=server.js.map