Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ jobs:
- name: Install PostgreSQL 17 and jq
run: bash .github/scripts/install-postgresql17-ubuntu.sh
- name: Verify the console and gateway release check
run: python3 -B -m unittest discover -s scripts -p test_smoke_hosted_console.py
run: |
python3 -B -m unittest discover -s scripts -p test_smoke_hosted_console.py
node --test deploy/cloudflare/gateway-runtime.test.mjs deploy/cloudflare/production-profile.test.mjs
- name: Install Rust and verify PostgreSQL tools
run: |
rustup show
Expand Down
80 changes: 62 additions & 18 deletions .github/workflows/cloudflare-production.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,20 @@ on:
description: Digest-pinned TokenCraft gateway image in the Storyteller registry
required: true
type: string
fal_pilot:
description: Enable Storyteller-funded FLUX.1 schnell for the fal pilot
type: boolean
default: false
artcraft_inference:
description: Enable ArtCraft model presets using customer fal and Kinovi keys
type: boolean
default: false
gateway_revision:
description: Full source revision of the verified gateway image for a console-only release
required: false
type: string
inference_profile:
description: Keep the active profile, or explicitly select which inference routes to enable
type: choice
default: preserve
options:
- preserve
- none
- fal
- artcraft
- both

permissions:
contents: read
Expand All @@ -33,8 +39,7 @@ jobs:
PRODUCTION_ORIGIN: https://tokencraft-console.brandon-396.workers.dev
WRANGLER_VERSION: 4.170.0
WRANGLER_SEND_METRICS: "false"
TOKENCRAFT_PROVIDER_PILOT: ${{ inputs.fal_pilot }}
TOKENCRAFT_ARTCRAFT_INFERENCE: ${{ inputs.artcraft_inference }}
TOKENCRAFT_GATEWAY_SOURCE_REVISION: ${{ inputs.gateway_revision || github.sha }}
steps:
- uses: actions/checkout@v4
with:
Expand All @@ -44,6 +49,23 @@ jobs:
node-version: "22"
cache: npm
cache-dependency-path: frontend/package-lock.json
- name: Resolve the inference profile
shell: bash
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
INFERENCE_PROFILE: ${{ inputs.inference_profile }}
run: |
set -euo pipefail
test -n "$CLOUDFLARE_API_TOKEN"
if [[ "$INFERENCE_PROFILE" == preserve ]]; then
version=$(npx --yes "wrangler@$WRANGLER_VERSION" deployments list --name tokencraft-console --json |
node deploy/cloudflare/production-profile.mjs active-version)
settings=$(npx --offline --yes "wrangler@$WRANGLER_VERSION" versions view "$version" --name tokencraft-console --json |
node deploy/cloudflare/production-profile.mjs preserve)
printf 'TOKENCRAFT_EXPECTED_WORKER_VERSION=%s\n%s\n' "$version" "$settings" >> "$GITHUB_ENV"
else
node deploy/cloudflare/production-profile.mjs "$INFERENCE_PROFILE" >> "$GITHUB_ENV"
fi
- name: Build and validate the production package
env:
TOKENCRAFT_SOURCE_REVISION: ${{ github.sha }}
Expand All @@ -52,10 +74,15 @@ jobs:
VITE_TOKENCRAFT_STATIC_PREVIEW: "false"
GATEWAY_IMAGE: ${{ inputs.gateway_image }}
run: |
[[ "$TOKENCRAFT_GATEWAY_SOURCE_REVISION" =~ ^[a-f0-9]{40}$ ]]
if [[ "$TOKENCRAFT_GATEWAY_SOURCE_REVISION" != "$GITHUB_SHA" ]]; then
git fetch --no-tags --depth=1 origin "$TOKENCRAFT_GATEWAY_SOURCE_REVISION"
fi
npm --prefix frontend ci --ignore-scripts
npm --prefix frontend run build
node scripts/console_security_headers.mjs --cloudflare > frontend/dist/_headers
node deploy/cloudflare/production-config.mjs "$GATEWAY_IMAGE" "$GITHUB_SHA" > "$RUNNER_TEMP/wrangler.json"
node deploy/cloudflare/production-config.mjs "$GATEWAY_IMAGE" "$GITHUB_SHA" \
"$TOKENCRAFT_GATEWAY_SOURCE_REVISION" > "$RUNNER_TEMP/wrangler.json"
npx --yes "wrangler@$WRANGLER_VERSION" deploy --config "$RUNNER_TEMP/wrangler.json" --dry-run
- name: Publish and verify the production release
env:
Expand All @@ -67,16 +94,33 @@ jobs:
remote_main=$(git ls-remote --exit-code origin refs/heads/main)
read -r revision _ <<< "$remote_main"
test "$revision" = "$GITHUB_SHA"
npx --offline --yes "wrangler@$WRANGLER_VERSION" secret list --format json --config "$RUNNER_TEMP/wrangler.json" |
if ! npx --offline --yes "wrangler@$WRANGLER_VERSION" secret list --format json --config "$RUNNER_TEMP/wrangler.json" |
jq -e --arg pilot "$TOKENCRAFT_PROVIDER_PILOT" --arg artcraft "$TOKENCRAFT_ARTCRAFT_INFERENCE" '
any(.[]; .name == "TOKENCRAFT_ARTCRAFT_CLIENT_SECRET") and
($pilot != "true" or any(.[]; .name == "FAL_KEY" and .type == "secret_text")) and
($artcraft != "true" or any(.[]; .name == "TOKENCRAFT_PROVIDER_CREDENTIAL_KEY" and .type == "secret_text"))' >/dev/null
npx --offline --yes "wrangler@$WRANGLER_VERSION" deploy \
(["DATABASE_URL", "SESSION_SECRET", "TOKENCRAFT_DEMO_PAYLOAD_KEY", "TOKENCRAFT_ARTCRAFT_CLIENT_SECRET"] +
(if $pilot == "true" then ["FAL_KEY"] else [] end) +
(if $artcraft == "true" then ["TOKENCRAFT_PROVIDER_CREDENTIAL_KEY"] else [] end)) as $required |
($required - [.[] | select(.type == "secret_text") | .name]) == []' >/dev/null; then
echo '::error::Unable to verify all required encrypted Worker secrets for the selected profile.'
exit 1
fi
if [[ -n "${TOKENCRAFT_EXPECTED_WORKER_VERSION:-}" ]]; then
version=$(npx --offline --yes "wrangler@$WRANGLER_VERSION" deployments list --config "$RUNNER_TEMP/wrangler.json" --json |
node deploy/cloudflare/production-profile.mjs active-version)
if [[ "$version" != "$TOKENCRAFT_EXPECTED_WORKER_VERSION" ]]; then
echo '::error::The active Worker changed during the build. Dispatch the release again to preserve its current settings.'
exit 1
fi
fi
# Wrangler's dashboard diff can contain plaintext variable values.
WRANGLER_LOG=error WRANGLER_OUTPUT_FILE_PATH="$RUNNER_TEMP/production-deploy.jsonl" \
npx --offline --yes "wrangler@$WRANGLER_VERSION" deploy \
--config "$RUNNER_TEMP/wrangler.json" --message "TokenCraft $GITHUB_SHA"
jq -r 'select(.type == "deploy") | "Uploaded Worker version \(.version_id)"' "$RUNNER_TEMP/production-deploy.jsonl"
for attempt in {1..12}; do
if curl -fsS --max-time 35 -H 'Accept: application/json' "$PRODUCTION_ORIGIN/ready" |
jq -e '.ready == true' >/dev/null; then
if curl -fsS --max-time 55 -D "$RUNNER_TEMP/production-ready.headers" "$PRODUCTION_ORIGIN/ready" |
jq -e '.ready == true' >/dev/null &&
awk -v revision="$TOKENCRAFT_GATEWAY_SOURCE_REVISION" 'tolower($1) == "tokencraft-source-revision:" {sub(/\r$/, "", $2); if ($2 == revision) found = 1} END {exit !found}' \
"$RUNNER_TEMP/production-ready.headers"; then
bash scripts/smoke_hosted_console.sh "$PRODUCTION_ORIGIN" "$PRODUCTION_ORIGIN" \
"$GITHUB_SHA" frontend/dist/release.json
curl -fsS --max-time 15 "$PRODUCTION_ORIGIN/v1/catalog/offers" |
Expand Down
71 changes: 71 additions & 0 deletions deploy/cloudflare/gateway-runtime.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
export const gatewayPort = 4000;
export const journalHost = "tokencraft-provider-state.invalid";

export function gatewayRuntime(env) {
const { DATABASE_URL, SESSION_SECRET, TOKENCRAFT_DEMO_PAYLOAD_KEY, CONSOLE_ORIGIN } = env;
const catalog = env.TOKENCRAFT_PROVIDER_CATALOG;
const artcraft = env.TOKENCRAFT_ARTCRAFT_INFERENCE;
const usesConnectors = Boolean(catalog || artcraft);
if (!DATABASE_URL || !SESSION_SECRET || !TOKENCRAFT_DEMO_PAYLOAD_KEY || !CONSOLE_ORIGIN) {
throw new Error("TokenCraft gateway settings are missing");
}
if (catalog && !env.FAL_KEY?.trim()) throw new Error("fal Worker secret is missing");
if (artcraft && !env.TOKENCRAFT_PROVIDER_CREDENTIAL_KEY) {
throw new Error("TokenCraft provider credential key is missing");
}
return {
usesConnectors,
entrypoint: usesConnectors ? ["/usr/local/bin/node", "/opt/tokencraft/provider-pilot.mjs"] : [
"/bin/sh", "-ec",
'umask 077; printf \'%s\\n\' \'{"version":1,"offers":[]}\' > "$TOKENCRAFT_CORE_CATALOG"; exec /usr/local/bin/api-gateway',
],
processEnv: {
FOUNDATION_ENV: "production",
API_GATEWAY_PORT: String(gatewayPort),
TOKENCRAFT_LISTEN_IP: "0.0.0.0",
TOKENCRAFT_PROCESS_ROLE: "combined",
TOKENCRAFT_CORE_CATALOG: "/tmp/tokencraft-catalog.json",
APP_BASE_URL: CONSOLE_ORIGIN,
COOKIE_SECURE: "true",
DATABASE_URL,
SESSION_SECRET,
TOKENCRAFT_DEMO_PAYLOAD_KEY,
...(usesConnectors && { TOKENCRAFT_QUEUE_STATE_ORIGIN: `http://${journalHost}` }),
...(catalog && { FAL_KEY: env.FAL_KEY, TOKENCRAFT_PROVIDER_CATALOG: catalog }),
...(artcraft && {
TOKENCRAFT_ARTCRAFT_INFERENCE: artcraft,
TOKENCRAFT_PROVIDER_CREDENTIAL_KEY: env.TOKENCRAFT_PROVIDER_CREDENTIAL_KEY,
}),
...(env.TOKENCRAFT_ARTCRAFT_CLIENT_SECRET && {
TOKENCRAFT_ARTCRAFT_ISSUER: env.TOKENCRAFT_ARTCRAFT_ISSUER,
TOKENCRAFT_ARTCRAFT_CLIENT_ID: env.TOKENCRAFT_ARTCRAFT_CLIENT_ID,
TOKENCRAFT_ARTCRAFT_CLIENT_SECRET: env.TOKENCRAFT_ARTCRAFT_CLIENT_SECRET,
}),
},
};
}

const names = new WeakMap();

export function gatewayName(env) {
// Bindings are immutable within a Worker version. Share cold computation within an isolate.
if (!names.has(env)) names.set(env, nameForRuntime(env));
return names.get(env);
}

async function nameForRuntime(env) {
const runtime = gatewayRuntime(env);
if (!env.TOKENCRAFT_GATEWAY_IMAGE || !env.SOURCE_REVISION) {
throw new Error("TokenCraft gateway release identity is missing");
}
// Keep secret values and unkeyed fingerprints out of the visible instance name.
const encoder = new TextEncoder();
const key = await crypto.subtle.importKey("raw", encoder.encode(env.SESSION_SECRET),
{ name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
const identity = encoder.encode(JSON.stringify([
"tokencraft/cloudflare-gateway/v1", env.SOURCE_REVISION, env.TOKENCRAFT_GATEWAY_IMAGE, runtime,
]));
const signature = await crypto.subtle.sign("HMAC", key, identity);
const digest = Array.from(new Uint8Array(signature, 0, 16), (byte) => byte.toString(16).padStart(2, "0")).join("");
return `gateway-${digest}`;
}
47 changes: 47 additions & 0 deletions deploy/cloudflare/gateway-runtime.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { gatewayName, gatewayRuntime } from "./gateway-runtime.mjs";

const runtime = {
CONSOLE_ORIGIN: "https://console.example.test",
DATABASE_URL: "postgres://runtime:fictitious@database.example.test/tokencraft?sslmode=verify-full",
SESSION_SECRET: "fixture-session-secret",
TOKENCRAFT_DEMO_PAYLOAD_KEY: "fixture-payload-key",
SOURCE_REVISION: "a".repeat(40),
TOKENCRAFT_GATEWAY_IMAGE: `registry.example.test/gateway@sha256:${"b".repeat(64)}`,
TOKENCRAFT_PROVIDER_CATALOG: '{"version":1,"offers":[{"id":"fal_flux_schnell"}]}',
TOKENCRAFT_ARTCRAFT_INFERENCE: "true",
TOKENCRAFT_PROVIDER_CREDENTIAL_KEY: "fixture-vault-key",
FAL_KEY: "fixture-fal-key",
TOKENCRAFT_ARTCRAFT_ISSUER: "https://identity.example.test/realms/example",
TOKENCRAFT_ARTCRAFT_CLIENT_ID: "fixture-client",
TOKENCRAFT_ARTCRAFT_CLIENT_SECRET: "fixture-identity-secret",
};

test("a console-only release uses the same gateway name with inference enabled", async () => {
const previous = { ...runtime, WORKER_VERSION: { id: "old-worker" } };
const newer = { ...runtime, WORKER_VERSION: { id: "new-worker" } };
const name = await gatewayName(previous);
assert.match(name, /^gateway-[\da-f]{32}$/);
assert.equal(await gatewayName(newer), name);
});

test("changes to shipped runtime inputs select a fresh gateway", async () => {
const existing = await gatewayName(runtime);
for (const key of Object.keys(runtime)) {
assert.notEqual(await gatewayName({ ...runtime, [key]: `${runtime[key]}-changed` }), existing, key);
}
assert.notEqual(await gatewayName({ ...runtime, TOKENCRAFT_PROVIDER_CATALOG: undefined }), existing);
assert.notEqual(await gatewayName({ ...runtime, TOKENCRAFT_ARTCRAFT_INFERENCE: undefined }), existing);
});

test("inactive provider secrets stay out of the runtime and changing them never restarts it", async () => {
const inactive = { ...runtime, TOKENCRAFT_PROVIDER_CATALOG: undefined, TOKENCRAFT_ARTCRAFT_INFERENCE: undefined };
const { usesConnectors, processEnv } = gatewayRuntime(inactive);
assert.equal(usesConnectors, false);
assert.equal(Object.hasOwn(processEnv, "FAL_KEY"), false);
assert.equal(Object.hasOwn(processEnv, "TOKENCRAFT_PROVIDER_CREDENTIAL_KEY"), false);
assert.equal(await gatewayName(inactive), await gatewayName({ ...inactive, FAL_KEY: "other-fixture-key" }));
await assert.rejects(gatewayName({ ...runtime, FAL_KEY: undefined }), /fal Worker secret is missing/);
await assert.rejects(gatewayName({ ...runtime, TOKENCRAFT_GATEWAY_IMAGE: undefined }), /release identity is missing/);
});
2 changes: 1 addition & 1 deletion deploy/cloudflare/production-config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,12 @@ console.log(JSON.stringify({
vars: {
CONSOLE_ORIGIN: "https://tokencraft-console.brandon-396.workers.dev",
SOURCE_REVISION: gatewayRevision,
TOKENCRAFT_GATEWAY_IMAGE: image,
TOKENCRAFT_PROVIDER_CATALOG: catalog,
TOKENCRAFT_ARTCRAFT_INFERENCE: artcraft ? "true" : undefined,
TOKENCRAFT_ARTCRAFT_ISSUER: "https://auth.craft.ing/realms/artcraft",
TOKENCRAFT_ARTCRAFT_CLIENT_ID: "craft-tokencraft",
},
version_metadata: { binding: "WORKER_VERSION" },
triggers: { crons: connectors ? ["* * * * *"] : [] },
...(connectors && { observability: { enabled: true, logs: { invocation_logs: false } } }),
assets: {
Expand Down
66 changes: 66 additions & 0 deletions deploy/cloudflare/production-profile.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { readFileSync } from "node:fs";
import { pathToFileURL } from "node:url";

export function activeVersion(deployments) {
const active = [...deployments].sort((a, b) => Date.parse(b.created_on) - Date.parse(a.created_on))[0];
const version = active?.versions?.[0];
if (active?.versions?.length !== 1 || version?.percentage !== 100 ||
!/^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i.test(version.version_id)) {
throw new Error("Production must have a single active Worker version to preserve its inference profile");
}
return version.version_id;
}

export function productionProfile(mode, version) {
if (mode === "none") return { fal: false, artcraft: false };
if (mode === "fal") return { fal: true, artcraft: false };
if (mode === "artcraft") return { fal: false, artcraft: true };
if (mode === "both") return { fal: true, artcraft: true };
if (mode !== "preserve") throw new Error("Unknown Cloudflare inference profile");
const bindings = version?.resources?.bindings;
if (!Array.isArray(bindings)) throw new Error("The active Worker configuration is unavailable");
const binding = (name) => {
const matches = bindings.filter((item) => item.name === name);
if (matches.length > 1 || (matches.length &&
(matches[0].type !== "plain_text" || typeof matches[0].text !== "string"))) {
throw new Error("The active Worker has an unsupported inference configuration");
}
return matches[0]?.text;
};
const artcraft = binding("TOKENCRAFT_ARTCRAFT_INFERENCE");
const catalog = binding("TOKENCRAFT_PROVIDER_CATALOG");
if (artcraft !== undefined && artcraft !== "true") {
throw new Error("The active Worker has an unsupported ArtCraft inference setting");
}
if (catalog !== undefined) {
let managed;
try {
managed = JSON.parse(catalog);
} catch {
throw new Error("The active Worker has an invalid managed catalog");
}
if (managed?.version !== 1 || !Array.isArray(managed.offers) || managed.offers.length !== 1 ||
managed.offers[0]?.id !== "fal_flux_schnell") {
throw new Error("The active Worker has an unsupported managed catalog");
}
}
return { fal: catalog !== undefined, artcraft: artcraft === "true" };
}

if (process.argv[1] && pathToFileURL(process.argv[1]).href === import.meta.url) {
const mode = process.argv[2];
try {
if (mode === "active-version") {
console.log(activeVersion(JSON.parse(readFileSync(0, "utf8"))));
} else {
const version = mode === "preserve" ? JSON.parse(readFileSync(0, "utf8")) : undefined;
const profile = productionProfile(mode, version);
console.log(`TOKENCRAFT_PROVIDER_PILOT=${profile.fal}`);
console.log(`TOKENCRAFT_ARTCRAFT_INFERENCE=${profile.artcraft}`);
}
} catch (error) {
if (error instanceof SyntaxError) console.error("Cloudflare did not return valid release metadata");
else console.error(error.message);
process.exitCode = 1;
}
}
38 changes: 38 additions & 0 deletions deploy/cloudflare/production-profile.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { activeVersion, productionProfile } from "./production-profile.mjs";

const fal = { type: "plain_text", name: "TOKENCRAFT_PROVIDER_CATALOG",
text: JSON.stringify({ version: 1, offers: [{ id: "fal_flux_schnell" }] }) };
const artcraft = { type: "plain_text", name: "TOKENCRAFT_ARTCRAFT_INFERENCE", text: "true" };
const worker = (bindings) => ({ resources: { bindings } });

test("preserve retains the modes in the active configuration", () => {
assert.deepEqual(productionProfile("preserve", worker([fal, artcraft, { name: "FAL_KEY", type: "secret_text" }])),
productionProfile("both"));
assert.deepEqual(productionProfile("preserve", worker([fal])), productionProfile("fal"));
assert.deepEqual(productionProfile("preserve", worker([artcraft])), productionProfile("artcraft"));
assert.deepEqual(productionProfile("preserve", worker([])), productionProfile("none"));
});

test("an ambiguous configuration fails without exposing binding contents", () => {
assert.throws(() => productionProfile("preserve", worker([fal, fal])), /unsupported inference configuration/);
assert.throws(() => productionProfile("preserve", worker([{ ...artcraft, text: "false" }])),
/unsupported ArtCraft inference setting/);
assert.throws(() => productionProfile("preserve", worker([{ ...fal, text: "sensitive fixture" }])),
{ message: "The active Worker has an invalid managed catalog" });
assert.throws(() => productionProfile("preserve"), /configuration is unavailable/);
});

test("the latest deployment must send all traffic to exactly one version", () => {
const older = { created_on: "2026-01-01T00:00:00Z", versions: [
{ version_id: "87d75895-6657-4ea2-a4be-78044212a01b", percentage: 100 },
] };
const newer = { created_on: "2026-01-02T00:00:00Z", versions: [
{ version_id: "cbd57497-5eb8-4eed-8130-83b43886bbb3", percentage: 100 },
] };
assert.equal(activeVersion([newer, older]), newer.versions[0].version_id);
const split = { ...newer, versions: newer.versions.concat(older.versions) };
assert.throws(() => activeVersion([older, split]), /single active Worker version/);
assert.throws(() => activeVersion([]), /single active Worker version/);
});
Loading
Loading