refactor: replace admin bootstrap script with first-run setup

This commit is contained in:
2026-06-06 00:02:43 +01:00
parent b435a92da8
commit 5be93c65ea
7 changed files with 210 additions and 114 deletions
+3 -18
View File
@@ -32,22 +32,14 @@ Apply database migrations:
DATABASE_URL=file:local.db pnpm db:migrate DATABASE_URL=file:local.db pnpm db:migrate
``` ```
Create an initial admin user:
```sh
ADMIN_EMAIL=admin@example.com \
ADMIN_PASSWORD='change-me' \
ADMIN_NAME='Administrator' \
DATABASE_URL=file:local.db \
pnpm admin:create
```
Start the development server: Start the development server:
```sh ```sh
pnpm dev pnpm dev
``` ```
Open `http://localhost:5173/login`. If no Better Auth users exist yet, Clearity shows a first-admin setup form instead of the normal sign-in form. Submitting it creates the initial user with the default Better Auth `admin` role and signs you in.
Useful development commands: Useful development commands:
```sh ```sh
@@ -68,13 +60,6 @@ Required:
- `ORIGIN`: Public app origin, for example `http://localhost:5173` locally or `https://clearity.example.com` in production. - `ORIGIN`: Public app origin, for example `http://localhost:5173` locally or `https://clearity.example.com` in production.
- `BETTER_AUTH_SECRET`: Secret used by Better Auth. - `BETTER_AUTH_SECRET`: Secret used by Better Auth.
Admin bootstrap script:
- `ADMIN_EMAIL`: Email address for the admin account.
- `ADMIN_PASSWORD`: Password for the admin account.
- `ADMIN_NAME`: Optional display name. Defaults to `Administrator`.
- `ADMIN_OVERWRITE`: Set to `1` to update an existing admin user.
## Database ## Database
The application schema lives in `src/lib/server/db`. Drizzle migration files live in `drizzle`. The application schema lives in `src/lib/server/db`. Drizzle migration files live in `drizzle`.
@@ -163,4 +148,4 @@ Preview the built Worker locally:
pnpm preview pnpm preview
``` ```
Create the first production admin user by running the admin script against the production database connection before exposing the app to users. Create the first production admin by opening `/login` after migrations have run. The setup form is only shown while the Better Auth `user` table is empty.
+1 -4
View File
@@ -6,7 +6,6 @@
"scripts": { "scripts": {
"dev": "vite dev", "dev": "vite dev",
"build": "wrangler types --check && vite build", "build": "wrangler types --check && vite build",
"preview": "wrangler dev .svelte-kit/cloudflare/_worker.js --port 4173",
"prepare": "svelte-kit sync || echo ''", "prepare": "svelte-kit sync || echo ''",
"check": "wrangler types --check && svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", "check": "wrangler types --check && svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch", "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
@@ -16,9 +15,7 @@
"db:push": "drizzle-kit push", "db:push": "drizzle-kit push",
"db:generate": "drizzle-kit generate", "db:generate": "drizzle-kit generate",
"db:migrate": "drizzle-kit migrate", "db:migrate": "drizzle-kit migrate",
"db:studio": "drizzle-kit studio", "auth:schema": "better-auth generate --config src/lib/server/auth.ts --output src/lib/server/db/auth.schema.ts --yes"
"auth:schema": "better-auth generate --config src/lib/server/auth.ts --output src/lib/server/db/auth.schema.ts --yes",
"admin:create": "sh -c 'db=\"${DATABASE_URL:-$([ -d .wrangler/state/v3/d1 ] && find .wrangler/state/v3/d1 -name \"*.sqlite\" -print -quit)}\"; if [ -z \"$db\" ]; then echo \"No local Wrangler D1 SQLite database found. Start wrangler dev or run a local D1 command first.\" >&2; exit 1; fi; if [ -z \"$DATABASE_URL\" ]; then db=\"file:$db\"; fi; DATABASE_URL=\"$db\" node scripts/create-admin.mjs'"
}, },
"devDependencies": { "devDependencies": {
"@better-auth/cli": "~1.4.21", "@better-auth/cli": "~1.4.21",
-90
View File
@@ -1,90 +0,0 @@
import { createClient } from '@libsql/client';
import { hashPassword } from 'better-auth/crypto';
import { readFileSync } from 'node:fs';
import { randomUUID } from 'node:crypto';
function readDotEnv() {
try {
const entries = readFileSync('.env', 'utf8')
.split('\n')
.map((line) => line.trim())
.filter((line) => line && !line.startsWith('#'))
.map((line) => {
const index = line.indexOf('=');
const key = line.slice(0, index);
const value = line.slice(index + 1).replace(/^"|"$/g, '');
return [key, value];
});
for (const [key, value] of entries) {
process.env[key] ??= value;
}
} catch {
// .env is optional in deployed or scripted environments.
}
}
readDotEnv();
const databaseUrl = process.env.DATABASE_URL;
const email = process.env.ADMIN_EMAIL?.trim().toLowerCase();
const password = process.env.ADMIN_PASSWORD;
const name = process.env.ADMIN_NAME?.trim() || 'Administrator';
const overwrite = process.env.ADMIN_OVERWRITE === '1';
if (!databaseUrl) {
console.error('DATABASE_URL is required.');
process.exit(1);
}
if (!email || !password) {
console.error('ADMIN_EMAIL and ADMIN_PASSWORD are required.');
console.error('Example: ADMIN_EMAIL=admin@example.com ADMIN_PASSWORD=change-me pnpm admin:create');
process.exit(1);
}
const client = createClient({ url: databaseUrl });
const now = Date.now();
const existing = await client.execute({
sql: 'select id from user where email = ? limit 1',
args: [email]
});
if (existing.rows.length > 0 && !overwrite) {
console.error(`A user with email ${email} already exists. Set ADMIN_OVERWRITE=1 to update the password.`);
process.exit(1);
}
const userId = existing.rows[0]?.id?.toString() ?? randomUUID();
const passwordHash = await hashPassword(password);
if (existing.rows.length === 0) {
await client.execute({
sql: 'insert into user (id, name, email, email_verified, image, created_at, updated_at) values (?, ?, ?, ?, ?, ?, ?)',
args: [userId, name, email, 1, null, now, now]
});
} else {
await client.execute({
sql: 'update user set name = ?, email_verified = ?, updated_at = ? where id = ?',
args: [name, 1, now, userId]
});
}
const account = await client.execute({
sql: 'select id from account where user_id = ? and provider_id = ? limit 1',
args: [userId, 'credential']
});
if (account.rows.length === 0) {
await client.execute({
sql: 'insert into account (id, account_id, provider_id, user_id, password, created_at, updated_at) values (?, ?, ?, ?, ?, ?, ?)',
args: [randomUUID(), userId, 'credential', userId, passwordHash, now, now]
});
} else {
await client.execute({
sql: 'update account set password = ?, updated_at = ? where id = ?',
args: [passwordHash, now, account.rows[0].id]
});
}
console.log(`Admin user ready: ${email}`);
+131
View File
@@ -0,0 +1,131 @@
<script lang="ts">
import GalleryVerticalEndIcon from '@lucide/svelte/icons/gallery-vertical-end';
import { toast } from 'svelte-sonner';
import { Field as FormField, Control, FieldErrors } from 'formsnap';
import * as Field from '$lib/components/ui/field/index.js';
import { superForm, type SuperValidated } from 'sveltekit-superforms';
import { zod4Client } from 'sveltekit-superforms/adapters';
import type { HTMLAttributes } from 'svelte/elements';
import { Button } from '$lib/components/ui/button/index.js';
import { Input } from '$lib/components/ui/input/index.js';
import { cn, type WithElementRef } from '$lib/utils.js';
import { firstAdminSchema, type FirstAdminSchema } from '$lib/schemas/auth';
let {
ref = $bindable(null),
class: className,
form: initialForm,
...restProps
}: WithElementRef<HTMLAttributes<HTMLDivElement>> & {
form: SuperValidated<FirstAdminSchema['_output'], string>;
} = $props();
const id = $props.id();
// svelte-ignore state_referenced_locally
const firstAdminForm = superForm(initialForm, {
validators: zod4Client(firstAdminSchema),
resetForm: false,
onUpdated: ({ form }) => {
if (!form.valid) {
toast.error(form.message ?? firstError(form.errors), {
id: 'first-admin-error',
position: 'top-center'
});
}
},
onError: ({ result }) => {
toast.error(result.error.message, {
id: 'first-admin-error',
position: 'top-center'
});
}
});
const { form: formData, enhance } = firstAdminForm;
function firstError(errors: Record<string, unknown>) {
for (const value of Object.values(errors)) {
if (Array.isArray(value) && typeof value[0] === 'string') {
return value[0];
}
}
return 'Check the highlighted fields.';
}
</script>
<div class={cn('flex flex-col gap-6', className)} bind:this={ref} {...restProps}>
<form method="POST" action="?/bootstrap" use:enhance>
<Field.Group>
<div class="flex flex-col items-center gap-2 text-center">
<div class="flex flex-col items-center gap-2 font-medium">
<div
class="flex size-9 items-center justify-center rounded-md bg-primary text-primary-foreground"
>
<GalleryVerticalEndIcon class="size-6" />
</div>
<span class="sr-only">Clearity</span>
</div>
<h1 class="text-xl font-bold">Create the first admin</h1>
<Field.Description>
Set up the initial Better Auth admin account for this workspace.
</Field.Description>
</div>
<FormField form={firstAdminForm} name="name">
<Field.Field>
<Control id="name-{id}">
{#snippet children({ props })}
<Field.Label>Name</Field.Label>
<Input
{...props}
autocomplete="name"
placeholder="Administrator"
bind:value={$formData.name}
/>
{/snippet}
</Control>
<Field.Error><FieldErrors /></Field.Error>
</Field.Field>
</FormField>
<FormField form={firstAdminForm} name="email">
<Field.Field>
<Control id="email-{id}">
{#snippet children({ props })}
<Field.Label>Email</Field.Label>
<Input
{...props}
type="email"
autocomplete="email"
placeholder="admin@example.com"
bind:value={$formData.email}
/>
{/snippet}
</Control>
<Field.Error><FieldErrors /></Field.Error>
</Field.Field>
</FormField>
<FormField form={firstAdminForm} name="password">
<Field.Field>
<Control id="password-{id}">
{#snippet children({ props })}
<Field.Label>Password</Field.Label>
<Input
{...props}
type="password"
autocomplete="new-password"
bind:value={$formData.password}
/>
{/snippet}
</Control>
<Field.Error><FieldErrors /></Field.Error>
</Field.Field>
</FormField>
<Field.Field>
<Button type="submit" class="w-full">Create admin</Button>
</Field.Field>
</Field.Group>
</form>
<Field.Description class="px-6 text-center">
This setup screen disappears once the first user exists.
</Field.Description>
</div>
+7
View File
@@ -5,4 +5,11 @@ export const loginSchema = z.object({
password: z.string().min(1, 'Enter your password.') password: z.string().min(1, 'Enter your password.')
}); });
export const firstAdminSchema = z.object({
name: z.string().trim().min(1, 'Enter your name.'),
email: z.email('Enter a valid email address.').transform((value) => value.toLowerCase()),
password: z.string().min(8, 'Password must be at least 8 characters.')
});
export type LoginSchema = typeof loginSchema; export type LoginSchema = typeof loginSchema;
export type FirstAdminSchema = typeof firstAdminSchema;
+62 -1
View File
@@ -1,9 +1,12 @@
import { redirect } from '@sveltejs/kit'; import { redirect } from '@sveltejs/kit';
import { APIError } from 'better-auth/api'; import { APIError } from 'better-auth/api';
import { count } from 'drizzle-orm';
import { message, superValidate } from 'sveltekit-superforms/server'; import { message, superValidate } from 'sveltekit-superforms/server';
import { zod4 } from 'sveltekit-superforms/adapters'; import { zod4 } from 'sveltekit-superforms/adapters';
import { auth } from '$lib/server/auth'; import { auth } from '$lib/server/auth';
import { loginSchema } from '$lib/schemas/auth'; import { db } from '$lib/server/db';
import { user } from '$lib/server/db/schema';
import { firstAdminSchema, loginSchema } from '$lib/schemas/auth';
import type { Actions, PageServerLoad } from './$types'; import type { Actions, PageServerLoad } from './$types';
function getSafeRedirect(url: URL) { function getSafeRedirect(url: URL) {
@@ -21,7 +24,11 @@ export const load: PageServerLoad = async ({ locals, url }) => {
redirect(303, getSafeRedirect(url)); redirect(303, getSafeRedirect(url));
} }
const [{ total }] = await db.select({ total: count() }).from(user);
const needsBootstrap = total === 0;
return { return {
needsBootstrap,
form: await superValidate( form: await superValidate(
{ {
email: url.searchParams.get('email') ?? '', email: url.searchParams.get('email') ?? '',
@@ -29,11 +36,65 @@ export const load: PageServerLoad = async ({ locals, url }) => {
}, },
zod4(loginSchema), zod4(loginSchema),
{ id: 'login' } { id: 'login' }
),
firstAdminForm: await superValidate(
{
name: '',
email: url.searchParams.get('email') ?? '',
password: ''
},
zod4(firstAdminSchema),
{ id: 'first-admin' }
) )
}; };
}; };
export const actions: Actions = { export const actions: Actions = {
bootstrap: async (event) => {
const form = await superValidate(event, zod4(firstAdminSchema), { id: 'first-admin' });
if (!form.valid) {
return message(form, 'Check the highlighted fields.', { status: 400 });
}
const [{ total }] = await db.select({ total: count() }).from(user);
if (total > 0) {
return message(form, 'The first admin account has already been created.', { status: 409 });
}
try {
await auth.api.createUser({
body: {
name: form.data.name,
email: form.data.email,
password: form.data.password,
role: 'admin'
}
});
await auth.api.signInEmail({
body: {
email: form.data.email,
password: form.data.password,
callbackURL: getSafeRedirect(event.url)
}
});
} catch (error) {
if (error instanceof APIError) {
return message(form, error.message || 'Unable to create the first admin account.', {
status: 400
});
}
return message(form, 'Something went wrong while creating the first admin account.', {
status: 500
});
}
redirect(303, getSafeRedirect(event.url));
},
default: async (event) => { default: async (event) => {
const form = await superValidate(event, zod4(loginSchema), { id: 'login' }); const form = await superValidate(event, zod4(loginSchema), { id: 'login' });
+5
View File
@@ -1,4 +1,5 @@
<script lang="ts"> <script lang="ts">
import FirstAdminForm from '$lib/components/first-admin-form.svelte';
import LoginForm from '$lib/components/login-form.svelte'; import LoginForm from '$lib/components/login-form.svelte';
import type { PageData } from './$types'; import type { PageData } from './$types';
@@ -7,6 +8,10 @@
<div class="flex min-h-svh flex-col items-center justify-center gap-6 bg-background p-6 md:p-10"> <div class="flex min-h-svh flex-col items-center justify-center gap-6 bg-background p-6 md:p-10">
<div class="w-full max-w-sm"> <div class="w-full max-w-sm">
{#if data.needsBootstrap}
<FirstAdminForm form={data.firstAdminForm} />
{:else}
<LoginForm form={data.form} /> <LoginForm form={data.form} />
{/if}
</div> </div>
</div> </div>