remove proxy pattern in db and auth (#513)
Some checks failed
Release Workflow / determine-release-type (push) Has been cancelled
Release Workflow / checks (push) Has been cancelled
Release Workflow / e2e-tests (push) Has been cancelled
Release Workflow / build-images (push) Has been cancelled
Release Workflow / publish-release (push) Has been cancelled

* refactor: add nitro bootstrap plugin to ensure app is started before first call

* refactor(bootstrap): avoid duplicate event firing

* refactor: extract common setup in initModule function

* refactor: remove proxy pattern for db and auth

Since we migrated away from rr this is not needed anymore as the bundler
correctly split chunks
This commit is contained in:
Nico 2026-02-13 21:18:40 +01:00 committed by GitHub
parent 297e14ebb2
commit a4fbe3c8df
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 169 additions and 229 deletions

View file

@ -1,24 +1,18 @@
import { logger } from "./server/utils/logger"; import { logger } from "./server/utils/logger";
import { shutdown } from "./server/modules/lifecycle/shutdown"; import { shutdown } from "./server/modules/lifecycle/shutdown";
import { runCLI } from "./server/cli"; import { runCLI } from "./server/cli";
import { createStartHandler, defaultStreamHandler, defineHandlerCallback } from "@tanstack/react-start/server"; import {
createStartHandler,
defaultStreamHandler,
defineHandlerCallback,
} from "@tanstack/react-start/server";
import { createServerEntry } from "@tanstack/react-start/server-entry"; import { createServerEntry } from "@tanstack/react-start/server-entry";
import { initAuth } from "~/server/lib/auth";
import { setSchema } from "./server/db/db";
import * as schema from "./server/db/schema";
import { toMessage } from "./server/utils/errors";
const cliRun = await runCLI(Bun.argv); const cliRun = await runCLI(Bun.argv);
if (cliRun) { if (cliRun) {
process.exit(0); process.exit(0);
} }
setSchema(schema);
await initAuth().catch((err) => {
logger.error(`Error initializing auth: ${toMessage(err)}`);
throw err;
});
const customHandler = defineHandlerCallback((ctx) => { const customHandler = defineHandlerCallback((ctx) => {
return defaultStreamHandler(ctx); return defaultStreamHandler(ctx);
}); });

View file

@ -6,53 +6,22 @@ import { migrate } from "drizzle-orm/bun-sqlite/migrator";
import { DATABASE_URL } from "../core/constants"; import { DATABASE_URL } from "../core/constants";
import fs from "node:fs"; import fs from "node:fs";
import { config } from "../core/config"; import { config } from "../core/config";
import type * as schemaTypes from "./schema"; import * as schema from "./schema";
/** fs.mkdirSync(path.dirname(DATABASE_URL), { recursive: true });
* TODO: try to remove this if moving away from react-router.
* The rr vite plugin doesn't let us customize the chunk names
* to isolate the db initialization code from the rest of the server code.
*/
let _sqlite: Database | undefined;
let _db: ReturnType<typeof initDb> | undefined;
let _schema: typeof schemaTypes | undefined;
/** if (
* Sets the database schema. This must be called before any database operations. fs.existsSync(path.join(path.dirname(DATABASE_URL), "ironmount.db")) &&
*/ !fs.existsSync(DATABASE_URL)
export const setSchema = (schema: typeof schemaTypes) => { ) {
_schema = schema; fs.renameSync(
}; path.join(path.dirname(DATABASE_URL), "ironmount.db"),
DATABASE_URL,
);
}
const initDb = () => { const sqlite = new Database(DATABASE_URL);
if (!_schema) { export const db = drizzle({ client: sqlite, relations, schema });
throw new Error("Database schema not set. Call setSchema() before accessing the database.");
}
fs.mkdirSync(path.dirname(DATABASE_URL), { recursive: true });
if (fs.existsSync(path.join(path.dirname(DATABASE_URL), "ironmount.db")) && !fs.existsSync(DATABASE_URL)) {
fs.renameSync(path.join(path.dirname(DATABASE_URL), "ironmount.db"), DATABASE_URL);
}
_sqlite = new Database(DATABASE_URL);
return drizzle({ client: _sqlite, relations, schema: _schema });
};
/**
* Database instance (Proxy for lazy initialization)
*/
export const db = new Proxy(
{},
{
get(_, prop, receiver) {
if (!_db) {
_db = initDb();
}
return Reflect.get(_db, prop, receiver);
},
},
) as ReturnType<typeof initDb>;
export const runDbMigrations = () => { export const runDbMigrations = () => {
let migrationsFolder: string; let migrationsFolder: string;
@ -67,9 +36,5 @@ export const runDbMigrations = () => {
migrate(db, { migrationsFolder }); migrate(db, { migrationsFolder });
if (!_sqlite) { sqlite.run("PRAGMA foreign_keys = ON;");
throw new Error("Database not initialized");
}
_sqlite.run("PRAGMA foreign_keys = ON;");
}; };

View file

@ -6,177 +6,172 @@ import {
type MiddlewareOptions, type MiddlewareOptions,
} from "better-auth"; } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle"; import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { admin, createAuthMiddleware, twoFactor, username, organization } from "better-auth/plugins"; import {
admin,
createAuthMiddleware,
twoFactor,
username,
organization,
} from "better-auth/plugins";
import { UnauthorizedError } from "http-errors-enhanced"; import { UnauthorizedError } from "http-errors-enhanced";
import { convertLegacyUserOnFirstLogin } from "./auth-middlewares/convert-legacy-user"; import { convertLegacyUserOnFirstLogin } from "./auth-middlewares/convert-legacy-user";
import { eq } from "drizzle-orm"; import { eq } from "drizzle-orm";
import { config } from "../core/config"; import { config } from "../core/config";
import { db } from "../db/db"; import { db } from "../db/db";
import { cryptoUtils } from "../utils/crypto"; import { cryptoUtils } from "../utils/crypto";
import { organization as organizationTable, member, usersTable } from "../db/schema"; import {
organization as organizationTable,
member,
usersTable,
} from "../db/schema";
import { ensureOnlyOneUser } from "./auth-middlewares/only-one-user"; import { ensureOnlyOneUser } from "./auth-middlewares/only-one-user";
import { authService } from "../modules/auth/auth.service"; import { authService } from "../modules/auth/auth.service";
import { tanstackStartCookies } from "better-auth/tanstack-start"; import { tanstackStartCookies } from "better-auth/tanstack-start";
export type AuthMiddlewareContext = MiddlewareContext<MiddlewareOptions, AuthContext<BetterAuthOptions>>; export type AuthMiddlewareContext = MiddlewareContext<
MiddlewareOptions,
AuthContext<BetterAuthOptions>
>;
const createBetterAuth = (secret: string) => { export const auth = betterAuth({
return betterAuth({ secret: await cryptoUtils.deriveSecret("better-auth"),
secret, baseURL: config.baseUrl,
baseURL: config.baseUrl, trustedOrigins: config.trustedOrigins,
trustedOrigins: config.trustedOrigins, advanced: {
advanced: { cookiePrefix: "zerobyte",
cookiePrefix: "zerobyte", useSecureCookies: config.isSecure,
useSecureCookies: config.isSecure, },
}, onAPIError: {
onAPIError: { throw: true,
throw: true, },
}, hooks: {
hooks: { before: createAuthMiddleware(async (ctx) => {
before: createAuthMiddleware(async (ctx) => { await ensureOnlyOneUser(ctx);
await ensureOnlyOneUser(ctx); await convertLegacyUserOnFirstLogin(ctx);
await convertLegacyUserOnFirstLogin(ctx);
}),
},
database: drizzleAdapter(db, {
provider: "sqlite",
}), }),
databaseHooks: { },
user: { database: drizzleAdapter(db, {
delete: { provider: "sqlite",
before: async (user) => { }),
await authService.cleanupUserOrganizations(user.id); databaseHooks: {
},
},
create: {
before: async (user) => {
const anyUser = await db.query.usersTable.findFirst();
const isFirstUser = !anyUser;
if (isFirstUser) {
user.role = "admin";
}
return { data: user };
},
after: async (user) => {
const slug = user.email.split("@")[0] + "-" + Math.random().toString(36).slice(-4);
const resticPassword = cryptoUtils.generateResticPassword();
const metadata = {
resticPassword: await cryptoUtils.sealSecret(resticPassword),
};
try {
await db.transaction(async (tx) => {
const orgId = Bun.randomUUIDv7();
await tx.insert(organizationTable).values({
name: `${user.name}'s Workspace`,
slug: slug,
id: orgId,
createdAt: new Date(),
metadata,
});
await tx.insert(member).values({
id: Bun.randomUUIDv7(),
userId: user.id,
role: "owner",
organizationId: orgId,
createdAt: new Date(),
});
});
} catch {
await db.delete(usersTable).where(eq(usersTable.id, user.id));
throw new Error(`Failed to create organization for user ${user.id}`);
}
},
},
},
session: {
create: {
before: async (session) => {
const orgMembership = await db.query.member.findFirst({
where: { userId: session.userId },
});
if (!orgMembership) {
throw new UnauthorizedError("User does not belong to any organization");
}
return {
data: {
...session,
activeOrganizationId: orgMembership?.organizationId,
},
};
},
},
},
},
emailAndPassword: {
enabled: true,
},
user: { user: {
modelName: "usersTable", delete: {
additionalFields: { before: async (user) => {
username: { await authService.cleanupUserOrganizations(user.id);
type: "string",
returned: true,
required: true,
}, },
hasDownloadedResticPassword: { },
type: "boolean", create: {
returned: true, before: async (user) => {
const anyUser = await db.query.usersTable.findFirst();
const isFirstUser = !anyUser;
if (isFirstUser) {
user.role = "admin";
}
return { data: user };
},
after: async (user) => {
const slug =
user.email.split("@")[0] +
"-" +
Math.random().toString(36).slice(-4);
const resticPassword = cryptoUtils.generateResticPassword();
const metadata = {
resticPassword:
await cryptoUtils.sealSecret(resticPassword),
};
try {
await db.transaction(async (tx) => {
const orgId = Bun.randomUUIDv7();
await tx.insert(organizationTable).values({
name: `${user.name}'s Workspace`,
slug: slug,
id: orgId,
createdAt: new Date(),
metadata,
});
await tx.insert(member).values({
id: Bun.randomUUIDv7(),
userId: user.id,
role: "owner",
organizationId: orgId,
createdAt: new Date(),
});
});
} catch {
await db
.delete(usersTable)
.where(eq(usersTable.id, user.id));
throw new Error(
`Failed to create organization for user ${user.id}`,
);
}
}, },
}, },
}, },
session: { session: {
modelName: "sessionsTable", create: {
}, before: async (session) => {
plugins: [ const orgMembership = await db.query.member.findFirst({
username(), where: { userId: session.userId },
admin({ });
defaultRole: "user",
}), if (!orgMembership) {
organization({ throw new UnauthorizedError(
allowUserToCreateOrganization: false, "User does not belong to any organization",
}), );
twoFactor({ }
backupCodeOptions: {
storeBackupCodes: "encrypted", return {
amount: 5, data: {
...session,
activeOrganizationId: orgMembership?.organizationId,
},
};
}, },
}), },
tanstackStartCookies(),
],
});
};
type Auth = ReturnType<typeof createBetterAuth>;
let _auth: Auth | null = null;
const createAuth = async (): Promise<Auth> => {
if (_auth) return _auth;
_auth = createBetterAuth(await cryptoUtils.deriveSecret("better-auth"));
return _auth;
};
export const auth = new Proxy(
{},
{
get(_, prop, receiver) {
if (!_auth) {
throw new Error("Auth not initialized. Call initAuth() first.");
}
return Reflect.get(_auth, prop, receiver);
}, },
}, },
) as Auth; emailAndPassword: {
enabled: true,
export const initAuth = createAuth; },
user: {
modelName: "usersTable",
additionalFields: {
username: {
type: "string",
returned: true,
required: true,
},
hasDownloadedResticPassword: {
type: "boolean",
returned: true,
},
},
},
session: {
modelName: "sessionsTable",
},
plugins: [
username(),
admin({
defaultRole: "user",
}),
organization({
allowUserToCreateOrganization: false,
}),
twoFactor({
backupCodeOptions: {
storeBackupCodes: "encrypted",
amount: 5,
},
}),
tanstackStartCookies(),
],
});

View file

@ -1,12 +1,10 @@
import * as schema from "../../db/schema"; import { runDbMigrations } from "../../db/db";
import { runDbMigrations, setSchema } from "../../db/db";
import { runMigrations } from "./migrations"; import { runMigrations } from "./migrations";
import { startup } from "./startup"; import { startup } from "./startup";
let bootstrapPromise: Promise<void> | undefined; let bootstrapPromise: Promise<void> | undefined;
const runBootstrap = async () => { const runBootstrap = async () => {
setSchema(schema);
runDbMigrations(); runDbMigrations();
await runMigrations(); await runMigrations();
await startup(); await startup();

View file

@ -12,8 +12,6 @@ import { repositoriesService } from "../repositories/repositories.service";
import { notificationsService } from "../notifications/notifications.service"; import { notificationsService } from "../notifications/notifications.service";
import { VolumeAutoRemountJob } from "~/server/jobs/auto-remount"; import { VolumeAutoRemountJob } from "~/server/jobs/auto-remount";
import { cache } from "~/server/utils/cache"; import { cache } from "~/server/utils/cache";
import { initAuth } from "~/server/lib/auth";
import { toMessage } from "~/server/utils/errors";
import { withContext } from "~/server/core/request-context"; import { withContext } from "~/server/core/request-context";
const ensureLatestConfigurationSchema = async () => { const ensureLatestConfigurationSchema = async () => {
@ -54,11 +52,6 @@ export const startup = async () => {
await Scheduler.start(); await Scheduler.start();
await Scheduler.clear(); await Scheduler.clear();
await initAuth().catch((err) => {
logger.error(`Error initializing auth: ${toMessage(err)}`);
throw err;
});
await ensureLatestConfigurationSchema(); await ensureLatestConfigurationSchema();
const volumes = await db.query.volumesTable.findMany({ const volumes = await db.query.volumesTable.findMany({

View file

@ -2,11 +2,7 @@ import { beforeAll, mock } from "bun:test";
import { migrate } from "drizzle-orm/bun-sqlite/migrator"; import { migrate } from "drizzle-orm/bun-sqlite/migrator";
import path from "node:path"; import path from "node:path";
import { cwd } from "node:process"; import { cwd } from "node:process";
import * as schema from "~/server/db/schema"; import { db } from "~/server/db/db";
import { db, setSchema } from "~/server/db/db";
import { initAuth } from "~/server/lib/auth";
setSchema(schema);
void mock.module("~/server/utils/logger", () => ({ void mock.module("~/server/utils/logger", () => ({
logger: { logger: {
@ -29,5 +25,4 @@ void mock.module("~/server/utils/crypto", () => ({
beforeAll(async () => { beforeAll(async () => {
const migrationsFolder = path.join(cwd(), "app", "drizzle"); const migrationsFolder = path.join(cwd(), "app", "drizzle");
migrate(db, { migrationsFolder }); migrate(db, { migrationsFolder });
await initAuth();
}); });