Skip to content
Draft
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
40 changes: 40 additions & 0 deletions cloud/migrations/0003_pairing_claim.sql
Original file line number Diff line number Diff line change
@@ -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;
62 changes: 62 additions & 0 deletions docs/cloud-p0c1-pairing.md
Original file line number Diff line number Diff line change
@@ -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/ .
160 changes: 160 additions & 0 deletions relay/src/cloud/pairingRepository.ts
Original file line number Diff line number Diff line change
@@ -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<PairingPreview | null> {
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<boolean> {
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;
}
}
Loading
Loading