diff --git a/TODO.md b/TODO.md index 94859593..3d4ceaa6 100644 --- a/TODO.md +++ b/TODO.md @@ -1,84 +1,58 @@ -# Built-in MCP workflows and renewable VM grants +# Factorize Clients, VMs, and Apps -## Execution instructions +Implement the items below in order, from top to bottom. Work on one item until all its acceptance criteria are met and checked, then move to the next item. Check a box only after verifying it with the available VM shell, repository tests, browser tests, or GitHub tools. Record the verification command and result alongside each completed section. Fix recoverable failures and rerun the relevant checks. Do not stop until every criterion is complete. If access or infrastructure genuinely blocks progress, record the exact failed operation and leave the affected boxes open. -Implement each item from top to bottom. An item is complete only when all its acceptance criteria are fulfilled and checked off, with local verification evidence recorded beneath it. Only then start the next item. Continue until all items are complete. Do not mark unverified work complete. +Work in the exe.dev checkout on `codex/clients-vms-apps`. Follow `AGENTS.md` and the current contracts in this checkout. Use fixtures and the isolated local validation database. Do not run tests against production. -All criteria must be achievable by this agent in this VM. Use the existing pinned Factorize validation runner container (Node 24.12.0, npm 11.19.0), isolated loopback PostgreSQL and deterministic local provider/model fixtures. No criterion requires production deployment, a live provider account, external approval or publishing a plugin. Never validate against production/shared databases. Preserve package boundaries and existing client compatibility. Register JSON application operations under /api/v1, document them in OpenAPI and regenerate the public client. Run the complete root npm test after the final code change. +## 0. Verify the development environment -## 1. [x] Canonical build-shipped workflow skills +- [x] Boot the VM from the pinned Factorize validation runner image. +- [x] Clone `GenerationSoftware/factorize` and verify write access from the guest by pushing the feature branch and reading its ref back from GitHub. +- [x] Verify Node 24.12.0 and npm 11.19.0. Run the image smoke check for PostgreSQL and Chromium and run `npm ci`. -Create five standard, portable SKILL.md files: manage presets; manage skills; run and supervise work; manage triggers; manage environments and access. Explain real MCP operations with useful examples, authorization prerequisites, safe edits/retries and verification. Cover all preset types/defaults, skill frontmatter and dependencies, direct runs and pinned inputs, completion subscriptions and fallback, automation delivery diagnostics, reflection, exe.dev/Fly.io lifecycle and renewable grants. These files are the single source of truth; no plugin manifests or installation artifacts yet. Embed deterministic generated content into the Worker build without reading files at runtime. +Verified on `factorize-clients-vms-apps`. The image smoke script passed with the image-provided `/etc/environment` loaded for the non-login guest process. PostgreSQL authenticated on loopback, Chromium launched as `exedev`, and `npm ci` succeeded. -Acceptance: +## 1. Display existing VM attachments -- [x] Exactly five canonical skills have valid standard name/description frontmatter and cover the agreed workflows and operation names. -- [x] Local tests compare embedded bytes against the canonical files and validate stable, content-versioned URIs, exact byte sizes and SHA-256 manifests. -- [x] Generation is deterministic; a local drift check rejects stale generated content. No team/session/provider credentials appear in the catalog. +- [x] Add a **VMs** dashboard navigation entry. Show VMs with active Factorize proxy access, with machine name or ID, provider, access status, and links to the authorizing run or client connection. +- [x] Add **VMs** beside **Trace** and **Info** on run details. Show current and historical run VM access from retained binding records, including terminated runs where a record exists. +- [x] Make the same tenant-scoped read model support current and historical client VM grants for the Clients screen in item 2. Record attachment source, expiry and revocation where available. Use persisted access eligibility without polling provider power state or changing how VMs are granted or provisioned. +- [x] Verify with application tests that active and historical records appear in the appropriate views, unrelated machines are excluded, and another tenant cannot read them. Verify navigation and links in Chromium, including the empty state. -Evidence: Pinned runner npm ci completed; generate:skills and check:skills passed. builtin-skills.test.ts: 4 tests passed, including exact canonical bytes/manifests, deterministic generation, stale-output rejection and invalid URI rejection. +Verified with `vitest run test/vm-attachments.postgres.test.ts` (2 passed), `npm run build:app`, the focused Chromium inventory test (1 passed), and `git diff --check`. -## 2. [x] Static MCP Skills extension boundary +## 2. Move Authorized Clients to Clients -Publish only the built-in catalog through skills/list and skills/get for active authenticated identities, independent of skills:read. Serve its exact Markdown through resources/read. Editable team skills remain behind existing tools; retain authorized legacy team resources for compatibility. Pinned run packages remain readable resources but never appear in extension discovery. Keep authorization checks on every read and preserve Pi's pinned input references. +- [x] Add **Clients** to the dashboard navigation and redirect the old Authorized Clients settings URL. Show one row per MCP connection and put the OAuth app name in its own column. Keep API tokens and registered sign-in app connections outside this list. +- [x] A connection detail shows its active and historical VM grants, including access state. Verify two connections with the same OAuth client ID keep separate VM histories and can be revoked independently. +- [x] **Edit permissions** offers the team default via a preset selector. Reuse the repository's team permission default where available and the existing consent and scope definitions. Applying the default cannot grant additional scopes without consent. Keep grants as-is until an edit. Where no applicable default exists, show its unavailable state and preserve the grant. +- [x] Verify that narrowing permissions takes effect for outstanding requests and any dependent VM access that requires removed permissions. Verify the existing per-connection and compatibility client-wide revoke operations still work. -Acceptance: +Verified with the PostgreSQL attachment and client tests (3 passed), `npm run build:app`, the focused Chromium client permissions test (1 passed), and `git diff --check`. -- [x] Local MCP tests discover/get/read exactly five built-ins with matching manifests and no team or run entries, including clients without skills:read. -- [x] Different tenants/scopes/runs and team edits/renames/deletes cannot change built-in catalog content; inactive identities and invalid/noncanonical URIs are rejected. -- [x] Local tests prove team list/get tools still work with their existing scopes, legacy resources remain protected, and active runs can read their own immutable pinned supporting files without skills:read. -- [x] Hosted Pi discovery/read tests pass with the static catalog and retained pinned input resources. +## 3. Register and manage apps -Evidence: Pinned runner MCP catalog tests (4), package helpers (3), canonical catalog tests (4) passed; hosted-pi-mcp.postgres.test.ts (7) passed after updating the deterministic model fixture to discover built-ins. Tests cover cross-team/scope stability, rejected inactive identities/paths, retained team tools/resources and pinned supporting files after edits/deletion. Logs: /tmp/factorize-workflows-item2.log and /tmp/factorize-workflows-item2-pi.log. +- [x] Add **Apps** to the dashboard navigation with **Connected apps** and **Registered apps** views. Use **Registered apps** for team-owned registrations. The connected view consumes sign-in grants from item 4, with empty-state and fixture coverage in this item. +- [x] Team owners can register, list, inspect, edit, and disable confidential server-side apps and configure exact redirect URLs. Apps are team-only by default and support an opt-in **Available to everyone** setting. +- [x] Add dedicated app-management authorization for MCP. Verify a scoped MCP caller can manage non-secret fields for its team and an unscoped or cross-team caller is rejected. +- [x] Verify client secret creation and rotation are available only to an authorized browser session. Return newly issued secrets once, store a verifier, and never expose secret material in MCP, registration reads, logs, or test output. -## 3. [x] Explicit renewable one-hour grant leases +Verified with the PostgreSQL app registration test, the backend TypeScript check, the production frontend build, and the focused Chromium Apps test. -Decouple new VM grant expiry from the issuing OAuth access token. Creation and explicit renewal give one hour from that operation; token refresh alone does not renew a grant. Add renew_vm_grant and POST /api/v1/agent/vm-grants/{grantId}/renew. Only the same active parent OAuth authorization may renew with vm:grant, proxy:use and continuing access to the provider and every selected integration. Expired/revoked grants cannot be renewed or revived by replaying creation; require a new grant/idempotency key. Preserve existing exe.dev grant input and receipt compatibility. Timeout/revocation removes access, never deletes the VM. +## 4. Implement Sign in with Factorize -Acceptance: +- [x] Implement OpenID Connect for confidential server-side applications with code flow, PKCE S256, registered redirect URLs, client authentication, discovery, JWKS, and signed ID tokens. Verify a sample server app can perform sign-in and validate its ID token. +- [x] The built-in default is minimal identity with a stable subject. An app can explicitly ask for the current Factorize API scopes and receives only scopes expressly authorized by the user. Verify identity-only tokens cannot exercise Factorize application permissions and an approved scope can access its API operation. +- [x] Verify private apps reject other teams, public apps can accept other teams, and granted API access applies to the authorizing user's team. Cover invalid redirect, client secret, PKCE, and code reuse, and handling of scope and token audience. +- [x] **Connected apps** displays authorized sign-in app connections and supports revoking each connection. Verify revocation, app disabling, and secret rotation enforce their respective token and authentication effects. Verify existing MCP OAuth and device-code flows still work. -- [x] Local database/API tests verify one-hour creation independent of remaining token lifetime, successful renewal and no implicit renewal during ordinary requests/replayed creation. -- [x] Tests reject expired/revoked/foreign-parent/foreign-tenant renewal, missing scopes and revoked/disconnected provider or selected integrations; rejected renewal does not extend expiry. -- [x] Proxy access remains limited to selected integrations and checks current parent authorization; expiry/revocation blocks access and cleanup preserves the VM. -- [x] REST/MCP renewal use the same implementation; OpenAPI and generated client contain the validated operation. +Verified with the PostgreSQL server-app and token tests (3 passed), the Chromium sign-in consent test, and the existing OAuth and device-code runtime test. -Evidence: vm-grant-renewal.postgres.test.ts: 12 passed for shared REST/MCP renewal, token-independent leases, replay, ownership, expiry/revocation and integration access changes. Real Worker/OAuth agent-api-runtime.test.mjs: 2 passed with signed exe.dev identity, grant creation/renewal, subset enforcement, expiry/revocation and cleanup. npm run generate passed. Logs: /tmp/factorize-workflows-item3.log and /tmp/factorize-workflows-item3-runtime.log. +## 5. Finish validation and open the PR -## 4. [x] Fly.io grants using shared OIDC primitives +- [x] New JSON application operations use the shared documented `/api/v1` contract. Register routes in `protected-api.ts`, update OpenAPI, regenerate the API client, and verify authorization, validation and contract tests. Keep OAuth and OIDC wire-protocol routes in their protocol namespaces. +- [x] Document server app sign-in setup, team and public visibility, scopes, client secret rotation, and revocation. Preserve REST and MCP full/detail/trace responses and conditional-write omission compatibility. +- [x] Run `npm run check:boundaries`, `git diff --check`, and `npm run test:local` on the final code. The last command runs the complete root `npm test` suite with the isolated database. Record results and check every criterion supported by verification. +- [x] Commit and push the completed branch from the VM. Open a pull request against `main`, verify its URL and head, and include validation results. Update the final checklist state on the branch. -Extend grant_vm to Fly.io with an app selector plus exact Machine ID, preserving exe.dev calls. Reuse shared issuer discovery/signature/claim verification, Fly token acquisition and guest execution. Bind grants to the connected organization, app, machine, exact subject, grant-specific audience and guest-local proof. Return usable provider-specific token acquisition instructions. Expose both provider capabilities in reflection. Provider-specific cleanup never destroys the VM. - -Acceptance: - -- [x] Deterministic local provider fixtures enroll both providers and authenticate actual signed OIDC tokens through the proxy boundary; Fly grants renew/revoke/expire like exe.dev grants. -- [x] Tests reject wrong organization/app/machine/subject/audience, invalid/expired signatures, wrong proof, cross-parent access and changed provider identity/configuration. -- [x] Tests verify idempotent enrollment/retries, conflicting idempotency input rejection, selected-integration limits, fresh token renewal and safe cleanup without VM deletion. -- [x] Reflection and generated contracts identify exe.dev and Fly.io grant capabilities; existing exe.dev callers and receipts remain compatible. - -Evidence: Real Worker/OAuth runtime suite: 2 passed, including signed Fly and exe.dev OIDC enrollment/authentication, malformed identities/proofs, changed app organization/machine subject, idempotent enrollment recovery, token refresh plus explicit renewal, parent revocation and non-destructive cleanup. Shared verifier/token-source/lease suites: 29 passed. API TypeScript check passed. Logs: /tmp/factorize-workflows-item4-runtime.log and /tmp/factorize-workflows-item4-tests.log. - -## 5. [x] Documentation, integration review and complete validation - -Update MCP overview/tool reference and integration authorization documentation for static workflow discovery, live team skill tools, pinned resources, both grant providers and explicit one-hour lease renewal. Verify examples and contracts against implementation. Review authorization and compatibility together and complete root validation. - -Acceptance: - -- [x] Documentation validation, generated-content/contract drift checks, TypeScript and package boundary checks pass locally. -- [x] The complete root npm test passes after the final code change in the pinned runner with isolated databases, including real Worker/OAuth and Chromium lanes. -- [x] git diff --check passes; review confirms exact build-owned skills, preserved pinned/team reads, bounded delegation, renewal ownership and provider identity verification. -- [x] All preceding items have local evidence recorded here; the handoff reports changed behavior, validation and any limitations honestly. - - -Evidence: Complete root npm test passed after the final code change on 2026-11-21 in factorize-proxy-validation-final, using the pinned runner image sha256:1333c4a7bb49c4cbcdd28ca2b57331dfcbff7cf611db1aaeaa4830517aacf6d4, Node 24.12.0 and npm 11.19.0. npm ci completed before validation; bootstrap:test created the isolated loopback database and db:migrate applied 0093_fly_vm_grants. Reproduce from the repository root: - -```sh -docker exec -u exedev -w /work \ - -e DATABASE_URL=postgresql://postgres:local-validation-only@127.0.0.1:55434/factorize_workflows_validation \ - -e AUTH_TEST_DATABASE_URL=postgresql://postgres:local-validation-only@127.0.0.1:55434/factorize_workflows_validation \ - -e QUEUE_TEST_DATABASE_URL=postgresql://postgres:local-validation-only@127.0.0.1:55434/factorize_workflows_validation \ - factorize-proxy-validation-final npm test -git diff --check -git diff --cached --check -``` - -Result: all root validation steps passed, including generated skills/contracts and drift checks, builds, documentation/MCP inventory, package/API boundaries, TypeScript, Worker bundles/runtimes and OAuth, compiled app/API/PostgreSQL integration, Chromium, portable proxy and Docker. Backend: 149 files, 892 passed / 5 existing skips. Compiled integration: 40 passed. Functional Chromium: 6 passed. Application/browser checks: 139 passed / 1 existing skip. Proxy: 32 protocol tests and 4 harness tests passed. Docker historical compatibility: 2 passed. Full log: /tmp/factorize-workflows-root-final.log. Separate documentation generation/validation and package boundary checks passed; both whitespace checks passed. Final review covered static exact-byte publication and deployment generation, authenticated built-in reads, protected team/pinned resources, additive migration compatibility, parent ownership and current integration epochs at renewal, exact provider OIDC bindings, guest proof handling and non-destructive cleanup. Provider acceptance uses deterministic local fixtures and signed JWTs, without claiming new live-provider/deployment validation. Plugin packaging remains intentionally outside scope. +Verified on the exe.dev validation runner. `npm run check:boundaries`, `git diff --check`, and `npm run test:local` passed. The full suite passed generated contract checks, backend checks, compiled app/API/PostgreSQL integration, Chromium checks, proxy checks, and Docker compatibility. Opened [PR #421](https://github.com/GenerationSoftware/factorize/pull/421) against `main` from this VM. diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 1d14aa3b..fc74cc3f 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -2977,6 +2977,242 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/app-consent/{requestId}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Preview a registered app sign-in request + * @description Requires the team:read scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + get: operations["get_api_v1_app_consent_requestId"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/app-consent/decision": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Allow or deny a registered app sign-in request + * @description Requires the team:read scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + post: operations["post_api_v1_app_consent_decision"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/apps": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * List the team's app registrations + * @description Requires the apps:manage scope. + * + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. + */ + get: operations["get_api_v1_apps"]; + put?: never; + /** + * Register a server-side application + * @description Requires the apps:manage scope. + * + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. + */ + post: operations["post_api_v1_apps"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/apps/{appId}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Read an app registration + * @description Requires the apps:manage scope. + * + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. + */ + get: operations["get_api_v1_apps_appId"]; + /** + * Change an app registration, its visibility, or its enabled state + * @description Requires the apps:manage scope. + * + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. + */ + put: operations["put_api_v1_apps_appId"]; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/apps/{appId}/secret": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Issue or rotate a client secret in a browser session + * @description Requires the apps:manage scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + post: operations["post_api_v1_apps_appId_secret"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/app-connections": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * List sign-in apps authorized by the current user + * @description Requires the team:read scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + get: operations["get_api_v1_app_connections"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/app-connections/{connectionId}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + post?: never; + /** + * Revoke one sign-in app connection + * @description Requires the team:write scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + delete: operations["delete_api_v1_app_connections_connectionId"]; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/vms": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * List VMs with active Factorize proxy access + * @description Requires an interactive owner session. Reports access status from Factorize records. + * + * Requires the runs:read scope. + * + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. + */ + get: operations["get_api_v1_vms"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/runs/{runId}/vms": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * List a run's current and historical VM access + * @description Requires the runs:read scope. + * + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. + */ + get: operations["get_api_v1_runs_runId_vms"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/access/authorizations/{grantId}/vms": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * List current and historical VM access delegated by an MCP connection + * @description Requires an interactive owner session. + * + * Requires the runs:read scope. + * + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. + */ + get: operations["get_api_v1_access_authorizations_grantId_vms"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/runs/{runId}/status": { parameters: { query?: never; @@ -4775,7 +5011,7 @@ export interface operations { /** @constant */ role: "owner"; }; - capabilities: ("team:read" | "team:write" | "triggers:read" | "triggers:write" | "runs:read" | "runs:invoke" | "runs:start" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write")[]; + capabilities: ("team:read" | "team:write" | "triggers:read" | "triggers:write" | "runs:read" | "runs:invoke" | "runs:start" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write" | "apps:manage")[]; /** Format: date-time */ expiresAt: string; }; @@ -7126,7 +7362,7 @@ export interface operations { }; content: { "application/json": { - availableScopes: ("team:read" | "team:write" | "triggers:read" | "triggers:write" | "runs:read" | "runs:invoke" | "runs:start" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write" | "proxy:use" | "vm:grant")[]; + availableScopes: ("team:read" | "team:write" | "triggers:read" | "triggers:write" | "runs:read" | "runs:invoke" | "runs:start" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write" | "proxy:use" | "vm:grant" | "apps:manage")[]; /** @description Integration ID to approved epoch-bound scope, or false to block. */ integrationOverrides: { [key: string]: string | false; @@ -7135,6 +7371,7 @@ export interface operations { grantId: string; clientId: string; clientName: string; + appName?: string; scopes: string[]; authorizationDate: string; expiresAt: string | null; @@ -7276,12 +7513,16 @@ export interface operations { requestBody: { content: { "application/json": { - disabledScopes: ("team:read" | "team:write" | "triggers:read" | "triggers:write" | "runs:read" | "runs:invoke" | "runs:start" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write" | "proxy:use" | "vm:grant")[]; + disabledScopes: ("team:read" | "team:write" | "triggers:read" | "triggers:write" | "runs:read" | "runs:invoke" | "runs:start" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write" | "proxy:use" | "vm:grant" | "apps:manage")[]; /** @description Integration ID to approved epoch-bound scope, or false to block. */ integrationOverrides: { [key: string]: string | false; }; expectedRevision?: number; + } | { + /** @constant */ + preset: "team-default"; + expectedRevision?: number; }; }; }; @@ -12836,6 +13077,484 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; + get_api_v1_app_consent_requestId: { + parameters: { + query?: never; + header?: never; + path: { + requestId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Requested app permissions */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + appName: string; + scopes: string[]; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + post_api_v1_app_consent_decision: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + /** Format: uuid */ + requestId: string; + /** @enum {string} */ + decision: "allow" | "deny"; + }; + }; + }; + responses: { + /** @description Registered redirect destination */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + redirectTo: string; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 415: components["responses"]["Error415"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + get_api_v1_apps: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Registered apps */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** Format: uuid */ + id: string; + name: string; + redirectUris: string[]; + public: boolean; + enabled: boolean; + secretConfigured: boolean; + }[]; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + post_api_v1_apps: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + name: string; + redirectUris: string[]; + /** @default false */ + public?: boolean; + }; + }; + }; + responses: { + /** @description Registered app */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** Format: uuid */ + id: string; + name: string; + redirectUris: string[]; + public: boolean; + enabled: boolean; + secretConfigured: boolean; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 415: components["responses"]["Error415"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + get_api_v1_apps_appId: { + parameters: { + query?: never; + header?: never; + path: { + appId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Registered app */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** Format: uuid */ + id: string; + name: string; + redirectUris: string[]; + public: boolean; + enabled: boolean; + secretConfigured: boolean; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + put_api_v1_apps_appId: { + parameters: { + query?: never; + header?: never; + path: { + appId: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + name: string; + redirectUris: string[]; + /** @default false */ + public?: boolean; + enabled: boolean; + }; + }; + }; + responses: { + /** @description Registered app */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** Format: uuid */ + id: string; + name: string; + redirectUris: string[]; + public: boolean; + enabled: boolean; + secretConfigured: boolean; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 415: components["responses"]["Error415"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + post_api_v1_apps_appId_secret: { + parameters: { + query?: never; + header?: never; + path: { + appId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description One-time secret */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** Format: uuid */ + clientId: string; + clientSecret: string; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + get_api_v1_app_connections: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Connected apps */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** Format: uuid */ + id: string; + /** Format: uuid */ + appId: string; + name: string; + scopes: string[]; + /** Format: date-time */ + authorizedAt: string; + }[]; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + delete_api_v1_app_connections_connectionId: { + parameters: { + query?: never; + header?: never; + path: { + connectionId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Connection revoked */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + ok: boolean; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + get_api_v1_vms: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Active VM access attachments */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + id: string; + /** @enum {string} */ + source: "run" | "client"; + sourceId: string; + sourceName: string | null; + vmId: string; + app: string | null; + /** @enum {string} */ + provider: "exe.dev" | "fly.io"; + /** Format: date-time */ + expiresAt: string; + revokedAt: string | null; + /** @enum {string} */ + status: "active" | "expired" | "revoked" | "inactive" | "pending"; + }[]; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + get_api_v1_runs_runId_vms: { + parameters: { + query?: never; + header?: never; + path: { + runId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Run VM attachments */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + id: string; + /** @enum {string} */ + source: "run" | "client"; + sourceId: string; + sourceName: string | null; + vmId: string; + app: string | null; + /** @enum {string} */ + provider: "exe.dev" | "fly.io"; + /** Format: date-time */ + expiresAt: string; + revokedAt: string | null; + /** @enum {string} */ + status: "active" | "expired" | "revoked" | "inactive" | "pending"; + }[]; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + get_api_v1_access_authorizations_grantId_vms: { + parameters: { + query?: never; + header?: never; + path: { + grantId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Connection VM attachments */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + id: string; + /** @enum {string} */ + source: "run" | "client"; + sourceId: string; + sourceName: string | null; + vmId: string; + app: string | null; + /** @enum {string} */ + provider: "exe.dev" | "fly.io"; + /** Format: date-time */ + expiresAt: string; + revokedAt: string | null; + /** @enum {string} */ + status: "active" | "expired" | "revoked" | "inactive" | "pending"; + }[]; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; get_api_v1_runs_runId_status: { parameters: { query?: never; diff --git a/packages/api/migrations/0095_oauth_apps.sql b/packages/api/migrations/0095_oauth_apps.sql new file mode 100644 index 00000000..e6eab497 --- /dev/null +++ b/packages/api/migrations/0095_oauth_apps.sql @@ -0,0 +1,23 @@ +CREATE TABLE app.oauth_apps ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + tenant_id uuid NOT NULL REFERENCES app.tenants(id) ON DELETE CASCADE, + name text NOT NULL, + redirect_uris text[] NOT NULL, + is_public boolean NOT NULL DEFAULT false, + enabled boolean NOT NULL DEFAULT true, + secret_digest text, + secret_version integer NOT NULL DEFAULT 0 +); +CREATE INDEX oauth_apps_team ON app.oauth_apps(tenant_id); +CREATE TABLE app.oauth_app_connections ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + app_id uuid NOT NULL REFERENCES app.oauth_apps(id) ON DELETE CASCADE, + tenant_id uuid NOT NULL REFERENCES app.tenants(id) ON DELETE CASCADE, + user_id uuid NOT NULL REFERENCES app.auth_users(id) ON DELETE CASCADE, + session_version integer NOT NULL, + scopes text[] NOT NULL, + authorized_at timestamptz NOT NULL DEFAULT now(), + revoked_at timestamptz +); +CREATE INDEX oauth_app_connections_owner ON app.oauth_app_connections(tenant_id, user_id); +INSERT INTO app.schema_migrations(version) VALUES ('0095_oauth_apps'); diff --git a/packages/api/migrations/0096_oidc_provider.sql b/packages/api/migrations/0096_oidc_provider.sql new file mode 100644 index 00000000..051a1869 --- /dev/null +++ b/packages/api/migrations/0096_oidc_provider.sql @@ -0,0 +1,39 @@ +CREATE TABLE app.oidc_requests ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + app_id uuid NOT NULL REFERENCES app.oauth_apps(id) ON DELETE CASCADE, + redirect_uri text NOT NULL, + challenge text NOT NULL, + state text, + nonce text, + scopes text[] NOT NULL, + expires_at timestamptz NOT NULL, + decided_at timestamptz +); +CREATE INDEX oidc_requests_expiry ON app.oidc_requests(expires_at); +CREATE TABLE app.oidc_codes ( + digest text PRIMARY KEY, + connection_id uuid NOT NULL REFERENCES app.oauth_app_connections(id) ON DELETE CASCADE, + secret_version integer NOT NULL, + redirect_uri text NOT NULL, + challenge text NOT NULL, + nonce text, + expires_at timestamptz NOT NULL +); +CREATE INDEX oidc_codes_expiry ON app.oidc_codes(expires_at); +CREATE TABLE app.oidc_tokens ( + access_digest text PRIMARY KEY, + refresh_digest text UNIQUE, + connection_id uuid NOT NULL REFERENCES app.oauth_app_connections(id) ON DELETE CASCADE, + secret_version integer NOT NULL, + scopes text[] NOT NULL, + access_expires_at timestamptz NOT NULL, + refresh_expires_at timestamptz +); +CREATE INDEX oidc_tokens_expiry ON app.oidc_tokens(access_expires_at, refresh_expires_at); +CREATE TABLE app.oidc_signing_key ( + singleton boolean PRIMARY KEY DEFAULT true CHECK (singleton), + kid uuid NOT NULL DEFAULT gen_random_uuid(), + public_key jsonb NOT NULL, + encrypted_private_key text NOT NULL +); +INSERT INTO app.schema_migrations(version) VALUES ('0096_oidc_provider'); diff --git a/packages/api/src/access-tokens.ts b/packages/api/src/access-tokens.ts index fa072467..3c0c213b 100644 --- a/packages/api/src/access-tokens.ts +++ b/packages/api/src/access-tokens.ts @@ -4,7 +4,7 @@ import { databaseFor } from "./postgres/database"; import { AccessTokenRepository } from "./postgres/access-token-repository"; export const ACCESS_SCOPES = ["team:read", "team:write", "triggers:read", "triggers:write", "runs:read", "runs:invoke", "runs:start", "runs:cancel", "runs:write", "integrations:read", "integrations:write", "skills:read", "skills:write"] as const; -export const AGENT_SCOPES = [...ACCESS_SCOPES, "proxy:use", "vm:grant"] as const; +export const AGENT_SCOPES = [...ACCESS_SCOPES, "proxy:use", "vm:grant", "apps:manage"] as const; export type AccessScope = typeof ACCESS_SCOPES[number]; export function normalizeScopes(scopes: readonly string[]): string[] { return [...new Set(scopes.filter(scope => (AGENT_SCOPES as readonly string[]).includes(scope) || isIntegrationScope(scope)))]; diff --git a/packages/api/src/agent-api.ts b/packages/api/src/agent-api.ts index 8f287baa..0fc92e72 100644 --- a/packages/api/src/agent-api.ts +++ b/packages/api/src/agent-api.ts @@ -20,7 +20,7 @@ import type { z } from "zod"; export type AgentIntegration = {id: string; kind: "bearer" | "model" | "github" | "linear" | "fly" | "exe" | "amp" | "clickup" | "x"; credential_id: string; name: string; description: string | null; available: boolean; policy: "baseline" | "requestable" | "disabled"; epoch: number; revision: number}; export const requiredIntegrationScope = (row: AgentIntegration) => `integration:${row.id}:${row.epoch}`; type ConnectionPolicy = { integration_overrides: Record; disabled_scopes: string[] }; -function connectionAccess(row: AgentIntegration, scopes: string[], policy: ConnectionPolicy) { +export function connectionAccess(row: AgentIntegration, scopes: string[], policy: ConnectionPolicy) { const scope = requiredIntegrationScope(row); if (policy.disabled_scopes.includes("proxy:use") || policy.integration_overrides[row.id] === false || row.policy === "disabled" || !row.available) return "blocked"; return row.policy === "baseline" || policy.integration_overrides[row.id] === scope || scopes.includes(scope) ? "granted" : "requestable"; diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index d4bb9335..a933277d 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -19,12 +19,15 @@ import { queryOf } from "./query-params"; import { launchPayloadResponse } from "./launch-payload"; import { searchResponse } from "./search-contracts"; import { consentPreviewInput, consentPreviewResponse, consentDecisionInput, consentDecisionResponse } from "./consent-api"; -import { exeConnection, integrationStatus, clientPermissionsInput, authorizedClient, accessToken, createdAccessToken, savedExe, testedExe, savedAmp, savedTail, okResult } from "./settings-contracts"; +import { exeConnection, integrationStatus, clientPermissionsUpdate, authorizedClient, accessToken, createdAccessToken, savedExe, testedExe, savedAmp, savedTail, okResult } from "./settings-contracts"; import { eventAvailabilityResponse, namedOption, providerOptions, githubInstallation, githubRepository, tailIntegration } from "./editor-contracts"; import { runSummaryResponse, runPageResponse, runStatusResponse, fullRunResponse, revisionTracePage, revisionTraceQuery, runtimeContextResponse, runtimeIntegrationsResponse } from "./run-read-contracts"; import { triggerPageQuery, triggerSummaryPage, triggerSelectorPage, triggerResponse, triggerUpdateInput } from "./job-contracts"; import { projectGraphResponse } from "./project-graph-contracts"; import { z } from "zod"; +import { oidcConsentInput, oidcConsentPreview } from "./oidc-provider"; +import { appRegistrationInput, appRegistrationUpdate, appSecret, connectedApp, registeredApp } from "./apps-contracts"; +import { vmAttachments } from "./vm-attachment-contracts"; import type { ApiService } from "./flow-service"; import { triggerInputSchema, @@ -675,7 +678,7 @@ export const API_ROUTES: RouteContract[] = [ route("PUT", "/api/v1/access/authorizations/{grantId}/permissions", "triggers:write", { summary: "Edit an OAuth connection’s scopes and integration access", responses: {"200": {description: "Permissions saved", content: {"application/json": {schema: jsonSchema(okResult, "output")}}}}, - }, (service, {params, body}) => service.updateClientPermissions(params.grantId, body), {ownerSession: true, body: clientPermissionsInput}), + }, (service, {params, body}) => service.updateClientPermissions(params.grantId, body), {ownerSession: true, body: clientPermissionsUpdate}), route("DELETE", "/api/v1/access/authorizations/{grantId}", "triggers:write", {summary:"Revoke one isolated OAuth connection", description:"Other connections, including copies of the same client, retain their approvals.",responses:{"200":{description:"Authorization revoked",content:{"application/json":{schema:jsonSchema(z.object({revoked:z.number().int()}),"output")}}}}}, (service,{params})=>service.revokeOAuthAuthorization(params.grantId), {ownerSession:true}), route( "DELETE", @@ -1085,6 +1088,56 @@ export const API_ROUTES: RouteContract[] = [ }, (service, { params }) => service.getWebhookDelivery(params.deliveryId), ), + route("GET", "/api/v1/app-consent/{requestId}", "team:read", { + summary: "Preview a registered app sign-in request", + responses: { "200": { description: "Requested app permissions", content: { "application/json": { schema: jsonSchema(oidcConsentPreview, "output") } } } }, + }, (service, { params }) => service.inspectAppConsent(params.requestId), { parameters: z.object({ requestId: z.uuid() }), ownerSession: true }), + route("POST", "/api/v1/app-consent/decision", "team:read", { + summary: "Allow or deny a registered app sign-in request", + responses: { "200": { description: "Registered redirect destination", content: { "application/json": { schema: jsonSchema(z.object({ redirectTo: z.string() }), "output") } } } }, + }, (service, { body }) => service.decideAppConsent(body), { body: oidcConsentInput, ownerSession: true }), + route("GET", "/api/v1/apps", "apps:manage", { + summary: "List the team's app registrations", + responses: { "200": { description: "Registered apps", content: { "application/json": { schema: jsonSchema(z.array(registeredApp), "output") } } } }, + }, service => service.listApps()), + route("POST", "/api/v1/apps", "apps:manage", { + summary: "Register a server-side application", + responses: { "200": { description: "Registered app", content: { "application/json": { schema: jsonSchema(registeredApp, "output") } } } }, + }, (service, { body }) => service.createApp(body), { body: appRegistrationInput }), + route("GET", "/api/v1/apps/{appId}", "apps:manage", { + summary: "Read an app registration", + responses: { "200": { description: "Registered app", content: { "application/json": { schema: jsonSchema(registeredApp, "output") } } } }, + }, (service, { params }) => service.getApp(params.appId), { parameters: z.object({ appId: z.uuid() }) }), + route("PUT", "/api/v1/apps/{appId}", "apps:manage", { + summary: "Change an app registration, its visibility, or its enabled state", + responses: { "200": { description: "Registered app", content: { "application/json": { schema: jsonSchema(registeredApp, "output") } } } }, + }, (service, { params, body }) => service.updateApp(params.appId, body), { parameters: z.object({ appId: z.uuid() }), body: appRegistrationUpdate }), + route("POST", "/api/v1/apps/{appId}/secret", "apps:manage", { + summary: "Issue or rotate a client secret in a browser session", + responses: { "200": { description: "One-time secret", content: { "application/json": { schema: jsonSchema(appSecret, "output") } } } }, + }, (service, { params }) => service.rotateAppSecret(params.appId), { parameters: z.object({ appId: z.uuid() }), ownerSession: true }), + route("GET", "/api/v1/app-connections", "team:read", { + summary: "List sign-in apps authorized by the current user", + responses: { "200": { description: "Connected apps", content: { "application/json": { schema: jsonSchema(z.array(connectedApp), "output") } } } }, + }, service => service.listConnectedApps(), { ownerSession: true }), + route("DELETE", "/api/v1/app-connections/{connectionId}", "team:write", { + summary: "Revoke one sign-in app connection", + responses: { "200": { description: "Connection revoked", content: { "application/json": { schema: jsonSchema(okResult, "output") } } } }, + }, (service, { params }) => service.revokeConnectedApp(params.connectionId), { parameters: z.object({ connectionId: z.uuid() }), ownerSession: true }), + route("GET", "/api/v1/vms", "runs:read", { + summary: "List VMs with active Factorize proxy access", + description: "Requires an interactive owner session. Reports access status from Factorize records.", + responses: { "200": { description: "Active VM access attachments", content: { "application/json": { schema: jsonSchema(vmAttachments, "output") } } } }, + }, service => service.listProxyVms()), + route("GET", "/api/v1/runs/{runId}/vms", "runs:read", { + summary: "List a run's current and historical VM access", + responses: { "200": { description: "Run VM attachments", content: { "application/json": { schema: jsonSchema(vmAttachments, "output") } } } }, + }, (service, { params }) => service.listRunVms(params.runId), { parameters: z.object({ runId: z.guid() }) }), + route("GET", "/api/v1/access/authorizations/{grantId}/vms", "runs:read", { + summary: "List current and historical VM access delegated by an MCP connection", + description: "Requires an interactive owner session.", + responses: { "200": { description: "Connection VM attachments", content: { "application/json": { schema: jsonSchema(vmAttachments, "output") } } } }, + }, (service, { params }) => service.listClientVms(params.grantId), { parameters: z.object({ grantId: z.string().min(1).max(255) }) }), route("GET", "/api/v1/runs/{runId}/status", "runs:read", { summary: "Get lightweight run status", description: "Only bounded encrypted prompt/script previews are decrypted; full prompt, invocation context, artifacts, activity and diagnostics stay in the detail operation. Continue polling terminal runs while finalizing is true. trace_revision changes on generation transition or canonical projection/replay; live appends retain the revision. Full detail remains available at GET /runs/{runId}.", diff --git a/packages/api/src/apps-contracts.ts b/packages/api/src/apps-contracts.ts new file mode 100644 index 00000000..0d89d6e4 --- /dev/null +++ b/packages/api/src/apps-contracts.ts @@ -0,0 +1,36 @@ +import { z } from "zod"; + +const redirectUri = z.string().max(2048).refine(value => { + try { + const parsed = new URL(value); + return (parsed.protocol === "https:" || + (parsed.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(parsed.hostname))) && + !parsed.username && !parsed.password && !value.includes("#"); + } catch { + return false; + } +}, "Use an HTTPS callback URL, or an HTTP loopback URL for local development."); + +export const appRegistrationInput = z.object({ + name: z.string().trim().min(1).max(100), + redirectUris: z.array(redirectUri).min(1).max(10).refine(values => new Set(values).size === values.length), + public: z.boolean().default(false), +}).strict(); + +export const appRegistrationUpdate = appRegistrationInput.extend({ enabled: z.boolean() }); +export const registeredApp = z.object({ + id: z.uuid(), + name: z.string(), + redirectUris: z.array(z.string()), + public: z.boolean(), + enabled: z.boolean(), + secretConfigured: z.boolean(), +}); +export const appSecret = z.object({ clientId: z.uuid(), clientSecret: z.string() }); +export const connectedApp = z.object({ + id: z.uuid(), + appId: z.uuid(), + name: z.string(), + scopes: z.array(z.string()), + authorizedAt: z.iso.datetime(), +}); diff --git a/packages/api/src/auth-api.ts b/packages/api/src/auth-api.ts index dad8dcdf..1a5a03aa 100644 --- a/packages/api/src/auth-api.ts +++ b/packages/api/src/auth-api.ts @@ -12,7 +12,7 @@ import { databaseFor } from "./postgres/database"; import { readSession, requestCookie, signSession, type Session } from "./session"; import type { Env } from "./types"; -export const SESSION_SCOPES = ACCESS_SCOPES; +export const SESSION_SCOPES = [...ACCESS_SCOPES, "apps:manage"] as const; const email = z.string().trim().toLowerCase().email().max(320); const password = z.string().min(12).max(200).meta({ writeOnly: true }); const connection = z.uuid().optional(); @@ -48,7 +48,7 @@ export function safeReturnTo(value: string | undefined): string { try { const url = new URL(value, "https://local.invalid"); if (url.origin !== "https://local.invalid") return "/integrations"; - if (!/^\/(?:authorize|device|integrations|skills(?:\/[^/]+(?:\/(?:runs|settings(?:\/(?:general|vm|permissions|trigger))?))?)?|triggers(?:\/[^/]+(?:\/(?:edit|settings(?:\/(?:general|vm|context|permissions|events))?))?)?|runs(?:\/[^/]+(?:\/(?:trace|info))?)?|settings(?:\/(?:profile|vm|permissions|skills|vm-presets|integrations|api-keys(?:\/new)?|authorized-clients|password))?)$/.test(url.pathname)) return "/integrations"; + if (!/^\/(?:authorize|device|integrations|app-consent|vms|clients(?:\/[^/]+)?|apps(?:\/registered)?|skills(?:\/[^/]+(?:\/(?:runs|settings(?:\/(?:general|vm|permissions|trigger))?))?)?|triggers(?:\/[^/]+(?:\/(?:edit|settings(?:\/(?:general|vm|context|permissions|events))?))?)?|runs(?:\/[^/]+(?:\/(?:trace|info|vms))?)?|settings(?:\/(?:profile|vm|permissions|skills|vm-presets|integrations|api-keys(?:\/new)?|authorized-clients|password))?)$/.test(url.pathname)) return "/integrations"; return url.pathname + url.search + url.hash; } catch { return "/integrations"; } } diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index d5ee7e52..d39193f6 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -30,6 +30,11 @@ import { submitRun } from "./postgres/run-submission"; import type { DatabaseClient } from "./postgres/database"; import { startRunInput,projectRunDefaults,scopeSchema, teamRunDefaults } from "./flow-schemas"; import { grantVm, renewVmGrant, revokeVmGrant } from "./vm-grants"; +import { decideOidcConsent, inspectOidcConsent, oidcConsentInput, oidcConsentPreview } from "./oidc-provider"; +import { AppsRepository } from "./postgres/apps-repository"; +import { appRegistrationInput, appRegistrationUpdate, appSecret, connectedApp, registeredApp } from "./apps-contracts"; +import { VmAttachmentRepository } from "./postgres/vm-attachment-repository"; +import { vmAttachments } from "./vm-attachment-contracts"; import { AgentApiService, listAgentPolicies } from "./agent-api"; import {PhoenixIntegration,runPhoenixStatus} from "./phoenix"; import {phoenixInput,phoenixRevision} from "./phoenix-contracts"; @@ -42,7 +47,7 @@ import { apiPolicyInput, integrationRef, requestApiInput, readApiResponseInput } import { DEFAULT_RUN_SCOPES } from "./run-scopes"; import { launchPayloadResponse } from "./launch-payload"; import { searchResponse } from "./search-contracts"; -import { integrationStatus, exeConnection, accessToken, createdAccessToken, clientPermissionsInput, clientNameInput, authorizedClient } from "./settings-contracts"; +import { integrationStatus, exeConnection, accessToken, createdAccessToken, clientPermissionsUpdate, clientNameInput, authorizedClient } from "./settings-contracts"; import { namedOption, providerOptions, githubRepository, githubInstallation, tailIntegration } from "./editor-contracts"; import { z } from "zod"; import { runPageResponse, fullRunResponse, runtimeContextResponse, runtimeIntegrationsResponse } from "./run-read-contracts"; @@ -106,7 +111,7 @@ export function publicValue(schema: T, value: unknown): z.o return result.data; } -type Scope = "runs:start" | "team:read" | "team:write" | "triggers:read" | "triggers:write" | "runs:read" | "runs:invoke" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write"; +type Scope = "apps:manage" | "runs:start" | "team:read" | "team:write" | "triggers:read" | "triggers:write" | "runs:read" | "runs:invoke" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write"; export class ApiService { authorizationDuration = 0; @@ -701,6 +706,25 @@ export class ApiService { } async search(query: string) { await this.authorize("skills:read"); await this.authorize("runs:read"); return publicValue(searchResponse, await new OperationsRepository(databaseFor(this.env), this.auth.tenantId).search(query)); } async eventContextMetadata() { await this.authorize("triggers:read"); return eventContextCatalog; } + async listProxyVms() { + await this.authorizeOwnerSession("runs:read"); + const repository = new VmAttachmentRepository(databaseFor(this.env), this.auth.tenantId); + const [runs, clients] = await Promise.all([repository.runs(), repository.clients(this.auth.userId)]); + return publicValue(vmAttachments, [...runs, ...clients].filter(attachment => attachment.status === "active")); + } + + async listRunVms(runId: string) { + await this.getRunStatus(runId); + const repository = new VmAttachmentRepository(databaseFor(this.env), this.auth.tenantId); + return publicValue(vmAttachments, await repository.runs(runId)); + } + + async listClientVms(grantId: string) { + await this.authorizeOwnerSession("runs:read"); + const repository = new VmAttachmentRepository(databaseFor(this.env), this.auth.tenantId); + return publicValue(vmAttachments, await repository.clients(this.auth.userId, grantId)); + } + async getRunStatus(runId: string) { await this.authorize("runs:read"); const status = await new RunQueryRepository(databaseFor(this.env), this.auth.tenantId).status(runId); if (!status) throw new ServiceError(404, "not_found", "Run not found"); return status; } async reportRunError(runId: string, input: unknown) { await this.authorize("runs:write"); @@ -1682,6 +1706,56 @@ export class ApiService { async githubIssueOptions(installationId: number, repositoryId: number) { await this.authorize("integrations:read"); return publicValue(providerOptions, await this.providers().githubIssueOptions(installationId, repositoryId)); } async removeGitHubInstallation(id: number) { await this.authorize("integrations:write"); if (!await new GitHubRepository(databaseFor(this.env), this.auth.tenantId).delete(id)) throw new ServiceError(404, "not_found", "Installation not found"); return { id, deleted: true }; } + async inspectAppConsent(requestId: string) { + await this.authorizeOwnerSession("team:read"); + const preview = await inspectOidcConsent(this.env, this.auth, requestId); + if (!preview) throw new ServiceError(404, "not_found", "App sign-in request is unavailable."); + return publicValue(oidcConsentPreview, preview); + } + async decideAppConsent(body: unknown) { + await this.authorizeOwnerSession("team:read"); + const redirectTo = await decideOidcConsent(this.env, this.auth, oidcConsentInput.parse(body)); + if (!redirectTo) throw new ServiceError(404, "not_found", "App sign-in request is unavailable."); + return { redirectTo }; + } + + private apps() { return new AppsRepository(databaseFor(this.env), this.auth.tenantId); } + async listApps() { + await this.authorize("apps:manage"); + return publicValue(z.array(registeredApp), await this.apps().list()); + } + async getApp(id: string) { + await this.authorize("apps:manage"); + const value = await this.apps().find(id); + if (!value) throw new ServiceError(404, "not_found", "App not found."); + return publicValue(registeredApp, value); + } + async createApp(body: unknown) { + await this.authorize("apps:manage"); + return publicValue(registeredApp, await this.apps().create(appRegistrationInput.parse(body))); + } + async updateApp(id: string, body: unknown) { + await this.authorize("apps:manage"); + const value = await this.apps().update(id, appRegistrationUpdate.parse(body)); + if (!value) throw new ServiceError(404, "not_found", "App not found."); + return publicValue(registeredApp, value); + } + async rotateAppSecret(id: string) { + await this.authorizeOwnerSession("apps:manage"); + const secret = await this.apps().rotateSecret(id); + if (!secret) throw new ServiceError(404, "not_found", "App not found."); + return publicValue(appSecret, secret); + } + async listConnectedApps() { + await this.authorizeOwnerSession("team:read"); + return publicValue(z.array(connectedApp), await this.apps().connected(this.auth.userId)); + } + async revokeConnectedApp(id: string) { + await this.authorizeOwnerSession("team:write"); + if (!await this.apps().revoke(this.auth.userId, id)) throw new ServiceError(404, "not_found", "App connection not found."); + return { ok: true }; + } + async renameMcpClient(input: unknown) { const { name } = clientNameInput.parse(input); if (this.auth.authMethod !== "oauth") throw new ServiceError(403, "forbidden", "An OAuth connection is required."); @@ -1691,16 +1765,29 @@ export class ApiService { } async updateClientPermissions(grantId: string, input: unknown) { await this.authorizeOwnerSession("triggers:write"); - const edit = clientPermissionsInput.parse(input); + const edit = clientPermissionsUpdate.parse(input); const client = (await this.listAuthorizedClients()).find(client => client.grantId === grantId); if (!client) throw new ServiceError(404, "not_found", "Authorization not found."); - if (edit.disabledScopes.some(scope => !client.availableScopes.includes(scope))) throw new ServiceError(400, "invalid_request", "Scope is outside this authorization."); - const { integrations } = await listAgentPolicies(this.env, this.auth.tenantId); - const current = new Map(integrations.map(row => [row.id, row])); - if (Object.entries(edit.integrationOverrides).some(([id, approval]) => { - const row = current.get(id); - return !row || (approval !== false && (!row.available || row.policy === "disabled" || approval !== row.requiredScope)); - })) throw new ServiceError(409, "conflict", "Integration availability changed. Reload permissions."); + let disabledScopes: typeof client.availableScopes; + let integrationOverrides: Record; + if ("preset" in edit) { + await migratePresetSkills(this.env, this.auth.tenantId); + const preset = (await this.presets().list()).find(item => item.kind === "permission" && item.isDefault); + if (!preset || preset.kind !== "permission") throw new ServiceError(409, "conflict", "Team permission default is unavailable."); + const allowed = new Set(preset.settings.runScopes ?? []); + disabledScopes = client.availableScopes.filter(scope => !allowed.has(scope) || !client.scopes.includes(scope)); + integrationOverrides = client.integrationOverrides; + } else { + disabledScopes = edit.disabledScopes; + integrationOverrides = edit.integrationOverrides; + if (disabledScopes.some(scope => !client.availableScopes.includes(scope))) throw new ServiceError(400, "invalid_request", "Scope is outside this authorization."); + const { integrations } = await listAgentPolicies(this.env, this.auth.tenantId); + const current = new Map(integrations.map(row => [row.id, row])); + if (Object.entries(integrationOverrides).some(([id, approval]) => { + const row = current.get(id); + return !row || (approval !== false && (!row.available || row.policy === "disabled" || approval !== row.requiredScope)); + })) throw new ServiceError(409, "conflict", "Integration availability changed. Reload permissions."); + } const result = await databaseFor(this.env).pool.query(` INSERT INTO app.agent_identities AS i(tenant_id,kind,subject,user_id,session_version,disabled_scopes,integration_overrides,permissions_revision) SELECT $1,'oauth',$2,$3,$4,$5,$6,1 WHERE coalesce($7::integer,0)=0 OR EXISTS @@ -1708,7 +1795,7 @@ export class ApiService { ON CONFLICT(tenant_id,kind,subject) DO UPDATE SET disabled_scopes=excluded.disabled_scopes, integration_overrides=excluded.integration_overrides, permissions_revision=i.permissions_revision+1 WHERE i.revoked_at IS NULL AND i.user_id=excluded.user_id AND ($7 IS NULL OR i.permissions_revision=$7) - RETURNING permissions_revision`, [this.auth.tenantId, grantId, this.auth.userId, this.auth.sessionVersion, edit.disabledScopes, JSON.stringify(edit.integrationOverrides), edit.expectedRevision]); + RETURNING permissions_revision`, [this.auth.tenantId, grantId, this.auth.userId, this.auth.sessionVersion, disabledScopes, JSON.stringify(integrationOverrides), edit.expectedRevision ?? ("preset" in edit ? client.revision : undefined)]); if (!result.rowCount) throw new ServiceError(409, "conflict", "Connection permissions changed. Reload permissions."); return { ok: true }; } @@ -1723,7 +1810,7 @@ export class ApiService { const byGrant = new Map(settings.rows.map(row => [row.subject, row])); return publicValue(z.array(authorizedClient), grants.map(grant => { const row = byGrant.get(grant.id), availableScopes = normalizeScopes(grant.scope); - return { grantId: grant.id, clientId: grant.clientId, clientName: row?.display_name ?? byId.get(grant.clientId)?.clientName ?? grant.clientId, + return { grantId: grant.id, clientId: grant.clientId, clientName: row?.display_name ?? byId.get(grant.clientId)?.clientName ?? grant.clientId, appName: byId.get(grant.clientId)?.clientName ?? grant.clientId, availableScopes: availableScopes.filter(scope => !scope.startsWith("integration:")), scopes: availableScopes.filter(scope => !row?.disabled_scopes.includes(scope)), revision: row?.permissions_revision ?? 0, integrationOverrides: row?.integration_overrides ?? {}, authorizationDate: new Date(grant.createdAt * 1000).toISOString(), expiresAt: grant.expiresAt ? new Date(grant.expiresAt * 1000).toISOString() : null, lastUsedAt: null }; diff --git a/packages/api/src/oidc-provider.ts b/packages/api/src/oidc-provider.ts new file mode 100644 index 00000000..7fe82eee --- /dev/null +++ b/packages/api/src/oidc-provider.ts @@ -0,0 +1,275 @@ +import { Buffer } from "node:buffer"; +import { randomBytes, timingSafeEqual } from "node:crypto"; +import { z } from "zod"; +import { ACCESS_SCOPES, accessTokenDigest } from "./access-tokens"; +import { oidcJwks, oidcSigner } from "./oidc-signing"; +import { databaseFor, type DatabaseClient } from "./postgres/database"; +import type { Session } from "./session"; +import type { Env, OAuthProps } from "./types"; + +const path = "/oauth/apps"; +const scopesSupported = ["openid", "email", "offline_access", ...ACCESS_SCOPES]; +const secretPattern = /^[A-Za-z0-9_-]{43}$/; +const verifierPattern = /^[A-Za-z0-9._~-]{43,128}$/; +const browserPage = "/app-consent"; +const uuid = z.uuid(); +const random = () => randomBytes(32).toString("base64url"); + +type App = { + id: string; + name: string; + tenant_id: string; + is_public: boolean; + enabled: boolean; + redirect_uris: string[]; + secret_digest: string | null; + secret_version: number; +}; +type Consent = { + id: string; + app_id: string; + redirect_uri: string; + challenge: string; + state: string | null; + nonce: string | null; + scopes: string[]; +}; +type Credential = { + connection_id: string; + tenant_id: string; + user_id: string; + session_version: number; + scopes: string[]; + email: string; +}; +type Code = Credential & { challenge: string; redirect_uri: string; nonce: string | null }; +type Refresh = Credential & { access_digest: string; refresh_expires_at: Date }; + +export const oidcConsentInput = z.object({ requestId: uuid, decision: z.enum(["allow", "deny"]) }).strict(); +export const oidcConsentPreview = z.object({ appName: z.string(), scopes: z.array(z.string()) }); +const activeMembership = "m.role='owner' AND m.session_version=c.session_version AND u.email_verified"; +const joinedMembership = "JOIN app.members m ON m.tenant_id=c.tenant_id AND m.user_id=c.user_id JOIN app.auth_users u ON u.id=c.user_id"; +const identityColumns = "c.id AS connection_id,c.tenant_id,c.user_id,c.session_version,m.email"; +const credentialsActive = `c.revoked_at IS NULL AND a.enabled AND (a.is_public OR a.tenant_id=c.tenant_id) AND ${activeMembership}`; +const issuerOf = (env: Env) => env.APP_ORIGIN + path; +const noStore = { "Cache-Control": "no-store", Pragma: "no-cache", "X-Content-Type-Options": "nosniff" }; +function json(value: unknown, status = 200, headers?: Record) { + return Response.json(value, { status, headers: { ...noStore, ...headers } }); +} +function error(code: string, status = 400) { + return json({ error: code }, status, status === 401 ? { "WWW-Authenticate": code === "invalid_client" ? 'Basic realm="Factorize Apps"' : 'Bearer error="invalid_token"' } : undefined); +} +function redirect(uri: string, params: Record) { + const target = new URL(uri); + for (const [key, value] of Object.entries(params)) if (value !== null) target.searchParams.set(key, value); + return target.href; +} +function go(uri: string) { return new Response(null, { status: 302, headers: { ...noStore, Location: uri, "Referrer-Policy": "no-referrer" } }); } +function scopesOf(value: string | null) { + return [...new Set((value ?? "openid").split(/ +/).filter(Boolean))]; +} +function visible(app: App, tenantId: string) { return app.enabled && !!app.secret_digest && (app.is_public || app.tenant_id === tenantId); } +async function findApp(db: Pick, id: string, lock = false) { + return (await db.query(`SELECT id,name,tenant_id,is_public,enabled,redirect_uris,secret_digest,secret_version + FROM app.oauth_apps WHERE id=$1${lock ? " FOR UPDATE" : ""}`, [id])).rows[0]; +} + +async function authorize(request: Request, env: Env) { + const url = new URL(request.url); + if (request.method !== "GET" || url.search.length > 8192) return error("invalid_request"); + const q = url.searchParams; + if (Array.from(q.keys()).some(key => q.getAll(key).length > 1)) return error("invalid_request"); + const id = q.get("client_id"), uri = q.get("redirect_uri"); + if (!uuid.safeParse(id).success || !uri) return error("invalid_request"); + const db = databaseFor(env); + const app = await findApp(db.pool, id!); + if (!app?.enabled || !app.secret_digest || !app.redirect_uris.includes(uri)) return error("invalid_request"); + const state = q.get("state"), nonce = q.get("nonce"), challenge = q.get("code_challenge"); + const reject = (cause: string) => go(redirect(uri, { error: cause, state })); + if (q.get("response_type") !== "code") return reject("unsupported_response_type"); + if (state && state.length > 1024 || nonce && nonce.length > 1024 || !challenge || !secretPattern.test(challenge) || q.get("code_challenge_method") !== "S256") return reject("invalid_request"); + if (q.has("request") || q.has("request_uri") || q.has("max_age") || (q.has("response_mode") && q.get("response_mode") !== "query")) return reject("invalid_request"); + if (q.get("prompt") === "none") return reject("interaction_required"); + if (q.has("prompt") && q.get("prompt") !== "consent") return reject("invalid_request"); + const scopes = scopesOf(q.get("scope")); + if (!scopes.includes("openid") || scopes.some(scope => !scopesSupported.includes(scope))) return reject("invalid_scope"); + + await db.pool.query("DELETE FROM app.oidc_requests WHERE id IN (SELECT id FROM app.oidc_requests WHERE expires_at(`INSERT INTO app.oidc_requests(app_id,redirect_uri,challenge,state,nonce,scopes,expires_at) + VALUES($1,$2,$3,$4,$5,$6,now()+interval '10 minutes') RETURNING id`, [app.id, uri, challenge, state, nonce, scopes]); + const page = new URL(browserPage, env.APP_ORIGIN); + page.searchParams.set("request", row.id); + return go(page.href); +} + +export async function inspectOidcConsent(env: Env, session: Pick, requestId: string) { + const db = databaseFor(env); + const { rows: [pending] } = await db.pool.query("SELECT * FROM app.oidc_requests WHERE id=$1 AND decided_at IS NULL AND expires_at>now()", [requestId]); + if (!pending) return null; + const app = await findApp(db.pool, pending.app_id); + if (!app || !visible(app, session.tenantId) || !app.redirect_uris.includes(pending.redirect_uri)) return null; + return { appName: app.name, scopes: pending.scopes }; +} + +export async function decideOidcConsent(env: Env, session: Pick, input: z.infer) { + return databaseFor(env).transaction(async tx => { + const { rows: [pending] } = await tx.query("SELECT * FROM app.oidc_requests WHERE id=$1 AND decided_at IS NULL AND expires_at>now() FOR UPDATE", [input.requestId]); + if (!pending) return null; + const app = await findApp(tx, pending.app_id, true); + if (!app || !visible(app, session.tenantId) || !app.redirect_uris.includes(pending.redirect_uri)) return null; + await tx.query("UPDATE app.oidc_requests SET decided_at=now() WHERE id=$1", [input.requestId]); + if (input.decision === "deny") return redirect(pending.redirect_uri, { error: "access_denied", state: pending.state }); + const { rows: [connection] } = await tx.query<{ id: string }>(`INSERT INTO app.oauth_app_connections(app_id,tenant_id,user_id,session_version,scopes) + VALUES($1,$2,$3,$4,$5) RETURNING id`, [app.id, session.tenantId, session.userId, session.sessionVersion, pending.scopes]); + const code = random(); + await tx.query(`INSERT INTO app.oidc_codes(digest,connection_id,secret_version,redirect_uri,challenge,nonce,expires_at) + VALUES($1,$2,$3,$4,$5,$6,now()+interval '5 minutes')`, [await accessTokenDigest(code), connection.id, app.secret_version, + pending.redirect_uri, pending.challenge, pending.nonce]); + return redirect(pending.redirect_uri, { code, state: pending.state }); + }); +} + +function clientCredentials(request: Request, form: URLSearchParams) { + const auth = request.headers.get("Authorization"); + if (!auth) return { id: form.get("client_id"), secret: form.get("client_secret") }; + if (!/^Basic /i.test(auth) || auth.length > 1024 || form.has("client_secret") || form.has("client_id")) return {}; + try { + const decoded = Buffer.from(auth.slice(6), "base64").toString(); + const boundary = decoded.indexOf(":"); + if (boundary === -1) return {}; + const unescape = (part: string) => decodeURIComponent(part.replaceAll("+", " ")); + return { id: unescape(decoded.slice(0, boundary)), secret: unescape(decoded.slice(boundary + 1)) }; + } catch { + return {}; + } +} + +async function matchesSecret(digest: string | null, value: string) { + if (!digest || !secretPattern.test(value)) return false; + const supplied = Buffer.from(await accessTokenDigest(value)); + const expected = Buffer.from(digest); + return supplied.length === expected.length && timingSafeEqual(supplied, expected); +} + +function claims(credential: Credential) { + return credential.scopes.includes("email") + ? { sub: credential.user_id, email: credential.email, email_verified: true } + : { sub: credential.user_id }; +} + +async function mint(tx: DatabaseClient, app: App, credential: Credential, scopes: string[], refreshUntil?: Date) { + const access = "fza_" + random(); + const refresh = scopes.includes("offline_access") ? "fzr_" + random() : null; + const refreshExpiry = refresh ? refreshUntil ?? new Date(Date.now() + 30 * 86_400_000) : null; + await tx.query(`INSERT INTO app.oidc_tokens(access_digest,refresh_digest,connection_id,secret_version,scopes,access_expires_at,refresh_expires_at) + VALUES($1,$2,$3,$4,$5,now()+interval '1 hour',$6)`, + [await accessTokenDigest(access), refresh ? await accessTokenDigest(refresh) : null, credential.connection_id, app.secret_version, scopes, refreshExpiry]); + return { access_token: access, token_type: "Bearer", expires_in: 3600, scope: scopes.join(" "), ...(refresh ? { refresh_token: refresh } : {}) }; +} + +async function readForm(request: Request) { + if (!/^application\/x-www-form-urlencoded(?:;|$)/i.test(request.headers.get("Content-Type") ?? "")) return null; + const reader = request.body?.getReader(); + if (!reader) return null; + const decoder = new TextDecoder(); + let length = 0, body = ""; + for (;;) { + const part = await reader.read(); + if (part.done) break; + length += part.value.length; + if (length > 8192) { await reader.cancel(); return null; } + body += decoder.decode(part.value, { stream: true }); + } + const form = new URLSearchParams(body + decoder.decode()); + return Array.from(form.keys()).some(key => form.getAll(key).length > 1) ? null : form; +} + +async function token(request: Request, env: Env) { + if (request.method !== "POST") return error("invalid_request", 405); + const form = await readForm(request); + if (!form) return error("invalid_request"); + const { id, secret } = clientCredentials(request, form); + if (!uuid.safeParse(id).success || !secret) return error("invalid_client", 401); + const method = form.get("grant_type"); + if (method !== "authorization_code" && method !== "refresh_token") return error("unsupported_grant_type"); + const db = databaseFor(env); + const app = await findApp(db.pool, id!); + if (!app?.enabled || !await matchesSecret(app.secret_digest, secret)) return error("invalid_client", 401); + const sign = method === "authorization_code" ? await oidcSigner(env) : null; + + await db.pool.query("DELETE FROM app.oidc_codes WHERE digest IN (SELECT digest FROM app.oidc_codes WHERE expires_at { + const current = await findApp(tx, app.id, true); + if (!current?.enabled || current.secret_version !== app.secret_version) return error("invalid_client", 401); + if (method === "authorization_code") { + const code = form.get("code"), verifier = form.get("code_verifier"); + if (!code || !secretPattern.test(code) || !verifier || !verifierPattern.test(verifier)) return error("invalid_grant"); + const digest = await accessTokenDigest(code); + const { rows: [grant] } = await tx.query(`SELECT ${identityColumns},c.scopes,g.challenge,g.redirect_uri,g.nonce + FROM app.oidc_codes g JOIN app.oauth_app_connections c ON c.id=g.connection_id JOIN app.oauth_apps a ON a.id=c.app_id ${joinedMembership} + WHERE g.digest=$1 AND c.app_id=$2 AND g.secret_version=$3 AND g.expires_at>now() AND ${credentialsActive} + FOR UPDATE OF g,c`, [digest, app.id, app.secret_version]); + if (!grant || grant.redirect_uri !== form.get("redirect_uri") || !current.redirect_uris.includes(grant.redirect_uri) + || grant.challenge !== await accessTokenDigest(verifier)) return error("invalid_grant"); + const now = Math.floor(Date.now() / 1000); + const idToken = await sign!({ ...claims(grant), iss: issuerOf(env), aud: app.id, iat: now, exp: now + 300, ...(grant.nonce ? { nonce: grant.nonce } : {}) }); + await tx.query("DELETE FROM app.oidc_codes WHERE digest=$1", [digest]); + return json({ ...await mint(tx, current, grant, grant.scopes), id_token: idToken }); + } + const refresh = form.get("refresh_token"); + if (!refresh || !/^fzr_[A-Za-z0-9_-]{43}$/.test(refresh)) return error("invalid_grant"); + const { rows: [grant] } = await tx.query(`SELECT ${identityColumns},t.scopes,t.access_digest,t.refresh_expires_at + FROM app.oidc_tokens t JOIN app.oauth_app_connections c ON c.id=t.connection_id JOIN app.oauth_apps a ON a.id=c.app_id ${joinedMembership} + WHERE t.refresh_digest=$1 AND c.app_id=$2 AND t.secret_version=$3 AND t.refresh_expires_at>now() AND ${credentialsActive} + FOR UPDATE OF t,c`, [await accessTokenDigest(refresh), app.id, app.secret_version]); + if (!grant) return error("invalid_grant"); + const requested = form.has("scope") ? scopesOf(form.get("scope")) : grant.scopes; + if (!requested.length || requested.some(scope => !grant.scopes.includes(scope))) return error("invalid_scope"); + await tx.query("UPDATE app.oidc_tokens SET refresh_digest=NULL,refresh_expires_at=NULL WHERE access_digest=$1", [grant.access_digest]); + return json(await mint(tx, current, grant, requested, grant.refresh_expires_at)); + }); +} + +async function access(request: Request, env: Env) { + const credential = request.headers.get("Authorization")?.match(/^Bearer (fza_[A-Za-z0-9_-]{43})$/i)?.[1]; + if (!credential) return null; + const { rows: [row] } = await databaseFor(env).pool.query(`SELECT ${identityColumns},t.scopes + FROM app.oidc_tokens t JOIN app.oauth_app_connections c ON c.id=t.connection_id JOIN app.oauth_apps a ON a.id=c.app_id ${joinedMembership} + WHERE t.access_digest=$1 AND t.access_expires_at>now() AND t.secret_version=a.secret_version AND ${credentialsActive}`, + [await accessTokenDigest(credential)]); + return row ?? null; +} + +export async function oidcApiAuth(request: Request, env: Env): Promise { + const row = await access(request, env); + if (!row) return null; + return { userId: row.user_id, tenantId: row.tenant_id, sessionVersion: row.session_version, + authMethod: "access_token", scopes: row.scopes.filter(scope => (ACCESS_SCOPES as readonly string[]).includes(scope)) }; +} + +export async function oidcRequest(request: Request, env: Env): Promise { + const target = new URL(request.url).pathname; + if (!target.startsWith(path + "/")) return null; + const issuer = issuerOf(env); + switch (target.slice(path.length)) { + case "/authorize": return authorize(request, env); + case "/token": return token(request, env); + case "/userinfo": { + if (request.method !== "GET" && request.method !== "POST") return error("invalid_request", 405); + const row = await access(request, env); + return row?.scopes.includes("openid") ? json(claims(row)) : error("invalid_token", 401); + } + case "/jwks": return request.method === "GET" ? json(await oidcJwks(env)) : error("invalid_request", 405); + case "/.well-known/openid-configuration": return request.method === "GET" ? json({ + issuer, authorization_endpoint: issuer + "/authorize", token_endpoint: issuer + "/token", userinfo_endpoint: issuer + "/userinfo", + jwks_uri: issuer + "/jwks", response_types_supported: ["code"], grant_types_supported: ["authorization_code", "refresh_token"], + response_modes_supported: ["query"], subject_types_supported: ["public"], id_token_signing_alg_values_supported: ["RS256"], + code_challenge_methods_supported: ["S256"], token_endpoint_auth_methods_supported: ["client_secret_basic", "client_secret_post"], + scopes_supported: scopesSupported, claims_supported: ["iss", "sub", "aud", "iat", "exp", "nonce", "email", "email_verified"], + }) : error("invalid_request", 405); + default: return error("invalid_request", 404); + } +} diff --git a/packages/api/src/oidc-signing.ts b/packages/api/src/oidc-signing.ts new file mode 100644 index 00000000..4f648dd7 --- /dev/null +++ b/packages/api/src/oidc-signing.ts @@ -0,0 +1,39 @@ +import { Buffer } from "node:buffer"; +import { decrypt, encrypt } from "./crypto"; +import { databaseFor } from "./postgres/database"; +import type { Env } from "./types"; + +const algorithm = { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }; +type Key = { kid: string; public_key: JsonWebKey; encrypted_private_key: string }; +const select = "SELECT kid,public_key,encrypted_private_key FROM app.oidc_signing_key WHERE singleton"; + +async function signingKey(env: Env): Promise { + const db = databaseFor(env); + const existing = (await db.pool.query(select)).rows[0]; + if (existing) return existing; + const pair = await crypto.subtle.generateKey({ ...algorithm, modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]) }, true, ["sign", "verify"]); + const [publicKey, privateKey] = await Promise.all([ + crypto.subtle.exportKey("jwk", pair.publicKey), + crypto.subtle.exportKey("jwk", pair.privateKey), + ]); + const encrypted = await encrypt(JSON.stringify(privateKey), env.CREDENTIAL_ENCRYPTION_KEY); + await db.pool.query("INSERT INTO app.oidc_signing_key(public_key,encrypted_private_key) VALUES($1,$2) ON CONFLICT DO NOTHING", [publicKey, encrypted]); + return (await db.pool.query(select)).rows[0]!; +} + +export async function oidcJwks(env: Env) { + const key = await signingKey(env); + return { keys: [{ ...key.public_key, kid: key.kid, use: "sig", alg: "RS256" }] }; +} + +export async function oidcSigner(env: Env) { + const key = await signingKey(env); + const privateJwk = JSON.parse(await decrypt(key.encrypted_private_key, env.CREDENTIAL_ENCRYPTION_KEY)); + const secret = await crypto.subtle.importKey("jwk", privateJwk, algorithm, false, ["sign"]); + return async (claims: object) => { + const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString("base64url"); + const input = encode({ alg: "RS256", kid: key.kid, typ: "JWT" }) + "." + encode(claims); + const signature = await crypto.subtle.sign(algorithm, secret, new TextEncoder().encode(input)); + return input + "." + Buffer.from(signature).toString("base64url"); + }; +} diff --git a/packages/api/src/postgres/apps-repository.ts b/packages/api/src/postgres/apps-repository.ts new file mode 100644 index 00000000..1eb84d01 --- /dev/null +++ b/packages/api/src/postgres/apps-repository.ts @@ -0,0 +1,59 @@ +import type { z } from "zod"; +import { randomBytes } from "node:crypto"; +import { accessTokenDigest } from "../access-tokens"; +import type { appRegistrationInput, appRegistrationUpdate, registeredApp } from "../apps-contracts"; +import type { Database } from "./database"; + +const metadata = 'id,name,redirect_uris AS "redirectUris",is_public AS "public",enabled,secret_digest IS NOT NULL AS "secretConfigured"'; +type App = z.infer; + +export class AppsRepository { + constructor(private db: Database, private teamId: string) {} + + async list() { + return (await this.db.pool.query(`SELECT ${metadata} FROM app.oauth_apps + WHERE tenant_id=$1 ORDER BY lower(name),id`, [this.teamId])).rows; + } + + async find(id: string) { + return (await this.db.pool.query(`SELECT ${metadata} FROM app.oauth_apps WHERE tenant_id=$1 AND id=$2`, [this.teamId, id])).rows[0]; + } + + async create(input: z.infer) { + return (await this.db.pool.query(`INSERT INTO app.oauth_apps(tenant_id,name,redirect_uris,is_public) + VALUES($1,$2,$3,$4) RETURNING ${metadata}`, [this.teamId, input.name, input.redirectUris, input.public])).rows[0]; + } + + async update(id: string, input: z.infer) { + return this.db.transaction(async tx => { + const { rows: [app] } = await tx.query(`UPDATE app.oauth_apps SET name=$3,redirect_uris=$4,is_public=$5,enabled=$6 + WHERE tenant_id=$1 AND id=$2 RETURNING ${metadata}`, [this.teamId, id, input.name, input.redirectUris, input.public, input.enabled]); + if (!app) return undefined; + if (!app.enabled || !app.public) await tx.query(`UPDATE app.oauth_app_connections SET revoked_at=now() + WHERE app_id=$1 AND revoked_at IS NULL AND ($2 OR tenant_id<>$3)`, [id, !app.enabled, this.teamId]); + return app; + }); + } + + async rotateSecret(id: string) { + const clientSecret = randomBytes(32).toString("base64url"); + const result = await this.db.pool.query(`UPDATE app.oauth_apps SET secret_digest=$3, secret_version=secret_version+1 + WHERE tenant_id=$1 AND id=$2`, [this.teamId, id, await accessTokenDigest(clientSecret)]); + return result.rowCount ? { clientId: id, clientSecret } : undefined; + } + + async connected(userId: string) { + const { rows } = await this.db.pool.query<{id: string; appId: string; name: string; scopes: string[]; authorizedAt: Date}>(` + SELECT c.id,c.app_id AS "appId",a.name,c.scopes,c.authorized_at AS "authorizedAt" + FROM app.oauth_app_connections c JOIN app.oauth_apps a ON a.id=c.app_id + WHERE c.tenant_id=$1 AND c.user_id=$2 AND c.revoked_at IS NULL AND a.enabled + ORDER BY c.authorized_at DESC,c.id`, [this.teamId, userId]); + return rows.map(row => ({ ...row, authorizedAt: row.authorizedAt.toISOString() })); + } + + async revoke(userId: string, id: string) { + const result = await this.db.pool.query(`UPDATE app.oauth_app_connections SET revoked_at=coalesce(revoked_at,now()) + WHERE tenant_id=$1 AND user_id=$2 AND id=$3`, [this.teamId, userId, id]); + return Boolean(result.rowCount); + } +} diff --git a/packages/api/src/postgres/vm-attachment-repository.ts b/packages/api/src/postgres/vm-attachment-repository.ts new file mode 100644 index 00000000..34e7fc2b --- /dev/null +++ b/packages/api/src/postgres/vm-attachment-repository.ts @@ -0,0 +1,110 @@ +import type { AgentIntegration } from "../agent-api"; +import { connectionAccess } from "../agent-api"; +import type { Database } from "./database"; + +type AttachmentStatus = "active" | "expired" | "revoked" | "inactive" | "pending"; +type RunBinding = { + sourceId: string; + sourceName: string | null; + vmId: string; + provider: "exe.dev" | "fly.io"; + expiresAt: Date; + revokedAt: Date | null; + runnable: boolean; +}; +type ClientBinding = { + id: string; + sourceId: string; + label: string | null; + vmId: string; + app: string | null; + provider: AgentIntegration; + providerEpoch: number; + expiresAt: Date; + revokedAt: Date | null; + parentRevokedAt: Date | null; + enrolled: boolean; + currentMember: boolean; + parent_scopes: string[]; + disabled_scopes: string[]; + integration_overrides: Record; +}; + +function accessStatus(revoked: Date | null, expiry: Date, now: number, enrolled: boolean, eligible: boolean): AttachmentStatus { + if (revoked) return "revoked"; + if (expiry.getTime() <= now) return "expired"; + if (!enrolled) return "pending"; + return eligible ? "active" : "inactive"; +} + +export class VmAttachmentRepository { + constructor(private db: Database, private tenantId: string) {} + + async runs(runId?: string) { + const { rows } = await this.db.pool.query(` + SELECT b.run_id AS "sourceId", NULLIF(r.run_name, '') AS "sourceName", b.vm_id AS "vmId", b.provider, b.expires_at AS "expiresAt", + b.revoked_at AS "revokedAt", + coalesce(t.state IN ('starting','running','blocked') AND r.state IN ('starting','running','blocked') + AND EXISTS (SELECT 1 FROM app.run_authorizations a + JOIN app.members m ON m.tenant_id=a.tenant_id AND m.user_id=a.user_id + JOIN app.auth_users u ON u.id=m.user_id AND u.email_verified + WHERE a.tenant_id=b.tenant_id AND a.run_id=b.run_id AND m.role='owner' + AND m.session_version=a.session_version), false) AS runnable + FROM app.vendor_run_identity_bindings b + JOIN app.trigger_runs t ON t.tenant_id=b.tenant_id AND t.id=b.run_id + LEFT JOIN app.runs r ON r.tenant_id=b.tenant_id AND r.id=b.run_id + WHERE b.tenant_id=$1 AND ($2::uuid IS NULL OR b.run_id=$2) + AND ($2::uuid IS NOT NULL OR (b.revoked_at IS NULL AND b.expires_at>now() + AND t.state IN ('starting','running','blocked'))) + ORDER BY b.issued_at DESC, b.run_id, b.provider`, [this.tenantId, runId ?? null]); + const now = Date.now(); + return rows.map(row => ({ + id: `${row.sourceId}:${row.provider}`, + source: "run" as const, + sourceId: row.sourceId, + sourceName: row.sourceName, + vmId: row.vmId, + app: null, + provider: row.provider, + expiresAt: row.expiresAt.toISOString(), + revokedAt: row.revokedAt?.toISOString() ?? null, + status: accessStatus(row.revokedAt, row.expiresAt, now, true, row.runnable), + })); + } + + async clients(userId: string, grantId?: string) { + const { rows } = await this.db.pool.query(` + SELECT g.id, p.subject AS "sourceId", p.display_name AS label, g.vm AS "vmId", g.app, + to_jsonb(i) AS provider, g.provider_epoch AS "providerEpoch", g.expires_at AS "expiresAt", + g.revoked_at AS "revokedAt", p.revoked_at AS "parentRevokedAt", g.issuer IS NOT NULL AS enrolled, + EXISTS (SELECT 1 FROM app.members m JOIN app.auth_users u ON u.id=m.user_id AND u.email_verified + WHERE m.tenant_id=p.tenant_id AND m.user_id=p.user_id AND m.role='owner' + AND m.session_version=p.session_version) AS "currentMember", + g.parent_scopes, p.disabled_scopes, p.integration_overrides + FROM app.vm_grants g + JOIN app.agent_identities p ON p.tenant_id=g.tenant_id AND p.id=g.parent_id AND p.kind='oauth' + JOIN app.agent_integrations i ON i.tenant_id=g.tenant_id AND i.id=g.provider_id + WHERE g.tenant_id=$1 AND p.user_id=$2 AND ($3::text IS NULL OR p.subject=$3) + AND ($3::text IS NOT NULL OR (g.revoked_at IS NULL AND p.revoked_at IS NULL AND g.expires_at>now())) + ORDER BY g.expires_at DESC, g.id`, [this.tenantId, userId, grantId ?? null]); + const now = Date.now(); + return rows.map(row => { + const eligible = row.currentMember && row.provider.epoch === row.providerEpoch + && !row.disabled_scopes.includes("vm:grant") + && connectionAccess(row.provider, row.parent_scopes, row) === "granted"; + const revokedAt = row.revokedAt ?? row.parentRevokedAt; + return { + id: row.id, + source: "client" as const, + sourceId: row.sourceId, + sourceName: row.label, + vmId: row.vmId, + app: row.app, + provider: row.app ? "fly.io" as const : "exe.dev" as const, + expiresAt: row.expiresAt.toISOString(), + revokedAt: revokedAt?.toISOString() ?? null, + status: accessStatus(revokedAt, row.expiresAt, now, row.enrolled, eligible), + }; + }); + } +} diff --git a/packages/api/src/protected-api.ts b/packages/api/src/protected-api.ts index 2832c81e..6c9aaf2f 100644 --- a/packages/api/src/protected-api.ts +++ b/packages/api/src/protected-api.ts @@ -1,3 +1,4 @@ +import { appRegistrationInput, appRegistrationUpdate } from "./apps-contracts"; import { presetInput } from "./presets"; import { skillTriggerInput } from "./skill-trigger"; import { skillInput,skillUpdateInput } from "./skills"; @@ -202,6 +203,10 @@ function createMcpServer(service: ApiService, subscriptions = true): McpServer { tool("renew_vm_grant", "Explicitly renew an active VM proxy grant for one hour. Only the same OAuth authorization with continuing provider and selected integration access may renew. Expired or revoked grants require a new grant.", revokeVmInput, ({grantId}: any) => service.renewVmGrant(grantId)); tool("revoke_vm_grant", "Revoke proxy access for an externally managed VM.", revokeVmInput, ({grantId}: any) => service.revokeVmGrant(grantId)); tool("list_exe_connections", "List safe metadata for saved exe.dev connections. API tokens are never returned.", z.object({}), () => service.listExeConnections()); + tool("list_apps", "List the team's registered server-side apps. Requires apps:manage.", z.object({}), () => service.listApps()); + tool("get_app", "Read a registered app's non-secret metadata.", z.object({appId:z.uuid()}), ({appId}: any) => service.getApp(appId)); + tool("create_app", "Register a server-side app. Create client secrets separately in the browser.", appRegistrationInput, input => service.createApp(input)); + tool("update_app", "Update redirect URLs, visibility, or enabled state for a registered app.", appRegistrationUpdate.extend({appId:z.uuid()}), ({appId,...input}: any) => service.updateApp(appId,input)); tool("get_runtime_context", "Inspect the verified invocation identity without exposing credentials.", z.object({}), () => service.getRuntimeContext()); tool("list_github_installations", "List connected GitHub App installations, including the installation IDs needed by GitHub Trigger events. Credentials are never returned.", z.object({}), () => service.listGitHubInstallations()); tool("list_runs", "List authoritative trigger runs by trigger ID, state, an optional case-insensitive literal substring of fired context, and validated sort field/direction. Sorting is applied before cursor pagination with deterministic ID tie-breaking. Automatic webhook, schedule, and lifecycle signals coalesce, so query runs and the provider API for authoritative work. Context matches include only a bounded excerpt.", listRunsSchema, (input: any) => service.listRuns(queryOf(input))); diff --git a/packages/api/src/settings-contracts.ts b/packages/api/src/settings-contracts.ts index 62fde852..b9051464 100644 --- a/packages/api/src/settings-contracts.ts +++ b/packages/api/src/settings-contracts.ts @@ -11,7 +11,11 @@ export const clientPermissionsInput = z.object({ integrationOverrides: z.record(z.uuid(), z.union([z.string(), z.literal(false)])).describe("Integration ID to approved epoch-bound scope, or false to block."), expectedRevision: z.number().int().nonnegative().optional(), }).strict(); -export const authorizedClient = z.object({ availableScopes: z.array(z.enum(AGENT_SCOPES)), integrationOverrides: clientPermissionsInput.shape.integrationOverrides, revision: z.number().int(), grantId: z.string(), clientId: z.string(), clientName: z.string(), scopes: z.array(z.string()), authorizationDate: timestamp, expiresAt: timestamp.nullable(), lastUsedAt: timestamp.nullable() }); +export const clientPermissionsUpdate = z.union([ + clientPermissionsInput, + z.object({ preset: z.literal("team-default"), expectedRevision: z.number().int().nonnegative().optional() }).strict(), +]); +export const authorizedClient = z.object({ availableScopes: z.array(z.enum(AGENT_SCOPES)), integrationOverrides: clientPermissionsInput.shape.integrationOverrides, revision: z.number().int(), grantId: z.string(), clientId: z.string(), clientName: z.string(), appName: z.string().optional(), scopes: z.array(z.string()), authorizationDate: timestamp, expiresAt: timestamp.nullable(), lastUsedAt: timestamp.nullable() }); export const accessToken = z.object({ id: z.string(), name: z.string(), scopes: z.array(z.enum(ACCESS_SCOPES)), created_at: timestamp, expires_at: timestamp, last_used_at: timestamp.nullable().optional(), revoked_at: timestamp.nullable().optional() }); export const createdAccessToken = accessToken.extend({ token: z.string() }); export const okResult = z.object({ ok: z.boolean() }); diff --git a/packages/api/src/vm-attachment-contracts.ts b/packages/api/src/vm-attachment-contracts.ts new file mode 100644 index 00000000..c79fe4e7 --- /dev/null +++ b/packages/api/src/vm-attachment-contracts.ts @@ -0,0 +1,16 @@ +import { z } from "zod"; + +export const vmAttachment = z.object({ + id: z.string(), + source: z.enum(["run", "client"]), + sourceId: z.string(), + sourceName: z.string().nullable(), + vmId: z.string(), + app: z.string().nullable(), + provider: z.enum(["exe.dev", "fly.io"]), + expiresAt: z.iso.datetime(), + revokedAt: z.iso.datetime().nullable(), + status: z.enum(["active", "expired", "revoked", "inactive", "pending"]), +}); + +export const vmAttachments = z.array(vmAttachment); diff --git a/packages/api/src/worker.ts b/packages/api/src/worker.ts index 8d9036c8..154e7ca2 100644 --- a/packages/api/src/worker.ts +++ b/packages/api/src/worker.ts @@ -19,9 +19,10 @@ import { traceChunkUpload } from "./trace-chunk-upload"; import { databaseFor } from "./postgres/database"; import { IdentityRepository } from "./postgres/identity-repository"; import { runOutboundProxyFetch } from "./run-outbound-proxy"; +import { oidcApiAuth, oidcRequest } from "./oidc-provider"; import { xOAuthCallback } from "./x-oauth-callback"; -const scopes = [...ACCESS_SCOPES]; +const scopes = [...ACCESS_SCOPES, "apps:manage"]; // Keep accepting grants issued by the pre-resource-scope protocol. New // consent screens and metadata advertise only the canonical scopes above. const oauthScopes = [...AGENT_SCOPES]; @@ -94,6 +95,8 @@ const backend = { async fetch(request: Request, env: Env, ctx: ExecutionContext) if (new URL(request.url).hostname === "git.factorize.sh") return gitHttpsFetch(request, env, ctx); if (new URL(request.url).pathname.startsWith("/internal/run-proxy/")) return runOutboundProxyFetch(request, env); if (new URL(request.url).pathname === "/oauth/x/callback") return request.method === "GET" ? xOAuthCallback(request, env) : new Response("Method not allowed", { status: 405, headers: { Allow: "GET" } }); + const oidc = await oidcRequest(request, env); + if (oidc) return oidc; const staticResponse = !["/authorize", "/device"].includes(new URL(request.url).pathname) ? await staticApp(request, env) : null; if (staticResponse) return staticResponse; const oauth = provider(env); @@ -118,6 +121,11 @@ const backend = { async fetch(request: Request, env: Env, ctx: ExecutionContext) if (!auth) return Response.json({ error: { code: "invalid_token", message: "The vendor identity is invalid or the run is no longer authorized." } }, { status: 401, headers: { "WWW-Authenticate": 'Bearer error="invalid_token"' } }); return protectedApiFetch(request, apiEnv, auth, ctx); } + if (url.pathname.startsWith("/api/v1/") && /^Bearer fza_/i.test(request.headers.get("Authorization") ?? "")) { + const auth = await oidcApiAuth(request, env); + if (!auth) return Response.json({ error: { code: "invalid_token" } }, {status: 401, headers: { "WWW-Authenticate": 'Bearer error="invalid_token"', "Cache-Control": "no-store" } }); + return protectedApiFetch(request, apiEnv, auth, ctx); + } const proxyEndpoint = request.method === "POST" && ["/api/v1/agent/requests","/api/v1/agent/responses/read"].includes(url.pathname); if (request.headers.has(VM_GRANT_HEADER)) { if (!proxyEndpoint) return Response.json({error:{code:"forbidden"}},{status:403}); diff --git a/packages/api/test/apps.postgres.test.ts b/packages/api/test/apps.postgres.test.ts new file mode 100644 index 00000000..6bade7cc --- /dev/null +++ b/packages/api/test/apps.postgres.test.ts @@ -0,0 +1,47 @@ +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { loadingFixture } from "./helpers/loading-fixture"; +import { ApiService } from "../src/flow-service"; +import { accessTokenDigest } from "../src/access-tokens"; + +vi.mock("cloudflare:workers", () => ({ WorkerEntrypoint: class {}, DurableObject: class {} })); +vi.mock("@cloudflare/workers-oauth-provider", () => ({ OAuthProvider: class {}, AuthorizationError: class extends Error {}, getOAuthApi: vi.fn() })); + +const url = process.env.AUTH_TEST_DATABASE_URL; +describe.skipIf(!url)("Registered apps", () => { + let f: Awaited>; + beforeAll(async () => { f = await loadingFixture(url!); }); + afterAll(async () => { await f?.cleanup(); }); + + it("permits scoped OAuth management and isolates registrations and browser-issued secrets", async () => { + const input = { name: "Server app", redirectUris: ["https://server.example/callback"] }; + const oauth = new ApiService(f.env, { ...f.auth, authMethod: "oauth", scopes: ["apps:manage"] }); + const unscoped = new ApiService(f.env, { ...f.auth, authMethod: "oauth", scopes: ["team:write"] }); + const browser = new ApiService(f.env, { ...f.auth, scopes: ["apps:manage", "team:read", "team:write"] }); + await expect(unscoped.createApp(input)).rejects.toMatchObject({ status: 403 }); + const app = await oauth.createApp(input); + expect(app).toMatchObject({ enabled: true, public: false, secretConfigured: false }); + expect(await oauth.getApp(app.id)).toEqual(app); + await expect(oauth.rotateAppSecret(app.id)).rejects.toMatchObject({ status: 403 }); + const first = await browser.rotateAppSecret(app.id); + const second = await browser.rotateAppSecret(app.id); + expect(first.clientSecret).not.toBe(second.clientSecret); + const stored = await f.db.pool.query("SELECT secret_digest FROM app.oauth_apps WHERE id=$1", [app.id]); + expect(stored.rows[0].secret_digest).toBe(await accessTokenDigest(second.clientSecret)); + expect(await oauth.getApp(app.id)).toMatchObject({ secretConfigured: true }); + expect(await oauth.getApp(app.id)).not.toHaveProperty("clientSecret"); + const response = await f.request("/api/v1/apps/" + app.id); + expect(response.status).toBe(200); + expect(await response.json()).toMatchObject({ id: app.id, secretConfigured: true }); + const owner = await f.db.pool.query("SELECT email FROM app.members WHERE tenant_id=$1 AND user_id=$2", [f.tenantId, f.userId]); + await f.db.pool.query("INSERT INTO app.members(tenant_id,user_id,email,role,session_version) VALUES($1,$2,$3,'owner',$4)", + [f.otherTenant, f.userId, owner.rows[0].email, f.auth.sessionVersion]); + const other = new ApiService(f.env, { ...f.auth, tenantId: f.otherTenant, authMethod: "oauth", scopes: ["apps:manage"] }); + await expect(other.getApp(app.id)).rejects.toMatchObject({ status: 404 }); + + await f.db.pool.query(`INSERT INTO app.oauth_app_connections(app_id,tenant_id,user_id,session_version,scopes) + VALUES($1,$2,$3,$4,ARRAY['openid'])`, [app.id, f.tenantId, f.userId, f.auth.sessionVersion]); + expect(await browser.listConnectedApps()).toMatchObject([{ appId: app.id, name: app.name, scopes: ["openid"] }]); + await oauth.updateApp(app.id, { ...input, public: true, enabled: false }); + expect(await browser.listConnectedApps()).toEqual([]); + }); +}); diff --git a/packages/api/test/oidc.postgres.test.ts b/packages/api/test/oidc.postgres.test.ts new file mode 100644 index 00000000..ec2da4cf --- /dev/null +++ b/packages/api/test/oidc.postgres.test.ts @@ -0,0 +1,156 @@ +import { createServer } from "node:http"; +import { Buffer } from "node:buffer"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { loadingFixture } from "./helpers/loading-fixture"; +import { accessTokenDigest } from "../src/access-tokens"; +import { ApiService } from "../src/flow-service"; +import { signSession } from "../src/session"; +import worker from "../src/worker"; + +vi.mock("cloudflare:workers", () => ({ WorkerEntrypoint: class {}, DurableObject: class {} })); +vi.mock("@cloudflare/workers-oauth-provider", () => ({ OAuthProvider: class {}, AuthorizationError: class extends Error {}, getOAuthApi: vi.fn() })); + +const dbUrl = process.env.AUTH_TEST_DATABASE_URL; +describe.skipIf(!dbUrl)("Sign in with Factorize", () => { + let f: Awaited>; + let callback: ReturnType; + let redirectUri: string; + const context = { waitUntil() {} } as unknown as ExecutionContext; + const verifier = "z".repeat(64); + const request = (path: string, init?: RequestInit) => worker.fetch(new Request(f.env.APP_ORIGIN + path, init), f.env, context); + const token = (body: Record, clientId: string, secret: string) => request("/oauth/apps/token", { + method: "POST", headers: { Authorization: "Basic " + Buffer.from(clientId + ":" + secret).toString("base64") }, body: new URLSearchParams(body), + }); + const authorize = async (clientId: string, options: Record = {}) => { + const query = new URLSearchParams({ client_id: clientId, redirect_uri: redirectUri, response_type: "code", + code_challenge: await accessTokenDigest(verifier), code_challenge_method: "S256", nonce: "sample-nonce", state: "sample-state", ...options }); + return request("/oauth/apps/authorize?" + query); + }; + const decide = (requestId: string, cookie: string, decision = "allow") => request("/api/v1/app-consent/decision", { + method: "POST", headers: { Cookie: cookie, Origin: f.env.APP_ORIGIN, "Content-Type": "application/json" }, body: JSON.stringify({ requestId, decision }), + }); + const reqId = (response: Response) => new URL(response.headers.get("Location")!).searchParams.get("request")!; + const appApi = (tenantId = f.tenantId) => new ApiService(f.env, { ...f.auth, tenantId, scopes: ["apps:manage", "team:read", "team:write"] }); + async function register(isPublic = false) { + const app = await appApi().createApp({ name: "Sample server", redirectUris: [redirectUri], public: isPublic }); + const { clientSecret } = await appApi().rotateAppSecret(app.id); + return { id: app.id, secret: clientSecret }; + } + async function receiveCode(id: string, cookie = f.cookie, options?: Record) { + const started = await authorize(id, options); + expect(started.status).toBe(302); + const approval = await decide(reqId(started), cookie); + expect(approval.status).toBe(200); + const { redirectTo } = await approval.json() as { redirectTo: string }; + const arrived = await fetch(redirectTo); + const response = await arrived.json() as { code: string; state: string }; + expect(response.state).toBe("sample-state"); + return response.code; + } + const exchange = (id: string, secret: string, code: string, codeVerifier = verifier) => token({ grant_type: "authorization_code", code, code_verifier: codeVerifier, redirect_uri: redirectUri }, id, secret); + const refresh = (id: string, secret: string, value: string) => token({ grant_type: "refresh_token", refresh_token: value }, id, secret); + + beforeAll(async () => { + f = await loadingFixture(dbUrl!); + callback = createServer((incoming, outgoing) => { + const query = new URL(incoming.url!, redirectUri).searchParams; + outgoing.setHeader("Content-Type","application/json"); + outgoing.end(JSON.stringify({ code: query.get("code"), state: query.get("state") })); + }); + await new Promise(resolve => callback.listen(0, "127.0.0.1", resolve)); + const address = callback.address(); + if (!address || typeof address === "string") throw new Error("Callback server is unavailable"); + redirectUri = `http://127.0.0.1:${address.port}/callback`; + }); + afterAll(async () => { + if (callback) await new Promise(resolve => callback.close(() => resolve())); + await f?.cleanup(); + }); + + it("discovers and signs an identity-only login to a server app", async () => { + const { id, secret } = await register(); + const discovery = await request("/oauth/apps/.well-known/openid-configuration"); + expect(discovery.status).toBe(200); + const metadata = await discovery.json() as { issuer: string; jwks_uri: string }; + expect(metadata.issuer).toBe(f.env.APP_ORIGIN + "/oauth/apps"); + const code = await receiveCode(id); + const response = await exchange(id, secret, code); + expect(response.status).toBe(200); + const issued = await response.json() as { id_token: string; access_token: string; scope: string }; + expect(issued.scope).toBe("openid"); + const [header,payload,signature] = issued.id_token.split("."); + const { kid } = JSON.parse(Buffer.from(header,"base64url").toString()); + const claims = JSON.parse(Buffer.from(payload,"base64url").toString()); + expect(claims).toMatchObject({ iss: metadata.issuer, aud: id, nonce: "sample-nonce", sub: f.userId }); + expect(claims).not.toHaveProperty("email"); + expect(issued).not.toHaveProperty("refresh_token"); + const jwks = await request(new URL(metadata.jwks_uri).pathname); + const { keys } = await jwks.json() as { keys: Array }; + const key = await crypto.subtle.importKey("jwk", keys.find(item => item.kid === kid)!, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["verify"]); + expect(await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key, Buffer.from(signature,"base64url"), new TextEncoder().encode(header+"."+payload))).toBe(true); + expect((await request("/api/v1/runs", { headers: { Authorization: "Bearer " + issued.access_token } })).status).toBe(403); + expect(await (await request("/oauth/apps/userinfo", { headers: { Authorization: "Bearer " + issued.access_token } })).json()).toEqual({ sub: f.userId }); + expect((await exchange(id, secret, code)).status).toBe(400); + }); + + it("checks redirect, scope, client secret, and PKCE before issuing access and revokes it per connection", async () => { + const { id, secret } = await register(); + const wrongRedirect = await authorize(id, { redirect_uri: redirectUri + "?unexpected=1" }); + expect(wrongRedirect.status).toBe(400); + expect(wrongRedirect.headers.get("Location")).toBeNull(); + const unsupported = await authorize(id, { scope: "openid invalid:scope" }); + expect(new URL(unsupported.headers.get("Location")!).searchParams.get("error")).toBe("invalid_scope"); + + const started = await authorize(id); + const denied = await decide(reqId(started), f.cookie, "deny"); + const denial = await denied.json() as { redirectTo: string }; + expect(new URL(denial.redirectTo).searchParams.get("error")).toBe("access_denied"); + expect((await decide(reqId(started), f.cookie)).status).toBe(404); + + const code = await receiveCode(id, f.cookie, { scope: "openid email runs:read offline_access" }); + expect((await exchange(id, "a".repeat(43), code)).status).toBe(401); + expect((await exchange(id, secret, code, "b".repeat(64))).status).toBe(400); + const response = await exchange(id, secret, code); + expect(response.status).toBe(200); + const issued = await response.json() as { access_token: string; refresh_token: string }; + const apiHeaders = { Authorization: "Bearer " + issued.access_token }; + expect((await request("/api/v1/runs", { headers: apiHeaders })).status).toBe(200); + expect(await (await request("/oauth/apps/userinfo", { headers: apiHeaders })).json()).toMatchObject({ sub: f.userId, email_verified: true }); + const refreshed = await refresh(id, secret, issued.refresh_token); + expect(refreshed.status).toBe(200); + expect((await refresh(id, secret, issued.refresh_token)).status).toBe(400); + const next = await refreshed.json() as { refresh_token: string }; + const connection = (await appApi().listConnectedApps()).find(value => value.appId === id)!; + await appApi().revokeConnectedApp(connection.id); + expect((await request("/api/v1/runs", { headers: apiHeaders })).status).toBe(401); + expect((await refresh(id, secret, next.refresh_token)).status).toBe(400); + }); + + it("permits public sign-in across teams and invalidates credentials on rotation or disable", async () => { + const sessionVersion = f.auth.sessionVersion; + await f.db.pool.query("INSERT INTO app.members(tenant_id,user_id,email,role,session_version) VALUES($1,$2,'owner@example.test','owner',$3)", + [f.otherTenant, f.userId, sessionVersion]); + const cookie = "factorize_session=" + await signSession({ + tenantId:f.otherTenant,userId:f.userId,email:"owner@example.test",sessionVersion,exp:Math.floor(Date.now()/1000)+3600, + }, f.env.SESSION_SIGNING_SECRET); + const { id, secret } = await register(); + expect((await decide(reqId(await authorize(id)), cookie)).status).toBe(404); + await appApi().updateApp(id, { name:"Sample server", redirectUris:[redirectUri], public:true, enabled:true }); + const code = await receiveCode(id, cookie, {scope:"openid offline_access runs:read"}); + const response = await exchange(id, secret, code); + expect(response.status).toBe(200); + const issued = await response.json() as { access_token: string; refresh_token: string }; + const apiHeaders = { Authorization: "Bearer " + issued.access_token }; + const result = await request("/api/v1/runs", { headers:apiHeaders }); + expect(result.status).toBe(200); + expect((await result.json() as {items:unknown[]}).items).toEqual([]); + const rotated = await appApi().rotateAppSecret(id); + expect((await refresh(id, secret, issued.refresh_token)).status).toBe(401); + expect((await refresh(id, rotated.clientSecret, issued.refresh_token)).status).toBe(400); + expect((await request("/api/v1/runs", { headers:apiHeaders })).status).toBe(401); + const newCode = await receiveCode(id,cookie,{scope:"openid runs:read"}); + const newest = await (await exchange(id,rotated.clientSecret,newCode)).json() as {access_token:string}; + await appApi().updateApp(id,{name:"Sample server",redirectUris:[redirectUri],public:true,enabled:false}); + expect((await request("/api/v1/runs",{headers:{Authorization:"Bearer "+newest.access_token}})).status).toBe(401); + }); +}); diff --git a/packages/api/test/pages-smoke.e2e.test.ts b/packages/api/test/pages-smoke.e2e.test.ts index a1a77c10..aa752acc 100644 --- a/packages/api/test/pages-smoke.e2e.test.ts +++ b/packages/api/test/pages-smoke.e2e.test.ts @@ -78,7 +78,12 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("every page E2E smoke", () "integrations": { path: () => "/integrations", ready: heading("Available integrations") }, "API keys": { path: () => "/settings/api-keys", ready: heading("API keys") }, "create API key": { path: () => "/settings/api-keys/new", ready: label("Key name") }, - "authorized clients": { path: () => "/settings/authorized-clients", ready: heading("Authorized clients") }, + "legacy authorized clients": { path: () => "/settings/authorized-clients", destination: () => "/clients", ready: heading("Clients") }, + "clients": { path: () => "/clients", ready: page => page.getByText("No authorized clients.", { exact: true }).waitFor() }, + "VM inventory": { path: () => "/vms", ready: page => page.getByText("No VMs currently have Factorize proxy access.", { exact: true }).waitFor() }, + "run VMs": { path: () => run() + "/vms", ready: page => page.getByText("No VM attachments recorded.", { exact: true }).waitFor() }, + "connected apps": { path: () => "/apps", ready: page => page.getByText("No connected apps.", { exact: true }).waitFor() }, + "registered apps": { path: () => "/apps/registered", ready: page => page.getByText("No registered apps.", { exact: true }).waitFor() }, "password": { path: () => "/settings/password", ready: label("Current password") }, "skills": { path: () => "/skills", ready: page => page.getByRole("link", { name: "smoke-skill", exact: true }).waitFor() }, "skill": { path: () => `/skills/${skillId}`, ready: page => page.getByText("Smoke test instructions", { exact: true }).waitFor() }, diff --git a/packages/api/test/vm-attachments.postgres.test.ts b/packages/api/test/vm-attachments.postgres.test.ts new file mode 100644 index 00000000..76c7fb28 --- /dev/null +++ b/packages/api/test/vm-attachments.postgres.test.ts @@ -0,0 +1,91 @@ +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { loadingFixture } from "./helpers/loading-fixture"; +import { VmAttachmentRepository } from "../src/postgres/vm-attachment-repository"; + +vi.mock("cloudflare:workers", () => ({ WorkerEntrypoint: class {}, DurableObject: class {} })); +vi.mock("@cloudflare/workers-oauth-provider", () => ({ OAuthProvider: class {}, AuthorizationError: class extends Error {}, getOAuthApi: vi.fn() })); + +const url = process.env.AUTH_TEST_DATABASE_URL; +describe.skipIf(!url)("VM attachment inventory", () => { + let fixture: Awaited>; + beforeAll(async () => { fixture = await loadingFixture(url!); }); + afterAll(async () => { await fixture?.cleanup(); }); + + it("keeps run access history and scopes reads to the authorizing tenant", async () => { + const { db, tenantId, runId, userId } = fixture; + await db.pool.query("UPDATE app.trigger_runs SET state='running' WHERE tenant_id=$1 AND id=$2", [tenantId, runId]); + await db.pool.query("UPDATE app.runs SET state='running' WHERE tenant_id=$1 AND id=$2", [tenantId, runId]); + await db.pool.query(`INSERT INTO app.run_authorizations(tenant_id,run_id,user_id,session_version,scopes) + SELECT tenant_id,$2,user_id,session_version,'[]' FROM app.members WHERE tenant_id=$1 AND user_id=$3 + ON CONFLICT (tenant_id,run_id) DO NOTHING`, [tenantId, runId, userId]); + await db.pool.query(`INSERT INTO app.vendor_run_identity_bindings + (tenant_id,run_id,provider,vm_id,issuer,subject,audience,issued_at,expires_at) + VALUES ($1,$2,'exe.dev',$3,'https://issuer.example','subject','audience',now(),now()+interval '1 hour')`, [tenantId, runId, `fixture-${runId}`]); + + const inventory = new VmAttachmentRepository(db, tenantId); + expect(await inventory.runs()).toMatchObject([{ sourceId: runId, status: "active" }]); + const route = await fixture.request("/api/v1/vms"); + expect(route.status).toBe(200); + expect(await route.json()).toMatchObject([{ sourceId: runId, status: "active" }]); + expect((await fixture.request("/api/v1/vms", "invalid-session")).status).toBe(401); + expect(await new VmAttachmentRepository(db, crypto.randomUUID()).runs(runId)).toEqual([]); + + await db.pool.query("UPDATE app.vendor_run_identity_bindings SET revoked_at=now() WHERE tenant_id=$1 AND run_id=$2", [tenantId, runId]); + expect(await inventory.runs()).toEqual([]); + expect(await inventory.runs(runId)).toMatchObject([{ sourceId: runId, status: "revoked" }]); + }); + + it("isolates delegated grants by OAuth authorization and retains expiry", async () => { + const { db, tenantId, userId } = fixture; + const providerId = crypto.randomUUID(); + await db.pool.query(`INSERT INTO app.agent_integrations(tenant_id,id,kind,credential_id,name,available,policy) + VALUES ($1,$2,'exe','vm-inventory','VM inventory',true,'baseline')`, [tenantId, providerId]); + const creators = [ + { subject: "fixture-connection-one", offset: "1 hour" }, + { subject: "fixture-connection-two", offset: "-1 hour" }, + ]; + for (const { subject, offset } of creators) { + const { rows: [parent] } = await db.pool.query(`INSERT INTO app.agent_identities(tenant_id,kind,subject,user_id,session_version) + SELECT tenant_id,'oauth',$2,user_id,session_version FROM app.members WHERE tenant_id=$1 AND user_id=$3 + RETURNING id`, [tenantId, subject, userId]); + await db.pool.query(`INSERT INTO app.vm_grants(tenant_id,parent_id,provider_id,provider_epoch,vm,permissions,parent_scopes,request_key,issuer,expires_at) + SELECT tenant_id,$2,id,epoch,$3,'{}','["proxy:use","vm:grant"]','inventory','https://issuer.example',now()+$4::interval + FROM app.agent_integrations WHERE tenant_id=$1 AND id=$5`, [tenantId, parent.id, subject, offset, providerId]); + } + const inventory = new VmAttachmentRepository(db, tenantId); + expect(await inventory.clients(userId)).toMatchObject([{ sourceId: creators[0].subject, status: "active" }]); + expect(await inventory.clients(userId, creators[1].subject)).toMatchObject([{ sourceId: creators[1].subject, status: "expired" }]); + expect(await inventory.clients(crypto.randomUUID(), creators[0].subject)).toEqual([]); + }); + + it("applies the current team default without widening access and revokes independently", async () => { + const { env, auth, db, tenantId } = fixture; + const { ApiService } = await import("../src/flow-service"); + const { PresetRepository } = await import("../src/postgres/preset-repository"); + const service = new ApiService(env, auth); + await service.listPresets(); + const presets = new PresetRepository(db, tenantId); + const preset = await presets.save({ kind: "permission", slug: "client-fixture", name: "Client fixture", settings: { runScopes: ["runs:read", "skills:write"] } }); + await presets.makeDefault(preset.id); + const grants = ["fixture-connection-one", "fixture-connection-two"].map(id => ({ + id, clientId: "same-client", metadata: { tenantId }, + scope: ["runs:read", "runs:write", "proxy:use", "vm:grant"], createdAt: Math.floor(Date.now() / 1000), + })); + env.OAUTH_PROVIDER = { + lookupClient: async () => ({ clientName: "MCP fixture" }), + listUserGrants: async () => ({ items: grants }), + revokeGrant: async (id: string) => { grants.splice(grants.findIndex(grant => grant.id === id), 1); }, + } as unknown as typeof env.OAUTH_PROVIDER; + + expect((await service.listAuthorizedClients()).map(connection => connection.appName)).toEqual(["MCP fixture", "MCP fixture"]); + await service.updateClientPermissions(grants[0].id, { preset: "team-default", expectedRevision: 0 }); + const [first, second] = await service.listAuthorizedClients(); + expect(first.scopes).toEqual(["runs:read"]); + expect(second.scopes).toContain("vm:grant"); + expect((await service.listClientVms(first.grantId))[0].status).toBe("inactive"); + await service.revokeOAuthAuthorization(second.grantId); + expect((await service.listAuthorizedClients()).map(connection => connection.grantId)).toEqual([first.grantId]); + expect((await service.listClientVms(second.grantId))[0].status).toBe("revoked"); + await expect(service.revokeAuthorizedClient(first.clientId)).resolves.toEqual({ revoked: 1 }); + }); +}); diff --git a/packages/app/src/features/apps/consent.tsx b/packages/app/src/features/apps/consent.tsx new file mode 100644 index 00000000..d1aa1ebb --- /dev/null +++ b/packages/app/src/features/apps/consent.tsx @@ -0,0 +1,48 @@ +import { useMutation, useQuery } from "@tanstack/react-query"; +import { useSearch } from "@tanstack/react-router"; +import { api } from "factorize-api-client"; +import { Button, Card, Page } from "../../shared/ui"; +import { messageOf } from "../auth/session"; + +const scopeLabel = (scope: string) => ({ + openid: "Your Factorize identity", + email: "Your verified email address", + offline_access: "Access when you’re away", +} as Record)[scope] ?? scope; + +export function AppConsentPage() { + const { request: requestId } = useSearch({ from: "/app-consent" }); + const preview = useQuery({ + queryKey: ["app-consent", requestId], + enabled: Boolean(requestId), + retry: false, + queryFn: async ({ signal }) => { + const { error, data } = await api.GET("/api/v1/app-consent/{requestId}", { params: { path: { requestId: requestId! } }, signal }); + if (!data || error) throw new Error(messageOf(error)); + return data; + }, + }); + const decide = useMutation({ + retry: false, + mutationFn: async (decision: "allow" | "deny") => { + const { error, data } = await api.POST("/api/v1/app-consent/decision", { body: { requestId: requestId!, decision } }); + if (!data || error) throw new Error(messageOf(error)); + window.location.assign(data.redirectTo); + }, + }); + return +

Sign in with Factorize

+ {!requestId &&

This sign-in request is missing.

} + {requestId && preview.isPending &&

Loading sign-in request…

} + {preview.error &&

{preview.error.message}

} + {decide.error &&

{decide.error.message}

} + {preview.data && <> +

{preview.data.appName} is requesting access to:

+
    {preview.data.scopes.map(scope =>
  • {scopeLabel(scope)}
  • )}
+
+ + +
+ } +
; +} diff --git a/packages/app/src/features/apps/index.tsx b/packages/app/src/features/apps/index.tsx new file mode 100644 index 00000000..6aea0665 --- /dev/null +++ b/packages/app/src/features/apps/index.tsx @@ -0,0 +1,132 @@ +import { useState, type FormEvent } from "react"; +import { Link, useLocation } from "@tanstack/react-router"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { api, type paths } from "factorize-api-client"; +import { Button, Input, Label, Page } from "../../shared/ui"; +import { Dialog } from "../../shared/dialog"; +import { messageOf } from "../auth/session"; +import { tabClasses } from "../auth/team-navigation"; + +type AppRegistration = paths["/api/v1/apps"]["get"]["responses"][200]["content"]["application/json"][number]; +const registeredKey = ["apps", "registered"]; +const connectedKey = ["apps", "connected"]; + +function AppNavigation() { + const registered = useLocation().pathname === "/apps/registered"; + return ; +} + +export function ConnectedAppsPage() { + const cache = useQueryClient(); + const connected = useQuery({ + queryKey: connectedKey, queryFn: async ({ signal }) => { + const { error, data } = await api.GET("/api/v1/app-connections", { signal }); + if (error) throw new Error(messageOf(error)); + return data ?? []; + }, + }); + const revoke = useMutation({ + mutationFn: async (connectionId: string) => { + const { error } = await api.DELETE("/api/v1/app-connections/{connectionId}", { params: { path: { connectionId } } }); + if (error) throw new Error(messageOf(error)); + }, + onSuccess: () => cache.invalidateQueries({ queryKey: connectedKey }), + }); + return

Apps

+ {connected.isPending &&

Loading connected apps…

} + {connected.error &&

{connected.error.message}

} + {revoke.error &&

{revoke.error.message}

} + {connected.data?.length === 0 &&

No connected apps.

} +
    {connected.data?.map(app => +
  • +
    {app.name}

    {app.scopes.join(", ")}

    + +
  • + )}
+
; +} + +function RegistrationEditor({ app, close }: { app: AppRegistration | null; close: () => void }) { + const cache = useQueryClient(); + const [name, setName] = useState(app?.name ?? ""); + const [redirects, setRedirects] = useState(app?.redirectUris.join("\n") ?? ""); + const [isPublic, setIsPublic] = useState(app?.public ?? false); + const [enabled, setEnabled] = useState(app?.enabled ?? true); + const save = useMutation({ + mutationFn: async () => { + const body = { name, redirectUris: redirects.split("\n").map(value => value.trim()).filter(Boolean), public: isPublic }; + const { error } = app + ? await api.PUT("/api/v1/apps/{appId}", { params: { path: { appId: app.id } }, body: { ...body, enabled } }) + : await api.POST("/api/v1/apps", { body }); + if (error) throw new Error(messageOf(error)); + }, + onSuccess: async () => { + await Promise.all([cache.invalidateQueries({ queryKey: registeredKey }), cache.invalidateQueries({ queryKey: connectedKey })]); + close(); + }, + }); + function submit(event: FormEvent) { event.preventDefault(); save.mutate(); } + return +
+ +