AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(frontend): schema-colocated Better Auth preview-account seeder (#13746)
Nicholas Tindleb4fab4f3f4bc
diff --git a/autogpt_platform/frontend/scripts/__tests__/seed-preview-accounts.orchestration.test.ts b/autogpt_platform/frontend/scripts/__tests__/seed-preview-accounts.orchestration.test.tsnew file mode 100644index 0000000000..183780aa65--- /dev/null+++ b/autogpt_platform/frontend/scripts/__tests__/seed-preview-accounts.orchestration.test.ts@@ -0,0 +1,207 @@+import { describe, expect, it, vi } from "vitest";+import {+ FAILURE_EXIT_CODE,+ NO_BETTER_AUTH_EXIT_CODE,+ SEEDED_EXIT_CODE,+ reportPreviewSeedFailure,+ resolvePreviewConnectionString,+ runInTransaction,+ seedPreviewAccounts,+ validatePreviewPassword,+} from "../seed-preview-accounts.orchestration";++const OPTIONS = {+ schema: "platform",+ identityTable: '"platform"."UserAuthIdentity"',+ accountTable: '"platform"."UserAuthAccount"',+ password: "twelve-chars", // pragma: allowlist secret+};++function fakePool(tableState: "present" | "absent" | "identity-only") {+ const transactionQueries: string[] = [];+ const release = vi.fn();+ const client = {+ async query(text: string) {+ transactionQueries.push(text);+ return { rows: [], rowCount: 0 };+ },+ release,+ };+ const connect = vi.fn(async () => client);+ const pool = {+ async query(_text: string, params: unknown[] = []) {+ const table = params[0] as string;+ const exists =+ tableState === "present" ||+ (tableState === "identity-only" && table.includes("Identity"));+ return { rows: [{ reg: exists ? table : null }] };+ },+ connect,+ };+ return { pool, client, connect, release, transactionQueries };+}++describe("preview seeder configuration", () => {+ it("pins the cross-repo exit-code contract", () => {+ expect(SEEDED_EXIT_CODE).toBe(0);+ expect(FAILURE_EXIT_CODE).toBe(1);+ expect(NO_BETTER_AUTH_EXIT_CODE).toBe(3);+ });++ it("enforces the 11-reject and 12-accept password boundary", () => {+ expect(() => validatePreviewPassword("x".repeat(11))).toThrow(+ /at least 12 characters/,+ );+ expect(validatePreviewPassword("x".repeat(12))).toBe("x".repeat(12));+ });++ it("rejects missing connection and password configuration", () => {+ expect(() => resolvePreviewConnectionString(undefined, undefined)).toThrow(+ "DIRECT_URL or DATABASE_URL must be set",+ );+ expect(() => validatePreviewPassword(undefined)).toThrow(+ "PREVIEW_ACCOUNTS_PASSWORD must be set",+ );+ });++ it("prefers DIRECT_URL and warns on the DATABASE_URL fallback", () => {+ const reportWarning = vi.fn();+ expect(+ resolvePreviewConnectionString("direct", "pooled", reportWarning),+ ).toBe("direct");+ expect(reportWarning).not.toHaveBeenCalled();+ expect(+ resolvePreviewConnectionString(undefined, "fallback", reportWarning),+ ).toBe("fallback");+ expect(reportWarning).toHaveBeenCalledWith(+ expect.stringContaining("supports an explicit transaction"),+ );+ });++ it("maps a scoped failure message to exit 1", () => {+ const reportError = vi.fn();+ const error = Object.assign(new Error("connection refused"), {+ code: "ECONNREFUSED",+ detail: "secret database detail",+ });++ expect(reportPreviewSeedFailure(error, reportError)).toBe(+ FAILURE_EXIT_CODE,+ );+ expect(reportError).toHaveBeenCalledWith(+ "Preview account seeding failed: connection refused (code ECONNREFUSED)",+ );+ });+});++describe("seedPreviewAccounts", () => {+ it("returns exit 3 when both Better Auth tables are absent", async () => {+ const { pool, connect } = fakePool("absent");+ const reportLog = vi.fn();++ await expect(+ seedPreviewAccounts(pool, OPTIONS, {+ hashPassword: vi.fn(),+ reportLog,+ }),+ ).resolves.toBe(NO_BETTER_AUTH_EXIT_CODE);+ expect(connect).not.toHaveBeenCalled();+ expect(reportLog).toHaveBeenCalledWith(+ expect.stringContaining("pre-migration database"),+ );+ });++ it("fails on a half-applied Better Auth migration", async () => {+ const { pool, connect } = fakePool("identity-only");++ await expect(+ seedPreviewAccounts(pool, OPTIONS, { hashPassword: vi.fn() }),+ ).rejects.toThrow(/half-applied migration/);+ expect(connect).not.toHaveBeenCalled();+ });++ it("returns exit 0 after a committed seed", async () => {+ const { pool, release, transactionQueries } = fakePool("present");+ const seedRoster = vi.fn(async () => ({+ createdIdentities: 5,+ createdAccounts: 5,+ }));+ const reportLog = vi.fn();++ await expect(+ seedPreviewAccounts(pool, OPTIONS, {+ hashPassword: vi.fn(async () => "hash"),+ seedRoster,+ reportLog,+ }),+ ).resolves.toBe(SEEDED_EXIT_CODE);+ expect(transactionQueries).toEqual(["BEGIN", "COMMIT"]);+ expect(release).toHaveBeenCalledOnce();+ expect(reportLog).toHaveBeenCalledWith(+ "Seeded preview accounts: 5 identities and 5 credential accounts created.",+ );+ });++ it("reports an idempotent seed as already up to date", async () => {+ const { pool } = fakePool("present");+ const reportLog = vi.fn();++ await expect(+ seedPreviewAccounts(pool, OPTIONS, {+ hashPassword: vi.fn(async () => "hash"),+ seedRoster: vi.fn(async () => ({+ createdIdentities: 0,+ createdAccounts: 0,+ })),+ reportLog,+ }),+ ).resolves.toBe(SEEDED_EXIT_CODE);+ expect(reportLog).toHaveBeenCalledWith(+ "Preview accounts are now up to date; no new identities or credential accounts created.",+ );+ });+});++describe("runInTransaction", () => {+ it("rolls back and preserves the original operation error", async () => {+ const originalError = new Error("seed failed");+ const queries: string[] = [];+ const client = {+ async query(text: string) {+ queries.push(text);+ return { rows: [], rowCount: 0 };+ },+ };++ await expect(+ runInTransaction(client, async () => {+ throw originalError;+ }),+ ).rejects.toBe(originalError);+ expect(queries).toEqual(["BEGIN", "ROLLBACK"]);+ });++ it("reports rollback failure but still preserves the operation error", async () => {+ const originalError = new Error("seed failed");+ const reportError = vi.fn();+ const client = {+ async query(text: string) {+ if (text === "ROLLBACK") throw new Error("connection lost");+ return { rows: [], rowCount: 0 };+ },+ };++ await expect(+ runInTransaction(+ client,+ async () => {+ throw originalError;+ },+ reportError,+ ),+ ).rejects.toBe(originalError);+ expect(reportError).toHaveBeenCalledWith(+ "Preview account seeder rollback failed: connection lost",+ );+ });+});diff --git a/autogpt_platform/frontend/scripts/__tests__/seed-preview-accounts.test.ts b/autogpt_platform/frontend/scripts/__tests__/seed-preview-accounts.test.tsnew file mode 100644index 0000000000..dd7b2fc6ce--- /dev/null+++ b/autogpt_platform/frontend/scripts/__tests__/seed-preview-accounts.test.ts@@ -0,0 +1,233 @@+import { createHash } from "node:crypto";+import { describe, expect, it, vi } from "vitest";+import {+ PREVIEW_ACCOUNTS,+ type QueryExecutor,+ assertSafeSchemaName,+ closePool,+ deterministicUserID,+ seedRoster,+} from "../seed-preview-accounts.helpers";++describe("preview account roster", () => {+ it("seeds the five standard accounts on the previews subdomain", () => {+ expect(PREVIEW_ACCOUNTS).toHaveLength(5);+ for (const account of PREVIEW_ACCOUNTS) {+ expect(account.email.endsWith("@previews.agpt.co")).toBe(true);+ }+ });++ it("uses addresses the login page's @agpt.co SSO block does not match", () => {+ // useLoginPage.ts gates on email.includes("@agpt.co"); the roster relies+ // on the subdomain not containing that substring.+ for (const account of PREVIEW_ACCOUNTS) {+ expect(account.email.includes("@agpt.co")).toBe(false);+ }+ });++ it("grants admin only to preview-admin", () => {+ const admins = PREVIEW_ACCOUNTS.filter((a) => a.role === "admin");+ expect(admins.map((a) => a.email)).toEqual([+ "[email protected]",+ ]);+ });+});++describe("deterministicUserID", () => {+ it("matches an independently computed sha256 truncation and the pinned literal", () => {+ const email = "[email protected]";+ const hex = createHash("sha256").update(email).digest("hex").slice(0, 32);+ const independent = [+ hex.slice(0, 8),+ hex.slice(8, 12),+ hex.slice(12, 16),+ hex.slice(16, 20),+ hex.slice(20, 32),+ ].join("-");+ expect(deterministicUserID(email)).toBe(independent);+ // Pinned literal so an accidental derivation change (which would orphan+ // IDs the seeder previously inserted) fails loudly.+ expect(deterministicUserID(email)).toBe(+ "5702fe7e-71d4-12ed-0728-436c56f6e8d1",+ );+ });++ it("derives distinct, stable, uuid-shaped IDs across the whole roster", () => {+ const userIDs = PREVIEW_ACCOUNTS.map((a) => deterministicUserID(a.email));+ expect(new Set(userIDs).size).toBe(PREVIEW_ACCOUNTS.length);+ for (const [i, account] of PREVIEW_ACCOUNTS.entries()) {+ expect(userIDs[i]).toBe(deterministicUserID(account.email));+ expect(userIDs[i]).toMatch(+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,+ );+ }+ });+});++describe("assertSafeSchemaName", () => {+ it("accepts plain lowercase identifiers", () => {+ expect(assertSafeSchemaName("platform")).toBe("platform");+ expect(assertSafeSchemaName("my_schema2")).toBe("my_schema2");+ });++ it("rejects anything that could break out of an identifier position", () => {+ for (const bad of ['platform"; DROP TABLE x; --', "Platform", "1abc", ""]) {+ expect(() => assertSafeSchemaName(bad)).toThrow(/Unsafe schema name/);+ }+ });+});++describe("closePool", () => {+ it("preserves the seed result when pool shutdown fails", async () => {+ const reportError = vi.fn();++ await expect(+ closePool(+ {+ async end() {+ throw new Error("shutdown failed");+ },+ },+ reportError,+ ),+ ).resolves.toBeUndefined();+ expect(reportError).toHaveBeenCalledWith(+ "Preview account seeder cleanup failed: shutdown failed",+ );+ });+});++const TABLES = {+ identityTable: '"platform"."UserAuthIdentity"',+ accountTable: '"platform"."UserAuthAccount"',+ passwordHash: "$2a$10$fakehashfakehashfakehashfa",+};++interface Call {+ text: string;+ params: unknown[];+}++/**+ * Fake pg client mirrors seedRoster's stable operation and table tokens.+ * `existingByEmail` maps a roster email to the id the SELECT-by-email returns+ * (simulating rows that pre-exist or were inserted); emails absent from the+ * map behave as freshly inserted (SELECT returns the deterministic id, INSERT+ * reports 1 row).+ */+function fakeClient(behavior: {+ existingByEmail?: Record<string, string | null>;+ existingCredentials?: Set<string>;+}): { client: QueryExecutor; calls: Call[] } {+ const calls: Call[] = [];+ const client: QueryExecutor = {+ async query(text: string, params: unknown[] = []) {+ calls.push({ text, params });+ if (text.includes("INSERT INTO") && text.includes("UserAuthIdentity")) {+ const email = params[2] as string;+ const preexisting = behavior.existingByEmail?.[email] !== undefined;+ return { rows: [], rowCount: preexisting ? 0 : 1 };+ }+ if (+ text.includes("SELECT id FROM") &&+ text.includes("UserAuthIdentity")+ ) {+ const email = params[0] as string;+ if (behavior.existingByEmail?.[email] !== undefined) {+ const id = behavior.existingByEmail[email];+ return { rows: id === null ? [] : [{ id }], rowCount: id ? 1 : 0 };+ }+ return { rows: [{ id: deterministicUserID(email) }], rowCount: 1 };+ }+ if (text.includes("UPDATE") && text.includes("UserAuthIdentity")) {+ return { rows: [], rowCount: 0 };+ }+ if (text.includes("INSERT INTO") && text.includes("UserAuthAccount")) {+ const userID = params[0] as string;+ const has = behavior.existingCredentials?.has(userID) ?? false;+ return { rows: [], rowCount: has ? 0 : 1 };+ }+ throw new Error(`Unscripted statement: ${text.slice(0, 60)}`);+ },+ };+ return { client, calls };+}++describe("seedRoster", () => {+ it("creates all five identities and credentials on a fresh database", async () => {+ const { client, calls } = fakeClient({});+ const result = await seedRoster(client, TABLES);+ expect(result).toEqual({ createdIdentities: 5, createdAccounts: 5 });+ expect(calls.filter((call) => call.text.includes("UPDATE"))).toHaveLength(+ 0,+ );+ });++ it("is idempotent: a second run creates nothing and never rewrites a credential", async () => {+ const existingByEmail = Object.fromEntries(+ PREVIEW_ACCOUNTS.map((a) => [a.email, deterministicUserID(a.email)]),+ );+ const existingCredentials = new Set(Object.values(existingByEmail));+ const { client, calls } = fakeClient({+ existingByEmail,+ existingCredentials,+ });++ const result = await seedRoster(client, TABLES);++ expect(result).toEqual({ createdIdentities: 0, createdAccounts: 0 });+ // The credential statement stays a guarded INSERT — nothing ever issues+ // an UPDATE against the account table, so passwords cannot be rewritten.+ const accountWrites = calls.filter((c) =>+ c.text.includes("UserAuthAccount"),+ );+ for (const write of accountWrites) {+ expect(write.text).toContain("WHERE NOT EXISTS");+ expect(write.text).not.toContain("UPDATE");+ }+ });++ it("attaches the credential to the email-matched id when the identity pre-exists under a different id", async () => {+ const legacyID = "6d08c936-9f91-dadf-0744-a7c3789b322c"; // old md5-derived ID+ const { client, calls } = fakeClient({+ existingByEmail: { "[email protected]": legacyID },+ });++ await seedRoster(client, TABLES);++ const credentialInsert = calls.find(+ (c) =>+ c.text.includes("UserAuthAccount") &&+ (c.params[0] as string) === legacyID,+ );+ expect(credentialInsert).toBeDefined();+ });++ it("converges role and emailVerified on the resolved identity", async () => {+ const legacyID = "6d08c936-9f91-dadf-0744-a7c3789b322c";+ const { client, calls } = fakeClient({+ existingByEmail: { "[email protected]": legacyID },+ });++ await seedRoster(client, TABLES);++ const convergence = calls.find(+ (c) => c.text.includes("UPDATE") && (c.params[0] as string) === legacyID,+ );+ expect(convergence).toBeDefined();+ expect(convergence?.params[1]).toBe("admin");+ });++ it("refuses to attach a credential when the deterministic id is taken by a different user", async () => {+ // Identity insert no-ops (id occupied) AND the roster email resolves to+ // nothing — attaching the shared password to the occupying user would be+ // a credential grant to a stranger.+ const { client } = fakeClient({+ existingByEmail: { "[email protected]": null },+ });++ await expect(seedRoster(client, TABLES)).rejects.toThrow(+ /neither existed nor could be created/,+ );+ });+});diff --git a/autogpt_platform/frontend/scripts/seed-preview-accounts.helpers.ts b/autogpt_platform/frontend/scripts/seed-preview-accounts.helpers.tsnew file mode 100644index 0000000000..6203569cab--- /dev/null+++ b/autogpt_platform/frontend/scripts/seed-preview-accounts.helpers.ts@@ -0,0 +1,180 @@+import { createHash } from "node:crypto";++/**+ * The login accounts every preview environment is seeded with. The+ * "@previews.agpt.co" subdomain dodges the frontend's "@agpt.co" SSO-only+ * login block, and `role` is what the backend's admin gate reads (Better+ * Auth mints it into the JWT role claim).+ */+export const PREVIEW_ACCOUNTS = [+ {+ email: "[email protected]",+ name: "preview-admin",+ role: "admin",+ },+ {+ email: "[email protected]",+ name: "preview-existing",+ role: "user",+ },+ {+ email: "[email protected]",+ name: "preview-clean",+ role: "user",+ },+ { email: "[email protected]", name: "preview-pro", role: "user" },+ {+ email: "[email protected]",+ name: "preview-enterprise",+ role: "user",+ },+] as const;++/**+ * Deterministic user id for FRESH inserts: uuid-shaped truncation of+ * SHA-256(email). These are stable login handles only; product entitlements+ * are outside this auth seeder. Legacy branch databases may carry identities+ * whose IDs were derived with Postgres md5(email)::uuid. Re-seeding remains+ * safe because identities are matched by email before any ID is derived, so+ * the derivation only has to be stable, not backward-identical.+ */+export function deterministicUserID(email: string): string {+ // SHA-256 provides a stable mapping from public roster emails to IDs; this+ // is not a security digest, so secrecy and password-hashing properties are+ // irrelevant here.+ const hex = createHash("sha256").update(email).digest("hex").slice(0, 32);+ return [+ hex.slice(0, 8),+ hex.slice(8, 12),+ hex.slice(12, 16),+ hex.slice(16, 20),+ hex.slice(20, 32),+ ].join("-");+}++/**+ * Schema names come from the AUTH_DB_SCHEMA env var and are interpolated as+ * SQL identifiers, so refuse anything that isn't a plain lowercase+ * identifier rather than attempting to escape it.+ */+export function assertSafeSchemaName(schema: string): string {+ if (!/^[a-z_][a-z0-9_]*$/.test(schema)) {+ throw new Error(`Unsafe schema name: ${JSON.stringify(schema)}`);+ }+ return schema;+}++interface PoolCloser {+ end(): Promise<void>;+}++/** Closes the pool without allowing cleanup to replace the seed outcome. */+export async function closePool(+ pool: PoolCloser,+ reportError: (message: string) => void = console.error,+) {+ try {+ await pool.end();+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ reportError(`Preview account seeder cleanup failed: ${message}`);+ }+}++interface QueryResultLike {+ rows: { id?: string }[];+ rowCount: number | null;+}++/** The subset of a pg client the seeder needs — injectable for tests. */+export interface QueryExecutor {+ query(text: string, params?: unknown[]): Promise<QueryResultLike>;+}++/**+ * Seeds the roster into the given (already-open, ideally transactional)+ * client. Extracted from the CLI entry so the orchestration — idempotency,+ * email-match attachment, id-collision refusal, role convergence — is unit+ * testable without a database.+ */+export async function seedRoster(+ client: QueryExecutor,+ opts: { identityTable: string; accountTable: string; passwordHash: string },+) {+ const { identityTable, accountTable, passwordHash } = opts;+ let createdIdentities = 0;+ let createdAccounts = 0;++ for (const account of PREVIEW_ACCOUNTS) {+ // Bare ON CONFLICT DO NOTHING arbitrates on ANY constraint, so both+ // "id already taken" and "email already registered" (including a+ // concurrent seeder racing this one) no-op instead of aborting the+ // transaction.+ const insertedIdentity = await client.query(+ `INSERT INTO ${identityTable}+ (id, name, email, "emailVerified", role, "createdAt", "updatedAt")+ VALUES ($1, $2, $3, true, $4, now(), now())+ ON CONFLICT DO NOTHING`,+ [+ deterministicUserID(account.email),+ account.name,+ account.email,+ account.role,+ ],+ );+ createdIdentities += insertedIdentity.rowCount ?? 0;++ // Resolve the id by email AFTER the insert: this is the identity the+ // credential must attach to whether the row pre-existed, was just+ // created, or was created by a concurrent run. If it's still absent,+ // the deterministic id belongs to some other user and the insert+ // no-opped — attaching a credential to that id would hand the preview+ // password to an unrelated account, so fail loudly instead.+ const identity = await client.query(+ `SELECT id FROM ${identityTable} WHERE email = $1`,+ [account.email],+ );+ const userID = identity.rows[0]?.id;+ if (!userID) {+ throw new Error(+ `Identity for ${account.email} neither existed nor could be ` ++ "created (its deterministic id is taken by a different user)",+ );+ }++ // The roster is the source of truth: deliberately converge pre-existing+ // rows even if a long-lived preview has drifted. An identity that+ // predates this seeder (older seed generations, or a DB cloned from a+ // template) may carry the wrong role or an unverified email, and+ // preview-admin's role='admin' is the property the roster exists to+ // guarantee. Passwords are deliberately NOT converged (see the entry+ // script's docstring).+ if (insertedIdentity.rowCount !== 1) {+ await client.query(+ `UPDATE ${identityTable}+ SET role = $2, "emailVerified" = true, "updatedAt" = now()+ WHERE id = $1+ AND (role IS DISTINCT FROM $2 OR "emailVerified" IS DISTINCT FROM true)`,+ [userID, account.role],+ );+ }++ // The guarded insert keeps sequential retries idempotent. Preview CD runs+ // one seeder per branch DB; cross-process safety would require a partial+ // credential-only unique index because OAuth allows multiple accounts for+ // the same user/provider. Existing credentials are never overwritten.+ const insertedCredential = await client.query(+ `INSERT INTO ${accountTable}+ (id, "accountId", "providerId", "userId", password, "createdAt", "updatedAt")+ SELECT gen_random_uuid()::text, $1, 'credential', $1, $2, now(), now()+ WHERE NOT EXISTS (+ SELECT 1 FROM ${accountTable}+ WHERE "userId" = $1 AND "providerId" = 'credential'+ )`,+ [userID, passwordHash],+ );+ createdAccounts += insertedCredential.rowCount ?? 0;+ }++ return { createdIdentities, createdAccounts };+}diff --git a/autogpt_platform/frontend/scripts/seed-preview-accounts.orchestration.ts b/autogpt_platform/frontend/scripts/seed-preview-accounts.orchestration.tsnew file mode 100644index 0000000000..92e9053c4c--- /dev/null+++ b/autogpt_platform/frontend/scripts/seed-preview-accounts.orchestration.ts@@ -0,0 +1,179 @@+import { AUTH_PASSWORD_MIN_LENGTH } from "../src/lib/auth/password-policy";+import {+ type QueryExecutor,+ seedRoster as seedRosterDefault,+} from "./seed-preview-accounts.helpers";++export const SEEDED_EXIT_CODE = 0;+export const FAILURE_EXIT_CODE = 1;+export const NO_BETTER_AUTH_EXIT_CODE = 3;++interface TableProbe {+ query(+ text: string,+ params?: unknown[],+ ): Promise<{ rows: { reg?: string | null }[] }>;+}++interface SeedClient extends QueryExecutor {+ release(): void;+}++interface SeedPool extends TableProbe {+ connect(): Promise<SeedClient>;+}++interface SeedOptions {+ schema: string;+ identityTable: string;+ accountTable: string;+ password: string;+}++interface SeedDependencies {+ hashPassword(password: string): Promise<string>;+ seedRoster?: typeof seedRosterDefault;+ reportLog?: (message: string) => void;+ reportError?: (message: string) => void;+}++export function resolvePreviewConnectionString(+ directURL: string | undefined,+ databaseURL: string | undefined,+ reportWarning: (message: string) => void = console.warn,+) {+ if (directURL) return directURL;+ if (!databaseURL) {+ throw new Error("DIRECT_URL or DATABASE_URL must be set");+ }+ reportWarning(+ "DIRECT_URL is unset; using DATABASE_URL. Ensure the endpoint supports " ++ "an explicit transaction on one checked-out client.",+ );+ return databaseURL;+}++export function validatePreviewPassword(password: string | undefined) {+ if (!password) {+ throw new Error("PREVIEW_ACCOUNTS_PASSWORD must be set");+ }+ if (password.length < AUTH_PASSWORD_MIN_LENGTH) {+ throw new Error(+ `PREVIEW_ACCOUNTS_PASSWORD must be at least ${AUTH_PASSWORD_MIN_LENGTH} characters`,+ );+ }+ return password;+}++export async function probeBetterAuthTables(+ pool: TableProbe,+ identityTable: string,+ accountTable: string,+ schema: string,+) {+ async function tableExists(qualified: string) {+ const { rows } = await pool.query("SELECT to_regclass($1)::text AS reg", [+ qualified,+ ]);+ return Boolean(rows[0]?.reg);+ }++ const hasIdentity = await tableExists(identityTable);+ const hasAccount = await tableExists(accountTable);+ if (!hasIdentity && !hasAccount) return "absent" as const;+ if (!hasIdentity || !hasAccount) {+ throw new Error(+ `Schema "${schema}" has only one of UserAuthIdentity/UserAuthAccount ` ++ "— half-applied migration; refusing to seed or fall back.",+ );+ }+ return "present" as const;+}++export async function rollbackTransaction(+ client: QueryExecutor,+ reportError: (message: string) => void = console.error,+) {+ try {+ await client.query("ROLLBACK");+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ reportError(`Preview account seeder rollback failed: ${message}`);+ }+}++export async function runInTransaction<T>(+ client: QueryExecutor,+ operation: () => Promise<T>,+ reportError: (message: string) => void = console.error,+) {+ await client.query("BEGIN");+ try {+ const result = await operation();+ await client.query("COMMIT");+ return result;+ } catch (error) {+ await rollbackTransaction(client, reportError);+ throw error;+ }+}++export async function seedPreviewAccounts(+ pool: SeedPool,+ options: SeedOptions,+ dependencies: SeedDependencies,+) {+ const { schema, identityTable, accountTable, password } = options;+ const reportLog = dependencies.reportLog ?? console.log;+ const reportError = dependencies.reportError ?? console.error;+ const tableState = await probeBetterAuthTables(+ pool,+ identityTable,+ accountTable,+ schema,+ );+ if (tableState === "absent") {+ reportLog(+ `Better Auth tables not present in schema "${schema}" — ` ++ "pre-migration database, nothing to seed here.",+ );+ return NO_BETTER_AUTH_EXIT_CODE;+ }++ const passwordHash = await dependencies.hashPassword(password);+ const client = await pool.connect();+ try {+ const seed = dependencies.seedRoster ?? seedRosterDefault;+ const { createdIdentities, createdAccounts } = await runInTransaction(+ client,+ () => seed(client, { identityTable, accountTable, passwordHash }),+ reportError,+ );+ if (createdIdentities === 0 && createdAccounts === 0) {+ reportLog(+ "Preview accounts are now up to date; no new identities or credential accounts created.",+ );+ } else {+ reportLog(+ `Seeded preview accounts: ${createdIdentities} identities and ` ++ `${createdAccounts} credential accounts created.`,+ );+ }+ return SEEDED_EXIT_CODE;+ } finally {+ client.release();+ }+}++export function reportPreviewSeedFailure(+ error: unknown,+ reportError: (message: string) => void = console.error,+) {+ const code =+ error instanceof Error && "code" in error+ ? ` (code ${(error as { code?: string }).code})`+ : "";+ const message = error instanceof Error ? error.message : String(error);+ reportError(`Preview account seeding failed: ${message}${code}`);+ return FAILURE_EXIT_CODE;+}diff --git a/autogpt_platform/frontend/scripts/seed-preview-accounts.ts b/autogpt_platform/frontend/scripts/seed-preview-accounts.tsnew file mode 100644index 0000000000..b7165d6025--- /dev/null+++ b/autogpt_platform/frontend/scripts/seed-preview-accounts.ts@@ -0,0 +1,84 @@+/**+ * Seeds the shared preview-environment login accounts into the Better Auth+ * tables of a (branch) database.+ *+ * This lives in the platform repo — next to the schema — because the seed+ * must name real tables (`UserAuthIdentity` / `UserAuthAccount`) and hash+ * passwords exactly the way the frontend verifies them (bcrypt cost 10, see+ * src/lib/auth/auth.ts). A seed maintained anywhere else silently breaks the+ * moment either of those changes; the preview pipeline should call this+ * script instead of carrying its own SQL.+ *+ * Usage (the preview CD pipeline runs this after `prisma migrate deploy`):+ * DIRECT_URL=postgresql://... PREVIEW_ACCOUNTS_PASSWORD=... \+ * npx --yes tsx scripts/seed-preview-accounts.ts+ * (tsx is not a package dependency; npx fetches it, matching the other+ * scripts in this folder. Prefer DIRECT_URL; a DATABASE_URL fallback must+ * support an explicit transaction on one checked-out client.)+ *+ * Behavior:+ * - Idempotent: existing identities are kept (matched by email; role and+ * emailVerified are converged to the roster), and an existing credential+ * account is never overwritten — rotating PREVIEW_ACCOUNTS_PASSWORD only+ * affects freshly seeded databases.+ * - Exit codes are the cross-repo contract with the preview CD pipeline —+ * see the named constants in seed-preview-accounts.orchestration.ts.+ */+import { hash } from "bcryptjs";+import { Pool } from "pg";+import { AUTH_PASSWORD_BCRYPT_COST } from "../src/lib/auth/password-policy";+import {+ assertSafeSchemaName,+ closePool,+} from "./seed-preview-accounts.helpers";+import {+ reportPreviewSeedFailure,+ resolvePreviewConnectionString,+ seedPreviewAccounts,+ validatePreviewPassword,+} from "./seed-preview-accounts.orchestration";++async function main() {+ const connectionString = resolvePreviewConnectionString(+ process.env.DIRECT_URL,+ process.env.DATABASE_URL,+ );+ const password = validatePreviewPassword(+ process.env.PREVIEW_ACCOUNTS_PASSWORD,+ );+ const schema = assertSafeSchemaName(process.env.AUTH_DB_SCHEMA || "platform");+ const identityTable = `"${schema}"."UserAuthIdentity"`;+ const accountTable = `"${schema}"."UserAuthAccount"`;++ // Prisma-style URLs carry ?schema=/&pgbouncer= params that node-postgres+ // does not understand but tolerates; strip nothing, qualify tables instead.+ // Bounded timeouts keep the exit-code contract honest: a database that+ // accepts TCP but never answers must become exit 1, not a hung CI step.+ const pool = new Pool({+ connectionString,+ max: 1,+ connectionTimeoutMillis: 15_000,+ query_timeout: 30_000,+ });++ try {+ process.exitCode = await seedPreviewAccounts(+ pool,+ {+ schema,+ identityTable,+ accountTable,+ password,+ },+ {+ hashPassword: (value) => hash(value, AUTH_PASSWORD_BCRYPT_COST),+ },+ );+ } finally {+ await closePool(pool);+ }+}++main().catch((error: unknown) => {+ process.exitCode = reportPreviewSeedFailure(error);+});diff --git a/autogpt_platform/frontend/src/lib/auth/auth.ts b/autogpt_platform/frontend/src/lib/auth/auth.tsindex 5823d14bb4..51a410bc8b 100644--- a/autogpt_platform/frontend/src/lib/auth/auth.ts+++ b/autogpt_platform/frontend/src/lib/auth/auth.ts@@ -6,6 +6,10 @@ import { compare, hash } from "bcryptjs";import { Pool } from "pg";import { mirrorVerifiedEmailToPlatformUser } from "./email-mirror";import { sendAuthEmail } from "./email";+import {+ AUTH_PASSWORD_BCRYPT_COST,+ AUTH_PASSWORD_MIN_LENGTH,+} from "./password-policy";import { JWKS_ALG } from "./service-token";import { isSignupAllowed, readSignupGateConfig } from "./signup-gate";import { supabaseBridge } from "./supabase-bridge";@@ -48,7 +52,7 @@ const authDbPool =// DATABASE_URL explicitly.connectionString:process.env.DATABASE_URL ||- "postgresql://postgres:your-super-secret-and-long-postgres-password@localhost:5432/postgres",+ "postgresql://postgres:your-super-secret-and-long-postgres-password@localhost:5432/postgres", // pragma: allowlist secret// Better Auth shares the platform Postgres; its tables live in the same// schema as the Prisma-managed ones (created by the backend migrations).options: `-c search_path=${process.env.AUTH_DB_SCHEMA || "platform"}`,@@ -124,7 +128,7 @@ export const auth = betterAuth({// otherwise slip a 6-char password through. minPasswordLength is checked// when a password is *set* (sign-up / reset / change), never on sign-in,// so this does NOT lock out migrated users whose old password is shorter.- minPasswordLength: 12,+ minPasswordLength: AUTH_PASSWORD_MIN_LENGTH,// A password reset kicks every active session, matching the previous// flow's signOut({ scope: "global" }) — the standard defense when a// user resets their password to evict a stolen session.@@ -134,7 +138,7 @@ export const auth = betterAuth({password: {// bcrypt instead of Better Auth's default scrypt so password hashes// migrated from Supabase GoTrue keep verifying without a reset.- hash: (password) => hash(password, 10),+ hash: (password) => hash(password, AUTH_PASSWORD_BCRYPT_COST),verify: ({ hash: hashValue, password }) => compare(password, hashValue),},sendResetPassword: async ({ user, url }) => {diff --git a/autogpt_platform/frontend/src/lib/auth/password-policy.ts b/autogpt_platform/frontend/src/lib/auth/password-policy.tsnew file mode 100644index 0000000000..91b962ae44--- /dev/null+++ b/autogpt_platform/frontend/src/lib/auth/password-policy.ts@@ -0,0 +1,2 @@+export const AUTH_PASSWORD_MIN_LENGTH = 12;+export const AUTH_PASSWORD_BCRYPT_COST = 10;diff --git a/autogpt_platform/frontend/src/types/auth.ts b/autogpt_platform/frontend/src/types/auth.tsindex 545ac976da..f2c9b7ed6a 100644--- a/autogpt_platform/frontend/src/types/auth.ts+++ b/autogpt_platform/frontend/src/types/auth.ts@@ -1,4 +1,7 @@import { z } from "zod";+import { AUTH_PASSWORD_MIN_LENGTH } from "@/lib/auth/password-policy";++const MIN_LENGTH_MESSAGE = `Password must contain at least ${AUTH_PASSWORD_MIN_LENGTH} characters`;export type LoginProvider = "google" | "github" | "discord";@@ -23,11 +26,11 @@ export const signupFormSchema = z.trim(),password: z.string()- .min(12, "Password must contain at least 12 characters")+ .min(AUTH_PASSWORD_MIN_LENGTH, MIN_LENGTH_MESSAGE).max(64, "Password must contain at most 64 characters"),confirmPassword: z.string()- .min(12, "Password must contain at least 12 characters")+ .min(AUTH_PASSWORD_MIN_LENGTH, MIN_LENGTH_MESSAGE).max(64, "Password must contain at most 64 characters"),agreeToTerms: z.boolean().refine((value) => value === true, {message: "You must agree to the Terms of Use and Privacy Policy",@@ -50,11 +53,11 @@ export const changePasswordFormSchema = z.object({password: z.string()- .min(12, "Password must contain at least 12 characters")+ .min(AUTH_PASSWORD_MIN_LENGTH, MIN_LENGTH_MESSAGE).max(64, "Password must contain at most 64 characters"),confirmPassword: z.string()- .min(12, "Password must contain at least 12 characters")+ .min(AUTH_PASSWORD_MIN_LENGTH, MIN_LENGTH_MESSAGE).max(64, "Password must contain at most 64 characters"),}).refine((data) => data.password === data.confirmPassword, {diff --git a/autogpt_platform/frontend/vitest.config.mts b/autogpt_platform/frontend/vitest.config.mtsindex 4e8c035673..2dbb925374 100644--- a/autogpt_platform/frontend/vitest.config.mts+++ b/autogpt_platform/frontend/vitest.config.mts@@ -6,7 +6,7 @@ export default defineConfig({plugins: [tsconfigPaths(), react()],test: {environment: "happy-dom",- include: ["src/**/*.test.tsx", "src/**/*.test.ts"],+ include: ["src/**/*.test.tsx", "src/**/*.test.ts", "scripts/**/*.test.ts"],setupFiles: ["./src/tests/integrations/vitest.setup.tsx"],coverage: {provider: "v8",