import Surreal from 'surrealdb'; /** * Connects to the SurrealDB instance with root credentials. * * IMPORTANT: This connects as root, so queries MUST filter by user_did * to enforce data isolation. The caller is responsible for providing * the correct user_did from the verified JWT. * * @returns The authenticated SurrealDB instance */ export async function connectToDB(): Promise { const SURREALDB_URL = process.env.SURREALDB_URL; const SURREALDB_NAMESPACE = process.env.SURREALDB_NS; const SURREALDB_DATABASE = process.env.SURREALDB_DB; const SURREALDB_USER = process.env.SURREALDB_USER; const SURREALDB_PASS = process.env.SURREALDB_PASS; if (!SURREALDB_URL || !SURREALDB_NAMESPACE || !SURREALDB_DATABASE) { throw new Error('SurrealDB configuration is missing'); } if (!SURREALDB_USER || !SURREALDB_PASS) { throw new Error('SurrealDB credentials are missing'); } // Create a new instance for each request to avoid connection state issues const db = new Surreal(); // Connect to SurrealDB await db.connect(SURREALDB_URL); // Sign in with root credentials // NOTE: We use root access because our JWT-based auth is app-level, // not SurrealDB-level. Queries must filter by user_did from the verified JWT. await db.signin({ username: SURREALDB_USER, password: SURREALDB_PASS, }); // Use the correct namespace and database await db.use({ namespace: SURREALDB_NAMESPACE, database: SURREALDB_DATABASE, }); return db; }