@atolis-hq/wake 0.3.116 → 0.3.118

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -127,7 +127,11 @@ nothing new to learn, no separate dashboard to babysit.
127
127
 
128
128
  A local control-plane UI exists for operators who want to watch runs, inspect
129
129
  events, or resume a session directly, but it's a window into the same state -
130
- not a required part of the workflow.
130
+ not a required part of the workflow. The API and UI require an operator login:
131
+ run `wake ui token` to print a single-use pairing link or temporary code, then
132
+ enter it in the UI. Successful logins persist for two years across browser and
133
+ Wake-container restarts. Use `wake ui token set <key>` to replace the durable
134
+ access key; replacement signs out existing sessions.
131
135
 
132
136
  ## Supported Agent CLIs
133
137
 
@@ -1,5 +1,4 @@
1
1
  import { execFile as nodeExecFile, spawn } from 'node:child_process';
2
- import { once } from 'node:events';
3
2
  import { access, copyFile, mkdir, writeFile as writeFileContent } from 'node:fs/promises';
4
3
  import { join } from 'node:path';
5
4
  import { createInterface } from 'node:readline/promises';
@@ -9,7 +8,7 @@ import { IntakeHost, ResidentHost, TickHost } from '../control-plane/index.js';
9
8
  import { ExecutionCancellationReason, ExecutionFailureCode, RunStatus, loadPromptTemplate, } from '../execution/index.js';
10
9
  import { EventActorKind, JOURNAL_CHANGE_FALLBACK_MS, correlationId } from '../kernel/index.js';
11
10
  import { ResourceCorrelationRole, resourceId } from '../resources/index.js';
12
- import { DockerProcessError, createApiDispatcher, createApiHttpServer, createLoggedDockerCli, createPackagedAssetSource, createProcessLogSink, createSandboxDockerPort, drainProcessOutput, runDoctor, runSandbox, runSandboxEntrypoint, runSandboxSetup, runSelfUpdateLatestLoop, runTargetSmoke, verifyResidentStart, waitForActiveRuns, waitForever, } from '../surfaces/index.js';
11
+ import { DockerProcessError, createApiDispatcher, createLoggedDockerCli, createPackagedAssetSource, createPairingGrant, createProcessLogSink, createSandboxDockerPort, createSurfaceHttpServer, drainProcessOutput, loadOrCreateCredentials, redeemPairingGrant, replaceAccessKey, runDoctor, runSandbox, runSandboxEntrypoint, runSandboxSetup, runSelfUpdateLatestLoop, runTargetSmoke, verifyResidentStart, waitForActiveRuns, waitForever, } from '../surfaces/index.js';
13
12
  import { WorkStreamKind, workItemId } from '../work/index.js';
14
13
  import { loadConfig } from './config/load-config.js';
15
14
  import { runtimeProjectionDefinitions } from './projection-runtime.js';
@@ -91,6 +90,30 @@ export function createSurfaceCliApplications(root, api, now) {
91
90
  },
92
91
  api: { start: (options) => startHttp(options, false) },
93
92
  ui: { start: (options) => startHttp(options, true) },
93
+ auth: {
94
+ async token(accessKey) {
95
+ if (root.config.surfaces.web.auth.disabled)
96
+ return 'UI authentication is disabled by surfaces.web.auth.disabled.';
97
+ if (accessKey !== undefined)
98
+ await replaceAccessKey(root.paths.wakeRoot, accessKey);
99
+ const grant = await createPairingGrant(root.paths.wakeRoot);
100
+ const localHost = root.config.surfaces.api.host === '0.0.0.0' ? 'localhost' : root.config.surfaces.api.host;
101
+ const local = `http://${localHost}:${root.config.surfaces.api.port}/?grant=${encodeURIComponent(grant.value)}`;
102
+ const publicUrl = root.config.surfaces.web.publicUrl;
103
+ return [
104
+ 'Wake login link (single use; expires in 10 minutes):',
105
+ ` Local: ${local}`,
106
+ ...(publicUrl === undefined
107
+ ? []
108
+ : [
109
+ ` Public: ${new URL(`?grant=${encodeURIComponent(grant.value)}`, publicUrl).href}`,
110
+ ]),
111
+ '',
112
+ 'Open a link on this device or scan its QR code from a mobile device. Do not share the link.',
113
+ '',
114
+ ].join('\n');
115
+ },
116
+ },
94
117
  audit: {
95
118
  async read(id) {
96
119
  return (await root.journal.readAll(0))
@@ -167,14 +190,21 @@ function createHttpStarter(root, api, servers) {
167
190
  const assets = web ? createPackagedAssetSource() : undefined;
168
191
  if (web && (await assets.get('/index.html')) === undefined)
169
192
  throw new Error('Packaged Wake web assets are missing');
170
- const server = createApiHttpServer(createApiDispatcher(api), assets);
193
+ const server = createSurfaceHttpServer({
194
+ dispatcher: createApiDispatcher(api),
195
+ credentials: await loadOrCreateCredentials(root.paths.wakeRoot),
196
+ auth: {
197
+ disabled: root.config.surfaces.web.auth.disabled,
198
+ redeemGrant: (grant) => redeemPairingGrant(root.paths.wakeRoot, grant),
199
+ },
200
+ ...(assets === undefined ? {} : { assets }),
201
+ });
171
202
  servers.add(server);
172
- server.listen(options.port ?? root.config.surfaces.api.port, options.host ?? root.config.surfaces.api.host);
173
203
  try {
174
- await Promise.race([
175
- once(server, 'listening'),
176
- once(server, 'error').then(([error]) => Promise.reject(error)),
177
- ]);
204
+ await server.listen({
205
+ port: options.port ?? root.config.surfaces.api.port,
206
+ host: options.host ?? root.config.surfaces.api.host,
207
+ });
178
208
  }
179
209
  catch (error) {
180
210
  servers.delete(server);
@@ -637,10 +667,9 @@ function commandContext(commandId, occurredAt) {
637
667
  }
638
668
  async function closeAll(servers) {
639
669
  await Promise.all([...servers].map(async (server) => {
640
- if (!server.listening)
670
+ if (!server.server.listening)
641
671
  return;
642
- server.close();
643
- await once(server, 'close');
672
+ await server.close();
644
673
  servers.delete(server);
645
674
  }));
646
675
  }
@@ -108,4 +108,4 @@ export function resolveWakeVersion(options = {}) {
108
108
  return `g${headHash.slice(0, 7)}`;
109
109
  return '0.1.0-dev';
110
110
  }
111
- export const wakeVersion = "g7af14f8";
111
+ export const wakeVersion = "g4d812e5";
@@ -1,54 +1,107 @@
1
- import { createServer } from 'node:http';
1
+ import rateLimit from '@fastify/rate-limit';
2
+ import secureSession from '@fastify/secure-session';
3
+ import Fastify from 'fastify';
4
+ import { verifyAccessKey } from '../auth/credentials.js';
5
+ import { SurfaceCookieSecurity, SurfaceSessionAttribute } from '../auth/vocabulary.js';
2
6
  import { problemDetails } from './problem-details.js';
3
7
  import { BrowserRouteOutcome, routeBrowserRequest } from './router.js';
4
- export function createApiHttpServer(dispatcher, assets) {
5
- return createServer((request, response) => {
6
- void handleRequest(dispatcher, assets, request, response);
8
+ const operatorSessionLifetimeSeconds = 2 * 365 * 24 * 60 * 60;
9
+ /**
10
+ * The production HTTP surface. Public login routes are declared separately;
11
+ * every operational API route is protected in its own Fastify scope before
12
+ * Fastify parses the request body.
13
+ */
14
+ export function createSurfaceHttpServer(options) {
15
+ const app = Fastify({ bodyLimit: 64 * 1024, logger: { level: 'error' }, trustProxy: true });
16
+ app.register(rateLimit, { global: false });
17
+ const authDisabled = options.auth?.disabled === true;
18
+ app.register(secureSession, {
19
+ key: Buffer.from(options.credentials.sessionPassword, 'base64url'),
20
+ cookieName: 'wake_session',
21
+ expiry: operatorSessionLifetimeSeconds,
22
+ cookie: {
23
+ httpOnly: true,
24
+ maxAge: operatorSessionLifetimeSeconds,
25
+ sameSite: 'lax',
26
+ secure: SurfaceCookieSecurity.Auto,
27
+ path: '/',
28
+ },
7
29
  });
8
- }
9
- async function handleRequest(dispatcher, assets, request, response) {
10
- try {
11
- await dispatchRequest(dispatcher, assets, request, response);
12
- }
13
- catch (error) {
14
- sendJson(response, errorResult(error));
15
- }
16
- }
17
- async function dispatchRequest(dispatcher, assets, request, response) {
18
- const url = new URL(request.url ?? '/', 'http://wake.local');
19
- const method = request.method ?? 'GET';
20
- const head = method === 'HEAD';
21
- const result = await dispatcher.dispatch(method, `${url.pathname}${url.search}`, await jsonBody(request));
22
- if (result !== undefined)
23
- return sendJson(response, result, head);
24
- await serveWebRequest(assets, method, url.pathname, response, head);
25
- }
26
- async function serveWebRequest(assets, method, pathname, response, head) {
27
- const asset = method === 'GET' || head ? await assets?.get(pathname) : undefined;
28
- if (asset !== undefined)
29
- return send(response, { status: 200, ...asset, head });
30
- if (routeBrowserRequest(method, pathname) === BrowserRouteOutcome.Spa) {
31
- const index = await assets?.get('/index.html');
32
- if (index !== undefined)
33
- return send(response, {
34
- status: 200,
35
- ...index,
36
- contentType: 'text/html; charset=utf-8',
37
- head,
38
- });
39
- }
40
- if (pathname.startsWith('/api/'))
41
- return sendJson(response, {
42
- status: 404,
43
- body: problemDetails(404, 'Not Found', `No route for ${pathname}`),
44
- contentType: 'application/problem+json',
45
- }, head);
46
- return send(response, {
47
- status: 404,
48
- contentType: 'text/plain; charset=utf-8',
49
- body: Buffer.from('Not Found'),
50
- head,
30
+ app.setErrorHandler((error, request, reply) => {
31
+ request.log.error({ err: error }, 'Wake HTTP request failed');
32
+ if (isFastifyBodyLimitError(error))
33
+ return sendFastifyJson(reply, {
34
+ status: 413,
35
+ body: problemDetails(413, 'Payload Too Large', 'The request body is too large.', {
36
+ code: 'payload-too-large',
37
+ }),
38
+ contentType: 'application/problem+json',
39
+ }, false);
40
+ if (error instanceof SyntaxError || isFastifyMalformedJsonError(error))
41
+ return sendFastifyJson(reply, errorResult(new MalformedJsonError()), false);
42
+ return sendFastifyJson(reply, errorResult(error), false);
51
43
  });
44
+ app.get('/api/v1/auth/session', async (request, reply) => {
45
+ if (authDisabled)
46
+ return { authenticated: true };
47
+ if (request.session.get(SurfaceSessionAttribute.Operator) === true)
48
+ return { authenticated: true };
49
+ return reply.code(401).send({ status: 401, title: 'Unauthorized' });
50
+ });
51
+ if (!authDisabled)
52
+ app.post('/api/v1/auth/login', { bodyLimit: 1024, config: { rateLimit: { max: 5, timeWindow: '1 minute' } } }, async (request, reply) => {
53
+ const key = typeof request.body?.accessKey === 'string' ? request.body.accessKey : '';
54
+ if (!verifyAccessKey(key, options.credentials.accessKey))
55
+ return reply.code(401).send({ status: 401, title: 'Unauthorized' });
56
+ request.session.set(SurfaceSessionAttribute.Operator, true);
57
+ return { authenticated: true };
58
+ });
59
+ if (!authDisabled)
60
+ app.post('/api/v1/auth/redeem', { bodyLimit: 1024, config: { rateLimit: { max: 5, timeWindow: '1 minute' } } }, async (request, reply) => {
61
+ const grant = typeof request.body?.grant === 'string' ? request.body.grant : '';
62
+ if (options.auth === undefined || !(await options.auth.redeemGrant(grant)))
63
+ return reply.code(401).send({ status: 401, title: 'Unauthorized' });
64
+ request.session.set(SurfaceSessionAttribute.Operator, true);
65
+ return { authenticated: true };
66
+ });
67
+ app.register((protectedApi, _pluginOptions, done) => {
68
+ protectedApi.addHook('onRequest', async (request, reply) => {
69
+ if (!authDisabled && request.session.get(SurfaceSessionAttribute.Operator) !== true)
70
+ return reply.code(401).send({ status: 401, title: 'Unauthorized' });
71
+ });
72
+ protectedApi.all('/*', async (request, reply) => {
73
+ const result = await options.dispatcher.dispatch(request.method, request.raw.url ?? request.url, request.body);
74
+ if (result === undefined)
75
+ return sendFastifyJson(reply, {
76
+ status: 404,
77
+ body: problemDetails(404, 'Not Found', `No route for ${request.url}`),
78
+ contentType: 'application/problem+json',
79
+ }, request.method === 'HEAD');
80
+ return sendFastifyJson(reply, result, request.method === 'HEAD');
81
+ });
82
+ done();
83
+ }, { prefix: '/api/v1' });
84
+ app.route({
85
+ method: ['GET', 'HEAD'],
86
+ url: '/*',
87
+ handler: async (request, reply) => {
88
+ const pathname = new URL(request.raw.url ?? request.url, 'http://wake.local').pathname;
89
+ const head = request.method === 'HEAD';
90
+ const asset = await options.assets?.get(pathname);
91
+ if (asset !== undefined)
92
+ return sendFastifyAsset(reply, asset, head);
93
+ if (routeBrowserRequest(request.method, pathname) === BrowserRouteOutcome.Spa) {
94
+ const index = await options.assets?.get('/index.html');
95
+ if (index !== undefined)
96
+ return sendFastifyAsset(reply, { ...index, contentType: 'text/html; charset=utf-8' }, head);
97
+ }
98
+ return reply
99
+ .code(404)
100
+ .type('text/plain; charset=utf-8')
101
+ .send(head ? undefined : 'Not Found');
102
+ },
103
+ });
104
+ return app;
52
105
  }
53
106
  function errorResult(error) {
54
107
  if (error instanceof MalformedJsonError)
@@ -85,37 +138,30 @@ function isUpstreamProviderError(error) {
85
138
  typeof error.status === 'number' &&
86
139
  error.status >= 400);
87
140
  }
88
- async function jsonBody(request) {
89
- if (request.method === 'GET' || request.method === 'HEAD')
90
- return undefined;
91
- const chunks = [];
92
- for await (const chunk of request)
93
- chunks.push(Buffer.from(chunk));
94
- if (chunks.length === 0)
95
- return undefined;
96
- try {
97
- return JSON.parse(Buffer.concat(chunks).toString('utf8'));
98
- }
99
- catch {
100
- throw new MalformedJsonError();
101
- }
102
- }
103
141
  class MalformedJsonError extends Error {
104
142
  }
105
- function sendJson(response, result, head = false) {
106
- send(response, {
107
- status: result.status,
108
- contentType: result.contentType ?? 'application/json; charset=utf-8',
109
- body: Buffer.from(JSON.stringify(result.body)),
110
- ...(result.headers === undefined ? {} : { headers: result.headers }),
111
- head,
112
- });
143
+ function sendFastifyJson(reply, result, head) {
144
+ reply.code(result.status);
145
+ reply.headers(result.headers ?? {});
146
+ reply.type(result.contentType ?? 'application/json; charset=utf-8');
147
+ return reply.send(head ? undefined : result.body);
113
148
  }
114
- function send(response, options) {
115
- response.writeHead(options.status, {
116
- 'content-type': options.contentType,
117
- 'content-length': options.body.byteLength,
118
- ...options.headers,
119
- });
120
- response.end(options.head ? undefined : options.body);
149
+ function sendFastifyAsset(reply, asset, head) {
150
+ reply.code(200);
151
+ reply.headers(asset.headers);
152
+ reply.header('content-length', asset.body.byteLength);
153
+ reply.type(asset.contentType);
154
+ return reply.send(head ? undefined : asset.body);
155
+ }
156
+ function isFastifyBodyLimitError(error) {
157
+ return (typeof error === 'object' &&
158
+ error !== null &&
159
+ 'code' in error &&
160
+ error.code === 'FST_ERR_CTP_BODY_TOO_LARGE');
161
+ }
162
+ function isFastifyMalformedJsonError(error) {
163
+ return (typeof error === 'object' &&
164
+ error !== null &&
165
+ 'code' in error &&
166
+ error.code === 'FST_ERR_CTP_INVALID_JSON_BODY');
121
167
  }
@@ -0,0 +1,134 @@
1
+ import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
2
+ import { chmod, mkdir, readFile, rename, writeFile } from 'node:fs/promises';
3
+ import { dirname, join } from 'node:path';
4
+ import { withFileLock } from '../../persistence/index.js';
5
+ const pairingGrantLifetimeMs = 10 * 60 * 1000;
6
+ const credentialLockName = 'surface-credentials.lock';
7
+ export function credentialsPath(wakeRoot) {
8
+ return join(wakeRoot, '.wake', 'auth', 'credentials.json');
9
+ }
10
+ export async function loadOrCreateCredentials(wakeRoot) {
11
+ const path = credentialsPath(wakeRoot);
12
+ try {
13
+ return decodeCredentials(JSON.parse(await readFile(path, 'utf8')));
14
+ }
15
+ catch (error) {
16
+ if (!isMissing(error))
17
+ throw error;
18
+ }
19
+ const credentials = createCredentials();
20
+ await saveCredentials(path, credentials);
21
+ return credentials;
22
+ }
23
+ export async function replaceAccessKey(wakeRoot, accessKey) {
24
+ if (accessKey.trim() === '')
25
+ throw new Error('UI access key must not be empty');
26
+ const path = credentialsPath(wakeRoot);
27
+ return mutateCredentials(path, async () => {
28
+ const current = await loadOrCreateCredentials(wakeRoot);
29
+ const replacement = {
30
+ ...current,
31
+ accessKey,
32
+ sessionPassword: randomBytes(32).toString('base64url'),
33
+ };
34
+ await saveCredentials(path, replacement);
35
+ return replacement;
36
+ });
37
+ }
38
+ export async function createPairingGrant(wakeRoot, now = new Date()) {
39
+ const path = credentialsPath(wakeRoot);
40
+ return mutateCredentials(path, async () => {
41
+ const current = await loadOrCreateCredentials(wakeRoot);
42
+ const value = randomBytes(24).toString('base64url');
43
+ const expiresAt = new Date(now.getTime() + pairingGrantLifetimeMs).toISOString();
44
+ const active = (current.pairingGrants ?? [])
45
+ .filter((grant) => grant.expiresAt > now.toISOString())
46
+ .slice(-19);
47
+ await saveCredentials(path, {
48
+ ...current,
49
+ pairingGrants: [...active, { hash: grantHash(value), expiresAt }],
50
+ });
51
+ return { value, expiresAt };
52
+ });
53
+ }
54
+ export async function redeemPairingGrant(wakeRoot, value, now = new Date()) {
55
+ const path = credentialsPath(wakeRoot);
56
+ return mutateCredentials(path, async () => {
57
+ const current = await loadOrCreateCredentials(wakeRoot);
58
+ const nowIso = now.toISOString();
59
+ const hash = grantHash(value);
60
+ const grants = current.pairingGrants ?? [];
61
+ const matching = grants.find((grant) => grant.hash === hash && grant.expiresAt > nowIso);
62
+ const remaining = grants.filter((grant) => grant.expiresAt > nowIso && grant.hash !== hash);
63
+ if (matching === undefined) {
64
+ if (remaining.length !== grants.length)
65
+ await saveCredentials(path, { ...current, pairingGrants: remaining });
66
+ return false;
67
+ }
68
+ await saveCredentials(path, { ...current, pairingGrants: remaining });
69
+ return true;
70
+ });
71
+ }
72
+ export function verifyAccessKey(candidate, expected) {
73
+ const left = Buffer.from(candidate);
74
+ const right = Buffer.from(expected);
75
+ return left.byteLength === right.byteLength && timingSafeEqual(left, right);
76
+ }
77
+ function createCredentials() {
78
+ return {
79
+ accessKey: randomBytes(24).toString('base64url'),
80
+ sessionPassword: randomBytes(32).toString('base64url'),
81
+ createdAt: new Date().toISOString(),
82
+ pairingGrants: [],
83
+ };
84
+ }
85
+ async function saveCredentials(path, credentials) {
86
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
87
+ const temporaryPath = `${path}.${process.pid}.${randomBytes(8).toString('hex')}.tmp`;
88
+ await writeFile(temporaryPath, JSON.stringify(credentials), { encoding: 'utf8', mode: 0o600 });
89
+ if (process.platform !== 'win32')
90
+ await chmod(temporaryPath, 0o600);
91
+ await rename(temporaryPath, path);
92
+ }
93
+ async function mutateCredentials(path, mutation) {
94
+ return withFileLock(credentialLockPath(path), mutation, {
95
+ waitMs: 5_000,
96
+ retryIntervalMs: 10,
97
+ });
98
+ }
99
+ function credentialLockPath(credentials) {
100
+ return join(dirname(dirname(credentials)), 'locks', credentialLockName);
101
+ }
102
+ function decodeCredentials(value) {
103
+ if (typeof value !== 'object' ||
104
+ value === null ||
105
+ !('accessKey' in value) ||
106
+ !('sessionPassword' in value) ||
107
+ !('createdAt' in value) ||
108
+ typeof value.accessKey !== 'string' ||
109
+ typeof value.sessionPassword !== 'string' ||
110
+ typeof value.createdAt !== 'string' ||
111
+ Buffer.from(value.sessionPassword, 'base64url').byteLength !== 32)
112
+ throw new Error('Wake UI credentials are malformed');
113
+ return {
114
+ accessKey: value.accessKey,
115
+ sessionPassword: value.sessionPassword,
116
+ createdAt: value.createdAt,
117
+ pairingGrants: 'pairingGrants' in value && Array.isArray(value.pairingGrants)
118
+ ? value.pairingGrants.flatMap((grant) => typeof grant === 'object' &&
119
+ grant !== null &&
120
+ 'hash' in grant &&
121
+ 'expiresAt' in grant &&
122
+ typeof grant.hash === 'string' &&
123
+ typeof grant.expiresAt === 'string'
124
+ ? [{ hash: grant.hash, expiresAt: grant.expiresAt }]
125
+ : [])
126
+ : [],
127
+ };
128
+ }
129
+ function grantHash(value) {
130
+ return createHash('sha256').update(value).digest('base64url');
131
+ }
132
+ function isMissing(error) {
133
+ return error instanceof Error && 'code' in error && error.code === 'ENOENT';
134
+ }
@@ -0,0 +1,7 @@
1
+ import { defineClosedVocabulary } from '../../kernel/index.js';
2
+ export const SurfaceSessionAttribute = defineClosedVocabulary({
3
+ Operator: 'operator',
4
+ });
5
+ export const SurfaceCookieSecurity = defineClosedVocabulary({
6
+ Auto: 'auto',
7
+ });
@@ -1,4 +1,5 @@
1
1
  import { readFile } from 'node:fs/promises';
2
+ import qrcodeTerminal from 'qrcode-terminal';
2
3
  import { ExecutionStreamKind, RunStatus } from '../../execution/index.js';
3
4
  const defaultBudget = { maxAdvances: 100, maxRuns: 100, maxDurationMs: 30_000 };
4
5
  /** Parses Surface vocabulary only; Bootstrap supplies every application facade. */
@@ -18,8 +19,9 @@ export function parseWakeCommand(arguments_) {
18
19
  return parseRunCommand(arguments_.slice(1));
19
20
  case 'validate-state':
20
21
  return parseValidateState(arguments_.slice(1));
21
- case 'api':
22
22
  case 'ui':
23
+ return parseUiCommand(arguments_.slice(1));
24
+ case 'api':
23
25
  return { kind: command, ...parseHostOptions(arguments_.slice(1)) };
24
26
  case 'tick':
25
27
  case 'start':
@@ -37,6 +39,22 @@ export function parseWakeCommand(arguments_) {
37
39
  throw new Error(`Unknown wake command: ${command ?? ''}`);
38
40
  }
39
41
  }
42
+ function parseUiCommand(arguments_) {
43
+ if (arguments_[0] !== 'token')
44
+ return { kind: 'ui', ...parseHostOptions(arguments_) };
45
+ let index = 1;
46
+ let accessKey;
47
+ if (arguments_[index] === 'set') {
48
+ accessKey = requiredArgument(arguments_[index + 1], 'UI access key');
49
+ index += 2;
50
+ }
51
+ const options = parseHostOptions(arguments_.slice(index), false);
52
+ return {
53
+ kind: 'ui-token',
54
+ ...(accessKey === undefined ? {} : { accessKey }),
55
+ ...(options.wakeRoot === undefined ? {} : { wakeRoot: options.wakeRoot }),
56
+ };
57
+ }
40
58
  // eslint-disable-next-line complexity -- the resolution flags are mutually exclusive by design.
41
59
  function parseRunCommand(arguments_) {
42
60
  if (arguments_[0] !== 'resolve')
@@ -165,6 +183,9 @@ export async function runWakeCommand(command, applications, output, signal) {
165
183
  case 'ui':
166
184
  await applications.ui.start(command);
167
185
  return;
186
+ case 'ui-token':
187
+ output.write(await formatUiTokenOutput(auth(applications).token(command.accessKey)));
188
+ return;
168
189
  case 'audit':
169
190
  for (const record of await applications.audit.read(command.workItemId))
170
191
  output.write(`${JSON.stringify(record)}\n`);
@@ -183,6 +204,21 @@ export async function runWakeCommand(command, applications, output, signal) {
183
204
  }
184
205
  }
185
206
  }
207
+ async function formatUiTokenOutput(message) {
208
+ const text = await message;
209
+ const urls = [...text.matchAll(/^\s*Public:\s+(https:\/\/\S+)$/gm)].map((match) => match[1]);
210
+ if (urls.length === 0)
211
+ return `${text}\n`;
212
+ const qr = urls.map((url) => `QR code:\n${renderQr(url)}`).join('\n');
213
+ return `${text}\n${qr}\n`;
214
+ }
215
+ function renderQr(url) {
216
+ let output = '';
217
+ qrcodeTerminal.generate(url, { small: true }, (qr) => {
218
+ output = qr;
219
+ });
220
+ return output;
221
+ }
186
222
  async function resolveCliOutcome(resolution) {
187
223
  if (resolution.status === RunStatus.Failed)
188
224
  return resolution;
@@ -198,6 +234,11 @@ function runs(applications) {
198
234
  throw new Error('Run CLI applications were not composed');
199
235
  return applications.runs;
200
236
  }
237
+ function auth(applications) {
238
+ if (applications.auth === undefined)
239
+ throw new Error('UI auth CLI application was not composed');
240
+ return applications.auth;
241
+ }
201
242
  function writeResult(output, value) {
202
243
  if (value !== undefined)
203
244
  output.write(`${JSON.stringify(value)}\n`);
@@ -10,6 +10,8 @@ export const usage = [
10
10
  ' wake stop Wait for active runs to finish',
11
11
  ' wake smoke Smoke-test the configured runner',
12
12
  ' wake ui Run the control-plane UI server',
13
+ ' wake ui token Print the UI login access key',
14
+ ' wake ui token set <key> Replace the UI login access key',
13
15
  ' wake audit Show autonomous decision audit history',
14
16
  ' wake correlate Manually correlate a resource to a work item',
15
17
  ' wake run resolve Resolve an escalated ambiguous run',
@@ -12,6 +12,10 @@ export const surfacesConfigSchema = z
12
12
  web: z
13
13
  .object({
14
14
  enabled: z.boolean().default(false),
15
+ auth: z
16
+ .object({ disabled: z.boolean().default(false) })
17
+ .strict()
18
+ .default({ disabled: false }),
15
19
  publicUrl: z
16
20
  .string()
17
21
  .trim()
@@ -22,10 +26,13 @@ export const surfacesConfigSchema = z
22
26
  .optional(),
23
27
  })
24
28
  .strict()
25
- .default({ enabled: false }),
29
+ .default({ enabled: false, auth: { disabled: false } }),
26
30
  })
27
31
  .strict()
28
- .default({ api: { enabled: false, host: '127.0.0.1', port: 4317 }, web: { enabled: false } })
32
+ .default({
33
+ api: { enabled: false, host: '127.0.0.1', port: 4317 },
34
+ web: { enabled: false, auth: { disabled: false } },
35
+ })
29
36
  .superRefine((value, context) => {
30
37
  if (value.web.enabled && !value.api.enabled)
31
38
  context.addIssue({
@@ -42,6 +49,7 @@ export const surfacesConfigSchema = z
42
49
  },
43
50
  web: {
44
51
  enabled: value.web.enabled ?? false,
52
+ auth: { disabled: value.web.auth.disabled ?? false },
45
53
  ...(value.web.publicUrl === undefined ? {} : { publicUrl: value.web.publicUrl }),
46
54
  },
47
55
  }));
@@ -1,5 +1,7 @@
1
1
  export * from './api/contracts/index.js';
2
2
  export * from './api/http-server.js';
3
+ export * from './auth/credentials.js';
4
+ export * from './auth/vocabulary.js';
3
5
  export * from './api/presenters/activities.js';
4
6
  export * from './api/presenters/board.js';
5
7
  export * from './api/presenters/status.js';