@anhlp/alp-cli 0.0.1-beta.4 → 0.0.1-beta.7
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/dist/THIRD-PARTY-NOTICES.txt +26 -1
- package/dist/acp/main.js +1 -1
- package/dist/acp.js +152 -33
- package/dist/alp-web/THIRD-PARTY-NOTICES.txt +666 -0
- package/dist/alp-web/alp-boundary.json +1 -0
- package/dist/alp-web/assets/TerminalPanel-BeMws9CP.js +22 -0
- package/dist/alp-web/assets/highlighter-BnicKQ_d.js +18 -0
- package/dist/alp-web/assets/index-Dl7motn1.js +59 -0
- package/dist/alp-web/assets/index-DwqDSiIi.css +1 -0
- package/dist/alp-web/index.html +2 -2
- package/dist/alp-web.js +529 -172
- package/dist/alpd.js +10623 -2570
- package/dist/backup.js +1 -1
- package/dist/build-manifest.json +22 -2
- package/dist/cli.js +28 -3
- package/dist/daemon.d.ts +1 -1
- package/dist/daemon.js +5 -0
- package/dist/interfaces.d.ts +13 -1
- package/dist/interfaces.js +95 -11
- package/dist/paths.d.ts +1 -0
- package/dist/paths.js +2 -1
- package/dist/roles.d.ts +15 -0
- package/dist/roles.js +16 -0
- package/dist/self-update.d.ts +149 -0
- package/dist/self-update.js +399 -0
- package/dist/sessions.d.ts +4 -0
- package/dist/sessions.js +22 -1
- package/dist/tasks.js +22 -8
- package/dist/terminal-native/README.md +201 -0
- package/dist/terminal-native/prebuilt/darwin-arm64/manifest.json +11 -0
- package/dist/terminal-native/prebuilt/darwin-arm64/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/darwin-x64/manifest.json +11 -0
- package/dist/terminal-native/prebuilt/darwin-x64/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-arm64-musl/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-x64-glibc/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-x64-musl/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-x64-musl/terminal-owner +0 -0
- package/dist/terminal-native/terminal-owner.c +389 -0
- package/dist/terminal.d.ts +5 -0
- package/dist/terminal.js +4 -3
- package/dist/usage.d.ts +1 -1
- package/dist/usage.js +14 -5
- package/dist/web-service.d.ts +22 -4
- package/dist/web-service.js +32 -8
- package/package.json +6 -5
- package/src/cli.js +35 -4
- package/src/daemon.js +3 -0
- package/src/interfaces.js +101 -12
- package/src/paths.js +3 -1
- package/src/roles.js +26 -0
- package/src/self-update.js +406 -0
- package/src/sessions.js +23 -2
- package/src/tasks.js +22 -8
- package/src/terminal.js +4 -3
- package/src/usage.js +14 -5
- package/src/web-service.js +56 -13
- package/dist/alp-web/assets/TerminalPanel-PrU2l3u5.js +0 -16
- package/dist/alp-web/assets/index-BJdBTDFX.css +0 -1
- package/dist/alp-web/assets/index-DpfiPv5s.js +0 -52
- package/src/web/grant.js +0 -204
- package/src/web/main.js +0 -285
- package/src/web/serve.js +0 -144
package/src/web/grant.js
DELETED
|
@@ -1,204 +0,0 @@
|
|
|
1
|
-
// @ts-check
|
|
2
|
-
import { mkdir, realpath, stat } from 'node:fs/promises';
|
|
3
|
-
import path from 'node:path';
|
|
4
|
-
import { assertPrivateDirectory, connect } from '@anhlp/alp-client/index';
|
|
5
|
-
import { createCredential, listCredentials, revokeCredential, updateCredential } from '@anhlp/alp-gateway';
|
|
6
|
-
import { DEFAULT_PERMISSIONS, PERMISSIONS } from '@anhlp/alp-gateway/policy';
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* The one gateway credential `alp web` hands the browser (docs/alp/web.md): its token travels in
|
|
10
|
-
* the URL the CLI opens, so it is a real `alpgw1.*` credential with the least the app needs.
|
|
11
|
-
*
|
|
12
|
-
* Single writer: the credentials live in `<home>/web/credentials.json`, a file of alp-web's own
|
|
13
|
-
* (not the standalone gateway's `<home>/gateway`). Only the process holding the `web` integration
|
|
14
|
-
* lock writes it, and inside that process every write goes through one queue (`serial`), so no
|
|
15
|
-
* two writes interleave their read-modify-write. Another tool must not write it while the service
|
|
16
|
-
* runs. Because the file is alp-web's own, `alp-gateway credential list/revoke` (which read
|
|
17
|
-
* `<home>/gateway`) do not see this credential: `alp web rotate` is the way to replace or end it.
|
|
18
|
-
* The gateway's own checks apply to this path as to its default one: the directory must be the
|
|
19
|
-
* user's and private (0700, checked on every start, not only on a write) and the file 0600 and the
|
|
20
|
-
* user's, else nothing is read or written and the service does not start.
|
|
21
|
-
*
|
|
22
|
-
* Grant: permissions are DEFAULT_PERMISSIONS + workspace.write, plus `web.permissions` from the
|
|
23
|
-
* user's settings when every entry is a permission a credential may hold (with any unknown entry
|
|
24
|
-
* the whole list is ignored, with a warning naming it, so the grant stays the default). Workspaces are alpd's project
|
|
25
|
-
* registry (live projects) ∪ the `--project` directory the caller named; with none, a private
|
|
26
|
-
* empty directory stands in (a credential needs one workspace, and it grants nothing).
|
|
27
|
-
*/
|
|
28
|
-
|
|
29
|
-
export const LABEL = 'alp web (this machine)';
|
|
30
|
-
export const BASE_PERMISSIONS = Object.freeze([...DEFAULT_PERMISSIONS, 'workspace.write']);
|
|
31
|
-
|
|
32
|
-
/** Where alp-web keeps its credentials. @param {string} home */
|
|
33
|
-
export const webGatewayHome = home => path.join(home, 'web');
|
|
34
|
-
|
|
35
|
-
/**
|
|
36
|
-
* The permissions to grant: the base set and, when valid, `web.permissions`.
|
|
37
|
-
* @param {unknown} extra the `web.permissions` setting
|
|
38
|
-
* @param {(message: string) => void} [warn]
|
|
39
|
-
*/
|
|
40
|
-
export function grantPermissions(extra, warn = () => {}) {
|
|
41
|
-
const wanted = new Set(BASE_PERMISSIONS);
|
|
42
|
-
if (extra !== undefined) {
|
|
43
|
-
const unknown = Array.isArray(extra) ? extra.filter(entry => typeof entry !== 'string' || !PERMISSIONS.includes(entry)) : [extra];
|
|
44
|
-
if (!unknown.length) for (const entry of /** @type {string[]} */ (extra)) wanted.add(entry);
|
|
45
|
-
else warn(`ignoring web.permissions: ${unknown.map(entry => JSON.stringify(entry)).join(', ')} ${unknown.length === 1 ? 'is not a permission' : 'are not permissions'} a credential may hold (${PERMISSIONS.join(', ')}); the default grant (${BASE_PERMISSIONS.join(', ')}) is in use`);
|
|
46
|
-
}
|
|
47
|
-
// As the gateway stores them: a write permission holds its read (credentials.js checkPermissions).
|
|
48
|
-
if (wanted.has('session.write')) wanted.add('session.read');
|
|
49
|
-
if (wanted.has('project.write') || wanted.has('library.write')) wanted.add('project.read');
|
|
50
|
-
return PERMISSIONS.filter(permission => wanted.has(permission));
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
/**
|
|
54
|
-
* Existing directories among `paths`, as the gateway stores workspaces: absolute and normalized as
|
|
55
|
-
* given, one per real path (the first wins). Anything else is dropped, never resolved further.
|
|
56
|
-
* @param {Iterable<unknown>} paths
|
|
57
|
-
* @returns {Promise<Array<{ path: string, canonical: string }>>}
|
|
58
|
-
*/
|
|
59
|
-
export async function existingWorkspaces(paths) {
|
|
60
|
-
/** @type {Array<{ path: string, canonical: string }>} */
|
|
61
|
-
const found = [];
|
|
62
|
-
for (const entry of paths) {
|
|
63
|
-
if (typeof entry !== 'string' || !path.isAbsolute(entry) || path.resolve(entry) !== entry || entry.includes('\0')) continue;
|
|
64
|
-
const canonical = await realpath(entry).catch(() => undefined);
|
|
65
|
-
if (!canonical || !(await stat(canonical).then(info => info.isDirectory(), () => false))) continue;
|
|
66
|
-
if (!found.some(known => known.canonical === canonical)) found.push({ path: entry, canonical });
|
|
67
|
-
}
|
|
68
|
-
return found;
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
/**
|
|
72
|
-
* The live project roots in alpd's registry, through its socket; undefined when alpd cannot answer
|
|
73
|
-
* within `timeoutMs` (the grant is then left as it is).
|
|
74
|
-
* @param {string | undefined} socket @param {{ timeoutMs?: number }} [options]
|
|
75
|
-
*/
|
|
76
|
-
export async function registryRoots(socket, { timeoutMs = 3_000 } = {}) {
|
|
77
|
-
if (!socket) return undefined;
|
|
78
|
-
/** @type {any} */
|
|
79
|
-
let client;
|
|
80
|
-
let finished = false;
|
|
81
|
-
let timer;
|
|
82
|
-
const late = new Promise(resolve => { timer = setTimeout(() => resolve(undefined), timeoutMs); });
|
|
83
|
-
// A connection that opens after the answer was given up on is closed at once.
|
|
84
|
-
const opened = (/** @type {any} */ value) => { if (finished) { try { value.close(); } catch {} } else client = value; };
|
|
85
|
-
try { return await Promise.race([listRoots(socket, opened), late]); }
|
|
86
|
-
finally { finished = true; clearTimeout(timer); try { client?.close(); } catch {} }
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
/** @param {string} socket @param {(client: any) => void} opened */
|
|
90
|
-
async function listRoots(socket, opened) {
|
|
91
|
-
let client;
|
|
92
|
-
try {
|
|
93
|
-
client = await connect(socket, { name: 'alp-web', version: '1' });
|
|
94
|
-
opened(client);
|
|
95
|
-
/** @type {string[]} */
|
|
96
|
-
const roots = [];
|
|
97
|
-
let cursor;
|
|
98
|
-
for (let page = 0; page < 100; page++) {
|
|
99
|
-
const result = /** @type {any} */ (await client.request('project.list', { limit: 500, ...(cursor ? { cursor } : {}) }));
|
|
100
|
-
for (const project of result?.projects ?? []) if (typeof project?.root === 'string' && !project.removedAt) roots.push(project.root);
|
|
101
|
-
cursor = result?.nextCursor;
|
|
102
|
-
if (!cursor) return roots;
|
|
103
|
-
}
|
|
104
|
-
return undefined;
|
|
105
|
-
} catch { return undefined; } finally { try { client?.close(); } catch {} }
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
/** @param {Array<{ path: string, canonical: string }>} a @param {Array<{ path: string, canonical: string }>} b */
|
|
110
|
-
const sameWorkspaces = (a, b) => {
|
|
111
|
-
const key = (/** @type {Array<{ path: string, canonical: string }>} */ list) => JSON.stringify(list.map(entry => [entry.path, entry.canonical]).sort());
|
|
112
|
-
return key(a) === key(b);
|
|
113
|
-
};
|
|
114
|
-
/** @param {string[]} a @param {string[]} b */
|
|
115
|
-
const samePermissions = (a, b) => JSON.stringify([...a].sort()) === JSON.stringify([...b].sort());
|
|
116
|
-
|
|
117
|
-
/**
|
|
118
|
-
* Owns alp-web's credential while this process holds the web lock.
|
|
119
|
-
* @param {{
|
|
120
|
-
* home: string,
|
|
121
|
-
* store: import('@anhlp/alp-gateway').CredentialStore,
|
|
122
|
-
* permissions: string[],
|
|
123
|
-
* project?: string,
|
|
124
|
-
* socket: () => string | undefined,
|
|
125
|
-
* log?: (message: string) => void,
|
|
126
|
-
* }} options
|
|
127
|
-
*/
|
|
128
|
-
export function createGrant({ home, store, permissions, project, socket, log = () => {} }) {
|
|
129
|
-
const credentialsHome = webGatewayHome(home);
|
|
130
|
-
const placeholder = path.join(credentialsHome, 'no-project');
|
|
131
|
-
/** @type {Promise<unknown>} */
|
|
132
|
-
let tail = Promise.resolve();
|
|
133
|
-
/** One credentials write at a time, in order. @template T @param {() => Promise<T>} run @returns {Promise<T>} */
|
|
134
|
-
const serial = run => { const result = tail.then(run); tail = result.catch(() => {}); return result; };
|
|
135
|
-
/** @type {string | undefined} */
|
|
136
|
-
let id;
|
|
137
|
-
/** The last registry answer, kept while alpd is down. @type {string[]} */
|
|
138
|
-
let known = [];
|
|
139
|
-
/** The refresh under way, if any: a timer tick while one runs joins it rather than queueing another. @type {Promise<boolean> | undefined} */
|
|
140
|
-
let refreshing;
|
|
141
|
-
|
|
142
|
-
/** The workspaces to grant now. */
|
|
143
|
-
async function wanted() {
|
|
144
|
-
const roots = await registryRoots(socket());
|
|
145
|
-
if (roots) known = roots;
|
|
146
|
-
const found = await existingWorkspaces([...(project ? [project] : []), ...known]);
|
|
147
|
-
if (found.length) return found;
|
|
148
|
-
await mkdir(placeholder, { recursive: true, mode: 0o700 });
|
|
149
|
-
return existingWorkspaces([placeholder]);
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
return {
|
|
153
|
-
get id() { return id; },
|
|
154
|
-
/** Resolves once every queued credentials write has finished. */
|
|
155
|
-
settled: () => tail.then(() => undefined),
|
|
156
|
-
/**
|
|
157
|
-
* Reuses the credential of `token` when it still verifies, else creates one; revokes every other
|
|
158
|
-
* live credential in alp-web's file. Returns the token to publish.
|
|
159
|
-
* @param {{ token?: unknown, credentialId?: unknown }} previous what web.json held
|
|
160
|
-
*/
|
|
161
|
-
ensure: previous => serial(async () => {
|
|
162
|
-
// Throws unless the directory is the user's and private; creates it (0700) on the first start.
|
|
163
|
-
await assertPrivateDirectory(credentialsHome, { create: true }).catch(error => {
|
|
164
|
-
throw new Error(`alp web keeps its credentials in ${credentialsHome}, which must be a directory owned by you with private permissions (0700); run chmod 700 on it (${error?.message ?? error})`, { cause: error });
|
|
165
|
-
});
|
|
166
|
-
await store.reload();
|
|
167
|
-
const reused = typeof previous.token === 'string' ? store.verify(previous.token) : undefined;
|
|
168
|
-
let token;
|
|
169
|
-
if (reused && reused.id === previous.credentialId) { id = reused.id; token = /** @type {string} */ (previous.token); }
|
|
170
|
-
else {
|
|
171
|
-
const created = await createCredential(credentialsHome, { label: LABEL, workspaces: (await wanted()).map(entry => entry.path), permissions });
|
|
172
|
-
id = created.credential.id;
|
|
173
|
-
token = created.token;
|
|
174
|
-
log(`created credential ${id}`);
|
|
175
|
-
}
|
|
176
|
-
for (const entry of await listCredentials(credentialsHome)) {
|
|
177
|
-
if (entry.id !== id && !entry.revokedAt) { await revokeCredential(credentialsHome, entry.id); log(`revoked stale credential ${entry.id}`); }
|
|
178
|
-
}
|
|
179
|
-
await store.reload();
|
|
180
|
-
return token;
|
|
181
|
-
}),
|
|
182
|
-
/** Brings the credential's workspaces and permissions in line; keeps its token. Never throws. */
|
|
183
|
-
refresh: () => refreshing ??= serial(async () => {
|
|
184
|
-
if (!id) return false;
|
|
185
|
-
try {
|
|
186
|
-
const current = (await listCredentials(credentialsHome)).find(entry => entry.id === id);
|
|
187
|
-
if (!current || current.revokedAt) return false;
|
|
188
|
-
const workspaces = await wanted();
|
|
189
|
-
const update = {
|
|
190
|
-
...(sameWorkspaces(current.workspaces, workspaces) ? {} : { workspaces: workspaces.map(entry => entry.path) }),
|
|
191
|
-
...(samePermissions(current.permissions, permissions) ? {} : { permissions }),
|
|
192
|
-
};
|
|
193
|
-
if (!Object.keys(update).length) return false;
|
|
194
|
-
await updateCredential(credentialsHome, id, update);
|
|
195
|
-
await store.reload();
|
|
196
|
-
log(`updated the grant of ${id}: ${workspaces.length} workspace(s)`);
|
|
197
|
-
return true;
|
|
198
|
-
} catch (error) {
|
|
199
|
-
log(`grant not refreshed: ${/** @type {any} */ (error)?.message ?? error}`);
|
|
200
|
-
return false;
|
|
201
|
-
}
|
|
202
|
-
}).finally(() => { refreshing = undefined; }),
|
|
203
|
-
};
|
|
204
|
-
}
|
package/src/web/main.js
DELETED
|
@@ -1,285 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
// @ts-check
|
|
3
|
-
/**
|
|
4
|
-
* alp-web (docs/alp/web.md): the service behind `alp web`. ONE loopback listener at `web.port`
|
|
5
|
-
* (default 7433, then the next nine ports) carries the ALP gateway and the built apps/web files.
|
|
6
|
-
* It owns the `web` integration lock and `<home>/web.json`, which names its pid, port, URL and the
|
|
7
|
-
* `alpgw1.*` token of its credential, so the CLI can open the app with the token in the address.
|
|
8
|
-
* It keeps alpd running (ALP_SUPERVISE=0 opts out) and keeps the credential's workspaces in step
|
|
9
|
-
* with alpd's project registry.
|
|
10
|
-
*
|
|
11
|
-
* node alp-web.js [--service] [--project DIR]
|
|
12
|
-
* node alp-web.js --rotate [--project DIR]
|
|
13
|
-
* `--service` (how startIntegration starts it) writes the log to <home>/logs/integrations/alp-web.log.
|
|
14
|
-
* `--rotate` (how `alp web rotate` replaces the token) takes the web lock, which fails with exit 3
|
|
15
|
-
* while the service runs, creates a new credential, revokes every other one, records the new token
|
|
16
|
-
* in web.json for the next start, releases the lock and exits. It ignores web.enabled: turning alp
|
|
17
|
-
* web off must not keep an old token alive.
|
|
18
|
-
* ALP_WEB_APP names another directory of built app files (tests).
|
|
19
|
-
*/
|
|
20
|
-
import { randomBytes } from 'node:crypto';
|
|
21
|
-
import { mkdirSync, openSync, writeSync } from 'node:fs';
|
|
22
|
-
import { chmod, link, mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
|
|
23
|
-
import path from 'node:path';
|
|
24
|
-
import { fileURLToPath } from 'node:url';
|
|
25
|
-
import { parseArgs } from 'node:util';
|
|
26
|
-
import { alpHome, connectSocket, daemonPaths } from '@anhlp/alp-client/index';
|
|
27
|
-
import { createIntegrationLock } from '@anhlp/alp-client/integration-lock';
|
|
28
|
-
import { superviseDaemon } from '@anhlp/alp-client/supervise';
|
|
29
|
-
import { validateUserSettings } from '@anhlp/alp-core/validation';
|
|
30
|
-
import { CredentialStore, createGateway, createGatewayLogger, parseToken, resolveConfig } from '@anhlp/alp-gateway';
|
|
31
|
-
import { TERMINAL_EXEC_WARNING } from '@anhlp/alp-gateway/policy';
|
|
32
|
-
import { createGrant, grantPermissions, webGatewayHome } from './grant.js';
|
|
33
|
-
import { createStaticServer } from './serve.js';
|
|
34
|
-
|
|
35
|
-
// __ALP_VERSION__ is replaced at build time (esbuild define); a run from source reports a placeholder.
|
|
36
|
-
// @ts-ignore -- a build-time constant, not a declared global
|
|
37
|
-
const VERSION = typeof __ALP_VERSION__ === 'string' ? __ALP_VERSION__ : '0.0.0-source';
|
|
38
|
-
|
|
39
|
-
export const DEFAULT_WEB_PORT = 7433;
|
|
40
|
-
/** Ports tried from web.port: it and the next nine. */
|
|
41
|
-
const PORT_TRIES = 10;
|
|
42
|
-
/** How often the workspace grant follows alpd's registry. */
|
|
43
|
-
const REFRESH_MS = Number(process.env.ALP_WEB_GRANT_REFRESH_MS) > 0 ? Number(process.env.ALP_WEB_GRANT_REFRESH_MS) : 5_000;
|
|
44
|
-
const WEB_FILE_VERSION = 2;
|
|
45
|
-
|
|
46
|
-
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
47
|
-
const appDir = () => path.resolve(process.env.ALP_WEB_APP || path.join(here, 'alp-web'));
|
|
48
|
-
const daemonEntry = () => process.env.ALP_DAEMON_ENTRY ?? path.join(here, 'alpd.js');
|
|
49
|
-
const webFile = (/** @type {string} */ home) => path.join(home, 'web.json');
|
|
50
|
-
|
|
51
|
-
/** The service's output goes to its own log: startIntegration starts it detached with stdio ignored. @param {string} home */
|
|
52
|
-
function serviceLog(home) {
|
|
53
|
-
const file = path.join(home, 'logs', 'integrations', 'alp-web.log');
|
|
54
|
-
mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
55
|
-
const fd = openSync(file, 'a', 0o600);
|
|
56
|
-
for (const stream of [process.stdout, process.stderr]) {
|
|
57
|
-
stream.write = /** @type {any} */ ((/** @type {any} */ chunk) => { try { if (typeof chunk === 'string') writeSync(fd, chunk); else writeSync(fd, Buffer.from(chunk)); } catch {} return true; });
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
/** @param {string} home @param {import('@anhlp/alp-core/log').Logger} log */
|
|
62
|
-
async function userSettings(home, log) {
|
|
63
|
-
const file = path.join(home, 'settings.json');
|
|
64
|
-
let text;
|
|
65
|
-
try { text = await readFile(file, 'utf8'); } catch { return {}; }
|
|
66
|
-
try { return /** @type {any} */ (validateUserSettings(JSON.parse(text), file)); }
|
|
67
|
-
catch (error) { log.warn(`ignoring ${file}: ${/** @type {any} */ (error)?.message ?? error}`, { code: 'ALP_SETTINGS_INVALID' }); return {}; }
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
/** What the last run published, if it was alp-web's. @param {string} home */
|
|
71
|
-
async function previousWeb(home) {
|
|
72
|
-
try {
|
|
73
|
-
const kept = JSON.parse(await readFile(webFile(home), 'utf8'));
|
|
74
|
-
if (kept?.app !== 'alp-web' || kept?.version !== WEB_FILE_VERSION || !parseToken(kept.token)) return {};
|
|
75
|
-
return { token: kept.token, credentialId: kept.credentialId };
|
|
76
|
-
} catch { return {}; }
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
/** Writes web.json whole, private, in one rename. @param {string} home @param {object} info */
|
|
80
|
-
async function publish(home, info) {
|
|
81
|
-
const file = webFile(home);
|
|
82
|
-
const temporary = `${file}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
|
|
83
|
-
try {
|
|
84
|
-
await writeFile(temporary, `${JSON.stringify(info)}\n`, { mode: 0o600, flag: 'wx' });
|
|
85
|
-
await chmod(temporary, 0o600);
|
|
86
|
-
await rename(temporary, file);
|
|
87
|
-
} catch (error) { await unlink(temporary).catch(() => {}); throw error; }
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
/** Exit code of `--rotate` when the service holds the web lock. */
|
|
91
|
-
const LOCK_HELD = 3;
|
|
92
|
-
|
|
93
|
-
/**
|
|
94
|
-
* Before the rename, the Paseo integration ran as integration `web` and kept its identity (the token
|
|
95
|
-
* paired devices sign in with, and its server id) in web.json, without `app`. Before alp-web first
|
|
96
|
-
* overwrites such a file, and only when the Paseo integration has no paseo.json yet, that identity
|
|
97
|
-
* is written to paseo.json, where the integration looks for it, so paired devices stay paired. The
|
|
98
|
-
* file appears whole (written aside, then linked into place) and an existing paseo.json is never
|
|
99
|
-
* replaced. Returns whether it carried anything.
|
|
100
|
-
* @param {string} home @param {import('@anhlp/alp-core/log').Logger} log
|
|
101
|
-
*/
|
|
102
|
-
async function carryPaseoIdentity(home, log) {
|
|
103
|
-
let legacy;
|
|
104
|
-
try { legacy = JSON.parse(await readFile(webFile(home), 'utf8')); } catch { return false; }
|
|
105
|
-
if (!legacy || typeof legacy !== 'object' || legacy.app !== undefined) return false;
|
|
106
|
-
const identity = {
|
|
107
|
-
...(typeof legacy.token === 'string' && /^[a-f0-9]{64}$/.test(legacy.token) ? { token: legacy.token } : {}),
|
|
108
|
-
...(typeof legacy.serverId === 'string' && /^alp-[a-f0-9]{16}$/.test(legacy.serverId) ? { serverId: legacy.serverId } : {}),
|
|
109
|
-
};
|
|
110
|
-
if (!Object.keys(identity).length) return false;
|
|
111
|
-
const target = path.join(home, 'paseo.json');
|
|
112
|
-
const temporary = `${target}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
|
|
113
|
-
try {
|
|
114
|
-
await writeFile(temporary, `${JSON.stringify(identity)}\n`, { mode: 0o600, flag: 'wx' });
|
|
115
|
-
await chmod(temporary, 0o600);
|
|
116
|
-
await link(temporary, target);
|
|
117
|
-
} catch (error) {
|
|
118
|
-
if (/** @type {any} */ (error)?.code === 'EEXIST') return false;
|
|
119
|
-
throw new Error(`the Paseo integration's identity in ${webFile(home)} could not be kept in ${target}, so alp web leaves web.json alone: ${/** @type {any} */ (error)?.message ?? error}`, { cause: error });
|
|
120
|
-
} finally { await unlink(temporary).catch(() => {}); }
|
|
121
|
-
log.info(`kept the Paseo integration's identity from web.json in ${target}, so paired devices stay paired`, { code: 'ALP_WEB_PASEO_IDENTITY' });
|
|
122
|
-
return true;
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
/**
|
|
126
|
-
* `--rotate`: a new credential and token, recorded in web.json, under the web lock.
|
|
127
|
-
* @param {string} home @param {string | undefined} project @param {any} settings @param {import('@anhlp/alp-core/log').Logger} log
|
|
128
|
-
*/
|
|
129
|
-
async function rotate(home, project, settings, log) {
|
|
130
|
-
const lock = createIntegrationLock(home, 'web');
|
|
131
|
-
const { acquired, lock: held } = await lock.acquire();
|
|
132
|
-
if (!acquired) {
|
|
133
|
-
process.stderr.write(`alp web runs (pid ${held.pid}); it must stop before its token is rotated\n`);
|
|
134
|
-
process.exit(LOCK_HELD);
|
|
135
|
-
}
|
|
136
|
-
let code = 0;
|
|
137
|
-
try {
|
|
138
|
-
await carryPaseoIdentity(home, log);
|
|
139
|
-
const permissions = grantPermissions(settings?.web?.permissions, message => log.warn(message, { code: 'ALP_WEB_PERMISSIONS_IGNORED' }));
|
|
140
|
-
const store = new CredentialStore({ home: webGatewayHome(home), logger: log });
|
|
141
|
-
try {
|
|
142
|
-
const socket = daemonPaths(home).socket;
|
|
143
|
-
const grant = createGrant({ home, store, permissions, project, socket: () => socket, log: message => log.info(message, { code: 'ALP_WEB_GRANT' }) });
|
|
144
|
-
// No previous token to keep: a new credential, and every other one revoked.
|
|
145
|
-
const token = await grant.ensure({});
|
|
146
|
-
await grant.settled();
|
|
147
|
-
await publish(home, { version: WEB_FILE_VERSION, app: 'alp-web', token, credentialId: grant.id });
|
|
148
|
-
log.info(`rotated the token: credential ${grant.id}`, { code: 'ALP_WEB_ROTATED' });
|
|
149
|
-
} finally { store.close(); }
|
|
150
|
-
} catch (error) {
|
|
151
|
-
log.error('alp web could not rotate its token', { code: 'ALP_WEB_ROTATE_FAILED', error });
|
|
152
|
-
code = 1;
|
|
153
|
-
}
|
|
154
|
-
// A failed release leaves the lock (fail closed); the next acquire reclaims it once this pid is gone.
|
|
155
|
-
await lock.release().catch(error => { log.error('web lock not released', { code: 'ALP_LOCK_RELEASE_FAILED', error }); code = 1; });
|
|
156
|
-
process.exit(code);
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
/** The page's Content-Security-Policy on `port`: its own origin only, the socket included. @param {number} port */
|
|
160
|
-
const policy = port => {
|
|
161
|
-
const origins = [`127.0.0.1:${port}`, `localhost:${port}`, `[::1]:${port}`];
|
|
162
|
-
return ["default-src 'self'", "script-src 'self'", "style-src 'self' 'unsafe-inline'", "img-src 'self' data:", "font-src 'self'",
|
|
163
|
-
`connect-src 'self' ${origins.map(origin => `http://${origin} ws://${origin}`).join(' ')}`,
|
|
164
|
-
"object-src 'none'", "base-uri 'none'", "form-action 'none'", "frame-ancestors 'none'"].join('; ');
|
|
165
|
-
};
|
|
166
|
-
|
|
167
|
-
async function run() {
|
|
168
|
-
const { values } = parseArgs({ options: { service: { type: 'boolean' }, rotate: { type: 'boolean' }, project: { type: 'string' } }, strict: true });
|
|
169
|
-
const home = alpHome();
|
|
170
|
-
await mkdir(home, { recursive: true, mode: 0o700 });
|
|
171
|
-
if (values.service) serviceLog(home);
|
|
172
|
-
const log = createGatewayLogger();
|
|
173
|
-
const settings = await userSettings(home, log);
|
|
174
|
-
if (values.rotate) return rotate(home, values.project ? path.resolve(values.project) : undefined, settings, log);
|
|
175
|
-
if (settings?.web?.enabled === false) {
|
|
176
|
-
log.info('alp web is disabled by settings ("web.enabled": false)', { code: 'ALP_WEB_DISABLED' });
|
|
177
|
-
process.exit(0);
|
|
178
|
-
}
|
|
179
|
-
const project = values.project ? path.resolve(values.project) : undefined;
|
|
180
|
-
|
|
181
|
-
const lock = createIntegrationLock(home, 'web');
|
|
182
|
-
const { acquired, lock: held } = await lock.acquire();
|
|
183
|
-
if (!acquired) {
|
|
184
|
-
log.info(`alp web already runs (pid ${held.pid})`, { code: 'ALP_LOCK_HELD' });
|
|
185
|
-
process.exit(0);
|
|
186
|
-
}
|
|
187
|
-
// A failed release leaves the lock and its guard in place (fail closed); report it and stop anyway.
|
|
188
|
-
const releaseLock = () => lock.release().catch(error => log.error('web lock not released; alp web stops anyway', { code: 'ALP_LOCK_RELEASE_FAILED', error }));
|
|
189
|
-
|
|
190
|
-
/** @type {Array<() => Promise<unknown>>} */
|
|
191
|
-
const cleanups = [];
|
|
192
|
-
let shuttingDown = false;
|
|
193
|
-
/** Startup, once it began; shutdown waits for it, so nothing it does lands after the lock is released. @type {Promise<unknown>} */
|
|
194
|
-
let startup = Promise.resolve();
|
|
195
|
-
/** @param {number} [code] */
|
|
196
|
-
const shutdown = async (code = 0) => {
|
|
197
|
-
// A later signal or uncaught exception starts no second shutdown; the first always reaches exit.
|
|
198
|
-
if (shuttingDown) return;
|
|
199
|
-
shuttingDown = true;
|
|
200
|
-
try {
|
|
201
|
-
// Startup stops at its next step once shuttingDown is set (each step is bounded).
|
|
202
|
-
await startup.catch(() => {});
|
|
203
|
-
for (const cleanup of cleanups.reverse()) await cleanup().catch(error => log.warn('a shutdown step failed', { code: 'ALP_WEB_SHUTDOWN_STEP', error }));
|
|
204
|
-
await releaseLock();
|
|
205
|
-
} finally { process.exit(code); }
|
|
206
|
-
};
|
|
207
|
-
for (const signal of /** @type {const} */ (['SIGINT', 'SIGTERM'])) process.on(signal, () => void shutdown());
|
|
208
|
-
process.on('uncaughtException', error => { log.error('uncaught exception; alp web stops', { code: 'ALP_FATAL', error }); void shutdown(1); });
|
|
209
|
-
|
|
210
|
-
startup = (async () => {
|
|
211
|
-
const stopDaemon = process.env.ALP_SUPERVISE === '0'
|
|
212
|
-
? async () => {}
|
|
213
|
-
: superviseDaemon({ home, entry: daemonEntry, by: 'alp web', log: (/** @type {string} */ message) => log.warn(message, { code: 'ALP_DAEMON_SUPERVISION' }) });
|
|
214
|
-
cleanups.push(() => stopDaemon());
|
|
215
|
-
|
|
216
|
-
const permissions = grantPermissions(settings?.web?.permissions, message => log.warn(message, { code: 'ALP_WEB_PERMISSIONS_IGNORED' }));
|
|
217
|
-
if (permissions.includes('terminal.exec')) log.warn(TERMINAL_EXEC_WARNING, { code: 'ALP_WEB_TERMINAL_EXEC' });
|
|
218
|
-
const store = new CredentialStore({ home: webGatewayHome(home), logger: log });
|
|
219
|
-
cleanups.push(async () => store.close());
|
|
220
|
-
const socket = daemonPaths(home).socket;
|
|
221
|
-
const grant = createGrant({
|
|
222
|
-
home, store, permissions, project,
|
|
223
|
-
socket: () => socket,
|
|
224
|
-
log: message => log.info(message, { code: 'ALP_WEB_GRANT' }),
|
|
225
|
-
});
|
|
226
|
-
// A credentials write under way finishes before the process exits (no half-done temporary file).
|
|
227
|
-
cleanups.push(() => grant.settled());
|
|
228
|
-
// Before web.json is first overwritten (publish, below).
|
|
229
|
-
await carryPaseoIdentity(home, log);
|
|
230
|
-
if (shuttingDown) return;
|
|
231
|
-
const token = await grant.ensure(await previousWeb(home));
|
|
232
|
-
if (shuttingDown) return;
|
|
233
|
-
// The registry, if alpd answers already, before the first page asks for it.
|
|
234
|
-
await grant.refresh();
|
|
235
|
-
if (shuttingDown) return;
|
|
236
|
-
|
|
237
|
-
const dir = appDir();
|
|
238
|
-
let bound = 0;
|
|
239
|
-
const serveStatic = createStaticServer({ dir, csp: () => policy(bound), log: message => log.warn(message, { code: 'ALP_WEB_STATIC' }) });
|
|
240
|
-
const base = settings?.web?.port ?? DEFAULT_WEB_PORT;
|
|
241
|
-
for (let attempt = 0; ; attempt++) {
|
|
242
|
-
if (shuttingDown) return;
|
|
243
|
-
const port = base + attempt;
|
|
244
|
-
const config = resolveConfig({
|
|
245
|
-
host: '127.0.0.1',
|
|
246
|
-
port,
|
|
247
|
-
socketPath: socket,
|
|
248
|
-
// The page's own origin, by every loopback name the gateway accepts as Host.
|
|
249
|
-
origins: [`http://127.0.0.1:${port}`, `http://localhost:${port}`, `http://[::1]:${port}`],
|
|
250
|
-
// One local user's browser: a stale token in an open tab must not lock that user out.
|
|
251
|
-
// (DEFAULT_LIMITS is frozen, so its type has the literal defaults; any positive number is valid.)
|
|
252
|
-
limits: /** @type {any} */ ({ authFailures: 1_000 }),
|
|
253
|
-
});
|
|
254
|
-
const candidate = createGateway({ config, store, logger: log, version: VERSION, openTransport: () => connectSocket(socket), serveStatic });
|
|
255
|
-
try {
|
|
256
|
-
await candidate.listen();
|
|
257
|
-
bound = port;
|
|
258
|
-
cleanups.push(() => candidate.close());
|
|
259
|
-
break;
|
|
260
|
-
}
|
|
261
|
-
catch (error) {
|
|
262
|
-
await candidate.close().catch(() => {});
|
|
263
|
-
if (/** @type {any} */ (error)?.code !== 'EADDRINUSE' || attempt + 1 >= PORT_TRIES) throw error;
|
|
264
|
-
log.info(`port ${port} is in use; trying ${port + 1}`, { code: 'ALP_WEB_PORT_BUSY' });
|
|
265
|
-
}
|
|
266
|
-
}
|
|
267
|
-
if (shuttingDown) return;
|
|
268
|
-
const url = `http://127.0.0.1:${bound}/`;
|
|
269
|
-
await publish(home, { version: WEB_FILE_VERSION, app: 'alp-web', pid: process.pid, port: bound, url, token, credentialId: grant.id });
|
|
270
|
-
if (shuttingDown) return;
|
|
271
|
-
const timer = setInterval(() => { if (!shuttingDown) void grant.refresh(); }, REFRESH_MS);
|
|
272
|
-
timer.unref();
|
|
273
|
-
cleanups.push(async () => clearInterval(timer));
|
|
274
|
-
// A lock that is no longer ours means another process may own the credentials file: stop writing it.
|
|
275
|
-
if (!(await lock.setReady(true))) throw new Error('the web lock is no longer held by this process');
|
|
276
|
-
log.info(`alp web on ${url}`, { code: 'ALP_WEB_LISTENING' });
|
|
277
|
-
})();
|
|
278
|
-
// A failed start stops the service; shutdown waits for startup, which has settled by now.
|
|
279
|
-
await startup.catch(error => {
|
|
280
|
-
log.error('alp web did not start', { code: 'ALP_WEB_START_FAILED', error });
|
|
281
|
-
void shutdown(1);
|
|
282
|
-
});
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
await run();
|
package/src/web/serve.js
DELETED
|
@@ -1,144 +0,0 @@
|
|
|
1
|
-
// @ts-check
|
|
2
|
-
import { createReadStream } from 'node:fs';
|
|
3
|
-
import { realpath, stat } from 'node:fs/promises';
|
|
4
|
-
import path from 'node:path';
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
* The static side of `alp web` (docs/alp/web.md): the built apps/web files, served through the
|
|
8
|
-
* gateway's `serveStatic` hook on the gateway's own loopback listener. The gateway has refused an
|
|
9
|
-
* unknown Host (421) before a request reaches this, and hands over GET and HEAD only, with the RAW
|
|
10
|
-
* request target. This module normalizes that target itself and never serves a file whose real
|
|
11
|
-
* path lies outside the app directory:
|
|
12
|
-
* - the target must be origin-form (`/...`); it is parsed with `new URL` against a fixed origin,
|
|
13
|
-
* so `//host/x` stays a path and dot segments (also `%2e%2e`) are resolved by the URL parser;
|
|
14
|
-
* - each path segment is percent-decoded exactly once; a decoded segment holding `/`, `\`, `:`,
|
|
15
|
-
* NUL, a control character, or that is empty, `.`, `..` or starts with `.` is refused (400);
|
|
16
|
-
* - a backslash anywhere in the raw target or its decoded form is refused (400);
|
|
17
|
-
* - the file's realpath must lie under the app directory's realpath (no symlink escapes), else 404.
|
|
18
|
-
* Paths without an extension that name no file get index.html (the app's own routes); a missing
|
|
19
|
-
* file with an extension is a 404. index.html is never cached; files under /assets/ are named by
|
|
20
|
-
* content and immutable.
|
|
21
|
-
*/
|
|
22
|
-
|
|
23
|
-
/** @type {Record<string, string>} */
|
|
24
|
-
const TYPES = {
|
|
25
|
-
'.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8',
|
|
26
|
-
'.css': 'text/css; charset=utf-8', '.json': 'application/json; charset=utf-8', '.map': 'application/json; charset=utf-8',
|
|
27
|
-
'.txt': 'text/plain; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
|
|
28
|
-
'.ico': 'image/x-icon', '.gif': 'image/gif', '.webp': 'image/webp', '.woff': 'font/woff', '.woff2': 'font/woff2',
|
|
29
|
-
'.ttf': 'font/ttf', '.otf': 'font/otf', '.wasm': 'application/wasm', '.webmanifest': 'application/manifest+json',
|
|
30
|
-
};
|
|
31
|
-
|
|
32
|
-
// eslint-disable-next-line no-control-regex
|
|
33
|
-
// `:` names a drive or an NTFS stream on Windows; the built app has no such file anywhere.
|
|
34
|
-
const FORBIDDEN_IN_SEGMENT = /[\u0000-\u001f\u007f/\\:]/;
|
|
35
|
-
|
|
36
|
-
/** What a page without the built app says. @param {string} dir */
|
|
37
|
-
const missingPage = dir => `<!doctype html><meta charset="utf-8"><title>ALP</title><body style="font:16px system-ui;max-width:40rem;margin:4rem auto;padding:0 1rem">
|
|
38
|
-
<h1>ALP web is not built</h1><p>The web app's files are missing from <code>${dir.replace(/[&<>"]/g, char => `&#${char.charCodeAt(0)};`)}</code>. Build them from a checkout with <code>node scripts/build-workspace.mjs cli</code> (or <code>node scripts/build-alp-web.mjs</code>), or install ALP from npm, which carries them. The gateway on this address keeps running.</p>`;
|
|
39
|
-
|
|
40
|
-
/**
|
|
41
|
-
* The path segments a raw request target names, each decoded once, or a refusal.
|
|
42
|
-
* @param {string | undefined} raw
|
|
43
|
-
* @returns {{ segments: string[] } | { status: 400 }}
|
|
44
|
-
*/
|
|
45
|
-
export function parseTarget(raw) {
|
|
46
|
-
if (typeof raw !== 'string' || !raw.startsWith('/') || raw.includes('\\') || /%5c/i.test(raw) || raw.includes('\0')) return { status: 400 };
|
|
47
|
-
let url;
|
|
48
|
-
// Never `new URL(raw, base)`: a raw `//host/x` would name another host. The fixed origin keeps it a path.
|
|
49
|
-
try { url = new URL(`http://alp-web.invalid${raw}`); } catch { return { status: 400 }; }
|
|
50
|
-
if (url.host !== 'alp-web.invalid') return { status: 400 };
|
|
51
|
-
const parts = url.pathname.split('/').slice(1);
|
|
52
|
-
/** @type {string[]} */
|
|
53
|
-
const segments = [];
|
|
54
|
-
for (let index = 0; index < parts.length; index++) {
|
|
55
|
-
const part = parts[index];
|
|
56
|
-
// A trailing slash (`/` itself, or `/route/`) is the directory's index; any other empty segment is `//`.
|
|
57
|
-
if (part === '' && index === parts.length - 1) break;
|
|
58
|
-
let segment;
|
|
59
|
-
try { segment = decodeURIComponent(part); } catch { return { status: 400 }; }
|
|
60
|
-
if (!segment || segment === '.' || segment === '..' || segment.startsWith('.') || FORBIDDEN_IN_SEGMENT.test(segment)) return { status: 400 };
|
|
61
|
-
segments.push(segment);
|
|
62
|
-
}
|
|
63
|
-
return { segments };
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
/** @param {string} file */
|
|
67
|
-
const isFile = file => stat(file).then(info => info.isFile(), () => false);
|
|
68
|
-
|
|
69
|
-
/**
|
|
70
|
-
* @param {{ dir: string, csp: () => string, log?: (message: string) => void }} options
|
|
71
|
-
* `dir` holds the built app (index.html and assets/); `csp` is the Content-Security-Policy for the
|
|
72
|
-
* current listener (it names the bound port).
|
|
73
|
-
*/
|
|
74
|
-
export function createStaticServer({ dir, csp, log = () => {} }) {
|
|
75
|
-
const configured = path.resolve(dir);
|
|
76
|
-
/** @type {Promise<string | undefined> | undefined} */
|
|
77
|
-
let root;
|
|
78
|
-
/** The app directory's real path while it holds an index.html; checked again after a miss. */
|
|
79
|
-
const appRoot = async () => {
|
|
80
|
-
const found = await (root ??= realpath(configured).then(async real => (await isFile(path.join(real, 'index.html')) ? real : undefined), () => undefined));
|
|
81
|
-
if (!found) root = undefined;
|
|
82
|
-
return found;
|
|
83
|
-
};
|
|
84
|
-
|
|
85
|
-
/** @param {string} type @param {string} cache */
|
|
86
|
-
const headers = (type, cache) => ({
|
|
87
|
-
'content-type': type,
|
|
88
|
-
'cache-control': cache,
|
|
89
|
-
'x-content-type-options': 'nosniff',
|
|
90
|
-
'x-frame-options': 'DENY',
|
|
91
|
-
'referrer-policy': 'no-referrer',
|
|
92
|
-
'cross-origin-opener-policy': 'same-origin',
|
|
93
|
-
'cross-origin-resource-policy': 'same-origin',
|
|
94
|
-
'content-security-policy': csp(),
|
|
95
|
-
});
|
|
96
|
-
|
|
97
|
-
/** @param {import('node:http').IncomingMessage} request @param {import('node:http').ServerResponse} response @param {number} status @param {string} text */
|
|
98
|
-
function plain(request, response, status, text) {
|
|
99
|
-
response.writeHead(status, { ...headers('text/plain; charset=utf-8', 'no-store'), 'content-length': String(Buffer.byteLength(text)) });
|
|
100
|
-
response.end(request.method === 'HEAD' ? undefined : text);
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
/** @param {string} base @param {string[]} segments @returns {Promise<string | undefined>} a regular file under `base`, by realpath */
|
|
104
|
-
async function contained(base, segments) {
|
|
105
|
-
const candidate = path.join(base, ...segments);
|
|
106
|
-
let real;
|
|
107
|
-
try { real = await realpath(candidate); } catch { return undefined; }
|
|
108
|
-
if (real !== base && !real.startsWith(base + path.sep)) return undefined;
|
|
109
|
-
return (await isFile(real)) ? real : undefined;
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
/**
|
|
113
|
-
* The gateway's serveStatic hook.
|
|
114
|
-
* @param {import('node:http').IncomingMessage} request @param {import('node:http').ServerResponse} response
|
|
115
|
-
*/
|
|
116
|
-
return async function serveStatic(request, response) {
|
|
117
|
-
const base = await appRoot();
|
|
118
|
-
if (!base) {
|
|
119
|
-
const page = missingPage(configured);
|
|
120
|
-
response.writeHead(503, { ...headers('text/html; charset=utf-8', 'no-store'), 'content-length': String(Buffer.byteLength(page)) });
|
|
121
|
-
response.end(request.method === 'HEAD' ? undefined : page);
|
|
122
|
-
return true;
|
|
123
|
-
}
|
|
124
|
-
const target = parseTarget(request.url);
|
|
125
|
-
if ('status' in target) { plain(request, response, 400, 'Bad request'); return true; }
|
|
126
|
-
const { segments } = target;
|
|
127
|
-
let file = segments.length ? await contained(base, segments) : undefined;
|
|
128
|
-
if (!file) {
|
|
129
|
-
const last = segments.at(-1) ?? '';
|
|
130
|
-
if (path.extname(last)) { plain(request, response, 404, 'Not found'); return true; }
|
|
131
|
-
// The app's own routes (and `/`): its index page.
|
|
132
|
-
file = await contained(base, ['index.html']);
|
|
133
|
-
if (!file) { plain(request, response, 404, 'Not found'); return true; }
|
|
134
|
-
}
|
|
135
|
-
const relative = path.relative(base, file).split(path.sep).join('/');
|
|
136
|
-
const type = TYPES[path.extname(file).toLowerCase()] ?? 'application/octet-stream';
|
|
137
|
-
const cache = relative === 'index.html' ? 'no-cache' : relative.startsWith('assets/') ? 'public, max-age=31536000, immutable' : 'no-cache';
|
|
138
|
-
const { size } = await stat(file);
|
|
139
|
-
response.writeHead(200, { ...headers(type, cache), 'content-length': String(size) });
|
|
140
|
-
if (request.method === 'HEAD') { response.end(); return true; }
|
|
141
|
-
createReadStream(file).on('error', error => { log(`could not read ${relative}: ${error.message}`); response.destroy(); }).pipe(response);
|
|
142
|
-
return true;
|
|
143
|
-
};
|
|
144
|
-
}
|