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

35 lines
1.6 KiB
TypeScript

// Sealing the customer's own provider keys (Wave P PY1.4). AES-256-GCM with
// WebCrypto under RAILYARD_CREDENTIALS_KEY (32 bytes, base64); the org and the
// provider are bound as associated data, so a row copied to another org or
// provider does not open. Only the last four characters are ever read back.
import { b64decode, b64encode } from "../crypto.ts";
const enc = new TextEncoder();
const dec = new TextDecoder();
async function importKey(masterB64: string): Promise<CryptoKey> {
const raw = b64decode(masterB64.trim());
if (!raw || raw.length !== 32) throw new Error("RAILYARD_CREDENTIALS_KEY must be 32 bytes, base64");
return crypto.subtle.importKey("raw", raw, { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);
}
export async function seal(masterB64: string, aad: string, plaintext: string): Promise<{ nonce: string; ciphertext: string }> {
const key = await importKey(masterB64);
const iv = crypto.getRandomValues(new Uint8Array(12));
const ct = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: enc.encode(aad) }, key, enc.encode(plaintext)));
return { nonce: b64encode(iv), ciphertext: b64encode(ct) };
}
export async function open(masterB64: string, aad: string, nonce: string, ciphertext: string): Promise<string> {
const key = await importKey(masterB64);
const iv = b64decode(nonce);
const ct = b64decode(ciphertext);
if (!iv || !ct) throw new Error("sealed value is not base64");
return dec.decode(await crypto.subtle.decrypt({ name: "AES-GCM", iv, additionalData: enc.encode(aad) }, key, ct));
}
export function hint(secret: string): string {
return `...${secret.slice(-4)}`;
}