foldrun 10.5.0 → 11.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/foldrun.mjs CHANGED
@@ -426,7 +426,7 @@ if (!command || command === "--help" || command === "-h") {
426
426
  // `--value` as the account's argument and stored an empty secret; `--force
427
427
  // ./dir` swallowed the directory. A flag followed by another flag is also
428
428
  // boolean, so an unlisted switch at least does not eat its neighbour.
429
- const BOOLEAN_FLAGS = new Set(["read-only", "account", "follow", "force", "oauth2", "wait", "watch", "print", "dry-run", "help", "no-browser", "local", "test", "flat", "yes", "platform", "json", "forever", "all", "check", "new-client", "quiet", "off", "can-ask", "preview", "csv", "failed", "starter", "history", "list", "library", "clear", "security", "changed", "write-baseline", "no-baseline", "rules", "calls", "tree", "tool-error", "stop", "last", "no-pkce", "export", "isolated", "no-wait", "dismissed", "unread", "team", "started", "mine", "none", "a2a", "public-card", "private-card", "return-immediately"]);
429
+ const BOOLEAN_FLAGS = new Set(["read-only", "account", "follow", "force", "oauth2", "wait", "watch", "print", "dry-run", "help", "no-browser", "local", "test", "flat", "yes", "platform", "json", "forever", "all", "check", "new-client", "quiet", "off", "can-ask", "preview", "csv", "failed", "starter", "history", "list", "library", "clear", "security", "changed", "write-baseline", "no-baseline", "rules", "calls", "tree", "tool-error", "stop", "last", "no-pkce", "generate-key", "device", "write", "dpop", "export", "isolated", "no-wait", "dismissed", "unread", "team", "started", "mine", "none", "a2a", "public-card", "private-card", "return-immediately"]);
430
430
  // Flags said more than once collect into a list: `--tag a --tag b`.
431
431
  const REPEATABLE = new Set(["tag", "expect", "header", "site", "add", "remove", "rule", "authorize-param", "example"]);
432
432
  // `--wait` is a switch everywhere but `flow add <flow> wait`, where it takes
package/docs/api.md CHANGED
@@ -339,7 +339,7 @@ its header and requires a URL it can GET for itself.
339
339
 
340
340
  | Route | Methods | |
341
341
  |---|---|---|
342
- | `/api/secrets?workspace=` | GET, PUT, PATCH, DELETE | the vault: list which secrets exist (never a value), each with the `sites` it is bound to; set one (`name` plus one shape, below, and optionally `sites`); bind one to sites with PATCH `{ name, sites }` — `sites` a list like `["api.example.com", "*.example.com"]`, `[]` unbinds, the value untouched, 404 for a secret that is not there, 400 for a site with a scheme, path or port and for a file, ssh or api secret ([bound to sites](secrets#bound-to-sites)); delete one (`name`). `workspace` names a workspace's own store; unsaid is the account's, which a key scoped to some workspaces may not touch. `name` is a string (400 otherwise). The account's `RESEND_API_KEY` and `EMAIL_FROM` — the sender of everyone's sign-in mail — are set, rebound and deleted by the owner alone (403 to anyone else), here and through an OAuth connect — the owner in person: their signed-in session or the key their own `foldrun login` minted, never another key they minted. An oauth2 recipe from a caller scoped to some workspaces links to the account's saved OAuth app with the same token URL and client id but never saves or changes one (as `POST /api/oauth/clients` refuses them). PATCH also takes `workspaces` (with or instead of `sites`): `{ name, workspaces: ["sales", "ops"] }` limits an **account** secret to those workspaces — every other one finds it not set, in runs, tool tests, `notify:` (its email too), the egress proxy and MCP, for runs that start after it ([limited to some workspaces](secrets#limited-to-some-workspaces)); `null` opens it to every workspace, `[]` to none; the answer carries `workspaces` (sorted, or `null`). `ifWorkspaces` — the list you loaded, `null` for every workspace — makes it conditional: 409 when the list changed since, nothing written. PUT takes the same `workspaces` and saves it with the value in one write (the answer carries it too); it is never ignored. Account store only (400 with `workspace`), an admin over every workspace (403 for a scoped caller), names of workspaces that exist, checked under the vault's lock (400 otherwise), 404 for a secret that is not there; audited as `secret.workspaces` (PATCH) and in `secret.set` (PUT). GET of the account store lists each limited secret's `workspaces`, and `?workspace=` leaves out an account secret that workspace may not use. PUT is idempotent; PATCH and a PUT with `sites` are audited as `secret.sites` / `secret.set` |
342
+ | `/api/secrets?workspace=` | GET, PUT, PATCH, DELETE | the vault: list which secrets exist (never a value), each with the `sites` it is bound to; set one (`name` plus one shape, below, and optionally `sites`); bind one to sites with PATCH `{ name, sites }` — `sites` a list like `["api.example.com", "*.example.com"]`, `[]` unbinds, the value untouched, 404 for a secret that is not there, 400 for a site with a scheme, path or port and for a file, ssh or api secret ([bound to sites](secrets#bound-to-sites)); delete one (`name`). `workspace` names a workspace's own store; unsaid is the account's, which a key scoped to some workspaces may not touch. `name` is a string (400 otherwise). The account's `RESEND_API_KEY` and `EMAIL_FROM` — the sender of everyone's sign-in mail — are set, rebound and deleted by the owner alone (403 to anyone else), here and through an OAuth connect — the owner in person: their signed-in session or the key their own `foldrun login` minted, never another key they minted. An oauth2 recipe from a caller scoped to some workspaces links to the account's saved OAuth app with the same token URL and client id but never saves or changes one (as `POST /api/oauth/clients` refuses them). PATCH also takes `workspaces` (with or instead of `sites`): `{ name, workspaces: ["sales", "ops"] }` limits an **account** secret to those workspaces — every other one finds it not set, in runs, tool tests, `notify:` (its email too), the egress proxy and MCP, for runs that start after it ([limited to some workspaces](secrets#limited-to-some-workspaces)); `null` opens it to every workspace, `[]` to none; the answer carries `workspaces` (sorted, or `null`). `ifWorkspaces` — the list you loaded, `null` for every workspace — makes it conditional: 409 when the list changed since, nothing written. PUT takes the same `workspaces` and saves it with the value in one write (the answer carries it too); it is never ignored. Account store only (400 with `workspace`), an admin over every workspace (403 for a scoped caller), names of workspaces that exist, checked under the vault's lock (400 otherwise), 404 for a secret that is not there; audited as `secret.workspaces` (PATCH) and in `secret.set` (PUT). GET of the account store lists each limited secret's `workspaces`, and `?workspace=` leaves out an account secret that workspace may not use. PUT is idempotent; PATCH and a PUT with `sites` are audited as `secret.sites` / `secret.set`. PUT also takes `token_exchange: { token_url, client_id, client_secret?, token_auth?, subject_secret, subject_token_type?, requested_token_type?, audience?, resource?, scope? }`: a secret whose value is another secret's token traded at a token endpoint (RFC 8693); its `kind` is `token-exchange`. Deleting an `oauth2` secret, or replacing one with a PUT, revokes the old grant at the provider (RFC 7009) when its recipe has a `revocation_url`. The secret is written or deleted first, then the old grant is revoked, and the answer carries `revoked: { skipped?, revoked: [refresh_token, access_token], error? }`. `skipped` is `no-revocation-url`, `shared-grant` (another secret holds the same refresh token, or a grant from the same app; providers such as Google revoke per app, so it is kept), `same-app` (the replacement is from the same app, so revoking would end it too) or `unreadable`. A refusal is reported in `error` and never undoes the write. The recipe's `token_auth` (`client_secret_post`, `client_secret_basic`, `none`, `private_key_jwt` with `client_assertion_key`) and `revocation_url` are kept with it. `oauth2.generate_key: true` with `private_key_jwt` makes the key, and the answer carries `public_jwk` |
343
343
 
344
344
  `PUT` takes `name` plus exactly one shape: `value` (a string), `file` (a PEM,
345
345
  a cert), `oauth2`, `service_account`, `ssh`, `api`, `client_cert` (`{ cert, key, passphrase?, export? }` — mutual TLS, presented by the egress proxy to the exact sites the secret is bound to), or `identity` (`{ audience }` — keyless cloud access). They go to the vault;
@@ -490,7 +490,10 @@ signed-in person, never by a key — mints an ordinary API key at their role.
490
490
 
491
491
  | Route | Methods | |
492
492
  |---|---|---|
493
- | `/api/oauth/clients` | GET, POST, DELETE | saved OAuth apps (`name`, `client`, `config`). `config`: `authorize_url`, `token_url`, `client_id`, `client_secret` (empty for a public app), `scopes`, optional `authorize_extra` (`{ name: value }` added to the authorize URL — the flow's own parameters are refused), `pkce` (false to turn it off), `issuer`, `token_auth` (`client_secret_post`, the default: the secret in the form body; `client_secret_basic`: HTTP Basic, which Notion, Spotify, Reddit and Zoom require; `none`: a public app) |
493
+ | `/api/oauth/clients` | GET, POST, DELETE | saved OAuth apps (`name`, `client`, `config`). `config`: `authorize_url`, `token_url`, `client_id`, `client_secret` (empty for a public app), `scopes`, optional `authorize_extra` (`{ name: value }` added to the authorize URL — the flow's own parameters are refused), `pkce` (false to turn it off), `issuer`, `iss_parameter` (with `issuer`: false lets a callback without `iss` through, as a server that does not advertise RFC 9207 sends none; one that comes back must still match), `revocation_url`, `device_url`, `par_url` (https; what discovery found), `token_auth` (`client_secret_post`, the default: the secret in the form body; `client_secret_basic`: HTTP Basic, which Notion, Spotify, Reddit and Zoom require; `none`: a public app; `private_key_jwt`: a JWT signed with `client_assertion_key`, a private key as PEM or JWK, with optional `client_assertion_kid`, `client_assertion_alg` and `client_assertion_cert`). `generate_key: true` with `private_key_jwt` and no key makes one (EC P-256), and the answer carries `public_jwk` for the provider. `token_auth: tls_client_auth` (or `self_signed_tls_client_auth`) takes `tls_client_cert`, `tls_client_key` and `tls_client_passphrase` (the key and passphrase are sealed). `dpop: true` makes every connection from the app DPoP-bound, each with its own key. The key is sealed and never listed; the list shows `public_jwk` |
494
+ | `/api/oauth/device` | POST | connect a saved app with a code (RFC 8628) instead of a redirect: `{ client, secret, workspace?, scopes? }` → `{ id, user_code, verification_uri, verification_uri_complete?, expires_in, interval }`. The app needs a `device_url`. The device code and the app's credentials are parked sealed for at most ten minutes, and PKCE is sent with the device grant. `secret` is checked as `PUT /api/secrets` checks a name. Audited as `oauth.device.started`. `secrets:write` |
495
+ | `/api/oauth/device/<id>` | POST | one poll: one token request to the provider. Answers `{ status: pending }`, `{ status: slow_down }` (add five seconds to the interval), `{ status: connected, name, workspace?, stored, revoked? }` (the grant is stored as a consent's would be, audited as `secret.set`), or `{ status: denied \| expired, reason }`. A finished code is used up; another account's id is refused. `secrets:write` |
496
+ | `/api/oauth/discover` | POST | read a provider's metadata from its issuer (RFC 8414, OpenID Connect Discovery) and answer the app config it gives — nothing is saved. `{ issuer, has_secret?, pkce?, token_auth? }` → `{ config: { issuer, authorize_url, token_url, revocation_url?, device_url?, par_url?, par_required?, iss_parameter, token_auth?, metadata_url, metadata } }`. Tried at `/.well-known/oauth-authorization-server{path}`, `/.well-known/openid-configuration{path}`, then `{path}/.well-known/openid-configuration`, through the SSRF guard. The document's `issuer` must equal the one asked for, every endpoint must be https, and a server that lists PKCE methods without `S256` is refused unless `pkce: false` (`422` with the reason). `token_auth` is picked from `token_endpoint_auth_methods_supported`: the form body when listed, else Basic (RFC 8414's default); none with no secret. `secrets:write` |
494
497
  | `/api/oauth/start` | POST | begin a connection (`client`, `secret`, `workspace`, optional `scopes`). `secret` is checked as `PUT /api/secrets` checks a name — the account's `RESEND_API_KEY`/`EMAIL_FROM` are the owner's alone (403), and so is accepting a hand-off for them. From a signed-in browser: `{ url }` is the provider's consent, bound to that browser by a cookie the callback checks, with PKCE. With an API key: `{ url, handoff: true }` is a dashboard page where a signed-in person accepts first (`foldrun connect --client` opens it). `scopes` (space-separated, as the provider spells them) is what this connection asks for instead of the client's default, and the connection keeps it for its reconnects — one saved app serves any number of connections at different scopes |
495
498
  | `/api/oauth/callback` | GET | where the provider returns — refuses a consent that comes back to another browser, and an `iss` that is not the app's issuer |
496
499
  | `/api/identity?workspace=` | GET | keyless cloud identity: `{ enabled, issuer, subject, tokenSeconds }` — the issuer a cloud must trust and the subject pattern each agent's tokens carry (`account:<a>:workspace:<w>:agent:<agent>`). Open (no key), outside `/api`: `/.well-known/openid-configuration` and `/.well-known/jwks.json`, 404 when the install does not issue tokens |
@@ -543,9 +546,11 @@ with `HTTP <status>: <the route's error>`.
543
546
  | Route | Methods | |
544
547
  |---|---|---|
545
548
  | `/api/mcp` | POST | one JSON-RPC message: `initialize` (revisions `2025-11-25`, `2025-06-18`, `2025-03-26`; an unknown one is answered with the newest), `ping`, `tools/list`, `tools/call`; a notification is `202` with no body. `?readonly=1` offers only the tools that read and refuses the rest (`-32602`). The tools: `whoami`, `list_workspaces`, `inbox`, `list_approvals`, `list_flows`, `list_runs`, `get_run`, `read_file`, `run_flow`, `decide_approval`, `answer_question`, `message_run`, `stop_run` — see [MCP](mcp#the-tools). `foldrun mcp` serves the same over stdio |
546
- | `/api/mcp/oauth/register` | POST | an AI app registers itself (RFC 7591), before anyone signs it in. Open, as the protocol needs — no key. `{ redirect_uris, client_name?, token_endpoint_auth_method?, grant_types?, response_types?, client_uri? }`: one to ten redirect URIs, each `https` or `http` to localhost, no fragment; `token_endpoint_auth_method` `none` (PKCE alone), `client_secret_post` or `client_secret_basic` (the default). Answers `201 { client_id, client_id_issued_at, client_name, redirect_uris, grant_types, response_types, token_endpoint_auth_method, client_secret?, client_secret_expires_at? }` — the secret only for the two secret methods, shown once. Errors are OAuth's `{ error, error_description }` (`invalid_redirect_uri`, `invalid_client_metadata`); `503` past 5,000 apps on the install |
549
+ | `/api/mcp/oauth/register` | POST | an AI app registers itself (RFC 7591), before anyone signs it in. Open, as the protocol needs — no key. `{ redirect_uris, client_name?, token_endpoint_auth_method?, grant_types?, response_types?, client_uri? }`: one to ten redirect URIs, each `https` or `http` to localhost, no fragment; `token_endpoint_auth_method` `none` (PKCE alone), `client_secret_post` or `client_secret_basic` (the default). Answers `201 { client_id, client_id_issued_at, client_name, redirect_uris, grant_types, response_types, token_endpoint_auth_method, client_secret?, client_secret_expires_at? }` — the secret only for the two secret methods, shown once. Errors are OAuth's `{ error, error_description }` (`invalid_redirect_uri`, `invalid_client_metadata`); `503` past 5,000 apps on the install An app may register `token_endpoint_auth_method: private_key_jwt` with `jwks` (`{ keys: [...] }`, public keys only) or an https `jwks_uri`; it gets no secret and signs a client assertion at the token and revocation endpoints (RFC 7523: `iss` = `sub` = its client id, `aud` the issuer or the endpoint, at most five minutes, each `jti` once).|
547
550
  | `/api/mcp/oauth/authorize` | GET, POST | the person's half of the sign-in, for the page at `/mcp/authorize` — a signed-in person only, never a key or a support view. GET `?request=<the app's query>` checks it and answers `{ client: { name, id, kind, uri }, redirectHost, loopback, scopes, account, person: { email, role }, workspaces, allWorkspaces }`; POST `{ request, decision: approve\|deny, access?: read\|write, workspaces?: [names] \| null }` answers `{ ok, redirect }` — the app's redirect URI with a one-time `code` (ten minutes), `state` and `iss`, or with `error=access_denied`. A request that names an unknown app or a redirect URI it did not register is `400` and never redirected; the rest of its faults (no PKCE `S256` challenge, a `resource` that is not this `/api/mcp`, an unknown scope) come back as `{ redirect }` with OAuth's error. `access: write` needs the app to have asked for `mcp:write`; `workspaces` must be ones the person may open (`403` otherwise) |
548
551
  | `/api/mcp/oauth/token` | POST | OAuth 2.1's token endpoint, form-encoded (JSON is read too), no key: `grant_type=authorization_code` with `code`, `redirect_uri`, `code_verifier` (PKCE S256) and `client_id` — or the app's secret, Basic or in the form —, or `grant_type=refresh_token` with `refresh_token`. `resource`, when sent, must be this `/api/mcp`. Answers `{ access_token, token_type: "Bearer", expires_in: 3600, refresh_token, scope }` with `Cache-Control: no-store`. A code is good once, right or wrong. A refresh token is rotated on use; one used twice revokes the whole connection. Errors: `400 invalid_grant` / `invalid_target` / `unsupported_grant_type`, `401 invalid_client` |
552
+ | `/api/mcp/oauth/revoke` | POST | RFC 7009's revocation endpoint, form-encoded (JSON is read too), no key: `token` (an `fmcp_at_` or `fmcp_rt_` this app holds), optional `token_type_hint` (`access_token`, `refresh_token`), and the app's `client_id` or its secret as at the token endpoint. Either token ends the connection, and every token it issued. `200` with an empty body, also for a token already unknown, expired or revoked (§2.2); `400 unauthorized_client` for another app's token, `401 invalid_client` for a wrong secret. Audited as `mcp.revoked`. Advertised as `revocation_endpoint` |
553
+ | `/api/mcp/clients` | POST | register a machine client for `/api/mcp` (client credentials): `{ name, role?, workspaces?, access?: read\|write, token_auth?: client_secret_basic\|client_secret_post\|private_key_jwt, jwks?, jwks_uri? }` → `201 { client_id, client_secret?, grant, token_endpoint, token_endpoint_auth_method }`. The secret is shown once. Role and workspaces are never above the caller's, and are capped by the registering admin's again at every use. `keys:manage`, and a person (a session, or a key minted by one). It gets access tokens at the token endpoint with `grant_type=client_credentials`, no refresh token. It is listed by `GET /api/mcp/connections` with `machine: true` and ended by `DELETE /api/mcp/connections/<id>`, after which it is `invalid_client`. Audited as `mcp.connected` |
549
554
  | `/api/mcp/connections` | GET | the AI apps connected over OAuth: `{ connections: [{ id, client, clientId, redirectHost, person, role, workspaces, access: read\|write, createdAt, lastUsedAt, revokedAt }], everyone }` — every one for `keys:manage` (`everyone: true`), else your own. `?all=1` adds the revoked |
550
555
  | `/api/mcp/connections/<id>` | DELETE | disconnect one: the grant is revoked and every token it issued stops at once. Your own, or anyone's with `keys:manage` (`403` otherwise); `404` when there is none or it is already revoked. Audited as `mcp.revoked` |
551
556
 
package/docs/cli.md CHANGED
@@ -97,6 +97,7 @@ claude.ai or Claude Code there, nor any MCP configuration on disk.
97
97
  | `foldrun inbox read\|unread\|dismiss\|restore <id>…` | mark items in your own view: `dismiss` sets one aside (it still waits where it lives), `restore` puts it back |
98
98
  | `foldrun mcp` | this account as an [MCP server](mcp) on stdin/stdout, for an AI app to start: `claude mcp add foldrun -- foldrun mcp`, `codex mcp add foldrun -- foldrun mcp`. Each line is one JSON-RPC message, forwarded to the platform's `POST /api/mcp` with this machine's sign-in (`--profile`, `--url`, `--token` as for any platform command); stdout carries nothing but protocol. `--read-only` offers only the tools that read. Typed into a terminal it prints how to connect and exits 2 |
99
99
  | `foldrun mcp connections` | the AI apps connected to the account over OAuth (claude.ai and the like): the app, where its answers go, whose approval, read only or read and act, which workspaces, connected and last used. Everyone's for an admin (`keys:manage`), else your own; `--all` adds the disconnected, `--json` the raw list |
100
+ | `foldrun mcp clients add <name>` | register a machine client that signs in to `/api/mcp` with client credentials (no person approves its tokens): `--role viewer\|editor\|admin`, `--workspaces a,b`, `--write` (else read only), `--token-auth basic\|post\|jwt` with `--jwks-file <path>` for jwt. Prints the client id and secret, the secret once. Listed and ended like any connection |
100
101
  | `foldrun mcp disconnect <id>` | end one connection: every token it holds stops at once. Your own, or anyone's as an admin. Asks first; `--yes` when there is no terminal |
101
102
  | `foldrun issues` | the account's [issues](runs#issues): what went wrong, grouped, open until someone resolves it — kind, desk and flow (or the platform cause and every desk it hit), how many times since when, the newest reason and what to do. `--to <workspace>` narrows it, `--all` adds resolved ones (`--status open\|acknowledged\|snoozed\|resolved\|all`), `--json` |
102
103
  | `foldrun issues show\|ack\|snooze\|resolve\|reopen <id>` | one issue: `show` adds its runs and history; `ack` says you have seen it, `snooze --for 30m\|4h\|1d\|1w` (or `--until <ISO>`, or `--times <n>`: until it happens n more times) hides it for a while, `resolve` closes it until it happens again, `reopen` undoes that. `--note "…"` is kept in its history |
@@ -107,9 +108,9 @@ claude.ai or Claude Code there, nor any MCP configuration on disk.
107
108
  | `foldrun stop <run-id>` | kill a run in flight: the queued job is dropped and the sandbox the current step is spending in is destroyed. It prints which step is running and what has been spent, then asks you to type the run id back unless `--yes`. Finished steps keep their results, and costs already incurred stay on the bill. A run that has already finished is said so, not stopped. With no run id and a filter — `--status running,queued`, `--since 2h`, `--until 1h` (started before then: a span ago, or a date), `--flow <name>` — it stops every run that matches (`POST …/runs/bulk`), in `--to <workspace>` or across the account: it lists what matches first, asks, and then stops exactly the runs it listed, so one that starts in between is not swept up. `--dry-run` lists and touches nothing. The route refuses more than 100 at once |
108
109
  | `foldrun answer <run-id> "…"` | answer the question an agent is asking mid-step (`tools: [ask]`). `--option <n>` picks one of the choices it offered; `--question <id>` one of several. The agent is waiting in its sandbox and carries on at once. `foldrun approvals` lists what is being asked |
109
110
  | `foldrun message <run-id> "…"` | say something to a running agent. It reaches the model after its next tool call, as context — it changes none of the step's tools. `--step <n>` picks one when a parallel group has several running. Platform only |
110
- | `foldrun secrets set NAME` | store a secret — also `ls`, `rm`, and `status` (OAuth grant health). `--site <domain>` (repeatable, or `a,b`) binds it as it is stored |
111
+ | `foldrun secrets set NAME` | store a secret — also `ls`, `rm`, and `status` (OAuth grant health). `rm` of an oauth2 secret also revokes its grant at the provider when it has a revocation URL, and says if that failed. `--site <domain>` (repeatable, or `a,b`) binds it as it is stored |
111
112
  | `foldrun secrets sites NAME [site…]` | bind a secret to the sites it is for: the egress proxy fills it in requests to those sites alone, and it never enters a sandbox ([bound to sites](secrets#bound-to-sites)). No sites prints what it is bound to; `--clear` unbinds. On the platform, or this machine's vault with `--local` |
112
- | `foldrun secrets set NAME --kind <k>` | the other shapes the Connections form stores: `file` (`--file <path>`), `ssh` (`--host`, `--user`, `--port`, `--key-file <path>` or a prompted password), `api` (`--base-url`, `--header "Name: value"` repeatable, or `--basic-user <u>` with the password prompted or `--basic-password`), `service-account` (`--file <key.json>`, `--scopes`, `--subject <user>` to act as a user where the provider allows it), `client-cert` (`--cert-file`, `--key-file`, `--passphrase`, `--export` to put it in the sandbox as files too; bind it with `secrets sites`), `identity` (`--audience`: keyless cloud access — nothing secret is stored), `m2m` (a client-credentials app: `--token-url`, `--client-id`, `--scopes`, the secret prompted, `--token-auth basic` for a provider that takes the secret only as HTTP Basic). On the platform, or this machine's vault with `--local` |
113
+ | `foldrun secrets set NAME --kind <k>` | the other shapes the Connections form stores: `file` (`--file <path>`), `ssh` (`--host`, `--user`, `--port`, `--key-file <path>` or a prompted password), `api` (`--base-url`, `--header "Name: value"` repeatable, or `--basic-user <u>` with the password prompted or `--basic-password`), `service-account` (`--file <key.json>`, `--scopes`, `--subject <user>` to act as a user where the provider allows it), `client-cert` (`--cert-file`, `--key-file`, `--passphrase`, `--export` to put it in the sandbox as files too; bind it with `secrets sites`), `identity` (`--audience`: keyless cloud access — nothing secret is stored), `m2m` (a client-credentials app: `--token-url`, `--client-id`, `--scopes`, the secret prompted, `--token-auth basic` for a provider that takes the secret only as HTTP Basic), `token-exchange` (RFC 8693: `--token-url`, `--client-id`, `--subject-secret <NAME>` whose token is traded, and `--audience`, `--scopes`, `--requested-token-type` to narrow it). On the platform, or this machine's vault with `--local` |
113
114
  | `foldrun secrets clients` | the OAuth clients saved on the platform — what a consent runs from without typing the client again; the client secret is never shown. `clients add <name> --authorize-url … --token-url … --client-id … --scopes …` saves one (secret prompted), with `--authorize-param name=value` for anything else the provider's authorize URL takes and `--token-auth basic` for a provider that takes the secret only as HTTP Basic, `clients rm <name>` removes it |
114
115
  | `foldrun connect NAME` | OAuth sign-in from the terminal, stored as an auto-refreshing secret — `--authorize-url` and `--token-url` from the provider's OAuth docs, `--authorize-param name=value` for its extras; PKCE is on (`--no-pkce` only for an app with a secret whose provider refuses it), and an app with no client secret is a public app; `--token-auth basic` sends the secret as HTTP Basic, for providers that refuse it in the form body; reconnecting a secret whose client is saved asks for nothing (`--new-client` to enter one) |
115
116
  | `foldrun connect NAME --client <saved>` | the Connections page's **Connect**: a consent from a client saved on the platform (`--scopes "<a b>"` asks for this connection's own scopes instead of the client's default; the connection keeps them). It opens a page in the dashboard where you, signed in, accept the connection before the provider is asked, returning to the platform's own callback, which stores the grant as NAME (`--to <workspace>` for a workspace's). Opens the browser (`--no-browser` prints the address) and waits for it to land |
@@ -251,7 +252,13 @@ claude.ai or Claude Code there, nor any MCP configuration on disk.
251
252
  | `--scopes "<a b c>"` | `connect`: space-separated, as OAuth defines it |
252
253
  | `--client-id` / `--client-secret` | `connect`: the OAuth app; prompted when omitted, the secret never echoed |
253
254
  | `--port <n>` | `connect`: the loopback port (default 8642) |
254
- | `--token-auth <how>` | `connect`, `secrets clients add`, `secrets set --kind m2m`, `secrets set --oauth2`: how the app proves itself at the token URL — `post` (the form body, the default), `basic` (HTTP Basic: Notion, Spotify, Reddit, Zoom) or `none` (a public app with no secret) |
255
+ | `--issuer <url>` | `connect`, `secrets clients add`: the provider's issuer. Its metadata (RFC 8414 / OpenID Connect) fills the authorize and token URLs not given, picks `--token-auth`, and keeps the revocation, device and PAR endpoints; the callback's `iss` is checked against it (RFC 9207) |
256
+ | `--revoke-url <url>` | `connect`, `secrets clients add`: the provider's revocation endpoint (RFC 7009), when discovery does not give it. Deleting or reconnecting the secret revokes its grant there |
257
+ | `--token-auth <how>` | `connect`, `secrets clients add`, `secrets set --kind m2m`, `secrets set --oauth2`: how the app proves itself at the token URL — `post` (the form body, the default), `basic` (HTTP Basic: Notion, Spotify, Reddit, Zoom), `none` (a public app with no secret) or `jwt` (`private_key_jwt`: a JWT signed with the app's key, no secret) |
258
+ | `--key-file <path>`, `--cert-file <path>` | with `--token-auth jwt`: the app's private key (PEM or JWK) and, for Microsoft Entra, its certificate. With `--token-auth mtls`: the client certificate and its key for mutual TLS (RFC 8705), on `secrets clients add` and `secrets set --kind m2m` |
259
+ | `--dpop` | `connect`, `secrets clients add`, `secrets set --kind m2m`: DPoP-bound tokens (RFC 9449). The connection gets its own key and its requests carry proofs; use it through a site binding |
260
+ | `--device`, `--device-url <url>` | `connect`: connect with a code you type on any device (RFC 8628) instead of a redirect — no browser and no loopback port here. With `--client <saved app>` the platform runs it; otherwise the device endpoint comes from `--issuer` or `--device-url` |
261
+ | `--generate-key` | with `--token-auth jwt`: foldrun makes the key (EC P-256) and prints the public JWK to register with the provider; `connect` waits for Enter before it opens the consent |
255
262
  | `--role <r>` | `keys create`: `viewer`, `editor` (default) or `admin` |
256
263
  | `--expires <span>` | `keys create`: when it stops working — `30d`, `90d`, `365d` or `never` (default) |
257
264
  | `--grace <span>` | `keys rotate`: keep the old key working for `1h` or `24h` (default `0`: revoked now) |
package/docs/mcp.md CHANGED
@@ -96,7 +96,27 @@ they chose then and the role they hold now, in the workspaces both allow. A
96
96
  person who leaves the account, or is made a viewer, takes their apps with
97
97
  them. The access token lasts an hour and opens `/api/mcp` only — sent to any
98
98
  other route it is refused. Refresh tokens rotate on every use, and one used
99
- twice disconnects the app: someone else has a copy. Approving, disconnecting
99
+ twice disconnects the app: someone else has a copy. **Machine clients.** A program with no person to approve it, such as a
100
+ nightly job, a CI step or another service, can sign in with client
101
+ credentials. An admin registers it in Settings → API keys → Connected AI apps
102
+ (**Add a machine client**), or with `foldrun mcp clients add <name>`, choosing
103
+ its role, its workspaces, and whether it may act or only read. It gets a
104
+ client id and a secret, shown once, or it registers public keys and signs
105
+ assertions (`private_key_jwt`). It asks the token endpoint with
106
+ `grant_type=client_credentials` and gets an access token for an hour, with no
107
+ refresh token: it simply asks again. It acts within the role and workspaces of
108
+ the admin who registered it, and stops if that admin loses them. It is listed
109
+ with the connected apps, and disconnecting it ends it at once: its next token
110
+ request is refused with `invalid_client`.
111
+
112
+ An app that holds a private key can authenticate with it instead of a client
113
+ secret (`private_key_jwt`). It registers its public keys (`jwks` or
114
+ `jwks_uri`) and signs a short assertion each time it uses the token
115
+ endpoint. A copied assertion is refused when it is used a second time.
116
+
117
+ An app can also end its own connection by handing a token back to
118
+ `/api/mcp/oauth/revoke` (RFC 7009, advertised as `revocation_endpoint`).
119
+ Approving, disconnecting
100
120
  and that automatic disconnect are in the audit log (`mcp.connected`,
101
121
  `mcp.revoked`).
102
122
 
package/docs/oauth.md ADDED
@@ -0,0 +1,70 @@
1
+ ---
2
+ title: OAuth support
3
+ description: Every kind of OAuth, and what foldrun does about it — when an agent connects to a provider, and when an AI app signs in to foldrun.
4
+ ---
5
+
6
+ <!-- Generated from foldrun-core/src/oauth-capabilities.ts by
7
+ `node scripts/oauth-doc.mjs` in foldrun-core. Edit the list, not this page. -->
8
+
9
+ # OAuth support
10
+
11
+ foldrun meets OAuth in two roles:
12
+
13
+ - **As a client.** An agent reaches Google, Slack, Notion or a bank. You
14
+ connect the account once ([connected accounts](secrets#connected-accounts)),
15
+ and foldrun holds the token and refreshes it.
16
+ - **As an authorization server.** An AI app such as claude.ai signs in to
17
+ foldrun's MCP endpoint ([MCP](mcp)), and foldrun issues the token.
18
+
19
+ Each row that says *Supported* is proven by tests that run against a real
20
+ authorization server (Keycloak) and against recorded provider answers.
21
+
22
+ ## When an agent connects to a provider
23
+
24
+ | What | Spec | Status | How, or why not |
25
+ |---|---|---|---|
26
+ | Authorization code with PKCE (S256) | RFC 6749 §4.1, RFC 7636 | Supported | Settings → Connections or `foldrun connect`. PKCE is on for every connection. |
27
+ | Refresh, and refresh-token rotation | RFC 6749 §6, RFC 9700 §2.2.2 | Supported | Refreshed before every use; a rotated refresh token replaces the stored one. |
28
+ | Client credentials (machine to machine) | RFC 6749 §4.4 | Supported | The "OAuth — client credentials" connection, or `foldrun secrets set NAME --kind m2m`. |
29
+ | Client secret in the form body | RFC 6749 §2.3.1 | Supported | The default (`token_auth: client_secret_post`). |
30
+ | Client secret as HTTP Basic | RFC 6749 §2.3.1 | Supported | `token_auth: client_secret_basic`, or `--token-auth basic`. Notion, Spotify, Reddit and Zoom need it. |
31
+ | Public app (no secret), PKCE only | RFC 9700 §2.1.1 | Supported | Leave the client secret empty. |
32
+ | Metadata discovery from an issuer | RFC 8414, OpenID Connect Discovery | Supported | The Issuer field's Discover, or `--issuer`. |
33
+ | Issuer in the authorization response (mix-up defence) | RFC 9207 | Supported | With an issuer, the `iss` that comes back must be it. |
34
+ | Revocation when a connection ends | RFC 7009 | Supported | Deleting a connection, or reconnecting it with another app, revokes the old grant. |
35
+ | Pushed authorization requests | RFC 9126 | Supported | Used whenever the provider has a PAR endpoint. |
36
+ | Token responses as providers send them | RFC 6749 §5.1 | Supported | JSON or form-encoded, `expires_in` as a string, Slack's `authed_user`. |
37
+ | JWT bearer grant (service accounts) | RFC 7523 §2.1 | Supported | The service-account connection (`--kind service-account`). |
38
+ | Rich authorization requests | RFC 9396 | Supported | `authorization_details` as an extra authorize parameter (a JSON value). |
39
+ | Signed client assertion (private_key_jwt) | RFC 7523 §2.2 | Supported | `token_auth: private_key_jwt` with a key you paste or foldrun makes; a certificate adds Entra's thumbprint. `--token-auth jwt`. |
40
+ | Device authorization | RFC 8628 | Supported | Connect with a code on any device: the Connections form, or `foldrun connect --device`. PKCE is sent with the device grant. |
41
+ | Token exchange | RFC 8693 | Supported | A `token-exchange` secret: another secret's live token traded for a narrower one, cached. Cloud STS is covered by the keyless identity kind; a workload identity as the subject is not yet. |
42
+ | DPoP sender-constrained tokens | RFC 9449 | Supported | `dpop: true` on the app (`--dpop`): each connection's own key; the egress proxy signs a proof for every call through a site binding; nonces honoured. |
43
+ | Mutual-TLS client auth and bound tokens | RFC 8705 | Supported | `token_auth: tls_client_auth` with the certificate and key; presented to the token URL and, through the egress proxy, on the calls the token is bound to. |
44
+ | Client-initiated backchannel authentication | OpenID CIBA | Not needed | No provider an agent needs uses it. |
45
+
46
+ ## When an AI app signs in to foldrun (`/api/mcp`)
47
+
48
+ | What | Spec | Status | How, or why not |
49
+ |---|---|---|---|
50
+ | Authorization code with PKCE (S256) | OAuth 2.1, MCP authorization | Supported | How claude.ai and other AI apps sign in to /api/mcp. |
51
+ | Refresh rotation, reuse revokes | OAuth 2.1 §4.3.1 | Supported | A refresh token used twice ends the connection. |
52
+ | Client secret (Basic or body), or a public app | RFC 6749 §2.3.1 | Supported | Registered apps choose `none`, `client_secret_post` or `client_secret_basic`. |
53
+ | Authorization server and resource metadata | RFC 8414, RFC 9728 | Supported | `/.well-known/oauth-authorization-server` and `/.well-known/oauth-protected-resource`. |
54
+ | Dynamic registration and client metadata documents | RFC 7591, CIMD | Supported | An app registers itself, or names itself by an https URL. |
55
+ | Resource indicators | RFC 8707 | Supported | Tokens are bound to /api/mcp. |
56
+ | Issuer in the authorization response | RFC 9207 | Supported | Every answer carries `iss`. |
57
+ | Revocation endpoint | RFC 7009 | Supported | `POST /api/mcp/oauth/revoke`: an app ends its own connection. |
58
+ | Client credentials for machine clients | RFC 6749 §4.4 | Supported | An admin registers a machine client (Settings, or `foldrun mcp clients add`) with a role, workspaces and access; no refresh token; disconnecting it makes it `invalid_client`. |
59
+ | Signed client assertion (private_key_jwt) | RFC 7523 §2.2 | Supported | Apps that register `jwks` or `jwks_uri` sign in with assertions; each `jti` is used once. |
60
+
61
+ ## Refused on purpose
62
+
63
+ These are refused, and the error says why. They are never quietly ignored.
64
+
65
+ | What | Spec | Status | How, or why not |
66
+ |---|---|---|---|
67
+ | Implicit grant | RFC 9700 §2.1.2 | Refused | Tokens in the browser's URL leak; OAuth 2.1 removes it. |
68
+ | Resource owner password grant | RFC 9700 §2.4 | Refused | foldrun never holds a person's password for another service. |
69
+ | PKCE `plain` | RFC 9700 §2.1.1 | Refused | Only S256 is accepted: `plain` protects nothing if the request is seen. |
70
+ | Wildcard or prefix redirect matching | RFC 9700 §4.1 | Refused | Redirect URIs match exactly (a loopback port may vary). |
package/docs/secrets.md CHANGED
@@ -290,6 +290,98 @@ How a connection is kept safe, whatever the provider:
290
290
  - A provider that **rotates refresh tokens** sends a new one with each
291
291
  refresh; it replaces the old one in the vault, where that secret is kept.
292
292
 
293
+ Every kind of OAuth, and what foldrun does about each, is listed in
294
+ [OAuth support](oauth).
295
+
296
+ ### Discovery from an issuer
297
+
298
+ Most providers publish their own OAuth metadata. Type the provider's
299
+ **Issuer** (`https://login.example.com`, `https://accounts.google.com`, a
300
+ Keycloak realm URL) and press **Discover**. CLI: `--issuer`. The form then
301
+ fills in the authorize and token URLs and how the app signs in at the token
302
+ URL. It also keeps the revocation, device sign-in and pushed-request (PAR)
303
+ endpoints when the provider has them. foldrun refuses what it reads when:
304
+
305
+ - the document names another issuer (RFC 8414 §3.3);
306
+ - an endpoint is not https;
307
+ - the provider lists its PKCE methods without S256.
308
+
309
+ If the provider says it sends `iss` with every answer (RFC 9207), a callback
310
+ without it is refused. Either way, an `iss` that comes back must be the
311
+ issuer's own.
312
+
313
+ When the provider has a pushed authorization request endpoint (PAR, RFC
314
+ 9126), foldrun uses it. The consent's parameters go to the provider first,
315
+ signed in as at the token URL. The browser then carries only the client id and
316
+ a one-time `request_uri`, so nothing in the browser can change or leak them.
317
+ Providers that require PAR need this; every other provider accepts it.
318
+
319
+ ### Sender-constrained tokens: DPoP and client certificates
320
+
321
+ Some providers bind a token to something only foldrun holds, so a copied
322
+ token is useless:
323
+
324
+ - **DPoP** (RFC 9449; Bluesky/atproto, Okta's DPoP mode). Turn on
325
+ **DPoP-bound tokens** for the app (CLI: `--dpop`). Each connection gets a
326
+ key of its own. Its refreshes carry a proof signed with that key, and so
327
+ does every call that uses the token.
328
+ - **A client certificate** (mutual TLS, RFC 8705; banks, FAPI). Choose
329
+ **client certificate** as how the app signs in at the token URL and paste
330
+ the certificate and its key (CLI: `--token-auth mtls --cert-file … --key-file
331
+ …`). The certificate is presented to the token URL, and on the calls the
332
+ token is bound to.
333
+
334
+ Use these connections through a [site binding](#bound-to-sites). The egress
335
+ proxy then makes the proof for each call, or presents the certificate. The
336
+ sandbox holds only the placeholder, never the key. A server that asks for a
337
+ DPoP nonce gets its nonce in the next proof.
338
+
339
+ ### Token exchange
340
+
341
+ A downstream service may accept only a token made for it: another audience,
342
+ fewer scopes. A **token exchange** secret (RFC 8693) is a recipe for one. It
343
+ names another secret, the subject, whose live token it trades at a token
344
+ endpoint for the narrower one. Use **OAuth — token exchange** in
345
+ Connections, or `foldrun secrets set NAME --kind token-exchange --token-url …
346
+ --client-id … --subject-secret UPSTREAM --audience … --scopes …`. Declare the
347
+ subject beside it in the agent's `secrets:` (otherwise it is looked up at the
348
+ same scope). Each use makes the subject live first, then trades its token;
349
+ the result is cached until it expires. The subject may be any token secret,
350
+ including an `oauth2` or service-account one, but not another token exchange.
351
+
352
+ ### Connect with a code
353
+
354
+ Some places have no browser to send a consent through: a terminal over ssh,
355
+ or a provider that will not redirect to your address. If a saved app's
356
+ provider has a device authorization endpoint (RFC 8628; Discover finds it),
357
+ the form shows **Connect with a code**. It gives you a short code and a page:
358
+ open that page on any device, sign in as the account that owns the resource,
359
+ and type the code. foldrun stores the grant the moment the provider says yes,
360
+ exactly as a browser consent would. From a terminal:
361
+ `foldrun connect NAME --client <saved app> --device`, or `foldrun connect
362
+ NAME --device --issuer <url>` for an app that is not saved.
363
+
364
+ ### Revocation
365
+
366
+ A provider that has a revocation endpoint (found by discovery, or given with
367
+ `--revoke-url`) is told when a connection ends (RFC 7009):
368
+
369
+ - **deleting** the secret revokes its refresh token, then its access token;
370
+ - **reconnecting with a different app** revokes the old app's grant once the
371
+ new one is stored.
372
+
373
+ Two cases are left alone, because some providers (Google among them) revoke
374
+ every token a person gave one app at once:
375
+
376
+ - reconnecting with the same app;
377
+ - deleting one of several connections made with the same app.
378
+
379
+ Revoking in either case would end the connection you are keeping.
380
+
381
+ The secret is deleted first. A provider that is down or refuses never keeps
382
+ it, and the dashboard and `foldrun secrets rm` say so, so you can revoke the
383
+ app's access in the provider's own settings.
384
+
293
385
  ### How the app signs in at the token URL
294
386
 
295
387
  The client secret goes to the provider's token URL every time a code is
@@ -301,6 +393,15 @@ traded or a token refreshed. Providers take it one of two ways, and the form's
301
393
  | in the form body (default) | `client_id` and `client_secret` as form fields | most providers: Google, Microsoft, GitHub, LinkedIn, Slack |
302
394
  | HTTP Basic | an `Authorization: Basic` header (RFC 6749 §2.3.1) | Notion, Spotify, Reddit, Zoom, and any provider whose docs say Basic |
303
395
  | none | `client_id` only | a public app, which has no secret (PKCE protects it) |
396
+ | signed JWT (`private_key_jwt`) | a short JWT signed with the app's private key, no secret at all (RFC 7523) | Microsoft Entra certificate credentials, Okta, FAPI providers |
397
+
398
+ For a signed JWT, paste the app's private key (PEM or JWK), or leave the box
399
+ empty and foldrun makes one. If foldrun makes it, the form shows the public
400
+ key (a JWK) to register with the provider before you connect. Microsoft Entra
401
+ names keys by their certificate, so give the certificate too and the
402
+ assertion carries its thumbprint. The private key is sealed like a secret and
403
+ never shown again. CLI: `--token-auth jwt` with `--key-file` (and
404
+ `--cert-file`) or `--generate-key`.
304
405
 
305
406
  If the provider answers `invalid_client` when you connect, try the other
306
407
  setting. The choice stays with the saved app and the secret, so refreshes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "foldrun",
3
- "version": "10.5.0",
3
+ "version": "11.0.0",
4
4
  "description": "Agents are just folders. Write them, check them, run them — on your machine.",
5
5
  "license": "FSL-1.1-ALv2",
6
6
  "type": "module",
@@ -11,7 +11,7 @@
11
11
  "node": ">=22"
12
12
  },
13
13
  "dependencies": {
14
- "@foldrun/core": "^9.3.0"
14
+ "@foldrun/core": "^11.0.0"
15
15
  },
16
16
  "files": [
17
17
  "bin",
package/src/commands.mjs CHANGED
@@ -3476,10 +3476,19 @@ async function secretsCmd(positional, flags, layout) {
3476
3476
  (await promptVisible(" token URL [https://oauth2.googleapis.com/token]: ")) ||
3477
3477
  "https://oauth2.googleapis.com/token";
3478
3478
  const client_id = await promptVisible(" client_id: ");
3479
- const client_secret = await promptHidden(" client_secret: ");
3480
- const refresh_token = await promptHidden(" refresh_token: ");
3481
3479
  const token_auth = await tokenAuthFlag(flags);
3482
- const config = { token_url, client_id, client_secret, refresh_token, ...(token_auth ? { token_auth } : {}) };
3480
+ // private_key_jwt: the key from --key-file or made here, no secret asked.
3481
+ /** @type {any} */
3482
+ let keyFields = assertionKeyFlags(flags);
3483
+ if (token_auth === "private_key_jwt" && !keyFields) {
3484
+ if (flags["generate-key"] !== true) throw new Error("--token-auth jwt needs the app's key: --key-file <pem> (and --cert-file for Entra), or --generate-key");
3485
+ const made = (await core()).generateClientKey("ES256");
3486
+ keyFields = { client_assertion_key: made.privateKey, client_assertion_kid: made.publicJwk.kid, client_assertion_alg: made.publicJwk.alg };
3487
+ showPublicJwk(made.publicJwk);
3488
+ }
3489
+ const client_secret = token_auth === "private_key_jwt" ? undefined : await promptHidden(" client_secret: ");
3490
+ const refresh_token = await promptHidden(" refresh_token: ");
3491
+ const config = { token_url, client_id, ...(client_secret !== undefined ? { client_secret } : {}), refresh_token, ...(token_auth ? { token_auth } : {}), ...(token_auth === "private_key_jwt" ? keyFields : {}) };
3483
3492
  if (url) {
3484
3493
  await remoteCall(url, flags, "/api/secrets", {
3485
3494
  method: "PUT",
@@ -3514,15 +3523,26 @@ async function secretsCmd(positional, flags, layout) {
3514
3523
 
3515
3524
  if (verb === "rm") {
3516
3525
  if (!(await sureToDelete(flags, "secrets rm", `secret ${name}${scope ? ` (workspace ${scope})` : " (account)"}${url ? ` on ${url}` : ""}`))) return 1;
3526
+ /** @type {any} */
3527
+ let revoked;
3517
3528
  if (url) {
3518
- await remoteCall(url, flags, "/api/secrets", {
3529
+ ({ revoked } = await remoteCall(url, flags, "/api/secrets", {
3519
3530
  method: "DELETE",
3520
3531
  body: JSON.stringify({ name, workspace: scope }),
3521
- });
3532
+ }));
3522
3533
  } else {
3523
- (await core()).deleteSecret("default", name, scope);
3524
- }
3525
- console.log(`\n ${c.green("✓")} ${name} removed\n`);
3534
+ // As the platform does it: deleted first, then its grant revoked at the
3535
+ // provider (RFC 7009) when the recipe names a revocation endpoint.
3536
+ const k = await core();
3537
+ const before = k.oauth2ValueAt("default", name, scope);
3538
+ k.deleteSecret("default", name, scope);
3539
+ if (before) revoked = await k.revokeOAuth2Value(before, { tenant: "default", name, workspace: scope, fetcher: (u, init) => fetch(u, init) });
3540
+ }
3541
+ console.log(`\n ${c.green("✓")} ${name} removed`);
3542
+ if (revoked?.error) console.log(` ${c.amber("!")} ${revoked.error} — revoke the app's access in the provider's own settings`);
3543
+ else if (revoked?.revoked?.length) console.log(` ${c.dim(`grant revoked at the provider (${revoked.revoked.join(", ")})`)}`);
3544
+ else if (revoked?.skipped === "shared-grant") console.log(` ${c.dim("grant kept: another secret uses the same app, which the provider may revoke together")}`);
3545
+ console.log();
3526
3546
  return 0;
3527
3547
  }
3528
3548
 
@@ -3821,7 +3841,7 @@ function authorizeParams(flags) {
3821
3841
  * on stderr, so a script reading stdout is not disturbed. */
3822
3842
  function warnProviderDeprecated(flags) {
3823
3843
  if (flags.provider !== undefined) {
3824
- console.error(c.dim(" --provider is deprecated — pass the provider's own --authorize-url and --token-url, and any --authorize-param it documents"));
3844
+ console.error(c.dim(" --provider is deprecated — pass the provider's --issuer (its metadata fills the URLs), or its own --authorize-url and --token-url, and any --authorize-param it documents"));
3825
3845
  }
3826
3846
  }
3827
3847
 
@@ -3831,10 +3851,44 @@ async function tokenAuthFlag(flags) {
3831
3851
  if (flags["token-auth"] === undefined) return undefined;
3832
3852
  const { parseTokenAuth } = await core();
3833
3853
  const auth = typeof flags["token-auth"] === "string" ? parseTokenAuth(flags["token-auth"]) : null;
3834
- if (!auth) throw new Error("--token-auth is basic (HTTP Basic: Notion, Spotify, Reddit, Zoom), post (the form body, the default) or none (a public app)");
3854
+ if (!auth) throw new Error("--token-auth is basic (HTTP Basic: Notion, Spotify, Reddit, Zoom), post (the form body, the default), none (a public app) or jwt (private_key_jwt: a signed assertion with --key-file or --generate-key)");
3835
3855
  return auth;
3836
3856
  }
3837
3857
 
3858
+ /** private_key_jwt's key: --key-file (PEM or JWK) and --cert-file, read
3859
+ * here; undefined when neither is given (then --generate-key, or refused). */
3860
+ function assertionKeyFlags(flags) {
3861
+ if (flags["key-file"] === undefined) {
3862
+ if (flags["cert-file"] !== undefined) throw new Error("--cert-file goes with --key-file");
3863
+ return undefined;
3864
+ }
3865
+ if (typeof flags["key-file"] !== "string") throw new Error("--key-file <path> — the app's private key, PEM or JWK");
3866
+ return {
3867
+ client_assertion_key: fs.readFileSync(flags["key-file"], "utf8"),
3868
+ ...(typeof flags["cert-file"] === "string" ? { client_assertion_cert: fs.readFileSync(flags["cert-file"], "utf8") } : {}),
3869
+ };
3870
+ }
3871
+
3872
+ /** Tell the person where to type the device code (RFC 8628). */
3873
+ function showDeviceCode(started) {
3874
+ console.log(`\n On any device, open ${c.bold(started.verification_uri_complete ?? started.verification_uri)}`);
3875
+ console.log(` and enter the code ${c.bold(started.user_code)} ${c.dim(`(it runs out in ${Math.round(started.expires_in / 60)} minutes)`)}\n`);
3876
+ console.log(` ${c.dim("Waiting for the provider to say yes…")}`);
3877
+ }
3878
+
3879
+ /** tls_client_auth's certificate and key (RFC 8705), from --cert-file and --key-file. */
3880
+ function certAuthFlags(flags) {
3881
+ if (typeof flags["cert-file"] !== "string" || typeof flags["key-file"] !== "string") throw new Error("--token-auth mtls needs --cert-file <pem> and --key-file <pem>: the client certificate and its key");
3882
+ return { tls_client_cert: fs.readFileSync(flags["cert-file"], "utf8"), tls_client_key: fs.readFileSync(flags["key-file"], "utf8") };
3883
+ }
3884
+
3885
+ /** Print a public JWK for the person to register with the provider. */
3886
+ function showPublicJwk(jwk) {
3887
+ console.log(`\n Register this public key with the provider (a JWK; it is not secret):\n`);
3888
+ for (const line of JSON.stringify(jwk, null, 2).split("\n")) console.log(` ${line}`);
3889
+ console.log();
3890
+ }
3891
+
3838
3892
  async function connect(positional, flags) {
3839
3893
  const name = positional[0];
3840
3894
  if (!name) throw new Error("usage: foldrun connect NAME --authorize-url <url> --token-url <url> [--authorize-param name=value …] [--scopes …] [--token-auth basic|post|none] [--workspace <name>] [--new-client]");
@@ -3847,8 +3901,13 @@ async function connect(positional, flags) {
3847
3901
  if (providerName && !preset) {
3848
3902
  throw new Error(`unknown provider "${providerName}" — one of ${Object.keys(OAUTH_PRESETS).join(", ")}, or pass --authorize-url and --token-url`);
3849
3903
  }
3850
- const authorizeUrl = flags["authorize-url"] ?? preset?.authorize_url;
3851
- const tokenUrl = flags["token-url"] ?? preset?.token_url;
3904
+ let authorizeUrl = flags["authorize-url"] ?? preset?.authorize_url;
3905
+ let tokenUrl = flags["token-url"] ?? preset?.token_url;
3906
+ // --issuer: the provider's metadata fills whichever URL was not given
3907
+ // (RFC 8414), and the callback's `iss` is checked against it (RFC 9207).
3908
+ if (flags.issuer !== undefined && typeof flags.issuer !== "string") throw new Error("--issuer is the provider's https issuer URL");
3909
+ const issuer = typeof flags.issuer === "string" ? flags.issuer : undefined;
3910
+ if (flags["revoke-url"] !== undefined && (typeof flags["revoke-url"] !== "string" || !/^https:\/\//.test(flags["revoke-url"]))) throw new Error("--revoke-url is the provider's https revocation endpoint");
3852
3911
 
3853
3912
  // Where the result goes: the platform when one is named or signed in,
3854
3913
  // this machine's vault otherwise. Decided before the browser opens, so a
@@ -3862,7 +3921,12 @@ async function connect(positional, flags) {
3862
3921
  // provider) was connected with, so run its consent flow — no client id, no
3863
3922
  // secret, nothing typed. The redirect is the platform's own callback, which
3864
3923
  // rewrites the same secret at the same scope; we wait for it to land.
3865
- if (url && !flags["client-id"] && !env("OAUTH_CLIENT_ID") && flags["new-client"] !== true) {
3924
+ // --dpop belongs to the app: a reconnect through a saved app signs as that
3925
+ // app does, so it is refused rather than silently ignored (Codex review).
3926
+ if (flags.dpop === true && url && !flags["client-id"] && !env("OAUTH_CLIENT_ID") && flags["new-client"] !== true) {
3927
+ throw new Error("--dpop applies to a new app given here (--client-id …). For a saved app, turn DPoP on for the app: `foldrun secrets clients add <name> --dpop …`, then `foldrun connect NAME --client <name>`");
3928
+ }
3929
+ if (url && !flags["client-id"] && !env("OAUTH_CLIENT_ID") && flags["new-client"] !== true && flags.device !== true) {
3866
3930
  /** @type {any} */
3867
3931
  let started = null;
3868
3932
  try {
@@ -3897,26 +3961,73 @@ async function connect(positional, flags) {
3897
3961
  }
3898
3962
  }
3899
3963
 
3900
- if (!authorizeUrl || !tokenUrl) throw new Error("--authorize-url and --token-url — the provider's own addresses, from its OAuth docs");
3964
+ // A device grant uses no authorize URL: a token URL (and a device URL) is all it needs.
3965
+ const device = flags.device === true;
3966
+ if ((!tokenUrl || (!device && !authorizeUrl)) && !issuer) throw new Error(device
3967
+ ? "--device needs --issuer (its metadata gives the device and token URLs), or --device-url and --token-url"
3968
+ : "--issuer (the provider's issuer URL, its metadata fills the rest), or --authorize-url and --token-url — the provider's own addresses, from its OAuth docs");
3901
3969
  const extra = { ...(preset?.authorize_extra ?? {}), ...authorizeParams(flags) };
3902
- if (!/^https:\/\//.test(tokenUrl) && !/^http:\/\/(127\.0\.0\.1|localhost)[:/]/.test(tokenUrl)) {
3903
- throw new Error("token URL must be https — a refresh token over http is a leaked one");
3904
- }
3905
3970
 
3906
3971
  const clientId = flags["client-id"] ?? env("OAUTH_CLIENT_ID") ?? (await promptVisible(" client_id: "));
3907
3972
  const pkce = flags["no-pkce"] !== true;
3908
- const clientSecret = flags["client-secret"] ?? env("OAUTH_CLIENT_SECRET") ?? (await promptHidden(` client_secret${pkce ? " (empty for a public app)" : ""}: `));
3973
+ let tokenAuth = await tokenAuthFlag(flags);
3974
+ const { oauthTokenRequest, readTokenResponse, tokenAuthProblem, discoverOAuth, isSecureUrl, generateClientKey, generateDpopKey, dpopProof } = await core();
3975
+ // --dpop: this connection's own key (RFC 9449); the exchange and every
3976
+ // refresh carry proofs, and the token is bound to it.
3977
+ if (flags.dpop === true && flags.device === true) throw new Error("--dpop with --device is not supported — connect with the browser (drop --device), or without DPoP");
3978
+ const dpopKey = flags.dpop === true ? generateDpopKey() : undefined;
3979
+ // A client certificate is presented by the platform or by core's refresh;
3980
+ // this machine's own exchange cannot carry one.
3981
+ if (tokenAuth === "tls_client_auth" || tokenAuth === "self_signed_tls_client_auth") throw new Error("--token-auth mtls connects through the platform (`foldrun connect NAME --client <saved app>`, after `secrets clients add --token-auth mtls`) or as a client-credentials secret (`secrets set NAME --kind m2m --token-auth mtls`)");
3982
+ // private_key_jwt signs with a key and sends no secret: none is asked for.
3983
+ /** @type {any} */
3984
+ let keyFields = assertionKeyFlags(flags);
3985
+ if (tokenAuth === "private_key_jwt" && !keyFields) {
3986
+ if (flags["generate-key"] !== true) throw new Error("--token-auth jwt needs the app's key: --key-file <pem> (and --cert-file for Entra), or --generate-key");
3987
+ const made = generateClientKey("ES256");
3988
+ keyFields = { client_assertion_key: made.privateKey, client_assertion_kid: made.publicJwk.kid, client_assertion_alg: made.publicJwk.alg };
3989
+ showPublicJwk(made.publicJwk);
3990
+ await promptVisible(" Press Enter once the provider has it: ");
3991
+ }
3992
+ const clientSecret = tokenAuth === "private_key_jwt" ? "" : flags["client-secret"] ?? env("OAUTH_CLIENT_SECRET") ?? (await promptHidden(` client_secret${pkce ? " (empty for a public app)" : ""}: `));
3909
3993
  if (!clientId) throw new Error("client_id is required");
3910
3994
  // No secret is a public app, which PKCE alone protects (RFC 9700 §2.1.1).
3911
- if (!clientSecret && !pkce) throw new Error("an app with no client_secret needs PKCE — drop --no-pkce");
3912
- const tokenAuth = await tokenAuthFlag(flags);
3913
- const { oauthTokenRequest, readTokenResponse, tokenAuthProblem } = await core();
3995
+ if (!clientSecret && tokenAuth !== "private_key_jwt" && !pkce) throw new Error("an app with no client_secret needs PKCE — drop --no-pkce");
3996
+ /** @type {any} */
3997
+ let discovered = null;
3998
+ // Read whenever there is an issuer, URLs given or not: what it says about
3999
+ // `iss` (RFC 9207) and revocation is needed either way; given URLs win.
4000
+ if (issuer) {
4001
+ discovered = await discoverOAuth(issuer, (u, init) => fetch(u, init), { hasSecret: !!clientSecret, ...(pkce ? {} : { pkce: false }), ...(tokenAuth ? { tokenAuth } : {}), needsAuthorize: !device });
4002
+ authorizeUrl ??= discovered.authorize_url;
4003
+ tokenUrl ??= discovered.token_url;
4004
+ tokenAuth ??= discovered.token_auth;
4005
+ console.log(` ${c.dim(`read ${discovered.metadata_url}`)}`);
4006
+ }
4007
+ if (!isSecureUrl(tokenUrl)) {
4008
+ throw new Error("token URL must be https — a refresh token over http is a leaked one");
4009
+ }
4010
+ const revocationUrl = flags["revoke-url"] ?? discovered?.revocation_url;
3914
4011
  // Before the browser opens: a consent is never spent on a client that
3915
4012
  // cannot then authenticate (Basic with no secret, none with one).
3916
- const authProblem = tokenAuthProblem({ client_secret: clientSecret, token_auth: tokenAuth });
4013
+ // How the app signs in at the token URL, PAR and the exchange alike.
4014
+ const signer = { client_id: clientId, ...(clientSecret ? { client_secret: clientSecret } : {}), ...(tokenAuth ? { token_auth: tokenAuth } : {}), ...(tokenAuth === "private_key_jwt" ? keyFields : {}) };
4015
+ const authProblem = tokenAuthProblem(signer);
3917
4016
  if (authProblem) throw new Error(authProblem);
3918
4017
  const scopes = flags.scopes ?? preset?.scopes_example ?? "";
3919
4018
 
4019
+ /** @type {any} */
4020
+ let payload;
4021
+ if (flags.device === true) {
4022
+ // RFC 8628: a code to type on any device, for a terminal with no browser
4023
+ // of its own (ssh) or a provider that will not redirect to localhost.
4024
+ const deviceUrl = flags["device-url"] ?? discovered?.device_url;
4025
+ if (typeof deviceUrl !== "string" || !isSecureUrl(deviceUrl)) throw new Error("--device needs the provider's device authorization endpoint: --issuer (discovery finds it) or --device-url <https url>");
4026
+ const { startDeviceAuthorization, waitForDeviceToken } = await core();
4027
+ const started = await startDeviceAuthorization({ ...signer, device_url: deviceUrl, token_url: tokenUrl, ...(issuer ? { issuer } : {}) }, scopes, (u, i) => fetch(u, i), extra);
4028
+ showDeviceCode(started);
4029
+ payload = await waitForDeviceToken({ ...signer, token_url: tokenUrl }, started, (u, i) => fetch(u, i));
4030
+ } else {
3920
4031
  // One fixed loopback address, the same on every developer's machine, so an
3921
4032
  // OAuth app is set up once — `http://localhost:8642/callback` — and never
3922
4033
  // per person. Fixed because most providers match the port exactly; 8642
@@ -3945,6 +4056,22 @@ async function connect(positional, flags) {
3945
4056
  authorize.searchParams.set("code_challenge", crypto.createHash("sha256").update(verifier).digest("base64url"));
3946
4057
  authorize.searchParams.set("code_challenge_method", "S256");
3947
4058
  }
4059
+ // PAR (RFC 9126), when the provider has the endpoint (discovery found it):
4060
+ // the parameters are pushed first, client-authenticated as at the token
4061
+ // URL, and the browser carries only client_id and the request_uri.
4062
+ if (discovered?.par_url) {
4063
+ const pushed = oauthTokenRequest(signer, Object.fromEntries(authorize.searchParams), { clientIdInBody: true, audience: issuer ?? tokenUrl });
4064
+ const res = await fetch(discovered.par_url, { method: "POST", headers: pushed.headers, body: pushed.body, redirect: "error" });
4065
+ const answer = /** @type {any} */ (await res.json().catch(() => ({})));
4066
+ if (!res.ok || typeof answer.request_uri !== "string") throw new Error(`the provider refused the pushed authorization request (${res.status}): ${answer.error_description ?? answer.error ?? "no request_uri in the reply"}`);
4067
+ // The authorize URL's own query (a tenant, a policy) stays; the flow's
4068
+ // parameters give way to client_id and the request_uri.
4069
+ const own = new URL(authorizeUrl).searchParams;
4070
+ const flowParams = ["client_id", "redirect_uri", "response_type", "scope", "state", "code_challenge", "code_challenge_method"];
4071
+ for (const k of [...authorize.searchParams.keys()]) if (!own.has(k) || flowParams.includes(k)) authorize.searchParams.delete(k);
4072
+ authorize.searchParams.set("client_id", clientId);
4073
+ authorize.searchParams.set("request_uri", answer.request_uri);
4074
+ }
3948
4075
 
3949
4076
  // One request, then the listener closes. The state is the whole authority:
3950
4077
  // a callback with any other value is answered and ignored.
@@ -3960,6 +4087,21 @@ async function connect(positional, flags) {
3960
4087
  reject(new Error(`${providerName ?? "provider"} refused: ${err} ${u.searchParams.get("error_description") ?? ""}`.trim()));
3961
4088
  return;
3962
4089
  }
4090
+ // Mix-up defence (RFC 9207) with --issuer: a returned iss must equal
4091
+ // it, and a missing one is refused unless discovery said the server
4092
+ // does not send it. Without an issuer there is nothing to compare an
4093
+ // iss with — an issuer and its authorize URL may be on different hosts.
4094
+ const iss = u.searchParams.get("iss");
4095
+ /** @type {string | null} */
4096
+ let wrong = null;
4097
+ if (issuer && (iss !== null ? iss !== issuer : discovered?.iss_parameter !== false)) wrong = `the provider answered as ${iss ?? "nobody"} — expected ${issuer}`;
4098
+ if (wrong) {
4099
+ res.statusCode = 400;
4100
+ res.end(`${wrong}. Nothing was stored; you can close this tab.`);
4101
+ server.close();
4102
+ reject(new Error(wrong));
4103
+ return;
4104
+ }
3963
4105
  res.end("Connected. You can close this tab and return to the terminal.");
3964
4106
  server.close();
3965
4107
  resolve(u.searchParams.get("code"));
@@ -3981,19 +4123,32 @@ async function connect(positional, flags) {
3981
4123
  // header, as --token-auth says; the answer read however the provider
3982
4124
  // wrote it (form-encoded, Slack's nested user token, a string expiry).
3983
4125
  const request = oauthTokenRequest(
3984
- { client_id: clientId, ...(clientSecret ? { client_secret: clientSecret } : {}), ...(tokenAuth ? { token_auth: tokenAuth } : {}) },
4126
+ signer,
3985
4127
  { grant_type: "authorization_code", code, redirect_uri: redirectUri, ...(verifier ? { code_verifier: verifier } : {}) },
4128
+ { audience: tokenUrl },
3986
4129
  );
3987
- const exchange = await fetch(tokenUrl, { method: "POST", headers: request.headers, body: request.body, redirect: "error" });
3988
- const payload = readTokenResponse(await exchange.text().catch(() => ""), exchange.headers.get("content-type") ?? "");
4130
+ /** @param {string | undefined} nonce */
4131
+ const send = (nonce) => fetch(tokenUrl, { method: "POST", headers: dpopKey ? { ...request.headers, dpop: dpopProof(dpopKey, { htm: "POST", htu: tokenUrl, ...(nonce ? { nonce } : {}) }) } : request.headers, body: request.body, redirect: "error" });
4132
+ let exchange = await send(undefined);
4133
+ let text = await exchange.text().catch(() => "");
4134
+ // A DPoP server may ask for its nonce in the proof (RFC 9449 §8): once more, with it.
4135
+ if (dpopKey && exchange.status === 400 && exchange.headers.get("dpop-nonce") && readTokenResponse(text, exchange.headers.get("content-type") ?? "").error === "use_dpop_nonce") {
4136
+ exchange = await send(exchange.headers.get("dpop-nonce") ?? undefined);
4137
+ text = await exchange.text().catch(() => "");
4138
+ }
4139
+ payload = readTokenResponse(text, exchange.headers.get("content-type") ?? "");
3989
4140
  if (!exchange.ok || (!payload.refresh_token && !payload.access_token)) {
3990
4141
  throw new Error(`token exchange failed (${exchange.status}): ${payload.error_description ?? payload.error ?? "no token in the reply"}`);
3991
4142
  }
4143
+ }
3992
4144
 
4145
+ // A DPoP-bound token without a refresh token cannot be stored with its key:
4146
+ // refused rather than saved unusable (Codex review).
4147
+ if (dpopKey && !payload.refresh_token) throw new Error("the provider issued no refresh token — a DPoP-bound connection needs one (ask for offline access, or drop --dpop)");
3993
4148
  // Store: the refresh recipe when there is one, the bare token otherwise.
3994
4149
  /** @type {any} */
3995
4150
  const body = payload.refresh_token
3996
- ? { name, oauth2: { token_url: tokenUrl, client_id: clientId, ...(clientSecret ? { client_secret: clientSecret } : {}), refresh_token: payload.refresh_token, ...(tokenAuth ? { token_auth: tokenAuth } : {}), ...(Object.keys(payload.fields).length ? { fields: payload.fields } : {}) }, workspace: workspaceName, scopes, ...(payload.refresh_token_expires_in ? { refresh_token_expires_in: payload.refresh_token_expires_in } : {}) }
4151
+ ? { name, oauth2: { ...signer, ...(dpopKey ? { dpop_key: dpopKey } : {}), token_url: tokenUrl, refresh_token: payload.refresh_token, ...(revocationUrl ? { revocation_url: revocationUrl } : {}), ...(Object.keys(payload.fields).length ? { fields: payload.fields } : {}) }, workspace: workspaceName, scopes, ...(payload.refresh_token_expires_in ? { refresh_token_expires_in: payload.refresh_token_expires_in } : {}) }
3997
4152
  : { name, value: payload.access_token, workspace: workspaceName };
3998
4153
  if (url) {
3999
4154
  // The same PUT `secrets set` makes. A store that fails here has spent the
@@ -6650,6 +6805,7 @@ function issueDoctor(issue) {
6650
6805
  async function mcpCmd(positional, flags) {
6651
6806
  const [verb, arg, ...extra] = positional;
6652
6807
  if (verb === "connections" || verb === "ls") return mcpConnectionsCmd(flags);
6808
+ if (verb === "clients") return mcpMachineClientsCmd(arg, extra, flags);
6653
6809
  if (verb === "disconnect" || verb === "revoke") {
6654
6810
  if (!arg || extra.length) throw new Error("which connection? `foldrun mcp disconnect <id>` — ids are in `foldrun mcp connections`");
6655
6811
  const url = platformFor(flags, "mcp disconnect");
@@ -6658,7 +6814,7 @@ async function mcpCmd(positional, flags) {
6658
6814
  console.log(`\n ${c.green("✓")} disconnected ${arg}\n`);
6659
6815
  return 0;
6660
6816
  }
6661
- if (positional.length) throw new Error("`foldrun mcp` serves the tools to an AI app (`claude mcp add foldrun -- foldrun mcp`); its verbs are connections and disconnect <id> — not " + verb);
6817
+ if (positional.length) throw new Error("`foldrun mcp` serves the tools to an AI app (`claude mcp add foldrun -- foldrun mcp`); its verbs are connections, disconnect <id> and clients add <name> — not " + verb);
6662
6818
  if (process.stdin.isTTY && flags.yes !== true) {
6663
6819
  console.error(`\n ${c.bold("foldrun mcp")} is an MCP server on stdin/stdout, for an AI app to start — not to type into.\n\n claude mcp add foldrun -- foldrun mcp${flags["read-only"] === true ? " --read-only" : ""}\n codex mcp add foldrun -- foldrun mcp\n\n ${c.dim("Claude Desktop, Cursor: { \"mcpServers\": { \"foldrun\": { \"command\": \"foldrun\", \"args\": [\"mcp\"] } } } — `foldrun docs mcp`")}\n`);
6664
6820
  return 2;
@@ -6763,6 +6919,40 @@ async function mcpCmd(positional, flags) {
6763
6919
  return 0;
6764
6920
  }
6765
6921
 
6922
+ /**
6923
+ * `foldrun mcp clients add <name>` — register a machine client for /api/mcp
6924
+ * (client credentials, part G): no person approves its tokens. --role,
6925
+ * --workspaces a,b, --write (else read only), --token-auth basic|post|jwt
6926
+ * (jwt with --jwks-file: the client's public keys). The secret is printed
6927
+ * once. It is listed and ended like any connection (`mcp connections`,
6928
+ * `mcp disconnect <id>`).
6929
+ */
6930
+ async function mcpMachineClientsCmd(sub, rest, flags) {
6931
+ if (sub !== "add" || rest.length !== 1) throw new Error("`foldrun mcp clients add <name> [--role viewer|editor|admin] [--workspaces a,b] [--write] [--token-auth basic|post|jwt --jwks-file <path>]` — list and end them with `mcp connections` and `mcp disconnect <id>`");
6932
+ const url = platformFor(flags, "mcp clients add");
6933
+ const auth = flags["token-auth"] === undefined ? "client_secret_basic" : ((await tokenAuthFlag(flags)) ?? "client_secret_basic");
6934
+ if (!["client_secret_basic", "client_secret_post", "private_key_jwt"].includes(auth)) throw new Error("--token-auth for a machine client is basic, post or jwt");
6935
+ if (auth === "private_key_jwt" && typeof flags["jwks-file"] !== "string") throw new Error("--token-auth jwt needs --jwks-file <path>: the client's public keys ({ \"keys\": [...] })");
6936
+ // Not given: left out, so the platform uses the caller's own workspaces
6937
+ // (a scoped admin cannot give "all").
6938
+ const workspaces = typeof flags.workspaces === "string" ? flags.workspaces.split(",").map((w) => w.trim()).filter(Boolean) : undefined;
6939
+ const body = {
6940
+ name: rest[0],
6941
+ role: typeof flags.role === "string" ? flags.role : "viewer",
6942
+ ...(workspaces ? { workspaces } : {}),
6943
+ access: flags.write === true ? "write" : "read",
6944
+ token_auth: auth,
6945
+ ...(auth === "private_key_jwt" ? { jwks: JSON.parse(fs.readFileSync(flags["jwks-file"], "utf8")) } : {}),
6946
+ };
6947
+ const made = await remoteCall(url, flags, "/api/mcp/clients", { method: "POST", body: JSON.stringify(body) });
6948
+ console.log(`\n ${c.green("✓")} registered ${c.bold(rest[0])} ${c.dim(`(${body.access === "write" ? "read and act" : "read only"} · ${body.role} · ${workspaces ? workspaces.join(", ") : "the workspaces you can open"})`)}\n`);
6949
+ console.log(` client_id ${made.client_id}`);
6950
+ if (made.client_secret) console.log(` client_secret ${made.client_secret} ${c.amber("— shown once")}`);
6951
+ console.log(` token URL ${made.token_endpoint}`);
6952
+ console.log(`\n ${c.dim("grant_type=client_credentials at the token URL, then Bearer the access token to /api/mcp. `foldrun mcp disconnect " + made.grant + "` ends it.")}\n`);
6953
+ return 0;
6954
+ }
6955
+
6766
6956
  /** `foldrun mcp connections` — the AI apps connected to the account over OAuth
6767
6957
  * (claude.ai and the like): which app, whose approval, what access. Every
6768
6958
  * one for an admin; your own otherwise. */
@@ -6778,7 +6968,7 @@ async function mcpConnectionsCmd(flags) {
6778
6968
  if (!rows.length) console.log(`\n ${c.dim("none — claude.ai connects itself when you add this platform's /api/mcp as a custom connector")}`);
6779
6969
  for (const r of rows) {
6780
6970
  const used = r.lastUsedAt ? `last used ${String(r.lastUsedAt).slice(0, 16).replace("T", " ")}` : "not used yet";
6781
- console.log(`\n ${c.bold(r.client)} ${c.dim(`· ${r.redirectHost} · ${r.access === "read" ? "read only" : "read and act"} · ${r.workspaces ? r.workspaces.join(", ") : "all workspaces"}`)}${r.revokedAt ? c.red(" · disconnected") : ""}`);
6971
+ console.log(`\n ${c.bold(r.client)} ${c.dim(`· ${r.machine ? "machine client" : r.redirectHost} · ${r.access === "read" ? "read only" : "read and act"} · ${r.workspaces ? r.workspaces.join(", ") : "all workspaces"}`)}${r.revokedAt ? c.red(" · disconnected") : ""}`);
6782
6972
  console.log(` ${c.dim(`${r.id} · ${r.person} · connected ${String(r.createdAt).slice(0, 16).replace("T", " ")} · ${used}`)}`);
6783
6973
  }
6784
6974
  console.log("");
@@ -11683,25 +11873,53 @@ async function oauthClientsCmd(positional, flags) {
11683
11873
  const { OAUTH_PRESETS } = await core();
11684
11874
  const preset = flags.provider ? OAUTH_PRESETS[flags.provider] : undefined;
11685
11875
  if (flags.provider && !preset) throw new Error(`unknown provider "${flags.provider}" — one of ${Object.keys(OAUTH_PRESETS).join(", ")}, or pass --authorize-url and --token-url`);
11686
- const authorize_url = flags["authorize-url"] ?? preset?.authorize_url;
11687
- const token_url = flags["token-url"] ?? preset?.token_url;
11688
- if (!authorize_url || !token_url) throw new Error("--authorize-url and --token-url — the provider's own addresses, from its OAuth docs");
11876
+ let authorize_url = flags["authorize-url"] ?? preset?.authorize_url;
11877
+ let token_url = flags["token-url"] ?? preset?.token_url;
11878
+ if ((!authorize_url || !token_url) && typeof flags.issuer !== "string") throw new Error("--issuer (the provider's issuer URL, its metadata fills the rest), or --authorize-url and --token-url — the provider's own addresses, from its OAuth docs");
11689
11879
  const authorize_extra = { ...(preset?.authorize_extra ?? {}), ...authorizeParams(flags) };
11690
11880
  const client_id = flags["client-id"] ?? env("OAUTH_CLIENT_ID") ?? (await promptVisible(" client_id: "));
11691
11881
  const pkce = flags["no-pkce"] !== true;
11692
- const client_secret = flags["client-secret"] ?? env("OAUTH_CLIENT_SECRET") ?? (await promptHidden(` client_secret${pkce ? " (empty for a public app)" : ""}: `));
11882
+ let token_auth = await tokenAuthFlag(flags);
11883
+ const certAuth = token_auth === "tls_client_auth" || token_auth === "self_signed_tls_client_auth";
11884
+ const keyFields = certAuth ? undefined : assertionKeyFlags(flags);
11885
+ const certFields = certAuth ? certAuthFlags(flags) : undefined;
11886
+ if (token_auth === "private_key_jwt" && !keyFields && flags["generate-key"] !== true) throw new Error("--token-auth jwt needs the app's key: --key-file <pem> (and --cert-file for Entra), or --generate-key");
11887
+ const client_secret = token_auth === "private_key_jwt" || certAuth ? "" : flags["client-secret"] ?? env("OAUTH_CLIENT_SECRET") ?? (await promptHidden(` client_secret${pkce ? " (empty for a public app)" : ""}: `));
11693
11888
  if (!client_id) throw new Error("client_id is required");
11694
- if (!client_secret && !pkce) throw new Error("an app with no client_secret needs PKCE — drop --no-pkce");
11889
+ if (!client_secret && token_auth !== "private_key_jwt" && !certAuth && !pkce) throw new Error("an app with no client_secret needs PKCE — drop --no-pkce");
11695
11890
  if (flags.issuer !== undefined && (typeof flags.issuer !== "string" || !/^https:\/\/[^?#]+$/.test(flags.issuer))) throw new Error("--issuer is the provider's https issuer URL, no query or fragment");
11696
- const token_auth = await tokenAuthFlag(flags);
11891
+ /** @type {any} */
11892
+ let found = null;
11893
+ if (typeof flags.issuer === "string") {
11894
+ // The platform reads the metadata (POST /api/oauth/discover, through its
11895
+ // SSRF guard) — the same call the Connections form's Discover makes.
11896
+ ({ config: found } = await remoteCall(url, flags, "/api/oauth/discover", {
11897
+ method: "POST",
11898
+ body: JSON.stringify({ issuer: flags.issuer, has_secret: !!client_secret, ...(pkce ? {} : { pkce: false }), ...(token_auth ? { token_auth } : {}) }),
11899
+ }));
11900
+ authorize_url ??= found.authorize_url;
11901
+ token_url ??= found.token_url;
11902
+ token_auth ??= found.token_auth;
11903
+ console.log(` ${c.dim(`read ${found.metadata_url}${found.revocation_url ? " · revocation" : ""}${found.device_url ? " · device sign-in" : ""}${found.par_url ? " · PAR" : ""}`)}`);
11904
+ }
11905
+ if (flags["revoke-url"] !== undefined && (typeof flags["revoke-url"] !== "string" || !/^https:\/\//.test(flags["revoke-url"]))) throw new Error("--revoke-url is the provider's https revocation endpoint");
11906
+ const revocation_url = flags["revoke-url"] ?? found?.revocation_url;
11697
11907
  const config = {
11698
11908
  authorize_url, token_url, client_id, client_secret: client_secret ?? "", scopes: flags.scopes ?? preset?.scopes_example ?? "",
11699
11909
  ...(Object.keys(authorize_extra).length ? { authorize_extra } : {}),
11700
11910
  ...(pkce ? {} : { pkce: false }),
11701
11911
  ...(typeof flags.issuer === "string" ? { issuer: flags.issuer } : {}),
11702
11912
  ...(token_auth ? { token_auth } : {}),
11913
+ ...(found ? { iss_parameter: found.iss_parameter === true } : {}),
11914
+ ...(revocation_url ? { revocation_url } : {}),
11915
+ ...(found?.device_url ? { device_url: found.device_url } : {}),
11916
+ ...(found?.par_url ? { par_url: found.par_url } : {}),
11703
11917
  };
11704
- await remoteCall(url, flags, "/api/oauth/clients", { method: "POST", body: JSON.stringify({ name, config }) });
11918
+ if (token_auth === "private_key_jwt") Object.assign(config, keyFields ?? { generate_key: true });
11919
+ if (certFields) Object.assign(config, certFields);
11920
+ if (flags.dpop === true) Object.assign(config, { dpop: true });
11921
+ const saved = await remoteCall(url, flags, "/api/oauth/clients", { method: "POST", body: JSON.stringify({ name, config }) });
11922
+ if (saved?.public_jwk && !keyFields) showPublicJwk(saved.public_jwk);
11705
11923
  console.log(`\n ${c.green("✓")} saved ${name} ${c.dim(`— \`foldrun connect NAME --client ${name}\` runs a consent from it`)}\n`);
11706
11924
  return 0;
11707
11925
  }
@@ -11714,12 +11932,29 @@ async function oauthClientsCmd(positional, flags) {
11714
11932
  * the platform's own callback. Waits for it to arrive.
11715
11933
  */
11716
11934
  async function connectFromClient(name, flags) {
11935
+ if (flags.dpop === true) throw new Error("--dpop is the saved app's setting, not a connection's: `foldrun secrets clients add <name> --dpop …` makes every connection from it DPoP-bound");
11717
11936
  const url = platformFor(flags, "connect --client");
11718
11937
  const workspace = typeof flags.to === "string" ? flags.to : undefined;
11719
11938
  const before = (await remoteCall(url, flags, "/api/oauth/connections")).connections?.find((s) => s.name === name && (s.workspace ?? undefined) === workspace)?.connectedAt ?? null;
11720
11939
  // --scopes: this connection's own, instead of the saved client's default;
11721
11940
  // the platform keeps them with the connection for its reconnects.
11722
11941
  const scopes = typeof flags.scopes === "string" && flags.scopes.trim() ? { scopes: flags.scopes } : {};
11942
+ if (flags.device === true) {
11943
+ // The platform asks the provider for a device code and stores the grant
11944
+ // when a poll finds it approved (POST /api/oauth/device, …/device/<id>).
11945
+ const d = await remoteCall(url, flags, "/api/oauth/device", { method: "POST", body: JSON.stringify({ client: flags.client, secret: name, ...(workspace ? { workspace } : {}), ...scopes }) });
11946
+ showDeviceCode(d);
11947
+ let interval = Number(env("FOLDRUN_DEVICE_POLL_S") ?? d.interval ?? 5);
11948
+ for (;;) {
11949
+ await new Promise((r) => setTimeout(r, interval * 1000));
11950
+ const r = await remoteCall(url, flags, `/api/oauth/device/${d.id}`, { method: "POST" });
11951
+ if (r.status === "slow_down") interval += 5;
11952
+ else if (r.status === "connected") {
11953
+ console.log(`\n ${c.green("✓")} ${name} connected on ${url}${workspace ? ` · ${workspace}` : " · account"}\n`);
11954
+ return 0;
11955
+ } else if (r.status === "denied" || r.status === "expired") throw new Error(`${r.reason} — run it again`);
11956
+ }
11957
+ }
11723
11958
  const started = await remoteCall(url, flags, "/api/oauth/start", { method: "POST", body: JSON.stringify({ client: flags.client, secret: name, ...(workspace ? { workspace } : {}), ...scopes }) });
11724
11959
  const opened = flags["no-browser"] === true || !process.stdout.isTTY ? false : await openInBrowser(started.url);
11725
11960
  // The platform answers a hand-off page: a signed-in person accepts the
@@ -11807,13 +12042,50 @@ async function secretOfKind(kind, flags) {
11807
12042
  case "m2m": {
11808
12043
  if (typeof flags["token-url"] !== "string") throw new Error("--kind m2m needs --token-url, --client-id (and the client secret, prompted or --client-secret)");
11809
12044
  const client_id = flags["client-id"] ?? (await promptVisible(" client_id: "));
11810
- const client_secret = flags["client-secret"] ?? (await promptHidden(" client_secret: "));
11811
12045
  const token_auth = await tokenAuthFlag(flags);
11812
- const oauth2 = { token_url: flags["token-url"], client_id, client_secret, grant_type: "client_credentials", ...(flags.scopes ? { extra: { scope: flags.scopes } } : {}), ...(token_auth ? { token_auth } : {}) };
12046
+ const certAuth = token_auth === "tls_client_auth" || token_auth === "self_signed_tls_client_auth";
12047
+ /** @type {any} */
12048
+ let keyFields = certAuth ? certAuthFlags(flags) : assertionKeyFlags(flags);
12049
+ if (token_auth === "private_key_jwt" && !keyFields) {
12050
+ if (flags["generate-key"] !== true) throw new Error("--token-auth jwt needs the app's key: --key-file <pem> (and --cert-file for Entra), or --generate-key");
12051
+ const made = (await core()).generateClientKey("ES256");
12052
+ keyFields = { client_assertion_key: made.privateKey, client_assertion_kid: made.publicJwk.kid, client_assertion_alg: made.publicJwk.alg };
12053
+ showPublicJwk(made.publicJwk);
12054
+ }
12055
+ const client_secret = token_auth === "private_key_jwt" || certAuth ? undefined : flags["client-secret"] ?? (await promptHidden(" client_secret: "));
12056
+ // --dpop: the recipe's own DPoP key, made here (RFC 9449).
12057
+ const dpop = flags.dpop === true ? { dpop_key: (await core()).generateDpopKey() } : {};
12058
+ const oauth2 = { token_url: flags["token-url"], client_id, ...(client_secret !== undefined ? { client_secret } : {}), ...(token_auth === "private_key_jwt" || certAuth ? keyFields : {}), ...dpop, grant_type: "client_credentials", ...(flags.scopes ? { extra: { scope: flags.scopes } } : {}), ...(token_auth ? { token_auth } : {}) };
11813
12059
  return { body: { oauth2 }, local: (k, n, b, s, l) => k.setOAuth2Secret("default", n, b.oauth2, s, l) };
11814
12060
  }
12061
+ case "token-exchange": {
12062
+ // RFC 8693: another secret's live token traded for a narrower one.
12063
+ if (typeof flags["token-url"] !== "string" || typeof flags["subject-secret"] !== "string") throw new Error("--kind token-exchange needs --token-url, --client-id and --subject-secret <NAME> (the secret whose token is traded); --audience, --scopes and --requested-token-type narrow it");
12064
+ const client_id = flags["client-id"] ?? (await promptVisible(" client_id: "));
12065
+ const token_auth = await tokenAuthFlag(flags);
12066
+ // As --kind m2m: a signed assertion's key or a client certificate instead of a secret.
12067
+ const certAuth = token_auth === "tls_client_auth" || token_auth === "self_signed_tls_client_auth";
12068
+ /** @type {any} */
12069
+ let keyFields = certAuth ? certAuthFlags(flags) : assertionKeyFlags(flags);
12070
+ if (token_auth === "private_key_jwt" && !keyFields) {
12071
+ if (flags["generate-key"] !== true) throw new Error("--token-auth jwt needs the app's key: --key-file <pem> (and --cert-file for Entra), or --generate-key");
12072
+ const made = (await core()).generateClientKey("ES256");
12073
+ keyFields = { client_assertion_key: made.privateKey, client_assertion_kid: made.publicJwk.kid, client_assertion_alg: made.publicJwk.alg };
12074
+ showPublicJwk(made.publicJwk);
12075
+ }
12076
+ const client_secret = token_auth === "private_key_jwt" || certAuth ? undefined : flags["client-secret"] ?? (await promptHidden(" client_secret (empty for none): "));
12077
+ const token_exchange = {
12078
+ token_url: flags["token-url"], client_id, ...(client_secret ? { client_secret } : {}), ...(token_auth ? { token_auth } : {}),
12079
+ ...(token_auth === "private_key_jwt" || certAuth ? keyFields : {}),
12080
+ subject_secret: flags["subject-secret"],
12081
+ ...(typeof flags.audience === "string" ? { audience: flags.audience } : {}),
12082
+ ...(typeof flags.scopes === "string" ? { scope: flags.scopes } : {}),
12083
+ ...(typeof flags["requested-token-type"] === "string" ? { requested_token_type: flags["requested-token-type"] } : {}),
12084
+ };
12085
+ return { body: { token_exchange }, local: (k, n, b, s, l) => k.setTokenExchangeSecret("default", n, b.token_exchange, s, l) };
12086
+ }
11815
12087
  default:
11816
- throw new Error(`unknown --kind "${kind}" — file, ssh, api, service-account, m2m, client-cert or identity (a plain value needs no --kind; --oauth2 a refresh token; \`foldrun connect\` a browser sign-in)`);
12088
+ throw new Error(`unknown --kind "${kind}" — file, ssh, api, service-account, m2m, client-cert, identity or token-exchange (a plain value needs no --kind; --oauth2 a refresh token; \`foldrun connect\` a browser sign-in)`);
11817
12089
  }
11818
12090
  }
11819
12091