From 26ac562adbb94320f513e32e5a88aad8424b4916 Mon Sep 17 00:00:00 2001 From: teaspoonai Date: Sat, 28 Nov 2026 20:07:45 -0600 Subject: [PATCH 01/22] Worker tests: share the D1 and R2 fakes Moves bucket(), d1() and manifest() out of index.test.mjs into worker/test/fakes.mjs (not a *.test.mjs, so the test glob skips it), for the license tests that follow. No test changes. Co-Authored-By: Claude Opus 5.5 --- worker/test/fakes.mjs | 53 ++++++++++++++++++++++++++++++++++++++ worker/test/index.test.mjs | 48 +--------------------------------- 2 files changed, 54 insertions(+), 47 deletions(-) create mode 100644 worker/test/fakes.mjs diff --git a/worker/test/fakes.mjs b/worker/test/fakes.mjs new file mode 100644 index 00000000..db812e90 --- /dev/null +++ b/worker/test/fakes.mjs @@ -0,0 +1,53 @@ +// The fakes of the download gate's bindings the tests share: R2 buckets in memory, and D1 as +// a real SQLite database (node:sqlite, Node 22.13+) built from migrations/, so the schema +// and every query run as written. Not a test file itself (the tests are *.test.mjs). +import { readFileSync, readdirSync } from "node:fs"; +import { DatabaseSync } from "node:sqlite"; + +export const MIGRATIONS = new URL("../migrations/", import.meta.url); +export const SHA = "33334d85d3f087da738131fcfe5ee6f862859c8130c4bbdd0aad441aff34effb"; + +export function bucket(objects) { + const meta = (key, o) => ({ + key, size: o.bytes.length, httpEtag: `"etag-${key}"`, + writeHttpMetadata(h) { // as R2's: the object's stored HTTP metadata + h.set("content-type", o.type ?? "application/octet-stream"); + if (o.cacheControl) h.set("cache-control", o.cacheControl); + }, + }); + return { + objects, + async head(key) { const o = objects.get(key); return o ? meta(key, o) : null; }, + async get(key, opts) { + const o = objects.get(key); + if (!o) return null; + const r = opts?.range; + const bytes = r ? o.bytes.slice(r.offset, r.offset + r.length) : o.bytes; + return { ...meta(key, o), range: r, body: bytes, + async json() { return JSON.parse(new TextDecoder().decode(o.bytes)); } }; + }, + }; +} + +export function d1() { + const db = new DatabaseSync(":memory:"); + for (const f of readdirSync(MIGRATIONS).filter((n) => n.endsWith(".sql")).sort()) { + db.exec(readFileSync(new URL(f, MIGRATIONS), "utf8")); + } + return { + db, + prepare(sql) { + let args = []; + const stmt = { + bind(...a) { args = a; return stmt; }, + async run() { db.prepare(sql).run(...args); return { success: true }; }, + async first() { return db.prepare(sql).get(...args) ?? null; }, + }; + return stmt; + }, + }; +} + +export function manifest(version = "1.0", sha = SHA) { + return { bytes: new TextEncoder().encode(JSON.stringify({ engine: { eula: { version, sha256: sha } } })) }; +} diff --git a/worker/test/index.test.mjs b/worker/test/index.test.mjs index 16f35c6e..ab66e803 100644 --- a/worker/test/index.test.mjs +++ b/worker/test/index.test.mjs @@ -8,57 +8,11 @@ import assert from "node:assert/strict"; import { readFileSync, readdirSync } from "node:fs"; import { DatabaseSync } from "node:sqlite"; import worker, { MAKER_PER_BOX_DAY, expire, makeToken, parseRange, resetCache, TOKEN_TTL_SECS } from "../src/index.js"; +import { MIGRATIONS, SHA, bucket, d1, manifest } from "./fakes.mjs"; -const MIGRATIONS = new URL("../migrations/", import.meta.url); -const SHA = "33334d85d3f087da738131fcfe5ee6f862859c8130c4bbdd0aad441aff34effb"; const ENGINE = "dl/engine/teaport-engine-1.6-l4t38-cu13"; const BYTES = new TextEncoder().encode("0123456789abcdefghij"); // 20 bytes -function bucket(objects) { - const meta = (key, o) => ({ - key, size: o.bytes.length, httpEtag: `"etag-${key}"`, - writeHttpMetadata(h) { // as R2's: the object's stored HTTP metadata - h.set("content-type", o.type ?? "application/octet-stream"); - if (o.cacheControl) h.set("cache-control", o.cacheControl); - }, - }); - return { - objects, - async head(key) { const o = objects.get(key); return o ? meta(key, o) : null; }, - async get(key, opts) { - const o = objects.get(key); - if (!o) return null; - const r = opts?.range; - const bytes = r ? o.bytes.slice(r.offset, r.offset + r.length) : o.bytes; - return { ...meta(key, o), range: r, body: bytes, - async json() { return JSON.parse(new TextDecoder().decode(o.bytes)); } }; - }, - }; -} - -function d1() { - const db = new DatabaseSync(":memory:"); - for (const f of readdirSync(MIGRATIONS).filter((n) => n.endsWith(".sql")).sort()) { - db.exec(readFileSync(new URL(f, MIGRATIONS), "utf8")); - } - return { - db, - prepare(sql) { - let args = []; - const stmt = { - bind(...a) { args = a; return stmt; }, - async run() { db.prepare(sql).run(...args); return { success: true }; }, - async first() { return db.prepare(sql).get(...args) ?? null; }, - }; - return stmt; - }, - }; -} - -function manifest(version = "1.0", sha = SHA) { - return { bytes: new TextEncoder().encode(JSON.stringify({ engine: { eula: { version, sha256: sha } } })) }; -} - let env, waits; const ctx = { waitUntil(p) { waits.push(p); } }; From bbde3acf64591e5e52bd7ecebabc0685bd8e12aa Mon Sep 17 00:00:00 2001 From: teaspoonai Date: Sat, 28 Nov 2026 20:07:45 -0600 Subject: [PATCH 02/22] Worker: issue and renew engine license keys (#474) POST /api/license signs license.json ({payload, signature}) per the design's wire format: payload v=2, an SSHSIG blob (namespace teaport-license, sha512) over JCS(payload), made with WebCrypto Ed25519 (src/sshsig.js). - {acceptance_id, device}: a personal key for a year, with the acceptance id the installer's receipt holds, checked as /api/token checks it. Licensed acceptances are refused (licensed_use). At most 3 devices per normalized email hold an unexpired, unrevoked personal key (device_cap); a device asking again gets the same license_id, so it never counts twice. - {maker_id, device}: the appliance key of a live maker acceptance, no expiry; one per maker acceptance (a unique index), the same device gets it signed again, another is refused (maker_device). - {license_id, device}: a renewal keeping the license_id. Personal: another year (keeping its engine_major), the cap again. Appliance: the same terms under the current key, past MAKER_MAX_DAYS too. LICENSE_SIGNING_KEY (secret, PKCS#8 PEM) signs only if it is the key that LICENSE_PUBKEY (var, OpenSSH line labelled LICENSE_KID) names; otherwise 503 license_unavailable and nothing is read or written. LICENSE_PUBKEY ships empty, so this deploys before the key exists. Migration 0004 is additive: the licenses table, and an index on acceptances' normalized email for the cap. The retention cron deletes a personal key's row RETENTION_DAYS after it expired; appliance rows stay. Tests cover each path, the cap, the 503 cases, the migration, and interop with ssh-keygen -Y verify / -Y sign. Co-Authored-By: Claude Opus 5.5 --- worker/migrations/0004_licenses.sql | 38 +++ worker/src/index.js | 223 ++++++++++++- worker/src/sshsig.js | 180 +++++++++++ worker/test/license.test.mjs | 484 ++++++++++++++++++++++++++++ worker/wrangler.toml | 20 +- 5 files changed, 940 insertions(+), 5 deletions(-) create mode 100644 worker/migrations/0004_licenses.sql create mode 100644 worker/src/sshsig.js create mode 100644 worker/test/license.test.mjs diff --git a/worker/migrations/0004_licenses.sql b/worker/migrations/0004_licenses.sql new file mode 100644 index 00000000..e7fb7fea --- /dev/null +++ b/worker/migrations/0004_licenses.sql @@ -0,0 +1,38 @@ +-- teaport download gate: the engine license keys it signs (teaport#474). +-- Applied by .github/workflows/worker-deploy.yml before each deploy, never by hand from a branch. +-- Additive only: a new table and new indexes, so the Worker before it still runs against +-- this schema (a rollback), and nothing here needs one. +-- What each column holds, and how long it is kept: docs/engine-license-data.md. + +-- One row per license key (POST /api/license): its terms, the device it is bound to and +-- the record it was issued under. A renewal re-signs the same row (same license_id), so +-- revoking one id stops it for good, however often it was renewed. No email and no name: +-- the key file holds none, and this row reaches the person only through acceptance_id. +-- No foreign keys: D1 enforces them, and the retention cron (the Worker before this one +-- included) must go on deleting acceptances and maker acceptances a license names. +CREATE TABLE licenses ( + license_id TEXT PRIMARY KEY, -- "TPL-" + 20 random Crockford base32 characters + tier TEXT NOT NULL CHECK (tier IN ('personal', 'appliance', 'commercial')), -- commercial: recorded by hand, signed offline + device TEXT NOT NULL, -- tpdev2-<32 hex>, from `voxtral --device-id` + kid TEXT NOT NULL, -- the label of the key that signed it last + engine_major INTEGER NOT NULL, + issued_at INTEGER NOT NULL, -- Unix seconds, as signed + expires_at INTEGER, -- Unix seconds, as signed; personal only + acceptance_id TEXT, -- personal: the acceptance it was last issued under; appliance: its owner's, once linked (teaport#465) + maker_id TEXT, -- appliance: the maker acceptance it was issued under (one key each) + created_at TEXT NOT NULL, -- ISO 8601, UTC: first issued + signed_at TEXT NOT NULL, -- ISO 8601, UTC: last signed (an issue, a repeat or a renewal) + revoked_at TEXT, -- set by hand: no renewal, and (W2) on the revocation list + revoke_reason TEXT +); +-- One appliance key per maker acceptance, held by the database itself: two requests at once +-- cannot both write one. +CREATE UNIQUE INDEX licenses_maker ON licenses (maker_id) WHERE maker_id IS NOT NULL; +CREATE INDEX licenses_acceptance ON licenses (acceptance_id); -- the 3-device cap, access and erasure +CREATE INDEX licenses_device ON licenses (device); +CREATE INDEX licenses_expires ON licenses (tier, expires_at); -- the retention cron + +-- The 3-device cap counts a person's devices by their acceptances' email, lowercased and +-- trimmed, as SQLite's lower() and trim() do it (ASCII letters only): the Worker compares +-- it in SQL, so the address never reaches the Worker's code on this path. +CREATE INDEX acceptances_email_norm ON acceptances (lower(trim(email))); diff --git a/worker/src/index.js b/worker/src/index.js index f5de2323..ffc105ff 100644 --- a/worker/src/index.js +++ b/worker/src/index.js @@ -31,6 +31,18 @@ // gets tokens with it. One row each time (a box provisioned again gets // a new one); at most FACTORY_DAILY_MAX boxes, and MAKER_PER_BOX_DAY // records a box, in any 24 hours. +// POST /api/license {acceptance_id, device} | {maker_id, device} | {license_id, device} +// -> license.json, {payload, signature}: an engine license key +// (teaport#474), bound to the box's tpdev2 device id (`voxtral +// --device-id`), signed as an SSH signature with LICENSE_SIGNING_KEY +// (src/sshsig.js). With the acceptance id from the box's receipt, a +// personal key for a year, on at most PERSONAL_DEVICES devices per +// email address (a licensed acceptance's key comes with its license, +// by hand). With a maker acceptance's id (a factory install, while it +// gets tokens), the box's appliance key, which never expires: one per +// maker acceptance, for one device. With a license id, a renewal: a +// personal key gets another year, an appliance key is signed again +// under the current key. Only ids are sent: never audio or transcripts. // GET|HEAD /dl/engine/*, /dl/models/* Authorization: Bearer . Streams the file // from teaport-engine-dist, with byte ranges (curl -C - resumes the // multi-GB models), and logs the download against the acceptance. @@ -58,10 +70,17 @@ // password manager, never in git, R2, a GitHub secret or a box (packaging/RELEASING.md, // "Worker secrets"). // +// LICENSE_SIGNING_KEY (a Worker secret, optional; unset, /api/license signs nothing) is the +// online license key, prod-online-2026-12: a PKCS#8 PEM. It signs only as the key that +// LICENSE_PUBKEY (a var: its OpenSSH public line, labelled LICENSE_KID) names, so a Worker +// deployed before the key exists, or with the wrong one, answers 503 and records nothing. +// // Bindings (wrangler.toml): DIST (teaport-engine-dist), PUBLIC (teaport-get, read for the // manifests), DB (D1, schema in migrations/), ACCEPT_LIMIT (rate limit per IP on /api/*, // optional). Tests: node --test worker/test/*.test.mjs (from the repo root; no dependencies). +import { b64, jcs, resetSigners, signer } from "./sshsig.js"; + export const TOKEN_TTL_SECS = 24 * 3600; const MANIFEST_TTL_MS = 60 * 1000; const CHANNELS = new Set(["stable", "beta"]); @@ -79,7 +98,7 @@ export const MAKER_PER_BOX_DAY = 10; const manifests = new Map(); // channel -> {at, eula: {version, sha256}} -export function resetCache() { manifests.clear(); } +export function resetCache() { manifests.clear(); resetSigners(); } function json(status, body, extra = {}) { return new Response(JSON.stringify(body), { @@ -407,6 +426,200 @@ async function factory(request, env, now) { return json(200, { acceptance_id: id, expires_at: new Date((now + makerTtl(env)) * 1000).toISOString() }); } +// --- /api/license: engine license keys ------------------------------------------------------- + +const CONTACT = "stefano@teaspoon.tech"; +const LICENSE_NS = "teaport-license"; +const LICENSE_ID = /^[A-Z0-9][A-Z0-9-]{3,39}$/; +const TPDEV2 = /^tpdev2-[0-9a-f]{32}$/; +const KID = /^[A-Za-z0-9._-]{1,64}$/; +const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"; +export const PERSONAL_DAYS = 365; +// The most devices one email address holds personal keys on (EULA §3.1/§3.2). +export const PERSONAL_DEVICES = 3; + +// "TPL-" and 20 characters of Crockford base32: 100 random bits (256 is a multiple of 32, +// so b & 31 is uniform). +function newLicenseId() { + return `TPL-${Array.from(crypto.getRandomValues(new Uint8Array(20)), (b) => CROCKFORD[b & 31]).join("")}`; +} + +// The signer, with the engine major version keys are issued for; null when either is not set +// up right (sshsig.js signer(): no secret, no public line, or a secret that is not its key). +async function licenseSigner(env) { + const major = Number(env.LICENSE_ENGINE_MAJOR); + if (!Number.isSafeInteger(major) || major < 1 || typeof env.LICENSE_KID !== "string" || !KID.test(env.LICENSE_KID)) { + return null; + } + const s = await signer(env.LICENSE_SIGNING_KEY, env.LICENSE_PUBKEY, env.LICENSE_KID); + return s && { kid: s.kid, sign: s.sign, major }; +} + +// The payload of a licenses row (v=2, the design's appendix), signed by . +function payloadOf(row, kid) { + const p = { v: 2, license_id: row.license_id, tier: row.tier, device: row.device, + issued_at: row.issued_at, engine_major: row.engine_major, kid }; + if (row.expires_at !== null && row.expires_at !== undefined) p.expires_at = row.expires_at; + return p; +} + +// license.json: the payload, and the base64 of the SSHSIG blob over JCS(payload). +async function licenseDoc(sig, payload) { + return { payload, signature: b64(await sig.sign(LICENSE_NS, enc.encode(jcs(payload)))) }; +} + +const iso = (now) => new Date(now * 1000).toISOString(); + +// A personal key for under acceptance : is the license it renews (or +// issues again), null for a new one. A year from now, signed, then recorded. The cap: the +// devices other than this one holding an unexpired, unrevoked personal key under the +// acceptance's email address (compared in SQL, normalized: the address never reaches this +// code). (Counted, then written: k requests at once can go k-1 over.) +async function signPersonal(env, sig, { id, acc, device, major }, now) { + const { n } = await env.DB.prepare( + `SELECT count(DISTINCT l.device) AS n FROM licenses l JOIN acceptances a ON a.id = l.acceptance_id + WHERE lower(trim(a.email)) = (SELECT lower(trim(email)) FROM acceptances WHERE id = ?1) + AND l.tier = 'personal' AND l.revoked_at IS NULL AND l.expires_at > ?2 AND l.device <> ?3`, + ).bind(acc, now, device).first(); + if (n >= PERSONAL_DEVICES) { + return fail(403, "device_cap", `this email address holds personal license keys on ${n} other devices, the most personal use allows (${PERSONAL_DEVICES}). A device drops out when its key expires; to free one sooner, or for a commercial license, contact ${CONTACT}. Teaspoon AI may decline any key request.`, + {}, { contact: CONTACT }); + } + const row = { license_id: id ?? newLicenseId(), tier: "personal", device, issued_at: now, + expires_at: now + PERSONAL_DAYS * 86400, engine_major: major }; + const doc = await licenseDoc(sig, payloadOf(row, sig.kid)); + if (id) { + await env.DB.prepare( + `UPDATE licenses SET acceptance_id = ?2, issued_at = ?3, expires_at = ?4, engine_major = ?5, kid = ?6, signed_at = ?7 + WHERE license_id = ?1`, + ).bind(id, acc, row.issued_at, row.expires_at, major, sig.kid, iso(now)).run(); + } else { + await env.DB.prepare( + `INSERT INTO licenses (license_id, tier, device, kid, engine_major, issued_at, expires_at, acceptance_id, + created_at, signed_at) VALUES (?1, 'personal', ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?8)`, + ).bind(row.license_id, device, sig.kid, major, row.issued_at, row.expires_at, acc, iso(now)).run(); + } + return json(200, doc); +} + +// An existing key signed again as it stands, under the current key (an appliance key: its +// terms never change; only kid follows the signing key). +async function resign(env, sig, row, now) { + const doc = await licenseDoc(sig, payloadOf(row, sig.kid)); + await env.DB.prepare("UPDATE licenses SET kid = ?2, signed_at = ?3 WHERE license_id = ?1") + .bind(row.license_id, sig.kid, iso(now)).run(); + return json(200, doc); +} + +const REVOKED_KEY = `this license key was revoked: contact ${CONTACT}`; + +// A personal key, with the acceptance id from the box's receipt: what /api/token takes, and +// as /api/token checks it (on record, not revoked, of the current license). A device that +// already holds an unrevoked personal key under the same email address gets that key again +// (same license_id, another year), so it never counts twice. +async function personalLicense(env, sig, id, device, now) { + if (MAKER_ID.test(id)) return fail(400, "bad_request", "acceptance_id: a factory install record's id goes in maker_id"); + if (!/^[A-Za-z0-9_-]{8,64}$/.test(id)) return fail(400, "bad_request", "acceptance_id: the id your acceptance was recorded under"); + const row = await env.DB.prepare( + "SELECT channel, eula_version, eula_sha256, use_type, revoked_at FROM acceptances WHERE id = ?1").bind(id).first(); + if (!row) return fail(404, "unknown_acceptance", "no acceptance is recorded under this id: accept the license again"); + if (row.revoked_at) return fail(403, "revoked", `this acceptance was revoked: contact ${CONTACT}`); + if (row.use_type !== "personal") { + return fail(403, "licensed_use", `a licensed acceptance's license key comes with its Teaspoon AI license, not from here: contact ${CONTACT}`, + {}, { contact: CONTACT }); + } + const eula = await currentEula(env, row.channel, now * 1000); + if (!eula) return fail(503, "no_license", `the ${row.channel} channel has no published license`); + if (row.eula_version !== eula.version || row.eula_sha256 !== eula.sha256) { + return fail(409, "eula_changed", `the license changed to version ${eula.version}: read and accept it`, {}, { eula_version: eula.version, eula_sha256: eula.sha256 }); + } + const held = await env.DB.prepare( + `SELECT l.license_id FROM licenses l JOIN acceptances a ON a.id = l.acceptance_id + WHERE l.device = ?2 AND l.tier = 'personal' AND l.revoked_at IS NULL + AND lower(trim(a.email)) = (SELECT lower(trim(email)) FROM acceptances WHERE id = ?1) + ORDER BY l.signed_at DESC LIMIT 1`, + ).bind(id, device).first(); + return signPersonal(env, sig, { id: held?.license_id ?? null, acc: id, device, major: sig.major }, now); +} + +// The appliance key of a factory install (teaport#464), with the maker acceptance's id from +// the box's receipt, while that gets tokens (makerState). One key per maker acceptance, held +// by migrations/0004's unique index: asked again for the same device, the same key, signed +// again; for another device, refused. +async function applianceLicense(env, sig, id, device, now) { + if (!MAKER_ID.test(id)) return fail(400, "bad_request", "maker_id: the factory install record's id, maker- and 24 characters"); + const maker = await env.DB.prepare("SELECT created_at, revoked_at FROM maker_acceptances WHERE id = ?1").bind(id).first(); + const st = makerState(env, maker, now); + if (st.refuse) return st.refuse; + const find = () => env.DB.prepare("SELECT * FROM licenses WHERE maker_id = ?1").bind(id).first(); + let row = await find(); + if (!row) { + const fresh = { license_id: newLicenseId(), tier: "appliance", device, issued_at: now, engine_major: sig.major }; + const doc = await licenseDoc(sig, payloadOf(fresh, sig.kid)); + await env.DB.prepare( + `INSERT OR IGNORE INTO licenses (license_id, tier, device, kid, engine_major, issued_at, maker_id, created_at, signed_at) + VALUES (?1, 'appliance', ?2, ?3, ?4, ?5, ?6, ?7, ?7)`, + ).bind(fresh.license_id, device, sig.kid, sig.major, now, id, iso(now)).run(); + row = await find(); + if (row?.license_id === fresh.license_id) return json(200, doc); + // Another request for this maker acceptance wrote its key first: answer as for that one. + if (!row) return fail(500, "internal", "the license key was not recorded: try again"); + } + if (row.device !== device) { + return fail(403, "maker_device", `this factory install record already has a license key, for another device: contact ${CONTACT}`); + } + if (row.revoked_at) return fail(403, "revoked", REVOKED_KEY); + return resign(env, sig, row, now); +} + +// A renewal, with the license id from the box's license.json and the device it is bound to. +// Either is on the box's key file, which only works on that device anyway: what a renewal +// returns is useful nowhere else. The key's record must still stand (not revoked; for a +// personal key, its acceptance on record and not revoked; the cap again, which an unexpired +// key passes, as its device is already counted). The license id stays: a revocation reaches +// every renewal of it. +async function renewLicense(env, sig, id, device, now) { + if (!LICENSE_ID.test(id)) return fail(400, "bad_request", "license_id: the license_id of this box's license.json"); + const row = await env.DB.prepare("SELECT * FROM licenses WHERE license_id = ?1").bind(id).first(); + if (!row) return fail(404, "unknown_license", "no license key is recorded under this id: run the installer again to get one"); + if (row.revoked_at) return fail(403, "revoked", REVOKED_KEY); + if (row.device !== device) return fail(403, "device_mismatch", "this license key is bound to another device"); + if (row.tier === "personal") { + const acc = await env.DB.prepare("SELECT revoked_at FROM acceptances WHERE id = ?1").bind(row.acceptance_id).first(); + if (!acc) return fail(404, "unknown_acceptance", "the acceptance this key was issued under is no longer on record: run the installer again to accept the license"); + if (acc.revoked_at) return fail(403, "revoked", `this acceptance was revoked: contact ${CONTACT}`); + // The major version it was issued for: a renewal never moves a box to keys its engine refuses. + return signPersonal(env, sig, { id, acc: row.acceptance_id, device, major: row.engine_major }, now); + } + if (row.tier === "appliance") { + // Not the maker acceptance's MAKER_MAX_DAYS: an appliance key outlives its factory record. + const maker = row.maker_id + ? await env.DB.prepare("SELECT revoked_at FROM maker_acceptances WHERE id = ?1").bind(row.maker_id).first() : null; + if (maker?.revoked_at) return fail(403, "revoked", `this box's factory install record was revoked: contact ${CONTACT}`); + return resign(env, sig, row, now); + } + return fail(403, "commercial", `a commercial license key is renewed by Teaspoon AI, not here: contact ${CONTACT}`, {}, { contact: CONTACT }); +} + +async function license(request, env, now) { + const b = await body(request); + if (!b) return fail(400, "bad_request", "expected a JSON object of at most 4 KB"); + const given = ["acceptance_id", "maker_id", "license_id"].filter((k) => b[k] !== undefined); + if (given.length !== 1 || typeof b[given[0]] !== "string") { + return fail(400, "bad_request", "one of acceptance_id (personal use), maker_id (a factory install) or license_id (a renewal), with device"); + } + if (typeof b.device !== "string" || !TPDEV2.test(b.device)) { + return fail(400, "bad_request", "device: this box's, from `voxtral --device-id`: tpdev2- and 32 lowercase hex digits"); + } + // Before any lookup or write: unable to sign, it records nothing. + const sig = await licenseSigner(env); + if (!sig) return fail(503, "license_unavailable", "the license server cannot issue license keys now: try again later"); + const id = b[given[0]]; + if (given[0] === "acceptance_id") return personalLicense(env, sig, id, b.device, now); + if (given[0] === "maker_id") return applianceLicense(env, sig, id, b.device, now); + return renewLicense(env, sig, id, b.device, now); +} + // --- /dl ----------------------------------------------------------------------------------- const DENIED = "This file downloads only after the Teaport Engine License is accepted: install with " @@ -503,13 +716,14 @@ export default { const url = new URL(request.url); const now = Math.floor(Date.now() / 1000); const path = url.pathname; - if (path === "/api/accept" || path === "/api/token" || path === "/api/factory") { + if (path === "/api/accept" || path === "/api/token" || path === "/api/factory" || path === "/api/license") { if (request.method !== "POST") return fail(405, "method_not_allowed", "POST only", { allow: "POST" }); if (env.ACCEPT_LIMIT) { const { success } = await env.ACCEPT_LIMIT.limit({ key: client(request).ip || "unknown" }); if (!success) return fail(429, "rate_limited", "too many requests: try again in a minute"); } if (path === "/api/factory") return factory(request, env, now); + if (path === "/api/license") return license(request, env, now); return path === "/api/accept" ? accept(request, env, now) : token(request, env, now); } if (path.startsWith("/dl/engine/") || path.startsWith("/dl/models/")) { @@ -545,4 +759,9 @@ export async function expire(env, now) { "DELETE FROM downloads WHERE acceptance_id IN (SELECT id FROM maker_acceptances WHERE created_at < ?1)", ).bind(cutoff).run(); await env.DB.prepare("DELETE FROM maker_acceptances WHERE created_at < ?1").bind(cutoff).run(); + // License keys (migrations/0004): a personal key's row once it has been expired that long. + // Appliance and commercial keys never expire, so their rows stay: a renewal needs one, and + // a revoked one must stay on the revocation list for as long as its key file can exist. + await env.DB.prepare("DELETE FROM licenses WHERE tier = 'personal' AND expires_at < ?1") + .bind(now - days * 86400).run(); } diff --git a/worker/src/sshsig.js b/worker/src/sshsig.js new file mode 100644 index 00000000..542d69f1 --- /dev/null +++ b/worker/src/sshsig.js @@ -0,0 +1,180 @@ +// Engine license signatures (teaport#474): JCS of a payload, and an SSH signature (SSHSIG, +// OpenSSH's PROTOCOL.sshsig) over it, made with WebCrypto Ed25519. What `ssh-keygen -Y sign +// -n ` makes over the same bytes, and what `ssh-keygen -Y verify` and the engine +// check (the wire format: the design's appendix, teaport-license-key-design.md). +// +// The signing key is LICENSE_SIGNING_KEY (a Worker secret): a PKCS#8 PEM, as `openssl +// genpkey -algorithm ed25519` writes it. LICENSE_PUBKEY (a var) is its OpenSSH public line, +// `ssh-ed25519 AAAA... `, the one the engine trusts under that label. The +// Worker signs only when the secret's key is the one the line names (signer()), so a +// Worker deployed before the key exists, or with the wrong one, signs nothing. + +const enc = new TextEncoder(); + +// --- JCS (RFC 8785) ------------------------------------------------------------------------ + +// JCS of , for the values a license payload holds: objects of strings and non-negative +// safe integers (and arrays of them, for the revocation list). Keys sorted by UTF-16 code +// units (what Array.prototype.sort compares), no whitespace, strings escaped as +// JSON.stringify escapes them (RFC 8785 3.2.2.2 is that). Anything else throws: a float, +// a negative, a boolean or null has no place in a payload, so none is ever signed. +export function jcs(v) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number") { + if (!Number.isSafeInteger(v) || v < 0 || Object.is(v, -0)) throw new TypeError(`JCS: not a non-negative integer: ${v}`); + return String(v); + } + if (Array.isArray(v)) return `[${v.map(jcs).join(",")}]`; + if (typeof v === "object" && v !== null) { + return `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${jcs(v[k])}`).join(",")}}`; + } + throw new TypeError(`JCS: not a payload value: ${typeof v}`); +} + +// --- SSH wire encoding --------------------------------------------------------------------- + +function concat(parts) { + const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0)); + let at = 0; + for (const p of parts) { out.set(p, at); at += p.length; } + return out; +} + +// An SSH "string": a uint32 big-endian length, then the bytes. +function sshString(bytes) { + if (typeof bytes === "string") bytes = enc.encode(bytes); + const out = new Uint8Array(4 + bytes.length); + new DataView(out.buffer).setUint32(0, bytes.length); + out.set(bytes, 4); + return out; +} + +// The strings of in order, or null when it is not exactly a run of strings. +function sshStrings(bytes, at = 0) { + const out = []; + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + while (at < bytes.length) { + if (at + 4 > bytes.length) return null; + const n = view.getUint32(at); + if (at + 4 + n > bytes.length) return null; + out.push(bytes.subarray(at + 4, at + 4 + n)); + at += 4 + n; + } + return out; +} + +const same = (a, b) => a.length === b.length && a.every((x, i) => x === b[i]); +const MAGIC = enc.encode("SSHSIG"); +const ED25519 = "ssh-ed25519"; + +// The public key blob of an Ed25519 key: string "ssh-ed25519", string <32 bytes>. +export function pubkeyBlob(raw) { + return concat([sshString(ED25519), sshString(raw)]); +} + +export function b64(bytes) { + let s = ""; + for (const b of bytes) s += String.fromCharCode(b); + return btoa(s); +} + +function unb64(s) { + return Uint8Array.from(atob(s), (c) => c.charCodeAt(0)); +} + +// The 32-byte key and label of an OpenSSH public line, `ssh-ed25519