Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/cli-client-header.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@makespdf/cli": patch
---

Send `X-MakesPDF-Client: cli/<version>` 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.
24 changes: 24 additions & 0 deletions src/client-info.test.ts
Original file line number Diff line number Diff line change
@@ -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/<package version>` 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");
});
});
37 changes: 37 additions & 0 deletions src/client-info.ts
Original file line number Diff line number Diff line change
@@ -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/<package version>` so the server can classify CLI
* traffic by client kind. Per operator decision 2f382669, official clients
* send plain `<kind>/<version>` 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<string, string> {
return {
"Content-Type": "application/json",
"User-Agent": "@makespdf/cli",
[CLIENT_HEADER]: CLIENT_NAME,
};
}
2 changes: 2 additions & 0 deletions src/client.test.ts
Original file line number Diff line number Diff line change
@@ -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<Response>): typeof fetch {
Expand Down Expand Up @@ -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" }));
});

Expand Down
7 changes: 4 additions & 3 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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(
Expand Down Expand Up @@ -78,9 +80,8 @@ export class ApiClient {
const url = `${this.baseUrl}${path.startsWith("/") ? path : `/${path}`}`;
const expect = opts.expect ?? "bytes";
const headers: Record<string, string> = {
"Content-Type": "application/json",
...clientHeaders(),
Authorization: `Bearer ${this.apiKey}`,
"User-Agent": "@makespdf/cli",
};
if (expect === "json") headers.Accept = "application/json";

Expand Down
78 changes: 78 additions & 0 deletions src/commands/login.test.ts
Original file line number Diff line number Diff line change
@@ -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<Response> => {
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<string, string>;
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",
});
});
});
5 changes: 3 additions & 2 deletions src/commands/login.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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) {
Expand Down
Loading