Skip to content

Commit 49cd1c5

Browse files
Add admin password reset / recovery script
For when you're locked out (e.g. a typo in the admin password during setup): - scripts/reset-admin.sh: lists existing administrators, then prompts for an email and a new password (hidden, confirmed). Creates the account if the email is new, otherwise resets its password, forces role ADMIN + enabled, and clears its sessions; can optionally disable its 2FA. Starts the project-local PostgreSQL on demand if it isn't already running. - apps/api/scripts/reset-admin.ts: the env-driven worker (argon2 hashing, same as the app), also supports RESET_LIST=1 to just list admins. Verified end to end: reset changes the hash (old password rejected, new accepted), role/enabled enforced, sessions cleared; creating a brand-new admin works too. Documented in DEPLOYMENT.
1 parent 6fc9116 commit 49cd1c5

3 files changed

Lines changed: 165 additions & 0 deletions

File tree

‎apps/api/scripts/reset-admin.ts‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
/**
2+
* Admin account recovery. Reset (or create) an administrator's password directly in the
3+
* database — for when you've locked yourself out. Driven by env vars so the shell wrapper
4+
* (scripts/reset-admin.sh) can collect the password securely:
5+
*
6+
* RESET_LIST=1 -> just list existing admin accounts
7+
* RESET_EMAIL=, RESET_PASSWORD= -> reset that account's password (creates it if new)
8+
* RESET_CLEAR_2FA=1 -> also disable 2FA + clear recovery codes
9+
*
10+
* Run via: pnpm --filter @opencoperlock/api exec tsx scripts/reset-admin.ts
11+
*/
12+
import '../src/config/dotenv.js';
13+
import { PrismaClient } from '@prisma/client';
14+
import { hashPassword } from '../src/services/password.js';
15+
16+
const prisma = new PrismaClient();
17+
18+
async function main(): Promise<void> {
19+
if (process.env.RESET_LIST === '1') {
20+
const admins = await prisma.user.findMany({
21+
where: { role: 'ADMIN' },
22+
select: { email: true, disabled: true, totpEnabled: true },
23+
orderBy: { createdAt: 'asc' },
24+
});
25+
if (admins.length === 0) {
26+
console.log(' (no administrator accounts exist yet)');
27+
} else {
28+
for (const a of admins) {
29+
const flags = [a.disabled ? 'disabled' : null, a.totpEnabled ? '2FA on' : null]
30+
.filter(Boolean)
31+
.join(', ');
32+
console.log(` - ${a.email}${flags ? ` (${flags})` : ''}`);
33+
}
34+
}
35+
return;
36+
}
37+
38+
const email = process.env.RESET_EMAIL?.trim().toLowerCase();
39+
const password = process.env.RESET_PASSWORD;
40+
const clear2fa = process.env.RESET_CLEAR_2FA === '1';
41+
if (!email || !password) throw new Error('RESET_EMAIL and RESET_PASSWORD are required.');
42+
if (password.length < 12) throw new Error('Password must be at least 12 characters.');
43+
44+
const passwordHash = await hashPassword(password);
45+
const existing = await prisma.user.findUnique({ where: { email } });
46+
47+
if (existing) {
48+
await prisma.user.update({
49+
where: { email },
50+
data: {
51+
passwordHash,
52+
role: 'ADMIN',
53+
disabled: false,
54+
...(clear2fa ? { totpEnabled: false, totpSecret: null } : {}),
55+
},
56+
});
57+
// Invalidate existing sessions so any attacker-held session is dropped too.
58+
await prisma.session.deleteMany({ where: { userId: existing.id } });
59+
if (clear2fa) await prisma.recoveryCode.deleteMany({ where: { userId: existing.id } });
60+
console.log(
61+
`Reset password for admin '${email}'${clear2fa ? ' and disabled 2FA' : ''}; sessions cleared.`,
62+
);
63+
} else {
64+
const quota = process.env.DEFAULT_USER_QUOTA_BYTES;
65+
await prisma.user.create({
66+
data: { email, passwordHash, role: 'ADMIN', quotaBytes: quota ? BigInt(quota) : null },
67+
});
68+
console.log(`Created new admin '${email}'.`);
69+
}
70+
}
71+
72+
main()
73+
.catch((err) => {
74+
console.error('ERROR:', err instanceof Error ? err.message : err);
75+
process.exit(1);
76+
})
77+
.finally(() => prisma.$disconnect());

‎docs/DEPLOYMENT.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,20 @@ Put both processes behind your proxy exactly as in the Docker section above (web
237237
:3000, API on :4000), terminating TLS there. Set `WEB_HOST=127.0.0.1` in the environment
238238
if you want the web process to bind only to localhost behind the proxy.
239239

240+
## Locked out? Reset the admin password
241+
242+
If you mistyped the admin email or password during setup (or forgot it), reset it from the
243+
server — no database knowledge required:
244+
245+
```bash
246+
./scripts/reset-admin.sh
247+
```
248+
249+
It lists the existing administrator accounts, then prompts for an email and a new password
250+
(it creates the account if that email doesn't exist, or resets it if it does). It also
251+
clears that account's sessions, and can optionally disable its two-factor. The
252+
project-local database is started automatically if it isn't already running.
253+
240254
## Running without Docker (dev)
241255

242256
```bash

‎scripts/reset-admin.sh‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
#!/usr/bin/env bash
2+
#
3+
# Reset (or create) an OpenCoperLock administrator's password — for when you're locked out
4+
# (e.g. a typo in the password during setup). Lists existing admins, then prompts for an
5+
# email and a new password. Works with the project-local PostgreSQL (started on demand).
6+
#
7+
# ./scripts/reset-admin.sh
8+
#
9+
set -euo pipefail
10+
11+
cd "$(dirname "$0")/.."
12+
[[ -f .env ]] || { echo "ERROR: .env not found (run from the project, after setup)." >&2; exit 1; }
13+
14+
# Read a value from .env without sourcing it (safe with special characters).
15+
read_env() {
16+
local key="$1" line val
17+
line="$(grep -E "^${key}=" .env | tail -1 || true)"
18+
val="${line#*=}"
19+
[[ "$val" == \"*\" ]] && val="${val:1:${#val}-2}"
20+
[[ "$val" == \'*\' ]] && val="${val:1:${#val}-2}"
21+
printf '%s' "$val"
22+
}
23+
24+
export DATABASE_URL="$(read_env DATABASE_URL)"
25+
[[ -n "$DATABASE_URL" ]] || { echo "ERROR: DATABASE_URL not set in .env" >&2; exit 1; }
26+
27+
# Ensure the database is reachable; start the project-local cluster if it isn't running.
28+
db_reachable() {
29+
local hp="${DATABASE_URL#*@}"; hp="${hp%%/*}"
30+
local host="${hp%%:*}"; local port="${hp##*:}"
31+
[[ "$port" == "$host" ]] && port=5432
32+
(exec 3<>"/dev/tcp/${host}/${port}") 2>/dev/null
33+
}
34+
STARTED_LOCAL_PG=false
35+
if ! db_reachable; then
36+
if [[ -f .postgres/data/PG_VERSION ]]; then
37+
./scripts/postgres-local.sh ctl-start >/dev/null
38+
STARTED_LOCAL_PG=true
39+
else
40+
echo "ERROR: the database is not reachable (is PM2 running it?)." >&2
41+
exit 1
42+
fi
43+
fi
44+
cleanup() { [[ "$STARTED_LOCAL_PG" == true ]] && ./scripts/postgres-local.sh ctl-stop >/dev/null 2>&1 || true; }
45+
trap cleanup EXIT
46+
47+
run_node() { pnpm --filter @opencoperlock/api exec tsx scripts/reset-admin.ts; }
48+
49+
echo "Existing administrator accounts:"
50+
RESET_LIST=1 run_node || true
51+
echo ""
52+
53+
DEF_EMAIL="$(read_env ADMIN_EMAIL)"
54+
read -r -p "Admin email to reset or create [${DEF_EMAIL}]: " EMAIL
55+
EMAIL="${EMAIL:-$DEF_EMAIL}"
56+
[[ -n "$EMAIL" ]] || { echo "ERROR: no email given." >&2; exit 1; }
57+
58+
PW=''
59+
while :; do
60+
read -r -s -p "New password (min 12 chars): " PW; echo
61+
if [[ ${#PW} -lt 12 ]]; then echo " Too short."; continue; fi
62+
read -r -s -p "Confirm password: " PW2; echo
63+
if [[ "$PW" != "$PW2" ]]; then echo " Passwords do not match."; continue; fi
64+
break
65+
done
66+
67+
CLEAR2FA=0
68+
read -r -p "Also disable two-factor for this account? [y/N] " ans
69+
[[ "$ans" =~ ^[Yy]$ ]] && CLEAR2FA=1
70+
71+
RESET_EMAIL="$EMAIL" RESET_PASSWORD="$PW" RESET_CLEAR_2FA="$CLEAR2FA" run_node
72+
73+
echo ""
74+
echo "Done — sign in at your app URL with this email and the new password."

0 commit comments

Comments
 (0)