{"version":3,"sources":["../src/index.ts","../src/config/index.ts","../src/installer/index.ts"],"sourcesContent":["// @cipherstash/cli\n// Public API exports\n\nexport { defineConfig, loadStashConfig } from './config/index.ts'\nexport type { StashConfig } from './config/index.ts'\nexport {\n  EQLInstaller,\n  loadBundledEqlSql,\n  downloadEqlSql,\n} from './installer/index.ts'\nexport type { PermissionCheckResult } from './installer/index.ts'\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport type { EncryptionClient } from '@cipherstash/stack/encryption'\nimport type { EncryptConfig } from '@cipherstash/stack/schema'\nimport { z } from 'zod'\n\nexport interface StashConfig {\n  /** PostgreSQL connection string */\n  databaseUrl: string\n  /** Path to encryption client file. Defaults to `'./src/encryption/index.ts'`. */\n  client?: string\n}\n\n/** The config shape after Zod validation, with all defaults applied. */\nexport type ResolvedStashConfig = Required<Pick<StashConfig, 'client'>> &\n  Omit<StashConfig, 'client'>\n\n/**\n * Define a stash config with type checking.\n * Use this as the default export in your `stash.config.ts`.\n *\n * @example\n * ```ts\n * import { defineConfig } from '@cipherstash/cli'\n *\n * export default defineConfig({\n *   databaseUrl: process.env.DATABASE_URL!,\n *   client: './src/encryption/index.ts',\n * })\n * ```\n */\nexport function defineConfig(config: StashConfig): StashConfig {\n  return config\n}\n\nconst CONFIG_FILENAME = 'stash.config.ts'\n\nconst DEFAULT_ENCRYPT_CLIENT_PATH = './src/encryption/index.ts'\n\nconst stashConfigSchema = z.object({\n  databaseUrl: z\n    .string({ error: 'databaseUrl is required' })\n    .min(1, 'databaseUrl must not be empty'),\n  client: z.string().default(DEFAULT_ENCRYPT_CLIENT_PATH),\n})\n\n/**\n * Search for `stash.config.ts` starting from `startDir` and walking up\n * parent directories until the filesystem root is reached.\n *\n * Returns the absolute path if found, or `undefined` if not.\n */\nfunction findConfigFile(startDir: string): string | undefined {\n  let dir = path.resolve(startDir)\n\n  while (true) {\n    const candidate = path.join(dir, CONFIG_FILENAME)\n\n    if (fs.existsSync(candidate)) {\n      return candidate\n    }\n\n    const parent = path.dirname(dir)\n\n    // Reached filesystem root\n    if (parent === dir) {\n      return undefined\n    }\n\n    dir = parent\n  }\n}\n\n/**\n * Load and validate the `stash.config.ts` from the user's project.\n *\n * Searches from `process.cwd()` upward. Uses `jiti` to evaluate the\n * TypeScript config file at runtime without a separate compile step.\n *\n * Exits with code 1 if the config file is not found or fails validation.\n */\nexport async function loadStashConfig(): Promise<ResolvedStashConfig> {\n  const configPath = findConfigFile(process.cwd())\n\n  if (!configPath) {\n    console.error(`Error: Could not find ${CONFIG_FILENAME}\n\nCreate a ${CONFIG_FILENAME} file in your project root:\n\n  import { defineConfig } from '@cipherstash/cli'\n\n  export default defineConfig({\n    databaseUrl: process.env.DATABASE_URL!,\n  })\n`)\n    process.exit(1)\n  }\n\n  const { createJiti } = await import('jiti')\n  const jiti = createJiti(configPath)\n\n  let rawConfig: unknown\n  try {\n    // The per-call `{ default: true }` option is the jiti 2.x way to ask\n    // for the default export to be unwrapped. The `interopDefault`\n    // *constructor* option only applies to the deprecated synchronous\n    // `jiti(id)` callable form — `jiti.import()` silently ignores it and\n    // returns the full module namespace (`{ default: { ... } }`). That\n    // wrapper would then fail Zod validation with a misleading\n    // \"databaseUrl: received undefined\" even when the user's config sets\n    // it (#374).\n    rawConfig = await jiti.import(configPath, { default: true })\n  } catch (error) {\n    console.error(`Error: Failed to load ${CONFIG_FILENAME} at ${configPath}\\n`)\n    console.error(error)\n    process.exit(1)\n  }\n\n  const result = stashConfigSchema.safeParse(rawConfig)\n\n  if (!result.success) {\n    console.error(`Error: Invalid ${CONFIG_FILENAME}\\n`)\n\n    for (const issue of result.error.issues) {\n      console.error(`  - ${issue.path.join('.')}: ${issue.message}`)\n    }\n\n    console.error()\n    process.exit(1)\n  }\n\n  return result.data\n}\n\n/**\n * Load the encryption schema file referenced by the stash config.\n *\n * Resolves the schema path relative to `process.cwd()`, loads the file via\n * `jiti`, collects all exported `EncryptedTable` instances, and builds the\n * encrypt config via `buildEncryptConfig`.\n *\n * Exits with code 1 if the file cannot be loaded or contains no tables.\n */\nexport async function loadEncryptConfig(\n  encryptClientPath: string,\n): Promise<EncryptConfig | undefined> {\n  const resolvedPath = path.resolve(process.cwd(), encryptClientPath)\n\n  if (!fs.existsSync(resolvedPath)) {\n    console.error(\n      `Error: Encrypt client file not found at ${resolvedPath}\\n\\nCheck the \"encryptClient\" path in your ${CONFIG_FILENAME}.`,\n    )\n    process.exit(1)\n  }\n\n  const { createJiti } = await import('jiti')\n  const jiti = createJiti(resolvedPath)\n\n  let moduleExports: Record<string, unknown>\n  try {\n    // No `{ default: true }` here — we want the full module namespace so\n    // `Object.values` can find an EncryptionClient regardless of whether\n    // the user re-exports it as `default` or as a named binding.\n    moduleExports = (await jiti.import(resolvedPath)) as Record<string, unknown>\n  } catch (error) {\n    console.error(\n      `Error: Failed to load encrypt client file at ${resolvedPath}\\n`,\n    )\n    console.error(error)\n    process.exit(1)\n  }\n\n  const encryptClient = Object.values(moduleExports).find(\n    (value): value is EncryptionClient =>\n      !!value &&\n      typeof value === 'object' &&\n      'getEncryptConfig' in value &&\n      typeof (value as { getEncryptConfig?: unknown }).getEncryptConfig ===\n        'function',\n  )\n\n  if (!encryptClient) {\n    console.error(\n      `Error: No EncryptionClient export found in ${encryptClientPath}.`,\n    )\n    process.exit(1)\n  }\n\n  const config = encryptClient.getEncryptConfig()\n  if (!config) {\n    console.error(\n      `Error: Encryption client in ${encryptClientPath} has no initialized encrypt config.`,\n    )\n    process.exit(1)\n  }\n  return config\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { dirname, join, resolve } from 'node:path'\nimport pg from 'pg'\n\nconst EQL_INSTALL_URL =\n  'https://github.com/cipherstash/encrypt-query-language/releases/latest/download/cipherstash-encrypt.sql'\nconst EQL_INSTALL_NO_OPERATOR_FAMILY_URL =\n  'https://github.com/cipherstash/encrypt-query-language/releases/latest/download/cipherstash-encrypt-supabase.sql'\nconst EQL_SCHEMA_NAME = 'eql_v2'\n\n/**\n * SQL block that grants the EQL schema, tables, routines, and sequences to\n * Supabase's built-in roles (`anon`, `authenticated`, `service_role`).\n *\n * Supabase uses dedicated roles that don't own the schema, so explicit grants\n * are required. We expose this as a single multi-statement string so it can be\n * executed in one `client.query()` (Postgres accepts multi-statement strings)\n * AND embedded directly into a Supabase migration file. One source of truth\n * for both the runtime install path and the generated migration file.\n */\nexport const SUPABASE_PERMISSIONS_SQL = `GRANT USAGE ON SCHEMA ${EQL_SCHEMA_NAME} TO anon, authenticated, service_role;\nGRANT SELECT ON ALL TABLES IN SCHEMA ${EQL_SCHEMA_NAME} TO anon, authenticated, service_role;\nGRANT EXECUTE ON ALL ROUTINES IN SCHEMA ${EQL_SCHEMA_NAME} TO anon, authenticated, service_role;\nGRANT USAGE ON ALL SEQUENCES IN SCHEMA ${EQL_SCHEMA_NAME} TO anon, authenticated, service_role;\nALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA ${EQL_SCHEMA_NAME} GRANT SELECT ON TABLES TO anon, authenticated, service_role;\nALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA ${EQL_SCHEMA_NAME} GRANT EXECUTE ON ROUTINES TO anon, authenticated, service_role;\nALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA ${EQL_SCHEMA_NAME} GRANT USAGE ON SEQUENCES TO anon, authenticated, service_role;\n`\n\n/**\n * Get the directory of the current file, supporting both ESM and CJS.\n */\nfunction getCurrentDir(): string {\n  // ESM: import.meta.url is available\n  if (typeof import.meta?.url === 'string' && import.meta.url) {\n    return dirname(new URL(import.meta.url).pathname)\n  }\n  // CJS: __dirname is available\n  return __dirname\n}\n\n/**\n * Resolve the path to a bundled SQL file shipped with the package.\n *\n * tsup bundles everything flat:\n *   - Library: dist/index.js   → SQL at dist/sql/\n *   - CLI:     dist/bin/stash.js → SQL at dist/sql/\n *\n * We walk up from the current file until we find the sql/ directory.\n */\nfunction bundledSqlPath(filename: string): string {\n  const thisDir = getCurrentDir()\n\n  // Try sql/ as a sibling first (library path: dist/ -> dist/sql/)\n  const sibling = join(thisDir, 'sql', filename)\n  if (existsSync(sibling)) return sibling\n\n  // Try one level up (CLI path: dist/bin/ -> dist/sql/)\n  const parent = join(thisDir, '..', 'sql', filename)\n  if (existsSync(parent)) return resolve(parent)\n\n  // Fallback: return the sibling path and let the caller handle the error\n  return sibling\n}\n\nexport interface PermissionCheckResult {\n  ok: boolean\n  missing: string[]\n  /**\n   * Whether the connected role is a Postgres superuser. Managed Postgres\n   * providers (Supabase, Neon, RDS, etc.) do not grant superuser, which means\n   * `CREATE OPERATOR FAMILY` / `CREATE OPERATOR CLASS` in the EQL install\n   * script will fail. Callers use this to auto-fall back to the\n   * no-operator-family install variant (OPE index only) instead of aborting.\n   */\n  isSuperuser: boolean\n}\n\nexport class EQLInstaller {\n  private readonly databaseUrl: string\n\n  constructor(options: { databaseUrl: string }) {\n    this.databaseUrl = options.databaseUrl\n  }\n\n  /**\n   * Check whether the connected database role has the permissions required\n   * to install EQL.\n   *\n   * EQL installation requires:\n   * - SUPERUSER or CREATEDB — for `CREATE EXTENSION IF NOT EXISTS pgcrypto`\n   * - CREATE on the current database — for `CREATE SCHEMA eql_v2`\n   * - CREATE on the public schema — for `CREATE TYPE public.eql_v2_encrypted`\n   */\n  async checkPermissions(): Promise<PermissionCheckResult> {\n    const client = new pg.Client({ connectionString: this.databaseUrl })\n\n    try {\n      await client.connect()\n\n      const missing: string[] = []\n\n      // Check if the role is a superuser (can do everything)\n      const roleResult = await client.query(`\n        SELECT\n          rolsuper,\n          rolcreatedb\n        FROM pg_roles\n        WHERE rolname = current_user\n      `)\n\n      const role = roleResult.rows[0]\n      const isSuperuser = role?.rolsuper === true\n\n      if (isSuperuser) {\n        return { ok: true, missing: [], isSuperuser: true }\n      }\n\n      // Not a superuser — check individual permissions\n\n      // CREATE on the current database (needed for CREATE SCHEMA, CREATE EXTENSION)\n      const dbCreateResult = await client.query(`\n        SELECT has_database_privilege(current_user, current_database(), 'CREATE') AS has_create\n      `)\n      if (!dbCreateResult.rows[0]?.has_create) {\n        missing.push(\n          'CREATE on database (required for CREATE SCHEMA and CREATE EXTENSION)',\n        )\n      }\n\n      // CREATE on the public schema (needed for CREATE TYPE public.eql_v2_encrypted)\n      const schemaCreateResult = await client.query(`\n        SELECT has_schema_privilege(current_user, 'public', 'CREATE') AS has_create\n      `)\n      if (!schemaCreateResult.rows[0]?.has_create) {\n        missing.push(\n          'CREATE on public schema (required for CREATE TYPE public.eql_v2_encrypted)',\n        )\n      }\n\n      // Check if pgcrypto is already installed — if not, we need CREATE EXTENSION privilege\n      const pgcryptoResult = await client.query(`\n        SELECT 1 FROM pg_extension WHERE extname = 'pgcrypto'\n      `)\n      if (pgcryptoResult.rowCount === 0 || pgcryptoResult.rowCount === null) {\n        // pgcrypto not installed — need to be able to create extensions\n        // This typically requires superuser or the role must be the extension owner\n        if (!role?.rolcreatedb) {\n          missing.push(\n            'SUPERUSER or extension owner (required for CREATE EXTENSION pgcrypto)',\n          )\n        }\n      }\n\n      return { ok: missing.length === 0, missing, isSuperuser: false }\n    } catch (error) {\n      const detail = error instanceof Error ? error.message : String(error)\n      throw new Error(`Failed to connect to database: ${detail}`, {\n        cause: error,\n      })\n    } finally {\n      await client.end()\n    }\n  }\n\n  /**\n   * Check whether the EQL extension is installed by looking for the `eql_v2` schema.\n   */\n  async isInstalled(): Promise<boolean> {\n    const client = new pg.Client({ connectionString: this.databaseUrl })\n\n    try {\n      await client.connect()\n\n      const result = await client.query(\n        'SELECT schema_name FROM information_schema.schemata WHERE schema_name = $1',\n        [EQL_SCHEMA_NAME],\n      )\n\n      return result.rowCount !== null && result.rowCount > 0\n    } catch (error) {\n      const detail = error instanceof Error ? error.message : String(error)\n      throw new Error(`Failed to connect to database: ${detail}`, {\n        cause: error,\n      })\n    } finally {\n      await client.end()\n    }\n  }\n\n  /**\n   * Return the installed EQL version, or `null` if EQL is not installed.\n   *\n   * This is best-effort: if the schema exists but no version metadata is\n   * available, `'unknown'` is returned.\n   */\n  async getInstalledVersion(): Promise<string | null> {\n    const client = new pg.Client({ connectionString: this.databaseUrl })\n\n    try {\n      await client.connect()\n\n      const schemaResult = await client.query(\n        'SELECT schema_name FROM information_schema.schemata WHERE schema_name = $1',\n        [EQL_SCHEMA_NAME],\n      )\n\n      if (schemaResult.rowCount === null || schemaResult.rowCount === 0) {\n        return null\n      }\n\n      // Attempt to read a version from the schema — the EQL extension may\n      // expose a `version()` function or a `version` table. If neither exists\n      // we fall back to 'unknown'.\n      try {\n        const versionResult = await client.query(\n          `SELECT ${EQL_SCHEMA_NAME}.version() AS version`,\n        )\n\n        if (versionResult.rows.length > 0 && versionResult.rows[0].version) {\n          return String(versionResult.rows[0].version)\n        }\n      } catch {\n        // version() function does not exist — that's fine\n      }\n\n      return 'unknown'\n    } catch (error) {\n      const detail = error instanceof Error ? error.message : String(error)\n      throw new Error(`Failed to connect to database: ${detail}`, {\n        cause: error,\n      })\n    } finally {\n      await client.end()\n    }\n  }\n\n  /**\n   * Install the CipherStash EQL PostgreSQL extension.\n   *\n   * By default, uses the SQL bundled with this package. Pass `latest: true`\n   * to fetch the latest version from GitHub instead.\n   *\n   * This method is intentionally \"silent\" — it does not produce any console\n   * output. The calling CLI command is responsible for all user-facing output.\n   */\n  async install(options?: {\n    excludeOperatorFamily?: boolean\n    supabase?: boolean\n    latest?: boolean\n  }): Promise<void> {\n    const { supabase = false, latest = false } = options ?? {}\n    const excludeOperatorFamily = options?.excludeOperatorFamily || supabase\n    const sql = latest\n      ? await this.downloadInstallScript(excludeOperatorFamily)\n      : this.loadBundledInstallScript({ excludeOperatorFamily, supabase })\n\n    const client = new pg.Client({ connectionString: this.databaseUrl })\n\n    try {\n      await client.connect()\n    } catch (error) {\n      const detail = error instanceof Error ? error.message : String(error)\n      throw new Error(`Failed to connect to database: ${detail}`, {\n        cause: error,\n      })\n    }\n\n    try {\n      await client.query('BEGIN')\n      await client.query(sql)\n\n      if (supabase) {\n        await this.grantSupabasePermissions(client)\n      }\n\n      await client.query('COMMIT')\n    } catch (error) {\n      await client.query('ROLLBACK').catch(() => {\n        // Swallow rollback errors — the original error is more important.\n      })\n\n      const detail = error instanceof Error ? error.message : String(error)\n      throw new Error(`Failed to install EQL: ${detail}`, {\n        cause: error,\n      })\n    } finally {\n      await client.end()\n    }\n  }\n\n  /**\n   * Grant Supabase roles access to the eql_v2 schema.\n   *\n   * Supabase uses dedicated roles (anon, authenticated, service_role) that\n   * don't own the schema, so explicit grants are required. Issues\n   * {@link SUPABASE_PERMISSIONS_SQL} as a single multi-statement query —\n   * Postgres accepts that and it keeps the SQL identical to what we'd write\n   * into a Supabase migration file.\n   */\n  private async grantSupabasePermissions(client: pg.Client): Promise<void> {\n    await client.query(SUPABASE_PERMISSIONS_SQL)\n  }\n\n  /**\n   * Load the EQL SQL install script bundled with this package.\n   */\n  private loadBundledInstallScript(options: {\n    excludeOperatorFamily: boolean\n    supabase: boolean\n  }): string {\n    const filename = resolveBundledFilename(options)\n\n    try {\n      return readFileSync(bundledSqlPath(filename), 'utf-8')\n    } catch (error) {\n      throw new Error(\n        `Failed to load bundled EQL install script (${filename}). The package may be corrupted — try reinstalling @cipherstash/cli.`,\n        { cause: error },\n      )\n    }\n  }\n\n  /**\n   * Download the EQL SQL install script from GitHub.\n   */\n  private async downloadInstallScript(\n    excludeOperatorFamily: boolean,\n  ): Promise<string> {\n    const url = excludeOperatorFamily\n      ? EQL_INSTALL_NO_OPERATOR_FAMILY_URL\n      : EQL_INSTALL_URL\n\n    let response: Response\n\n    try {\n      response = await fetch(url)\n    } catch (error) {\n      throw new Error('Failed to download EQL install script from GitHub.', {\n        cause: error,\n      })\n    }\n\n    if (!response.ok) {\n      throw new Error(\n        `Failed to download EQL install script from GitHub. HTTP ${response.status}: ${response.statusText}`,\n      )\n    }\n\n    return response.text()\n  }\n}\n\n/**\n * Determine which bundled SQL file to use based on install options.\n *\n * - `supabase: true` → Supabase-specific variant\n * - `excludeOperatorFamily: true` → no operator family variant\n * - default → standard install\n */\nfunction resolveBundledFilename(options: {\n  excludeOperatorFamily: boolean\n  supabase: boolean\n}): string {\n  if (options.supabase) return 'cipherstash-encrypt-supabase.sql'\n  if (options.excludeOperatorFamily)\n    return 'cipherstash-encrypt-no-operator-family.sql'\n  return 'cipherstash-encrypt.sql'\n}\n\n/**\n * Load the bundled EQL install SQL. Used by the Drizzle migration path.\n */\nexport function loadBundledEqlSql(\n  options: {\n    excludeOperatorFamily?: boolean\n    supabase?: boolean\n  } = {},\n): string {\n  const filename = resolveBundledFilename({\n    excludeOperatorFamily: options.excludeOperatorFamily ?? false,\n    supabase: options.supabase ?? false,\n  })\n\n  try {\n    return readFileSync(bundledSqlPath(filename), 'utf-8')\n  } catch (error) {\n    throw new Error(\n      `Failed to load bundled EQL install script (${filename}). The package may be corrupted — try reinstalling @cipherstash/cli.`,\n      { cause: error },\n    )\n  }\n}\n\n/**\n * Download the latest EQL install SQL from GitHub. Used by the Drizzle migration path\n * when `--latest` is passed.\n *\n * Supabase uses the same GitHub asset as the no-operator-family variant —\n * treating either flag as \"no operator families\" keeps the intent explicit\n * even though the underlying URL is the same.\n */\nexport async function downloadEqlSql(\n  options:\n    | { excludeOperatorFamily?: boolean; supabase?: boolean }\n    | boolean = false,\n): Promise<string> {\n  const normalized =\n    typeof options === 'boolean'\n      ? { excludeOperatorFamily: options, supabase: false }\n      : {\n          excludeOperatorFamily: options.excludeOperatorFamily ?? false,\n          supabase: options.supabase ?? false,\n        }\n\n  const useNoOperatorFamilyUrl =\n    normalized.excludeOperatorFamily || normalized.supabase\n  const url = useNoOperatorFamilyUrl\n    ? EQL_INSTALL_NO_OPERATOR_FAMILY_URL\n    : EQL_INSTALL_URL\n\n  let response: Response\n\n  try {\n    response = await fetch(url)\n  } catch (error) {\n    throw new Error('Failed to download EQL install script from GitHub.', {\n      cause: error,\n    })\n  }\n\n  if (!response.ok) {\n    throw new Error(\n      `Failed to download EQL install script. HTTP ${response.status}: ${response.statusText}`,\n    )\n  }\n\n  return response.text()\n}\n"],"mapp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