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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 26 additions & 3 deletions docs/mcp-client.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,21 @@ arguments or resource data; do not publish them indiscriminately.
| `getToolUI(name)` | Returns a copy of `_meta.ui` or undefined when absent. |
| `getAppResource(name)` | Resolves a tool's `_meta.ui.resourceUri` through `resources/read`; requires a `ui://` URI. Returns the full resource envelope. |
| `hasApps()` | Discovers whether any visible tool has UI resource metadata. This is discovery, not a claim that a browser host exists. |
| `clearCache()` | Drops every response held by the opt-in response cache. |

Resource methods require the advertised `resources` capability. Server errors and
`input_required` results remain observable rather than becoming empty lists.
Discovery is not cached by this client: a new list call refreshes it. Applications
that cache results should invalidate their own cache on the appropriate event.
By default discovery is not cached: a new list call refreshes it. With
`cache:true` the client reuses complete `server/discover`, list (per page) and
`resources/read` results while their `ttlMs` is fresh, reporting the remaining
lifetime in `ttlMs`. `ttlMs` 0 or absent is never cached. `"private"` results are
reused only for the same authorization context (a fingerprint of the current
auth headers); `"public"` ones for any. MRTR retries (`inputResponses`/
`requestState`), per-call HTTP options and errors are never cached.
`notifications/tools/list_changed`, `prompts/list_changed`,
`resources/list_changed` and `resources/updated` invalidate the related entries;
`initialize()`, session-expiry recovery and `destroy()` clear the cache. There is
no background refetch. `cacheMax` (default 500) bounds the number of entries.

## Transports, protocol versions and lifecycle

Expand All @@ -50,7 +60,20 @@ An explicit `protocolVersion:"2026-07-28"` probes that era and fails if unsuppor
Legacy negotiation recognizes 2024-11-05, 2025-03-26, 2025-06-18 and 2025-11-25;
unrecognized negotiated versions fail explicitly. Modern calls carry per-request
version, client capabilities and identity. HTTP sends the negotiated protocol
header, plus `Mcp-Method`/`Mcp-Name` for modern calls. Modern `input_required`
header, plus `Mcp-Method` for modern calls and `Mcp-Name` for `tools/call`/
`prompts/get` (`params.name`), `resources/read` (`params.uri`) and the tasks
extension's `tasks/get`/`tasks/update`/`tasks/cancel` (`params.taskId`). Non-ASCII or
sentinel-like names use the `=?base64?…?=` encoding. On the modern era the
`MCP-Protocol-Version` header always matches the per-request `_meta` version,
including on the `server/discover` probe. Modern HTTP `callTool()` and
`continueRequest("tools/call", …)` also mirror every argument whose input schema
property declares `x-mcp-header` into a `Mcp-Param-{Name}` header (strings as-is,
integers in decimal, booleans as `true`/`false`; absent or null arguments are
omitted). The client learns schemas from `listTools()`; tools with invalid
annotations are excluded from it with a warning and calling them fails. A tool
called before being listed carries no `Mcp-Param` headers: if the server answers
HeaderMismatch (the tool did not run), the client re-lists the tools and retries
once when the mirrored headers changed. Modern `input_required`
results remain visible through `isInputRequired(result)` until the caller explicitly
continues them. Do not indiscriminately retry a tool with side effects.

Expand Down
5 changes: 5 additions & 0 deletions docs/mcp-oauth.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# Localhost OAuth2 authentication

For service-account access to generic REST APIs, see [OAuth for REST clients](oauth-client.md).

To protect an OpenAF HTTP or MCP server with incoming access tokens, see
[OAuth 2.0 resource servers](oauth-resource-server.md).

`ow.server.httpd.oauth2(options)` provides a reusable browser login for OAuth2
providers that support authorization-code flow with S256 PKCE and an HTTP loopback
redirect. It uses OpenAF's HTTPd server to receive the callback and `$sec` to
Expand Down
109 changes: 109 additions & 0 deletions docs/oauth-authorization-server.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
# OpenAF machine-to-machine authorization server

Use `ow.server.oauth.authorizationServer(options)` to issue short-lived access
tokens to pre-registered machine clients. The issuer provides authorization
server metadata, token issuance, introspection and revocation. Select
`tokenFormat: "jwt"` and supply an RSA signing key pair and key ID to issue
typed JWT access tokens and publish JWKS.

For a local demonstration, set `REPORTS_CLIENT_SECRET` and
`REPORTS_VERIFIER_SECRET` to separate generated secrets. Start the server with
this script.

```javascript
ow.loadServer()
var issuer = "http://127.0.0.1:17880"
var resource = "https://api.example.org/reports"
var server = ow.server.oauth.authorizationServer({
issuer: issuer,
allowLoopbackHTTP: true,
resources: { [resource]: { scopes: ["reports:read"] } },
clients: {
reports: {
clientSecretEnv: "REPORTS_CLIENT_SECRET",
resources: { [resource]: ["reports:read"] }
},
verifier: {
clientSecretEnv: "REPORTS_VERIFIER_SECRET",
introspection: true,
resources: { [resource]: [] }
}
}
})
var listener = ow.server.httpd.start(17880, "127.0.0.1", __, __, __, __, 30000, "java")
server.mount(listener)
addOnOpenAFShutdown(server.close)
ow.server.daemon()
```

With the same machine secret in the client process, request a token for the
registered resource.

```javascript
ow.loadServer()
var client = ow.server.oauth.client({
issuer: "http://127.0.0.1:17880",
resource: "https://api.example.org/reports",
clientId: "reports",
clientSecretEnv: "REPORTS_CLIENT_SECRET",
tokenEndpointAuthMethod: "client_secret_basic",
scope: "reports:read",
allowLoopbackHTTP: true
})
var status
try {
client.authenticate()
status = client.getAuthStatus()
} finally {
client.close()
}
print(status)
```

Configure the resource server with `validation: "introspection"`, the
issuer's introspection endpoint, its own client credentials and the required
scopes. Introspection identities can only inspect tokens for their assigned
resources. A machine client can revoke its own credentials. For JWT access
tokens, online validation reflects revocation and offline validation relies on
the token's expiration.

The example uses `client_credentials`, configured clients, and an in-memory
token store on one Java HTTP listener. Restarting this example clears online
token state. Use HTTPS for a deployed issuer. In oJob-common, include
`oJobOAuth.yaml` and supply the issuer map to the `oauthServerStart` shortcut
as its `oauth` argument.

For single-process access-token persistence, set `storage: { type: "h2", file:
"/private/path/tokens" }`. Give one running issuer exclusive ownership of the
database and back up the file under the same issuer configuration. Supply
the same signing key across restarts when using JWTs.

To enable interactive consent, add `authorization_code` to `grants` and
supply an application identity callback. The callback receives the issuer
request and returns a verified `{ subject, sessionId, resources }` or an
undefined value if the requester has no authenticated session. The application
authenticates the session before returning a subject or permissions.
Register the client's exact redirect URIs and use S256 PKCE. With the memory
store, enable `refresh_token` and set `allowRefresh: true` on clients that can
request `offline_access`. Refresh credentials rotate and replay revokes the
family's online access tokens. Restart clears memory-backed consent and refresh
state.

Select `senderConstraint: "dpop"` or `"mtls"` on a machine client registration
to bind tokens at issuance. A registered mutual TLS client supplies its
certificate thumbprint and uses a direct, client-authenticated Java HTTPS
listener.

Set `par: true` to enable `/par`, or `requirePAR: true` to require the
pushed request flow. The issuer binds each short-lived request URI to its
client and accepts it once. Dynamic registration is disabled by default.
To enable the public-client registration profile, configure
`registration.initialAccessTokenEnv` and an `allowRedirect(uri)` policy.
Registering a client does not grant resource access. Use the issuer's local
`admin.grantResource` operation to provision its allowed scopes.

The in-memory issuer's `admin` handle can create and disable clients,
remove them, change resource grants and rotate client secrets. Keep this
handle in trusted application code and keep newly generated secrets out of
logs. A deployment that uses HTTPS with oJob can configure a keystore and
`passwordEnv`. Add a `tlsProfile` for direct mutual TLS.
80 changes: 80 additions & 0 deletions docs/oauth-client.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
# OAuth for REST clients

Use `$rest()` to acquire and renew OAuth 2.0 bearer tokens for a service account.

```javascript
var reports = $rest({
throwExceptions: true,
auth: {
type: "oauth2",
issuer: "https://id.example.org/realms/services",
clientId: "service-a",
clientSecretEnv: "SERVICE_A_SECRET",
tokenEndpointAuthMethod: "client_secret_basic",
scope: "reports:read",
resource: "https://api.example.org/reports"
}
})
var result = reports.get("https://api.example.org/reports")
```

OpenAF discovers the token endpoint from the configured issuer. You can provide
`tokenURL` explicitly. Discovered token endpoints must share the configured
issuer's origin. If you also omit the issuer, OpenAF looks for protected resource
metadata and accepts a single issuer on the resource origin. Configure the issuer
explicitly for a resource served on a different origin.

Call `ow.loadServer()` and create an `ow.server.oauth.client(options)` to
control the client lifecycle explicitly. Pass the instance as `$rest({ auth:
client })` to reuse its in-memory credential across REST callers.
`getAuthStatus()` reports local credential status. `clearAuth()` discards the
cached credential so the next call acquires a fresh one. `close()` releases the
client. Use a separate client for each logical resource and credential profile.

The default grant is `client_credentials`. The client obtains a fresh access
token when it renews. To authenticate with a signing key, configure
`tokenEndpointAuthMethod: "private_key_jwt"`, a Java `privateKey`, its
`keyId`, and the exact `issuer`. OpenAF uses the issuer as the assertion's
sole audience. Providers that require the token endpoint as the audience need
a different authentication method. Set `algorithm: "ML-DSA-65"` to sign
with an RFC 9964 key on a Java runtime and provider supporting pure ML-DSA.
The authorization server must explicitly support this algorithm.

For a browser login with explicit endpoints, set
`grantType: "authorization_code"`, `authURL`, `tokenURL`, a registered
loopback `redirectURI` and `interactive: true`. The existing loopback helper
handles PKCE and optional encrypted `tokenStore` configuration.

The OAuth client checks the final request URL after REST hooks. With a configured
resource, it confines credentials to that origin and path and its descendants.
Without a configured resource, it binds to the first target. Authenticated calls
disable automatic redirects and request retries. Use HTTPS for services.
`allowLoopbackHTTP: true` explicitly permits plain HTTP to loopback for local
development.

For a machine client whose issuer supports ES256 DPoP, add
`senderConstraint: { type: "dpop" }`. OpenAF generates an ephemeral key and
uses it for both token and resource proofs. Supply a Java ES256 `keyPair` in
that map to reuse a managed key. A resource nonce challenge updates the client
for its next request. The application decides whether the original operation
can be repeated.

For client credentials, an optional `tokenStore: { type: "sec", profile: "…" }`
stores bearer credentials for an explicitly configured resource. A custom store
supplies `withLock`, `load`, `save` and `clear`. Use a profile specific to the
deployment and keep the profile stable across cooperating processes.

Set `tlsProfile: "x25519mlkem768"` on a machine client to require TLS 1.3
hybrid key exchange for discovery, token acquisition and resource calls. The TLS
profile uses SunJSSE and the JVM trust store. The peer must support
`X25519MLKEM768`. ML-DSA assertion signing and hybrid TLS are configured
independently.

For direct mutual TLS, use `senderConstraint: { type: "mtls", keyStore,
keyStorePasswordEnv, trustStore, trustStorePasswordEnv }`. The two stores use
PKCS12 and the identity keystore contains one private-key entry. The default
token endpoint authentication method for this profile is `tls_client_auth`.
Use a separate client when rotating the certificate.

To preserve a DPoP key across restarts, set `senderConstraint.keyStore` to
`{ type: "sec", profile: "…" }` and configure the exact issuer and resource.
Loading
Loading