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
+108
-23
@@ -140,6 +140,8 @@ async function http(method, path, opts = {}) {
|
||||
method,
|
||||
headers,
|
||||
body,
|
||||
// `redirect: "manual"` keeps 30x responses inspectable (e.g. /pair/<code>).
|
||||
redirect: opts.redirect ?? "follow",
|
||||
signal: AbortSignal.timeout(opts.timeoutMs ?? 30_000),
|
||||
});
|
||||
} catch (error) {
|
||||
@@ -152,7 +154,14 @@ async function http(method, path, opts = {}) {
|
||||
} catch {
|
||||
json = undefined;
|
||||
}
|
||||
return { status: response.status, ok: response.ok, text, json, contentType: response.headers.get("content-type") ?? "" };
|
||||
return {
|
||||
status: response.status,
|
||||
ok: response.ok,
|
||||
text,
|
||||
json,
|
||||
contentType: response.headers.get("content-type") ?? "",
|
||||
location: response.headers.get("location"),
|
||||
};
|
||||
}
|
||||
|
||||
/** `POST /api/v1/cmd` with the CLI token by default. */
|
||||
@@ -965,20 +974,89 @@ scenario("A0", "Bootstrap & auth", async (ctx) => {
|
||||
observed: health.text.slice(0, 120),
|
||||
});
|
||||
|
||||
// Pairing: a fresh code, treat it as single-use, then revoke the device.
|
||||
const created = await cmd({ method: "pair.create", params: { ttlSec: 600 } });
|
||||
ctx.eq("pair.create → 202", created.status, 202);
|
||||
const code = created.json?.code;
|
||||
ctx.check("pair.create returns an 8-char code", typeof code === "string" && /^[A-Z0-9]{8}$/.test(code), {
|
||||
// Pairing (ADR 0001): `POST /api/v1/pair` only *mints* a code (authenticated,
|
||||
// QR matrix + reachable bases included), the public
|
||||
// `POST /api/v1/pair/redeem` exchanges it for a device token, and
|
||||
// `GET /pair/<code>` is the scanned link that bounces into the SPA.
|
||||
const minted = await http("POST", "/api/v1/pair", { token: CLI_TOKEN, body: { ttlSec: 600 } });
|
||||
ctx.eq("POST /api/v1/pair (mint) → 200", minted.status, 200);
|
||||
ctx.eq("mint reports accepted", minted.json?.accepted, true);
|
||||
const code = minted.json?.code;
|
||||
ctx.check("mint returns an 8-char code", typeof code === "string" && /^[A-Z0-9]{8}$/.test(code), {
|
||||
expected: "8 uppercase alphanumerics",
|
||||
observed: code,
|
||||
});
|
||||
if (typeof code !== "string") return;
|
||||
|
||||
const redeemed = await http("POST", "/api/v1/pair", {
|
||||
const mintedUrl = minted.json?.url;
|
||||
ctx.check("mint returns the /pair/<code> url", typeof mintedUrl === "string" && mintedUrl.endsWith(`/pair/${code}`), {
|
||||
expected: `…/pair/${code}`,
|
||||
observed: mintedUrl,
|
||||
});
|
||||
ctx.check(
|
||||
"mint returns expiresAt + nonce",
|
||||
typeof minted.json?.expiresAt === "number" &&
|
||||
minted.json.expiresAt > Date.now() &&
|
||||
/^[0-9a-f]{32}$/.test(String(minted.json?.nonce ?? "")),
|
||||
{
|
||||
expected: { expiresAt: "future epoch ms", nonce: "32 hex chars" },
|
||||
observed: { expiresAt: minted.json?.expiresAt, nonce: minted.json?.nonce },
|
||||
},
|
||||
);
|
||||
|
||||
const qr = minted.json?.qr;
|
||||
const qrRows = Array.isArray(qr?.rows) ? qr.rows : [];
|
||||
ctx.check(
|
||||
"mint carries the QR matrix (version/ecc/mask/size/rows)",
|
||||
qr !== null &&
|
||||
typeof qr === "object" &&
|
||||
typeof qr.version === "number" &&
|
||||
qr.ecc === "M" &&
|
||||
typeof qr.mask === "number" &&
|
||||
typeof qr.size === "number" &&
|
||||
qrRows.length === qr.size &&
|
||||
qrRows.every((row) => typeof row === "string" && row.length === qr.size),
|
||||
{
|
||||
expected: "{version, ecc:'M', mask, size, rows: size strings of size modules}",
|
||||
observed:
|
||||
qr === null
|
||||
? null
|
||||
: { version: qr?.version, ecc: qr?.ecc, mask: qr?.mask, size: qr?.size, rowCount: qrRows.length },
|
||||
},
|
||||
);
|
||||
|
||||
const bases = Array.isArray(minted.json?.bases) ? minted.json.bases : [];
|
||||
ctx.check(
|
||||
"mint lists the reachable bases",
|
||||
bases.length > 0 &&
|
||||
bases.every(
|
||||
(base) =>
|
||||
typeof base?.kind === "string" &&
|
||||
typeof base?.name === "string" &&
|
||||
typeof base?.address === "string" &&
|
||||
typeof base?.url === "string",
|
||||
),
|
||||
{ expected: "non-empty [{kind, name, address, url}]", observed: bases },
|
||||
);
|
||||
ctx.check("the minted url is built from the primary base", typeof mintedUrl === "string" && String(bases[0]?.url ?? "").replace(/\/$/, "") === mintedUrl.slice(0, mintedUrl.indexOf("/pair/")), {
|
||||
expected: { primaryBase: bases[0]?.url, url: mintedUrl },
|
||||
observed: { primaryBase: bases[0]?.url, url: mintedUrl },
|
||||
});
|
||||
|
||||
// The scanned link: a redirect into the SPA, never an API call.
|
||||
const scanned = await http("GET", `/pair/${code}`, { redirect: "manual" });
|
||||
ctx.eq("GET /pair/<code> → 302", scanned.status, 302);
|
||||
const pairLocation = scanned.location ?? "";
|
||||
ctx.check(
|
||||
"the scanned link redirects to /connect?code=<code>&auto=1",
|
||||
/\/connect\?/.test(pairLocation) && pairLocation.includes(`code=${code}`) && pairLocation.includes("auto=1"),
|
||||
{ expected: "/connect?code=<code>&auto=1", observed: pairLocation },
|
||||
);
|
||||
|
||||
const redeemed = await http("POST", "/api/v1/pair/redeem", {
|
||||
body: { code, kind: "laptop", deviceName: "E2E A0 device" },
|
||||
});
|
||||
ctx.eq("POST /api/v1/pair (redeem) → 200", redeemed.status, 200);
|
||||
ctx.eq("POST /api/v1/pair/redeem → 200", redeemed.status, 200);
|
||||
const token = redeemed.json?.token;
|
||||
ctx.check("redeem returns {token, device}", typeof token === "string" && token.length > 10 && Boolean(redeemed.json?.device?.id), {
|
||||
expected: "{token, device.id}",
|
||||
@@ -995,26 +1073,24 @@ scenario("A0", "Bootstrap & auth", async (ctx) => {
|
||||
ctx.check("redeemed token authorizes the API", false, { expected: "token", observed: "<no token>" });
|
||||
}
|
||||
|
||||
const reuse = await http("POST", "/api/v1/pair", { body: { code, kind: "laptop", deviceName: "dup" } });
|
||||
const reuse = await http("POST", "/api/v1/pair/redeem", { body: { code, kind: "laptop", deviceName: "dup" } });
|
||||
ctx.eq("re-using the pairing code → 401", reuse.status, 401);
|
||||
ctx.eq("re-use error code", reuse.json?.code, "E_UNAUTHORIZED");
|
||||
|
||||
if (PAIR_CODE) {
|
||||
const consumed = await http("POST", "/api/v1/pair", {
|
||||
const consumed = await http("POST", "/api/v1/pair/redeem", {
|
||||
body: { code: PAIR_CODE, kind: "laptop", deviceName: "reuse of the suite code" },
|
||||
});
|
||||
ctx.eq("the suite's consumed pairing code → 401", consumed.status, 401);
|
||||
}
|
||||
|
||||
const existingRedeem = await http("POST", "/api/v1/pair/redeem", {
|
||||
token: CLI_TOKEN,
|
||||
// The public redeem endpoint exists and is the only way to exchange a code:
|
||||
// an unknown code is rejected with 401 (never 404 — the route is live).
|
||||
const unknownRedeem = await http("POST", "/api/v1/pair/redeem", {
|
||||
body: { code: "AAAAAAAA", kind: "laptop", deviceName: "nope" },
|
||||
});
|
||||
ctx.check("there is no /api/v1/pair/redeem endpoint", existingRedeem.status === 404, {
|
||||
expected: 404,
|
||||
observed: existingRedeem.status,
|
||||
severity: "warn",
|
||||
});
|
||||
ctx.eq("POST /api/v1/pair/redeem exists (unknown code → 401, not 404)", unknownRedeem.status, 401);
|
||||
ctx.eq("unknown-code redeem error code", unknownRedeem.json?.code, "E_UNAUTHORIZED");
|
||||
|
||||
const deviceId = redeemed.json?.device?.id;
|
||||
if (typeof deviceId === "string") {
|
||||
@@ -2885,12 +2961,21 @@ scenario("A13", "Console login handoff", async (ctx) => {
|
||||
|
||||
ctx.eq("the session names the local-browser device", first.json?.device?.name, "local browser");
|
||||
ctx.eq("the local-browser device is a laptop", first.json?.device?.kind, "laptop");
|
||||
ctx.eq("the local-browser device holds every scope", first.json?.device?.scopes, [
|
||||
"read",
|
||||
"steer",
|
||||
"control",
|
||||
"admin",
|
||||
]);
|
||||
// ADR 0001 deleted the scope model: the device payload carries identity and
|
||||
// lifecycle timestamps only.
|
||||
const deviceFields = Object.keys(first.json?.device ?? {}).sort();
|
||||
ctx.check("the device payload carries no `scopes` field", !deviceFields.includes("scopes"), {
|
||||
expected: { fields: ["createdAt", "id", "kind", "lastSeenAt", "name", "revokedAt"] },
|
||||
observed: deviceFields,
|
||||
});
|
||||
ctx.check(
|
||||
"the device payload is {id, name, kind, createdAt, lastSeenAt, revokedAt}",
|
||||
["id", "name", "kind"].every((key) => typeof first.json?.device?.[key] === "string") &&
|
||||
typeof first.json?.device?.createdAt === "number" &&
|
||||
typeof first.json?.device?.lastSeenAt === "number" &&
|
||||
"revokedAt" in (first.json?.device ?? {}),
|
||||
{ expected: "identity + timestamps, no scopes", observed: first.json?.device },
|
||||
);
|
||||
ctx.check("the handoff url puts the token in the fragment", /\/#t=[A-Za-z0-9_-]{20,}$/.test(url), {
|
||||
expected: "http://127.0.0.1:<port>/#t=<token>",
|
||||
observed: url.replace(/#t=.{6}.*/, "#t=<redacted>"),
|
||||
|
||||
+14
-23
@@ -384,7 +384,6 @@ class Ctx {
|
||||
{ name: "pi2-endpoint", value: BASE },
|
||||
// Raw token (web/src/lib/api.ts strips an optional `Bearer ` prefix).
|
||||
{ name: "pi2-device-token", value: DEVICE_TOKEN },
|
||||
{ name: "pi2-device-scopes", value: JSON.stringify(["read", "steer", "apply"]) },
|
||||
{ name: "pi2-device", value: "Playwright" },
|
||||
{ name: "pi2-connected-at", value: String(Date.now()) },
|
||||
...Object.entries(localExtra).map(([name, value]) => ({ name, value: String(value) })),
|
||||
@@ -947,7 +946,7 @@ async function fillManualForm(page, code, device = "Playwright") {
|
||||
await page.locator('[data-testid="connect-submit"]').click();
|
||||
}
|
||||
|
||||
scenario("B2", "Manual pairing: host/port/pair-code/device → POST /api/v1/pair + redirect (wrong code → inline error)", async (ctx) => {
|
||||
scenario("B2", "Manual pairing: host/port/pair-code/device → POST /api/v1/pair/redeem + redirect (wrong code → inline error)", async (ctx) => {
|
||||
const { page } = await ctx.openPage("unpaired");
|
||||
await page.goto(`${BASE}/connect?next=%2Fworkspaces`, { waitUntil: "domcontentloaded" });
|
||||
await page.locator('[data-testid="connect-pair-code"]').waitFor({ state: "visible", timeout: 15000 });
|
||||
@@ -975,13 +974,13 @@ scenario("B2", "Manual pairing: host/port/pair-code/device → POST /api/v1/pair
|
||||
return null;
|
||||
}, 25000);
|
||||
|
||||
const pairCalls = ctx.apiCalls.filter((call) => call.method === "POST" && call.path === "/api/v1/pair");
|
||||
const pairCalls = ctx.apiCalls.filter((call) => call.method === "POST" && call.path === "/api/v1/pair/redeem");
|
||||
ctx.log(`redeem calls: ${JSON.stringify(pairCalls)}`);
|
||||
ctx.check("the redeem posts the public POST /api/v1/pair", pairCalls.length >= 1, {
|
||||
expected: "POST /api/v1/pair {code,deviceName,kind}",
|
||||
ctx.check("the redeem posts the public POST /api/v1/pair/redeem", pairCalls.length >= 1, {
|
||||
expected: "POST /api/v1/pair/redeem {code,deviceName,kind}",
|
||||
observed: { pairCalls, cmdMethods: ctx.cmdRequests.map((request) => request.method) },
|
||||
});
|
||||
ctx.check("POST /api/v1/pair answered 200", pairCalls.some((call) => call.status === 200), {
|
||||
ctx.check("POST /api/v1/pair/redeem answered 200", pairCalls.some((call) => call.status === 200), {
|
||||
expected: 200,
|
||||
observed: pairCalls,
|
||||
});
|
||||
@@ -1000,11 +999,10 @@ scenario("B2", "Manual pairing: host/port/pair-code/device → POST /api/v1/pair
|
||||
const storage = await page.evaluate(() => ({
|
||||
connection: localStorage.getItem("pi2-connection"),
|
||||
token: localStorage.getItem("pi2-device-token"),
|
||||
scopes: localStorage.getItem("pi2-device-scopes"),
|
||||
endpoint: localStorage.getItem("pi2-endpoint"),
|
||||
}));
|
||||
const connWrites = await page.evaluate(() =>
|
||||
(window.__pi2Writes ?? []).filter((write) => ["pi2-connection", "pi2-device-token", "pi2-device-scopes"].includes(write.key)),
|
||||
(window.__pi2Writes ?? []).filter((write) => ["pi2-connection", "pi2-device-token"].includes(write.key)),
|
||||
);
|
||||
ctx.note(`pi2-* storage writes: ${short(connWrites, 700)}`);
|
||||
ctx.note(`navigations: ${short(ctx.navigations, 400)}`);
|
||||
@@ -1014,7 +1012,6 @@ scenario("B2", "Manual pairing: host/port/pair-code/device → POST /api/v1/pair
|
||||
/^Bearer\s+/i,
|
||||
"",
|
||||
);
|
||||
const mintedScopes = (connWrites.find((write) => write.key === "pi2-device-scopes" && write.op === "set")?.value ?? "").trim();
|
||||
|
||||
const wsErrors = socketErrors(ctx.wsFrames);
|
||||
const wsAuthErrors = wsErrors.filter((entry) => entry.code === "E_UNAUTHORIZED");
|
||||
@@ -1036,22 +1033,17 @@ scenario("B2", "Manual pairing: host/port/pair-code/device → POST /api/v1/pair
|
||||
expected: "paired",
|
||||
observed: { connection: storage.connection, setToken: Boolean(mintedRaw), writes: connWrites, navigations: ctx.navigations },
|
||||
cause:
|
||||
"the flow writes pi2-connection=paired (see the write log), then ~100 ms later the app removes the token + scopes and writes 'unpaired' " +
|
||||
"the flow writes pi2-connection=paired (see the write log), then ~100 ms later the app removes the token and writes 'unpaired' " +
|
||||
"because the socket auth of that same token fails with E_UNAUTHORIZED",
|
||||
});
|
||||
ctx.softCheck("localStorage pi2-device-token is still set", Boolean(storage.token), {
|
||||
expected: "<device token>",
|
||||
observed: storage.token ? "set" : { removedAfterMs: connWrites.at(-1)?.at, writes: connWrites },
|
||||
});
|
||||
let scopes = null;
|
||||
try {
|
||||
scopes = JSON.parse(storage.scopes ?? mintedScopes ?? "null");
|
||||
} catch {
|
||||
scopes = null;
|
||||
}
|
||||
ctx.softCheck("the paired scopes are a non-empty array", Array.isArray(scopes) && scopes.length > 0, {
|
||||
expected: '["read", …]',
|
||||
observed: storage.scopes ?? mintedScopes,
|
||||
const legacyScopes = await page.evaluate(() => localStorage.getItem("pi2-device-scopes"));
|
||||
ctx.softCheck("the browser writes no legacy pi2-device-scopes key (ADR 0001)", legacyScopes === null, {
|
||||
expected: null,
|
||||
observed: { legacyScopes },
|
||||
});
|
||||
|
||||
// A paired browser shows the summary instead of the form.
|
||||
@@ -1178,10 +1170,9 @@ scenario("B3", "Paste-link pairing: pi2:// and /pair/<code> links reach the conf
|
||||
const linkStorage = await page.evaluate(() => ({
|
||||
connection: localStorage.getItem("pi2-connection"),
|
||||
token: localStorage.getItem("pi2-device-token"),
|
||||
scopes: localStorage.getItem("pi2-device-scopes"),
|
||||
}));
|
||||
const linkWrites = await page.evaluate(() =>
|
||||
(window.__pi2Writes ?? []).filter((write) => ["pi2-connection", "pi2-device-token", "pi2-device-scopes"].includes(write.key)),
|
||||
(window.__pi2Writes ?? []).filter((write) => ["pi2-connection", "pi2-device-token"].includes(write.key)),
|
||||
);
|
||||
ctx.note(`link-flow pi2-* storage writes: ${short(linkWrites, 700)}`);
|
||||
const linkWsErrors = socketErrors(ctx.wsFrames);
|
||||
@@ -1194,7 +1185,7 @@ scenario("B3", "Paste-link pairing: pi2:// and /pair/<code> links reach the conf
|
||||
cause: "same stored 'Bearer <token>' passed verbatim to the WS auth frame (web/src/lib/api.ts + web/src/lib/ws.ts:219)",
|
||||
},
|
||||
);
|
||||
ctx.softCheck("the link flow keeps paired + token + scopes", linkStorage.connection === "paired" && Boolean(linkStorage.token), {
|
||||
ctx.softCheck("the link flow keeps paired + token", linkStorage.connection === "paired" && Boolean(linkStorage.token), {
|
||||
expected: { connection: "paired", token: "set" },
|
||||
observed: { ...linkStorage, token: linkStorage.token ? "set" : null, writes: linkWrites },
|
||||
cause: "the same write-then-clear sequence as B2 (socket auth of the fresh token is rejected → app-shell disconnects)",
|
||||
@@ -2253,7 +2244,7 @@ scenario("B11", "Status: six API-backed cards + metrics strip, devices list/revo
|
||||
const created = await cmd("pair.create", { ttlSec: 600 });
|
||||
const code = created.json?.code;
|
||||
ctx.check("pair.create returns a code", typeof code === "string" && code.length > 0, { observed: created.json });
|
||||
const redeemed = await apiRaw("POST", "/api/v1/pair", { token: null, body: { code, deviceName: "e2e-second-device", kind: "phone" } });
|
||||
const redeemed = await apiRaw("POST", "/api/v1/pair/redeem", { token: null, body: { code, deviceName: "e2e-second-device", kind: "phone" } });
|
||||
ctx.check("second device pairs", redeemed.status === 200 && Boolean(redeemed.json?.token), {
|
||||
expected: "200 with a device token",
|
||||
observed: { status: redeemed.status, body: short(redeemed.json) },
|
||||
|
||||
Reference in new issue
Block a user