foldrun 10.5.0 → 10.6.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/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`. 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`) and `revocation_url` are kept with it |
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,8 @@ 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) |
494
+ | `/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
495
  | `/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
496
  | `/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
497
  | `/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 |
@@ -546,6 +547,7 @@ with `HTTP <status>: <the route's error>`.
546
547
  | `/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 |
547
548
  | `/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
549
  | `/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` |
550
+ | `/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` |
549
551
  | `/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
552
  | `/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
553
 
package/docs/cli.md CHANGED
@@ -107,7 +107,7 @@ claude.ai or Claude Code there, nor any MCP configuration on disk.
107
107
  | `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
108
  | `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
109
  | `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 |
110
+ | `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
111
  | `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
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
113
  | `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 |
@@ -251,6 +251,8 @@ claude.ai or Claude Code there, nor any MCP configuration on disk.
251
251
  | `--scopes "<a b c>"` | `connect`: space-separated, as OAuth defines it |
252
252
  | `--client-id` / `--client-secret` | `connect`: the OAuth app; prompted when omitted, the secret never echoed |
253
253
  | `--port <n>` | `connect`: the loopback port (default 8642) |
254
+ | `--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) |
255
+ | `--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 |
254
256
  | `--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
257
  | `--role <r>` | `keys create`: `viewer`, `editor` (default) or `admin` |
256
258
  | `--expires <span>` | `keys create`: when it stops working — `30d`, `90d`, `365d` or `never` (default) |
package/docs/mcp.md CHANGED
@@ -96,7 +96,9 @@ 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. An app can also end its own connection by handing a token back to
100
+ `/api/mcp/oauth/revoke` (RFC 7009, advertised as `revocation_endpoint`).
101
+ Approving, disconnecting
100
102
  and that automatic disconnect are in the audit log (`mcp.connected`,
101
103
  `mcp.revoked`).
102
104
 
package/docs/secrets.md CHANGED
@@ -290,6 +290,50 @@ 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
+ ### Discovery from an issuer
294
+
295
+ Most providers publish their own OAuth metadata. Type the provider's
296
+ **Issuer** (`https://login.example.com`, `https://accounts.google.com`, a
297
+ Keycloak realm URL) and press **Discover**. CLI: `--issuer`. The form then
298
+ fills in the authorize and token URLs and how the app signs in at the token
299
+ URL. It also keeps the revocation, device sign-in and pushed-request (PAR)
300
+ endpoints when the provider has them. foldrun refuses what it reads when:
301
+
302
+ - the document names another issuer (RFC 8414 §3.3);
303
+ - an endpoint is not https;
304
+ - the provider lists its PKCE methods without S256.
305
+
306
+ If the provider says it sends `iss` with every answer (RFC 9207), a callback
307
+ without it is refused. Either way, an `iss` that comes back must be the
308
+ issuer's own.
309
+
310
+ When the provider has a pushed authorization request endpoint (PAR, RFC
311
+ 9126), foldrun uses it. The consent's parameters go to the provider first,
312
+ signed in as at the token URL. The browser then carries only the client id and
313
+ a one-time `request_uri`, so nothing in the browser can change or leak them.
314
+ Providers that require PAR need this; every other provider accepts it.
315
+
316
+ ### Revocation
317
+
318
+ A provider that has a revocation endpoint (found by discovery, or given with
319
+ `--revoke-url`) is told when a connection ends (RFC 7009):
320
+
321
+ - **deleting** the secret revokes its refresh token, then its access token;
322
+ - **reconnecting with a different app** revokes the old app's grant once the
323
+ new one is stored.
324
+
325
+ Two cases are left alone, because some providers (Google among them) revoke
326
+ every token a person gave one app at once:
327
+
328
+ - reconnecting with the same app;
329
+ - deleting one of several connections made with the same app.
330
+
331
+ Revoking in either case would end the connection you are keeping.
332
+
333
+ The secret is deleted first. A provider that is down or refuses never keeps
334
+ it, and the dashboard and `foldrun secrets rm` say so, so you can revoke the
335
+ app's access in the provider's own settings.
336
+
293
337
  ### How the app signs in at the token URL
294
338
 
295
339
  The client secret goes to the provider's token URL every time a code is
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "foldrun",
3
- "version": "10.5.0",
3
+ "version": "10.6.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": "^9.5.0"
15
15
  },
16
16
  "files": [
17
17
  "bin",
package/src/commands.mjs CHANGED
@@ -3514,15 +3514,26 @@ async function secretsCmd(positional, flags, layout) {
3514
3514
 
3515
3515
  if (verb === "rm") {
3516
3516
  if (!(await sureToDelete(flags, "secrets rm", `secret ${name}${scope ? ` (workspace ${scope})` : " (account)"}${url ? ` on ${url}` : ""}`))) return 1;
3517
+ /** @type {any} */
3518
+ let revoked;
3517
3519
  if (url) {
3518
- await remoteCall(url, flags, "/api/secrets", {
3520
+ ({ revoked } = await remoteCall(url, flags, "/api/secrets", {
3519
3521
  method: "DELETE",
3520
3522
  body: JSON.stringify({ name, workspace: scope }),
3521
- });
3523
+ }));
3522
3524
  } else {
3523
- (await core()).deleteSecret("default", name, scope);
3524
- }
3525
- console.log(`\n ${c.green("✓")} ${name} removed\n`);
3525
+ // As the platform does it: deleted first, then its grant revoked at the
3526
+ // provider (RFC 7009) when the recipe names a revocation endpoint.
3527
+ const k = await core();
3528
+ const before = k.oauth2ValueAt("default", name, scope);
3529
+ k.deleteSecret("default", name, scope);
3530
+ if (before) revoked = await k.revokeOAuth2Value(before, { tenant: "default", name, workspace: scope, fetcher: (u, init) => fetch(u, init) });
3531
+ }
3532
+ console.log(`\n ${c.green("✓")} ${name} removed`);
3533
+ if (revoked?.error) console.log(` ${c.amber("!")} ${revoked.error} — revoke the app's access in the provider's own settings`);
3534
+ else if (revoked?.revoked?.length) console.log(` ${c.dim(`grant revoked at the provider (${revoked.revoked.join(", ")})`)}`);
3535
+ else if (revoked?.skipped === "shared-grant") console.log(` ${c.dim("grant kept: another secret uses the same app, which the provider may revoke together")}`);
3536
+ console.log();
3526
3537
  return 0;
3527
3538
  }
3528
3539
 
@@ -3821,7 +3832,7 @@ function authorizeParams(flags) {
3821
3832
  * on stderr, so a script reading stdout is not disturbed. */
3822
3833
  function warnProviderDeprecated(flags) {
3823
3834
  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"));
3835
+ 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
3836
  }
3826
3837
  }
3827
3838
 
@@ -3847,8 +3858,13 @@ async function connect(positional, flags) {
3847
3858
  if (providerName && !preset) {
3848
3859
  throw new Error(`unknown provider "${providerName}" — one of ${Object.keys(OAUTH_PRESETS).join(", ")}, or pass --authorize-url and --token-url`);
3849
3860
  }
3850
- const authorizeUrl = flags["authorize-url"] ?? preset?.authorize_url;
3851
- const tokenUrl = flags["token-url"] ?? preset?.token_url;
3861
+ let authorizeUrl = flags["authorize-url"] ?? preset?.authorize_url;
3862
+ let tokenUrl = flags["token-url"] ?? preset?.token_url;
3863
+ // --issuer: the provider's metadata fills whichever URL was not given
3864
+ // (RFC 8414), and the callback's `iss` is checked against it (RFC 9207).
3865
+ if (flags.issuer !== undefined && typeof flags.issuer !== "string") throw new Error("--issuer is the provider's https issuer URL");
3866
+ const issuer = typeof flags.issuer === "string" ? flags.issuer : undefined;
3867
+ 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
3868
 
3853
3869
  // Where the result goes: the platform when one is named or signed in,
3854
3870
  // this machine's vault otherwise. Decided before the browser opens, so a
@@ -3897,11 +3913,8 @@ async function connect(positional, flags) {
3897
3913
  }
3898
3914
  }
3899
3915
 
3900
- if (!authorizeUrl || !tokenUrl) throw new Error("--authorize-url and --token-url — the provider's own addresses, from its OAuth docs");
3916
+ if ((!authorizeUrl || !tokenUrl) && !issuer) 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");
3901
3917
  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
3918
 
3906
3919
  const clientId = flags["client-id"] ?? env("OAUTH_CLIENT_ID") ?? (await promptVisible(" client_id: "));
3907
3920
  const pkce = flags["no-pkce"] !== true;
@@ -3909,8 +3922,23 @@ async function connect(positional, flags) {
3909
3922
  if (!clientId) throw new Error("client_id is required");
3910
3923
  // No secret is a public app, which PKCE alone protects (RFC 9700 §2.1.1).
3911
3924
  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();
3925
+ let tokenAuth = await tokenAuthFlag(flags);
3926
+ const { oauthTokenRequest, readTokenResponse, tokenAuthProblem, discoverOAuth, isSecureUrl } = await core();
3927
+ /** @type {any} */
3928
+ let discovered = null;
3929
+ // Read whenever there is an issuer, URLs given or not: what it says about
3930
+ // `iss` (RFC 9207) and revocation is needed either way; given URLs win.
3931
+ if (issuer) {
3932
+ discovered = await discoverOAuth(issuer, (u, init) => fetch(u, init), { hasSecret: !!clientSecret, ...(pkce ? {} : { pkce: false }), ...(tokenAuth ? { tokenAuth } : {}) });
3933
+ authorizeUrl ??= discovered.authorize_url;
3934
+ tokenUrl ??= discovered.token_url;
3935
+ tokenAuth ??= discovered.token_auth;
3936
+ console.log(` ${c.dim(`read ${discovered.metadata_url}`)}`);
3937
+ }
3938
+ if (!isSecureUrl(tokenUrl)) {
3939
+ throw new Error("token URL must be https — a refresh token over http is a leaked one");
3940
+ }
3941
+ const revocationUrl = flags["revoke-url"] ?? discovered?.revocation_url;
3914
3942
  // Before the browser opens: a consent is never spent on a client that
3915
3943
  // cannot then authenticate (Basic with no secret, none with one).
3916
3944
  const authProblem = tokenAuthProblem({ client_secret: clientSecret, token_auth: tokenAuth });
@@ -3945,6 +3973,26 @@ async function connect(positional, flags) {
3945
3973
  authorize.searchParams.set("code_challenge", crypto.createHash("sha256").update(verifier).digest("base64url"));
3946
3974
  authorize.searchParams.set("code_challenge_method", "S256");
3947
3975
  }
3976
+ // PAR (RFC 9126), when the provider has the endpoint (discovery found it):
3977
+ // the parameters are pushed first, client-authenticated as at the token
3978
+ // URL, and the browser carries only client_id and the request_uri.
3979
+ if (discovered?.par_url) {
3980
+ const pushed = oauthTokenRequest(
3981
+ { client_id: clientId, ...(clientSecret ? { client_secret: clientSecret } : {}), ...(tokenAuth ? { token_auth: tokenAuth } : {}) },
3982
+ Object.fromEntries(authorize.searchParams),
3983
+ { clientIdInBody: true },
3984
+ );
3985
+ const res = await fetch(discovered.par_url, { method: "POST", headers: pushed.headers, body: pushed.body, redirect: "error" });
3986
+ const answer = /** @type {any} */ (await res.json().catch(() => ({})));
3987
+ 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"}`);
3988
+ // The authorize URL's own query (a tenant, a policy) stays; the flow's
3989
+ // parameters give way to client_id and the request_uri.
3990
+ const own = new URL(authorizeUrl).searchParams;
3991
+ const flowParams = ["client_id", "redirect_uri", "response_type", "scope", "state", "code_challenge", "code_challenge_method"];
3992
+ for (const k of [...authorize.searchParams.keys()]) if (!own.has(k) || flowParams.includes(k)) authorize.searchParams.delete(k);
3993
+ authorize.searchParams.set("client_id", clientId);
3994
+ authorize.searchParams.set("request_uri", answer.request_uri);
3995
+ }
3948
3996
 
3949
3997
  // One request, then the listener closes. The state is the whole authority:
3950
3998
  // a callback with any other value is answered and ignored.
@@ -3960,6 +4008,21 @@ async function connect(positional, flags) {
3960
4008
  reject(new Error(`${providerName ?? "provider"} refused: ${err} ${u.searchParams.get("error_description") ?? ""}`.trim()));
3961
4009
  return;
3962
4010
  }
4011
+ // Mix-up defence (RFC 9207) with --issuer: a returned iss must equal
4012
+ // it, and a missing one is refused unless discovery said the server
4013
+ // does not send it. Without an issuer there is nothing to compare an
4014
+ // iss with — an issuer and its authorize URL may be on different hosts.
4015
+ const iss = u.searchParams.get("iss");
4016
+ /** @type {string | null} */
4017
+ let wrong = null;
4018
+ if (issuer && (iss !== null ? iss !== issuer : discovered?.iss_parameter !== false)) wrong = `the provider answered as ${iss ?? "nobody"} — expected ${issuer}`;
4019
+ if (wrong) {
4020
+ res.statusCode = 400;
4021
+ res.end(`${wrong}. Nothing was stored; you can close this tab.`);
4022
+ server.close();
4023
+ reject(new Error(wrong));
4024
+ return;
4025
+ }
3963
4026
  res.end("Connected. You can close this tab and return to the terminal.");
3964
4027
  server.close();
3965
4028
  resolve(u.searchParams.get("code"));
@@ -3993,7 +4056,7 @@ async function connect(positional, flags) {
3993
4056
  // Store: the refresh recipe when there is one, the bare token otherwise.
3994
4057
  /** @type {any} */
3995
4058
  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 } : {}) }
4059
+ ? { name, oauth2: { token_url: tokenUrl, client_id: clientId, ...(clientSecret ? { client_secret: clientSecret } : {}), refresh_token: payload.refresh_token, ...(tokenAuth ? { token_auth: tokenAuth } : {}), ...(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
4060
  : { name, value: payload.access_token, workspace: workspaceName };
3998
4061
  if (url) {
3999
4062
  // The same PUT `secrets set` makes. A store that fails here has spent the
@@ -11683,9 +11746,9 @@ async function oauthClientsCmd(positional, flags) {
11683
11746
  const { OAUTH_PRESETS } = await core();
11684
11747
  const preset = flags.provider ? OAUTH_PRESETS[flags.provider] : undefined;
11685
11748
  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");
11749
+ let authorize_url = flags["authorize-url"] ?? preset?.authorize_url;
11750
+ let token_url = flags["token-url"] ?? preset?.token_url;
11751
+ 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
11752
  const authorize_extra = { ...(preset?.authorize_extra ?? {}), ...authorizeParams(flags) };
11690
11753
  const client_id = flags["client-id"] ?? env("OAUTH_CLIENT_ID") ?? (await promptVisible(" client_id: "));
11691
11754
  const pkce = flags["no-pkce"] !== true;
@@ -11693,13 +11756,33 @@ async function oauthClientsCmd(positional, flags) {
11693
11756
  if (!client_id) throw new Error("client_id is required");
11694
11757
  if (!client_secret && !pkce) throw new Error("an app with no client_secret needs PKCE — drop --no-pkce");
11695
11758
  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);
11759
+ let token_auth = await tokenAuthFlag(flags);
11760
+ /** @type {any} */
11761
+ let found = null;
11762
+ if (typeof flags.issuer === "string") {
11763
+ // The platform reads the metadata (POST /api/oauth/discover, through its
11764
+ // SSRF guard) — the same call the Connections form's Discover makes.
11765
+ ({ config: found } = await remoteCall(url, flags, "/api/oauth/discover", {
11766
+ method: "POST",
11767
+ body: JSON.stringify({ issuer: flags.issuer, has_secret: !!client_secret, ...(pkce ? {} : { pkce: false }), ...(token_auth ? { token_auth } : {}) }),
11768
+ }));
11769
+ authorize_url ??= found.authorize_url;
11770
+ token_url ??= found.token_url;
11771
+ token_auth ??= found.token_auth;
11772
+ console.log(` ${c.dim(`read ${found.metadata_url}${found.revocation_url ? " · revocation" : ""}${found.device_url ? " · device sign-in" : ""}${found.par_url ? " · PAR" : ""}`)}`);
11773
+ }
11774
+ 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");
11775
+ const revocation_url = flags["revoke-url"] ?? found?.revocation_url;
11697
11776
  const config = {
11698
11777
  authorize_url, token_url, client_id, client_secret: client_secret ?? "", scopes: flags.scopes ?? preset?.scopes_example ?? "",
11699
11778
  ...(Object.keys(authorize_extra).length ? { authorize_extra } : {}),
11700
11779
  ...(pkce ? {} : { pkce: false }),
11701
11780
  ...(typeof flags.issuer === "string" ? { issuer: flags.issuer } : {}),
11702
11781
  ...(token_auth ? { token_auth } : {}),
11782
+ ...(found ? { iss_parameter: found.iss_parameter === true } : {}),
11783
+ ...(revocation_url ? { revocation_url } : {}),
11784
+ ...(found?.device_url ? { device_url: found.device_url } : {}),
11785
+ ...(found?.par_url ? { par_url: found.par_url } : {}),
11703
11786
  };
11704
11787
  await remoteCall(url, flags, "/api/oauth/clients", { method: "POST", body: JSON.stringify({ name, config }) });
11705
11788
  console.log(`\n ${c.green("✓")} saved ${name} ${c.dim(`— \`foldrun connect NAME --client ${name}\` runs a consent from it`)}\n`);