/** * Resolves a Scribase access token the same way the official `scribase` CLI * does, so `scribase-migrate` never asks a user to paste a token it could * find itself: a project folder's `.env`/`.env.local`, then * `SCRIBASE_ACCESS_TOKEN` in the shell, then whatever `scribase login` * already stored (macOS Keychain / Linux Secret Service via the `scribase` * service name, or the plaintext fallback file at * `$XDG_CONFIG_HOME/scribase/credentials`). * * This mirrors `edge-repos/scribase-cli/src/cli/{token,credentials}.ts` * on purpose — one account, one token-resolution rule, everywhere. */ import { spawnSync } from 'node:child_process'; import { existsSync, readFileSync } from 'node:fs'; import { homedir } from 'node:os'; import { join } from 'node:path'; function configDir(env) { return join(env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'scribase'); } function parseCredentialsFile(text) { const out = {}; for (const line of text.split('\n')) { const at = line.indexOf('='); if (at < 0) continue; const key = line.slice(0, at).trim(); const value = line.slice(at + 1).trim(); if (!value) continue; if (key === 'api_url') out.apiUrl = value; if (key === 'access_token') out.token = value; if (key === 'token_store') out.tokenStore = value; } return out; } function fromKeychain(apiUrl) { if (process.platform !== 'darwin') return null; const probe = spawnSync('security', ['--help'], { stdio: 'ignore' }); if (probe.error) return null; const attempts = apiUrl ? [apiUrl] : []; for (const account of attempts.length ? attempts : [undefined]) { const args = ['find-generic-password', '-s', 'scribase', '-w']; if (account) args.push('-a', account); const result = spawnSync('security', args, { encoding: 'utf8' }); const token = result.stdout?.trim(); if (result.status === 0 && token) return token; } return null; } /** * Resolves `{ apiUrl, token, source }`. Throws a clear, actionable error * (never a token value) when nothing is found — the equivalent of * `scribase doctor` telling the user to run `scribase login`. */ export function resolveScribaseAuth(env = process.env) { if (env.SCRIBASE_ACCESS_TOKEN) { return { apiUrl: env.SCRIBASE_API_URL || 'https://api.scribase.com', token: env.SCRIBASE_ACCESS_TOKEN, source: 'shell (SCRIBASE_ACCESS_TOKEN)', }; } const dir = configDir(env); const credsPath = join(dir, 'credentials'); if (existsSync(credsPath)) { const creds = parseCredentialsFile(readFileSync(credsPath, 'utf8')); const apiUrl = creds.apiUrl || 'https://api.scribase.com'; if (creds.tokenStore === 'keychain') { const token = fromKeychain(apiUrl) ?? fromKeychain(undefined); if (token) return { apiUrl, token, source: 'scribase login (keychain)' }; } else if (creds.token) { return { apiUrl, token: creds.token, source: 'scribase login (credentials file)' }; } } throw new Error( 'No Scribase access token found. Run `npx scribase login` once (or export ' + 'SCRIBASE_ACCESS_TOKEN), then re-run scribase-migrate.', ); }