diff --git a/.changeset/login-read-only.md b/.changeset/login-read-only.md new file mode 100644 index 0000000..5978fdc --- /dev/null +++ b/.changeset/login-read-only.md @@ -0,0 +1,5 @@ +--- +"@freeticket/cli": minor +--- + +`ft login --read-only`: pide una key de solo lectura (pre-marca "Solo lectura" en /device) y se niega a guardar una que pueda escribir. `ft whoami` muestra el scope. Requiere contrato 1.43.0. diff --git a/openapi.json b/openapi.json index e470bfb..284a34d 100644 --- a/openapi.json +++ b/openapi.json @@ -2,7 +2,7 @@ "openapi": "3.1.0", "info": { "title": "FreeTicket B2B API", - "version": "1.42.0", + "version": "1.43.0", "description": "FreeTicket B2B REST API for integrations, the `ft` CLI and the FreeTicket MCP server. Authentication is by API key (`Authorization: Bearer ` header or `x-api-key`); the active workspace is selected with the `X-Workspace-Id` header.\n\nScopes: each key is either `read` (GET/HEAD only) or `write` (additionally creates, edits, deletes, cancels, refunds and checks in). Self-service keys are issued as `read`. A `read` key calling a mutating method gets a 403. The machine-readable declaration lives at `/.well-known/oauth-protected-resource` (RFC 9728).\n\nGetting a key (self-serve, no sales contact): `ft login` runs the Device Authorization Grant (RFC 8628, `POST /auth/device/code` + `POST /auth/device/token`); the user approves the code at https://admin.appfreeticket.com/device and the CLI receives a key. New organizers can bootstrap headless with `POST /auth/signup` (verify-first, then `ft login`). With a key, `POST /api-keys` mints more (born `read` unless `write` is requested). There is no sandbox environment: test against a dedicated workspace with `read` keys.\n\n## Versioning and deprecation\n\n- **Path version.** The B2B API is versioned in the path (`/api/v1`). A breaking change ships under a new path (`/api/v2`); the previous version keeps running in parallel until its sunset date.\n- **Contract version.** `info.version` is the semantic version of this document. MINOR = additive (new endpoints, new optional fields, new enum values, new error codes; clients must ignore unknown fields). PATCH = documentation or fixes that do not change shapes. The public API (`/api/public`) is pre-1.0 and not versioned in the path: there, a MINOR bump may include a breaking change and PATCH never does.\n- **Deprecation signals.** A deprecated operation is marked `deprecated: true` in this document and its responses carry `Deprecation` (RFC 9745, e.g. `Deprecation: @1767225600`), `Sunset` (RFC 8594, an HTTP-date after which the operation may stop working) and `Link: ; rel=\"deprecation\"`.\n- **Timeline.** At least 6 months between the first `Deprecation` header and the `Sunset` date for `/api/v1`, and at least 90 days for `/api/public`. A path version is only retired after all its operations have sunset.\n- **Current status.** No operation is deprecated today.\n\n## Rate limits\n\n- **429 always carries `Retry-After`** (seconds). Wait at least that long before retrying the same request. The JSON error envelope comes with `error.retryable: true`; most rate-limited responses use `error.code: \"RATE_LIMITED\"`, and some return a more specific code (for example `TOO_MANY_REQUESTS` or `SEAT_BUDGET_EXHAUSTED`).\n- **RateLimit headers are sent where listed below.** Those endpoints answer every response, success or error, with the IETF RateLimit headers (draft-ietf-httpapi-ratelimit-headers): `RateLimit-Policy: \"\";q=;w=` and `RateLimit: \"\";r=;t=`. Other endpoints may answer 429 without them.\n- Counters are fixed windows kept per server instance: treat the numbers as pacing hints, not as a global account quota.\n\nEndpoints that send RateLimit headers today: `POST /auth/signup` (per client IP), `POST /customer/auth/request` and `POST /customer/auth/verify` (per client IP), and the buyer-session endpoints `GET /customer/orders/{id}`, `POST /customer/orders/{id}/payment`, `/payment/card`, `/payment/pse`, `/release`, `POST /customer/purchase-sessions` and `POST /customer/purchase-sessions/{id}/release`." }, "servers": [ @@ -23997,6 +23997,14 @@ "items": { "$ref": "#/components/schemas/WorkspaceAccess" } + }, + "scope": { + "type": "string", + "enum": [ + "read", + "write" + ], + "description": "Scope of the API key in use. `read` = only GET/HEAD; any mutating method answers 403." } }, "required": [ @@ -24005,7 +24013,8 @@ "email", "role", "activeWorkspaceId", - "workspaces" + "workspaces", + "scope" ], "additionalProperties": false }, diff --git a/src/commands/auth.test.ts b/src/commands/auth.test.ts new file mode 100644 index 0000000..afcc727 --- /dev/null +++ b/src/commands/auth.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from "vitest"; +import { readOnlyRefusal, withQuery } from "./auth"; + +describe("ft login --read-only", () => { + it("adds scope=read and keeps the device code", () => { + const url = new URL( + withQuery("https://admin.x/device?code=ABCD-EFGH", "scope", "read"), + ); + expect(url.searchParams.get("code")).toBe("ABCD-EFGH"); + expect(url.searchParams.get("scope")).toBe("read"); + }); + + it.each([ + ["write", true], + [undefined, true], // server older than contract 1.43.0 + ["read", false], + ])("scope %s → refused: %s", (scope, refused) => { + expect(readOnlyRefusal(true, scope) !== null).toBe(refused); + }); + + it("never refuses without --read-only", () => { + expect(readOnlyRefusal(undefined, "write")).toBeNull(); + }); +}); diff --git a/src/commands/auth.ts b/src/commands/auth.ts index b5f3e54..e955456 100644 --- a/src/commands/auth.ts +++ b/src/commands/auth.ts @@ -50,6 +50,10 @@ export function registerAuth(program: Command): void { "--workspace ", "pin this login to one workspace (default: every workspace the account reaches)", ) + .option( + "--read-only", + "ask for a read-only key (GET only; any write answers 403) and refuse to save one that is not. Not a sandbox: the real gate is the person approving in the browser", + ) .option("--json", "raw JSON output (confirmation goes to stderr)") .action(async (opts) => { const apiUrl: string = @@ -59,7 +63,8 @@ export function registerAuth(program: Command): void { DEFAULT_API_URL; // Browser device flow is the default; --key stays for headless/CI. - const apiKey: string = opts.key ?? (await deviceLogin(apiUrl)); + const apiKey: string = + opts.key ?? (await deviceLogin(apiUrl, opts.readOnly)); const workspaceId: string | undefined = opts.workspace; // Verify the credential against /me before storing anything: a bad key @@ -71,6 +76,8 @@ export function registerAuth(program: Command): void { workspaceId, }); const me = unwrap(await getMe({})).data; + const refusal = readOnlyRefusal(opts.readOnly, me.scope); + if (refusal) fail(refusal); // Adds this one account, or replaces the stored one of the same user; // every other login stays. const { name, replaces } = loginTarget( @@ -90,7 +97,8 @@ export function registerAuth(program: Command): void { ); // stderr so `ft login --json | jq` stays parseable. console.error( - `${chalk.green("✓")} Account ${chalk.bold(name)} saved in ${chalk.dim(CONFIG_PATH)}`, + `${chalk.green("✓")} Account ${chalk.bold(name)} saved in ${chalk.dim(CONFIG_PATH)}` + + (me.scope === "read" ? chalk.yellow(" (read-only)") : ""), ); const { activeAccount, accounts } = readConfig(); if (activeAccount && activeAccount !== name) { @@ -192,6 +200,7 @@ export function registerAuth(program: Command): void { account: m.account, email: m.email, name: m.name, + scope: m.scope, workspaces: m.workspaces.map((w) => w.slug).join(", "), })), ); @@ -265,6 +274,27 @@ export function registerAuth(program: Command): void { }); } +export function withQuery(url: string, key: string, value: string): string { + const u = new URL(url); + u.searchParams.set(key, value); + return u.toString(); +} + +/** + * `--read-only` refusal: the box is pre-ticked but the approver can untick it, + * `--key` can be a write key, and a server older than contract 1.43.0 sends no + * `scope`. All three fail closed: never hand an agent a write key it asked not + * to have. ponytail: the refused key stays live in the backend (nobody holds + * its secret); revoke it here if orphan "FreeTicket CLI" keys pile up. + */ +export function readOnlyRefusal( + readOnly: boolean | undefined, + scope: string | undefined, +): string | null { + if (!readOnly || scope === "read") return null; + return "That key can write (the read-only box was unticked, or --key is a write key). Nothing was saved."; +} + /** First characters of a credential: enough to tell two apart, not to use one. */ export function mask(secret: string): string { return `${secret.slice(0, 12)}…`; @@ -300,7 +330,7 @@ function openBrowser(url: string): void { * the account's default one, which is what /api/v1 does when X-Workspace-Id is * absent. `ft workspace use ` still pins on purpose. */ -async function deviceLogin(baseUrl: string): Promise { +async function deviceLogin(baseUrl: string, readOnly = false): Promise { const apiUrl = baseUrl.replace(/\/$/, ""); // Anonymous client: the device endpoints carry no auth header. client.setConfig({ baseUrl: `${apiUrl}/api/v1` }); @@ -312,7 +342,12 @@ async function deviceLogin(baseUrl: string): Promise { `\n ${chalk.bold(start.user_code)}\n` + `\n${chalk.dim("Opening your browser… (Ctrl+C to cancel)")}\n`, ); - openBrowser(start.verification_uri_complete); + // Pre-ticks "Solo lectura" on /device; the login re-checks the key's scope. + openBrowser( + readOnly + ? withQuery(start.verification_uri_complete, "scope", "read") + : start.verification_uri_complete, + ); const deadline = Date.now() + start.expires_in * 1000; let interval = start.interval;