@hideandseeklab/aoox 0.1.0-alpha.12 → 0.1.0-alpha.13

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,12 +1,14 @@
1
- import { confirm } from '@inquirer/prompts';
1
+ import { confirm, input } from '@inquirer/prompts';
2
2
  import { Command, Flags } from '@oclif/core';
3
3
  import { randomBytes } from 'node:crypto';
4
- import { copyFile, mkdir, readFile, stat, writeFile } from 'node:fs/promises';
4
+ import { chmod, copyFile, mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
5
5
  import { resolve } from 'node:path';
6
6
  import { fileURLToPath } from 'node:url';
7
- import { dockerInherit } from '../lib/docker.js';
7
+ import { dockerCapture, dockerInherit } from '../lib/docker.js';
8
8
  import { buildEnvFile, resolveTerminalSshUser } from '../lib/install-env.js';
9
- import { parseEnv } from '../lib/reinstall.js';
9
+ import { explicitOverrides, planInstall, wipeWarning } from '../lib/install-plan.js';
10
+ import { composeProjectName, declaredVolumeNames, latestEnvBackup, leftoverVolumes } from '../lib/leftover-volumes.js';
11
+ import { backupInstallFiles, backupStamp, chooseComposeFiles, composeArgs, composeDefaults, composeVariables, DIST_FILE, DOMAIN_FILE, mergeEnv, MissingSecretsError, OVERRIDE_FILE, parseEnv, repairDefaults, REQUIRED_SECRETS, } from '../lib/reinstall.js';
10
12
  import { stepLine, successLine, warnLine } from '../lib/style.js';
11
13
  import { commandExists, detectPublicIp, dockerRunning, dockerSocketGid, isRoot, runShellInherit } from '../lib/system.js';
12
14
  import { authorizeTerminalKey, skipReason } from '../lib/terminal-key.js';
@@ -14,11 +16,21 @@ const DOCKER_INSTALL_SCRIPT = 'curl -fsSL https://get.docker.com | sh';
14
16
  /** How long to wait for the API to answer after `docker compose up -d` (migrations run on boot). */
15
17
  const READY_TIMEOUT_MS = 120_000;
16
18
  const READY_POLL_MS = 2000;
19
+ async function readIfExists(path) {
20
+ try {
21
+ return await readFile(path, 'utf8');
22
+ }
23
+ catch {
24
+ return undefined;
25
+ }
26
+ }
17
27
  export default class Install extends Command {
18
28
  static description = 'Install aoox (postgres + api + web) on a fresh VPS with Docker Compose';
19
29
  static examples = [
20
30
  'sudo <%= config.bin %> <%= command.id %>',
21
31
  'sudo <%= config.bin %> <%= command.id %> --web-domain panel.example.com --api-domain api.panel.example.com --acme-email me@example.com',
32
+ 'sudo <%= config.bin %> <%= command.id %> --force # reinstall over an existing install, keeping data and secrets',
33
+ 'sudo <%= config.bin %> <%= command.id %> --force --new-secrets --wipe-data # start from scratch (deletes all panel data)',
22
34
  ];
23
35
  static flags = {
24
36
  'acme-email': Flags.string({ description: 'Required with --web-domain/--api-domain (Let’s Encrypt)' }),
@@ -26,8 +38,18 @@ export default class Install extends Command {
26
38
  'admin-name': Flags.string({ dependsOn: ['admin-email'], description: 'Name of the first owner' }),
27
39
  'admin-password': Flags.string({ dependsOn: ['admin-email'], description: 'Password of the first owner (min. 8 characters)' }),
28
40
  'api-domain': Flags.string({ dependsOn: ['web-domain'], description: 'Domain for the API, served through the bundled proxy' }),
41
+ 'confirm-wipe': Flags.string({
42
+ description: 'Non-interactive confirmation for --wipe-data: must be exactly the install directory (--yes alone is not enough)',
43
+ }),
29
44
  dir: Flags.string({ default: '/opt/aoox', description: 'Installation directory' }),
30
- force: Flags.boolean({ default: false, description: 'Overwrite an existing installation in --dir' }),
45
+ force: Flags.boolean({
46
+ default: false,
47
+ description: 'Reinstall over an existing installation in --dir: previous files are backed up to <dir>/backups/ and existing secrets and values are kept (data survives)',
48
+ }),
49
+ 'new-secrets': Flags.boolean({
50
+ default: false,
51
+ description: 'Only with --force --wipe-data: generate new secrets for a completely fresh install (DELETES all panel data)',
52
+ }),
31
53
  'no-terminal-authorize': Flags.boolean({
32
54
  default: false,
33
55
  description: 'Do not create/authorize the web Terminal SSH key automatically (do it in Settings > Terminal instead)',
@@ -36,61 +58,111 @@ export default class Install extends Command {
36
58
  description: 'SSH user the web Terminal uses to log in to this host (default: the user running sudo, or root if there is none)',
37
59
  }),
38
60
  'web-domain': Flags.string({ dependsOn: ['api-domain'], description: 'Domain for the web panel, served through the bundled proxy' }),
39
- yes: Flags.boolean({ char: 'y', default: false, description: 'Do not ask for any confirmation' }),
61
+ 'wipe-data': Flags.boolean({
62
+ default: false,
63
+ description: 'Only with --force --new-secrets: run `docker compose down -v` first, removing the panel database volume (and any leftover panel volumes from an earlier install) (DELETES all panel data)',
64
+ }),
65
+ yes: Flags.boolean({ char: 'y', default: false, description: 'Do not ask for any confirmation (does not confirm a wipe)' }),
40
66
  };
67
+ // eslint-disable-next-line complexity -- linear orchestration: plan, confirm, backup, (wipe), write, up
41
68
  async run() {
42
69
  const { flags } = await this.parse(Install);
43
70
  this.assertPreconditions(flags);
71
+ const dir = resolve(flags.dir);
72
+ const existingEnv = await readIfExists(`${dir}/.env.dist`);
73
+ const existingCompose = await readIfExists(`${dir}/${DIST_FILE}`);
74
+ const present = await this.presentFiles(dir);
75
+ const assets = fileURLToPath(new URL('../../assets/install/', import.meta.url));
76
+ const leftover = existingEnv === undefined && existingCompose === undefined ? await this.findLeftoverVolumes(assets) : [];
77
+ const plan = planInstall({
78
+ composeExists: existingCompose !== undefined,
79
+ confirmWipe: flags['confirm-wipe'] === undefined ? undefined : resolve(flags['confirm-wipe']),
80
+ dir,
81
+ envExists: existingEnv !== undefined,
82
+ force: flags.force,
83
+ hasSecrets: existingEnv !== undefined && REQUIRED_SECRETS.every((k) => Boolean(parseEnv(existingEnv).get(k))),
84
+ interactive: Boolean(process.stdin.isTTY),
85
+ latestBackup: leftover.length > 0 ? await latestEnvBackup(dir) : undefined,
86
+ leftoverVolumes: leftover,
87
+ newSecrets: flags['new-secrets'],
88
+ wipeData: flags['wipe-data'],
89
+ yes: flags.yes,
90
+ });
91
+ if (plan.kind === 'error')
92
+ this.error(plan.message, { suggestions: plan.suggestions });
44
93
  await this.ensureDocker(flags.yes);
45
- const { dir } = flags;
46
- await this.confirmPlan(dir, flags);
94
+ await this.confirmPlan(plan, dir, flags.yes, leftover);
95
+ // Never overwrite an existing install without a copy of what is being replaced.
96
+ if (plan.kind !== 'fresh' && (present.size > 0 || existingEnv !== undefined)) {
97
+ const backupDir = `${dir}/backups/${backupStamp()}`;
98
+ await backupInstallFiles(dir, backupDir, present);
99
+ this.log(stepLine('Backed up the previous files to', backupDir));
100
+ }
101
+ if (plan.kind === 'wipe')
102
+ await this.wipe(dir, present, existingEnv !== undefined, leftover);
47
103
  await mkdir(dir, { recursive: true });
48
- const assets = fileURLToPath(new URL('../../assets/install/', import.meta.url));
49
- await copyFile(`${assets}docker-compose.dist.yml`, `${dir}/docker-compose.dist.yml`);
104
+ await copyFile(`${assets}${DIST_FILE}`, `${dir}/${DIST_FILE}`);
50
105
  const domainMode = Boolean(flags['web-domain']);
51
- if (domainMode)
52
- await copyFile(`${assets}docker-compose.domain.yml`, `${dir}/docker-compose.domain.yml`);
106
+ // A reinstall that keeps data also keeps (and refreshes) a domain compose file that is already there.
107
+ const keepDomain = plan.kind === 'reuse' && present.has(DOMAIN_FILE);
108
+ if (domainMode || keepDomain)
109
+ await copyFile(`${assets}${DOMAIN_FILE}`, `${dir}/${DOMAIN_FILE}`);
53
110
  const secretsDir = `${dir}/secrets`;
54
111
  await mkdir(secretsDir, { recursive: true });
55
112
  // The api container writes its terminal SSH key here as uid 1000 (the
56
113
  // `node` user) — chown it now so first use doesn't hit EACCES.
57
114
  await this.chownNode(secretsDir);
58
- this.log(stepLine('Detecting the server public IP'));
59
- const publicIp = await detectPublicIp();
60
- const webOrigin = domainMode ? `https://${flags['web-domain']}` : `http://${publicIp ?? 'localhost'}:3000`;
61
- const publicApiUrl = domainMode ? `https://${flags['api-domain']}` : `http://${publicIp ?? 'localhost'}:3001`;
62
- const env = buildEnvFile({
63
- acmeEmail: flags['acme-email'],
64
- adminEmail: flags['admin-email'],
65
- adminName: flags['admin-name'],
66
- adminPassword: flags['admin-password'],
67
- apiDomain: flags['api-domain'],
68
- dockerGid: dockerSocketGid(),
69
- encryptionKey: randomBytes(32).toString('hex'),
70
- installDir: resolve(dir),
71
- jwtSecret: randomBytes(32).toString('hex'),
72
- postgresPassword: randomBytes(24).toString('hex'),
73
- publicApiUrl,
74
- publicIp,
75
- terminalSshUser: resolveTerminalSshUser(flags['terminal-ssh-user'], process.env),
76
- webDomain: flags['web-domain'],
77
- webOrigin,
78
- });
115
+ let env;
116
+ let webOrigin;
117
+ if (plan.kind === 'reuse') {
118
+ env = await this.reuseEnv(existingEnv ?? '', dir, assets, flags);
119
+ const vars = parseEnv(env);
120
+ webOrigin = vars.get('WEB_ORIGIN') || `http://localhost:${vars.get('WEB_PORT') || '3000'}`;
121
+ }
122
+ else {
123
+ this.log(stepLine('Detecting the server public IP'));
124
+ const publicIp = await detectPublicIp();
125
+ webOrigin = domainMode ? `https://${flags['web-domain']}` : `http://${publicIp ?? 'localhost'}:3000`;
126
+ const publicApiUrl = domainMode ? `https://${flags['api-domain']}` : `http://${publicIp ?? 'localhost'}:3001`;
127
+ env = buildEnvFile({
128
+ acmeEmail: flags['acme-email'],
129
+ adminEmail: flags['admin-email'],
130
+ adminName: flags['admin-name'],
131
+ adminPassword: flags['admin-password'],
132
+ apiDomain: flags['api-domain'],
133
+ dockerGid: dockerSocketGid(),
134
+ encryptionKey: randomBytes(32).toString('hex'),
135
+ installDir: dir,
136
+ jwtSecret: randomBytes(32).toString('hex'),
137
+ postgresPassword: randomBytes(24).toString('hex'),
138
+ publicApiUrl,
139
+ publicIp,
140
+ terminalSshUser: resolveTerminalSshUser(flags['terminal-ssh-user'], process.env),
141
+ webDomain: flags['web-domain'],
142
+ webOrigin,
143
+ });
144
+ }
79
145
  await writeFile(`${dir}/.env.dist`, env, { mode: 0o600 });
146
+ await chmod(`${dir}/.env.dist`, 0o600);
80
147
  this.authorizeTerminal(dir, env, flags['no-terminal-authorize']);
81
148
  this.log(stepLine('Running docker compose up -d'));
82
- const composeArgs = ['compose', '-f', 'docker-compose.dist.yml'];
83
- if (domainMode)
84
- composeArgs.push('-f', 'docker-compose.domain.yml');
85
- composeArgs.push('--env-file', '.env.dist', 'up', '-d');
86
- await dockerInherit(composeArgs, dir);
149
+ let files = [DIST_FILE];
150
+ if (plan.kind === 'reuse')
151
+ files = chooseComposeFiles({ present: await this.presentFiles(dir) });
152
+ else if (domainMode)
153
+ files = [DIST_FILE, DOMAIN_FILE];
154
+ await dockerInherit(composeArgs(files, 'up', '-d'), dir);
87
155
  this.log(stepLine('Waiting for the API to be ready'));
88
156
  await this.waitReady();
89
157
  this.log('');
90
158
  this.log(successLine(`aoox is installed in ${dir}.`));
91
159
  this.log(`Open: ${webOrigin}`);
92
- if (!flags['admin-email'])
160
+ if (plan.kind === 'reuse') {
161
+ this.log('Existing data and secrets were kept. The previous files are in the backups folder of the install directory.');
162
+ }
163
+ else if (!flags['admin-email']) {
93
164
  this.log('Create the first owner account at /setup.');
165
+ }
94
166
  }
95
167
  assertPreconditions(flags) {
96
168
  if (process.platform !== 'linux') {
@@ -136,44 +208,29 @@ export default class Install extends Command {
136
208
  this.logToStderr(warnLine(`Cannot chown ${dir} (${String(error)}) — the web terminal may need this done manually later.`));
137
209
  }
138
210
  }
139
- async confirmPlan(dir, flags) {
140
- let exists = false;
141
- try {
142
- await stat(`${dir}/docker-compose.dist.yml`);
143
- exists = true;
144
- }
145
- catch {
146
- /* not installed yet, as expected */
147
- }
148
- if (exists && !flags.force) {
149
- this.error(`An installation already exists in ${dir}.`, { suggestions: [
150
- 'To repair/refresh the existing installation without losing data: `sudo aoox reinstall`.',
151
- 'Use --force only for a clean reinstall from scratch — it creates new secrets and cuts off access to the existing data.',
152
- ],
153
- });
154
- }
155
- let hasSecrets = false;
156
- if (exists) {
157
- try {
158
- hasSecrets = /^\s*(POSTGRES_PASSWORD|JWT_SECRET|ENCRYPTION_KEY)=\S/m.test(await readFile(`${dir}/.env.dist`, 'utf8'));
159
- }
160
- catch {
161
- /* no .env.dist — nothing to overwrite */
211
+ async confirmPlan(plan, dir, yes, leftover) {
212
+ if (plan.kind === 'wipe') {
213
+ for (const line of wipeWarning(dir, leftover))
214
+ this.logToStderr(warnLine(line));
215
+ if (plan.confirm === 'typed') {
216
+ const typed = await input({ message: `Type the install directory (${dir}) to confirm that all panel data is deleted:` });
217
+ if (resolve(typed.trim()) !== dir)
218
+ this.error('The typed path does not match — nothing was changed.');
162
219
  }
220
+ return;
163
221
  }
164
- if (hasSecrets) {
165
- this.logToStderr(warnLine(`--force OVERWRITES ${dir}/.env.dist with new random secrets (POSTGRES_PASSWORD, JWT_SECRET, ENCRYPTION_KEY): ` +
166
- 'the existing database can no longer be accessed and all stored credentials (registry, git, S3, notifications, 2FA) can no longer be decrypted. ' +
167
- 'To repair the existing installation without losing data, cancel and run `sudo aoox reinstall`.'));
222
+ if (plan.kind === 'reuse') {
223
+ this.logToStderr(warnLine(`--force reinstalls over the existing installation in ${dir}: the previous files are backed up first and existing secrets and values are kept, so your data stays readable.`));
224
+ if (yes)
225
+ return;
226
+ const ok = await confirm({ default: true, message: `Reinstall in ${dir} (data and secrets are kept) and run docker compose up -d?` });
227
+ if (!ok)
228
+ this.exit(0);
229
+ return;
168
230
  }
169
- if (flags.yes)
231
+ if (yes)
170
232
  return;
171
- const ok = await confirm({
172
- default: !hasSecrets,
173
- message: hasSecrets
174
- ? `Still overwrite .env.dist and create new secrets in ${dir} (the existing data will not be readable)?`
175
- : `Install aoox in ${dir}${exists ? ' (overwriting the existing one)' : ''} and run docker compose up -d?`,
176
- });
233
+ const ok = await confirm({ default: true, message: `Install aoox in ${dir} and run docker compose up -d?` });
177
234
  if (!ok)
178
235
  this.exit(0);
179
236
  }
@@ -194,6 +251,79 @@ export default class Install extends Command {
194
251
  });
195
252
  }
196
253
  }
254
+ /**
255
+ * Data volumes of an earlier installation that are still on this Docker host while the install folder is
256
+ * empty. Only asked when Docker already runs: without Docker there cannot be any.
257
+ */
258
+ async findLeftoverVolumes(assets) {
259
+ if (!(commandExists('docker') && dockerRunning()))
260
+ return [];
261
+ const declared = declaredVolumeNames(await readFile(`${assets}${DIST_FILE}`, 'utf8'));
262
+ const existing = (await dockerCapture(['volume', 'ls', '--format', '{{.Name}}'])).split(/\r?\n/).filter(Boolean);
263
+ return leftoverVolumes(declared, existing);
264
+ }
265
+ async presentFiles(dir) {
266
+ const found = new Set();
267
+ for (const name of [DIST_FILE, DOMAIN_FILE, OVERRIDE_FILE]) {
268
+ try {
269
+ // eslint-disable-next-line no-await-in-loop
270
+ await stat(`${dir}/${name}`);
271
+ found.add(name);
272
+ }
273
+ catch {
274
+ /* absent */
275
+ }
276
+ }
277
+ return found;
278
+ }
279
+ /**
280
+ * Volumes from an earlier installation whose folder is gone (so there is no compose file to `down -v` with).
281
+ * Removes the stack's own containers that still hold them, then the volumes. A volume that is still in use by
282
+ * anything else makes docker refuse, and the install stops there with docker's own message.
283
+ */
284
+ async removeLeftoverVolumes(volumes) {
285
+ const assets = fileURLToPath(new URL('../../assets/install/', import.meta.url));
286
+ const project = composeProjectName(await readFile(`${assets}${DIST_FILE}`, 'utf8'));
287
+ this.log(stepLine(`Removing leftover volumes: ${volumes.join(', ')}`));
288
+ for (const volume of volumes) {
289
+ const holders = (
290
+ // eslint-disable-next-line no-await-in-loop
291
+ await dockerCapture(['ps', '-aq', '--filter', `volume=${volume}`, '--filter', `label=com.docker.compose.project=${project}`]))
292
+ .split(/\r?\n/)
293
+ .filter(Boolean);
294
+ // eslint-disable-next-line no-await-in-loop
295
+ if (holders.length > 0)
296
+ await dockerInherit(['rm', '-f', ...holders], '/');
297
+ // eslint-disable-next-line no-await-in-loop
298
+ await dockerInherit(['volume', 'rm', volume], '/');
299
+ }
300
+ }
301
+ /** Reuse mode: the existing `.env.dist` is merged, never regenerated; only explicit flags replace values. */
302
+ async reuseEnv(existing, dir, assets, flags) {
303
+ const dist = await readFile(`${assets}${DIST_FILE}`, 'utf8');
304
+ const domain = await readIfExists(`${dir}/${DOMAIN_FILE}`);
305
+ try {
306
+ const defaults = repairDefaults(composeVariables(dist, domain ?? ''), { dockerGid: dockerSocketGid(), installDir: dir }, composeDefaults(dist, domain ?? ''));
307
+ const overrides = explicitOverrides({
308
+ acmeEmail: flags['acme-email'],
309
+ adminEmail: flags['admin-email'],
310
+ adminName: flags['admin-name'],
311
+ adminPassword: flags['admin-password'],
312
+ apiDomain: flags['api-domain'],
313
+ terminalSshUser: flags['terminal-ssh-user'],
314
+ webDomain: flags['web-domain'],
315
+ });
316
+ const merged = mergeEnv(existing, defaults, overrides);
317
+ for (const w of merged.warnings)
318
+ this.logToStderr(warnLine(w));
319
+ return merged.content;
320
+ }
321
+ catch (error) {
322
+ if (error instanceof MissingSecretsError)
323
+ this.error(error.message);
324
+ throw error;
325
+ }
326
+ }
197
327
  /** Polls the API's own setup-status endpoint — migrations run on boot, so "up" isn't "ready". */
198
328
  async waitReady(deadline = Date.now() + READY_TIMEOUT_MS) {
199
329
  try {
@@ -213,4 +343,23 @@ export default class Install extends Command {
213
343
  });
214
344
  return this.waitReady(deadline);
215
345
  }
346
+ /** `docker compose down -v` for the existing stack (dist + domain file only: the override just changes ports/labels). */
347
+ async wipe(dir, present, hasEnv, leftover) {
348
+ this.log(stepLine('Removing the existing stack and its volumes (docker compose down -v)'));
349
+ if (present.has(DIST_FILE)) {
350
+ const files = [DIST_FILE, ...(present.has(DOMAIN_FILE) ? [DOMAIN_FILE] : [])];
351
+ // Without a .env.dist the required secrets cannot be interpolated: placeholders are enough to remove the stack.
352
+ await (hasEnv
353
+ ? dockerInherit(composeArgs(files, 'down', '-v', '--remove-orphans'), dir)
354
+ : dockerInherit(['compose', ...files.flatMap((f) => ['-f', f]), 'down', '-v', '--remove-orphans'], dir, {
355
+ JWT_SECRET: 'x',
356
+ POSTGRES_PASSWORD: 'x',
357
+ }));
358
+ }
359
+ if (leftover.length > 0)
360
+ await this.removeLeftoverVolumes(leftover);
361
+ // Settings of the wiped database no longer exist; the backup keeps the old copies.
362
+ await rm(`${dir}/${OVERRIDE_FILE}`, { force: true });
363
+ await rm(`${dir}/${DOMAIN_FILE}`, { force: true });
364
+ }
216
365
  }
@@ -0,0 +1,19 @@
1
+ import { Command } from '@oclif/core';
2
+ /**
3
+ * Shows or resets the self-hosted registry's password — the CLI equivalent of
4
+ * Settings -> Registry -> "Show password" / "Reset password". A reset keeps
5
+ * every image (only the login changes), but every client using the old
6
+ * password has to `docker login` again.
7
+ */
8
+ export default class RegistryPassword extends Command {
9
+ static description: string;
10
+ static examples: string[];
11
+ static flags: {
12
+ reset: import("@oclif/core/interfaces").BooleanFlag<boolean>;
13
+ show: import("@oclif/core/interfaces").BooleanFlag<boolean>;
14
+ yes: import("@oclif/core/interfaces").BooleanFlag<boolean>;
15
+ token: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
16
+ url: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
17
+ };
18
+ run(): Promise<void>;
19
+ }
@@ -0,0 +1,74 @@
1
+ import { Command, Flags } from '@oclif/core';
2
+ import { api, ApiError } from '../../lib/api.js';
3
+ import { MissingCredentialsError } from '../../lib/config.js';
4
+ import { connectionFlags, loadCredentials } from '../../lib/flags.js';
5
+ import { warnIfOutdated } from '../../lib/outdated.js';
6
+ import { successLine, warnLine } from '../../lib/style.js';
7
+ /**
8
+ * Shows or resets the self-hosted registry's password — the CLI equivalent of
9
+ * Settings -> Registry -> "Show password" / "Reset password". A reset keeps
10
+ * every image (only the login changes), but every client using the old
11
+ * password has to `docker login` again.
12
+ */
13
+ export default class RegistryPassword extends Command {
14
+ static description = 'Show or reset the password of the self-hosted registry';
15
+ static examples = [
16
+ '<%= config.bin %> <%= command.id %> --show',
17
+ '<%= config.bin %> <%= command.id %> --reset --yes',
18
+ ];
19
+ static flags = {
20
+ ...connectionFlags,
21
+ reset: Flags.boolean({ description: 'Generate a new password (owner only). Images are kept; docker login again afterwards' }),
22
+ show: Flags.boolean({ description: 'Print the current username, address and password' }),
23
+ yes: Flags.boolean({ char: 'y', description: 'Confirm --reset without asking' }),
24
+ };
25
+ async run() {
26
+ const { flags } = await this.parse(RegistryPassword);
27
+ if (flags.show === flags.reset) {
28
+ this.error('Pass one of: --show or --reset.');
29
+ }
30
+ if (flags.reset && !flags.yes) {
31
+ this.error('Resetting the password logs out every client and CI job that uses the old one (docker login again).', {
32
+ suggestions: ['Re-run with --yes to confirm.'],
33
+ });
34
+ }
35
+ let config;
36
+ try {
37
+ config = await loadCredentials(this.config.configDir, flags);
38
+ }
39
+ catch (error) {
40
+ if (error instanceof MissingCredentialsError) {
41
+ this.error(error.message, { suggestions: ['Run `aoox login` against this panel first.'] });
42
+ }
43
+ throw error;
44
+ }
45
+ await warnIfOutdated((m) => this.logToStderr(warnLine(m)), this.config.version, config);
46
+ const registries = await api(config, '/registries');
47
+ const registry = registries.find((r) => r.type === 'self-hosted');
48
+ if (!registry) {
49
+ this.error('There is no self-hosted registry in this panel yet.', {
50
+ suggestions: ['Provision one first from Settings -> Registry.'],
51
+ });
52
+ }
53
+ try {
54
+ if (flags.reset) {
55
+ const fresh = await api(config, '/registries/self-hosted/password', { method: 'POST' });
56
+ this.log(successLine('Password reset. Images were not touched.'));
57
+ this.log(` username: ${fresh.username}`);
58
+ this.log(` password: ${fresh.password}`);
59
+ this.log(`Log in again with: docker login ${registry.url} -u ${fresh.username}`);
60
+ return;
61
+ }
62
+ const creds = await api(config, `/registries/${registry.id}/credentials`);
63
+ this.log(` address: ${creds.url}`);
64
+ this.log(` username: ${creds.username ?? ''}`);
65
+ this.log(` password: ${creds.password ?? ''}`);
66
+ }
67
+ catch (error) {
68
+ if (error instanceof ApiError && (error.status === 403 || error.status === 404 || error.status === 502)) {
69
+ this.error(error.message);
70
+ }
71
+ throw error;
72
+ }
73
+ }
74
+ }
@@ -1,11 +1,11 @@
1
1
  import { confirm } from '@inquirer/prompts';
2
2
  import { Command, Flags } from '@oclif/core';
3
- import { chmod, copyFile, mkdir, readFile, rename, stat, writeFile } from 'node:fs/promises';
3
+ import { readFile, rename, stat, writeFile } from 'node:fs/promises';
4
4
  import { resolve } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { overrideDryRunNote, overrideGuardMessage } from '../lib/compose-version.js';
7
7
  import { dockerCapture, dockerInherit } from '../lib/docker.js';
8
- import { backupStamp, chooseComposeFiles, composeArgs, composeDefaults, composeVariables, DIST_FILE, DOMAIN_FILE, mergeEnv, MissingSecretsError, OVERRIDE_FILE, parseEnv, repairDefaults, runningFileNames, summarizeDiff, } from '../lib/reinstall.js';
8
+ import { backupInstallFiles, backupStamp, chooseComposeFiles, composeArgs, composeDefaults, composeVariables, DIST_FILE, DOMAIN_FILE, mergeEnv, MissingSecretsError, OVERRIDE_FILE, parseEnv, repairDefaults, runningFileNames, summarizeDiff, } from '../lib/reinstall.js';
9
9
  import { stepLine, successLine, warnLine } from '../lib/style.js';
10
10
  import { commandExists, dockerRunning, dockerSocketGid, isRoot, waitForApi } from '../lib/system.js';
11
11
  const READY_TIMEOUT_MS = 120_000;
@@ -152,16 +152,7 @@ export default class Reinstall extends Command {
152
152
  await rename(tmp, path);
153
153
  }
154
154
  async backup(dir, backupDir, present) {
155
- await mkdir(backupDir, { mode: 0o700, recursive: true });
156
- for (const name of ['.env.dist', ...present]) {
157
- const src = `${dir}/${name}`;
158
- // eslint-disable-next-line no-await-in-loop
159
- await copyFile(src, `${backupDir}/${name}`);
160
- // .env.dist holds the secrets — the copy must be just as private.
161
- // eslint-disable-next-line no-await-in-loop
162
- if (name === '.env.dist')
163
- await chmod(`${backupDir}/${name}`, 0o600);
164
- }
155
+ await backupInstallFiles(dir, backupDir, present);
165
156
  this.log(stepLine('Backing up previous files to', backupDir));
166
157
  }
167
158
  async ensureDocker() {
@@ -93,6 +93,10 @@ export default class Run extends EnvCommand {
93
93
  async linkedVariables(flags) {
94
94
  const { config, link } = await this.connect(flags);
95
95
  const owner = (await this.resolveOwner(config, link, flags, true));
96
+ // A viewer gets no env text, so running would silently drop the own env.
97
+ if (owner.detail.envHidden) {
98
+ this.fail(`${owner.label}: your role in this project cannot read its environment.`, "Ask a developer or admin of the project, or use --set/--env for a set environment you may read.");
99
+ }
96
100
  const links = [...owner.detail.variableSets].sort((a, b) => a.position - b.position);
97
101
  const layers = [];
98
102
  // One at a time, in order: a refused reveal (protected, viewer, token
@@ -30,10 +30,29 @@ export default class UpdatePanel extends Command {
30
30
  throw error;
31
31
  }
32
32
  await warnIfOutdated((m) => this.logToStderr(warnLine(m)), this.config.version, config);
33
- const status = await api(config, '/instance/update');
33
+ let status;
34
+ try {
35
+ status = await api(config, '/instance/update');
36
+ }
37
+ catch (error) {
38
+ if (error instanceof ApiError && error.status >= 500) {
39
+ this.error(`The panel could not check for updates: ${error.message}`, {
40
+ suggestions: ['Check the panel logs (docker compose logs api) and that API_IMAGE / WEB_IMAGE point at a reachable registry.'],
41
+ });
42
+ }
43
+ throw error;
44
+ }
34
45
  this.log(`Running version: ${status.currentVersion}`);
35
46
  this.printImage('api', status.api);
36
47
  this.printImage('web', status.web);
48
+ const failed = [status.api, status.web].filter((image) => image.error);
49
+ for (const image of failed)
50
+ this.logToStderr(warnLine(image.error ?? 'Registry lookup failed.'));
51
+ if (failed.length > 0 && !status.api.updateAvailable && !status.web.updateAvailable) {
52
+ this.error('Could not compare with the registry, so no update status is available.', {
53
+ suggestions: ['Set API_IMAGE / WEB_IMAGE in the panel .env.dist to images the registry serves, or check its connectivity.'],
54
+ });
55
+ }
37
56
  const available = status.api.updateAvailable || status.web.updateAvailable;
38
57
  if (!available) {
39
58
  this.log(successLine('Already up to date.'));
@@ -52,12 +71,15 @@ export default class UpdatePanel extends Command {
52
71
  suggestions: ['Make sure INSTALL_DIR is set in the panel .env.dist, then restart the stack and try again.'],
53
72
  });
54
73
  }
74
+ if (error instanceof ApiError && error.status === 502) {
75
+ this.error(error.message);
76
+ }
55
77
  throw error;
56
78
  }
57
79
  this.log(successLine('Update applied — the panel will restart for a few seconds to apply it.'));
58
80
  }
59
81
  printImage(label, status) {
60
- const state = status.currentDigest === null ? 'new baseline' : status.updateAvailable ? 'update available' : 'up to date';
82
+ const state = status.error ? 'lookup failed' : status.currentDigest === null ? 'new baseline' : status.updateAvailable ? 'update available' : 'up to date';
61
83
  this.log(` ${label}: ${status.image} (${state})`);
62
84
  }
63
85
  }
@@ -3,7 +3,7 @@ export declare class DockerCommandError extends Error {
3
3
  constructor(command: string, code: number);
4
4
  }
5
5
  /** Runs `docker <args>` with the child's stdout/stderr shown as-is (docker's own output is already readable). */
6
- export declare function dockerInherit(args: string[], cwd: string): Promise<void>;
6
+ export declare function dockerInherit(args: string[], cwd: string, env?: NodeJS.ProcessEnv): Promise<void>;
7
7
  /**
8
8
  * `docker login <registry> -u <user> --password-stdin`: the password never
9
9
  * touches argv (visible in `ps`/Task Manager) or shell history.
@@ -8,9 +8,9 @@ export class DockerCommandError extends Error {
8
8
  }
9
9
  }
10
10
  /** Runs `docker <args>` with the child's stdout/stderr shown as-is (docker's own output is already readable). */
11
- export function dockerInherit(args, cwd) {
11
+ export function dockerInherit(args, cwd, env) {
12
12
  return new Promise((resolve, reject) => {
13
- const child = spawn('docker', args, { cwd, stdio: 'inherit' });
13
+ const child = spawn('docker', args, { cwd, env: env ? { ...process.env, ...env } : undefined, stdio: 'inherit' });
14
14
  child.on('error', (error) => {
15
15
  reject(error.code === 'ENOENT'
16
16
  ? new Error('docker not found in PATH. Install Docker Desktop or Docker Engine first.')