From 356bfcebeea305c5cedec86e3622b6e68a263688 Mon Sep 17 00:00:00 2001 From: "propr-dev[bot]" <1316198+propr-dev[bot]@users.noreply.github.com> Date: Sat, 29 Aug 2026 14:29:57 +0000 Subject: [PATCH] fix(ai): Resolve issue #1955 - Add secure desktop pairing tokens and compatibilit Implemented by ProPR AI using gpt-5.6-sol model. Implementation completed successfully. --- .env.example | 8 + docs/docs/concepts/security-overview.md | 2 +- docs/docs/operations/desktop-pairing.md | 102 ++++ docs/sidebars.ts | 1 + packages/api/README.md | 9 +- packages/api/auth.ts | 78 ++- packages/api/desktopAuthService.ts | 443 ++++++++++++++++++ packages/api/expressUser.d.ts | 2 + packages/api/requestRateLimits.ts | 39 ++ packages/api/routes/desktopAuthRoutes.ts | 162 +++++++ packages/api/routes/index.ts | 1 + packages/api/routes/statusRoutes.ts | 13 +- packages/api/server.ts | 44 +- packages/api/test/desktopAuth.test.ts | 261 +++++++++++ packages/api/test/requestRateLimits.test.ts | 3 + .../api/test/socketAuthentication.test.ts | 13 + packages/api/test/statusRoutes.test.ts | 27 ++ .../20260829000000_create_desktop_auth.js | 67 +++ packages/shared/src/index.ts | 1 + packages/shared/src/proprCompatibility.ts | 16 +- propr-ui/src/App.tsx | 2 + propr-ui/src/api/desktopAuth.ts | 32 ++ .../src/pages/DesktopPairingPage.test.tsx | 51 ++ propr-ui/src/pages/DesktopPairingPage.tsx | 91 ++++ 24 files changed, 1446 insertions(+), 22 deletions(-) create mode 100644 docs/docs/operations/desktop-pairing.md create mode 100644 packages/api/desktopAuthService.ts create mode 100644 packages/api/routes/desktopAuthRoutes.ts create mode 100644 packages/api/test/desktopAuth.test.ts create mode 100644 packages/core/src/db/migrations/20260829000000_create_desktop_auth.js create mode 100644 propr-ui/src/api/desktopAuth.ts create mode 100644 propr-ui/src/pages/DesktopPairingPage.test.tsx create mode 100644 propr-ui/src/pages/DesktopPairingPage.tsx diff --git a/.env.example b/.env.example index e27d41336..4f2f762b6 100644 --- a/.env.example +++ b/.env.example @@ -312,6 +312,14 @@ DASHBOARD_API_PORT=4000 # security). Defaults to http://localhost:4000 when unset; set it to the # https://t-.propr.dev host when the hosted UI tunnel is enabled. # API_PUBLIC_URL=http://localhost:4000 +# Optional lifetime for newly paired desktop instance tokens. When unset, +# tokens remain valid until the owner revokes them. Range: 1-3650 days. +# PROPR_DESKTOP_TOKEN_TTL_DAYS=90 +# Optional per-IP desktop discovery/pairing quotas. Defaults are documented in +# docs/docs/operations/desktop-pairing.md. +# PROPR_DISCOVERY_RATE_LIMIT_MAX=60 +# PROPR_PAIRING_START_RATE_LIMIT_MAX=10 +# PROPR_PAIRING_POLL_RATE_LIMIT_MAX=180 # Session cookie domain. Leave UNSET for v1 — including hosted UI tunnel proxy # sessions, which run on a single t-.propr.dev host (see the tunnel # section above). Only set it for a custom multi-subdomain deployment. diff --git a/docs/docs/concepts/security-overview.md b/docs/docs/concepts/security-overview.md index ea8bd9266..d64023dbb 100644 --- a/docs/docs/concepts/security-overview.md +++ b/docs/docs/concepts/security-overview.md @@ -30,7 +30,7 @@ The API and worker use the host Docker socket to launch task containers; the API - **Inbound: none required.** The default event intake is an outbound WebSocket to the routing service, so a stack behind NAT or a firewall works without exposing any port. The API (4000) and Web UI (5173) bind locally; expose them deliberately (reverse proxy, VPN, or the managed [hosted UI tunnel](../operations/deployment.md#hosted-ui-tunnel)). - **`direct_webhook` mode** (advanced) is the exception: it requires a public `POST /webhook` endpoint and a webhook secret. -- **Unauthenticated endpoints:** `GET /api/compatibility` is intentionally unauthenticated so the hosted UI can check version compatibility before login — the release version of your stack is readable pre-auth. Treat that as public information or keep the API off the public internet. +- **Unauthenticated endpoints:** `GET /api/compatibility` and `GET /api/desktop/discovery` intentionally expose only product/version compatibility and desktop-auth capabilities. The rate-limited desktop pairing start/poll endpoints use a high-entropy, body-only device secret and disclose an instance token only after browser-session approval. Treat version metadata as public information or keep the API off the public internet. - API access is protected by session auth (GitHub OAuth) and optional bearer-token auth for automation. - **Organizations with GitHub IP allow lists**: add your ProPR server's egress IP to the org allow list. The GitHub App deliberately declares no IP allow list of its own: every API call comes from your self-hosted stack at your own address, so inheriting an App-level list would block your own stack. diff --git a/docs/docs/operations/desktop-pairing.md b/docs/docs/operations/desktop-pairing.md new file mode 100644 index 000000000..5d2e035a7 --- /dev/null +++ b/docs/docs/operations/desktop-pairing.md @@ -0,0 +1,102 @@ +# Desktop pairing protocol + +Packaged desktop clients authenticate to one ProPR instance with an opaque +instance token. They never receive or persist a GitHub access or refresh token. +Protocol version 1 is designed for the Electron main process (or another trusted +native process); renderer code must communicate with it through a narrow IPC +bridge and must not read the device secret or instance token. + +## Discovery + +Before login, call `GET /api/desktop/discovery` (or the existing +`GET /api/compatibility`). The dedicated response is deliberately limited to +the product name, release/API/UI compatibility values, and this capability: + +```json +{ + "product": "ProPR", + "version": "0.8.15", + "apiCompatibility": "2026-06-27", + "uiCompatibility": "2026-06-27", + "desktopAuthentication": { + "protocolVersion": 1, + "browserPairing": true, + "instanceBearerTokens": true, + "socketIoBearerAuthentication": true + } +} +``` + +Discovery is rate limited per trusted network address. A `false` capability +means the deployment (for example, public demo mode) must not be paired. + +## Pairing sequence + +1. The trusted desktop process sends `POST /api/desktop/pairings` with + `{"clientName":"Alice's MacBook"}`. `clientName` is printable text from 1 + through 80 characters. +2. A `201` response contains `pairingId`, `deviceSecret`, `approvalUrl`, + `expiresAt`, and `interval` (seconds). Both identifiers have at least 128 bits + of entropy; the device secret has 256 bits. Store the secret only in trusted + process memory and open the exact `approvalUrl` in the system browser. Do not + append a redirect or origin supplied by the renderer. +3. The browser entry validates the unexpired request, initiates the instance's + normal GitHub login when necessary, and redirects to the fixed ProPR approval + page. The approval page shows the client name and requires an explicit click. + `POST /api/desktop/pairings/{pairingId}/approve` accepts only an authenticated + browser session and the exact configured `FRONTEND_URL` origin. GitHub bearer + and instance-token principals cannot approve a pairing. +4. No more often than `interval`, the trusted process sends + `POST /api/desktop/pairings/{pairingId}/poll` with + `{"deviceSecret":"..."}`. The secret is in the JSON body, never a URL or + header that an intermediary normally logs. A pending request returns `202` + with `{"status":"pending","interval":5}`. +5. The first valid poll after approval returns `200` with + `{"status":"complete","token":"propr_it_...","tokenType":"Bearer","expiresAt":null}`. + The polling grant is consumed in the same transaction that creates the token; + subsequent polls return `409 PAIRING_ALREADY_CONSUMED`. If the success response + is lost, begin a new pairing rather than retrying for the credential. + +Pairings expire after ten minutes. An unknown ID or wrong secret returns the +same `404 PAIRING_NOT_FOUND`; an expired request returns `410 PAIRING_EXPIRED`. +Start and poll routes have separate IP quotas. Clients must honor HTTP `429` and +`Retry-After` and must stop at `expiresAt`. + +## Using and storing the token + +Send the returned token as `Authorization: Bearer propr_it_...` on normal REST +requests. For Socket.IO, set that same header on the Engine.IO WebSocket +handshake (Electron/Node clients can use `extraHeaders`). The socket identity is +revalidated periodically, so token revocation, expiry, role changes, permission +changes, or whitelist removal disconnect an established client. + +Store the token in an operating-system credential facility such as macOS +Keychain, Windows Credential Manager, or Linux Secret Service. Never put it in +`localStorage`, IndexedDB, renderer state, a pairing URL, logs, crash reports, or +analytics. Keep the instance origin with the credential and refuse to send it to +another origin. Treat TLS certificate failures as terminal; HTTP is accepted +only for loopback development. + +The server stores SHA-256 token and device-secret hashes, never plaintext. Token +rows retain the owner GitHub ID/profile snapshot, creation and last-use times, +optional expiry, and revocation metadata. Authorization still resolves the +owner's current instance role and permissions on each request. Set +`PROPR_DESKTOP_TOKEN_TTL_DAYS` to an integer from 1 through 3650 to issue expiring +tokens; when unset, tokens remain valid until revoked. Expired pairing rows are +cleaned hourly after a short retention period used for stable client errors. + +## Token management + +Both routes require any accepted authentication method and operate only on the +authenticated user's tokens: + +- `GET /api/desktop/tokens` returns `{ "tokens": [...] }` with `id`, `name`, + `tokenHint`, `createdAt`, `lastUsedAt`, `expiresAt`, and `revokedAt`. It never + returns a hash or token. +- `DELETE /api/desktop/tokens/{tokenId}` returns `204` after revoking an active + owned token. Unknown, already-revoked, and other users' IDs all return + `404 TOKEN_NOT_FOUND`. + +Pairing start, approval, token issuance, and revocation write audit rows and +structured logs containing IDs and the display name only. Device secrets, +instance tokens, token hashes, and GitHub tokens are excluded. diff --git a/docs/sidebars.ts b/docs/sidebars.ts index 00ebb2b77..5a2ca320c 100644 --- a/docs/sidebars.ts +++ b/docs/sidebars.ts @@ -127,6 +127,7 @@ const sidebars: SidebarsConfig = { 'operations/propr-connect', 'operations/connect-dashboard', 'operations/hosted-ui-tunnel', + 'operations/desktop-pairing', 'operations/pwa-web-push', 'operations/configuration-reference', 'operations/metrics', diff --git a/packages/api/README.md b/packages/api/README.md index f83083f6a..e253cec97 100644 --- a/packages/api/README.md +++ b/packages/api/README.md @@ -59,12 +59,19 @@ To run the API in development mode: ## API Endpoints -All API endpoints are protected by authentication: +All operational API endpoints are protected by authentication. Compatibility, +desktop discovery, and the bounded pairing bootstrap/poll routes are the +documented pre-authentication exceptions: - `GET /api/auth/github` - Initiate GitHub OAuth flow - `GET /api/auth/github/callback` - OAuth callback - `GET /api/auth/logout` - Logout user - `GET /api/auth/user` - Get sanitized current user info, instance role, and permissions +- `GET /api/desktop/discovery` - Public product/API compatibility and desktop-auth capabilities only +- `POST /api/desktop/pairings` - Start a short-lived browser pairing request +- `POST /api/desktop/pairings/:pairingId/poll` - Poll with the device secret in the JSON body +- `GET /api/desktop/tokens` - List the current user's safe instance-token metadata +- `DELETE /api/desktop/tokens/:tokenId` - Revoke one of the current user's instance tokens - `GET /api/catalog` - Get the sanitized enabled repository/agent catalog needed by member workflows - `GET /api/repositories/indexing-status` - Get indexing status projected to enabled catalog repository/branch entries - `GET /api/admin/members` - List explicit role assignments (administrator) diff --git a/packages/api/auth.ts b/packages/api/auth.ts index 8cc796ec7..7cb526634 100644 --- a/packages/api/auth.ts +++ b/packages/api/auth.ts @@ -1,3 +1,4 @@ +/* eslint-disable max-lines -- browser, GitHub bearer, instance-token, and Socket.IO auth share one policy boundary */ import passport from 'passport'; import { Strategy as GitHubStrategy, Profile } from 'passport-github2'; import session from 'express-session'; @@ -7,6 +8,7 @@ import { randomBytes } from 'node:crypto'; import type { Express, Request, Response, NextFunction, RequestHandler } from 'express'; import { validateSessionSecret } from '@propr/shared'; import { validateGitHubToken } from './authBearer.js'; +import { desktopAuthService, INSTANCE_TOKEN_PREFIX } from './desktopAuthService.js'; import { configureDemoMode, getDemoUser, isDemoMode } from './demoMode.js'; import { clearSessionForReauth, isGitHubTokenExpired, refreshGitHubTokenIfNeeded, refreshGitHubTokenWithResult } from './authGithubTokens.js'; import { getValidatedRedirectTo, getDefaultRedirectUrl } from './authRedirect.js'; @@ -50,6 +52,7 @@ export interface SocketPrincipal { export interface SocketAuthenticationDependencies { validateToken: typeof validateGitHubToken; + validateInstanceToken?: typeof desktopAuthService.validateToken; isWhitelisted: typeof isUserWhitelisted; resolveInstanceAuthorization: typeof resolveInstanceAuthorization; refreshToken: typeof refreshGitHubTokenWithResult; @@ -57,6 +60,7 @@ export interface SocketAuthenticationDependencies { const defaultSocketAuthenticationDependencies: SocketAuthenticationDependencies = { validateToken: validateGitHubToken, + validateInstanceToken: token => desktopAuthService.validateToken(token), isWhitelisted: isUserWhitelisted, resolveInstanceAuthorization, refreshToken: refreshGitHubTokenWithResult, @@ -324,6 +328,8 @@ export function setupAuth(app: Express, demoModeAtStartup = isDemoMode()): Socke * HTTP API. Browser clients normally arrive with a Passport session cookie; * non-browser clients may provide the normal Authorization: Bearer header. */ +// Session refresh and two bearer credential classes intentionally fail closed here. +// eslint-disable-next-line complexity export async function authenticateSocketRequest( req: Request, dependencies: SocketAuthenticationDependencies = defaultSocketAuthenticationDependencies, @@ -350,20 +356,41 @@ export async function authenticateSocketRequest( throw new SocketAuthenticationError('USER_NOT_WHITELISTED', 'GitHub user is not allowed'); } + req.authenticationMethod = 'session'; return { user: req.user, authorization: await dependencies.resolveInstanceAuthorization(req.user), }; } - const bearerEnabled = process.env.ENABLE_BEARER_AUTH !== 'false'; const rawAuthHeader = req.headers.authorization; const authHeader = Array.isArray(rawAuthHeader) ? rawAuthHeader[0] : rawAuthHeader; - if (bearerEnabled && authHeader?.startsWith('Bearer ')) { + if (authHeader?.startsWith('Bearer ')) { const token = authHeader.slice(7).trim(); if (!token) { throw new SocketAuthenticationError('INVALID_BEARER_TOKEN', 'Bearer token is empty'); } + if (token.startsWith(INSTANCE_TOKEN_PREFIX)) { + const identity = await (dependencies.validateInstanceToken + ? dependencies.validateInstanceToken(token) + : desktopAuthService.validateToken(token)); + if (!identity) { + throw new SocketAuthenticationError('INVALID_INSTANCE_TOKEN', 'Instance token is invalid'); + } + if (!dependencies.isWhitelisted(identity.user.username)) { + throw new SocketAuthenticationError('USER_NOT_WHITELISTED', 'GitHub user is not allowed'); + } + req.authenticationMethod = 'instance_token'; + req.instanceTokenId = identity.tokenId; + return { + user: identity.user, + authorization: await dependencies.resolveInstanceAuthorization(identity.user), + }; + } + const bearerEnabled = process.env.ENABLE_BEARER_AUTH !== 'false'; + if (!bearerEnabled) { + throw new SocketAuthenticationError('AUTHENTICATION_REQUIRED', 'Authentication required'); + } const user = await dependencies.validateToken(token); if (!user) { throw new SocketAuthenticationError('INVALID_BEARER_TOKEN', 'Bearer token is invalid'); @@ -371,6 +398,7 @@ export async function authenticateSocketRequest( if (!dependencies.isWhitelisted(user.username)) { throw new SocketAuthenticationError('USER_NOT_WHITELISTED', 'GitHub user is not allowed'); } + req.authenticationMethod = 'github_bearer'; return { user, authorization: await dependencies.resolveInstanceAuthorization(user), @@ -380,12 +408,20 @@ export async function authenticateSocketRequest( throw new SocketAuthenticationError('AUTHENTICATION_REQUIRED', 'Authentication required'); } -export async function ensureAuthenticated(req: Request, res: Response, next: NextFunction): Promise { +// Keep REST precedence identical to Socket.IO: demo, session, instance token, GitHub bearer. +// eslint-disable-next-line complexity +export async function ensureAuthenticated( + req: Request, + res: Response, + next: NextFunction, + validateInstanceToken: (token: string) => ReturnType = token => desktopAuthService.validateToken(token), +): Promise { if (isDemoMode()) { res.set('X-ProPR-Demo-Mode', 'true'); // Demo mode is deployment-wide: browser callers receive the synthetic read-only user. // Stale bearer headers are ignored so public demo visitors are treated consistently. (req as Request & { user: GitHubUser }).user = getDemoUser(); + req.authenticationMethod = 'demo'; return next(); } @@ -424,15 +460,42 @@ export async function ensureAuthenticated(req: Request, res: Response, next: Nex console.error('Background token refresh failed:', err); }); } + req.authenticationMethod = 'session'; return next(); } - // Bearer token auth (CLI) - const bearerEnabled = process.env.ENABLE_BEARER_AUTH !== 'false'; + // Bearer token auth (desktop instance token or optional GitHub token for CLI) const authHeader = req.headers.authorization; - if (bearerEnabled && authHeader?.startsWith('Bearer ')) { - const token = authHeader.slice(7); + if (authHeader?.startsWith('Bearer ')) { + const token = authHeader.slice(7).trim(); + + if (token.startsWith(INSTANCE_TOKEN_PREFIX)) { + try { + const identity = await validateInstanceToken(token); + if (!identity) { + res.status(401).json({ error: 'Unauthorized: invalid instance token', code: 'INVALID_INSTANCE_TOKEN' }); + return; + } + if (!isUserWhitelisted(identity.user.username)) { + res.status(403).json({ error: 'Forbidden', code: 'USER_NOT_WHITELISTED', message: 'Your GitHub account is not authorized for this ProPR instance. Ask an admin to add you to the user whitelist.' }); + return; + } + (req as Request & { user: GitHubUser }).user = identity.user; + req.authenticationMethod = 'instance_token'; + req.instanceTokenId = identity.tokenId; + return next(); + } catch { + res.status(401).json({ error: 'Unauthorized: instance token validation failed', code: 'INVALID_INSTANCE_TOKEN' }); + return; + } + } + + const bearerEnabled = process.env.ENABLE_BEARER_AUTH !== 'false'; + if (!bearerEnabled) { + res.status(401).json({ error: 'Unauthorized' }); + return; + } try { const user = await validateGitHubToken(token); @@ -443,6 +506,7 @@ export async function ensureAuthenticated(req: Request, res: Response, next: Nex } // Populate req.user so downstream handlers work the same way (req as Request & { user: GitHubUser }).user = user; + req.authenticationMethod = 'github_bearer'; return next(); } res.status(401).json({ error: 'Unauthorized: invalid token' }); diff --git a/packages/api/desktopAuthService.ts b/packages/api/desktopAuthService.ts new file mode 100644 index 000000000..8ef5bf756 --- /dev/null +++ b/packages/api/desktopAuthService.ts @@ -0,0 +1,443 @@ +/* eslint-disable max-lines -- pairing and token state transitions are kept together for transactional review */ +import { createHash, randomBytes, randomUUID } from 'node:crypto'; +import type { Knex } from 'knex'; +import { db } from '@propr/core'; +import type { GitHubUser } from './authTypes.js'; + +const DEFAULT_PAIRING_TTL_MS = 10 * 60_000; +const DEFAULT_POLL_INTERVAL_SECONDS = 5; +const RETAIN_FINISHED_PAIRINGS_MS = 24 * 60 * 60_000; +export const INSTANCE_TOKEN_PREFIX = 'propr_it_'; + +type PairingStatus = 'pending' | 'approved' | 'consumed'; + +interface PairingRow { + id: string; + device_secret_hash: string; + client_name: string; + status: PairingStatus; + approved_by_user_id: string | null; + approved_by_username: string | null; + approved_by_display_name: string | null; + approved_by_email: string | null; + approved_by_avatar_url: string | null; + created_at: string; + expires_at: string; + approved_at: string | null; + consumed_at: string | null; +} + +interface TokenRow { + id: string; + token_hash: string; + token_hint: string; + name: string; + owner_github_user_id: string; + owner_github_username: string; + owner_display_name: string; + owner_email: string | null; + owner_avatar_url: string | null; + created_at: string; + last_used_at: string | null; + expires_at: string | null; + revoked_at: string | null; + revoked_by_user_id: string | null; +} + +export interface DesktopPairingStart { + pairingId: string; + deviceSecret: string; + approvalUrl: string; + expiresAt: string; + interval: number; +} + +export interface DesktopPairingApproval { + pairingId: string; + clientName: string; + status: PairingStatus; + createdAt: string; + expiresAt: string; +} + +export type DesktopPairingPoll = + | { status: 'pending'; interval: number } + | { status: 'complete'; token: string; tokenType: 'Bearer'; expiresAt: string | null }; + +export interface DesktopTokenSummary { + id: string; + name: string; + tokenHint: string; + createdAt: string; + lastUsedAt: string | null; + expiresAt: string | null; + revokedAt: string | null; +} + +export interface InstanceTokenIdentity { + tokenId: string; + user: GitHubUser; +} + +export class DesktopAuthError extends Error { + constructor( + public readonly code: string, + public readonly status: number, + message: string, + ) { + super(message); + this.name = 'DesktopAuthError'; + } +} + +export interface DesktopAuthServiceOptions { + database?: Knex; + now?: () => Date; + pairingTtlMs?: number; + tokenTtlMs?: number | null; + approvalBaseUrl?: string; + publicApiUrl?: string; +} + +function digest(value: string): string { + return createHash('sha256').update(value, 'utf8').digest('hex'); +} + +function opaqueValue(bytes = 32): string { + return randomBytes(bytes).toString('base64url'); +} + +function validClientName(value: unknown): string { + if (typeof value !== 'string') { + throw new DesktopAuthError('INVALID_CLIENT_NAME', 400, 'clientName must be a string'); + } + if ([...value].some(character => { + const codePoint = character.codePointAt(0) ?? 0; + return codePoint < 32 || codePoint === 127; + })) { + throw new DesktopAuthError('INVALID_CLIENT_NAME', 400, 'clientName must contain 1 to 80 printable characters'); + } + const normalized = value.trim().replace(/\s+/g, ' '); + if (normalized.length < 1 || normalized.length > 80) { + throw new DesktopAuthError('INVALID_CLIENT_NAME', 400, 'clientName must contain 1 to 80 printable characters'); + } + return normalized; +} + +function validPairingId(value: string): void { + if (!/^dpr_[A-Za-z0-9_-]{22}$/.test(value)) { + throw new DesktopAuthError('PAIRING_NOT_FOUND', 404, 'Pairing request was not found'); + } +} + +function requireDeviceSecret(value: unknown): string { + if (typeof value !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(value)) { + throw new DesktopAuthError('PAIRING_NOT_FOUND', 404, 'Pairing request was not found'); + } + return value; +} + +function frontendApprovalBase(configured?: string): URL { + const raw = configured ?? process.env.FRONTEND_URL; + if (!raw) throw new Error('FRONTEND_URL is required for desktop pairing'); + const url = new URL(raw); + if (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost', '127.0.0.1', '::1', '[::1]'].includes(url.hostname))) { + throw new Error('Desktop pairing approval requires HTTPS except on loopback hosts'); + } + if (url.username || url.password) throw new Error('FRONTEND_URL must not contain credentials'); + return url; +} + +function publicApiBase(configured?: string): URL | null { + const raw = configured ?? process.env.API_PUBLIC_URL; + if (!raw) return null; + const url = new URL(raw); + if (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost', '127.0.0.1', '::1', '[::1]'].includes(url.hostname))) { + throw new Error('Desktop pairing browser entry requires HTTPS except on loopback hosts'); + } + if (url.username || url.password || url.pathname !== '/' || url.search || url.hash) { + throw new Error('API_PUBLIC_URL must be an origin without credentials, a path, query, or fragment'); + } + return url; +} + +function tokenSummary(row: TokenRow): DesktopTokenSummary { + return { + id: row.id, + name: row.name, + tokenHint: row.token_hint, + createdAt: row.created_at, + lastUsedAt: row.last_used_at, + expiresAt: row.expires_at, + revokedAt: row.revoked_at, + }; +} + +function configuredTokenTtlMs(): number | null { + const configured = process.env.PROPR_DESKTOP_TOKEN_TTL_DAYS?.trim(); + if (!configured) return null; + const days = Number(configured); + if (!Number.isSafeInteger(days) || days <= 0 || days > 3650) { + throw new Error('PROPR_DESKTOP_TOKEN_TTL_DAYS must be an integer from 1 to 3650'); + } + return days * 24 * 60 * 60_000; +} + +export class DesktopAuthService { + private readonly database: Knex; + private readonly now: () => Date; + private readonly pairingTtlMs: number; + private readonly tokenTtlMs: number | null; + private readonly approvalBaseUrl?: string; + private readonly publicApiUrl?: string; + + constructor(options: DesktopAuthServiceOptions = {}) { + this.database = options.database ?? db; + this.now = options.now ?? (() => new Date()); + this.pairingTtlMs = options.pairingTtlMs ?? DEFAULT_PAIRING_TTL_MS; + this.tokenTtlMs = options.tokenTtlMs === undefined ? configuredTokenTtlMs() : options.tokenTtlMs; + this.approvalBaseUrl = options.approvalBaseUrl; + this.publicApiUrl = options.publicApiUrl; + } + + async startPairing(clientNameInput: unknown): Promise { + const clientName = validClientName(clientNameInput); + const pairingId = `dpr_${opaqueValue(16)}`; + const deviceSecret = opaqueValue(); + const createdAt = this.now(); + const expiresAt = new Date(createdAt.getTime() + this.pairingTtlMs); + const apiApprovalUrl = publicApiBase(this.publicApiUrl); + const approvalUrl = apiApprovalUrl ?? this.getFrontendApprovalUrl(pairingId); + if (apiApprovalUrl) { + approvalUrl.pathname = `${approvalUrl.pathname.replace(/\/$/, '')}/api/desktop/pairings/${pairingId}/browser`; + approvalUrl.search = ''; + approvalUrl.hash = ''; + } + + await this.database('desktop_pairing_requests').insert({ + id: pairingId, + device_secret_hash: digest(deviceSecret), + client_name: clientName, + status: 'pending', + created_at: createdAt.toISOString(), + expires_at: expiresAt.toISOString(), + }); + await this.audit('pairing_started', { pairingId, clientName }); + + return { + pairingId, + deviceSecret, + approvalUrl: approvalUrl.toString(), + expiresAt: expiresAt.toISOString(), + interval: DEFAULT_POLL_INTERVAL_SECONDS, + }; + } + + getFrontendApprovalUrl(pairingId: string): URL { + validPairingId(pairingId); + const approvalUrl = frontendApprovalBase(this.approvalBaseUrl); + approvalUrl.pathname = `${approvalUrl.pathname.replace(/\/$/, '')}/desktop/pairing`; + approvalUrl.search = ''; + approvalUrl.hash = ''; + approvalUrl.searchParams.set('pairing_id', pairingId); + const apiUrl = publicApiBase(this.publicApiUrl); + if (approvalUrl.hostname === 'app.propr.dev' && apiUrl?.hostname.startsWith('t-') && apiUrl.hostname.endsWith('.propr.dev')) { + approvalUrl.searchParams.set('tunnel', apiUrl.hostname); + } + return approvalUrl; + } + + async getPairingForApproval(pairingId: string): Promise { + const row = await this.activePairing(pairingId); + return { + pairingId: row.id, + clientName: row.client_name, + status: row.status, + createdAt: row.created_at, + expiresAt: row.expires_at, + }; + } + + async approvePairing(pairingId: string, user: GitHubUser): Promise { + validPairingId(pairingId); + const approvedAt = this.now().toISOString(); + const updated = await this.database('desktop_pairing_requests') + .where({ id: pairingId, status: 'pending' }) + .andWhere('expires_at', '>', approvedAt) + .update({ + status: 'approved', + approved_by_user_id: user.id, + approved_by_username: user.username, + approved_by_display_name: user.displayName || user.username, + approved_by_email: user.email, + approved_by_avatar_url: user.avatarUrl, + approved_at: approvedAt, + }); + if (updated !== 1) { + const current = await this.database('desktop_pairing_requests').where({ id: pairingId }).first(); + if (current?.status === 'approved' && current.approved_by_user_id === user.id && current.expires_at > approvedAt) { + return this.getPairingForApproval(pairingId); + } + if (current?.status === 'consumed') { + throw new DesktopAuthError('PAIRING_ALREADY_CONSUMED', 409, 'Pairing request was already used'); + } + throw new DesktopAuthError('PAIRING_NOT_FOUND', 404, 'Pairing request was not found or has expired'); + } + const result = await this.getPairingForApproval(pairingId); + await this.audit('pairing_approved', { + pairingId, + clientName: result.clientName, + actor: user, + }); + return result; + } + + async pollPairing(pairingId: string, secretInput: unknown): Promise { + validPairingId(pairingId); + const deviceSecret = requireDeviceSecret(secretInput); + const now = this.now(); + const nowIso = now.toISOString(); + + return this.database.transaction(async transaction => { + const row = await transaction('desktop_pairing_requests') + .where({ id: pairingId, device_secret_hash: digest(deviceSecret) }) + .first(); + if (!row) throw new DesktopAuthError('PAIRING_NOT_FOUND', 404, 'Pairing request was not found'); + if (row.expires_at <= nowIso) throw new DesktopAuthError('PAIRING_EXPIRED', 410, 'Pairing request has expired'); + if (row.status === 'pending') return { status: 'pending', interval: DEFAULT_POLL_INTERVAL_SECONDS }; + if (row.status === 'consumed') { + throw new DesktopAuthError('PAIRING_ALREADY_CONSUMED', 409, 'Pairing request was already used'); + } + if (!row.approved_by_user_id || !row.approved_by_username) { + throw new DesktopAuthError('PAIRING_INVALID_STATE', 409, 'Pairing request cannot be completed'); + } + + const token = `${INSTANCE_TOKEN_PREFIX}${opaqueValue()}`; + const tokenId = randomUUID(); + const tokenExpiresAt = this.tokenTtlMs === null + ? null + : new Date(now.getTime() + this.tokenTtlMs).toISOString(); + await transaction('instance_api_tokens').insert({ + id: tokenId, + token_hash: digest(token), + token_hint: token.slice(-8), + name: row.client_name, + owner_github_user_id: row.approved_by_user_id, + owner_github_username: row.approved_by_username, + owner_display_name: row.approved_by_display_name || row.approved_by_username, + owner_email: row.approved_by_email, + owner_avatar_url: row.approved_by_avatar_url, + created_at: nowIso, + expires_at: tokenExpiresAt, + }); + const consumed = await transaction('desktop_pairing_requests') + .where({ id: pairingId, status: 'approved', device_secret_hash: digest(deviceSecret) }) + .update({ status: 'consumed', consumed_at: nowIso }); + if (consumed !== 1) { + throw new DesktopAuthError('PAIRING_ALREADY_CONSUMED', 409, 'Pairing request was already used'); + } + await this.audit('token_issued', { + pairingId, + tokenId, + clientName: row.client_name, + actor: { id: row.approved_by_user_id, username: row.approved_by_username }, + }, transaction); + return { status: 'complete', token, tokenType: 'Bearer', expiresAt: tokenExpiresAt }; + }); + } + + async validateToken(token: string): Promise { + if (!token.startsWith(INSTANCE_TOKEN_PREFIX) || token.length !== INSTANCE_TOKEN_PREFIX.length + 43) return null; + const nowIso = this.now().toISOString(); + const row = await this.database('instance_api_tokens') + .where({ token_hash: digest(token) }) + .whereNull('revoked_at') + .andWhere(builder => builder.whereNull('expires_at').orWhere('expires_at', '>', nowIso)) + .first(); + if (!row) return null; + + await this.database('instance_api_tokens') + .where({ id: row.id }) + .whereNull('revoked_at') + .update({ last_used_at: nowIso }); + return { + tokenId: row.id, + user: { + id: row.owner_github_user_id, + login: row.owner_github_username, + username: row.owner_github_username, + displayName: row.owner_display_name, + email: row.owner_email, + avatarUrl: row.owner_avatar_url, + }, + }; + } + + async listTokens(ownerUserId: string): Promise { + const rows = await this.database('instance_api_tokens') + .where({ owner_github_user_id: ownerUserId }) + .orderBy('created_at', 'desc'); + return rows.map(tokenSummary); + } + + async revokeToken(tokenId: string, actor: GitHubUser): Promise { + if (!/^[0-9a-f-]{36}$/i.test(tokenId)) { + throw new DesktopAuthError('TOKEN_NOT_FOUND', 404, 'Token was not found'); + } + const revokedAt = this.now().toISOString(); + const updated = await this.database('instance_api_tokens') + .where({ id: tokenId, owner_github_user_id: actor.id }) + .whereNull('revoked_at') + .update({ revoked_at: revokedAt, revoked_by_user_id: actor.id }); + if (updated !== 1) throw new DesktopAuthError('TOKEN_NOT_FOUND', 404, 'Active token was not found'); + await this.audit('token_revoked', { tokenId, actor }); + } + + async cleanupPairings(): Promise { + const cutoff = new Date(this.now().getTime() - RETAIN_FINISHED_PAIRINGS_MS).toISOString(); + return this.database('desktop_pairing_requests') + .where('expires_at', '<', cutoff) + .delete(); + } + + private async activePairing(pairingId: string): Promise { + validPairingId(pairingId); + const nowIso = this.now().toISOString(); + const row = await this.database('desktop_pairing_requests') + .where({ id: pairingId }) + .andWhere('expires_at', '>', nowIso) + .first(); + if (!row) throw new DesktopAuthError('PAIRING_NOT_FOUND', 404, 'Pairing request was not found or has expired'); + return row; + } + + private async audit( + action: string, + details: { + actor?: Pick; + pairingId?: string; + tokenId?: string; + clientName?: string; + }, + database: Knex | Knex.Transaction = this.database, + ): Promise { + await database('desktop_auth_audit').insert({ + action, + actor_github_user_id: details.actor?.id ?? null, + actor_github_username: details.actor?.username ?? null, + pairing_id: details.pairingId ?? null, + token_id: details.tokenId ?? null, + client_name: details.clientName ?? null, + created_at: this.now().toISOString(), + }); + console.info('[desktop-auth]', { + action, + actorUserId: details.actor?.id, + pairingId: details.pairingId, + tokenId: details.tokenId, + clientName: details.clientName, + }); + } +} + +export const desktopAuthService = new DesktopAuthService(); diff --git a/packages/api/expressUser.d.ts b/packages/api/expressUser.d.ts index 2f0d91243..57e36d598 100644 --- a/packages/api/expressUser.d.ts +++ b/packages/api/expressUser.d.ts @@ -7,6 +7,8 @@ declare global { interface User extends GitHubUser {} interface Request { authorization?: InstanceAuthorization; + authenticationMethod?: 'session' | 'github_bearer' | 'instance_token' | 'demo'; + instanceTokenId?: string; } } } diff --git a/packages/api/requestRateLimits.ts b/packages/api/requestRateLimits.ts index 48f1cfe25..fdac4167c 100644 --- a/packages/api/requestRateLimits.ts +++ b/packages/api/requestRateLimits.ts @@ -15,12 +15,18 @@ interface RequestRateLimitPolicy { export interface RequestRateLimitPolicies { api: RequestRateLimitPolicy; auth: RequestRateLimitPolicy; + discovery: RequestRateLimitPolicy; + pairingStart: RequestRateLimitPolicy; + pairingPoll: RequestRateLimitPolicy; webhook: RequestRateLimitPolicy; } const DEFAULT_POLICIES: RequestRateLimitPolicies = { api: { identifier: 'api', limit: 600, windowMs: 60_000 }, auth: { identifier: 'auth', limit: 30, windowMs: 15 * 60_000 }, + discovery: { identifier: 'desktop-discovery', limit: 60, windowMs: 60_000 }, + pairingStart: { identifier: 'desktop-pairing-start', limit: 10, windowMs: 15 * 60_000 }, + pairingPoll: { identifier: 'desktop-pairing-poll', limit: 180, windowMs: 15 * 60_000 }, webhook: { identifier: 'webhook', limit: 300, windowMs: 60_000 }, }; @@ -101,6 +107,21 @@ export function resolveRequestRateLimitPolicies( limit: positiveInteger(environment, 'PROPR_AUTH_RATE_LIMIT_MAX', DEFAULT_POLICIES.auth.limit), windowMs: windowMilliseconds(environment, 'PROPR_AUTH_RATE_LIMIT_WINDOW_MS', DEFAULT_POLICIES.auth.windowMs), }, + discovery: { + identifier: 'desktop-discovery', + limit: positiveInteger(environment, 'PROPR_DISCOVERY_RATE_LIMIT_MAX', DEFAULT_POLICIES.discovery.limit), + windowMs: windowMilliseconds(environment, 'PROPR_DISCOVERY_RATE_LIMIT_WINDOW_MS', DEFAULT_POLICIES.discovery.windowMs), + }, + pairingStart: { + identifier: 'desktop-pairing-start', + limit: positiveInteger(environment, 'PROPR_PAIRING_START_RATE_LIMIT_MAX', DEFAULT_POLICIES.pairingStart.limit), + windowMs: windowMilliseconds(environment, 'PROPR_PAIRING_START_RATE_LIMIT_WINDOW_MS', DEFAULT_POLICIES.pairingStart.windowMs), + }, + pairingPoll: { + identifier: 'desktop-pairing-poll', + limit: positiveInteger(environment, 'PROPR_PAIRING_POLL_RATE_LIMIT_MAX', DEFAULT_POLICIES.pairingPoll.limit), + windowMs: windowMilliseconds(environment, 'PROPR_PAIRING_POLL_RATE_LIMIT_WINDOW_MS', DEFAULT_POLICIES.pairingPoll.windowMs), + }, webhook: { identifier: 'webhook', limit: positiveInteger(environment, 'PROPR_WEBHOOK_RATE_LIMIT_MAX', DEFAULT_POLICIES.webhook.limit), @@ -157,6 +178,24 @@ export function createAuthRequestRateLimiter( return createRequestRateLimiter(resolveRequestRateLimitPolicies(environment).auth); } +export function createDiscoveryRequestRateLimiter( + environment: RateLimitEnvironment = process.env, +): RateLimitRequestHandler { + return createRequestRateLimiter(resolveRequestRateLimitPolicies(environment).discovery); +} + +export function createPairingStartRateLimiter( + environment: RateLimitEnvironment = process.env, +): RateLimitRequestHandler { + return createRequestRateLimiter(resolveRequestRateLimitPolicies(environment).pairingStart); +} + +export function createPairingPollRateLimiter( + environment: RateLimitEnvironment = process.env, +): RateLimitRequestHandler { + return createRequestRateLimiter(resolveRequestRateLimitPolicies(environment).pairingPoll); +} + export function createWebhookRequestRateLimiter( environment: RateLimitEnvironment = process.env, ): RateLimitRequestHandler { diff --git a/packages/api/routes/desktopAuthRoutes.ts b/packages/api/routes/desktopAuthRoutes.ts new file mode 100644 index 000000000..972435b1f --- /dev/null +++ b/packages/api/routes/desktopAuthRoutes.ts @@ -0,0 +1,162 @@ +import type { Request, RequestHandler, Response } from 'express'; +import { + DesktopAuthError, + DesktopAuthService, + desktopAuthService, +} from '../desktopAuthService.js'; +import { isUserWhitelisted } from '../userWhitelist.js'; + +interface DesktopAuthRoutesOptions { + service?: DesktopAuthService; + frontendUrl?: string; +} + +function pathParameter(value: string | string[]): string { + return Array.isArray(value) ? value[0] ?? '' : value; +} + +function sendDesktopAuthError(error: unknown, res: Response): void { + if (error instanceof DesktopAuthError) { + res.status(error.status).json({ code: error.code, error: error.message }); + return; + } + console.error('[desktop-auth] Request failed:', error); + res.status(500).json({ code: 'DESKTOP_AUTH_FAILED', error: 'Desktop authentication request failed' }); +} + +export function isTrustedPairingApprovalOrigin(origin: string | undefined, frontendUrl: string | undefined): boolean { + if (!origin || !frontendUrl) return false; + try { + const expected = new URL(frontendUrl); + const supplied = new URL(origin); + return supplied.origin === expected.origin + && (supplied.protocol === 'https:' + || (supplied.protocol === 'http:' && ['localhost', '127.0.0.1', '::1', '[::1]'].includes(supplied.hostname))); + } catch { + return false; + } +} + +/** Pairing approval is intentionally session-only. */ +export function requireBrowserPairingSession(): RequestHandler { + return (req, res, next) => { + if (req.authenticationMethod !== 'session' || !req.isAuthenticated?.() || !req.user) { + res.status(403).json({ + code: 'BROWSER_SESSION_REQUIRED', + error: 'Pairing approval requires an authenticated browser session', + }); + return; + } + next(); + }; +} + +/** Mutating approval additionally requires the exact configured UI origin. */ +export function requirePairingApprovalOrigin(frontendUrl = process.env.FRONTEND_URL): RequestHandler { + return (req, res, next) => { + if (!isTrustedPairingApprovalOrigin(req.header('origin'), frontendUrl)) { + res.status(403).json({ code: 'UNTRUSTED_APPROVAL_ORIGIN', error: 'Pairing approval origin is not trusted' }); + return; + } + next(); + }; +} + +export function createDesktopAuthRoutes(options: DesktopAuthRoutesOptions = {}) { + const service = options.service ?? desktopAuthService; + const browserSessionGuard = requireBrowserPairingSession(); + const approvalOriginGuard = requirePairingApprovalOrigin(options.frontendUrl); + + async function startPairing(req: Request, res: Response): Promise { + try { + const result = await service.startPairing((req.body as { clientName?: unknown } | undefined)?.clientName); + res.status(201).json(result); + } catch (error) { + sendDesktopAuthError(error, res); + } + } + + async function pollPairing(req: Request, res: Response): Promise { + try { + const result = await service.pollPairing( + pathParameter(req.params.pairingId), + (req.body as { deviceSecret?: unknown } | undefined)?.deviceSecret, + ); + res.status(result.status === 'pending' ? 202 : 200).json(result); + } catch (error) { + sendDesktopAuthError(error, res); + } + } + + async function getPairingApproval(req: Request, res: Response): Promise { + try { + res.json(await service.getPairingForApproval(pathParameter(req.params.pairingId))); + } catch (error) { + sendDesktopAuthError(error, res); + } + } + + async function openPairingApproval(req: Request, res: Response): Promise { + const pairingId = pathParameter(req.params.pairingId); + try { + await service.getPairingForApproval(pairingId); + const frontendUrl = service.getFrontendApprovalUrl(pairingId).toString(); + if (req.isAuthenticated?.() && req.user && isUserWhitelisted(req.user.username)) { + res.redirect(frontendUrl); + return; + } + res.redirect(`/api/auth/github?redirect_to=${encodeURIComponent(frontendUrl)}`); + } catch (error) { + sendDesktopAuthError(error, res); + } + } + + async function approvePairing(req: Request, res: Response): Promise { + if (!req.user) { + res.status(401).json({ code: 'AUTHENTICATION_REQUIRED', error: 'Authentication required' }); + return; + } + try { + res.json(await service.approvePairing(pathParameter(req.params.pairingId), req.user)); + } catch (error) { + sendDesktopAuthError(error, res); + } + } + + async function listTokens(req: Request, res: Response): Promise { + if (!req.user) { + res.status(401).json({ code: 'AUTHENTICATION_REQUIRED', error: 'Authentication required' }); + return; + } + try { + res.json({ tokens: await service.listTokens(req.user.id) }); + } catch (error) { + sendDesktopAuthError(error, res); + } + } + + async function revokeToken(req: Request, res: Response): Promise { + if (!req.user) { + res.status(401).json({ code: 'AUTHENTICATION_REQUIRED', error: 'Authentication required' }); + return; + } + try { + await service.revokeToken(pathParameter(req.params.tokenId), req.user); + res.status(204).end(); + } catch (error) { + sendDesktopAuthError(error, res); + } + } + + return { + browserSessionGuard, + approvalOriginGuard, + startPairing, + pollPairing, + getPairingApproval, + openPairingApproval, + approvePairing, + listTokens, + revokeToken, + }; +} diff --git a/packages/api/routes/index.ts b/packages/api/routes/index.ts index 8c018e944..23dd12495 100644 --- a/packages/api/routes/index.ts +++ b/packages/api/routes/index.ts @@ -29,3 +29,4 @@ export { createUserRepoPreferencesRoutes } from './userRepoPreferencesRoutes.js' export { createAgentRuntimeRoutes } from './agentRuntimeRoutes.js'; export { createNotificationRoutes } from './notificationRoutes.js'; export { createAdminRoutes } from './adminRoutes.js'; +export { createDesktopAuthRoutes } from './desktopAuthRoutes.js'; diff --git a/packages/api/routes/statusRoutes.ts b/packages/api/routes/statusRoutes.ts index 5439fac52..27c234b2c 100644 --- a/packages/api/routes/statusRoutes.ts +++ b/packages/api/routes/statusRoutes.ts @@ -69,12 +69,19 @@ export function createStatusRoutes(deps: StatusRoutesDeps) { let agentStatusCache: { expiresAt: number; statuses: AgentStatus[] } | undefined; function getCompatibility(_req: Request, res: Response): void { - res.json(getProprCompatibilityMetadata()); + res.json(getProprCompatibilityMetadata(!isDemoMode())); + } + + function getDesktopDiscovery(_req: Request, res: Response): void { + res.json({ + product: 'ProPR', + ...getProprCompatibilityMetadata(!isDemoMode()), + }); } async function getStatus(req: Request, res: Response): Promise { try { - const compatibility = getProprCompatibilityMetadata(); + const compatibility = getProprCompatibilityMetadata(!isDemoMode()); // In demo mode, return all-green status if (isDemoMode()) { res.json({ @@ -195,7 +202,7 @@ export function createStatusRoutes(deps: StatusRoutesDeps) { } } - return { getCompatibility, getStatus }; + return { getCompatibility, getDesktopDiscovery, getStatus }; async function getCachedAgentStatuses(): Promise { const currentTime = now(); diff --git a/packages/api/server.ts b/packages/api/server.ts index 2c6651eea..fcfa415bc 100644 --- a/packages/api/server.ts +++ b/packages/api/server.ts @@ -32,6 +32,7 @@ import { createAgentRuntimeRoutes, createNotificationRoutes, createAdminRoutes, createInstanceCatalogRoutes, + createDesktopAuthRoutes, attachmentUpload } from './routes/index.js'; import { agentLoginSessionManager } from './services/agentLoginSessionManager.js'; @@ -62,7 +63,15 @@ import { NotificationProjectionService } from './services/notificationProjection import { WebPushDispatcher } from './services/webPushDispatcher.js'; import { assertInstanceAdministratorConfigured, resolveAuthorization } from './authorization.js'; import { resolveApiListenHost } from './listenAddress.js'; -import { configureApiProxyTrust, createApiRequestRateLimiter, createWebhookRequestRateLimiter } from './requestRateLimits.js'; +import { + configureApiProxyTrust, + createApiRequestRateLimiter, + createDiscoveryRequestRateLimiter, + createPairingPollRateLimiter, + createPairingStartRateLimiter, + createWebhookRequestRateLimiter, +} from './requestRateLimits.js'; +import { desktopAuthService } from './desktopAuthService.js'; import { startConfigReloadSubscription, type ConfigReloadSubscription } from './services/configReloadSubscription.js'; import { assertNoDuplicateRoutes, @@ -190,6 +199,7 @@ let configReloadSubscription: ConfigReloadSubscription | undefined; let notificationProjection: NotificationProjectionService | undefined; let webPushDispatcher: WebPushDispatcher | undefined; let webPushDispatcherConfigured = false; +let desktopPairingCleanupTimer: NodeJS.Timeout | undefined; function createDemoTaskQueue(): Queue { return { @@ -242,15 +252,21 @@ function setupRoutes(): void { ) => notificationProjection!.projectSystemSnapshot(snapshot, additionalAdministratorIds), }), }); - // INTENTIONALLY UNAUTHENTICATED: /api/compatibility is registered BEFORE the - // `ensureAuthenticated` guard below so the hosted UI can run its pre-auth - // version-gate before the user logs in. This is the one deliberate exception to - // "everything under /api/* requires auth" — do not move it after the guard, and - // keep its handler returning only non-sensitive build metadata (version + - // compatibility dates). All other /api routes registered after this line are - // authenticated. - app.get('/api/compatibility', statusRoutes.getCompatibility); + const desktopAuthRoutes = createDesktopAuthRoutes(); + // INTENTIONALLY UNAUTHENTICATED: compatibility/discovery and the bounded + // pairing bootstrap, poll, and browser entry are registered before the guard. + // They return only compatibility/capability metadata or pairing state gated by + // a high-entropy secret; all operational routes below remain authenticated. + app.get('/api/compatibility', createDiscoveryRequestRateLimiter(), statusRoutes.getCompatibility); + app.get('/api/desktop/discovery', createDiscoveryRequestRateLimiter(), statusRoutes.getDesktopDiscovery); + app.post('/api/desktop/pairings', createPairingStartRateLimiter(), desktopAuthRoutes.startPairing); + app.post('/api/desktop/pairings/:pairingId/poll', createPairingPollRateLimiter(), desktopAuthRoutes.pollPairing); + app.get('/api/desktop/pairings/:pairingId/browser', createPairingStartRateLimiter(), desktopAuthRoutes.openPairingApproval); app.use('/api', ensureAuthenticated, resolveAuthorization); + app.get('/api/desktop/pairings/:pairingId/approval', desktopAuthRoutes.browserSessionGuard, desktopAuthRoutes.getPairingApproval); + app.post('/api/desktop/pairings/:pairingId/approve', desktopAuthRoutes.browserSessionGuard, desktopAuthRoutes.approvalOriginGuard, desktopAuthRoutes.approvePairing); + app.get('/api/desktop/tokens', desktopAuthRoutes.listTokens); + app.delete('/api/desktop/tokens/:tokenId', desktopAuthRoutes.revokeToken); const taskRoutes = createTaskRoutes({ db, taskQueue }); const taskHistoryRoutes = createTaskHistoryRoutes({ redisClient, taskQueue, db }); const liveDetailsRoutes = createLiveDetailsRoutes({ redisClient, db }); @@ -437,6 +453,15 @@ async function start(): Promise { console.log('Demo mode: skipped startup config initialization; API config reads use the curated database directly'); } setupRoutes(); + if (!demoMode) { + await desktopAuthService.cleanupPairings(); + desktopPairingCleanupTimer = setInterval(() => { + void desktopAuthService.cleanupPairings().catch(error => { + console.warn('[desktop-auth] Pairing cleanup failed:', error); + }); + }, 60 * 60_000); + desktopPairingCleanupTimer.unref(); + } if (!demoMode) { const socketService = initSocketService(httpServer, validateCorsOrigin, { engineMiddleware: socketAuthMiddleware.engineMiddleware, @@ -485,6 +510,7 @@ async function start(): Promise { { name: 'agent login sessions', close: () => agentLoginSessionManager.close() }, { name: 'redis client', close: () => redisClient.quit() } ]; + if (desktopPairingCleanupTimer) clearInterval(desktopPairingCleanupTimer); if (!demoMode) { shutdownTasks.push( { name: 'Web Push dispatcher', close: () => webPushDispatcher?.close() ?? Promise.resolve() }, diff --git a/packages/api/test/desktopAuth.test.ts b/packages/api/test/desktopAuth.test.ts new file mode 100644 index 000000000..7753ff5be --- /dev/null +++ b/packages/api/test/desktopAuth.test.ts @@ -0,0 +1,261 @@ +import assert from 'node:assert/strict'; +import { after, afterEach, beforeEach, describe, test } from 'node:test'; +import type { NextFunction, Request, Response } from 'express'; +import knex, { type Knex } from 'knex'; +import { closeConnection } from '@propr/core'; +import { up as createDesktopAuthTables } from '../../core/src/db/migrations/20260829000000_create_desktop_auth.js'; +import { + DesktopAuthError, + DesktopAuthService, + INSTANCE_TOKEN_PREFIX, +} from '../desktopAuthService.js'; +import { + isTrustedPairingApprovalOrigin, + requireBrowserPairingSession, +} from '../routes/desktopAuthRoutes.js'; +import type { GitHubUser } from '../authTypes.js'; +import { ensureAuthenticated } from '../auth.js'; + +const owner: GitHubUser = { + id: '101', + login: 'desktop-owner', + username: 'desktop-owner', + displayName: 'Desktop Owner', + email: 'owner@example.test', + avatarUrl: 'https://avatars.example.test/101', + accessToken: 'github-secret-that-must-not-be-stored', +}; + +let database: Knex; +let now: Date; +let service: DesktopAuthService; + +beforeEach(async () => { + database = knex({ + client: 'better-sqlite3', + connection: { filename: ':memory:' }, + useNullAsDefault: true, + }); + await createDesktopAuthTables(database); + now = new Date('2026-08-29T14:00:00.000Z'); + service = new DesktopAuthService({ + database, + now: () => new Date(now), + approvalBaseUrl: 'https://app.example.test/base/', + }); +}); + +afterEach(async () => database.destroy()); +after(async () => closeConnection()); + +describe('desktop browser pairing', () => { + test('stores only a device-secret hash and builds a fixed trusted approval URL', async () => { + const pairing = await service.startPairing(' Work Laptop '); + const row = await database('desktop_pairing_requests').where({ id: pairing.pairingId }).first(); + const audit = await database('desktop_auth_audit').first(); + + assert.match(pairing.pairingId, /^dpr_[A-Za-z0-9_-]{22}$/); + assert.match(pairing.deviceSecret, /^[A-Za-z0-9_-]{43}$/); + assert.equal(pairing.approvalUrl, `https://app.example.test/base/desktop/pairing?pairing_id=${pairing.pairingId}`); + assert.equal(pairing.approvalUrl.includes(pairing.deviceSecret), false); + assert.equal(row.client_name, 'Work Laptop'); + assert.notEqual(row.device_secret_hash, pairing.deviceSecret); + assert.equal(JSON.stringify(row).includes(pairing.deviceSecret), false); + assert.equal(JSON.stringify(audit).includes(pairing.deviceSecret), false); + }); + + test('uses the configured API browser entry and preserves only a managed hosted tunnel selector', async () => { + const hosted = new DesktopAuthService({ + database, + now: () => new Date(now), + approvalBaseUrl: 'https://app.propr.dev', + publicApiUrl: 'https://t-instance123.propr.dev', + }); + const pairing = await hosted.startPairing('Windows desktop'); + + assert.equal( + pairing.approvalUrl, + `https://t-instance123.propr.dev/api/desktop/pairings/${pairing.pairingId}/browser`, + ); + assert.equal( + hosted.getFrontendApprovalUrl(pairing.pairingId).toString(), + `https://app.propr.dev/desktop/pairing?pairing_id=${pairing.pairingId}&tunnel=t-instance123.propr.dev`, + ); + }); + + test('issues an opaque token once, resolves its owner, and never stores plaintext credentials', async () => { + const pairing = await service.startPairing('MacBook Pro'); + assert.deepEqual(await service.pollPairing(pairing.pairingId, pairing.deviceSecret), { + status: 'pending', + interval: 5, + }); + await service.approvePairing(pairing.pairingId, owner); + + const completed = await service.pollPairing(pairing.pairingId, pairing.deviceSecret); + assert.equal(completed.status, 'complete'); + if (completed.status !== 'complete') return; + assert.match(completed.token, new RegExp(`^${INSTANCE_TOKEN_PREFIX}[A-Za-z0-9_-]{43}$`)); + assert.equal(completed.expiresAt, null); + + const tokenRow = await database('instance_api_tokens').first(); + const pairingRow = await database('desktop_pairing_requests').first(); + const databaseDump = JSON.stringify({ tokenRow, pairingRow }); + assert.equal(databaseDump.includes(completed.token), false); + assert.equal(databaseDump.includes(pairing.deviceSecret), false); + assert.equal(databaseDump.includes(owner.accessToken!), false); + assert.equal(tokenRow.owner_github_user_id, owner.id); + assert.equal(pairingRow.status, 'consumed'); + + await assert.rejects( + service.pollPairing(pairing.pairingId, pairing.deviceSecret), + (error: unknown) => error instanceof DesktopAuthError && error.code === 'PAIRING_ALREADY_CONSUMED', + ); + + const identity = await service.validateToken(completed.token); + assert.equal(identity?.user.id, owner.id); + assert.equal(identity?.user.accessToken, undefined); + assert.equal((await database('instance_api_tokens').first()).last_used_at, now.toISOString()); + }); + + test('rejects the wrong secret without revealing pairing state', async () => { + const pairing = await service.startPairing('Linux workstation'); + await service.approvePairing(pairing.pairingId, owner); + + await assert.rejects( + service.pollPairing(pairing.pairingId, 'A'.repeat(43)), + (error: unknown) => error instanceof DesktopAuthError + && error.code === 'PAIRING_NOT_FOUND' + && error.status === 404, + ); + assert.equal((await database('desktop_pairing_requests').first()).status, 'approved'); + }); + + test('expires unapproved pairings and cleans retained expired records', async () => { + const expiringService = new DesktopAuthService({ + database, + now: () => new Date(now), + pairingTtlMs: 1_000, + approvalBaseUrl: 'https://app.example.test', + }); + const pairing = await expiringService.startPairing('Old laptop'); + now = new Date(now.getTime() + 1_001); + + await assert.rejects( + expiringService.pollPairing(pairing.pairingId, pairing.deviceSecret), + (error: unknown) => error instanceof DesktopAuthError && error.code === 'PAIRING_EXPIRED', + ); + assert.equal(await expiringService.cleanupPairings(), 0, 'recent expired rows remain briefly for stable errors'); + now = new Date(now.getTime() + 24 * 60 * 60_000); + assert.equal(await expiringService.cleanupPairings(), 1); + }); + + test('rejects unsafe names and non-HTTPS approval origins', async () => { + await assert.rejects(service.startPairing('bad\nname'), /printable characters/); + await assert.rejects(service.startPairing('x'.repeat(81)), /1 to 80/); + const insecure = new DesktopAuthService({ database, approvalBaseUrl: 'http://remote.example.test' }); + await assert.rejects(insecure.startPairing('Laptop'), /requires HTTPS/); + }); +}); + +describe('instance token ownership and revocation', () => { + async function issueToken(): Promise<{ token: string; tokenId: string }> { + const pairing = await service.startPairing('Desktop app'); + await service.approvePairing(pairing.pairingId, owner); + const completed = await service.pollPairing(pairing.pairingId, pairing.deviceSecret); + assert.equal(completed.status, 'complete'); + if (completed.status !== 'complete') throw new Error('token was not issued'); + const tokenId = (await service.listTokens(owner.id))[0].id; + return { token: completed.token, tokenId }; + } + + test('lists safe metadata only and limits revocation to the owner', async () => { + const { token, tokenId } = await issueToken(); + const listed = await service.listTokens(owner.id); + + assert.equal(listed.length, 1); + assert.equal(JSON.stringify(listed).includes(token), false); + assert.deepEqual(await service.listTokens('someone-else'), []); + await assert.rejects( + service.revokeToken(tokenId, { ...owner, id: 'someone-else' }), + (error: unknown) => error instanceof DesktopAuthError && error.code === 'TOKEN_NOT_FOUND', + ); + assert.notEqual(await service.validateToken(token), null); + + await service.revokeToken(tokenId, owner); + assert.equal(await service.validateToken(token), null); + assert.notEqual((await service.listTokens(owner.id))[0].revokedAt, null); + }); + + test('honors optional token expiry', async () => { + service = new DesktopAuthService({ + database, + now: () => new Date(now), + tokenTtlMs: 1_000, + approvalBaseUrl: 'https://app.example.test', + }); + const { token } = await issueToken(); + now = new Date(now.getTime() + 1_001); + assert.equal(await service.validateToken(token), null); + }); + + test('REST authentication accepts instance tokens while optional GitHub bearer auth is disabled', async () => { + const original = process.env.ENABLE_BEARER_AUTH; + process.env.ENABLE_BEARER_AUTH = 'false'; + const request = { + headers: { authorization: `Bearer ${INSTANCE_TOKEN_PREFIX}${'A'.repeat(43)}` }, + isAuthenticated: () => false, + } as unknown as Request; + let nextCalls = 0; + const response = {} as Response; + try { + await ensureAuthenticated(request, response, (() => { nextCalls++; }) as NextFunction, async () => ({ + tokenId: 'token-1', + user: owner, + })); + } finally { + if (original === undefined) delete process.env.ENABLE_BEARER_AUTH; + else process.env.ENABLE_BEARER_AUTH = original; + } + + assert.equal(nextCalls, 1); + assert.equal(request.authenticationMethod, 'instance_token'); + assert.equal(request.instanceTokenId, 'token-1'); + assert.equal(request.user?.id, owner.id); + }); +}); + +describe('pairing approval request protection', () => { + test('accepts only the exact HTTPS frontend origin', () => { + assert.equal(isTrustedPairingApprovalOrigin('https://app.example.test', 'https://app.example.test/path'), true); + assert.equal(isTrustedPairingApprovalOrigin('https://preview.app.example.test', 'https://app.example.test'), false); + assert.equal(isTrustedPairingApprovalOrigin('http://app.example.test', 'https://app.example.test'), false); + assert.equal(isTrustedPairingApprovalOrigin(undefined, 'https://app.example.test'), false); + }); + + test('requires a browser session even when another authentication method supplied the user', () => { + const guard = requireBrowserPairingSession(); + const calls: Array<{ status?: number; body?: unknown }> = []; + const response = { + status(value: number) { calls.push({ status: value }); return response; }, + json(value: unknown) { calls[calls.length - 1].body = value; return response; }, + } as unknown as Response; + let nextCalls = 0; + const next = (() => { nextCalls++; }) as NextFunction; + + guard({ + authenticationMethod: 'instance_token', + user: owner, + isAuthenticated: () => false, + header: () => 'https://app.example.test', + } as unknown as Request, response, next); + assert.equal(calls[0].status, 403); + + guard({ + authenticationMethod: 'session', + user: owner, + isAuthenticated: () => true, + header: () => 'https://app.example.test', + } as unknown as Request, response, next); + assert.equal(nextCalls, 1); + }); +}); diff --git a/packages/api/test/requestRateLimits.test.ts b/packages/api/test/requestRateLimits.test.ts index e9a3ca6e0..0920d3562 100644 --- a/packages/api/test/requestRateLimits.test.ts +++ b/packages/api/test/requestRateLimits.test.ts @@ -208,6 +208,9 @@ test('resolves secure defaults and explicit positive-integer overrides', () => { const defaults = resolveRequestRateLimitPolicies({}); assert.deepEqual(defaults.api, { identifier: 'api', limit: 600, windowMs: 60_000 }); assert.deepEqual(defaults.auth, { identifier: 'auth', limit: 30, windowMs: 900_000 }); + assert.deepEqual(defaults.discovery, { identifier: 'desktop-discovery', limit: 60, windowMs: 60_000 }); + assert.deepEqual(defaults.pairingStart, { identifier: 'desktop-pairing-start', limit: 10, windowMs: 900_000 }); + assert.deepEqual(defaults.pairingPoll, { identifier: 'desktop-pairing-poll', limit: 180, windowMs: 900_000 }); assert.deepEqual(defaults.webhook, { identifier: 'webhook', limit: 300, windowMs: 60_000 }); const configured = resolveRequestRateLimitPolicies({ diff --git a/packages/api/test/socketAuthentication.test.ts b/packages/api/test/socketAuthentication.test.ts index d6e66fedc..d1bc5a3a3 100644 --- a/packages/api/test/socketAuthentication.test.ts +++ b/packages/api/test/socketAuthentication.test.ts @@ -8,6 +8,7 @@ import { io as createSocketClient, type Socket as ClientSocket } from 'socket.io import { closeConnection } from '@propr/core'; import { INDEXING_UPDATE, type IndexingUpdatePayload } from '@propr/shared'; import type { GitHubUser } from '../authTypes.js'; +import { INSTANCE_TOKEN_PREFIX } from '../desktopAuthService.js'; import { authenticateSocketRequest, SocketAuthenticationError, @@ -117,6 +118,18 @@ describe('Socket.IO authentication', () => { assert.equal(result.authorization.role, 'admin'); }); + test('accepts an instance token without enabling optional GitHub bearer auth', async () => { + process.env.ENABLE_BEARER_AUTH = 'false'; + const result = await authenticateSocketRequest( + request({ headers: { authorization: `Bearer ${INSTANCE_TOKEN_PREFIX}${'A'.repeat(43)}` } }), + dependencies({ + validateInstanceToken: async () => ({ tokenId: 'token-1', user: user({ id: '77' }) }), + }), + ); + + assert.equal(result.user.id, '77'); + }); + test('rejects a session user removed from the whitelist', async () => { const sessionUser = user({ username: 'removed' }); await assert.rejects( diff --git a/packages/api/test/statusRoutes.test.ts b/packages/api/test/statusRoutes.test.ts index 7725c22e4..bcc4b041d 100644 --- a/packages/api/test/statusRoutes.test.ts +++ b/packages/api/test/statusRoutes.test.ts @@ -205,6 +205,33 @@ test('/api/compatibility returns public version contract metadata', async () => version: PROPR_VERSION, apiCompatibility: PROPR_API_COMPATIBILITY, uiCompatibility: PROPR_UI_COMPATIBILITY, + desktopAuthentication: { + protocolVersion: 1, + browserPairing: true, + instanceBearerTokens: true, + socketIoBearerAuthentication: true, + }, + }); +}); + +test('/api/desktop/discovery adds only the stable product name to compatibility metadata', async () => { + configureStatusEnv(); + const { response, body } = createJsonResponse(); + const routes = await createRoutes({ redisClient: createRedisClient() as never }); + + routes.getDesktopDiscovery({} as Request, response); + + assert.deepEqual(body(), { + product: 'ProPR', + version: PROPR_VERSION, + apiCompatibility: PROPR_API_COMPATIBILITY, + uiCompatibility: PROPR_UI_COMPATIBILITY, + desktopAuthentication: { + protocolVersion: 1, + browserPairing: true, + instanceBearerTokens: true, + socketIoBearerAuthentication: true, + }, }); }); diff --git a/packages/core/src/db/migrations/20260829000000_create_desktop_auth.js b/packages/core/src/db/migrations/20260829000000_create_desktop_auth.js new file mode 100644 index 000000000..5b40337db --- /dev/null +++ b/packages/core/src/db/migrations/20260829000000_create_desktop_auth.js @@ -0,0 +1,67 @@ +/** + * Device pairing requests and opaque, instance-scoped API credentials. + * + * Pairing secrets and API tokens are deliberately represented only by their + * SHA-256 digests. The plaintext values exist only in the response that hands + * them to the desktop client. + */ +export async function up(knex) { + await knex.schema.createTable('desktop_pairing_requests', (table) => { + table.text('id').primary(); + table.text('device_secret_hash').notNullable(); + table.text('client_name').notNullable(); + table.text('status').notNullable().defaultTo('pending').checkIn(['pending', 'approved', 'consumed']); + table.text('approved_by_user_id').nullable(); + table.text('approved_by_username').nullable(); + table.text('approved_by_display_name').nullable(); + table.text('approved_by_email').nullable(); + table.text('approved_by_avatar_url').nullable(); + table.timestamp('created_at').notNullable(); + table.timestamp('expires_at').notNullable(); + table.timestamp('approved_at').nullable(); + table.timestamp('consumed_at').nullable(); + + table.index(['status', 'expires_at']); + }); + + await knex.schema.createTable('instance_api_tokens', (table) => { + table.text('id').primary(); + table.text('token_hash').notNullable().unique(); + table.text('token_hint').notNullable(); + table.text('name').notNullable(); + table.text('owner_github_user_id').notNullable(); + table.text('owner_github_username').notNullable(); + table.text('owner_display_name').notNullable(); + table.text('owner_email').nullable(); + table.text('owner_avatar_url').nullable(); + table.timestamp('created_at').notNullable(); + table.timestamp('last_used_at').nullable(); + table.timestamp('expires_at').nullable(); + table.timestamp('revoked_at').nullable(); + table.text('revoked_by_user_id').nullable(); + + table.index('owner_github_user_id'); + table.index(['revoked_at', 'expires_at']); + }); + + await knex.schema.createTable('desktop_auth_audit', (table) => { + table.increments('id').primary(); + table.text('action').notNullable(); + table.text('actor_github_user_id').nullable(); + table.text('actor_github_username').nullable(); + table.text('pairing_id').nullable(); + table.text('token_id').nullable(); + table.text('client_name').nullable(); + table.timestamp('created_at').notNullable(); + + table.index('created_at'); + table.index('actor_github_user_id'); + table.index('token_id'); + }); +} + +export async function down(knex) { + await knex.schema.dropTableIfExists('desktop_auth_audit'); + await knex.schema.dropTableIfExists('instance_api_tokens'); + await knex.schema.dropTableIfExists('desktop_pairing_requests'); +} diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 9357f0be9..ecbb3b448 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -147,6 +147,7 @@ export { getProprCompatibilityMetadata, evaluateProprApiCompatibility, type ProprCompatibilityMetadata, + type ProprDesktopAuthenticationCapabilities, type ProprApiCompatibilityInput, type ProprApiCompatibilityResult, } from './proprCompatibility.js'; diff --git a/packages/shared/src/proprCompatibility.ts b/packages/shared/src/proprCompatibility.ts index 4b7ccc176..0110aae11 100644 --- a/packages/shared/src/proprCompatibility.ts +++ b/packages/shared/src/proprCompatibility.ts @@ -18,6 +18,14 @@ export interface ProprCompatibilityMetadata { version: string; apiCompatibility: string; uiCompatibility: string; + desktopAuthentication: ProprDesktopAuthenticationCapabilities; +} + +export interface ProprDesktopAuthenticationCapabilities { + protocolVersion: 1; + browserPairing: boolean; + instanceBearerTokens: boolean; + socketIoBearerAuthentication: boolean; } export interface ProprApiCompatibilityInput { @@ -39,11 +47,17 @@ export type ProprApiCompatibilityResult = message: string; }; -export function getProprCompatibilityMetadata(): ProprCompatibilityMetadata { +export function getProprCompatibilityMetadata(desktopAuthenticationEnabled = true): ProprCompatibilityMetadata { return { version: PROPR_VERSION, apiCompatibility: PROPR_API_COMPATIBILITY, uiCompatibility: PROPR_UI_COMPATIBILITY, + desktopAuthentication: { + protocolVersion: 1, + browserPairing: desktopAuthenticationEnabled, + instanceBearerTokens: desktopAuthenticationEnabled, + socketIoBearerAuthentication: desktopAuthenticationEnabled, + }, }; } diff --git a/propr-ui/src/App.tsx b/propr-ui/src/App.tsx index 76cebf0f3..72168045f 100644 --- a/propr-ui/src/App.tsx +++ b/propr-ui/src/App.tsx @@ -28,6 +28,7 @@ const Dashboard = lazy(() => import('./components/Dashboard')) const LlmLogsPage = lazy(() => import('./pages/LlmLogsPage')) const InboxPage = lazy(() => import('./pages/InboxPage')) const LoginPage = lazy(() => import('./pages/LoginPage')) +const DesktopPairingPage = lazy(() => import('./pages/DesktopPairingPage')) const PlansPage = lazy(() => import('./pages/PlansPage')) const PlanStudioPage = lazy(() => import('./pages/PlanStudioPage')) const RepositoriesPage = lazy(() => import('./pages/RepositoriesPage')) @@ -235,6 +236,7 @@ const AppContent: React.FC = () => { }> } /> + } /> } /> + `${API_BASE_URL}/api/desktop/pairings/${encodeURIComponent(pairingId)}`; + +export async function getDesktopPairingApproval(pairingId: string): Promise { + const response = await apiFetch(`${pairingPath(pairingId)}/approval`, { + credentials: 'include', + cache: 'no-store', + }); + await handleApiResponse(response); + return response.json() as Promise; +} + +export async function approveDesktopPairing(pairingId: string): Promise { + const response = await apiFetch(`${pairingPath(pairingId)}/approve`, { + method: 'POST', + credentials: 'include', + headers: { 'Content-Type': 'application/json' }, + body: '{}', + }); + await handleApiResponse(response); + return response.json() as Promise; +} diff --git a/propr-ui/src/pages/DesktopPairingPage.test.tsx b/propr-ui/src/pages/DesktopPairingPage.test.tsx new file mode 100644 index 000000000..32c050287 --- /dev/null +++ b/propr-ui/src/pages/DesktopPairingPage.test.tsx @@ -0,0 +1,51 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; +import DesktopPairingPage from './DesktopPairingPage'; +import { approveDesktopPairing, getDesktopPairingApproval } from '../api/desktopAuth'; + +vi.mock('../api/desktopAuth', () => ({ + approveDesktopPairing: vi.fn(), + getDesktopPairingApproval: vi.fn(), +})); + +const pairingId = `dpr_${'A'.repeat(22)}`; +const pending = { + pairingId, + clientName: 'Alice’s MacBook', + status: 'pending' as const, + createdAt: '2026-08-29T14:00:00.000Z', + expiresAt: '2026-08-29T14:10:00.000Z', +}; + +describe('DesktopPairingPage', () => { + beforeEach(() => vi.clearAllMocks()); + + it('shows the server-provided client name and requires an explicit approval click', async () => { + vi.mocked(getDesktopPairingApproval).mockResolvedValue(pending); + vi.mocked(approveDesktopPairing).mockResolvedValue({ ...pending, status: 'approved' }); + render( + + + , + ); + + expect(await screen.findByText('Alice’s MacBook')).toBeInTheDocument(); + expect(approveDesktopPairing).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole('button', { name: 'Approve desktop' })); + + await waitFor(() => expect(approveDesktopPairing).toHaveBeenCalledWith(pairingId)); + expect(await screen.findByText('Desktop paired')).toBeInTheDocument(); + }); + + it('rejects malformed URL identifiers without making an API request', () => { + render( + + + , + ); + + expect(screen.getByRole('alert')).toHaveTextContent(/invalid/i); + expect(getDesktopPairingApproval).not.toHaveBeenCalled(); + }); +}); diff --git a/propr-ui/src/pages/DesktopPairingPage.tsx b/propr-ui/src/pages/DesktopPairingPage.tsx new file mode 100644 index 000000000..71304ca01 --- /dev/null +++ b/propr-ui/src/pages/DesktopPairingPage.tsx @@ -0,0 +1,91 @@ +import { useEffect, useMemo, useState } from 'react'; +import { useSearchParams } from 'react-router-dom'; +import { + approveDesktopPairing, + getDesktopPairingApproval, + type DesktopPairingApproval, +} from '../api/desktopAuth'; + +const PAIRING_ID_PATTERN = /^dpr_[A-Za-z0-9_-]{22}$/; + +const DesktopPairingPage = () => { + const [searchParams] = useSearchParams(); + const pairingId = useMemo(() => searchParams.get('pairing_id') ?? '', [searchParams]); + const [pairing, setPairing] = useState(null); + const [error, setError] = useState(''); + const [approving, setApproving] = useState(false); + + useEffect(() => { + if (!PAIRING_ID_PATTERN.test(pairingId)) { + setError('This desktop pairing link is invalid. Start pairing again from the desktop app.'); + return; + } + let cancelled = false; + getDesktopPairingApproval(pairingId) + .then(result => { if (!cancelled) setPairing(result); }) + .catch(() => { + if (!cancelled) setError('This pairing request was not found or has expired. Start pairing again from the desktop app.'); + }); + return () => { cancelled = true; }; + }, [pairingId]); + + const approve = async () => { + if (!pairing || pairing.status !== 'pending') return; + setApproving(true); + setError(''); + try { + setPairing(await approveDesktopPairing(pairing.pairingId)); + } catch { + setError('The pairing request could not be approved. It may have expired; start pairing again from the desktop app.'); + } finally { + setApproving(false); + } + }; + + const completed = pairing?.status === 'approved' || pairing?.status === 'consumed'; + + return ( +
+
+ ProPR +

+ {completed ? 'Desktop paired' : 'Approve desktop access'} +

+ {pairing && !completed && ( + <> +

+ Allow {pairing.clientName} to access this ProPR instance as you. + It receives your current instance role and permissions, but never your GitHub access token. +

+
+ + +
+ + )} + {completed && ( +

+ Return to the ProPR desktop app. You can revoke this device later from any authenticated client. +

+ )} + {!pairing && !error &&

Loading pairing request…

} + {error &&

{error}

} +
+
+ ); +}; + +export default DesktopPairingPage;