diff --git a/cloud/migrations/0001_core.sql b/cloud/migrations/0001_core.sql new file mode 100644 index 0000000..8f653f2 --- /dev/null +++ b/cloud/migrations/0001_core.sql @@ -0,0 +1,77 @@ +-- Proposed initial schema for the NEW hosted Mote Cloud D1 database. +-- IMPORTANT: Do NOT run against the self-hosted Durable Object SQLite. +-- The existing Mote Protocol v1 and single-user storage stay unchanged. +-- +-- Apply to an isolated staging database only after hosted Worker bindings, +-- rollback instructions, identity verification and claim transaction tests +-- have been reviewed. This is a schema scaffold, not a deployed migration. + +CREATE TABLE cloud_accounts ( + id TEXT PRIMARY KEY NOT NULL, + apple_subject TEXT NOT NULL UNIQUE, + status TEXT NOT NULL DEFAULT 'active' + CHECK (status IN ('active', 'disabled', 'deleting')), + created_at_ms INTEGER NOT NULL CHECK (created_at_ms > 0) +); + +CREATE TABLE cloud_sessions ( + id TEXT PRIMARY KEY NOT NULL, + account_id TEXT NOT NULL REFERENCES cloud_accounts(id) ON DELETE CASCADE, + refresh_token_hash TEXT NOT NULL UNIQUE CHECK (length(refresh_token_hash) = 64), + created_at_ms INTEGER NOT NULL CHECK (created_at_ms > 0), + expires_at_ms INTEGER NOT NULL, + revoked_at_ms INTEGER, + CHECK (expires_at_ms > created_at_ms), + CHECK (revoked_at_ms IS NULL OR revoked_at_ms >= created_at_ms) +); + +CREATE INDEX idx_cloud_sessions_account ON cloud_sessions(account_id); +CREATE INDEX idx_cloud_sessions_expires ON cloud_sessions(expires_at_ms); + +CREATE TABLE cloud_devices ( + id TEXT PRIMARY KEY NOT NULL, + owner_account_id TEXT NOT NULL REFERENCES cloud_accounts(id) ON DELETE CASCADE, + name TEXT NOT NULL CHECK (length(name) BETWEEN 1 AND 120), + platform TEXT NOT NULL CHECK (platform IN ('macos', 'windows')), + credential_hash TEXT NOT NULL UNIQUE CHECK (length(credential_hash) = 64), + status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'revoked')), + created_at_ms INTEGER NOT NULL CHECK (created_at_ms > 0), + updated_at_ms INTEGER NOT NULL CHECK (updated_at_ms >= created_at_ms) +); + +CREATE INDEX idx_cloud_devices_owner_status + ON cloud_devices(owner_account_id, status); + +-- Device produces its own random device credential and polling proof locally. +-- It sends only SHA-256 digests to this service. A short-lived claim secret +-- (shown in an iOS-scannable QR) is likewise stored only as a digest. +-- +-- For account approval, implement an atomic D1 transaction that: +-- 1. Validates the ticket digest, pending state and expiry. +-- 2. Inserts exactly one owned cloud_devices row with the committed hash. +-- 3. Marks the ticket approved for the same account. +-- Any uniqueness failure or zero matching pending ticket aborts the claim. +-- Desktop checks status with the separate polling proof. No plaintext device +-- credential may be returned from any endpoint or written to D1. +CREATE TABLE cloud_pairing_tickets ( + id TEXT PRIMARY KEY NOT NULL, + device_id TEXT NOT NULL, + device_name TEXT NOT NULL CHECK (length(device_name) BETWEEN 1 AND 120), + device_platform TEXT NOT NULL CHECK (device_platform IN ('macos', 'windows')), + claim_secret_hash TEXT NOT NULL CHECK (length(claim_secret_hash) = 64), + poll_secret_hash TEXT NOT NULL CHECK (length(poll_secret_hash) = 64), + device_credential_hash TEXT NOT NULL CHECK (length(device_credential_hash) = 64), + status TEXT NOT NULL DEFAULT 'pending' + CHECK (status IN ('pending', 'approved', 'rejected', 'expired')), + claimed_by_account_id TEXT REFERENCES cloud_accounts(id) ON DELETE CASCADE, + created_at_ms INTEGER NOT NULL CHECK (created_at_ms > 0), + expires_at_ms INTEGER NOT NULL CHECK (expires_at_ms > created_at_ms), + CHECK ( + (status = 'approved' AND claimed_by_account_id IS NOT NULL) + OR (status <> 'approved' AND claimed_by_account_id IS NULL) + ) +); + +CREATE UNIQUE INDEX idx_cloud_pairing_one_pending_device + ON cloud_pairing_tickets(device_id) WHERE status = 'pending'; +CREATE INDEX idx_cloud_pairing_expiry ON cloud_pairing_tickets(status, expires_at_ms); diff --git a/docs/cloud-p0a-security.md b/docs/cloud-p0a-security.md new file mode 100644 index 0000000..a44da9b --- /dev/null +++ b/docs/cloud-p0a-security.md @@ -0,0 +1,95 @@ +# Mote Cloud P0A — Account ownership and pairing security contract + +**Status: PARTIAL / SOURCE ONLY** +2026-11-16 — branch `feature/mote-cloud-p0a-20261116`, based on `mote-v2`. + +This document describes the security boundary for the planned public zero-configuration Mote Cloud. **No hosted API, public registration, Apple token verification, Durable Object tenant routing, database migration, or deployment is activated by this PR.** The existing single-operator Worker, self-host pairing and Protocol v1 are unchanged. + +## Completed scope in this PR + +- `relay/src/cloud/authorization.ts` defines a fail-closed `lock` policy that evaluates a **trusted, already verified** hosted session and an **authoritative D1 owned-device row**. It returns the database-derived `tenantAccountId` routing key only for an active owned device. +- `relay/test/cloudAuthorization.test.ts` checks owner, missing/foreign/revoked device indistinguishability, session expiry/revocation/disabled state, target mismatch and rejection of all actions except `lock`. +- `cloud/migrations/0001_core.sql` defines a **separate future hosted D1 database** with Apple identity subjects, refresh sessions, per-device owner/credential hashes and short-lived pairing tickets. It must never be applied to the existing personal Durable Object storage. +- `relay/test/cloudSchema.test.ts` exercises the schema using built-in SQLite, including uniqueness, foreign keys, one outstanding pairing ticket per device and account-deletion cascades. This is not a substitute for a real D1 staging migration test. + +## Trust boundaries + +1. The account/session passed to `authorizeCloudLock` must originate from an actual **server-verified Sign in with Apple identity** and a currently live D1 session. The interface alone is **not an authentication mechanism**. Never construct a session from request JSON, a query parameter, a self-asserted user ID or an unverified JWT. +2. Resolve the target device by ID from D1 on every command. Permission checks must verify *owner account ID*, *active account/session*, *active device* and *action allowlist* BEFORE accessing the account's Durable Object. Cross-account, non-existent and revoked-device requests must have indistinguishable 404 responses. +3. Use the **D1 device row's owner ID**, not a caller-controlled account query or an unverified JWT claim, as the Durable Object key. On WebSocket authentication repeat credential, device state, ownership and tenant checks. On command response, bind the response to the original authenticated device socket and command ID. +4. A session's expiry is insufficient for revocation. The D1 session must be checked for revocation and account status at every sensitive operation. On account deletion, revoke device credentials and close connected sockets; failing closed is preferable to a stale allowed command. +5. Only `lock` is permitted. Maintain Protocol v1's command TTL (10 seconds by default), replay protections, no offline command queue, and no arbitrary scripts or remote unlock. +6. Errors must not include foreign device name, owner account, platform, presence or timestamps. + +## Proposed hosted API contracts (not implemented) + +All APIs below are **future Cloud-only** endpoints; the existing self-host `/v1/*` API stays as-is. + +| Method / route | Caller | Essential checks | +|---|---|---| +| `POST /cloud/v1/auth/apple` | iOS | Verify Apple JWT signature, issuer/audience/nonce and expiry; create or locate account | +| `POST /cloud/v1/session/refresh` | iOS | Verify and rotate hashed refresh session; prevent replay | +| `GET /cloud/v1/devices` | iOS | Return only devices owned by session account | +| `POST /cloud/v1/pairings` | Desktop | Enforce rate limits, random hashes, expiry and device ID uniqueness | +| `POST /cloud/v1/pairings/:id/approve` | iOS | Validate session, one-time QR claim proof, matching code, not expired; atomic claim | +| `GET /cloud/v1/pairings/:id` | Desktop | Authenticate **separate polling proof**; never return device secret | +| `POST /cloud/v1/devices/:id/commands` | iOS | Authorize requested lock against DB ownership before routing to owner's DO | +| `DELETE /cloud/v1/devices/:id` | iOS | Owner-only revoke and live socket disconnect | +| `DELETE /cloud/v1/account` | iOS | Revoke all sessions/devices, invalidate DO connections, complete deletion process | + +Consider a separate `/cloud/v1/ws/device` for hosted agents; reuse the **Protocol v1 frame format**, not the self-host credential store. Disable every Cloud route unless full auth and tenant routing is active. A future staging Worker must use isolated bindings/secrets and must not expose the legacy `idFromName("mote")` DO. + +## Zero-config pairing protocol proposal + +This protocol is **not implemented**; its state transitions and concurrency require live integration tests. + +1. A new Mac/Windows agent chooses Mote Cloud by default from signed application configuration; it generates a persistent UUID, a 256-bit device credential and a different random polling proof on the device. It sends only secure digests and a name/platform to the rate-limited Cloud pairing endpoint. +2. The server creates a fresh random short-lived QR claim secret and ticket. D1 holds only the `claim_secret_hash`, `poll_secret_hash` and `device_credential_hash`, never plaintext device keys. The returned QR encodes the one-time ticket ID and claim secret, **not** a permanent device credential. Desktop retains its private proofs. +3. The already signed-in iOS App scans the QR, fetches a constrained device name and platform, and displays a matching code/confirmation step. The logged-in user explicitly approves. The server checks ticket digest, expiry, pending state and session validity. +4. Approval is **atomic**: claim ticket exactly once and register the device with the account and its committed device credential digest in one D1 transaction. Replayed/expired QR, duplicate device ID and concurrent competing claims all fail closed. Cloudflare documents D1 `batch()` as transactional, but implement only after validating the exact SQL and zero-matched-row behavior. +5. Desktop polls with its separate secret, sees confirmation and begins the existing authenticated Protocol v1 device WebSocket against the account-authorized Cloud service. The server never transports the plaintext device credential to iPhone or another machine. +6. If the device has no approval by expiry, show **Try again** and generate a new challenge. Already registered device IDs cannot be silently re-paired; removal or explicit credential rotation requires owner action. + +### Explicit abuse and failure cases to test in P0B + +- Two accounts attempt to claim the same ticket concurrently: **only one owned device**, one durable owner. +- A replayed QR/ticket cannot attach a second device or change ownership. +- A claimed ticket's polling proof cannot be replaced with another desktop's proof. +- A stolen refresh credential cannot keep working after rotation; access tokens expire and session revocation is honored. +- Unknown/foreign/revoked device IDs are indistinguishable to the requester. +- A device disconnect/DO eviction cannot cause a pending lock to execute late. +- Deleting an account and revoking a device must invalidate open WebSockets, not just D1 rows. +- Rate limits cover unauthenticated pairing, QR approval and account bootstrap separately. No unbounded unauthenticated write path. +- Secrets, full Apple ID tokens, one-time pairing proofs and device identifiers should be redacted from application event logs. + +## Why this is deliberately not yet the full Cloud implementation + +The `mote-v2` app is a **personal single-Durable-Object Relay**. Adding an `account_id` field to its own database or changing `idFromName("mote")` to a user-controlled key would be insecure. Before exposing any hosted endpoint, implement: + +- A **new** Worker deployment and D1 binding with replayable staged migrations and rollback plan. +- Apple's signed identity verification, session storage/rotation/revocation, and account deletion lifecycle. +- Real D1 atomic pairing and comprehensive two-account adversarial E2E tests. +- Per-account DO isolation and fresh ownership checks on both command dispatch and device socket admission. +- Bounded work/cost limits, visibility of errors, recovery from DO hibernation/eviction and resource billing tests. + +## CI and validation + +From a normal checkout of this branch: + +```bash +npm ci +npm ci --prefix relay +npm test --prefix relay +npm run typecheck --prefix relay +npm run worker:dry-run +``` + +The Relay test glob automatically includes `cloudAuthorization.test.ts` and `cloudSchema.test.ts`. Those test files do **not** contact Cloudflare, lock a desktop or deploy a Worker. + +**Unverified until CI:** tests and typecheck must pass in an actual GitHub Actions run. **Not claimed:** D1 staging, Sign in with Apple, live desktop pairing, real iOS, tenant isolation across DOs, App Store readiness. + +## Next narrow PR (P0B) + +Implement staged Cloud-only identity/session verification and the D1 ownership repository behind a separate Worker configuration. Add two-account integration tests. Keep public route exposure disabled until P0C pairing and tenant-isolated DO routing tests pass. Align iOS Cloud-first UI with the hosted API contract, while maintaining the advanced self-host UI as a distinct credential profile. + +Source of truth: [Mote public launch roadmap (Draft PR #1)](https://github.com/Nardo021/Mote/pull/1). See the existing [self-host security document](security.md) for Protocol v1 and personal Relay credential roles. diff --git a/relay/src/cloud/authorization.ts b/relay/src/cloud/authorization.ts new file mode 100644 index 0000000..b6144ed --- /dev/null +++ b/relay/src/cloud/authorization.ts @@ -0,0 +1,92 @@ +import { isUuid } from "../utils/ids.js"; + +/** + * These values MUST come from a trusted session lookup and D1 ownership query. + * Do not construct them from JSON, URL parameters, headers or decoded (but + * unverified) identity tokens. + */ +export type AuthenticatedCloudSession = Readonly<{ + accountId: string; + sessionId: string; + expiresAtMs: number; + revokedAtMs: number | null; + accountStatus: "active" | "disabled"; +}>; + +export type OwnedCloudDevice = Readonly<{ + id: string; + ownerAccountId: string; + status: "active" | "revoked"; +}>; + +export type CloudLockAuthorization = + | Readonly<{ + allowed: true; + deviceId: string; + tenantAccountId: string; + action: "lock"; + }> + | Readonly<{ + allowed: false; + status: 401 | 404 | 422; + reason: "unauthenticated" | "not_found" | "unsupported_action"; + }>; + +export type CloudLockRequest = Readonly<{ + /** Resolved from verified, non-revoked login, never the request body. */ + session: AuthenticatedCloudSession | null; + /** Resolved from the hosted device database, never from the request body. */ + device: OwnedCloudDevice | null; + requestedDeviceId: string; + requestedAction: unknown; + nowMs: number; +}>; + +/** + * Fail-closed policy for the hosted API. This does not authenticate callers, + * access D1 or dispatch a command: those boundaries need their own tests. + * + * Check the owner and device state BEFORE validating the action so that a + * cross-account request cannot distinguish another user's device metadata. + * The resulting DO routing key is taken from the database row, not user input. + */ +export function authorizeCloudLock(request: CloudLockRequest): CloudLockAuthorization { + const { session, device, requestedDeviceId, requestedAction, nowMs } = request; + if ( + session === null || + !isUuid(session.accountId) || + !isUuid(session.sessionId) || + session.accountStatus !== "active" || + session.revokedAtMs !== null || + !Number.isSafeInteger(session.expiresAtMs) || + !Number.isSafeInteger(nowMs) || + nowMs < 0 || + session.expiresAtMs <= nowMs + ) { + return { allowed: false, status: 401, reason: "unauthenticated" }; + } + + if ( + !isUuid(requestedDeviceId) || + device === null || + !isUuid(device.id) || + !isUuid(device.ownerAccountId) || + device.id !== requestedDeviceId || + device.ownerAccountId !== session.accountId || + device.status !== "active" + ) { + // Do not differentiate a missing device from another tenant's device. + return { allowed: false, status: 404, reason: "not_found" }; + } + + if (requestedAction !== "lock") { + return { allowed: false, status: 422, reason: "unsupported_action" }; + } + + return { + allowed: true, + deviceId: device.id, + tenantAccountId: device.ownerAccountId, + action: "lock", + }; +} diff --git a/relay/test/cloudAuthorization.test.ts b/relay/test/cloudAuthorization.test.ts new file mode 100644 index 0000000..92948f4 --- /dev/null +++ b/relay/test/cloudAuthorization.test.ts @@ -0,0 +1,121 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + authorizeCloudLock, + type AuthenticatedCloudSession, + type CloudLockRequest, + type OwnedCloudDevice, +} from "../src/cloud/authorization.js"; + +const accountA = "11111111-1111-4111-8111-111111111111"; +const accountB = "22222222-2222-4222-8222-222222222222"; +const sessionId = "33333333-3333-4333-8333-333333333333"; +const deviceId = "44444444-4444-4444-8444-444444444444"; +const otherDeviceId = "55555555-5555-4555-8555-555555555555"; + +const session: AuthenticatedCloudSession = { + accountId: accountA, + sessionId, + expiresAtMs: 20_000, + revokedAtMs: null, + accountStatus: "active", +}; +const device: OwnedCloudDevice = { + id: deviceId, + ownerAccountId: accountA, + status: "active", +}; +const valid: CloudLockRequest = { + session, + device, + requestedDeviceId: deviceId, + requestedAction: "lock", + nowMs: 10_000, +}; + +test("allows exactly lock on an active account-owned device", () => { + assert.deepEqual(authorizeCloudLock(valid), { + allowed: true, + deviceId, + tenantAccountId: accountA, + action: "lock", + }); +}); + +test("rejects absent, expired and revoked sessions before looking up a device", () => { + const blocked: CloudLockRequest[] = [ + { ...valid, session: null }, + { ...valid, nowMs: 20_000 }, + { ...valid, session: { ...session, revokedAtMs: 9_000 } }, + { ...valid, session: { ...session, accountStatus: "disabled" } }, + { ...valid, session: { ...session, accountId: "not-a-uuid" } }, + { ...valid, session: { ...session, sessionId: "not-a-uuid" } }, + { ...valid, nowMs: Number.NaN }, + ]; + for (const request of blocked) { + assert.deepEqual(authorizeCloudLock(request), { + allowed: false, + status: 401, + reason: "unauthenticated", + }); + } +}); + +test("does not reveal whether another account's device exists", () => { + const foreignDevice: OwnedCloudDevice = { ...device, ownerAccountId: accountB }; + const missing = authorizeCloudLock({ ...valid, device: null }); + const crossAccount = authorizeCloudLock({ ...valid, device: foreignDevice }); + const disabled = authorizeCloudLock({ + ...valid, + device: { ...device, status: "revoked" }, + }); + const targetMismatch = authorizeCloudLock({ ...valid, requestedDeviceId: otherDeviceId }); + const malformedTarget = authorizeCloudLock({ ...valid, requestedDeviceId: "__proto__" }); + const expected = { allowed: false, status: 404, reason: "not_found" }; + for (const result of [missing, crossAccount, disabled, targetMismatch, malformedTarget]) { + assert.deepEqual(result, expected); + } +}); + +test("rejects remote unlock, shell-like and unknown actions even for the owner", () => { + for (const requestedAction of [ + "unlock", + "sleep", + "powershell -Command Start-Process", + { action: "lock" }, + null, + "", + ]) { + assert.deepEqual(authorizeCloudLock({ ...valid, requestedAction }), { + allowed: false, + status: 422, + reason: "unsupported_action", + }); + } +}); + +test("checks account ownership before unsupported action so foreign devices remain opaque", () => { + assert.deepEqual( + authorizeCloudLock({ + ...valid, + device: { ...device, ownerAccountId: accountB }, + requestedAction: "unlock", + }), + { allowed: false, status: 404, reason: "not_found" }, + ); +}); + +test("does not route to a requester-supplied account or device ID", () => { + const result = authorizeCloudLock({ + ...valid, + session: { ...session, accountId: accountB }, + }); + assert.deepEqual(result, { allowed: false, status: 404, reason: "not_found" }); + const owned = authorizeCloudLock(valid); + assert.equal(owned.allowed, true); + if (owned.allowed) { + assert.equal(owned.tenantAccountId, device.ownerAccountId); + assert.equal(owned.deviceId, device.id); + } +}); diff --git a/relay/test/cloudSchema.test.ts b/relay/test/cloudSchema.test.ts new file mode 100644 index 0000000..dc2e26e --- /dev/null +++ b/relay/test/cloudSchema.test.ts @@ -0,0 +1,126 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { DatabaseSync } from "node:sqlite"; +import test from "node:test"; + +const schema = readFileSync( + new URL("../../cloud/migrations/0001_core.sql", import.meta.url), + "utf8", +); + +const accountId = "11111111-1111-4111-8111-111111111111"; +const otherAccountId = "22222222-2222-4222-8222-222222222222"; +const deviceId = "44444444-4444-4444-8444-444444444444"; +const shaA = "a".repeat(64); +const shaB = "b".repeat(64); +const shaC = "c".repeat(64); + +function database(): DatabaseSync { + const db = new DatabaseSync(":memory:"); + db.exec("PRAGMA foreign_keys = ON"); + db.exec(schema); + db.prepare( + "INSERT INTO cloud_accounts(id, apple_subject, created_at_ms) VALUES(?, ?, ?)", + ).run(accountId, "apple-a", 1_000); + db.prepare( + "INSERT INTO cloud_accounts(id, apple_subject, created_at_ms) VALUES(?, ?, ?)", + ).run(otherAccountId, "apple-b", 1_000); + return db; +} + +test("hosted D1 schema is valid SQLite and enforces Apple identity uniqueness", () => { + const db = database(); + try { + assert.throws(() => { + db.prepare( + "INSERT INTO cloud_accounts(id, apple_subject, created_at_ms) VALUES(?, ?, ?)", + ).run("88888888-8888-4888-8888-888888888888", "apple-a", 1_000); + }); + } finally { + db.close(); + } +}); + +test("device ownership and credential hashes enforce foreign keys and uniqueness", () => { + const db = database(); + try { + const insert = db.prepare( + `INSERT INTO cloud_devices + (id, owner_account_id, name, platform, credential_hash, created_at_ms, updated_at_ms) + VALUES (?, ?, ?, ?, ?, ?, ?)`, + ); + assert.throws(() => + insert.run(deviceId, "missing-account", "PC", "windows", shaA, 1_000, 1_000), + ); + insert.run(deviceId, accountId, "PC", "windows", shaA, 1_000, 1_000); + assert.throws(() => + insert.run("55555555-5555-4555-8555-555555555555", otherAccountId, "Mac", "macos", shaA, 1_000, 1_000), + ); + assert.throws(() => + insert.run("55555555-5555-4555-8555-555555555555", otherAccountId, "Mac", "linux", shaB, 1_000, 1_000), + ); + assert.equal( + (db.prepare("SELECT owner_account_id FROM cloud_devices WHERE id = ?").get(deviceId) as { owner_account_id: string }).owner_account_id, + accountId, + ); + } finally { + db.close(); + } +}); + +test("session refresh digests are unique and deletions revoke sessions", () => { + const db = database(); + try { + const insert = db.prepare( + `INSERT INTO cloud_sessions + (id, account_id, refresh_token_hash, created_at_ms, expires_at_ms) + VALUES (?, ?, ?, ?, ?)`, + ); + insert.run("s1", accountId, shaA, 1_000, 20_000); + assert.throws(() => insert.run("s2", otherAccountId, shaA, 1_000, 20_000)); + assert.throws(() => insert.run("s3", otherAccountId, "short", 1_000, 20_000)); + db.prepare("DELETE FROM cloud_accounts WHERE id = ?").run(accountId); + assert.equal( + (db.prepare("SELECT count(*) AS n FROM cloud_sessions").get() as { n: number }).n, + 0, + ); + } finally { + db.close(); + } +}); + +test("only one pending ticket exists per device and approval requires a known account", () => { + const db = database(); + try { + const insert = db.prepare( + `INSERT INTO cloud_pairing_tickets + (id, device_id, device_name, device_platform, claim_secret_hash, + poll_secret_hash, device_credential_hash, created_at_ms, expires_at_ms) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, + ); + insert.run("ticket1", deviceId, "My PC", "windows", shaA, shaB, shaC, 1_000, 20_000); + assert.throws(() => + insert.run("ticket2", deviceId, "My PC", "windows", shaB, shaA, shaC, 1_000, 20_000), + ); + assert.throws(() => + db.prepare( + "UPDATE cloud_pairing_tickets SET status = 'approved' WHERE id = 'ticket1'", + ).run(), + ); + db.prepare( + "UPDATE cloud_pairing_tickets SET status = 'approved', claimed_by_account_id = ? WHERE id = ?", + ).run(accountId, "ticket1"); + insert.run("ticket2", deviceId, "My PC", "windows", shaB, shaA, shaC, 1_000, 20_000); + db.prepare("DELETE FROM cloud_accounts WHERE id = ?").run(accountId); + assert.equal( + (db.prepare("SELECT count(*) AS n FROM cloud_pairing_tickets WHERE id = 'ticket1'").get() as { n: number }).n, + 0, + ); + assert.equal( + (db.prepare("SELECT count(*) AS n FROM cloud_pairing_tickets WHERE id = 'ticket2'").get() as { n: number }).n, + 1, + ); + } finally { + db.close(); + } +});