@basaltkit/deploy-ui 0.0.0-stage → 0.1.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.
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Deploy targets (RFC 0009 §5): where the operator's SSH key and the `.env`
3
+ * answers they type are sent. They live in the operator's own config
4
+ * directory — never in the app repository, which anyone with commit access
5
+ * could repoint — and every field has a closed grammar. They hold no secret.
6
+ */
7
+ export interface Target {
8
+ /** The UI's key for the target: shown everywhere, never put in argv. */
9
+ name: string;
10
+ /** `[user@]host`, or a `Host` alias of the operator's `~/.ssh/config`. */
11
+ ssh: string;
12
+ port?: number;
13
+ /** The checkout on the server, absolute. */
14
+ dir: string;
15
+ /** The server's node, when a non-interactive shell lacks it on PATH. */
16
+ node?: string;
17
+ /** `--config=<path>`, relative to the checkout. */
18
+ config?: string;
19
+ /** run and rollback need the target's name typed to confirm. */
20
+ protected?: boolean;
21
+ }
22
+ export interface TargetsFile {
23
+ version: 1;
24
+ /** Becomes `--actor`: self-declared attribution. */
25
+ actor?: string;
26
+ targets: Target[];
27
+ }
28
+ export declare const NAME: RegExp;
29
+ export declare const ABSOLUTE_PATH: RegExp;
30
+ export declare const RELATIVE_PATH: RegExp;
31
+ /** The server's own `--actor` pattern (`@basaltkit/deploy` audit.ts). */
32
+ export declare const ACTOR: RegExp;
33
+ export declare const MAX_TARGETS = 100;
34
+ export declare function validSsh(value: string): boolean;
35
+ export declare const validDir: (value: string) => boolean;
36
+ export declare const validConfig: (value: string) => boolean;
37
+ export type Checked<T> = {
38
+ ok: true;
39
+ value: T;
40
+ } | {
41
+ ok: false;
42
+ errors: Record<string, string>;
43
+ };
44
+ /** One target, every field against its grammar; unknown fields are refused, never ignored. */
45
+ export declare function checkTarget(input: unknown): Checked<Target>;
46
+ /** The whole file: the version, the actor, every target, unique names. */
47
+ export declare function checkTargetsFile(input: unknown): Checked<TargetsFile>;
48
+ /** `$XDG_CONFIG_HOME/basalt/deploy-targets.json` (absolute only, per the spec), `%APPDATA%\basalt\…` on Windows. */
49
+ export declare function defaultTargetsPath(platform: NodeJS.Platform, env: NodeJS.ProcessEnv, home: string): string;
50
+ export declare class TargetsFileError extends Error {
51
+ }
52
+ export interface LoadedTargets {
53
+ file: TargetsFile;
54
+ /** False until the operator saves a first target. */
55
+ exists: boolean;
56
+ }
57
+ /** What the ownership checks need from the OS: injectable, since a test cannot chown. */
58
+ export interface TargetsFs {
59
+ platform?: NodeJS.Platform;
60
+ /** The operator's uid (default: `process.getuid()`). */
61
+ uid?: number;
62
+ /** `stat` of a directory (follows links, as path resolution does). */
63
+ statDir?: (path: string) => Promise<{
64
+ uid: number;
65
+ mode: number;
66
+ isDirectory(): boolean;
67
+ }>;
68
+ }
69
+ /**
70
+ * Reads the targets file without following a link (O_NOFOLLOW), and only if
71
+ * it is a regular file the operator owns and nobody else can write, in
72
+ * directories nobody else can rename it in. Missing → an empty file.
73
+ */
74
+ export declare function readTargets(path: string, fs?: TargetsFs): Promise<LoadedTargets>;
75
+ /**
76
+ * Written 0600 to a new temp file in the same directory (0700 when created),
77
+ * then renamed over the old one — only into directories that pass the same
78
+ * ownership checks as a read, and never over a file another user owns.
79
+ */
80
+ export declare function writeTargets(path: string, file: TargetsFile, fs?: TargetsFs): Promise<void>;
@@ -0,0 +1,242 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { constants } from 'node:fs';
3
+ import { lstat, mkdir, open, rename, rm, stat as statPath } from 'node:fs/promises';
4
+ import { dirname, isAbsolute, join, resolve, win32 } from 'node:path';
5
+ export const NAME = /^[a-z0-9][a-z0-9-]{0,39}$/;
6
+ const SSH_USER = /^[a-z_][a-z0-9_.-]{0,31}$/;
7
+ const SSH_HOST = /^[A-Za-z0-9](?:[A-Za-z0-9.-]{0,252})$/;
8
+ const SSH_IPV6 = /^[0-9A-Fa-f:]{2,39}$/;
9
+ export const ABSOLUTE_PATH = /^\/[A-Za-z0-9._@+/-]{0,255}$/;
10
+ export const RELATIVE_PATH = /^[A-Za-z0-9._-][A-Za-z0-9._/-]{0,127}$/;
11
+ /** The server's own `--actor` pattern (`@basaltkit/deploy` audit.ts). */
12
+ export const ACTOR = /^[A-Za-z0-9._@+-]{1,64}$/;
13
+ const TARGET_FIELDS = new Set(['name', 'ssh', 'port', 'dir', 'node', 'config', 'protected']);
14
+ const FILE_FIELDS = new Set(['version', 'actor', 'targets']);
15
+ /** No file the UI reads is larger: a targets file is a few hundred bytes. */
16
+ const MAX_FILE_BYTES = 1024 * 1024;
17
+ export const MAX_TARGETS = 100;
18
+ const segments = (path) => path.split('/');
19
+ const hasDotDot = (path) => segments(path).includes('..');
20
+ export function validSsh(value) {
21
+ const at = value.lastIndexOf('@');
22
+ const user = at === -1 ? undefined : value.slice(0, at);
23
+ const host = at === -1 ? value : value.slice(at + 1);
24
+ if (user !== undefined && !SSH_USER.test(user))
25
+ return false;
26
+ return SSH_HOST.test(host) || (host.includes(':') && SSH_IPV6.test(host));
27
+ }
28
+ export const validDir = (value) => ABSOLUTE_PATH.test(value) && !hasDotDot(value) && !value.includes('//');
29
+ export const validConfig = (value) => RELATIVE_PATH.test(value) && !hasDotDot(value) && !value.includes('//');
30
+ const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
31
+ /** One target, every field against its grammar; unknown fields are refused, never ignored. */
32
+ export function checkTarget(input) {
33
+ if (!isObject(input))
34
+ return { ok: false, errors: { target: 'a target is a JSON object' } };
35
+ const errors = {};
36
+ for (const key of Object.keys(input)) {
37
+ if (!TARGET_FIELDS.has(key))
38
+ errors[key] = `unknown field "${key}" — jump hosts, identity files and proxies belong in ~/.ssh/config, under a Host alias`;
39
+ }
40
+ const { name, ssh, port, dir, node, config } = input;
41
+ const isProtected = input['protected'];
42
+ if (typeof name !== 'string' || !NAME.test(name))
43
+ errors['name'] = 'lowercase letters, digits and -, at most 40, starting with a letter or digit';
44
+ if (typeof ssh !== 'string' || !validSsh(ssh))
45
+ errors['ssh'] = '[user@]host or a Host alias from ~/.ssh/config: no spaces, no leading -, no ssh:// URL';
46
+ if (port !== undefined && (typeof port !== 'number' || !Number.isInteger(port) || port < 1 || port > 65535))
47
+ errors['port'] = 'a whole number from 1 to 65535';
48
+ if (typeof dir !== 'string' || !validDir(dir))
49
+ errors['dir'] = 'an absolute path of letters, digits and ._@+/- (no .., no //)';
50
+ if (node !== undefined && (typeof node !== 'string' || !validDir(node)))
51
+ errors['node'] = 'an absolute path to node on the server (no .., no //)';
52
+ if (config !== undefined && (typeof config !== 'string' || !validConfig(config)))
53
+ errors['config'] = 'a path relative to the checkout (no .., no leading /)';
54
+ if (isProtected !== undefined && typeof isProtected !== 'boolean')
55
+ errors['protected'] = 'true or false';
56
+ if (Object.keys(errors).length > 0)
57
+ return { ok: false, errors };
58
+ return {
59
+ ok: true,
60
+ value: {
61
+ name: name, ssh: ssh, dir: dir,
62
+ ...(port === undefined ? {} : { port: port }),
63
+ ...(node === undefined ? {} : { node: node }),
64
+ ...(config === undefined ? {} : { config: config }),
65
+ ...(isProtected === true ? { protected: true } : {}),
66
+ },
67
+ };
68
+ }
69
+ /** The whole file: the version, the actor, every target, unique names. */
70
+ export function checkTargetsFile(input) {
71
+ if (!isObject(input))
72
+ return { ok: false, errors: { file: 'the targets file is not a JSON object' } };
73
+ const errors = {};
74
+ for (const key of Object.keys(input))
75
+ if (!FILE_FIELDS.has(key))
76
+ errors[key] = `unknown field "${key}"`;
77
+ if (input['version'] !== 1)
78
+ errors['version'] = 'version must be 1';
79
+ const actor = input['actor'];
80
+ if (actor !== undefined && (typeof actor !== 'string' || !ACTOR.test(actor)))
81
+ errors['actor'] = 'letters, digits and ._@+-, at most 64';
82
+ const list = input['targets'];
83
+ const targets = [];
84
+ if (!Array.isArray(list) || list.length > MAX_TARGETS)
85
+ errors['targets'] = `targets must be a list of at most ${MAX_TARGETS}`;
86
+ else {
87
+ const names = new Set();
88
+ list.forEach((item, index) => {
89
+ const checked = checkTarget(item);
90
+ if (!checked.ok) {
91
+ for (const [field, message] of Object.entries(checked.errors))
92
+ errors[`targets[${index}].${field}`] = message;
93
+ return;
94
+ }
95
+ if (names.has(checked.value.name))
96
+ errors[`targets[${index}].name`] = `"${checked.value.name}" is used twice`;
97
+ names.add(checked.value.name);
98
+ targets.push(checked.value);
99
+ });
100
+ }
101
+ if (Object.keys(errors).length > 0)
102
+ return { ok: false, errors };
103
+ return { ok: true, value: { version: 1, ...(actor === undefined ? {} : { actor: actor }), targets } };
104
+ }
105
+ /** `$XDG_CONFIG_HOME/basalt/deploy-targets.json` (absolute only, per the spec), `%APPDATA%\basalt\…` on Windows. */
106
+ export function defaultTargetsPath(platform, env, home) {
107
+ if (platform === 'win32') {
108
+ const appData = env['APPDATA'] && win32.isAbsolute(env['APPDATA']) ? env['APPDATA'] : win32.join(home, 'AppData', 'Roaming');
109
+ return win32.join(appData, 'basalt', 'deploy-targets.json');
110
+ }
111
+ const xdg = env['XDG_CONFIG_HOME'];
112
+ const base = xdg && isAbsolute(xdg) ? xdg : join(home, '.config');
113
+ return join(base, 'basalt', 'deploy-targets.json');
114
+ }
115
+ export class TargetsFileError extends Error {
116
+ }
117
+ const NOFOLLOW = constants.O_NOFOLLOW ?? 0;
118
+ const STICKY = 0o1000;
119
+ const operatorUid = (fs) => fs.uid ?? (typeof process.getuid === 'function' ? process.getuid() : undefined);
120
+ const posix = (fs) => (fs.platform ?? process.platform) !== 'win32';
121
+ /**
122
+ * Every directory from the file's up to `/` must be owned by the operator or
123
+ * root, and writable by nobody else unless sticky (as `/tmp` is): whoever can
124
+ * rename an entry in one of them can swap the file for their own (the checks
125
+ * sshd's StrictModes makes). POSIX only.
126
+ */
127
+ async function checkDirectories(path, fs) {
128
+ const uid = operatorUid(fs);
129
+ if (!posix(fs) || uid === undefined)
130
+ return;
131
+ const statDir = fs.statDir ?? statPath;
132
+ let dir = dirname(resolve(path));
133
+ for (;;) {
134
+ let info;
135
+ try {
136
+ info = await statDir(dir);
137
+ }
138
+ catch (error) {
139
+ throw new TargetsFileError(`cannot check ${dir}: ${error.message}`);
140
+ }
141
+ if (!info.isDirectory())
142
+ throw new TargetsFileError(`${dir} is not a directory — refused`);
143
+ if (info.uid !== uid && info.uid !== 0) {
144
+ throw new TargetsFileError(`${dir} belongs to another user (uid ${info.uid}): they choose where your secrets go — keep the targets file in your own directory (the default is ~/.config/basalt)`);
145
+ }
146
+ if ((info.mode & 0o022) !== 0 && (info.mode & STICKY) === 0) {
147
+ throw new TargetsFileError(`${dir} is writable by other users (mode ${(info.mode & 0o7777).toString(8)}) and not sticky: anyone who can write it can replace the targets file — keep it in your own directory`);
148
+ }
149
+ const parent = dirname(dir);
150
+ if (parent === dir)
151
+ return;
152
+ dir = parent;
153
+ }
154
+ }
155
+ /**
156
+ * Reads the targets file without following a link (O_NOFOLLOW), and only if
157
+ * it is a regular file the operator owns and nobody else can write, in
158
+ * directories nobody else can rename it in. Missing → an empty file.
159
+ */
160
+ export async function readTargets(path, fs = {}) {
161
+ let handle;
162
+ try {
163
+ handle = await open(path, constants.O_RDONLY | NOFOLLOW);
164
+ }
165
+ catch (error) {
166
+ const code = error.code;
167
+ if (code === 'ENOENT')
168
+ return { file: { version: 1, targets: [] }, exists: false };
169
+ if (code === 'ELOOP' || code === 'EMLINK')
170
+ throw new TargetsFileError(`${path} is a symbolic link — refused, never followed`);
171
+ throw new TargetsFileError(`cannot read ${path}: ${error.message}`);
172
+ }
173
+ try {
174
+ const stat = await handle.stat();
175
+ if (!stat.isFile())
176
+ throw new TargetsFileError(`${path} is not a regular file — refused`);
177
+ if (posix(fs)) {
178
+ if ((stat.mode & 0o022) !== 0) {
179
+ throw new TargetsFileError(`${path} is writable by other users (mode ${(stat.mode & 0o777).toString(8)}): anyone who can change it chooses where your secrets go — chmod 600 ${path}`);
180
+ }
181
+ const uid = operatorUid(fs);
182
+ if (uid !== undefined && stat.uid !== uid) {
183
+ throw new TargetsFileError(`${path} belongs to another user (uid ${stat.uid}, you are ${uid}): its owner chooses where your secrets go — refused`);
184
+ }
185
+ await checkDirectories(path, fs);
186
+ }
187
+ if (stat.size > MAX_FILE_BYTES)
188
+ throw new TargetsFileError(`${path} is larger than ${MAX_FILE_BYTES} bytes — refused`);
189
+ const text = await handle.readFile({ encoding: 'utf8' });
190
+ let parsed;
191
+ try {
192
+ parsed = JSON.parse(text);
193
+ }
194
+ catch {
195
+ throw new TargetsFileError(`${path} is not JSON`);
196
+ }
197
+ const checked = checkTargetsFile(parsed);
198
+ if (!checked.ok) {
199
+ throw new TargetsFileError(`${path} is refused: ${Object.entries(checked.errors).map(([k, v]) => `${k}: ${v}`).join('; ')}`);
200
+ }
201
+ return { file: checked.value, exists: true };
202
+ }
203
+ finally {
204
+ await handle.close();
205
+ }
206
+ }
207
+ /**
208
+ * Written 0600 to a new temp file in the same directory (0700 when created),
209
+ * then renamed over the old one — only into directories that pass the same
210
+ * ownership checks as a read, and never over a file another user owns.
211
+ */
212
+ export async function writeTargets(path, file, fs = {}) {
213
+ const checked = checkTargetsFile(file);
214
+ if (!checked.ok)
215
+ throw new TargetsFileError(`refused: ${Object.entries(checked.errors).map(([k, v]) => `${k}: ${v}`).join('; ')}`);
216
+ const dir = dirname(path);
217
+ await mkdir(dir, { recursive: true, mode: 0o700 });
218
+ await checkDirectories(path, fs);
219
+ const uid = operatorUid(fs);
220
+ if (posix(fs) && uid !== undefined) {
221
+ const existing = await lstat(path).catch((error) => { if (error.code === 'ENOENT')
222
+ return undefined; throw error; });
223
+ if (existing && existing.uid !== uid)
224
+ throw new TargetsFileError(`${path} belongs to another user (uid ${existing.uid}): not replaced`);
225
+ }
226
+ const temp = join(dir, `.deploy-targets.${randomBytes(6).toString('hex')}.tmp`);
227
+ const handle = await open(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | NOFOLLOW, 0o600);
228
+ try {
229
+ await handle.writeFile(`${JSON.stringify(checked.value, null, 2)}\n`);
230
+ await handle.sync();
231
+ }
232
+ finally {
233
+ await handle.close();
234
+ }
235
+ try {
236
+ await rename(temp, path);
237
+ }
238
+ catch (error) {
239
+ await rm(temp, { force: true });
240
+ throw error;
241
+ }
242
+ }
package/package.json CHANGED
@@ -1,6 +1,54 @@
1
1
  {
2
2
  "name": "@basaltkit/deploy-ui",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "engines": {
5
+ "node": ">=22.5.0"
6
+ },
7
+ "description": "A local web UI for @basaltkit/deploy: runs on the operator's machine, listens on 127.0.0.1 only, and drives the server over the system ssh with the operator's own keys. Never an app dependency.",
8
+ "license": "MIT",
9
+ "type": "module",
10
+ "sideEffects": false,
11
+ "bin": {
12
+ "basalt-deploy-ui": "./dist/bin.js"
13
+ },
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "import": "./dist/index.js"
18
+ }
19
+ },
20
+ "files": [
21
+ "dist"
22
+ ],
23
+ "dependencies": {
24
+ "@basaltkit/deploy": "^0.5.0"
25
+ },
26
+ "devDependencies": {
27
+ "@types/node": "^26.6.1",
28
+ "jsdom": "^30.0.1",
29
+ "typescript": "^7.0.2",
30
+ "vitest": "^5.0.1",
31
+ "@basaltkit/tsconfig": "^0.24.0"
32
+ },
33
+ "publishConfig": {
34
+ "access": "public"
35
+ },
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "git+https://github.com/basaltkit/basalt.git",
39
+ "directory": "packages/deploy-ui"
40
+ },
41
+ "homepage": "https://github.com/basaltkit/basalt/tree/main/packages/deploy-ui#readme",
42
+ "bugs": "https://github.com/basaltkit/basalt/issues",
43
+ "keywords": [
44
+ "basalt",
45
+ "deploy",
46
+ "ssh",
47
+ "ui"
48
+ ],
49
+ "scripts": {
50
+ "build": "tsc -p tsconfig.build.json && tsc -p tsconfig.client.json",
51
+ "test": "vitest run",
52
+ "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.client.json"
53
+ }
6
54
  }