@atolis-hq/wake 0.3.115 → 0.3.117

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.
@@ -1,54 +1,100 @@
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
+ /**
9
+ * The production HTTP surface. Public login routes are declared separately;
10
+ * every operational API route is protected in its own Fastify scope before
11
+ * Fastify parses the request body.
12
+ */
13
+ export function createSurfaceHttpServer(options) {
14
+ const app = Fastify({ bodyLimit: 64 * 1024, logger: { level: 'error' }, trustProxy: true });
15
+ app.register(rateLimit, { global: false });
16
+ const authDisabled = options.auth?.disabled === true;
17
+ app.register(secureSession, {
18
+ key: Buffer.from(options.credentials.sessionPassword, 'base64url'),
19
+ cookieName: 'wake_session',
20
+ expiry: 24 * 60 * 60,
21
+ cookie: { httpOnly: true, sameSite: 'lax', secure: SurfaceCookieSecurity.Auto, path: '/' },
7
22
  });
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,
23
+ app.setErrorHandler((error, request, reply) => {
24
+ request.log.error({ err: error }, 'Wake HTTP request failed');
25
+ if (isFastifyBodyLimitError(error))
26
+ return sendFastifyJson(reply, {
27
+ status: 413,
28
+ body: problemDetails(413, 'Payload Too Large', 'The request body is too large.', {
29
+ code: 'payload-too-large',
30
+ }),
31
+ contentType: 'application/problem+json',
32
+ }, false);
33
+ if (error instanceof SyntaxError || isFastifyMalformedJsonError(error))
34
+ return sendFastifyJson(reply, errorResult(new MalformedJsonError()), false);
35
+ return sendFastifyJson(reply, errorResult(error), false);
51
36
  });
37
+ app.get('/api/v1/auth/session', async (request, reply) => {
38
+ if (authDisabled)
39
+ return { authenticated: true };
40
+ if (request.session.get(SurfaceSessionAttribute.Operator) === true)
41
+ return { authenticated: true };
42
+ return reply.code(401).send({ status: 401, title: 'Unauthorized' });
43
+ });
44
+ if (!authDisabled)
45
+ app.post('/api/v1/auth/login', { bodyLimit: 1024, config: { rateLimit: { max: 5, timeWindow: '1 minute' } } }, async (request, reply) => {
46
+ const key = typeof request.body?.accessKey === 'string' ? request.body.accessKey : '';
47
+ if (!verifyAccessKey(key, options.credentials.accessKey))
48
+ return reply.code(401).send({ status: 401, title: 'Unauthorized' });
49
+ request.session.set(SurfaceSessionAttribute.Operator, true);
50
+ return { authenticated: true };
51
+ });
52
+ if (!authDisabled)
53
+ app.post('/api/v1/auth/redeem', { bodyLimit: 1024, config: { rateLimit: { max: 5, timeWindow: '1 minute' } } }, async (request, reply) => {
54
+ const grant = typeof request.body?.grant === 'string' ? request.body.grant : '';
55
+ if (options.auth === undefined || !(await options.auth.redeemGrant(grant)))
56
+ return reply.code(401).send({ status: 401, title: 'Unauthorized' });
57
+ request.session.set(SurfaceSessionAttribute.Operator, true);
58
+ return { authenticated: true };
59
+ });
60
+ app.register((protectedApi, _pluginOptions, done) => {
61
+ protectedApi.addHook('onRequest', async (request, reply) => {
62
+ if (!authDisabled && request.session.get(SurfaceSessionAttribute.Operator) !== true)
63
+ return reply.code(401).send({ status: 401, title: 'Unauthorized' });
64
+ });
65
+ protectedApi.all('/*', async (request, reply) => {
66
+ const result = await options.dispatcher.dispatch(request.method, request.raw.url ?? request.url, request.body);
67
+ if (result === undefined)
68
+ return sendFastifyJson(reply, {
69
+ status: 404,
70
+ body: problemDetails(404, 'Not Found', `No route for ${request.url}`),
71
+ contentType: 'application/problem+json',
72
+ }, request.method === 'HEAD');
73
+ return sendFastifyJson(reply, result, request.method === 'HEAD');
74
+ });
75
+ done();
76
+ }, { prefix: '/api/v1' });
77
+ app.route({
78
+ method: ['GET', 'HEAD'],
79
+ url: '/*',
80
+ handler: async (request, reply) => {
81
+ const pathname = new URL(request.raw.url ?? request.url, 'http://wake.local').pathname;
82
+ const head = request.method === 'HEAD';
83
+ const asset = await options.assets?.get(pathname);
84
+ if (asset !== undefined)
85
+ return sendFastifyAsset(reply, asset, head);
86
+ if (routeBrowserRequest(request.method, pathname) === BrowserRouteOutcome.Spa) {
87
+ const index = await options.assets?.get('/index.html');
88
+ if (index !== undefined)
89
+ return sendFastifyAsset(reply, { ...index, contentType: 'text/html; charset=utf-8' }, head);
90
+ }
91
+ return reply
92
+ .code(404)
93
+ .type('text/plain; charset=utf-8')
94
+ .send(head ? undefined : 'Not Found');
95
+ },
96
+ });
97
+ return app;
52
98
  }
53
99
  function errorResult(error) {
54
100
  if (error instanceof MalformedJsonError)
@@ -85,37 +131,30 @@ function isUpstreamProviderError(error) {
85
131
  typeof error.status === 'number' &&
86
132
  error.status >= 400);
87
133
  }
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
134
  class MalformedJsonError extends Error {
104
135
  }
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
- });
136
+ function sendFastifyJson(reply, result, head) {
137
+ reply.code(result.status);
138
+ reply.headers(result.headers ?? {});
139
+ reply.type(result.contentType ?? 'application/json; charset=utf-8');
140
+ return reply.send(head ? undefined : result.body);
113
141
  }
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);
142
+ function sendFastifyAsset(reply, asset, head) {
143
+ reply.code(200);
144
+ reply.headers(asset.headers);
145
+ reply.header('content-length', asset.body.byteLength);
146
+ reply.type(asset.contentType);
147
+ return reply.send(head ? undefined : asset.body);
148
+ }
149
+ function isFastifyBodyLimitError(error) {
150
+ return (typeof error === 'object' &&
151
+ error !== null &&
152
+ 'code' in error &&
153
+ error.code === 'FST_ERR_CTP_BODY_TOO_LARGE');
154
+ }
155
+ function isFastifyMalformedJsonError(error) {
156
+ return (typeof error === 'object' &&
157
+ error !== null &&
158
+ 'code' in error &&
159
+ error.code === 'FST_ERR_CTP_INVALID_JSON_BODY');
121
160
  }
@@ -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';