railyard/apps/console/lib/ai/provision.ts
caelum0x 4016a68d18 feat(ai): BYOK AI gateway for Scribase projects with per-key caps, traces and a secure connect page (PY1.4)
Railyard side of PY1.4 (ADR RY-0003). Acceptance:
1. Bridge `ai` gives a Scribase project environment one key (ry_ai_..., shown
   once, to the Scribase control plane only, stored here as SHA-256; `rotate`
   revokes the old one) and a one-time link to /connect/ai (15 minutes), the
   only place a provider key is typed. It is sealed with AES-256-GCM under
   RAILYARD_CREDENTIALS_KEY, bound to org and provider, and only a
   four-character hint is ever read back.
2. BYOK only: POST /api/v1/ai/chat/completions (OpenAI-compatible) refuses
   with 403 byok_required when the org has not connected the provider the
   model names, and never calls Relay then. When it does call, the customer's
   key fills that provider's slot and every other slot carries a refusal
   marker, so Relay (caller credential wins) can never use our keys, not even
   on failover; a test pins the slot list to Relay's PROVIDER_KEY_SLOTS.
   Credentials in a request body are refused.
3. Daily and monthly token caps per key (429 with the period); usage (atomic
   rpc) and one trace per call (model, provider, status, tokens, latency),
   read per project key by the bridge `ai_usage` route for the Scribase tab;
   Relay traces carry tensorzero::tags for the same filter.
4. Copy says "your provider bills you directly"; no credits are included
   anywhere (copy lint over the connect page and every gateway message).
apps/relay/config/tenants/README.md records the tenant rules.

Migration: apps/console/db/migrations/0003_ai_gateway.sql (idempotent;
applied twice to a scratch local cluster by test/migration.test.ts).
Env: RELAY_URL (var), RELAY_TENANT_KEY, RAILYARD_CREDENTIALS_KEY (secrets).

Tests: console 63/63 (gateway 6, bridge 12, migration 3, repo 5), tsc clean,
tests/contract 3/3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 21:44:04 +03:00

69 lines
3.0 KiB
TypeScript

// Keys and the secure connect page for the AI gateway (Wave P PY1.4).
//
// - A project's key (`ry_ai_...`) is returned once, to the Scribase control
// plane, which stores it as the project's function secret. Only its
// SHA-256 is kept here.
// - The customer's provider key is typed once, on the connect page, reached
// through a one-time link (15 minutes). It is sealed before it is stored and
// never shown again (only a four-character hint).
import { randomToken, sha256Hex } from "../crypto.ts";
import type { Repo } from "../repo.ts";
import type { AiKey, AiProvider } from "../types.ts";
import { PROVIDERS } from "./gateway.ts";
import { hint, seal } from "./seal.ts";
export const CONNECT_TTL_SECONDS = 15 * 60;
export const DEFAULT_CAPS = Object.freeze({ daily: 1_000_000, monthly: 20_000_000 });
export async function issueAiKey(
repo: Repo,
orgId: string,
label: string,
caps: { daily: number; monthly: number } = DEFAULT_CAPS,
): Promise<{ token: string; key: AiKey }> {
const token = `ry_ai_${randomToken(32)}`;
const key = await repo.createAiKey({
org_id: orgId,
label: label.slice(0, 80),
key_hash: await sha256Hex(token),
daily_token_cap: caps.daily,
monthly_token_cap: caps.monthly,
});
return { token, key };
}
export async function issueConnectToken(repo: Repo, orgId: string, now: Date): Promise<string> {
const token = `ry_ct_${randomToken(32)}`;
await repo.createConnectToken({
token_hash: await sha256Hex(token),
org_id: orgId,
purpose: "ai",
expires_at: new Date(now.getTime() + CONNECT_TTL_SECONDS * 1000).toISOString(),
used_at: null,
});
return token;
}
export type ConnectResult = { ok: true; provider: AiProvider; hint: string } | { ok: false; status: number; message: string };
/** Stores the customer's provider key for the token's org. The token works once. */
export async function connectCredential(
deps: { repo: Repo; credentialsKey: string; now: () => Date },
token: string,
provider: string,
secret: string,
): Promise<ConnectResult> {
if (!PROVIDERS.includes(provider as AiProvider)) return { ok: false, status: 400, message: "Choose a provider from the list." };
const value = secret.trim();
if (value.length < 8 || value.length > 1024 || /\s/.test(value)) return { ok: false, status: 400, message: "That does not look like a provider key." };
if (!/^ry_ct_[A-Za-z0-9_-]{20,}$/.test(token)) return { ok: false, status: 400, message: "This link is not valid. Start again from your terminal." };
const now = deps.now();
const t = await deps.repo.consumeConnectToken(await sha256Hex(token), now.toISOString());
if (!t) return { ok: false, status: 410, message: "This link was used already or expired. Start again from your terminal." };
const p = provider as AiProvider;
const sealed = await seal(deps.credentialsKey, `${t.org_id}:${p}`, value);
await deps.repo.saveAiCredential({ org_id: t.org_id, provider: p, nonce: sealed.nonce, ciphertext: sealed.ciphertext, key_hint: hint(value) });
return { ok: true, provider: p, hint: hint(value) };
}