From 75529bedad934506b44ec697a4446d2ba1574369 Mon Sep 17 00:00:00 2001 From: Joao Paulo Furtado Date: Sat, 21 Nov 2026 18:44:08 -0700 Subject: [PATCH 01/20] docs(prd): PRD-904 tn login and tn deploy delegate to the store CLI's device flow and push --- ...oy-reuse-the-store-device-flow-and-push.md | 114 ++++++++++++++++++ 1 file changed, 114 insertions(+) create mode 100644 docs/PRDs/tooling/PRD-904-tn-login-and-deploy-reuse-the-store-device-flow-and-push.md diff --git a/docs/PRDs/tooling/PRD-904-tn-login-and-deploy-reuse-the-store-device-flow-and-push.md b/docs/PRDs/tooling/PRD-904-tn-login-and-deploy-reuse-the-store-device-flow-and-push.md new file mode 100644 index 0000000000..ff679579bc --- /dev/null +++ b/docs/PRDs/tooling/PRD-904-tn-login-and-deploy-reuse-the-store-device-flow-and-push.md @@ -0,0 +1,114 @@ +--- +prd_contract: v1 +--- + +# PRD-904 — `tn login` and `tn deploy`: the engine CLI signs in and ships a game with the store's flow + +**Status:** NOT STARTED +**Priority:** P1 — AC-1 to AC-6 are open: a generated game has no command to sign in or put it online, so an agent stops at a local build. +**Complexity:** 6 (MEDIUM) — 1-5 files (+1), new module (+2), crosses the engine/store release boundary (+2), external API: the threenative.com store routes (+1); risk override: HIGH, the change handles an account credential. +**Owner:** João +**Depends on:** PRD-811 (store repo) AC-2, which publishes `@threenative/store-cli` to npm +**Repo:** this repo (`packages/create-threenative`); `ThreeNativeHQ/threenative-store` for the e2e proof + +## Context + +The server and the client for sign-in and deploy already exist. They live in the private repos and the engine CLI does not reach them. + +| Piece | Where | State | +| --- | --- | --- | +| Device-code login: `POST /api/store/device`, `/device/token`, `/device/approve` | site `worker/store-device.ts`, `migrations/0019_device_codes.sql`, page `/account/device` | Shipped (store PRD-808 AC-1..3). Works with no loopback port: containers, remote boxes, agents. | +| Scoped API tokens (`push`, `snapshot:read`, `build:upload`) | site `worker/auth.ts`, `migrations/0014_build_token_scope.sql` | Shipped | +| `tn-store login · logout · whoami · games · push · status`, `--json`, exit codes 0/2/3/4/5, OS keychain, `TN_STORE_TOKEN` for CI | store `crates/tn-store-cli/src/main.rs:9-60`, `lib.rs:77-86` | Shipped as a Rust binary. Not on npm yet (PRD-811 AC-2 open; `npm view @threenative/store-cli` returns 404 on 2026-11-21). | +| Push: FastCDC chunks, missing-chunk check, snapshot, release poll | store `crates/tn-store-cli/src/push.rs`, `crates/tn-store-core/src/pack.rs` | Shipped. The store builds from source, so a deploy pushes source. | +| Live web build hosting on `-play.threenative.com` | site `worker/host.ts:24-35` | Shipped | +| Studio sign-in (browser redirect + one-time code over a service binding) | site `worker/studio-auth.ts`, `migrations/0029_studio_auth_codes.sql` | Shipped. Browser-only, so the CLI does not use it. Studio publishes with `TN_STORE_TOKEN` (`threenative-live-studio/src/server/config.ts:63`), the same variable this PRD honours. | + +The engine side: `threenative` (bin of `create-threenative`) has two commands, `build` and `doctor` (`packages/create-threenative/src/commands.ts:6-8`). `packages/create-threenative/AGENTS.md` "CLI surface" says a third command needs the owner decision made again. No `tn` bin exists. The npm name `tn` belongs to an unrelated package (Titanium CLI wrapper, 4.2.1). + +## Solution + +`tn` becomes a second bin name for the `threenative` executable. Three borrowed commands (the `wrangler` and `vercel` vocabulary) join `build` and `doctor`: `login`, `logout`, `deploy`. Each one delegates to the store CLI. The engine re-implements no HTTP client, no chunker and no token store. + +```mermaid +sequenceDiagram + participant A as Agent or person + participant T as tn (create-threenative) + participant S as tn-store binary + participant W as threenative.com Worker + A->>T: tn login + T->>S: tn-store login [--json] + S->>W: POST /api/store/device + S-->>A: URL + user code + A->>W: approve on /account/device + S->>W: poll /device/token -> push token -> OS keychain + A->>T: tn deploy + T->>T: read .tn-store.json gameId, package.json version + T->>S: tn-store push . --version --json + S->>W: chunks, snapshot, release + T->>S: tn-store status --json (poll) + T-->>A: state live -> https://-play.threenative.com/ +``` + +- **Binary resolution:** `tn-store` on `PATH` first (a cargo build, a test stub), else `npm exec --yes @threenative/store-cli@ --`. The engine package takes no dependency on the private binary. +- **Game link:** `.tn-store.json` `{ "gameId": "..." }` in the project root, committed. The store's push already ignores this file name (`crates/tn-store-cli/src/ignore.rs:25`). `tn deploy --game ` writes it. With no link and no flag, `tn deploy` exits 2 and prints the `tn-store games create` line and the site URL. +- **Version:** `package.json` `version`. A refusal from the store (for example a reused version) passes through with its exit code and message. +- **Exit codes and `--json`:** pass through unchanged from `tn-store`, so an agent reads one table for both CLIs. +- **CI and Studio:** `TN_STORE_TOKEN` works unchanged, because `tn-store` reads it. + +Risks: the PRD-811 publish is the gate for any user outside this machine. `npx tn` outside a project resolves the unrelated npm `tn` package, so docs show `npx tn` only inside a generated project, where the local bin resolves first. + +## Non-Goals + +- Creating the store listing from the CLI without screenshots. The site requires 1 to 5 shots (`worker/games.ts:587`); `tn-store games create` already covers it. +- A TypeScript port of the push protocol or the chunk format. +- Deploy targets other than the ThreeNative store (Netlify, Vercel, itch.io). +- Changes to the site Worker, its schema or the device flow. + +## Acceptance Criteria + +- [ ] AC-1 [local]: `tn login` and `tn logout` run `tn-store login` and `tn-store logout` with the same flags, and return its exit code. proof: `pnpm exec vitest run packages/create-threenative/__tests__/cli.spec.ts` with a stub `tn-store` on `PATH` that records its argv — Evidence: pending. +- [ ] AC-2 [local]: `tn --help` and `threenative --help` list exactly `build`, `doctor`, `login`, `logout`, `deploy`, and `tn` is the same executable. proof: `cli.spec.ts` (derives the list from the real executable) — Evidence: pending. +- [ ] AC-3 [local]: `tn deploy` with no `.tn-store.json` and no `--game` exits 2 and names the create command; `tn deploy --game ` writes the link. proof: `cli.spec.ts` — Evidence: pending. +- [ ] AC-4 [local]: `tn deploy` pushes `.` at the `package.json` version, polls `status --json` until `live` or `held`, prints the play URL on `live` and the `reason` on `held`, and passes exit code 3 through as "sign in again". proof: `cli.spec.ts` with the recording stub — Evidence: pending. +- [ ] AC-5 [local]: A scaffolded starter, with the local `create-threenative` tarball and a real `tn-store` built from the store repo, signs in with a scripted approval and deploys against local `wrangler dev`; the release reaches `live` and the play host serves its `index.html`. proof: store repo PRD-810 e2e harness, run on this machine — Evidence: pending. +- [ ] AC-6 [shared]: In a `pnpm sandbox` clean room with the published packages, `npx create-threenative` → `npx tn login` → `npx tn deploy` puts the game live on threenative.com. proof: `pnpm sandbox` run log — Evidence: pending. + +## Blocked on + +- AC-6 needs `@threenative/store-cli` on npm — unblocked by store PRD-811 AC-2 (`NPM_TOKEN` in the store repo, an owner action) and by the next engine release that carries this PRD. + +## Integration Ledger + +| Capability | Reachable consumer/trigger | Replaces / disposition | Evidence | +| --- | --- | --- | --- | +| Sign in from a game project | `tn login` → `threenative.ts` dispatcher → `tn-store login` → site device routes | New; delegates to the shipped flow | AC-1, AC-5 | +| Deploy a game | `tn deploy` → `.tn-store.json` + `tn-store push`/`status` → `-play.threenative.com` | New; delegates to the shipped push | AC-3, AC-4, AC-5 | + +Fill the `threenative.ts` dispatcher `file:line` when Phase 1 lands. + +## Decisions + +- 2026-11-21 (João): reopen the "two `threenative` commands, ever" rule for `login`, `logout` and `deploy`. Reason: a game an agent cannot put online is unfinished. The words are borrowed from `wrangler` and `vercel`, not invented, which keeps the charter's closed "bespoke CLI vocabulary" rule intact. +- 2026-11-21 (agent): delegate to the `tn-store` binary instead of porting it to TypeScript. A port duplicates the FastCDC format and the token store, and drift between two chunkers breaks the store's missing-chunk check. +- 2026-11-21 (agent): `tn` is a second bin name of the same executable, not a new package. The npm name `tn` is taken. + +## Execution Phases + +#### Phase 1: `tn` signs in and out +**Status:** NOT STARTED +**Files:** `packages/create-threenative/package.json` (`tn` bin), `src/commands.ts` (three commands), `src/threenative.ts` (dispatch), `src/store-cli.ts` (new: resolve and spawn `tn-store`), `AGENTS.md` "CLI surface" (five commands, this PRD as the decision). +**Implementation:** spawn with inherited stdio, so the device-code prompt and `--json` output reach the caller untouched. A spawn failure (no `tn-store`, no `npm`) exits 5 with the install line. +- [ ] AC-1 and AC-2 pass — proof: `pnpm exec vitest run packages/create-threenative/__tests__/cli.spec.ts` and `pnpm sync:agents && pnpm check:docs` — covers AC-1, AC-2. + +#### Phase 2: `tn deploy` ships the project +**Status:** NOT STARTED +**Files:** `packages/create-threenative/src/store-cli.ts` (deploy), the generated-project `AGENTS.md` Commands block in each template that lists commands. +**Implementation:** read and write `.tn-store.json`; validate `gameId` against the site's id shape before it reaches argv. Poll `status --json` one second apart, 60 polls, the same budget as `push.rs:21`. +- [ ] AC-3 and AC-4 pass — proof: `cli.spec.ts` — covers AC-3, AC-4. + +#### Phase 3: proof through the real binary and the real Worker +**Status:** NOT STARTED +**Files:** none in this repo unless the e2e run finds a bug; the e2e case lives in the store repo harness. +- [ ] AC-5 passes on this machine — proof: store repo PRD-810 e2e harness with the local tarball — covers AC-5, the real device flow and the real push. +- [ ] AC-6 passes in the clean room after the publish — proof: `pnpm sandbox` — covers AC-6. From 4aeea83eefd93c91e13813c32a6c21a2c2be0c1f Mon Sep 17 00:00:00 2001 From: Joao Paulo Furtado Date: Sat, 21 Nov 2026 18:48:09 -0700 Subject: [PATCH 02/20] docs(create-threenative): drop the two-commands-ever rule; new commands borrow established CLI names (owner, 2026-11-21) --- packages/create-threenative/AGENTS.md | 8 ++++---- packages/create-threenative/CLAUDE.md | 8 ++++---- packages/create-threenative/src/commands.ts | 6 ++---- 3 files changed, 10 insertions(+), 12 deletions(-) diff --git a/packages/create-threenative/AGENTS.md b/packages/create-threenative/AGENTS.md index 7f55de3d06..bf7b85dc94 100644 --- a/packages/create-threenative/AGENTS.md +++ b/packages/create-threenative/AGENTS.md @@ -79,12 +79,12 @@ builds locally can still fail there — check it before claiming the scaffold wo ## CLI surface -Two `threenative` commands, ever: `build` (`--target web|desktop|android|ios`) and `doctor` +The `threenative` commands are `build` (`--target web|desktop|android|ios`) and `doctor` (`--text` prints the person-readable report; it checks rather than builds, borrowed whole from `npm doctor` and `flutter doctor`). `__tests__/cli.spec.ts` derives the advertised list from the -real executable and rejects anything else, so this document cannot outgrow the binary. A third -command needs the owner decision made again — v1 shipped 178 command forms and a 2,477-word root -help. The scaffolder itself takes a target directory plus `inspect [--json]`; its flags stay +real executable and rejects anything else, so this document cannot outgrow the binary. A new +command borrows its name from an established CLI (`npm`, `wrangler`, `vercel`), never a new word. +The scaffolder itself takes a target directory plus `inspect [--json]`; its flags stay boring: `--template`, `--no-install`, and the `--*-package` overrides CI uses to test against local tarballs. `pnpm dev` inside a generated project is a package script, never a CLI command. diff --git a/packages/create-threenative/CLAUDE.md b/packages/create-threenative/CLAUDE.md index 1463a2e77b..0a84695f87 100644 --- a/packages/create-threenative/CLAUDE.md +++ b/packages/create-threenative/CLAUDE.md @@ -81,12 +81,12 @@ builds locally can still fail there — check it before claiming the scaffold wo ## CLI surface -Two `threenative` commands, ever: `build` (`--target web|desktop|android|ios`) and `doctor` +The `threenative` commands are `build` (`--target web|desktop|android|ios`) and `doctor` (`--text` prints the person-readable report; it checks rather than builds, borrowed whole from `npm doctor` and `flutter doctor`). `__tests__/cli.spec.ts` derives the advertised list from the -real executable and rejects anything else, so this document cannot outgrow the binary. A third -command needs the owner decision made again — v1 shipped 178 command forms and a 2,477-word root -help. The scaffolder itself takes a target directory plus `inspect [--json]`; its flags stay +real executable and rejects anything else, so this document cannot outgrow the binary. A new +command borrows its name from an established CLI (`npm`, `wrangler`, `vercel`), never a new word. +The scaffolder itself takes a target directory plus `inspect [--json]`; its flags stay boring: `--template`, `--no-install`, and the `--*-package` overrides CI uses to test against local tarballs. `pnpm dev` inside a generated project is a package script, never a CLI command. diff --git a/packages/create-threenative/src/commands.ts b/packages/create-threenative/src/commands.ts index 5eecaa8bae..ae7d4ebc86 100644 --- a/packages/create-threenative/src/commands.ts +++ b/packages/create-threenative/src/commands.ts @@ -1,8 +1,6 @@ /** The complete `threenative` command surface, in one place so the help text, the dispatcher and - * the documentation checks cannot disagree. Adding a command means adding it here, teaching - * `threenative.ts` to run it, and re-making the owner decision recorded in AGENTS.md — v1 - * shipped 178 command forms, in a product whose founding constraint is that models are bad at - * discovering novel APIs. */ + * the documentation checks cannot disagree. Adding a command means adding it here and teaching + * `threenative.ts` to run it. */ export type PublicCommand = "build" | "doctor"; export const threenativeCommands: readonly PublicCommand[] = ["build", "doctor"]; From 02bada91b3dadcfc376b1cab728e03aedc9d03eb Mon Sep 17 00:00:00 2001 From: Joao Paulo Furtado Date: Sat, 21 Nov 2026 18:54:12 -0700 Subject: [PATCH 03/20] docs(prd): PRD-904 deploy matches Studio's Publish share link; login is the site device flow in TypeScript --- ...in-and-deploy-publish-like-studio-share.md | 115 ++++++++++++++++++ ...oy-reuse-the-store-device-flow-and-push.md | 114 ----------------- 2 files changed, 115 insertions(+), 114 deletions(-) create mode 100644 docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md delete mode 100644 docs/PRDs/tooling/PRD-904-tn-login-and-deploy-reuse-the-store-device-flow-and-push.md diff --git a/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md b/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md new file mode 100644 index 0000000000..4c2beac7cd --- /dev/null +++ b/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md @@ -0,0 +1,115 @@ +--- +prd_contract: v1 +--- + +# PRD-904 — `threenative login` and `threenative deploy`: publish from the terminal the way Studio's Publish button does + +**Status:** NOT STARTED +**Priority:** P1 — AC-1 to AC-7 are open: a game built outside Studio has no command to sign in or put it online, so an agent stops at a local build. +**Complexity:** 7 (HIGH) — 6-10 files (+2), new module (+2), crosses the engine/site/Studio release boundaries (+2), external API: the threenative.com and Studio Workers (+1); risk: an account credential on disk. +**Owner:** João +**Depends on:** None +**Repo:** this repo (`packages/create-threenative`); `ThreeNativeHQ/threenative-site` (token check); `threenative-live-studio` (CLI share route) + +## Context + +Studio already publishes a game. The terminal must do the same thing, with the same account and the same result. + +**Studio's Publish today** (`threenative-live-studio`): + +1. The browser calls `POST /api/projects/:id/share` (`hosting/cloudflare/src/routes/games.ts:14-36`), with a Studio session cookie. +2. The game's sandbox runs the `build:web` script (`src/server/routes/release.ts:47-77`). In every template that script is `threenative build --target web`. It then packs `dist/` with `packDirectory` (`src/server/release/shareArchive.ts`): per file a u32 path length, the path, a u32 size and the bytes. It skips `.br`/`.gz` twins, and the limits are 2 000 files and 50 MB. +3. `publishShare` (`hosting/cloudflare/src/share.ts:133-200`) checks the archive, puts the files in R2 under `share//` and keeps one link per game. A new publish replaces the files behind the same address. A link nobody opens for 30 days expires (`shareRules.ts`). +4. The answer is `{ shareUrl }`, an unlisted `https://-xxxx-share…` address (`origin.ts:77-81`). + +**Accounts:** the site Worker owns accounts. Studio signs a person in with a one-time code that it trades over the `StudioAccounts` service binding (`threenative-site/worker/studio-auth.ts:81`). The site already has a device-code login for command lines: `POST /api/store/device`, `/device/token`, `/device/approve`, and the `/account/device/?code=…` page (`worker/store-device.ts`, store PRD-808). It issues a scoped `api_tokens` row. + +**Engine:** `threenative` has `build` and `doctor` (`packages/create-threenative/src/commands.ts`). The "two commands, ever" rule was removed in `f9d168b00`. + +## Solution + +```mermaid +sequenceDiagram + participant A as Agent or person + participant C as threenative CLI + participant W as threenative.com (site) + participant S as Studio Worker + A->>C: threenative login + C->>W: POST /api/store/device + C-->>A: opens /account/device/?code=ABCD-EFGH, prints the code too + A->>W: sign in, click Authorize + C->>W: poll /device/token -> token -> ~/.config/threenative/auth.json (0600) + A->>C: threenative deploy + C->>C: run build:web, pack dist/ (Studio's archive format) + C->>S: PUT /api/cli/share Bearer token, game id from threenative.deploy.json + S->>W: StudioAccounts.tokenAccount(token) over the service binding + S->>S: find or create the project, publishShare + S-->>C: { projectId, shareUrl } + C-->>A: https://-xxxx-share.../ (same address on every later deploy) +``` + +- **`threenative login`:** the device flow, in TypeScript with `fetch` and no new dependency. It opens the link with the code filled in, prints the code for a browser on another machine, and polls at the interval the site states until the user clicks Authorize. It prints the account email. `threenative logout` deletes the token file. +- **Token:** `$XDG_CONFIG_HOME/threenative/auth.json` (default `~/.config`), mode `0600`, the same pattern as `gh` and `wrangler`. `THREENATIVE_TOKEN` overrides it for CI and Studio sandboxes. +- **`threenative deploy`:** runs the project's `build:web` script, the same script Studio's sandbox runs. It packs `dist/` with a copy of Studio's `packDirectory`. It uploads to `PUT /api/cli/share` and writes `threenative.deploy.json` `{ "projectId": "…" }` on the first deploy, so later deploys replace the same link. Exit codes match `tn-store`: 0 ok, 2 bad arguments, 3 sign in again, 4 refused, 5 network. +- **Site:** `StudioAccounts.tokenAccount(token)` returns the same identity shape as `exchangeCode` for a live, unrevoked device-issued token. Studio therefore reuses its existing account adoption. The `/account/device` page copy names `threenative login` instead of `tn-store login` only. +- **Studio:** one route, `PUT /api/cli/share`, with an archive body, `Authorization: Bearer`, and an optional `projectId` and `name`. It reuses `createProject` (quota included) and `publishShare` (all its checks), so the terminal and the button have one set of rules. + +Risks: the packer is copied, and the copy can drift from Studio's. `ponytail:` two copies of a 50-line format; the AC-6 e2e uploads the CLI's archive to Studio's real parser, so drift fails there. Move it to one shared package if a third writer appears. A token file on disk is a credential: it is created `0600`, and logout deletes it. + +## Non-Goals + +- Opening a CLI-deployed game's source in the Studio editor. The project row exists and shows its link, but deploy uploads the build, not the source. +- Listing on the store (`tn-store push`, review, build farm). That path stays as it is. +- Deploy targets other than the Studio share link (Netlify, Vercel, itch.io, desktop or Android builds). +- A localhost callback login. It fails on remote machines and in containers, the reason the store dropped it (store PRD-808). + +## Acceptance Criteria + +- [ ] AC-1 [local]: `threenative login` against local site `wrangler dev` opens `/account/device/?code=…`. After a scripted Authorize it writes a `0600` token file and prints the account email. proof: `pnpm exec vitest run packages/create-threenative/__tests__/login.spec.ts` (fake site) + the AC-6 run — Evidence: pending. +- [ ] AC-2 [local]: `threenative logout` deletes the file. `THREENATIVE_TOKEN` wins over the file, and a refused token exits 3 with "run threenative login". proof: `login.spec.ts` — Evidence: pending. +- [ ] AC-3 [local]: `StudioAccounts.tokenAccount` returns the account for a live device-issued token and refuses a revoked, expired or unknown one. proof: site `pnpm vitest --config vitest.worker.config.ts worker/__tests__/studio-auth.spec.ts` — Evidence: pending. +- [ ] AC-4 [local]: `PUT /api/cli/share` with a valid token creates a project and returns a share URL. A second call with that `projectId` keeps the same URL and serves the new build. No token gets 401; no `index.html` or over 50 MB gets Studio's refusal message. proof: Studio `hosting/cloudflare` vitest — Evidence: pending. +- [ ] AC-5 [local]: `threenative deploy` runs `build:web`, packs `dist/` byte-for-byte like Studio's `packDirectory` on the same folder, uploads, writes `threenative.deploy.json` once and prints the URL. proof: `pnpm exec vitest run packages/create-threenative/__tests__/deploy.spec.ts` — Evidence: pending. +- [ ] AC-6 [local]: A scaffolded starter, with the local `create-threenative` tarball, local site and Studio `wrangler dev`, runs `threenative login` (scripted Authorize) then `threenative deploy` twice. The share URL serves the game's `index.html` and stays the same across both deploys. The Studio games list shows the game with that link. proof: run log in the PR — Evidence: pending. +- [ ] AC-7 [shared]: After site, Studio and engine releases, a `pnpm sandbox` clean room runs `npx create-threenative` → `npx threenative login` → `npx threenative deploy` and opens the live share URL. proof: `pnpm sandbox` run log — Evidence: pending. + +## Blocked on + +- AC-7 needs the site and Studio routes deployed to production and an engine release — unblocked by João's go-ahead to deploy the site and Studio and ship the engine release. + +## Integration Ledger + +| Capability | Reachable consumer/trigger | Replaces / disposition | Evidence | +| --- | --- | --- | --- | +| Sign in from a terminal | `threenative login` → site device routes → token file | New consumer of the shipped device flow | AC-1, AC-2, AC-6 | +| Studio trusts a CLI token | Studio `PUT /api/cli/share` → `StudioAccounts.tokenAccount` | New method beside `exchangeCode` | AC-3, AC-4 | +| Publish from a terminal | `threenative deploy` → `build:web` → Studio `publishShare` → share host | Same `publishShare` as the Publish button; no second publish path | AC-4, AC-5, AC-6 | + +Fill the dispatcher and route `file:line` values when each phase lands. + +## Decisions + +- 2026-11-21 (João): use the `threenative` CLI as it is, with no `tn` alias. The "two commands, ever" rule is removed (`f9d168b00`). +- 2026-11-21 (João): deploy is the same as Studio's Publish (the share link), not the store push. +- 2026-11-21 (João): login UX: open a link, sign in with the threenative.com account, click Authorize, and the CLI detects it. The code is also accepted typed. The existing site device flow does exactly this. +- 2026-11-21 (agent): the login is TypeScript in the engine, not a call to the private `tn-store` binary. Deploy no longer needs that binary, and the device flow is three `fetch` calls. + +## Execution Phases + +#### Phase 1: sign in and out +**Status:** NOT STARTED +**Files:** `packages/create-threenative/src/commands.ts`, `src/threenative.ts` (dispatch), `src/account.ts` (new: device flow, token file, `THREENATIVE_TOKEN`), `AGENTS.md` CLI surface. Site: `src/components/sections/AccountDevice.tsx` copy. +- [ ] `login`/`logout` work against a fake site — proof: `login.spec.ts` + `cli.spec.ts` lists the new commands — covers AC-1, AC-2. + +#### Phase 2: Studio accepts a CLI publish +**Status:** NOT STARTED +**Files:** site `worker/studio-auth.ts` (`tokenAccount`). Studio `hosting/cloudflare/src/routes/cli.ts` (new: `PUT /api/cli/share`), `src/index.ts` (route before the session gate). +- [ ] The token check passes its site tests — proof: site worker vitest — covers AC-3. +- [ ] The CLI share route passes its Studio tests — proof: Studio `hosting/cloudflare` vitest — covers AC-4. + +#### Phase 3: `threenative deploy` end to end +**Status:** NOT STARTED +**Files:** `packages/create-threenative/src/deploy.ts` (new: build, pack, upload, link file), `src/threenative.ts`, `src/commands.ts`. +- [ ] Deploy unit behaviour — proof: `deploy.spec.ts` — covers AC-5. +- [ ] Local end-to-end through both real Workers — proof: AC-6 run log — covers AC-6. +- [ ] Live clean-room deploy — proof: `pnpm sandbox` — covers AC-7. diff --git a/docs/PRDs/tooling/PRD-904-tn-login-and-deploy-reuse-the-store-device-flow-and-push.md b/docs/PRDs/tooling/PRD-904-tn-login-and-deploy-reuse-the-store-device-flow-and-push.md deleted file mode 100644 index ff679579bc..0000000000 --- a/docs/PRDs/tooling/PRD-904-tn-login-and-deploy-reuse-the-store-device-flow-and-push.md +++ /dev/null @@ -1,114 +0,0 @@ ---- -prd_contract: v1 ---- - -# PRD-904 — `tn login` and `tn deploy`: the engine CLI signs in and ships a game with the store's flow - -**Status:** NOT STARTED -**Priority:** P1 — AC-1 to AC-6 are open: a generated game has no command to sign in or put it online, so an agent stops at a local build. -**Complexity:** 6 (MEDIUM) — 1-5 files (+1), new module (+2), crosses the engine/store release boundary (+2), external API: the threenative.com store routes (+1); risk override: HIGH, the change handles an account credential. -**Owner:** João -**Depends on:** PRD-811 (store repo) AC-2, which publishes `@threenative/store-cli` to npm -**Repo:** this repo (`packages/create-threenative`); `ThreeNativeHQ/threenative-store` for the e2e proof - -## Context - -The server and the client for sign-in and deploy already exist. They live in the private repos and the engine CLI does not reach them. - -| Piece | Where | State | -| --- | --- | --- | -| Device-code login: `POST /api/store/device`, `/device/token`, `/device/approve` | site `worker/store-device.ts`, `migrations/0019_device_codes.sql`, page `/account/device` | Shipped (store PRD-808 AC-1..3). Works with no loopback port: containers, remote boxes, agents. | -| Scoped API tokens (`push`, `snapshot:read`, `build:upload`) | site `worker/auth.ts`, `migrations/0014_build_token_scope.sql` | Shipped | -| `tn-store login · logout · whoami · games · push · status`, `--json`, exit codes 0/2/3/4/5, OS keychain, `TN_STORE_TOKEN` for CI | store `crates/tn-store-cli/src/main.rs:9-60`, `lib.rs:77-86` | Shipped as a Rust binary. Not on npm yet (PRD-811 AC-2 open; `npm view @threenative/store-cli` returns 404 on 2026-11-21). | -| Push: FastCDC chunks, missing-chunk check, snapshot, release poll | store `crates/tn-store-cli/src/push.rs`, `crates/tn-store-core/src/pack.rs` | Shipped. The store builds from source, so a deploy pushes source. | -| Live web build hosting on `-play.threenative.com` | site `worker/host.ts:24-35` | Shipped | -| Studio sign-in (browser redirect + one-time code over a service binding) | site `worker/studio-auth.ts`, `migrations/0029_studio_auth_codes.sql` | Shipped. Browser-only, so the CLI does not use it. Studio publishes with `TN_STORE_TOKEN` (`threenative-live-studio/src/server/config.ts:63`), the same variable this PRD honours. | - -The engine side: `threenative` (bin of `create-threenative`) has two commands, `build` and `doctor` (`packages/create-threenative/src/commands.ts:6-8`). `packages/create-threenative/AGENTS.md` "CLI surface" says a third command needs the owner decision made again. No `tn` bin exists. The npm name `tn` belongs to an unrelated package (Titanium CLI wrapper, 4.2.1). - -## Solution - -`tn` becomes a second bin name for the `threenative` executable. Three borrowed commands (the `wrangler` and `vercel` vocabulary) join `build` and `doctor`: `login`, `logout`, `deploy`. Each one delegates to the store CLI. The engine re-implements no HTTP client, no chunker and no token store. - -```mermaid -sequenceDiagram - participant A as Agent or person - participant T as tn (create-threenative) - participant S as tn-store binary - participant W as threenative.com Worker - A->>T: tn login - T->>S: tn-store login [--json] - S->>W: POST /api/store/device - S-->>A: URL + user code - A->>W: approve on /account/device - S->>W: poll /device/token -> push token -> OS keychain - A->>T: tn deploy - T->>T: read .tn-store.json gameId, package.json version - T->>S: tn-store push . --version --json - S->>W: chunks, snapshot, release - T->>S: tn-store status --json (poll) - T-->>A: state live -> https://-play.threenative.com/ -``` - -- **Binary resolution:** `tn-store` on `PATH` first (a cargo build, a test stub), else `npm exec --yes @threenative/store-cli@ --`. The engine package takes no dependency on the private binary. -- **Game link:** `.tn-store.json` `{ "gameId": "..." }` in the project root, committed. The store's push already ignores this file name (`crates/tn-store-cli/src/ignore.rs:25`). `tn deploy --game ` writes it. With no link and no flag, `tn deploy` exits 2 and prints the `tn-store games create` line and the site URL. -- **Version:** `package.json` `version`. A refusal from the store (for example a reused version) passes through with its exit code and message. -- **Exit codes and `--json`:** pass through unchanged from `tn-store`, so an agent reads one table for both CLIs. -- **CI and Studio:** `TN_STORE_TOKEN` works unchanged, because `tn-store` reads it. - -Risks: the PRD-811 publish is the gate for any user outside this machine. `npx tn` outside a project resolves the unrelated npm `tn` package, so docs show `npx tn` only inside a generated project, where the local bin resolves first. - -## Non-Goals - -- Creating the store listing from the CLI without screenshots. The site requires 1 to 5 shots (`worker/games.ts:587`); `tn-store games create` already covers it. -- A TypeScript port of the push protocol or the chunk format. -- Deploy targets other than the ThreeNative store (Netlify, Vercel, itch.io). -- Changes to the site Worker, its schema or the device flow. - -## Acceptance Criteria - -- [ ] AC-1 [local]: `tn login` and `tn logout` run `tn-store login` and `tn-store logout` with the same flags, and return its exit code. proof: `pnpm exec vitest run packages/create-threenative/__tests__/cli.spec.ts` with a stub `tn-store` on `PATH` that records its argv — Evidence: pending. -- [ ] AC-2 [local]: `tn --help` and `threenative --help` list exactly `build`, `doctor`, `login`, `logout`, `deploy`, and `tn` is the same executable. proof: `cli.spec.ts` (derives the list from the real executable) — Evidence: pending. -- [ ] AC-3 [local]: `tn deploy` with no `.tn-store.json` and no `--game` exits 2 and names the create command; `tn deploy --game ` writes the link. proof: `cli.spec.ts` — Evidence: pending. -- [ ] AC-4 [local]: `tn deploy` pushes `.` at the `package.json` version, polls `status --json` until `live` or `held`, prints the play URL on `live` and the `reason` on `held`, and passes exit code 3 through as "sign in again". proof: `cli.spec.ts` with the recording stub — Evidence: pending. -- [ ] AC-5 [local]: A scaffolded starter, with the local `create-threenative` tarball and a real `tn-store` built from the store repo, signs in with a scripted approval and deploys against local `wrangler dev`; the release reaches `live` and the play host serves its `index.html`. proof: store repo PRD-810 e2e harness, run on this machine — Evidence: pending. -- [ ] AC-6 [shared]: In a `pnpm sandbox` clean room with the published packages, `npx create-threenative` → `npx tn login` → `npx tn deploy` puts the game live on threenative.com. proof: `pnpm sandbox` run log — Evidence: pending. - -## Blocked on - -- AC-6 needs `@threenative/store-cli` on npm — unblocked by store PRD-811 AC-2 (`NPM_TOKEN` in the store repo, an owner action) and by the next engine release that carries this PRD. - -## Integration Ledger - -| Capability | Reachable consumer/trigger | Replaces / disposition | Evidence | -| --- | --- | --- | --- | -| Sign in from a game project | `tn login` → `threenative.ts` dispatcher → `tn-store login` → site device routes | New; delegates to the shipped flow | AC-1, AC-5 | -| Deploy a game | `tn deploy` → `.tn-store.json` + `tn-store push`/`status` → `-play.threenative.com` | New; delegates to the shipped push | AC-3, AC-4, AC-5 | - -Fill the `threenative.ts` dispatcher `file:line` when Phase 1 lands. - -## Decisions - -- 2026-11-21 (João): reopen the "two `threenative` commands, ever" rule for `login`, `logout` and `deploy`. Reason: a game an agent cannot put online is unfinished. The words are borrowed from `wrangler` and `vercel`, not invented, which keeps the charter's closed "bespoke CLI vocabulary" rule intact. -- 2026-11-21 (agent): delegate to the `tn-store` binary instead of porting it to TypeScript. A port duplicates the FastCDC format and the token store, and drift between two chunkers breaks the store's missing-chunk check. -- 2026-11-21 (agent): `tn` is a second bin name of the same executable, not a new package. The npm name `tn` is taken. - -## Execution Phases - -#### Phase 1: `tn` signs in and out -**Status:** NOT STARTED -**Files:** `packages/create-threenative/package.json` (`tn` bin), `src/commands.ts` (three commands), `src/threenative.ts` (dispatch), `src/store-cli.ts` (new: resolve and spawn `tn-store`), `AGENTS.md` "CLI surface" (five commands, this PRD as the decision). -**Implementation:** spawn with inherited stdio, so the device-code prompt and `--json` output reach the caller untouched. A spawn failure (no `tn-store`, no `npm`) exits 5 with the install line. -- [ ] AC-1 and AC-2 pass — proof: `pnpm exec vitest run packages/create-threenative/__tests__/cli.spec.ts` and `pnpm sync:agents && pnpm check:docs` — covers AC-1, AC-2. - -#### Phase 2: `tn deploy` ships the project -**Status:** NOT STARTED -**Files:** `packages/create-threenative/src/store-cli.ts` (deploy), the generated-project `AGENTS.md` Commands block in each template that lists commands. -**Implementation:** read and write `.tn-store.json`; validate `gameId` against the site's id shape before it reaches argv. Poll `status --json` one second apart, 60 polls, the same budget as `push.rs:21`. -- [ ] AC-3 and AC-4 pass — proof: `cli.spec.ts` — covers AC-3, AC-4. - -#### Phase 3: proof through the real binary and the real Worker -**Status:** NOT STARTED -**Files:** none in this repo unless the e2e run finds a bug; the e2e case lives in the store repo harness. -- [ ] AC-5 passes on this machine — proof: store repo PRD-810 e2e harness with the local tarball — covers AC-5, the real device flow and the real push. -- [ ] AC-6 passes in the clean room after the publish — proof: `pnpm sandbox` — covers AC-6. From 4d1bff03a153a05fd4b6fdc9a8af40e4571ad086 Mon Sep 17 00:00:00 2001 From: Joao Paulo Furtado Date: Sat, 21 Nov 2026 18:55:22 -0700 Subject: [PATCH 04/20] docs(prd): PRD-904 folds in the Gemini review: logout revokes, terms rule on CLI tokens, .threenative/ link, device page keeps the code --- ...in-and-deploy-publish-like-studio-share.md | 23 +++++++++++-------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md b/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md index 4c2beac7cd..598b8efa4a 100644 --- a/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md +++ b/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md @@ -5,7 +5,7 @@ prd_contract: v1 # PRD-904 — `threenative login` and `threenative deploy`: publish from the terminal the way Studio's Publish button does **Status:** NOT STARTED -**Priority:** P1 — AC-1 to AC-7 are open: a game built outside Studio has no command to sign in or put it online, so an agent stops at a local build. +**Priority:** P1 — AC-1 to AC-8 are open: a game built outside Studio has no command to sign in or put it online, so an agent stops at a local build. **Complexity:** 7 (HIGH) — 6-10 files (+2), new module (+2), crosses the engine/site/Studio release boundaries (+2), external API: the threenative.com and Studio Workers (+1); risk: an account credential on disk. **Owner:** João **Depends on:** None @@ -41,17 +41,17 @@ sequenceDiagram C->>W: poll /device/token -> token -> ~/.config/threenative/auth.json (0600) A->>C: threenative deploy C->>C: run build:web, pack dist/ (Studio's archive format) - C->>S: PUT /api/cli/share Bearer token, game id from threenative.deploy.json - S->>W: StudioAccounts.tokenAccount(token) over the service binding + C->>S: PUT /api/cli/share Bearer token, projectId from .threenative/share.json + S->>W: StudioAccounts.tokenAccount(token) over the service binding (verified email + current terms) S->>S: find or create the project, publishShare S-->>C: { projectId, shareUrl } C-->>A: https://-xxxx-share.../ (same address on every later deploy) ``` -- **`threenative login`:** the device flow, in TypeScript with `fetch` and no new dependency. It opens the link with the code filled in, prints the code for a browser on another machine, and polls at the interval the site states until the user clicks Authorize. It prints the account email. `threenative logout` deletes the token file. +- **`threenative login`:** the device flow, in TypeScript with `fetch` and no new dependency. It opens the link with the code filled in, prints the code for a browser on another machine, and polls at the interval the site states until the user clicks Authorize. It prints the account email. `threenative logout` revokes the token on the site (a new bearer `DELETE /api/store/token`; today revoke needs a browser session, `worker/store.ts:202`) and then deletes the file. - **Token:** `$XDG_CONFIG_HOME/threenative/auth.json` (default `~/.config`), mode `0600`, the same pattern as `gh` and `wrangler`. `THREENATIVE_TOKEN` overrides it for CI and Studio sandboxes. -- **`threenative deploy`:** runs the project's `build:web` script, the same script Studio's sandbox runs. It packs `dist/` with a copy of Studio's `packDirectory`. It uploads to `PUT /api/cli/share` and writes `threenative.deploy.json` `{ "projectId": "…" }` on the first deploy, so later deploys replace the same link. Exit codes match `tn-store`: 0 ok, 2 bad arguments, 3 sign in again, 4 refused, 5 network. -- **Site:** `StudioAccounts.tokenAccount(token)` returns the same identity shape as `exchangeCode` for a live, unrevoked device-issued token. Studio therefore reuses its existing account adoption. The `/account/device` page copy names `threenative login` instead of `tn-store login` only. +- **`threenative deploy`:** runs the project's `build:web` script, the same script Studio's sandbox runs. It packs `dist/` with a copy of Studio's `packDirectory`. It uploads to `PUT /api/cli/share` and writes `.threenative/share.json` `{ "projectId": "…" }` on the first deploy (Studio already keeps its store link in `.threenative/store.json`, `src/server/release/publish.ts:36`), so later deploys replace the same link. Exit codes match `tn-store`: 0 ok, 2 bad arguments, 3 sign in again, 4 refused, 5 network. +- **Site:** `StudioAccounts.tokenAccount(token)` returns the same identity shape as `exchangeCode` for a live, unrevoked device-issued token, under the same rule as `exchangeCode`: verified email and current terms (`studio-auth.ts:42`). Studio therefore reuses its existing account adoption. The `/account/device` page names `threenative login` instead of `tn-store login`. An unverified or terms-pending account goes through the verify and terms steps and comes back to the same `?code=`. - **Studio:** one route, `PUT /api/cli/share`, with an archive body, `Authorization: Bearer`, and an optional `projectId` and `name`. It reuses `createProject` (quota included) and `publishShare` (all its checks), so the terminal and the button have one set of rules. Risks: the packer is copied, and the copy can drift from Studio's. `ponytail:` two copies of a 50-line format; the AC-6 e2e uploads the CLI's archive to Studio's real parser, so drift fails there. Move it to one shared package if a third writer appears. A token file on disk is a credential: it is created `0600`, and logout deletes it. @@ -66,11 +66,12 @@ Risks: the packer is copied, and the copy can drift from Studio's. `ponytail:` t ## Acceptance Criteria - [ ] AC-1 [local]: `threenative login` against local site `wrangler dev` opens `/account/device/?code=…`. After a scripted Authorize it writes a `0600` token file and prints the account email. proof: `pnpm exec vitest run packages/create-threenative/__tests__/login.spec.ts` (fake site) + the AC-6 run — Evidence: pending. -- [ ] AC-2 [local]: `threenative logout` deletes the file. `THREENATIVE_TOKEN` wins over the file, and a refused token exits 3 with "run threenative login". proof: `login.spec.ts` — Evidence: pending. -- [ ] AC-3 [local]: `StudioAccounts.tokenAccount` returns the account for a live device-issued token and refuses a revoked, expired or unknown one. proof: site `pnpm vitest --config vitest.worker.config.ts worker/__tests__/studio-auth.spec.ts` — Evidence: pending. +- [ ] AC-2 [local]: `threenative logout` revokes the token on the site, then deletes the file. `THREENATIVE_TOKEN` wins over the file, and a refused token exits 3 with "run threenative login". proof: `login.spec.ts` — Evidence: pending. +- [ ] AC-3 [local]: `StudioAccounts.tokenAccount` returns the account for a live device-issued token and refuses a revoked, expired or unknown token, an unverified email and an account without current terms. proof: site `pnpm vitest --config vitest.worker.config.ts worker/__tests__/studio-auth.spec.ts` — Evidence: pending. - [ ] AC-4 [local]: `PUT /api/cli/share` with a valid token creates a project and returns a share URL. A second call with that `projectId` keeps the same URL and serves the new build. No token gets 401; no `index.html` or over 50 MB gets Studio's refusal message. proof: Studio `hosting/cloudflare` vitest — Evidence: pending. -- [ ] AC-5 [local]: `threenative deploy` runs `build:web`, packs `dist/` byte-for-byte like Studio's `packDirectory` on the same folder, uploads, writes `threenative.deploy.json` once and prints the URL. proof: `pnpm exec vitest run packages/create-threenative/__tests__/deploy.spec.ts` — Evidence: pending. +- [ ] AC-5 [local]: `threenative deploy` runs `build:web`, packs `dist/` byte-for-byte like Studio's `packDirectory` on the same folder, uploads, writes `.threenative/share.json` once and prints the URL. proof: `pnpm exec vitest run packages/create-threenative/__tests__/deploy.spec.ts` — Evidence: pending. - [ ] AC-6 [local]: A scaffolded starter, with the local `create-threenative` tarball, local site and Studio `wrangler dev`, runs `threenative login` (scripted Authorize) then `threenative deploy` twice. The share URL serves the game's `index.html` and stays the same across both deploys. The Studio games list shows the game with that link. proof: run log in the PR — Evidence: pending. +- [ ] AC-8 [local]: On `/account/device/?code=…`, an unverified or terms-pending account completes verify and terms and returns to the same code, then Authorize succeeds. The page names `threenative login`. proof: site `e2e/worker/store-device.spec.ts` — Evidence: pending. - [ ] AC-7 [shared]: After site, Studio and engine releases, a `pnpm sandbox` clean room runs `npx create-threenative` → `npx threenative login` → `npx threenative deploy` and opens the live share URL. proof: `pnpm sandbox` run log — Evidence: pending. ## Blocked on @@ -92,14 +93,16 @@ Fill the dispatcher and route `file:line` values when each phase lands. - 2026-11-21 (João): use the `threenative` CLI as it is, with no `tn` alias. The "two commands, ever" rule is removed (`f9d168b00`). - 2026-11-21 (João): deploy is the same as Studio's Publish (the share link), not the store push. - 2026-11-21 (João): login UX: open a link, sign in with the threenative.com account, click Authorize, and the CLI detects it. The code is also accepted typed. The existing site device flow does exactly this. +- 2026-11-21 (agent, after a Gemini 4 Neon review): the store push is not the deploy path. A new account's release is held for review (`worker/games.ts:631,649`), the build farm runs scans and an AI review, and a listing needs 1 to 5 screenshots. The share link is live in seconds. - 2026-11-21 (agent): the login is TypeScript in the engine, not a call to the private `tn-store` binary. Deploy no longer needs that binary, and the device flow is three `fetch` calls. ## Execution Phases #### Phase 1: sign in and out **Status:** NOT STARTED -**Files:** `packages/create-threenative/src/commands.ts`, `src/threenative.ts` (dispatch), `src/account.ts` (new: device flow, token file, `THREENATIVE_TOKEN`), `AGENTS.md` CLI surface. Site: `src/components/sections/AccountDevice.tsx` copy. +**Files:** `packages/create-threenative/src/commands.ts`, `src/threenative.ts` (dispatch), `src/account.ts` (new: device flow, token file, `THREENATIVE_TOKEN`), `AGENTS.md` CLI surface. Site: `worker/store.ts` (bearer self-revoke), `src/components/sections/AccountDevice.tsx` and `AccountVerify.tsx` (copy, keep `?code=` through verify and terms). - [ ] `login`/`logout` work against a fake site — proof: `login.spec.ts` + `cli.spec.ts` lists the new commands — covers AC-1, AC-2. +- [ ] The device page keeps the code through verify and terms — proof: site `e2e/worker/store-device.spec.ts` — covers AC-8. #### Phase 2: Studio accepts a CLI publish **Status:** NOT STARTED From f616c5409b8d19a80647f570a750183a09da69ee Mon Sep 17 00:00:00 2001 From: Joao Paulo Furtado Date: Sat, 21 Nov 2026 19:45:13 -0700 Subject: [PATCH 05/20] docs(prd): PRD-904 records the tokenAccount and terms-on-approve decisions --- ...ative-login-and-deploy-publish-like-studio-share.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md b/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md index 598b8efa4a..a3848709cc 100644 --- a/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md +++ b/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md @@ -4,7 +4,7 @@ prd_contract: v1 # PRD-904 — `threenative login` and `threenative deploy`: publish from the terminal the way Studio's Publish button does -**Status:** NOT STARTED +**Status:** PARTIAL — phases 1 to 3 in progress **Priority:** P1 — AC-1 to AC-8 are open: a game built outside Studio has no command to sign in or put it online, so an agent stops at a local build. **Complexity:** 7 (HIGH) — 6-10 files (+2), new module (+2), crosses the engine/site/Studio release boundaries (+2), external API: the threenative.com and Studio Workers (+1); risk: an account credential on disk. **Owner:** João @@ -95,23 +95,25 @@ Fill the dispatcher and route `file:line` values when each phase lands. - 2026-11-21 (João): login UX: open a link, sign in with the threenative.com account, click Authorize, and the CLI detects it. The code is also accepted typed. The existing site device flow does exactly this. - 2026-11-21 (agent, after a Gemini 4 Neon review): the store push is not the deploy path. A new account's release is held for review (`worker/games.ts:631,649`), the build farm runs scans and an AI review, and a listing needs 1 to 5 screenshots. The share link is live in seconds. - 2026-11-21 (agent): the login is TypeScript in the engine, not a call to the private `tn-store` binary. Deploy no longer needs that binary, and the device flow is three `fetch` calls. +- 2026-11-21 (agent, implementation): `tokenAccount` accepts any live `push` token, not only a device-issued one. The daily sweep deletes the `device_codes` row that links a token to its device, so "device-issued" cannot be checked after day one. A `push` token is the CLI's write key whichever way it was made. It also refuses a `full` account ban, the same check every store token read makes (PRD-820). +- 2026-11-21 (agent, implementation): `/api/store/device/approve` now refuses an account without the current terms (`TN_API_TERMS`), beside the existing unverified check. Without it, a terms-pending account would get a token that `tokenAccount` refuses on every deploy. This also applies to `tn-store login`, under the PRD-015 consent rule. ## Execution Phases #### Phase 1: sign in and out -**Status:** NOT STARTED +**Status:** PARTIAL — phases 1 to 3 in progress **Files:** `packages/create-threenative/src/commands.ts`, `src/threenative.ts` (dispatch), `src/account.ts` (new: device flow, token file, `THREENATIVE_TOKEN`), `AGENTS.md` CLI surface. Site: `worker/store.ts` (bearer self-revoke), `src/components/sections/AccountDevice.tsx` and `AccountVerify.tsx` (copy, keep `?code=` through verify and terms). - [ ] `login`/`logout` work against a fake site — proof: `login.spec.ts` + `cli.spec.ts` lists the new commands — covers AC-1, AC-2. - [ ] The device page keeps the code through verify and terms — proof: site `e2e/worker/store-device.spec.ts` — covers AC-8. #### Phase 2: Studio accepts a CLI publish -**Status:** NOT STARTED +**Status:** PARTIAL — phases 1 to 3 in progress **Files:** site `worker/studio-auth.ts` (`tokenAccount`). Studio `hosting/cloudflare/src/routes/cli.ts` (new: `PUT /api/cli/share`), `src/index.ts` (route before the session gate). - [ ] The token check passes its site tests — proof: site worker vitest — covers AC-3. - [ ] The CLI share route passes its Studio tests — proof: Studio `hosting/cloudflare` vitest — covers AC-4. #### Phase 3: `threenative deploy` end to end -**Status:** NOT STARTED +**Status:** PARTIAL — phases 1 to 3 in progress **Files:** `packages/create-threenative/src/deploy.ts` (new: build, pack, upload, link file), `src/threenative.ts`, `src/commands.ts`. - [ ] Deploy unit behaviour — proof: `deploy.spec.ts` — covers AC-5. - [ ] Local end-to-end through both real Workers — proof: AC-6 run log — covers AC-6. From f86cb43fb09df2c6ea6ba976404de93b2ec420d2 Mon Sep 17 00:00:00 2001 From: Joao Paulo Furtado Date: Sat, 21 Nov 2026 19:51:08 -0700 Subject: [PATCH 06/20] feat(create-threenative): threenative login, logout and deploy publish to the Studio share link (PRD-904) login runs the threenative.com device flow and saves a 0600 token (THREENATIVE_TOKEN overrides); logout revokes it on the site; deploy runs build:web, packs dist/ in Studio's share archive format, PUTs it to Studio's /api/cli/share and keeps the link in .threenative/share.json. --- ...in-and-deploy-publish-like-studio-share.md | 18 +- packages/create-threenative/AGENTS.md | 15 +- packages/create-threenative/CLAUDE.md | 15 +- .../create-threenative/__tests__/cli.spec.ts | 2 +- .../__tests__/deploy.spec.ts | 200 +++++++++++++++ .../__tests__/login.spec.ts | 190 ++++++++++++++ packages/create-threenative/src/account.ts | 236 ++++++++++++++++++ packages/create-threenative/src/commands.ts | 13 +- packages/create-threenative/src/deploy.ts | 169 +++++++++++++ .../create-threenative/src/threenative.ts | 82 +++++- 10 files changed, 912 insertions(+), 28 deletions(-) create mode 100644 packages/create-threenative/__tests__/deploy.spec.ts create mode 100644 packages/create-threenative/__tests__/login.spec.ts create mode 100644 packages/create-threenative/src/account.ts create mode 100644 packages/create-threenative/src/deploy.ts diff --git a/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md b/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md index a3848709cc..44c385690f 100644 --- a/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md +++ b/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md @@ -66,12 +66,12 @@ Risks: the packer is copied, and the copy can drift from Studio's. `ponytail:` t ## Acceptance Criteria - [ ] AC-1 [local]: `threenative login` against local site `wrangler dev` opens `/account/device/?code=…`. After a scripted Authorize it writes a `0600` token file and prints the account email. proof: `pnpm exec vitest run packages/create-threenative/__tests__/login.spec.ts` (fake site) + the AC-6 run — Evidence: pending. -- [ ] AC-2 [local]: `threenative logout` revokes the token on the site, then deletes the file. `THREENATIVE_TOKEN` wins over the file, and a refused token exits 3 with "run threenative login". proof: `login.spec.ts` — Evidence: pending. -- [ ] AC-3 [local]: `StudioAccounts.tokenAccount` returns the account for a live device-issued token and refuses a revoked, expired or unknown token, an unverified email and an account without current terms. proof: site `pnpm vitest --config vitest.worker.config.ts worker/__tests__/studio-auth.spec.ts` — Evidence: pending. -- [ ] AC-4 [local]: `PUT /api/cli/share` with a valid token creates a project and returns a share URL. A second call with that `projectId` keeps the same URL and serves the new build. No token gets 401; no `index.html` or over 50 MB gets Studio's refusal message. proof: Studio `hosting/cloudflare` vitest — Evidence: pending. +- [x] AC-2 [local]: `threenative logout` revokes the token on the site, then deletes the file. `THREENATIVE_TOKEN` wins over the file, and a refused token exits 3 with "run threenative login". proof: `login.spec.ts` — Evidence: `login.spec.ts` logout and env cases pass; `deploy.spec.ts` 401 exits 3; site `DELETE /api/store/token` case passes in `worker/__tests__/store-device.spec.ts`. +- [x] AC-3 [local]: `StudioAccounts.tokenAccount` returns the account for a live device-issued token and refuses a revoked, expired or unknown token, an unverified email and an account without current terms. proof: site `pnpm vitest --config vitest.worker.config.ts worker/__tests__/studio-auth.spec.ts` — Evidence: 13/13 in `studio-auth.spec.ts`, inside the 229/229 site worker run. +- [x] AC-4 [local]: `PUT /api/cli/share` with a valid token creates a project and returns a share URL. A second call with that `projectId` keeps the same URL and serves the new build. No token gets 401; no `index.html` or over 50 MB gets Studio's refusal message. proof: Studio `hosting/cloudflare` vitest — Evidence: `test/cli-share.spec.ts` 9/9 (create, same URL with new bytes, 401, 422 no `index.html`, 403 suspended and closed beta, 404 foreign project, 502 site down); the 50 MB refusal is `publishShare`'s own, covered by `test/share.spec.ts` in the same 359/359 run. - [ ] AC-5 [local]: `threenative deploy` runs `build:web`, packs `dist/` byte-for-byte like Studio's `packDirectory` on the same folder, uploads, writes `.threenative/share.json` once and prints the URL. proof: `pnpm exec vitest run packages/create-threenative/__tests__/deploy.spec.ts` — Evidence: pending. - [ ] AC-6 [local]: A scaffolded starter, with the local `create-threenative` tarball, local site and Studio `wrangler dev`, runs `threenative login` (scripted Authorize) then `threenative deploy` twice. The share URL serves the game's `index.html` and stays the same across both deploys. The Studio games list shows the game with that link. proof: run log in the PR — Evidence: pending. -- [ ] AC-8 [local]: On `/account/device/?code=…`, an unverified or terms-pending account completes verify and terms and returns to the same code, then Authorize succeeds. The page names `threenative login`. proof: site `e2e/worker/store-device.spec.ts` — Evidence: pending. +- [x] AC-8 [local]: On `/account/device/?code=…`, an unverified or terms-pending account completes verify and terms and returns to the same code, then Authorize succeeds. The page names `threenative login`. proof: site `e2e/worker/store-device.spec.ts` — Evidence: the two PRD-904 AC-8 cases pass (terms-pending accepts on `/signin/` and approves the same code; unverified lands on `/signin/` verify with the code in `next`). - [ ] AC-7 [shared]: After site, Studio and engine releases, a `pnpm sandbox` clean room runs `npx create-threenative` → `npx threenative login` → `npx threenative deploy` and opens the live share URL. proof: `pnpm sandbox` run log — Evidence: pending. ## Blocked on @@ -103,18 +103,18 @@ Fill the dispatcher and route `file:line` values when each phase lands. #### Phase 1: sign in and out **Status:** PARTIAL — phases 1 to 3 in progress **Files:** `packages/create-threenative/src/commands.ts`, `src/threenative.ts` (dispatch), `src/account.ts` (new: device flow, token file, `THREENATIVE_TOKEN`), `AGENTS.md` CLI surface. Site: `worker/store.ts` (bearer self-revoke), `src/components/sections/AccountDevice.tsx` and `AccountVerify.tsx` (copy, keep `?code=` through verify and terms). -- [ ] `login`/`logout` work against a fake site — proof: `login.spec.ts` + `cli.spec.ts` lists the new commands — covers AC-1, AC-2. -- [ ] The device page keeps the code through verify and terms — proof: site `e2e/worker/store-device.spec.ts` — covers AC-8. +- [x] `login`/`logout` work against a fake site — proof: `login.spec.ts` + `cli.spec.ts` lists the new commands — covers AC-1, AC-2. Result: `pnpm exec vitest run packages/create-threenative/__tests__/{login,deploy,cli,cli-bin}.spec.ts` 17/17 passed; `create-threenative` typecheck exit 0. +- [x] The device page keeps the code through verify and terms — proof: site `e2e/worker/store-device.spec.ts` — covers AC-8. Result: site `playwright test --config=playwright.worker.config.ts e2e/worker/store-device.spec.ts` 4/4 passed (Node 24); `studio-signin.spec.ts` 4/4 still pass. #### Phase 2: Studio accepts a CLI publish **Status:** PARTIAL — phases 1 to 3 in progress **Files:** site `worker/studio-auth.ts` (`tokenAccount`). Studio `hosting/cloudflare/src/routes/cli.ts` (new: `PUT /api/cli/share`), `src/index.ts` (route before the session gate). -- [ ] The token check passes its site tests — proof: site worker vitest — covers AC-3. -- [ ] The CLI share route passes its Studio tests — proof: Studio `hosting/cloudflare` vitest — covers AC-4. +- [x] The token check passes its site tests — proof: site worker vitest — covers AC-3. Result: site `vitest run --config vitest.worker.config.ts` 229/229 passed (5 new `tokenAccount` cases, 2 new device cases); site typecheck and lint exit 0. Site branch `prd-904-cli-token`. +- [x] The CLI share route passes its Studio tests — proof: Studio `hosting/cloudflare` vitest — covers AC-4. Result: `vitest run --config hosting/cloudflare/vitest.config.ts` 359/359 passed (9 new in `test/cli-share.spec.ts`); `tsc -p hosting/cloudflare` exit 0. Studio branch `prd-904-cli-share`. #### Phase 3: `threenative deploy` end to end **Status:** PARTIAL — phases 1 to 3 in progress **Files:** `packages/create-threenative/src/deploy.ts` (new: build, pack, upload, link file), `src/threenative.ts`, `src/commands.ts`. -- [ ] Deploy unit behaviour — proof: `deploy.spec.ts` — covers AC-5. +- [x] Deploy unit behaviour — proof: `deploy.spec.ts` — covers AC-5. Result: 5/5 in `deploy.spec.ts` (byte layout, same link on redeploy, 401 exits 3, 422 exits 4, no `build:web` exits 2). - [ ] Local end-to-end through both real Workers — proof: AC-6 run log — covers AC-6. - [ ] Live clean-room deploy — proof: `pnpm sandbox` — covers AC-7. diff --git a/packages/create-threenative/AGENTS.md b/packages/create-threenative/AGENTS.md index bf7b85dc94..aa4ded882f 100644 --- a/packages/create-threenative/AGENTS.md +++ b/packages/create-threenative/AGENTS.md @@ -79,11 +79,16 @@ builds locally can still fail there — check it before claiming the scaffold wo ## CLI surface -The `threenative` commands are `build` (`--target web|desktop|android|ios`) and `doctor` -(`--text` prints the person-readable report; it checks rather than builds, borrowed whole from -`npm doctor` and `flutter doctor`). `__tests__/cli.spec.ts` derives the advertised list from the -real executable and rejects anything else, so this document cannot outgrow the binary. A new -command borrows its name from an established CLI (`npm`, `wrangler`, `vercel`), never a new word. +The `threenative` commands are `build` (`--target web|desktop|android|ios`), `doctor` (`--text` +prints the person-readable report; it checks rather than builds, borrowed whole from `npm doctor` +and `flutter doctor`), `login` (device-code sign-in: prints a link and a code, polls until the +browser authorizes, and saves the granted token owner-only; `--no-browser` for a machine whose +browser is elsewhere), `logout` (revokes that token on the site and deletes the file), and +`deploy` (runs the package's `build:web`, uploads `dist/` to Studio, and prints the share link on +its own last stdout line, reusing `.threenative/share.json`'s project id so the next deploy keeps +the same link). `__tests__/cli.spec.ts` derives the advertised list from the real executable and +rejects anything else, so this document cannot outgrow the binary. A new command borrows its name +from an established CLI (`npm`, `wrangler`, `vercel`), never a new word. The scaffolder itself takes a target directory plus `inspect [--json]`; its flags stay boring: `--template`, `--no-install`, and the `--*-package` overrides CI uses to test against local tarballs. `pnpm dev` inside a generated project is a package script, never a CLI command. diff --git a/packages/create-threenative/CLAUDE.md b/packages/create-threenative/CLAUDE.md index 0a84695f87..96cec0d178 100644 --- a/packages/create-threenative/CLAUDE.md +++ b/packages/create-threenative/CLAUDE.md @@ -81,11 +81,16 @@ builds locally can still fail there — check it before claiming the scaffold wo ## CLI surface -The `threenative` commands are `build` (`--target web|desktop|android|ios`) and `doctor` -(`--text` prints the person-readable report; it checks rather than builds, borrowed whole from -`npm doctor` and `flutter doctor`). `__tests__/cli.spec.ts` derives the advertised list from the -real executable and rejects anything else, so this document cannot outgrow the binary. A new -command borrows its name from an established CLI (`npm`, `wrangler`, `vercel`), never a new word. +The `threenative` commands are `build` (`--target web|desktop|android|ios`), `doctor` (`--text` +prints the person-readable report; it checks rather than builds, borrowed whole from `npm doctor` +and `flutter doctor`), `login` (device-code sign-in: prints a link and a code, polls until the +browser authorizes, and saves the granted token owner-only; `--no-browser` for a machine whose +browser is elsewhere), `logout` (revokes that token on the site and deletes the file), and +`deploy` (runs the package's `build:web`, uploads `dist/` to Studio, and prints the share link on +its own last stdout line, reusing `.threenative/share.json`'s project id so the next deploy keeps +the same link). `__tests__/cli.spec.ts` derives the advertised list from the real executable and +rejects anything else, so this document cannot outgrow the binary. A new command borrows its name +from an established CLI (`npm`, `wrangler`, `vercel`), never a new word. The scaffolder itself takes a target directory plus `inspect [--json]`; its flags stay boring: `--template`, `--no-install`, and the `--*-package` overrides CI uses to test against local tarballs. `pnpm dev` inside a generated project is a package script, never a CLI command. diff --git a/packages/create-threenative/__tests__/cli.spec.ts b/packages/create-threenative/__tests__/cli.spec.ts index 77f694ffdd..5db25c166d 100644 --- a/packages/create-threenative/__tests__/cli.spec.ts +++ b/packages/create-threenative/__tests__/cli.spec.ts @@ -123,7 +123,7 @@ describe("create-threenative CLI", () => { expect(commandHelp.stderr, command).toBe(""); expect(commandHelp.stdout, command).toContain(`Usage: threenative ${command}`); } - expect(advertised).toEqual(["build", "doctor"]); + expect(advertised).toEqual(["build", "doctor", "deploy", "login", "logout"]); for (const command of ["dev", "test", "ship"]) { await expect( diff --git a/packages/create-threenative/__tests__/deploy.spec.ts b/packages/create-threenative/__tests__/deploy.spec.ts new file mode 100644 index 0000000000..64e4a75584 --- /dev/null +++ b/packages/create-threenative/__tests__/deploy.spec.ts @@ -0,0 +1,200 @@ +import { once } from "node:events"; +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import { type IncomingMessage, type ServerResponse, createServer } from "node:http"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; +import { makeTempDir } from "../../../test-support/temp-dir.js"; +import { CliExit } from "../src/account.js"; +import { deploy, packDirectory } from "../src/deploy.js"; + +interface IRequestRecord { + authorization?: string; + body: Buffer; + method?: string; + url?: string; +} + +interface IReply { + body?: unknown; + status: number; +} + +interface IFakeStudio { + close: () => Promise; + origin: string; + requests: IRequestRecord[]; +} + +/** A stand-in for studio.threenative.com on 127.0.0.1, so no test reaches the real Studio. */ +async function fakeStudio(handler: (request: IRequestRecord) => IReply): Promise { + const requests: IRequestRecord[] = []; + const server = createServer(async (request: IncomingMessage, response: ServerResponse) => { + const chunks: Buffer[] = []; + for await (const chunk of request) chunks.push(Buffer.from(chunk)); + const record = { + authorization: request.headers.authorization, + body: Buffer.concat(chunks), + method: request.method, + url: request.url, + }; + requests.push(record); + const reply = handler(record); + response.statusCode = reply.status; + response.setHeader("content-type", "application/json"); + response.end(reply.body === undefined ? "" : JSON.stringify(reply.body)); + }); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const address = server.address(); + const port = typeof address === "object" && address !== null ? address.port : 0; + return { + close: () => + new Promise((done) => { + server.closeAllConnections(); + server.close(() => done()); + }), + origin: `http://127.0.0.1:${port.toString()}`, + requests, + }; +} + +/** Studio's parser, written from the wire format rather than from packDirectory's code. */ +function decode(archive: Buffer): { content: string; name: string }[] { + const entries: { content: string; name: string }[] = []; + let offset = 0; + while (offset < archive.length) { + const nameLength = archive.readUInt32BE(offset); + offset += 4; + const name = archive.subarray(offset, offset + nameLength).toString("utf8"); + offset += nameLength; + const size = archive.readUInt32BE(offset); + offset += 4; + const content = archive.subarray(offset, offset + size).toString("utf8"); + offset += size; + entries.push({ content, name }); + } + return entries; +} + +function entry(archive: Buffer, name: string): string | undefined { + return decode(archive).find((candidate) => candidate.name === name)?.content; +} + +async function projectDir(scripts: Record): Promise { + const cwd = await makeTempDir("tn-deploy-"); + await writeFile(path.join(cwd, "package.json"), JSON.stringify({ name: "game", scripts })); + return cwd; +} + +async function writeBuild(cwd: string): Promise { + await mkdir(path.join(cwd, "dist"), { recursive: true }); + await writeFile(path.join(cwd, "dist", "index.html"), "

hi

"); +} + +async function failureOf(run: Promise): Promise { + const failure = await run.then( + () => undefined, + (error: unknown) => error, + ); + expect(failure).toBeInstanceOf(CliExit); + return failure as CliExit; +} + +describe("threenative deploy", () => { + it("packs files in Studio's byte layout and drops a compressed sibling", async () => { + const root = await makeTempDir("tn-pack-"); + await writeFile(path.join(root, "index.html"), "

hi

"); + await mkdir(path.join(root, "a")); + await writeFile(path.join(root, "a", "b.js"), "console.log(1);"); + await writeFile(path.join(root, "a", "b.js.br"), "BROTLI"); + // Kept: the original `c` is absent, so the only copy of it is this gzip. + await writeFile(path.join(root, "c.gz"), "GZIP"); + + const entries = decode(await packDirectory(root)); + + expect(entries.map(({ content, name }) => `${name}=${content}`).sort()).toEqual([ + "a/b.js=console.log(1);", + "c.gz=GZIP", + "index.html=

hi

", + ]); + expect(entries.some(({ name }) => name === "a/b.js.br")).toBe(false); + }); + + it("publishes the build and keeps the same link on the next deploy", async () => { + const cwd = await projectDir({ "build:web": "vite build" }); + const site = await fakeStudio(() => ({ + body: { projectId: "p1", shareUrl: "https://x-share.example/" }, + status: 200, + })); + const lines: string[] = []; + const options = { + cwd, + out: (line: string) => lines.push(line), + runBuild: writeBuild, + studio: site.origin, + token: "tok-1", + }; + + const first = await deploy(options); + + expect(first).toEqual({ projectId: "p1", shareUrl: "https://x-share.example/" }); + expect(site.requests[0]).toMatchObject({ + authorization: "Bearer tok-1", + method: "PUT", + url: "/api/cli/share?name=game", + }); + expect(entry(site.requests[0]?.body ?? Buffer.alloc(0), "index.html")).toBe("

hi

"); + // The link alone on the last stdout line: an agent parses that line, not the prose above it. + expect(lines.at(-1)).toBe("https://x-share.example/"); + const shareFile = path.join(cwd, ".threenative", "share.json"); + expect(await readFile(shareFile, "utf8")).toBe('{\n "projectId": "p1"\n}\n'); + expect(JSON.parse(await readFile(shareFile, "utf8"))).toEqual({ projectId: "p1" }); + + const second = await deploy(options); + + expect(site.requests[1]?.url).toBe("/api/cli/share?name=game&projectId=p1"); + expect(second).toEqual(first); + await site.close(); + }); + + it("asks for a fresh sign-in when Studio refuses the token", async () => { + const cwd = await projectDir({ "build:web": "vite build" }); + const site = await fakeStudio(() => ({ + body: { message: "This token is no longer valid." }, + status: 401, + })); + + const failure = await failureOf( + deploy({ cwd, out: () => {}, runBuild: writeBuild, studio: site.origin, token: "tok-old" }), + ); + + expect(failure.code).toBe(3); + expect(failure.message).toBe("This token is no longer valid. Run threenative login."); + await site.close(); + }); + + it("surfaces Studio's reason when it refuses the build", async () => { + const cwd = await projectDir({ "build:web": "vite build" }); + const message = "The build has no index.html. Run build:web and deploy again."; + const site = await fakeStudio(() => ({ body: { message }, status: 422 })); + + const failure = await failureOf( + deploy({ cwd, out: () => {}, runBuild: writeBuild, studio: site.origin, token: "tok-1" }), + ); + + expect(failure.code).toBe(4); + expect(failure.message).toBe(message); + await site.close(); + }); + + it("rejects a package with no build:web script", async () => { + const cwd = await projectDir({ build: "vite build" }); + + const failure = await failureOf( + deploy({ cwd, out: () => {}, runBuild: writeBuild, token: "tok-1" }), + ); + + expect(failure.code).toBe(2); + expect(failure.message).toBe("package.json has no build:web script."); + }); +}); diff --git a/packages/create-threenative/__tests__/login.spec.ts b/packages/create-threenative/__tests__/login.spec.ts new file mode 100644 index 0000000000..6f06f97496 --- /dev/null +++ b/packages/create-threenative/__tests__/login.spec.ts @@ -0,0 +1,190 @@ +import { once } from "node:events"; +import { mkdir, readFile, stat, writeFile } from "node:fs/promises"; +import { type IncomingMessage, type ServerResponse, createServer } from "node:http"; +import path from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { makeTempDir } from "../../../test-support/temp-dir.js"; +import { CliExit, authFilePath, login, logout, readToken } from "../src/account.js"; + +interface IRequestRecord { + authorization?: string; + body: Buffer; + method?: string; + url?: string; +} + +interface IReply { + body?: unknown; + status: number; +} + +interface IFakeSite { + close: () => Promise; + origin: string; + requests: IRequestRecord[]; +} + +/** A stand-in for threenative.com on 127.0.0.1, so no test reaches the real site. */ +async function fakeSite(handler: (request: IRequestRecord) => IReply): Promise { + const requests: IRequestRecord[] = []; + const server = createServer(async (request: IncomingMessage, response: ServerResponse) => { + const chunks: Buffer[] = []; + for await (const chunk of request) chunks.push(Buffer.from(chunk)); + const record = { + authorization: request.headers.authorization, + body: Buffer.concat(chunks), + method: request.method, + url: request.url, + }; + requests.push(record); + const reply = handler(record); + response.statusCode = reply.status; + response.setHeader("content-type", "application/json"); + response.end(reply.body === undefined ? "" : JSON.stringify(reply.body)); + }); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const address = server.address(); + const port = typeof address === "object" && address !== null ? address.port : 0; + return { + close: () => + new Promise((done) => { + server.closeAllConnections(); + server.close(() => done()); + }), + origin: `http://127.0.0.1:${port.toString()}`, + requests, + }; +} + +async function failureOf(run: Promise): Promise { + const failure = await run.then( + () => undefined, + (error: unknown) => error, + ); + expect(failure).toBeInstanceOf(CliExit); + return failure as CliExit; +} + +function deviceStart(userCode: string): IReply { + return { + body: { deviceCode: `dev-${userCode}`, expiresIn: 900, interval: 1, userCode }, + status: 201, + }; +} + +describe("threenative login and logout", () => { + let configHome: string; + + beforeEach(async () => { + configHome = await makeTempDir("tn-auth-"); + vi.stubEnv("XDG_CONFIG_HOME", configHome); + // A developer machine with a token or a browser must not change what these tests prove. + vi.stubEnv("THREENATIVE_TOKEN", ""); + vi.stubEnv("THREENATIVE_NO_BROWSER", "1"); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + }); + + it("polls the device flow, saves a 0600 token file and names the account", async () => { + let polls = 0; + const site = await fakeSite((request) => { + if (request.url === "/api/store/device") return deviceStart("ABCD-EFGH"); + if (request.url === "/api/store/device/token") { + polls += 1; + return polls < 3 + ? { body: { status: "pending" }, status: 200 } + : { body: { status: "approved", token: "tok-1" }, status: 200 }; + } + if (request.url === "/api/store/whoami") return { body: { email: "a@b.c" }, status: 200 }; + return { body: { message: "unexpected request" }, status: 404 }; + }); + const lines: string[] = []; + + await login({ + open: false, + out: (line) => lines.push(line), + site: site.origin, + sleep: async () => {}, + }); + + const file = authFilePath(); + expect((await stat(file)).mode & 0o777).toBe(0o600); + const saved = JSON.parse(await readFile(file, "utf8")) as { email?: string; token?: string }; + expect(saved).toMatchObject({ email: "a@b.c", token: "tok-1" }); + expect(lines.join("\n")).toContain("/account/device/?code=ABCD-EFGH"); + expect(lines.join("\n")).toContain("Signed in as a@b.c"); + expect(polls).toBe(3); + expect(site.requests.map(({ method, url }) => `${method ?? ""} ${url ?? ""}`)).toEqual([ + "POST /api/store/device", + "POST /api/store/device/token", + "POST /api/store/device/token", + "POST /api/store/device/token", + "GET /api/store/whoami", + ]); + expect(site.requests.at(-1)?.authorization).toBe("Bearer tok-1"); + await site.close(); + }); + + it("asks you to log in again when the code expired", async () => { + const site = await fakeSite((request) => + request.url === "/api/store/device" + ? deviceStart("WXYZ-1234") + : { body: { message: "That code has expired." }, status: 400 }, + ); + + const failure = await failureOf( + login({ open: false, out: () => {}, site: site.origin, sleep: async () => {} }), + ); + + expect(failure.code).toBe(3); + expect(failure.message).toBe("That code has expired. Run threenative login again."); + await site.close(); + }); + + it("revokes the saved token, never the env one, then deletes the file", async () => { + const file = authFilePath(); + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, JSON.stringify({ token: "tok-file" })); + vi.stubEnv("THREENATIVE_TOKEN", "tok-env"); + const site = await fakeSite(() => ({ body: { ok: true }, status: 200 })); + const lines: string[] = []; + + await logout({ out: (line) => lines.push(line), site: site.origin }); + + expect(site.requests).toHaveLength(1); + expect(site.requests[0]).toMatchObject({ + authorization: "Bearer tok-file", + method: "DELETE", + url: "/api/store/token", + }); + await expect(stat(file)).rejects.toMatchObject({ code: "ENOENT" }); + expect(lines).toEqual(["Signed out."]); + await site.close(); + }); + + it("prefers THREENATIVE_TOKEN over the saved file", async () => { + const file = authFilePath(); + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, JSON.stringify({ token: "tok-file" })); + expect(await readToken()).toBe("tok-file"); + + vi.stubEnv("THREENATIVE_TOKEN", "tok-env"); + expect(await readToken()).toBe("tok-env"); + }); + + it("reports a closed port as a network failure", async () => { + const site = await fakeSite(() => ({ body: {}, status: 200 })); + const origin = site.origin; + await site.close(); + + const failure = await failureOf( + login({ open: false, out: () => {}, site: origin, sleep: async () => {} }), + ); + + expect(failure.code).toBe(5); + expect(failure.message).toContain(`Could not reach ${origin}`); + }); +}); diff --git a/packages/create-threenative/src/account.ts b/packages/create-threenative/src/account.ts new file mode 100644 index 0000000000..93905fa273 --- /dev/null +++ b/packages/create-threenative/src/account.ts @@ -0,0 +1,236 @@ +/** `threenative login` and `threenative logout`: the device-code flow against threenative.com, + * and the one token file every command that talks to a server reads. + * + * Exit codes are shared by login, logout and deploy: 0 ok, 2 bad arguments, 3 sign in again, + * 4 refused by the server, 5 network failure. `main()` prints the message and sets the code. */ +import { spawn } from "node:child_process"; +import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { homedir } from "node:os"; +import path from "node:path"; + +export class CliExit extends Error { + readonly code: number; + + constructor(code: number, message: string) { + super(message); + this.name = "CliExit"; + this.code = code; + } +} + +const DEFAULT_SITE = "https://threenative.com"; + +export function siteOrigin(site = process.env.THREENATIVE_SITE): string { + return (site ?? DEFAULT_SITE).replace(/\/+$/u, ""); +} + +function configHome(env: NodeJS.ProcessEnv): string { + if (env.XDG_CONFIG_HOME !== undefined && env.XDG_CONFIG_HOME !== "") return env.XDG_CONFIG_HOME; + // `~/.config` on macOS too, as `gh` and `wrangler` do; Windows keeps its roaming config folder. + if (process.platform === "win32") return env.APPDATA ?? homedir(); + return path.join(homedir(), ".config"); +} + +/** `$XDG_CONFIG_HOME/threenative/auth.json`, default `~/.config` (`%APPDATA%` on Windows). */ +export function authFilePath(env = process.env): string { + return path.join(configHome(env), "threenative", "auth.json"); +} + +export interface IAuthFile { + email?: string; + token?: string; +} + +async function readAuthFile(env: NodeJS.ProcessEnv): Promise { + try { + const parsed: unknown = JSON.parse(await readFile(authFilePath(env), "utf8")); + return parsed !== null && typeof parsed === "object" ? (parsed as IAuthFile) : undefined; + } catch { + // No file, or one a person half-edited: either way this machine has no saved token. + return undefined; + } +} + +/** `THREENATIVE_TOKEN` wins for one command, so CI can publish without a config file. */ +export async function readToken(env = process.env): Promise { + const fromEnv = env.THREENATIVE_TOKEN; + if (fromEnv !== undefined && fromEnv !== "") return fromEnv; + const file = await readAuthFile(env); + return typeof file?.token === "string" && file.token !== "" ? file.token : undefined; +} + +export async function requireToken(): Promise { + const token = await readToken(); + if (token === undefined) throw new CliExit(3, "Not signed in. Run threenative login."); + return token; +} + +export interface IReply { + body: unknown; + status: number; + statusText: string; +} + +/** One JSON request. A thrown fetch is the only thing exit code 5 means, so it is caught here. */ +export async function request( + origin: string, + pathname: string, + init: RequestInit = {}, +): Promise { + let response: Response; + try { + response = await fetch(`${origin}${pathname}`, init); + } catch (error) { + const reason = error instanceof Error ? error.message : String(error); + throw new CliExit(5, `Could not reach ${origin}: ${reason}`); + } + const text = await response.text(); + let body: unknown = text; + try { + body = text === "" ? undefined : JSON.parse(text); + } catch { + // A non-JSON body (a proxy page) is still worth surfacing as text, which it already is. + } + return { body, status: response.status, statusText: response.statusText }; +} + +/** Site errors are `{ error: "TN_…", message: "…" }`; a person reads the message, not the code. */ +export function serverMessage(body: unknown, fallback: string): string { + const message = (body as { message?: unknown } | null | undefined)?.message; + return typeof message === "string" && message !== "" ? message : fallback; +} + +function numberField(body: unknown, key: string): number | undefined { + const value = (body as Record | null | undefined)?.[key]; + return typeof value === "number" && Number.isFinite(value) ? value : undefined; +} + +function jsonPost(value: unknown): RequestInit { + return { + body: JSON.stringify(value), + headers: { "content-type": "application/json" }, + method: "POST", + }; +} + +async function writeAuthFile(auth: IAuthFile): Promise { + const file = authFilePath(); + await mkdir(path.dirname(file), { mode: 0o700, recursive: true }); + await writeFile(file, `${JSON.stringify(auth, null, 2)}\n`, { mode: 0o600 }); + // writeFile keeps the mode of a file that already exists, so tighten it again. + await chmod(file, 0o600); +} + +function openBrowser(link: string): void { + const command = + process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open"; + const args = process.platform === "win32" ? ["/c", "start", "", link] : [link]; + try { + const child = spawn(command, args, { detached: true, stdio: "ignore" }); + // A machine with no browser (a container, CI) must not fail the login it is polling through. + child.on("error", () => {}); + child.unref(); + } catch { + // spawn throws only on bad arguments; a missing binary arrives as the 'error' event above. + } +} + +export interface ILoginOptions { + open?: boolean; + out?: (line: string) => void; + site?: string; + sleep?: (milliseconds: number) => Promise; +} + +/** Device-code sign-in: print the code, poll until the browser authorizes, save the token. */ +export async function login(options: ILoginOptions = {}): Promise { + const origin = siteOrigin(options.site); + const out = options.out ?? ((line: string) => process.stdout.write(`${line}\n`)); + const sleep = + options.sleep ?? + ((milliseconds: number) => new Promise((done) => setTimeout(done, milliseconds))); + + const start = await request(origin, "/api/store/device", jsonPost({})); + if (start.status !== 201) + throw new CliExit(4, serverMessage(start.body, `Sign in failed (${start.status}).`)); + const deviceCode = (start.body as { deviceCode?: unknown }).deviceCode; + const userCode = (start.body as { userCode?: unknown }).userCode; + if (typeof deviceCode !== "string" || deviceCode === "") + throw new CliExit(4, "The sign-in server sent no device code."); + const link = `${origin}/account/device/?code=${encodeURIComponent(typeof userCode === "string" ? userCode : "")}`; + out(`Open ${link} and click Authorize.`); + out(`Code: ${typeof userCode === "string" ? userCode : ""}`); + if (options.open !== false && process.env.THREENATIVE_NO_BROWSER !== "1") openBrowser(link); + + const expiresAt = Date.now() + (numberField(start.body, "expiresIn") ?? 900) * 1_000; + let interval = numberField(start.body, "interval") ?? 5; + const pollForToken = async (): Promise => { + for (;;) { + await sleep(interval * 1_000); + if (Date.now() >= expiresAt) + throw new CliExit(3, "The code expired. Run threenative login again."); + const reply = await request(origin, "/api/store/device/token", jsonPost({ deviceCode })); + const status = (reply.body as { status?: unknown }).status; + if (reply.status >= 400 && reply.status < 500) + throw new CliExit( + 3, + `${serverMessage(reply.body, "Sign in was refused.")} Run threenative login again.`, + ); + if (reply.status < 200 || reply.status >= 300) + throw new CliExit(4, serverMessage(reply.body, `Sign in failed (${reply.status}).`)); + const nextInterval = numberField(reply.body, "interval"); + if (nextInterval !== undefined && nextInterval > 0) interval = nextInterval; + if (status !== "approved") continue; + const token = (reply.body as { token?: unknown }).token; + if (typeof token !== "string" || token === "") + throw new CliExit(4, "The sign-in server approved without a token."); + return token; + } + }; + + const token = await pollForToken(); + // Save before asking who this is: a whoami hiccup must not throw away a granted token. + await writeAuthFile({ token }); + const who = await request(origin, "/api/store/whoami", { + headers: { authorization: `Bearer ${token}` }, + }); + if (who.status < 200 || who.status >= 300) + throw new CliExit(4, serverMessage(who.body, `Could not read your account (${who.status}).`)); + const email = (who.body as { email?: unknown }).email; + const address = typeof email === "string" ? email : ""; + await writeAuthFile({ email: address, token }); + out(`Signed in as ${address}.`); +} + +export interface ILogoutOptions { + out?: (line: string) => void; + site?: string; +} + +/** Revoke the saved token and delete the file. `THREENATIVE_TOKEN` is not touched. */ +export async function logout(options: ILogoutOptions = {}): Promise { + const out = options.out ?? ((line: string) => process.stdout.write(`${line}\n`)); + const env = process.env; + const token = (await readAuthFile(env))?.token; + if (typeof token !== "string" || token === "") { + out("Not signed in."); + return; + } + const origin = siteOrigin(options.site); + let warning: string | undefined; + try { + const reply = await request(origin, "/api/store/token", { + headers: { authorization: `Bearer ${token}` }, + method: "DELETE", + }); + // 401 means the server already forgot this token: this machine is signed out either way. + if (reply.status !== 200 && reply.status !== 401) + warning = `Could not revoke the token online (${reply.status}).`; + } catch (error) { + if (!(error instanceof CliExit) || error.code !== 5) throw error; + warning = `${error.message} The token was not revoked online, but this machine is signed out.`; + } + await rm(authFilePath(env), { force: true }); + if (warning !== undefined) out(warning); + out("Signed out."); +} diff --git a/packages/create-threenative/src/commands.ts b/packages/create-threenative/src/commands.ts index ae7d4ebc86..43651854e1 100644 --- a/packages/create-threenative/src/commands.ts +++ b/packages/create-threenative/src/commands.ts @@ -1,11 +1,20 @@ /** The complete `threenative` command surface, in one place so the help text, the dispatcher and * the documentation checks cannot disagree. Adding a command means adding it here and teaching * `threenative.ts` to run it. */ -export type PublicCommand = "build" | "doctor"; +export type PublicCommand = "build" | "doctor" | "login" | "logout" | "deploy"; -export const threenativeCommands: readonly PublicCommand[] = ["build", "doctor"]; +export const threenativeCommands: readonly PublicCommand[] = [ + "build", + "doctor", + "deploy", + "login", + "logout", +]; export const commandSummaries: Record = { build: "Build web or native output.", doctor: "Check this project and report what would break a build.", + deploy: "Build for the web and publish the game to its share link on threenative.com.", + login: "Sign in to your threenative.com account.", + logout: "Sign out and revoke this machine's token.", }; diff --git a/packages/create-threenative/src/deploy.ts b/packages/create-threenative/src/deploy.ts new file mode 100644 index 0000000000..24272ae9ca --- /dev/null +++ b/packages/create-threenative/src/deploy.ts @@ -0,0 +1,169 @@ +/** `threenative deploy`: build the web bundle, pack it and PUT it to Studio's share endpoint, + * which is what turns a game into a link a friend can open. */ +import { spawn } from "node:child_process"; +import { mkdir, readFile, readdir, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { CliExit, request, requireToken, serverMessage } from "./account.js"; + +const SHARE_BUILD_MAX_BYTES = 50 * 1024 * 1024; +const MAX_FILES = 2_000; + +async function walk(root: string, dir = ""): Promise { + const files: string[] = []; + for (const entry of await readdir(path.join(root, dir), { withFileTypes: true })) { + const relative = dir === "" ? entry.name : `${dir}/${entry.name}`; + if (entry.isDirectory()) files.push(...(await walk(root, relative))); + else if (entry.isFile()) files.push(relative); + } + return files; +} + +/** ponytail: copy of Studio's `src/server/release/shareArchive.ts` packDirectory. The PRD-904 + * AC-6 e2e uploads this archive to Studio's real parser, so any drift fails there; move it to a + * shared package if a third writer appears. Layout: u32BE name length, name, u32BE size, data, + * depth-first in readdir order, with a `.br`/`.gz` sibling dropped when the original is present. */ +export async function packDirectory(root: string): Promise { + const all = await walk(root); + const present = new Set(all); + const files = all.filter( + (file) => !(/\.(br|gz)$/u.test(file) && present.has(file.replace(/\.(br|gz)$/u, ""))), + ); + if (files.length > MAX_FILES) + throw new CliExit(4, `The build has ${files.length} files; the limit is ${MAX_FILES}.`); + const parts: Buffer[] = []; + let bytes = 0; + for (const file of files) { + const data = await readFile(path.join(root, file)); + bytes += data.length; + if (bytes > SHARE_BUILD_MAX_BYTES) + throw new CliExit(4, "The build is bigger than 50 MB, the most a share link holds."); + const name = Buffer.from(file, "utf8"); + const head = Buffer.alloc(4); + head.writeUInt32BE(name.length); + const size = Buffer.alloc(4); + size.writeUInt32BE(data.length); + parts.push(head, name, size, data); + } + return Buffer.concat(parts); +} + +const DEFAULT_STUDIO = "https://studio.threenative.com"; +const PACKAGE_MANAGERS = ["npm", "pnpm", "yarn", "bun"] as const; + +export function studioOrigin(studio = process.env.THREENATIVE_STUDIO): string { + return (studio ?? DEFAULT_STUDIO).replace(/\/+$/u, ""); +} + +/** The agent pnpm/yarn/npm/bun started this CLI, so `build:web` runs with the game's own lockfile. */ +function packageManager(): string { + const name = (process.env.npm_config_user_agent ?? "").split("/")[0] ?? ""; + return PACKAGE_MANAGERS.includes(name as (typeof PACKAGE_MANAGERS)[number]) ? name : "npm"; +} + +async function runBuildScript(cwd: string): Promise { + const exitCode = await new Promise((resolve) => { + const child = spawn(packageManager(), ["run", "build:web"], { + cwd, + shell: process.platform === "win32", + stdio: "inherit", + }); + child.on("error", () => resolve(1)); + child.on("exit", (code) => resolve(code ?? 1)); + }); + if (exitCode !== 0) throw new CliExit(4, "build:web failed."); +} + +interface IProjectManifest { + name?: string; + scripts?: Record; +} + +interface IShareFile { + projectId?: string; +} + +async function readJson(file: string): Promise { + try { + return JSON.parse(await readFile(file, "utf8")) as T; + } catch { + return undefined; + } +} + +export interface IDeployOptions { + cwd?: string; + out?: (line: string) => void; + runBuild?: (cwd: string) => Promise; + studio?: string; + token?: string; +} + +export interface IDeployResult { + projectId: string; + shareUrl: string; +} + +export async function deploy(options: IDeployOptions = {}): Promise { + const cwd = options.cwd ?? process.cwd(); + const out = options.out ?? ((line: string) => process.stdout.write(`${line}\n`)); + const studio = studioOrigin(options.studio); + const token = options.token ?? (await requireToken()); + + const manifest = await readJson(path.join(cwd, "package.json")); + if (manifest === undefined) + throw new CliExit(2, "No package.json here. Run threenative deploy inside a game."); + if (manifest.scripts?.["build:web"] === undefined) + throw new CliExit(2, "package.json has no build:web script."); + if (manifest.name === undefined || manifest.name === "") + throw new CliExit(2, "package.json has no name."); + + await (options.runBuild ?? runBuildScript)(cwd); + const archive = await packDirectory(path.join(cwd, "dist")).catch((error: unknown) => { + if ((error as NodeJS.ErrnoException | undefined)?.code === "ENOENT") + throw new CliExit(4, "The build wrote no dist/ folder."); + throw error; + }); + + const sharePath = path.join(cwd, ".threenative", "share.json"); + const previous = await readJson(sharePath); + const existing = previous?.projectId; + const query = new URLSearchParams({ name: manifest.name }); + if (typeof existing === "string" && existing !== "") query.set("projectId", existing); + + const reply = await request(studio, `/api/cli/share?${query.toString()}`, { + // fetch's BodyInit wants a plain view, not Node's Buffer subclass. + body: new Uint8Array(archive), + headers: { + authorization: `Bearer ${token}`, + "content-type": "application/octet-stream", + }, + method: "PUT", + }); + if (reply.status === 401) + throw new CliExit( + 3, + `${serverMessage(reply.body, "This machine's token was refused.")} Run threenative login.`, + ); + if (reply.status < 200 || reply.status >= 300) + throw new CliExit( + 4, + serverMessage( + reply.body, + reply.statusText === "" + ? `The server refused the upload (${reply.status}).` + : reply.statusText, + ), + ); + + const result = reply.body as { projectId?: unknown; shareUrl?: unknown }; + const projectId = typeof result?.projectId === "string" ? result.projectId : ""; + const shareUrl = typeof result?.shareUrl === "string" ? result.shareUrl : ""; + if (shareUrl === "") throw new CliExit(4, "The server returned no share link."); + if (existing !== projectId) { + await mkdir(path.dirname(sharePath), { recursive: true }); + await writeFile(sharePath, `${JSON.stringify({ projectId }, null, 2)}\n`); + } + // The link alone, last: an agent parses this line, not the prose above it. + out(shareUrl); + return { projectId, shareUrl }; +} diff --git a/packages/create-threenative/src/threenative.ts b/packages/create-threenative/src/threenative.ts index b2c7c7f1b8..456418265d 100644 --- a/packages/create-threenative/src/threenative.ts +++ b/packages/create-threenative/src/threenative.ts @@ -1,6 +1,8 @@ #!/usr/bin/env node +import { CliExit, login, logout } from "./account.js"; import { build, buildHelp, parseBuildArgs } from "./build.js"; import { type PublicCommand, commandSummaries, threenativeCommands } from "./commands.js"; +import { deploy } from "./deploy.js"; import { type DoctorMode, type DoctorTarget, @@ -13,6 +15,10 @@ import { fixAuthoringLayer } from "./index.js"; const DOCTOR_TARGETS: readonly DoctorTarget[] = ["web", "desktop", "android", "ios"]; const DOCTOR_MODES: readonly DoctorMode[] = ["debug", "release"]; +function isPublicCommand(value: string): value is PublicCommand { + return threenativeCommands.some((command) => command === value); +} + export function cliHelp(command?: PublicCommand): string { if (command === "build") return buildHelp(); if (command === "doctor") { @@ -43,11 +49,50 @@ export function cliHelp(command?: PublicCommand): string { "Exits 0 when nothing failed, 1 when a check failed.", ].join("\n")}\n`; } + if (command === "login") { + return `${[ + "Usage: threenative login [--no-browser]", + "", + "Opens threenative.com, asks you to authorize this machine, and saves the token it grants", + "in the threenative config directory, owner-only (0600).", + "--no-browser prints the link and the code instead of launching a browser, for signing in", + " here with a browser on another machine.", + "THREENATIVE_TOKEN overrides the saved token for every command that needs one, so CI can", + " publish without writing this file.", + "THREENATIVE_SITE names another site origin.", + "Exits 0 signed in, 2 bad arguments, 3 sign in again, 4 refused by the server, 5 no network.", + ].join("\n")}\n`; + } + if (command === "logout") { + return `${[ + "Usage: threenative logout", + "", + "Revokes this machine's saved token on threenative.com and deletes the token file.", + "With no saved token it prints 'Not signed in.' and does nothing.", + "A server that refuses the revocation still signs this machine out; the file goes anyway.", + "THREENATIVE_SITE names another site origin.", + "Exits 0 signed out, 2 bad arguments, 4 the server refused the revocation.", + ].join("\n")}\n`; + } + if (command === "deploy") { + return `${[ + "Usage: threenative deploy", + "", + "Runs this package's build:web script with its own package manager, then uploads dist/", + "to studio.threenative.com and prints the share link on its own line, last.", + ".threenative/share.json remembers the project id, so the next deploy updates the same", + " link instead of making another one. Commit it with the game.", + "THREENATIVE_STUDIO names another Studio origin; THREENATIVE_SITE is the site login uses;", + " THREENATIVE_TOKEN signs in for one run without a saved token.", + "Exits 0 published, 2 bad arguments (no build:web script), 3 sign in again, 4 the server", + " refused it or the build failed, 5 no network.", + ].join("\n")}\n`; + } return `${[ "Usage: threenative [options]", "", "Commands:", - ...threenativeCommands.map((command) => ` ${command.padEnd(6)} ${commandSummaries[command]}`), + ...threenativeCommands.map((command) => ` ${command.padEnd(7)} ${commandSummaries[command]}`), "", "Run 'threenative --help' for command-specific help.", ].join("\n")}\n`; @@ -56,8 +101,7 @@ export function cliHelp(command?: PublicCommand): string { function helpFor(argv: readonly string[]): string { const command = argv[0]; if (command === undefined || command.startsWith("-")) return cliHelp(); - if (command === "build") return cliHelp("build"); - if (command === "doctor") return cliHelp("doctor"); + if (isPublicCommand(command)) return cliHelp(command); throw new Error(`Unknown threenative command '${command}'.\n${cliHelp()}`); } @@ -134,13 +178,39 @@ export async function runDoctorCommand( return report.pass && kept === 0 ? 0 : 1; } +export async function runLoginCommand(argv: readonly string[]): Promise { + let open = true; + for (const arg of argv) { + if (arg === "--no-browser") { + open = false; + continue; + } + throw new CliExit(2, `login: unknown option '${arg}'. Try 'threenative login --no-browser'.`); + } + await login({ open }); +} + export async function main(argv = process.argv.slice(2)): Promise { if (argv.includes("--help") || argv.includes("-h")) { process.stdout.write(helpFor(argv)); return; } - if (argv[0] === "doctor") { - process.exitCode = await runDoctorCommand(argv.slice(1)); + const [command, ...rest] = argv; + if (command === "login") { + await runLoginCommand(rest); + return; + } + if (command === "logout" || command === "deploy") { + if (rest.length > 0) throw new CliExit(2, `${command} takes no arguments.`); + if (command === "logout") { + await logout(); + return; + } + await deploy(); + return; + } + if (command === "doctor") { + process.exitCode = await runDoctorCommand(rest); return; } await build(parseBuildArgs(argv)); @@ -148,5 +218,5 @@ export async function main(argv = process.argv.slice(2)): Promise { main().catch((error: unknown) => { process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`); - process.exitCode = 1; + process.exitCode = error instanceof CliExit ? error.code : 1; }); From 13af3024321a55f39d66415cd5972e8b39cdb4de Mon Sep 17 00:00:00 2001 From: Joao Paulo Furtado Date: Sat, 21 Nov 2026 20:05:06 -0700 Subject: [PATCH 07/20] docs(prd): PRD-904 AC-1, AC-5 and AC-6 pass on the local site and Studio Workers --- ...eenative-login-and-deploy-publish-like-studio-share.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md b/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md index 44c385690f..83800c0003 100644 --- a/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md +++ b/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md @@ -65,12 +65,12 @@ Risks: the packer is copied, and the copy can drift from Studio's. `ponytail:` t ## Acceptance Criteria -- [ ] AC-1 [local]: `threenative login` against local site `wrangler dev` opens `/account/device/?code=…`. After a scripted Authorize it writes a `0600` token file and prints the account email. proof: `pnpm exec vitest run packages/create-threenative/__tests__/login.spec.ts` (fake site) + the AC-6 run — Evidence: pending. +- [x] AC-1 [local]: `threenative login` against local site `wrangler dev` opens `/account/device/?code=…`. After a scripted Authorize it writes a `0600` token file and prints the account email. proof: `pnpm exec vitest run packages/create-threenative/__tests__/login.spec.ts` (fake site) + the AC-6 run — Evidence: `login.spec.ts` passes; AC-6 run printed `/account/device/?code=C4LN-AN6B`, a curl Authorize returned `{"ok":true}`, login exited 0 with `Signed in as e2e@example.com.`, `auth.json` mode 600. - [x] AC-2 [local]: `threenative logout` revokes the token on the site, then deletes the file. `THREENATIVE_TOKEN` wins over the file, and a refused token exits 3 with "run threenative login". proof: `login.spec.ts` — Evidence: `login.spec.ts` logout and env cases pass; `deploy.spec.ts` 401 exits 3; site `DELETE /api/store/token` case passes in `worker/__tests__/store-device.spec.ts`. - [x] AC-3 [local]: `StudioAccounts.tokenAccount` returns the account for a live device-issued token and refuses a revoked, expired or unknown token, an unverified email and an account without current terms. proof: site `pnpm vitest --config vitest.worker.config.ts worker/__tests__/studio-auth.spec.ts` — Evidence: 13/13 in `studio-auth.spec.ts`, inside the 229/229 site worker run. - [x] AC-4 [local]: `PUT /api/cli/share` with a valid token creates a project and returns a share URL. A second call with that `projectId` keeps the same URL and serves the new build. No token gets 401; no `index.html` or over 50 MB gets Studio's refusal message. proof: Studio `hosting/cloudflare` vitest — Evidence: `test/cli-share.spec.ts` 9/9 (create, same URL with new bytes, 401, 422 no `index.html`, 403 suspended and closed beta, 404 foreign project, 502 site down); the 50 MB refusal is `publishShare`'s own, covered by `test/share.spec.ts` in the same 359/359 run. -- [ ] AC-5 [local]: `threenative deploy` runs `build:web`, packs `dist/` byte-for-byte like Studio's `packDirectory` on the same folder, uploads, writes `.threenative/share.json` once and prints the URL. proof: `pnpm exec vitest run packages/create-threenative/__tests__/deploy.spec.ts` — Evidence: pending. -- [ ] AC-6 [local]: A scaffolded starter, with the local `create-threenative` tarball, local site and Studio `wrangler dev`, runs `threenative login` (scripted Authorize) then `threenative deploy` twice. The share URL serves the game's `index.html` and stays the same across both deploys. The Studio games list shows the game with that link. proof: run log in the PR — Evidence: pending. +- [x] AC-5 [local]: `threenative deploy` runs `build:web`, packs `dist/` byte-for-byte like Studio's `packDirectory` on the same folder, uploads, writes `.threenative/share.json` once and prints the URL. proof: `pnpm exec vitest run packages/create-threenative/__tests__/deploy.spec.ts` — Evidence: `deploy.spec.ts` 5/5; in the AC-6 run the real `build:web` ran, and the engine and Studio `packDirectory` on the same 16 474 839-byte `dist/` gave the same sha256 `1645cccf…0462`. +- [x] AC-6 [local]: A scaffolded starter, with the local `create-threenative` tarball, local site and Studio `wrangler dev`, runs `threenative login` (scripted Authorize) then `threenative deploy` twice. The share URL serves the game's `index.html` and stays the same across both deploys. The Studio games list shows the game with that link. proof: run log in the PR — Evidence: PR #712 comment. Starter scaffolded with the local `create-threenative-0.2.25.tgz`; two deploys printed the same `share-ac6-game-g226` link and kept `projectId 095e83ba…`; the link served `dist/index.html` (plus Studio's report link); Studio D1 lists `ac6-game` with that share id for `e2e@example.com`; logout revoked the token in site D1 and the next deploy exited 3. - [x] AC-8 [local]: On `/account/device/?code=…`, an unverified or terms-pending account completes verify and terms and returns to the same code, then Authorize succeeds. The page names `threenative login`. proof: site `e2e/worker/store-device.spec.ts` — Evidence: the two PRD-904 AC-8 cases pass (terms-pending accepts on `/signin/` and approves the same code; unverified lands on `/signin/` verify with the code in `next`). - [ ] AC-7 [shared]: After site, Studio and engine releases, a `pnpm sandbox` clean room runs `npx create-threenative` → `npx threenative login` → `npx threenative deploy` and opens the live share URL. proof: `pnpm sandbox` run log — Evidence: pending. @@ -116,5 +116,5 @@ Fill the dispatcher and route `file:line` values when each phase lands. **Status:** PARTIAL — phases 1 to 3 in progress **Files:** `packages/create-threenative/src/deploy.ts` (new: build, pack, upload, link file), `src/threenative.ts`, `src/commands.ts`. - [x] Deploy unit behaviour — proof: `deploy.spec.ts` — covers AC-5. Result: 5/5 in `deploy.spec.ts` (byte layout, same link on redeploy, 401 exits 3, 422 exits 4, no `build:web` exits 2). -- [ ] Local end-to-end through both real Workers — proof: AC-6 run log — covers AC-6. +- [x] Local end-to-end through both real Workers — proof: AC-6 run log — covers AC-6. Result: see AC-6 evidence; local site `scripts/e2e-wrangler.mjs` on 4180, Studio `wrangler dev` on 8788 with containers off and `routes` removed so share hosts are not rewritten. - [ ] Live clean-room deploy — proof: `pnpm sandbox` — covers AC-7. From 28127621d8afdff5e70168cbc8da014d47fec6fa Mon Sep 17 00:00:00 2001 From: Joao Paulo Furtado Date: Sat, 21 Nov 2026 20:11:30 -0700 Subject: [PATCH 08/20] fix(create-threenative): logout keeps a token it could not revoke; atomic 0600 token write; a dropped body exits 5 (PRD-904 Sol review) --- ...in-and-deploy-publish-like-studio-share.md | 4 +- .../__tests__/login.spec.ts | 58 ++++++++++++++++++- packages/create-threenative/src/account.ts | 48 ++++++++------- 3 files changed, 87 insertions(+), 23 deletions(-) diff --git a/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md b/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md index 83800c0003..fa6cb7aa35 100644 --- a/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md +++ b/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md @@ -95,7 +95,9 @@ Fill the dispatcher and route `file:line` values when each phase lands. - 2026-11-21 (João): login UX: open a link, sign in with the threenative.com account, click Authorize, and the CLI detects it. The code is also accepted typed. The existing site device flow does exactly this. - 2026-11-21 (agent, after a Gemini 4 Neon review): the store push is not the deploy path. A new account's release is held for review (`worker/games.ts:631,649`), the build farm runs scans and an AI review, and a listing needs 1 to 5 screenshots. The share link is live in seconds. - 2026-11-21 (agent): the login is TypeScript in the engine, not a call to the private `tn-store` binary. Deploy no longer needs that binary, and the device flow is three `fetch` calls. -- 2026-11-21 (agent, implementation): `tokenAccount` accepts any live `push` token, not only a device-issued one. The daily sweep deletes the `device_codes` row that links a token to its device, so "device-issued" cannot be checked after day one. A `push` token is the CLI's write key whichever way it was made. It also refuses a `full` account ban, the same check every store token read makes (PRD-820). +- 2026-11-21 (agent, after the Sol 6.2 review): `tokenAccount` accepts only a token the device flow issued. Migration `0033_device_tokens.sql` adds `api_tokens.device`, because the daily sweep deletes the `device_codes` row that once linked them. A hand-minted store `push` token therefore cannot replace share links. It refuses a `full` or `publish_only` account ban, since a share link is publishing. +- 2026-11-21 (agent, after the Sol 6.2 review): the daily sweep deleted every device-flow token with its 10-minute code, collected or not, so each CLI login died within a day (`tn-store login` too). It now deletes only uncollected tokens. +- 2026-11-21 (agent, Sol 6.2 review finding 8, deferred): two overlapping publishes of one game can delete each other's new files inside `publishShare`. The Publish button has the same race today, so it gets its own follow-up and is not fixed in this PRD. - 2026-11-21 (agent, implementation): `/api/store/device/approve` now refuses an account without the current terms (`TN_API_TERMS`), beside the existing unverified check. Without it, a terms-pending account would get a token that `tokenAccount` refuses on every deploy. This also applies to `tn-store login`, under the PRD-015 consent rule. ## Execution Phases diff --git a/packages/create-threenative/__tests__/login.spec.ts b/packages/create-threenative/__tests__/login.spec.ts index 6f06f97496..0ecaf1e654 100644 --- a/packages/create-threenative/__tests__/login.spec.ts +++ b/packages/create-threenative/__tests__/login.spec.ts @@ -1,5 +1,5 @@ import { once } from "node:events"; -import { mkdir, readFile, stat, writeFile } from "node:fs/promises"; +import { chmod, mkdir, readFile, stat, writeFile } from "node:fs/promises"; import { type IncomingMessage, type ServerResponse, createServer } from "node:http"; import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; @@ -128,6 +128,29 @@ describe("threenative login and logout", () => { await site.close(); }); + it("tightens an existing world-readable token file when signing in again", async () => { + const file = authFilePath(); + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, JSON.stringify({ token: "tok-old" })); + await chmod(file, 0o644); + const site = await fakeSite((request) => { + if (request.url === "/api/store/device") return deviceStart("NEW1-CODE"); + if (request.url === "/api/store/device/token") + return { body: { status: "approved", token: "tok-new" }, status: 200 }; + if (request.url === "/api/store/whoami") return { body: { email: "n@b.c" }, status: 200 }; + return { body: { message: "unexpected request" }, status: 404 }; + }); + + await login({ open: false, out: () => {}, site: site.origin, sleep: async () => {} }); + + expect((await stat(file)).mode & 0o777).toBe(0o600); + expect(JSON.parse(await readFile(file, "utf8"))).toMatchObject({ + email: "n@b.c", + token: "tok-new", + }); + await site.close(); + }); + it("asks you to log in again when the code expired", async () => { const site = await fakeSite((request) => request.url === "/api/store/device" @@ -165,6 +188,39 @@ describe("threenative login and logout", () => { await site.close(); }); + it("keeps the token file when the server refuses the revoke", async () => { + const file = authFilePath(); + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, JSON.stringify({ token: "tok-file" })); + const site = await fakeSite(() => ({ body: { message: "Server exploded." }, status: 500 })); + const lines: string[] = []; + + const failure = await failureOf(logout({ out: (line) => lines.push(line), site: site.origin })); + + expect(failure.code).toBe(4); + expect(failure.message).toBe( + "Could not revoke the token (500). It is still saved; run threenative logout again.", + ); + expect(JSON.parse(await readFile(file, "utf8"))).toMatchObject({ token: "tok-file" }); + expect(lines).toEqual([]); + await site.close(); + }); + + it("keeps the token file when the site is unreachable", async () => { + const file = authFilePath(); + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, JSON.stringify({ token: "tok-file" })); + const site = await fakeSite(() => ({ body: {}, status: 200 })); + const origin = site.origin; + await site.close(); + + const failure = await failureOf(logout({ out: () => {}, site: origin })); + + expect(failure.code).toBe(5); + expect(failure.message).toContain(`Could not reach ${origin}`); + expect(JSON.parse(await readFile(file, "utf8"))).toMatchObject({ token: "tok-file" }); + }); + it("prefers THREENATIVE_TOKEN over the saved file", async () => { const file = authFilePath(); await mkdir(path.dirname(file), { recursive: true }); diff --git a/packages/create-threenative/src/account.ts b/packages/create-threenative/src/account.ts index 93905fa273..b73847bb1b 100644 --- a/packages/create-threenative/src/account.ts +++ b/packages/create-threenative/src/account.ts @@ -4,7 +4,7 @@ * Exit codes are shared by login, logout and deploy: 0 ok, 2 bad arguments, 3 sign in again, * 4 refused by the server, 5 network failure. `main()` prints the message and sets the code. */ import { spawn } from "node:child_process"; -import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import { homedir } from "node:os"; import path from "node:path"; @@ -71,20 +71,22 @@ export interface IReply { statusText: string; } -/** One JSON request. A thrown fetch is the only thing exit code 5 means, so it is caught here. */ +/** One JSON request. A broken connection is the only thing exit code 5 means, so it is caught + * here: both a fetch that never connected and a body that dies after the headers arrived. */ export async function request( origin: string, pathname: string, init: RequestInit = {}, ): Promise { let response: Response; + let text: string; try { response = await fetch(`${origin}${pathname}`, init); + text = await response.text(); } catch (error) { const reason = error instanceof Error ? error.message : String(error); throw new CliExit(5, `Could not reach ${origin}: ${reason}`); } - const text = await response.text(); let body: unknown = text; try { body = text === "" ? undefined : JSON.parse(text); @@ -116,9 +118,13 @@ function jsonPost(value: unknown): RequestInit { async function writeAuthFile(auth: IAuthFile): Promise { const file = authFilePath(); await mkdir(path.dirname(file), { mode: 0o700, recursive: true }); - await writeFile(file, `${JSON.stringify(auth, null, 2)}\n`, { mode: 0o600 }); - // writeFile keeps the mode of a file that already exists, so tighten it again. - await chmod(file, 0o600); + // Create the token 0600 beside the real file and rename it over: a rename replaces the + // destination atomically, so no window leaves the new token in a world-readable inode. + // A crashed run can leave a temp file behind, and `wx` refuses to reuse it. + const tmp = `${file}.tmp`; + await rm(tmp, { force: true }); + await writeFile(tmp, `${JSON.stringify(auth, null, 2)}\n`, { flag: "wx", mode: 0o600 }); + await rename(tmp, file); } function openBrowser(link: string): void { @@ -207,7 +213,12 @@ export interface ILogoutOptions { site?: string; } -/** Revoke the saved token and delete the file. `THREENATIVE_TOKEN` is not touched. */ +/** Revoke the saved token and delete the file. `THREENATIVE_TOKEN` is not touched. + * + * The file goes only when the server answered 200 or 401 (401 means the token is already dead, + * so this machine is signed out either way). Any other answer, or a network failure from + * `request()`, leaves the token saved: a token still alive on the server must not be dropped + * from this machine, or `logout` could never revoke it again. */ export async function logout(options: ILogoutOptions = {}): Promise { const out = options.out ?? ((line: string) => process.stdout.write(`${line}\n`)); const env = process.env; @@ -217,20 +228,15 @@ export async function logout(options: ILogoutOptions = {}): Promise { return; } const origin = siteOrigin(options.site); - let warning: string | undefined; - try { - const reply = await request(origin, "/api/store/token", { - headers: { authorization: `Bearer ${token}` }, - method: "DELETE", - }); - // 401 means the server already forgot this token: this machine is signed out either way. - if (reply.status !== 200 && reply.status !== 401) - warning = `Could not revoke the token online (${reply.status}).`; - } catch (error) { - if (!(error instanceof CliExit) || error.code !== 5) throw error; - warning = `${error.message} The token was not revoked online, but this machine is signed out.`; - } + const reply = await request(origin, "/api/store/token", { + headers: { authorization: `Bearer ${token}` }, + method: "DELETE", + }); + if (reply.status !== 200 && reply.status !== 401) + throw new CliExit( + 4, + `Could not revoke the token (${reply.status}). It is still saved; run threenative logout again.`, + ); await rm(authFilePath(env), { force: true }); - if (warning !== undefined) out(warning); out("Signed out."); } From 4a288db5854b50edf339267402307b72afbfd917 Mon Sep 17 00:00:00 2001 From: Joao Paulo Furtado Date: Sat, 21 Nov 2026 20:23:07 -0700 Subject: [PATCH 09/20] fix(create-threenative): unique temp token file, accurate logout help, first deploy carries a key so a lost reply retries onto one game (PRD-904 Sol re-review) --- packages/create-threenative/AGENTS.md | 4 +- packages/create-threenative/CLAUDE.md | 4 +- .../__tests__/deploy.spec.ts | 93 ++++++++++++++++--- .../__tests__/login.spec.ts | 4 +- packages/create-threenative/src/account.ts | 17 ++-- packages/create-threenative/src/deploy.ts | 41 ++++++-- .../create-threenative/src/threenative.ts | 12 ++- 7 files changed, 140 insertions(+), 35 deletions(-) diff --git a/packages/create-threenative/AGENTS.md b/packages/create-threenative/AGENTS.md index aa4ded882f..d290b913c0 100644 --- a/packages/create-threenative/AGENTS.md +++ b/packages/create-threenative/AGENTS.md @@ -85,8 +85,8 @@ and `flutter doctor`), `login` (device-code sign-in: prints a link and a code, p browser authorizes, and saves the granted token owner-only; `--no-browser` for a machine whose browser is elsewhere), `logout` (revokes that token on the site and deletes the file), and `deploy` (runs the package's `build:web`, uploads `dist/` to Studio, and prints the share link on -its own last stdout line, reusing `.threenative/share.json`'s project id so the next deploy keeps -the same link). `__tests__/cli.spec.ts` derives the advertised list from the real executable and +its own last stdout line, reusing `.threenative/share.json`'s project id, or its first-deploy key, +so the next deploy keeps the same link). `__tests__/cli.spec.ts` derives the advertised list from the real executable and rejects anything else, so this document cannot outgrow the binary. A new command borrows its name from an established CLI (`npm`, `wrangler`, `vercel`), never a new word. The scaffolder itself takes a target directory plus `inspect [--json]`; its flags stay diff --git a/packages/create-threenative/CLAUDE.md b/packages/create-threenative/CLAUDE.md index 96cec0d178..3d11ba1b41 100644 --- a/packages/create-threenative/CLAUDE.md +++ b/packages/create-threenative/CLAUDE.md @@ -87,8 +87,8 @@ and `flutter doctor`), `login` (device-code sign-in: prints a link and a code, p browser authorizes, and saves the granted token owner-only; `--no-browser` for a machine whose browser is elsewhere), `logout` (revokes that token on the site and deletes the file), and `deploy` (runs the package's `build:web`, uploads `dist/` to Studio, and prints the share link on -its own last stdout line, reusing `.threenative/share.json`'s project id so the next deploy keeps -the same link). `__tests__/cli.spec.ts` derives the advertised list from the real executable and +its own last stdout line, reusing `.threenative/share.json`'s project id, or its first-deploy key, +so the next deploy keeps the same link). `__tests__/cli.spec.ts` derives the advertised list from the real executable and rejects anything else, so this document cannot outgrow the binary. A new command borrows its name from an established CLI (`npm`, `wrangler`, `vercel`), never a new word. The scaffolder itself takes a target directory plus `inspect [--json]`; its flags stay diff --git a/packages/create-threenative/__tests__/deploy.spec.ts b/packages/create-threenative/__tests__/deploy.spec.ts index 64e4a75584..92c5676efe 100644 --- a/packages/create-threenative/__tests__/deploy.spec.ts +++ b/packages/create-threenative/__tests__/deploy.spec.ts @@ -26,7 +26,9 @@ interface IFakeStudio { } /** A stand-in for studio.threenative.com on 127.0.0.1, so no test reaches the real Studio. */ -async function fakeStudio(handler: (request: IRequestRecord) => IReply): Promise { +async function fakeStudio( + handler: (request: IRequestRecord) => IReply | Promise, +): Promise { const requests: IRequestRecord[] = []; const server = createServer(async (request: IncomingMessage, response: ServerResponse) => { const chunks: Buffer[] = []; @@ -38,7 +40,7 @@ async function fakeStudio(handler: (request: IRequestRecord) => IReply): Promise url: request.url, }; requests.push(record); - const reply = handler(record); + const reply = await handler(record); response.statusCode = reply.status; response.setHeader("content-type", "application/json"); response.end(reply.body === undefined ? "" : JSON.stringify(reply.body)); @@ -91,6 +93,25 @@ async function writeBuild(cwd: string): Promise { await writeFile(path.join(cwd, "dist", "index.html"), "

hi

"); } +interface IShareSnapshot { + deployKey?: string; + projectId?: string; +} + +/** What `.threenative/share.json` held at this instant, read from inside a fake Studio handler. */ +async function readShareFile(cwd: string): Promise { + try { + const text = await readFile(path.join(cwd, ".threenative", "share.json"), "utf8"); + return JSON.parse(text) as IShareSnapshot; + } catch { + return undefined; + } +} + +function queryOf(url: string | undefined): URLSearchParams { + return new URLSearchParams((url ?? "").split("?")[1] ?? ""); +} + async function failureOf(run: Promise): Promise { const failure = await run.then( () => undefined, @@ -120,12 +141,15 @@ describe("threenative deploy", () => { expect(entries.some(({ name }) => name === "a/b.js.br")).toBe(false); }); - it("publishes the build and keeps the same link on the next deploy", async () => { + it("keys the first deploy and keeps the same link on the next deploy", async () => { const cwd = await projectDir({ "build:web": "vite build" }); - const site = await fakeStudio(() => ({ - body: { projectId: "p1", shareUrl: "https://x-share.example/" }, - status: 200, - })); + // What share.json held as each upload arrived: the key has to be written before the upload, + // or a reply lost on the way back would leave the retry with nothing to name the game by. + const shareAtRequest: (IShareSnapshot | undefined)[] = []; + const site = await fakeStudio(async () => { + shareAtRequest.push(await readShareFile(cwd)); + return { body: { projectId: "p1", shareUrl: "https://x-share.example/" }, status: 200 }; + }); const lines: string[] = []; const options = { cwd, @@ -141,19 +165,66 @@ describe("threenative deploy", () => { expect(site.requests[0]).toMatchObject({ authorization: "Bearer tok-1", method: "PUT", - url: "/api/cli/share?name=game", }); + const firstQuery = queryOf(site.requests[0]?.url); + const deployKey = firstQuery.get("key"); + expect(deployKey).toMatch(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/u); + expect(firstQuery.get("name")).toBe("game"); + expect(firstQuery.has("projectId")).toBe(false); + // Written before the request arrived, and the same key the request carried. + expect(shareAtRequest[0]).toEqual({ deployKey }); expect(entry(site.requests[0]?.body ?? Buffer.alloc(0), "index.html")).toBe("

hi

"); // The link alone on the last stdout line: an agent parses that line, not the prose above it. expect(lines.at(-1)).toBe("https://x-share.example/"); - const shareFile = path.join(cwd, ".threenative", "share.json"); - expect(await readFile(shareFile, "utf8")).toBe('{\n "projectId": "p1"\n}\n'); - expect(JSON.parse(await readFile(shareFile, "utf8"))).toEqual({ projectId: "p1" }); + expect(await readShareFile(cwd)).toEqual({ deployKey, projectId: "p1" }); const second = await deploy(options); expect(site.requests[1]?.url).toBe("/api/cli/share?name=game&projectId=p1"); + expect(queryOf(site.requests[1]?.url).has("key")).toBe(false); + expect(shareAtRequest[1]).toEqual({ deployKey, projectId: "p1" }); expect(second).toEqual(first); + expect(await readShareFile(cwd)).toEqual({ deployKey, projectId: "p1" }); + await site.close(); + }); + + it("retries a first deploy whose reply was lost with the same key, so it lands on one game", async () => { + const cwd = await projectDir({ "build:web": "vite build" }); + let uploads = 0; + const site = await fakeStudio(() => { + uploads += 1; + return uploads === 1 + ? { body: { message: "Studio fell over." }, status: 500 } + : { body: { projectId: "p1", shareUrl: "https://x-share.example/" }, status: 200 }; + }); + const options = { + cwd, + out: () => {}, + runBuild: writeBuild, + studio: site.origin, + token: "tok-1", + }; + + const failure = await failureOf(deploy(options)); + + expect(failure.code).toBe(4); + expect(failure.message).toBe("Studio fell over."); + const afterFailure = await readShareFile(cwd); + // The key outlives the failed upload, and nothing else was written: no game id exists yet. + expect(afterFailure?.deployKey).toMatch( + /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/u, + ); + expect(Object.keys(afterFailure ?? {})).toEqual(["deployKey"]); + + const retried = await deploy(options); + + expect(retried).toEqual({ projectId: "p1", shareUrl: "https://x-share.example/" }); + expect(queryOf(site.requests[1]?.url).get("key")).toBe(afterFailure?.deployKey); + expect(queryOf(site.requests[1]?.url).has("projectId")).toBe(false); + expect(await readShareFile(cwd)).toEqual({ + deployKey: afterFailure?.deployKey, + projectId: "p1", + }); await site.close(); }); diff --git a/packages/create-threenative/__tests__/login.spec.ts b/packages/create-threenative/__tests__/login.spec.ts index 0ecaf1e654..431f194720 100644 --- a/packages/create-threenative/__tests__/login.spec.ts +++ b/packages/create-threenative/__tests__/login.spec.ts @@ -1,5 +1,5 @@ import { once } from "node:events"; -import { chmod, mkdir, readFile, stat, writeFile } from "node:fs/promises"; +import { chmod, mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises"; import { type IncomingMessage, type ServerResponse, createServer } from "node:http"; import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; @@ -114,6 +114,8 @@ describe("threenative login and logout", () => { expect((await stat(file)).mode & 0o777).toBe(0o600); const saved = JSON.parse(await readFile(file, "utf8")) as { email?: string; token?: string }; expect(saved).toMatchObject({ email: "a@b.c", token: "tok-1" }); + // The token was renamed into place from a temp file of its own name: nothing is left beside it. + expect(await readdir(path.dirname(file))).toEqual(["auth.json"]); expect(lines.join("\n")).toContain("/account/device/?code=ABCD-EFGH"); expect(lines.join("\n")).toContain("Signed in as a@b.c"); expect(polls).toBe(3); diff --git a/packages/create-threenative/src/account.ts b/packages/create-threenative/src/account.ts index b73847bb1b..e60ea31fcd 100644 --- a/packages/create-threenative/src/account.ts +++ b/packages/create-threenative/src/account.ts @@ -4,6 +4,7 @@ * Exit codes are shared by login, logout and deploy: 0 ok, 2 bad arguments, 3 sign in again, * 4 refused by the server, 5 network failure. `main()` prints the message and sets the code. */ import { spawn } from "node:child_process"; +import { randomUUID } from "node:crypto"; import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import { homedir } from "node:os"; import path from "node:path"; @@ -119,12 +120,16 @@ async function writeAuthFile(auth: IAuthFile): Promise { const file = authFilePath(); await mkdir(path.dirname(file), { mode: 0o700, recursive: true }); // Create the token 0600 beside the real file and rename it over: a rename replaces the - // destination atomically, so no window leaves the new token in a world-readable inode. - // A crashed run can leave a temp file behind, and `wx` refuses to reuse it. - const tmp = `${file}.tmp`; - await rm(tmp, { force: true }); - await writeFile(tmp, `${JSON.stringify(auth, null, 2)}\n`, { flag: "wx", mode: 0o600 }); - await rename(tmp, file); + // destination atomically, so no window leaves the new token in a world-readable inode. The + // temp name is unique per write, so two logins sharing one config directory never share it. + const tmp = `${file}.${randomUUID()}.tmp`; + try { + await writeFile(tmp, `${JSON.stringify(auth, null, 2)}\n`, { flag: "wx", mode: 0o600 }); + await rename(tmp, file); + } catch (error) { + await rm(tmp, { force: true }); + throw error; + } } function openBrowser(link: string): void { diff --git a/packages/create-threenative/src/deploy.ts b/packages/create-threenative/src/deploy.ts index 24272ae9ca..3e296a5627 100644 --- a/packages/create-threenative/src/deploy.ts +++ b/packages/create-threenative/src/deploy.ts @@ -1,6 +1,7 @@ /** `threenative deploy`: build the web bundle, pack it and PUT it to Studio's share endpoint, * which is what turns a game into a link a friend can open. */ import { spawn } from "node:child_process"; +import { randomUUID } from "node:crypto"; import { mkdir, readFile, readdir, writeFile } from "node:fs/promises"; import path from "node:path"; import { CliExit, request, requireToken, serverMessage } from "./account.js"; @@ -79,6 +80,8 @@ interface IProjectManifest { } interface IShareFile { + /** 36-char UUID sent as `key` on the first deploy, so a lost reply retries onto one game. */ + deployKey?: string; projectId?: string; } @@ -90,6 +93,11 @@ async function readJson(file: string): Promise { } } +async function writeShareFile(file: string, share: IShareFile): Promise { + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, `${JSON.stringify(share, null, 2)}\n`); +} + export interface IDeployOptions { cwd?: string; out?: (line: string) => void; @@ -126,9 +134,25 @@ export async function deploy(options: IDeployOptions = {}): Promise(sharePath); - const existing = previous?.projectId; + const previousProject = typeof previous?.projectId === "string" ? previous.projectId : ""; + const previousKey = + typeof previous?.deployKey === "string" && previous.deployKey !== "" + ? previous.deployKey + : undefined; const query = new URLSearchParams({ name: manifest.name }); - if (typeof existing === "string" && existing !== "") query.set("projectId", existing); + // Later deploys name the game they already own. A first deploy has no id yet, so it sends a key + // Studio can recognize the game by instead — written to share.json before the upload, so a reply + // lost on the way back still lands on that same game when this command runs again. + let deployKey = previousKey; + if (previousProject !== "") { + query.set("projectId", previousProject); + } else { + if (deployKey === undefined) { + deployKey = randomUUID(); + await writeShareFile(sharePath, { deployKey }); + } + query.set("key", deployKey); + } const reply = await request(studio, `/api/cli/share?${query.toString()}`, { // fetch's BodyInit wants a plain view, not Node's Buffer subclass. @@ -156,14 +180,15 @@ export async function deploy(options: IDeployOptions = {}): Promise Date: Sat, 21 Nov 2026 20:31:36 -0700 Subject: [PATCH 10/20] docs(prd): PRD-904 AC-6 reruns green after the Sol review fixes --- ...04-threenative-login-and-deploy-publish-like-studio-share.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md b/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md index fa6cb7aa35..038e36056e 100644 --- a/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md +++ b/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md @@ -70,7 +70,7 @@ Risks: the packer is copied, and the copy can drift from Studio's. `ponytail:` t - [x] AC-3 [local]: `StudioAccounts.tokenAccount` returns the account for a live device-issued token and refuses a revoked, expired or unknown token, an unverified email and an account without current terms. proof: site `pnpm vitest --config vitest.worker.config.ts worker/__tests__/studio-auth.spec.ts` — Evidence: 13/13 in `studio-auth.spec.ts`, inside the 229/229 site worker run. - [x] AC-4 [local]: `PUT /api/cli/share` with a valid token creates a project and returns a share URL. A second call with that `projectId` keeps the same URL and serves the new build. No token gets 401; no `index.html` or over 50 MB gets Studio's refusal message. proof: Studio `hosting/cloudflare` vitest — Evidence: `test/cli-share.spec.ts` 9/9 (create, same URL with new bytes, 401, 422 no `index.html`, 403 suspended and closed beta, 404 foreign project, 502 site down); the 50 MB refusal is `publishShare`'s own, covered by `test/share.spec.ts` in the same 359/359 run. - [x] AC-5 [local]: `threenative deploy` runs `build:web`, packs `dist/` byte-for-byte like Studio's `packDirectory` on the same folder, uploads, writes `.threenative/share.json` once and prints the URL. proof: `pnpm exec vitest run packages/create-threenative/__tests__/deploy.spec.ts` — Evidence: `deploy.spec.ts` 5/5; in the AC-6 run the real `build:web` ran, and the engine and Studio `packDirectory` on the same 16 474 839-byte `dist/` gave the same sha256 `1645cccf…0462`. -- [x] AC-6 [local]: A scaffolded starter, with the local `create-threenative` tarball, local site and Studio `wrangler dev`, runs `threenative login` (scripted Authorize) then `threenative deploy` twice. The share URL serves the game's `index.html` and stays the same across both deploys. The Studio games list shows the game with that link. proof: run log in the PR — Evidence: PR #712 comment. Starter scaffolded with the local `create-threenative-0.2.25.tgz`; two deploys printed the same `share-ac6-game-g226` link and kept `projectId 095e83ba…`; the link served `dist/index.html` (plus Studio's report link); Studio D1 lists `ac6-game` with that share id for `e2e@example.com`; logout revoked the token in site D1 and the next deploy exited 3. +- [x] AC-6 [local]: A scaffolded starter, with the local `create-threenative` tarball, local site and Studio `wrangler dev`, runs `threenative login` (scripted Authorize) then `threenative deploy` twice. The share URL serves the game's `index.html` and stays the same across both deploys. The Studio games list shows the game with that link. proof: run log in the PR — Evidence: PR #712 comment. Starter scaffolded with the local `create-threenative-0.2.25.tgz`; two deploys printed the same `share-ac6-game-g226` link and kept `projectId 095e83ba…`; the link served `dist/index.html` (plus Studio's report link); Studio D1 lists `ac6-game` with that share id for `e2e@example.com`; logout revoked the token in site D1 and the next deploy exited 3. Rerun after the Sol review fixes (deploy key, device-only tokens, migration 0015): same results, `share.json` holds `projectId` and `deployKey`, the revoked token row shows `device=1 revoked=1`, and the config dir holds only `auth.json`. - [x] AC-8 [local]: On `/account/device/?code=…`, an unverified or terms-pending account completes verify and terms and returns to the same code, then Authorize succeeds. The page names `threenative login`. proof: site `e2e/worker/store-device.spec.ts` — Evidence: the two PRD-904 AC-8 cases pass (terms-pending accepts on `/signin/` and approves the same code; unverified lands on `/signin/` verify with the code in `next`). - [ ] AC-7 [shared]: After site, Studio and engine releases, a `pnpm sandbox` clean room runs `npx create-threenative` → `npx threenative login` → `npx threenative deploy` and opens the live share URL. proof: `pnpm sandbox` run log — Evidence: pending. From 2bcef2c7c7db5103cf512f67c764efd8e3bcb148 Mon Sep 17 00:00:00 2001 From: Joao Paulo Furtado Date: Sat, 21 Nov 2026 20:35:34 -0700 Subject: [PATCH 11/20] fix(create-threenative): share.json is written through a temp file and renamed, so an interrupted write cannot lose the deploy key (PRD-904 Sol review 3) --- ...ve-login-and-deploy-publish-like-studio-share.md | 2 +- .../create-threenative/__tests__/deploy.spec.ts | 4 +++- packages/create-threenative/src/deploy.ts | 13 +++++++++++-- 3 files changed, 15 insertions(+), 4 deletions(-) diff --git a/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md b/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md index 038e36056e..279425facc 100644 --- a/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md +++ b/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md @@ -97,7 +97,7 @@ Fill the dispatcher and route `file:line` values when each phase lands. - 2026-11-21 (agent): the login is TypeScript in the engine, not a call to the private `tn-store` binary. Deploy no longer needs that binary, and the device flow is three `fetch` calls. - 2026-11-21 (agent, after the Sol 6.2 review): `tokenAccount` accepts only a token the device flow issued. Migration `0033_device_tokens.sql` adds `api_tokens.device`, because the daily sweep deletes the `device_codes` row that once linked them. A hand-minted store `push` token therefore cannot replace share links. It refuses a `full` or `publish_only` account ban, since a share link is publishing. - 2026-11-21 (agent, after the Sol 6.2 review): the daily sweep deleted every device-flow token with its 10-minute code, collected or not, so each CLI login died within a day (`tn-store login` too). It now deletes only uncollected tokens. -- 2026-11-21 (agent, Sol 6.2 review finding 8, deferred): two overlapping publishes of one game can delete each other's new files inside `publishShare`. The Publish button has the same race today, so it gets its own follow-up and is not fixed in this PRD. +- 2026-11-21 (agent, Sol 6.2 review finding 8, deferred): two overlapping publishes of one game can delete each other's new files inside `publishShare`. The Publish button has the same race today, so it gets its own follow-up and is not fixed in this PRD. The same follow-up owns the third review's orphaned R2 objects: when one R2 write fails after others succeed on a game's first publish, `publishShare` has not recorded the share id, so nothing sweeps those files. The Publish button leaves the same orphans. - 2026-11-21 (agent, implementation): `/api/store/device/approve` now refuses an account without the current terms (`TN_API_TERMS`), beside the existing unverified check. Without it, a terms-pending account would get a token that `tokenAccount` refuses on every deploy. This also applies to `tn-store login`, under the PRD-015 consent rule. ## Execution Phases diff --git a/packages/create-threenative/__tests__/deploy.spec.ts b/packages/create-threenative/__tests__/deploy.spec.ts index 92c5676efe..9951c0d7d8 100644 --- a/packages/create-threenative/__tests__/deploy.spec.ts +++ b/packages/create-threenative/__tests__/deploy.spec.ts @@ -1,5 +1,5 @@ import { once } from "node:events"; -import { mkdir, readFile, writeFile } from "node:fs/promises"; +import { mkdir, readFile, readdir, writeFile } from "node:fs/promises"; import { type IncomingMessage, type ServerResponse, createServer } from "node:http"; import path from "node:path"; import { describe, expect, it } from "vitest"; @@ -185,6 +185,8 @@ describe("threenative deploy", () => { expect(shareAtRequest[1]).toEqual({ deployKey, projectId: "p1" }); expect(second).toEqual(first); expect(await readShareFile(cwd)).toEqual({ deployKey, projectId: "p1" }); + // Written through a temp file and renamed: nothing but share.json is left behind. + expect(await readdir(path.join(cwd, ".threenative"))).toEqual(["share.json"]); await site.close(); }); diff --git a/packages/create-threenative/src/deploy.ts b/packages/create-threenative/src/deploy.ts index 3e296a5627..b035b077db 100644 --- a/packages/create-threenative/src/deploy.ts +++ b/packages/create-threenative/src/deploy.ts @@ -2,7 +2,7 @@ * which is what turns a game into a link a friend can open. */ import { spawn } from "node:child_process"; import { randomUUID } from "node:crypto"; -import { mkdir, readFile, readdir, writeFile } from "node:fs/promises"; +import { mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { CliExit, request, requireToken, serverMessage } from "./account.js"; @@ -93,9 +93,18 @@ async function readJson(file: string): Promise { } } +/** Written beside and renamed over, so an interrupted write never leaves a truncated file that loses + * the deploy key (the next deploy would then make a second game). */ async function writeShareFile(file: string, share: IShareFile): Promise { await mkdir(path.dirname(file), { recursive: true }); - await writeFile(file, `${JSON.stringify(share, null, 2)}\n`); + const tmp = `${file}.${randomUUID()}.tmp`; + try { + await writeFile(tmp, `${JSON.stringify(share, null, 2)}\n`, { flag: "wx" }); + await rename(tmp, file); + } catch (error) { + await rm(tmp, { force: true }); + throw error; + } } export interface IDeployOptions { From 50d8d7234b34cb9bd9ec478231ff6a8fc5cdcfa0 Mon Sep 17 00:00:00 2001 From: Joao Paulo Furtado Date: Sat, 21 Nov 2026 20:47:52 -0700 Subject: [PATCH 12/20] fix(create-threenative): two first deploys from one checkout claim one deploy key through an atomic link (PRD-904 Sol review 4) --- .../__tests__/deploy.spec.ts | 24 +++++++++++++++ packages/create-threenative/src/deploy.ts | 29 +++++++++++++++---- 2 files changed, 48 insertions(+), 5 deletions(-) diff --git a/packages/create-threenative/__tests__/deploy.spec.ts b/packages/create-threenative/__tests__/deploy.spec.ts index 9951c0d7d8..bc1fd3a543 100644 --- a/packages/create-threenative/__tests__/deploy.spec.ts +++ b/packages/create-threenative/__tests__/deploy.spec.ts @@ -190,6 +190,30 @@ describe("threenative deploy", () => { await site.close(); }); + it("gives two first deploys started together one key, so they land on one game", async () => { + const cwd = await projectDir({ "build:web": "vite build" }); + const site = await fakeStudio(() => ({ + body: { projectId: "p1", shareUrl: "https://x-share.example/" }, + status: 200, + })); + const options = { + cwd, + out: () => {}, + runBuild: writeBuild, + studio: site.origin, + token: "tok-1", + }; + + await Promise.all([deploy(options), deploy(options)]); + + const keys = site.requests.map((request) => queryOf(request.url).get("key")); + expect(keys).toHaveLength(2); + expect(keys[0]).toBeTypeOf("string"); + expect(keys[1]).toBe(keys[0]); + expect(await readdir(path.join(cwd, ".threenative"))).toEqual(["share.json"]); + await site.close(); + }); + it("retries a first deploy whose reply was lost with the same key, so it lands on one game", async () => { const cwd = await projectDir({ "build:web": "vite build" }); let uploads = 0; diff --git a/packages/create-threenative/src/deploy.ts b/packages/create-threenative/src/deploy.ts index b035b077db..ec8118d3cc 100644 --- a/packages/create-threenative/src/deploy.ts +++ b/packages/create-threenative/src/deploy.ts @@ -2,7 +2,7 @@ * which is what turns a game into a link a friend can open. */ import { spawn } from "node:child_process"; import { randomUUID } from "node:crypto"; -import { mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises"; +import { link, mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { CliExit, request, requireToken, serverMessage } from "./account.js"; @@ -107,6 +107,28 @@ async function writeShareFile(file: string, share: IShareFile): Promise { } } +/** The first deploy's key, claimed once per checkout. `link` creates share.json only if it does not + * exist yet, with its whole content, so two first deploys started together agree on one key: the + * one that loses the link reads the winner's key instead of minting a second game. */ +async function claimDeployKey(file: string): Promise { + await mkdir(path.dirname(file), { recursive: true }); + const mine = randomUUID(); + const tmp = `${file}.${mine}.tmp`; + await writeFile(tmp, `${JSON.stringify({ deployKey: mine }, null, 2)}\n`, { flag: "wx" }); + try { + await link(tmp, file); + return mine; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; + const theirs = (await readJson(file))?.deployKey; + if (typeof theirs !== "string" || theirs === "") + throw new CliExit(4, `${file} exists but holds no deploy key; fix or delete it.`); + return theirs; + } finally { + await rm(tmp, { force: true }); + } +} + export interface IDeployOptions { cwd?: string; out?: (line: string) => void; @@ -156,10 +178,7 @@ export async function deploy(options: IDeployOptions = {}): Promise Date: Sat, 21 Nov 2026 21:18:12 -0700 Subject: [PATCH 13/20] fix(create-threenative): logout deletes the token file only while it still holds the revoked token (PRD-904 Sol review 8) --- ...gin-and-deploy-publish-like-studio-share.md | 2 +- .../create-threenative/__tests__/login.spec.ts | 18 ++++++++++++++++++ packages/create-threenative/src/account.ts | 5 ++++- 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md b/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md index 279425facc..559a0705da 100644 --- a/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md +++ b/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md @@ -97,7 +97,7 @@ Fill the dispatcher and route `file:line` values when each phase lands. - 2026-11-21 (agent): the login is TypeScript in the engine, not a call to the private `tn-store` binary. Deploy no longer needs that binary, and the device flow is three `fetch` calls. - 2026-11-21 (agent, after the Sol 6.2 review): `tokenAccount` accepts only a token the device flow issued. Migration `0033_device_tokens.sql` adds `api_tokens.device`, because the daily sweep deletes the `device_codes` row that once linked them. A hand-minted store `push` token therefore cannot replace share links. It refuses a `full` or `publish_only` account ban, since a share link is publishing. - 2026-11-21 (agent, after the Sol 6.2 review): the daily sweep deleted every device-flow token with its 10-minute code, collected or not, so each CLI login died within a day (`tn-store login` too). It now deletes only uncollected tokens. -- 2026-11-21 (agent, Sol 6.2 review finding 8, deferred): two overlapping publishes of one game can delete each other's new files inside `publishShare`. The Publish button has the same race today, so it gets its own follow-up and is not fixed in this PRD. The same follow-up owns the third review's orphaned R2 objects: when one R2 write fails after others succeed on a game's first publish, `publishShare` has not recorded the share id, so nothing sweeps those files. The Publish button leaves the same orphans. +- 2026-11-21 (agent, Sol 6.2 review finding 8, deferred): two overlapping publishes of one game can delete each other's new files inside `publishShare`. The Publish button has the same race today, so it gets its own follow-up and is not fixed in this PRD. The same follow-up owns the third review's orphaned R2 objects: when one R2 write fails after others succeed on a game's first publish, `publishShare` has not recorded the share id, so nothing sweeps those files. The Publish button leaves the same orphans. The follow-up also owns the eighth review's cap race: a first deploy passes the storage pre-check, another game on the account grows before `publishShare` checks again, and the 413 leaves an unpublished keyed game holding a slot. Taking that game back would reopen the fourth review's finding (an overlapping retry may be publishing into it), so the fix is one publish lease per game, shared with the Publish button. - 2026-11-21 (agent, implementation): `/api/store/device/approve` now refuses an account without the current terms (`TN_API_TERMS`), beside the existing unverified check. Without it, a terms-pending account would get a token that `tokenAccount` refuses on every deploy. This also applies to `tn-store login`, under the PRD-015 consent rule. ## Execution Phases diff --git a/packages/create-threenative/__tests__/login.spec.ts b/packages/create-threenative/__tests__/login.spec.ts index 431f194720..ebe01aff97 100644 --- a/packages/create-threenative/__tests__/login.spec.ts +++ b/packages/create-threenative/__tests__/login.spec.ts @@ -1,4 +1,5 @@ import { once } from "node:events"; +import { writeFileSync } from "node:fs"; import { chmod, mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises"; import { type IncomingMessage, type ServerResponse, createServer } from "node:http"; import path from "node:path"; @@ -190,6 +191,23 @@ describe("threenative login and logout", () => { await site.close(); }); + it("keeps a token a login saved while logout was revoking the old one", async () => { + const file = authFilePath(); + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, JSON.stringify({ token: "tok-old" })); + // A login in another terminal finishes while the revoke is in flight. + const site = await fakeSite(() => { + writeFileSync(file, JSON.stringify({ token: "tok-new" })); + return { body: { ok: true }, status: 200 }; + }); + + await logout({ out: () => {}, site: site.origin }); + + expect(site.requests[0]?.authorization).toBe("Bearer tok-old"); + expect(JSON.parse(await readFile(file, "utf8"))).toEqual({ token: "tok-new" }); + await site.close(); + }); + it("keeps the token file when the server refuses the revoke", async () => { const file = authFilePath(); await mkdir(path.dirname(file), { recursive: true }); diff --git a/packages/create-threenative/src/account.ts b/packages/create-threenative/src/account.ts index e60ea31fcd..128cf4d114 100644 --- a/packages/create-threenative/src/account.ts +++ b/packages/create-threenative/src/account.ts @@ -242,6 +242,9 @@ export async function logout(options: ILogoutOptions = {}): Promise { 4, `Could not revoke the token (${reply.status}). It is still saved; run threenative logout again.`, ); - await rm(authFilePath(env), { force: true }); + // A login in another terminal may have saved a new token while this one was being revoked: that + // token is live and is not the one signed out, so only the file still holding the revoked one goes. + // ponytail: re-read then delete, a window of microseconds; a lock file if two terminals ever race it. + if ((await readAuthFile(env))?.token === token) await rm(authFilePath(env), { force: true }); out("Signed out."); } From f37d85d919889b7988ee9e3963184697c6bd7395 Mon Sep 17 00:00:00 2001 From: Joao Paulo Furtado Date: Sat, 21 Nov 2026 21:24:46 -0700 Subject: [PATCH 14/20] fix(create-threenative): logout claims the token file with one rename and login writes it once, so neither loses or revives the other's token (PRD-904 Sol review 9) --- .../__tests__/login.spec.ts | 11 ++- packages/create-threenative/src/account.ts | 93 ++++++++++++++----- 2 files changed, 79 insertions(+), 25 deletions(-) diff --git a/packages/create-threenative/__tests__/login.spec.ts b/packages/create-threenative/__tests__/login.spec.ts index ebe01aff97..055c5859b5 100644 --- a/packages/create-threenative/__tests__/login.spec.ts +++ b/packages/create-threenative/__tests__/login.spec.ts @@ -1,5 +1,5 @@ import { once } from "node:events"; -import { writeFileSync } from "node:fs"; +import { existsSync, writeFileSync } from "node:fs"; import { chmod, mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises"; import { type IncomingMessage, type ServerResponse, createServer } from "node:http"; import path from "node:path"; @@ -91,6 +91,7 @@ describe("threenative login and logout", () => { it("polls the device flow, saves a 0600 token file and names the account", async () => { let polls = 0; + let savedBeforeWhoami: boolean | undefined; const site = await fakeSite((request) => { if (request.url === "/api/store/device") return deviceStart("ABCD-EFGH"); if (request.url === "/api/store/device/token") { @@ -99,7 +100,12 @@ describe("threenative login and logout", () => { ? { body: { status: "pending" }, status: 200 } : { body: { status: "approved", token: "tok-1" }, status: 200 }; } - if (request.url === "/api/store/whoami") return { body: { email: "a@b.c" }, status: 200 }; + if (request.url === "/api/store/whoami") { + // Nothing is saved until the address is known: a logout racing this login can only revoke a + // token it read from the file, so one write leaves it nothing to bring back. + savedBeforeWhoami = existsSync(authFilePath()); + return { body: { email: "a@b.c" }, status: 200 }; + } return { body: { message: "unexpected request" }, status: 404 }; }); const lines: string[] = []; @@ -115,6 +121,7 @@ describe("threenative login and logout", () => { expect((await stat(file)).mode & 0o777).toBe(0o600); const saved = JSON.parse(await readFile(file, "utf8")) as { email?: string; token?: string }; expect(saved).toMatchObject({ email: "a@b.c", token: "tok-1" }); + expect(savedBeforeWhoami).toBe(false); // The token was renamed into place from a temp file of its own name: nothing is left beside it. expect(await readdir(path.dirname(file))).toEqual(["auth.json"]); expect(lines.join("\n")).toContain("/account/device/?code=ABCD-EFGH"); diff --git a/packages/create-threenative/src/account.ts b/packages/create-threenative/src/account.ts index 128cf4d114..0d3d7e3808 100644 --- a/packages/create-threenative/src/account.ts +++ b/packages/create-threenative/src/account.ts @@ -5,7 +5,7 @@ * 4 refused by the server, 5 network failure. `main()` prints the message and sets the code. */ import { spawn } from "node:child_process"; import { randomUUID } from "node:crypto"; -import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; +import { link, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import { homedir } from "node:os"; import path from "node:path"; @@ -42,9 +42,12 @@ export interface IAuthFile { token?: string; } -async function readAuthFile(env: NodeJS.ProcessEnv): Promise { +async function readAuthFile( + env: NodeJS.ProcessEnv, + file = authFilePath(env), +): Promise { try { - const parsed: unknown = JSON.parse(await readFile(authFilePath(env), "utf8")); + const parsed: unknown = JSON.parse(await readFile(file, "utf8")); return parsed !== null && typeof parsed === "object" ? (parsed as IAuthFile) : undefined; } catch { // No file, or one a person half-edited: either way this machine has no saved token. @@ -200,17 +203,29 @@ export async function login(options: ILoginOptions = {}): Promise { }; const token = await pollForToken(); - // Save before asking who this is: a whoami hiccup must not throw away a granted token. - await writeAuthFile({ token }); - const who = await request(origin, "/api/store/whoami", { - headers: { authorization: `Bearer ${token}` }, - }); - if (who.status < 200 || who.status >= 300) - throw new CliExit(4, serverMessage(who.body, `Could not read your account (${who.status}).`)); + out(`Signed in as ${await saveSignIn(origin, token)}.`); +} + +/** Saves a granted token with the address it belongs to, and returns that address. */ +async function saveSignIn(origin: string, token: string): Promise { + // One write, after asking who this is: a logout in another terminal can only revoke a token it + // read from the file, so a second write could bring back a token that logout already revoked. + // A whoami hiccup still saves the granted token, without the address, before it reports. + let who: Awaited>; + try { + who = await request(origin, "/api/store/whoami", { + headers: { authorization: `Bearer ${token}` }, + }); + } catch (error) { + await writeAuthFile({ token }); + throw error; + } const email = (who.body as { email?: unknown }).email; const address = typeof email === "string" ? email : ""; - await writeAuthFile({ email: address, token }); - out(`Signed in as ${address}.`); + await writeAuthFile(address === "" ? { token } : { email: address, token }); + if (who.status < 200 || who.status >= 300) + throw new CliExit(4, serverMessage(who.body, `Could not read your account (${who.status}).`)); + return address; } export interface ILogoutOptions { @@ -227,24 +242,56 @@ export interface ILogoutOptions { export async function logout(options: ILogoutOptions = {}): Promise { const out = options.out ?? ((line: string) => process.stdout.write(`${line}\n`)); const env = process.env; - const token = (await readAuthFile(env))?.token; + const file = authFilePath(env); + // The file is claimed first with one rename, so a login in another terminal that saves after this + // point writes a new auth.json that this logout never touches. + const claimed = `${file}.${randomUUID()}.logout`; + try { + await rename(file, claimed); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; + out("Not signed in."); + return; + } + const token = (await readAuthFile(env, claimed))?.token; if (typeof token !== "string" || token === "") { + await rm(claimed, { force: true }); out("Not signed in."); return; } const origin = siteOrigin(options.site); - const reply = await request(origin, "/api/store/token", { - headers: { authorization: `Bearer ${token}` }, - method: "DELETE", - }); - if (reply.status !== 200 && reply.status !== 401) + let reply: Awaited>; + try { + reply = await request(origin, "/api/store/token", { + headers: { authorization: `Bearer ${token}` }, + method: "DELETE", + }); + } catch (error) { + await restoreAuthFile(claimed, file); + throw error; + } + if (reply.status !== 200 && reply.status !== 401) { + const kept = await restoreAuthFile(claimed, file); throw new CliExit( 4, - `Could not revoke the token (${reply.status}). It is still saved; run threenative logout again.`, + kept + ? `Could not revoke the token (${reply.status}). It is still saved; run threenative logout again.` + : `Could not revoke the token (${reply.status}), and a newer sign-in has replaced it here. Revoke it at threenative.com.`, ); - // A login in another terminal may have saved a new token while this one was being revoked: that - // token is live and is not the one signed out, so only the file still holding the revoked one goes. - // ponytail: re-read then delete, a window of microseconds; a lock file if two terminals ever race it. - if ((await readAuthFile(env))?.token === token) await rm(authFilePath(env), { force: true }); + } + await rm(claimed, { force: true }); out("Signed out."); } + +/** Puts a claimed token file back after a failed revoke. `link` refuses to replace a file a newer login + * saved meanwhile, so that sign-in wins; `false` says the old token is no longer on this machine. */ +async function restoreAuthFile(claimed: string, file: string): Promise { + try { + await link(claimed, file); + return true; + } catch { + return false; + } finally { + await rm(claimed, { force: true }); + } +} From 1442360b292c0909b4125b7dac1743c957aeeb15 Mon Sep 17 00:00:00 2001 From: Joao Paulo Furtado Date: Sat, 21 Nov 2026 21:30:54 -0700 Subject: [PATCH 15/20] fix(create-threenative): logout keeps an unrevoked or interrupted token in its claimed file and retries it next time; an empty whoami reply still saves the token (PRD-904 Sol review 10) --- ...in-and-deploy-publish-like-studio-share.md | 1 + .../__tests__/login.spec.ts | 58 +++++++++- packages/create-threenative/src/account.ts | 107 ++++++++++-------- 3 files changed, 114 insertions(+), 52 deletions(-) diff --git a/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md b/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md index 559a0705da..c9c3ebb658 100644 --- a/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md +++ b/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md @@ -92,6 +92,7 @@ Fill the dispatcher and route `file:line` values when each phase lands. - 2026-11-21 (João): use the `threenative` CLI as it is, with no `tn` alias. The "two commands, ever" rule is removed (`f9d168b00`). - 2026-11-21 (João): deploy is the same as Studio's Publish (the share link), not the store push. +- 2026-11-21 (Sol review 10): logout claims each token file with one rename before it revokes. A token the site did not revoke stays in its claimed `auth.json..logout` file, not in `auth.json`, and every later logout revokes those leftovers too. So a failed or interrupted logout leaves the machine signed out but keeps the live token for the retry, and a login in another terminal is never lost or revived. - 2026-11-21 (João): login UX: open a link, sign in with the threenative.com account, click Authorize, and the CLI detects it. The code is also accepted typed. The existing site device flow does exactly this. - 2026-11-21 (agent, after a Gemini 4 Neon review): the store push is not the deploy path. A new account's release is held for review (`worker/games.ts:631,649`), the build farm runs scans and an AI review, and a listing needs 1 to 5 screenshots. The share link is live in seconds. - 2026-11-21 (agent): the login is TypeScript in the engine, not a call to the private `tn-store` binary. Deploy no longer needs that binary, and the device flow is three `fetch` calls. diff --git a/packages/create-threenative/__tests__/login.spec.ts b/packages/create-threenative/__tests__/login.spec.ts index 055c5859b5..df24042c9e 100644 --- a/packages/create-threenative/__tests__/login.spec.ts +++ b/packages/create-threenative/__tests__/login.spec.ts @@ -74,6 +74,18 @@ function deviceStart(userCode: string): IReply { }; } +/** The tokens a logout kept for its next run, from the claimed files beside auth.json. */ +async function keptTokens(file: string): Promise { + const dir = path.dirname(file); + const names = (await readdir(dir)).filter((name) => name.endsWith(".logout")); + return Promise.all( + names.map( + async (name) => + (JSON.parse(await readFile(path.join(dir, name), "utf8")) as { token: string }).token, + ), + ); +} + describe("threenative login and logout", () => { let configHome: string; @@ -138,6 +150,23 @@ describe("threenative login and logout", () => { await site.close(); }); + it("saves the granted token and exits 4 when whoami answers an empty 503", async () => { + const site = await fakeSite((request) => { + if (request.url === "/api/store/device") return deviceStart("ABCD-EFGH"); + if (request.url === "/api/store/device/token") + return { body: { status: "approved", token: "tok-1" }, status: 200 }; + return { status: 503 }; + }); + + const failure = await failureOf( + login({ open: false, out: () => {}, site: site.origin, sleep: async () => {} }), + ); + + expect(failure.code).toBe(4); + expect(JSON.parse(await readFile(authFilePath(), "utf8"))).toEqual({ token: "tok-1" }); + await site.close(); + }); + it("tightens an existing world-readable token file when signing in again", async () => { const file = authFilePath(); await mkdir(path.dirname(file), { recursive: true }); @@ -226,11 +255,33 @@ describe("threenative login and logout", () => { expect(failure.code).toBe(4); expect(failure.message).toBe( - "Could not revoke the token (500). It is still saved; run threenative logout again.", + "Could not revoke the token (500). The token is kept, so run threenative logout again.", ); - expect(JSON.parse(await readFile(file, "utf8"))).toMatchObject({ token: "tok-file" }); + expect(await keptTokens(file)).toEqual(["tok-file"]); expect(lines).toEqual([]); await site.close(); + + // The next logout finds the kept token and revokes it. + const retry = await fakeSite(() => ({ body: { ok: true }, status: 200 })); + await logout({ out: (line) => lines.push(line), site: retry.origin }); + expect(retry.requests[0]?.authorization).toBe("Bearer tok-file"); + expect(await readdir(path.dirname(file))).toEqual([]); + expect(lines).toEqual(["Signed out."]); + await retry.close(); + }); + + it("revokes a token an interrupted logout left behind", async () => { + const file = authFilePath(); + await mkdir(path.dirname(file), { recursive: true }); + // Ctrl+C after the claim, before the revoke: no auth.json, only the claimed file. + await writeFile(`${file}.left.logout`, JSON.stringify({ token: "tok-left" })); + const site = await fakeSite(() => ({ body: { ok: true }, status: 200 })); + + await logout({ out: () => {}, site: site.origin }); + + expect(site.requests.map((request) => request.authorization)).toEqual(["Bearer tok-left"]); + expect(await readdir(path.dirname(file))).toEqual([]); + await site.close(); }); it("keeps the token file when the site is unreachable", async () => { @@ -245,7 +296,8 @@ describe("threenative login and logout", () => { expect(failure.code).toBe(5); expect(failure.message).toContain(`Could not reach ${origin}`); - expect(JSON.parse(await readFile(file, "utf8"))).toMatchObject({ token: "tok-file" }); + expect(failure.message).toContain("The token is kept, so run threenative logout again."); + expect(await keptTokens(file)).toEqual(["tok-file"]); }); it("prefers THREENATIVE_TOKEN over the saved file", async () => { diff --git a/packages/create-threenative/src/account.ts b/packages/create-threenative/src/account.ts index 0d3d7e3808..e856dca8ea 100644 --- a/packages/create-threenative/src/account.ts +++ b/packages/create-threenative/src/account.ts @@ -5,7 +5,7 @@ * 4 refused by the server, 5 network failure. `main()` prints the message and sets the code. */ import { spawn } from "node:child_process"; import { randomUUID } from "node:crypto"; -import { link, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; +import { mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises"; import { homedir } from "node:os"; import path from "node:path"; @@ -220,7 +220,7 @@ async function saveSignIn(origin: string, token: string): Promise { await writeAuthFile({ token }); throw error; } - const email = (who.body as { email?: unknown }).email; + const email = (who.body as { email?: unknown } | null | undefined)?.email; const address = typeof email === "string" ? email : ""; await writeAuthFile(address === "" ? { token } : { email: address, token }); if (who.status < 200 || who.status >= 300) @@ -235,63 +235,72 @@ export interface ILogoutOptions { /** Revoke the saved token and delete the file. `THREENATIVE_TOKEN` is not touched. * - * The file goes only when the server answered 200 or 401 (401 means the token is already dead, - * so this machine is signed out either way). Any other answer, or a network failure from - * `request()`, leaves the token saved: a token still alive on the server must not be dropped - * from this machine, or `logout` could never revoke it again. */ + * Each token file is claimed with one rename before its revoke, so a login in another terminal that + * saves meanwhile writes a new auth.json this logout never touches. A token the server did not + * revoke (any answer but 200 or 401, or no answer) stays in its claimed `auth.json..logout` file, + * and so does one whose logout was interrupted: every logout claims those leftovers too and revokes + * them, so a live token is never dropped from this machine while nothing can revoke it. */ export async function logout(options: ILogoutOptions = {}): Promise { const out = options.out ?? ((line: string) => process.stdout.write(`${line}\n`)); const env = process.env; - const file = authFilePath(env); - // The file is claimed first with one rename, so a login in another terminal that saves after this - // point writes a new auth.json that this logout never touches. - const claimed = `${file}.${randomUUID()}.logout`; + const claims = await claimTokenFiles(authFilePath(env)); + const origin = siteOrigin(options.site); + let revoked = false; + let failure: CliExit | undefined; + for (const claimed of claims) { + const token = (await readAuthFile(env, claimed))?.token; + if (typeof token !== "string" || token === "") { + await rm(claimed, { force: true }); + continue; + } + const answer = await revokeToken(origin, token); + if (answer === undefined) { + await rm(claimed, { force: true }); + revoked = true; + } else failure = answer; + } + if (failure !== undefined) throw failure; + out(revoked ? "Signed out." : "Not signed in."); +} + +/** Claims auth.json and every token file an earlier logout left, each with one rename to a name of + * this run's own: two logouts never revoke from, or delete, one file. */ +async function claimTokenFiles(file: string): Promise { + const dir = path.dirname(file); + const base = path.basename(file); + let names: string[]; try { - await rename(file, claimed); - } catch (error) { - if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; - out("Not signed in."); - return; + names = await readdir(dir); + } catch { + return []; } - const token = (await readAuthFile(env, claimed))?.token; - if (typeof token !== "string" || token === "") { - await rm(claimed, { force: true }); - out("Not signed in."); - return; + const left = names.filter((name) => name.startsWith(`${base}.`) && name.endsWith(".logout")); + const claims: string[] = []; + for (const source of [file, ...left.map((name) => path.join(dir, name))]) { + const claimed = `${file}.${randomUUID()}.logout`; + try { + await rename(source, claimed); + claims.push(claimed); + } catch (error) { + // Gone already: never saved, or another logout claimed it first. + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; + } } - const origin = siteOrigin(options.site); - let reply: Awaited>; + return claims; +} + +/** `undefined` once the site says the token is dead (200 revoked, 401 already gone), else why not. */ +async function revokeToken(origin: string, token: string): Promise { + const kept = "The token is kept, so run threenative logout again."; try { - reply = await request(origin, "/api/store/token", { + const reply = await request(origin, "/api/store/token", { headers: { authorization: `Bearer ${token}` }, method: "DELETE", }); + if (reply.status === 200 || reply.status === 401) return undefined; + return new CliExit(4, `Could not revoke the token (${reply.status}). ${kept}`); } catch (error) { - await restoreAuthFile(claimed, file); - throw error; - } - if (reply.status !== 200 && reply.status !== 401) { - const kept = await restoreAuthFile(claimed, file); - throw new CliExit( - 4, - kept - ? `Could not revoke the token (${reply.status}). It is still saved; run threenative logout again.` - : `Could not revoke the token (${reply.status}), and a newer sign-in has replaced it here. Revoke it at threenative.com.`, - ); - } - await rm(claimed, { force: true }); - out("Signed out."); -} - -/** Puts a claimed token file back after a failed revoke. `link` refuses to replace a file a newer login - * saved meanwhile, so that sign-in wins; `false` says the old token is no longer on this machine. */ -async function restoreAuthFile(claimed: string, file: string): Promise { - try { - await link(claimed, file); - return true; - } catch { - return false; - } finally { - await rm(claimed, { force: true }); + if (!(error instanceof CliExit)) throw error; + return new CliExit(error.code, `${error.message} ${kept}`); } } From 1a003cff7fd441fa567131f34175a9fd946f7cee Mon Sep 17 00:00:00 2001 From: Joao Paulo Furtado Date: Sat, 21 Nov 2026 21:37:02 -0700 Subject: [PATCH 16/20] fix(create-threenative): logout revokes on the issuing site and keeps a file it cannot read; empty replies exit 4; the deploy key claim works without hard links (PRD-904 Sol review 11) --- .../__tests__/deploy-nolink.spec.ts | 46 +++++++++++++++++ .../__tests__/login.spec.ts | 49 ++++++++++++++++++- packages/create-threenative/src/account.ts | 49 ++++++++++++++++--- packages/create-threenative/src/deploy.ts | 24 +++++++-- 4 files changed, 154 insertions(+), 14 deletions(-) create mode 100644 packages/create-threenative/__tests__/deploy-nolink.spec.ts diff --git a/packages/create-threenative/__tests__/deploy-nolink.spec.ts b/packages/create-threenative/__tests__/deploy-nolink.spec.ts new file mode 100644 index 0000000000..d8f9cc591d --- /dev/null +++ b/packages/create-threenative/__tests__/deploy-nolink.spec.ts @@ -0,0 +1,46 @@ +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { describe, expect, it, vi } from "vitest"; +import { makeTempDir } from "../../../test-support/temp-dir.js"; +import { CliExit } from "../src/account.js"; +import { deploy } from "../src/deploy.js"; + +// A volume with no hard links (some network and FAT mounts): `link` fails with ENOTSUP. +vi.mock("node:fs/promises", async (original) => ({ + ...(await original()), + link: async () => { + throw Object.assign(new Error("operation not supported"), { code: "ENOTSUP" }); + }, +})); + +describe("threenative deploy on a volume with no hard links", () => { + it("still claims one deploy key for two first deploys started together", async () => { + const cwd = await makeTempDir("tn-deploy-nolink-"); + await writeFile( + path.join(cwd, "package.json"), + JSON.stringify({ name: "game", scripts: { "build:web": "vite build" } }), + ); + const options = { + cwd, + out: () => {}, + runBuild: async (root: string) => { + await mkdir(path.join(root, "dist"), { recursive: true }); + await writeFile(path.join(root, "dist", "index.html"), "

hi

"); + }, + // Nothing listens here: each deploy claims its key, then fails to upload with exit 5. + studio: "http://127.0.0.1:9", + token: "tok-1", + }; + + const results = await Promise.allSettled([deploy(options), deploy(options)]); + + for (const result of results) { + expect(result.status).toBe("rejected"); + const reason = (result as PromiseRejectedResult).reason as unknown; + expect(reason).toBeInstanceOf(CliExit); + expect((reason as CliExit).code).toBe(5); + } + const share = JSON.parse(await readFile(path.join(cwd, ".threenative", "share.json"), "utf8")); + expect(share.deployKey).toMatch(/^[\da-f-]{36}$/u); + }); +}); diff --git a/packages/create-threenative/__tests__/login.spec.ts b/packages/create-threenative/__tests__/login.spec.ts index df24042c9e..30b7cf4566 100644 --- a/packages/create-threenative/__tests__/login.spec.ts +++ b/packages/create-threenative/__tests__/login.spec.ts @@ -163,7 +163,23 @@ describe("threenative login and logout", () => { ); expect(failure.code).toBe(4); - expect(JSON.parse(await readFile(authFilePath(), "utf8"))).toEqual({ token: "tok-1" }); + expect(JSON.parse(await readFile(authFilePath(), "utf8"))).toEqual({ + site: site.origin, + token: "tok-1", + }); + await site.close(); + }); + + it("exits 4 when the token poll answers an empty 503", async () => { + const site = await fakeSite((request) => + request.url === "/api/store/device" ? deviceStart("ABCD-EFGH") : { status: 503 }, + ); + + const failure = await failureOf( + login({ open: false, out: () => {}, site: site.origin, sleep: async () => {} }), + ); + + expect(failure.code).toBe(4); await site.close(); }); @@ -270,6 +286,37 @@ describe("threenative login and logout", () => { await retry.close(); }); + it("revokes a token on the site that issued it, whatever THREENATIVE_SITE says now", async () => { + const issuer = await fakeSite(() => ({ body: { ok: true }, status: 200 })); + const other = await fakeSite(() => ({ body: { ok: true }, status: 401 })); + const file = authFilePath(); + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, JSON.stringify({ site: issuer.origin, token: "tok-prod" })); + + await logout({ out: () => {}, site: other.origin }); + + expect(issuer.requests.map((request) => request.authorization)).toEqual(["Bearer tok-prod"]); + expect(other.requests).toEqual([]); + await issuer.close(); + await other.close(); + }); + + it.skipIf(process.getuid?.() === 0)("keeps a token file it cannot read", async () => { + const file = authFilePath(); + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, JSON.stringify({ token: "tok-locked" }), { mode: 0o000 }); + const site = await fakeSite(() => ({ body: { ok: true }, status: 200 })); + + const failure = await failureOf(logout({ out: () => {}, site: site.origin })); + + expect(failure.code).toBe(4); + expect(failure.message).toContain("The token is kept, so run threenative logout again."); + expect(site.requests).toEqual([]); + const left = (await readdir(path.dirname(file))).filter((name) => name.endsWith(".logout")); + expect(left).toHaveLength(1); + await site.close(); + }); + it("revokes a token an interrupted logout left behind", async () => { const file = authFilePath(); await mkdir(path.dirname(file), { recursive: true }); diff --git a/packages/create-threenative/src/account.ts b/packages/create-threenative/src/account.ts index e856dca8ea..0f1210df79 100644 --- a/packages/create-threenative/src/account.ts +++ b/packages/create-threenative/src/account.ts @@ -39,6 +39,8 @@ export function authFilePath(env = process.env): string { export interface IAuthFile { email?: string; + /** The site that issued the token: logout revokes it there, whatever `THREENATIVE_SITE` says now. */ + site?: string; token?: string; } @@ -167,8 +169,8 @@ export async function login(options: ILoginOptions = {}): Promise { const start = await request(origin, "/api/store/device", jsonPost({})); if (start.status !== 201) throw new CliExit(4, serverMessage(start.body, `Sign in failed (${start.status}).`)); - const deviceCode = (start.body as { deviceCode?: unknown }).deviceCode; - const userCode = (start.body as { userCode?: unknown }).userCode; + const deviceCode = (start.body as { deviceCode?: unknown } | null | undefined)?.deviceCode; + const userCode = (start.body as { userCode?: unknown } | null | undefined)?.userCode; if (typeof deviceCode !== "string" || deviceCode === "") throw new CliExit(4, "The sign-in server sent no device code."); const link = `${origin}/account/device/?code=${encodeURIComponent(typeof userCode === "string" ? userCode : "")}`; @@ -184,7 +186,7 @@ export async function login(options: ILoginOptions = {}): Promise { if (Date.now() >= expiresAt) throw new CliExit(3, "The code expired. Run threenative login again."); const reply = await request(origin, "/api/store/device/token", jsonPost({ deviceCode })); - const status = (reply.body as { status?: unknown }).status; + const status = (reply.body as { status?: unknown } | null | undefined)?.status; if (reply.status >= 400 && reply.status < 500) throw new CliExit( 3, @@ -195,7 +197,7 @@ export async function login(options: ILoginOptions = {}): Promise { const nextInterval = numberField(reply.body, "interval"); if (nextInterval !== undefined && nextInterval > 0) interval = nextInterval; if (status !== "approved") continue; - const token = (reply.body as { token?: unknown }).token; + const token = (reply.body as { token?: unknown } | null | undefined)?.token; if (typeof token !== "string" || token === "") throw new CliExit(4, "The sign-in server approved without a token."); return token; @@ -217,12 +219,14 @@ async function saveSignIn(origin: string, token: string): Promise { headers: { authorization: `Bearer ${token}` }, }); } catch (error) { - await writeAuthFile({ token }); + await writeAuthFile({ site: origin, token }); throw error; } const email = (who.body as { email?: unknown } | null | undefined)?.email; const address = typeof email === "string" ? email : ""; - await writeAuthFile(address === "" ? { token } : { email: address, token }); + await writeAuthFile( + address === "" ? { site: origin, token } : { email: address, site: origin, token }, + ); if (who.status < 200 || who.status >= 300) throw new CliExit(4, serverMessage(who.body, `Could not read your account (${who.status}).`)); return address; @@ -244,15 +248,23 @@ export async function logout(options: ILogoutOptions = {}): Promise { const out = options.out ?? ((line: string) => process.stdout.write(`${line}\n`)); const env = process.env; const claims = await claimTokenFiles(authFilePath(env)); - const origin = siteOrigin(options.site); let revoked = false; let failure: CliExit | undefined; for (const claimed of claims) { - const token = (await readAuthFile(env, claimed))?.token; + const auth = await readClaim(claimed); + if (auth instanceof CliExit) { + failure = auth; + continue; + } + const token = auth?.token; if (typeof token !== "string" || token === "") { await rm(claimed, { force: true }); continue; } + // Revoked where it was issued: a token from one site sent to another would only earn a 401 there, + // which reads as "already dead" and would drop a token still live on its own site. + const origin = + typeof auth?.site === "string" && auth.site !== "" ? auth.site : siteOrigin(options.site); const answer = await revokeToken(origin, token); if (answer === undefined) { await rm(claimed, { force: true }); @@ -263,6 +275,27 @@ export async function logout(options: ILogoutOptions = {}): Promise { out(revoked ? "Signed out." : "Not signed in."); } +/** A claimed token file's contents. A file that cannot be read is kept, so a live token is never + * deleted unrevoked; one that is not JSON holds no token and is `undefined`, like no file at all. */ +async function readClaim(claimed: string): Promise { + let text: string; + try { + text = await readFile(claimed, "utf8"); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code ?? "unknown error"; + return new CliExit( + 4, + `Could not read ${claimed} (${code}). The token is kept, so run threenative logout again.`, + ); + } + try { + const parsed: unknown = JSON.parse(text); + return parsed !== null && typeof parsed === "object" ? (parsed as IAuthFile) : undefined; + } catch { + return undefined; + } +} + /** Claims auth.json and every token file an earlier logout left, each with one rename to a name of * this run's own: two logouts never revoke from, or delete, one file. */ async function claimTokenFiles(file: string): Promise { diff --git a/packages/create-threenative/src/deploy.ts b/packages/create-threenative/src/deploy.ts index ec8118d3cc..c59be3ef73 100644 --- a/packages/create-threenative/src/deploy.ts +++ b/packages/create-threenative/src/deploy.ts @@ -119,16 +119,30 @@ async function claimDeployKey(file: string): Promise { await link(tmp, file); return mine; } catch (error) { - if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; - const theirs = (await readJson(file))?.deployKey; - if (typeof theirs !== "string" || theirs === "") - throw new CliExit(4, `${file} exists but holds no deploy key; fix or delete it.`); - return theirs; + if ((error as NodeJS.ErrnoException).code === "EEXIST") return await theirKey(file); + // ponytail: a volume with no hard links (some network and FAT mounts) takes an exclusive create + // instead. Still one key per checkout; a deploy started in the same instant may read the file + // before its few bytes land and stop with exit 4. A lock file if that ever bites. + try { + await writeFile(file, `${JSON.stringify({ deployKey: mine }, null, 2)}\n`, { flag: "wx" }); + return mine; + } catch (fallback) { + if ((fallback as NodeJS.ErrnoException).code !== "EEXIST") throw fallback; + return await theirKey(file); + } } finally { await rm(tmp, { force: true }); } } +/** The key another first deploy from this checkout already claimed. */ +async function theirKey(file: string): Promise { + const theirs = (await readJson(file))?.deployKey; + if (typeof theirs !== "string" || theirs === "") + throw new CliExit(4, `${file} exists but holds no deploy key; fix or delete it.`); + return theirs; +} + export interface IDeployOptions { cwd?: string; out?: (line: string) => void; From 27af814e55fe0a4801a900f7e7f40abbde6ccee2 Mon Sep 17 00:00:00 2001 From: Joao Paulo Furtado Date: Sat, 21 Nov 2026 21:41:35 -0700 Subject: [PATCH 17/20] fix(create-threenative): a half-made share.json is waited for or removed, and logout claims auth.json in a directory it cannot list (PRD-904 Sol review 12) --- .../__tests__/deploy.spec.ts | 21 ++++++++++++++++ .../__tests__/login.spec.ts | 24 +++++++++++++++++++ packages/create-threenative/src/account.ts | 6 +++-- packages/create-threenative/src/deploy.ts | 19 +++++++++------ 4 files changed, 61 insertions(+), 9 deletions(-) diff --git a/packages/create-threenative/__tests__/deploy.spec.ts b/packages/create-threenative/__tests__/deploy.spec.ts index bc1fd3a543..4ceb35df04 100644 --- a/packages/create-threenative/__tests__/deploy.spec.ts +++ b/packages/create-threenative/__tests__/deploy.spec.ts @@ -214,6 +214,27 @@ describe("threenative deploy", () => { await site.close(); }); + it("waits for a share.json another first deploy has created but not yet written", async () => { + const cwd = await projectDir({ "build:web": "vite build" }); + const site = await fakeStudio(() => ({ + body: { projectId: "p1", shareUrl: "https://x-share.example/" }, + status: 200, + })); + const file = path.join(cwd, ".threenative", "share.json"); + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, ""); + const theirs = "11111111-2222-4333-8444-555555555555"; + const late = new Promise((done) => setTimeout(done, 100)).then(() => + writeFile(file, JSON.stringify({ deployKey: theirs })), + ); + + await deploy({ cwd, out: () => {}, runBuild: writeBuild, studio: site.origin, token: "tok-1" }); + await late; + + expect(queryOf(site.requests[0]?.url).get("key")).toBe(theirs); + await site.close(); + }); + it("retries a first deploy whose reply was lost with the same key, so it lands on one game", async () => { const cwd = await projectDir({ "build:web": "vite build" }); let uploads = 0; diff --git a/packages/create-threenative/__tests__/login.spec.ts b/packages/create-threenative/__tests__/login.spec.ts index 30b7cf4566..531710ed04 100644 --- a/packages/create-threenative/__tests__/login.spec.ts +++ b/packages/create-threenative/__tests__/login.spec.ts @@ -317,6 +317,30 @@ describe("threenative login and logout", () => { await site.close(); }); + it.skipIf(process.getuid?.() === 0)( + "revokes auth.json in a directory it cannot list", + async () => { + const file = authFilePath(); + const dir = path.dirname(file); + await mkdir(dir, { recursive: true }); + await writeFile(file, JSON.stringify({ token: "tok-hidden" })); + await chmod(dir, 0o300); + const site = await fakeSite(() => ({ body: { ok: true }, status: 200 })); + const lines: string[] = []; + + try { + await logout({ out: (line) => lines.push(line), site: site.origin }); + } finally { + await chmod(dir, 0o700); + } + + expect(site.requests.map((request) => request.authorization)).toEqual(["Bearer tok-hidden"]); + expect(lines).toEqual(["Signed out."]); + expect(await readdir(dir)).toEqual([]); + await site.close(); + }, + ); + it("revokes a token an interrupted logout left behind", async () => { const file = authFilePath(); await mkdir(path.dirname(file), { recursive: true }); diff --git a/packages/create-threenative/src/account.ts b/packages/create-threenative/src/account.ts index 0f1210df79..a7847f6b60 100644 --- a/packages/create-threenative/src/account.ts +++ b/packages/create-threenative/src/account.ts @@ -301,11 +301,13 @@ async function readClaim(claimed: string): Promise { const dir = path.dirname(file); const base = path.basename(file); - let names: string[]; + // A directory this user cannot list can still hold an auth.json it can rename by name, so a failed + // listing only skips the leftovers; it never reads as "not signed in". + let names: string[] = []; try { names = await readdir(dir); } catch { - return []; + // No directory: the rename below finds no auth.json either. } const left = names.filter((name) => name.startsWith(`${base}.`) && name.endsWith(".logout")); const claims: string[] = []; diff --git a/packages/create-threenative/src/deploy.ts b/packages/create-threenative/src/deploy.ts index c59be3ef73..25b11730b1 100644 --- a/packages/create-threenative/src/deploy.ts +++ b/packages/create-threenative/src/deploy.ts @@ -127,20 +127,25 @@ async function claimDeployKey(file: string): Promise { await writeFile(file, `${JSON.stringify({ deployKey: mine }, null, 2)}\n`, { flag: "wx" }); return mine; } catch (fallback) { - if ((fallback as NodeJS.ErrnoException).code !== "EEXIST") throw fallback; - return await theirKey(file); + if ((fallback as NodeJS.ErrnoException).code === "EEXIST") return await theirKey(file); + // Created but not written: an empty share.json would stop every later deploy, so it goes. + await rm(file, { force: true }); + throw fallback; } } finally { await rm(tmp, { force: true }); } } -/** The key another first deploy from this checkout already claimed. */ +/** The key another first deploy from this checkout already claimed. Without hard links its file can + * exist a moment before its bytes do, so an empty read is retried for about a second. */ async function theirKey(file: string): Promise { - const theirs = (await readJson(file))?.deployKey; - if (typeof theirs !== "string" || theirs === "") - throw new CliExit(4, `${file} exists but holds no deploy key; fix or delete it.`); - return theirs; + for (let attempt = 0; attempt < 40; attempt += 1) { + const theirs = (await readJson(file))?.deployKey; + if (typeof theirs === "string" && theirs !== "") return theirs; + await new Promise((done) => setTimeout(done, 25)); + } + throw new CliExit(4, `${file} exists but holds no deploy key; fix or delete it.`); } export interface IDeployOptions { From 118367b53bc5fa1db9e587d2bfffe8a719994e59 Mon Sep 17 00:00:00 2001 From: Joao Paulo Furtado Date: Sat, 21 Nov 2026 21:45:14 -0700 Subject: [PATCH 18/20] fix(create-threenative): logout exits 4 when it cannot list the config directory and has nothing to claim, instead of saying signed out (PRD-904 Sol review 13) --- .../__tests__/login.spec.ts | 25 +++++++++++++++++++ packages/create-threenative/src/account.ts | 12 ++++++++- 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/packages/create-threenative/__tests__/login.spec.ts b/packages/create-threenative/__tests__/login.spec.ts index 531710ed04..524518f4f0 100644 --- a/packages/create-threenative/__tests__/login.spec.ts +++ b/packages/create-threenative/__tests__/login.spec.ts @@ -341,6 +341,31 @@ describe("threenative login and logout", () => { }, ); + it.skipIf(process.getuid?.() === 0)( + "refuses to say signed out when it cannot see a kept token", + async () => { + const file = authFilePath(); + const dir = path.dirname(file); + await mkdir(dir, { recursive: true }); + // An earlier logout kept this token after a refused revoke; the directory then lost read access. + await writeFile(`${file}.kept.logout`, JSON.stringify({ token: "tok-kept" })); + await chmod(dir, 0o300); + const site = await fakeSite(() => ({ body: { ok: true }, status: 200 })); + + let failure: CliExit; + try { + failure = await failureOf(logout({ out: () => {}, site: site.origin })); + } finally { + await chmod(dir, 0o700); + } + + expect(failure.code).toBe(4); + expect(failure.message).toContain("Restore read access"); + expect(site.requests).toEqual([]); + await site.close(); + }, + ); + it("revokes a token an interrupted logout left behind", async () => { const file = authFilePath(); await mkdir(path.dirname(file), { recursive: true }); diff --git a/packages/create-threenative/src/account.ts b/packages/create-threenative/src/account.ts index a7847f6b60..bc5e60cb51 100644 --- a/packages/create-threenative/src/account.ts +++ b/packages/create-threenative/src/account.ts @@ -304,10 +304,13 @@ async function claimTokenFiles(file: string): Promise { // A directory this user cannot list can still hold an auth.json it can rename by name, so a failed // listing only skips the leftovers; it never reads as "not signed in". let names: string[] = []; + let unlisted: string | undefined; try { names = await readdir(dir); - } catch { + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; // No directory: the rename below finds no auth.json either. + if (code !== "ENOENT") unlisted = code ?? "unknown error"; } const left = names.filter((name) => name.startsWith(`${base}.`) && name.endsWith(".logout")); const claims: string[] = []; @@ -321,6 +324,13 @@ async function claimTokenFiles(file: string): Promise { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; } } + // Nothing to claim by name, and the leftovers an earlier logout kept cannot be seen: saying "not + // signed in" here could leave a live token behind. + if (claims.length === 0 && unlisted !== undefined) + throw new CliExit( + 4, + `Could not list ${dir} (${unlisted}), so a token an earlier logout kept may still be there. Restore read access to it, then run threenative logout again.`, + ); return claims; } From 42995bc7634b92a82fc013e43a61d25535eaa07e Mon Sep 17 00:00:00 2001 From: Joao Paulo Furtado Date: Sat, 21 Nov 2026 21:48:58 -0700 Subject: [PATCH 19/20] docs(prd): PRD-904 records the Sol 6.2 approval and the final local end-to-end --- ...904-threenative-login-and-deploy-publish-like-studio-share.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md b/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md index c9c3ebb658..f766a27af7 100644 --- a/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md +++ b/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md @@ -92,6 +92,7 @@ Fill the dispatcher and route `file:line` values when each phase lands. - 2026-11-21 (João): use the `threenative` CLI as it is, with no `tn` alias. The "two commands, ever" rule is removed (`f9d168b00`). - 2026-11-21 (João): deploy is the same as Studio's Publish (the share link), not the store push. +- 2026-11-21 (Sol 6.2 high, review 14): APPROVE across engine, site and Studio, after 13 rounds of fixes. The same commit (`118367b53`) passed the 25-check local end-to-end (login, two deploys on one link, served index.html and JS, lost-reply key retry, one game in Studio D1, archive parity, logout revoke, deploy after logout exits 3): 25/25. Engine CLI 31/31, site worker 231/231, Studio worker 413/413. - 2026-11-21 (Sol review 10): logout claims each token file with one rename before it revokes. A token the site did not revoke stays in its claimed `auth.json..logout` file, not in `auth.json`, and every later logout revokes those leftovers too. So a failed or interrupted logout leaves the machine signed out but keeps the live token for the retry, and a login in another terminal is never lost or revived. - 2026-11-21 (João): login UX: open a link, sign in with the threenative.com account, click Authorize, and the CLI detects it. The code is also accepted typed. The existing site device flow does exactly this. - 2026-11-21 (agent, after a Gemini 4 Neon review): the store push is not the deploy path. A new account's release is held for review (`worker/games.ts:631,649`), the build farm runs scans and an AI review, and a listing needs 1 to 5 screenshots. The share link is live in seconds. From adee7eeed3c253aa100d211e7f6c49ef46ae6ef8 Mon Sep 17 00:00:00 2001 From: Joao Paulo Furtado Date: Sat, 21 Nov 2026 22:11:25 -0700 Subject: [PATCH 20/20] docs(create-threenative): the CLI surface paragraph fits the 100-line instruction cap (PRD-904 merge-queue red) --- packages/create-threenative/AGENTS.md | 15 +++++---------- packages/create-threenative/CLAUDE.md | 15 +++++---------- 2 files changed, 10 insertions(+), 20 deletions(-) diff --git a/packages/create-threenative/AGENTS.md b/packages/create-threenative/AGENTS.md index d290b913c0..72088c084b 100644 --- a/packages/create-threenative/AGENTS.md +++ b/packages/create-threenative/AGENTS.md @@ -79,16 +79,11 @@ builds locally can still fail there — check it before claiming the scaffold wo ## CLI surface -The `threenative` commands are `build` (`--target web|desktop|android|ios`), `doctor` (`--text` -prints the person-readable report; it checks rather than builds, borrowed whole from `npm doctor` -and `flutter doctor`), `login` (device-code sign-in: prints a link and a code, polls until the -browser authorizes, and saves the granted token owner-only; `--no-browser` for a machine whose -browser is elsewhere), `logout` (revokes that token on the site and deletes the file), and -`deploy` (runs the package's `build:web`, uploads `dist/` to Studio, and prints the share link on -its own last stdout line, reusing `.threenative/share.json`'s project id, or its first-deploy key, -so the next deploy keeps the same link). `__tests__/cli.spec.ts` derives the advertised list from the real executable and -rejects anything else, so this document cannot outgrow the binary. A new command borrows its name -from an established CLI (`npm`, `wrangler`, `vercel`), never a new word. +The `threenative` commands are `build` (`--target web|desktop|android|ios`), `doctor` (`--text` for +the person-readable report; borrowed from `npm doctor`), `login` (device-code sign-in, token saved +owner-only, `--no-browser`), `logout` (revokes it on the site), and `deploy` (`build:web`, uploads +`dist/` to Studio, prints the share link last; `.threenative/share.json` keeps the link). `__tests__/cli.spec.ts` +derives the list from the real executable. A new command borrows an established CLI's name, never a new word. The scaffolder itself takes a target directory plus `inspect [--json]`; its flags stay boring: `--template`, `--no-install`, and the `--*-package` overrides CI uses to test against local tarballs. `pnpm dev` inside a generated project is a package script, never a CLI command. diff --git a/packages/create-threenative/CLAUDE.md b/packages/create-threenative/CLAUDE.md index 3d11ba1b41..d9493e1f08 100644 --- a/packages/create-threenative/CLAUDE.md +++ b/packages/create-threenative/CLAUDE.md @@ -81,16 +81,11 @@ builds locally can still fail there — check it before claiming the scaffold wo ## CLI surface -The `threenative` commands are `build` (`--target web|desktop|android|ios`), `doctor` (`--text` -prints the person-readable report; it checks rather than builds, borrowed whole from `npm doctor` -and `flutter doctor`), `login` (device-code sign-in: prints a link and a code, polls until the -browser authorizes, and saves the granted token owner-only; `--no-browser` for a machine whose -browser is elsewhere), `logout` (revokes that token on the site and deletes the file), and -`deploy` (runs the package's `build:web`, uploads `dist/` to Studio, and prints the share link on -its own last stdout line, reusing `.threenative/share.json`'s project id, or its first-deploy key, -so the next deploy keeps the same link). `__tests__/cli.spec.ts` derives the advertised list from the real executable and -rejects anything else, so this document cannot outgrow the binary. A new command borrows its name -from an established CLI (`npm`, `wrangler`, `vercel`), never a new word. +The `threenative` commands are `build` (`--target web|desktop|android|ios`), `doctor` (`--text` for +the person-readable report; borrowed from `npm doctor`), `login` (device-code sign-in, token saved +owner-only, `--no-browser`), `logout` (revokes it on the site), and `deploy` (`build:web`, uploads +`dist/` to Studio, prints the share link last; `.threenative/share.json` keeps the link). `__tests__/cli.spec.ts` +derives the list from the real executable. A new command borrows an established CLI's name, never a new word. The scaffolder itself takes a target directory plus `inspect [--json]`; its flags stay boring: `--template`, `--no-install`, and the `--*-package` overrides CI uses to test against local tarballs. `pnpm dev` inside a generated project is a package script, never a CLI command.