From 637e1ad20ab1583822eedc9ee2d758e7532ac23e Mon Sep 17 00:00:00 2001 From: Leo <91056950+Nardo021@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:37:43 +1100 Subject: [PATCH 01/14] feat(cloud): verify Apple JWT signatures and one-time nonce claims --- relay/src/cloud/appleIdentity.ts | 199 +++++++++++++++++++++++++++++++ 1 file changed, 199 insertions(+) create mode 100644 relay/src/cloud/appleIdentity.ts diff --git a/relay/src/cloud/appleIdentity.ts b/relay/src/cloud/appleIdentity.ts new file mode 100644 index 0000000..2da7363 --- /dev/null +++ b/relay/src/cloud/appleIdentity.ts @@ -0,0 +1,199 @@ +import { createHash, timingSafeEqual } from "node:crypto"; + +export const APPLE_JWKS_URL = "https://appleid.apple.com/auth/keys"; +const ISSUER = "https://appleid.apple.com"; +const MAX_TOKEN_LENGTH = 12_288; +const MAX_CLOCK_SKEW_SEC = 60; + +type ObjectMap = Record; +export type ApplePublicJwk = Readonly<{ + kty: "RSA"; + kid: string; + use?: string; + alg?: string; + n: string; + e: string; +}>; +export type AppleJwks = Readonly<{ keys: readonly ApplePublicJwk[] }>; +export type VerifiedAppleIdentity = Readonly<{ subject: string }>; + +function record(value: unknown): value is ObjectMap { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +function decodeSegment(value: string): unknown { + if (!/^[A-Za-z0-9_-]+$/.test(value) || value.length > MAX_TOKEN_LENGTH) { + throw new AppleIdentityError("Invalid JWT encoding."); + } + try { + return JSON.parse(Buffer.from(value, "base64url").toString("utf8")) as unknown; + } catch { + throw new AppleIdentityError("Invalid JWT JSON."); + } +} + +function digestNonce(nonce: string): Buffer { + return createHash("sha256").update(nonce, "utf8").digest(); +} + +export function hashAppleNonce(nonce: string): string { + return digestNonce(nonce).toString("hex"); +} + +export class AppleIdentityError extends Error { + constructor(message = "Apple identity could not be verified.") { + super(message); + this.name = "AppleIdentityError"; + } +} + +/** + * Verifies an Apple-issued JWS against pinned issuer/audience, trusted JWKS + * and a one-time nonce digest previously stored by the server in D1. + * + * The caller MUST atomically consume that nonce challenge after verification. + * This function does not do persistence, account creation or replay prevention. + */ +export async function verifyAppleIdentityToken( + token: string, + jwks: AppleJwks, + options: Readonly<{ + audience: string; + expectedNonceHash: string; + nowSec: number; + }>, +): Promise { + if ( + typeof token !== "string" || + token.length === 0 || + token.length > MAX_TOKEN_LENGTH || + !/^[0-9a-f]{64}$/i.test(options.expectedNonceHash) || + !options.audience || + !Number.isSafeInteger(options.nowSec) + ) { + throw new AppleIdentityError(); + } + const parts = token.split("."); + if (parts.length !== 3) { + throw new AppleIdentityError("Invalid JWT segments."); + } + const [protectedHeader, body, signature] = parts; + if (!protectedHeader || !body || !signature || !/^[A-Za-z0-9_-]+$/.test(signature)) { + throw new AppleIdentityError("Invalid JWT shape."); + } + const header = decodeSegment(protectedHeader); + const claims = decodeSegment(body); + if ( + !record(header) || !record(claims) || + header.alg !== "RS256" || + typeof header.kid !== "string" || header.kid.length === 0 || + header.kid.length > 128 || + header.crit !== undefined || + (header.typ !== undefined && header.typ !== "JWT") + ) { + throw new AppleIdentityError("Untrusted JWT header."); + } + const matchingKey = jwks.keys.find( + (key) => key.kid === header.kid && key.kty === "RSA" && + (key.use === undefined || key.use === "sig") && + (key.alg === undefined || key.alg === "RS256") && + typeof key.n === "string" && typeof key.e === "string", + ); + if (!matchingKey) { + throw new AppleIdentityError("Unknown Apple signing key."); + } + + let verified = false; + try { + const key = await crypto.subtle.importKey( + "jwk", + { kty: "RSA", n: matchingKey.n, e: matchingKey.e, alg: "RS256", ext: true }, + { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, + false, + ["verify"], + ); + verified = await crypto.subtle.verify( + "RSASSA-PKCS1-v1_5", + key, + Buffer.from(signature, "base64url"), + new TextEncoder().encode(`${protectedHeader}.${body}`), + ); + } catch { + throw new AppleIdentityError("Apple signature validation failed."); + } + if (!verified) { + throw new AppleIdentityError("Apple signature validation failed."); + } + + const { iss, aud, sub, iat, exp, nbf, nonce } = claims; + if ( + iss !== ISSUER || + aud !== options.audience || + typeof sub !== "string" || sub.length < 1 || sub.length > 256 || + !Number.isSafeInteger(iat) || !Number.isSafeInteger(exp) || + Number(iat) > options.nowSec + MAX_CLOCK_SKEW_SEC || + Number(exp) <= options.nowSec || + Number(exp) - Number(iat) > 24 * 60 * 60 || + (nbf !== undefined && + (!Number.isSafeInteger(nbf) || Number(nbf) > options.nowSec + MAX_CLOCK_SKEW_SEC)) || + typeof nonce !== "string" || + nonce.length < 16 || nonce.length > 512 + ) { + throw new AppleIdentityError("Invalid Apple identity claims."); + } + const expected = Buffer.from(options.expectedNonceHash, "hex"); + const actual = digestNonce(nonce); + if (!timingSafeEqual(actual, expected)) { + throw new AppleIdentityError("Apple identity nonce mismatch."); + } + return { subject: sub }; +} + +/** Fetch only Apple's fixed public JWKS endpoint; no caller-provided URL. */ +export async function fetchAppleJwks(fetcher: typeof fetch = fetch): Promise { + const res = await fetcher(APPLE_JWKS_URL, { + headers: { Accept: "application/json" }, + signal: AbortSignal.timeout(4_000), + }); + if (!res.ok) { + throw new AppleIdentityError("Apple key service unavailable."); + } + const payload = await res.text(); + if (payload.length > 32_768) { + throw new AppleIdentityError("Apple key response too large."); + } + let decoded: unknown; + try { + decoded = JSON.parse(payload) as unknown; + } catch { + throw new AppleIdentityError("Invalid Apple key response."); + } + if (!record(decoded) || !Array.isArray(decoded.keys) || decoded.keys.length > 24) { + throw new AppleIdentityError("Invalid Apple keyset."); + } + const keys: ApplePublicJwk[] = []; + for (const item of decoded.keys as unknown[]) { + if ( + record(item) && + item.kty === "RSA" && + typeof item.kid === "string" && + typeof item.n === "string" && + typeof item.e === "string" && + (item.use === undefined || item.use === "sig") && + (item.alg === undefined || item.alg === "RS256") + ) { + keys.push({ + kty: "RSA", + kid: item.kid, + n: item.n, + e: item.e, + ...(item.alg === undefined ? {} : { alg: item.alg as string }), + ...(item.use === undefined ? {} : { use: item.use as string }), + }); + } + } + if (keys.length === 0) { + throw new AppleIdentityError("Apple JWKS has no usable signing keys."); + } + return { keys }; +} From 887a326163b5fabbcbd21dacedb3a99fb28030ab Mon Sep 17 00:00:00 2001 From: Leo <91056950+Nardo021@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:38:12 +1100 Subject: [PATCH 02/14] feat(cloud): add separate access session credentials and one-time Apple challenges --- cloud/migrations/0002_auth.sql | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 cloud/migrations/0002_auth.sql diff --git a/cloud/migrations/0002_auth.sql b/cloud/migrations/0002_auth.sql new file mode 100644 index 0000000..8547002 --- /dev/null +++ b/cloud/migrations/0002_auth.sql @@ -0,0 +1,24 @@ +-- Mote Cloud hosted D1 ONLY. Stacked after 0001_core.sql. +-- NOT for the existing single-user Durable Object; NOT auto-deployed. + +-- Access credentials are distinct from refresh credentials. Every active API +-- request must check access hash, expiry, revocation, and account status in D1. +ALTER TABLE cloud_sessions ADD COLUMN access_token_hash TEXT; +ALTER TABLE cloud_sessions ADD COLUMN access_expires_at_ms INTEGER; +CREATE UNIQUE INDEX idx_cloud_sessions_access_token_hash + ON cloud_sessions(access_token_hash); +CREATE INDEX idx_cloud_sessions_refresh_token_hash + ON cloud_sessions(refresh_token_hash); + +-- The server issues random nonces. Only a SHA-256 nonce digest is persisted. +-- Consume with a conditional UPDATE and require exactly one affected row. +-- Multiple approvals/replays for the same challenge are rejected. +CREATE TABLE cloud_auth_challenges ( + id TEXT PRIMARY KEY NOT NULL, + nonce_hash TEXT NOT NULL UNIQUE CHECK (length(nonce_hash) = 64), + created_at_ms INTEGER NOT NULL CHECK (created_at_ms > 0), + expires_at_ms INTEGER NOT NULL CHECK (expires_at_ms > created_at_ms), + used_at_ms INTEGER CHECK (used_at_ms IS NULL OR used_at_ms >= created_at_ms) +); +CREATE INDEX idx_cloud_auth_challenges_expiry + ON cloud_auth_challenges(expires_at_ms); From aa228c0311656a1d3c7ff2374ef6fd90b5bf42a9 Mon Sep 17 00:00:00 2001 From: Leo <91056950+Nardo021@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:39:06 +1100 Subject: [PATCH 03/14] feat(cloud): D1-backed Apple challenges, account creation, sessions and owned devices --- relay/src/cloud/identityRepository.ts | 193 ++++++++++++++++++++++++++ 1 file changed, 193 insertions(+) create mode 100644 relay/src/cloud/identityRepository.ts diff --git a/relay/src/cloud/identityRepository.ts b/relay/src/cloud/identityRepository.ts new file mode 100644 index 0000000..3552bca --- /dev/null +++ b/relay/src/cloud/identityRepository.ts @@ -0,0 +1,193 @@ +import { createHash, randomBytes, randomUUID } from "node:crypto"; +import { hashAppleNonce } from "./appleIdentity.js"; +import type { AuthenticatedCloudSession, OwnedCloudDevice } from "./authorization.js"; + +type SqlValue = string | number | null; + +/** Minimal Cloudflare D1 binding surface, also used by the Node SQLite tests. */ +export interface CloudD1Statement { + bind(...values: SqlValue[]): CloudD1Statement; + first(): Promise; + all(): Promise<{ results: T[] }>; + run(): Promise<{ meta: { changes: number } }>; +} +export interface CloudD1Database { + prepare(sql: string): CloudD1Statement; +} + +export type CloudSessionTokens = Readonly<{ + accessToken: string; + refreshToken: string; + accessExpiresAtMs: number; + refreshExpiresAtMs: number; +}>; + +const ACCESS_LIFETIME_MS = 15 * 60_000; +const REFRESH_LIFETIME_MS = 30 * 24 * 60 * 60_000; +const CHALLENGE_LIFETIME_MS = 5 * 60_000; +const TOKEN_PATTERN = /^[A-Za-z0-9_-]{32,128}$/; + +function tokenHash(raw: string): string { + return createHash("sha256").update(raw, "utf8").digest("hex"); +} + +function randomToken(): string { + return randomBytes(32).toString("base64url"); +} + +export class CloudIdentityRepository { + constructor(private readonly db: CloudD1Database) {} + + async createChallenge(nowMs: number): Promise<{ + challengeId: string; + nonce: string; + expiresAtMs: number; + }> { + if (!Number.isSafeInteger(nowMs) || nowMs <= 0) { + throw new Error("Invalid request time."); + } + const challengeId = randomUUID(); + const nonce = randomToken(); + const expiresAtMs = nowMs + CHALLENGE_LIFETIME_MS; + await this.db.prepare( + `INSERT INTO cloud_auth_challenges + (id, nonce_hash, created_at_ms, expires_at_ms) VALUES(?, ?, ?, ?)`, + ).bind(challengeId, hashAppleNonce(nonce), nowMs, expiresAtMs).run(); + return { challengeId, nonce, expiresAtMs }; + } + + /** Returns only a server-stored nonce hash. The mobile client cannot set it. */ + async pendingChallengeHash(challengeId: string, nowMs: number): Promise { + if (typeof challengeId !== "string" || !/^[a-f0-9-]{36}$/i.test(challengeId)) { + return null; + } + const row = await this.db.prepare( + `SELECT nonce_hash FROM cloud_auth_challenges + WHERE id = ? AND used_at_ms IS NULL AND expires_at_ms > ?`, + ).bind(challengeId, nowMs).first<{ nonce_hash: string }>(); + return row?.nonce_hash ?? null; + } + + /** Atomic single-winner replay gate: never log in unless changes === 1. */ + async consumeChallenge(challengeId: string, expectedHash: string, nowMs: number): Promise { + const result = await this.db.prepare( + `UPDATE cloud_auth_challenges SET used_at_ms = ? + WHERE id = ? AND nonce_hash = ? AND used_at_ms IS NULL AND expires_at_ms > ?`, + ).bind(nowMs, challengeId, expectedHash, nowMs).run(); + return result.meta.changes === 1; + } + + async createOrGetAccount(verifiedAppleSubject: string, nowMs: number): Promise { + if (verifiedAppleSubject.length === 0 || verifiedAppleSubject.length > 256) { + return null; + } + await this.db.prepare( + `INSERT INTO cloud_accounts (id, apple_subject, status, created_at_ms) + VALUES(?, ?, 'active', ?) ON CONFLICT(apple_subject) DO NOTHING`, + ).bind(randomUUID(), verifiedAppleSubject, nowMs).run(); + const account = await this.db.prepare( + "SELECT id, status FROM cloud_accounts WHERE apple_subject = ?", + ).bind(verifiedAppleSubject).first<{ id: string; status: string }>(); + return account?.status === "active" ? account.id : null; + } + + async issueSession(accountId: string, nowMs: number): Promise { + const accessToken = randomToken(); + const refreshToken = randomToken(); + const accessExpiresAtMs = nowMs + ACCESS_LIFETIME_MS; + const refreshExpiresAtMs = nowMs + REFRESH_LIFETIME_MS; + await this.db.prepare( + `INSERT INTO cloud_sessions + (id, account_id, refresh_token_hash, access_token_hash, + created_at_ms, expires_at_ms, access_expires_at_ms) + VALUES (?, ?, ?, ?, ?, ?, ?)`, + ).bind( + randomUUID(), accountId, tokenHash(refreshToken), tokenHash(accessToken), + nowMs, refreshExpiresAtMs, accessExpiresAtMs, + ).run(); + return { accessToken, refreshToken, accessExpiresAtMs, refreshExpiresAtMs }; + } + + async authenticateAccess(rawToken: string, nowMs: number): Promise { + if (!TOKEN_PATTERN.test(rawToken)) { + return null; + } + const row = await this.db.prepare( + `SELECT s.id AS session_id, s.account_id, s.expires_at_ms, + s.revoked_at_ms, a.status AS account_status + FROM cloud_sessions s + JOIN cloud_accounts a ON a.id = s.account_id + WHERE s.access_token_hash = ? AND s.access_expires_at_ms > ? + AND s.expires_at_ms > ? AND s.revoked_at_ms IS NULL + AND a.status = 'active'`, + ).bind(tokenHash(rawToken), nowMs, nowMs).first<{ + session_id: string; account_id: string; expires_at_ms: number; + revoked_at_ms: number | null; account_status: "active"; + }>(); + if (!row) return null; + return { + sessionId: row.session_id, accountId: row.account_id, + expiresAtMs: row.expires_at_ms, revokedAtMs: row.revoked_at_ms, + accountStatus: row.account_status, + }; + } + + /** Refresh rotation uses one conditional UPDATE: simultaneous reuse fails. */ + async rotateRefresh(rawToken: string, nowMs: number): Promise { + if (!TOKEN_PATTERN.test(rawToken)) return null; + const accessToken = randomToken(); + const refreshToken = randomToken(); + const accessExpiresAtMs = nowMs + ACCESS_LIFETIME_MS; + const result = await this.db.prepare( + `UPDATE cloud_sessions + SET refresh_token_hash = ?, access_token_hash = ?, access_expires_at_ms = ? + WHERE refresh_token_hash = ? AND revoked_at_ms IS NULL AND expires_at_ms > ? + AND EXISTS ( + SELECT 1 FROM cloud_accounts a + WHERE a.id = cloud_sessions.account_id AND a.status = 'active' + )`, + ).bind( + tokenHash(refreshToken), tokenHash(accessToken), accessExpiresAtMs, + tokenHash(rawToken), nowMs, + ).run(); + if (result.meta.changes !== 1) return null; + // Refresh expiry is fixed at session creation; no unbounded extension. + const row = await this.db.prepare( + "SELECT expires_at_ms FROM cloud_sessions WHERE refresh_token_hash = ?", + ).bind(tokenHash(refreshToken)).first<{ expires_at_ms: number }>(); + if (!row) return null; + return { accessToken, refreshToken, accessExpiresAtMs, refreshExpiresAtMs: row.expires_at_ms }; + } + + async revokeAccessSession(rawToken: string, nowMs: number): Promise { + if (!TOKEN_PATTERN.test(rawToken)) return false; + const result = await this.db.prepare( + `UPDATE cloud_sessions SET revoked_at_ms = ? + WHERE access_token_hash = ? AND revoked_at_ms IS NULL + AND access_expires_at_ms > ? AND expires_at_ms > ?`, + ).bind(nowMs, tokenHash(rawToken), nowMs, nowMs).run(); + return result.meta.changes === 1; + } + + async listActiveDevices(ownerAccountId: string): Promise & { name: string; platform: "macos" | "windows" } + >> { + const rows = await this.db.prepare( + `SELECT id, name, platform, status FROM cloud_devices + WHERE owner_account_id = ? AND status = 'active' ORDER BY created_at_ms DESC`, + ).bind(ownerAccountId).all<{ + id: string; name: string; platform: "macos" | "windows"; status: "active"; + }>(); + return rows.results; + } + + /** Only for future authenticated command routing; never returns secret hashes. */ + async getActiveDevice(deviceId: string): Promise { + const row = await this.db.prepare( + "SELECT id, owner_account_id, status FROM cloud_devices WHERE id = ?", + ).bind(deviceId).first<{ + id: string; owner_account_id: string; status: "active" | "revoked"; + }>(); + return row ? { id: row.id, ownerAccountId: row.owner_account_id, status: row.status } : null; + } +} From 8ab16c5a1aac60eb4e82c2302b0550a0f20b0ded Mon Sep 17 00:00:00 2001 From: Leo <91056950+Nardo021@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:39:58 +1100 Subject: [PATCH 04/14] feat(cloud): add gated isolated staging identity Worker and account device API --- relay/src/cloud/stagingWorker.ts | 169 +++++++++++++++++++++++++++++++ 1 file changed, 169 insertions(+) create mode 100644 relay/src/cloud/stagingWorker.ts diff --git a/relay/src/cloud/stagingWorker.ts b/relay/src/cloud/stagingWorker.ts new file mode 100644 index 0000000..7a88343 --- /dev/null +++ b/relay/src/cloud/stagingWorker.ts @@ -0,0 +1,169 @@ +import { timingSafeEqual } from "node:crypto"; + +import { + AppleIdentityError, + fetchAppleJwks, + verifyAppleIdentityToken, + type AppleJwks, +} from "./appleIdentity.js"; +import { CloudIdentityRepository, type CloudD1Database } from "./identityRepository.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. + */ +export type CloudStagingEnv = Readonly<{ + CLOUD_DB?: CloudD1Database; + MOTE_CLOUD_STAGING_ENABLED?: string; + MOTE_CLOUD_STAGING_GATE?: string; + APPLE_CLIENT_ID?: string; +}>; + +type HandlerDependencies = Readonly<{ + jwks?: () => Promise; + now?: () => number; +}>; + +const SECURITY_HEADERS = { + "Cache-Control": "no-store", + "Content-Type": "application/json; charset=utf-8", + "X-Content-Type-Options": "nosniff", + "Referrer-Policy": "no-referrer", + "X-Frame-Options": "DENY", +} as const; + +function respond(status: number, body: unknown): Response { + return new Response(JSON.stringify(body), { status, headers: SECURITY_HEADERS }); +} + +function gateMatches(provided: string | null, configured: string | undefined): boolean { + if (!provided || !configured || configured.length < 32 || + provided.length !== configured.length) return false; + return timingSafeEqual(Buffer.from(provided, "utf8"), Buffer.from(configured, "utf8")); +} + +async function jsonBody(request: Request): Promise | null> { + const declared = Number(request.headers.get("Content-Length") ?? 0); + if (declared > 16_384) return null; + const text = await request.text(); + if (Buffer.byteLength(text, "utf8") > 16_384) return null; + try { + const parsed: unknown = JSON.parse(text); + if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return null; + return parsed as Record; + } catch { + return null; + } +} + +function bearerToken(request: Request): string | null { + const authorization = request.headers.get("Authorization"); + if (!authorization?.startsWith("Bearer ")) return null; + const token = authorization.slice(7); + return /^[A-Za-z0-9_-]{32,128}$/.test(token) ? token : null; +} + +/** + * P0B staging identity API. Disabled unless BOTH the explicit enable flag + * and the private non-shipped staging gate secret are configured. + * + * NEVER embed MOTE_CLOUD_STAGING_GATE in a public application. + * Rate-limit and pairing hardening precede removing this staging-only gate. + */ +export function createCloudStagingHandler(deps: HandlerDependencies = {}) { + return async function handle(request: Request, env: CloudStagingEnv): Promise { + if ( + env.MOTE_CLOUD_STAGING_ENABLED !== "true" || + !env.CLOUD_DB || + !env.APPLE_CLIENT_ID || + !gateMatches(request.headers.get("X-Mote-Staging-Gate"), env.MOTE_CLOUD_STAGING_GATE) + ) { + return respond(503, { error: "staging_unavailable" }); + } + const url = new URL(request.url); + if (url.protocol !== "https:" && + !(url.hostname === "127.0.0.1" || url.hostname === "localhost")) { + return respond(400, { error: "https_required" }); + } + const nowMs = (deps.now ?? Date.now)(); + const repo = new CloudIdentityRepository(env.CLOUD_DB); + + try { + if (url.pathname === "/cloud/v1/health" && request.method === "GET") { + return respond(200, { service: "mote-cloud", status: "staging" }); + } + + if (url.pathname === "/cloud/v1/auth/challenge" && request.method === "POST") { + return respond(201, await repo.createChallenge(nowMs)); + } + + if (url.pathname === "/cloud/v1/auth/apple" && request.method === "POST") { + const body = await jsonBody(request); + if (typeof body?.identityToken !== "string" || + typeof body.challengeId !== "string") { + return respond(400, { error: "invalid_request" }); + } + const expectedNonceHash = await repo.pendingChallengeHash(body.challengeId, nowMs); + if (!expectedNonceHash) return respond(401, { error: "authentication_failed" }); + const identity = await verifyAppleIdentityToken( + body.identityToken, await (deps.jwks ?? fetchAppleJwks)(), + { + audience: env.APPLE_CLIENT_ID, + expectedNonceHash, + nowSec: Math.floor(nowMs / 1000), + }, + ); + if (!(await repo.consumeChallenge(body.challengeId, expectedNonceHash, nowMs))) { + return respond(401, { error: "authentication_failed" }); + } + const accountId = await repo.createOrGetAccount(identity.subject, nowMs); + if (!accountId) return respond(403, { error: "account_disabled" }); + return respond(200, { accountId, ...(await repo.issueSession(accountId, nowMs)) }); + } + + if (url.pathname === "/cloud/v1/session/refresh" && request.method === "POST") { + const body = await jsonBody(request); + if (typeof body?.refreshToken !== "string") return respond(400, { error: "invalid_request" }); + const tokens = await repo.rotateRefresh(body.refreshToken, nowMs); + return tokens ? respond(200, tokens) : respond(401, { error: "unauthenticated" }); + } + + if (url.pathname === "/cloud/v1/session/logout" && request.method === "POST") { + const raw = bearerToken(request); + if (!raw || !(await repo.authenticateAccess(raw, nowMs))) { + return respond(401, { error: "unauthenticated" }); + } + await repo.revokeAccessSession(raw, nowMs); + return respond(204, null); + } + + if ( + (url.pathname === "/cloud/v1/me" || url.pathname === "/cloud/v1/devices") && + request.method === "GET" + ) { + const raw = bearerToken(request); + const session = raw ? await repo.authenticateAccess(raw, nowMs) : null; + if (!session) return respond(401, { error: "unauthenticated" }); + if (url.pathname === "/cloud/v1/me") { + return respond(200, { accountId: session.accountId }); + } + return respond(200, { devices: await repo.listActiveDevices(session.accountId) }); + } + + // Command dispatch, device WS, pairing and account deletion intentionally + // do NOT exist yet. Never delegate to the personal Relay singleton. + return respond(404, { error: "not_found" }); + } catch (error) { + if (error instanceof AppleIdentityError) { + return respond(401, { error: "authentication_failed" }); + } + console.error("mote cloud staging request failed", { + path: url.pathname, errorName: error instanceof Error ? error.name : "unknown", + }); + return respond(503, { error: "service_unavailable" }); + } + }; +} + +const handler = createCloudStagingHandler(); +export default { fetch: handler }; From 68dfb5f0eefbd9de842cad67e94a380b6bca731a Mon Sep 17 00:00:00 2001 From: Leo <91056950+Nardo021@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:40:31 +1100 Subject: [PATCH 05/14] fix(cloud): send no response body for 204 logout --- relay/src/cloud/stagingWorker.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/relay/src/cloud/stagingWorker.ts b/relay/src/cloud/stagingWorker.ts index 7a88343..604f3c0 100644 --- a/relay/src/cloud/stagingWorker.ts +++ b/relay/src/cloud/stagingWorker.ts @@ -33,7 +33,7 @@ const SECURITY_HEADERS = { } as const; function respond(status: number, body: unknown): Response { - return new Response(JSON.stringify(body), { status, headers: SECURITY_HEADERS }); + return new Response(status === 204 ? null : JSON.stringify(body), { status, headers: SECURITY_HEADERS }); } function gateMatches(provided: string | null, configured: string | undefined): boolean { From 1fab01a9c3acb642283799fe5c0c8003b57ec4d4 Mon Sep 17 00:00:00 2001 From: Leo <91056950+Nardo021@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:40:58 +1100 Subject: [PATCH 06/14] test(cloud): verify Apple JWT signature, claims, nonce and fixed JWKS origin --- relay/test/cloudAppleIdentity.test.ts | 85 +++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 relay/test/cloudAppleIdentity.test.ts diff --git a/relay/test/cloudAppleIdentity.test.ts b/relay/test/cloudAppleIdentity.test.ts new file mode 100644 index 0000000..88ffbe2 --- /dev/null +++ b/relay/test/cloudAppleIdentity.test.ts @@ -0,0 +1,85 @@ +import assert from "node:assert/strict"; +import { generateKeyPairSync, sign } from "node:crypto"; +import test from "node:test"; + +import { + APPLE_JWKS_URL, + fetchAppleJwks, + hashAppleNonce, + verifyAppleIdentityToken, + type AppleJwks, +} from "../src/cloud/appleIdentity.js"; + +const { privateKey, publicKey } = generateKeyPairSync("rsa", { modulusLength: 2048 }); +const jwk = publicKey.export({ format: "jwk" }); +const keys: AppleJwks = { + keys: [{ kty: "RSA", kid: "test-apple-kid", alg: "RS256", use: "sig", n: jwk.n!, e: jwk.e! }], +}; +const nowSec = 1_800_000_000; +const nonce = "super-random-server-issued-nonce-value-123"; +const audience = "com.example.mote.test.ios"; + +function jwt(overrides: Record = {}, header: Record = {}): string { + const head = Buffer.from(JSON.stringify({ alg: "RS256", kid: "test-apple-kid", ...header })).toString("base64url"); + const payload = Buffer.from(JSON.stringify({ + iss: "https://appleid.apple.com", aud: audience, sub: "apple-team-scoped-user-a", + iat: nowSec - 30, exp: nowSec + 600, nonce, ...overrides, + })).toString("base64url"); + const data = `${head}.${payload}`; + return `${data}.${sign("RSA-SHA256", Buffer.from(data), privateKey).toString("base64url")}`; +} + +const settings = { audience, expectedNonceHash: hashAppleNonce(nonce), nowSec }; + +test("verifies genuine RS256 JWT with Apple issuer, audience and server nonce", async () => { + assert.deepEqual(await verifyAppleIdentityToken(jwt(), keys, settings), { + subject: "apple-team-scoped-user-a", + }); +}); + +test("rejects forged claims, changed signature and invalid header", async () => { + const examples = [ + jwt({ iss: "https://attacker.invalid" }), + jwt({ aud: "another.bundle" }), + jwt({ nonce: "forged-server-nonce-value" }), + jwt({ exp: nowSec }), + jwt({ iat: nowSec + 600 }), + jwt({ nbf: nowSec + 600 }), + jwt({ sub: "" }), + jwt({}, { alg: "none" }), + jwt({}, { kid: "other-key" }), + jwt({}, { crit: ["b64"] }), + jwt().replace(/.$/, "x"), + "abc.def.ghi", + "", + ]; + for (const example of examples) { + await assert.rejects( + verifyAppleIdentityToken(example, keys, settings), + { name: "AppleIdentityError" }, + ); + } +}); + +test("rejects wrong nonce digest or untrusted JWKS", async () => { + await assert.rejects(verifyAppleIdentityToken(jwt(), keys, { + ...settings, expectedNonceHash: "a".repeat(64), + })); + await assert.rejects(verifyAppleIdentityToken(jwt(), { keys: [] }, settings)); + await assert.rejects(verifyAppleIdentityToken(jwt(), { + keys: [{ ...keys.keys[0]!, use: "enc" }], + }, settings)); +}); + +test("JWKS resolver accepts only Apple's pinned origin and rejects malformed data", async () => { + let requested = ""; + const safeFetch = (async (input: string | URL | Request) => { + requested = String(input); + return new Response(JSON.stringify({ keys: keys.keys }), { status: 200 }); + }) as typeof fetch; + assert.deepEqual(await fetchAppleJwks(safeFetch), keys); + assert.equal(requested, APPLE_JWKS_URL); + await assert.rejects(fetchAppleJwks((async () => + new Response(JSON.stringify({ keys: [{ kty: "oct", kid: "x" }] }), { status: 200 }) + ) as typeof fetch)); +}); From 021ac249b6c0a83b6edf0ec26d80f53ada0df12b Mon Sep 17 00:00:00 2001 From: Leo <91056950+Nardo021@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:41:53 +1100 Subject: [PATCH 07/14] test(cloud): exercise staged Apple login, nonce replay, account isolation and session rotation --- relay/test/cloudStaging.test.ts | 183 ++++++++++++++++++++++++++++++++ 1 file changed, 183 insertions(+) create mode 100644 relay/test/cloudStaging.test.ts diff --git a/relay/test/cloudStaging.test.ts b/relay/test/cloudStaging.test.ts new file mode 100644 index 0000000..f408b30 --- /dev/null +++ b/relay/test/cloudStaging.test.ts @@ -0,0 +1,183 @@ +import assert from "node:assert/strict"; +import { generateKeyPairSync, sign } from "node:crypto"; +import { readFileSync } from "node:fs"; +import { DatabaseSync, type SQLInputValue } from "node:sqlite"; +import test from "node:test"; + +import type { AppleJwks } from "../src/cloud/appleIdentity.js"; +import type { CloudD1Database, CloudD1Statement } from "../src/cloud/identityRepository.js"; +import { + createCloudStagingHandler, + type CloudStagingEnv, +} from "../src/cloud/stagingWorker.js"; + +const { publicKey, privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 }); +const exported = publicKey.export({ format: "jwk" }); +const jwks: AppleJwks = { keys: [{ + kid: "test-key", kty: "RSA", alg: "RS256", use: "sig", n: exported.n!, e: exported.e!, +}] }; +const nowMs = 1_800_000_000_000; +const audience = "com.example.mote.ios"; +const gate = "test-only-private-staging-gate-not-for-apps"; +const db1 = readFileSync(new URL("../../cloud/migrations/0001_core.sql", import.meta.url), "utf8"); +const db2 = readFileSync(new URL("../../cloud/migrations/0002_auth.sql", import.meta.url), "utf8"); + +class SqliteStatement implements CloudD1Statement { + constructor( + private readonly db: DatabaseSync, + private readonly sql: string, + private readonly args: SQLInputValue[] = [], + ) {} + bind(...values: Array): CloudD1Statement { + return new SqliteStatement(this.db, this.sql, values); + } + async first(): Promise { + return (this.db.prepare(this.sql).get(...this.args) ?? null) as T | null; + } + async all(): Promise<{ results: T[] }> { + return { results: this.db.prepare(this.sql).all(...this.args) as T[] }; + } + async run(): Promise<{ meta: { changes: number } }> { + const result = this.db.prepare(this.sql).run(...this.args); + return { meta: { changes: Number(result.changes) } }; + } +} +function newDb(): { raw: DatabaseSync; binding: CloudD1Database } { + const raw = new DatabaseSync(":memory:"); + raw.exec("PRAGMA foreign_keys = ON"); + raw.exec(db1); + raw.exec(db2); + return { raw, binding: { prepare: (sql) => new SqliteStatement(raw, sql) } }; +} + +function appleToken(nonce: string, subject: string): string { + const header = Buffer.from(JSON.stringify({ kid: "test-key", alg: "RS256" })).toString("base64url"); + const payload = Buffer.from(JSON.stringify({ + iss: "https://appleid.apple.com", aud: audience, sub: subject, + iat: Math.floor(nowMs / 1_000) - 20, exp: Math.floor(nowMs / 1_000) + 600, + nonce, + })).toString("base64url"); + const message = `${header}.${payload}`; + return `${message}.${sign("RSA-SHA256", Buffer.from(message), privateKey).toString("base64url")}`; +} + +function harness() { + const { raw, binding } = newDb(); + const env: CloudStagingEnv = { + CLOUD_DB: binding, + MOTE_CLOUD_STAGING_ENABLED: "true", + MOTE_CLOUD_STAGING_GATE: gate, + APPLE_CLIENT_ID: audience, + }; + const handler = createCloudStagingHandler({ now: () => nowMs, jwks: async () => jwks }); + async function request( + path: string, method = "GET", body?: unknown, token?: string, customGate?: string, + ): Promise<{ status: number; body: any }> { + const response = await handler(new Request(`https://staging.mote.test${path}`, { + method, + headers: { + "X-Mote-Staging-Gate": customGate ?? gate, + ...(body === undefined ? {} : { "Content-Type": "application/json" }), + ...(token === undefined ? {} : { Authorization: `Bearer ${token}` }), + }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + }), env); + const result = await response.text(); + return { status: response.status, body: result ? JSON.parse(result) as unknown : null }; + } + async function signIn(subject: string) { + const challenge = await request("/cloud/v1/auth/challenge", "POST"); + assert.equal(challenge.status, 201); + const login = await request("/cloud/v1/auth/apple", "POST", { + challengeId: challenge.body.challengeId, + identityToken: appleToken(challenge.body.nonce, subject), + }); + assert.equal(login.status, 200); + return { login: login.body, challenge }; + } + return { raw, env, handler, request, signIn }; +} + +test("staging Worker fails closed if not explicitly enabled or gate is invalid", async () => { + const { raw, env, handler, request } = harness(); + try { + assert.equal((await request("/cloud/v1/health", "GET", undefined, undefined, "invalid")).status, 503); + const response = await handler(new Request("https://staging.mote.test/cloud/v1/health", { + headers: { "X-Mote-Staging-Gate": gate }, + }), { ...env, MOTE_CLOUD_STAGING_ENABLED: "false" }); + assert.equal(response.status, 503); + assert.deepEqual(await request("/cloud/v1/health"), { + status: 200, body: { service: "mote-cloud", status: "staging" }, + }); + assert.equal((await request("/cloud/v1/devices")).status, 401); + assert.equal((await request("/cloud/v1/pairings", "POST", {})).status, 404); + } finally { raw.close(); } +}); + +test("Apple identity registers once and consumes its server nonce exactly once", async () => { + const { raw, request, signIn } = harness(); + try { + const { login, challenge } = await signIn("apple-subject-user-a"); + assert.equal(typeof login.accountId, "string"); + assert.equal(typeof login.accessToken, "string"); + const replay = await request("/cloud/v1/auth/apple", "POST", { + challengeId: challenge.body.challengeId, + identityToken: appleToken(challenge.body.nonce, "apple-subject-user-a"), + }); + assert.equal(replay.status, 401); + const second = await signIn("apple-subject-user-a"); + assert.equal(second.login.accountId, login.accountId); + assert.equal( + (raw.prepare("SELECT count(*) AS n FROM cloud_accounts").get() as { n: number }).n, + 1, + ); + const me = await request("/cloud/v1/me", "GET", undefined, login.accessToken); + assert.deepEqual(me, { status: 200, body: { accountId: login.accountId } }); + } finally { raw.close(); } +}); + +test("a wrong Apple subject cannot view another account's devices", async () => { + const { raw, request, signIn } = harness(); + try { + const a = (await signIn("apple-subject-a")).login; + const b = (await signIn("apple-subject-b")).login; + assert.notEqual(a.accountId, b.accountId); + raw.prepare( + `INSERT INTO cloud_devices + (id, owner_account_id, name, platform, credential_hash, created_at_ms, updated_at_ms) + VALUES (?, ?, ?, ?, ?, ?, ?)`, + ).run( + "44444444-4444-4444-8444-444444444444", a.accountId, + "Alice PC", "windows", "f".repeat(64), nowMs, nowMs, + ); + const listA = await request("/cloud/v1/devices", "GET", undefined, a.accessToken); + const listB = await request("/cloud/v1/devices", "GET", undefined, b.accessToken); + assert.equal(listA.status, 200); + assert.equal(listA.body.devices.length, 1); + assert.deepEqual(listB, { status: 200, body: { devices: [] } }); + assert.equal(JSON.stringify(listA.body).includes("credential_hash"), false); + } finally { raw.close(); } +}); + +test("refresh rotation invalidates old credentials, logout revokes, disabled account fails closed", async () => { + const { raw, request, signIn } = harness(); + try { + const { login } = await signIn("apple-subject-a"); + const refreshed = await request("/cloud/v1/session/refresh", "POST", { + refreshToken: login.refreshToken, + }); + assert.equal(refreshed.status, 200); + assert.notEqual(refreshed.body.accessToken, login.accessToken); + assert.equal((await request("/cloud/v1/me", "GET", undefined, login.accessToken)).status, 401); + assert.equal((await request("/cloud/v1/session/refresh", "POST", { + refreshToken: login.refreshToken, + })).status, 401); + assert.equal((await request("/cloud/v1/me", "GET", undefined, refreshed.body.accessToken)).status, 200); + const logout = await request("/cloud/v1/session/logout", "POST", undefined, refreshed.body.accessToken); + assert.equal(logout.status, 204); + assert.equal((await request("/cloud/v1/me", "GET", undefined, refreshed.body.accessToken)).status, 401); + const another = (await signIn("apple-subject-a")).login; + raw.prepare("UPDATE cloud_accounts SET status = 'disabled' WHERE id = ?").run(another.accountId); + assert.equal((await request("/cloud/v1/me", "GET", undefined, another.accessToken)).status, 401); + } finally { raw.close(); } +}); From 3abc020918dbf0d270383db06653b0025b990535 Mon Sep 17 00:00:00 2001 From: Leo <91056950+Nardo021@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:42:23 +1100 Subject: [PATCH 08/14] chore(cloud): add disabled-by-default separate staging Worker template --- cloud/wrangler.staging.example.jsonc | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 cloud/wrangler.staging.example.jsonc diff --git a/cloud/wrangler.staging.example.jsonc b/cloud/wrangler.staging.example.jsonc new file mode 100644 index 0000000..308bf74 --- /dev/null +++ b/cloud/wrangler.staging.example.jsonc @@ -0,0 +1,21 @@ +{ + "$schema": "../node_modules/wrangler/config-schema.json", + "name": "mote-cloud-staging", + "main": "../relay/src/cloud/stagingWorker.ts", + "compatibility_date": "2026-11-16", + "compatibility_flags": ["nodejs_compat"], + "workers_dev": true, + "observability": { "enabled": true }, + "vars": { + "MOTE_CLOUD_STAGING_ENABLED": "false", + "APPLE_CLIENT_ID": "REPLACE_WITH_REAL_IOS_BUNDLE_ID" + }, + "d1_databases": [ + { + "binding": "CLOUD_DB", + "database_name": "mote-cloud-staging", + "database_id": "REPLACE_WITH_NEW_STAGING_D1_ID", + "migrations_dir": "migrations" + } + ] +} From b6d7f9bdff646c1721d11c59ad83c17d97cc962a Mon Sep 17 00:00:00 2001 From: Leo <91056950+Nardo021@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:42:55 +1100 Subject: [PATCH 09/14] ci(cloud): define fail-closed isolated Worker bundle for dry-run checks --- cloud/wrangler.ci.jsonc | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 cloud/wrangler.ci.jsonc diff --git a/cloud/wrangler.ci.jsonc b/cloud/wrangler.ci.jsonc new file mode 100644 index 0000000..ae35dc3 --- /dev/null +++ b/cloud/wrangler.ci.jsonc @@ -0,0 +1,12 @@ +{ + "$schema": "../node_modules/wrangler/config-schema.json", + "name": "mote-cloud-ci-dry-run", + "main": "../relay/src/cloud/stagingWorker.ts", + "compatibility_date": "2026-11-16", + "compatibility_flags": ["nodejs_compat"], + "workers_dev": false, + "vars": { + "MOTE_CLOUD_STAGING_ENABLED": "false", + "APPLE_CLIENT_ID": "ci-placeholder-never-for-auth" + } +} From 892f34be7846c0fef98067af6b263e24bbc61571 Mon Sep 17 00:00:00 2001 From: Leo <91056950+Nardo021@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:43:06 +1100 Subject: [PATCH 10/14] ci(cloud): verify staged Cloud Worker bundles without deploying --- .github/workflows/ci.yml | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index da3885d..d060a94 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -183,6 +183,27 @@ jobs: - name: Test run: dotnet test windows/tests/Mote.Windows.IntegrationTests/Mote.Windows.IntegrationTests.csproj --configuration Release --verbosity normal + cloud-staging: + name: Mote Cloud staging / bundle (dry-run) + runs-on: ubuntu-latest + env: + WRANGLER_SEND_METRICS: "false" + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + cache-dependency-path: | + package-lock.json + relay/package-lock.json + - name: Install + run: | + npm ci + npm ci --prefix relay + - name: Bundle staged Cloud Worker without bindings or deployment + run: npx wrangler deploy --config cloud/wrangler.ci.jsonc --dry-run --outdir dist/cloud + consistency: name: Repository consistency runs-on: ubuntu-latest From 9c4c629b3347e3d6216b3c5af87a3c9f8229a3cb Mon Sep 17 00:00:00 2001 From: Leo <91056950+Nardo021@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:44:16 +1100 Subject: [PATCH 11/14] docs(cloud): document protected staging auth, rollout gates and P0C pairing handoff --- docs/cloud-p0b-identity.md | 77 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 docs/cloud-p0b-identity.md diff --git a/docs/cloud-p0b-identity.md b/docs/cloud-p0b-identity.md new file mode 100644 index 0000000..b394280 --- /dev/null +++ b/docs/cloud-p0b-identity.md @@ -0,0 +1,77 @@ +# Mote Cloud P0B — Staging authentication and D1 ownership API + +**Date:** 2026-11-16 +**Status:** SOURCE IMPLEMENTED; CI and staging deployment evidence must be checked separately. +**Branch:** `feature/mote-cloud-p0b-auth-20261116`, stacked on `feature/mote-cloud-p0a-20261116` / Draft PR #2. + +## What this slice adds + +A separate staging-only Worker entrypoint, **not a change to the existing self-hosted Worker**: + +- `relay/src/cloud/stagingWorker.ts` — gated HTTP API; never forwarded by `relay/src/worker/index.ts`. +- `relay/src/cloud/appleIdentity.ts` — Apple identity token JWS signature verification using the **fixed** Apple signing-keys URL, RS256 JWKS key ID and server-stored challenge nonce, plus issuer, exact configured audience, issuance and expiry validation. The verified `sub` is used as identity, **never email**. Apple currently publishes RSA/RS256 keys at `https://appleid.apple.com/auth/keys`. +- `relay/src/cloud/identityRepository.ts` — D1 read/write operations for one-time sign-in challenges, Apple-subject account lookup/creation, 15-minute opaque access tokens, 30-day refresh sessions, single-winner refresh rotation and revocation; device queries always filter by verified account ID. +- `cloud/migrations/0002_auth.sql` — adds access-token digest and one-time nonce challenge table to the *new, separate* hosted D1 database. +- `relay/test/cloudAppleIdentity.test.ts`, `relay/test/cloudStaging.test.ts` — local synthetic-JWT, SQLite and HTTP-handler tests. No real Apple identity, live Cloudflare traffic or desktop lock is simulated or claimed. +- `cloud/wrangler.ci.jsonc` — fail-closed **dry-run bundle only**. Root CI separately builds this new Worker with `--dry-run` and never deploys it. +- `cloud/wrangler.staging.example.jsonc` — disabled-by-default deploy template with unfilled Apple Bundle ID and isolated D1 ID. + +## Staging API (all routes require a private staging gate) + +| Method | Route | Purpose | State | +|---|---|---|---| +| GET | `/cloud/v1/health` | Staging health | Implemented, gated | +| POST | `/cloud/v1/auth/challenge` | Create random nonce, store SHA-256 digest | Implemented, gated | +| POST | `/cloud/v1/auth/apple` | Verify Apple JWT and atomic challenge use; create/get account, issue session | Implemented, gated | +| POST | `/cloud/v1/session/refresh` | Rotate refresh and access tokens; old credentials fail | Implemented, gated | +| POST | `/cloud/v1/session/logout` | Revoke current session | Implemented, gated | +| GET | `/cloud/v1/me` | Display authenticated account ID | Implemented, gated | +| GET | `/cloud/v1/devices` | List only the signed-in account's active devices | Implemented, gated | +| ALL | `/cloud/v1/pairings/*`, `/cloud/v1/ws/*`, commands, deletion | No public device control yet | **404 / NOT IMPLEMENTED** | + +**First-run authentication:** client calls challenge endpoint, sends returned `nonce` as the Apple request nonce in a real `ASAuthorizationAppleIDRequest`, receives Apple identity token, then sends `identityToken` + `challengeId` to the exchange endpoint. Backend reads expected nonce hash from D1; refuses token mismatch; consumes nonce through `UPDATE ... WHERE used_at_ms IS NULL AND expires_at_ms > now` and requires exactly one changed row. It creates a Mote account for Apple's stable subject and returns random access + refresh session tokens. The app will store tokens in iOS Keychain; never send them through URL query strings. + +**Environment guard:** requests are rejected unless `MOTE_CLOUD_STAGING_ENABLED=true`, `APPLE_CLIENT_ID` is configured, `CLOUD_DB` is bound, and a non-empty private `MOTE_CLOUD_STAGING_GATE` of at least 32 characters is supplied in `X-Mote-Staging-Gate`. This gate is ONLY for internal staging and must **never** be embedded in a distributed iOS/desktop app. Native users will use the eventual public API after abuse limiting and secure end-to-end pairing exist. + +## Configuration and activation procedure (NOT EXECUTED) + +No live D1 database was created or modified in this PR. To set up a **future isolated staging sandbox**, a human operator must first review the test and security evidence and then: + +1. Create a **new** Cloudflare D1 database specifically for Mote Cloud Staging, not the personal/self-host DO. Record its actual ID using the provider's tool. Validate the database is not referenced by other Workers. +2. Copy `cloud/wrangler.staging.example.jsonc` to `cloud/wrangler.staging.jsonc` (a local, intentionally untracked operator file). Replace `REPLACE_WITH_NEW_STAGING_D1_ID` with the verified database ID; replace `APPLE_CLIENT_ID` with the actual signed iOS app's Bundle ID. Keep `MOTE_CLOUD_STAGING_ENABLED=false` during initial setup. +3. Review and apply `0001_core.sql`, then `0002_auth.sql` **only to the new staging database** via Wrangler D1 migrations with an explicit `--config cloud/wrangler.staging.jsonc` and `--remote`, after reviewing migration target and backup/rollback. Never use the root `wrangler.jsonc` or the `mote` DO as migration target. +4. Configure a high-entropy private `MOTE_CLOUD_STAGING_GATE` as a **secret**, not a file or public Worker var. Test the default disabled mode and missing/wrong-gate refusal before enabling the explicit staging flag. +5. Gate test traffic to a small authorized internal team. Verify with an actual Apple-signed native token, then run rotation, replay and account A/B negative tests against the real staging D1 and Worker. Keep logs free of credentials. +6. If any test fails, set `MOTE_CLOUD_STAGING_ENABLED=false` and investigate; no DNS/public launch follows from this stage. + +**Caution:** The template uses placeholder database ID and Bundle ID; it is intentionally not deployable without operator configuration. Nothing here implies Apple Developer credentials have been created or that a public URL is live. + +## Security caveats / next required work + +- **No public registration:** the unauthenticated challenge endpoint is **not** yet safe against distributed abuse at internet scale. The staging gate is a temporary internal control, not something to ship. Before removing it, add edge-level rate limiting, request budgets/abuse detection and validated session issuance load tests. +- **Apple token assurance:** tests validate locally signed synthetic tokens against locally generated JWKS. Real Apple server integration and Apple authorization code exchange / Apple refresh-token account standing checks must be reviewed before public launch. If Apple's active ID-token signature algorithm or key shape changes, update the strict verifier only with authoritative evidence and tests. +- **No device pairing or locking:** P0A's ownership policy and P0B's D1 device queries exist, but no Cloud WebSocket, pairing, command dispatch, account deletion, revocation broadcast or device key enrollment have been implemented. Existing `/v1/*` personal relay remains isolated. +- **No customer app:** native iOS, default Cloud desktop bootstrap and account deletion UI are separate P1–P3 slices. +- **Operational safety:** real D1 schema/migration tests, failure-injection, quota enforcement, 24-hour soak and observability are still blockers. For production, assess session token theft/reuse detection and robust refresh-token family revocation. Current rotation rejects the old token, but does not yet detect prior token theft using token family history. +- **Access token policy:** opaque random 256-bit tokens, SHA-256 hashes at rest, 15-minute access life, 30-day non-sliding refresh session lifetime. Logout revokes the current session. No raw credentials in the database or activity logs. +- **Endpoint DNS:** no production/staging domain committed; do not embed a guessed base URL in signed clients. + +### Validation commands + +```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 +``` + +CI should execute these through existing Relay/Protocol and new staging dry-run jobs. A passing bundle **does not** prove a live deploy, a genuine Apple token, Cloudflare D1 semantics under contention, or App Store readiness. + +## Next implementation (P0C) + +1. Add **real D1 transactional one-time pairing claims**, separate desktop polling proof and authenticated per-account WebSocket tenant isolation. +2. Add two-account **end-to-end** negative authorization tests under real staging, alongside appropriate rate limiting and device credential revocation. +3. Only then implement signed desktop Cloud-first pairing and iOS screens against the public-ready API. Keep self-hosting as an independent Advanced profile. + +[GitHub P0A security contract](cloud-p0a-security.md) · [Public product roadmap (Draft PR #1)](https://github.com/Nardo021/Mote/pull/1). From 42c134e6889bb51028af861a5b9ce1e6fa783d59 Mon Sep 17 00:00:00 2001 From: Leo <91056950+Nardo021@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:44:35 +1100 Subject: [PATCH 12/14] chore(cloud): ignore operator-specific staging config and database ID --- .gitignore | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitignore b/.gitignore index eeac28c..31375b1 100644 --- a/.gitignore +++ b/.gitignore @@ -26,6 +26,8 @@ id_ecdsa # Node.js / TypeScript node_modules/ +# Local operator-specific Cloud staging binding configuration (never commit IDs). +cloud/wrangler.staging.jsonc # Wrangler binding types. Regenerated by `npm run cf-typegen`. relay/worker-configuration.d.ts dist/ From 133bb437779ba5947dbc3e5016a003439cd00f5e Mon Sep 17 00:00:00 2001 From: Leo <91056950+Nardo021@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:46:04 +1100 Subject: [PATCH 13/14] test(cloud): use dedicated test audience without forbidden legacy bundle ID --- relay/test/cloudAppleIdentity.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/relay/test/cloudAppleIdentity.test.ts b/relay/test/cloudAppleIdentity.test.ts index 88ffbe2..041c7cf 100644 --- a/relay/test/cloudAppleIdentity.test.ts +++ b/relay/test/cloudAppleIdentity.test.ts @@ -17,7 +17,7 @@ const keys: AppleJwks = { }; const nowSec = 1_800_000_000; const nonce = "super-random-server-issued-nonce-value-123"; -const audience = "com.example.mote.test.ios"; +const audience = "com.nardo021.mote.testing.test.ios"; function jwt(overrides: Record = {}, header: Record = {}): string { const head = Buffer.from(JSON.stringify({ alg: "RS256", kid: "test-apple-kid", ...header })).toString("base64url"); From 8d93b130bf88f319197d713f7fd383df420f733f Mon Sep 17 00:00:00 2001 From: Leo <91056950+Nardo021@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:46:07 +1100 Subject: [PATCH 14/14] test(cloud): use dedicated test audience without forbidden legacy bundle ID --- relay/test/cloudStaging.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/relay/test/cloudStaging.test.ts b/relay/test/cloudStaging.test.ts index f408b30..bfc9a16 100644 --- a/relay/test/cloudStaging.test.ts +++ b/relay/test/cloudStaging.test.ts @@ -17,7 +17,7 @@ const jwks: AppleJwks = { keys: [{ kid: "test-key", kty: "RSA", alg: "RS256", use: "sig", n: exported.n!, e: exported.e!, }] }; const nowMs = 1_800_000_000_000; -const audience = "com.example.mote.ios"; +const audience = "com.nardo021.mote.testing.ios"; const gate = "test-only-private-staging-gate-not-for-apps"; const db1 = readFileSync(new URL("../../cloud/migrations/0001_core.sql", import.meta.url), "utf8"); const db2 = readFileSync(new URL("../../cloud/migrations/0002_auth.sql", import.meta.url), "utf8");