@di-framework/cli-plugin-platform 6.2.0 → 6.3.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 (50) hide show
  1. package/README.md +10 -0
  2. package/dist/args.d.ts +8 -0
  3. package/dist/args.js +73 -28
  4. package/dist/assets/platform/README.md +68 -19
  5. package/dist/assets/platform/index.ts.tmpl +1 -1
  6. package/dist/assets/platform/tsconfig.json +2 -2
  7. package/dist/assets/sqlite/BUILD-INFO.txt +1 -1
  8. package/dist/build.js +17 -4
  9. package/dist/bundle.d.ts +85 -0
  10. package/dist/bundle.js +608 -0
  11. package/dist/command.js +85 -3
  12. package/dist/console/cluster.d.ts +4 -2
  13. package/dist/console/cluster.js +38 -40
  14. package/dist/controller/client.d.ts +47 -0
  15. package/dist/controller/client.js +157 -0
  16. package/dist/controller/commands.d.ts +48 -0
  17. package/dist/controller/commands.js +584 -0
  18. package/dist/controller/credentials.d.ts +63 -0
  19. package/dist/controller/credentials.js +156 -0
  20. package/dist/controller/index.d.ts +6 -0
  21. package/dist/controller/index.js +6 -0
  22. package/dist/controller/oidc.d.ts +54 -0
  23. package/dist/controller/oidc.js +121 -0
  24. package/dist/controller/registry.d.ts +15 -0
  25. package/dist/controller/registry.js +47 -0
  26. package/dist/controller/schema.d.ts +157 -0
  27. package/dist/controller/schema.js +1 -0
  28. package/dist/controller/sse.d.ts +12 -0
  29. package/dist/controller/sse.js +61 -0
  30. package/dist/controller/trust.d.ts +14 -0
  31. package/dist/controller/trust.js +39 -0
  32. package/dist/deploy.d.ts +8 -1
  33. package/dist/deploy.js +89 -2
  34. package/dist/deps.d.ts +4 -0
  35. package/dist/destroy.js +26 -2
  36. package/dist/index.d.ts +4 -2
  37. package/dist/index.js +4 -2
  38. package/dist/manifest.d.ts +45 -1
  39. package/dist/manifest.js +197 -4
  40. package/dist/pglite.d.ts +12 -2
  41. package/dist/pglite.js +19 -11
  42. package/dist/publish.d.ts +7 -1
  43. package/dist/publish.js +33 -1
  44. package/dist/service.d.ts +34 -0
  45. package/dist/service.js +156 -145
  46. package/dist/target.d.ts +7 -1
  47. package/dist/target.js +19 -0
  48. package/dist/workload.d.ts +17 -1
  49. package/dist/workload.js +44 -11
  50. package/package.json +1 -1
@@ -0,0 +1,584 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { CommandFailure, } from '@di-framework/cli-extension';
3
+ import { readEnvFlag, readStringFlag } from '../args.js';
4
+ import { DEFAULT_DEPS } from '../deps.js';
5
+ import { findDeployManifest, loadDeployManifest, } from '../manifest.js';
6
+ import { loadProject } from '../project.js';
7
+ import { invalidUsage, matchOption } from '../support.js';
8
+ import { discoverAccountControllerUrl, isControllerBackedTarget, resolveTarget } from '../target.js';
9
+ import { deploymentResourceName } from '../workload.js';
10
+ import { createClient } from './client.js';
11
+ import { bearer, CliError, issuedTokens, load, readStore, resolveAccount, resolveControllerSession, resolveControllerTargetCredential, writeStore, } from './credentials.js';
12
+ import { authorizationUrl, discover, exchangeCode, OidcError, pkce, randomToken, revokeToken, } from './oidc.js';
13
+ import { caPem, readCaFile, trusting } from './trust.js';
14
+ const SCOPE = 'openid profile email offline_access';
15
+ const TLS_TRUST_CODES = new Set([
16
+ 'UNABLE_TO_VERIFY_LEAF_SIGNATURE',
17
+ 'UNABLE_TO_GET_ISSUER_CERT',
18
+ 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY',
19
+ 'SELF_SIGNED_CERT_IN_CHAIN',
20
+ 'DEPTH_ZERO_SELF_SIGNED_CERT',
21
+ 'CERT_UNTRUSTED',
22
+ ]);
23
+ export function tlsTrustCode(error) {
24
+ const code = error?.code;
25
+ return typeof code === 'string' && TLS_TRUST_CODES.has(code) ? code : undefined;
26
+ }
27
+ export function wrapControllerError(error) {
28
+ if (error instanceof CommandFailure)
29
+ throw error;
30
+ if (error instanceof CliError) {
31
+ throw new CommandFailure('WASMCLOUD_CONTROLLER_AUTH_REQUIRED', error.message, 2);
32
+ }
33
+ if (error instanceof OidcError) {
34
+ const details = error.status === undefined ? {} : { status: error.status };
35
+ throw new CommandFailure('WASMCLOUD_OIDC_FAILED', `identity: ${error.message}`, 3, details);
36
+ }
37
+ const tlsCode = tlsTrustCode(error);
38
+ if (tlsCode) {
39
+ const msg = `tls: ${error.message} (${tlsCode}). Trust the tenant's controller CA (ConfigMap tenant-controller-ca): login --ca-file <ca.crt>, or NODE_EXTRA_CA_CERTS=<ca.crt>.`;
40
+ throw new CommandFailure('WASMCLOUD_TLS_UNTRUSTED', msg, 3, { code: tlsCode });
41
+ }
42
+ if (error?.name === 'ControllerError') {
43
+ const failure = error;
44
+ const exitCode = failure.status >= 500 ? 3 : 2;
45
+ const details = {
46
+ status: failure.status,
47
+ ...(failure.problem.title ? { title: failure.problem.title } : {}),
48
+ };
49
+ throw new CommandFailure('WASMCLOUD_CONTROLLER_ERROR', `controller: ${failure.status} ${failure.message}`, exitCode, details);
50
+ }
51
+ throw error;
52
+ }
53
+ function resolveOptionalControllerTarget(targetName, deps, command) {
54
+ if (targetName !== undefined) {
55
+ const manifest = loadDeployManifest(deps.cwd(), deps.env);
56
+ const target = resolveTarget(manifest, targetName);
57
+ if (!isControllerBackedTarget(target)) {
58
+ const msg = `Target "${target.name}" is a ${target.kind} target; ${command} requires an account or controller target.`;
59
+ throw new CommandFailure('WASMCLOUD_TARGET_INVALID_KIND', msg, 2, {
60
+ target: target.name,
61
+ kind: target.kind,
62
+ command,
63
+ });
64
+ }
65
+ return { manifest, target };
66
+ }
67
+ const manifestPath = findDeployManifest(deps.cwd());
68
+ if (manifestPath === undefined)
69
+ return {};
70
+ const manifest = loadDeployManifest(deps.cwd(), deps.env);
71
+ if (manifest.defaultTarget !== undefined) {
72
+ const candidate = manifest.targets[manifest.defaultTarget];
73
+ if (candidate && isControllerBackedTarget(candidate))
74
+ return { manifest, target: candidate };
75
+ }
76
+ return { manifest };
77
+ }
78
+ const page = (text, status = 200) => new Response(`<!doctype html><title>di-framework</title><p style="font:16px system-ui;padding:24px">${text}</p>`, { status, headers: { 'content-type': 'text/html' } });
79
+ async function browserLogin(info, noBrowser, io, deps) {
80
+ const metadata = await discover(info.issuer, deps.fetch);
81
+ const { verifier, challenge } = await pkce();
82
+ const state = randomToken(16);
83
+ const { promise, resolve, reject } = Promise.withResolvers();
84
+ const server = Bun.serve({
85
+ hostname: '127.0.0.1',
86
+ port: 0,
87
+ fetch(request) {
88
+ const url = new URL(request.url);
89
+ if (url.pathname !== '/callback')
90
+ return page('Not found.', 404);
91
+ const refused = url.searchParams.get('error');
92
+ if (refused) {
93
+ reject(new CliError(`the identity server refused the login: ${refused}`));
94
+ return page('Login failed. Return to the terminal.', 400);
95
+ }
96
+ const code = url.searchParams.get('code');
97
+ if (!code || url.searchParams.get('state') !== state) {
98
+ reject(new CliError('the browser returned an unexpected login response'));
99
+ return page('Login failed. Return to the terminal.', 400);
100
+ }
101
+ resolve(code);
102
+ return page('Signed in. You can close this window and return to the terminal.');
103
+ },
104
+ });
105
+ const redirectUri = `http://127.0.0.1:${server.port}/callback`;
106
+ try {
107
+ const url = authorizationUrl(metadata, {
108
+ clientId: info.clientId,
109
+ redirectUri,
110
+ scope: SCOPE,
111
+ state,
112
+ nonce: randomToken(16),
113
+ codeChallenge: challenge,
114
+ });
115
+ io.stderr.write(`Opening your browser to sign in to ${info.account} at ${info.issuer}.\nIf it does not open, visit:\n ${url}\n`);
116
+ if (!noBrowser)
117
+ deps.openBrowser?.(url);
118
+ const timer = setTimeout(() => reject(new CliError('timed out waiting for the browser login')), deps.loginTimeoutMs ?? 300_000);
119
+ const code = await promise.finally(() => clearTimeout(timer));
120
+ return await exchangeCode(metadata, { clientId: info.clientId, redirectUri, code, codeVerifier: verifier }, deps.fetch);
121
+ }
122
+ finally {
123
+ await server.stop();
124
+ }
125
+ }
126
+ function storedCa(store, controller, drop) {
127
+ if (drop)
128
+ return undefined;
129
+ return Object.values(store).find((c) => c.controller.url === controller)?.controller
130
+ .certificateAuthorityData;
131
+ }
132
+ const LOGIN_STRING_FLAGS = {
133
+ '--target': 'target',
134
+ '--controller': 'controller',
135
+ '--account': 'account',
136
+ '--api-key': 'apiKey',
137
+ '--ca-file': 'caFile',
138
+ };
139
+ export function parseLoginArgs(args) {
140
+ const values = {};
141
+ let noCa = false;
142
+ let noBrowser = false;
143
+ let position = 0;
144
+ while (position < args.length) {
145
+ const token = args[position];
146
+ const nextPos = readStringFlag(args, position, token, LOGIN_STRING_FLAGS, values);
147
+ if (nextPos !== undefined) {
148
+ position = nextPos;
149
+ continue;
150
+ }
151
+ if (token === '--no-ca') {
152
+ noCa = true;
153
+ position += 1;
154
+ continue;
155
+ }
156
+ if (token === '--no-browser') {
157
+ noBrowser = true;
158
+ position += 1;
159
+ continue;
160
+ }
161
+ invalidUsage(token.startsWith('--') ? `Unknown option: ${token}` : `Unexpected argument: ${token}`, token, { command: 'platform login' });
162
+ }
163
+ if (values.caFile !== undefined && noCa) {
164
+ invalidUsage('--ca-file and --no-ca are exclusive', '--no-ca', { command: 'platform login' });
165
+ }
166
+ return {
167
+ ...values,
168
+ noCa,
169
+ noBrowser,
170
+ };
171
+ }
172
+ function resolveLoginEndpoint(options, target, store, env) {
173
+ let account = options.account;
174
+ let rawController = options.controller;
175
+ if (target?.kind === 'account') {
176
+ account = account ?? target.account;
177
+ const defaultUrl = store[account]?.controller.url ?? discoverAccountControllerUrl(account, undefined, env);
178
+ const targetUrl = target.domain
179
+ ? discoverAccountControllerUrl(account, target.domain, env)
180
+ : defaultUrl;
181
+ rawController = rawController ?? targetUrl;
182
+ }
183
+ else if (target?.kind === 'controller') {
184
+ account = account ?? target.account;
185
+ rawController = rawController ?? target.controller;
186
+ }
187
+ else if (rawController === undefined && account !== undefined) {
188
+ rawController =
189
+ store[account]?.controller.url ?? discoverAccountControllerUrl(account, undefined, env);
190
+ }
191
+ if (rawController === undefined) {
192
+ invalidUsage('Missing required --controller <url> or --target <name> for platform login', '--controller', { command: 'platform login' });
193
+ }
194
+ return { account, controller: rawController.replace(/\/$/, '') };
195
+ }
196
+ export async function runWasmcloudLogin(args, io, deps = DEFAULT_DEPS) {
197
+ const options = parseLoginArgs(args);
198
+ try {
199
+ const store = readStore(deps.env);
200
+ const { target } = resolveOptionalControllerTarget(options.target, deps, 'platform login');
201
+ const { account, controller } = resolveLoginEndpoint(options, target, store, deps.env);
202
+ const certificateAuthorityData = options.caFile
203
+ ? readCaFile(options.caFile)
204
+ : storedCa(store, controller, options.noCa);
205
+ const controllerInfo = { url: controller, certificateAuthorityData };
206
+ const controllerFetch = trusting(deps.fetch, caPem(controllerInfo));
207
+ const info = await createClient({ baseUrl: controller, fetch: controllerFetch }).authInfo();
208
+ if (account !== undefined && info.account !== account) {
209
+ throw new CliError(`${controller} serves account ${info.account}, not ${account}`);
210
+ }
211
+ const tokens = options.apiKey
212
+ ? undefined
213
+ : await browserLogin(info, options.noBrowser, io, deps);
214
+ const token = options.apiKey ?? tokens.access_token;
215
+ const who = await createClient({
216
+ baseUrl: controller,
217
+ token,
218
+ fetch: controllerFetch,
219
+ }).whoami();
220
+ const base = {
221
+ account: info.account,
222
+ user: who.user,
223
+ role: who.role,
224
+ controller: certificateAuthorityData ? controllerInfo : { url: controller },
225
+ };
226
+ const credential = options.apiKey
227
+ ? { ...base, via: 'api-key', apiKey: options.apiKey }
228
+ : {
229
+ ...base,
230
+ via: 'identity',
231
+ issuer: info.issuer,
232
+ clientId: info.clientId,
233
+ ...issuedTokens(tokens),
234
+ };
235
+ store[info.account] = credential;
236
+ writeStore(store, deps.env);
237
+ const text = `Logged in to ${info.account} as ${who.user} (${who.role}) via ${credential.via}.`;
238
+ io.stderr.write(`${text}\n`);
239
+ return {
240
+ data: {
241
+ account: info.account,
242
+ user: who.user,
243
+ role: who.role,
244
+ via: credential.via,
245
+ controller,
246
+ },
247
+ text,
248
+ };
249
+ }
250
+ catch (error) {
251
+ wrapControllerError(error);
252
+ }
253
+ }
254
+ const ACCOUNT_STRING_FLAGS = {
255
+ '--target': 'target',
256
+ '--account': 'account',
257
+ };
258
+ export function parseAccountCommandArgs(args, command) {
259
+ const values = {};
260
+ let position = 0;
261
+ while (position < args.length) {
262
+ const token = args[position];
263
+ const nextPos = readStringFlag(args, position, token, ACCOUNT_STRING_FLAGS, values);
264
+ if (nextPos !== undefined) {
265
+ position = nextPos;
266
+ continue;
267
+ }
268
+ invalidUsage(token.startsWith('--') ? `Unknown option: ${token}` : `Unexpected argument: ${token}`, token, { command });
269
+ }
270
+ return values;
271
+ }
272
+ function resolveLogoutCredential(options, target, store, env) {
273
+ if (target?.kind === 'controller') {
274
+ return resolveControllerTargetCredential(target, options.account, store);
275
+ }
276
+ const account = options.account ??
277
+ (target?.kind === 'account' ? target.account : resolveAccount(undefined, env, store));
278
+ return load(account, env);
279
+ }
280
+ export async function runWasmcloudLogout(args, io, deps = DEFAULT_DEPS) {
281
+ const options = parseAccountCommandArgs(args, 'platform logout');
282
+ try {
283
+ const store = readStore(deps.env);
284
+ const { target } = resolveOptionalControllerTarget(options.target, deps, 'platform logout');
285
+ const credential = resolveLogoutCredential(options, target, store, deps.env);
286
+ const account = credential.account;
287
+ try {
288
+ await createClient({
289
+ baseUrl: credential.controller.url,
290
+ token: bearer(credential),
291
+ fetch: trusting(deps.fetch, caPem(credential.controller)),
292
+ }).logout();
293
+ }
294
+ catch {
295
+ // An expired or already revoked token; nothing to tell the controller.
296
+ }
297
+ if (credential.via === 'identity' && credential.refreshToken && credential.issuer) {
298
+ try {
299
+ const trustedFetch = trusting(deps.fetch, caPem(credential.controller));
300
+ await revokeToken(await discover(credential.issuer, trustedFetch), credential.clientId ?? '', credential.refreshToken, trustedFetch, credential.issuer);
301
+ }
302
+ catch (error) {
303
+ io.stderr.write(`warning: failed to revoke token at ${credential.issuer}: ${error.message}\n`);
304
+ }
305
+ }
306
+ delete store[account];
307
+ writeStore(store, deps.env);
308
+ const text = `Logged out of ${account}.`;
309
+ io.stderr.write(`${text}\n`);
310
+ return {
311
+ data: { account, loggedOut: true },
312
+ text,
313
+ };
314
+ }
315
+ catch (error) {
316
+ wrapControllerError(error);
317
+ }
318
+ }
319
+ export async function runWasmcloudWhoami(args, _io, deps = DEFAULT_DEPS) {
320
+ const options = parseAccountCommandArgs(args, 'platform whoami');
321
+ try {
322
+ const { target } = resolveOptionalControllerTarget(options.target, deps, 'platform whoami');
323
+ const { credential, client } = await resolveControllerSession({ target, account: options.account }, deps);
324
+ const who = await client.whoami();
325
+ return {
326
+ data: {
327
+ ...who,
328
+ controller: credential.controller.url,
329
+ },
330
+ text: `${who.user} (${who.role}) in ${who.account} via ${who.via}`,
331
+ };
332
+ }
333
+ catch (error) {
334
+ wrapControllerError(error);
335
+ }
336
+ }
337
+ const LOGS_STRING_FLAGS = {
338
+ '--service': 'service',
339
+ '--target': 'target',
340
+ '--account': 'account',
341
+ '--deployment': 'deployment',
342
+ '--since': 'since',
343
+ };
344
+ export function parseLogsArgs(args) {
345
+ const values = {};
346
+ let env;
347
+ let follow = false;
348
+ let tail;
349
+ let position = 0;
350
+ while (position < args.length) {
351
+ const token = args[position];
352
+ const nextPos = readStringFlag(args, position, token, LOGS_STRING_FLAGS, values);
353
+ if (nextPos !== undefined) {
354
+ position = nextPos;
355
+ continue;
356
+ }
357
+ const envOpt = readEnvFlag(args, position, token, env, 'platform logs');
358
+ if (envOpt) {
359
+ env = envOpt.value;
360
+ position = envOpt.nextPosition;
361
+ continue;
362
+ }
363
+ const tailOpt = matchOption(args, position, token, '--tail');
364
+ if (tailOpt) {
365
+ if (tail !== undefined)
366
+ invalidUsage('Option may be provided only once: --tail', '--tail');
367
+ const parsed = Number(tailOpt.value);
368
+ if (!Number.isInteger(parsed) || parsed < 0) {
369
+ invalidUsage('--tail must be a whole number', tailOpt.value, { command: 'platform logs' });
370
+ }
371
+ tail = parsed;
372
+ position = tailOpt.consumedThrough + 1;
373
+ continue;
374
+ }
375
+ if (token === '--follow') {
376
+ follow = true;
377
+ position += 1;
378
+ continue;
379
+ }
380
+ if (token.startsWith('--')) {
381
+ invalidUsage(`Unknown option: ${token}`, token, { command: 'platform logs' });
382
+ }
383
+ if (values.service !== undefined) {
384
+ invalidUsage(`Unexpected argument: ${token}`, token, { command: 'platform logs' });
385
+ }
386
+ values.service = token;
387
+ position += 1;
388
+ }
389
+ return {
390
+ ...values,
391
+ ...(env ? { env } : {}),
392
+ follow,
393
+ ...(tail !== undefined ? { tail } : {}),
394
+ };
395
+ }
396
+ export async function runWasmcloudLogs(args, io, deps = DEFAULT_DEPS) {
397
+ const options = parseLogsArgs(args);
398
+ try {
399
+ const { manifest, target } = resolveOptionalControllerTarget(options.target, deps, 'platform logs');
400
+ const env = options.env ?? target?.env ?? manifest?.env ?? 'prod';
401
+ let service = options.service;
402
+ if (service === undefined) {
403
+ try {
404
+ service = deploymentResourceName(loadProject(deps.cwd()));
405
+ }
406
+ catch {
407
+ invalidUsage('Missing required --service for platform logs', '--service', {
408
+ command: 'platform logs',
409
+ });
410
+ }
411
+ }
412
+ const { credential, client } = await resolveControllerSession({ target, account: options.account }, deps);
413
+ const events = [];
414
+ const lines = [];
415
+ for await (const event of client.logs(service, {
416
+ env,
417
+ deployment: options.deployment,
418
+ follow: options.follow,
419
+ since: options.since,
420
+ tail: options.tail,
421
+ })) {
422
+ events.push(event);
423
+ const line = `${event.timestamp} ${event.deployment} ${event.level ?? 'info'} ${event.message}`;
424
+ lines.push(line);
425
+ io.stdout.write(`${line}\n`);
426
+ }
427
+ return {
428
+ data: {
429
+ service,
430
+ env,
431
+ account: credential.account,
432
+ events: events,
433
+ },
434
+ text: lines.join('\n'),
435
+ };
436
+ }
437
+ catch (error) {
438
+ wrapControllerError(error);
439
+ }
440
+ }
441
+ const CONFIG_STRING_FLAGS = {
442
+ '--target': 'target',
443
+ '--account': 'account',
444
+ '--from-file': 'fromFile',
445
+ '--value': 'value',
446
+ };
447
+ const CONFIG_ACTIONS = new Set(['list', 'set', 'update', 'unset']);
448
+ function validateConfigOptions(action, name, values, command) {
449
+ if (action === undefined) {
450
+ invalidUsage(`Usage: ${command} <list|set|update|unset> [name]`, command, { command });
451
+ }
452
+ if (action === 'list' && name !== undefined) {
453
+ invalidUsage(`Unexpected argument for ${command} list: ${name}`, name, { command });
454
+ }
455
+ if (action !== 'list' && name === undefined) {
456
+ invalidUsage(`Missing required <name> for ${command} ${action}`, action, { command });
457
+ }
458
+ if (values.fromFile !== undefined && values.value !== undefined) {
459
+ invalidUsage('--from-file and --value are exclusive', '--value', { command });
460
+ }
461
+ if ((action === 'set' || action === 'update') &&
462
+ values.fromFile === undefined &&
463
+ values.value === undefined) {
464
+ invalidUsage(`Missing required --from-file <path|-> or --value for ${command} ${action}`, '--from-file', { command });
465
+ }
466
+ return action;
467
+ }
468
+ export function parseConfigArgs(args, command) {
469
+ let action;
470
+ let name;
471
+ const values = {};
472
+ let env;
473
+ let position = 0;
474
+ while (position < args.length) {
475
+ const token = args[position];
476
+ const nextPos = readStringFlag(args, position, token, CONFIG_STRING_FLAGS, values);
477
+ if (nextPos !== undefined) {
478
+ position = nextPos;
479
+ continue;
480
+ }
481
+ const envOpt = readEnvFlag(args, position, token, env, command);
482
+ if (envOpt) {
483
+ env = envOpt.value;
484
+ position = envOpt.nextPosition;
485
+ continue;
486
+ }
487
+ if (token.startsWith('--')) {
488
+ invalidUsage(`Unknown option: ${token}`, token, { command });
489
+ }
490
+ if (action === undefined) {
491
+ if (!CONFIG_ACTIONS.has(token)) {
492
+ invalidUsage(`Usage: ${command} <list|set|update|unset> [name]`, token, { command });
493
+ }
494
+ action = token;
495
+ position += 1;
496
+ continue;
497
+ }
498
+ if (name !== undefined) {
499
+ invalidUsage(`Unexpected argument: ${token}`, token, { command });
500
+ }
501
+ name = token;
502
+ position += 1;
503
+ }
504
+ const validAction = validateConfigOptions(action, name, values, command);
505
+ return {
506
+ action: validAction,
507
+ ...(name ? { name } : {}),
508
+ ...values,
509
+ ...(env ? { env } : {}),
510
+ };
511
+ }
512
+ function readConfigValue(options, deps) {
513
+ if (options.value !== undefined)
514
+ return options.value;
515
+ const source = options.fromFile;
516
+ const raw = source === '-' ? (deps.stdin?.() ?? '') : readFileSync(source, 'utf8');
517
+ return raw.replace(/\r?\n$/, '');
518
+ }
519
+ async function listConfigItems(kind, env, account, client) {
520
+ const isSecret = kind === 'secrets';
521
+ const list = isSecret ? await client.secrets(env) : await client.vars(env);
522
+ const formatEntry = (entry) => isSecret ? entry.name : `${entry.name}=${entry.value ?? ''}`;
523
+ const text = list.items.length === 0 ? `no ${kind} in ${env}` : list.items.map(formatEntry).join('\n');
524
+ return {
525
+ data: { env, account, items: list.items },
526
+ text,
527
+ };
528
+ }
529
+ async function unsetConfigItem(kind, name, env, account, client, io) {
530
+ if (kind === 'secrets') {
531
+ await client.unsetSecret(env, name);
532
+ const text = `unset secret ${name} in ${env}`;
533
+ io.stderr.write(`${text}\n`);
534
+ return { data: { action: 'unset', name, env, account }, text };
535
+ }
536
+ const result = await client.unsetVar(env, name);
537
+ for (const warning of result.warnings) {
538
+ io.stderr.write(`warning: ${warning.detail}\n`);
539
+ }
540
+ const text = `unset var ${name} in ${env}`;
541
+ io.stderr.write(`${text}\n`);
542
+ const warnings = result.warnings;
543
+ return { data: { action: 'unset', name, env, account, warnings }, text };
544
+ }
545
+ async function runConfigCommand(kind, args, io, deps) {
546
+ const command = `platform ${kind}`;
547
+ const options = parseConfigArgs(args, command);
548
+ const isSecret = kind === 'secrets';
549
+ const singular = isSecret ? 'secret' : 'var';
550
+ try {
551
+ const { manifest, target } = resolveOptionalControllerTarget(options.target, deps, command);
552
+ const env = options.env ?? target?.env ?? manifest?.env ?? 'prod';
553
+ const { credential, client } = await resolveControllerSession({ target, account: options.account }, deps);
554
+ if (options.action === 'list') {
555
+ return await listConfigItems(kind, env, credential.account, client);
556
+ }
557
+ const name = options.name;
558
+ if (options.action === 'unset') {
559
+ return await unsetConfigItem(kind, name, env, credential.account, client, io);
560
+ }
561
+ const value = readConfigValue(options, deps);
562
+ if (options.action === 'set') {
563
+ await (isSecret ? client.setSecret(env, name, value) : client.setVar(env, name, value));
564
+ }
565
+ else {
566
+ await (isSecret ? client.updateSecret(env, name, value) : client.updateVar(env, name, value));
567
+ }
568
+ const text = `${options.action} ${singular} ${name} in ${env}`;
569
+ io.stderr.write(`${text}\n`);
570
+ return {
571
+ data: { action: options.action, name, env, account: credential.account },
572
+ text,
573
+ };
574
+ }
575
+ catch (error) {
576
+ wrapControllerError(error);
577
+ }
578
+ }
579
+ export function runWasmcloudSecrets(args, io, deps = DEFAULT_DEPS) {
580
+ return runConfigCommand('secrets', args, io, deps);
581
+ }
582
+ export function runWasmcloudVars(args, io, deps = DEFAULT_DEPS) {
583
+ return runConfigCommand('vars', args, io, deps);
584
+ }
@@ -0,0 +1,63 @@
1
+ import type { WasmcloudDeps } from '../deps.js';
2
+ import type { AccountTarget, ControllerTarget } from '../manifest.js';
3
+ import { type TenantClient } from './client.js';
4
+ import { type TokenResponse } from './oidc.js';
5
+ export interface Credential {
6
+ account: string;
7
+ user: string;
8
+ role: string;
9
+ via: 'identity' | 'api-key';
10
+ accessToken?: string;
11
+ refreshToken?: string;
12
+ apiKey?: string;
13
+ /** Access token expiry; absent for API keys. */
14
+ expiresAt?: string;
15
+ /** Where an identity login refreshes and revokes: the issuer and the public client id. */
16
+ issuer?: string;
17
+ clientId?: string;
18
+ controller: {
19
+ url: string;
20
+ certificateAuthorityData?: string;
21
+ };
22
+ registry?: {
23
+ host: string;
24
+ config?: string;
25
+ fingerprint?: string;
26
+ tool?: string;
27
+ };
28
+ console?: string;
29
+ }
30
+ /** True when an identity token is gone or within a minute of expiring, so it must be refreshed. */
31
+ export declare function needsRefresh(credential: Credential, now?: number): boolean;
32
+ export type CredentialStore = Record<string, Credential>;
33
+ export declare class CliError extends Error {
34
+ readonly exitCode: number;
35
+ constructor(message: string, exitCode?: number);
36
+ }
37
+ export declare const home: (env?: Record<string, string | undefined>) => string;
38
+ export declare function readStore(env?: Record<string, string | undefined>): CredentialStore;
39
+ export declare function writeStore(store: CredentialStore, env?: Record<string, string | undefined>): void;
40
+ /** The bearer a credential presents: the API key, or the identity access token while it lasts. */
41
+ export declare function bearer(credential: Credential): string;
42
+ /**
43
+ * The account a command runs against: `--account`, then `DI_TENANT_ACCOUNT`, then the only
44
+ * credential on disk.
45
+ */
46
+ export declare function resolveAccount(flag: string | undefined, env: Record<string, string | undefined>, store: CredentialStore): string;
47
+ export declare function load(account: string, env?: Record<string, string | undefined>): Credential;
48
+ export declare function issuedTokens(tokens: TokenResponse, previousRefresh?: string): {
49
+ accessToken: string;
50
+ refreshToken: string | undefined;
51
+ expiresAt: string;
52
+ };
53
+ export declare function refreshCredential(credential: Credential, doFetch?: typeof fetch): Promise<Credential>;
54
+ export type ResolveControllerSessionOptions = {
55
+ target?: AccountTarget | ControllerTarget;
56
+ account?: string;
57
+ fresh?: boolean;
58
+ };
59
+ export declare function resolveControllerTargetCredential(target: ControllerTarget, account: string | undefined, store: CredentialStore): Credential;
60
+ export declare function resolveControllerSession(options: ResolveControllerSessionOptions, deps: Pick<WasmcloudDeps, 'env' | 'fetch'>): Promise<{
61
+ credential: Credential;
62
+ client: TenantClient;
63
+ }>;