diff --git a/.changeset/cli-client-header.md b/.changeset/cli-client-header.md new file mode 100644 index 0000000..2c0ce19 --- /dev/null +++ b/.changeset/cli-client-header.md @@ -0,0 +1,7 @@ +--- +"@makespdf/cli": patch +--- + +Send `X-MakesPDF-Client: cli/` on every makesPDF API request — `md`, +`preview`, `render`, `validate`, and the device-flow login — so the API can +classify CLI traffic by client kind instead of guessing from the User-Agent. diff --git a/src/client-info.test.ts b/src/client-info.test.ts new file mode 100644 index 0000000..5bec22d --- /dev/null +++ b/src/client-info.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from "vitest"; +import pkg from "../package.json"; +import { + CLIENT_HEADER, + CLIENT_KIND, + CLIENT_NAME, + CLIENT_VERSION, + clientHeaders, +} from "./client-info.js"; + +describe("client identity", () => { + it("identifies as the plain `cli/` kind", () => { + expect(CLIENT_KIND).toBe("cli"); + expect(CLIENT_VERSION).toBe(pkg.version); + expect(CLIENT_NAME).toBe(`cli/${pkg.version}`); + }); + + it("carries the identity in the shared request headers", () => { + const headers = clientHeaders(); + expect(headers[CLIENT_HEADER]).toBe(CLIENT_NAME); + expect(headers["Content-Type"]).toBe("application/json"); + expect(headers["User-Agent"]).toBe("@makespdf/cli"); + }); +}); diff --git a/src/client-info.ts b/src/client-info.ts new file mode 100644 index 0000000..ce4423d --- /dev/null +++ b/src/client-info.ts @@ -0,0 +1,37 @@ +/** + * Identity of this CLI as a makesPDF API client. + * + * Every request the CLI sends to the makesPDF API carries + * `X-MakesPDF-Client: cli/` so the server can classify CLI + * traffic by client kind. Per operator decision 2f382669, official clients + * send plain `/` values and the server matches them exactly. + * + * This module is the single source of truth for that header: both + * `ApiClient` and the raw device-flow login requests spread + * `clientHeaders()`. + */ +import pkg from "../package.json"; + +/** Client kind, as recognised by the server's known-client list. */ +export const CLIENT_KIND = "cli"; + +/** Version of the CLI package, inlined from package.json at build time. */ +export const CLIENT_VERSION: string = pkg.version; + +/** Value sent in the `X-MakesPDF-Client` header, e.g. `cli/0.2.0`. */ +export const CLIENT_NAME = `${CLIENT_KIND}/${CLIENT_VERSION}`; + +/** Name of the header carrying the client identity. */ +export const CLIENT_HEADER = "X-MakesPDF-Client"; + +/** + * Headers common to every makesPDF API request from the CLI, before auth. + * Callers add `Authorization` or per-request headers on top. + */ +export function clientHeaders(): Record { + return { + "Content-Type": "application/json", + "User-Agent": "@makespdf/cli", + [CLIENT_HEADER]: CLIENT_NAME, + }; +} diff --git a/src/client.test.ts b/src/client.test.ts index 11bfc9c..e9c232e 100644 --- a/src/client.test.ts +++ b/src/client.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it, vi } from "vitest"; +import { CLIENT_HEADER, CLIENT_NAME } from "./client-info.js"; import { ApiClient, ApiError, NetworkError } from "./client.js"; function makeFetch(response: Partial): typeof fetch { @@ -27,6 +28,7 @@ describe("ApiClient", () => { expect(init.method).toBe("POST"); expect(init.headers.Authorization).toBe("Bearer secret"); expect(init.headers["Content-Type"]).toBe("application/json"); + expect(init.headers[CLIENT_HEADER]).toBe(CLIENT_NAME); expect(init.body).toBe(JSON.stringify({ markdown: "# hi" })); }); diff --git a/src/client.ts b/src/client.ts index 9bcd249..4ecc72c 100644 --- a/src/client.ts +++ b/src/client.ts @@ -2,7 +2,7 @@ * Thin fetch wrapper for the makesPDF HTTP API. * * Responsibilities: - * - Attach the Authorization header. + * - Attach the Authorization and client-identity headers. * - Turn non-2xx responses into typed `ApiError`s (exit-code 2). * - Turn network/DNS failures into `NetworkError`s (exit-code 3). * - Return the response body typed as either bytes or JSON. @@ -11,6 +11,8 @@ * the CLI is a thin pipe to the API. */ +import { clientHeaders } from "./client-info.js"; + export class ApiError extends Error { override readonly name = "ApiError"; constructor( @@ -78,9 +80,8 @@ export class ApiClient { const url = `${this.baseUrl}${path.startsWith("/") ? path : `/${path}`}`; const expect = opts.expect ?? "bytes"; const headers: Record = { - "Content-Type": "application/json", + ...clientHeaders(), Authorization: `Bearer ${this.apiKey}`, - "User-Agent": "@makespdf/cli", }; if (expect === "json") headers.Accept = "application/json"; diff --git a/src/commands/login.test.ts b/src/commands/login.test.ts new file mode 100644 index 0000000..29925fb --- /dev/null +++ b/src/commands/login.test.ts @@ -0,0 +1,78 @@ +import { runCommand } from "citty"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { CLIENT_HEADER, CLIENT_NAME } from "../client-info.js"; +import { loginCommand } from "./login.js"; + +/** + * The device-flow login talks to the API with raw `fetch` calls (it has no + * API key yet, so it cannot use ApiClient), which makes it the easiest place + * for the client-identity header to drift. This drives the command through + * citty the same way the binary does, against a stubbed fetch. + */ +describe("login command", () => { + let dir: string; + let configFile: string; + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "makespdf-login-test-")); + configFile = join(dir, "config.json"); + process.env.MAKESPDF_CONFIG = configFile; + }); + + afterEach(() => { + vi.unstubAllGlobals(); + delete process.env.MAKESPDF_CONFIG; + rmSync(dir, { recursive: true, force: true }); + }); + + it("sends the client header on every device-flow request", async () => { + const fetchMock = vi.fn( + async (input: string | URL | Request, _init?: RequestInit): Promise => { + const url = String(input); + if (url.endsWith("/api/v1/device/code")) { + return new Response( + JSON.stringify({ + device_code: "dev-1", + user_code: "ABCD-1234", + verification_uri: "http://test.local/device", + verification_uri_complete: "http://test.local/device?code=ABCD-1234", + expires_in: 60, + interval: 0, + }), + { status: 200, headers: { "Content-Type": "application/json" } }, + ); + } + return new Response( + JSON.stringify({ access_token: "tok-1", token_type: "bearer" }), + { status: 200, headers: { "Content-Type": "application/json" } }, + ); + }, + ); + vi.stubGlobal("fetch", fetchMock); + + await runCommand(loginCommand, { + rawArgs: ["--base-url", "http://test.local", "--no-browser"], + }); + + expect(fetchMock).toHaveBeenCalledTimes(2); + const urls = fetchMock.mock.calls.map(([input]) => String(input)); + expect(urls).toEqual([ + "http://test.local/api/v1/device/code", + "http://test.local/api/v1/device/token", + ]); + for (const [, init] of fetchMock.mock.calls) { + const headers = init?.headers as Record; + expect(headers[CLIENT_HEADER]).toBe(CLIENT_NAME); + expect(headers["Content-Type"]).toBe("application/json"); + } + + // Sanity: the flow completed and persisted the token. + expect(JSON.parse(readFileSync(configFile, "utf8"))).toMatchObject({ + apiKey: "tok-1", + baseUrl: "http://test.local", + }); + }); +}); diff --git a/src/commands/login.ts b/src/commands/login.ts index 3a8a57a..902db06 100644 --- a/src/commands/login.ts +++ b/src/commands/login.ts @@ -1,5 +1,6 @@ import { defineCommand } from "citty"; import { hostname } from "node:os"; +import { clientHeaders } from "../client-info.js"; import { resolveBaseUrl, loadConfig, saveConfig, configPath } from "../config.js"; import { EXIT, fail } from "../errors.js"; import { openBrowser } from "../open-browser.js"; @@ -56,7 +57,7 @@ export const loginCommand = defineCommand({ try { codeHttp = await fetch(`${baseUrl}/api/v1/device/code`, { method: "POST", - headers: { "Content-Type": "application/json", "User-Agent": "@makespdf/cli" }, + headers: clientHeaders(), body: JSON.stringify({ client_name: hostname() }), }); } catch (err) { @@ -112,7 +113,7 @@ export const loginCommand = defineCommand({ try { pollRes = await fetch(`${baseUrl}/api/v1/device/token`, { method: "POST", - headers: { "Content-Type": "application/json", "User-Agent": "@makespdf/cli" }, + headers: clientHeaders(), body: JSON.stringify({ device_code: codeRes.device_code }), }); } catch (err) {