diff --git a/docs/engine-license-data.md b/docs/engine-license-data.md index 7b1f0063..0d7496ce 100644 --- a/docs/engine-license-data.md +++ b/docs/engine-license-data.md @@ -3,12 +3,12 @@ Internal note (not published on the docs site). It exists so that the Teaport Engine License and a privacy notice can describe this processing accurately. If the code changes, change this note in the same PR. The code is `worker/src/index.js` (`accept()`, `token()`, -`factory()`, `download()`, `expire()`), `worker/migrations/`, and `install.sh` (`eula_gate`, -`eula_record`). +`factory()`, `license()` and the functions it calls, `download()`, `expire()`), +`worker/migrations/`, and `install.sh` (`eula_gate`, `eula_record`). ## Where -Three tables in the Cloudflare D1 database `teaport-gate`, in Teaspoon AI's Cloudflare +Five tables in the Cloudflare D1 database `teaport-gate`, in Teaspoon AI's Cloudflare account. The Worker `teaport-download-gate`, in front of get.teaspoon.tech's `/api/*`, `/dl/engine/*` and `/dl/models/*`, writes them: @@ -19,6 +19,11 @@ account. The Worker `teaport-download-gate`, in front of get.teaspoon.tech's `/a file that does not exist, writes none). A resumed download is several rows. - `maker_acceptances`: one row each time the factory station provisions a box (`POST /api/factory`). See "The factory's rows". +- `licenses`: one row per engine license key the Worker signs (`POST /api/license`, + teaport#474). See "License keys". +- `license_makers`: one row per maker acceptance that ever held an appliance key (issued + under it, or moved to it): its id, the key's `license_id` and when. Written by a trigger + with the key's own write, and never changed. ## What an acceptance row holds @@ -89,6 +94,105 @@ boxes it never built: packaging/RELEASING.md, "Worker secrets"). Lawful basis, i applies once they are linkable: the legitimate interest in those purposes (Art. 6(1)(f)); there is no contract with the owner behind them. +## License keys + +After the engine is downloaded, the box asks for its engine license key (`POST +/api/license`), and later renews it. The request carries ids only: the acceptance's `id` +(personal use) or the maker acceptance's (a box at the factory), or the key's +`license_id` (a renewal), and the box's `tpdev2` device id. Never audio, transcripts or +conversations, and no email address or name. The Worker answers with the key, +`license.json`, and records it: + +| Column of `licenses` | Content | Personal data? | +| --- | --- | --- | +| `license_id` | `TPL-` and 20 random characters. It is in the key file. | Pseudonymous identifier | +| `tier` | `personal` or `appliance` (`commercial`: recorded by hand) | No | +| `device` | The box's `tpdev2` id, from `voxtral --device-id`: a hash of its GPU's UUID and its Jetson module's serial. It is in the key file, which works on that device only. | Pseudonymous device identifier | +| `kid` | Which signing key signed it last, such as `prod-online-2026-12` | No | +| `engine_major` | The engine major version it is for | No | +| `issued_at`, `expires_at` | When it was signed, and (personal keys) when it expires, a year later. As in the key file. | Yes, with the rest | +| `acceptance_id` | A personal key: the acceptance it was last issued or renewed under. An appliance key: empty until its owner's acceptance is linked to it (teaport#465). | The link to the person | +| `maker_id` | An appliance key: the maker acceptance that holds it now (it moves when the box is provisioned again) | As "The factory's rows" | +| `first_maker_id` | An appliance key: the maker acceptance it was first issued under. A move never changes it; a leak's cleanup sorts keys by it. | As "The factory's rows" | +| `created_at`, `signed_at` | When it was first issued, and last signed (an issue, a repeat or a renewal) | Yes, with the rest | +| `revoked_at`, `revoke_reason` | Empty. Set only by hand, to revoke the key (no renewal; and the revocation list, once it exists). | No | +| `released_at` | Empty. Set only by hand, when the owner asks (by email) to free a personal key's device slot: the key no longer counts toward the cap or renews, and the device may get a new key. On a revoked row of any tier, it lifts the bar on the device. | No | + +A row holds no email address. The person behind a personal key is found through +`acceptance_id`, in `acceptances`; the 3-device cap compares the email addresses of those +acceptances inside the database (trimmed, ASCII letters lowercased), and the Worker's code never +reads them. A renewal signs the same row again: it keeps its `license_id`, and records +the new dates and `kid`. + +A personal key renews only while its acceptance is of the current license version, as a +new key is issued only then. After a license change, a renewal gets 409 `eula_changed` +(the same answer as the acceptance's own request), and nothing is written. The box keeps +the key it has, which runs until it expires and then for the engine's 30-day grace +(teaport#474 E2), while teaport asks for the new license to be accepted (I2). That new +acceptance gets the same key again (same `license_id`, another year), and renewals go on +from it. Appliance keys come with the box and renew whatever the license version (no +personal acceptance stands behind them; the owner's link, teaport#465, carries no version +yet). + +Revocations stick, as far as an email address that is not verified allows: +- **Revoking a key bars the device**, whatever the key's tier (`personal`, `appliance` or + `commercial`) and whatever the email address. While the device holds a revoked row that + is not released, it gets no new key and no renewal of any tier: no personal key under + whatever address anyone asks next (the same one written another way, a `+` variant, an + unrelated one), no renewal of another person's key on it, and no appliance key, new, + asked for again or renewed. So a box whose appliance key was revoked (a stolen + appliance, say) cannot switch to a personal key, nor a device whose personal key was + revoked to an appliance one. Releasing that row (`released_at`) lifts the bar; a box + that comes back to the factory after a revocation is released by staff before it is + provisioned again. +- **Revoking an acceptance** (`acceptances.revoked_at`) blocks the person: the personal keys + last issued under it no longer renew, and their devices get no key under that address, + even after the person accepts again. (Under another address they can, as for any new + person: the email address is not verified.) +- **Revoked keys still count** toward the address's 3-device cap until they expire, the + keys of a revoked acceptance too. Revoking for abuse leaves the person, under that + address, with what they already held, until it expires; accepting again starts no new + cap. +- **Freeing a device's slot** is `released_at`, not a revocation: the key no longer counts + or renews, and the device may get a new key. + +An appliance key goes to the first device that asks with a live maker acceptance's id +(design §6): the factory box, at its first boot. The id is on that box only, in its receipt, +for at most `MAKER_MAX_DAYS` (the seal removes it); whoever else held it in that time could +take the key for another device, and the factory box would then be refused +(`maker_device`), which shows. + +A box provisioned again gets a new maker acceptance, but keeps its key: when the new record +asks for a key from a device that holds a live appliance key (not revoked, not released) +under an older maker acceptance of the same box (the same `device_id`, its serial's hash), +that key moves to the new record, with the same `license_id`, its `maker_id` updated and +signed again. An older record already deleted by retention counts as the same box's. A +record for another serial never takes it (403 `maker_serial`, nothing written): otherwise a +leaked `FACTORY_TOKEN` and a box's `tpdev2` could move its key onto a made-up record, and +revoking that record would then stop the real box's renewals. A leaked `FACTORY_TOKEN` +still mints appliance keys for made-up boxes, and a made-up record for a box's own serial +(serials are guessable, "The factory's rows") can take its key. After a leak, the secret +is rotated and the suspect maker acceptances revoked first (no mint, move or renewal goes +on under a revoked one); then their keys are sorted, the made-up ones revoked and the real +ones given back to their boxes' own records (packaging/RELEASING.md, "Worker secrets", +`FACTORY_TOKEN`, "Cleaning up after a leak"). A box whose module or serial +was swapped needs staff: they release its old key (`released_at`), and the new record gets +a new one. It moves in one statement, so of +records asking at once the newest ends up with it, and it never moves back to an older one +(which gets 409 `maker_superseded`). A device with no live appliance key gets a new one. +A maker acceptance that ever held a key (`license_makers`) never issues or receives +another (403 `maker_spent`): a box provisioned again leaves its old record holding +nothing, and that record's id is still in the box's old receipt, which the box's agent can +read, so without this rule anyone with it could mint a second, perpetual key for other +hardware. A box whose key was released gets its next key under its next record. +The device bar above still holds: a key on a device with a revoked row moves nowhere. Nothing else about the box is sent or recorded, and the request's +IP address, country and user agent are not stored for it (Workers Logs may still keep +them, below). + +The key file, `license.json`, holds the same terms: `license_id`, `tier`, `device`, the +dates, `engine_major`, `kid`, and the signature. No email address and no name, so a key +file that leaks exposes no one; it traces back only through this table. + ## What is not stored No name, from the Worker deployed with migration `0002_drop_acceptance_name.sql`. Earlier @@ -109,7 +213,8 @@ an unverified typed name adds nothing to the email, the use and the accepted tex below); that copy is the owner's and never leaves the box. Also not stored: the box's hostname or local user, the manifest, the request bodies of downloads, and the -token itself (it is signed, not stored). A new token for an existing acceptance +token itself (it is signed, not stored); for a license key, the IP address, country and user +agent of the request. A new token for an existing acceptance (`POST /api/token`) writes no row; it only updates `last_token_at`. ## On the box @@ -122,6 +227,10 @@ Neither file leaves the box, apart from the `id`, which the box sends to get a n A box being installed at the factory has, instead, the receipt its factory agent wrote (the seal removes it before the box ships): `"method": "factory"` and the maker acceptance's `id`, nothing else: no license version, name or email, and no license text. +The engine license key is `/etc/teaport/license.json` (written by `install.sh`, +teaport#474): the key's terms and signature, as in "License keys", and no personal data +beyond its `license_id` and `device`. It leaves the box only as those two ids, in a +renewal. ## Who else sees it @@ -139,7 +248,8 @@ nothing else: no license version, name or email, and no license text. it say whether the request body is recorded. The Worker itself writes nothing to the logs (it has no `console.log`); the email (and, from an older `install.sh`, a name the Worker discards) travel only in the body of - `POST /api/accept`. Setting `invocation_logs = false` under `[observability.logs]` turns + `POST /api/accept`. The bodies of `POST /api/token` and `POST /api/license` carry an + acceptance's `id`, which gets download tokens, if the logs keep bodies. Setting `invocation_logs = false` under `[observability.logs]` turns the invocation logs off. ## How long @@ -156,6 +266,19 @@ nothing else: no license version, name or email, and no license text. The factory's rows follow the same period today. They prove no contract, so counsel may want a shorter one for them (a box's warranty, say); that would need a retention setting of their own. +- **License keys:** a personal key's row, `RETENTION_DAYS` (7 years) after it expired: + then the daily cron deletes it. While it is in force or renewing, it stays; a key whose + acceptance is deleted (by this cron; an erasure request keeps it, below) is no longer renewed, and its box asks + for acceptance again. So a key's row can outlive its acceptance by up to 8 years (the + acceptance goes 7 years after it was made, the key's row 7 years after the key expired): + it then names an acceptance that is gone, and holds only the device id, the dates and + the ids. Access and erasure find those rows by device (below). Appliance and commercial keys never expire, so their rows are kept + for as long as the key can be in use: a renewal needs the row, and a revoked key must + stay on the revocation list. They hold personal data only once linked to an owner + (teaport#465), or through the factory's rows. +- **`license_makers`:** kept for good. Its rows hold only ids and a time, and must + outlive the maker acceptances they name (deleted by retention), so a record's id can + never get a key again. - **Workers Logs:** Cloudflare's retention for the plan: 3 days on Workers Free, 7 days on Workers Paid (the same page). - **The box's copy:** until the box is wiped. It is the owner's own record. @@ -165,6 +288,9 @@ nothing else: no license version, name or email, and no license text. - **Purpose:** proof that this person accepted this exact license text, when, and for which use, and which files were downloaded under that acceptance. The record also lets Teaspoon AI enforce the license, including organizational use without a commercial license. The + license key rows record which keys were issued, to which device, under which acceptance: + they enforce the 3-device limit on personal use, let a key renew or be revoked, and + trace a key file back to its acceptance. The engine downloads only after acceptance, except the factory's install of Teaspoon AI's own boxes ("The factory's rows"). - **Lawful basis (if GDPR applies):** entering into and performing the license contract @@ -176,20 +302,38 @@ nothing else: no license version, name or email, and no license text. - **Access requests:** find the person's rows by `email`, and their downloads by those rows' `id`. For a box bought from Teaspoon AI, also compute its factory `device_id` from its serial (SHA-256 of `teaport-appliance:` plus the serial), then find its - `maker_acceptances` rows by that `device_id`, and their downloads by their `id`. Send the + `maker_acceptances` rows by that `device_id`, and their downloads by their `id`. + License keys, in two steps. (1) The `licenses` rows whose `acceptance_id` is one of the + person's acceptances (and, for a box from Teaspoon AI, whose `maker_id` is one of its + maker acceptances). (2) The rows that outlived their acceptance: the rows whose `device` + is a device from step 1, or one the person names (the `device` or `license_id` in their + box's `/etc/teaport/license.json`, or `voxtral --device-id`), and whose `acceptance_id` + is no longer in `acceptances` (or is empty). A row of that device whose acceptance is on + record and is someone else's (a box sold on) is that person's, not this one's. Send the person a copy of their rows. -- **Erasure requests:** the acceptance and download rows are **kept, and used only for the - license**. They are not deleted early. - - **While the license is in force** (the person's box still installs, updates or - downloads under that acceptance), the rows are needed to perform it (Art. 6(1)(b)), so - erasure under Art. 17(1) does not reach them. +- **Erasure requests:** the acceptance, download and license key rows found as above are + **kept, and used only for the license**. They are not deleted early. + - **While the license is in force** (a personal key unexpired or renewing, an appliance + or commercial key, which never expires, or downloads under the acceptance), the rows + are needed to perform it (Art. 6(1)(b)), so erasure under Art. 17(1) does not reach + them. - **After that,** they are kept to establish or defend legal claims (Art. 17(3)(e)), - until the 7-year retention above deletes them. + until their own retention above deletes them. A revoked key's row is kept while it + must stay on the revocation list. - **Restricted:** they are used for nothing but the license, read only to answer a - license question or a legal claim. Note the request, with the rows' `id`s, in the + license question or a legal claim. Note the request, with the rows' ids, in the record of privacy requests kept outside this repository, so later reads know. + - The request changes nothing about the license: the keys keep working and renewing. - Everything else the request covers is still deleted: support mail, any copy outside D1. -- **Ending the license** is a separate request from erasure. It stops further downloads - under the acceptance (set `revoked_at` on the person's acceptances). The rows themselves - stay, kept as above, until their retention ends. The privacy notice says this (§7). + - `license_makers` (ids and a time) and `link_secret_hash` (a hash) are not personal + data. +- **Ending the license** is a separate request from erasure: + - **Downloads:** set `revoked_at` on the person's acceptances. That stops further + downloads and, for their personal keys, renewal. + - **Personal keys:** release them (`released_at`). They renew no more, each works until + it expires plus the engine's grace period, and its device slot is freed. + - **An appliance:** unlink the owner (`acceptance_id = NULL` on its key). The key stays + with the box, which it belongs to. + - The rows themselves stay, kept as above, until their retention ends. The privacy + notice says this (§7). diff --git a/docs/src/content/docs/reference/licenses.md b/docs/src/content/docs/reference/licenses.md index 5db5fed6..4d0bfea8 100644 --- a/docs/src/content/docs/reference/licenses.md +++ b/docs/src/content/docs/reference/licenses.md @@ -43,7 +43,7 @@ The installer records your acceptance with Teaspoon AI, together with the licens To accept without the prompt, name the version you read: `--accept-eula=`, with the version the license's title names, and give `--email`, plus `--license-id` for licensed use. A bare `--accept-eula`, or another version, stops the installer. - + ## The LGPL libraries diff --git a/packaging/RELEASING.md b/packaging/RELEASING.md index ee781571..5183ae93 100644 --- a/packaging/RELEASING.md +++ b/packaging/RELEASING.md @@ -302,6 +302,14 @@ runs it is the review. files a customer's token reaches) for `MAKER_MAX_DAYS`, with no license accepted. `CHECK_TOKEN` reaches the same files. `FACTORY_TOKEN` itself downloads nothing and gets no token. + Each made-up record also gets an engine license key (`POST /api/license {maker_id, + device}`, teaport#474): an `appliance` key, for any `tpdev2` that holds no live + appliance key and no revoked row. That is up to `FACTORY_DAILY_MAX` keys a day, and + they never expire: each is a free commercial license for that hardware. With a box's + serial (guessable: docs/engine-license-data.md, "The factory's rows") and its + `tpdev2`, a made-up record for the same serial can also take that box's key (a key + moves to a newer record of its own serial), and once a box's old record is gone (past + `RETENTION_DAYS`), a record for any serial can take its key. The station's `/provision` hands out the same records without the secret leaking, to whoever can ask it: so it answers only to the boxes' USB network (below). If the factory's public IP address is stable, a Cloudflare rule letting `/api/factory` in @@ -322,10 +330,8 @@ runs it is the review. long), restart `factory serve`, which reads it at startup (stripping the trailing newline `openssl rand -hex 32 > file` leaves). That stops new records; boxes already provisioned keep theirs. The daily cap counts from zero for the new secret. Rotate it - when anyone who held it leaves, and on any doubt. To stop records a leak made, revoke - them: `UPDATE maker_acceptances SET revoked_at = '' WHERE …` (by IP, by time, or - all since the leak; a revoked box's next run gets no token, and its owner accepts). A - Worker version carries the secrets it was deployed with, so a rollback (`wrangler + when anyone who held it leaves, and on any doubt. Then clean up what the leak made + (below). A Worker version carries the secrets it was deployed with, so a rollback (`wrangler rollback`, the way back above) to a version from before a rotation brings the old `FACTORY_TOKEN` back (wrangler asks first): rotate again after it, by redeploying a fixed main and then `secret put` (a plain `secret put` is refused while the deployed @@ -334,6 +340,123 @@ runs it is the review. @100%`. A rollback to a Worker from before the factory kind refuses every maker acceptance (and its retention cron leaves them alone) until main is deployed again. + - **Cleaning up after a leak,** in this order. Rotate `FACTORY_TOKEN` first (above), so + no new record can be made. Then revoke the suspect maker acceptances, before touching + any key: the Worker refuses every mint, move and renewal under a revoked maker + acceptance, so that stops whatever the leak could still do with the records it made + (revoking one changes no license row). Only then sort their keys, revoke the made-up + ones and give the real ones back. `worker/test/leak-runbook.test.mjs` runs the + commands below, as written here, against a leak, so change them together. + - **The placeholders.** `` is the earliest time the secret may have been + out, in the stored form, with milliseconds: `2026-12-01T00:00:00.000Z`. Times are + compared as text, and `2026-12-01T00:00:00Z` sorts after + `2026-12-01T00:00:00.400Z`, so a shorter form misses that first second. + `` is every public address the station calls from, IPv4 and IPv6, + quoted and comma-separated: `'198.51.100.10', '2001:db8::10'`. `` is + the id of a maker acceptance the station made with the leaked secret (it gives the + secret's `mark`). `` is the time, in the same form as ``. + `wrangler` is the locked one, from `worker/`. + - **What is a real box's key.** A key under a suspect record is real if it was made + before ``, or it was first issued (`first_maker_id`, which a move never + changes) under a record that is not suspect: a real box's key that a suspect record + took, the box built before or during the leak. It is also real if its `device` is + the `tpdev2` the same serial's box held a key for before the leak (a key bound to + that box's own hardware is of use on that box only). Anything else is made-up: a key + first issued under a suspect record, even one moved on to another suspect record, + and even under a serial Teaspoon AI sold, as a made-up record can name a sold serial + and get a key for other hardware. + + 1. **The suspect records,** and a check of ``. Compare both lists with the + station's own provisioning log (the serial and time of each box it provisioned). A + record in the first list that the station made is not suspect: its address belongs + in ``. The second list is every record the leaked secret made before + `` (by its `mark`), with whether it came from a factory address: if any + of them is missing from the station's log, the secret was out earlier. Move + `` before it and start again from here; a `` set too late + finds nothing, and the check in step 6 would still print 0. + + ```bash + wrangler d1 execute teaport-gate --remote --command "SELECT m.id, m.created_at, m.device_id, m.ip, m.country FROM maker_acceptances m + WHERE m.created_at >= '' AND COALESCE(m.ip, '') NOT IN () ORDER BY m.created_at" + wrangler d1 execute teaport-gate --remote --command "SELECT m.id, m.created_at, m.device_id, m.ip, COALESCE(m.ip, '') IN () AS from_factory + FROM maker_acceptances m WHERE m.mark = (SELECT k.mark FROM maker_acceptances k WHERE k.id = '') + AND m.created_at < '' ORDER BY m.created_at DESC" + ``` + + 2. **Revoke them, first** (a revoked record's box gets no token, and its owner + accepts): + + ```bash + wrangler d1 execute teaport-gate --remote --command "UPDATE maker_acceptances SET revoked_at = '' + WHERE created_at >= '' AND COALESCE(ip, '') NOT IN () AND revoked_at IS NULL" + ``` + + 3. **Their keys, sorted** (`kind` is `real` or `made-up`, by the rule above): + + ```bash + wrangler d1 execute teaport-gate --remote --command "SELECT l.license_id, l.device, l.created_at AS key_created, l.first_maker_id, l.revoked_at, m.id AS maker_id, m.device_id, + CASE WHEN (l.created_at < '' + OR l.first_maker_id IS NULL OR l.first_maker_id NOT IN (SELECT f.id FROM maker_acceptances f WHERE f.created_at >= '' AND COALESCE(f.ip, '') NOT IN ()) + OR EXISTS (SELECT 1 FROM licenses p JOIN maker_acceptances pm ON pm.id = p.maker_id + WHERE p.device = l.device AND p.tier = 'appliance' AND p.created_at < '' + AND pm.device_id = (SELECT s.device_id FROM maker_acceptances s WHERE s.id = l.maker_id))) + THEN 'real' ELSE 'made-up' END AS kind + FROM licenses l JOIN maker_acceptances m ON m.id = l.maker_id + WHERE m.created_at >= '' AND COALESCE(m.ip, '') NOT IN () ORDER BY kind, m.device_id" + ``` + + 4. **Revoke the made-up keys.** That stops their renewals and bars their devices from + any other key. It does not stop the keys themselves: an appliance key never + expires, and boxes learn of a revocation only from the revocation list + (`/api/revocations`, teaport#474 W2). Until W2 ships, they keep working, offline and + on. + + ```bash + wrangler d1 execute teaport-gate --remote --command "UPDATE licenses SET revoked_at = '', revoke_reason = 'FACTORY_TOKEN leak: made-up box' + WHERE revoked_at IS NULL AND maker_id IN (SELECT m.id FROM maker_acceptances m WHERE m.created_at >= '' AND COALESCE(m.ip, '') NOT IN ()) + AND NOT (licenses.created_at < '' + OR licenses.first_maker_id IS NULL OR licenses.first_maker_id NOT IN (SELECT f.id FROM maker_acceptances f WHERE f.created_at >= '' AND COALESCE(f.ip, '') NOT IN ()) + OR EXISTS (SELECT 1 FROM licenses p JOIN maker_acceptances pm ON pm.id = p.maker_id + WHERE p.device = licenses.device AND p.tier = 'appliance' AND p.created_at < '' + AND pm.device_id = (SELECT s.device_id FROM maker_acceptances s WHERE s.id = licenses.maker_id)))" + ``` + + 5. **Give the real keys back:** each to its box's own newest record that is not + suspect (the key file does not change: it names no maker record). A box with no + such record left (past its retention), or whose record holds another key (the + one-key-per-record index refuses the move), is unlinked instead (`maker_id` + empty), which keeps its key renewing. Nothing here releases or revokes a real key, + and both statements take real keys only (the rule above), so a made-up key is + never given a record, even if step 4 was missed. + + ```bash + wrangler d1 execute teaport-gate --remote --command "UPDATE OR IGNORE licenses SET maker_id = (SELECT o.id FROM maker_acceptances o + WHERE o.device_id = (SELECT s.device_id FROM maker_acceptances s WHERE s.id = licenses.maker_id) + AND NOT (o.created_at >= '' AND COALESCE(o.ip, '') NOT IN ()) ORDER BY o.created_at DESC LIMIT 1) + WHERE revoked_at IS NULL AND maker_id IN (SELECT m.id FROM maker_acceptances m WHERE m.created_at >= '' AND COALESCE(m.ip, '') NOT IN ()) + AND (licenses.created_at < '' + OR licenses.first_maker_id IS NULL OR licenses.first_maker_id NOT IN (SELECT f.id FROM maker_acceptances f WHERE f.created_at >= '' AND COALESCE(f.ip, '') NOT IN ()) + OR EXISTS (SELECT 1 FROM licenses p JOIN maker_acceptances pm ON pm.id = p.maker_id + WHERE p.device = licenses.device AND p.tier = 'appliance' AND p.created_at < '' + AND pm.device_id = (SELECT s.device_id FROM maker_acceptances s WHERE s.id = licenses.maker_id)))" + wrangler d1 execute teaport-gate --remote --command "UPDATE licenses SET maker_id = NULL + WHERE revoked_at IS NULL AND maker_id IN (SELECT m.id FROM maker_acceptances m WHERE m.created_at >= '' AND COALESCE(m.ip, '') NOT IN ()) + AND (licenses.created_at < '' + OR licenses.first_maker_id IS NULL OR licenses.first_maker_id NOT IN (SELECT f.id FROM maker_acceptances f WHERE f.created_at >= '' AND COALESCE(f.ip, '') NOT IN ()) + OR EXISTS (SELECT 1 FROM licenses p JOIN maker_acceptances pm ON pm.id = p.maker_id + WHERE p.device = licenses.device AND p.tier = 'appliance' AND p.created_at < '' + AND pm.device_id = (SELECT s.device_id FROM maker_acceptances s WHERE s.id = licenses.maker_id)))" + ``` + + 6. **Check that no live key is left under a suspect record.** It must print 0; if it + does not, go again from step 2. + + ```bash + wrangler d1 execute teaport-gate --remote --command "SELECT count(*) AS n FROM licenses l JOIN maker_acceptances m ON m.id = l.maker_id + WHERE m.created_at >= '' AND COALESCE(m.ip, '') NOT IN () AND l.revoked_at IS NULL AND l.released_at IS NULL" + ``` + + - **Turning it off:** `wrangler secret delete FACTORY_TOKEN`. The factory then records nothing until a new one is set and on the station; rotate instead to keep it going. Never fall back to an ordinary acceptance in Teaspoon AI's name: it records the @@ -454,11 +577,75 @@ runs it is the review. accepted, recorded under the maker's id. - **Provisioning a box again** (its install outlasted `MAKER_MAX_DAYS`, or its record was revoked): remove its `/etc/appliance-id` (the provisioning unit runs only - without it), and it records a new maker acceptance at its next boot. + without it), and it records a new maker acceptance at its next boot. The box keeps + its engine license key: its first-boot request with the new record moves the live + appliance key to it (same `license_id`; docs/engine-license-data.md, "License + keys"), when the new record is for the same serial. A box given another serial, or + a swapped module, gets 403 `maker_serial` until staff release its old key + (`released_at`); then the new record gets a new one. The old record, which held + the key, gets none again (403 `maker_spent`), whatever happens to the key. A box whose key, or any key on it, was revoked gets none until staff + release that row (`released_at`) before provisioning it again. - **After the factory:** the owner's acceptance (teaport#465) writes a receipt `install.sh` takes as its own (`version`, `acceptance_id`), or every engine update asks again. The maker record itself stays in `maker_acceptances`, with its age past `MAKER_MAX_DAYS` soon after; nothing needs to revoke it. +- **`LICENSE_SIGNING_KEY`** is the online license key, `prod-online-2026-12` + (teaport#474): `POST /api/license` signs the engine's personal and appliance license + keys with it (an SSH signature, namespace `teaport-license`). Commercial keys are never + signed with it: the offline key on the signing laptop signs those. It has to be in + Cloudflare, so the product owner makes it in their own terminal on the desktop, not on + the laptop, and keeps the only other copy in Bitwarden. Never in git, R2, a GitHub + secret or variable, or a box; the Worker's tests make throwaway keys of their own. + - **Making it**, and its OpenSSH public line (`ssh-keygen -y` cannot read openssl's + PKCS#8 file, so the line is built from the raw key: the `printf` is the key blob's + header, the string `ssh-ed25519` and the length 32, and the raw key is the last 32 + bytes of the DER public key; bash and zsh both): + + ```bash + umask 077 + openssl genpkey -algorithm ed25519 -out license-online.pem + { printf '\000\000\000\013ssh-ed25519\000\000\000\040' + openssl pkey -in license-online.pem -pubout -outform DER | tail -c 32 + } | base64 -w0 | sed 's/^/ssh-ed25519 /; s/$/ prod-online-2026-12\n/' > license-online.pub + ssh-keygen -l -f license-online.pub # 256 SHA256:… prod-online-2026-12 (ED25519) + ``` + + Save `license-online.pem` (a secure note: the whole file) and the line in + `license-online.pub` in Bitwarden. + - **Putting it on the Worker:** `wrangler secret put LICENSE_SIGNING_KEY < + license-online.pem`. The public line goes, by pull request, into `LICENSE_PUBKEY` in + `worker/wrangler.toml` (deployed by `worker-deploy`; its label must equal + `LICENSE_KID`) and into the engine's `engine/license_keys/prod.pub` as that line + followed by its capabilities, comma-separated with no spaces + (`ssh-ed25519 AAAA… prod-online-2026-12 personal,appliance,revocations`; the engine's + `docs/LICENSE_KEYS.md`, "Trusted keys"). Until the secret and `LICENSE_PUBKEY` + are both there and are one key pair, `/api/license` answers 503 + `license_unavailable` and records nothing, so either may come first. Then, once the + Bitwarden copy opens: `shred -u license-online.pem`. The `.pub` file is public. + - **What a leak exposes:** whoever holds it can sign personal and appliance keys for any + device, for every engine release that trusts `prod-online-2026-12`; not commercial + ones (the engine's key list gives it no such capability). Every key the Worker signed + is a `licenses` row, so a key with no row was not. The key never travels in a request, + so Workers Logs never hold it. + - **Rotating it** (on a leak, or by plan): make the next key the same way under a new + label (`prod-online--`); ship an engine release that trusts both; then, in + one go, `wrangler secret put LICENSE_SIGNING_KEY` with the new key and a deploy of + `LICENSE_KID` and `LICENSE_PUBKEY` set to it (`/api/license` answers 503 between the + two). Every key is signed again under the new one at its next renewal, appliance keys + included (the daily timer, teaport#474 I2). Drop the old public key from engine + releases 13 months later, when every personal key has renewed. After a leak, revoking + what it signed is by dropping the old key from releases; the revocation list + (`/api/revocations`, W2) only lists keys by id. + - **A new engine license version** (the manifest's `engine.eula`): from then on every + personal key's renewal answers 409 `eula_changed` until its owner accepts the new + version, and nothing is written. The box keeps its key until it expires, plus the + engine's 30-day grace (teaport#474 E2); teaport asks for the license to be accepted + again (I2), and that acceptance renews the same key. Appliance keys renew as before. + - **Rollbacks:** a Worker version carries the secrets it was deployed with, as with + `FACTORY_TOKEN` above: a rollback past a rotation signs with the old key again (under + the old `LICENSE_KID`, which the vars of that version carry too). A rollback to a + Worker from before `/api/license` answers it 404 `not_found`, and the `licenses` table + stays (migration 0004 only adds). ## Release candidates diff --git a/worker/migrations/0004_licenses.sql b/worker/migrations/0004_licenses.sql new file mode 100644 index 00000000..46094c3c --- /dev/null +++ b/worker/migrations/0004_licenses.sql @@ -0,0 +1,77 @@ +-- 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. A device holds at most +-- one personal key per email address that is not released (the Worker's insert checks it). +-- Revoking a key, of any tier, is the device's: it gets no new key and no renewal of any +-- tier, under any email address, until the row is released. Revoking an acceptance (acceptances.revoked_at) revokes the personal +-- keys last issued under it for that person. Revoked keys count toward the person's cap +-- until they expire. 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 that holds it now (one key each) + first_maker_id TEXT, -- appliance: the maker acceptance it was first issued under; a move (a box + -- provisioned again) never changes it: what a leak's cleanup sorts keys by + 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; it sticks: + -- the device (whatever this key's tier) gets no new key and no renewal + -- of any tier, and a personal key counts toward its person's cap until + -- it expires + revoke_reason TEXT, + released_at TEXT -- set by hand: a personal key's slot freed (the owner asked, by email), + -- or any revoked key's bar on its device lifted; + -- it no longer counts or renews, and the device may get a new key + -- (on a revoked row too: that lifts the revocation for the device) +); +-- 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 + +-- Every maker acceptance that ever held an appliance key, and the key: issued under it, or +-- moved to it (a box provisioned again). Insert-only, written by the triggers below in the +-- same statement as the key's write, so no request can slip between the two. A record here +-- never issues or receives another key (the Worker checks it): a box provisioned again +-- leaves its old record holding nothing, and that record's id is still in the box's old +-- receipt, so without this anyone who can read it could mint a second, perpetual key for +-- other hardware. Kept for good: only ids, and the maker acceptance may be deleted by +-- retention while the key it held is still in use. +CREATE TABLE license_makers ( + maker_id TEXT PRIMARY KEY, -- a maker acceptance's id + license_id TEXT NOT NULL, -- the key it held first + at TEXT NOT NULL -- ISO 8601, UTC: when it got it +); +CREATE TRIGGER licenses_maker_insert AFTER INSERT ON licenses WHEN NEW.maker_id IS NOT NULL +BEGIN + INSERT OR IGNORE INTO license_makers (maker_id, license_id, at) + VALUES (NEW.maker_id, NEW.license_id, strftime('%Y-%m-%dT%H:%M:%fZ', 'now')); +END; +CREATE TRIGGER licenses_maker_update AFTER UPDATE OF maker_id ON licenses + WHEN NEW.maker_id IS NOT NULL AND NEW.maker_id IS NOT OLD.maker_id +BEGIN + INSERT OR IGNORE INTO license_makers (maker_id, license_id, at) + VALUES (NEW.maker_id, NEW.license_id, strftime('%Y-%m-%dT%H:%M:%fZ', 'now')); +END; + +-- 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..5f087e16 100644 --- a/worker/src/index.js +++ b/worker/src/index.js @@ -31,6 +31,21 @@ // 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 (a box provisioned again keeps its +// key: it moves to the new maker acceptance). With a license id, a +// renewal: a personal key gets another year while its acceptance is of +// the current license (409 eula_changed after a change), an appliance +// key is signed again under the current key. A device with any revoked +// key gets none. 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 +73,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 +101,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 +429,365 @@ 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(); + +// 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). +// Written first, then signed, as the personal keys are, and refused in the same statement +// when the key is revoked or released, or its device holds any revoked key. +async function resign(env, sig, row, now) { + for (let i = 0; i < TRIES; i++) { + const { meta } = await env.DB.prepare(LICENSE_SQL.resign).bind(row.license_id, sig.kid, iso(now), row.device).run(); + if (meta.changes === 1) return json(200, await licenseDoc(sig, payloadOf(row, sig.kid))); + const cur = await env.DB.prepare("SELECT revoked_at, released_at FROM licenses WHERE license_id = ?1").bind(row.license_id).first(); + if (!cur) return fail(404, "unknown_license", "no license key is recorded under this id: run the installer again to get one"); + if (cur.revoked_at) return fail(403, "revoked", REVOKED_KEY); + if (cur.released_at) return fail(403, "released", RELEASED_KEY); + if (await deviceRevoked(env, row.device)) return fail(403, "revoked", REVOKED_DEVICE); + } + return CONFLICT(); +} + +// The personal keys of the person behind acceptance : every key issued under an +// acceptance of the same email address (lowercased and trimmed in SQL, so the address never +// reaches this code). It starts from the acceptances, by acceptances_email_norm, then their +// keys by licenses_acceptance, both by name: D1 keeps no planner statistics (no ANALYZE), +// and without them SQLite may start from licenses and read every personal key there is. +// (An index named here that is missing makes the statement fail to prepare: a 500, and +// nothing signed or written. That fails closed; migrations/0004 makes them.) +const mine = (acc) => `acceptances a INDEXED BY acceptances_email_norm + CROSS JOIN licenses l INDEXED BY licenses_acceptance ON l.acceptance_id = a.id + WHERE lower(trim(a.email)) = (SELECT lower(trim(email)) FROM acceptances WHERE id = ${acc}) AND l.tier = 'personal'`; +// The devices other than that count toward the cap: holding an unexpired personal +// key that is not released. A revoked key, or one whose acceptance is revoked, counts until +// it expires: revoking binds the person to what they already hold, and a new acceptance of +// the same address starts no new cap. Only releasing a key (released_at) frees its slot. +const counted = (acc, now, device) => `SELECT count(DISTINCT l.device) FROM ${mine(acc)} + AND l.released_at IS NULL AND l.expires_at > ${now} AND l.device <> ${device}`; +// holds a revoked key that is not released, of any tier, under any email address: +// revoking a key is the device's, whoever asks next. No new key and no renewal of any tier +// on it until that row is released (a revoked appliance key does not become a personal one, +// nor a revoked personal key an appliance one). By licenses_device, named as above. +// holds a live appliance key: not revoked, not released. By licenses_device. +const liveAppliance = (device) => `SELECT 1 FROM licenses e INDEXED BY licenses_device + WHERE e.device = ${device} AND e.tier = 'appliance' AND e.revoked_at IS NULL AND e.released_at IS NULL`; +// Maker acceptance ever held an appliance key, issued or moved to it (license_makers, +// which migrations/0004's triggers fill with the key's write): it gets no other. By its +// primary key. +const spent = (maker) => `SELECT 1 FROM license_makers h WHERE h.maker_id = ${maker}`; +const revokedDevice = (device) => `SELECT 1 FROM licenses d INDEXED BY licenses_device + WHERE d.device = ${device} AND d.revoked_at IS NOT NULL AND d.released_at IS NULL`; + +// The statements of the cap. Each write is one statement that checks and writes at once (D1 +// runs one at a time), so requests at the same moment can neither pass the cap together nor +// give one device two keys. Exported for the tests' EXPLAIN QUERY PLAN. +export const LICENSE_SQL = { + // ?1 acceptance: the devices counted (for the refusal's message). + counted: `SELECT (${counted("?1", "?2", "?3")}) AS n`, + // ?1 device: revoked, whatever the address. + revoked: `SELECT EXISTS (${revokedDevice("?1")}) AS r`, + // ?1 acceptance, ?2 device: the device's key under this person, unless released. At most + // one (insert below): live, or revoked (itself, or through its acceptance), which sticks. + held: `SELECT l.license_id, l.revoked_at, a.revoked_at AS acceptance_revoked_at FROM ${mine("?1")} + AND l.device = ?2 AND l.released_at IS NULL ORDER BY l.created_at DESC LIMIT 1`, + // A new key: only when the device holds none under this person (released ones aside), none + // revoked under anyone, and fewer than ?9 other devices count. + insert: `INSERT INTO licenses (license_id, tier, device, kid, engine_major, issued_at, expires_at, acceptance_id, created_at, signed_at) + SELECT ?1, 'personal', ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?8 + WHERE NOT EXISTS (SELECT 1 FROM ${mine("?7")} AND l.device = ?2 AND l.released_at IS NULL) + AND NOT EXISTS (${revokedDevice("?2")}) + AND (${counted("?7", "?5", "?2")}) < ?9`, + // Another year for key ?1 on device ?8, under acceptance ?2: only while it is neither revoked + // nor released, the device holds no revoked key under anyone, and fewer than ?9 other + // devices count. + renew: `UPDATE licenses SET acceptance_id = ?2, issued_at = ?3, expires_at = ?4, engine_major = ?5, kid = ?6, signed_at = ?7 + WHERE license_id = ?1 AND revoked_at IS NULL AND released_at IS NULL + AND NOT EXISTS (${revokedDevice("?8")}) AND (${counted("?2", "?3", "?8")}) < ?9`, + // An appliance key ?1 for device ?2 under maker acceptance ?6: one per maker acceptance + // (OR IGNORE: the unique index), none for a device that holds a revoked key or already a + // live appliance key (that one moves instead: applianceMove). first_maker_id records ?6 + // for good: a move changes maker_id only. + applianceInsert: `INSERT OR IGNORE INTO licenses (license_id, tier, device, kid, engine_major, issued_at, maker_id, first_maker_id, created_at, signed_at) + SELECT ?1, 'appliance', ?2, ?3, ?4, ?5, ?6, ?6, ?7, ?7 WHERE NOT EXISTS (${revokedDevice("?2")}) + AND NOT EXISTS (${spent("?6")}) + AND NOT EXISTS (${liveAppliance("?2")})`, + // A box provisioned again: its live appliance key, under an older maker acceptance for the + // same box (the same device_id, its serial's hash), moves to maker acceptance ?1 (same + // license_id), signed again under kid ?2, for device ?4. One statement: of maker + // acceptances racing for it, the newest ends up with it (a key under a newer one never + // moves back), and OR IGNORE keeps the unique index (?1 holding a key already moves + // nothing). A factory record that is gone (past its retention) is older, and of the box. + // Another serial's record never takes it: with a leaked FACTORY_TOKEN and a box's tpdev2, + // a made-up record could otherwise take the box's key, and revoking that record (the + // leak's cleanup) would stop the real box's renewals. + applianceMove: `UPDATE OR IGNORE licenses SET maker_id = ?1, kid = ?2, signed_at = ?3 + WHERE license_id = (SELECT d.license_id FROM licenses d INDEXED BY licenses_device + WHERE d.device = ?4 AND d.tier = 'appliance' AND d.revoked_at IS NULL AND d.released_at IS NULL + AND (SELECT (m.created_at, m.id) < (n.created_at, n.id) AND (m.id IS NULL OR m.device_id = n.device_id) + FROM maker_acceptances n LEFT JOIN maker_acceptances m ON m.id = d.maker_id WHERE n.id = ?1) IS NOT 0 + LIMIT 1) + AND NOT EXISTS (${revokedDevice("?4")}) AND NOT EXISTS (${spent("?1")})`, + // ?1 ever held an appliance key (license_makers). + spent: `SELECT EXISTS (${spent("?1")}) AS r`, + // Device ?2's live appliance key, as maker acceptance ?1 sees it: whether its record is of + // another box (serial: 1), or newer than ?1 (newer: 1). Why a move did not happen. + applianceHeld: `SELECT (m.id IS NOT NULL AND m.device_id <> n.device_id) AS serial, + ((m.created_at, m.id) < (n.created_at, n.id)) IS 0 AS newer + FROM licenses d INDEXED BY licenses_device LEFT JOIN maker_acceptances m ON m.id = d.maker_id + JOIN maker_acceptances n ON n.id = ?1 + WHERE d.device = ?2 AND d.tier = 'appliance' AND d.revoked_at IS NULL AND d.released_at IS NULL + LIMIT 1`, + // Key ?1 (on device ?4) signed again under kid ?2: an appliance key asked for again or + // renewed. Not when it is revoked or released, or its device holds a revoked key. + resign: `UPDATE licenses SET kid = ?2, signed_at = ?3 + WHERE license_id = ?1 AND revoked_at IS NULL AND released_at IS NULL AND NOT EXISTS (${revokedDevice("?4")})`, +}; + +// device_cap, with how many other devices count; null when fewer than the cap do (the state +// changed under the statement that refused: the caller tries again). +async function capRefusal(env, acc, device, now) { + const { n } = await env.DB.prepare(LICENSE_SQL.counted).bind(acc, now, device).first(); + if (n < PERSONAL_DEVICES) return null; + 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 REVOKED_KEY = `this license key was revoked: contact ${CONTACT}`; +const REVOKED_DEVICE = `a license key of this device was revoked: contact ${CONTACT}`; +const RELEASED_KEY = "this license key's device was released from its owner's devices: run the installer again for a new key"; +// A refused write whose reason was gone when it was looked for, this many times over: rows +// changed under every try (a key released or deleted meanwhile). Rare; the box asks again. +const TRIES = 3; +const CONFLICT = () => fail(409, "conflict", "the license key records changed while this was asked: try again"); + +const personalTerms = (license_id, device, major, now) => ({ + license_id, tier: "personal", device, issued_at: now, expires_at: now + PERSONAL_DAYS * 86400, engine_major: major }); + +// A refusal when acceptance ({channel, eula_version, eula_sha256}) is not of its +// channel's current license, as /api/token refuses it; null when it is. +async function eulaRefusal(env, row, now) { + 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 }); + } + return null; +} + +const deviceRevoked = async (env, device) => + (await env.DB.prepare(LICENSE_SQL.revoked).bind(device).first()).r === 1; + +// Key (device , engine ) another year, under acceptance : written +// first, then signed. Not written: it is gone, revoked or released, its device holds a +// revoked key, or the cap is full; none of those (they changed meanwhile): again. +async function renewPersonal(env, sig, { id, acc, device, major }, now) { + const row = personalTerms(id, device, major, now); + for (let i = 0; i < TRIES; i++) { + const { meta } = await env.DB.prepare(LICENSE_SQL.renew) + .bind(id, acc, now, row.expires_at, major, sig.kid, iso(now), device, PERSONAL_DEVICES).run(); + if (meta.changes === 1) return json(200, await licenseDoc(sig, payloadOf(row, sig.kid))); + const cur = await env.DB.prepare("SELECT revoked_at, released_at FROM licenses WHERE license_id = ?1").bind(id).first(); + if (!cur) return fail(404, "unknown_license", "no license key is recorded under this id: run the installer again to get one"); + if (cur.revoked_at) return fail(403, "revoked", REVOKED_KEY); + if (cur.released_at) return fail(403, "released", RELEASED_KEY); + if (await deviceRevoked(env, device)) return fail(403, "revoked", REVOKED_DEVICE); + const cap = await capRefusal(env, acc, device, now); + if (cap) return cap; + } + return CONFLICT(); +} + +// 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 new key, if the +// device holds none under this person; else the one it holds, another year (same license_id, +// counted once), unless that one is revoked, or its acceptance is: a revocation sticks, and +// a new acceptance of the same address does not undo it. A device with a revoked key gets +// none under any other address either. Only a released key (a slot freed by hand, +// released_at) leaves the device free to get a new one. +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 stale = await eulaRefusal(env, row, now); + if (stale) return stale; + for (let i = 0; i < TRIES; i++) { + const fresh = personalTerms(newLicenseId(), device, sig.major, now); + const { meta } = await env.DB.prepare(LICENSE_SQL.insert) + .bind(fresh.license_id, device, sig.kid, sig.major, now, fresh.expires_at, id, iso(now), PERSONAL_DEVICES).run(); + if (meta.changes === 1) return json(200, await licenseDoc(sig, payloadOf(fresh, sig.kid))); + // Not written: why, now. + if (await deviceRevoked(env, device)) return fail(403, "revoked", REVOKED_DEVICE); + const held = await env.DB.prepare(LICENSE_SQL.held).bind(id, device).first(); + if (held?.revoked_at) return fail(403, "revoked", REVOKED_KEY); + if (held?.acceptance_revoked_at) return fail(403, "revoked", `the acceptance this device's key was issued under was revoked: contact ${CONTACT}`); + if (held) return renewPersonal(env, sig, { id: held.license_id, acc: id, device, major: sig.major }, now); + const cap = await capRefusal(env, id, device, now); + if (cap) return cap; + } + return CONFLICT(); +} + +// 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; for a device holding any revoked key, none. So the key +// goes to the first device to ask with the id (design §6): the factory box, whose receipt +// alone holds it, for at most MAKER_MAX_DAYS. A box provisioned again (a new maker +// acceptance for the same serial) that holds a live appliance key keeps it: the key moves +// to the new record (same license_id), and the box gets a new one only when it holds none. +// A record for another serial never takes it (403 maker_serial). A record that ever held a +// key (license_makers) never issues or receives another (403 maker_spent): the one a box +// provisioned again leaves behind holds nothing, and its id is still in the box's old receipt. +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(); + for (let i = 0; !row && i < TRIES; i++) { + const moved = await env.DB.prepare(LICENSE_SQL.applianceMove).bind(id, sig.kid, iso(now), device).run(); + if (moved.meta.changes === 1) { + row = await find(); + if (row?.device === device) return json(200, await licenseDoc(sig, payloadOf(row, sig.kid))); + continue; // moved on to a newer record meanwhile: look again + } + const fresh = { license_id: newLicenseId(), tier: "appliance", device, issued_at: now, engine_major: sig.major }; + await env.DB.prepare(LICENSE_SQL.applianceInsert) + .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, await licenseDoc(sig, payloadOf(fresh, sig.kid))); + // Another request for this maker acceptance wrote its key first: answer as for that one. + if (row) break; + if (await deviceRevoked(env, device)) return fail(403, "revoked", REVOKED_DEVICE); + // The device holds a live appliance key that did not move: under another box's record (a + // swapped module or serial, or a made-up record: staff release the old key), or under a + // newer record of this box (it was provisioned again since). Nothing is written. + const held = await env.DB.prepare(LICENSE_SQL.applianceHeld).bind(id, device).first(); + if (held?.serial === 1) { + return fail(403, "maker_serial", `this device's license key belongs to another box's factory install record: contact ${CONTACT}`); + } + if (held?.newer === 1) { + return fail(409, "maker_superseded", `this box's license key belongs to a newer factory install record than this one: contact ${CONTACT}`); + } + // This record held a key once, which moved on to a newer record of its box: it gets no other. + if ((await env.DB.prepare(LICENSE_SQL.spent).bind(id).first()).r === 1) { + return fail(403, "maker_spent", `this factory install record's license key moved to a newer record of its box; it gets no other: contact ${CONTACT}`); + } + } + if (!row) return CONFLICT(); + 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 or +// released; for a personal key, its acceptance on record, not revoked and of the current +// license (409 eula_changed, as for a new key); 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.released_at) return fail(403, "released", RELEASED_KEY); + if (row.tier === "personal") { + const acc = await env.DB.prepare( + "SELECT channel, eula_version, eula_sha256, 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}`); + // Of the current license, as a new key's (the owner's decision): after a license change + // the box keeps the key it has (to its expiry, then the engine's 30-day grace) while + // teaport has the license accepted again; that acceptance renews it. + const stale = await eulaRefusal(env, acc, now); + if (stale) return stale; + // The major version it was issued for: a renewal never moves a box to keys its engine refuses. + return renewPersonal(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 +884,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 +927,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