@di-framework/cli-plugin-platform 6.0.3 → 6.0.5

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 (69) hide show
  1. package/README.md +196 -21
  2. package/dist/args.d.ts +2 -1
  3. package/dist/args.js +9 -5
  4. package/dist/assets/http-adapter.js +63 -0
  5. package/dist/assets/platform/README.md +22 -6
  6. package/dist/assets/sqlite/BUILD-INFO.txt +1 -1
  7. package/dist/assets/wit/deps/wasi-clocks-0.2.12/package.wit +43 -0
  8. package/dist/assets/wit/deps/wasi-filesystem-0.2.12/package.wit +196 -0
  9. package/dist/assets/wit/deps/wasi-io-0.2.12/package.wit +66 -0
  10. package/dist/assets/wit/deps/wasi-logging/package.wit +36 -0
  11. package/dist/build.d.ts +3 -1
  12. package/dist/build.js +4 -2
  13. package/dist/command.js +31 -13
  14. package/dist/console/auth.d.ts +20 -0
  15. package/dist/console/auth.js +82 -0
  16. package/dist/console/catalog.d.ts +196 -0
  17. package/dist/console/catalog.js +821 -0
  18. package/dist/console/cluster.d.ts +30 -0
  19. package/dist/console/cluster.js +299 -0
  20. package/dist/console/errors.d.ts +10 -0
  21. package/dist/console/errors.js +32 -0
  22. package/dist/console/run.d.ts +18 -0
  23. package/dist/console/run.js +102 -0
  24. package/dist/console/server.d.ts +25 -0
  25. package/dist/console/server.js +668 -0
  26. package/dist/console/services.d.ts +47 -0
  27. package/dist/console/services.js +111 -0
  28. package/dist/console-ui/app.css +1 -0
  29. package/dist/console-ui/app.js +260 -0
  30. package/dist/console-ui/di-framework-mark.png +0 -0
  31. package/dist/console-ui/index.html +13 -0
  32. package/dist/deps.d.ts +2 -0
  33. package/dist/deps.js +5 -3
  34. package/dist/dev.js +10 -5
  35. package/dist/egress.d.ts +40 -0
  36. package/dist/egress.js +214 -0
  37. package/dist/host-interface.js +2 -1
  38. package/dist/index.d.ts +1 -0
  39. package/dist/index.js +1 -0
  40. package/dist/manifest.d.ts +7 -0
  41. package/dist/manifest.js +35 -8
  42. package/dist/node-compat/console.d.ts +18 -0
  43. package/dist/node-compat/console.js +42 -0
  44. package/dist/node-compat/env.js +6 -0
  45. package/dist/node-compat/events.d.ts +20 -0
  46. package/dist/node-compat/events.js +55 -0
  47. package/dist/node-compat/fetch-runtime.d.ts +31 -0
  48. package/dist/node-compat/fetch-runtime.js +62 -0
  49. package/dist/node-compat/fs-promises.d.ts +30 -0
  50. package/dist/node-compat/fs-promises.js +3 -0
  51. package/dist/node-compat/fs.d.ts +79 -0
  52. package/dist/node-compat/fs.js +112 -5
  53. package/dist/node-compat/net.d.ts +2 -1
  54. package/dist/node-compat/net.js +3 -1
  55. package/dist/node-compat/storage.d.ts +87 -0
  56. package/dist/node-compat/storage.js +244 -0
  57. package/dist/node-compat/stream.d.ts +24 -0
  58. package/dist/node-compat/stream.js +70 -0
  59. package/dist/platform.js +2 -4
  60. package/dist/project.d.ts +5 -0
  61. package/dist/project.js +4 -0
  62. package/dist/service.d.ts +21 -2
  63. package/dist/service.js +71 -5
  64. package/dist/target.js +6 -1
  65. package/dist/wit.d.ts +8 -0
  66. package/dist/wit.js +28 -0
  67. package/dist/workload.d.ts +45 -0
  68. package/dist/workload.js +98 -26
  69. package/package.json +14 -4
@@ -0,0 +1,668 @@
1
+ import { createReadStream, existsSync, statSync } from 'node:fs';
2
+ import { createServer } from 'node:http';
3
+ import { extname, join, normalize, sep } from 'node:path';
4
+ import { isCommandFailure } from '@di-framework/cli-extension';
5
+ import { loadDeployManifest } from '../manifest.js';
6
+ import { isBackingServiceName, isServiceType, SERVICE_TYPES } from '../service.js';
7
+ import { resolveConnection, resolveTarget } from '../target.js';
8
+ import { CSRF_HEADER, createSessionStore, readCookie, SESSION_COOKIE, SESSION_TTL_MS, sessionCookie, tokensMatch, } from './auth.js';
9
+ import { assertResourceName, planEnvironmentDelete, planEnvironmentSet, planRouteUpdate, planSecretReassign, summarizeApplications, tenantIdentity, toSummary, withRouteUrls, withServiceClasses, workloadInTenantScope, } from './catalog.js';
10
+ import { createKubectlConsoleCluster, } from './cluster.js';
11
+ import { ConsoleError, platformSentence, sanitizePublicText } from './errors.js';
12
+ import { createCliConsoleServices, } from './services.js';
13
+ const SECURITY_HEADERS = {
14
+ 'content-security-policy': "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'; object-src 'none'",
15
+ 'x-content-type-options': 'nosniff',
16
+ 'x-frame-options': 'DENY',
17
+ 'referrer-policy': 'no-referrer',
18
+ 'permissions-policy': 'camera=(), microphone=(), geolocation=()',
19
+ 'cross-origin-resource-policy': 'same-origin',
20
+ 'cross-origin-opener-policy': 'same-origin',
21
+ 'cache-control': 'no-store',
22
+ };
23
+ const ASSET_EXTENSIONS = new Set([
24
+ '.js',
25
+ '.css',
26
+ '.map',
27
+ '.woff',
28
+ '.woff2',
29
+ '.ttf',
30
+ '.svg',
31
+ '.png',
32
+ ]);
33
+ const MAX_BODY_BYTES = 65_536;
34
+ const WRITES_FORBIDDEN = 'This credential cannot change the application.';
35
+ export function startConsoleServer(options) {
36
+ const log = (line) => options.io?.stderr.write(`${line}\n`);
37
+ const cluster = options.cluster ?? createKubectlConsoleCluster(options.deps, log);
38
+ const services = options.services ?? createCliConsoleServices(options.deps, options.io ?? silentIo());
39
+ const sessions = createSessionStore();
40
+ const now = options.now ?? Date.now;
41
+ const connections = new Map();
42
+ const writers = new Map();
43
+ const server = createServer((request, response) => {
44
+ void handle(request, response, {
45
+ ...options,
46
+ cluster,
47
+ services,
48
+ sessions,
49
+ now,
50
+ connections,
51
+ writers,
52
+ log,
53
+ }).catch((error) => {
54
+ log(sanitizePublicText(error instanceof Error ? error.message : 'console request failed'));
55
+ sendJson(response, 500, {
56
+ error: 'The console request failed.',
57
+ code: 'CONSOLE_REQUEST_FAILED',
58
+ });
59
+ });
60
+ });
61
+ return new Promise((resolve, reject) => {
62
+ server.once('error', reject);
63
+ server.listen(options.port, options.host, () => {
64
+ const address = server.address();
65
+ const port = typeof address === 'object' && address !== null ? address.port : options.port;
66
+ resolve({
67
+ port,
68
+ url: `http://${options.host}:${port}`,
69
+ close: () => new Promise((done, fail) => {
70
+ if (!server.listening) {
71
+ done();
72
+ return;
73
+ }
74
+ server.close((error) => (error ? fail(error) : done()));
75
+ }),
76
+ });
77
+ });
78
+ });
79
+ }
80
+ async function handle(request, response, options) {
81
+ const hostHeader = request.headers.host;
82
+ if (typeof hostHeader !== 'string' ||
83
+ !allowedHost(hostHeader, options.host, boundPort(request))) {
84
+ sendJson(response, 403, {
85
+ error: 'This host is not allowed to use the console.',
86
+ code: 'HOST_NOT_ALLOWED',
87
+ });
88
+ return;
89
+ }
90
+ const url = new URL(request.url ?? '/', `http://${hostHeader}`);
91
+ const method = request.method ?? 'GET';
92
+ if (method === 'GET' && (url.pathname === '/' || isSpaPath(url.pathname))) {
93
+ sendFile(response, join(options.assetsDirectory, 'index.html'), 'text/html; charset=utf-8');
94
+ return;
95
+ }
96
+ if (method === 'GET' && url.pathname.startsWith('/assets/')) {
97
+ const asset = resolveAsset(options.assetsDirectory, url.pathname.slice('/assets/'.length));
98
+ if (asset === undefined) {
99
+ sendJson(response, 404, { error: 'Not found', code: 'NOT_FOUND' });
100
+ return;
101
+ }
102
+ sendFile(response, asset.path, asset.type);
103
+ return;
104
+ }
105
+ if (!url.pathname.startsWith('/api/')) {
106
+ sendJson(response, 404, { error: 'Not found', code: 'NOT_FOUND' });
107
+ return;
108
+ }
109
+ try {
110
+ await routeApi(method, url, request, response, options);
111
+ }
112
+ catch (error) {
113
+ const mapped = publicError(error);
114
+ if (mapped.status >= 500) {
115
+ options.log(sanitizePublicText(error instanceof Error ? error.message : 'request failed'));
116
+ }
117
+ sendJson(response, mapped.status, mapped.body);
118
+ }
119
+ }
120
+ async function routeApi(method, url, request, response, options) {
121
+ if (method === 'GET' && url.pathname === '/api/session') {
122
+ await openSession(request, response, options);
123
+ return;
124
+ }
125
+ const session = options.sessions.read(readCookie(request.headers.cookie, SESSION_COOKIE), options.now());
126
+ if (session === undefined) {
127
+ sendJson(response, 401, {
128
+ error: 'Reload the console and try again.',
129
+ code: 'SESSION_REQUIRED',
130
+ });
131
+ return;
132
+ }
133
+ if (method !== 'GET' && method !== 'HEAD') {
134
+ requireOrigin(request);
135
+ const header = request.headers[CSRF_HEADER];
136
+ const provided = Array.isArray(header) ? header[0] : header;
137
+ if (!tokensMatch(provided, session.csrf)) {
138
+ throw new ConsoleError(403, 'CSRF_REJECTED', 'The form token does not match this page.');
139
+ }
140
+ await requireWrite(options);
141
+ }
142
+ if (method === 'GET' && url.pathname === '/api/applications') {
143
+ sendJson(response, 200, await listApplications(options));
144
+ return;
145
+ }
146
+ if (method === 'GET' && url.pathname === '/api/signals') {
147
+ sendJson(response, 200, await listSignals(options));
148
+ return;
149
+ }
150
+ if (method === 'GET' && url.pathname === '/api/backing-services') {
151
+ sendJson(response, 200, {
152
+ services: (await options.services.list(options.target)).map(publicService),
153
+ });
154
+ return;
155
+ }
156
+ if (method === 'POST' && url.pathname === '/api/backing-services') {
157
+ const input = parseServiceCreate(await readBody(request), options.target);
158
+ sendJson(response, 201, { service: publicService(await options.services.create(input)) });
159
+ return;
160
+ }
161
+ if (method === 'GET' && url.pathname === '/api/backing-service-classes') {
162
+ const listed = await options.services.classes(options.target);
163
+ sendJson(response, 200, {
164
+ classes: listed.classes.map((entry) => ({
165
+ name: entry.name,
166
+ type: entry.type,
167
+ default: entry.default,
168
+ })),
169
+ });
170
+ return;
171
+ }
172
+ const serviceName = namedPath(url.pathname, '/api/backing-services/');
173
+ if (serviceName !== undefined && method === 'DELETE') {
174
+ if (!isBackingServiceName(serviceName)) {
175
+ throw new ConsoleError(400, 'INVALID_NAME', 'Service name must use lowercase letters, digits, and hyphens.');
176
+ }
177
+ await options.services.delete(options.target, serviceName);
178
+ sendJson(response, 200, { name: serviceName });
179
+ return;
180
+ }
181
+ const application = applicationPath(url.pathname);
182
+ if (application === undefined) {
183
+ sendJson(response, 404, { error: 'Not found', code: 'NOT_FOUND' });
184
+ return;
185
+ }
186
+ assertResourceName(application.name, 'Application name');
187
+ await routeApplication(method, application.name, application.rest, request, response, options);
188
+ }
189
+ async function routeApplication(method, name, rest, request, response, options) {
190
+ if (rest.length === 0 && method === 'GET') {
191
+ sendJson(response, 200, { application: await present(options, name) });
192
+ return;
193
+ }
194
+ if (rest.length === 1 && rest[0] === 'logs' && method === 'GET') {
195
+ const loaded = await loadApplications(options);
196
+ requireApplication(loaded.applications, name);
197
+ sendJson(response, 200, await logsFor(options, loaded.connection, name));
198
+ return;
199
+ }
200
+ if (rest.length === 2 && rest[0] === 'routes' && method === 'PATCH') {
201
+ const body = recordBody(await readBody(request), ['enabled']);
202
+ if (typeof body.enabled !== 'boolean') {
203
+ throw new ConsoleError(400, 'INVALID_BODY', 'enabled must be true or false.');
204
+ }
205
+ const loaded = await loadApplications(options);
206
+ const members = membersOf(loaded, name);
207
+ const change = planRouteUpdate(members, rest[1] ?? '', body.enabled);
208
+ if (change.ops.length > 0)
209
+ await options.cluster.patchWorkload(loaded.connection, change.workload, change.ops);
210
+ sendJson(response, 200, { application: await present(options, name) });
211
+ return;
212
+ }
213
+ if (rest.length === 1 && rest[0] === 'environment' && method === 'PUT') {
214
+ const body = recordBody(await readBody(request), ['key', 'value', 'part']);
215
+ if (typeof body.key !== 'string' || typeof body.value !== 'string') {
216
+ throw new ConsoleError(400, 'INVALID_BODY', 'An environment variable needs a name and a value.');
217
+ }
218
+ if (body.part !== undefined && typeof body.part !== 'string') {
219
+ throw new ConsoleError(400, 'INVALID_BODY', 'part must be the name of a part.');
220
+ }
221
+ const loaded = await loadApplications(options);
222
+ const change = planEnvironmentSet(membersOf(loaded, name), body.key, body.value, body.part);
223
+ if (change.ops.length > 0)
224
+ await options.cluster.patchWorkload(loaded.connection, change.workload, change.ops);
225
+ sendJson(response, 200, { application: await present(options, name) });
226
+ return;
227
+ }
228
+ // DELETE environment/<key> removes the first match; environment/<part>/<key> names the part.
229
+ if ((rest.length === 2 || rest.length === 3) &&
230
+ rest[0] === 'environment' &&
231
+ method === 'DELETE') {
232
+ const loaded = await loadApplications(options);
233
+ const [part, key] = rest.length === 3 ? [rest[1], rest[2]] : [undefined, rest[1]];
234
+ const change = planEnvironmentDelete(membersOf(loaded, name), key ?? '', part);
235
+ await options.cluster.patchWorkload(loaded.connection, change.workload, change.ops);
236
+ sendJson(response, 200, { application: await present(options, name) });
237
+ return;
238
+ }
239
+ if (rest.length === 2 && rest[0] === 'secrets' && method === 'POST') {
240
+ const secretName = rest[1] ?? '';
241
+ const body = recordBody(await readBody(request), ['value']);
242
+ if (typeof body.value !== 'string') {
243
+ throw new ConsoleError(400, 'INVALID_SECRET', 'Provide a new credential value.');
244
+ }
245
+ const loaded = await loadApplications(options);
246
+ const planned = planSecretReassign(membersOf(loaded, name), secretName, body.value);
247
+ if ('secret' in planned)
248
+ await options.cluster.reassignSecret(loaded.connection, planned.secret, body.value);
249
+ else if (planned.ops.length > 0) {
250
+ await options.cluster.patchWorkload(loaded.connection, planned.workload, planned.ops);
251
+ }
252
+ sendJson(response, 200, { name: secretName });
253
+ return;
254
+ }
255
+ if (rest.length === 1 && rest[0] === 'bindings' && method === 'POST') {
256
+ const input = parseBind(await readBody(request), name);
257
+ const loaded = await loadApplications(options);
258
+ requireApplication(loaded.applications, name);
259
+ if (input.capability === 'egress')
260
+ input.workload = egressWorkload(membersOf(loaded, name));
261
+ await options.cluster.bindService(loaded.connection, input);
262
+ sendJson(response, 200, { application: await present(options, name) });
263
+ return;
264
+ }
265
+ if (rest.length === 2 && rest[0] === 'bindings' && method === 'DELETE') {
266
+ const loaded = await loadApplications(options);
267
+ const application = requireApplication(loaded.applications, name);
268
+ const binding = application.backingServices.find((entry) => entry.name === rest[1]);
269
+ if (binding === undefined) {
270
+ throw new ConsoleError(404, 'BINDING_NOT_FOUND', 'That backing service is not bound to this application.');
271
+ }
272
+ await options.cluster.unbindService(loaded.connection, name, binding.name);
273
+ sendJson(response, 200, { application: await present(options, name) });
274
+ return;
275
+ }
276
+ sendJson(response, 404, { error: 'Not found', code: 'NOT_FOUND' });
277
+ }
278
+ async function openSession(request, response, options) {
279
+ const now = options.now();
280
+ let current = options.sessions.read(readCookie(request.headers.cookie, SESSION_COOKIE), now);
281
+ if (current === undefined) {
282
+ const created = options.sessions.create(now);
283
+ current = created.session;
284
+ response.setHeader('set-cookie', sessionCookie(created.id, Math.floor(SESSION_TTL_MS / 1000)));
285
+ }
286
+ const connection = await connectionFor(options, options.target);
287
+ const identity = tenantIdentity(connection.hostgroup, options.target);
288
+ const writable = await writerFor(options, connection);
289
+ sendJson(response, 200, {
290
+ csrfToken: current.csrf,
291
+ writable,
292
+ tenant: identity.tenant,
293
+ ...(identity.hostgroup ? { hostgroup: identity.hostgroup } : {}),
294
+ });
295
+ }
296
+ async function listApplications(options) {
297
+ try {
298
+ const loaded = await loadApplications(options);
299
+ return { applications: loaded.applications.map(toSummary) };
300
+ }
301
+ catch (error) {
302
+ options.log(sanitizePublicText(error instanceof Error ? error.message : 'application query failed'));
303
+ const message = error instanceof ConsoleError ? error.message : 'The applications could not be read.';
304
+ return { applications: [], error: message };
305
+ }
306
+ }
307
+ /** Signals for every application in scope; an application whose projection fails is left out. */
308
+ async function listSignals(options) {
309
+ const loaded = await loadApplications(options);
310
+ const read = await Promise.all(loaded.applications.map(async (application) => {
311
+ try {
312
+ const signals = await options.cluster.readSignals(loaded.connection, application.name);
313
+ return signals ? { application: application.name, ...signals } : undefined;
314
+ }
315
+ catch (error) {
316
+ options.log(sanitizePublicText(error instanceof Error ? error.message : 'signal query failed'));
317
+ return undefined;
318
+ }
319
+ }));
320
+ return { signals: read.filter((entry) => entry !== undefined) };
321
+ }
322
+ async function present(options, name) {
323
+ const loaded = await loadApplications(options);
324
+ const application = requireApplication(loaded.applications, name);
325
+ const logs = await logsFor(options, loaded.connection, name);
326
+ const signals = await options.cluster.readSignals(loaded.connection, name);
327
+ const routes = application.routes.length === 0
328
+ ? application.routes
329
+ : withRouteUrls(application.routes, await options.cluster.readRouteTemplate(loaded.connection));
330
+ const backingServices = application.backingServices.length === 0
331
+ ? application.backingServices
332
+ : withServiceClasses(application.backingServices, await serviceClasses(options));
333
+ return withProjections({ ...application, routes, backingServices }, logs, signals);
334
+ }
335
+ /** Class of each backing service by name; empty when the services cannot be read. */
336
+ async function serviceClasses(options) {
337
+ try {
338
+ const listed = await options.services.list(options.target);
339
+ return new Map(listed.map((service) => [service.name, service.className]));
340
+ }
341
+ catch (error) {
342
+ options.log(sanitizePublicText(error instanceof Error ? error.message : 'service query failed'));
343
+ return new Map();
344
+ }
345
+ }
346
+ function withProjections(application, logs, signals) {
347
+ return { ...application, logs, ...(signals ? { signals } : {}) };
348
+ }
349
+ async function logsFor(options, connection, name) {
350
+ const lines = await options.cluster.readLogs(connection, name);
351
+ return lines === undefined
352
+ ? { unpublished: true }
353
+ : { lines: lines.map((line) => sanitizePublicText(line, 500)) };
354
+ }
355
+ async function loadApplications(options) {
356
+ const connection = await connectionFor(options, options.target);
357
+ const [documents, bindings, failures] = await Promise.all([
358
+ options.cluster.listWorkloads(connection),
359
+ options.cluster.listBindings(connection),
360
+ // Status without host failures is still useful; a projection read error is only logged.
361
+ options.cluster.readFailures(connection).catch((error) => {
362
+ options.log(sanitizePublicText(error instanceof Error ? error.message : 'failure query failed'));
363
+ return new Map();
364
+ }),
365
+ ]);
366
+ const scoped = documents.filter((document) => workloadInTenantScope(document, connection));
367
+ return {
368
+ connection,
369
+ documents: scoped,
370
+ applications: summarizeApplications(scoped, bindings, failures),
371
+ };
372
+ }
373
+ function membersOf(loaded, name) {
374
+ requireApplication(loaded.applications, name);
375
+ return loaded.documents.filter((document) => {
376
+ const workload = document.metadata?.labels?.['di-framework.dev/workload'];
377
+ return document.metadata?.name === name || workload === name;
378
+ });
379
+ }
380
+ function requireApplication(applications, name) {
381
+ const application = applications.find((entry) => entry.name === name);
382
+ if (application === undefined) {
383
+ throw new ConsoleError(404, 'APP_NOT_FOUND', `No application named ${name}.`);
384
+ }
385
+ return application;
386
+ }
387
+ async function requireWrite(options) {
388
+ const connection = await connectionFor(options, options.target);
389
+ if (!(await writerFor(options, connection))) {
390
+ throw new ConsoleError(403, 'WRITES_FORBIDDEN', WRITES_FORBIDDEN);
391
+ }
392
+ }
393
+ function writerFor(options, connection) {
394
+ const cached = options.writers.get(options.target);
395
+ if (cached !== undefined)
396
+ return cached;
397
+ const pending = options.cluster.canWrite(connection).catch((error) => {
398
+ options.log(sanitizePublicText(error instanceof Error ? error.message : 'write check failed'));
399
+ options.writers.delete(options.target);
400
+ return false;
401
+ });
402
+ options.writers.set(options.target, pending);
403
+ return pending;
404
+ }
405
+ function connectionFor(options, targetName) {
406
+ const cached = options.connections.get(targetName);
407
+ if (cached !== undefined)
408
+ return cached;
409
+ const manifest = loadDeployManifest(options.deps.cwd(), options.deps.env);
410
+ const selected = manifest.targets[targetName];
411
+ if (targetName !== options.target ||
412
+ selected?.kind !== 'external' ||
413
+ selected.hostgroup === undefined) {
414
+ throw new ConsoleError(404, 'TENANT_SCOPE', 'This console is scoped to one tenant.');
415
+ }
416
+ const target = resolveTarget(manifest, targetName);
417
+ const pending = resolveConnection(target, manifest.workspaceRoot, manifest.path, options.deps);
418
+ options.connections.set(target.name, pending);
419
+ pending.catch(() => options.connections.delete(target.name));
420
+ return pending;
421
+ }
422
+ function parseServiceCreate(body, target) {
423
+ const record = recordBody(body, ['type', 'name', 'className', 'memory', 'storage', 'cpu']);
424
+ if (typeof record.type !== 'string' || !isServiceType(record.type)) {
425
+ throw new ConsoleError(400, 'INVALID_SERVICE', `Service type must be one of ${SERVICE_TYPES.join(', ')}.`);
426
+ }
427
+ if (typeof record.name !== 'string' || !isBackingServiceName(record.name)) {
428
+ throw new ConsoleError(400, 'INVALID_NAME', 'Service name must use lowercase letters, digits, and hyphens.');
429
+ }
430
+ if (record.type === 'egress') {
431
+ throw new ConsoleError(400, 'INVALID_SERVICE', 'Egress services need destinations; create them with di-framework platform service create egress.');
432
+ }
433
+ const input = { target, type: record.type, name: record.name };
434
+ for (const key of ['className', 'memory', 'storage', 'cpu']) {
435
+ const value = record[key];
436
+ if (value === undefined)
437
+ continue;
438
+ if (typeof value !== 'string' || value.length === 0 || value.length > 40) {
439
+ throw new ConsoleError(400, 'INVALID_SERVICE', `${key} must be a short string.`);
440
+ }
441
+ if (key === 'className' && !isBackingServiceName(value)) {
442
+ throw new ConsoleError(400, 'INVALID_NAME', 'Class name must use lowercase letters, digits, and hyphens.');
443
+ }
444
+ input[key] = value;
445
+ }
446
+ return input;
447
+ }
448
+ /** Egress is granted to one WorkloadDeployment, so only a single-part application can bind it here. */
449
+ export function egressWorkload(members) {
450
+ const only = members.length === 1 ? members[0]?.metadata?.name : undefined;
451
+ if (only === undefined) {
452
+ throw new ConsoleError(409, 'EGRESS_PER_PART', 'Egress is granted per part; set allowedIpNameLookups in that part and deploy it.');
453
+ }
454
+ return only;
455
+ }
456
+ function parseBind(body, workload) {
457
+ const record = recordBody(body, ['binding', 'service', 'capability']);
458
+ if (typeof record.binding !== 'string' || !isBackingServiceName(record.binding, 54)) {
459
+ throw new ConsoleError(400, 'INVALID_NAME', 'Binding name must use lowercase letters, digits, and hyphens.');
460
+ }
461
+ if (typeof record.service !== 'string' || !isBackingServiceName(record.service)) {
462
+ throw new ConsoleError(400, 'INVALID_NAME', 'Service name must use lowercase letters, digits, and hyphens.');
463
+ }
464
+ if (typeof record.capability !== 'string' || !isServiceType(record.capability)) {
465
+ throw new ConsoleError(400, 'INVALID_SERVICE', `Service type must be one of ${SERVICE_TYPES.join(', ')}.`);
466
+ }
467
+ return {
468
+ workload,
469
+ binding: record.binding,
470
+ service: record.service,
471
+ capability: record.capability,
472
+ };
473
+ }
474
+ function recordBody(body, allowed) {
475
+ if (body === null || typeof body !== 'object' || Array.isArray(body)) {
476
+ throw new ConsoleError(400, 'INVALID_BODY', 'Request body must be an object.');
477
+ }
478
+ const record = body;
479
+ if (Object.keys(record).some((key) => !allowed.includes(key))) {
480
+ throw new ConsoleError(400, 'INVALID_BODY', 'The request contains unsupported fields.');
481
+ }
482
+ return record;
483
+ }
484
+ function applicationPath(pathname) {
485
+ if (!pathname.startsWith('/api/applications/'))
486
+ return undefined;
487
+ const tail = pathname.slice('/api/applications/'.length);
488
+ if (tail.length === 0)
489
+ return undefined;
490
+ const [rawName, ...rest] = tail.split('/');
491
+ if (rawName === undefined || rawName.length === 0 || rest.some((part) => part.length === 0))
492
+ return undefined;
493
+ try {
494
+ return {
495
+ name: decodeURIComponent(rawName),
496
+ rest: rest.map((part) => decodeURIComponent(part)),
497
+ };
498
+ }
499
+ catch {
500
+ return undefined;
501
+ }
502
+ }
503
+ function namedPath(pathname, prefix) {
504
+ if (!pathname.startsWith(prefix))
505
+ return undefined;
506
+ const rest = pathname.slice(prefix.length);
507
+ if (rest.length === 0 || rest.includes('/'))
508
+ return undefined;
509
+ try {
510
+ return decodeURIComponent(rest);
511
+ }
512
+ catch {
513
+ return undefined;
514
+ }
515
+ }
516
+ function requireOrigin(request) {
517
+ const origin = request.headers.origin;
518
+ const host = request.headers.host;
519
+ if (typeof origin !== 'string' || typeof host !== 'string' || origin !== `http://${host}`) {
520
+ throw new ConsoleError(403, 'ORIGIN_REJECTED', 'The request origin is not allowed.');
521
+ }
522
+ }
523
+ function allowedHost(hostHeader, bindHost, port) {
524
+ const normalized = hostHeader.trim().toLowerCase();
525
+ const names = new Set([`${bindHost.toLowerCase()}:${port}`]);
526
+ if (bindHost === '127.0.0.1' || bindHost === 'localhost' || bindHost === '::1') {
527
+ names.add(`127.0.0.1:${port}`);
528
+ names.add(`localhost:${port}`);
529
+ names.add(`[::1]:${port}`);
530
+ }
531
+ return names.has(normalized);
532
+ }
533
+ function boundPort(request) {
534
+ const address = request.socket.localPort;
535
+ return typeof address === 'number' ? address : 0;
536
+ }
537
+ async function readBody(request) {
538
+ const chunks = [];
539
+ let total = 0;
540
+ for await (const chunk of request) {
541
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
542
+ total += buffer.length;
543
+ if (total > MAX_BODY_BYTES) {
544
+ throw new ConsoleError(413, 'BODY_TOO_LARGE', 'The request body is too large.');
545
+ }
546
+ chunks.push(buffer);
547
+ }
548
+ if (chunks.length === 0)
549
+ return {};
550
+ try {
551
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));
552
+ }
553
+ catch {
554
+ throw new ConsoleError(400, 'INVALID_BODY', 'Request body must be JSON.');
555
+ }
556
+ }
557
+ function publicService(service) {
558
+ const ready = service.ready === 'True';
559
+ const detail = ready ? undefined : platformSentence(service.message);
560
+ return {
561
+ name: service.name,
562
+ className: service.className,
563
+ type: service.type,
564
+ ready,
565
+ ...(detail ? { detail } : {}),
566
+ };
567
+ }
568
+ function publicError(error) {
569
+ if (error instanceof ConsoleError) {
570
+ return { status: error.status, body: { error: error.message, code: error.code } };
571
+ }
572
+ if (isCommandFailure(error)) {
573
+ const status = error.code === 'WASMCLOUD_SERVICE_NOT_FOUND' || error.code === 'WASMCLOUD_TARGET_NOT_FOUND'
574
+ ? 404
575
+ : error.code === 'WASMCLOUD_SERVICE_ALREADY_EXISTS' ||
576
+ error.code === 'WASMCLOUD_SERVICE_IN_USE'
577
+ ? 409
578
+ : error.code === 'WASMCLOUD_SERVICE_UNAUTHORIZED'
579
+ ? 403
580
+ : error.exitCode === 2
581
+ ? 400
582
+ : 502;
583
+ return {
584
+ status,
585
+ body: { error: failureSentence(error.code, error.message, status), code: error.code },
586
+ };
587
+ }
588
+ return {
589
+ status: 502,
590
+ body: { error: 'The application could not be read.', code: 'REQUEST_FAILED' },
591
+ };
592
+ }
593
+ function failureSentence(code, message, status) {
594
+ if (code === 'WASMCLOUD_SERVICE_UNAUTHORIZED')
595
+ return 'This credential cannot change backing services.';
596
+ if (code === 'WASMCLOUD_SERVICE_NOT_FOUND')
597
+ return 'No backing service with that name.';
598
+ if (code === 'WASMCLOUD_TARGET_NOT_FOUND')
599
+ return 'This tenant could not be opened.';
600
+ if (code === 'WASMCLOUD_SERVICE_IN_USE')
601
+ return 'That backing service is still bound to an application.';
602
+ if (code === 'WASMCLOUD_SERVICE_ALREADY_EXISTS')
603
+ return 'A backing service with that name already exists.';
604
+ const sentence = platformSentence(message);
605
+ if (sentence !== undefined)
606
+ return sentence;
607
+ return status === 400 ? 'The request was not accepted.' : 'The request could not be completed.';
608
+ }
609
+ function sendJson(response, status, body) {
610
+ if (response.headersSent)
611
+ return;
612
+ response.writeHead(status, {
613
+ ...SECURITY_HEADERS,
614
+ 'content-type': 'application/json; charset=utf-8',
615
+ });
616
+ response.end(JSON.stringify(body));
617
+ }
618
+ function sendFile(response, path, contentType) {
619
+ if (!existsSync(path)) {
620
+ sendJson(response, 404, { error: 'Not found', code: 'NOT_FOUND' });
621
+ return;
622
+ }
623
+ response.writeHead(200, { ...SECURITY_HEADERS, 'content-type': contentType });
624
+ createReadStream(path).pipe(response);
625
+ }
626
+ function resolveAsset(root, name) {
627
+ if (name.length === 0 || name.includes('..') || name.includes('\\') || name.includes('\0'))
628
+ return undefined;
629
+ const full = normalize(join(root, name));
630
+ const prefix = root.endsWith(sep) ? root : root + sep;
631
+ if (full !== root && !full.startsWith(prefix))
632
+ return undefined;
633
+ if (!existsSync(full) || !statSync(full).isFile())
634
+ return undefined;
635
+ const extension = extname(full).toLowerCase();
636
+ if (!ASSET_EXTENSIONS.has(extension))
637
+ return undefined;
638
+ return { path: full, type: contentType(extension) };
639
+ }
640
+ function contentType(extension) {
641
+ switch (extension) {
642
+ case '.js':
643
+ return 'text/javascript; charset=utf-8';
644
+ case '.css':
645
+ return 'text/css; charset=utf-8';
646
+ case '.svg':
647
+ return 'image/svg+xml';
648
+ case '.png':
649
+ return 'image/png';
650
+ case '.woff':
651
+ return 'font/woff';
652
+ case '.woff2':
653
+ return 'font/woff2';
654
+ case '.ttf':
655
+ return 'font/ttf';
656
+ default:
657
+ return 'application/octet-stream';
658
+ }
659
+ }
660
+ function isSpaPath(pathname) {
661
+ if (pathname.startsWith('/api/') || pathname.startsWith('/assets/'))
662
+ return false;
663
+ const leaf = pathname.split('/').pop() ?? '';
664
+ return !leaf.includes('.');
665
+ }
666
+ function silentIo() {
667
+ return { stdout: { write: () => undefined }, stderr: { write: () => undefined } };
668
+ }