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..f766a27af7 --- /dev/null +++ b/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md @@ -0,0 +1,124 @@ +--- +prd_contract: v1 +--- + +# PRD-904 — `threenative login` and `threenative deploy`: publish from the terminal the way Studio's Publish button does + +**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 +**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, 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` 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/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. + +## 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 + +- [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. +- [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. 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. + +## 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 (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. +- 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. 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 + +#### 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). +- [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). +- [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`. +- [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). +- [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. diff --git a/packages/create-threenative/AGENTS.md b/packages/create-threenative/AGENTS.md index 7f55de3d06..72088c084b 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` -(`--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 +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 1463a2e77b..d9493e1f08 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` -(`--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 +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/__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-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__/deploy.spec.ts b/packages/create-threenative/__tests__/deploy.spec.ts new file mode 100644 index 0000000000..4ceb35df04 --- /dev/null +++ b/packages/create-threenative/__tests__/deploy.spec.ts @@ -0,0 +1,318 @@ +import { once } from "node:events"; +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"; +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, +): 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 = await 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

"); +} + +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, + (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("keys the first deploy and keeps the same link on the next deploy", async () => { + const cwd = await projectDir({ "build:web": "vite build" }); + // 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, + 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", + }); + 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/"); + 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" }); + // 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(); + }); + + 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("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; + 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(); + }); + + 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..524518f4f0 --- /dev/null +++ b/packages/create-threenative/__tests__/login.spec.ts @@ -0,0 +1,421 @@ +import { once } from "node:events"; +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"; +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, + }; +} + +/** 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; + + 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; + 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") { + polls += 1; + return polls < 3 + ? { body: { status: "pending" }, status: 200 } + : { body: { status: "approved", token: "tok-1" }, 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[] = []; + + 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(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"); + 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("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({ + 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(); + }); + + 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" + ? 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("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 }); + 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). The token is kept, so run threenative logout again.", + ); + 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 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.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.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 }); + // 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 () => { + 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(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 () => { + 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..bc5e60cb51 --- /dev/null +++ b/packages/create-threenative/src/account.ts @@ -0,0 +1,351 @@ +/** `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 { randomUUID } from "node:crypto"; +import { mkdir, readFile, readdir, rename, 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; + /** The site that issued the token: logout revokes it there, whatever `THREENATIVE_SITE` says now. */ + site?: string; + token?: string; +} + +async function readAuthFile( + env: NodeJS.ProcessEnv, + file = authFilePath(env), +): Promise { + try { + 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. + 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 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}`); + } + 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 }); + // 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. 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 { + 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 } | 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 : "")}`; + 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 } | null | undefined)?.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 } | null | undefined)?.token; + if (typeof token !== "string" || token === "") + throw new CliExit(4, "The sign-in server approved without a token."); + return token; + } + }; + + const token = await pollForToken(); + 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({ site: origin, token }); + throw error; + } + const email = (who.body as { email?: unknown } | null | undefined)?.email; + const address = typeof email === "string" ? email : ""; + 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; +} + +export interface ILogoutOptions { + out?: (line: string) => void; + site?: string; +} + +/** Revoke the saved token and delete the file. `THREENATIVE_TOKEN` is not touched. + * + * 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 claims = await claimTokenFiles(authFilePath(env)); + let revoked = false; + let failure: CliExit | undefined; + for (const claimed of claims) { + 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 }); + revoked = true; + } else failure = answer; + } + if (failure !== undefined) throw failure; + 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 { + const dir = path.dirname(file); + const base = path.basename(file); + // 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 (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[] = []; + 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; + } + } + // 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; +} + +/** `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 { + 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) { + if (!(error instanceof CliExit)) throw error; + return new CliExit(error.code, `${error.message} ${kept}`); + } +} diff --git a/packages/create-threenative/src/commands.ts b/packages/create-threenative/src/commands.ts index 5eecaa8bae..43651854e1 100644 --- a/packages/create-threenative/src/commands.ts +++ b/packages/create-threenative/src/commands.ts @@ -1,13 +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, 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. */ -export type PublicCommand = "build" | "doctor"; + * the documentation checks cannot disagree. Adding a command means adding it here and teaching + * `threenative.ts` to run it. */ +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..25b11730b1 --- /dev/null +++ b/packages/create-threenative/src/deploy.ts @@ -0,0 +1,241 @@ +/** `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 { link, mkdir, readFile, readdir, rename, rm, 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 { + /** 36-char UUID sent as `key` on the first deploy, so a lost reply retries onto one game. */ + deployKey?: string; + projectId?: string; +} + +async function readJson(file: string): Promise { + try { + return JSON.parse(await readFile(file, "utf8")) as T; + } catch { + return undefined; + } +} + +/** 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 }); + 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; + } +} + +/** 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") 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") 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. 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 { + 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 { + 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 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 }); + // 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 = await claimDeployKey(sharePath); + 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. + 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 savedProject = 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."); + const saved: IShareFile = {}; + if (savedProject !== "") saved.projectId = savedProject; + if (deployKey !== undefined) saved.deployKey = deployKey; + if (previous?.projectId !== saved.projectId || previous?.deployKey !== saved.deployKey) + await writeShareFile(sharePath, saved); + // The link alone, last: an agent parses this line, not the prose above it. + out(shareUrl); + return { projectId: savedProject, shareUrl }; +} diff --git a/packages/create-threenative/src/threenative.ts b/packages/create-threenative/src/threenative.ts index b2c7c7f1b8..cebd2ecaaa 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,52 @@ 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 first. The token file is deleted", + " only once the site confirms the revocation, or says the token is already invalid.", + "Otherwise the file is kept and the command exits 4 (refused) or 5 (no network), so it can", + " be run again and still revoke the token.", + "With no saved token it prints 'Not signed in.' and does nothing.", + "THREENATIVE_SITE names another site origin.", + "Exits 0 signed out, 4 the server refused the revocation, 5 no network.", + ].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 and the first deploy's key, 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 +103,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 +180,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 +220,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; });