caelum0x 90f6ba3b78 feat(ship): custom domains for shipped apps on the customer's own Cloudflare account (QY1.5, I6)
- packages/cli/src/domains.mjs: a dependency-free client of Cloudflare's
  public Workers Custom Domains API (zones lookup, PUT/GET/DELETE
  /accounts/{id}/workers/domains, certificate pack state). Cloudflare
  issues the TLS certificate; a domain reads active once it is. The token
  goes in the Authorization header only and is scrubbed from every error.
  Byte copy at apps/console/lib/ship/cf-domains.mjs (drift test).
- railyard domains [add|remove HOSTNAME] [--app]: the console attaches the
  hostname to the app's production Worker with the org's Cloudflare grant
  (the QY1.1 OAuth step; the access token is opened and used inside the
  console only). Without a grant (409 no_cloudflare_grant) the CLI does the
  same with the local login (CLOUDFLARE_API_TOKEN or the wrangler login
  file after `wrangler whoami`) and the console records the outcome. Adding
  an attached hostname keeps it; one on another Worker is refused; remove
  is idempotent; a hostname outside the account's zones is refused plainly.
- Console: migration 0010 railyard.app_domains (one org per hostname,
  lower case, cascade, RLS, no anon); GET/POST/DELETE /api/v1/domains and
  POST /api/v1/domains/record (CLI bearer); states refreshed from
  Cloudflare when the org has a grant. Cloudflare OAuth default scopes add
  zone:read and ssl_certs:write (orgs linked before need to run
  railyard link once more for console-side domains).
- Scribase bridge: new signed route domains {scribase_org_id, app?} ->
  {available, domains:[{app, hostname, state, checked_at, created_at}],
  next} for the Deploy tab; contract fixture v2 adds it (additive).

Tests: CLI 23/23 (new domains.test.mjs 5: grant path with the real console
handlers and a fake Cloudflare, local-login path, wrangler config file,
refusals, idempotent remove, no token printed or sent to the console);
console 147/147 (new lib/ship/domains.test.ts 4: drift, worker naming
equal to the CLI's, attach/detach and cross-org refusal, record and
refresh, bridge listing; 0010 migration on a scratch PG); contract 6/6;
console tsc clean.

Owner-only: one real-domain proof (railyard domains add on a domain in the
owner's Cloudflare account) is not run here; record it at the deploy gate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 13:45:57 +03:00

664 lines
34 KiB
TypeScript

// The Scribase bridge (Wave P PY1.0, RYP-E6). Scribase sells Railyard inside
// its portfolio add-on; its control-api calls these three routes, server to
// server, signed with Standard Webhooks (a shared `whsec_` secret):
//
// POST /api/v1/bridge/scribase/orgs {scribase_org_id, name, addon}
// Creates the Railyard org on first use, bound to the Scribase org id
// (no second sign-up), and mirrors the add-on state into its
// entitlement. Idempotent.
// POST /api/v1/bridge/scribase/claims {scribase_org_id, slot}
// A one-time, pre-approved device code (two minutes). Scribase hands it
// to its own CLI, which exchanges it once at /api/v1/device/token and
// writes the token to the Railyard CLI's credentials file (mode 600).
// The token is never in a response to Scribase, a terminal or a chat.
// POST /api/v1/bridge/scribase/deploys {scribase_org_id, app?, branch?}
// The org's deploys (newest first) for the Scribase Deploy tab (PY1.2).
// POST /api/v1/bridge/scribase/proof {scribase_org_id, slot}
// {slot, state, live, proof:{kind,id,at}, next}: the real thing that
// happened for this slot, or "arriving" while its package has not landed.
// POST /api/v1/bridge/scribase/domains {scribase_org_id, app?}
// (QY1.5) The custom domains attached to the org's apps and their
// certificate state, for the Scribase Deploy tab.
// POST /api/v1/bridge/scribase/product_analytics {scribase_org_id, app, days?, with_server_key?}
// (QY1.2) The project's product analytics: public host and key, the
// first product event, the web view, and (only when asked, only to the
// control plane) the project's server key for server-side forwarders.
//
// Contract fixtures: railyard/tests/contract/fixtures/scribase-bridge/.
import { sha256Hex } from "../../../../../lib/crypto.ts";
import { access } from "../../../../../lib/ladder.ts";
import { listDeploys } from "../../deploys/service.ts";
import { addApp, AppError, normaliseAppName } from "../../../../../lib/apps.ts";
import { firstEvent, type InsightsClient } from "../../../../../lib/insights.ts";
import { markTimes, vitalsView } from "../../../../../lib/vitals-view.ts";
import { capMessage } from "../../../../../lib/caps.ts";
import { registerSite, syncSites, type SitesStore } from "../../../../../lib/sites.ts";
import { issueAiKey, issueConnectToken } from "../../../../../lib/ai/provision.ts";
import type { Repo } from "../../../../../lib/repo.ts";
import { verify, type WebhookHeaders } from "../../../../../lib/standard-webhooks.ts";
import { createApprovedDevice } from "../../../../../lib/tokens.ts";
import type { ProductAnalyticsClient, ProductFirstEvent } from "../../../../../lib/product-analytics.ts";
import { appDomains } from "../../../../../lib/ship/domains.ts";
import type { ShipDeps } from "../../../../../lib/ship/service.ts";
import { emptyEntitlement, type Entitlement } from "../../../../../lib/types.ts";
import { ensureEnv, firstRead, FlagsError, listFlags, setFlag, type FlagsDeps } from "../../../../../lib/flags/service.ts";
import { createCheck, listWithState, WatchError, type WatchDeps } from "../../../../../lib/watch/service.ts";
export const CLAIM_TTL_SECONDS = 120;
/** Every slot of the portfolio add-on (dispatch section 5.2). */
export const ADDON_SLOTS = ["deploy", "analytics", "flags", "errors", "uptime", "ai", "billing", "consent"] as const;
export type AddonSlot = (typeof ADDON_SLOTS)[number];
/**
* The slots Railyard serves through this bridge, the package that makes each
* one live, and whether that package has landed. `errors` is Scribase's own
* slot (SP-D6); the add-on only lifts its caps, so it is not served here.
*/
export const BRIDGE_SLOTS = {
deploy: { pkg: "PY1.2", landed: true, proof: "deploy" },
analytics: { pkg: "PY1.3", landed: true, proof: "first_event" },
ai: { pkg: "PY1.4", landed: true, proof: "gateway_key" },
flags: { pkg: "PY2.1", landed: true, proof: "first_flag_read" },
uptime: { pkg: "PY2.2", landed: true, proof: "check_result" },
billing: { pkg: "PY2.3", landed: false, proof: "test_purchase" },
consent: { pkg: "PY2.5", landed: false, proof: "consent_record" },
} as const;
export type BridgeSlot = keyof typeof BRIDGE_SLOTS;
export interface BridgeDeps {
repo: Repo;
secret: string;
consoleUrl: string;
now: () => Date;
/** Site entries for the edge collector (PY1.3); absent in tests that do not need them. */
sites?: SitesStore;
/** Insights tenant API for the analytics proof (PY1.3). */
insights?: InsightsClient | null;
/** Public base of the edge collector and page tag. */
insightsUrl?: string;
/** Railyard Flags (PY2.1); absent in tests that do not need them. */
flags?: FlagsDeps;
/** Railyard Watch (PY2.2); absent in tests that do not need it. */
watch?: WatchDeps;
/** Page speed with deploy markers in the Analytics tab (PY3.3), only with RAILYARD_REPLAY_LIVE=1. */
replayLive?: boolean;
/** Ship on push and custom domains (QY1.5); absent or null while not configured. */
ship?: ShipDeps | null;
/** Product analytics (QY1.2); absent or null while the service is not connected. */
productAnalytics?: ProductAnalyticsClient | null;
/** P-Y1 transition: accept unbound ids and orgs syncs without `addon.as_of` (RAILYARD_BRIDGE_ACCEPT_LEGACY=1). */
acceptLegacy?: boolean;
}
export interface BridgeResult {
status: number;
body: Record<string, unknown>;
}
export interface SlotState {
slot: string;
state: "live" | "arriving" | "not_entitled" | "no_proof_yet";
live: boolean;
proof: { kind: string; id: string; at: string } | null;
next: string | null;
}
const ORG_ID = /^[A-Za-z0-9_-]{1,128}$/;
const MAX_APPS = 1000;
const MAX_EVENTS = 1_000_000_000;
// Fixed namespace for the synthetic owner id of a bridged org (UUID v5).
const OWNER_NAMESPACE = "6f3b8a2e-4c1d-5e7f-9a0b-1c2d3e4f5a6b";
const fail = (status: number, error: string): BridgeResult => ({ status, body: { error } });
/** The deterministic owner id of the Railyard org bound to one Scribase org (UUID v5). */
export async function ownerIdFor(scribaseOrgId: string): Promise<string> {
const ns = OWNER_NAMESPACE.replace(/-/g, "").match(/../g)!.map((h) => parseInt(h, 16));
const name = new TextEncoder().encode(`scribase-org:${scribaseOrgId}`);
const digest = new Uint8Array(await crypto.subtle.digest("SHA-1", new Uint8Array([...ns, ...name])));
const b = digest.slice(0, 16);
b[6] = (b[6] & 0x0f) | 0x50;
b[8] = (b[8] & 0x3f) | 0x80;
const hex = [...b].map((x) => x.toString(16).padStart(2, "0")).join("");
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}
interface AddonState {
active: boolean;
slots: AddonSlot[];
renews_at: string | null;
caps: { apps: number; analytics_events_month: number };
/** Scribase's time (epoch ms) for this state; null only from a legacy sender. */
as_of: number | null;
}
interface SyncInput {
scribase_org_id: string;
name: string;
addon: AddonState;
}
const isInt = (v: unknown, max: number): v is number => typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= max;
// as_of may run at most the signature tolerance ahead of our clock.
const AS_OF_SKEW_MS = 300_000;
function parseAddon(v: unknown, nowMs: number, acceptLegacy: boolean): AddonState | string {
if (!v || typeof v !== "object") return "addon must be an object";
const a = v as Record<string, unknown>;
let as_of: number | null = null;
if (a.as_of === undefined && acceptLegacy) as_of = null;
else if (typeof a.as_of === "number" && Number.isSafeInteger(a.as_of) && a.as_of > 0 && a.as_of <= nowMs + AS_OF_SKEW_MS) as_of = a.as_of;
else return "addon.as_of must be the time of this state in epoch milliseconds";
if (typeof a.active !== "boolean") return "addon.active must be true or false";
if (!Array.isArray(a.slots) || !a.slots.every((s) => (ADDON_SLOTS as readonly unknown[]).includes(s))) {
return `addon.slots must list only: ${ADDON_SLOTS.join(", ")}`;
}
const renews = a.renews_at ?? null;
if (renews !== null && (typeof renews !== "string" || Number.isNaN(Date.parse(renews)))) return "addon.renews_at must be a date or null";
const caps = a.caps as Record<string, unknown> | undefined;
if (!caps || !isInt(caps.apps, MAX_APPS) || !isInt(caps.analytics_events_month, MAX_EVENTS)) {
return "addon.caps needs apps and analytics_events_month as whole numbers";
}
const slots = [...new Set(a.slots as AddonSlot[])].sort();
return { active: a.active, slots, renews_at: renews as string | null, caps: { apps: caps.apps, analytics_events_month: caps.analytics_events_month }, as_of };
}
function parseOrgRef(b: Record<string, unknown>): string | null {
return typeof b.scribase_org_id === "string" && ORG_ID.test(b.scribase_org_id) ? b.scribase_org_id : null;
}
function parseSync(body: Record<string, unknown>, nowMs: number, acceptLegacy: boolean): SyncInput | string {
const scribase_org_id = parseOrgRef(body);
if (!scribase_org_id) return "scribase_org_id must be 1-128 letters, digits, dashes or underscores";
const name = typeof body.name === "string" ? body.name.trim() : "";
if (name.length < 1 || name.length > 80) return "name must be 1-80 characters";
const addon = parseAddon(body.addon, nowMs, acceptLegacy);
if (typeof addon === "string") return addon;
return { scribase_org_id, name, addon };
}
function withAddon(ent: Entitlement, addon: AddonState, now: Date): Entitlement {
return {
...ent,
plan: "addon",
status: addon.active ? "active" : "inactive",
paused: false,
cancel_at_period_end: false,
// Limits are kept when the add-on lapses: the org is paused, never emptied.
apps_limit: addon.caps.apps,
events_limit: addon.caps.analytics_events_month,
addon_slots: addon.slots,
addon_renews_at: addon.renews_at,
updated_at: now.toISOString(),
};
}
/** Creates or finds the bound org and mirrors the add-on into its entitlement. */
export async function syncOrg(repo: Repo, input: SyncInput, now: Date, sites?: SitesStore): Promise<BridgeResult> {
const bound = await repo.findScribaseBinding(input.scribase_org_id);
let orgId = bound?.org_id ?? null;
const created = !orgId;
if (!orgId) {
const ownerId = await ownerIdFor(input.scribase_org_id);
const org = await repo.createOrgForUser({
userId: ownerId,
// Not a mailbox: bridged orgs have no Railyard sign-in of their own.
email: `scribase-org-${(await sha256Hex(input.scribase_org_id)).slice(0, 16)}@scribase.invalid`,
name: input.name,
});
orgId = (await repo.bindScribaseOrg(input.scribase_org_id, org.id)).org_id;
}
const current = (await repo.getEntitlement(orgId)) ?? emptyEntitlement(orgId, now);
const saved = await repo.saveAddonEntitlement(withAddon(current, input.addon, now), input.addon.as_of);
if (!saved) {
// A newer state already arrived (a late or out-of-order delivery): nothing changes.
const kept = (await repo.getEntitlement(orgId)) ?? current;
return {
status: 200,
body: { org_id: orgId, created: false, addon: { active: kept.status === "active", slots: kept.addon_slots ?? [] }, stale: true },
};
}
// Caps and pauses reach the edge collector with the next site-entry read.
if (sites) await syncSites(sites, repo, orgId, now);
return {
status: 200,
body: { org_id: orgId, created, addon: { active: saved.status === "active", slots: saved.addon_slots ?? [] } },
};
}
async function entitledOrg(repo: Repo, scribaseOrgId: string, slot: string, now: Date): Promise<{ orgId: string; ownerId: string } | BridgeResult> {
const bound = await repo.findScribaseBinding(scribaseOrgId);
if (!bound) return fail(404, "This Scribase organization has no Railyard org yet. Turn on the add-on first.");
const ent = await repo.getEntitlement(bound.org_id);
const a = access(ent, now);
if (a.state !== "active" || !(ent?.addon_slots ?? []).includes(slot)) {
return fail(402, `The add-on is not active for ${slot}. Nothing was changed; your data is kept.`);
}
return { orgId: bound.org_id, ownerId: await ownerIdFor(scribaseOrgId) };
}
export async function issueClaim(deps: BridgeDeps, body: Record<string, unknown>): Promise<BridgeResult> {
const scribaseOrgId = parseOrgRef(body);
if (!scribaseOrgId) return fail(400, "scribase_org_id is required");
const slot = body.slot;
if (typeof slot !== "string" || !(slot in BRIDGE_SLOTS)) return fail(400, `slot must be one of: ${Object.keys(BRIDGE_SLOTS).join(", ")}`);
const now = deps.now();
const who = await entitledOrg(deps.repo, scribaseOrgId, slot, now);
if ("status" in who) return who;
const claim = await createApprovedDevice(deps.repo, who.orgId, who.ownerId, CLAIM_TTL_SECONDS, now);
return {
status: 200,
body: { claim, expires_in: CLAIM_TTL_SECONDS, token_endpoint: `${deps.consoleUrl}/api/v1/device/token` },
};
}
/** The proof for one slot of one org. `landed` overrides the table in tests of a later package. */
export async function slotProof(
repo: Repo,
orgId: string,
slot: BridgeSlot,
landed: Partial<Record<BridgeSlot, boolean>> = {},
insights: InsightsClient | null = null,
flags: FlagsDeps | null = null,
watch: WatchDeps | null = null,
productAnalytics: ProductAnalyticsClient | null = null,
): Promise<SlotState> {
const isLanded = landed[slot] ?? BRIDGE_SLOTS[slot].landed;
if (!isLanded) {
return { slot, state: "arriving", live: false, proof: null, next: `This slot is arriving (${BRIDGE_SLOTS[slot].pkg}); nothing was changed.` };
}
if (slot === "deploy") {
const last = (await repo.listDeploys(orgId)).find((d) => d.status === "succeeded");
return last
? { slot, state: "live", live: true, proof: { kind: "deploy", id: last.id, at: last.created_at }, next: null }
: { slot, state: "no_proof_yet", live: true, proof: null, next: "Deploy from the project folder to see the first deploy here." };
}
if (slot === "ai") {
const creds = (await repo.listAiCredentials(orgId)).sort((a, b) => (a.updated_at < b.updated_at ? -1 : 1));
return creds[0]
? { slot, state: "live", live: true, proof: { kind: "gateway_key", id: creds[0].provider, at: creds[0].updated_at }, next: null }
: { slot, state: "no_proof_yet", live: true, proof: null, next: "Connect your own AI provider on the connect page." };
}
if (slot === "analytics") {
if (!insights && !productAnalytics) return { slot, state: "no_proof_yet", live: true, proof: null, next: "Analytics is being set up on this deployment; events are counted meanwhile." };
const first = insights ? firstEvent(await insights.summary(orgId)) : null;
if (first) return { slot, state: "live", live: true, proof: { kind: "first_event", id: first.app_id, at: first.at }, next: null };
// QY1.2: an app that only uses the product analytics SDK proves the slot with its first product event.
const product = productAnalytics ? await firstProductEvent(productAnalytics, repo, orgId) : null;
return product
? { slot, state: "live", live: true, proof: { kind: "first_product_event", id: product.app_id, at: product.at }, next: null }
: { slot, state: "no_proof_yet", live: true, proof: null, next: "Waiting for the first event from the app." };
}
if (slot === "flags") {
const read = flags ? await firstRead(flags.store, orgId) : null;
return read
? { slot, state: "live", live: true, proof: read, next: null }
: { slot, state: "no_proof_yet", live: true, proof: null, next: "Read a flag from the app (or run the add command again) to see the first read here." };
}
if (slot === "uptime") {
if (!watch?.live) return { slot, state: "arriving", live: false, proof: null, next: "This slot is arriving (PY2.2); nothing was changed." };
const checks = await listWithState(watch, orgId);
const first = checks.filter((c) => c.first_result_at).sort((a, b) => (a.first_result_at! < b.first_result_at! ? -1 : 1))[0];
return first
? { slot, state: "live", live: true, proof: { kind: "check_result", id: first.id, at: first.first_result_at! }, next: null }
: { slot, state: "no_proof_yet", live: true, proof: null, next: checks.length ? "The first result arrives within two minutes." : "Add your app's address to check." };
}
return { slot, state: "no_proof_yet", live: true, proof: null, next: null };
}
/** The org's earliest first product event over its apps (QY1.2); a service error reads as none yet. */
async function firstProductEvent(pa: ProductAnalyticsClient, repo: Repo, orgId: string): Promise<{ app_id: string; at: string } | null> {
const apps = await repo.listApps(orgId);
const firsts = await Promise.all(apps.map(async (a) => ({ app_id: a.id, first: await pa.firstEvent(orgId, a.id).catch(() => null) })));
const seen = firsts.filter((f): f is { app_id: string; first: ProductFirstEvent } => f.first !== null).sort((a, b) => (a.first.at < b.first.at ? -1 : 1));
return seen[0] ? { app_id: seen[0].app_id, at: seen[0].first.at } : null;
}
async function proofFor(deps: BridgeDeps, body: Record<string, unknown>): Promise<BridgeResult> {
const scribaseOrgId = parseOrgRef(body);
if (!scribaseOrgId) return fail(400, "scribase_org_id is required");
const slot = body.slot;
if (typeof slot !== "string" || !(slot in BRIDGE_SLOTS)) return fail(400, `slot must be one of: ${Object.keys(BRIDGE_SLOTS).join(", ")}`);
const s = slot as BridgeSlot;
if (!BRIDGE_SLOTS[s].landed) return { status: 200, body: { ...(await slotProof(deps.repo, "", s)) } };
const bound = await deps.repo.findScribaseBinding(scribaseOrgId);
if (!bound) return { status: 200, body: { slot: s, state: "not_entitled", live: false, proof: null, next: "Turn on the add-on first." } };
return { status: 200, body: { ...(await slotProof(deps.repo, bound.org_id, s, {}, deps.insights ?? null, deps.flags ?? null, deps.watch ?? null, deps.productAnalytics ?? null)) } };
}
async function deploysFor(deps: BridgeDeps, body: Record<string, unknown>): Promise<BridgeResult> {
const scribaseOrgId = parseOrgRef(body);
if (!scribaseOrgId) return fail(400, "scribase_org_id is required");
const str = (k: string, max: number) => (typeof body[k] === "string" && (body[k] as string).length <= max ? (body[k] as string) : null);
const bound = await deps.repo.findScribaseBinding(scribaseOrgId);
if (!bound) return { status: 200, body: { deploys: [] } };
const r = await listDeploys(deps.repo, bound.org_id, str("app", 60), str("branch", 200));
return { status: r.status, body: r.body };
}
/** The app for one Scribase project environment, and its public page-tag settings (PY1.3). */
async function siteFor(deps: BridgeDeps, body: Record<string, unknown>): Promise<BridgeResult> {
const scribaseOrgId = parseOrgRef(body);
if (!scribaseOrgId) return fail(400, "scribase_org_id is required");
const name = typeof body.app === "string" ? normaliseAppName(body.app) : "";
if (!/^[a-z0-9][a-z0-9-]{0,39}$/.test(name)) return fail(400, "app must be a project name (letters, numbers, dashes)");
const now = deps.now();
const who = await entitledOrg(deps.repo, scribaseOrgId, "analytics", now);
if ("status" in who) return who;
let app = await deps.repo.findAppByName(who.orgId, name);
if (!app) {
try {
app = await addApp(deps.repo, who.orgId, name, now);
} catch (e) {
if (e instanceof AppError) return fail(e.code === "no_plan" ? 402 : 409, e.message);
throw e;
}
}
if (deps.sites) await registerSite(deps.sites, deps.repo, app, now);
const base = (deps.insightsUrl ?? "").replace(/\/$/, "");
return {
status: 200,
body: {
app_id: app.id,
app: app.name,
site_key: app.site_key,
script_url: base ? `${base}/s.js` : null,
collector_url: base || null,
// QY1.2 (contract 5.3): the product analytics host and the project's public key (the site key).
analytics_host: deps.productAnalytics?.host ?? null,
analytics_key: app.site_key,
},
};
}
/** The Scribase Analytics tab: one project's numbers and the cap note (PY1.3). */
async function insightsFor(deps: BridgeDeps, body: Record<string, unknown>): Promise<BridgeResult> {
const scribaseOrgId = parseOrgRef(body);
if (!scribaseOrgId) return fail(400, "scribase_org_id is required");
const name = typeof body.app === "string" ? normaliseAppName(body.app) : "";
if (!name) return fail(400, "app is required");
const now = deps.now();
const who = await entitledOrg(deps.repo, scribaseOrgId, "analytics", now);
if ("status" in who) return who;
const app = await deps.repo.findAppByName(who.orgId, name);
if (!app) return { status: 200, body: { available: false, next: "Turn on analytics for this project first." } };
const product = deps.productAnalytics ? await deps.productAnalytics.firstEvent(who.orgId, app.id).catch(() => null) : null;
const first_product_event_at = product?.at ?? null;
if (!deps.insights) return { status: 200, body: { available: false, first_product_event_at, next: "Analytics is being set up on this deployment; events are counted meanwhile." } };
const summary = await deps.insights.summary(who.orgId, { app: app.id, days: 7 });
const row = summary.apps.find((a) => a.app_id === app.id);
const limit = access(await deps.repo.getEntitlement(who.orgId), now).eventsLimit;
const vitals = await vitalsFor(deps, who.orgId, app.id, now);
return {
status: 200,
body: {
...(vitals ? { vitals } : {}),
available: true,
app: app.name,
first_event_at: row?.first_event_at ?? null,
first_product_event_at,
visitors: row?.visitors ?? 0,
events: row?.events ?? 0,
month_events: row?.month_events ?? 0,
events_limit: limit,
funnel: summary.funnel.steps,
cap_note: capMessage(row?.month_events ?? 0, limit, now),
},
};
}
/**
* Page speed and deploy markers for the Analytics tab (PY3.3). Absent unless
* RAILYARD_REPLAY_LIVE is on; a vitals error never hides the rest of the tab.
*/
async function vitalsFor(deps: BridgeDeps, orgId: string, appId: string, now: Date) {
if (!deps.replayLive || !deps.insights?.vitals) return null;
const since = new Date(now.getTime() - 7 * 86_400_000);
const marks = markTimes(await deps.repo.listDeploys(orgId, appId), appId, since);
const v = await deps.insights.vitals(orgId, { app: appId, days: 7, marks: marks.map((d) => d.created_at) }).catch(() => null);
return v ? vitalsView(v, appId, marks) : null;
}
/** The org's custom domains for the Scribase Deploy tab (QY1.5): `{scribase_org_id, app?}`. */
async function domainsFor(deps: BridgeDeps, body: Record<string, unknown>): Promise<BridgeResult> {
const scribaseOrgId = parseOrgRef(body);
if (!scribaseOrgId) return fail(400, "scribase_org_id is required");
const app = typeof body.app === "string" ? normaliseAppName(body.app) : null;
if (app !== null && !/^[a-z0-9][a-z0-9-]{0,39}$/.test(app)) return fail(400, "app must be a project name (letters, numbers, dashes)");
const now = deps.now();
const who = await entitledOrg(deps.repo, scribaseOrgId, "deploy", now);
if ("status" in who) return who;
if (!deps.ship) return { status: 200, body: { available: false, domains: [], next: "Custom domains are being set up on this deployment." } };
const rows = await appDomains(deps.ship, who.orgId, app, now);
return {
status: 200,
body: {
available: true,
domains: rows.map((d) => ({ app: d.app, hostname: d.hostname, state: d.state, checked_at: d.checked_at, created_at: d.created_at })),
next: rows.length ? null : "Attach one from the app's folder: railyard domains add app.example.com",
},
};
}
const WEB_DAYS = new Set([1, 7, 30, 90]);
/**
* Product analytics for one Scribase project environment (QY1.2, A26):
* `{scribase_org_id, app, days?, with_server_key?}`. The server key goes to
* the Scribase control plane only, which keeps it as an environment secret.
*/
async function productAnalyticsFor(deps: BridgeDeps, body: Record<string, unknown>): Promise<BridgeResult> {
const scribaseOrgId = parseOrgRef(body);
if (!scribaseOrgId) return fail(400, "scribase_org_id is required");
const name = typeof body.app === "string" ? normaliseAppName(body.app) : "";
if (!/^[a-z0-9][a-z0-9-]{0,39}$/.test(name)) return fail(400, "app must be a project name (letters, numbers, dashes)");
const days = body.days === undefined ? 7 : body.days;
if (typeof days !== "number" || !WEB_DAYS.has(days)) return fail(400, "days must be 1, 7, 30 or 90");
const now = deps.now();
const who = await entitledOrg(deps.repo, scribaseOrgId, "analytics", now);
if ("status" in who) return who;
const app = await deps.repo.findAppByName(who.orgId, name);
if (!app) return { status: 200, body: { available: false, next: "Turn on analytics for this project first." } };
const pa = deps.productAnalytics;
if (!pa) return { status: 200, body: { available: false, next: "Product analytics is being set up on this deployment; page analytics keeps working meanwhile." } };
try {
const [first, web] = await Promise.all([pa.firstEvent(who.orgId, app.id), pa.web(who.orgId, app.id, days)]);
return {
status: 200,
body: {
available: true,
app: app.name,
host: pa.host,
key: app.site_key,
first_event: first,
web,
...(body.with_server_key === true ? { server_key: await pa.serverKey(app.id) } : {}),
},
};
} catch {
return { status: 200, body: { available: false, next: "Product analytics could not be reached. Try again shortly." } };
}
}
/** The AI gateway for one project environment (PY1.4, BYOK only). The key goes to the Scribase control plane only. */
async function aiFor(deps: BridgeDeps, body: Record<string, unknown>): Promise<BridgeResult> {
const scribaseOrgId = parseOrgRef(body);
if (!scribaseOrgId) return fail(400, "scribase_org_id is required");
const label = typeof body.project === "string" ? normaliseAppName(body.project) : "";
if (!label) return fail(400, "project is required");
const now = deps.now();
const who = await entitledOrg(deps.repo, scribaseOrgId, "ai", now);
if ("status" in who) return who;
const live = (await deps.repo.listAiKeys(who.orgId)).filter((k) => k.label === label && !k.revoked_at);
let key: string | null = null;
if (live.length === 0 || body.rotate === true) {
for (const k of live) await deps.repo.revokeAiKey(who.orgId, k.id, now.toISOString());
key = (await issueAiKey(deps.repo, who.orgId, label)).token;
}
const connect = await issueConnectToken(deps.repo, who.orgId, now);
const providers = (await deps.repo.listAiCredentials(who.orgId)).map((c) => ({ provider: c.provider, hint: c.key_hint }));
return {
status: 200,
body: { key, gateway_url: `${deps.consoleUrl}/api/v1/ai`, connect_url: `${deps.consoleUrl}/connect/ai?t=${connect}`, providers },
};
}
/** The AI tab: keys (no secrets), caps, today's and this month's tokens, recent calls (PY1.4). */
async function aiUsageFor(deps: BridgeDeps, body: Record<string, unknown>): Promise<BridgeResult> {
const scribaseOrgId = parseOrgRef(body);
if (!scribaseOrgId) return fail(400, "scribase_org_id is required");
const label = typeof body.project === "string" ? normaliseAppName(body.project) : "";
const now = deps.now();
const who = await entitledOrg(deps.repo, scribaseOrgId, "ai", now);
if ("status" in who) return who;
const keys = (await deps.repo.listAiKeys(who.orgId)).filter((k) => !k.revoked_at && (!label || k.label === label));
const day = now.toISOString().slice(0, 10);
const month = `${now.toISOString().slice(0, 7)}-01`;
const rows = await Promise.all(
keys.map(async (k) => ({
id: k.id,
label: k.label,
daily_token_cap: k.daily_token_cap,
monthly_token_cap: k.monthly_token_cap,
tokens_today: await deps.repo.aiTokensSince(k.id, day),
tokens_month: await deps.repo.aiTokensSince(k.id, month),
})),
);
const traces = await deps.repo.listAiTraces(keys.map((k) => k.id), 50);
const providers = (await deps.repo.listAiCredentials(who.orgId)).map((c) => ({ provider: c.provider, hint: c.key_hint, updated_at: c.updated_at }));
return { status: 200, body: { keys: rows, providers, traces } };
}
/**
* The flags of one Scribase project environment or branch (PY2.1):
* `{scribase_org_id, app, env, copy_from?, set?}`. Creates the environment on
* first use (a branch starts with `copy_from`'s flags), applies `set` when
* given, and answers the public client key, the read URL and the flags.
*/
async function flagsFor(deps: BridgeDeps, body: Record<string, unknown>): Promise<BridgeResult> {
const scribaseOrgId = parseOrgRef(body);
if (!scribaseOrgId) return fail(400, "scribase_org_id is required");
const app = typeof body.app === "string" ? normaliseAppName(body.app) : "";
if (!/^[a-z0-9][a-z0-9-]{0,39}$/.test(app)) return fail(400, "app must be a project name (letters, numbers, dashes)");
if (typeof body.env !== "string") return fail(400, "env is required");
const copyFrom = typeof body.copy_from === "string" ? body.copy_from : null;
const now = deps.now();
const who = await entitledOrg(deps.repo, scribaseOrgId, "flags", now);
if ("status" in who) return who;
if (!deps.flags) return fail(503, "Flags are being set up on this deployment. Nothing was changed.");
try {
const { env, created } = await ensureEnv(deps.flags, { orgId: who.orgId, orgName: scribaseOrgId, app, env: body.env, copyFrom }, now);
if (body.set !== undefined) await setFlag(deps.flags, env, body.set, `scribase:${scribaseOrgId}`, now);
return {
status: 200,
body: {
app: env.app,
env: env.env,
created,
client_key: env.client_key,
flags_url: `${deps.consoleUrl}/api/v1/flags/client`,
flags: await listFlags(deps.flags, env),
first_read_at: env.first_read_at,
},
};
} catch (e) {
if (e instanceof FlagsError) return fail(e.status, e.message);
throw e;
}
}
/**
* Uptime for one Scribase project (PY2.2): `{scribase_org_id, app, url?,
* name?, owner_email?}`. With a URL (or, without one, the app's latest live
* deploy) it adds a check; it always answers the app's checks with their
* state and public status page.
*/
async function uptimeFor(deps: BridgeDeps, body: Record<string, unknown>): Promise<BridgeResult> {
const scribaseOrgId = parseOrgRef(body);
if (!scribaseOrgId) return fail(400, "scribase_org_id is required");
const app = typeof body.app === "string" ? normaliseAppName(body.app) : "";
if (!/^[a-z0-9][a-z0-9-]{0,39}$/.test(app)) return fail(400, "app must be a project name (letters, numbers, dashes)");
const now = deps.now();
const who = await entitledOrg(deps.repo, scribaseOrgId, "uptime", now);
if ("status" in who) return who;
if (!deps.watch || !deps.watch.live) return fail(503, "This slot is arriving (PY2.2). Nothing was changed.");
const ownerEmail = typeof body.owner_email === "string" && body.owner_email.length <= 254 ? body.owner_email : null;
let url = typeof body.url === "string" && body.url.trim() ? body.url.trim() : null;
if (!url) {
const railyardApp = await deps.repo.findAppByName(who.orgId, app);
const live = railyardApp ? (await deps.repo.listDeploys(who.orgId, railyardApp.id)).find((d) => d.status === "succeeded") : undefined;
url = live?.url ?? null;
}
try {
const before = (await deps.watch.store.listChecks(who.orgId)).length;
if (url) await createCheck(deps.watch, { orgId: who.orgId, app, name: body.name, url, ownerEmail });
const checks = await listWithState(deps.watch, who.orgId, app);
if (checks.length === 0) return fail(400, "Give the https address of your app to check, or deploy it first.");
const created = (await deps.watch.store.listChecks(who.orgId)).length > before;
return { status: 200, body: { app, created, checks } };
} catch (e) {
if (e instanceof WatchError) return fail(e.status, e.message);
throw e;
}
}
export type BridgeRoute = "orgs" | "claims" | "proof" | "deploys" | "sites" | "insights" | "ai" | "ai_usage" | "flags" | "uptime" | "product_analytics" | "domains";
/**
* The route a signed message id names (P-Y1). Scribase sends
* `webhook-id: msg_<route>_<24 hex>`; the id is inside the signed content, so
* a signature made for one route never verifies on another.
*/
export function routeOfId(id: string | null): string | null {
const m = /^msg_([a-z_]{2,20})_([0-9a-f]{24})$/.exec(id ?? "");
return m ? m[1] : null;
}
/** Verify, refuse replays, parse, dispatch. Framework-free so the routes stay three lines. */
export async function handleBridge(deps: BridgeDeps, route: BridgeRoute, headers: WebhookHeaders, raw: string): Promise<BridgeResult> {
const now = deps.now();
if (!(await verify(deps.secret, headers, raw, Math.floor(now.getTime() / 1000)))) return fail(401, "invalid signature");
const named = routeOfId(headers.id);
if (named !== route && !(named === null && deps.acceptLegacy)) return fail(401, "the signed message was made for another route");
let body: unknown;
try {
body = JSON.parse(raw);
} catch {
return fail(400, "body must be JSON");
}
if (!body || typeof body !== "object" || Array.isArray(body)) return fail(400, "body must be a JSON object");
if (!(await deps.repo.recordBridgeMessage(`scribase:${headers.id}`))) return fail(409, "this message was already processed");
const b = body as Record<string, unknown>;
switch (route) {
case "orgs": {
const input = parseSync(b, now.getTime(), deps.acceptLegacy === true);
return typeof input === "string" ? fail(400, input) : syncOrg(deps.repo, input, now, deps.sites);
}
case "claims":
return issueClaim(deps, b);
case "proof":
return proofFor(deps, b);
case "deploys":
return deploysFor(deps, b);
case "sites":
return siteFor(deps, b);
case "insights":
return insightsFor(deps, b);
case "ai":
return aiFor(deps, b);
case "ai_usage":
return aiUsageFor(deps, b);
case "flags":
return flagsFor(deps, b);
case "uptime":
return uptimeFor(deps, b);
case "product_analytics":
return productAnalyticsFor(deps, b);
case "domains":
return domainsFor(deps, b);
}
}