Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: add CLI to reset a lost/broken instance password (#9226)

[._.]/3d2ec9223c35
diff --git a/package.json b/package.json
index e974cf4d80..2e256ba898 100644
--- a/package.json
+++ b/package.json
@@ -43,6 +43,7 @@
"setup:guide": "node scripts/setup-guide.js",
"setup:ghostty": "node scripts/setup-ghostty.js",
"setup:hooks": "bash scripts/setup-git-hooks.sh",
+ "reset:password": "node scripts/reset-password.js",
"update": "node -e \"const{spawnSync:s}=require('child_process');const w=process.platform==='win32';const r=s(w?'powershell':'bash',w?['-NoProfile','-ExecutionPolicy','Bypass','-File','update.ps1']:['update.sh'],{stdio:'inherit'});process.exit(r.status??1)\"",
"test": "npm test --prefix server && npm test --prefix client",
"pregate": "node scripts/pregate.js",
diff --git a/scripts/reset-password.js b/scripts/reset-password.js
new file mode 100644
index 0000000000..79f3259d80
--- /dev/null
+++ b/scripts/reset-password.js
@@ -0,0 +1,154 @@
+#!/usr/bin/env node
+/**
+ * CLI recovery path for a lost/broken PortOS instance password (the web UI's
+ * own password change requires the CURRENT password, so it cannot help here).
+ * Writes `secrets.auth` in `data/settings.json` directly — the same shape
+ * `server/services/auth.js` `setPassword`/`clearPassword` produce — using the
+ * same scrypt primitives from `lib/portosAuthCore.js` so the result is
+ * byte-compatible with a normal in-app password change. Bypasses the
+ * current-password check on purpose: this tool exists for the case where that
+ * check can no longer be satisfied. Filesystem access to the install already
+ * implies the same trust level as the running server process (see AGENTS.md
+ * "Security Model").
+ *
+ * All existing sessions are revoked, matching setPassword/clearPassword's
+ * behavior. The running server caches settings.json in memory and only
+ * refreshes it on an in-app write, so it must be RESTARTED after this runs.
+ *
+ * Usage:
+ * node scripts/reset-password.js <newPassword> # set/replace the password
+ * node scripts/reset-password.js --disable # turn the password gate off
+ * node scripts/reset-password.js --status # report enabled/disabled only
+ */
+import { randomBytes } from 'node:crypto';
+import { join } from 'node:path';
+import { hashPassword, SALT_BYTES } from '../lib/portosAuthCore.js';
+import { atomicWrite, safeJSONParse, tryReadFileStrict, PATHS } from '../server/lib/fileUtils.js';
+import { isPlainObject } from '../server/lib/objects.js';
+import { isDirectlyInvoked } from './lib/directInvocation.js';
+
+export const USAGE = [
+ 'Usage:',
+ ' node scripts/reset-password.js <newPassword> # set/replace the password',
+ ' node scripts/reset-password.js --disable # turn the password gate off',
+ ' node scripts/reset-password.js --status # report enabled/disabled only',
+].join('\n');
+
+export const isPasswordAuthEnabled = (settings) => {
+ const auth = settings?.secrets?.auth;
+ return !!(auth?.enabled && auth?.passwordHash && auth?.salt);
+};
+
+// Pure: builds the next settings object for `--disable`, or `null` when auth
+// was already off (nothing to write).
+export const buildDisabledSettings = (settings) => {
+ if (!settings?.secrets?.auth) return null;
+ const secrets = { ...settings.secrets };
+ delete secrets.auth;
+ return { ...settings, secrets, passwordRiskRevision: randomBytes(16).toString('hex') };
+};
+
+// Validates the candidate password (mirrors setPassword's bounds) and builds
+// the next settings object with a freshly-hashed `secrets.auth` record.
+export const buildPasswordSettings = async (settings, newPassword) => {
+ if (typeof newPassword !== 'string' || newPassword.length < 8) {
+ throw new Error('Password must be at least 8 characters.');
+ }
+ if (newPassword.length > 256) {
+ throw new Error('Password too long (max 256 characters).');
+ }
+ const salt = randomBytes(SALT_BYTES).toString('hex');
+ const passwordHash = await hashPassword(newPassword, salt);
+ const secrets = { ...(settings.secrets || {}) };
+ secrets.auth = {
+ enabled: true,
+ kdf: 'scrypt',
+ passwordHash,
+ salt,
+ updatedAt: new Date().toISOString(),
+ };
+ return { ...settings, secrets, passwordRiskRevision: randomBytes(16).toString('hex') };
+};
+
+// Strict read: a present-but-unreadable settings.json (a transient lock, a
+// permission error) must never be treated as "absent" — collapsing it to {}
+// would make the write below silently discard every other setting on disk.
+const loadSettings = async (settingsFile) => {
+ const { ok, value: raw } = await tryReadFileStrict(settingsFile);
+ if (!ok) {
+ throw new Error(`settings.json exists but could not be read (permission or I/O error): ${settingsFile}`);
+ }
+ const parsed = safeJSONParse(raw ?? '{}', {});
+ return isPlainObject(parsed) ? parsed : {};
+};
+
+const writeJSON = async (filePath, value) => {
+ await atomicWrite(filePath, JSON.stringify(value, null, 2) + '\n');
+};
+
+/**
+ * Runs one reset-password action against the given data directory and
+ * returns `{ code, message }` for the caller to print/exit with — kept
+ * separate from `main()` so tests can point it at a temp directory instead of
+ * the real install's `data/`.
+ */
+export const runResetPassword = async (arg, { dataDir = PATHS.data } = {}) => {
+ if (!arg || arg === '--help' || arg === '-h') {
+ return { code: arg ? 0 : 1, message: USAGE };
+ }
+
+ const settingsFile = join(dataDir, 'settings.json');
+ let settings;
+ try {
+ settings = await loadSettings(settingsFile);
+ } catch (err) {
+ return { code: 1, message: `❌ ${err.message}` };
+ }
+
+ if (arg === '--status') {
+ return {
+ code: 0,
+ message: isPasswordAuthEnabled(settings) ? '🔒 Password auth is enabled.' : '🔓 Password auth is disabled.',
+ };
+ }
+
+ const sessionsFile = join(dataDir, 'auth-sessions.json');
+ const restartReminder = '⚠️ Restart PortOS for this to take effect (it caches settings.json in memory):\n npm run pm2:restart';
+
+ if (arg === '--disable') {
+ const next = buildDisabledSettings(settings);
+ if (!next) return { code: 0, message: '🔓 Password auth is already disabled — nothing to do.' };
+ // Revoke sessions BEFORE committing the new auth state: if the process is
+ // interrupted between the two writes, an old session must not stay valid
+ // under whatever auth state lands — better to have revoked and nothing
+ // else changed than to have changed auth state with stale sessions live.
+ await writeJSON(sessionsFile, { tokens: [] });
+ await writeJSON(settingsFile, next);
+ return { code: 0, message: `✅ Password auth disabled and all sessions revoked.\n${restartReminder}` };
+ }
+
+ let next;
+ try {
+ next = await buildPasswordSettings(settings, arg);
+ } catch (err) {
+ return { code: 1, message: `❌ ${err.message}` };
+ }
+ await writeJSON(sessionsFile, { tokens: [] });
+ await writeJSON(settingsFile, next);
+ return { code: 0, message: `✅ Password reset and all sessions revoked.\n${restartReminder}` };
+};
+
+const main = async () => {
+ const [arg] = process.argv.slice(2);
+ const { code, message } = await runResetPassword(arg);
+ if (code === 0) console.log(message);
+ else console.error(message);
+ process.exit(code);
+};
+
+if (isDirectlyInvoked(import.meta.url)) {
+ main().catch((err) => {
+ console.error(`❌ Password reset failed: ${err.message}`);
+ process.exit(1);
+ });
+}
diff --git a/scripts/reset-password.test.js b/scripts/reset-password.test.js
new file mode 100644
index 0000000000..257a58627e
--- /dev/null
+++ b/scripts/reset-password.test.js
@@ -0,0 +1,147 @@
+import { describe, expect, it } from 'vitest';
+import { mkdir, mkdtemp, readFile, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import {
+ buildDisabledSettings,
+ buildPasswordSettings,
+ isPasswordAuthEnabled,
+ runResetPassword,
+ USAGE,
+} from './reset-password.js';
+
+const withTempDataDir = async (fn) => {
+ const dataDir = await mkdtemp(join(tmpdir(), 'portos-reset-password-'));
+ try {
+ await fn(dataDir);
+ } finally {
+ await rm(dataDir, { recursive: true, force: true });
+ }
+};
+
+describe('isPasswordAuthEnabled', () => {
+ it('is false when secrets.auth is absent, incomplete, or disabled', () => {
+ expect(isPasswordAuthEnabled({})).toBe(false);
+ expect(isPasswordAuthEnabled({ secrets: {} })).toBe(false);
+ expect(isPasswordAuthEnabled({ secrets: { auth: { enabled: true } } })).toBe(false);
+ expect(isPasswordAuthEnabled({ secrets: { auth: { enabled: false, passwordHash: 'h', salt: 's' } } })).toBe(false);
+ });
+
+ it('is true only with enabled + passwordHash + salt all present', () => {
+ expect(isPasswordAuthEnabled({ secrets: { auth: { enabled: true, passwordHash: 'h', salt: 's' } } })).toBe(true);
+ });
+});
+
+describe('buildDisabledSettings', () => {
+ it('returns null when auth was already off — nothing to write', () => {
+ expect(buildDisabledSettings({})).toBeNull();
+ expect(buildDisabledSettings({ secrets: {} })).toBeNull();
+ });
+
+ it('drops secrets.auth and rotates passwordRiskRevision, preserving unrelated settings', () => {
+ const before = { foo: 'bar', secrets: { auth: { enabled: true, passwordHash: 'h', salt: 's' }, other: 1 } };
+ const next = buildDisabledSettings(before);
+ expect(next.foo).toBe('bar');
+ expect(next.secrets).toEqual({ other: 1 });
+ expect(typeof next.passwordRiskRevision).toBe('string');
+ expect(next.passwordRiskRevision.length).toBeGreaterThan(0);
+ });
+});
+
+describe('buildPasswordSettings', () => {
+ it('rejects a password shorter than 8 characters', async () => {
+ await expect(buildPasswordSettings({}, 'short')).rejects.toThrow(/at least 8 characters/);
+ });
+
+ it('rejects a password longer than 256 characters', async () => {
+ await expect(buildPasswordSettings({}, 'x'.repeat(257))).rejects.toThrow(/too long/);
+ });
+
+ it('produces a scrypt secrets.auth record that verifies against the given password', async () => {
+ const before = { foo: 'bar', secrets: { other: 1 } };
+ const next = await buildPasswordSettings(before, 'correct horse battery staple');
+ expect(next.foo).toBe('bar');
+ expect(next.secrets.other).toBe(1);
+ expect(next.secrets.auth.enabled).toBe(true);
+ expect(next.secrets.auth.kdf).toBe('scrypt');
+ expect(typeof next.secrets.auth.salt).toBe('string');
+ expect(typeof next.secrets.auth.passwordHash).toBe('string');
+
+ const { hashPassword, constantEqual } = await import('../lib/portosAuthCore.js');
+ const rehash = await hashPassword('correct horse battery staple', next.secrets.auth.salt);
+ expect(constantEqual(rehash, next.secrets.auth.passwordHash)).toBe(true);
+ });
+});
+
+describe('runResetPassword', () => {
+ it('prints usage and exits 1 when called with no argument', async () => {
+ const result = await runResetPassword(undefined, { dataDir: '/unused' });
+ expect(result).toEqual({ code: 1, message: USAGE });
+ });
+
+ it('--status reports disabled against a settings.json that never mentions auth', async () => {
+ await withTempDataDir(async (dataDir) => {
+ const result = await runResetPassword('--status', { dataDir });
+ expect(result).toEqual({ code: 0, message: '🔓 Password auth is disabled.' });
+ });
+ });
+
+ it('sets a password, persists it, and revokes sessions; --status then reports enabled', async () => {
+ await withTempDataDir(async (dataDir) => {
+ const setResult = await runResetPassword('a-new-password', { dataDir });
+ expect(setResult.code).toBe(0);
+ expect(setResult.message).toMatch(/Password reset and all sessions revoked/);
+ expect(setResult.message).toMatch(/npm run pm2:restart/);
+
+ const settings = JSON.parse(await readFile(join(dataDir, 'settings.json'), 'utf8'));
+ expect(isPasswordAuthEnabled(settings)).toBe(true);
+
+ const sessions = JSON.parse(await readFile(join(dataDir, 'auth-sessions.json'), 'utf8'));
+ expect(sessions).toEqual({ tokens: [] });
+
+ const statusResult = await runResetPassword('--status', { dataDir });
+ expect(statusResult).toEqual({ code: 0, message: '🔒 Password auth is enabled.' });
+ });
+ });
+
+ it('rejects a too-short password without writing anything', async () => {
+ await withTempDataDir(async (dataDir) => {
+ const result = await runResetPassword('short', { dataDir });
+ expect(result).toEqual({ code: 1, message: '❌ Password must be at least 8 characters.' });
+ const statusResult = await runResetPassword('--status', { dataDir });
+ expect(statusResult.message).toBe('🔓 Password auth is disabled.');
+ });
+ });
+
+ it('--disable turns off a previously-set password and revokes sessions', async () => {
+ await withTempDataDir(async (dataDir) => {
+ await runResetPassword('a-new-password', { dataDir });
+ const disableResult = await runResetPassword('--disable', { dataDir });
+ expect(disableResult.code).toBe(0);
+ expect(disableResult.message).toMatch(/disabled and all sessions revoked/);
+
+ const statusResult = await runResetPassword('--status', { dataDir });
+ expect(statusResult.message).toBe('🔓 Password auth is disabled.');
+ });
+ });
+
+ it('--disable is a no-op when auth is already off', async () => {
+ await withTempDataDir(async (dataDir) => {
+ const result = await runResetPassword('--disable', { dataDir });
+ expect(result).toEqual({ code: 0, message: '🔓 Password auth is already disabled — nothing to do.' });
+ });
+ });
+
+ it('refuses to proceed when settings.json exists but cannot be read, rather than treating it as empty and overwriting it', async () => {
+ await withTempDataDir(async (dataDir) => {
+ // A directory in settings.json's place reads as EISDIR — present but
+ // unreadable, distinct from ENOENT (genuinely absent). Collapsing this
+ // to `{}` would make the write path silently discard every real
+ // setting on disk; it must instead refuse without writing anything.
+ await mkdir(join(dataDir, 'settings.json'));
+ const result = await runResetPassword('a-new-password', { dataDir });
+ expect(result.code).toBe(1);
+ expect(result.message).toMatch(/could not be read/);
+ });
+ });
+});