()
| 27 | import { passwordService } from "../../src/lib/password"; |
| 28 | |
| 29 | async function main(): Promise<void> { |
| 30 | const email = env.SUPERUSER_EMAIL.trim(); |
| 31 | const password = env.SUPERUSER_PASSWORD; |
| 32 | |
| 33 | if (email === "" || password === "") { |
| 34 | console.log( |
| 35 | "[seed-superuser] SUPERUSER_EMAIL or SUPERUSER_PASSWORD unset — skipping. " + |
| 36 | "Set both, then run `bun run db:seed`, to create a privileged user, or sign up via the UI. " + |
| 37 | "Running under docker-compose? The api-migrate service interpolates these " + |
| 38 | "from compose/.env (NOT apps/api/.env)." |
| 39 | ); |
| 40 | |
| 41 | return; |
| 42 | } |
| 43 | |
| 44 | const existing = await db.query.users.findFirst({ |
| 45 | where: eq(users.email, email), |
| 46 | }); |
| 47 | |
| 48 | if (existing !== undefined) { |
| 49 | console.log( |
| 50 | `[seed-superuser] user ${email} already exists — skipping. ` + |
| 51 | "Rotate via the password-reset flow if needed." |
| 52 | ); |
| 53 | |
| 54 | return; |
| 55 | } |
| 56 | |
| 57 | const passwordHash = await passwordService.hash(password); |
| 58 | const nowIso = now(); |
| 59 | |
| 60 | await db.transaction(async (tx) => { |
| 61 | const [user] = await tx |
| 62 | .insert(users) |
| 63 | .values({ |
| 64 | email, |
| 65 | firstName: "Admin", |
| 66 | lastName: "", |
| 67 | emailVerifiedAt: nowIso, |
| 68 | isPlatformAdmin: true, |
| 69 | }) |
| 70 | .returning(); |
| 71 | |
| 72 | if (!user) { |
| 73 | throw new Error("Failed to insert superuser"); |
| 74 | } |
| 75 | |
| 76 | await tx.insert(userAuthProviders).values({ |
| 77 | userId: user.id, |
| 78 | provider: EMAIL_PROVIDER_KEY, |
| 79 | providerUserId: email, |
| 80 | passwordHash, |
| 81 | }); |
| 82 | |
| 83 | /* |
| 84 | * Login resolves `aid` from the user's first active membership, |
| 85 | * so the seed reaches the same convergence point a real verify- |
| 86 | * email click would. Passing `tx` keeps the whole bootstrap |
no test coverage detected