Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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/
Expand Down
24 changes: 24 additions & 0 deletions cloud/migrations/0002_auth.sql
Original file line number Diff line number Diff line change
@@ -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);
12 changes: 12 additions & 0 deletions cloud/wrangler.ci.jsonc
Original file line number Diff line number Diff line change
@@ -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"
}
}
21 changes: 21 additions & 0 deletions cloud/wrangler.staging.example.jsonc
Original file line number Diff line number Diff line change
@@ -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"
}
]
}
77 changes: 77 additions & 0 deletions docs/cloud-p0b-identity.md
Original file line number Diff line number Diff line change
@@ -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).
199 changes: 199 additions & 0 deletions relay/src/cloud/appleIdentity.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>;
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<VerifiedAppleIdentity> {
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<AppleJwks> {
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 };
}
Loading
Loading