Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

feat(host,cloud): short pairing codes and account hints for headless computers

leepokai4eaf8e9a49e4
diff --git a/cloud/migrations/0005_pairing_codes.sql b/cloud/migrations/0005_pairing_codes.sql
new file mode 100644
index 00000000..5a5dbd03
--- /dev/null
+++ b/cloud/migrations/0005_pairing_codes.sql
@@ -0,0 +1,10 @@
+-- Short pairing codes (docs/plans/require-sign-in.md, phase 3): `codync-host pair` registers its QR link under a
+-- code people can type, like QRTX-4821. One use, ten minutes.
+CREATE TABLE pairing_codes (
+ code TEXT PRIMARY KEY,
+ computer_id TEXT NOT NULL REFERENCES computers(id),
+ link TEXT NOT NULL,
+ expires_at INTEGER NOT NULL,
+ used_at INTEGER
+);
+CREATE INDEX pairing_codes_computer ON pairing_codes(computer_id);
diff --git a/cloud/src/api.ts b/cloud/src/api.ts
index 429d69ee..a2457cd8 100644
--- a/cloud/src/api.ts
+++ b/cloud/src/api.ts
@@ -8,6 +8,7 @@ export { ApiError, type Ctx } from "./routes/common";
export * from "./routes/account";
export * from "./routes/assistant";
export * from "./routes/host";
+export * from "./routes/pairing-codes";
export * from "./routes/relay";
export * from "./routes/webhooks";
diff --git a/cloud/src/index.ts b/cloud/src/index.ts
index eb78bd1f..db111b8f 100644
--- a/cloud/src/index.ts
+++ b/cloud/src/index.ts
@@ -78,6 +78,8 @@ const routes: [string, RegExp, Handler][] = [
["POST", new RegExp(`^/v1/host/access-requests/${ID}/decision$`), api.hostDecision],
["POST", new RegExp(`^/v1/host/grants/${ID}/revoke$`), api.hostRevokeGrant],
["POST", /^\/v1\/host\/unclaim$/, api.hostUnclaim],
+ ["POST", /^\/v1\/host\/pairing-codes$/, api.createPairingCode],
+ ["GET", new RegExp(`^/v1/pairing-codes/${ID}$`), api.redeemPairingCode],
["GET", /^\/v1\/relay\/host$/, api.relayHost],
// Any segment reaches the handler so a malformed computerId gets its 400 (§7.1).
["GET", /^\/v1\/relay\/device\/([^/]+)$/, api.relayDevice],
diff --git a/cloud/src/routes/pairing-codes.ts b/cloud/src/routes/pairing-codes.ts
new file mode 100644
index 00000000..fc22c184
--- /dev/null
+++ b/cloud/src/routes/pairing-codes.ts
@@ -0,0 +1,67 @@
+// Short pairing codes (docs/plans/require-sign-in.md, phase 3): a computer registers its pairing link under a code
+// people can type where scanning a terminal is awkward; a signed-in app trades the code for the link once.
+// The computer's own check (the 6-digit code it shows when it asks) catches a cloud that hands out another link.
+
+import { ApiError, body, host, user, type Ctx } from "./common";
+
+const TTL_MS = 10 * 60_000;
+const LIVE_PER_COMPUTER = 5;
+const LETTERS = "ABCDEFGHJKLMNPQRSTUVWXYZ";
+
+/** `QRTX-4821`: four letters (no I or O) and four digits. */
+function newCode(): string {
+ const bytes = crypto.getRandomValues(new Uint8Array(8));
+ const letters = Array.from(bytes.subarray(0, 4), (b) => LETTERS[b % LETTERS.length]).join("");
+ const digits = Array.from(bytes.subarray(4), (b) => String(b % 10)).join("");
+ return `${letters}-${digits}`;
+}
+
+/** What people type, as stored: case, spaces and the dash don't matter. */
+export function normalizeCode(raw: string): string | null {
+ const s = raw.toUpperCase().replace(/[\s-]/g, "");
+ return /^[A-Z]{4}[0-9]{4}$/.test(s) ? `${s.slice(0, 4)}-${s.slice(4)}` : null;
+}
+
+export async function createPairingCode(c: Ctx) {
+ const comp = await host(c);
+ const b = body(c);
+ const link = b.link;
+ if (typeof link !== "string" || link.length > 4096 || !/^codync(-dev)?:\/\/pair\?/.test(link)) {
+ throw new ApiError("badRequest", "Invalid link");
+ }
+ const expiresAt = Math.min(typeof b.expiresAt === "number" ? b.expiresAt : c.now + TTL_MS, c.now + TTL_MS);
+ await c.env.DB.prepare("DELETE FROM pairing_codes WHERE computer_id = ? AND (expires_at <= ? OR used_at IS NOT NULL)")
+ .bind(comp.id, c.now)
+ .run();
+ const live = await c.env.DB.prepare("SELECT count(*) AS n FROM pairing_codes WHERE computer_id = ?").bind(comp.id).first<{ n: number }>();
+ if ((live?.n ?? 0) >= LIVE_PER_COMPUTER) {
+ await c.env.DB.prepare(
+ "DELETE FROM pairing_codes WHERE code = (SELECT code FROM pairing_codes WHERE computer_id = ? ORDER BY expires_at LIMIT 1)",
+ )
+ .bind(comp.id)
+ .run();
+ }
+ for (let attempt = 0; attempt < 3; attempt++) {
+ const code = newCode();
+ const r = await c.env.DB.prepare(
+ "INSERT INTO pairing_codes(code, computer_id, link, expires_at) VALUES (?, ?, ?, ?) ON CONFLICT(code) DO NOTHING",
+ )
+ .bind(code, comp.id, link, expiresAt)
+ .run();
+ if (r.meta.changes === 1) return { code, expiresAt };
+ }
+ throw new ApiError("conflict", "Try again");
+}
+
+export async function redeemPairingCode(c: Ctx, [raw]: string[]) {
+ await user(c);
+ const code = normalizeCode(decodeURIComponent(raw ?? ""));
+ if (!code) throw new ApiError("notFound", "That code isn't valid. Check it on the computer.");
+ const row = await c.env.DB.prepare(
+ "UPDATE pairing_codes SET used_at = ?1 WHERE code = ?2 AND used_at IS NULL AND expires_at > ?1 RETURNING link",
+ )
+ .bind(c.now, code)
+ .first<{ link: string }>();
+ if (!row) throw new ApiError("notFound", "That code expired or was used. Show a new one on the computer.");
+ return { link: row.link };
+}
diff --git a/cloud/test/pairing-codes.test.ts b/cloud/test/pairing-codes.test.ts
new file mode 100644
index 00000000..834eeb47
--- /dev/null
+++ b/cloud/test/pairing-codes.test.ts
@@ -0,0 +1,37 @@
+// Short pairing codes (docs/plans/require-sign-in.md, phase 3).
+
+import { describe, expect, it } from "vitest";
+import { normalizeCode } from "../src/routes/pairing-codes";
+import { call, clerkToken, newHost } from "./helpers";
+
+const LINK = "codync-dev://pair?v=3&name=VPS&id=abc&code=xyz";
+
+describe("pairing codes", () => {
+ it("trades a code a computer registered for its link, once", async () => {
+ const host = await newHost();
+ const created = await call("POST", "/v1/host/pairing-codes", { key: host.sign, body: { link: LINK } });
+ expect(created.status).toBe(200);
+ const code = created.body.code as string;
+ expect(code).toMatch(/^[A-HJ-NP-Z]{4}-[0-9]{4}$/);
+ const token = await clerkToken(`user_codes_${Date.now()}`);
+ // Typed loosely: lower case, no dash.
+ const typed = code.toLowerCase().replace("-", "");
+ const redeemed = await call("GET", `/v1/pairing-codes/${typed}`, { token });
+ expect(redeemed).toMatchObject({ status: 200, body: { link: LINK } });
+ expect((await call("GET", `/v1/pairing-codes/${code}`, { token })).status).toBe(404);
+ });
+
+ it("needs a signed-in app, a registered computer and a pairing link", async () => {
+ const host = await newHost();
+ const created = await call("POST", "/v1/host/pairing-codes", { key: host.sign, body: { link: LINK } });
+ expect((await call("GET", `/v1/pairing-codes/${created.body.code}`)).status).toBe(401);
+ expect((await call("POST", "/v1/host/pairing-codes", { key: host.sign, body: { link: "https://evil.example" } })).status).toBe(400);
+ const token = await clerkToken(`user_codes_${Date.now()}`);
+ expect((await call("GET", "/v1/pairing-codes/NOPE-0000", { token })).status).toBe(404);
+ });
+
+ it("normalizes what people type", () => {
+ expect(normalizeCode(" qrtx 4821 ")).toBe("QRTX-4821");
+ expect(normalizeCode("QRTX-48210")).toBeNull();
+ });
+});
diff --git a/host/src/api/remote.rs b/host/src/api/remote.rs
index a87d1414..baaeaf68 100644
--- a/host/src/api/remote.rs
+++ b/host/src/api/remote.rs
@@ -64,7 +64,7 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value
hub.store.remove_activity_ticket(str_arg(&b, "botId")?, caller.device_key())?;
json!({})
}
- "pairing" => pairing(hub).await?,
+ "pairing" => pairing(hub, b["shortCode"] == true).await?,
"devices" => {
let connected = hub.connected.locked().clone();
let devices: Vec<Value> = hub
@@ -133,7 +133,7 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value
}
/// A new one-time pairing code and the QR that carries it (§4.1).
-async fn pairing(hub: &Arc<Hub>) -> Result<Value> {
+async fn pairing(hub: &Arc<Hub>, short_code: bool) -> Result<Value> {
let port = hub.port;
// Shells out to `tailscale`: keep it off the async workers.
let urls = tokio::task::spawn_blocking(move || crate::service::addresses(port)).await?;
@@ -152,7 +152,16 @@ async fn pairing(hub: &Arc<Hub>) -> Result<Value> {
urls: &urls,
cloud: cloud.as_deref(),
});
- Ok(json!({"pairingUrl": url, "urls": urls, "expiresAt": issued.expires_at}))
+ // Asked for (`codync-host pair`): a code to type instead of scanning, when the Codync cloud can hold the link.
+ let short_code = if short_code {
+ crate::remote::short_code::register(hub, &url, issued.expires_at)
+ .await
+ .inspect_err(|e| tracing::info!(error = format!("{e:#}"), "no short pairing code"))
+ .ok()
+ } else {
+ None
+ };
+ Ok(json!({"pairingUrl": url, "urls": urls, "expiresAt": issued.expires_at, "shortCode": short_code}))
}
/// Signs this computer into an account claim (§4.2 A) for the signed-in desktop app to complete.
diff --git a/host/src/cloud_cli.rs b/host/src/cloud_cli.rs
index af5e1f8a..e8b0f145 100644
--- a/host/src/cloud_cli.rs
+++ b/host/src/cloud_cli.rs
@@ -81,5 +81,36 @@ pub async fn run(args: CloudArgs) -> Result<()> {
if status["assistants"] == true { "on" } else { "off" },
text("lastError"),
);
+ if let Some(hint) = account_hint(&status) {
+ println!("\n{hint}");
+ }
Ok(())
}
+
+/// How a computer with no desktop app gets into an account (docs/architecture/connections.md, headless computers).
+fn account_hint(status: &serde_json::Value) -> Option<&'static str> {
+ if !status["owner"].is_null() {
+ return None;
+ }
+ Some(if status["enabled"] != true || status["relay"] == "private" {
+ "Not in an account. Phones pair with `codync-host pair` and a QR code; joining an account needs the Codync cloud (`codync-host cloud --enable`)."
+ } else {
+ "Not in an account. Add it from a signed-in phone: run `codync-host pair` and scan the code, or type its short code. Or, from a desktop app that reaches this computer over SSH, choose Add to account."
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_computer_out_of_an_account_says_how_to_join_one() {
+ assert_eq!(account_hint(&json!({"owner": {"userId": "u"}, "enabled": true})), None);
+ assert!(
+ account_hint(&json!({"owner": null, "enabled": true, "relay": "codync"}))
+ .unwrap()
+ .contains("signed-in phone")
+ );
+ assert!(account_hint(&json!({"owner": null, "enabled": false})).unwrap().contains("--enable"));
+ }
+}
diff --git a/host/src/main.rs b/host/src/main.rs
index 2abf34d7..294ec5c8 100644
--- a/host/src/main.rs
+++ b/host/src/main.rs
@@ -582,14 +582,14 @@ async fn shutdown_signal() {
async fn pair(port: u16, as_json: bool) -> Result<()> {
let hello = local_call(port, "hello", json!({})).await?;
- let p = local_call(port, "pairing", json!({})).await?;
+ let p = local_call(port, "pairing", json!({"shortCode": true})).await?;
if as_json {
println!(
"{}",
json!({
"name": hello["name"], "computerId": hello["computerId"], "signKey": hello["signKey"],
"boxKey": hello["boxKey"], "urls": p["urls"], "cloud": hello["cloud"],
- "pairingUrl": p["pairingUrl"], "expiresAt": p["expiresAt"],
+ "pairingUrl": p["pairingUrl"], "expiresAt": p["expiresAt"], "shortCode": p["shortCode"],
})
);
return Ok(());
@@ -598,6 +598,9 @@ async fn pair(port: u16, as_json: bool) -> Result<()> {
let code = qrcode::QrCode::new(url.as_bytes())?;
println!("{}", code.render::<qrcode::render::unicode::Dense1x2>().quiet_zone(true).build());
println!("Scan with the Codync iOS app within 10 minutes, or open this link on the phone:\n{url}\n");
+ if let Some(code) = p["shortCode"].as_str() {
+ println!("Or type this code in the app (Pair a computer → Type a code): {code}\n");
+ }
if hello["cloud"].is_null()
&& p["urls"].as_array().is_none_or(|u| {
!u.iter().any(|u| {
diff --git a/host/src/remote/cloud.rs b/host/src/remote/cloud.rs
index aca03ef5..7d778366 100644
--- a/host/src/remote/cloud.rs
+++ b/host/src/remote/cloud.rs
@@ -227,7 +227,7 @@ fn signed(hub: &Hub, base: &str, method: Method, path: &str, body: Option<&Value
}
/// One signed `/v1/host/*` call.
-async fn call(hub: &Hub, base: &str, method: Method, path: &str, body: Option<&Value>) -> Result<Value> {
+pub(super) async fn call(hub: &Hub, base: &str, method: Method, path: &str, body: Option<&Value>) -> Result<Value> {
answer(signed(hub, base, method, path, body)?).await
}
diff --git a/host/src/remote/mod.rs b/host/src/remote/mod.rs
index bb3aa8c9..37d28d84 100644
--- a/host/src/remote/mod.rs
+++ b/host/src/remote/mod.rs
@@ -11,3 +11,4 @@ pub mod owner;
pub mod pairing_requests;
pub mod push;
pub mod relay;
+pub mod short_code;
diff --git a/host/src/remote/short_code.rs b/host/src/remote/short_code.rs
new file mode 100644
index 00000000..e1bb4475
--- /dev/null
+++ b/host/src/remote/short_code.rs
@@ -0,0 +1,19 @@
+//! Short pairing codes (docs/plans/require-sign-in.md, phase 3): the QR's link registered with the Codync cloud
+//! under a code people type where scanning a terminal is awkward, like `QRTX-4821`.
+
+use super::cloud::{call, codync_url};
+use crate::hub::Hub;
+use anyhow::{Context, Result};
+use reqwest::Method;
+use serde_json::json;
+use std::time::Duration;
+
+/// The code for `link`, or an error with the cloud off, on a private relay, or unreachable within a few seconds.
+pub async fn register(hub: &Hub, link: &str, expires_at: i64) -> Result<String> {
+ let base = codync_url(hub)?;
+ let body = json!({"link": link, "expiresAt": expires_at});
+ let request = call(hub, &base, Method::POST, "/v1/host/pairing-codes", Some(&body));
+ let answer =
+ tokio::time::timeout(Duration::from_secs(5), request).await.context("the Codync cloud didn't answer")??;
+ Ok(answer["code"].as_str().context("the cloud gave no code")?.to_owned())
+}