From fde6d330d18b6ff5a9db8867c94750381560d308 Mon Sep 17 00:00:00 2001 From: Leo <91056950+Nardo021@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:00:03 +1100 Subject: [PATCH 01/19] feat(cloud): add protocol v1 tenant-scoped realtime engine with no offline queue --- relay/src/cloud/realtimeCore.ts | 309 ++++++++++++++++++++++++++++++++ 1 file changed, 309 insertions(+) create mode 100644 relay/src/cloud/realtimeCore.ts diff --git a/relay/src/cloud/realtimeCore.ts b/relay/src/cloud/realtimeCore.ts new file mode 100644 index 0000000..6359e1f --- /dev/null +++ b/relay/src/cloud/realtimeCore.ts @@ -0,0 +1,309 @@ +import { createHash, randomBytes, randomUUID } from "node:crypto"; + +import { parseIncomingDeviceMessage, rawDataToString } from "../protocol/codec.js"; +import type { CommandMessage, CommandResultMessage } from "../protocol/messages.js"; +import { PROTOCOL_VERSION } from "../protocol/protocolVersion.js"; +import { isUuid } from "../utils/ids.js"; +import type { CloudD1Database } from "./identityRepository.js"; +import { + authorizeCloudCommandAdmission, + authorizeCloudDeviceAdmission, +} from "./tenantAdmission.js"; + +const COMMAND_TTL_MS = 10_000; +const COMMAND_WAIT_MS = 10_500; +const STALE_SOCKET_MS = 90_000; +const AUTH_GRACE_MS = 5_000; +const MAX_FRAME_BYTES = 8_192; +const MAX_PENDING = 32; + +export type CloudSocketAttachment = { + kind: "cloud-device"; + expectedDeviceId: string; + ownerAccountId: string; + connectionId: string; + openedAtMs: number; + authenticatedDeviceId?: string; + credentialHash?: string; + lastHeartbeatMs?: number; + actions?: readonly string[]; +}; + +/** Same methods offered by Cloudflare's hibernatable server WebSocket. */ +export interface CloudRealtimeSocket { + send(data: string): void; + close(code?: number, reason?: string): void; + serializeAttachment(value: CloudSocketAttachment): void; + deserializeAttachment(): CloudSocketAttachment | null; +} + +export type CloudCommandOutcome = Readonly<{ + httpStatus: number; + status: "offline" | "busy" | "timeout" | "completed" | "failed" | + "expired" | "invalid" | "unsupported" | "permission_required"; + commandId?: string; +}>; + +type Pending = { + deviceId: string; + socket: CloudRealtimeSocket; + expiresAtMs: number; + resolve: (value: CloudCommandOutcome) => void; + timer: ReturnType; +}; + +function digest(value: string): string { + return createHash("sha256").update(value, "utf8").digest("hex"); +} + +function attachmentIsValid(value: CloudSocketAttachment | null, owner: string): value is CloudSocketAttachment { + return value !== null && value.kind === "cloud-device" && + isUuid(value.expectedDeviceId) && value.ownerAccountId === owner && + typeof value.connectionId === "string" && isUuid(value.connectionId) && + Number.isSafeInteger(value.openedAtMs) && value.openedAtMs > 0; +} + +/** + * Cloud-only realtime state machine. The DO owns one of these per tenant. + * No offline queue or persistent command log: a DO restart fails any in-flight + * command, and all new dispatches require an authenticated online socket. + */ +export class CloudTenantRealtime { + private readonly devices = new Map(); + private readonly pending = new Map(); + + constructor( + private readonly db: CloudD1Database, + readonly ownerAccountId: string, + private readonly now: () => number = Date.now, + ) { + if (!isUuid(ownerAccountId)) throw new Error("Invalid tenant owner."); + } + + /** The WS upgrade is PROVISIONAL until a valid Protocol v1 auth frame. */ + accept(socket: CloudRealtimeSocket, expectedDeviceId: string): void { + if (!isUuid(expectedDeviceId)) throw new Error("Invalid device ID."); + socket.serializeAttachment({ + kind: "cloud-device", + expectedDeviceId, + ownerAccountId: this.ownerAccountId, + connectionId: randomUUID(), + openedAtMs: this.now(), + }); + } + + /** Restore only attachment metadata; recheck D1 before accepting frames. */ + restore(socket: CloudRealtimeSocket): void { + const a = socket.deserializeAttachment(); + if (!attachmentIsValid(a, this.ownerAccountId) || + !a.authenticatedDeviceId || !isUuid(a.authenticatedDeviceId) || + a.expectedDeviceId !== a.authenticatedDeviceId || + !/^[0-9a-f]{64}$/.test(a.credentialHash ?? "")) { + socket.close(4401, "invalid_session"); + return; + } + const old = this.devices.get(a.authenticatedDeviceId); + if (old && old !== socket) old.close(4409, "superseded"); + this.devices.set(a.authenticatedDeviceId, socket); + } + + private async matchesD1(a: CloudSocketAttachment): Promise { + if (!a.credentialHash || !a.authenticatedDeviceId) return false; + const row = await this.db.prepare( + `SELECT d.id FROM cloud_devices d + INNER JOIN cloud_accounts acc ON acc.id = d.owner_account_id + WHERE d.id = ? AND d.owner_account_id = ? + AND d.credential_hash = ? AND d.status = 'active' + AND acc.status = 'active'`, + ).bind(a.authenticatedDeviceId, this.ownerAccountId, a.credentialHash) + .first<{ id: string }>(); + return row?.id === a.authenticatedDeviceId; + } + + async onMessage(socket: CloudRealtimeSocket, raw: string | ArrayBuffer): Promise { + const a = socket.deserializeAttachment(); + if (!attachmentIsValid(a, this.ownerAccountId)) { + socket.close(4401, "invalid_session"); + return; + } + const text = rawDataToString(raw); + if (Buffer.byteLength(text, "utf8") > MAX_FRAME_BYTES) { + this.disconnect(socket, 4400, "invalid_frame"); + return; + } + const parsed = parseIncomingDeviceMessage(text); + if (!parsed.ok) { + this.disconnect(socket, 4400, "invalid_frame"); + return; + } + + if (!a.authenticatedDeviceId) { + if (parsed.message.type !== "auth" || + parsed.message.device_id !== a.expectedDeviceId) { + this.disconnect(socket, 4401, "invalid_credentials"); + return; + } + const verified = await authorizeCloudDeviceAdmission( + this.db, a.expectedDeviceId, parsed.message.credential, + ); + if (!verified || verified.tenantAccountId !== this.ownerAccountId || + parsed.message.actions?.includes("lock") === false) { + this.disconnect(socket, 4401, "invalid_credentials"); + return; + } + const previous = this.devices.get(verified.deviceId); + if (previous && previous !== socket) this.disconnect(previous, 4409, "superseded"); + const lastHeartbeatMs = this.now(); + socket.serializeAttachment({ + ...a, + authenticatedDeviceId: verified.deviceId, + credentialHash: digest(parsed.message.credential), + lastHeartbeatMs, + actions: parsed.message.actions ?? ["lock"], + }); + this.devices.set(verified.deviceId, socket); + socket.send(JSON.stringify({ type: "auth_result", version: PROTOCOL_VERSION, status: "ok" })); + return; + } + + if (this.devices.get(a.authenticatedDeviceId) !== socket || + !(await this.matchesD1(a))) { + this.disconnect(socket, 4401, "revoked_or_superseded"); + return; + } + switch (parsed.message.type) { + case "auth": + this.disconnect(socket, 4400, "duplicate_auth"); + return; + case "heartbeat": + if (parsed.message.device_id !== a.authenticatedDeviceId) { + this.disconnect(socket, 4400, "wrong_device"); + return; + } + socket.serializeAttachment({ ...a, lastHeartbeatMs: this.now() }); + socket.send(JSON.stringify({ + type: "heartbeat_ack", + version: PROTOCOL_VERSION, + sent_at: parsed.message.sent_at, + server_at: this.now(), + })); + return; + case "command_result": + this.onResult(socket, a.authenticatedDeviceId, parsed.message); + return; + default: { + const neverMessage: never = parsed.message; + void neverMessage; + } + } + } + + private onResult(socket: CloudRealtimeSocket, deviceId: string, result: CommandResultMessage): void { + const pending = this.pending.get(result.command_id); + if (!pending || pending.socket !== socket || pending.deviceId !== deviceId) return; + if (this.now() > pending.expiresAtMs) { + this.complete(result.command_id, { httpStatus: 504, status: "timeout", commandId: result.command_id }); + return; + } + this.complete(result.command_id, { + httpStatus: 200, + status: result.status, + commandId: result.command_id, + }); + } + + /** + * The DO independently revalidates the caller's access token and ownership. + * A gateway caller cannot choose a different tenant or issue other actions. + */ + async command(accessToken: string, deviceId: string, action: unknown): Promise { + const verdict = await authorizeCloudCommandAdmission(this.db, accessToken, deviceId, action, this.now()); + if (!verdict.allowed || verdict.tenantAccountId !== this.ownerAccountId) { + return { httpStatus: verdict.allowed ? 404 : verdict.status, status: "failed" }; + } + const socket = this.devices.get(deviceId); + if (!socket) return { httpStatus: 409, status: "offline" }; + const a = socket.deserializeAttachment(); + if (!attachmentIsValid(a, this.ownerAccountId) || + a.authenticatedDeviceId !== deviceId || !(await this.matchesD1(a))) { + this.disconnect(socket, 4401, "revoked_or_superseded"); + return { httpStatus: 409, status: "offline" }; + } + if (!a.actions?.includes("lock")) { + return { httpStatus: 422, status: "unsupported" }; + } + if (this.pending.size >= MAX_PENDING || + [...this.pending.values()].some(p => p.deviceId === deviceId)) { + return { httpStatus: 429, status: "busy" }; + } + const createdAt = this.now(); + const command: CommandMessage = { + type: "command", + version: PROTOCOL_VERSION, + id: `cmd_${randomUUID()}`, + device_id: deviceId, + action: "lock", + created_at: createdAt, + expires_at: createdAt + COMMAND_TTL_MS, + nonce: randomBytes(16).toString("base64url"), + }; + return new Promise((resolve) => { + const timer = setTimeout(() => { + this.complete(command.id, { httpStatus: 504, status: "timeout", commandId: command.id }); + }, COMMAND_WAIT_MS); + this.pending.set(command.id, { + socket, deviceId, expiresAtMs: command.expires_at, resolve, timer, + }); + try { + socket.send(JSON.stringify(command)); + } catch { + this.disconnect(socket, 1011, "transport_error"); + } + }); + } + + private complete(id: string, outcome: CloudCommandOutcome): void { + const pending = this.pending.get(id); + if (!pending) return; + clearTimeout(pending.timer); + this.pending.delete(id); + pending.resolve(outcome); + } + + disconnect(socket: CloudRealtimeSocket, code = 1000, reason = "closed"): void { + const a = socket.deserializeAttachment(); + if (a?.authenticatedDeviceId && this.devices.get(a.authenticatedDeviceId) === socket) { + this.devices.delete(a.authenticatedDeviceId); + } + for (const [id, p] of this.pending) { + if (p.socket === socket) { + this.complete(id, { httpStatus: 409, status: "offline", commandId: id }); + } + } + try { + socket.close(code, reason); + } catch { + // Closing an already closed socket is safe to ignore. + } + } + + onClose(socket: CloudRealtimeSocket): void { + this.disconnect(socket); + } + + /** Called from a Durable Object alarm. No stale sockets or queued commands. */ + sweep(sockets: readonly CloudRealtimeSocket[]): void { + const now = this.now(); + for (const socket of sockets) { + const a = socket.deserializeAttachment(); + if (!attachmentIsValid(a, this.ownerAccountId)) { + this.disconnect(socket, 4401, "invalid_session"); + } else if (!a.authenticatedDeviceId && now - a.openedAtMs > AUTH_GRACE_MS) { + this.disconnect(socket, 4408, "auth_timeout"); + } else if (a.authenticatedDeviceId && + now - (a.lastHeartbeatMs ?? a.openedAtMs) > STALE_SOCKET_MS) { + this.disconnect(socket, 4408, "heartbeat_timeout"); + } + } + } +} From 7db0c7018ce989f2a5367c3505a5a648d231b277 Mon Sep 17 00:00:00 2001 From: Leo <91056950+Nardo021@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:00:56 +1100 Subject: [PATCH 02/19] feat(cloud): add isolated hibernating tenant Durable Object and Protocol v1 WebSocket handler --- relay/src/cloud/tenantDurableObject.ts | 165 +++++++++++++++++++++++++ 1 file changed, 165 insertions(+) create mode 100644 relay/src/cloud/tenantDurableObject.ts diff --git a/relay/src/cloud/tenantDurableObject.ts b/relay/src/cloud/tenantDurableObject.ts new file mode 100644 index 0000000..2ad713f --- /dev/null +++ b/relay/src/cloud/tenantDurableObject.ts @@ -0,0 +1,165 @@ +import { timingSafeEqual } from "node:crypto"; +import { DurableObject } from "cloudflare:workers"; + +import { isUuid } from "../utils/ids.js"; +import type { CloudD1Database } from "./identityRepository.js"; +import { + CloudTenantRealtime, + type CloudRealtimeSocket, +} from "./realtimeCore.js"; + +type TenantEnv = { + CLOUD_DB?: CloudD1Database; + MOTE_CLOUD_INTERNAL_SECRET?: string; +}; + +const ALARM_INTERVAL_MS = 15_000; +const OWNER_KEY = "moteCloudTenantOwnerId"; + +function verifiedInternalRequest(request: Request, secret: string | undefined): boolean { + const provided = request.headers.get("X-Mote-Cloud-Internal"); + if (!secret || secret.length < 32 || !provided || + Buffer.byteLength(provided) !== Buffer.byteLength(secret)) return false; + return timingSafeEqual(Buffer.from(provided), Buffer.from(secret)); +} +function reply(status: number, payload: object): Response { + return new Response(JSON.stringify(payload), { + status, + headers: { "Content-Type": "application/json", "Cache-Control": "no-store" }, + }); +} +function asCloudSocket(socket: WebSocket): CloudRealtimeSocket { + return socket as unknown as CloudRealtimeSocket; +} + +/** + * One distinct hibernating DO per account. The gateway must derive owner + * solely from D1, not a user-supplied tenant ID. This DO independently + * revalidates all device credentials and phone session tokens using D1. + */ +export class MoteCloudTenant extends DurableObject { + #ownerId: string | undefined; + #realtime: CloudTenantRealtime | undefined; + #queues = new WeakMap>(); + + constructor(ctx: DurableObjectState, env: TenantEnv) { + super(ctx, env); + ctx.blockConcurrencyWhile(async () => { + const ownerId = await ctx.storage.get(OWNER_KEY); + if (ownerId && isUuid(ownerId) && env.CLOUD_DB) { + this.#ownerId = ownerId; + this.#realtime = new CloudTenantRealtime(env.CLOUD_DB, ownerId); + for (const socket of ctx.getWebSockets()) { + this.#realtime.restore(asCloudSocket(socket)); + } + } else { + // Do not accept old sockets when the owner boundary is unknown. + for (const socket of ctx.getWebSockets()) { + try { socket.close(4401, "invalid_tenant"); } catch { /* ignore */ } + } + } + }); + } + + private async bindOwner(ownerId: string): Promise { + if (!isUuid(ownerId) || !this.env.CLOUD_DB) return false; + if (this.#ownerId !== undefined) return this.#ownerId === ownerId; + // Durable Object storage is the stable tenant boundary across hibernation. + return this.ctx.blockConcurrencyWhile(async () => { + const stored = await this.ctx.storage.get(OWNER_KEY); + if (stored !== undefined && stored !== ownerId) return false; + if (stored === undefined) await this.ctx.storage.put(OWNER_KEY, ownerId); + this.#ownerId = ownerId; + this.#realtime = new CloudTenantRealtime(this.env.CLOUD_DB!, ownerId); + return true; + }); + } + + override async fetch(request: Request): Promise { + if (!verifiedInternalRequest(request, this.env.MOTE_CLOUD_INTERNAL_SECRET)) { + return reply(404, { error: "not_found" }); + } + const owner = request.headers.get("X-Mote-Cloud-Owner") ?? ""; + if (!(await this.bindOwner(owner)) || !this.#realtime || !this.env.CLOUD_DB) { + return reply(404, { error: "not_found" }); + } + const url = new URL(request.url); + + if (request.method === "GET" && request.headers.get("Upgrade")?.toLowerCase() === "websocket") { + const match = /^\/internal\/ws\/([0-9a-f-]{36})$/i.exec(url.pathname); + if (!match || !match[1] || !isUuid(match[1])) return reply(404, { error: "not_found" }); + const deviceId = match[1]; + // This is a provisional route, NOT authenticated admission. The + // following Protocol v1 auth frame must prove the device credential. + const row = await this.env.CLOUD_DB.prepare( + `SELECT d.id FROM cloud_devices d JOIN cloud_accounts a + ON a.id = d.owner_account_id + WHERE d.id = ? AND d.owner_account_id = ? AND d.status = 'active' + AND a.status = 'active'`, + ).bind(deviceId, owner).first<{ id: string }>(); + if (!row) return reply(404, { error: "not_found" }); + const pair = new WebSocketPair(); + const [client, server] = [pair[0], pair[1]]; + this.ctx.acceptWebSocket(server); + this.#realtime.accept(asCloudSocket(server), deviceId); + await this.ctx.storage.setAlarm(Date.now() + ALARM_INTERVAL_MS); + return new Response(null, { status: 101, webSocket: client }); + } + + if (request.method === "POST" && url.pathname === "/internal/command") { + let body: unknown; + try { + const raw = await request.text(); + if (Buffer.byteLength(raw, "utf8") > 4096) return reply(413, { error: "invalid_request" }); + body = JSON.parse(raw); + } catch { + return reply(400, { error: "invalid_request" }); + } + if (!body || typeof body !== "object" || Array.isArray(body)) { + return reply(400, { error: "invalid_request" }); + } + const record = body as Record; + if (typeof record.accessToken !== "string" || + typeof record.deviceId !== "string" || + record.action !== "lock") { + return reply(400, { error: "invalid_request" }); + } + const outcome = await this.#realtime.command( + record.accessToken, record.deviceId, record.action, + ); + return reply(outcome.httpStatus, { + status: outcome.status, + ...(outcome.commandId ? { command_id: outcome.commandId } : {}), + }); + } + return reply(404, { error: "not_found" }); + } + + override async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise { + if (!this.#realtime) { + try { ws.close(4401, "invalid_tenant"); } catch { /* ignore */ } + return; + } + // Serializes frames per device, including the initial asynchronous D1 + // credential check; a heartbeat cannot leap ahead of the auth frame. + const predecessor = this.#queues.get(ws) ?? Promise.resolve(); + const current = predecessor.then( + () => this.#realtime!.onMessage(asCloudSocket(ws), message), + ); + this.#queues.set(ws, current.catch(() => { + this.#realtime?.disconnect(asCloudSocket(ws), 1011, "validation_failed"); + })); + await current.catch(() => undefined); + } + + override async webSocketClose(ws: WebSocket): Promise { + this.#realtime?.onClose(asCloudSocket(ws)); + } + + override async alarm(): Promise { + this.#realtime?.sweep(this.ctx.getWebSockets().map(asCloudSocket)); + if (this.ctx.getWebSockets().length > 0) { + await this.ctx.storage.setAlarm(Date.now() + ALARM_INTERVAL_MS); + } + } +} From 259eb854b61b8ba290e7799d47271193df40e655 Mon Sep 17 00:00:00 2001 From: Leo <91056950+Nardo021@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:01:39 +1100 Subject: [PATCH 03/19] feat(cloud): route verified phone locks and provisional WS upgrades to D1-derived tenant DOs --- relay/src/cloud/stagingWorker.ts | 84 +++++++++++++++++++++++++++++++- 1 file changed, 82 insertions(+), 2 deletions(-) diff --git a/relay/src/cloud/stagingWorker.ts b/relay/src/cloud/stagingWorker.ts index f620bc7..fecfb3f 100644 --- a/relay/src/cloud/stagingWorker.ts +++ b/relay/src/cloud/stagingWorker.ts @@ -8,16 +8,25 @@ import { } from "./appleIdentity.js"; import { CloudIdentityRepository, type CloudD1Database } from "./identityRepository.js"; import { CloudPairingRepository } from "./pairingRepository.js"; +import { authorizeCloudCommandAdmission } from "./tenantAdmission.js"; /** * Entirely separate staging-only Worker entrypoint. The original self-hosted * relay/src/worker/index.ts must NOT import, route to or deploy this handler. */ +/** Real namespace binding is supplied by the isolated Cloud Worker config. */ +export type CloudTenantNamespace = { + idFromName(name: string): unknown; + get(id: unknown): { fetch(request: Request): Promise }; +}; + export type CloudStagingEnv = Readonly<{ CLOUD_DB?: CloudD1Database; MOTE_CLOUD_STAGING_ENABLED?: string; MOTE_CLOUD_STAGING_GATE?: string; APPLE_CLIENT_ID?: string; + CLOUD_TENANTS?: CloudTenantNamespace; + MOTE_CLOUD_INTERNAL_SECRET?: string; }>; type HandlerDependencies = Readonly<{ @@ -207,8 +216,79 @@ export function createCloudStagingHandler(deps: HandlerDependencies = {}) { 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. + + // The public WS URL contains ONLY a device UUID. It is a provisional + // D1 owner lookup; the target DO must independently verify the v1 + // device auth frame credential BEFORE admitting the socket. + const wsRoute = /^\\/cloud\\/v1\\/ws\\/device\\/([a-f0-9-]{36})$/i.exec(url.pathname); + if (wsRoute && request.method === "GET") { + if (request.headers.get("Upgrade")?.toLowerCase() !== "websocket") { + return respond(426, { error: "upgrade_required" }); + } + const deviceId = wsRoute[1]; + if (!deviceId || !env.CLOUD_TENANTS || + !env.MOTE_CLOUD_INTERNAL_SECRET || + env.MOTE_CLOUD_INTERNAL_SECRET.length < 32) { + return respond(503, { error: "service_unavailable" }); + } + const row = await env.CLOUD_DB.prepare( + `SELECT d.owner_account_id FROM cloud_devices d + JOIN cloud_accounts a ON a.id = d.owner_account_id + WHERE d.id = ? AND d.status = 'active' AND a.status = 'active'`, + ).bind(deviceId).first<{ owner_account_id: string }>(); + if (!row) return respond(404, { error: "not_found" }); + const key = `mote-cloud-account:${row.owner_account_id}`; + const stub = env.CLOUD_TENANTS.get(env.CLOUD_TENANTS.idFromName(key)); + // Copy the original upgrade request (including WebSocket handshake), + // but REPLACE all privileged headers with server-owned values. + const target = new URL(`/internal/ws/${deviceId}`, request.url); + const forwarded = new Request(target, request); + const headers = new Headers(forwarded.headers); + headers.delete("Authorization"); + headers.delete("X-Mote-Staging-Gate"); + headers.delete("X-Mote-Cloud-Internal"); + headers.delete("X-Mote-Cloud-Owner"); + headers.set("X-Mote-Cloud-Internal", env.MOTE_CLOUD_INTERNAL_SECRET); + headers.set("X-Mote-Cloud-Owner", row.owner_account_id); + return stub.fetch(new Request(forwarded, { headers })); + } + + const commandRoute = /^\\/cloud\\/v1\\/devices\\/([a-f0-9-]{36})\\/commands$/i.exec(url.pathname); + if (commandRoute && request.method === "POST") { + const deviceId = commandRoute[1]; + const accessToken = bearerToken(request); + if (!accessToken) return respond(401, { error: "unauthenticated" }); + if (!deviceId) return respond(404, { error: "not_found" }); + const body = await jsonBody(request); + if (!body || body.action === undefined) { + return respond(400, { error: "invalid_request" }); + } + const allowed = await authorizeCloudCommandAdmission( + env.CLOUD_DB, accessToken, deviceId, body.action, nowMs, + ); + if (!allowed.allowed) { + return respond(allowed.status, { error: allowed.reason }); + } + if (!env.CLOUD_TENANTS || !env.MOTE_CLOUD_INTERNAL_SECRET || + env.MOTE_CLOUD_INTERNAL_SECRET.length < 32) { + return respond(503, { error: "service_unavailable" }); + } + const stub = env.CLOUD_TENANTS.get( + env.CLOUD_TENANTS.idFromName(`mote-cloud-account:${allowed.tenantAccountId}`), + ); + return stub.fetch(new Request("https://mote-cloud.internal/internal/command", { + method: "POST", + headers: { + "Content-Type": "application/json", + "X-Mote-Cloud-Internal": env.MOTE_CLOUD_INTERNAL_SECRET, + "X-Mote-Cloud-Owner": allowed.tenantAccountId, + }, + body: JSON.stringify({ accessToken, deviceId: allowed.deviceId, action: "lock" }), + })); + } + + // Account deletion and public enrollment remain unimplemented. + // Never delegate Cloud routes to the personal Relay singleton. return respond(404, { error: "not_found" }); } catch (error) { if (error instanceof AppleIdentityError) { From 6b1758ce95e55737f5fb07bc003a4875842695c1 Mon Sep 17 00:00:00 2001 From: Leo <91056950+Nardo021@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:01:51 +1100 Subject: [PATCH 04/19] feat(cloud): export separate hosted Worker and tenant Durable Object runtime --- relay/src/cloud/cloudWorker.ts | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 relay/src/cloud/cloudWorker.ts diff --git a/relay/src/cloud/cloudWorker.ts b/relay/src/cloud/cloudWorker.ts new file mode 100644 index 0000000..40ef77f --- /dev/null +++ b/relay/src/cloud/cloudWorker.ts @@ -0,0 +1,9 @@ +/** + * Isolated hosted Cloud Worker module. + * + * Deliberately NOT the personal worker at relay/src/worker/index.ts. + * The default handler is separate from the Durable Object export so Node's + * offline HTTP tests can import stagingWorker without cloudflare:workers. + */ +export { default } from "./stagingWorker.js"; +export { MoteCloudTenant } from "./tenantDurableObject.js"; From 3355ce8bd6aec3eb26ecb66c7a7227236fa543fb Mon Sep 17 00:00:00 2001 From: Leo <91056950+Nardo021@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:02:06 +1100 Subject: [PATCH 05/19] feat(cloud): bind account-scoped hosted DO in isolated staging and CI configs --- cloud/wrangler.ci.jsonc | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/cloud/wrangler.ci.jsonc b/cloud/wrangler.ci.jsonc index ae35dc3..5e249e7 100644 --- a/cloud/wrangler.ci.jsonc +++ b/cloud/wrangler.ci.jsonc @@ -1,12 +1,30 @@ { "$schema": "../node_modules/wrangler/config-schema.json", "name": "mote-cloud-ci-dry-run", - "main": "../relay/src/cloud/stagingWorker.ts", + "main": "../relay/src/cloud/cloudWorker.ts", "compatibility_date": "2026-11-16", - "compatibility_flags": ["nodejs_compat"], + "compatibility_flags": [ + "nodejs_compat" + ], "workers_dev": false, "vars": { "MOTE_CLOUD_STAGING_ENABLED": "false", "APPLE_CLIENT_ID": "ci-placeholder-never-for-auth" - } + }, + "durable_objects": { + "bindings": [ + { + "name": "CLOUD_TENANTS", + "class_name": "MoteCloudTenant" + } + ] + }, + "migrations": [ + { + "tag": "cloud-v1", + "new_sqlite_classes": [ + "MoteCloudTenant" + ] + } + ] } From 99cfdf53e16468469f2eafd1e2cbb5671f17d61a Mon Sep 17 00:00:00 2001 From: Leo <91056950+Nardo021@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:02:09 +1100 Subject: [PATCH 06/19] feat(cloud): bind account-scoped hosted DO in isolated staging and CI configs --- cloud/wrangler.staging.example.jsonc | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/cloud/wrangler.staging.example.jsonc b/cloud/wrangler.staging.example.jsonc index 308bf74..5f372f5 100644 --- a/cloud/wrangler.staging.example.jsonc +++ b/cloud/wrangler.staging.example.jsonc @@ -1,11 +1,15 @@ { "$schema": "../node_modules/wrangler/config-schema.json", "name": "mote-cloud-staging", - "main": "../relay/src/cloud/stagingWorker.ts", + "main": "../relay/src/cloud/cloudWorker.ts", "compatibility_date": "2026-11-16", - "compatibility_flags": ["nodejs_compat"], + "compatibility_flags": [ + "nodejs_compat" + ], "workers_dev": true, - "observability": { "enabled": true }, + "observability": { + "enabled": true + }, "vars": { "MOTE_CLOUD_STAGING_ENABLED": "false", "APPLE_CLIENT_ID": "REPLACE_WITH_REAL_IOS_BUNDLE_ID" @@ -17,5 +21,21 @@ "database_id": "REPLACE_WITH_NEW_STAGING_D1_ID", "migrations_dir": "migrations" } + ], + "durable_objects": { + "bindings": [ + { + "name": "CLOUD_TENANTS", + "class_name": "MoteCloudTenant" + } + ] + }, + "migrations": [ + { + "tag": "cloud-v1", + "new_sqlite_classes": [ + "MoteCloudTenant" + ] + } ] } From 8022c73cf48582811bf04ca2f49a5ee4db73b760 Mon Sep 17 00:00:00 2001 From: Leo <91056950+Nardo021@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:03:49 +1100 Subject: [PATCH 07/19] test(cloud): exercise Protocol v1 lock lifecycle, tenant isolation, no offline queue and gateway header trust --- relay/test/cloudRealtime.test.ts | 332 +++++++++++++++++++++++++++++++ 1 file changed, 332 insertions(+) create mode 100644 relay/test/cloudRealtime.test.ts diff --git a/relay/test/cloudRealtime.test.ts b/relay/test/cloudRealtime.test.ts new file mode 100644 index 0000000..21f28db --- /dev/null +++ b/relay/test/cloudRealtime.test.ts @@ -0,0 +1,332 @@ +import assert from "node:assert/strict"; +import { createHash, randomBytes } from "node:crypto"; +import { readFileSync } from "node:fs"; +import { DatabaseSync, type SQLInputValue } from "node:sqlite"; +import test from "node:test"; + +import type { CloudD1Database, CloudD1Statement } from "../src/cloud/identityRepository.js"; +import { CloudIdentityRepository } from "../src/cloud/identityRepository.js"; +import { + CloudTenantRealtime, + type CloudRealtimeSocket, + type CloudSocketAttachment, +} from "../src/cloud/realtimeCore.js"; +import { + createCloudStagingHandler, + type CloudStagingEnv, +} from "../src/cloud/stagingWorker.js"; + +const nowMs = 1_800_000_000_000; +const A = "11111111-1111-4111-8111-111111111111"; +const B = "22222222-2222-4222-8222-222222222222"; +const DA = "44444444-4444-4444-8444-444444444444"; +const DA2 = "55555555-5555-4555-8555-555555555555"; +const DB = "66666666-6666-4666-8666-666666666666"; +const GA = randomBytes(32).toString("base64url"); +const GA2 = randomBytes(32).toString("base64url"); +const GB = randomBytes(32).toString("base64url"); + +function sha256(raw: string) { + return createHash("sha256").update(raw, "utf8").digest("hex"); +} +class Statement implements CloudD1Statement { + constructor( + private readonly db: DatabaseSync, + private readonly sql: string, + private readonly args: SQLInputValue[] = [], + ) {} + bind(...args: Array) { return new Statement(this.db, this.sql, args); } + async first() { return (this.db.prepare(this.sql).get(...this.args) ?? null) as T | null; } + async all() { return { results: this.db.prepare(this.sql).all(...this.args) as T[] }; } + async run() { + const result = this.db.prepare(this.sql).run(...this.args); + return { meta: { changes: Number(result.changes) } }; + } +} +function fixture() { + const raw = new DatabaseSync(":memory:"); + raw.exec("PRAGMA foreign_keys = ON"); + for (const file of ["0001_core.sql", "0002_auth.sql", "0003_pairing_claim.sql"]) { + raw.exec(readFileSync(new URL(`../../cloud/migrations/${file}`, import.meta.url), "utf8")); + } + const db: CloudD1Database = { prepare: (sql) => new Statement(raw, sql) }; + for (const [account, subject] of [[A, "apple-a"], [B, "apple-b"]]) { + raw.prepare("INSERT INTO cloud_accounts(id, apple_subject, created_at_ms) VALUES (?, ?, ?)").run( + account, subject, nowMs, + ); + } + const insert = raw.prepare( + `INSERT INTO cloud_devices(id, owner_account_id, name, platform, credential_hash, + created_at_ms, updated_at_ms) VALUES (?, ?, ?, 'windows', ?, ?, ?)`, + ); + insert.run(DA, A, "A PC", sha256(GA), nowMs, nowMs); + insert.run(DA2, A, "A second PC", sha256(GA2), nowMs, nowMs); + insert.run(DB, B, "B PC", sha256(GB), nowMs, nowMs); + return { raw, db }; +} + +class MockSocket implements CloudRealtimeSocket { + attachment: CloudSocketAttachment | null = null; + readonly sent: string[] = []; + readonly closed: Array<{ code?: number; reason?: string }> = []; + send(data: string): void { this.sent.push(data); } + close(code?: number, reason?: string): void { + this.closed.push({ ...(code === undefined ? {} : { code }), ...(reason === undefined ? {} : { reason }) }); + } + serializeAttachment(value: CloudSocketAttachment): void { this.attachment = value; } + deserializeAttachment(): CloudSocketAttachment | null { return this.attachment; } + last(): T { return JSON.parse(this.sent.at(-1)!) as T; } +} + +async function socketFor(hub: CloudTenantRealtime, deviceId: string, credential: string) { + const socket = new MockSocket(); + hub.accept(socket, deviceId); + await hub.onMessage(socket, JSON.stringify({ + type: "auth", version: 1, device_id: deviceId, + credential, platform: "windows", actions: ["lock"], + })); + return socket; +} +async function flushUntil(predicate: () => boolean): Promise { + for (let i = 0; i < 20 && !predicate(); i++) { + await new Promise(resolve => setImmediate(resolve)); + } + assert.ok(predicate(), "expected asynchronous command frame to be issued"); +} + +test("authenticated Protocol v1 device receives owner lock and matching result completes it", async () => { + const { raw, db } = fixture(); + try { + const identity = new CloudIdentityRepository(db); + const tokens = await identity.issueSession(A, nowMs); + const hub = new CloudTenantRealtime(db, A, () => nowMs); + const device = await socketFor(hub, DA, GA); + assert.deepEqual(device.last(), { type: "auth_result", version: 1, status: "ok" }); + + await hub.onMessage(device, JSON.stringify({ + type: "heartbeat", version: 1, device_id: DA, sent_at: nowMs, + })); + assert.deepEqual(device.last(), { + type: "heartbeat_ack", version: 1, sent_at: nowMs, server_at: nowMs, + }); + + const result = hub.command(tokens.accessToken, DA, "lock"); + await flushUntil(() => device.sent.some(item => JSON.parse(item).type === "command")); + const command = device.last<{ type: string; id: string; action: string; device_id: string; expires_at: number }>(); + assert.equal(command.type, "command"); + assert.equal(command.action, "lock"); + assert.equal(command.device_id, DA); + assert.equal(command.expires_at, nowMs + 10_000); + + await hub.onMessage(device, JSON.stringify({ + type: "command_result", version: 1, command_id: command.id, + status: "completed", completed_at: nowMs + 1_000, + })); + assert.deepEqual(await result, { + httpStatus: 200, status: "completed", commandId: command.id, + }); + } finally { raw.close(); } +}); + +test("cross-account command and fake credentials never send a device frame", async () => { + const { raw, db } = fixture(); + try { + const identity = new CloudIdentityRepository(db); + const b = await identity.issueSession(B, nowMs); + const a = await identity.issueSession(A, nowMs); + const hub = new CloudTenantRealtime(db, A, () => nowMs); + const fake = await socketFor(hub, DA, GB); + assert.equal(fake.closed.at(-1)?.code, 4401); + assert.equal(fake.sent.length, 0); + const actual = await socketFor(hub, DA, GA); + assert.deepEqual(await hub.command(b.accessToken, DA, "lock"), { + httpStatus: 404, status: "failed", + }); + assert.deepEqual(await hub.command(a.accessToken, DB, "lock"), { + httpStatus: 404, status: "failed", + }); + assert.deepEqual(await hub.command(a.accessToken, DA, "unlock"), { + httpStatus: 422, status: "failed", + }); + assert.equal(actual.sent.filter(line => JSON.parse(line).type === "command").length, 0); + } finally { raw.close(); } +}); + +test("offline commands are never queued, even if a device reconnects later", async () => { + const { raw, db } = fixture(); + try { + const identity = new CloudIdentityRepository(db); + const a = await identity.issueSession(A, nowMs); + const hub = new CloudTenantRealtime(db, A, () => nowMs); + assert.deepEqual(await hub.command(a.accessToken, DA, "lock"), { + httpStatus: 409, status: "offline", + }); + const socket = await socketFor(hub, DA, GA); + assert.equal(socket.sent.filter(line => JSON.parse(line).type === "command").length, 0); + hub.onClose(socket); + assert.deepEqual(await hub.command(a.accessToken, DA, "lock"), { + httpStatus: 409, status: "offline", + }); + } finally { raw.close(); } +}); + +test("a different device cannot forge another device's command result", async () => { + const { raw, db } = fixture(); + try { + const identity = new CloudIdentityRepository(db); + const a = await identity.issueSession(A, nowMs); + const hub = new CloudTenantRealtime(db, A, () => nowMs); + const one = await socketFor(hub, DA, GA); + const two = await socketFor(hub, DA2, GA2); + const pending = hub.command(a.accessToken, DA, "lock"); + await flushUntil(() => one.sent.some(item => JSON.parse(item).type === "command")); + const command = one.last<{ id: string }>(); + let settled = false; + void pending.then(() => { settled = true; }); + await hub.onMessage(two, JSON.stringify({ + type: "command_result", version: 1, command_id: command.id, + completed_at: nowMs + 500, status: "completed", + })); + assert.equal(settled, false); + await hub.onMessage(one, JSON.stringify({ + type: "command_result", version: 1, command_id: command.id, + completed_at: nowMs + 800, status: "completed", + })); + assert.equal((await pending).status, "completed"); + } finally { raw.close(); } +}); + +test("revocation and credential rotation fail closed for existing and restored sockets", async () => { + const { raw, db } = fixture(); + try { + const identity = new CloudIdentityRepository(db); + const a = await identity.issueSession(A, nowMs); + const hub = new CloudTenantRealtime(db, A, () => nowMs); + const ws = await socketFor(hub, DA, GA); + const restored = new CloudTenantRealtime(db, A, () => nowMs); + restored.restore(ws); + assert.equal((await restored.command(a.accessToken, DA, "lock")).status === "timeout", false); + } finally { raw.close(); } +}); + +test("heartbeat rejects credential rotation and disabled accounts on restored sockets", async () => { + const { raw, db } = fixture(); + try { + const hub = new CloudTenantRealtime(db, A, () => nowMs); + const socket = await socketFor(hub, DA, GA); + const afterRestart = new CloudTenantRealtime(db, A, () => nowMs); + afterRestart.restore(socket); + raw.prepare("UPDATE cloud_devices SET credential_hash = ? WHERE id = ?").run(sha256("new-secret"), DA); + await afterRestart.onMessage(socket, JSON.stringify({ + type: "heartbeat", version: 1, device_id: DA, sent_at: nowMs, + })); + assert.equal(socket.closed.at(-1)?.code, 4401); + const socket2 = await socketFor(hub, DA2, GA2); + raw.prepare("UPDATE cloud_accounts SET status = 'disabled' WHERE id = ?").run(A); + await hub.onMessage(socket2, JSON.stringify({ + type: "heartbeat", version: 1, device_id: DA2, sent_at: nowMs, + })); + assert.equal(socket2.closed.at(-1)?.code, 4401); + } finally { raw.close(); } +}); + +test("expired command results cannot convert timed-out locks into success", async () => { + const { raw, db } = fixture(); + let clock = nowMs; + try { + const identity = new CloudIdentityRepository(db); + const a = await identity.issueSession(A, nowMs); + const hub = new CloudTenantRealtime(db, A, () => clock); + const socket = await socketFor(hub, DA, GA); + const pending = hub.command(a.accessToken, DA, "lock"); + await flushUntil(() => socket.sent.some(line => JSON.parse(line).type === "command")); + const command = socket.last<{ id: string }>(); + clock += 10_001; + await hub.onMessage(socket, JSON.stringify({ + type: "command_result", version: 1, command_id: command.id, + completed_at: clock, status: "completed", + })); + assert.deepEqual(await pending, { + httpStatus: 504, status: "timeout", commandId: command.id, + }); + } finally { raw.close(); } +}); + +test("gateway derives provisional WS tenant and lock tenant from D1 only", async () => { + const { raw, db } = fixture(); + try { + const identity = new CloudIdentityRepository(db); + const a = await identity.issueSession(A, nowMs); + const b = await identity.issueSession(B, nowMs); + const captured: Array<{ key: string; request: Request; body?: unknown }> = []; + const namespace = { + idFromName: (name: string) => name, + get(key: unknown) { + return { + async fetch(request: Request): Promise { + captured.push({ key: String(key), request, ...(request.method === "POST" ? { body: await request.json() } : {}) }); + return new Response(JSON.stringify({ status: "offline" }), { status: 409 }); + }, + }; + }, + }; + const gate = "not-a-client-credential-staging-only-0123456"; + const internal = "server-to-durable-object-secret-only-123456"; + const env: CloudStagingEnv = { + CLOUD_DB: db, CLOUD_TENANTS: namespace, + MOTE_CLOUD_STAGING_ENABLED: "true", MOTE_CLOUD_STAGING_GATE: gate, + MOTE_CLOUD_INTERNAL_SECRET: internal, + APPLE_CLIENT_ID: "com.nardo021.mote.testing", + }; + const handler = createCloudStagingHandler({ now: () => nowMs }); + + const command = (token: string, deviceId: string, action = "lock") => handler( + new Request(`https://staging.test/cloud/v1/devices/${deviceId}/commands`, { + method: "POST", + headers: { + Authorization: `Bearer ${token}`, + "Content-Type": "application/json", + "X-Mote-Staging-Gate": gate, + "X-Mote-Cloud-Owner": B, + "X-Mote-Cloud-Internal": "forged-value", + }, + body: JSON.stringify({ action, tenantAccountId: B }), + }), env, + ); + + assert.equal((await command(b.accessToken, DA)).status, 404); + assert.equal(captured.length, 0); + assert.equal((await command(a.accessToken, DA, "unlock")).status, 422); + assert.equal(captured.length, 0); + assert.equal((await command(a.accessToken, DA)).status, 409); + assert.equal(captured.length, 1); + assert.equal(captured[0]?.key, `mote-cloud-account:${A}`); + assert.equal(captured[0]?.request.headers.get("X-Mote-Cloud-Owner"), A); + assert.equal(captured[0]?.request.headers.get("X-Mote-Cloud-Internal"), internal); + assert.deepEqual(captured[0]?.body, { + accessToken: a.accessToken, deviceId: DA, action: "lock", + }); + + const ws = await handler(new Request( + `https://staging.test/cloud/v1/ws/device/${DA}`, { + method: "GET", headers: { + "Upgrade": "websocket", "X-Mote-Staging-Gate": gate, + "X-Mote-Cloud-Owner": B, "X-Mote-Cloud-Internal": "forged-value", + }, + }), env); + assert.equal(ws.status, 409); // mocked internal endpoint, no real upgrade + assert.equal(captured[1]?.key, `mote-cloud-account:${A}`); + assert.equal(captured[1]?.request.headers.get("X-Mote-Cloud-Owner"), A); + assert.equal(captured[1]?.request.headers.get("X-Mote-Cloud-Internal"), internal); + assert.equal(captured[1]?.request.headers.get("X-Mote-Staging-Gate"), null); + assert.equal(captured[1]?.request.url.endsWith(`/internal/ws/${DA}`), true); + + // Unknown devices cannot choose an arbitrary tenant by guessing owner IDs. + const unknown = await handler(new Request( + "https://staging.test/cloud/v1/ws/device/88888888-8888-4888-8888-888888888888", { + headers: { Upgrade: "websocket", "X-Mote-Staging-Gate": gate }, + }), env); + assert.equal(unknown.status, 404); + assert.equal(captured.length, 2); + } finally { raw.close(); } +}); From eeaa1134a8fce62d58fbb5895488a521c20a74b0 Mon Sep 17 00:00:00 2001 From: Leo <91056950+Nardo021@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:04:13 +1100 Subject: [PATCH 08/19] test(cloud): verify hibernation restore and fail-closed revocation without waiting for timeout --- relay/test/cloudRealtime.test.ts | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/relay/test/cloudRealtime.test.ts b/relay/test/cloudRealtime.test.ts index 21f28db..5f4a869 100644 --- a/relay/test/cloudRealtime.test.ts +++ b/relay/test/cloudRealtime.test.ts @@ -196,7 +196,7 @@ test("a different device cannot forge another device's command result", async () } finally { raw.close(); } }); -test("revocation and credential rotation fail closed for existing and restored sockets", async () => { +test("hibernated socket metadata restores; a revoked device cannot receive more locks", async () => { const { raw, db } = fixture(); try { const identity = new CloudIdentityRepository(db); @@ -205,7 +205,21 @@ test("revocation and credential rotation fail closed for existing and restored s const ws = await socketFor(hub, DA, GA); const restored = new CloudTenantRealtime(db, A, () => nowMs); restored.restore(ws); - assert.equal((await restored.command(a.accessToken, DA, "lock")).status === "timeout", false); + const pending = restored.command(a.accessToken, DA, "lock"); + await flushUntil(() => ws.sent.some(line => JSON.parse(line).type === "command")); + const issued = ws.last<{ id: string }>(); + await restored.onMessage(ws, JSON.stringify({ + type: "command_result", version: 1, command_id: issued.id, + status: "completed", completed_at: nowMs + 300, + })); + assert.equal((await pending).status, "completed"); + + raw.prepare("UPDATE cloud_devices SET status = 'revoked' WHERE id = ?").run(DA); + const beforeCount = ws.sent.length; + assert.deepEqual(await restored.command(a.accessToken, DA, "lock"), { + httpStatus: 404, status: "failed", + }); + assert.equal(ws.sent.length, beforeCount); } finally { raw.close(); } }); From 5ecda99d5494234c8014514c0eb10108f40e76c0 Mon Sep 17 00:00:00 2001 From: Leo <91056950+Nardo021@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:05:22 +1100 Subject: [PATCH 09/19] docs(cloud): record tenant WebSocket threat boundary and live staging blockers --- docs/cloud-p0c2-realtime.md | 67 +++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 docs/cloud-p0c2-realtime.md diff --git a/docs/cloud-p0c2-realtime.md b/docs/cloud-p0c2-realtime.md new file mode 100644 index 0000000..f45785b --- /dev/null +++ b/docs/cloud-p0c2-realtime.md @@ -0,0 +1,67 @@ +# Mote Cloud P0C2 — Tenant WebSocket and online-only lock dispatch + +**Stage:** P0C2 Draft / staging-only source; 2026-11-16 +**Based on:** P0C1 PR #4 (which depends on P0B #3 and P0A #2) +**Release posture:** production BLOCKED; no live Cloudflare D1, genuine Apple login, desktop/iOS Cloud app or real device lock has been verified. + +## Implemented code scope + +- `relay/src/cloud/realtimeCore.ts`: separate tenant-owned Protocol v1 realtime engine. Authenticates the existing desktop `auth` frame via server-side D1 credential and account ownership; handles heartbeats, correlated `command_result` responses, single-in-flight `lock` per device, 10-second command expiry, request timeout and offline failures. Never persists or queues a command for later reconnection. +- `relay/src/cloud/tenantDurableObject.ts`: new Cloud-only `MoteCloudTenant` Durable Object with hibernating WebSockets, persistent tenant binding, per-socket ordered message handling, D1 checks on events and command admission, and stale socket alarm. It does **not** use the personal `MoteRelay` DO. +- `relay/src/cloud/cloudWorker.ts`: exports the hosted Worker handler and separate DO class. Node offline tests still import only `stagingWorker.ts`, avoiding `cloudflare:workers` module loading. +- `relay/src/cloud/stagingWorker.ts`: stages `GET /cloud/v1/ws/device/:deviceId` and `POST /cloud/v1/devices/:deviceId/commands`. Both are behind the **existing private staging gate**, not public API. All tenant IDs come from D1; user-supplied account/owner headers are stripped and overwritten before forwarding. +- `cloud/wrangler.ci.jsonc` and `cloud/wrangler.staging.example.jsonc`: new isolated `CLOUD_TENANTS` DO binding and **cloud-v1** SQLite class migration. CI only performs `wrangler deploy --dry-run`, never deployment. The operator's D1 ID and real Apple Bundle ID remain placeholders, and the staging flag remains false. +- `relay/test/cloudRealtime.test.ts`: offline SQLite/Protocol v1 tests, plus fake DO namespace routing. These do not prove Cloudflare's actual WebSocket runtime semantics. + +## Full request trust boundary + +### Device WebSocket + +1. A desktop already paired through P0C1 has a UUID and a locally retained random 256-bit device credential. +2. It opens `wss:///cloud/v1/ws/device/`. The URL carries **no device credential** or account ID. The private staging gate is currently required on all staging requests and **must never be distributed in an actual desktop build**. +3. The gateway verifies that the **D1 device row is active** and its owner account is active, and uses the D1 owner ID to choose `CLOUD_TENANTS.idFromName("mote-cloud-account:" + owner)`. This is **provisional routing, not authentication**. It does not require the client to supply account identity. +4. The gateway deletes caller-supplied internal/tenant headers, overwrites them with server-held values and forwards the WebSocket upgrade to the tenant DO. A separate 32+ character `MOTE_CLOUD_INTERNAL_SECRET` is required by the DO on every internal request. This secret is not the public staging gate and must not ship inside client code. +5. The DO persists its tenant account ID in its own storage. A request bearing a different owner is refused even if misrouted. It validates the D1 device row before upgrading, but does not trust the socket until it receives Protocol v1 `auth` with the **matching device credential** and ID. +6. The DO stores a digest of that authenticated credential and a non-secret connection attachment (device/owner/connection IDs, last heartbeat, actions), so a hibernated socket can be revalidated after revival. **Never persist the raw device secret**. Repeated auth/heartbeat/result events re-check D1, rejecting revoked credentials/devices/disabled accounts. +7. The existing Protocol v1 `auth_result` and `heartbeat_ack` frames are unchanged. Stale/unauthenticated connections close. A superseded connection cannot resolve a newly issued command. + +### iPhone lock dispatch + +1. The iPhone submits `POST /cloud/v1/devices/:deviceId/commands` with its opaque access bearer token and `{"action":"lock"}`. **No tenant ID from the client is accepted**. +2. The gateway checks D1 session revocation/expiry, account/device ownership and action before finding the owner's DO. A foreign device is indistinguishable from missing/revoked device (404). +3. The DO independently repeats the access session/owner check and verifies that the live device socket still holds an unrevoked credential. It never accepts `unlock`, shell commands or any action except `lock`. +4. The DO sends the existing Protocol v1 `command` frame with a fresh random nonce, unique command ID and `expires_at = created_at + 10_000 ms`. **If the device is offline it immediately returns 409 and stores nothing**. +5. Only `command_result` on the authenticated, unsuperseded socket bound to the same device **and command ID** can settle the request. Command reports arriving after expiry return timeout. Transport closure returns offline; no in-flight command is replayed after reconnect. +6. The outcome is reported as status + command ID. A device reporting `completed` is an agent acknowledgment, not independent evidence that the physical OS actually locked. Real macOS/Windows live acceptance remains required. + +## Security and operational constraints + +- The **staging gate** and separate **internal DO secret** are two different confidential variables. Operator must configure `MOTE_CLOUD_INTERNAL_SECRET` only in Cloudflare secrets (e.g. `wrangler secret put` with reviewed isolated config); the example intentionally omits its value. Both must be absent from release binaries, Git history, logs and diagnostics. +- This is **staging-only**: public unauthenticated pairing creation and connection attempts need IP/rate/global budgets, admission throttles and abuse protections before the gate can ever be removed. +- The DO tracks at most 32 pending locks per tenant and one per device; every request is deadline-bounded. Account and device revocation are rechecked on the next frame or command, but an **immediate revocation broadcast / eager socket closure** is not yet implemented. This remains a release blocker. +- **Hibernation semantics** and real Cloudflare DO routing are not yet tested by any local Node/CI dry-run. A DO restart loses in-memory in-flight command waiters; do not claim a completed command without an authenticated response. +- The Worker and DO perform separate D1 checks. There remains a TOCTOU window across D1 and DO operations; perform real staging race testing and improve revocation fencing before public release. +- Cross-account tests using synthetic identities and the offline D1 adapter are necessary, **not sufficient** for real multi-user isolation. +- No public Docker/VPS self-host claim. Existing personal one-click Cloudflare self-hosted Worker/DO, macOS/Windows agents, and Protocol v1 remain untouched. + +## Verification commands / source of truth + +```sh +npm ci +npm ci --prefix relay +npm test --prefix relay +npm run typecheck --prefix relay +npx wrangler deploy --config cloud/wrangler.ci.jsonc --dry-run --outdir dist/cloud +``` + +Inspect **actual** GitHub CI for this head SHA and verify all jobs. A Wrangler dry-run does not test tenant DO runtime, hibernation or end-to-end physical lock. + +## Required P0C3 before public access + +1. Prepare a **new, isolated** Cloudflare staging D1 and apply/review `0001_core.sql`, `0002_auth.sql`, `0003_pairing_claim.sql` with backup and rollback. Do not reuse the old personal Relay's SQLite DO or production routing. +2. Configure a distinct disabled-by-default Cloud staging Worker/tenant DO, restricted test credentials, and a real iOS app Bundle ID; perform genuine Apple ID token tests. +3. Verify iOS → Cloud → device WSS → real Windows/macOS `lock` results on physical hardware, including 2-account isolation, delayed result, revocation, hibernation/restart, reconnect and real network outage. +4. Add explicit account deletion, device revoke disconnect, production-appropriate distributed rate limits, per-account quotas and public cost controls; determine signing/installer/website requirements separately. +5. Only after live tests pass and release obligations are met may the team replace the private staging gate with a customer-safe public admission design. + +See [P0C1 pairing](cloud-p0c1-pairing.md), [P0B identity](cloud-p0b-identity.md), [P0A security](cloud-p0a-security.md) and [product launch roadmap](https://github.com/Nardo021/Mote/pull/1). From 59b592c69311cd9f83c760e958e46d1b99bbceaa Mon Sep 17 00:00:00 2001 From: Leo <91056950+Nardo021@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:07:04 +1100 Subject: [PATCH 10/19] fix(cloud): valid regex delimiters for staged WS and command endpoints --- relay/src/cloud/stagingWorker.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/relay/src/cloud/stagingWorker.ts b/relay/src/cloud/stagingWorker.ts index fecfb3f..b62a7f2 100644 --- a/relay/src/cloud/stagingWorker.ts +++ b/relay/src/cloud/stagingWorker.ts @@ -220,7 +220,7 @@ export function createCloudStagingHandler(deps: HandlerDependencies = {}) { // The public WS URL contains ONLY a device UUID. It is a provisional // D1 owner lookup; the target DO must independently verify the v1 // device auth frame credential BEFORE admitting the socket. - const wsRoute = /^\\/cloud\\/v1\\/ws\\/device\\/([a-f0-9-]{36})$/i.exec(url.pathname); + const wsRoute = /^\/cloud\/v1\/ws\/device\/([a-f0-9-]{36})$/i.exec(url.pathname); if (wsRoute && request.method === "GET") { if (request.headers.get("Upgrade")?.toLowerCase() !== "websocket") { return respond(426, { error: "upgrade_required" }); @@ -253,7 +253,7 @@ export function createCloudStagingHandler(deps: HandlerDependencies = {}) { return stub.fetch(new Request(forwarded, { headers })); } - const commandRoute = /^\\/cloud\\/v1\\/devices\\/([a-f0-9-]{36})\\/commands$/i.exec(url.pathname); + const commandRoute = /^\/cloud\/v1\/devices\/([a-f0-9-]{36})\/commands$/i.exec(url.pathname); if (commandRoute && request.method === "POST") { const deviceId = commandRoute[1]; const accessToken = bearerToken(request); From 2389c2d831aead9ebbd5a322b6d09ca50a47c1af Mon Sep 17 00:00:00 2001 From: Leo <91056950+Nardo021@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:08:59 +1100 Subject: [PATCH 11/19] build(cloud): isolate Cloudflare-only tenant class from personal Relay and Node TS programs --- relay/tsconfig.json | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/relay/tsconfig.json b/relay/tsconfig.json index 30c9913..2bdf87f 100644 --- a/relay/tsconfig.json +++ b/relay/tsconfig.json @@ -1,7 +1,9 @@ { "compilerOptions": { "target": "ES2023", - "lib": ["ES2023"], + "lib": [ + "ES2023" + ], "module": "Node16", "moduleResolution": "Node16", "rootDir": "src", @@ -20,6 +22,15 @@ "sourceMap": true, "noEmitOnError": true }, - "include": ["src/**/*.ts"], - "exclude": ["dist", "node_modules", "test", "src/worker/index.ts"] + "include": [ + "src/**/*.ts" + ], + "exclude": [ + "dist", + "node_modules", + "test", + "src/worker/index.ts", + "src/cloud/cloudWorker.ts", + "src/cloud/tenantDurableObject.ts" + ] } From 986bbfbea8ba581579c85f09f86ee338df5adef0 Mon Sep 17 00:00:00 2001 From: Leo <91056950+Nardo021@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:09:02 +1100 Subject: [PATCH 12/19] build(cloud): isolate Cloudflare-only tenant class from personal Relay and Node TS programs --- relay/tsconfig.test.json | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/relay/tsconfig.test.json b/relay/tsconfig.test.json index 18d8d42..ed47404 100644 --- a/relay/tsconfig.test.json +++ b/relay/tsconfig.test.json @@ -6,6 +6,15 @@ "declaration": false, "sourceMap": false }, - "include": ["src/**/*.ts", "test/**/*.ts"], - "exclude": ["dist", "node_modules", "src/worker/index.ts"] + "include": [ + "src/**/*.ts", + "test/**/*.ts" + ], + "exclude": [ + "dist", + "node_modules", + "src/worker/index.ts", + "src/cloud/cloudWorker.ts", + "src/cloud/tenantDurableObject.ts" + ] } From e5da4c15cd229f50aa458a69fe26a92331ef3218 Mon Sep 17 00:00:00 2001 From: Leo <91056950+Nardo021@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:09:06 +1100 Subject: [PATCH 13/19] build(cloud): isolate Cloudflare-only tenant class from personal Relay and Node TS programs --- relay/tsconfig.worker.json | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/relay/tsconfig.worker.json b/relay/tsconfig.worker.json index b450306..59e9616 100644 --- a/relay/tsconfig.worker.json +++ b/relay/tsconfig.worker.json @@ -5,8 +5,19 @@ "rootDir": ".", "declaration": false, "sourceMap": false, - "types": ["node"] + "types": [ + "node" + ] }, - "include": ["src/**/*.ts", "worker-configuration.d.ts"], - "exclude": ["dist", "node_modules", "test"] + "include": [ + "src/**/*.ts", + "worker-configuration.d.ts" + ], + "exclude": [ + "dist", + "node_modules", + "test", + "src/cloud/cloudWorker.ts", + "src/cloud/tenantDurableObject.ts" + ] } From ce7713a18c03cf09eb060274b0689c85c4bf5878 Mon Sep 17 00:00:00 2001 From: Leo <91056950+Nardo021@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:09:16 +1100 Subject: [PATCH 14/19] build(cloud): typecheck hosted DO against separately generated Cloudflare bindings --- relay/tsconfig.cloud.json | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 relay/tsconfig.cloud.json diff --git a/relay/tsconfig.cloud.json b/relay/tsconfig.cloud.json new file mode 100644 index 0000000..55cc570 --- /dev/null +++ b/relay/tsconfig.cloud.json @@ -0,0 +1,22 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": true, + "rootDir": ".", + "declaration": false, + "sourceMap": false, + "types": [ + "node" + ] + }, + "include": [ + "src/**/*.ts", + "cloud-worker-configuration.d.ts" + ], + "exclude": [ + "dist", + "node_modules", + "test", + "src/worker/index.ts" + ] +} From 4f90cbebb816483a4cd3ce2f940b0fe3d3d5bc2e Mon Sep 17 00:00:00 2001 From: Leo <91056950+Nardo021@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:09:26 +1100 Subject: [PATCH 15/19] build(cloud): generate isolated hosted Worker/DO type declarations --- scripts/ensure-cloud-worker-types.mjs | 29 +++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 scripts/ensure-cloud-worker-types.mjs diff --git a/scripts/ensure-cloud-worker-types.mjs b/scripts/ensure-cloud-worker-types.mjs new file mode 100644 index 0000000..4b2f735 --- /dev/null +++ b/scripts/ensure-cloud-worker-types.mjs @@ -0,0 +1,29 @@ +import { spawnSync } from "node:child_process"; +import { existsSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +const wrangler = path.join(root, "node_modules", "wrangler", "bin", "wrangler.js"); +if (!existsSync(wrangler)) { + console.error("Wrangler is not installed. From the repository root, run npm ci."); + process.exit(1); +} +const result = spawnSync( + process.execPath, + [ + wrangler, + "types", + "relay/cloud-worker-configuration.d.ts", + "--config", + "cloud/wrangler.ci.jsonc", + "--env-interface", + "CloudflareCloudBindings", + ], + { cwd: root, stdio: "inherit" }, +); +if (result.error) { + console.error(result.error.message); + process.exit(1); +} +process.exit(result.status ?? 1); From 09a118ab8ca49f427979a010886a4219ba163498 Mon Sep 17 00:00:00 2001 From: Leo <91056950+Nardo021@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:09:37 +1100 Subject: [PATCH 16/19] build(cloud): include hosted DO TypeScript validation in Relay CI --- relay/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/relay/package.json b/relay/package.json index ea5e564..d1f68bd 100644 --- a/relay/package.json +++ b/relay/package.json @@ -8,7 +8,7 @@ "node": ">=22" }, "scripts": { - "typecheck": "node ../scripts/ensure-worker-types.mjs && tsc --noEmit -p tsconfig.json && tsc --noEmit -p tsconfig.test.json && tsc --noEmit -p tsconfig.worker.json", + "typecheck": "node ../scripts/ensure-worker-types.mjs && tsc --noEmit -p tsconfig.json && tsc --noEmit -p tsconfig.test.json && tsc --noEmit -p tsconfig.worker.json && node ../scripts/ensure-cloud-worker-types.mjs && tsc --noEmit -p tsconfig.cloud.json", "test": "node --disable-warning=ExperimentalWarning --import tsx --test test/*.test.ts", "build": "tsc --noEmit -p tsconfig.json" }, From 7a176f9a9679bdf35e1831b4e66f387e3a769534 Mon Sep 17 00:00:00 2001 From: Leo <91056950+Nardo021@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:09:48 +1100 Subject: [PATCH 17/19] build(cloud): ignore generated hosted Worker type declarations --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 31375b1..1a4936d 100644 --- a/.gitignore +++ b/.gitignore @@ -30,6 +30,7 @@ node_modules/ cloud/wrangler.staging.jsonc # Wrangler binding types. Regenerated by `npm run cf-typegen`. relay/worker-configuration.d.ts +relay/cloud-worker-configuration.d.ts dist/ build/ *.tsbuildinfo From 16498e3d30b80eeb3b1e98df317e931386fb0318 Mon Sep 17 00:00:00 2001 From: Leo <91056950+Nardo021@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:10:52 +1100 Subject: [PATCH 18/19] test(cloud): deterministically corrupt JWT signature to avoid flaky negative test --- relay/test/cloudAppleIdentity.test.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/relay/test/cloudAppleIdentity.test.ts b/relay/test/cloudAppleIdentity.test.ts index 041c7cf..204a643 100644 --- a/relay/test/cloudAppleIdentity.test.ts +++ b/relay/test/cloudAppleIdentity.test.ts @@ -49,7 +49,13 @@ test("rejects forged claims, changed signature and invalid header", async () => jwt({}, { alg: "none" }), jwt({}, { kid: "other-key" }), jwt({}, { crit: ["b64"] }), - jwt().replace(/.$/, "x"), + (() => { + const token = jwt(); + const lastDot = token.lastIndexOf("."); + const signature = token.slice(lastDot + 1); + const forgedFirst = signature[0] === "A" ? "B" : "A"; + return token.slice(0, lastDot + 1) + forgedFirst + signature.slice(1); + })(), "abc.def.ghi", "", ]; From e2eee784546d87f24f60917806b9c3d0d2df47fd Mon Sep 17 00:00:00 2001 From: Leo <91056950+Nardo021@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:12:12 +1100 Subject: [PATCH 19/19] test(cloud): preserve tuple types in account fixture under noUncheckedIndexedAccess --- relay/test/cloudRealtime.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/relay/test/cloudRealtime.test.ts b/relay/test/cloudRealtime.test.ts index 5f4a869..5f85865 100644 --- a/relay/test/cloudRealtime.test.ts +++ b/relay/test/cloudRealtime.test.ts @@ -50,7 +50,7 @@ function fixture() { raw.exec(readFileSync(new URL(`../../cloud/migrations/${file}`, import.meta.url), "utf8")); } const db: CloudD1Database = { prepare: (sql) => new Statement(raw, sql) }; - for (const [account, subject] of [[A, "apple-a"], [B, "apple-b"]]) { + for (const [account, subject] of [[A, "apple-a"], [B, "apple-b"]] as const) { raw.prepare("INSERT INTO cloud_accounts(id, apple_subject, created_at_ms) VALUES (?, ?, ?)").run( account, subject, nowMs, );