feat(daemon)!: phone-first binding and a two-step pairing flow
Implements ADR 0001 (docs/adr/0001-phone-first-pairing.md): the console is
meant to be opened from a phone, so reachability stops being a mode and the
pairing link becomes the only access control that matters.
Binding / CORS
- `PI2_HOST` defaults to `0.0.0.0`; `PI2_ACCESS_MODE` (local|lan|tailscale) is
deleted, together with its parser, `AccessMode` type and LAN probe.
- `src/core/network.ts` is the single source of truth for reachable addresses:
kind classification, ordering (public → lan → other → tailscale → loopback,
physical NICs first, link-local skipped), bind-aware `networkBases()`,
`primaryBase()` and `localOrigins()`. Config, the pairing route, doctor and
the CLI all consume it, so the CORS allowlist always matches the pairing URL.
- `/api/v1/info` and `daemon.json` report `host` instead of `access`; doctor's
`access` check becomes `bind` (loopback ok, wildcard warns unless an `https:`
public URL is configured).
Pairing
- `POST /api/v1/pair` only mints, requires a token, and returns the code, the
chosen URL, the expiry, the nonce, the QR matrix and every usable base.
`base` may pin one of those bases; anything else is a 400.
- `POST /api/v1/pair/redeem` is the public half, rate limited per client
(5/min) and globally (50/h) → 429 `E_RATE_LIMITED` with `retry-after`.
- `GET /pair/:code` answers 302 to `/connect?code=…&auto=1`, so a scanned link
needs no JavaScript to reach the console.
- `src/core/qr.ts` (moved out of the CLI) is the one encoder: byte mode, EC
level M, versions 1–10, rows without a quiet zone, shared by the HTTP mint
response and the terminal renderer.
- `pi2 pairing` prints a human report plus a half-block terminal QR and keeps
`--base`; `--json` and `--public-url` are gone (the Neovim client calls the
HTTP mint directly).
Device scopes
- `Scope`, `SCOPES`, `DEFAULT_SCOPES`, `DeviceRecord.scopes` and the `scopes`
field in device/hello payloads are removed: nothing enforced them, and a
paired device now holds the same rights as the local browser. A permission
model, if wanted, gets its own ADR.
Breaking: `PI2_ACCESS_MODE`, `info.access`, `pi2 status --json`'s `access`,
`pi2 pairing --json`/`--public-url`, `POST /api/v1/pair {code}`, and the
`scopes` field. All in-repo callers and the e2e drivers are updated; the plugin
side (`:PiWebAccess`, `env.PI2_ACCESS_MODE`, text-format parsing) follows in
pi2.nvim.
Verification: root typecheck clean; 369/370 tests (the one failure is the
pre-existing supervisor timing flake, 24/24 in isolation ×3); `smoke.sh` green;
web suite 299/299; visual matrix 24/24.
This commit is contained in:
1 parent
3789394c85
commit
a57c874095
34 files changed
+2157
-488
No files matched your search
+85
-13
@@ -317,30 +317,102 @@ describe("HTTP API", () => {
|
||||
expect(h.auth.verifyToken(token)).toBeNull();
|
||||
});
|
||||
|
||||
it("redeems a pairing code over HTTP", async () => {
|
||||
const pair = h.auth.pairCreate();
|
||||
const res = await fetch(`${h.url}/api/v1/pair`, {
|
||||
/** `POST /api/v1/pair/redeem` — the public half of pairing (ADR 0001 §3). */
|
||||
async function redeem(code: string, kind = "phone"): Promise<Response> {
|
||||
return fetch(`${h.url}/api/v1/pair/redeem`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ code: pair.code, deviceName: "Pixel", kind: "phone" }),
|
||||
body: JSON.stringify({ code, deviceName: "Pixel", kind }),
|
||||
});
|
||||
}
|
||||
|
||||
it("redeems a pairing code over the public endpoint, once", async () => {
|
||||
const pair = h.auth.pairCreate();
|
||||
const res = await redeem(pair.code);
|
||||
expect(res.status).toBe(200);
|
||||
const body = (await res.json()) as { token: string; device: { name: string } };
|
||||
const body = (await res.json()) as { token: string; device: { name: string; scopes?: unknown } };
|
||||
expect(body.device.name).toBe("Pixel");
|
||||
expect(body.device.scopes).toBeUndefined();
|
||||
expect(h.auth.verifyToken(body.token)?.name).toBe("Pixel");
|
||||
|
||||
const replay = await fetch(`${h.url}/api/v1/pair`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ code: pair.code, deviceName: "Pixel", kind: "phone" }),
|
||||
});
|
||||
expect(replay.status).toBe(401);
|
||||
expect((await redeem(pair.code)).status).toBe(401);
|
||||
});
|
||||
|
||||
it("creates a pairing code for an authenticated client", async () => {
|
||||
it("rate limits repeated redeem attempts", async () => {
|
||||
// The default budget is 5/minute per client; the 6th attempt is refused
|
||||
// before it can touch the code store.
|
||||
for (let attempt = 0; attempt < 5; attempt += 1) {
|
||||
expect((await redeem("ZZZZZZZZ")).status).toBe(401);
|
||||
}
|
||||
const limited = await redeem("ZZZZZZZZ");
|
||||
expect(limited.status).toBe(429);
|
||||
expect(limited.headers.get("retry-after")).toMatch(/^\d+$/);
|
||||
const body = (await limited.json()) as { code: string };
|
||||
expect(body.code).toBe(ERROR_CODES.RATE_LIMITED);
|
||||
});
|
||||
|
||||
it("mints a code, its QR matrix and every usable base for an authenticated client", async () => {
|
||||
const res = await fetch(`${h.url}/api/v1/pair`, authed({ method: "POST", body: "{}" }));
|
||||
expect(res.status).toBe(200);
|
||||
const body = (await res.json()) as { code: string; url: string; expiresAt: number };
|
||||
const body = (await res.json()) as {
|
||||
code: string;
|
||||
url: string;
|
||||
expiresAt: number;
|
||||
nonce: string;
|
||||
qr: { version: number; ecc: string; size: number; rows: string[] } | null;
|
||||
bases: { kind: string; name: string; url: string }[];
|
||||
};
|
||||
expect(body.code).toMatch(/^[A-Z0-9]{8}$/);
|
||||
expect(body.url).toContain(body.code);
|
||||
expect(body.url).toContain(`/pair/${body.code}`);
|
||||
expect(body.expiresAt).toBeGreaterThan(Date.now());
|
||||
expect(body.nonce).toMatch(/^[0-9a-f]{32}$/);
|
||||
expect(body.qr).not.toBeNull();
|
||||
expect(body.qr!.size).toBe(body.qr!.version * 4 + 17);
|
||||
expect(body.qr!.rows).toHaveLength(body.qr!.size);
|
||||
expect(body.qr!.rows.every((row) => row.length === body.qr!.size && /^[01]+$/.test(row))).toBe(true);
|
||||
expect(body.bases.length).toBeGreaterThan(0);
|
||||
expect(body.bases.every((base) => typeof base.url === "string" && base.url.startsWith("http"))).toBe(true);
|
||||
// The chosen URL is always one of the offered bases.
|
||||
expect(body.bases.some((base) => body.url.startsWith(base.url))).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts a base it offered and rejects a foreign one", async () => {
|
||||
const first = (await (await fetch(`${h.url}/api/v1/pair`, authed({ method: "POST", body: "{}" }))).json()) as {
|
||||
bases: { url: string }[];
|
||||
};
|
||||
const chosen = first.bases.at(-1)!.url;
|
||||
|
||||
const ok = await fetch(
|
||||
`${h.url}/api/v1/pair`,
|
||||
authed({ method: "POST", body: JSON.stringify({ base: chosen }) }),
|
||||
);
|
||||
expect(ok.status).toBe(200);
|
||||
const minted = (await ok.json()) as { url: string };
|
||||
expect(minted.url.startsWith(chosen)).toBe(true);
|
||||
|
||||
const foreign = await fetch(
|
||||
`${h.url}/api/v1/pair`,
|
||||
authed({ method: "POST", body: JSON.stringify({ base: "http://evil.example:9999" }) }),
|
||||
);
|
||||
expect(foreign.status).toBe(400);
|
||||
});
|
||||
|
||||
it("requires a token to mint a code", async () => {
|
||||
const res = await fetch(`${h.url}/api/v1/pair`, { method: "POST", body: "{}" });
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it("redirects a scanned /pair/<code> link to the zero-input connect page", async () => {
|
||||
const res = await fetch(`${h.url}/pair/abcd2345`, { redirect: "manual" });
|
||||
expect(res.status).toBe(302);
|
||||
const location = res.headers.get("location") ?? "";
|
||||
expect(location).toContain("/connect?");
|
||||
expect(location).toContain("code=ABCD2345");
|
||||
expect(location).toContain("auto=1");
|
||||
|
||||
// A malformed code still lands on the console, just without a code.
|
||||
const malformed = await fetch(`${h.url}/pair/nope!`, { redirect: "manual" });
|
||||
expect(malformed.status).toBe(302);
|
||||
expect(malformed.headers.get("location")).not.toContain("code=");
|
||||
expect(malformed.headers.get("location")).toContain("auto=1");
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user