diff --git a/cloud/migrations/0003_pairing_claim.sql b/cloud/migrations/0003_pairing_claim.sql new file mode 100644 index 0000000..40fb90b --- /dev/null +++ b/cloud/migrations/0003_pairing_claim.sql @@ -0,0 +1,40 @@ +-- Mote Cloud D1 ONLY (after 0001_core.sql, 0002_auth.sql). +-- Single-statement atomic pairing: approving a pending ticket inserts the +-- account-owned device in the SAME SQL statement through this trigger. +-- Never apply to the existing personal Durable Object SQLite. + +CREATE TRIGGER cloud_pairing_only_active_account +BEFORE UPDATE OF status ON cloud_pairing_tickets +WHEN NEW.status = 'approved' AND ( + OLD.status <> 'pending' + OR NEW.claimed_by_account_id IS NULL + OR NOT EXISTS ( + SELECT 1 FROM cloud_accounts a + WHERE a.id = NEW.claimed_by_account_id AND a.status = 'active' + ) +) +BEGIN + SELECT RAISE(ABORT, 'invalid pairing approval'); +END; + +CREATE TRIGGER cloud_pairing_approve_create_device +AFTER UPDATE OF status ON cloud_pairing_tickets +WHEN OLD.status = 'pending' AND NEW.status = 'approved' +BEGIN + INSERT INTO cloud_devices ( + id, owner_account_id, name, platform, credential_hash, + status, created_at_ms, updated_at_ms + ) VALUES ( + NEW.device_id, NEW.claimed_by_account_id, NEW.device_name, + NEW.device_platform, NEW.device_credential_hash, + 'active', NEW.created_at_ms, NEW.created_at_ms + ); +END; + +-- After approval no status reversal may grant a second claim. +CREATE TRIGGER cloud_pairing_prevent_approved_reuse +BEFORE UPDATE OF status ON cloud_pairing_tickets +WHEN OLD.status = 'approved' AND NEW.status <> 'approved' +BEGIN + SELECT RAISE(ABORT, 'approved ticket is immutable'); +END; diff --git a/docs/cloud-p0c1-pairing.md b/docs/cloud-p0c1-pairing.md new file mode 100644 index 0000000..2acb12f --- /dev/null +++ b/docs/cloud-p0c1-pairing.md @@ -0,0 +1,62 @@ +# Mote Cloud P0C1 — Atomic QR pairing and tenant admission + +**Date:** 2026-11-16 +**Status:** staging-only source + synthetic tests. **No live Cloudflare D1, real desktop WebSocket, remote lock or iOS implementation has been validated.** +**Parent:** P0B Draft PR #3, which builds on P0A Draft PR #2. Do not merge this stacked branch independently of its parents. + +## Implemented in this PR + +- `cloud/migrations/0003_pairing_claim.sql`: **SQLite trigger** inserts an account-owned device in the **same SQL UPDATE** that marks a pending pairing ticket approved. A uniqueness/foreign-key failure aborts the entire statement. Second approval cannot transfer ownership; approved status cannot be reverted. +- `relay/src/cloud/pairingRepository.ts`: generates an opaque random short-lived claim secret; uses the existing P0A schema to store only SHA-256 digests of the claim, desktop polling proof and device credential. Returns a 6-digit visual verification code derived from the QR claim. The code is a display check, **not** an authentication factor. +- Staging-only `/cloud/v1/pairings` create endpoint, `/preview` and `/approve` endpoints requiring a verified iOS account/session, and `/status` endpoint requiring the **separate desktop polling proof**. All requests still require the private test gate from P0B. +- `relay/src/cloud/tenantAdmission.ts`: D1 verified device credential/owner lookup for future WebSocket admission and composition with P0A owner-only `lock` policy. Only the database-derived account ID is eligible as a DO key. **This is NOT a working DO server or public command endpoint.** +- Offline HTTP+SQLite tests for single-use QR, account race, expired claims, invalid proof, duplicate device credentials, 6-digit confirmation, cross-account invisibility and owner-derived route selection. **No device is actually locked in the tests.** + +## Staging-only pairing flow + +1. Desktop creates a 256-bit device credential **and independent 256-bit polling secret** locally; only their SHA-256 hex digests leave the desktop for `POST /cloud/v1/pairings`. Client also submits a newly generated UUID, display name and `macos|windows`. +2. Server inserts pending ticket (5-minute expiry), generates a 256-bit claim secret and returns `ticketId`, `claimSecret`, `verificationCode` and `expiresAtMs`. The desktop shows this ticket/claim secret as a QR code and the verificationCode as six digits. **Never encode the desktop credential or polling secret in the QR.** The QR's secret must not enter URL query parameters, logs, analytics or history. +3. iOS is already signed in. It scans QR, sends `claimSecret` in the JSON body to `POST /cloud/v1/pairings/:ticketId/preview` with its account access token; displays the **server-returned** device name/platform and code. User confirms the code matches the desktop screen. +4. iOS POSTs to `/approve` with bearer access token plus JSON `{claimSecret, confirmedCode}`. SQL UPDATE is constrained on ticket ID, digest, pending status, expiry, active account and absence of existing device. The trigger creates the device row in **that same statement**. A second approving account or replay cannot claim it. +5. Desktop POSTs to `/status` using `{pollSecret}` in JSON (not query parameters). It learns only `pending|approved|expired|rejected`; its secret device credential was always retained locally. On approval the desktop may begin connecting to a **future** device WebSocket endpoint that has not yet been implemented. +6. The same signed-in iOS account can see its approved device in `GET /cloud/v1/devices`; another account sees nothing. Existing P0A owner-only lock authorization remains a separate function, with **no remotely executable command endpoint** yet. + +## HTTP routes (all protected by the internal staging gate) + +| Method/route | Caller | Auth | Result | +|---|---|---|---| +| `POST /cloud/v1/pairings` | Desktop | staging gate (test-only) | New one-time ticket or 409 | +| `POST /cloud/v1/pairings/:id/preview` | iOS | access session + claim secret | Name/platform/code or 404 | +| `POST /cloud/v1/pairings/:id/approve` | iOS | access session + claim secret + confirmed code | Atomic approval, 409/404 failure | +| `POST /cloud/v1/pairings/:id/status` | Desktop | separate polling secret | Non-secret status or 404 | +| `POST /cloud/v1/devices/:id/commands` | iOS | N/A | NOT IMPLEMENTED / 404 | +| `/cloud/v1/ws/device` | Desktop | N/A | NOT IMPLEMENTED / 404 | + +**Important:** The internal staging gate is not a customer authentication system; **never ship it in iOS/desktop apps.** Device creation is untrusted while this gate is the sole admission control; before public launch implement per-IP/device/global rate limits, abuse protection, transport integrity, trusted client onboarding and backend budget controls. + +## Atomic claim correctness + +- Trigger attaches device registration to the same database update so a successful approval cannot be committed without inserting the device, and a failed insert rolls back approval. The ticket stays `pending` on a duplicate credential. +- Approved tickets are immutable, and the partial unique index permits only one outstanding pending ticket per device ID. A new attempt is allowed after expiry, but only when the device ID is not already registered. +- The claimed device's *owner* comes from a **verified account session** used for the update. The credential was generated and retained by the desktop; the D1 credential hash alone must not enable impersonation. +- The 6-digit code checks that both UIs display the same challenge. Since the full QR claim secret can derive that code, it does not protect against a malicious QR that the user voluntarily scans; require clear device name/platform and explicit physical user confirmation. + +## Tenant routing boundary (policy only) + +The next Cloud WS entrypoint must route by looking up device ownership in D1. Device Protocol v1 starts by sending an `auth` frame containing device UUID and credential. A future WebSocket handler **cannot safely route or deliver commands based on a caller-supplied account ID**; it must authenticate the credential and bind the socket to a D1-verified owner, then revalidate on reconnect/revocation/DO restart. + +`authorizeCloudDeviceAdmission` verifies the credential hash and both active device and active account. `authorizeCloudCommandAdmission` validates the signed-in phone session and that device ownership/action are permitted. The resulting `cloudTenantObjectKey` can be derived only from a server-verified admission. These functions do not create or connect a DO, and **no real WebSocket/remote lock feature can be claimed yet**. + +**Protocol v1 compatibility:** no change to existing personal Relay, no arbitrary action, no offline queue, no remote unlock. Keep existing `command`, `auth`, `heartbeat` and `command_result` frames when implementing tenant DO connectivity. + +## Test and release gates + +GitHub CI should run the new `relay/test/cloudStaging.test.ts` integration tests (Node SQLite) as part of `Relay / Protocol`; the existing Cloud Staging Worker dry-run job verifies it bundles but **does not deploy**. In all cases verify the actual workflow results before claiming PASS. + +**Still blocked:** creation/approval on real D1, trigger compatibility on actual Cloudflare deployment, Sign in with Apple on a genuine device, billing/abuse controls, actual tenant DO routing and hibernating WSS, device credential revocation and live disconnect, expiry/heartbeat/replay behavior under DO restart, desktop installer onboarding, native iOS and real OS lock, account deletion, signed binaries and App Store publication. + +## Next: P0C2 + +Implement a distinct Cloudflare-hosted **per-account** Durable Object class and WSS admission protocol with tenant binding and D1 credential check, then a verified command dispatch with correct ownership and 10-second TTL / response correlation. Require two-account adversarial tests, revoked socket test, replay detection, offline no-queue test, DO hibernation/restart test and actual cloud-staging integration. The personal single-operator Durable Object and self-host Dashboard must stay untouched. + +Sources: [P0A security plan](cloud-p0a-security.md) and [P0B identity stage](cloud-p0b-identity.md). Cloudflare D1: https://developers.cloudflare.com/d1/worker-api/d1-database/ . diff --git a/relay/src/cloud/pairingRepository.ts b/relay/src/cloud/pairingRepository.ts new file mode 100644 index 0000000..46bccaa --- /dev/null +++ b/relay/src/cloud/pairingRepository.ts @@ -0,0 +1,160 @@ +import { createHash, randomBytes, randomUUID } from "node:crypto"; +import { isUuid } from "../utils/ids.js"; +import type { CloudD1Database } from "./identityRepository.js"; + +const HEX_DIGEST = /^[a-f0-9]{64}$/; +const RAW_PROOF = /^[A-Za-z0-9_-]{32,128}$/; +const TTL_MS = 5 * 60_000; + +function sha256(value: string): string { + return createHash("sha256").update(value, "utf8").digest("hex"); +} +function newSecret(): string { + return randomBytes(32).toString("base64url"); +} +function validName(name: unknown): name is string { + return typeof name === "string" && name.length >= 1 && + name.length <= 120 && name.trim() === name && name.trim().length > 0; +} +function validTime(nowMs: number): boolean { + return Number.isSafeInteger(nowMs) && nowMs > 0 && nowMs < Number.MAX_SAFE_INTEGER - TTL_MS; +} + +export type CloudPairingRegistration = Readonly<{ + deviceId: string; + deviceName: string; + platform: "macos" | "windows"; + /** SHA-256 of a 256-bit device secret generated and retained on the desktop. */ + deviceCredentialHash: string; + /** SHA-256 of a separate 256-bit polling secret retained only on the desktop. */ + pollSecretHash: string; +}>; + +export type PairingPreview = Readonly<{ + deviceName: string; + platform: "macos" | "windows"; + verificationCode: string; + expiresAtMs: number; +}>; + +/** This code confirms both screens show the same QR claim; it is not a credential. */ +export function pairingVerificationCode(ticketId: string, claimSecret: string): string { + const value = createHash("sha256") + .update(`mote-cloud-pair-code:\0${ticketId}:\0${claimSecret}`, "utf8").digest(); + return String(value.readUInt32BE(0) % 1_000_000).padStart(6, "0"); +} + +export class CloudPairingRepository { + constructor(private readonly db: CloudD1Database) {} + + async create(reg: CloudPairingRegistration, nowMs: number): Promise< + { ticketId: string; claimSecret: string; verificationCode: string; expiresAtMs: number } | null + > { + if (!validTime(nowMs) || !isUuid(reg.deviceId) || + !validName(reg.deviceName) || + (reg.platform !== "macos" && reg.platform !== "windows") || + !HEX_DIGEST.test(reg.deviceCredentialHash) || + !HEX_DIGEST.test(reg.pollSecretHash) || + reg.deviceCredentialHash === reg.pollSecretHash) { + return null; + } + // A previously expired attempt may be replaced; never overwrite an approved + // or still-pending ticket, and never replace an already registered device. + await this.db.prepare( + `UPDATE cloud_pairing_tickets SET status = 'expired' + WHERE device_id = ? AND status = 'pending' AND expires_at_ms <= ?`, + ).bind(reg.deviceId, nowMs).run(); + + const existing = await this.db.prepare( + "SELECT id FROM cloud_devices WHERE id = ?", + ).bind(reg.deviceId).first<{ id: string }>(); + if (existing) return null; + + const ticketId = randomUUID(); + const claimSecret = newSecret(); + const expiresAtMs = nowMs + TTL_MS; + try { + await this.db.prepare( + `INSERT INTO cloud_pairing_tickets + (id, device_id, device_name, device_platform, claim_secret_hash, + poll_secret_hash, device_credential_hash, status, created_at_ms, expires_at_ms) + VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?)`, + ).bind( + ticketId, reg.deviceId, reg.deviceName, reg.platform, + sha256(claimSecret), reg.pollSecretHash, + reg.deviceCredentialHash, nowMs, expiresAtMs, + ).run(); + } catch { + // A concurrent ticket or duplicate ID may win; fail closed. + return null; + } + return { + ticketId, claimSecret, expiresAtMs, + verificationCode: pairingVerificationCode(ticketId, claimSecret), + }; + } + + /** Owner preview requires the server-verified iOS account plus secret. */ + async preview(ticketId: string, claimSecret: string, nowMs: number): Promise { + if (!isUuid(ticketId) || !RAW_PROOF.test(claimSecret) || !validTime(nowMs)) return null; + const row = await this.db.prepare( + `SELECT device_name, device_platform, expires_at_ms + FROM cloud_pairing_tickets + WHERE id = ? AND claim_secret_hash = ? + AND status = 'pending' AND expires_at_ms > ?`, + ).bind(ticketId, sha256(claimSecret), nowMs).first<{ + device_name: string; device_platform: "macos" | "windows"; expires_at_ms: number; + }>(); + if (!row) return null; + return { + deviceName: row.device_name, + platform: row.device_platform, + expiresAtMs: row.expires_at_ms, + verificationCode: pairingVerificationCode(ticketId, claimSecret), + }; + } + + /** + * Single SQL UPDATE, with database trigger atomically inserting the device. + * One winner: a 2nd account, replay, expired ticket or duplicate device + * returns false. Any INSERT constraint failure aborts and rolls back UPDATE. + */ + async approve(ticketId: string, claimSecret: string, accountId: string, nowMs: number): + Promise { + if (!isUuid(ticketId) || !isUuid(accountId) || + !RAW_PROOF.test(claimSecret) || !validTime(nowMs)) return false; + try { + const result = await this.db.prepare( + `UPDATE cloud_pairing_tickets + SET status = 'approved', claimed_by_account_id = ? + WHERE id = ? AND claim_secret_hash = ? + AND status = 'pending' AND expires_at_ms > ? + AND EXISTS (SELECT 1 FROM cloud_accounts + WHERE id = ? AND status = 'active') + AND NOT EXISTS ( + SELECT 1 FROM cloud_devices d + WHERE d.id = cloud_pairing_tickets.device_id + )`, + ).bind(accountId, ticketId, sha256(claimSecret), nowMs, accountId).run(); + return result.meta.changes === 1; + } catch { + // Trigger insertion fails transactionally on revoked/duplicate credential. + return false; + } + } + + /** Desktop-only status: authenticated by its separate 256-bit polling proof. */ + async poll(ticketId: string, pollSecret: string, nowMs: number): + Promise<"pending" | "approved" | "rejected" | "expired" | null> { + if (!isUuid(ticketId) || !RAW_PROOF.test(pollSecret) || !validTime(nowMs)) return null; + const row = await this.db.prepare( + `SELECT status, expires_at_ms FROM cloud_pairing_tickets + WHERE id = ? AND poll_secret_hash = ?`, + ).bind(ticketId, sha256(pollSecret)).first<{ + status: "pending" | "approved" | "rejected" | "expired"; expires_at_ms: number; + }>(); + if (!row) return null; + if (row.status === "pending" && row.expires_at_ms <= nowMs) return "expired"; + return row.status; + } +} diff --git a/relay/src/cloud/stagingWorker.ts b/relay/src/cloud/stagingWorker.ts index 604f3c0..f620bc7 100644 --- a/relay/src/cloud/stagingWorker.ts +++ b/relay/src/cloud/stagingWorker.ts @@ -7,6 +7,7 @@ import { type AppleJwks, } from "./appleIdentity.js"; import { CloudIdentityRepository, type CloudD1Database } from "./identityRepository.js"; +import { CloudPairingRepository } from "./pairingRepository.js"; /** * Entirely separate staging-only Worker entrypoint. The original self-hosted @@ -87,6 +88,7 @@ export function createCloudStagingHandler(deps: HandlerDependencies = {}) { } const nowMs = (deps.now ?? Date.now)(); const repo = new CloudIdentityRepository(env.CLOUD_DB); + const pairing = new CloudPairingRepository(env.CLOUD_DB); try { if (url.pathname === "/cloud/v1/health" && request.method === "GET") { @@ -150,7 +152,62 @@ export function createCloudStagingHandler(deps: HandlerDependencies = {}) { return respond(200, { devices: await repo.listActiveDevices(session.accountId) }); } - // Command dispatch, device WS, pairing and account deletion intentionally + // Staging-only pairing. The gate must never ship in user applications. + // Pairing creation is desktop-internal and subject to pre-public rate-limit + // work. Proof material is only accepted in request bodies, never URLs. + if (url.pathname === "/cloud/v1/pairings" && request.method === "POST") { + const body = await jsonBody(request); + if (typeof body?.deviceId !== "string" || + typeof body.deviceName !== "string" || + (body.platform !== "macos" && body.platform !== "windows") || + typeof body.deviceCredentialHash !== "string" || + typeof body.pollSecretHash !== "string") { + return respond(400, { error: "invalid_request" }); + } + const created = await pairing.create({ + deviceId: body.deviceId, + deviceName: body.deviceName, + platform: body.platform, + deviceCredentialHash: body.deviceCredentialHash, + pollSecretHash: body.pollSecretHash, + }, nowMs); + return created ? respond(201, created) : respond(409, { error: "pairing_unavailable" }); + } + + const pairingPath = /^\/cloud\/v1\/pairings\/([a-f0-9-]{36})\/(preview|approve|status)$/.exec(url.pathname); + if (pairingPath && request.method === "POST") { + const [, ticketId, operation] = pairingPath; + if (!ticketId) return respond(404, { error: "not_found" }); + const body = await jsonBody(request); + if (operation === "status") { + if (typeof body?.pollSecret !== "string") { + return respond(400, { error: "invalid_request" }); + } + const status = await pairing.poll(ticketId, body.pollSecret, nowMs); + return status ? respond(200, { status }) : respond(404, { error: "not_found" }); + } + + const raw = bearerToken(request); + const session = raw ? await repo.authenticateAccess(raw, nowMs) : null; + if (!session) return respond(401, { error: "unauthenticated" }); + if (typeof body?.claimSecret !== "string") { + return respond(400, { error: "invalid_request" }); + } + const preview = await pairing.preview(ticketId, body.claimSecret, nowMs); + if (!preview) return respond(404, { error: "not_found" }); + if (operation === "preview") return respond(200, preview); + + // Explicit visual code confirmation in the iOS pairing UI. + if (body.confirmedCode !== preview.verificationCode) { + return respond(400, { error: "confirmation_required" }); + } + const approved = await pairing.approve( + ticketId, body.claimSecret, session.accountId, nowMs, + ); + return approved ? respond(200, { status: "approved" }) : respond(409, { error: "pairing_unavailable" }); + } + + // Command dispatch, device WebSockets and account deletion intentionally // do NOT exist yet. Never delegate to the personal Relay singleton. return respond(404, { error: "not_found" }); } catch (error) { diff --git a/relay/src/cloud/tenantAdmission.ts b/relay/src/cloud/tenantAdmission.ts new file mode 100644 index 0000000..4268eb4 --- /dev/null +++ b/relay/src/cloud/tenantAdmission.ts @@ -0,0 +1,72 @@ +import { createHash } from "node:crypto"; +import { authorizeCloudLock, type CloudLockAuthorization } from "./authorization.js"; +import { CloudIdentityRepository, type CloudD1Database } from "./identityRepository.js"; +import { isUuid } from "../utils/ids.js"; + +const RAW_PROOF = /^[A-Za-z0-9_-]{32,128}$/; +// Non-serializable proof: only this module can mint a verified admission. +const verifiedAdmissions = new WeakSet(); + +export type VerifiedCloudDeviceAdmission = Readonly<{ + deviceId: string; + /** Authoritative owner from D1, never client-supplied. */ + tenantAccountId: string; +}>; + +/** + * Fail-closed admission decision for a future Cloud device WebSocket. + * Must run before entering any tenant Durable Object, and again after a + * connection restart / credential revocation. It does NOT accept a socket. + * + * The desktop's raw credential MUST be read from the existing v1 "auth" + * frame or another authenticated transport, not a URL query parameter. + */ +export async function authorizeCloudDeviceAdmission( + db: CloudD1Database, + deviceId: string, + rawCredential: string, +): Promise { + if (!isUuid(deviceId) || !RAW_PROOF.test(rawCredential)) return null; + const credentialHash = createHash("sha256").update(rawCredential, "utf8").digest("hex"); + const row = await db.prepare( + `SELECT d.id, d.owner_account_id + FROM cloud_devices d + INNER JOIN cloud_accounts a ON a.id = d.owner_account_id + WHERE d.id = ? AND d.credential_hash = ? + AND d.status = 'active' AND a.status = 'active'`, + ).bind(deviceId, credentialHash).first<{ id: string; owner_account_id: string }>(); + if (!row || !isUuid(row.owner_account_id)) return null; + const admission: VerifiedCloudDeviceAdmission = Object.freeze({ + deviceId: row.id, tenantAccountId: row.owner_account_id, + }); + verifiedAdmissions.add(admission); + return admission; +} + +/** + * Only a verified session can obtain the tenant's name for command dispatch. + * This is a policy/composition function, not the command execution endpoint. + */ +export async function authorizeCloudCommandAdmission( + db: CloudD1Database, + accessToken: string, + deviceId: string, + action: unknown, + nowMs: number, +): Promise { + const identity = new CloudIdentityRepository(db); + const session = await identity.authenticateAccess(accessToken, nowMs); + // Never look up device metadata for unauthenticated callers. + if (!session) return { allowed: false, status: 401, reason: "unauthenticated" }; + const device = isUuid(deviceId) ? await identity.getActiveDevice(deviceId) : null; + return authorizeCloudLock({ session, device, requestedDeviceId: deviceId, requestedAction: action, nowMs }); +} + +/** Use ONLY verified admissions' tenantAccountId as idFromName input. */ +export function cloudTenantObjectKey(admission: VerifiedCloudDeviceAdmission): string { + if (!verifiedAdmissions.has(admission) || + !isUuid(admission.deviceId) || !isUuid(admission.tenantAccountId)) { + throw new Error("Unverified tenant admission."); + } + return `mote-cloud-account:${admission.tenantAccountId}`; +} diff --git a/relay/test/cloudStaging.test.ts b/relay/test/cloudStaging.test.ts index bfc9a16..abc9c67 100644 --- a/relay/test/cloudStaging.test.ts +++ b/relay/test/cloudStaging.test.ts @@ -1,11 +1,12 @@ import assert from "node:assert/strict"; -import { generateKeyPairSync, sign } from "node:crypto"; +import { createHash, generateKeyPairSync, sign } from "node:crypto"; import { readFileSync } from "node:fs"; import { DatabaseSync, type SQLInputValue } from "node:sqlite"; import test from "node:test"; import type { AppleJwks } from "../src/cloud/appleIdentity.js"; import type { CloudD1Database, CloudD1Statement } from "../src/cloud/identityRepository.js"; +import { authorizeCloudCommandAdmission, authorizeCloudDeviceAdmission, cloudTenantObjectKey } from "../src/cloud/tenantAdmission.js"; import { createCloudStagingHandler, type CloudStagingEnv, @@ -21,6 +22,7 @@ const audience = "com.nardo021.mote.testing.ios"; const gate = "test-only-private-staging-gate-not-for-apps"; const db1 = readFileSync(new URL("../../cloud/migrations/0001_core.sql", import.meta.url), "utf8"); const db2 = readFileSync(new URL("../../cloud/migrations/0002_auth.sql", import.meta.url), "utf8"); +const db3 = readFileSync(new URL("../../cloud/migrations/0003_pairing_claim.sql", import.meta.url), "utf8"); class SqliteStatement implements CloudD1Statement { constructor( @@ -47,6 +49,7 @@ function newDb(): { raw: DatabaseSync; binding: CloudD1Database } { raw.exec("PRAGMA foreign_keys = ON"); raw.exec(db1); raw.exec(db2); + raw.exec(db3); return { raw, binding: { prepare: (sql) => new SqliteStatement(raw, sql) } }; } @@ -110,7 +113,7 @@ test("staging Worker fails closed if not explicitly enabled or gate is invalid", status: 200, body: { service: "mote-cloud", status: "staging" }, }); assert.equal((await request("/cloud/v1/devices")).status, 401); - assert.equal((await request("/cloud/v1/pairings", "POST", {})).status, 404); + assert.equal((await request("/cloud/v1/pairings", "POST", {})).status, 400); } finally { raw.close(); } }); @@ -181,3 +184,212 @@ test("refresh rotation invalidates old credentials, logout revokes, disabled acc assert.equal((await request("/cloud/v1/me", "GET", undefined, another.accessToken)).status, 401); } finally { raw.close(); } }); + +function sha256(value: string): string { + return createHash("sha256").update(value, "utf8").digest("hex"); +} +function desktopRegistration(deviceId = "44444444-4444-4444-8444-444444444444") { + const deviceSecret = "desktop-device-credential-" + "d".repeat(43); + const pollSecret = "desktop-only-poll-secret-" + "p".repeat(43); + return { + deviceSecret, + pollSecret, + registration: { + deviceId, + deviceName: "Mote Test Windows", + platform: "windows", + deviceCredentialHash: sha256(deviceSecret), + pollSecretHash: sha256(pollSecret), + }, + }; +} + +test("desktop creates QR; signed-in iOS user previews and approves; only owner sees device", async () => { + const { raw, request, signIn } = harness(); + try { + const a = (await signIn("owner-a")).login; + const b = (await signIn("owner-b")).login; + const desktop = desktopRegistration(); + const created = await request("/cloud/v1/pairings", "POST", desktop.registration); + assert.equal(created.status, 201); + const { ticketId, claimSecret, verificationCode } = created.body; + assert.equal(typeof claimSecret, "string"); + assert.match(verificationCode, /^\d{6}$/); + assert.equal((await request(`/cloud/v1/pairings/${ticketId}/preview`, "POST", { + claimSecret: "wrong-secret-" + "a".repeat(43), + }, a.accessToken)).status, 404); + assert.equal((await request(`/cloud/v1/pairings/${ticketId}/preview`, "POST", { + claimSecret, + })).status, 401); + + const preview = await request(`/cloud/v1/pairings/${ticketId}/preview`, "POST", { + claimSecret, + }, a.accessToken); + assert.equal(preview.status, 200); + assert.equal(preview.body.verificationCode, verificationCode); + assert.equal(preview.body.deviceName, desktop.registration.deviceName); + assert.equal((await request(`/cloud/v1/pairings/${ticketId}/approve`, "POST", { + claimSecret, confirmedCode: "000000" === verificationCode ? "999999" : "000000", + }, a.accessToken)).status, 400); + + const approved = await request(`/cloud/v1/pairings/${ticketId}/approve`, "POST", { + claimSecret, confirmedCode: verificationCode, + }, a.accessToken); + assert.deepEqual(approved, { status: 200, body: { status: "approved" } }); + assert.equal((await request(`/cloud/v1/pairings/${ticketId}/status`, "POST", { + pollSecret: desktop.pollSecret, + })).body.status, "approved"); + assert.equal((await request(`/cloud/v1/pairings/${ticketId}/status`, "POST", { + pollSecret: "other-secret-" + "x".repeat(43), + })).status, 404); + const listA = await request("/cloud/v1/devices", "GET", undefined, a.accessToken); + const listB = await request("/cloud/v1/devices", "GET", undefined, b.accessToken); + assert.equal(listA.body.devices.length, 1); + assert.equal(listB.body.devices.length, 0); + assert.equal(listA.body.devices[0].id, desktop.registration.deviceId); + assert.equal(JSON.stringify(listA.body).includes("hash"), false); + const hashRow = raw.prepare("SELECT credential_hash FROM cloud_devices WHERE id = ?") + .get(desktop.registration.deviceId) as { credential_hash: string }; + assert.equal(hashRow.credential_hash, desktop.registration.deviceCredentialHash); + assert.equal(JSON.stringify(created.body).includes(desktop.registration.deviceCredentialHash), false); + } finally { raw.close(); } +}); + +test("two accounts racing for same QR have one winner; replay never transfers ownership", async () => { + const { raw, request, signIn } = harness(); + try { + const a = (await signIn("race-a")).login; + const b = (await signIn("race-b")).login; + const desktop = desktopRegistration(); + const created = await request("/cloud/v1/pairings", "POST", desktop.registration); + assert.equal(created.status, 201); + const path = `/cloud/v1/pairings/${created.body.ticketId}/approve`; + const proof = { + claimSecret: created.body.claimSecret, + confirmedCode: created.body.verificationCode, + }; + const [first, second] = await Promise.all([ + request(path, "POST", proof, a.accessToken), + request(path, "POST", proof, b.accessToken), + ]); + assert.equal([first.status, second.status].filter(x => x === 200).length, 1); + assert.equal([first.status, second.status].filter(x => x !== 200).length, 1); + const row = raw.prepare( + "SELECT owner_account_id FROM cloud_devices WHERE id = ?", + ).get(desktop.registration.deviceId) as { owner_account_id: string }; + assert.ok(row.owner_account_id === a.accountId || row.owner_account_id === b.accountId); + assert.equal((await request(path, "POST", proof, a.accessToken)).status, 404); + assert.equal((await request(path, "POST", proof, b.accessToken)).status, 404); + assert.equal((await request("/cloud/v1/pairings", "POST", desktop.registration)).status, 409); + assert.equal( + (raw.prepare("SELECT count(*) AS n FROM cloud_devices").get() as { n: number }).n, 1, + ); + } finally { raw.close(); } +}); + +test("expired ticket, malformed data and credential collisions do not create orphan devices", async () => { + const { raw, request, signIn } = harness(); + try { + const a = (await signIn("expiration-owner")).login; + const first = desktopRegistration(); + const created = await request("/cloud/v1/pairings", "POST", first.registration); + assert.equal(created.status, 201); + const expiredAt = nowMs - 1; + raw.prepare("UPDATE cloud_pairing_tickets SET created_at_ms = ?, expires_at_ms = ? WHERE id = ?") + .run(nowMs - 10 * 60_000, expiredAt, created.body.ticketId); + const approve = await request(`/cloud/v1/pairings/${created.body.ticketId}/approve`, "POST", { + claimSecret: created.body.claimSecret, + confirmedCode: created.body.verificationCode, + }, a.accessToken); + assert.equal(approve.status, 404); + assert.deepEqual(await request(`/cloud/v1/pairings/${created.body.ticketId}/status`, "POST", { + pollSecret: first.pollSecret, + }), { status: 200, body: { status: "expired" } }); + + const replacement = await request("/cloud/v1/pairings", "POST", first.registration); + assert.equal(replacement.status, 201); + const approved = await request(`/cloud/v1/pairings/${replacement.body.ticketId}/approve`, "POST", { + claimSecret: replacement.body.claimSecret, confirmedCode: replacement.body.verificationCode, + }, a.accessToken); + assert.equal(approved.status, 200); + + const collision = desktopRegistration("55555555-5555-4555-8555-555555555555"); + const duplicateHash = await request("/cloud/v1/pairings", "POST", { + ...collision.registration, + deviceCredentialHash: first.registration.deviceCredentialHash, + }); + assert.equal(duplicateHash.status, 201); + const rejected = await request(`/cloud/v1/pairings/${duplicateHash.body.ticketId}/approve`, "POST", { + claimSecret: duplicateHash.body.claimSecret, + confirmedCode: duplicateHash.body.verificationCode, + }, a.accessToken); + assert.equal(rejected.status, 409); + assert.equal( + (raw.prepare("SELECT status FROM cloud_pairing_tickets WHERE id = ?") + .get(duplicateHash.body.ticketId) as { status: string }).status, + "pending", + ); + assert.equal( + (raw.prepare("SELECT count(*) AS n FROM cloud_devices").get() as { n: number }).n, 1, + ); + + assert.equal((await request("/cloud/v1/pairings", "POST", { + ...collision.registration, deviceCredentialHash: "short", + })).status, 409); + assert.equal((await request("/cloud/v1/pairings", "POST", { + ...collision.registration, platform: "linux", + })).status, 400); + } finally { raw.close(); } +}); + +test("tenant admissions use the server-owned account and device secret, not caller-supplied owner", async () => { + const { raw, env, request, signIn } = harness(); + try { + const a = (await signIn("socket-owner-a")).login; + const b = (await signIn("socket-owner-b")).login; + const desktop = desktopRegistration(); + const ticket = await request("/cloud/v1/pairings", "POST", desktop.registration); + assert.equal(ticket.status, 201); + assert.equal((await request(`/cloud/v1/pairings/${ticket.body.ticketId}/approve`, "POST", { + claimSecret: ticket.body.claimSecret, confirmedCode: ticket.body.verificationCode, + }, a.accessToken)).status, 200); + const db = env.CLOUD_DB!; + const admitted = await authorizeCloudDeviceAdmission(db, desktop.registration.deviceId, desktop.deviceSecret); + assert.ok(admitted); + assert.equal(admitted?.tenantAccountId, a.accountId); + assert.equal(cloudTenantObjectKey(admitted!), `mote-cloud-account:${a.accountId}`); + assert.throws(() => cloudTenantObjectKey({ ...admitted! }), /Unverified tenant admission/); + assert.equal(await authorizeCloudDeviceAdmission(db, desktop.registration.deviceId, b.accessToken), null); + assert.equal(await authorizeCloudDeviceAdmission(db, desktop.registration.deviceId, "wrong"), null); + assert.equal(await authorizeCloudDeviceAdmission(db, b.accountId, desktop.deviceSecret), null); + + const ownerCommand = await authorizeCloudCommandAdmission( + db, a.accessToken, desktop.registration.deviceId, "lock", nowMs, + ); + assert.deepEqual(ownerCommand, { + allowed: true, deviceId: desktop.registration.deviceId, + tenantAccountId: a.accountId, action: "lock", + }); + assert.deepEqual(await authorizeCloudCommandAdmission( + db, b.accessToken, desktop.registration.deviceId, "lock", nowMs, + ), { allowed: false, status: 404, reason: "not_found" }); + assert.deepEqual(await authorizeCloudCommandAdmission( + db, a.accessToken, desktop.registration.deviceId, "unlock", nowMs, + ), { allowed: false, status: 422, reason: "unsupported_action" }); + + raw.prepare("UPDATE cloud_devices SET status = 'revoked' WHERE id = ?") + .run(desktop.registration.deviceId); + assert.equal(await authorizeCloudDeviceAdmission(db, desktop.registration.deviceId, desktop.deviceSecret), null); + assert.deepEqual(await authorizeCloudCommandAdmission( + db, a.accessToken, desktop.registration.deviceId, "lock", nowMs, + ), { allowed: false, status: 404, reason: "not_found" }); + raw.prepare("UPDATE cloud_devices SET status = 'active' WHERE id = ?") + .run(desktop.registration.deviceId); + raw.prepare("UPDATE cloud_accounts SET status = 'disabled' WHERE id = ?") + .run(a.accountId); + assert.equal(await authorizeCloudDeviceAdmission(db, desktop.registration.deviceId, desktop.deviceSecret), null); + assert.deepEqual(await authorizeCloudCommandAdmission( + db, a.accessToken, desktop.registration.deviceId, "lock", nowMs, + ), { allowed: false, status: 401, reason: "unauthenticated" }); + } finally { raw.close(); } +});