diff --git a/docs/mcp-client.md b/docs/mcp-client.md index 60484b35..95fbeb2c 100644 --- a/docs/mcp-client.md +++ b/docs/mcp-client.md @@ -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 @@ -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. diff --git a/docs/mcp-oauth.md b/docs/mcp-oauth.md index 8b03f78d..4e57031f 100644 --- a/docs/mcp-oauth.md +++ b/docs/mcp-oauth.md @@ -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 diff --git a/docs/oauth-authorization-server.md b/docs/oauth-authorization-server.md new file mode 100644 index 00000000..f97013cb --- /dev/null +++ b/docs/oauth-authorization-server.md @@ -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. diff --git a/docs/oauth-client.md b/docs/oauth-client.md new file mode 100644 index 00000000..373347e9 --- /dev/null +++ b/docs/oauth-client.md @@ -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. diff --git a/docs/oauth-resource-server.md b/docs/oauth-resource-server.md new file mode 100644 index 00000000..bf06e6e9 --- /dev/null +++ b/docs/oauth-resource-server.md @@ -0,0 +1,167 @@ +# OAuth 2.0 resource servers + +Use `ow.server.httpd.oauthResourceServer(options)` to protect OpenAF HTTP routes with access tokens issued by a trusted external authorization server. The same API works with REST, JSON-RPC, and MCP. It validates tokens and publishes protected resource metadata. Authorization, consent, client registration, PKCE, token issuance and refresh take place at the external provider and client. + +| OpenAF API | Role | +| --- | --- | +| `ow.server.httpd.oauthResourceServer()` | Validate inbound access tokens, enforce scopes and describe the protected resource. | +| `ow.server.httpd.authOAuth()` | Sign users into an OpenAF web app and maintain browser sessions. | +| `ow.server.httpd.oauth2()` | Obtain outbound OAuth credentials with a loopback browser callback and optional encrypted token storage. | +| `$mcp()` with `auth.type: "oauth2"` | Discover an MCP server's authentication configuration and obtain outbound access tokens. See [MCP client OAuth](mcp-oauth.md). | + +## Protect an HTTP route + +```javascript +ow.loadServer() +var http = ow.server.httpd +var hs = http.start(17878, "127.0.0.1") +var oauth = http.oauthResourceServer({ + issuer: "https://id.example.org/realms/openaf", + resource: "https://api.example.org/report", + scopesSupported: ["reports:read"], + requiredScopes: ["reports:read"] +}) +var routes = {} +routes["/report"] = oauth.wrap((req, server, auth) => { + if (req.method !== "GET") return http.reply("", 405, "text/plain", { Allow: "GET" }) + return http.reply({ report: "ready", subject: auth.subject }, 200, "application/json", { "Cache-Control": "no-store" }) +}) +routes[oauth.metadataPath()] = oauth.metadataHandler +http.route(hs, routes, __, __, __, ["/report", oauth.metadataPath()]) +addOnOpenAFShutdown(oauth.close) +ow.server.daemon() +``` + +Terminate HTTPS at the ingress and forward both `/report` and `/.well-known/oauth-protected-resource/report` to this listener. Set `resource` to the canonical public URL. For a resource with a different internal mount, route the metadata handler at the internal path that the ingress forwards. The service uses the configured identifier and ignores request host and forwarding headers for OAuth trust. + +For JSON-RPC, use an equivalent route configured for the public RPC URL: + +```javascript +routes["/rpc"] = oauth.wrap((req, server, auth) => + http.replyJSONRPC(server, req, { describe: () => ({ principal: auth.principal }) }), + ["rpc:describe"]) +``` + +Use a separate instance and a distinct audience for each logical protected resource. Register the corresponding metadata handler on the same origin. OAuth-aware clients can follow the `resource_metadata` challenge or retrieve the path-specific RFC 9728 URI directly. If a global HTTP pre-router implements its own authentication, exempt the public metadata route. + +## API + +| Member | Contract | +| --- | --- | +| `authenticate(request)` | Checks the `Authorization` header and returns `{ ok: true, context }` or `{ ok: false, error }`. Header keys are case-insensitive. Supply the HTTP request's `params` so conflicting `access_token` query or form input can be rejected. | +| `authorize(context, scopes)` | Rechecks expiry and requires all global and supplied scopes. Use the context returned by the same live instance. Returns `{ ok: true }` or `{ ok: false, error }`. | +| `challenge(error, scopes)` | Produces the HTTPd reply map for a failed authentication or authorization. Combines the supplied and global scopes in the challenge. | +| `normalizeScopes(scopes)` | Validates and de-duplicates a list or space-delimited scope string for configuration. | +| `metadata()`, `metadataURI()`, `metadataPath()` | Describe the protected resource and derive the RFC 9728 URL and path. | +| `metadataHandler(request)` | Serves public metadata on GET and HEAD. Mount separately from the protected handler. | +| `wrap(handler, scopes)` | Authenticates and authorizes before calling `handler(request, httpd, context)`. The callback receives a copy with credential headers removed. | +| `stats()` | Snapshots instance counters for authentication, authorization, JWKS and introspection cache activity, and total introspection time in milliseconds. Use these counters from trusted operational code. | +| `invalidate()`, `close()` | Clear cached keys and introspection results. Close also cancels outbound calls and rejects future requests. Operations already in progress may finish before invalidation takes effect. | + +Contexts contain `authenticated`, `method`, `issuer`, `subject`, `principal`, `audience`, `scopes`, `expiresAt` (epoch milliseconds) and `claims`. `principal` is a stable SHA-256 identifier of the exact issuer and subject. Configure a provider that issues a stable `sub` for service accounts if you use machine credentials. Treat the context as sensitive and expose only the application fields callers need. The original credential is absent from the context. + +| Condition | HTTP status | Bearer challenge | +| --- | --- | --- | +| Missing Authorization | 401 | Metadata URI and configured required scopes | +| Invalid or expired token | 401 | `invalid_token`, metadata URI and required scopes | +| Insufficient scopes | 403 | `insufficient_scope`, metadata URI and all scopes needed for the operation | +| Malformed bearer header or conflicting `access_token` parameter | 400 | `invalid_request` | +| Provider or validation infrastructure unavailable | 503 | Retry according to application policy | + +Replies to failed authentication use `Cache-Control: no-store`. Use the same policy for user-specific responses. Cache inspection APIs and claim samples belong on trusted administrative paths. + +## Configuration + +| Option | Default and behavior | +| --- | --- | +| `issuer` | Required exact trusted issuer URL, including any tenant path or trailing slash. | +| `resource` | Required public HTTP resource identifier. HTTPS is required in production. The scheme and authority are used to construct metadata URLs. | +| `audience` | Defaults to `resource`. Override with the provider's identifier for this same resource. Accepts a single expected value. A token can contain an array of audiences. | +| `validation` | `jwt` or `introspection`. Each instance uses the selected mode. | +| `discovery` | `true`. Tries RFC 8414 followed by OIDC well-known URLs on HTTP 404 or 405. A fetched document must identify the exact configured issuer. | +| `metadataURL` | Optional explicit authorization-server metadata URL. Applies when discovery is used to find the validator endpoint. | +| `jwksURI`, `introspectionURL` | Optional explicit validator endpoint for the selected mode. Supplying it bypasses discovery. Required when `discovery: false`. | +| `discoveredEndpointOrigins` | Trusted HTTPS origins in addition to the issuer's origin, for discovered validator URLs. Include the port when it is nondefault. Explicit endpoints are trusted configuration. | +| `scopesSupported`, `requiredScopes` | Empty. The former is advertised, the latter enforced. Accept arrays or space-delimited strings. Scopes are case-sensitive and use exact matching. | +| `algorithms` | `["RS256"]`. Also accepts explicit RS384, RS512, PS256, PS384, PS512, ES256, ES384 and ES512. | +| `jwtProfile` | `rfc9068`, `keycloak`, `typed`, `entra-v2-delegated` or `entra-v2-app`. See token rules below. | +| `accessTokenClaim`, `accessTokenValue` | Required for `typed`. A named signed claim and exact string value reserved for access tokens by the provider. | +| `scopeClaim` | `scope`. Exact name of the claim that supplies permissions. Values can be arrays or space-delimited strings. | +| `claimAllowlist` | Empty. Exposes named scalar claims or arrays of scalars. | +| `clockSkew` | 30 seconds for JWTs, range 0–300. Introspection expiration has zero grace so cache entries never outlive token expiry. | +| `allowLoopbackHTTP` | `false`. Development exception for `127.0.0.1`, `::1` and `localhost` only. | +| `timeoutMs` | 3000 per outbound HTTP call and for waiting on a refresh lock, range 50–30000. Discovery can make multiple calls. | +| `maxResponseBytes` | 262144 decompressed bytes per provider response, range 1024–4194304. | +| `maxTokenBytes` | 16384, range 256–65536. | +| `jwksCacheTTL` | 300000 ms, range 100–86400000. Also bounds discovered introspection endpoint reuse. | +| `maxJwksKeys` | 64, range 1–256. Oversized JWKS documents fail closed. | +| `refreshCooldownMs` | 3000 ms, range 100–60000. Bounds refresh attempts triggered by unknown keys or provider failures. | +| `introspectionCacheTTL` | 0 ms, range 0–3600000. A positive value enables bounded LRU caching. | +| `introspectionCacheMax` | 256, range 1–10000. | +| `maxIntrospectionRequests` | 16 in flight per instance, range 1–128. Extra requests fail closed with HTTP 503. | +| `introspectionAuthMethod` | `client_secret_basic`; explicitly select `client_secret_post` if required by the provider. | +| `clientId`, `clientIdEnv` | Supply one client ID or environment variable name in introspection mode. | +| `clientSecretEnv`, `clientSecretSec` | Required alternative secret references in introspection mode. The former names an environment variable. The latter is a file-backed `$sec` reference with `repo`, `key`, and optional `bucket`, `file`, `mainSecret` and `lockSecret` options. The entry must contain a string. | + +### JWT and JWKS rules + +The default RFC 9068 profile requires explicit `at+jwt` or `application/at+jwt` typing, exact issuer and audience, and the `sub`, `exp`, `iat`, `jti` and `client_id` claims. It also checks `nbf` when present. The explicit Keycloak profile accepts a JOSE type of `JWT` or `at+jwt` with the signed Keycloak `typ: "Bearer"` claim. The `typed` profile accepts the same JOSE types and requires the configured signed access-token discriminator. Ordinary ID-token claims such as `sub`, `aud` or a username cannot provide reliable separation. Configure the authorization server to emit the discriminator exclusively on access tokens. + +The Entra v2 profiles require a tenant-specific issuer URL ending in the tenant +GUID and `/v2.0`, the API application's GUID audience, RS256, and the matching +signed `tid`. The delegated profile requires a nonempty `scp`; the app profile +requires `idtyp: "app"` and nonempty `roles`. The profiles derive authorization +from `scp` and `roles` respectively. The signing key's issuer must match the +configured issuer exactly or match after substituting the configured tenant into +a `{tenantid}` key-issuer template. These profiles require separate instances +for delegated and application tokens and use tenant-specific discovery. +[Microsoft Entra token validation](https://learn.microsoft.com/en-us/entra/identity-platform/access-tokens) + +Every JWT needs a bounded `kid` and a permitted asymmetric algorithm. RSA public keys must have a modulus of 2048–8192 bits and EC keys must match the algorithm's curve. EdDSA is deferred. If multiple allowed algorithms could use a key, set its JWK `alg` explicitly. Duplicate compatible key IDs and conflicting key algorithm bindings invalidate the new key set. Embedded token keys, token-supplied key URLs, compression and critical extensions are rejected. Tokens containing a confirmation key (`cnf`) are rejected because bearer validation does not establish proof of possession. + +Public keys are cached per resource server and its trust policy. A recognized key in a fresh cache needs no outbound call. An unknown key can trigger a single coalesced refresh after the cooldown. The new key set replaces the old one as a unit. Rotate to a new `kid`, publish the new key before issuing tokens, and keep old keys during the provider's planned overlap. After expiry the server requires a successful refresh. Fresh trusted keys may still verify during a provider outage. JWT revocation takes effect when the token expires or its key is removed and the replacement set is loaded. + +### Introspection rules + +The credential is sent only to the configured or trusted discovered endpoint over verified TLS (apart from the explicit development exception). That endpoint must provide boolean `active: true`, a matching `aud`, a stable `sub` and a future `exp`. When the response includes `iss`, it must match. When it omits `iss`, the endpoint's trusted configuration supplies the issuer. `token_type`, when present, must be Bearer. The provider must restrict its results to access tokens for this resource. The endpoint must report sender binding when it can introspect sender-constrained credentials so the resource server can reject them. + +Positive cache entries contain a digest and verified context. Expiration is bounded by the token's expiry and the configured TTL. Enabling the cache delays recognition of revocation for up to that TTL. Failure results are never cached as successful authentication. JWT errors never trigger introspection. + +## Operational guidance + +Use HTTPS in production and explicitly configure the resource, issuer and any cross-origin validator endpoint. Discovery follows no redirects and never uses an unverified claim or JWT header to choose a network location. Use explicit endpoints with private identity services and allow the relevant destinations in network policy. A configured trusted issuer may live on a private network. Keep the listener private behind a TLS terminator when it serves HTTP, forward Authorization unchanged, and avoid logging credentials at the proxy. + +If a newly rotated key produces 401, check the exact issuer, audience, allowed algorithm, provider `kid` and discovery URL. Allow the unknown-key cooldown to elapse. A 503 indicates the validator could not obtain a trustworthy response. Check HTTPS trust, provider reachability, key or response limits and the introspection client credentials. For 403, inspect the scope challenge and compare the token's provider-issued permissions with the required scopes. + +The implementation covers resource-server behavior from RFC 6750, RFC 7517, RFC 7519, RFC 7662, RFC 8414, RFC 8725, RFC 9068 and RFC 9728. RFC 6749, RFC 8707 and RFC 9700 also guide the boundary with the OAuth client and authorization server. The implementation uses the selected parts of the [MCP 2026-07-28 authorization specification](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization). Provider configuration and client features determine which login flows interoperate. + +## DPoP for a single protected route + +To require ES256 DPoP proofs, configure the resource server with +`senderConstraint: { mode: "required", methods: ["dpop"] }`. Use +`mode: "optional"` to also accept ordinary bearer tokens. The verifier +checks the configured public resource URL, the request method, access-token +hash, key thumbprint and proof freshness. Set `internalPath` when a trusted +reverse proxy maps that public resource to a different fixed internal path. +The configuration accepts simple exact paths. Query strings are excluded +from proof matching. + +The default replay store lives in the resource process and requires a +server-generated nonce. Configure a shared adapter implementing atomic +`claim(namespace, key, expiresAt)` for a multi-instance deployment. +Use the same public resource configuration on each replica. + +A PostgreSQL-backed replay adapter is available as +`ow.server.oauth.postgresReplayStore({ url, user, passwordEnv, maxEntries })`. +Each verifier connects to the same database and uses the same canonical public +resource URL. Supply the adapter as `senderConstraint.replayStore` and close it +when the application shuts down. Deploy the database with verified TLS and +permissions to create and maintain the replay table and index. + +For certificate-bound tokens, use `senderConstraint: { mode: "required", +methods: ["mtls"] }`. Start the Java HTTPS listener with its dedicated mTLS +profile as the ninth argument to `ow.server.httpd.start`. The profile declares +`trustStore` and `trustStorePasswordEnv`. In oJob-common the `httpdStart` +shortcut accepts the same map as `tlsProfile`. The listener obtains the +certificate from its authenticated TLS session. Use direct TLS or TCP +passthrough to that listener. diff --git a/docs/ref/.odoc-reference.json b/docs/ref/.odoc-reference.json index 51d9a97c..c2196305 100644 --- a/docs/ref/.odoc-reference.json +++ b/docs/ref/.odoc-reference.json @@ -2,10 +2,10 @@ "generator": "genODocReference/v1", "complete": true, "counts": { - "files": 238, - "entries": 1924, - "variants": 1923, - "apis": 1913, + "files": 243, + "entries": 1949, + "variants": 1948, + "apis": 1933, "errors": 0 }, "files": [ @@ -101,6 +101,7 @@ "ow/server/ldap/index.md", "ow/server/locks/index.md", "ow/server/mcp/index.md", + "ow/server/oauth/index.md", "ow/server/openafserver/index.md", "ow/server/queue/index.md", "ow/server/rest/index.md", diff --git a/docs/ref/af-50312687/index.md b/docs/ref/af-50312687/index.md index cf7470a4..7810f88a 100644 --- a/docs/ref/af-50312687/index.md +++ b/docs/ref/af-50312687/index.md @@ -390,7 +390,7 @@ Example: `af.fromJSONC('{"port":8080, // HTTP\n}', {allowTrailingComma:true})`. Sources: -- js/openaf.js:13552 +- js/openaf.js:13827 @@ -426,7 +426,7 @@ Tries to convert aMap into a similiar XML strucuture returned as string. Note th Sources: -- js/openaf.js:14548 +- js/openaf.js:14823 @@ -475,7 +475,7 @@ Tries to parse aTOML into a javascript object Sources: -- js/openaf.js:13721 +- js/openaf.js:13996 @@ -511,7 +511,7 @@ Tries to convert a XML object into a javascript object. Tag attributes will be i Sources: -- js/openaf.js:14471 +- js/openaf.js:14746 @@ -695,7 +695,7 @@ Returns aValue if it is defined or aDefault otherwise. Sources: -- js/openaf.js:13757 +- js/openaf.js:14032 @@ -841,7 +841,7 @@ myOpen; // AF Class Sources: -- js/openaf.js:13165 +- js/openaf.js:13440 @@ -982,7 +982,7 @@ Original formatting and comments are not preserved. Output uses LF without trail Sources: -- js/openaf.js:13629 +- js/openaf.js:13904 @@ -994,7 +994,7 @@ Tries to convert aObj into a TOML string. Sources: -- js/openaf.js:13742 +- js/openaf.js:14017 diff --git a/docs/ref/af-9b31d4ed/index.md b/docs/ref/af-9b31d4ed/index.md index aca4dea8..9aeb5d84 100644 --- a/docs/ref/af-9b31d4ed/index.md +++ b/docs/ref/af-9b31d4ed/index.md @@ -12,7 +12,7 @@ Interactevly asks to enter a text and then uses af.encrypt to print to stdout th Sources: -- js/openaf.js:14604 +- js/openaf.js:14879 @@ -24,7 +24,7 @@ Calls endOpenAFAndStart to start a detached process and then end the current Ope Sources: -- js/openaf.js:14612 +- js/openaf.js:14887 @@ -36,7 +36,7 @@ Calls endOpenAFAndStartOpenAF to detach and start another OpenAF with current ar Sources: -- js/openaf.js:14625 +- js/openaf.js:14900 @@ -48,7 +48,7 @@ Tries to convert the provided aString into an object. The string might be JSON o Sources: -- js/openaf.js:14072 +- js/openaf.js:14347 @@ -60,7 +60,7 @@ Tries to convert aJavaArray into a native an array. Sources: -- js/openaf.js:13204 +- js/openaf.js:13479 @@ -72,7 +72,7 @@ Converts a nLinq chained command line string representation into a suitable map Sources: -- js/openaf.js:14094 +- js/openaf.js:14369 @@ -84,7 +84,7 @@ Converts a SLON (https://github.com/nmaguiar/slon) string representation into th Sources: -- js/openaf.js:14059 +- js/openaf.js:14334 @@ -96,7 +96,7 @@ Converts a SQL expression into an ASP map. Sources: -- js/openaf.js:14107 +- js/openaf.js:14382 @@ -108,7 +108,7 @@ Converts a SQL expression into a suitable map to be used with $from.query. Sources: -- js/openaf.js:14120 +- js/openaf.js:14395 @@ -120,7 +120,7 @@ Tries to parse aTOONStr into a javascript object. If alternative = true (or, if Sources: -- js/openaf.js:13511 +- js/openaf.js:13786 @@ -132,7 +132,7 @@ Tries to parse aYaml into a javascript map. Sources: -- js/openaf.js:13528 +- js/openaf.js:13803 @@ -144,7 +144,7 @@ Given anArrayOfBytesORString will try to detect which encode is used and returns Sources: -- js/openaf.js:13252 +- js/openaf.js:13527 @@ -156,7 +156,7 @@ Executes aFunction but if it throws an exception and the exception is a Java exc Sources: -- js/openaf.js:13235 +- js/openaf.js:13510 @@ -168,7 +168,7 @@ Protects the current execution against a exit instruction if shouldProtect = tru Sources: -- js/openaf.js:14637 +- js/openaf.js:14912 @@ -180,7 +180,7 @@ Sets the current terminal to be interactive (no echo, no buffering). Sources: -- js/openaf.js:13279 +- js/openaf.js:13554 @@ -192,7 +192,7 @@ Swaps the elements at anIndex1 and anIndex2 in anArray. Returns the new array wi Sources: -- js/openaf.js:13218 +- js/openaf.js:13493 @@ -204,7 +204,7 @@ Converts aObject map/array into SLON representation with ansi colors (see more i Sources: -- js/openaf.js:14048 +- js/openaf.js:14323 @@ -224,7 +224,7 @@ If `sanitize` is true, Java objects are stringified. Toggle color with `shouldCo Sources: -- js/openaf.js:13355 +- js/openaf.js:13630 @@ -236,7 +236,7 @@ Converts aObject map/array into SLON representation (see more in help for ow.for Sources: -- js/openaf.js:14037 +- js/openaf.js:14312 @@ -248,7 +248,7 @@ Tries to convert aObj into a TOON string. If alternative = true (or, if unset, d Sources: -- js/openaf.js:13494 +- js/openaf.js:13769 @@ -260,7 +260,7 @@ Tries to dump aJson into a YAML string. If multiDoc = true and aJson is an array Sources: -- js/openaf.js:13293 +- js/openaf.js:13568 @@ -272,5 +272,5 @@ Unsets the current terminal to be interactive (no echo, no buffering). Sources: -- js/openaf.js:13286 +- js/openaf.js:13561 diff --git a/docs/ref/all-apis.md b/docs/ref/all-apis.md index 76bfe068..66c4945f 100644 --- a/docs/ref/all-apis.md +++ b/docs/ref/all-apis.md @@ -119,11 +119,15 @@ - [$m4a](globals/index.md#api-m4a-6d59cb28) - [$mcp](globals/index.md#api-mcp-da09ecd4) - [$mcp.cancelRequest](mcp/index.md#api-mcp-cancelrequest-dd70c550) +- [$mcp.cancelTask](mcp/index.md#api-mcp-canceltask-0f9b9262) +- [$mcp.clearCache](mcp/index.md#api-mcp-clearcache-73570504) - [$mcp.continueRequest](mcp/index.md#api-mcp-continuerequest-c2909a8b) +- [$mcp.continueTask](mcp/index.md#api-mcp-continuetask-02bd9a56) - [$mcp.getAgent](mcp/index.md#api-mcp-getagent-534579a8) - [$mcp.getAppResource](mcp/index.md#api-mcp-getappresource-2bebde8d) - [$mcp.getCapabilities](mcp/index.md#api-mcp-getcapabilities-81846c9e) - [$mcp.getSkill](mcp/index.md#api-mcp-getskill-e3334154) +- [$mcp.getTask](mcp/index.md#api-mcp-gettask-a1c8d90d) - [$mcp.getToolUI](mcp/index.md#api-mcp-gettoolui-798f8673) - [$mcp.hasApps](mcp/index.md#api-mcp-hasapps-3e461f66) - [$mcp.listAgents](mcp/index.md#api-mcp-listagents-caaee617) @@ -144,6 +148,7 @@ - [$mcp.subscribeResource](mcp/index.md#api-mcp-subscriberesource-cbbf5f92) - [$mcp.toGptTools](mcp/index.md#api-mcp-togpttools-a770bc78) - [$mcp.unsubscribeResource](mcp/index.md#api-mcp-unsubscriberesource-2c7cfa4c) +- [$mcp.updateTask](mcp/index.md#api-mcp-updatetask-647559da) - [$openaf](globals/index.md#api-openaf-dc8677e1) - [$output](globals/index.md#api-output-9cea1be1) - [$path](globals/index.md#api-path-78ad0d4d) @@ -892,6 +897,7 @@ - [ow.ai.gpt.promptWithStats](ow/ai/gpt/index.md#api-ow-ai-gpt-promptwithstats-f4137da4) - [ow.ai.gpt.prototype.getEmbeddings](ow/ai/gpt/prototype/index.md#api-ow-ai-gpt-prototype-getembeddings-e9cfe872) - [ow.ai.gpt.prototype.getModelInfo](ow/ai/gpt/prototype/index.md#api-ow-ai-gpt-prototype-getmodelinfo-d37dbffb) +- [ow.ai.gpt.prototype.getModelLimits](ow/ai/gpt/prototype/index.md#api-ow-ai-gpt-prototype-getmodellimits-e1c5d481) - [ow.ai.gpt.prototype.getModelName](ow/ai/gpt/prototype/index.md#api-ow-ai-gpt-prototype-getmodelname-30fda71f) - [ow.ai.gpt.prototype.getModels](ow/ai/gpt/prototype/index.md#api-ow-ai-gpt-prototype-getmodels-10d9d1e8) - [ow.ai.gpt.prototype.getType](ow/ai/gpt/prototype/index.md#api-ow-ai-gpt-prototype-gettype-a77f2868) @@ -1682,6 +1688,7 @@ - [ow.server.httpd.mapRoutesWithLibs](ow/server/httpd/index.md#api-ow-server-httpd-maprouteswithlibs-2a37582f) - [ow.server.httpd.mapWithExistingRoutes](ow/server/httpd/index.md#api-ow-server-httpd-mapwithexistingroutes-cc72e253) - [ow.server.httpd.oauth2](ow/server/httpd/index.md#api-ow-server-httpd-oauth2-583f7769) +- [ow.server.httpd.oauthResourceServer](ow/server/httpd/index.md#api-ow-server-httpd-oauthresourceserver-db4b988d) - [ow.server.httpd.reply](ow/server/httpd/index.md#api-ow-server-httpd-reply-ba06a3e7) - [ow.server.httpd.replyBrowse](ow/server/httpd/index.md#api-ow-server-httpd-replybrowse-20f2869b) - [ow.server.httpd.replyFile](ow/server/httpd/index.md#api-ow-server-httpd-replyfile-c734dae2) @@ -1722,16 +1729,29 @@ - [ow.server.locks.whenUnLocked](ow/server/locks/index.md#api-ow-server-locks-whenunlocked-b579225e) - [ow.server.mcp](ow/server/index.md#api-ow-server-mcp-a9aa8cea) - [ow.server.mcp.createSkillCatalog](ow/server/mcp/index.md#api-ow-server-mcp-createskillcatalog-c7bd6861) +- [ow.server.mcp.decodeHeaderValue](ow/server/mcp/index.md#api-ow-server-mcp-decodeheadervalue-5fcff2cf) - [ow.server.mcp.discoverResult](ow/server/mcp/index.md#api-ow-server-mcp-discoverresult-e78d43db) +- [ow.server.mcp.encodeHeaderValue](ow/server/mcp/index.md#api-ow-server-mcp-encodeheadervalue-0009900e) - [ow.server.mcp.eraOf](ow/server/mcp/index.md#api-ow-server-mcp-eraof-0403f521) +- [ow.server.mcp.headerAnnotations](ow/server/mcp/index.md#api-ow-server-mcp-headerannotations-0f8cc98d) +- [ow.server.mcp.headerMismatchError](ow/server/mcp/index.md#api-ow-server-mcp-headermismatcherror-78877ed6) +- [ow.server.mcp.headerValue](ow/server/mcp/index.md#api-ow-server-mcp-headervalue-ae3a1ae1) - [ow.server.mcp.invalidParamsError](ow/server/mcp/index.md#api-ow-server-mcp-invalidparamserror-5d646fbc) - [ow.server.mcp.isModern](ow/server/mcp/index.md#api-ow-server-mcp-ismodern-21ec9d17) - [ow.server.mcp.metaClientCapabilities](ow/server/mcp/index.md#api-ow-server-mcp-metaclientcapabilities-4b843ffe) - [ow.server.mcp.metaProtocolVersion](ow/server/mcp/index.md#api-ow-server-mcp-metaprotocolversion-061c895a) +- [ow.server.mcp.nameSourceOf](ow/server/mcp/index.md#api-ow-server-mcp-namesourceof-209b15dc) +- [ow.server.mcp.normalizeCacheHints](ow/server/mcp/index.md#api-ow-server-mcp-normalizecachehints-79ba2cee) +- [ow.server.mcp.openWorkflows](ow/server/mcp/index.md#api-ow-server-mcp-openworkflows-2d6c1c42) +- [ow.server.mcp.paramHeaders](ow/server/mcp/index.md#api-ow-server-mcp-paramheaders-86f4215b) +- [ow.server.mcp.paramValueOf](ow/server/mcp/index.md#api-ow-server-mcp-paramvalueof-a88762f4) - [ow.server.mcp.requestMeta](ow/server/mcp/index.md#api-ow-server-mcp-requestmeta-6de509e9) +- [ow.server.mcp.toolsOf](ow/server/mcp/index.md#api-ow-server-mcp-toolsof-67037054) - [ow.server.mcp.unsupportedVersionError](ow/server/mcp/index.md#api-ow-server-mcp-unsupportedversionerror-2edc1a52) +- [ow.server.mcp.validateHeaders](ow/server/mcp/index.md#api-ow-server-mcp-validateheaders-122306c3) - [ow.server.mcp.wrapResult](ow/server/mcp/index.md#api-ow-server-mcp-wrapresult-a07ccfbf) - [ow.server.mcpStdio](ow/server/index.md#api-ow-server-mcpstdio-3c6f4175) +- [ow.server.oauth.client](ow/server/oauth/index.md#api-ow-server-oauth-client-4c04ea08) - [ow.server.openafServer.exec](ow/server/openafserver/index.md#api-ow-server-openafserver-exec-3dcec209) - [ow.server.openafServer.load](ow/server/openafserver/index.md#api-ow-server-openafserver-load-3759ce8f) - [ow.server.openafServer.start](ow/server/openafserver/index.md#api-ow-server-openafserver-start-7bdc7013) diff --git a/docs/ref/bottleneck/index.md b/docs/ref/bottleneck/index.md index a3fcef4f..c3ccaf77 100644 --- a/docs/ref/bottleneck/index.md +++ b/docs/ref/bottleneck/index.md @@ -12,7 +12,7 @@ Destroys any existing bottleneck definition. Sources: -- js/openaf.js:12414 +- js/openaf.js:12689 @@ -33,7 +33,7 @@ $bottleneck("myFunc").exec(2, 2); Sources: -- js/openaf.js:12424 +- js/openaf.js:12699 @@ -45,7 +45,7 @@ Creates a bottleneck to a maximum concurrent execution number of aMaxNumber. Sources: -- js/openaf.js:12407 +- js/openaf.js:12682 @@ -57,5 +57,5 @@ Creates a bottleneck holding the function execution for a max period of aMs. Sources: -- js/openaf.js:12400 +- js/openaf.js:12675 diff --git a/docs/ref/cache/index.md b/docs/ref/cache/index.md index 3c60691f..eaf0c22d 100644 --- a/docs/ref/cache/index.md +++ b/docs/ref/cache/index.md @@ -12,7 +12,7 @@ Changes the behaviour of the cache to either use the default value (aDefault) if Sources: -- js/openaf.js:12574 +- js/openaf.js:12849 @@ -24,7 +24,7 @@ Changes the behaviour of the cache to use the most popular entries and prefer to Sources: -- js/openaf.js:12563 +- js/openaf.js:12838 @@ -36,7 +36,7 @@ Uses a pre-existing channel (e.g. aChannelName) as the cache channel. Sources: -- js/openaf.js:12502 +- js/openaf.js:12777 @@ -58,7 +58,7 @@ $cache("users") Sources: -- js/openaf.js:12515 +- js/openaf.js:12790 @@ -70,7 +70,7 @@ Defines the aFunction use to get aKey. The returned object will be cached. Sources: -- js/openaf.js:12488 +- js/openaf.js:12763 @@ -96,7 +96,7 @@ $cache("persisted").fn(k => ...).chType("mvs", { file: "cache.db" }).create() Sources: -- js/openaf.js:12609 +- js/openaf.js:12884 @@ -108,7 +108,7 @@ Creates a mvs channel to hold the cache data in aFile. Shortcut for $cache.chTyp Sources: -- js/openaf.js:12550 +- js/openaf.js:12825 @@ -120,7 +120,7 @@ Establishes the max number of entries cached at any given point in time. Sources: -- js/openaf.js:12543 +- js/openaf.js:12818 @@ -132,5 +132,5 @@ Defines the time-to-live (aTTL) to consider a cached result as valid. Sources: -- js/openaf.js:12495 +- js/openaf.js:12770 diff --git a/docs/ref/csv-53bb9b0b/index.md b/docs/ref/csv-53bb9b0b/index.md index b149488a..3f32cd7e 100644 --- a/docs/ref/csv-53bb9b0b/index.md +++ b/docs/ref/csv-53bb9b0b/index.md @@ -12,7 +12,7 @@ Tries to wirte anArray to aFile. If withHeadersOrStreamFormat is provided, if an Sources: -- js/openaf.js:15387 +- js/openaf.js:15662 @@ -24,5 +24,5 @@ Tries to read a CSV file and convert it into an array. If withHeadersOrStreamFor Sources: -- js/openaf.js:15422 +- js/openaf.js:15697 diff --git a/docs/ref/entry/index.md b/docs/ref/entry/index.md index 4b431df1..3bb4d36b 100644 --- a/docs/ref/entry/index.md +++ b/docs/ref/entry/index.md @@ -8,6 +8,30 @@ ### $$.get(aPath) : Object +Given aObject it will try to parse the aPath and retrive the corresponding object under that path. Example: + + + +var a = { a : 1, b : { c: 2, d: [0, 1] } }; + + + +print($$(a).get("b.c")); // 2 + +sprint($$(a).get("b.d")); // [0, 1] + +print($$(a).get("b.d[0]")); // 0 + + + + + +Sources: + +- js/nlinq.js:1071 + +### $$.get(aPath) : Object + Given `aObject` it will try to parse the `aPath` and retrieve the corresponding object under that path. Example: ```javascript @@ -28,6 +52,30 @@ Sources: ### $$.getI(aPath) : Object +Given aObject it will try to parse the aPath (in a case-insensitive way) and retrive the corresponding object under that path. Example: + + + +var a = { a : 1, b : { c: 2, d: [0, 1] } }; + + + +print($$(a).getI("b.C")); // 2 + +sprint($$(a).getI("B.d")); // [0, 1] + +print($$(a).getI("B.D[0]")); // 0 + + + + + +Sources: + +- js/nlinq.js:1101 + +### $$.getI(aPath) : Object + Given `aObject` it will try to parse the `aPath` (in a case-insensitive way) and retrieve the corresponding object under that path. Example: ```javascript @@ -48,6 +96,26 @@ Sources: ### $$.set(aPath, aNewValue) : Object +Given aObject it will try to parse the aPath and set the corresponding object under that path to aNewValue. Example: + + + +var a = { a : 1, b : { c: 2, d: [0, 1] } }; + + + +sprint($$(a).set("b.c", 123)); // { a : 1, b : { c: 123, d: [0, 1] } } + + + + + +Sources: + +- js/nlinq.js:1143 + +### $$.set(aPath, aNewValue) : Object + Given `aObject` it will try to parse the `aPath` and set the corresponding object under that path to `aNewValue`. Example: ```javascript @@ -66,6 +134,26 @@ Sources: ### $$.unset(aPath) : Object +Given aObject it will try to parse the aPath and unset the corresponding object under that path. Example: + + + +var a = { a : 1, b : { c: 2, d: [0, 1] } }; + + + +sprint($$(a).set("b.c")); // { a : 1, b : { d: [0, 1] } } + + + + + +Sources: + +- js/nlinq.js:1177 + +### $$.unset(aPath) : Object + Given `aObject` it will try to parse the `aPath` and unset the corresponding object under that path. Example: ```javascript diff --git a/docs/ref/flock/index.md b/docs/ref/flock/index.md index 673afe7e..a5ca7b03 100644 --- a/docs/ref/flock/index.md +++ b/docs/ref/flock/index.md @@ -16,7 +16,7 @@ $flock(aLockFile).destroy() Sources: -- js/openaf.js:17266 +- js/openaf.js:17541 @@ -32,7 +32,7 @@ $flock(aLockFile).isLocalLocked() Sources: -- js/openaf.js:17232 +- js/openaf.js:17507 @@ -48,7 +48,7 @@ $flock(aLockFile).isLocked() Sources: -- js/openaf.js:17251 +- js/openaf.js:17526 @@ -64,7 +64,7 @@ $flock(aLockFile).lock() Sources: -- js/openaf.js:17185 +- js/openaf.js:17460 @@ -81,7 +81,7 @@ $flock(aLockFile).tryLock(() => { ... }) Sources: -- js/openaf.js:17291 +- js/openaf.js:17566 @@ -97,5 +97,5 @@ $flock(aLockFile).unlock() Sources: -- js/openaf.js:17208 +- js/openaf.js:17483 diff --git a/docs/ref/ftp-8009661d/index.md b/docs/ref/ftp-8009661d/index.md index 5457acf7..50883079 100644 --- a/docs/ref/ftp-8009661d/index.md +++ b/docs/ref/ftp-8009661d/index.md @@ -12,7 +12,7 @@ Builds an object to allow access through ftp/ftps. aMap should be a ftp/ftps str Sources: -- js/openaf.js:18336 +- js/openaf.js:18611 @@ -24,7 +24,7 @@ Sets the file transfer mode between binary and ascii. Sources: -- js/openaf.js:18426 +- js/openaf.js:18701 @@ -36,7 +36,7 @@ Changes the current remote working directory. Sources: -- js/openaf.js:18381 +- js/openaf.js:18656 @@ -48,7 +48,7 @@ Closes a remote host connection defined by aMap. Sources: -- js/openaf.js:18515 +- js/openaf.js:18790 @@ -60,7 +60,7 @@ Gets aSource filepath and stores it locally on aTarget from a remote host define Sources: -- js/openaf.js:18448 +- js/openaf.js:18723 @@ -72,7 +72,7 @@ Returns an array of maps with the listing of aRemotePath provided. Sources: -- js/openaf.js:18481 +- js/openaf.js:18756 @@ -84,7 +84,7 @@ Creates aDirectory via FTP/FTPS on a remote host defined by aMap. Sources: -- js/openaf.js:18437 +- js/openaf.js:18712 @@ -96,7 +96,7 @@ Sets the passive mode for the ftp/ftps connection. Sources: -- js/openaf.js:18415 +- js/openaf.js:18690 @@ -108,7 +108,7 @@ Puts aSource local filepath or Java stream and stores it remotely in aTarget on Sources: -- js/openaf.js:18459 +- js/openaf.js:18734 @@ -120,7 +120,7 @@ Returns the current remote working directory. Sources: -- js/openaf.js:18392 +- js/openaf.js:18667 @@ -132,7 +132,7 @@ Renames aSource filepath to aTarget filepath on a remote host defined by aMap. Sources: -- js/openaf.js:18470 +- js/openaf.js:18745 @@ -144,7 +144,7 @@ Remove aFilePath from a remote host defined by aMap. Sources: -- js/openaf.js:18493 +- js/openaf.js:18768 @@ -156,7 +156,7 @@ Removes a directory from a remote host defined by aMap. Sources: -- js/openaf.js:18504 +- js/openaf.js:18779 @@ -168,5 +168,5 @@ Sets aTimeout in ms for the ftp/ftps connection to a remote host defined by aMap Sources: -- js/openaf.js:18404 +- js/openaf.js:18679 diff --git a/docs/ref/globals/index.md b/docs/ref/globals/index.md index 9b640e09..c691dc50 100644 --- a/docs/ref/globals/index.md +++ b/docs/ref/globals/index.md @@ -28,7 +28,7 @@ $a2m(['a', 'b', 'c'], [1, 2, 3]) // { a: 1, b: 2, c: 3 } Sources: -- js/openaf.js:15594 +- js/openaf.js:15869 @@ -57,7 +57,7 @@ $a4m(a, "key"); Sources: -- js/openaf.js:15535 +- js/openaf.js:15810 @@ -91,7 +91,7 @@ Creates an atomic object of `aType` (defaults to long) to be get/set atomically Sources: -- js/openaf.js:17044 +- js/openaf.js:17319 @@ -103,7 +103,7 @@ Wrapper around the Java wait/notify mechanism. For the provided name will reture Sources: -- js/openaf.js:17439 +- js/openaf.js:17714 @@ -151,7 +151,7 @@ Inter-channel HTTP REST: Sources: -- js/openaf.js:16342 +- js/openaf.js:16617 @@ -200,7 +200,7 @@ Inter-channel HTTP REST: Sources: -- js/openaf.js:16227 +- js/openaf.js:16502 @@ -221,7 +221,7 @@ $csv().fromInString( $csv().fromInArray( io.listFiles(".").files ) ).toOutArray( Sources: -- js/openaf.js:18529 +- js/openaf.js:18804 @@ -233,7 +233,7 @@ Instantiates and returns a oPromise. If you provide aFunction, this aFunction wi Sources: -- js/openaf.js:17537 +- js/openaf.js:17812 @@ -245,7 +245,7 @@ Will call aAFunction with a function as argument that should be used to "send" v Sources: -- js/openaf.js:17478 +- js/openaf.js:17753 @@ -257,7 +257,7 @@ Returns an oPromise that will be resolved when all oPromise part of the anArray Sources: -- js/openaf.js:17569 +- js/openaf.js:17844 @@ -269,7 +269,7 @@ Returns an oPromise that will be resolved when any oPromise part of the anArray Sources: -- js/openaf.js:17580 +- js/openaf.js:17855 @@ -281,7 +281,7 @@ Equivalent to $do but using virtual threads (if available) to execute the aFunct Sources: -- js/openaf.js:17555 +- js/openaf.js:17830 @@ -293,7 +293,7 @@ Blocks until aPromise is fullfilled or rejected. Optionally you can specify aWai Sources: -- js/openaf.js:17591 +- js/openaf.js:17866 @@ -305,7 +305,7 @@ Prints the exception stack trace and the code where it was thrown. If rethrow is Sources: -- js/openaf.js:19099 +- js/openaf.js:19374 @@ -335,7 +335,7 @@ $f("%10.2f", 1.9) Sources: -- js/openaf.js:12304 +- js/openaf.js:12579 @@ -366,7 +366,7 @@ The response object will have the following methods: Sources: -- js/openaf.js:12122 +- js/openaf.js:12397 @@ -378,7 +378,7 @@ Tries to retrieve an array of function argument names for the provided search st Sources: -- js/openaf.js:15456 +- js/openaf.js:15731 @@ -396,7 +396,7 @@ $fnM("h.get", { aUrl: "https://openaf.io/release" }); Sources: -- js/openaf.js:15639 +- js/openaf.js:15914 @@ -415,7 +415,7 @@ $fnM2A(h.get, h, $fnDef4Help("HTTP.get"), { aUrl: "https://openaf.io/build", isB Sources: -- js/openaf.js:15617 +- js/openaf.js:15892 @@ -439,7 +439,7 @@ Equivalant to $f but number types are converted to Integer, Long, Double, Float Sources: -- js/openaf.js:12350 +- js/openaf.js:12625 @@ -451,7 +451,7 @@ Returns a value previously set with $set with aKey. Sources: -- js/openaf.js:18702 +- js/openaf.js:18977 @@ -502,7 +502,7 @@ The returned object also exposes helper methods to inspect vendor usage informat Sources: -- js/owrap.ai.js:5218 +- js/owrap.ai.js:5324 @@ -514,7 +514,7 @@ Shortcut to oJobRunJob and ow.oJob.runJob to execute aJob with args and returned Sources: -- js/openaf.js:13002 +- js/openaf.js:13277 @@ -604,7 +604,7 @@ localClient.destroy(); Sources: -- js/openaf.js:9419 +- js/openaf.js:9458 @@ -616,7 +616,7 @@ Shortcut for $gpt on the owrap.AI library. Sources: -- js/openaf.js:14264 +- js/openaf.js:14539 @@ -632,7 +632,7 @@ $m2a(['c', 'b', 'a'], { a: 1, b: 2, c: 3 }) // [ 3, 2, 1 ] Sources: -- js/openaf.js:15478 +- js/openaf.js:15753 @@ -660,7 +660,7 @@ $m4a(a, "key"); Sources: -- js/openaf.js:15565 +- js/openaf.js:15840 @@ -694,6 +694,8 @@ The `aOptions` parameter is a map with the following possible keys: - `shared` (boolean) : Enable shared JSON-RPC connections when possible (default: false) - `sse` (boolean) : When true, remote/http MCP requests expect Server-Sent Events responses carrying JSON-RPC payloads - `strict` (boolean) : Enable strict MCP protocol compliance (default: true) +- `cache` (boolean) : Opt-in response cache for server/discover, list and resources/read results honoring the server's `ttlMs`/`cacheScope` hints; "private" results are only reused for the same authorization context, and list_changed/resources/updated notifications invalidate them (default: false) +- `cacheMax` (number) : Maximum number of cached responses when `cache` is true (default: 500) - `clientInfo` (map) : Client information sent during initialization (default: {name: "OpenAF MCP Client", version: "1.0.0"}) - `blacklist` (array) : Optional array of MCP tool names to hide from listTools() and block in callTool() - `preFn` (function) : Function called before each tool execution with (toolName, toolArguments) @@ -738,8 +740,8 @@ The returned client object provides these methods: - `url(aURL)`: Set the URL and switch to remote type - `sh(aCommand)`: Set the command and switch to stdio type - `initialize(clientInfo)`: Initialize the MCP connection and exchange capabilities -- `listTools()`: Get list of available tools from the MCP server -- `callTool(toolName, toolArguments, toolOptions)`: Execute a specific tool with given arguments and optional per-call options +- `listTools()`: Get list of available tools from the MCP server (modern HTTP excludes tools with invalid `x-mcp-header` annotations) +- `callTool(toolName, toolArguments, toolOptions)`: Execute a specific tool with given arguments and optional per-call options (modern HTTP mirrors `x-mcp-header` arguments in `Mcp-Param-{Name}` headers) - `listPrompts()`: Get list of available prompts from the MCP server - `getPrompt(promptName, promptArguments)`: Get a specific prompt with given arguments - `toGptTools(aGptInstance, aToolNames)`: Add MCP tools to a `$gpt` instance @@ -757,6 +759,7 @@ The returned client object provides these methods: - `cancelRequest(id, reason)`: Best-effort protocol cancellation - `getToolUI(name)` / `getAppResource(name)` / `hasApps()`: MCP Apps metadata and ui:// resource retrieval, without executing HTML - `exec(method, params, execOptions)`: Low-level MCP/JSON-RPC; optional `onRequestId(id)` callback in execOptions +- `clearCache()`: Drop every response held by the opt-in response cache - `destroy()`: Stop the client and cleanup resources Register sampling, elicitation and roots before legacy initialize(); only configured capabilities are advertised. @@ -861,7 +864,7 @@ ojobClient.destroy(); Sources: -- js/openaf.js:10253 +- js/openaf.js:10309 @@ -873,7 +876,7 @@ Tries to start an external process running openaf (if aOpenAF is provided, as a Sources: -- js/openaf.js:12253 +- js/openaf.js:12528 @@ -968,7 +971,7 @@ $output("# Results\n\n**Complete**", { __format: "md" }); Sources: -- js/openaf.js:18746 +- js/openaf.js:19021 @@ -1086,7 +1089,7 @@ Executes aPythonCodeOrFile using a map aInput as variables in python and returns Sources: -- js/openaf.js:12216 +- js/openaf.js:12491 @@ -1098,7 +1101,7 @@ Runs a standalone script with callbacks and returns a process result including e Sources: -- js/openaf.js:12231 +- js/openaf.js:12506 @@ -1110,7 +1113,7 @@ Start python process on the background. Should be stopped with $pyStop. Sources: -- js/openaf.js:12205 +- js/openaf.js:12480 @@ -1122,7 +1125,7 @@ Stops the background python process started by $pyStart. Sources: -- js/openaf.js:12243 +- js/openaf.js:12518 @@ -1147,7 +1150,7 @@ If `anArray` is provided, it will be added to the queue using addAll. Sources: -- js/openaf.js:12736 +- js/openaf.js:13011 @@ -1159,7 +1162,7 @@ Tries to execute aFunction and return the corresponding returned result. If aNum Sources: -- js/openaf.js:17121 +- js/openaf.js:17396 @@ -1171,7 +1174,7 @@ Sets aValue with aKey so it can be retrieved with $get later. Sources: -- js/openaf.js:18685 +- js/openaf.js:18960 @@ -1187,7 +1190,7 @@ NOTE: In "h2" you can use the table _TMP for your queries. Sources: -- js/openaf.js:14276 +- js/openaf.js:14551 @@ -1222,7 +1225,7 @@ s.run(() => { Sources: -- js/openaf.js:12700 +- js/openaf.js:12975 @@ -1241,7 +1244,7 @@ $tb().timeout(500).stopWhen(aStopFunc).exec(); // Stops when aStopFunc is true. Sources: -- js/openaf.js:8790 +- js/openaf.js:8796 @@ -1253,7 +1256,7 @@ Returns a function that tries to execute aFunc and throws and exception if the r Sources: -- js/openaf.js:17104 +- js/openaf.js:17379 @@ -1265,7 +1268,7 @@ Unset a previously set value with aKey. Sources: -- js/openaf.js:18720 +- js/openaf.js:18995 @@ -1311,6 +1314,26 @@ Sources: Shortcut to facilitate argument pre-validation and promote defensive programming. + + +.default(aNewObject) : aObject + +Checks if aObject is defined and returns aObject. If it's not defined it will return aNewObject (the default value). + + + +$_(aMessage) : aObject + +Throws an exception with aMessage if aObject is not defined otherwise returns aObject. + +Sources: + +- js/nlinq.js:1249 + +### _$(aObject, anErrorMessagePrefix) + +Shortcut to facilitate argument pre-validation and promote defensive programming. + - `.default(aNewObject)`: `aObject` Checks if `aObject` is defined and returns `aObject`. If it's not defined it will return `aNewObject` (the default value). @@ -1366,7 +1389,7 @@ Same as _$ but if aValue is not defined and aPrefixMessage if defined it wil Sources: -- js/openaf.js:13111 +- js/openaf.js:13386 @@ -1494,7 +1517,7 @@ Stops for user interaction prompting aPrompt waiting for an entire line of chara Sources: -- js/openaf.js:15758 +- js/openaf.js:16033 @@ -1506,7 +1529,7 @@ Stops for user interaction prompting aPrompt waiting for a single character with Sources: -- js/openaf.js:15809 +- js/openaf.js:16084 @@ -1520,7 +1543,7 @@ Optional aUI is the console/write/ansi map returned by askConsole (or a compatib Sources: -- js/openaf.js:15883 +- js/openaf.js:16158 @@ -1532,7 +1555,7 @@ Stops for user interaction prompting aPrompt waiting for a single character to c Sources: -- js/openaf.js:16015 +- js/openaf.js:16290 @@ -1544,7 +1567,7 @@ Opens an independent controlling terminal (including with piped stdin/redirected Sources: -- js/openaf.js:15222 +- js/openaf.js:15497 @@ -1556,7 +1579,7 @@ An optional sixth aOptions forwards onIdle/pollInterval to the input helper. If Sources: -- js/openaf.js:15862 +- js/openaf.js:16137 @@ -1568,7 +1591,7 @@ Similar to ask but the return user input will be encrypted. If an empty string i Sources: -- js/openaf.js:15794 +- js/openaf.js:16069 @@ -1580,7 +1603,7 @@ Reads a single key from aUI (a map returned by askConsole or compatible, providi Sources: -- js/openaf.js:15247 +- js/openaf.js:15522 @@ -1592,7 +1615,7 @@ An optional fourth aOptions forwards onIdle/pollInterval to each line prompt. St Sources: -- js/openaf.js:15838 +- js/openaf.js:16113 @@ -1626,7 +1649,7 @@ An optional third aOptions forwards onIdle/pollInterval to each input helper. Sources: -- js/openaf.js:16165 +- js/openaf.js:16440 @@ -1722,7 +1745,7 @@ Tries to determine what is the latest available version for OpenAF. Compare it w Sources: -- js/openaf.js:8197 +- js/openaf.js:8203 @@ -1734,7 +1757,7 @@ Clears the interval with the provided uuid returned by setInterval. Sources: -- js/openaf.js:12848 +- js/openaf.js:13123 @@ -1866,7 +1889,7 @@ Creates a DB object instantiated with a file based H2 database for the aFile pro Sources: -- js/openaf.js:7964 +- js/openaf.js:7970 @@ -1878,7 +1901,7 @@ Creates a DB object instantiated with an in-memory database for the given name. Sources: -- js/openaf.js:7925 +- js/openaf.js:7931 @@ -1890,7 +1913,7 @@ Creates a DB object instantiated with a server based H2 database, on the provide Sources: -- js/openaf.js:7950 +- js/openaf.js:7956 @@ -1902,7 +1925,7 @@ Deletes the array element at anIndex from the provided anArray. Returns the new Sources: -- js/openaf.js:12876 +- js/openaf.js:13151 @@ -1986,7 +2009,7 @@ Tries to find a random open port on all network interfaces. Useful to start netw Sources: -- js/openaf.js:8257 +- js/openaf.js:8263 @@ -1998,7 +2021,7 @@ Given aObject it will traverse it and create an array where each element will ha Sources: -- js/openaf.js:8143 +- js/openaf.js:8149 @@ -2082,7 +2105,7 @@ Returns the current value of the operating system anEnvironmentVariable. Sources: -- js/openaf.js:13042 +- js/openaf.js:13317 @@ -2118,7 +2141,7 @@ Retrieves aResource, as anArrayOfBytes, from aZipFile. This resource can be inBy Sources: -- js/openaf.js:8606 +- js/openaf.js:8612 @@ -2298,7 +2321,7 @@ Ensures that aOPackName is installed. Optionally you can provide a minimal opack Sources: -- js/openaf.js:16999 +- js/openaf.js:17274 @@ -2346,7 +2369,7 @@ Sets the default use of NIO in ioStream* functions. It's overridden if the i Sources: -- js/openaf.js:8278 +- js/openaf.js:8284 @@ -2358,7 +2381,7 @@ Copies the contents of a Java aInputStream to a Java aOutputStream. The two stre Sources: -- js/openaf.js:8496 +- js/openaf.js:8502 @@ -2370,7 +2393,7 @@ Given a Java input or output stream helps to read strings by using aFunction wit Sources: -- js/openaf.js:8341 +- js/openaf.js:8347 @@ -2382,7 +2405,7 @@ Given a Java input or output stream helps to read an array of bytes by using aFu Sources: -- js/openaf.js:8521 +- js/openaf.js:8527 @@ -2394,7 +2417,7 @@ Given aStream will read the entire buffer and call aFunctionPerLine(withALine) p Sources: -- js/openaf.js:8368 +- js/openaf.js:8374 @@ -2406,7 +2429,7 @@ Given a Java input or output stream helps to write aString into the same. Option Sources: -- js/openaf.js:8290 +- js/openaf.js:8296 @@ -2418,7 +2441,7 @@ Given a Java input or output stream helps to write aArrayBytes into the same. Op Sources: -- js/openaf.js:8306 +- js/openaf.js:8312 @@ -2706,8 +2729,8 @@ Mimics, using Java, the javascript match function. Supported mods are "g", "m" a Sources: -- js/openaf.js:16894 -- js/openaf.js:16925 +- js/openaf.js:17169 +- js/openaf.js:17200 ### javaRegExp(text).matchAll(regExp, mods) : Array @@ -2715,7 +2738,7 @@ Mimics, using Java, the javascript match function with the "g" modifier. Support Sources: -- js/openaf.js:16912 +- js/openaf.js:17187 ### javaRegExp(text).replaceAll(regExp, mods) : Array @@ -2723,7 +2746,7 @@ Mimics, using Java, the javascript replace function with the "g" modifier. Suppo Sources: -- js/openaf.js:16940 +- js/openaf.js:17215 ### javaRegExp().preCompile(regExp, mods) @@ -2731,7 +2754,7 @@ Pre-compiles the regExp with the corresponding mods to be used by match, matchAl Sources: -- js/openaf.js:16951 +- js/openaf.js:17226 ### javaRegExp().removePreCompiled(regExp, mods) @@ -2739,7 +2762,7 @@ Removes a previously added pre compiled combination of regExp and mods. Sources: -- js/openaf.js:16961 +- js/openaf.js:17236 ### javaRegExp(text).split(regExp, mods) : Array @@ -2747,7 +2770,7 @@ Returns an array of the result of spliting text using the provided regExp and mo Sources: -- js/openaf.js:16970 +- js/openaf.js:17245 ### javaRegExp(text).test(regExp, mods) : boolean @@ -2755,7 +2778,7 @@ Mimics, using Java, the javascript RegExp test function. Supported mods are "g", Sources: -- js/openaf.js:16985 +- js/openaf.js:17260 @@ -2767,7 +2790,7 @@ Compiles an Oniguruma (Ruby syntax) pattern once. Options are ignoreCase, dotAll Sources: -- js/openaf.js:16785 +- js/openaf.js:17060 @@ -2815,7 +2838,7 @@ Loads the bundled Ajv v8 JSON Schema validator as global Ajv. OpenAF schema help Sources: -- js/openaf.js:7772 +- js/openaf.js:7778 @@ -2851,7 +2874,7 @@ Tries to load to a in-memory database, aDB object, previously created by the fun Sources: -- js/openaf.js:8001 +- js/openaf.js:8007 @@ -2863,7 +2886,7 @@ Loads the JsDiff javascript library into scope (check https://github.com/kpdecke Sources: -- js/openaf.js:7760 +- js/openaf.js:7766 @@ -2889,7 +2912,7 @@ See more in: http://fusejs.io/ Sources: -- js/openaf.js:7745 +- js/openaf.js:7751 @@ -2913,7 +2936,7 @@ See more documentation in: http://handlebarsjs.com/ Sources: -- js/openaf.js:7699 +- js/openaf.js:7705 @@ -2925,7 +2948,7 @@ Loads into scope the ODoc objects for documentation support. Sources: -- js/openaf.js:7798 +- js/openaf.js:7804 @@ -2937,7 +2960,7 @@ Loads the JS-YAML library. Sources: -- js/openaf.js:13054 +- js/openaf.js:13329 @@ -2963,7 +2986,7 @@ See more in https://lodash.com/docs Sources: -- js/openaf.js:7784 +- js/openaf.js:7790 @@ -2985,7 +3008,7 @@ sprint($get("myresult")) Sources: -- js/openaf.js:13075 +- js/openaf.js:13350 @@ -3009,7 +3032,7 @@ Loads the TOON image encoding/decoding library. Sources: -- js/openaf.js:13064 +- js/openaf.js:13339 @@ -3023,7 +3046,7 @@ See more in: http://underscorejs.org and https://lodash.com/docs Sources: -- js/openaf.js:7724 +- js/openaf.js:7730 @@ -3143,7 +3166,7 @@ Helper functions to map selectors (inputs for ow.obj.getPath) from anArray retur Sources: -- js/openaf.js:8094 +- js/openaf.js:8100 @@ -3195,7 +3218,7 @@ Builds a new Function handling any debug needs if necessary. Sources: -- js/openaf.js:13144 +- js/openaf.js:13419 @@ -3214,7 +3237,7 @@ newJavaArray(java.lang.Integer.TYPE, 2); Sources: -- js/openaf.js:8719 +- js/openaf.js:8725 @@ -3310,7 +3333,7 @@ Runs a oJob from aJson definition with the provided args (arguments). Optionally Sources: -- js/openaf.js:12944 +- js/openaf.js:13219 @@ -3322,7 +3345,7 @@ Runs a oJob aFile with the provided args (arguments). Optionally you can provide Sources: -- js/openaf.js:12904 +- js/openaf.js:13179 @@ -3334,7 +3357,7 @@ Runs a oJob aFile async with the provided args (arguments). Optionally you can p Sources: -- js/openaf.js:12929 +- js/openaf.js:13204 @@ -3346,7 +3369,7 @@ Shortcut for ow.oJob.runJob. Please see help for ow.oJob.runJob. Optionally you Sources: -- js/openaf.js:12965 +- js/openaf.js:13240 @@ -3358,7 +3381,7 @@ Creates an oPromise to run the same arguments for oJobRunJob thus executing the Sources: -- js/openaf.js:13028 +- js/openaf.js:13303 @@ -3383,7 +3406,7 @@ Custom Promise-like implementation. If you provide aFunction, this aFunction wil Sources: -- js/openaf.js:16479 +- js/openaf.js:16754 @@ -3431,7 +3454,7 @@ Tries to open anURL on the current OS desktop browser. Returns false if it's una Sources: -- js/openaf.js:8182 +- js/openaf.js:8188 @@ -3542,7 +3565,7 @@ Tries to persist a in-memory database, aDB object, previously created by the fun Sources: -- js/openaf.js:7990 +- js/openaf.js:7996 @@ -3813,7 +3836,7 @@ Generates an array with aCount of numbers starting at 1. Optionally you can prov Sources: -- js/openaf.js:12860 +- js/openaf.js:13135 @@ -3873,7 +3896,7 @@ Given aMapOfFiles mapping subject ids to JavaScript or Java source filenames, ea Sources: -- js/openaf.js:7891 +- js/openaf.js:7897 @@ -3885,7 +3908,7 @@ Given aMapOfFiles mapping subject ids to JavaScript or Java source filenames, ea Sources: -- js/openaf.js:7907 +- js/openaf.js:7913 @@ -3897,7 +3920,7 @@ Shortcut to ow.obj.searchArray. Sources: -- js/openaf.js:8132 +- js/openaf.js:8138 @@ -3909,7 +3932,7 @@ Searches the OpenAF ODoc help system for a specific term. Optionally you can pro Sources: -- js/openaf.js:7838 +- js/openaf.js:7844 @@ -3921,7 +3944,7 @@ Traverses aObject looking for key matches, ignoring case if useCase is true, of Sources: -- js/openaf.js:8051 +- js/openaf.js:8057 @@ -3933,7 +3956,7 @@ Traverse aObject looking for value matches, ignoring case if useCase is true, of Sources: -- js/openaf.js:8072 +- js/openaf.js:8078 @@ -3957,7 +3980,7 @@ Tries to execute aFunction every aPeriod milliseconds. Returns an id that can be Sources: -- js/openaf.js:12823 +- js/openaf.js:13098 @@ -3992,7 +4015,7 @@ Forces help (odoc) to be retrieved locally (if aBoolean is true) or reestablishe Sources: -- js/openaf.js:7822 +- js/openaf.js:7828 @@ -4014,7 +4037,7 @@ var id = setInterval(() => { print("Hello after 2 seconds"); clearInterval(id); Sources: -- js/openaf.js:12798 +- js/openaf.js:13073 @@ -4039,7 +4062,7 @@ An optional `exitCallback` receives the exit code. Sources: -- js/openaf.js:8224 +- js/openaf.js:8230 @@ -4107,7 +4130,7 @@ Instantiates and returns a H2 Console object openning a browser (if possible) to Sources: -- js/openaf.js:7976 +- js/openaf.js:7982 @@ -4131,7 +4154,7 @@ Tries to sort the first level map keys returning the rewritten map. If moreLeve Sources: -- js/openaf.js:15502 +- js/openaf.js:15777 @@ -4341,7 +4364,7 @@ Note: see threadBoxCtrlC as aStopFunction to stop executing on Ctrl-C Sources: -- js/openaf.js:8738 +- js/openaf.js:8744 @@ -4353,7 +4376,7 @@ Meant to be use as a stopFunction for threadBox will return true if Ctrl-C is de Sources: -- js/openaf.js:12774 +- js/openaf.js:13049 @@ -4437,7 +4460,7 @@ Converts the provided aString to a different anEncoding (by default UTF-8). Sources: -- js/openaf.js:8585 +- js/openaf.js:8591 @@ -4533,7 +4556,7 @@ Traverses aObject executing aFunction for every single element. The aFunction wi Sources: -- js/openaf.js:8012 +- js/openaf.js:8018 @@ -4569,7 +4592,7 @@ Converts the provided aString into UTF-8 encoding. Sources: -- js/openaf.js:8596 +- js/openaf.js:8602 diff --git a/docs/ref/gpt/index.md b/docs/ref/gpt/index.md index 40765d41..2aeb331e 100644 --- a/docs/ref/gpt/index.md +++ b/docs/ref/gpt/index.md @@ -12,7 +12,7 @@ Closes the current GPT model. Sources: -- js/owrap.ai.js:5841 +- js/owrap.ai.js:5948 @@ -24,7 +24,7 @@ Returns a stateless versioned decision envelope. Also exposed through $llm. See Sources: -- js/owrap.ai.js:5294 +- js/owrap.ai.js:5400 @@ -36,7 +36,7 @@ Returns { response, stats } from one stateless decision execution. Sources: -- js/owrap.ai.js:5308 +- js/owrap.ai.js:5414 @@ -48,7 +48,7 @@ Exports the current conversation in a standard portable format that can be impor Sources: -- js/owrap.ai.js:5792 +- js/owrap.ai.js:5899 @@ -60,7 +60,7 @@ Reports decision adapter support and runtime availability without a network requ Sources: -- js/owrap.ai.js:5315 +- js/owrap.ai.js:5421 @@ -72,7 +72,7 @@ Gets text embeddings for aInput (string or array of strings) using aEmbeddingMod Sources: -- js/owrap.ai.js:5769 +- js/owrap.ai.js:5876 @@ -84,7 +84,7 @@ Gets text embeddings for aInput (string or array of strings) using aEmbeddingMod Sources: -- js/owrap.ai.js:5780 +- js/owrap.ai.js:5887 @@ -96,7 +96,7 @@ Returns the latest usage statistics reported by the underlying LLM vendor for th Sources: -- js/owrap.ai.js:5336 +- js/owrap.ai.js:5443 @@ -108,7 +108,7 @@ Returns the model information for aModelId (defaults to the current configured m Sources: -- js/owrap.ai.js:5327 +- js/owrap.ai.js:5433 @@ -120,7 +120,7 @@ Imports a portable conversation previously exported via exportConversation() int Sources: -- js/owrap.ai.js:5799 +- js/owrap.ai.js:5906 @@ -132,7 +132,7 @@ Tries to prompt aPrompt (a string or an array of strings) and aModel (defaults t Sources: -- js/owrap.ai.js:5536 +- js/owrap.ai.js:5643 @@ -157,7 +157,7 @@ Only supported by the `openai` provider. Sources: -- js/owrap.ai.js:5806 +- js/owrap.ai.js:5913 @@ -171,7 +171,7 @@ aResponseSchema should be a map with: name (string), description (string), schem Sources: -- js/owrap.ai.js:5830 +- js/owrap.ai.js:5937 @@ -183,7 +183,7 @@ Alias for $gpt.getLastStats. Sources: -- js/owrap.ai.js:5343 +- js/owrap.ai.js:5450 @@ -195,7 +195,7 @@ Tries to prompt aPrompt (a string or an array of strings) and aModel (defaults t Sources: -- js/owrap.ai.js:5360 +- js/owrap.ai.js:5467 @@ -207,7 +207,7 @@ Tries to prompt aPrompt (a string or an array of strings) and aModel (defaults t Sources: -- js/owrap.ai.js:5482 +- js/owrap.ai.js:5589 @@ -219,7 +219,7 @@ Tries to prompt aPrompt (a string or an array of strings) with aImage (a file pa Sources: -- js/owrap.ai.js:5454 +- js/owrap.ai.js:5561 @@ -231,7 +231,7 @@ Tries to prompt aPrompt and aModel (defaults to the one provided on the construc Sources: -- js/owrap.ai.js:5463 +- js/owrap.ai.js:5570 @@ -243,7 +243,7 @@ Tries to prompt aPrompt (a string or an array of strings) and aModel (defaults t Sources: -- js/owrap.ai.js:5509 +- js/owrap.ai.js:5616 @@ -255,7 +255,7 @@ Tries to prompt aPrompt (a string or an array of strings) and aModel (defaults t Sources: -- js/owrap.ai.js:5518 +- js/owrap.ai.js:5625 @@ -267,7 +267,7 @@ Tries to prompt aPrompt (a string or an array of strings) and aModel (defaults t Sources: -- js/owrap.ai.js:5527 +- js/owrap.ai.js:5634 @@ -279,7 +279,7 @@ Tries to prompt aPrompt (a string or an array of strings) and aModel (defaults t Sources: -- js/owrap.ai.js:5473 +- js/owrap.ai.js:5580 @@ -291,7 +291,7 @@ Tries to prompt aPrompt (a string or an array of strings) and aModel (defaults t Sources: -- js/owrap.ai.js:5500 +- js/owrap.ai.js:5607 @@ -303,7 +303,7 @@ Tries to prompt aPrompt (a string or an array of strings) and aModel (defaults t Sources: -- js/owrap.ai.js:5491 +- js/owrap.ai.js:5598 @@ -315,7 +315,7 @@ Executes a streaming prompt, calling aOnDelta for each streamed chunk, and retur Sources: -- js/owrap.ai.js:5369 +- js/owrap.ai.js:5476 @@ -327,7 +327,7 @@ Executes a streaming JSON prompt and returns the parsed JSON response. Sources: -- js/owrap.ai.js:5407 +- js/owrap.ai.js:5514 @@ -339,7 +339,7 @@ Executes a streaming JSON prompt and returns the parsed response with statistics Sources: -- js/owrap.ai.js:5416 +- js/owrap.ai.js:5523 @@ -351,7 +351,7 @@ Executes a streaming JSON prompt and returns the raw response, parsed response, Sources: -- js/owrap.ai.js:5425 +- js/owrap.ai.js:5532 @@ -363,7 +363,7 @@ Executes a streaming prompt and returns a map with the aggregated response and s Sources: -- js/owrap.ai.js:5387 +- js/owrap.ai.js:5494 @@ -375,7 +375,7 @@ Executes prompt and returns a map with the response and the reported statistics Sources: -- js/owrap.ai.js:5434 +- js/owrap.ai.js:5541 @@ -387,7 +387,7 @@ Returns execution metadata and the raw provider payload from one stateless reque Sources: -- js/owrap.ai.js:5301 +- js/owrap.ai.js:5407 @@ -399,7 +399,7 @@ Executes a streaming prompt and returns the raw streaming payloads together with Sources: -- js/owrap.ai.js:5378 +- js/owrap.ai.js:5485 @@ -411,7 +411,7 @@ Executes a streaming prompt and returns the raw streaming payloads, aggregated r Sources: -- js/owrap.ai.js:5397 +- js/owrap.ai.js:5504 @@ -423,7 +423,7 @@ Executes the underlying rawPrompt call and returns the raw response together wit Sources: -- js/owrap.ai.js:5444 +- js/owrap.ai.js:5551 @@ -435,7 +435,7 @@ Sets the debug channel name to aChName. When defined, creates an OpenAF channel Sources: -- js/owrap.ai.js:5350 +- js/owrap.ai.js:5457 @@ -447,7 +447,7 @@ Adds a prompt system aPrompt (a string or an array of strings) and aModel (defau Sources: -- js/owrap.ai.js:5545 +- js/owrap.ai.js:5652 @@ -474,7 +474,7 @@ var response = gpt.prompt("What's the weather in Lisbon?"); // GPT can call the Sources: -- js/owrap.ai.js:5655 +- js/owrap.ai.js:5762 @@ -486,7 +486,7 @@ Adds a context to the current conversation. Sources: -- js/owrap.ai.js:5563 +- js/owrap.ai.js:5670 @@ -498,7 +498,7 @@ Adds a JSON path aPath to be asserted with anAssert (e.g. isArray or isMap). Sources: -- js/owrap.ai.js:5752 +- js/owrap.ai.js:5859 @@ -524,7 +524,7 @@ var response = gpt.prompt("Read the file /tmp/example.txt"); Sources: -- js/owrap.ai.js:5587 +- js/owrap.ai.js:5694 @@ -536,7 +536,7 @@ Adds aDBName with aTableDefs to be used with promptSQL. Sources: -- js/owrap.ai.js:5737 +- js/owrap.ai.js:5844 @@ -548,5 +548,5 @@ Sets a tool with aName, aDesc (description), aParams (a json schema) and aFn (a Sources: -- js/owrap.ai.js:5577 +- js/owrap.ai.js:5684 diff --git a/docs/ref/httpd/index.md b/docs/ref/httpd/index.md index 30ea00d0..6dd8a39f 100644 --- a/docs/ref/httpd/index.md +++ b/docs/ref/httpd/index.md @@ -61,7 +61,7 @@ s.addWS("/websocket"); // makes it available at ws://127.0.0.1:8091/websocket Sources: -- src/openaf/plugins/HTTPServer.java:377 +- src/openaf/plugins/HTTPServer.java:393 @@ -79,7 +79,7 @@ hs.add("/example", function(req) { return hs.replyOKText(beautifier(req)); }); Sources: -- src/openaf/plugins/HTTPServer.java:824 +- src/openaf/plugins/HTTPServer.java:868 @@ -91,7 +91,7 @@ Adds a echo responder to the provided URI. Useful for debugging http requests to Sources: -- src/openaf/plugins/HTTPServer.java:712 +- src/openaf/plugins/HTTPServer.java:756 @@ -103,7 +103,7 @@ Adds a responder to the provided URI that provides a very basic file browse to t Sources: -- src/openaf/plugins/HTTPServer.java:935 +- src/openaf/plugins/HTTPServer.java:979 @@ -115,7 +115,7 @@ Provides a simple session track mechanism adding the session ID provided. See HT Sources: -- src/openaf/plugins/HTTPServer.java:1308 +- src/openaf/plugins/HTTPServer.java:1352 @@ -127,7 +127,7 @@ Adds a status responder to the provided URI. Useful for debugging proposes Sources: -- src/openaf/plugins/HTTPServer.java:775 +- src/openaf/plugins/HTTPServer.java:819 @@ -163,7 +163,7 @@ hs.addXDTServer('/xdt', Sources: -- src/openaf/plugins/HTTPServer.java:1059 +- src/openaf/plugins/HTTPServer.java:1103 @@ -175,7 +175,7 @@ Removes the provided session ID data from memory. Sources: -- src/openaf/plugins/HTTPServer.java:1341 +- src/openaf/plugins/HTTPServer.java:1385 @@ -187,7 +187,7 @@ Returns the implementation used by the HTTP server instance. Possible values are Sources: -- src/openaf/plugins/HTTPServer.java:606 +- src/openaf/plugins/HTTPServer.java:650 @@ -199,7 +199,7 @@ Returns the listen port of the HTTP server instance. Sources: -- src/openaf/plugins/HTTPServer.java:624 +- src/openaf/plugins/HTTPServer.java:668 @@ -211,7 +211,7 @@ Retrieves the current data stored for the provided session ID. Sources: -- src/openaf/plugins/HTTPServer.java:1319 +- src/openaf/plugins/HTTPServer.java:1363 @@ -223,7 +223,7 @@ Returns true if the provided session ID was add to memory. False otherwise. Sources: -- src/openaf/plugins/HTTPServer.java:1352 +- src/openaf/plugins/HTTPServer.java:1396 @@ -235,7 +235,7 @@ Builds a response object suitable to provide a reply to a HTTP request for a fun Sources: -- src/openaf/plugins/HTTPServer.java:1228 +- src/openaf/plugins/HTTPServer.java:1272 @@ -247,7 +247,7 @@ Builds a response object suitable to provide a reply to a HTTP request for a fun Sources: -- src/openaf/plugins/HTTPServer.java:1253 +- src/openaf/plugins/HTTPServer.java:1297 @@ -259,7 +259,7 @@ Builds a response object suitable to provide a reply to a HTTP request for a fun Sources: -- src/openaf/plugins/HTTPServer.java:1206 +- src/openaf/plugins/HTTPServer.java:1250 @@ -271,7 +271,7 @@ Builds a response object suitable to provide a reply to a HTTP request for a fun Sources: -- src/openaf/plugins/HTTPServer.java:1162 +- src/openaf/plugins/HTTPServer.java:1206 @@ -283,7 +283,7 @@ Builds a response object suitable to provide a reply to a HTTP request for a fun Sources: -- src/openaf/plugins/HTTPServer.java:1184 +- src/openaf/plugins/HTTPServer.java:1228 @@ -295,7 +295,7 @@ Builds a response object suitable to provide a reply to a HTTP request for a fun Sources: -- src/openaf/plugins/HTTPServer.java:1118 +- src/openaf/plugins/HTTPServer.java:1162 @@ -307,7 +307,7 @@ Builds a response object suitable to provide a reply to a HTTP request for a fun Sources: -- src/openaf/plugins/HTTPServer.java:1140 +- src/openaf/plugins/HTTPServer.java:1184 @@ -319,7 +319,7 @@ Builds a response object suitable to provide a reply to a HTTP request for a fun Sources: -- src/openaf/plugins/HTTPServer.java:1281 +- src/openaf/plugins/HTTPServer.java:1325 @@ -337,7 +337,7 @@ hs.setDefault("/echo"); Sources: -- src/openaf/plugins/HTTPServer.java:875 +- src/openaf/plugins/HTTPServer.java:919 @@ -349,7 +349,7 @@ Sets the positive maximum inbound body size for Java-mode custom and echo routes Sources: -- src/openaf/plugins/HTTPServer.java:99 +- src/openaf/plugins/HTTPServer.java:109 @@ -361,7 +361,7 @@ Sets the provided anObject as the session data for the session ID provided. Sources: -- src/openaf/plugins/HTTPServer.java:1330 +- src/openaf/plugins/HTTPServer.java:1374 @@ -373,5 +373,5 @@ Tries to stop the currently running HTTP server instance. Sources: -- src/openaf/plugins/HTTPServer.java:635 +- src/openaf/plugins/HTTPServer.java:679 diff --git a/docs/ref/index.md b/docs/ref/index.md index b2e89d0c..ee5b891c 100644 --- a/docs/ref/index.md +++ b/docs/ref/index.md @@ -47,4 +47,4 @@ - [ow](ow/index.md) - [pods](pods/index.md) -1913 APIs; 1924 entries from 238 source files. +1933 APIs; 1949 entries from 243 source files. diff --git a/docs/ref/io/index.md b/docs/ref/io/index.md index 5a5bdeef..fdc8526a 100644 --- a/docs/ref/io/index.md +++ b/docs/ref/io/index.md @@ -24,7 +24,7 @@ Copies an exclusive byte range discovered by io.scanJSON using bounded buffers. Sources: -- js/openaf.js:15167 +- js/openaf.js:15442 @@ -72,7 +72,7 @@ Copies the JSON value at a literal key/index path to a borrowed output stream. A Sources: -- js/openaf.js:15193 +- js/openaf.js:15468 @@ -210,7 +210,7 @@ Tries to determine if the provided aFile is a binary or text file by checking th Sources: -- js/openaf.js:15307 +- js/openaf.js:15582 @@ -246,7 +246,7 @@ Given aTARfile (or output stream (with isGzip = true/false)) will return an arra Sources: -- js/openaf.js:14871 +- js/openaf.js:15146 @@ -258,7 +258,7 @@ Compresses anInput using LZ4 compression and returns the compressed bytes. Sources: -- js/openaf.js:13942 +- js/openaf.js:14217 @@ -306,7 +306,7 @@ $doWait(p); Sources: -- js/openaf.js:15331 +- js/openaf.js:15606 @@ -318,7 +318,7 @@ Starts a wait on stdin calling aFunc everytime a character is sent to stdin. The Sources: -- js/openaf.js:14679 +- js/openaf.js:14954 @@ -330,7 +330,7 @@ Starts a wait on stdin calling aFunc everytime a line is sent to stdin. The wait Sources: -- js/openaf.js:14662 +- js/openaf.js:14937 @@ -394,7 +394,7 @@ Tries to read aFile in read-only mode (even if being used by another process) an Sources: -- js/openaf.js:14695 +- js/openaf.js:14970 @@ -426,7 +426,7 @@ Tries to read aJSONFile into a javascript object. Sources: -- js/openaf.js:14925 +- js/openaf.js:15200 @@ -439,7 +439,7 @@ Reads and parses JSONC using `af.fromJSONC`. Options include `allowTrailingComma Sources: -- js/openaf.js:13695 +- js/openaf.js:13970 @@ -451,7 +451,7 @@ Reads aFile as a LZ4 compressed stream and returns the InputStream to read from. Sources: -- js/openaf.js:14023 +- js/openaf.js:14298 @@ -497,7 +497,7 @@ Given aTARFile (or stream) will call aFunc(tion) with the corresponding Java TAR Sources: -- js/openaf.js:14751 +- js/openaf.js:15026 @@ -509,7 +509,7 @@ Given aTARFile (or stream) will try to retrieve aFilePath and return the corresp Sources: -- js/openaf.js:14709 +- js/openaf.js:14984 @@ -521,7 +521,7 @@ Given aTARFile (or stream) will try to retrieve aFilePath and call aFunc(tion) w Sources: -- js/openaf.js:14731 +- js/openaf.js:15006 @@ -533,7 +533,7 @@ Tries to read aFile and parse it as TOML into a javascript object. Sources: -- js/openaf.js:13732 +- js/openaf.js:14007 @@ -559,7 +559,7 @@ Tries to read aYAMLFile into a javascript object. Sources: -- js/openaf.js:14912 +- js/openaf.js:15187 @@ -571,7 +571,7 @@ Reads a top-level JSON array from a filename or a Java input stream, retaining o Sources: -- js/openaf.js:14988 +- js/openaf.js:15263 @@ -583,7 +583,7 @@ Opens aNDJSONFile (a newline delimited JSON) (a filename or an input stream) as Sources: -- js/openaf.js:14964 +- js/openaf.js:15239 @@ -605,7 +605,7 @@ var amap = io.readStreamJSON("someFile.har", Sources: -- js/openaf.js:15019 +- js/openaf.js:15294 @@ -641,7 +641,7 @@ Visits UTF-8 JSON without materializing values. Events have phase (value/end), p Sources: -- js/openaf.js:15087 +- js/openaf.js:15362 @@ -653,7 +653,7 @@ Decompresses anInput using LZ4 compression and returns the decompressed map or s Sources: -- js/openaf.js:13987 +- js/openaf.js:14262 @@ -670,7 +670,7 @@ The `logFn` will receive the following object: Sources: -- js/openaf.js:13775 +- js/openaf.js:14050 @@ -738,7 +738,7 @@ Tries to write a javascript aObj into a aJSONFile with an optional aSpace. Sources: -- js/openaf.js:14941 +- js/openaf.js:15216 @@ -752,7 +752,7 @@ See `af.toJSONC` for comment-map examples. I/O errors propagate. Sources: -- js/openaf.js:13707 +- js/openaf.js:13982 @@ -764,7 +764,7 @@ Reads aFile as a LZ4 compressed file and returns the InputStream to read from. T Sources: -- js/openaf.js:13973 +- js/openaf.js:14248 @@ -808,7 +808,7 @@ Given aTARfile (or output stream (with isGzip = true/false)) will call aFunc wit Sources: -- js/openaf.js:14789 +- js/openaf.js:15064 @@ -820,7 +820,7 @@ Given aTARfile (or output stream (with isGzip = true/false)) will write aArrayBy Sources: -- js/openaf.js:14828 +- js/openaf.js:15103 @@ -832,7 +832,7 @@ Given aTARfile (or output stream (with isGzip = true/false)) will call aFunc(tio Sources: -- js/openaf.js:14840 +- js/openaf.js:15115 @@ -844,7 +844,7 @@ Tries to write aObj into aFile as TOML. Sources: -- js/openaf.js:13765 +- js/openaf.js:14040 @@ -868,7 +868,7 @@ Tries to write a javascript aObj into a aYAMLFile. If multiDoc = true and aJson Sources: -- js/openaf.js:14934 +- js/openaf.js:15209 @@ -880,7 +880,7 @@ Writes aObj into a single line on aNDJSONFile (newline delimited JSON) (or an ou Sources: -- js/openaf.js:14949 +- js/openaf.js:15224 @@ -897,5 +897,5 @@ The `logFn` will receive the following object: Sources: -- js/openaf.js:13888 +- js/openaf.js:14163 diff --git a/docs/ref/jsonrpc/index.md b/docs/ref/jsonrpc/index.md index be2e8fab..9c390c2d 100644 --- a/docs/ref/jsonrpc/index.md +++ b/docs/ref/jsonrpc/index.md @@ -17,5 +17,5 @@ Stdio uses two bounded callback workers; HTTP POST SSE dispatches on its respons Sources: -- js/openaf.js:10118 +- js/openaf.js:10173 diff --git a/docs/ref/lock/index.md b/docs/ref/lock/index.md index 91326444..00e5c672 100644 --- a/docs/ref/lock/index.md +++ b/docs/ref/lock/index.md @@ -16,7 +16,7 @@ $lock(aLockName).destroy() Sources: -- js/openaf.js:17374 +- js/openaf.js:17649 @@ -32,7 +32,7 @@ $lock(aLockName).isLocked() Sources: -- js/openaf.js:17361 +- js/openaf.js:17636 @@ -48,7 +48,7 @@ $lock(aLockName).lock() Sources: -- js/openaf.js:17335 +- js/openaf.js:17610 @@ -65,7 +65,7 @@ $lock(aLockName).tryLock(() => { ... }) Sources: -- js/openaf.js:17391 +- js/openaf.js:17666 @@ -81,5 +81,5 @@ $lock(aLockName).unlock() Sources: -- js/openaf.js:17348 +- js/openaf.js:17623 diff --git a/docs/ref/mcp/index.md b/docs/ref/mcp/index.md index 986a7ac1..107c034a 100644 --- a/docs/ref/mcp/index.md +++ b/docs/ref/mcp/index.md @@ -12,7 +12,31 @@ Sends best-effort notifications/cancelled. Does not roll back remote side effect Sources: -- js/openaf.js:11835 +- js/openaf.js:12077 + + + +## $mcp.cancelTask + +### $mcp.cancelTask(taskId) : Map + +Requests cooperative cancellation of an MCP task. + +Sources: + +- js/openaf.js:11938 + + + +## $mcp.clearCache + +### $mcp.clearCache() : Map + +Drops every response held by the opt-in response cache (aOptions.cache). Returns the client. + +Sources: + +- js/openaf.js:12383 @@ -24,7 +48,19 @@ Explicitly continues one modern input_required round using registered handlers, Sources: -- js/openaf.js:11711 +- js/openaf.js:11957 + + + +## $mcp.continueTask + +### $mcp.continueTask(task) : Map + +Explicitly invokes the registered handlers for a paused task, then sends their answers. + +Sources: + +- js/openaf.js:11945 @@ -48,7 +84,7 @@ print(agent); Sources: -- js/openaf.js:11931 +- js/openaf.js:12187 @@ -60,7 +96,7 @@ Reads a tool's ui:// App resource, retaining the complete envelope. Never evalua Sources: -- js/openaf.js:11814 +- js/openaf.js:12056 @@ -72,7 +108,7 @@ Returns a copy of the negotiated server capabilities. Sources: -- js/openaf.js:11593 +- js/openaf.js:11807 @@ -84,7 +120,19 @@ Retrieves skill metadata by its SKILL.md resource URI. Use readResource to fetch Sources: -- js/openaf.js:11747 +- js/openaf.js:11989 + + + +## $mcp.getTask + +### $mcp.getTask(taskId) : Map + +Polls an MCP task. Pass tasks: true when constructing the client to opt into task creation. + +Sources: + +- js/openaf.js:11924 @@ -96,7 +144,7 @@ Returns a copy of a discovered tool's `_meta.ui` or undefined. Sources: -- js/openaf.js:11802 +- js/openaf.js:12044 @@ -108,7 +156,7 @@ Reports whether discovered tools reference UI resources; does not imply a browse Sources: -- js/openaf.js:11825 +- js/openaf.js:12067 @@ -131,7 +179,7 @@ print(agents.agents); Sources: -- js/openaf.js:11906 +- js/openaf.js:12162 @@ -143,7 +191,7 @@ Collects resourceTemplates pages. URI template expansion is the caller's respons Sources: -- js/openaf.js:11754 +- js/openaf.js:11996 @@ -155,7 +203,7 @@ Collects resource pages with metadata. Requires advertised resources capability; Sources: -- js/openaf.js:11733 +- js/openaf.js:11975 @@ -167,7 +215,7 @@ Collects skill entries from a server that advertises the Skills extension. Sources: -- js/openaf.js:11740 +- js/openaf.js:11982 @@ -179,7 +227,7 @@ Removes the registered notification callback. Sources: -- js/openaf.js:11650 +- js/openaf.js:11864 @@ -191,7 +239,7 @@ Removes the inbound handler and its optional capability from future requests. Sources: -- js/openaf.js:11628 +- js/openaf.js:11842 @@ -203,7 +251,7 @@ Opts into elicitation; modes defaults to `{form:{}}`. URL mode requires version Sources: -- js/openaf.js:11672 +- js/openaf.js:11886 @@ -215,7 +263,7 @@ Registers one event callback `(params, message)` per method on a dedicated conne Sources: -- js/openaf.js:11640 +- js/openaf.js:11854 @@ -227,7 +275,7 @@ Registers a synchronous inbound handler `(params, request)` on a dedicated conne Sources: -- js/openaf.js:11618 +- js/openaf.js:11832 @@ -239,7 +287,7 @@ Opts into basic sampling using a synchronous application handler. Register befor Sources: -- js/openaf.js:11657 +- js/openaf.js:11871 @@ -251,7 +299,7 @@ Reads an absolute resource URI through MCP, retaining all text/blob contents, MI Sources: -- js/openaf.js:11761 +- js/openaf.js:12003 @@ -281,7 +329,7 @@ print(response.content[0].text); Sources: -- js/openaf.js:11958 +- js/openaf.js:12214 @@ -293,7 +341,7 @@ Sets explicit absolute file URI roots and registers roots/list. An empty array s Sources: -- js/openaf.js:11690 +- js/openaf.js:11904 @@ -305,7 +353,7 @@ Opens one opt-in legacy HTTP GET event stream on an initialized dedicated client Sources: -- js/openaf.js:11600 +- js/openaf.js:11814 @@ -317,7 +365,7 @@ Closes the optional HTTP event stream; returns the client. Sources: -- js/openaf.js:11611 +- js/openaf.js:11825 @@ -329,7 +377,7 @@ Subscribes on a dedicated legacy transport with resources.subscribe. Callback re Sources: -- js/openaf.js:11768 +- js/openaf.js:12010 @@ -356,7 +404,7 @@ var response = gpt.prompt("Read the file /tmp/example.txt"); Sources: -- js/openaf.js:12009 +- js/openaf.js:12265 @@ -368,5 +416,17 @@ Unsubscribes and removes its callback after a successful response. Sources: -- js/openaf.js:11788 +- js/openaf.js:12030 + + + +## $mcp.updateTask + +### $mcp.updateTask(taskId, inputResponses) : Map + +Sends answers keyed by the outstanding task input request IDs. + +Sources: + +- js/openaf.js:11931 diff --git a/docs/ref/opromise/index.md b/docs/ref/opromise/index.md index 1280a9bb..7c5b9b61 100644 --- a/docs/ref/opromise/index.md +++ b/docs/ref/opromise/index.md @@ -12,7 +12,7 @@ Returns an oPromise that will be resolved when all oPromise part of the anArray Sources: -- js/openaf.js:16542 +- js/openaf.js:16817 @@ -24,7 +24,7 @@ Adds onRejected to the current oPromise stack to execute if the previous functio Sources: -- js/openaf.js:16526 +- js/openaf.js:16801 @@ -36,7 +36,7 @@ Returns an oPromise that will be resolved when any oPromise part of the anArray Sources: -- js/openaf.js:16603 +- js/openaf.js:16878 @@ -48,5 +48,5 @@ Adds onFulfilled to the current oPromise stack to execute if the previous functi Sources: -- js/openaf.js:16508 +- js/openaf.js:16783 diff --git a/docs/ref/ow/ai/gpt/index.md b/docs/ref/ow/ai/gpt/index.md index 84fa16b6..cf7ad591 100644 --- a/docs/ref/ow/ai/gpt/index.md +++ b/docs/ref/ow/ai/gpt/index.md @@ -16,7 +16,7 @@ Adds aPrompt (a string or an array of strings) with aRole (defaults to "develope Sources: -- js/owrap.ai.js:5003 +- js/owrap.ai.js:5109 @@ -28,7 +28,7 @@ Adds aPrompt (a string or an array of strings) with aRole (defaults to "user") t Sources: -- js/owrap.ai.js:4969 +- js/owrap.ai.js:5075 @@ -40,7 +40,7 @@ Adds aPrompt (a string or an array of strings) with aRole (defaults to "user") t Sources: -- js/owrap.ai.js:4991 +- js/owrap.ai.js:5097 @@ -52,7 +52,7 @@ Adds aPrompt (a string or an array of strings) with aRole (defaults to "user") t Sources: -- js/owrap.ai.js:4980 +- js/owrap.ai.js:5086 @@ -64,7 +64,7 @@ Tries to prompt aPrompt (a string or an array of strings) with aRole (defaults t Sources: -- js/owrap.ai.js:5074 +- js/owrap.ai.js:5180 @@ -76,7 +76,7 @@ Cleans the current conversation. Sources: -- js/owrap.ai.js:5014 +- js/owrap.ai.js:5120 @@ -88,7 +88,7 @@ Tries to prompt aPrompt (a string or an array of strings) with aRole (defaults t Sources: -- js/owrap.ai.js:5188 +- js/owrap.ai.js:5294 @@ -100,7 +100,7 @@ Evaluates text/JSON state with named choice, boolean and ordinal score questions Sources: -- js/owrap.ai.js:4552 +- js/owrap.ai.js:4658 @@ -112,7 +112,7 @@ Returns { response, stats } from one execution with request-scoped usa Sources: -- js/owrap.ai.js:4573 +- js/owrap.ai.js:4679 @@ -124,7 +124,7 @@ Exports the current conversation as a portable, provider-neutral format array. E Sources: -- js/owrap.ai.js:4791 +- js/owrap.ai.js:4897 @@ -136,7 +136,7 @@ Returns implemented decision strategies, verified contracts and model availabili Sources: -- js/owrap.ai.js:4473 +- js/owrap.ai.js:4578 @@ -148,7 +148,7 @@ Returns the current conversation. Sources: -- js/owrap.ai.js:4770 +- js/owrap.ai.js:4876 @@ -160,7 +160,7 @@ Returns the latest usage statistics reported by the underlying GPT model for the Sources: -- js/owrap.ai.js:4583 +- js/owrap.ai.js:4689 @@ -172,7 +172,7 @@ Imports a portable conversation previously exported via exportConversation() int Sources: -- js/owrap.ai.js:4807 +- js/owrap.ai.js:4913 @@ -184,7 +184,7 @@ Tries to prompt aPrompt (a string or an array of strings) with aRole (defaults t Sources: -- js/owrap.ai.js:5025 +- js/owrap.ai.js:5131 @@ -196,7 +196,7 @@ Executes jsonPrompt and returns the parsed response together with any reported s Sources: -- js/owrap.ai.js:5038 +- js/owrap.ai.js:5144 @@ -208,7 +208,7 @@ Executes jsonPrompt and returns the raw response, parsed response, and statistic Sources: -- js/owrap.ai.js:5052 +- js/owrap.ai.js:5158 @@ -233,7 +233,7 @@ Only supported by the `openai` provider. Throws if the underlying provider does Sources: -- js/owrap.ai.js:4864 +- js/owrap.ai.js:4970 @@ -247,7 +247,7 @@ aResponseSchema should be a map with: name (string), description (string), schem Sources: -- js/owrap.ai.js:4917 +- js/owrap.ai.js:5023 @@ -259,7 +259,7 @@ Tries to parse anAnswer and return the code between \``` and Sources: -- js/owrap.ai.js:5151 +- js/owrap.ai.js:5257 @@ -271,7 +271,7 @@ Tries to prompt aPrompt (a string or an array of strings) with aRole (defaults t Sources: -- js/owrap.ai.js:5137 +- js/owrap.ai.js:5243 @@ -283,7 +283,7 @@ Tries to prompt aPrompt (a string or an array of strings) with aRole (defaults t Sources: -- js/owrap.ai.js:4637 +- js/owrap.ai.js:4743 @@ -295,7 +295,7 @@ Tries to prompt aPrompt (a string or an array of strings) with aImage (a file pa Sources: -- js/owrap.ai.js:4760 +- js/owrap.ai.js:4866 @@ -307,7 +307,7 @@ Tries to prompt aPrompt (a string or an array of strings), aModel (defaults to t Sources: -- js/owrap.ai.js:4931 +- js/owrap.ai.js:5037 @@ -319,7 +319,7 @@ Executes a streaming prompt, calling aOnDelta for each streamed chunk, and retur Sources: -- js/owrap.ai.js:4648 +- js/owrap.ai.js:4754 @@ -331,7 +331,7 @@ Executes a streaming JSON prompt and returns the parsed JSON response. Sources: -- js/owrap.ai.js:4704 +- js/owrap.ai.js:4810 @@ -343,7 +343,7 @@ Executes a streaming JSON prompt and returns the parsed response with statistics Sources: -- js/owrap.ai.js:4718 +- js/owrap.ai.js:4824 @@ -355,7 +355,7 @@ Executes a streaming JSON prompt and returns the raw response, parsed response, Sources: -- js/owrap.ai.js:4733 +- js/owrap.ai.js:4839 @@ -367,7 +367,7 @@ Executes a streaming prompt and returns a map with the aggregated response and s Sources: -- js/owrap.ai.js:4678 +- js/owrap.ai.js:4784 @@ -379,7 +379,7 @@ Executes prompt and returns a map with the model response and any reported stati Sources: -- js/owrap.ai.js:4748 +- js/owrap.ai.js:4854 @@ -391,7 +391,7 @@ Returns { contractVersion, provider, model, strategy, raw } from one e Sources: -- js/owrap.ai.js:4563 +- js/owrap.ai.js:4669 @@ -403,7 +403,7 @@ Tries to generate an image based on aPrompt (a string or an array of strings) wi Sources: -- js/owrap.ai.js:4958 +- js/owrap.ai.js:5064 @@ -415,7 +415,7 @@ Tries to prompt aPrompt (a string or an array of strings) with aRole (defaults t Sources: -- js/owrap.ai.js:4833 +- js/owrap.ai.js:4939 @@ -427,7 +427,7 @@ Executes a streaming prompt and returns the raw streaming payloads together with Sources: -- js/owrap.ai.js:4660 +- js/owrap.ai.js:4766 @@ -439,7 +439,7 @@ Executes a streaming prompt and returns the raw streaming payloads, aggregated r Sources: -- js/owrap.ai.js:4691 +- js/owrap.ai.js:4797 @@ -451,7 +451,7 @@ Executes rawPrompt and returns the raw response together with any reported stati Sources: -- js/owrap.ai.js:4844 +- js/owrap.ai.js:4950 @@ -463,7 +463,7 @@ Sets the current conversation to aConversation. Sources: -- js/owrap.ai.js:4780 +- js/owrap.ai.js:4886 @@ -475,7 +475,7 @@ Sets the debug channel name to aChName. When defined, creates an OpenAF channel Sources: -- js/owrap.ai.js:4822 +- js/owrap.ai.js:4928 @@ -487,7 +487,7 @@ Sets the instructions for the current conversation. aType can be a string (e.g. Sources: -- js/owrap.ai.js:5098 +- js/owrap.ai.js:5204 @@ -499,7 +499,7 @@ Sets a tool with aName, aDesc (description), aParams (a json schema) and aFn (a Sources: -- js/owrap.ai.js:5087 +- js/owrap.ai.js:5193 @@ -511,5 +511,5 @@ Tries to prompt aPrompt (a string or an array of strings) with aRole (defaults t Sources: -- js/owrap.ai.js:5122 +- js/owrap.ai.js:5228 diff --git a/docs/ref/ow/ai/gpt/prototype/index.md b/docs/ref/ow/ai/gpt/prototype/index.md index 8fe6c1be..171b757b 100644 --- a/docs/ref/ow/ai/gpt/prototype/index.md +++ b/docs/ref/ow/ai/gpt/prototype/index.md @@ -12,7 +12,7 @@ Gets text embeddings for aInput (string or array of strings) using aEmbeddingMod Sources: -- js/owrap.ai.js:4457 +- js/owrap.ai.js:4562 @@ -24,7 +24,19 @@ Returns the model information for aModelId (defaults to the current configured m Sources: -- js/owrap.ai.js:4443 +- js/owrap.ai.js:4507 + + + +## ow.ai.gpt.prototype.getModelLimits + +### ow.ai.gpt.prototype.getModelLimits(aModelId) : Map + +Returns available contextWindow, maxInputTokens and maxOutputTokens limits and their source. Unavailable limits are omitted. An adapter may also return the exact catalogModelId. + +Sources: + +- js/owrap.ai.js:4541 @@ -36,7 +48,7 @@ Returns the default model name configured for this GPT instance. Sources: -- js/owrap.ai.js:4419 +- js/owrap.ai.js:4483 @@ -48,7 +60,7 @@ Returns the available models from the GPT AI service. Sources: -- js/owrap.ai.js:4433 +- js/owrap.ai.js:4497 @@ -60,5 +72,5 @@ Returns the GPT provider type used to create this instance. Sources: -- js/owrap.ai.js:4409 +- js/owrap.ai.js:4473 diff --git a/docs/ref/ow/ai/index.md b/docs/ref/ow/ai/index.md index 7f75049d..f6e3df8a 100644 --- a/docs/ref/ow/ai/index.md +++ b/docs/ref/ow/ai/index.md @@ -46,7 +46,7 @@ global.__a2a__.registerAgent(weatherAgent.meta, weatherAgent.handler); Sources: -- js/owrap.ai.js:4212 +- js/owrap.ai.js:4276 @@ -64,7 +64,7 @@ clustering: Sources: -- js/owrap.ai.js:7378 +- js/owrap.ai.js:7485 @@ -99,7 +99,7 @@ C45: Sources: -- js/owrap.ai.js:6529 +- js/owrap.ai.js:6636 @@ -146,7 +146,7 @@ Usage stats note: `getLastStats()` now includes OpenAI cached prompt tokens (`to Sources: -- js/owrap.ai.js:4340 +- js/owrap.ai.js:4404 @@ -158,7 +158,7 @@ Creates a neural network given the parameters in aMap. aMap should contain a "ty Sources: -- js/owrap.ai.js:5857 +- js/owrap.ai.js:5964 diff --git a/docs/ref/ow/ai/network/index.md b/docs/ref/ow/ai/network/index.md index 184e0855..24d5babc 100644 --- a/docs/ref/ow/ai/network/index.md +++ b/docs/ref/ow/ai/network/index.md @@ -14,7 +14,7 @@ Sources: -- js/owrap.ai.js:5985 +- js/owrap.ai.js:6092 @@ -26,7 +26,7 @@ Sources: Sources: -- js/owrap.ai.js:6110 +- js/owrap.ai.js:6217 @@ -38,7 +38,7 @@ Tries to rebuild the network from aMap returned previously by a toJson function. Sources: -- js/owrap.ai.js:6182 +- js/owrap.ai.js:6289 @@ -50,7 +50,7 @@ Given an inputArray of decimal values, normalize between 0 and 1, will activate Sources: -- js/owrap.ai.js:6123 +- js/owrap.ai.js:6230 @@ -62,7 +62,7 @@ Returns the current BrainJS object. Sources: -- js/owrap.ai.js:6016 +- js/owrap.ai.js:6123 @@ -74,7 +74,7 @@ Returns the current Synaptic object. Sources: -- js/owrap.ai.js:6006 +- js/owrap.ai.js:6113 @@ -88,7 +88,7 @@ Sources: Sources: -- js/owrap.ai.js:5975 +- js/owrap.ai.js:6082 @@ -102,7 +102,7 @@ Sources: Sources: -- js/owrap.ai.js:5945 +- js/owrap.ai.js:6052 @@ -114,7 +114,7 @@ Hopfield serves as a content-addressable memory remembering patterns and when fe Sources: -- js/owrap.ai.js:6071 +- js/owrap.ai.js:6178 @@ -126,7 +126,7 @@ Liquid state machines are neural networks where neurons are randomly connected t Sources: -- js/owrap.ai.js:6057 +- js/owrap.ai.js:6164 @@ -140,7 +140,7 @@ Sources: Sources: -- js/owrap.ai.js:5965 +- js/owrap.ai.js:6072 ### ow.ai.network.lstm(args) : ow.ai.network @@ -150,7 +150,7 @@ there are very long time lags of unknown size between important events. There is Sources: -- js/owrap.ai.js:6041 +- js/owrap.ai.js:6148 @@ -164,7 +164,7 @@ Sources: Sources: -- js/owrap.ai.js:5935 +- js/owrap.ai.js:6042 @@ -178,7 +178,7 @@ Sources: Sources: -- js/owrap.ai.js:5915 +- js/owrap.ai.js:6022 @@ -190,7 +190,7 @@ Perceptron or feed-forward neural networks. There is a minimum of 3 layers (inpu Sources: -- js/owrap.ai.js:6027 +- js/owrap.ai.js:6134 @@ -202,7 +202,7 @@ Given an inputArray of decimal values, normalize between 0 and 1, will activate Sources: -- js/owrap.ai.js:6141 +- js/owrap.ai.js:6248 @@ -214,7 +214,7 @@ Rebuilds a network from a map stored in aFile previously with ow.ai.network.writ Sources: -- js/owrap.ai.js:6208 +- js/owrap.ai.js:6315 @@ -228,7 +228,7 @@ Sources: Sources: -- js/owrap.ai.js:5995 +- js/owrap.ai.js:6102 @@ -242,7 +242,7 @@ Sources: Sources: -- js/owrap.ai.js:5955 +- js/owrap.ai.js:6062 @@ -256,7 +256,7 @@ Sources: Sources: -- js/owrap.ai.js:5925 +- js/owrap.ai.js:6032 @@ -268,7 +268,7 @@ Returns a map representation of the current network to be later rebuilt with the Sources: -- js/owrap.ai.js:6169 +- js/owrap.ai.js:6276 @@ -286,7 +286,7 @@ entry values and output values normalized to a decimal number between 0 and 1. E Sources: -- js/owrap.ai.js:6084 +- js/owrap.ai.js:6191 @@ -298,5 +298,5 @@ Writes a compressed file with the map representation of the current network. Sources: -- js/owrap.ai.js:6198 +- js/owrap.ai.js:6305 diff --git a/docs/ref/ow/ai/normalize/index.md b/docs/ref/ow/ai/normalize/index.md index 6d132d5f..b37d5be2 100644 --- a/docs/ref/ow/ai/normalize/index.md +++ b/docs/ref/ow/ai/normalize/index.md @@ -12,7 +12,7 @@ Tries to denormalize aMapOfNormalizedData (result from ow.ai.normalize.withSchem Sources: -- js/owrap.ai.js:6294 +- js/owrap.ai.js:6401 @@ -24,7 +24,7 @@ Returns anArray where all numbers have been rounded to an integer value. Sources: -- js/owrap.ai.js:6278 +- js/owrap.ai.js:6385 @@ -36,7 +36,7 @@ Given anArray of numbers tries to quantitize returning an array of values betwee Sources: -- js/owrap.ai.js:6253 +- js/owrap.ai.js:6360 @@ -48,7 +48,7 @@ Given anArray of numbers tries to normalize returning an array of values between Sources: -- js/owrap.ai.js:6219 +- js/owrap.ai.js:6326 @@ -60,7 +60,7 @@ Given anArray of numbers tries to apply a Softmax function returning an array of Sources: -- js/owrap.ai.js:6233 +- js/owrap.ai.js:6340 @@ -72,7 +72,7 @@ Tries to convert anArrayOfObjects into an array of array of values where each va Sources: -- js/owrap.ai.js:6486 +- js/owrap.ai.js:6593 @@ -106,5 +106,5 @@ $from(ar).sort("time").select((r) => { return normalize(r, sar); }); Sources: -- js/owrap.ai.js:6375 +- js/owrap.ai.js:6482 diff --git a/docs/ref/ow/index.md b/docs/ref/ow/index.md index 8506da73..5d28b672 100644 --- a/docs/ref/ow/index.md +++ b/docs/ref/ow/index.md @@ -45,7 +45,7 @@ Loads OpenWrap channels functionality. Sources: -- js/openaf.js:7636 +- js/openaf.js:7642 @@ -69,7 +69,7 @@ Loads the optional provider-independent HTML desktop facade. JavaFX support is s Sources: -- js/openaf.js:7667 +- js/openaf.js:7673 @@ -105,7 +105,7 @@ Loads the opt-in generic instrumentation module. Loading does not enable capture Sources: -- js/openaf.js:7602 +- js/openaf.js:7608 @@ -117,7 +117,7 @@ Loads OpenWrap Java functionality. Sources: -- js/openaf.js:7659 +- js/openaf.js:7665 @@ -129,7 +129,7 @@ Loads OpenWrap Metrics functionality. Basically functions to wrap access to serv Sources: -- js/openaf.js:7596 +- js/openaf.js:7602 @@ -153,7 +153,7 @@ Loads OpenWrap oBook functionality. Sources: -- js/openaf.js:7652 +- js/openaf.js:7658 @@ -165,7 +165,7 @@ Loads OpenWrap oJob functionality. Sources: -- js/openaf.js:7644 +- js/openaf.js:7650 @@ -177,7 +177,7 @@ Loads OpenWrap object functionality. Sources: -- js/openaf.js:7628 +- js/openaf.js:7634 @@ -189,7 +189,7 @@ Loads OpenWrap Python functionality. Sources: -- js/openaf.js:7612 +- js/openaf.js:7618 @@ -201,7 +201,7 @@ Loads the OpenWrap Screen TUI and terminal styling/layout library. Provides full Sources: -- js/openaf.js:7681 +- js/openaf.js:7687 @@ -237,7 +237,7 @@ Loads OpenWrap template functionality. Basically functions to wrap access to Han Sources: -- js/openaf.js:7620 +- js/openaf.js:7626 diff --git a/docs/ref/ow/obj/http/index.md b/docs/ref/ow/obj/http/index.md index 2fbd9009..a542a231 100644 --- a/docs/ref/ow/obj/http/index.md +++ b/docs/ref/ow/obj/http/index.md @@ -12,7 +12,7 @@ Closes the current http connection response (if any) and releases any pooled con Sources: -- js/owrap.obj.js:2308 +- js/owrap.obj.js:2345 @@ -36,7 +36,7 @@ Executes a GET request to aURL with the provided aIn, aRequestMap, isBytes, aTim Sources: -- js/owrap.obj.js:2117 +- js/owrap.obj.js:2154 @@ -48,7 +48,7 @@ Executes a GET request to aURL with the provided aIn, aRequestMap, aTimeout and Sources: -- js/owrap.obj.js:2127 +- js/owrap.obj.js:2164 @@ -72,7 +72,7 @@ Returns the response object with the response and responseBytes parsed as JSON i Sources: -- js/owrap.obj.js:2155 +- js/owrap.obj.js:2192 @@ -84,7 +84,7 @@ Returns the response object. Sources: -- js/owrap.obj.js:2175 +- js/owrap.obj.js:2212 @@ -96,7 +96,7 @@ Executes a GET request to aURL with the provided aIn, aRequestMap, aTimeout and Sources: -- js/owrap.obj.js:2136 +- js/owrap.obj.js:2173 @@ -120,7 +120,7 @@ Sets the login credentials to be used with the next request. If forceBasic is tr Sources: -- js/owrap.obj.js:2184 +- js/owrap.obj.js:2221 @@ -132,7 +132,7 @@ Executes a POST request to aURL with the provided aIn, aRequestMap, isBytes, aTi Sources: -- js/owrap.obj.js:2145 +- js/owrap.obj.js:2182 @@ -144,7 +144,7 @@ Returns the response as a string. Sources: -- js/owrap.obj.js:2234 +- js/owrap.obj.js:2271 @@ -156,7 +156,7 @@ Returns the response as bytes. Sources: -- js/owrap.obj.js:2247 +- js/owrap.obj.js:2284 @@ -168,7 +168,7 @@ Returns the response code. Sources: -- js/owrap.obj.js:2260 +- js/owrap.obj.js:2297 @@ -180,7 +180,7 @@ Returns the response headers. Sources: -- js/owrap.obj.js:2271 +- js/owrap.obj.js:2308 @@ -192,7 +192,7 @@ Returns the response as a stream. Sources: -- js/owrap.obj.js:2285 +- js/owrap.obj.js:2322 @@ -204,7 +204,7 @@ Returns the response content type. Sources: -- js/owrap.obj.js:2297 +- js/owrap.obj.js:2334 diff --git a/docs/ref/ow/obj/http0/index.md b/docs/ref/ow/obj/http0/index.md index bbb9b716..f3fdd1f0 100644 --- a/docs/ref/ow/obj/http0/index.md +++ b/docs/ref/ow/obj/http0/index.md @@ -12,5 +12,5 @@ Closes the current http connection response (if any) and shuts down the underlyi Sources: -- js/owrap.obj.js:2634 +- js/owrap.obj.js:2671 diff --git a/docs/ref/ow/obj/index.md b/docs/ref/ow/obj/index.md index 61330e90..fbde42e9 100644 --- a/docs/ref/ow/obj/index.md +++ b/docs/ref/ow/obj/index.md @@ -307,7 +307,7 @@ print(ow.obj.getPath(a, "b.d[0]")); // 0 Sources: -- js/owrap.obj.js:3310 +- js/owrap.obj.js:3363 @@ -348,7 +348,7 @@ Verifies if the provided aMap was signed with ow.obj.sign function. Sources: -- js/owrap.obj.js:3415 +- js/owrap.obj.js:3468 @@ -372,7 +372,7 @@ Chooses a random object from the provided anArray. If aWeightField is provided t Sources: -- js/owrap.obj.js:4291 +- js/owrap.obj.js:4344 @@ -384,7 +384,7 @@ Equivalent to ow.obj.oneOf but each object is expected to have a field "fn" whic Sources: -- js/owrap.obj.js:4311 +- js/owrap.obj.js:4364 @@ -401,7 +401,7 @@ randomDateRange("yyyyMMdd hhmm", "19991231 2300", "20000101 0200"); Sources: -- js/owrap.obj.js:4343 +- js/owrap.obj.js:4396 @@ -413,7 +413,7 @@ Generates a random long number between min and max. Sources: -- js/owrap.obj.js:4333 +- js/owrap.obj.js:4386 @@ -437,7 +437,7 @@ Registers a JSON Schema under aKey in its selected draft engine. Keys and root $ Sources: -- js/owrap.obj.js:3957 +- js/owrap.obj.js:4010 @@ -449,7 +449,7 @@ Checks whether aSchema is valid in its selected dialect, returning true/false. U Sources: -- js/owrap.obj.js:4012 +- js/owrap.obj.js:4065 @@ -461,7 +461,7 @@ Compiles a JSON Schema into a reusable validator returning true/false with detai Sources: -- js/owrap.obj.js:3928 +- js/owrap.obj.js:3981 @@ -483,7 +483,7 @@ The returned object exposes: Sources: -- js/owrap.obj.js:4411 +- js/owrap.obj.js:4464 @@ -505,7 +505,7 @@ Special notation: Sources: -- js/owrap.obj.js:4054 +- js/owrap.obj.js:4107 @@ -517,7 +517,7 @@ Initializes JSON Schema validation once per process. Without options, enables $d Sources: -- js/owrap.obj.js:3814 +- js/owrap.obj.js:3867 @@ -529,7 +529,7 @@ Removes schemas by key/$id, regular expression, or schema object across the draf Sources: -- js/owrap.obj.js:3979 +- js/owrap.obj.js:4032 @@ -541,7 +541,7 @@ Tries to generate a sample JSON map based on the provided aJsonSchema. There is Sources: -- js/owrap.obj.js:4186 +- js/owrap.obj.js:4239 @@ -553,7 +553,7 @@ Validates data against a schema object or registered key/$id. Returns true on su Sources: -- js/owrap.obj.js:4023 +- js/owrap.obj.js:4076 @@ -638,7 +638,7 @@ sprint(ow.obj.setPath(a, "b.c", 123)); // { a : 1, b : { c: 123, d: [0, 1] } } Sources: -- js/owrap.obj.js:3348 +- js/owrap.obj.js:3401 @@ -662,7 +662,7 @@ Given aMap and aKey will return a signed aMap using aHashFunction (defaults to s Sources: -- js/owrap.obj.js:3388 +- js/owrap.obj.js:3441 @@ -674,7 +674,7 @@ Verifies the signature of a signed aMap with ow.obj.sign function given aKey. Re Sources: -- js/owrap.obj.js:3432 +- js/owrap.obj.js:3485 @@ -686,7 +686,7 @@ Creates an instance of a thread-safe array/list. Optionally it can be initialize Sources: -- js/owrap.obj.js:3631 +- js/owrap.obj.js:3684 @@ -698,5 +698,5 @@ Creates an instance of a thread-safe map. Optionally it can be initialized with Sources: -- js/owrap.obj.js:3468 +- js/owrap.obj.js:3521 diff --git a/docs/ref/ow/obj/pmschema/index.md b/docs/ref/ow/obj/pmschema/index.md index b3a9cc93..bbf4ba16 100644 --- a/docs/ref/ow/obj/pmschema/index.md +++ b/docs/ref/ow/obj/pmschema/index.md @@ -12,7 +12,7 @@ Given aSchema (produced by ow.obj.pmSchema.fromJavaParameterMap) and aJavaPM (a Sources: -- js/owrap.obj.js:3285 +- js/owrap.obj.js:3338 @@ -24,7 +24,7 @@ Builds a type schema from the provided aJavaPM (a Java Parameter Map) to be used Sources: -- js/owrap.obj.js:3271 +- js/owrap.obj.js:3324 @@ -36,5 +36,5 @@ Produces a key for the aJavaPM (a Java parameter map or Map) to identify the pro Sources: -- js/owrap.obj.js:3124 +- js/owrap.obj.js:3177 diff --git a/docs/ref/ow/obj/rest/index.md b/docs/ref/ow/obj/rest/index.md index 5e93d94c..9847e87e 100644 --- a/docs/ref/ow/obj/rest/index.md +++ b/docs/ref/ow/obj/rest/index.md @@ -12,7 +12,7 @@ Tries to create a new aDataRowMap entry, identified by aIndexMap, on the REST aB Sources: -- js/owrap.obj.js:2760 +- js/owrap.obj.js:2807 @@ -24,7 +24,7 @@ Tries to parse the response of a rest call exception and the response also if it Sources: -- js/owrap.obj.js:2656 +- js/owrap.obj.js:2702 @@ -36,7 +36,7 @@ Tries to obtain aIndexMap from the REST aBaseURI service returning as a string ( Sources: -- js/owrap.obj.js:2708 +- js/owrap.obj.js:2754 @@ -48,7 +48,7 @@ Tries to get the content lenght for the given aBaseURI. Optionally you can provi Sources: -- js/owrap.obj.js:2669 +- js/owrap.obj.js:2715 @@ -60,7 +60,7 @@ Tries to get the header map with aIndexMap entry from the REST aBaseURI service Sources: -- js/owrap.obj.js:3042 +- js/owrap.obj.js:3094 @@ -72,7 +72,7 @@ Tries to create a new aDataRowMap entry, identified by aIndexMap, on the REST aB Sources: -- js/owrap.obj.js:2865 +- js/owrap.obj.js:2914 @@ -84,7 +84,7 @@ Tries to obtain aIndexMap from the REST aBaseURI service returning as a map (use Sources: -- js/owrap.obj.js:2748 +- js/owrap.obj.js:2795 @@ -96,7 +96,7 @@ Tries to set aDataRowMap entry, identified by aIndexMap, on the REST aBaseURI se Sources: -- js/owrap.obj.js:2980 +- js/owrap.obj.js:3031 @@ -108,7 +108,7 @@ Tries to remove aIndexMap entry from the REST aBaseURI service returning the rep Sources: -- js/owrap.obj.js:3031 +- js/owrap.obj.js:3083 @@ -120,7 +120,7 @@ Tries to set aDataRowMap entry, identified by aIndexMap, on the REST aBaseURI se Sources: -- js/owrap.obj.js:2923 +- js/owrap.obj.js:2973 @@ -132,7 +132,7 @@ Tries to upload a new aDataRowMap entry (composed of name and in (a filename, a Sources: -- js/owrap.obj.js:2852 +- js/owrap.obj.js:2901 @@ -144,7 +144,7 @@ Tries to set aDataRowMap entry, identified by aIndexMap, on the REST aBaseURI se Sources: -- js/owrap.obj.js:2936 +- js/owrap.obj.js:2986 @@ -156,7 +156,7 @@ Tries to remove aIndexMap entry from the REST aBaseURI service returning the rep Sources: -- js/owrap.obj.js:2992 +- js/owrap.obj.js:3043 @@ -168,7 +168,7 @@ Tries to set aDataRowMap entry, identified by aIndexMap, on the REST aBaseURI se Sources: -- js/owrap.obj.js:2878 +- js/owrap.obj.js:2927 @@ -180,7 +180,7 @@ Tries to upload a new aDataRowMap entry (composed of name and in (a filename, a Sources: -- js/owrap.obj.js:2805 +- js/owrap.obj.js:2853 @@ -192,7 +192,7 @@ Given a map of REST API indexes (aPropsMap) will return a corresponding URI. Sources: -- js/owrap.obj.js:3081 +- js/owrap.obj.js:3134 @@ -208,5 +208,5 @@ Given `aMap` will return a URL query string. Example: Sources: -- js/owrap.obj.js:3099 +- js/owrap.obj.js:3152 diff --git a/docs/ref/ow/obj/socket/index.md b/docs/ref/ow/obj/socket/index.md index b4a5b505..a714d806 100644 --- a/docs/ref/ow/obj/socket/index.md +++ b/docs/ref/ow/obj/socket/index.md @@ -12,7 +12,7 @@ Tries to open a socket to aHostAddress on aPort sending aInputString. Will retur Sources: -- js/owrap.obj.js:4387 +- js/owrap.obj.js:4440 @@ -24,5 +24,5 @@ Tries to open a socket to aHostAddress on aPort sending aInputString. Will retur Sources: -- js/owrap.obj.js:4365 +- js/owrap.obj.js:4418 diff --git a/docs/ref/ow/obj/syncarray/index.md b/docs/ref/ow/obj/syncarray/index.md index ec959359..2fff1f16 100644 --- a/docs/ref/ow/obj/syncarray/index.md +++ b/docs/ref/ow/obj/syncarray/index.md @@ -12,7 +12,7 @@ Adds aObject to the internal array/list. If aPosition is provided it will be add Sources: -- js/owrap.obj.js:3667 +- js/owrap.obj.js:3720 @@ -24,7 +24,7 @@ Concatenates anArray with the internal array/list. If aPosition is provided it w Sources: -- js/owrap.obj.js:3681 +- js/owrap.obj.js:3734 @@ -36,7 +36,7 @@ Clears the internal array/list. Sources: -- js/owrap.obj.js:3782 +- js/owrap.obj.js:3835 @@ -48,7 +48,7 @@ Executes aFunction for each element in the internal array/list. The function sho Sources: -- js/owrap.obj.js:3802 +- js/owrap.obj.js:3855 @@ -60,7 +60,7 @@ Returns the object on the internal array/list on position aIndex. Sources: -- js/owrap.obj.js:3752 +- js/owrap.obj.js:3805 @@ -72,7 +72,7 @@ Returns the internal java object. Sources: -- js/owrap.obj.js:3646 +- js/owrap.obj.js:3699 @@ -84,7 +84,7 @@ Returns the internal java object without synchronization. Use with care! Thi Sources: -- js/owrap.obj.js:3656 +- js/owrap.obj.js:3709 @@ -96,7 +96,7 @@ Returns the position of aObject in the internal array/list. Sources: -- js/owrap.obj.js:3792 +- js/owrap.obj.js:3845 @@ -108,7 +108,7 @@ Returns true if the internal array/list is empty. Sources: -- js/owrap.obj.js:3726 +- js/owrap.obj.js:3779 @@ -120,7 +120,7 @@ Returns the current size of the internal array/list. Sources: -- js/owrap.obj.js:3706 +- js/owrap.obj.js:3759 @@ -132,7 +132,7 @@ Removes the element at aIndex from the internal array/list. Sources: -- js/owrap.obj.js:3762 +- js/owrap.obj.js:3815 @@ -144,7 +144,7 @@ Sets aObject overwriting the previous value at aIndex on the internal array/list Sources: -- js/owrap.obj.js:3772 +- js/owrap.obj.js:3825 @@ -156,7 +156,7 @@ Returns a sublist of the internal array/list from aStart to aEnd (exclusive). If Sources: -- js/owrap.obj.js:3736 +- js/owrap.obj.js:3789 @@ -168,7 +168,7 @@ Returns the internal array/list as a javascript array. Sources: -- js/owrap.obj.js:3696 +- js/owrap.obj.js:3749 @@ -180,5 +180,5 @@ Trims the internal array/list to its current size. Sources: -- js/owrap.obj.js:3716 +- js/owrap.obj.js:3769 diff --git a/docs/ref/ow/obj/syncmap/index.md b/docs/ref/ow/obj/syncmap/index.md index f7436dfd..4cd6c62b 100644 --- a/docs/ref/ow/obj/syncmap/index.md +++ b/docs/ref/ow/obj/syncmap/index.md @@ -12,7 +12,7 @@ Clears the internal map. Sources: -- js/owrap.obj.js:3539 +- js/owrap.obj.js:3592 @@ -24,7 +24,7 @@ Returns true if the internal map contains aKey. Sources: -- js/owrap.obj.js:3579 +- js/owrap.obj.js:3632 @@ -36,7 +36,7 @@ Returns true if the internal map contains aValue. Sources: -- js/owrap.obj.js:3589 +- js/owrap.obj.js:3642 @@ -48,7 +48,7 @@ Executes aFunction for each entry in the internal map. The function should have Sources: -- js/owrap.obj.js:3619 +- js/owrap.obj.js:3672 @@ -60,7 +60,7 @@ Returns the value of aKey in the internal map. Sources: -- js/owrap.obj.js:3517 +- js/owrap.obj.js:3570 @@ -72,7 +72,7 @@ Returns the internal java object. Sources: -- js/owrap.obj.js:3484 +- js/owrap.obj.js:3537 @@ -84,7 +84,7 @@ Returns an array with the entries of the internal map. Sources: -- js/owrap.obj.js:3559 +- js/owrap.obj.js:3612 @@ -96,7 +96,7 @@ Returns an array with the values of the internal map. Sources: -- js/owrap.obj.js:3569 +- js/owrap.obj.js:3622 @@ -108,7 +108,7 @@ Returns true if the internal map is empty. Sources: -- js/owrap.obj.js:3599 +- js/owrap.obj.js:3652 @@ -120,7 +120,7 @@ Puts aKey with aValue in the internal map. Sources: -- js/owrap.obj.js:3494 +- js/owrap.obj.js:3547 @@ -132,7 +132,7 @@ Puts all the entries of aMap in the internal map. Sources: -- js/owrap.obj.js:3505 +- js/owrap.obj.js:3558 @@ -144,7 +144,7 @@ Removes the entry identified by aKey from the internal map. Sources: -- js/owrap.obj.js:3529 +- js/owrap.obj.js:3582 @@ -156,7 +156,7 @@ Returns the current size of the internal map. Sources: -- js/owrap.obj.js:3549 +- js/owrap.obj.js:3602 @@ -168,5 +168,5 @@ Returns the internal map as a javascript map. Sources: -- js/owrap.obj.js:3609 +- js/owrap.obj.js:3662 diff --git a/docs/ref/ow/server/a2a/prototype/index.md b/docs/ref/ow/server/a2a/prototype/index.md index 70cee514..5244158e 100644 --- a/docs/ref/ow/server/a2a/prototype/index.md +++ b/docs/ref/ow/server/a2a/prototype/index.md @@ -14,7 +14,7 @@ Throws an error if the agent is not found. Sources: -- js/owrap.server.js:2481 +- js/owrap.server.js:3261 @@ -28,7 +28,7 @@ Optionally filter agents using aFilterFn(agentMeta) which should return true to Sources: -- js/owrap.server.js:2464 +- js/owrap.server.js:3244 @@ -63,7 +63,7 @@ Registers an agent with the A2A registry. Sources: -- js/owrap.server.js:2389 +- js/owrap.server.js:3169 @@ -82,7 +82,7 @@ Returns MCP-style response: `{ content: [{ type: "text", text: "..." }], isError Sources: -- js/owrap.server.js:2498 +- js/owrap.server.js:3278 @@ -94,5 +94,5 @@ Removes an agent from the registry by ID. Sources: -- js/owrap.server.js:2452 +- js/owrap.server.js:3232 diff --git a/docs/ref/ow/server/cluster/index.md b/docs/ref/ow/server/cluster/index.md index 78f5e0bc..49607cb9 100644 --- a/docs/ref/ow/server/cluster/index.md +++ b/docs/ref/ow/server/cluster/index.md @@ -12,7 +12,7 @@ Tries to execute aFunction providing a map with all of the cluster list host + p Sources: -- js/owrap.server.js:2870 +- js/owrap.server.js:3650 @@ -24,7 +24,7 @@ Tries to execute aFunction providing a map with one of the cluster list host + p Sources: -- js/owrap.server.js:2841 +- js/owrap.server.js:3621 @@ -36,7 +36,7 @@ Sends messages to all other cluster nodes to reach quorum if can lock aLockName Sources: -- js/owrap.server.js:2916 +- js/owrap.server.js:3696 @@ -48,7 +48,7 @@ Sends messages to all other cluster nodes to reach quorum if can unlock aLockNam Sources: -- js/owrap.server.js:2926 +- js/owrap.server.js:3706 @@ -60,7 +60,7 @@ Checks in the current cluster node. Sources: -- js/owrap.server.js:3009 +- js/owrap.server.js:3789 @@ -72,7 +72,7 @@ Checks out the current cluster node. Sources: -- js/owrap.server.js:3026 +- js/owrap.server.js:3806 @@ -84,7 +84,7 @@ Returns the current cluster node ow.server.locks instance. Sources: -- js/owrap.server.js:2936 +- js/owrap.server.js:3716 @@ -96,7 +96,7 @@ Sends aMessageMap to a specific aHostMap (map composed of a host and a port) or Sources: -- js/owrap.server.js:2893 +- js/owrap.server.js:3673 @@ -108,7 +108,7 @@ Tries to send to another cluster node aData using aSendToOtherFn that receives, Sources: -- js/owrap.server.js:2815 +- js/owrap.server.js:3595 @@ -120,7 +120,7 @@ Sets aHandlerFunction to be called whenever the current node receives a message Sources: -- js/owrap.server.js:2905 +- js/owrap.server.js:3685 @@ -132,7 +132,7 @@ Verifies if all cluster nodes ports are reachable and updates the cluster file. Sources: -- js/owrap.server.js:2957 +- js/owrap.server.js:3737 @@ -144,5 +144,5 @@ A wrapper for ow.server.locks.lock that will try to lock aLockName after check i Sources: -- js/owrap.server.js:2946 +- js/owrap.server.js:3726 diff --git a/docs/ref/ow/server/httpd/browse/index.md b/docs/ref/ow/server/httpd/browse/index.md index 1865cc31..44d3a6e7 100644 --- a/docs/ref/ow/server/httpd/browse/index.md +++ b/docs/ref/ow/server/httpd/browse/index.md @@ -24,7 +24,7 @@ Provides a simple file browser for the provided `aURI`. The `aOptions` map can c Sources: -- js/owrap.server.js:5476 +- js/owrap.server.js:6875 @@ -43,7 +43,7 @@ Provides a simple oDoc browser. The `aOptions` map can contain the following key Sources: -- js/owrap.server.js:5761 +- js/owrap.server.js:7160 @@ -62,5 +62,5 @@ Provides a simple oPack browser. The `aOptions` map can contain the following ke Sources: -- js/owrap.server.js:5850 +- js/owrap.server.js:7249 diff --git a/docs/ref/ow/server/httpd/index.md b/docs/ref/ow/server/httpd/index.md index eaddb6a2..82dd68a1 100644 --- a/docs/ref/ow/server/httpd/index.md +++ b/docs/ref/ow/server/httpd/index.md @@ -16,7 +16,7 @@ Adds a new HTTP aCodeNum number that will be referenced by the name aCodeRef. Sources: -- js/owrap.server.js:5116 +- js/owrap.server.js:5933 @@ -28,7 +28,7 @@ Adds a new aMimeType for the corresponding anExtension. Sources: -- js/owrap.server.js:5106 +- js/owrap.server.js:5923 @@ -67,7 +67,7 @@ function(req) { Sources: -- js/owrap.server.js:5051 +- js/owrap.server.js:5868 @@ -93,7 +93,7 @@ provides the OAuth configurations to follow: Sources: -- js/owrap.server.js:4904 +- js/owrap.server.js:5721 @@ -105,7 +105,7 @@ Retrieves aResource, as anArrayOfBytes, from the openaf.jar. This resource can b Sources: -- js/owrap.server.js:4058 +- js/owrap.server.js:4828 @@ -117,7 +117,7 @@ Retrieves aResource, as anArrayOfBytes, from aZipFile. This resource can be inBy Sources: -- js/owrap.server.js:4069 +- js/owrap.server.js:4839 @@ -129,7 +129,7 @@ Returns the HTTPd object created, if any, for aPort. Sources: -- js/owrap.server.js:4021 +- js/owrap.server.js:4789 @@ -141,7 +141,7 @@ Tries to determine the mime type of aFilename and returns it. If not determined Sources: -- js/owrap.server.js:4888 +- js/owrap.server.js:5705 @@ -153,7 +153,7 @@ Helper to use with ow.server.httpd.route to automatically add routes for JQuery, Sources: -- js/owrap.server.js:4223 +- js/owrap.server.js:5012 @@ -165,7 +165,7 @@ Builds a map of routes taking into account the already defined routes for aHTTPd Sources: -- js/owrap.server.js:4188 +- js/owrap.server.js:4975 @@ -177,7 +177,26 @@ Creates a localhost OAuth2 authorization-code client. Requires authURL, tokenURL Sources: -- js/owrap.server.js:3626 +- js/owrap.server.js:4408 + + + +## ow.server.httpd.oauthResourceServer + +### ow.server.httpd.oauthResourceServer(options) : Map + +Creates an OAuth 2.0 bearer resource server with an explicit issuer and public resource URL. +Defaults to JWT access tokens (RFC 9068), RS256, discovery and the resource URL as audience. +Set `validation: "introspection"` to use an RFC 7662 endpoint with a secret reference. +Use `wrap(handler, scopes)` to protect an HTTP route and `metadataHandler` at `metadataPath()`. +`authenticate(request)` returns `{ ok, context }` or `{ ok, error }`. Pass successful contexts +to `authorize(context, scopes)` and failures to `challenge(error, scopes)`. `metadata()` and +`metadataURI()` describe discovery. `invalidate()` clears caches and `close()` releases resources. +See [OAuth resource servers](../../../../oauth-resource-server.md) for all options and examples. + +Sources: + +- js/owrap.server.js:6300 @@ -189,7 +208,7 @@ Builds the map response for a HTTP server request using aObject (map, array, str Sources: -- js/owrap.server.js:5178 +- js/owrap.server.js:5995 @@ -208,7 +227,7 @@ provide the following functions: Sources: -- js/owrap.server.js:4558 +- js/owrap.server.js:5347 @@ -228,7 +247,7 @@ ow.server.httpd.route(hs, ow.server.httpd.mapRoutesWithLibs(hs, { Sources: -- js/owrap.server.js:4338 +- js/owrap.server.js:5127 @@ -254,7 +273,7 @@ function(req) { Sources: -- js/owrap.server.js:4398 +- js/owrap.server.js:5187 @@ -266,7 +285,7 @@ Provides a helper function to call aFunctionName over aInstance (default this) g Sources: -- js/owrap.server.js:4526 +- js/owrap.server.js:5315 @@ -286,7 +305,7 @@ r => hs.replyOKText("nothing here...") Sources: -- js/owrap.server.js:4475 +- js/owrap.server.js:5264 @@ -309,13 +328,17 @@ ow.server.httpd.route(hs, { requests carrying a modern (2026-07-28+) per-`request` _meta protocol version are validated against `ow.server.mcp.versions.supported` (replying with an UnsupportedProtocolVersionError otherwise), results are wrapped with the required resultType (plus ttlMs/cacheScope for methods listed in `opts`.listMethods, default -["tools/list","prompts/list","resources/list","resources/templates/list"]), and the negotiated version is -echoed back via the MCP-Protocol-Version response header. Legacy requests (the default, and everything when -modern is false/omitted) are handled exactly as before -- zero behavior change. +`ow.server.mcp.cacheableMethods`, using `opts`.ttlMs (default 0) and `opts`.cacheScope (default "private")), +the MCP-Protocol-Version, Mcp-Method and Mcp-Name request headers must mirror the body (otherwise HTTP 400 with +a HeaderMismatch -32020 error, see `ow.server.mcp.validateHeaders`; tools/call `Mcp-Param-{Name}` headers are +checked against the `x-mcp-header` annotations of `opts`.tools, an array of tool definitions or a function +returning one, defaulting to the result of mapOfFunctions["tools/list"]), and the negotiated version is echoed +back via the MCP-Protocol-Version response header. Legacy requests (the default, and everything when modern is +false/omitted) are handled exactly as before -- zero behavior change. Sources: -- js/owrap.server.js:4612 +- js/owrap.server.js:5401 @@ -341,14 +364,15 @@ ow.server.httpd.route(hs, { }) ``` -`opts` is an optional map: { modern: false, listMethods: [...] } -- see `ow.server.httpd.replyJSONRPC` for the -meaning of both; the same opt-in 2026-07-28 modern-era handling (version validation, resultType/ttlMs/ -cacheScope wrapping, MCP-Protocol-Version response header) applies here, with legacy behavior (default) +`opts` is an optional map: { modern: false, listMethods: [...], ttlMs: 0, cacheScope: "private", tools: __ } -- see +`ow.server.httpd.replyJSONRPC` for their meaning; the same opt-in 2026-07-28 modern-era handling (version and +request header validation, resultType/ttlMs/cacheScope wrapping, MCP-Protocol-Version response header) +applies here, with legacy behavior (default) left fully unchanged. Sources: -- js/owrap.server.js:4753 +- js/owrap.server.js:5561 @@ -360,7 +384,7 @@ Provides a helper aHTTPd reply that will redirect the request to the newLocation Sources: -- js/owrap.server.js:4513 +- js/owrap.server.js:5302 @@ -372,16 +396,18 @@ Given aHTTPd it will reset all internal mapped routes to a reply HTTP code 401 t Sources: -- js/owrap.server.js:4041 +- js/owrap.server.js:4809 ## ow.server.httpd.route -### ow.server.httpd.route(aHTTPd, aMapOfRoutes, aDefaultRoute, aPath, aPreRouteFunc) +### ow.server.httpd.route(aHTTPd, aMapOfRoutes, aDefaultRoute, aPath, aPreRouteFunc, reservedRoutes) Adds a request router to `aHTTPd` given `aMapOfRoutes`. This router will use `aPath` if defined or /r otherwise. -Optionally you can also specify `aPreRouteFunc` that will run before any routing is made. +Optionally specify `aPreRouteFunc` to run before routing. Pass `reservedRoutes` (an array of paths) +as the sixth argument to register those paths exclusively. An existing handler cannot be replaced +by a reservation, and later calls cannot replace a reserved handler until the server stops. Example: ```javascript @@ -403,7 +429,7 @@ ow.server.daemon(); Sources: -- js/owrap.server.js:4080 +- js/owrap.server.js:4850 @@ -415,7 +441,7 @@ Using aHTTPd sets aURI to act as a websocket server. Sources: -- js/owrap.server.js:4031 +- js/owrap.server.js:4799 @@ -443,7 +469,7 @@ the timeout for the server to wait for a request before closing the connection. Sources: -- js/owrap.server.js:3938 +- js/owrap.server.js:4702 @@ -455,5 +481,5 @@ Will stop the aHTTPd server running. (available after ow.loadServer()) Sources: -- js/owrap.server.js:4208 +- js/owrap.server.js:4995 diff --git a/docs/ref/ow/server/index.md b/docs/ref/ow/server/index.md index 610335c5..80ddef79 100644 --- a/docs/ref/ow/server/index.md +++ b/docs/ref/ow/server/index.md @@ -13,6 +13,7 @@ - [ow.server.ldap](ldap/index.md) - [ow.server.locks](locks/index.md) - [ow.server.mcp](mcp/index.md) +- [ow.server.oauth](oauth/index.md) - [ow.server.openafServer](openafserver/index.md) - [ow.server.queue](queue/index.md) - [ow.server.rest](rest/index.md) @@ -30,7 +31,7 @@ Creates an agent registry for Agent-to-Agent (A2A) messaging over MCP. Agents ca Sources: -- js/owrap.server.js:2375 +- js/owrap.server.js:3155 @@ -148,7 +149,7 @@ To provide another custom `aListImplementation` it should contain the following Sources: -- js/owrap.server.js:2727 +- js/owrap.server.js:3507 @@ -179,7 +180,7 @@ There are several implementation options: Sources: -- js/owrap.server.js:3044 +- js/owrap.server.js:3824 @@ -278,8 +279,10 @@ The function will listen for incoming MCP requests on standard input and respond `opts`.rawToolResults (default false) preserves MCP content/structuredContent/isError envelopes returned by tools. `opts` is an optional map: { modern: false } (default). When modern is true this also serves the 2026-07-28 stateless/per-request MCP protocol era (per-request _meta protocol version, server/discover, resultType, -ttlMs/cacheScope on list results, UnsupportedProtocolVersionError) side-by-side with the legacy +ttlMs/cacheScope on cacheable results, UnsupportedProtocolVersionError) side-by-side with the legacy initialize-handshake era used above, for any request that carries a modern _meta protocol version. +`opts`.ttlMs (default 0) and `opts`.cacheScope (default "private") set the caching hints advertised on +server/discover, list and resources/read results in the modern era. When modern is false (the default) behavior is 100% unchanged from previous releases. Example usage: @@ -330,7 +333,7 @@ Example usage: Sources: -- js/owrap.server.js:2147 +- js/owrap.server.js:2916 diff --git a/docs/ref/ow/server/jwt/index.md b/docs/ref/ow/server/jwt/index.md index 6213db94..4979c078 100644 --- a/docs/ref/ow/server/jwt/index.md +++ b/docs/ref/ow/server/jwt/index.md @@ -12,7 +12,7 @@ Tries to decode the JWT aToken provided. Sources: -- js/owrap.server.js:5444 +- js/owrap.server.js:6261 @@ -24,7 +24,7 @@ Generates a key for the provided aAlgorithm (defaults to HS256). If aAlgorithm i Sources: -- js/owrap.server.js:5289 +- js/owrap.server.js:6106 @@ -49,7 +49,7 @@ Expected keys for `aData`: Sources: -- js/owrap.server.js:5381 +- js/owrap.server.js:6198 @@ -61,5 +61,5 @@ Verifies the JWT provided with aToken using aSecret1 (key (either a string or ja Sources: -- js/owrap.server.js:5326 +- js/owrap.server.js:6143 diff --git a/docs/ref/ow/server/mcp/index.md b/docs/ref/ow/server/mcp/index.md index 8066a2a3..0aa0ffd4 100644 --- a/docs/ref/ow/server/mcp/index.md +++ b/docs/ref/ow/server/mcp/index.md @@ -15,19 +15,43 @@ Read functions return UTF-8 text or `{ bytes, mimeType }`. Sources: -- js/owrap.server.js:1932 +- js/owrap.server.js:2183 + + + +## ow.server.mcp.decodeHeaderValue + +### ow.server.mcp.decodeHeaderValue(aValue) : String + +Decodes a MCP request metadata header value: a `=?base64?{UTF-8 Base64}?=` sentinel is decoded, any other value is returned unchanged. Returns __ if aValue is undefined or the sentinel isn't valid Base64. + +Sources: + +- js/owrap.server.js:1787 ## ow.server.mcp.discoverResult -### ow.server.mcp.discoverResult(initData) : Map +### ow.server.mcp.discoverResult(initData, opts) : Map -Builds the mandatory server/discover response (modern era) advertising this server's supported protocol versions, capabilities and identity. +Builds the mandatory server/discover response (modern era) advertising this server's supported protocol versions, capabilities and identity, plus the required caching hints from the optional opts map ({ ttlMs, cacheScope }, normalized by `ow.server.mcp.normalizeCacheHints`; default 0 and "private"). Sources: -- js/owrap.server.js:1879 +- js/owrap.server.js:2125 + + + +## ow.server.mcp.encodeHeaderValue + +### ow.server.mcp.encodeHeaderValue(aValue) : String + +Encodes aValue for a MCP request metadata header (e.g. Mcp-Name). Values that are not plain printable ASCII, or that already look like the Base64 sentinel, are encoded as `=?base64?{UTF-8 Base64}?=`; other values are returned unchanged. + +Sources: + +- js/owrap.server.js:1773 @@ -39,7 +63,43 @@ Classifies a parsed JSON-RPC request as "modern" (carries a modern params._m Sources: -- js/owrap.server.js:1807 +- js/owrap.server.js:2054 + + + +## ow.server.mcp.headerAnnotations + +### ow.server.mcp.headerAnnotations(anInputSchema) : Map + +Collects the `x-mcp-header` annotations of a tool's inputSchema (2026-07-28 Streamable HTTP custom headers). Returns { valid, error, params } where params is an array of { header, path, type }: header is the `Mcp-Param-{header}` name portion, path the chain of property names inside the tool arguments and type the property's JSON type. An annotation is invalid (valid false, error says why) unless it is reached only through `properties` keywords, is a non-empty HTTP token (RFC 9110 tchar), is case-insensitively unique and annotates a property of type "string", "integer" or "boolean". + +Sources: + +- js/owrap.server.js:1832 + + + +## ow.server.mcp.headerMismatchError + +### ow.server.mcp.headerMismatchError(anId, aMessage) : Map + +Builds a JSON-RPC HeaderMismatch (-32020) error response. + +Sources: + +- js/owrap.server.js:1822 + + + +## ow.server.mcp.headerValue + +### ow.server.mcp.headerValue(aHeaders, aName) : String + +Returns the value of the HTTP header aName from the aHeaders map using a case-insensitive name lookup (HTTP header names are case-insensitive), or __ if not present. + +Sources: + +- js/owrap.server.js:1759 @@ -51,7 +111,7 @@ Builds a JSON-RPC Invalid Params (-32602) error response, used when a modern-era Sources: -- js/owrap.server.js:1839 +- js/owrap.server.js:2086 @@ -63,7 +123,7 @@ Returns true if aVersion is a protocol version string on or after the modern (st Sources: -- js/owrap.server.js:1756 +- js/owrap.server.js:2003 @@ -75,7 +135,7 @@ Extracts the per-request client capabilities from params._meta["io.model Sources: -- js/owrap.server.js:1793 +- js/owrap.server.js:2040 @@ -87,7 +147,69 @@ Extracts the modern per-request protocol version from a parsed JSON-RPC request' Sources: -- js/owrap.server.js:1779 +- js/owrap.server.js:2026 + + + +## ow.server.mcp.nameSourceOf + +### ow.server.mcp.nameSourceOf(reqObj) : String + +Returns the request body value that the Mcp-Name header must mirror: params.name for tools/call and prompts/get, params.uri for resources/read, params.taskId for tasks/get, tasks/update and tasks/cancel (tasks extension), or __ for any other method. + +Sources: + +- js/owrap.server.js:1806 + + + +## ow.server.mcp.normalizeCacheHints + +### ow.server.mcp.normalizeCacheHints(aTTL, aScope) : Map + +Returns valid CacheableResult hints { ttlMs, cacheScope }: ttlMs is an integer >= 0 (default 0) and cacheScope is "public" or "private" (default "private"). + +Sources: + +- js/owrap.server.js:1990 + + + +## ow.server.mcp.openWorkflows + +### ow.server.mcp.openWorkflows(definitions, options) : Map + +Opens an endpoint's durable MCP Tasks and form continuation store. Definitions +bind wire tool names to inline, managed or external callbacks. Close the returned +runtime when the endpoint stops. Use a private state file per endpoint. + +Sources: + +- js/owrap.server.js:2398 + + + +## ow.server.mcp.paramHeaders + +### ow.server.mcp.paramHeaders(anInputSchema, anArguments) : Map + +Returns the `Mcp-Param-{Name}` request headers a client must send for a tools/call with anArguments given the tool's anInputSchema (strings as-is, integers in decimal, booleans as "true"/"false", Base64 sentinel encoded when needed). Absent or null arguments produce no header. Returns {} for invalid annotations. + +Sources: + +- js/owrap.server.js:1890 + + + +## ow.server.mcp.paramValueOf + +### ow.server.mcp.paramValueOf(anArguments, aPath) : Object + +Returns the tool argument value at aPath (array of property names) or __ if absent or null. + +Sources: + +- js/owrap.server.js:1875 @@ -99,7 +221,19 @@ Returns the request's params._meta map (per the spec, _meta is nested in Sources: -- js/owrap.server.js:1767 +- js/owrap.server.js:2014 + + + +## ow.server.mcp.toolsOf + +### ow.server.mcp.toolsOf(mapOfFunctions, opts) : Function + +Returns a function listing the server's tool definitions for `Mcp-Param-{Name}` validation: opts.tools (an array or a function returning one) when given, otherwise the tools returned by mapOfFunctions["tools/list"] (following nextCursor), or __ when neither is available. + +Sources: + +- js/owrap.server.js:1966 @@ -111,7 +245,19 @@ Builds a JSON-RPC UnsupportedProtocolVersionError (-32022) response listing the Sources: -- js/owrap.server.js:1821 +- js/owrap.server.js:2068 + + + +## ow.server.mcp.validateHeaders + +### ow.server.mcp.validateHeaders(aHeaders, reqObj, aVersion, aTools) : Map + +Validates the 2026-07-28 Streamable HTTP request metadata headers of a modern-era request against its body: MCP-Protocol-Version must equal aVersion (the params._meta protocol version), Mcp-Method must equal the JSON-RPC method and, for the methods listed in `ow.server.mcp.nameSourceOf`, Mcp-Name (Base64 sentinel decoded) must equal the corresponding params.name/params.uri/params.taskId. Header values are compared case-sensitively. For tools/call, when aTools (an array of tool definitions, or a function returning one) is given, every `x-mcp-header` annotated argument present in the body must be mirrored by its `Mcp-Param-{Name}` header and every such header must match its argument (integers compared numerically). Returns a HeaderMismatch (-32020) error response map, to be sent with HTTP 400, or __ if the headers are valid. + +Sources: + +- js/owrap.server.js:1908 @@ -119,9 +265,9 @@ Sources: ### ow.server.mcp.wrapResult(aBody, anEra, opts) : Map -Wraps a MCP result body per the negotiated era. Legacy eras ("legacy-initialize"/"legacy-stateless") return aBody unchanged -- zero behavior change for existing callers. The "modern" era merges in the required resultType ("complete"), and, when opts.isList is true, CacheableResult fields (ttlMs, cacheScope) with sensible defaults (opts.ttlMs default 0, opts.cacheScope default "private"). When opts.serverInfo is given, it is advertised (SHOULD, per spec) as result._meta["io.modelcontextprotocol/serverInfo"]. +Wraps a MCP result body per the negotiated era. Legacy eras ("legacy-initialize"/"legacy-stateless") return aBody unchanged -- zero behavior change for existing callers. The "modern" era merges in the required resultType ("complete"), and, when opts.isList is true (any cacheable method, see `ow.server.mcp.cacheableMethods`) and the result is complete, CacheableResult fields (ttlMs, cacheScope) normalized by `ow.server.mcp.normalizeCacheHints` (opts.ttlMs default 0, opts.cacheScope default "private"). Interim (e.g. input_required) results carry no caching hints. When opts.serverInfo is given, it is advertised (SHOULD, per spec) as result._meta["io.modelcontextprotocol/serverInfo"]. Sources: -- js/owrap.server.js:1852 +- js/owrap.server.js:2099 diff --git a/docs/ref/ow/server/oauth/index.md b/docs/ref/ow/server/oauth/index.md new file mode 100644 index 00000000..086cdb1e --- /dev/null +++ b/docs/ref/ow/server/oauth/index.md @@ -0,0 +1,16 @@ +# ow.server.oauth + +[Home](../../../index.md) / [All APIs](../../../all-apis.md) / [ow](../../index.md) / [ow.server](../index.md) / [ow.server.oauth](index.md) + + + +## ow.server.oauth.client + +### ow.server.oauth.client(options) : Object + +Creates an OAuth client for a configured issuer or token endpoint. + +Sources: + +- js/owrap.server.oauth.js:359 + diff --git a/docs/ref/ow/server/socket/index.md b/docs/ref/ow/server/socket/index.md index 8f93d178..32874251 100644 --- a/docs/ref/ow/server/socket/index.md +++ b/docs/ref/ow/server/socket/index.md @@ -30,7 +30,7 @@ ow.server.socket.start(12345, (clt, srv) => { Sources: -- js/owrap.server.js:5218 +- js/owrap.server.js:6035 @@ -42,5 +42,5 @@ Stops a thread socket server on aPort previously started by ow.server.socket.sta Sources: -- js/owrap.server.js:5268 +- js/owrap.server.js:6085 diff --git a/docs/ref/ow/server/telemetry/index.md b/docs/ref/ow/server/telemetry/index.md index 78ad53a1..6ed9f350 100644 --- a/docs/ref/ow/server/telemetry/index.md +++ b/docs/ref/ow/server/telemetry/index.md @@ -12,7 +12,7 @@ Setup recurrent execution of aSendFunc with the propose of sending ow.metrics fo Sources: -- js/owrap.server.js:2651 +- js/owrap.server.js:3431 @@ -24,7 +24,7 @@ Setup a HTTPd server on aHTTPdOrPort (defaults to 7777) on the aURI (defaults to Sources: -- js/owrap.server.js:2610 +- js/owrap.server.js:3390 @@ -36,7 +36,7 @@ Returns a function to be used with ow.server.telemetry.active to send metrics to Sources: -- js/owrap.server.js:2696 +- js/owrap.server.js:3476 @@ -48,5 +48,5 @@ Returns a function to be used with ow.server.telemetry.active to send metrics to Sources: -- js/owrap.server.js:2668 +- js/owrap.server.js:3448 diff --git a/docs/ref/rest/index.md b/docs/ref/rest/index.md index a2891040..f88d12ee 100644 --- a/docs/ref/rest/index.md +++ b/docs/ref/rest/index.md @@ -12,7 +12,7 @@ Shortcut for ow.obj.rest.jsonRemove (see help ow.obj.rest.jsonRemove) using aOpt Sources: -- js/openaf.js:9257 +- js/openaf.js:9296 @@ -24,7 +24,7 @@ Shortcut for ow.obj.rest.jsonRemove (see help ow.obj.rest.jsonRemove) using aOpt Sources: -- js/openaf.js:9285 +- js/openaf.js:9324 @@ -36,7 +36,7 @@ Shortcut for ow.obj.rest.jsonRemove (see help ow.obj.rest.jsonRemove) using aOpt Sources: -- js/openaf.js:9271 +- js/openaf.js:9310 @@ -48,7 +48,7 @@ Shortcut for ow.obj.rest.jsonGet (see help ow.obj.rest.jsonGet) using aOptions ( Sources: -- js/openaf.js:9054 +- js/openaf.js:9093 @@ -60,7 +60,7 @@ Shortcut for ow.obj.rest.jsonGet (see help ow.obj.rest.jsonGet) using aOptions ( Sources: -- js/openaf.js:9082 +- js/openaf.js:9121 @@ -72,7 +72,7 @@ Shortcut for ow.obj.rest.jsonGet (see help ow.obj.rest.jsonGet) using aOptions ( Sources: -- js/openaf.js:9068 +- js/openaf.js:9107 @@ -84,7 +84,7 @@ Shortcut for ow.obj.rest.head (see help ow.obj.rest.head) using aOptions ($rest( Sources: -- js/openaf.js:9383 +- js/openaf.js:9422 @@ -96,7 +96,7 @@ Shortcut for ow.obj.rest.writeIndexes (see help ow.obj.rest.writeIndexes). Sources: -- js/openaf.js:9406 +- js/openaf.js:9445 @@ -108,7 +108,7 @@ Shortcut for ow.obj.rest.jsonPatch (see help ow.obj.rest.jsonPatch) using aOptio Sources: -- js/openaf.js:9306 +- js/openaf.js:9345 @@ -120,7 +120,7 @@ Shortcut for ow.obj.rest.jsonPatch (see help ow.obj.rest.jsonPatch) using aOptio Sources: -- js/openaf.js:9362 +- js/openaf.js:9401 @@ -132,7 +132,7 @@ Shortcut for ow.obj.rest.jsonPatch (see help ow.obj.rest.jsonPatch) using aOptio Sources: -- js/openaf.js:9320 +- js/openaf.js:9359 @@ -144,7 +144,7 @@ Shortcut for ow.obj.rest.upload (see help ow.obj.rest.upload with patch) using a Sources: -- js/openaf.js:9334 +- js/openaf.js:9373 @@ -156,7 +156,7 @@ Shortcut for ow.obj.rest.upload (see help ow.obj.rest.upload with patch) using a Sources: -- js/openaf.js:9348 +- js/openaf.js:9387 @@ -168,7 +168,7 @@ Shortcut for ow.obj.rest.jsonCreate (see help ow.obj.rest.jsonCreate) using aOpt Sources: -- js/openaf.js:9103 +- js/openaf.js:9142 @@ -180,7 +180,7 @@ Shortcut for ow.obj.rest.jsonCreate (see help ow.obj.rest.jsonCreate) using aOpt Sources: -- js/openaf.js:9159 +- js/openaf.js:9198 @@ -192,7 +192,7 @@ Shortcut for ow.obj.rest.jsonCreate (see help ow.obj.rest.jsonCreate) using aOpt Sources: -- js/openaf.js:9117 +- js/openaf.js:9156 @@ -204,7 +204,7 @@ Shortcut for ow.obj.rest.upload (see help ow.obj.rest.upload with post) using aO Sources: -- js/openaf.js:9131 +- js/openaf.js:9170 @@ -216,7 +216,7 @@ Shortcut for ow.obj.rest.upload (see help ow.obj.rest.upload with post) using aO Sources: -- js/openaf.js:9145 +- js/openaf.js:9184 @@ -228,7 +228,7 @@ Shortcut for ow.obj.rest.jsonSet (see help ow.obj.rest.jsonSet) using aOptions ( Sources: -- js/openaf.js:9180 +- js/openaf.js:9219 @@ -240,7 +240,7 @@ Shortcut for ow.obj.rest.jsonSet (see help ow.obj.rest.jsonSet) using aOptions ( Sources: -- js/openaf.js:9236 +- js/openaf.js:9275 @@ -252,7 +252,7 @@ Shortcut for ow.obj.rest.jsonSet (see help ow.obj.rest.jsonSet) using aOptions ( Sources: -- js/openaf.js:9194 +- js/openaf.js:9233 @@ -264,7 +264,7 @@ Shortcut for ow.obj.rest.upload (see help ow.obj.rest.upload with put) using aOp Sources: -- js/openaf.js:9208 +- js/openaf.js:9247 @@ -276,7 +276,7 @@ Shortcut for ow.obj.rest.upload (see help ow.obj.rest.upload with post) using aO Sources: -- js/openaf.js:9222 +- js/openaf.js:9261 @@ -288,5 +288,5 @@ Shortcut for ow.obj.rest.writeQuery (see help ow.obj.rest.writeQuery). Sources: -- js/openaf.js:9397 +- js/openaf.js:9436 diff --git a/docs/ref/sh/index.md b/docs/ref/sh/index.md index 3d3db37b..667f290e 100644 --- a/docs/ref/sh/index.md +++ b/docs/ref/sh/index.md @@ -12,7 +12,7 @@ When executing aCmd (with .get) use aCallbackFunc function. Sources: -- js/openaf.js:17713 +- js/openaf.js:17988 @@ -24,7 +24,7 @@ Immediately copies aSource to aTarget before executing aCmd (with .exec). Sources: -- js/openaf.js:17785 +- js/openaf.js:18060 @@ -36,7 +36,7 @@ If aBooleanValue = true the execution won't wait for output (default: false). Sources: -- js/openaf.js:17665 +- js/openaf.js:17940 @@ -48,7 +48,7 @@ Uses aMap of strings as the environment variables map. If includeExisting = true Sources: -- js/openaf.js:17677 +- js/openaf.js:17952 @@ -60,7 +60,7 @@ Immediately copies the result of executing aCmd string or array (and any other c Sources: -- js/openaf.js:17918 +- js/openaf.js:18193 @@ -72,7 +72,7 @@ Sets aFunc function to execute after the execution of aCmd (with .exec). Sources: -- js/openaf.js:17943 +- js/openaf.js:18218 @@ -84,7 +84,7 @@ When executing aCmd if aFunction is provided it will be called to determine if t Sources: -- js/openaf.js:17724 +- js/openaf.js:17999 @@ -96,7 +96,7 @@ Immediately copies the result of executing aCmd string or array (and any other c Sources: -- js/openaf.js:17818 +- js/openaf.js:18093 @@ -108,7 +108,7 @@ Immediately copies the result of executing aCmd string or array (and any other c Sources: -- js/openaf.js:17872 +- js/openaf.js:18147 @@ -120,7 +120,7 @@ Immediately copies the result of executing aCmd string or array (and any other c Sources: -- js/openaf.js:17849 +- js/openaf.js:18124 @@ -132,7 +132,7 @@ Immediately copies the result of executing aCmd string or array (and any other c Sources: -- js/openaf.js:17895 +- js/openaf.js:18170 @@ -144,7 +144,7 @@ Immediately creates aDir before executing aCmd (with .exec). Sources: -- js/openaf.js:17763 +- js/openaf.js:18038 @@ -156,7 +156,7 @@ Immediately moves aSource to aTarget before executing aCmd (with .exec). Sources: -- js/openaf.js:17774 +- js/openaf.js:18049 @@ -168,7 +168,7 @@ When executing aCmd (with .get) it will use ow.format.streamSHPrefix with aPrefi Sources: -- js/openaf.js:17736 +- js/openaf.js:18011 @@ -180,7 +180,7 @@ When executing aCmd (with .exec) use aPwd as the current working directory. Sources: -- js/openaf.js:17702 +- js/openaf.js:17977 @@ -192,7 +192,7 @@ Immediately renames aSource to aTarget before executing aCmd (with .exec). Sources: -- js/openaf.js:17796 +- js/openaf.js:18071 @@ -204,7 +204,7 @@ Immediately removes aFilePath before executing aCmd (with .exec). Sources: -- js/openaf.js:17807 +- js/openaf.js:18082 @@ -216,7 +216,7 @@ When executing aCmd (with .exec) sets additional aCmds (with the optional corres Sources: -- js/openaf.js:17691 +- js/openaf.js:17966 @@ -228,7 +228,7 @@ When executing aCmd (with .exec) uses aTimeout. Sources: -- js/openaf.js:17752 +- js/openaf.js:18027 @@ -240,5 +240,5 @@ Forces the aEncoding to be used. Sources: -- js/openaf.js:17654 +- js/openaf.js:17929 diff --git a/docs/ref/ssh-68b8caa6/index.md b/docs/ref/ssh-68b8caa6/index.md index 6a66d933..8e06ae10 100644 --- a/docs/ref/ssh-68b8caa6/index.md +++ b/docs/ref/ssh-68b8caa6/index.md @@ -12,7 +12,7 @@ Builds an object to allow access through ssh. aMap should be a ssh string with t Sources: -- js/openaf.js:17958 +- js/openaf.js:18233 @@ -24,7 +24,7 @@ Sets aCallback function to execute during the execution of commands on a remote Sources: -- js/openaf.js:18041 +- js/openaf.js:18316 @@ -36,7 +36,7 @@ Closes a remote host connection defined by aMap (host, port, login, pass, id, co Sources: -- js/openaf.js:18165 +- js/openaf.js:18440 @@ -48,7 +48,7 @@ Deletes a local tunnel mapping aLocalInterface:aLocalPort Sources: -- js/openaf.js:18222 +- js/openaf.js:18497 @@ -60,7 +60,7 @@ Deletes a remote tunnel mapping aRemoteInterface:aRemotePort Sources: -- js/openaf.js:18233 +- js/openaf.js:18508 @@ -72,7 +72,7 @@ Executes a list of commands previously set on a remote host connection defined b Sources: -- js/openaf.js:18295 +- js/openaf.js:18570 @@ -84,7 +84,7 @@ Sets a callback aFunc to execute upon a command execution s a remote host connec Sources: -- js/openaf.js:18322 +- js/openaf.js:18597 @@ -96,7 +96,7 @@ Executes a list of commands previously set on a remote host connection defined b Sources: -- js/openaf.js:18244 +- js/openaf.js:18519 @@ -108,7 +108,7 @@ Gets aSource filepath and stores it locally on aTarget from a remote host define Sources: -- js/openaf.js:18076 +- js/openaf.js:18351 @@ -120,7 +120,7 @@ Executes a list of commands previously set on a remote host connection defined b Sources: -- js/openaf.js:18271 +- js/openaf.js:18546 @@ -132,7 +132,7 @@ Returns an array of maps with the listing of aRemotePath provided. Sources: -- js/openaf.js:18109 +- js/openaf.js:18384 @@ -144,7 +144,7 @@ Creates aDirectory via SFTP on a remote host defined by aMap (host, port, login, Sources: -- js/openaf.js:18065 +- js/openaf.js:18340 @@ -156,7 +156,7 @@ When executing aCmd (with .get) it will use ow.format.streamSHPrefix with aPrefi Sources: -- js/openaf.js:18052 +- js/openaf.js:18327 @@ -168,7 +168,7 @@ Sets the flag to use or not a pty term allocation on the ssh connection to a rem Sources: -- js/openaf.js:18143 +- js/openaf.js:18418 @@ -180,7 +180,7 @@ Puts aSource local filepath and stores it remotely in aTarget on a remote host d Sources: -- js/openaf.js:18087 +- js/openaf.js:18362 @@ -192,7 +192,7 @@ Sets aPwd directory for getting and sending files to a remote host defined by aM Sources: -- js/openaf.js:18019 +- js/openaf.js:18294 @@ -204,7 +204,7 @@ Renames aSource filepath to aTarget filepath on a remote host defined by aMap (h Sources: -- js/openaf.js:18098 +- js/openaf.js:18373 @@ -216,7 +216,7 @@ Remove aFilePath from a remote host defined by aMap (host, port, login, pass, id Sources: -- js/openaf.js:18121 +- js/openaf.js:18396 @@ -228,7 +228,7 @@ Removes a directory from a remote host defined by aMap (host, port, login, pass, Sources: -- js/openaf.js:18132 +- js/openaf.js:18407 @@ -240,7 +240,7 @@ Sets aCmd to be executed with an optional aIn (stdin) on the remote host defined Sources: -- js/openaf.js:18008 +- js/openaf.js:18283 @@ -252,7 +252,7 @@ Sets aTimeout in ms for the ssh/sftp connection to a remote host defined by aMap Sources: -- js/openaf.js:18030 +- js/openaf.js:18305 @@ -264,7 +264,7 @@ Creates a local tunnel mapping aLocalPort to aRemoteHost:aRemotePort using the s Sources: -- js/openaf.js:18178 +- js/openaf.js:18453 @@ -276,7 +276,7 @@ Creates a local tunnel mapping aLocalInterface:aLocalPort to aRemoteHost:aRemote Sources: -- js/openaf.js:18189 +- js/openaf.js:18464 @@ -288,7 +288,7 @@ Creates a remote tunnel mapping aRemotePort to aLocalAddress:aLocalPort using th Sources: -- js/openaf.js:18200 +- js/openaf.js:18475 @@ -300,5 +300,5 @@ Creates a remote tunnel mapping aRemoteInterface:aRemotePort to aLocalAddress:aL Sources: -- js/openaf.js:18211 +- js/openaf.js:18486 diff --git a/js/nlinq.js b/js/nlinq.js index d87ff43a..456dc227 100644 --- a/js/nlinq.js +++ b/js/nlinq.js @@ -1,55 +1,1527 @@ -/*v:0.1.6;b:Nuno Aguiar;Copyright 2025 Nuno Aguiar;*/ -var nLinq_USE_CASE=!1,nLinq=function(h,l){$$(h).isMap()&&(l=_$(l,"aKey").isString().default("_key"),h=Object.keys(h).map(a=>{$$(h[a]).isMap()&&(h[a][l]=a);return h[a]}));var f=h,m="",e=nLinq_USE_CASE,g=!1,p=!1,t=0,w=0,H=!1,x=[],E=0,K=function(a,b){if(a===null||a===void 0||b===null||b===void 0)return a===b;if(a.constructor!==b.constructor)return!1;if(a instanceof Function||a instanceof RegExp)return a===b;if(a===b||a.valueOf()===b.valueOf())return!0;if(Array.isArray(a)&&a.length!==b.length||a instanceof -Date||!(a instanceof Object)||!(b instanceof Object))return!1;var d=Object.keys(a),k=Object.keys(b);if(d.length!=k.length)return!1;for(var n in a)if(d=a[n],$$(b[n]).isUnDef()||!K(d,b[n]))return!1;return!0},L=function(a,b,d){_$(a).isArray().$_();var k,n=!1;for(k=0;k{b[d]=$$(a[d]).isMap()?A(a[d]):a[d]});return b},M=function(a,b){var d= -new Set;b.forEach(k=>d.add(JSON.stringify(A(k),void 0,"")));return a.filter(k=>!d.has(JSON.stringify(A(k),void 0,"")))},N=function(a,b){var d=new Set;b.forEach(k=>d.add(JSON.stringify(A(k),void 0,"")));return a.filter(k=>d.has(JSON.stringify(A(k),void 0,"")))},O=function(a,b){var d=new Set;a.forEach(k=>d.add(JSON.stringify(A(k),void 0,"")));return a.concat(b.filter(k=>!d.has(JSON.stringify(A(k),void 0,""))))},P=function(a,b){return a.map(d=>b.map(k=>isMap(k)?merge(d,k):[d,k])).reduce((d,k)=>d.concat(k))}, -u=(a,b,d)=>{$$(a).isFunction()&&(a=a());$$(a).isArray()||(a=[a]);if(!$$(a).isUnDef()){if(E>0)if(d)for(d=0;d0?t:void 0):a}m=m.replace(/;/g," ");var k=$$(b).isFunction()?b:new Function("r","whereFn","return $$(r).isDef() ? ("+m+") : void 0");f=a.filter(n=>H?!k(n,x):k(n,x));w!=0&&(f=f.slice(w));t!=0&&(f=f.slice(t<0?t:0,t>0?t:void 0));return f}},Q=a=>{if($$(a).isString()&&a.replace(/^[^a-zA-Z_$]|[^\w\[\]\.$]/g, -"")==a)return a;if($$(a).isDef())throw"'"+a+"' is not a valid key.";},I=a=>{$$(a).isNumber()||$$(a).isBoolean()||($$(a).isString()&&(a=e?a:a.toLowerCase()),a=JSON.stringify(a,void 0,""));return a},R=a=>{var b=(k,n,r)=>{var v=Object.keys(k);_$(n,"aFunc").isFunction().$_();r=_$(r).isString().default("");for(var y in v)$$(k[v[y]]).isMap()||$$(k[v[y]]).isArray()?b(k[v[y]],n,(r==""?"":r+".")+v[y]):n(v[y],k[v[y]],r,k)},d={};b(a,(k,n,r,v)=>{d[r+(r==""?"":".")+k]=n});return d},q=(a,b,d,k,n,r)=>{if($$(r).isUnDef()&& -$$(a).isMap()){var v=R(a);Object.keys(v).forEach(B=>{q(B,v[B],d,k)})}else{var y=!0;if(n){n=$$(r).isDef();var J=b;b=I(n?b:a);r=I(n?r:J)}else{n=$$(b).isDef();b=I(n?b:a);try{a=n?Q(a):void 0}catch(B){if(String(B).indexOf("is not a valid key")>0)y=!1;else throw B;}}d.indexOf("{ki}")>=0&&(d=d.replace(/{ki}/g,$$(b).isString()&&!e?".toLowerCase()":""));d.indexOf("{ski}")>=0&&(d=d.replace(/{ski}/g,$$(b).isString()&&!e?"String(":""));d.indexOf("{eki}")>=0&&(d=d.replace(/{eki}/g,$$(b).isString()&&!e?").toLowerCase()": -""));d=n?d.replace(/{k}/g,y?"r."+a:"$$$$(r).get("+JSON.stringify(a)+")"):d.replace(/{k}/g,"r");$$(b).isString()&&(b=b.replace(/\$/g,"$$$"));$$(r).isDef()?($$(r).isString()&&(r=r.replace(/\$/g,"$$$")),r=I(r),d=d.replace(/{v}/g,b).replace(/{v2}/g,r)):d=d.replace(/{v}/g,b);F(d,k)}},F=(a,b)=>{b=_$(b).default(g);m.trim().length>0&&!m.trim().endsWith("(")&&(m=b?"("+m+") || ":m+" && ");m+="("+a+")"},c={_setState:a=>{_$(a,"map").isMap().$_();m=a.where;e=a.useCase;g=a.useOr;p=a.useNot;t=a.alimit;w=a.askip; -H=a.negative;x=a.whereFn;return c},_getState:()=>({where:m,useCase:e,useOr:g,useNot:p,alimit:t,askip:w,negative:H,whereFn:x}),useCase:a=>{e=!(!$$(a).isUnDef()&&!a);return c},ignoreCase:a=>{e=!($$(a).isUnDef()||a);return c},limit:a=>{$$(a).isNumber()&&(t=a);return c},head:a=>{c.limit(a);return c},tail:a=>{$$(a).isNumber()&&(t=-a);return c},or:()=>{g=!0;return c},and:()=>{g=!1;return c},not:()=>{p=!0;return c},andNot:()=>{g=!1;p=!0;return c},orNot:()=>{p=g=!0;return c},setWhere:a=>{F(a,!1);return c}, -where:a=>{g?p?c.orNotWhere(a):c.orWhere(a):p?c.andNotWhere(a):c.andWhere(a);return c},orWhere:a=>{_$(a,"fn").isFunction().$_();x.push(a);F("whereFn["+(x.length-1)+"](r)",!0);return c},andWhere:a=>{_$(a,"fn").isFunction().$_();x.push(a);F("whereFn["+(x.length-1)+"](r)",!1);return c},notWhere:a=>{g?c.orNotWhere(a):c.andNotWhere(a);return c},andNotWhere:a=>{_$(a,"fn").isFunction().$_();x.push(a);F("!whereFn["+(x.length-1)+"](r)",!1);return c},orNotWhere:a=>{_$(a,"fn").isFunction().$_();x.push(a);F("!whereFn["+ -(x.length-1)+"](r)",!0);return c},begin:()=>{m+=(m.trim().length>0&&!m.trim().endsWith("(")?" && ":"")+"(";E++;return c},orBegin:()=>{m+=(m.trim().length>0&&!m.trim().endsWith("(")?" || ":"")+"(";E++;return c},andBegin:()=>c.begin(),end:()=>{E>0&&(m+=")",E--);return c},starts:(a,b)=>{g?p?c.orNotStarts(a,b):c.orStarts(a,b):p?c.andNotStarts(a,b):c.andStarts(a,b);return c},ends:(a,b)=>{g?p?c.orNotEnds(a,b):c.orEnds(a,b):p?c.andNotEnds(a,b):c.andEnds(a,b);return c},equals:(a,b)=>{g?p?c.orNotEquals(a, -b):c.orEquals(a,b):p?c.andNotEquals(a,b):c.andEquals(a,b);return c},greater:(a,b)=>{g?p?c.orNotGreater(a,b):c.orGreater(a,b):p?c.andNotGreater(a,b):c.andGreater(a,b);return c},less:(a,b)=>{g?p?c.orNotLess(a,b):c.orLess(a,b):p?c.andNotLess(a,b):c.andLess(a,b);return c},greaterEquals:(a,b)=>{g?p?c.orNotGreaterEquals(a,b):c.orGreaterEquals(a,b):p?c.andNotGreaterEquals(a,b):c.andGreaterEquals(a,b);return c},lessEquals:(a,b)=>{g?p?c.orNotLessEquals(a,b):c.orLessEquals(a,b):p?c.andNotLessEquals(a,b):c.andLessEquals(a, -b);return c},contains:(a,b)=>{g?p?c.orNotContains(a,b):c.orContains(a,b):p?c.andNotContains(a,b):c.andContains(a,b);return c},empty:(a,b)=>{g?p?c.orNotEmpty(a,b):c.orEmpty(a,b):p?c.andNotEmpty(a,b):c.andEmpty(a,b);return c},match:(a,b)=>{g?p?c.orNotMatch(a,b):c.orMatch(a,b):p?c.andNotMatch(a,b):c.andMatch(a,b);return c},type:(a,b)=>{g?p?c.orNotType(a,b):c.orType(a,b):p?c.andNotType(a,b):c.andType(a,b);return c},between:(a,b,d)=>{g?p?c.orNotBetween(a,b,d):c.orBetween(a,b,d):p?c.andNotBetween(a,b,d): -c.andBetween(a,b,d);return c},betweenEquals:(a,b,d)=>{g?p?c.orNotBetweenEquals(a,b,d):c.orBetweenEquals(a,b,d):p?c.andNotBetweenEquals(a,b,d):c.andBetweenEquals(a,b,d);return c},is:a=>{g?p?c.orNotIs(a):c.orIs(a):p?c.andNotIs(a):c.andIs(a);return c},andStarts:(a,b)=>{q(a,b,"String({k}){ki}.startsWith({v})",!1);return c},andEnds:(a,b)=>{q(a,b,"String({k}){ki}.endsWith({v})",!1);return c},andEquals:(a,b)=>{q(a,b,"{ski}{k}{eki} == {v}",!1);return c},andGreater:(a,b)=>{q(a,b,"{ski}{k}{eki} > {v}",!1); -return c},andLess:(a,b)=>{q(a,b,"{ski}{k}{eki} < {v}",!1);return c},andGreaterEquals:(a,b)=>{q(a,b,"{ski}{k}{eki} >= {v}",!1);return c},andLessEquals:(a,b)=>{q(a,b,"{ski}{k}{eki} <= {v}",!1);return c},andContains:(a,b)=>{q(a,b,"String({k}){ki}.indexOf({v}) >= 0",!1);return c},andEmpty:(a,b)=>{q(a,"","($$({k}).isUnDef() || String({k}){ki}.length == 0)",!1);return c},andMatch:(a,b)=>{q(a,b,"String({k}){ki}.match({v})",!1);return c},andType:(a,b)=>{q(a,b,"typeof {k} == {v}",!1);return c},andBetween:(a, -b,d)=>{q(a,b,"({ski}{k}{eki} > {v} && {ski}{k}{eki} < {v2})",!1,!0,d);return c},andBetweenEquals:(a,b,d)=>{q(a,b,"({ski}{k}{eki} >= {v} && {ski}{k}{eki} <= {v2})",!1,!0,d);return c},andIs:a=>{q(a,"","{k} != null && {k}",!1);return c},notStarts:(a,b)=>{g?c.orNotStarts(a,b):c.andNotStarts(a,b);return c},notEnds:(a,b)=>{g?c.orNotEnds(a,b):c.andNotEnds(a,b);return c},notEquals:(a,b)=>{g?c.orNotEquals(a,b):c.andNotEquals(a,b);return c},notGreater:(a,b)=>{g?c.orNotGreater(a,b):c.andNotGreater(a,b);return c}, -notLess:(a,b)=>{g?c.orNotLess(a,b):c.andNotLess(a,b);return c},notGreaterEquals:(a,b)=>{g?c.orNotGreaterEquals(a,b):c.andNotGreaterEquals(a,b);return c},notLessEquals:(a,b)=>{g?c.orNotLessEquals(a,b):c.andNotLessEquals(a,b);return c},notContains:(a,b)=>{g?c.orNotContains(a,b):c.andNotContains(a,b);return c},notEmpty:(a,b)=>{g?c.orNotEmpty(a,b):c.andNotEmpty(a,b);return c},notMatch:(a,b)=>{g?c.orNotMatch(a,b):c.andNotMatch(a,b);return c},notType:(a,b)=>{g?c.orNotType(a,b):c.andNotType(a,b);return c}, -notBetween:(a,b,d)=>{g?c.orNotBetween(a,b,d):c.andNotBetween(a,b,d);return c},notBetweenEquals:(a,b,d)=>{g?c.orNotBetweenEquals(a,b,d):c.andNotBetweenEquals(a,b,d);return c},notIs:a=>{g?c.orNotIs(a):c.andNotIs(a);return c},andNotStarts:(a,b)=>{q(a,b,"!(String({k}){ki}.startsWith({v}))",!1);return c},andNotEnds:(a,b)=>{q(a,b,"!(String({k}){ki}.endsWith({v}))",!1);return c},andNotEquals:(a,b)=>{q(a,b,"{ski}{k}{eki} != {v}",!1);return c},andNotGreater:(a,b)=>{q(a,b,"{ski}{k}{eki} <= {v}",!1);return c}, -andNotLess:(a,b)=>{q(a,b,"{ski}{k}{eki} >= {v}",!1);return c},andNotGreaterEquals:(a,b)=>{q(a,b,"{ski}{k}{eki} < {v}",!1);return c},andNotLessEquals:(a,b)=>{q(a,b,"{ski}{k}{eki} > {v}",!1);return c},andNotContains:(a,b)=>{q(a,b,"String({k}){ki}.indexOf({v}) < 0",!1);return c},andNotEmpty:(a,b)=>{q(a,"","($$({k}).isDef() && String({k}){ki}.length != 0)",!1);return c},andNotMatch:(a,b)=>{q(a,b,"!(String({k}){ki}.match({v}))",!1);return c},andNotType:(a,b)=>{q(a,b,"typeof {k} != {v}",!1);return c},andNotBetween:(a, -b,d)=>{q(a,b,"({ski}{k}{eki} < {v} || {ski}{k}{eki} > {v2})",!1,!0,d);return c},andNotBetweenEquals:(a,b,d)=>{q(a,b,"({ski}{k}{eki} <= {v} || {ski}{k}{eki} >= {v2})",!1,!0,d);return c},andNotIs:a=>{q(a,"","{k} == null || !({k})",!1);return c},orStarts:(a,b)=>{q(a,b,"String({k}){ki}.startsWith({v})",!0);return c},orEnds:(a,b)=>{q(a,b,"String({k}){ki}.endsWith({v})",!0);return c},orEquals:(a,b)=>{q(a,b,"{ski}{k}{eki} == {v}",!0);return c},orGreater:(a,b)=>{q(a,b,"{ski}{k}{eki} > {v}",!0);return c}, -orLess:(a,b)=>{q(a,b,"{ski}{k}{eki} < {v}",!0);return c},orGreaterEquals:(a,b)=>{q(a,b,"{ski}{k}{eki} >= {v}",!0);return c},orLessEquals:(a,b)=>{q(a,b,"{ski}{k}{eki} <= {v}",!0);return c},orContains:(a,b)=>{q(a,b,"String({k}){ki}.indexOf({v}) >= 0",!0);return c},orEmpty:(a,b)=>{q(a,"","($$({k}).isUnDef() || String({k}){ki}.length == 0)",!0);return c},orMatch:(a,b)=>{q(a,b,"String({k}){ki}.match({v})",!0);return c},orType:(a,b)=>{q(a,b,"typeof {k} == {v}",!0);return c},orBetween:(a,b,d)=>{q(a,b,"({ski}{k}{eki} > {v} && {ski}{k}{eki} < {v2})", -!0,d);return c},orBetweenEquals:(a,b,d)=>{q(a,b,"({ski}{k}{eki} >= {v} && {ski}{k}{eki} <= {v2})",!0,d);return c},orIs:a=>{q(a,"","{k} != null && {k}",!0);return c},orNotStarts:(a,b)=>{q(a,b,"!(String({k}){ki}.startsWith({v}))",!0);return c},orNotEnds:(a,b)=>{q(a,b,"!(String({k}){ki}.endsWith({v}))",!0);return c},orNotEquals:(a,b)=>{q(a,b,"{ski}{k}{eki} != {v}",!0);return c},orNotGreater:(a,b)=>{q(a,b,"{ski}{k}{eki} <= {v}",!0);return c},orNotLess:(a,b)=>{q(a,b,"{ski}{k}{eki} >= {v}",!0);return c}, -orNotGreaterEquals:(a,b)=>{q(a,b,"{ski}{k}{eki} < {v}",!0);return c},orNotLessEquals:(a,b)=>{q(a,b,"{ski}{k}{eki} > {v}",!0);return c},orNotContains:(a,b)=>{q(a,b,"String({k}){ki}.indexOf({v}) < 0",!0);return c},orNotEmpty:(a,b)=>{q(a,"","($$({k}).isDef() && String({k}){ki}.length != 0)",!0);return c},orNotMatch:(a,b)=>{q(a,b,"!(String({k}){ki}.match({v}))",!0);return c},orNotType:(a,b)=>{q(a,b,"typeof {k} != {v}",!0);return c},orNotBetween:(a,b,d)=>{q(a,b,"({ski}{k}{eki} < {v} || {ski}{k}{eki} > {v2})", -!1,!0,d);return c},orNotBetweenEquals:(a,b,d)=>{q(a,b,"({ski}{k}{eki} <= {v} || {ski}{k}{eki} >= {v2})",!1,!0,d);return c},orNotIs:a=>{q(a,"","{k} == null || !({k})",!0);return c},min:a=>{a=_$(a).isString().default(void 0);var b;c.select(d=>{var k=$$(a).isDef()?Number($$(d).get(a)):Number(d);k!=null&&$$(k).isNumber()&&($$(b).isUnDef()?b=d:($$(a).isDef()&&$$(b).get(a)>k&&(b=d),$$(a).isUnDef()&&b>k&&(b=d)))});return b},max:a=>{a=_$(a).isString().default(void 0);var b;c.select(d=>{var k=$$(a).isDef()? -Number($$(d).get(a)):Number(d);k!=null&&$$(k).isNumber()&&($$(b).isUnDef()?b=d:($$(a).isDef()&&$$(b).get(a){a=_$(a).isString().default(void 0);var b=0,d=0;c.select(k=>{k=$$(a).isDef()?Number($$(k).get(a)):Number(k);k!=null&&$$(k).isNumber()&&(d++,b+=k)});return d>0?b/d:void 0},sum:a=>{a=_$(a).isString().default(void 0);var b=0;c.select(d=>{d=$$(a).isDef()?Number($$(d).get(a)):Number(d);d!=null&&$$(d).isNumber()&&(b+=d)});return b},distinct:a=> -{a=_$(a).isString().default(void 0);var b=[];c.select(d=>{d=$$(a).isDef()?$$(d).get(a):d;b.indexOf(d)<0&&b.push(d)});return b},group:a=>{a=_$(a).isString().default(void 0);var b={};c.select(d=>{var k=$$(a).isDef()?$$(d).get(a):d;Object.prototype.hasOwnProperty.call(b,k)?b[k].push(d):Object.defineProperty(b,k,{value:[d],enumerable:!0,writable:!0,configurable:!0})});return b},groupBy:a=>{a=_$(a).isString().default("key");var b=a.split(",");a={};var d=(k,n,r)=>{Object.keys(k).forEach((v,y)=>{Object.defineProperty(r, -v,{value:{},enumerable:!0,writable:!0,configurable:!0});n+10?(d(c.group(b[0]),0,a),a):[]},minBy:(a,b,d,k)=>c.fnBy(a,n=>$$(nLinq(n).min(b)).get(b),_$(d).default("_min"),k),maxBy:(a,b,d,k)=>c.fnBy(a,n=>$$(nLinq(n).max(b)).get(b),_$(d).default("_max"),k),averageBy:(a,b,d,k)=>c.fnBy(a,n=>nLinq(n).average(b),_$(d).default("_avg"),k),sumBy:(a,b,d,k)=>c.fnBy(a,n=>nLinq(n).sum(b),_$(d).default("_sum"),k),countBy:(a, -b,d)=>c.fnBy(a,k=>nLinq(k).count(),_$(b).default("_count"),d),fnBy:(a,b,d,k)=>{a=_$(a).isString().default("key");b=_$(b).isFunction().default(B=>B.length);d=_$(d).isString().default("_result");k=_$(k).isString().default(a);var n=a.split(","),r=k.split(","),v=[],y=typeof clone==="function"?clone:function C(z){if(!Array.isArray(z)&&!$$(z).isMap())return z;var D=Array.isArray(z)?Array(z.length):{};Object.keys(z).forEach(G=>{Object.defineProperty(D,G,{value:C(z[G]),enumerable:!0,writable:!0,configurable:!0})}); -return D},J=(z,C,D)=>{Object.keys(z).forEach((G,S)=>{D[r[C]]=G;C+10?(J(c.group(n[0]),0,{}),v):[]},at:a=>{_$(a,"index").isNumber().$_();f=u(f,void 0,!0);return f[Number(a)]},all:a=>{f=u(f,void 0,!0);return $$(f).isArray()?f.length==h.length:a},count:()=>{f=u(f,void 0,!0);return f.length},first:a=>{f=u(f,void 0,!0);return f.length>0?f[0]:a},last:a=>{f=u(f,void 0,!0);return f.length>0?f[f.length- -1]:a},any:()=>{f=u(f,void 0,!0);return f.length>0},none:()=>{f=u(f,void 0,!0);return f.length==0},reverse:()=>{f=u(f,void 0,!0);return f.reverse()},each:a=>{_$(a,"each function").isFunction().$_();c.select(a);return c},intersect:a=>{_$(a,"intersect param").isArray().$_();f=u(f);f=N(f,a);return c},except:a=>{_$(a,"except param").isArray().$_();f=u(f);f=M(f,a);return c},union:a=>{_$(a,"union param").isArray().$_();f=u(f);f=O(f,a);return c},cartesian:a=>{_$(a,"cartesian param").isArray().$_();f=u(f); -f=P(f,a);return c},attach:(a,b)=>{_$(a,"key").$_();_$(b,"value").$_();f=u(f);f=$$(b).isFunction()?f.map(d=>{$$(d).set(a,b(d));return d}):f.map(d=>{$$(d).set(a,b);return d});return c},attachBy:(a,b,d,k)=>{_$(a,"newkey").isString().$_();_$(b,"key").isString().$_();_$(d,"value").$_();_$(k,"class").$_();f=u(f);f=f.map(n=>{d==$$(n).get(b)&&$$(n).set(a,k);return n});return c},attachNotBy:(a,b,d,k)=>{_$(a,"newkey").isString().$_();_$(b,"key").isString().$_();_$(d,"value").$_();_$(k,"class").$_();f=u(f); -f=f.map(n=>{d!=$$(n).get(b)&&$$(n).set(a,k);return n});return c},attachByEmpty:(a,b)=>{_$(a,"newkey").isString().$_();_$(b,"class").$_();f=u(f);f=f.map(d=>{($$(d).get(a)==null||$$($$(d).get(a)).isUnDef())&&$$(d).set(a,b);return d});return c},detach:a=>{_$(a,"key").$_();f=u(f);f=f.map(b=>{$$(b).unset(a);return b});return c},toDate:a=>{_$(a,"key").$_();f=u(f);f.forEach(b=>{try{var d=$$(b).get(a);($$(d).isString()||$$(d).isNumber())&&$$(b).set(a,new Date(d))}catch(k){}});return c},filter:a=>{_$(a,"value").$_(); -f=u(f);f=f.filter(b=>{var d=!0;$$(a).isMap()&&$$(b).isMap()&&Object.keys(a).forEach(k=>{K(a[k],b[k])||(d=!1)});$$(b).isArray()&&L(b,a)<0&&(d=!1);$$(a).isFunction()&&!a(b)&&(d=!1);($$(a).isNumber()||$$(a).isString())&&($$(b).isNumber()||$$(b).isString())&&b!=a&&(d=!1);return d});return c},sort:function(){var a="";f=u(f);for(var b=0;b0?a+" || ":"return ";a=k?a+(' ($$(a).get("'+d+'") > $$(b).get("'+ -d+'") ? -1 : ($$(a).get("'+d+'") < $$(b).get("'+d+'") ? 1 : 0)) '):a+(' ($$(a).get("'+d+'") > $$(b).get("'+d+'") ? 1 : ($$(a).get("'+d+'") < $$(b).get("'+d+'") ? -1 : 0)) ')}f=f.sort(new Function("a","b",a));return c},assign:(a,b,d,k,n)=>{f=u(f);f.forEach(r=>{r[b]=nLinq(a).equals(k,$$(r).get(d)).first(n)});return c},join:(a,b,d,k)=>{f=u(f);f.forEach(n=>{n[b]=nLinq(a).equals(k,$$(n).get(d)).select()});return c},skip:a=>{_$(a).isNumber().$_();w=a;return c},skipWhile:a=>{_$(a,"skip function").isFunction().$_(); -c.notWhere(a);return c},takeWhile:a=>{_$(a,"take function").isFunction().$_();c.where(a);return c},take:a=>{_$(a).isNumber().$_();return c.limit(a)},skipTake:(a,b)=>{_$(a).isNumber().$_();return c.skip(a).take(b)},apply:a=>{a=_$(a,"aMap").isMap().default({});a.where=_$(a.where,"where").isArray().default([]);a.select=_$(a.select,"select").default(void 0);a.transform=_$(a.transform,"transform").isArray().default([]);a.selector=_$(a.selector,"selector").isMap().default(void 0);a.where.forEach(d=>{$$(d.cond).isString()&& -(c=c[d.cond].apply(c,d.args))});a.transform.forEach(d=>{$$(d.func).isString()&&(c=c[d.func].apply(c,d.args))});var b;$$(a.select).isString()&&(b=c.tselect(new Function("elem","index","array",a.select)));$$(a.select).isMap()&&(b=c.select(a.select));$$(b).isUnDef()&&$$(a.selector).isMap()&&(b=$$(a.selector.func).isString()?$$({}).set(a.selector.func,c[a.selector.func].apply(c,a.selector.args)):b);$$(b).isUnDef()&&$$(a.select).isUnDef()&&(b=c.select());return b},select:a=>{f=u(f,void 0,!0);if($$(a).isUnDef())return f; -if($$(a).isFunction())return f.map(a);if($$(a).isArray()){var b={};a.forEach(k=>{if($$(k).isString())if(k.indexOf(":")>0){var n=k.substring(0,k.indexOf(":"));k=k.substring(k.indexOf(":")+1);b[n]=k}else b[k]=k});return f.map(k=>{var n={};Object.keys(b).forEach(r=>$$(n).set(r,$$(k).get(b[r])));return n})}if($$(a).isMap()){var d=Object.keys(a);return f.map(k=>{var n={};d.forEach(r=>{$$($$(k).get(r)).isDef()?$$(n).set(r,$$(k).get(r)):$$(n).set(r,$$(a).get(r))});return n})}},mselect:(a,b,d)=>{a=c.select(a); -b=_$(b,"aKey").isString().default("_key");d=_$(d,"dontRemove").isBoolean().default(!0);var k={},n;for(n in a){var r=a[n];if($$(b).isDef()&&$$(r[b]).isDef()){var v=r[b];k[v]=r;d||delete k[v][b]}else k["row"+n]=r}return k},define:a=>{f=c.select(a);return c},removed:a=>{H=!0;f=c.select(a);return c},stream:a=>{var b=t>0?t:1;a=c.streamFn(a);do a(),t>0&&b--;while($$(f).isDef()&&b>0)},streamFn:a=>()=>{var b=c.select(a);f=$$(h).isFunction()?h():h;return b},query:a=>{a=_$(a,"aMap").isMap().default({});a.where= -_$(a.where,"where").isArray().default([]);a.select=_$(a.select,"select").default(void 0);a.transform=_$(a.transform,"transform").isArray().default([]);a.selector=_$(a.selector,"selector").isMap().default(void 0);a.where.forEach(d=>{$$(d.cond).isString()&&(c=c[d.cond].apply(c,d.args))});a.transform.forEach(d=>{$$(d.func).isString()&&(c=c[d.func].apply(c,d.args))});var b;$$(a.select).isString()&&(b=c.tselect(newFn("elem","index","array",a.select)));$$(a.select).isMap()&&(b=c.select(a.select));$$(b).isUnDef()&& -$$(a.selector).isMap()&&(b=$$(a.selector.func).isString()?c[a.selector.func].apply(c,a.selector.args):b);$$(b).isUnDef()&&$$(a.select).isUnDef()&&(b=c.select());return b}};return c},$from=nLinq;typeof isJavaObject!="defined"&&(isJavaObject=()=>!1); -const $$=function(h){return{get:l=>{if($$(h).isObject()){l=l.replace(/\[(\w+)\]/g,".$1");l=l.replace(/^\./,"");l=l.split(".");for(var f=0,m=l.length;f{if($$(h).isObject()){l=l.replace(/\[(\w+)\]/g,".$1");l=l.replace(/^\./,"");l=l.split(".");for(var f=0,m=l.length;fg[p.toUpperCase()]=p);if(e in g)h=h[g[e]];else return}else if(e in h)h= -h[e];else return}return h}},set:(l,f)=>{if($$(h).isObject()){var m=h;l=l.replace(/\[(\w+)\]/g,".$1");l=l.replace(/^\./,"");l=l.split(".");for(var e,g,p=0,t=l.length;p{if($$(h).isObject()){var f=h;l=l.replace(/\[(\w+)\]/g,".$1");l=l.replace(/^\./,"");l=l.split(".");for(var m,e,g=0,p=l.length;g!(!isJavaObject(h)&&typeof h=="undefined"),isUnDef:()=> -!(isJavaObject(h)||typeof h!="undefined"),isJavaObject:()=>isJavaObjecta(h),isArray:()=>Array.isArray(h),isMap:()=>Object.prototype.toString.call(h)=="[object Object]",isObject:()=>{var l=typeof h;return l==="function"||l==="object"&&!!h},isFunction:()=>typeof h=="function"||!1,isString:()=>typeof h=="string"||!1,isNumber:()=>!isNaN(parseFloat(h))&&isFinite(h),isTNumber:()=>typeof h=="number"||!1,isBoolean:()=>typeof h=="boolean"||!1,isNull:()=>null==h||!1,isDate:()=>null!=h&&!isNaN(h)&&"undefined"!== -typeof h.getDate,isRegExp:()=>h instanceof RegExp,isUUID:()=>!!h.match(/^\b[0-9a-f]{8}\b-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-\b[0-9a-f]{12}\b$/),isSchema:(l,f)=>{if(typeof Ajv=="undefined")if(typeof loadAjv!="undefined")loadAjv();else throw"Ajv library not loaded.";ow.loadObj();return ow.obj.schemaValidate(l,h,f)}}},_$=function(h,l){l=$$(l).isDef()?l+" ":"";var f=!!$$(h).isDef();var m={default:e=>f?h:e,$_:e=>{$$(e).isUnDef()&&(e=l+"not defined or assigned");if(!f)throw e;return h},isNumber:e=>{$$(e).isUnDef()&& -(e=l+"is not a number");if(f&&!$$(h).isNumber())throw e;return m},toNumber:e=>{$$(e).isUnDef()&&(e=l+"can't be converted to number");if(f)try{h=Number(h)}catch(g){throw e;}return m},isTNumber:e=>{$$(e).isUnDef()&&(e=l+"is not a number type");if(f&&!$$(h).isTNumber())throw e;return m},isString:e=>{$$(e).isUnDef()&&(e=l+"is not a string");if(f&&!$$(h).isString())throw e;return m},toString:e=>{$$(e).isUnDef()&&(e=l+"can't be converted to string");if(f)try{h=String(h)}catch(g){throw e;}return m},isBoolean:e=> -{$$(e).isUnDef()&&(e=l+"is not boolean");if(f&&typeof h!=="boolean")throw e;return m},toBoolean:e=>{$$(e).isUnDef()&&(e=l+"can't be converted to a boolean");if(f)try{$$(h).isNumber()&&(h=!!h),$$(h).isString()&&(h=h.trim().toLowerCase()=="true")}catch(g){throw e;}return m},isArray:e=>{$$(e).isUnDef()&&(e=l+"is not an array");if(f&&!$$(h).isArray())throw e;return m},toArray:e=>{$$(e).isUnDef()&&(e=l+"can't be converted to an array");if(f)try{h=String(h).split(",").map(g=>g.trim())}catch(g){throw e; -}return m},isMap:e=>{$$(e).isUnDef()&&(e=l+"is not a map");if(f&&!$$(h).isMap())throw e;return m},toMap:e=>{$$(e).isUnDef()&&(e=l+"can't be converted to a map");if(f)try{var g=h;h=$$(global.jsonParse).isFunction()?global.jsonParse(g,!0):JSON.parse(g)}catch(p){throw e;}return m},isObject:e=>{$$(e).isUnDef()&&(e=l+"is not an object");if(f&&!$$(h).isObject())throw e;return m},isDate:e=>{$$(e).isUnDef()&&(e=l+"is not a date");if(f&&!$$(h).isDate())throw e;return m},toDate:e=>{$$(e).isUnDef()&&(e=l+"can't be converted to date"); -if(f)try{h=new Date(h)}catch(g){throw e;}return m},isRegExp:e=>{$$(e).isUnDef()&&(e=l+"is not a RegExp");if(f&&!$$(h).isRegExp())throw e;return m},isFunction:e=>{$$(e).isUnDef()&&(e=l+"is not a function");if(f&&!$$(h).isFunction())throw e;return m},isJavaObject:e=>{$$(e).isUnDef()&&(e=l+"is not a java object");if(f&&!isJavaObject(h))throw e;return m},isInstanceOf:(e,g)=>{$$(g).isUnDef()&&(g=l+"is not an instance of "+e);if(f&&!(h instanceof e))throw g;return m},isNotNull:e=>{$$(e).isUnDef()&&(e=l+ -"is null");if(f&&h==null)throw e;return m},isUUID:e=>{$$(e).isUnDef()&&(e=l+"is not an UUID");if(f&&(!$$(h).isString()||h.match(/^\b[0-9a-f]{8}\b-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-\b[0-9a-f]{12}\b$/)))throw e;return m},isSchema:(e,g,p)=>{if(typeof Ajv=="undefined")if(typeof loadAjv!="undefined")loadAjv();else throw"Ajv library not loaded.";ow.loadObj();try{ow.obj.schemaValidate(e,h,p)}catch(t){throw $$(g).isUnDef()&&(g=l+" "+String(t)),g;}return m},check:(e,g)=>{if(!$$(e).isFunction()&&!$$(e).isString())throw"please provide a function to check"; -e=$$(e).isFunction()?e(h):newFn("v","return "+e)(h);$$(g).isUnDef()&&(g=l+"is not ok");if(f&&!e)throw g;return m},expr:(e,g)=>{if(!$$(e).isString())throw"please provide an expression";e=af.eval(templify(e,{v:h}));$$(g).isUnDef()&&(g=l+"is not ok");if(f&&!e)throw g;return m},equals:(e,g)=>{$$(g).isUnDef()&&(g=l+"is equals to "+e);if(f&&h==e)throw g;return m},notEquals:(e,g)=>{$$(g).isUnDef()&&(g=l+"is not equals to "+e);if(f&&h!=e)throw g;return m},anyOf:(e,g)=>{if(!$$(e).isArray())throw"please provide an array of values"; -$$(g).isUnDef()&&(g=l+"has a value not in "+JSON.stringify(e));f&&$$(h).isArray()&&h.forEach(p=>{if(e.indexOf(p)<0)throw g;});return m},oneOf:(e,g)=>{if(!$$(e).isArray())throw"please provide an array of values";$$(g).isUnDef()&&(g=l+"is not one of "+JSON.stringify(e));if(f&&!$$(h).isArray()&&e.indexOf(h)<0)throw g;return m},between:(e,g,p)=>{$$(p).isUnDef()&&(p=l+"is not between "+e+" and "+g);if(f&&(h>=g||h<=e))throw p;},betweenEquals:(e,g,p)=>{$$(p).isUnDef()&&(p=l+"is not between "+e+" and "+g); -if(f&&(h>g||h{$$(g).isUnDef()&&(g=l+"is less than "+e);if(f&&h>=e)throw g;return m},lessEquals:(e,g)=>{$$(g).isUnDef()&&(g=l+"is less or equals than "+e);if(f&&h>e)throw g;return m},greater:(e,g)=>{$$(g).isUnDef()&&(g=l+"is greater than "+e);if(f&&h<=e)throw g;return m},greaterEquals:(e,g)=>{$$(g).isUnDef()&&(g=l+"is greater or equals than "+e);if(f&&h{$$(e).isUnDef()&&(e=l+"is empty");if(f&&String(h)=="")throw e;return m},empty:e=>{$$(e).isUnDef()&& -(e=l+"is not empty");if(f&&String(h)!="")throw e;return m},contains:(e,g)=>{if(!$$(e).isString())throw"please provide a string to check if contains";$$(g).isUnDef()&&(g=l+"doesn't contain "+e);if(f&&String(h).indexOf(e)<0)throw g;return m},notContains:(e,g)=>{if(!$$(e).isString())throw"please provide a string to check if not contains";$$(g).isUnDef()&&(g=l+"contains "+e);if(f&&String(h).indexOf(e)>=0)throw g;return m},starts:(e,g)=>{if(!$$(e).isString())throw"please provide a string to check if it starts with"; -$$(g).isUnDef()&&(g=l+"doesn't start with '"+e+"'");if(f&&!h.startsWith(aValu))throw g;return m},ends:(e,g)=>{if(!$$(e).isString())throw"please provide a string to check if it ends with";$$(g).isUnDef()&&(g=l+"doesn't end with '"+e+"'");if(f&&!h.endsWith(e))throw g;return m},notStarts:(e,g)=>{if(!$$(e).isString())throw"please provide a string to check if it not starts with";$$(g).isUnDef()&&(g=l+"starts with '"+e+"'");if(f&&h.startsWith(aValu))throw g;return m},notEnds:(e,g)=>{if(!$$(e).isString())throw"please provide a string to check if it not ends with"; -$$(g).isUnDef()&&(g=l+"ends with '"+e+"'");if(f&&h.endsWith(e))throw g;return m},regexp:(e,g)=>{$$(g).isUnDef()&&(g=l+"doesn't match '"+e+"'");if(!(e instanceof RegExp))throw"is not a regular expression ("+e+")";if(f&&!e.test(h))throw g;return m},javaRegexp:(e,g,p)=>{if($$(e).isUnDef()||!$$(e).isString())throw"please provide a regular expression string";$$(p).isUnDef()&&(p=l+"doesn't match '"+e+"'");if(f&&!javaRegExp(h).test(e,g))throw p;return m}};return m}; +// nlinq.js +// + +// Version: 0.1.6 +// Copyright 2025 Nuno Aguiar + +var nLinq_USE_CASE = false; +var nLinq = function(anObject, aK) { + // Verify input + if ($$(anObject).isMap()) { + aK = _$(aK, "aKey").isString().default("_key") + anObject = Object.keys(anObject).map(k => { + if ($$(anObject[k]).isMap()) anObject[k][aK] = k; + return anObject[k]; + }); + } + + //_$(anObject).isArray().$_(); + var res = anObject, where = "", useCase = nLinq_USE_CASE, useOr = false, useNot = false, alimit = 0, askip = 0, negative = false, whereFn = [], block = 0; + + // Auxiliary functions + + var aCompare = function(x, y) { + 'use strict'; + + if (x === null || x === undefined || y === null || y === undefined) { return x === y; } + if (x.constructor !== y.constructor) { return false; } + if (x instanceof Function) { return x === y; } + if (x instanceof RegExp) { return x === y; } + if (x === y || x.valueOf() === y.valueOf()) { return true; } + if (Array.isArray(x) && x.length !== y.length) { return false; } + if (x instanceof Date) { return false; } + if (!(x instanceof Object)) { return false; } + if (!(y instanceof Object)) { return false; } + + var p = Object.keys(x), q = Object.keys(y); + if (p.length != q.length) return false; + for(var k in x) { + var v = x[k]; + if ($$(y[k]).isUnDef() || (!aCompare(v, y[k]))) return false; + } + + return true; + } + + var aArrayContains = function(anArray, aObj, aPreFilter) { + _$(anArray).isArray().$_(); + + var ii, found = false; + for(ii = 0; ii < anArray.length && !found; ii++) { + var o = ($$(aPreFilter).isFunction()) ? aPreFilter(anArray[ii]) : anArray[ii]; + if (aCompare(aObj, o)) found = true; + } + + return (found ? ii-1 : -1); + } + + var aSortMap = function(aMap) { + if (!$$(aMap).isMap()) return aMap; + + var rrr = {}, ks = Object.keys(aMap).sort(); + ks.forEach(k => { + rrr[k] = ($$(aMap[k]).isMap() ? aSortMap(aMap[k]) : aMap[k]); + }); + return rrr; + } + + var aException = function(aArrayA, aArrayB) { + var cb = new Set() + aArrayB.forEach(r => cb.add(JSON.stringify(aSortMap(r), void 0, ""))) + return aArrayA.filter(r => !cb.has(JSON.stringify(aSortMap(r), void 0, ""))) + } + + var aIntersection = function(aArrayA, aArrayB) { + var cb = new Set() + aArrayB.forEach(r => cb.add(JSON.stringify(aSortMap(r), void 0, ""))) + return aArrayA.filter(r => cb.has(JSON.stringify(aSortMap(r), void 0, ""))) + } + + var aUnion = function(aArrayA, aArrayB) { + var ca = new Set() + aArrayA.forEach(r => ca.add(JSON.stringify(aSortMap(r), void 0, ""))) + return aArrayA.concat(aArrayB.filter(r => !ca.has(JSON.stringify(aSortMap(r), void 0, "")))) + } + + var aCartesian = function(aArrayA, aArrayB) { + return aArrayA.map(n => aArrayB.map(m => isMap(m) ? merge(n, m) : [n, m])).reduce((a, v) => a.concat(v)); + } + + // Auxiliary functions - apply query conditions + var applyConditions = (aOrig, aFunc, isEnd) => { + if ($$(aOrig).isFunction()) aOrig = aOrig(); + if (!$$(aOrig).isArray()) aOrig = [ aOrig ]; + if ($$(aOrig).isUnDef()) return void 0; + + if (block > 0) { + if (isEnd) { + for(var i = 0; i < block; i++) { + where += ")" + } + } else { + return aOrig + } + } + + if (where.length == 0) { + if (negative) return []; + + if (askip != 0) { + aOrig = aOrig.slice(askip); + } + if (alimit != 0) { + return aOrig.slice(alimit < 0 ? alimit : 0, alimit > 0 ? alimit : void 0); + } else { + return aOrig; + } + } + + where = where.replace(/\;/g, " "); + var f; + if ($$(aFunc).isFunction()) { + f = aFunc; + } else { + f = new Function("r", "whereFn", "return $$(r).isDef() ? (" + where + ") : void 0"); + } + res = aOrig.filter(r => negative ? !f(r, whereFn) : f(r, whereFn)) + if (askip != 0) { + res = res.slice(askip); + } + if (alimit != 0) { + res = res.slice(alimit < 0 ? alimit : 0, alimit > 0 ? alimit : void 0) + } + return res; + }; + + // Auxiliary functions - verify the provided key + var vKey = (aKey) => { + if ($$(aKey).isString() && aKey.replace(/^[^a-zA-Z_$]|[^\w\[\]\.$]/g, "") == aKey) { + return aKey; + } else { + if ($$(aKey).isDef()) throw "'" + aKey + "' is not a valid key."; else return void 0; + } + }; + + // Auxiliary functions - verify the provided value + var vValue = aValue => { + if (!($$(aValue).isNumber() || $$(aValue).isBoolean())) { + if ($$(aValue).isString()) aValue = (!useCase ? aValue.toLowerCase() : aValue); + aValue = JSON.stringify(aValue, void 0, ""); + } + return aValue; + }; + + var flatObj = aObj => { + var _t = (aMap, aFunc, aParent) => { + var keys = Object.keys(aMap) + _$(aFunc, "aFunc").isFunction().$_() + var aParent = _$(aParent).isString().default("") + + for(var i in keys) { + if ($$(aMap[keys[i]]).isMap() || $$(aMap[keys[i]]).isArray()) { + var newParent = ((aParent == "") ? "" : aParent + ".") + keys[i] + _t(aMap[keys[i]], aFunc, newParent) + } else { + aFunc(keys[i], aMap[keys[i]], aParent, aMap) + } + } + } + + var _m = {} + _t(aObj, (aK, aV, aP, aO) => { + _m[aP + (aP == "" ? "" : ".") + aK] = aV + }) + return _m + } + + // Auxiliary functions - given a key, a value, a query template app change the current query + var applyWhere = (aKey, aValue, aTmpl, isOr, isTwoValues, aValue2) => { + // If aKey is a map perform multiple applies + if ($$(aValue2).isUnDef() && $$(aKey).isMap()) { + var _m = flatObj(aKey) + Object.keys(_m).forEach(k => { + applyWhere(k, _m[k], aTmpl, isOr) + }) + return + } + + var isM, useDot = true; + if (isTwoValues) { + isM = $$(aValue2).isDef(); + var origValue = aValue; + aValue = vValue(isM ? aValue : aKey); + aValue2 = vValue(isM ? aValue2 : origValue); + } else { + isM = $$(aValue).isDef(); + aValue = vValue(isM ? aValue : aKey); + try { + aKey = isM ? vKey(aKey) : void 0; + } catch(e) { + if (String(e).indexOf("is not a valid key") > 0) { + useDot = false; + } else { + throw e; + } + } + } + + if (aTmpl.indexOf("{ki}") >= 0) aTmpl = aTmpl.replace(/{ki}/g, ($$(aValue).isString() && !useCase ? ".toLowerCase()" : "")); + if (aTmpl.indexOf("{ski}") >= 0) aTmpl = aTmpl.replace(/{ski}/g, ($$(aValue).isString() && !useCase ? "String(" : "")); + if (aTmpl.indexOf("{eki}") >= 0) aTmpl = aTmpl.replace(/{eki}/g, ($$(aValue).isString() && !useCase ? ").toLowerCase()" : "")); + if (isM) aTmpl = aTmpl.replace(/{k}/g, (!useDot ? "$$$$(r).get(" + JSON.stringify(aKey) + ")" : "r." + aKey)); else aTmpl = aTmpl.replace(/{k}/g, "r"); + + if ($$(aValue).isString()) aValue = aValue.replace(/\$/g, "$$$"); + if ($$(aValue2).isDef()) { + if ($$(aValue2).isString()) aValue2 = aValue2.replace(/\$/g, "$$$"); + aValue2 = vValue(aValue2); + aTmpl = aTmpl.replace(/{v}/g, aValue).replace(/{v2}/g, aValue2); + } else { + aTmpl = aTmpl.replace(/{v}/g, aValue); + } + applyWhereTmpl(aTmpl, isOr); + }; + + // Auxiliary functions - append a sub-query to the current query + var applyWhereTmpl = (aTmpl, isOr) => { + isOr = _$(isOr).default(useOr); + + if (where.trim().length > 0 && !where.trim().endsWith("(")) { + if (!isOr) { + where += " && "; + } else { + where = "(" + where + ") || "; + } + } + where += "(" + aTmpl + ")"; + }; + + var countRows = rows => rows.length; + var plainPath = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/; + var fieldReader = aKey => { + if (aKey === void 0) return null; + if (!plainPath.test(aKey)) return row => $$(row).get(aKey); + if (aKey.indexOf(".") < 0) { + return row => { + if (row === null || typeof row !== "object") return $$(row).get(aKey); + return aKey in row ? row[aKey] : void 0; + }; + } + var parts = aKey.split("."); + return row => { + if (row === null || typeof row !== "object") return $$(row).get(aKey); + for (var i = 0; i < parts.length; i++) { + if (!(parts[i] in row)) return void 0; + row = row[parts[i]]; + } + return row; + }; + }; + + // Main code + var code = { + _setState : aMap => { + _$(aMap, "map").isMap().$_(); + where = aMap.where; + useCase = aMap.useCase; + useOr = aMap.useOr; + useNot = aMap.useNot; + alimit = aMap.alimit; + askip = aMap.askip; + negative = aMap.negative; + whereFn = aMap.whereFn; + + return code; + }, + _getState : () => { + return { + where: where, + useCase: useCase, + useOr: useOr, + useNot: useNot, + alimit: alimit, + askip: askip, + negative: negative, + whereFn: whereFn + }; + }, + // Change default behaviour + useCase : aTmpl => { useCase = ($$(aTmpl).isUnDef() || aTmpl ? true : false); return code; }, + ignoreCase : aTmpl => { useCase = ($$(aTmpl).isUnDef() || aTmpl ? false : true); return code; }, + limit : aNum => { if ($$(aNum).isNumber()) { alimit = aNum; } return code; }, + head : aNum => { code.limit(aNum); return code; }, + tail : aNum => { if ($$(aNum).isNumber()) { alimit = -aNum; } return code; }, + // TODO: Support remembering the previous key if none provided + or : () => { useOr = true; return code; }, + and : () => { useOr = false; return code; }, + not : () => { useNot = true; return code; }, + andNot : () => { useOr = false; useNot = true; return code; }, + orNot : () => { useOr = true; useNot = true; return code; }, + + // WHEREs + setWhere : aTmpl => { applyWhereTmpl(aTmpl, false); return code; }, + where : aFn => { if (useOr) { if (useNot) code.orNotWhere(aFn); else code.orWhere(aFn); } else { if (useNot) code.andNotWhere(aFn); else code.andWhere(aFn); } return code; }, + orWhere : aFn => { + _$(aFn, "fn").isFunction().$_(); + + whereFn.push(aFn); + applyWhereTmpl("whereFn[" + (whereFn.length-1) + "](r)", true); + return code; + }, + andWhere : aFn => { + _$(aFn, "fn").isFunction().$_(); + + whereFn.push(aFn); + applyWhereTmpl("whereFn[" + (whereFn.length-1) + "](r)", false); + return code; + }, + notWhere : aFn => { if (useOr) code.orNotWhere(aFn); else code.andNotWhere(aFn); return code; }, + andNotWhere : aFn => { + _$(aFn, "fn").isFunction().$_(); + + whereFn.push(aFn); + applyWhereTmpl("!whereFn[" + (whereFn.length-1) + "](r)", false); + return code; + }, + orNotWhere : aFn => { + _$(aFn, "fn").isFunction().$_(); + + whereFn.push(aFn); + applyWhereTmpl("!whereFn[" + (whereFn.length-1) + "](r)", true); + return code; + }, + + begin: () => { + where += (where.trim().length > 0 && !where.trim().endsWith("(") ? " && " : "") + "(" + block++ + return code + }, + + orBegin: () => { + where += (where.trim().length > 0 && !where.trim().endsWith("(") ? " || " : "") + "(" + block++ + return code + }, + + andBegin: () => { + return code.begin() + }, + + end : () => { + if (block > 0) { + where += ")" + block-- + } + return code + }, + + // Main queries + starts : (aKey, aValue) => { if (useOr) { if (useNot) code.orNotStarts(aKey, aValue); else code.orStarts(aKey, aValue); } else { if (useNot) code.andNotStarts(aKey, aValue); else code.andStarts(aKey, aValue); } return code; }, + ends : (aKey, aValue) => { if (useOr) { if (useNot) code.orNotEnds(aKey, aValue); else code.orEnds(aKey, aValue); } else { if (useNot) code.andNotEnds(aKey, aValue); else code.andEnds(aKey, aValue); } return code; }, + equals : (aKey, aValue) => { if (useOr) { if (useNot) code.orNotEquals(aKey, aValue); else code.orEquals(aKey, aValue); } else { if (useNot) code.andNotEquals(aKey, aValue); else code.andEquals(aKey, aValue); } return code; }, + greater : (aKey, aValue) => { if (useOr) { if (useNot) code.orNotGreater(aKey, aValue); else code.orGreater(aKey, aValue); } else { if (useNot) code.andNotGreater(aKey, aValue); else code.andGreater(aKey, aValue); } return code; }, + less : (aKey, aValue) => { if (useOr) { if (useNot) code.orNotLess(aKey, aValue); else code.orLess(aKey, aValue); } else { if (useNot) code.andNotLess(aKey, aValue); else code.andLess(aKey, aValue); } return code; }, + greaterEquals: (aKey, aValue) => { if (useOr) { if (useNot) code.orNotGreaterEquals(aKey, aValue); else code.orGreaterEquals(aKey, aValue); } else { if (useNot) code.andNotGreaterEquals(aKey, aValue); else code.andGreaterEquals(aKey, aValue); } return code; }, + lessEquals : (aKey, aValue) => { if (useOr) { if (useNot) code.orNotLessEquals(aKey, aValue); else code.orLessEquals(aKey, aValue); } else { if (useNot) code.andNotLessEquals(aKey, aValue); else code.andLessEquals(aKey, aValue); } return code; }, + contains : (aKey, aValue) => { if (useOr) { if (useNot) code.orNotContains(aKey, aValue); else code.orContains(aKey, aValue); } else { if (useNot) code.andNotContains(aKey, aValue); else code.andContains(aKey, aValue); } return code; }, + empty : (aKey, aValue) => { if (useOr) { if (useNot) code.orNotEmpty(aKey, aValue); else code.orEmpty(aKey, aValue); } else { if (useNot) code.andNotEmpty(aKey, aValue); else code.andEmpty(aKey, aValue); } return code; }, + match : (aKey, aValue) => { if (useOr) { if (useNot) code.orNotMatch(aKey, aValue); else code.orMatch(aKey, aValue); } else { if (useNot) code.andNotMatch(aKey, aValue); else code.andMatch(aKey, aValue); } return code; }, + type : (aKey, aValue) => { if (useOr) { if (useNot) code.orNotType(aKey, aValue); else code.orType(aKey, aValue); } else { if (useNot) code.andNotType(aKey, aValue); else code.andType(aKey, aValue); } return code; }, + between : (aKey, aV1, aV2) => { if (useOr) { if (useNot) code.orNotBetween(aKey, aV1, aV2); else code.orBetween(aKey, aV1, aV2); } else { if (useNot) code.andNotBetween(aKey, aV1, aV2); else code.andBetween(aKey, aV1, aV2); } return code; }, + betweenEquals: (aKey, aV1, aV2) => { if (useOr) { if (useNot) code.orNotBetweenEquals(aKey, aV1, aV2); else code.orBetweenEquals(aKey, aV1, aV2); } else { if (useNot) code.andNotBetweenEquals(aKey, aV1, aV2); else code.andBetweenEquals(aKey, aV1, aV2); } return code; }, + is : (aKey) => { if (useOr) { if (useNot) code.orNotIs(aKey); else code.orIs(aKey); } else { if (useNot) code.andNotIs(aKey); else code.andIs(aKey); } return code; }, + + // Queries with and + andStarts : (aKey, aValue) => { applyWhere(aKey, aValue, "String({k}){ki}.startsWith({v})", false); return code; }, + andEnds : (aKey, aValue) => { applyWhere(aKey, aValue, "String({k}){ki}.endsWith({v})", false); return code; }, + andEquals : (aKey, aValue) => { applyWhere(aKey, aValue, "{ski}{k}{eki} == {v}", false); return code; }, + andGreater : (aKey, aValue) => { applyWhere(aKey, aValue, "{ski}{k}{eki} > {v}", false); return code; }, + andLess : (aKey, aValue) => { applyWhere(aKey, aValue, "{ski}{k}{eki} < {v}", false); return code; }, + andGreaterEquals: (aKey, aValue) => { applyWhere(aKey, aValue, "{ski}{k}{eki} >= {v}", false); return code; }, + andLessEquals : (aKey, aValue) => { applyWhere(aKey, aValue, "{ski}{k}{eki} <= {v}", false); return code; }, + andContains : (aKey, aValue) => { applyWhere(aKey, aValue, "String({k}){ki}.indexOf({v}) >= 0", false); return code; }, + andEmpty : (aKey, aValue) => { applyWhere(aKey, "", "($$({k}).isUnDef() || String({k}){ki}.length == 0)", false); return code; }, + andMatch : (aKey, aValue) => { applyWhere(aKey, aValue, "String({k}){ki}.match({v})", false); return code; }, + andType : (aKey, aValue) => { applyWhere(aKey, aValue, "typeof {k} == {v}", false); return code; }, + andBetween : (aKey, aV1, aV2) => { applyWhere(aKey, aV1, "({ski}{k}{eki} > {v} && {ski}{k}{eki} < {v2})", false, true, aV2); return code; }, + andBetweenEquals: (aKey, aV1, aV2) => { applyWhere(aKey, aV1, "({ski}{k}{eki} >= {v} && {ski}{k}{eki} <= {v2})", false, true, aV2); return code; }, + andIs : (aKey) => { applyWhere(aKey, "", "{k} != null && {k}", false); return code; }, + + // Queries with not + notStarts : (aKey, aValue) => { if (useOr) code.orNotStarts(aKey, aValue); else code.andNotStarts(aKey, aValue); return code; }, + notEnds : (aKey, aValue) => { if (useOr) code.orNotEnds(aKey, aValue); else code.andNotEnds(aKey, aValue); return code; }, + notEquals : (aKey, aValue) => { if (useOr) code.orNotEquals(aKey, aValue); else code.andNotEquals(aKey, aValue); return code; }, + notGreater : (aKey, aValue) => { if (useOr) code.orNotGreater(aKey, aValue); else code.andNotGreater(aKey, aValue); return code; }, + notLess : (aKey, aValue) => { if (useOr) code.orNotLess(aKey, aValue); else code.andNotLess(aKey, aValue); return code; }, + notGreaterEquals: (aKey, aValue) => { if (useOr) code.orNotGreaterEquals(aKey, aValue); else code.andNotGreaterEquals(aKey, aValue); return code; }, + notLessEquals : (aKey, aValue) => { if (useOr) code.orNotLessEquals(aKey, aValue); else code.andNotLessEquals(aKey, aValue); return code; }, + notContains : (aKey, aValue) => { if (useOr) code.orNotContains(aKey, aValue); else code.andNotContains(aKey, aValue); return code; }, + notEmpty : (aKey, aValue) => { if (useOr) code.orNotEmpty(aKey, aValue); else code.andNotEmpty(aKey, aValue); return code; }, + notMatch : (aKey, aValue) => { if (useOr) code.orNotMatch(aKey, aValue); else code.andNotMatch(aKey, aValue); return code; }, + notType : (aKey, aValue) => { if (useOr) code.orNotType(aKey, aValue); else code.andNotType(aKey, aValue); return code; }, + notBetween : (aKey, aV1, aV2) => { if (useOr) code.orNotBetween(aKey, aV1, aV2); else code.andNotBetween(aKey, aV1, aV2); return code; }, + notBetweenEquals: (aKey, aV1, aV2) => { if (useOr) code.orNotBetweenEquals(aKey, aV1, aV2); else code.andNotBetweenEquals(aKey, aV1, aV2); return code; }, + notIs : (aKey) => { if (useOr) code.orNotIs(aKey); else code.andNotIs(aKey); return code; }, + + // Queries with and & not + andNotStarts : (aKey, aValue) => { applyWhere(aKey, aValue, "!(String({k}){ki}.startsWith({v}))", false); return code; }, + andNotEnds : (aKey, aValue) => { applyWhere(aKey, aValue, "!(String({k}){ki}.endsWith({v}))", false); return code; }, + andNotEquals : (aKey, aValue) => { applyWhere(aKey, aValue, "{ski}{k}{eki} != {v}", false); return code; }, + andNotGreater : (aKey, aValue) => { applyWhere(aKey, aValue, "{ski}{k}{eki} <= {v}", false); return code; }, + andNotLess : (aKey, aValue) => { applyWhere(aKey, aValue, "{ski}{k}{eki} >= {v}", false); return code; }, + andNotGreaterEquals: (aKey, aValue) => { applyWhere(aKey, aValue, "{ski}{k}{eki} < {v}", false); return code; }, + andNotLessEquals : (aKey, aValue) => { applyWhere(aKey, aValue, "{ski}{k}{eki} > {v}", false); return code; }, + andNotContains : (aKey, aValue) => { applyWhere(aKey, aValue, "String({k}){ki}.indexOf({v}) < 0", false); return code; }, + andNotEmpty : (aKey, aValue) => { applyWhere(aKey, "", "($$({k}).isDef() && String({k}){ki}.length != 0)", false); return code; }, + andNotMatch : (aKey, aValue) => { applyWhere(aKey, aValue, "!(String({k}){ki}.match({v}))", false); return code; }, + andNotType : (aKey, aValue) => { applyWhere(aKey, aValue, "typeof {k} != {v}", false); return code; }, + andNotBetween : (aKey, aV1, aV2) => { applyWhere(aKey, aV1, "({ski}{k}{eki} < {v} || {ski}{k}{eki} > {v2})", false, true, aV2); return code; }, + andNotBetweenEquals: (aKey, aV1, aV2) => { applyWhere(aKey, aV1, "({ski}{k}{eki} <= {v} || {ski}{k}{eki} >= {v2})", false, true, aV2); return code; }, + andNotIs : (aKey) => { applyWhere(aKey, "", "{k} == null || !({k})", false); return code; }, + + // Queries with or + orStarts : (aKey, aValue) => { applyWhere(aKey, aValue, "String({k}){ki}.startsWith({v})", true); return code; }, + orEnds : (aKey, aValue) => { applyWhere(aKey, aValue, "String({k}){ki}.endsWith({v})", true); return code; }, + orEquals : (aKey, aValue) => { applyWhere(aKey, aValue, "{ski}{k}{eki} == {v}", true); return code; }, + orGreater : (aKey, aValue) => { applyWhere(aKey, aValue, "{ski}{k}{eki} > {v}", true); return code; }, + orLess : (aKey, aValue) => { applyWhere(aKey, aValue, "{ski}{k}{eki} < {v}", true); return code; }, + orGreaterEquals: (aKey, aValue) => { applyWhere(aKey, aValue, "{ski}{k}{eki} >= {v}", true); return code; }, + orLessEquals : (aKey, aValue) => { applyWhere(aKey, aValue, "{ski}{k}{eki} <= {v}", true); return code; }, + orContains : (aKey, aValue) => { applyWhere(aKey, aValue, "String({k}){ki}.indexOf({v}) >= 0", true); return code; }, + orEmpty : (aKey, aValue) => { applyWhere(aKey, "", "($$({k}).isUnDef() || String({k}){ki}.length == 0)", true); return code; }, + orMatch : (aKey, aValue) => { applyWhere(aKey, aValue, "String({k}){ki}.match({v})", true); return code; }, + orType : (aKey, aValue) => { applyWhere(aKey, aValue, "typeof {k} == {v}", true); return code; }, + orBetween : (aKey, aV1, aV2) => { applyWhere(aKey, aV1, "({ski}{k}{eki} > {v} && {ski}{k}{eki} < {v2})", true, aV2); return code; }, + orBetweenEquals: (aKey, aV1, aV2) => { applyWhere(aKey, aV1, "({ski}{k}{eki} >= {v} && {ski}{k}{eki} <= {v2})", true, aV2); return code; }, + orIs : (aKey) => { applyWhere(aKey, "", "{k} != null && {k}", true); return code; }, + + // Queries with or and not + orNotStarts : (aKey, aValue) => { applyWhere(aKey, aValue, "!(String({k}){ki}.startsWith({v}))", true); return code; }, + orNotEnds : (aKey, aValue) => { applyWhere(aKey, aValue, "!(String({k}){ki}.endsWith({v}))", true); return code; }, + orNotEquals : (aKey, aValue) => { applyWhere(aKey, aValue, "{ski}{k}{eki} != {v}", true); return code; }, + orNotGreater : (aKey, aValue) => { applyWhere(aKey, aValue, "{ski}{k}{eki} <= {v}", true); return code; }, + orNotLess : (aKey, aValue) => { applyWhere(aKey, aValue, "{ski}{k}{eki} >= {v}", true); return code; }, + orNotGreaterEquals: (aKey, aValue) => { applyWhere(aKey, aValue, "{ski}{k}{eki} < {v}", true); return code; }, + orNotLessEquals : (aKey, aValue) => { applyWhere(aKey, aValue, "{ski}{k}{eki} > {v}", true); return code; }, + orNotContains : (aKey, aValue) => { applyWhere(aKey, aValue, "String({k}){ki}.indexOf({v}) < 0", true); return code; }, + orNotEmpty : (aKey, aValue) => { applyWhere(aKey, "", "($$({k}).isDef() && String({k}){ki}.length != 0)", true); return code; }, + orNotMatch : (aKey, aValue) => { applyWhere(aKey, aValue, "!(String({k}){ki}.match({v}))", true); return code; }, + orNotType : (aKey, aValue) => { applyWhere(aKey, aValue, "typeof {k} != {v}", true); return code; }, + orNotBetween : (aKey, aV1, aV2) => { applyWhere(aKey, aV1, "({ski}{k}{eki} < {v} || {ski}{k}{eki} > {v2})", false, true, aV2); return code; }, + orNotBetweenEquals: (aKey, aV1, aV2) => { applyWhere(aKey, aV1, "({ski}{k}{eki} <= {v} || {ski}{k}{eki} >= {v2})", false, true, aV2); return code; }, + orNotIs : (aKey) => { applyWhere(aKey, "", "{k} == null || !({k})", true); return code; }, + + // SELECTS + + // Providing immediate result + min : aKey => { + var readKey = fieldReader(_$(aKey).isString().default(void 0)); + var min; + + code.select().forEach(r => { + var v = Number(readKey === null ? r : readKey(r)); + if (Number.isFinite(v) && (min === void 0 || (readKey === null ? min : readKey(min)) > v)) { + min = r; + } + }); + + return min; + }, + max : aKey => { + var readKey = fieldReader(_$(aKey).isString().default(void 0)); + var max; + + code.select().forEach(r => { + var v = Number(readKey === null ? r : readKey(r)); + if (Number.isFinite(v) && (max === void 0 || (readKey === null ? max : readKey(max)) < v)) { + max = r; + } + }); + + return max; + }, + average: aKey => { + var readKey = fieldReader(_$(aKey).isString().default(void 0)); + var sum = 0, c = 0; + + code.select().forEach(r => { + var v = Number(readKey === null ? r : readKey(r)); + if (Number.isFinite(v)) { + c++; + sum += v; + } + }); + + return (c > 0 ? sum / c : void 0); + }, + sum: aKey => { + var readKey = fieldReader(_$(aKey).isString().default(void 0)); + var sum = 0; + + code.select().forEach(r => { + var v = Number(readKey === null ? r : readKey(r)); + if (Number.isFinite(v)) { + sum += v; + } + }); + + return sum; + }, + distinct: aKey => { + var readKey = fieldReader(_$(aKey).isString().default(void 0)); + var vals = [], seen = new Set(); + + code.select().forEach(r => { + var v = readKey === null ? r : readKey(r); + // indexOf treats each NaN as distinct; retain the original value (including -0). + if (v !== v || !seen.has(v)) { + vals.push(v); + seen.add(v); + } + }); + + return vals; + }, + group : aKey => { + aKey = _$(aKey).isString().default(void 0); + var vals = {}, readKey = fieldReader(aKey); + + code.select().forEach(r => { + var v = readKey === null ? r : readKey(r); + if (!Object.prototype.hasOwnProperty.call(vals, v)) { + Object.defineProperty(vals, v, { value: [r], enumerable: true, writable: true, configurable: true }) + } else { + vals[v].push(r); + } + }); + + return vals + }, + groupBy: (aKey) => { + var keys = _$(aKey).isString().default("key").split(",") + var nest = (groups, depth) => { + // groupBy historically exposes only the string keys returned by Object.keys. + Object.getOwnPropertySymbols(groups).forEach(key => { delete groups[key] }) + if (depth < keys.length) { + Object.keys(groups).forEach(key => { + groups[key] = nest(nLinq(groups[key]).group(keys[depth]), depth + 1) + }) + } + return groups + } + return nest(code.group(keys[0]), 1) + }, + minBy: (aKey, aField, aFnKey, aAltKey) => { + return code.fnBy(aKey, v=>$$(nLinq(v).min(aField)).get(aField), _$(aFnKey).default("_min"), aAltKey) + }, + maxBy: (aKey, aField, aFnKey, aAltKey) => { + return code.fnBy(aKey, v=>$$(nLinq(v).max(aField)).get(aField), _$(aFnKey).default("_max"), aAltKey) + }, + averageBy: (aKey, aField, aFnKey, aAltKey) => { + return code.fnBy(aKey, v=>nLinq(v).average(aField), _$(aFnKey).default("_avg"), aAltKey) + }, + sumBy: (aKey, aField, aFnKey, aAltKey) => { + return code.fnBy(aKey, v=>nLinq(v).sum(aField), _$(aFnKey).default("_sum"), aAltKey) + }, + countBy: (aKey, aFnKey, aAltKey) => { + return code.fnBy(aKey, countRows, _$(aFnKey).default("_count"), aAltKey) + }, + fnBy: (aKey, aFn, aFnKey, aAltKey) => { + aKey = _$(aKey).isString().default("key") + aFn = _$(aFn).isFunction().default(countRows) + aFnKey = _$(aFnKey).isString().default("_result") + aAltKey = _$(aAltKey).isString().default(aKey) + + var ks = aKey.split(",") + var aks = aAltKey.split(",") + var _fr = [] + // Keep the runtime clone when available; browser results need independent containers too. + var copyResult = typeof clone === "function" ? clone : function copy(value) { + if (!Array.isArray(value) && !$$(value).isMap()) return value + var result = Array.isArray(value) ? new Array(value.length) : {} + Object.keys(value).forEach(key => { + Object.defineProperty(result, key, { + value: copy(value[key]), enumerable: true, writable: true, configurable: true + }) + }) + return result + } + + var fn = (_r, _i, m) => { + var _vs = Object.keys(_r) + _vs.forEach((v, _j) => { + m[aks[_i]] = v + if (_i + 1 < ks.length) { + fn(nLinq(_r[v]).group(ks[_i + 1]), _i + 1, m) + } + if (ks.length == _i + 1) { + m[aFnKey] = aFn(_r[v]) + _fr.push(copyResult(m)) + } + }) + } + + if (ks.length > 0) { + var groups + if (ks.length === 1 && aFn === countRows) { + var readKey = fieldReader(ks[0]) + groups = Object.create(null) + code.select().forEach(row => { + var key = readKey(row) + if (Object.prototype.hasOwnProperty.call(groups, key)) groups[key].length++ + else groups[key] = { length: 1 } + }) + } else { + groups = code.group(ks[0]) + } + fn(groups, 0, {}) + return _fr + } else { + return [] + } + }, + /*countBy: (aKey, aCountKey, aAltKey) => { + aKey = _$(aKey).isString().default("key") + aCountKey = _$(aCountKey).isString().default("_count") + aAltKey = _$(aAltKey).isString().default(aKey) + + var ks = aKey.split(",") + var aks = aAltKey.split(",") + var _fr = [] + + var fn = (_r, _i, m) => { + var _vs = Object.keys(_r) + _vs.forEach((v, _j) => { + m[aks[_i]] = v + if (_i + 1 < ks.length) { + fn(nLinq(_r[v]).group(ks[_i + 1]), _i + 1, m) + } + if (ks.length == _i + 1) { + m[aCountKey] = _r[v].length + _fr.push(clone(m)) + } + }) + } + + if (ks.length > 0) { + fn(code.group(ks[0]), 0, {}) + return _fr + } else { + return [] + } + },*/ + at : aParam => { + _$(aParam, "index").isNumber().$_(); + + res = applyConditions(res, void 0, true); + return res[Number(aParam)]; + }, + all : (aFallback) => { res = applyConditions(res, void 0, true); return $$(res).isArray() ? res.length == anObject.length : aFallback; }, + count : () => { res = applyConditions(res, void 0, true); return res.length; }, + first : (aFallback) => { res = applyConditions(res, void 0, true); return (res.length > 0 ? res[0] : aFallback); }, + last : (aFallback) => { res = applyConditions(res, void 0, true); return (res.length > 0 ? res[res.length-1] : aFallback); }, + any : () => { res = applyConditions(res, void 0, true); return (res.length > 0); }, + none : () => { res = applyConditions(res, void 0, true); return (res.length == 0); }, + reverse: () => { res = applyConditions(res, void 0, true); return res.reverse(); }, + + // Applying to current result set + each : aFn => { + _$(aFn, "each function").isFunction().$_(); + + code.select().forEach(aFn); + + return code; + }, + intersect: (aA2) => { + _$(aA2, "intersect param").isArray().$_(); + + res = applyConditions(res); + res = aIntersection(res, aA2); + + return code; + }, + except: (aA2) => { + _$(aA2, "except param").isArray().$_(); + + res = applyConditions(res); + res = aException(res, aA2); + + return code; + }, + union: (aA2) => { + _$(aA2, "union param").isArray().$_(); + + res = applyConditions(res); + res = aUnion(res, aA2); + + return code; + }, + cartesian: (aA2) => { + _$(aA2, "cartesian param").isArray().$_(); + + res = applyConditions(res); + res = aCartesian(res, aA2); + + return code; + }, + attach : (aKey, aValue) => { + _$(aKey, "key").$_(); + _$(aValue, "value").$_(); + + res = applyConditions(res); + + //aKey = vKey(aKey); + if ($$(aValue).isFunction()) { + res = res.map(r => { $$(r).set(aKey, aValue(r)); return r; }); + } else { + res = res.map(r => { $$(r).set(aKey, aValue); return r; }); + } + + return code; + }, + // Attach a new key to the result set based on an equal condition + // aNewKey: the new key to be attached + // aKey: the key to be compared + // aValue: the value to be compared + // aClass: the class value to be attached to aNewKey + attachBy: (aNewKey, aKey, aValue, aClass) => { + _$(aNewKey, "newkey").isString().$_() + _$(aKey, "key").isString().$_() + _$(aValue, "value").$_() + _$(aClass, "class").$_() + + res = applyConditions(res) + res = res.map(r => { + if (aValue == $$(r).get(aKey)) { + $$(r).set(aNewKey, aClass) + } + return r + }) + + return code + }, + // Attach a new key to the result set based on a negative equal condition + // aNewKey: the new key to be attached + // aKey: the key to be compared + // aValue: the value to be compared + // aClass: the class value to be attached to aNewKey + attachNotBy: (aNewKey, aKey, aValue, aClass) => { + _$(aNewKey, "newkey").isString().$_() + _$(aKey, "key").isString().$_() + _$(aValue, "value").$_() + _$(aClass, "class").$_() + + res = applyConditions(res) + res = res.map(r => { + if (aValue != $$(r).get(aKey)) { + $$(r).set(aNewKey, aClass) + } + return r + }) + + return code + }, + // Attach to an existing key the result set based on an empty condition + // aNewKey: the key to check if empty + // aClass: the class value to be attached to aNewKey + attachByEmpty: (aNewKey, aClass) => { + _$(aNewKey, "newkey").isString().$_() + _$(aClass, "class").$_() + + res = applyConditions(res) + res = res.map(r => { + if ($$(r).get(aNewKey) == null || $$($$(r).get(aNewKey)).isUnDef()) { + $$(r).set(aNewKey, aClass) + } + return r + }) + + return code + }, + detach: aKey => { + _$(aKey, "key").$_() + + res = applyConditions(res) + res = res.map(r => { $$(r).unset(aKey); return r; }) + + return code + }, + toDate: aKey => { + _$(aKey, "key").$_() + + res = applyConditions(res) + res.forEach(r => { + try { + var v = $$(r).get(aKey) + if ($$(v).isString() || $$(v).isNumber()) + $$(r).set(aKey, new Date(v)) + } catch(e) { + } + }) + + return code + }, + filter : aValue => { + _$(aValue, "value").$_(); + + res = applyConditions(res); + res = res.filter(r => { + var d = true; + + if ($$(aValue).isMap() && $$(r).isMap()) { + Object.keys(aValue).forEach(rr => { + if (!aCompare(aValue[rr], r[rr])) d = false; + }) + } + if ($$(r).isArray()) { + if (aArrayContains(r, aValue) < 0) d = false; + } + + if ($$(aValue).isFunction() && !aValue(r)) d = false; + + if ($$(aValue).isNumber() || $$(aValue).isString()) { + if ($$(r).isNumber() || $$(r).isString()) { + if (r != aValue) d = false; + } + } + + return d; + }); + + return code; + }, + sort : function() { + res = applyConditions(res); + + var readers = [], comparisons = []; + for (var i = 0; i < arguments.length; i++) { + var key = arguments[i]; + var descending = key.startsWith("-"); + if (descending) key = key.substr(1, key.length - 1); + + var left, right; + if (typeof key === "string" && plainPath.test(key)) { + var index = readers.length; + readers.push(fieldReader(key)); + left = "readers[" + index + "](a)"; + right = "readers[" + index + "](b)"; + } else { + // Preserve the existing path syntax for complex keys. + left = '$$(a).get("' + key + '")'; + right = '$$(b).get("' + key + '")'; + } + var direction = descending ? -1 : 1; + comparisons.push("(" + left + " > " + right + " ? " + direction + + " : (" + left + " < " + right + " ? " + -direction + " : 0))"); + } + + var compare = new Function("readers", "a", "b", "return " + comparisons.join(" || ")); + res = res.sort(compare.bind(null, readers)); + return code; + }, + assign: (aSource, aAlias, aPK, aFK, aFallback) => { + res = applyConditions(res); + res.forEach(r => { + r[aAlias] = nLinq(aSource).equals(aFK, $$(r).get(aPK)).first(aFallback); + }); + return code; + }, + join: (aSource, aAlias, aPK, aFK) => { + res = applyConditions(res); + res.forEach(r => { + r[aAlias] = nLinq(aSource).equals(aFK, $$(r).get(aPK)).select(); + }); + return code; + }, + skip: aSkip => { + _$(aSkip).isNumber().$_(); + + askip = aSkip; + return code; + }, + skipWhile: aSkipFn => { + _$(aSkipFn, "skip function").isFunction().$_(); + + code.notWhere(aSkipFn); + return code; + }, + takeWhile: aTakeFn => { + _$(aTakeFn, "take function").isFunction().$_(); + + code.where(aTakeFn); + return code; + }, + take: aNum => { + _$(aNum).isNumber().$_(); + + return code.limit(aNum); + }, + skipTake: (aSkip, aTake) => { + _$(aSkip).isNumber().$_(); + + return code.skip(aSkip).take(aTake); + }, + // Apply map + apply: aMap => { + aMap = _$(aMap, "aMap").isMap().default({}) + + aMap.where = _$(aMap.where, "where").isArray().default([]) + aMap.select = _$(aMap.select, "select").default(void 0) + aMap.transform = _$(aMap.transform, "transform").isArray().default([]) + aMap.selector = _$(aMap.selector, "selector").isMap().default(void 0) + + aMap.where.forEach(w => { + if ($$(w.cond).isString()) code = code[w.cond].apply(code, w.args) + }) + aMap.transform.forEach(t => { + if ($$(t.func).isString()) { + code = code[t.func].apply(code, t.args) + } + }) + + var res + if ($$(aMap.select).isString()) res = code.select(new Function("elem", "index", "array", aMap.select)) + if ($$(aMap.select).isMap()) res = code.select(aMap.select) + + if ($$(res).isUnDef() && $$(aMap.selector).isMap()) res = ($$(aMap.selector.func).isString() ? $$({}).set(aMap.selector.func, code[aMap.selector.func].apply(code, aMap.selector.args)) : res) + if ($$(res).isUnDef() && $$(aMap.select).isUnDef()) res = code.select() + + return res + }, + // Main selector + select : aParam => { + res = applyConditions(res, void 0, true); + // no parameters + if ($$(aParam).isUnDef()) { + return res; + } else { + // function parameter + if ($$(aParam).isFunction()) { + return res.map(aParam); + } else { + // array parameter + if ($$(aParam).isArray()) { + var _c = {} + aParam.forEach(r => { + if ($$(r).isString()) { + if (r.indexOf(":") > 0) { + var key = r.substring(0, r.indexOf(":")) + var mkey = r.substring(r.indexOf(":") + 1) + _c[key] = mkey + } else { + _c[r] = r + } + } + }) + return res.map(_r => { + var _res = {} + Object.keys(_c).forEach(r => $$(_res).set(r, $$(_r).get(_c[r]))) + return _res + }) + } + // map parameter + if ($$(aParam).isMap()) { + var keys = Object.keys(aParam); + return res.map(r => { + var nr = {}; + keys.forEach(k => { + if ($$($$(r).get(k)).isDef()) { + $$(nr).set(k, $$(r).get(k)); + } else { + $$(nr).set(k, $$(aParam).get(k)); + } + }); + return nr; + }); + } + } + } + }, + mselect: (aParam, aKey, dontRemove) => { + var anArray = code.select(aParam) + aKey = _$(aKey, "aKey").isString().default("_key") + dontRemove = _$(dontRemove, "dontRemove").isBoolean().default(true) + + var res = {}; + for(var i in anArray) { + var item = anArray[i] + if ($$(aKey).isDef() && $$(item[aKey]).isDef()) { + var k = item[aKey] + res[k] = item + if (!dontRemove) delete res[k][aKey] + } else { + res["row" + i] = item + } + } + return res + }, + define : aParam => { + res = code.select(aParam); + return code; + }, + removed: aParam => { + negative = true; + res = code.select(aParam); + return code; + }, + stream : aParam => { + var c = (alimit > 0 ? alimit : 1); + var fn = code.streamFn(aParam); + do { + fn(); + if (alimit > 0) c--; + } while ($$(res).isDef() && c > 0); + }, + streamFn : aParam => { + return () => { + var r = code.select(aParam); + res = ($$(anObject).isFunction() ? anObject() : anObject); + return r; + }; + }, + + // Map query + query: aMap => { + aMap = _$(aMap, "aMap").isMap().default({}) + + aMap.where = _$(aMap.where, "where").isArray().default([]) + aMap.select = _$(aMap.select, "select").default(void 0) + aMap.transform = _$(aMap.transform, "transform").isArray().default([]) + aMap.selector = _$(aMap.selector, "selector").isMap().default(void 0) + + var f = code + + aMap.where.forEach(w => { + if ($$(w.cond).isString()) code = code[w.cond].apply(code, w.args) + }) + aMap.transform.forEach(t => { + if ($$(t.func).isString()) code = code[t.func].apply(code, t.args) + }) + + var _res + if ($$(aMap.select).isString()) { + var compile = typeof newFn === "function" ? newFn : Function + _res = code.select(compile("elem", "index", "array", aMap.select)) + } + if ($$(aMap.select).isMap()) _res = code.select(aMap.select) + + if ($$(_res).isUnDef() && $$(aMap.selector).isMap()) _res = ($$(aMap.selector.func).isString() ? code[aMap.selector.func].apply(code, aMap.selector.args) : _res) + if ($$(_res).isUnDef() && $$(aMap.select).isUnDef()) _res = code.select() + + return _res + }, + + /* --extend here-- */ + }; + + return code; +}; + +var $from = nLinq; + + +// openafsigil.js +// + +// Version: 0.1.5 +// Copyright 2023 Nuno Aguiar +if (!(typeof isJavaObject == 'defined')) isJavaObject = () => false +const $$ = function(aObj) { + const _r = { + /** + * + * $$.get(aPath) : Object + * Given aObject it will try to parse the aPath and retrive the corresponding object under that path. Example:\ + * \ + * var a = { a : 1, b : { c: 2, d: [0, 1] } };\ + * \ + * print($$(a).get("b.c")); // 2\ + * sprint($$(a).get("b.d")); // [0, 1]\ + * print($$(a).get("b.d[0]")); // 0\ + * \ + * + */ + get: (aPath) => { + if (!$$(aObj).isObject()) return void 0; + + aPath = aPath.replace(/\[(\w+)\]/g, '.$1'); + aPath = aPath.replace(/^\./, ''); + + var a = aPath.split('.'); + for (var i = 0, n = a.length; i < n; ++i) { + var k = a[i]; + if (k in aObj) { + aObj = aObj[k]; + } else { + return; + } + } + return aObj; + }, + /** + * + * $$.getI(aPath) : Object + * Given aObject it will try to parse the aPath (in a case-insensitive way) and retrive the corresponding object under that path. Example:\ + * \ + * var a = { a : 1, b : { c: 2, d: [0, 1] } };\ + * \ + * print($$(a).getI("b.C")); // 2\ + * sprint($$(a).getI("B.d")); // [0, 1]\ + * print($$(a).getI("B.D[0]")); // 0\ + * \ + * + */ + getI: aPath => { + if (!$$(aObj).isObject()) return void 0 + + aPath = aPath.replace(/\[(\w+)\]/g, '.$1') + aPath = aPath.replace(/^\./, '') + + var a = aPath.split('.') + for (var i = 0, n = a.length; i < n; ++i) { + var k = a[i] + + if ($$(aObj).isMap()) { + var ks = {}, k2 = String(k).toUpperCase() + Object.keys(aObj).forEach(r => ks[r.toUpperCase()] = r) + + if (k2 in ks) { + aObj = aObj[ks[k2]] + } else { + return + } + } else { + if (k in aObj) { + aObj = aObj[k]; + } else { + return; + } + } + } + return aObj + }, + /** + * + * $$.set(aPath, aNewValue) : Object + * Given aObject it will try to parse the aPath and set the corresponding object under that path to aNewValue. Example:\ + * \ + * var a = { a : 1, b : { c: 2, d: [0, 1] } };\ + * \ + * sprint($$(a).set("b.c", 123)); // { a : 1, b : { c: 123, d: [0, 1] } }\ + * \ + * + */ + set: (aPath, aValue) => { + if (!$$(aObj).isObject()) return void 0; + var orig = aObj; + + aPath = aPath.replace(/\[(\w+)\]/g, '.$1'); + aPath = aPath.replace(/^\./, ''); + + var a = aPath.split('.'); + var prev, prevK; + for (var i = 0, n = a.length; i < n; ++i) { + var k = a[i]; + prev = aObj; + prevK = k; + if (k in aObj) { + aObj = aObj[k]; + } else { + aObj[k] = {}; + aObj = aObj[k]; + } + } + prev[prevK] = aValue; + return orig; + }, + /** + * + * $$.unset(aPath) : Object + * Given aObject it will try to parse the aPath and unset the corresponding object under that path. Example:\ + * \ + * var a = { a : 1, b : { c: 2, d: [0, 1] } };\ + * \ + * sprint($$(a).set("b.c")); // { a : 1, b : { d: [0, 1] } }\ + * \ + * + */ + unset: aPath => { + if (!$$(aObj).isObject()) return void 0 + var orig = aObj + + aPath = aPath.replace(/\[(\w+)\]/g, '.$1') + aPath = aPath.replace(/^\./, '') + + var a = aPath.split('.') + var prev, prevK + for (var i = 0, n = a.length; i < n; ++i) { + var k = a[i] + prev = aObj + prevK = k + if (k in aObj) { + aObj = aObj[k] + } else { + aObj[k] = {} + aObj = aObj[k] + } + } + delete prev[prevK] + return orig + }, + isDef: () => { return (isJavaObject(aObj) || !(typeof aObj == 'undefined')) ? true : false }, + isUnDef: () => { return (isJavaObject(aObj) || !(typeof aObj == 'undefined')) ? false : true }, + isJavaObject: () => { return isJavaObjecta(aObj) }, + isArray: () => { return Array.isArray(aObj); }, + isMap: () => { return (Object.prototype.toString.call(aObj) == "[object Object]"); }, + isObject: () => { var type = typeof aObj; return type === 'function' || type === 'object' && !!aObj; }, + isFunction: () => { return typeof aObj == 'function' || false; }, + isString: () => { return typeof aObj == 'string' || false; }, + isNumber: () => { return !isNaN(parseFloat(aObj)) && isFinite(aObj); }, + isTNumber: () => { return typeof aObj == 'number' || false; }, + isBoolean: () => { return typeof aObj == 'boolean' || false; }, + isNull: () => { return null == aObj || false; }, + isDate: () => { return (null != aObj) && !isNaN(aObj) && ("undefined" !== typeof aObj.getDate); }, + isRegExp: () => { return (aObj instanceof RegExp); }, + isUUID: () => { return (aObj.match(/^\b[0-9a-f]{8}\b-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-\b[0-9a-f]{12}\b$/) ? true : false); }, + isSchema: (aSchema, aOptions) => { + if (typeof Ajv == 'undefined') { + if (typeof loadAjv != 'undefined') + loadAjv(); + else + throw "Ajv library not loaded."; + } + + ow.loadObj(); + return ow.obj.schemaValidate(aSchema, aObj, aOptions); + } + }; + return _r; +}; + + +const _$ = function(aValue, aPrefixMessage) { + var defined; + if ($$(aPrefixMessage).isDef()) aPrefixMessage += " "; else aPrefixMessage = ""; + if ($$(aValue).isDef()) defined = true; else defined = false; + + const __r = { + // Defaults + /** + * + * _$(aObject, anErrorMessagePrefix) + * Shortcut to facilitate argument pre-validation and promote defensive programming.\ + * \ + * .default(aNewObject) : aObject\ + * Checks if aObject is defined and returns aObject. If it's not defined it will return aNewObject (the default value).\ + * \ + * $_(aMessage) : aObject\ + * Throws an exception with aMessage if aObject is not defined otherwise returns aObject. + * + */ + default : (aVal) => { + if (!defined) return aVal; else return aValue; + }, + $_ : (aMessage) => { + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "not defined or assigned"; + if (!defined) throw aMessage; + return aValue; + }, + + // Type check and conversion + isNumber: (aMessage) => { + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not a number"; + if (defined && !$$(aValue).isNumber()) throw aMessage; + return __r; + }, + toNumber: (aMessage) => { + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "can't be converted to number" + if (defined) try { aValue = Number(aValue) } catch(e) { throw aMessage } + return __r + }, + isTNumber: (aMessage) => { + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not a number type"; + if (defined && !$$(aValue).isTNumber()) throw aMessage; + return __r; + }, + isString: (aMessage) => { + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not a string"; + if (defined && !$$(aValue).isString()) throw aMessage; + return __r; + }, + toString: (aMessage) => { + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "can't be converted to string" + if (defined) try { aValue = String(aValue) } catch(e) { throw aMessage } + return __r + }, + isBoolean: (aMessage) => { + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not boolean"; + if (defined && (typeof aValue !== "boolean")) throw aMessage; + return __r; + }, + toBoolean: (aMessage) => { + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "can't be converted to a boolean" + if (defined) try { + if ($$(aValue).isNumber()) aValue = Boolean(aValue); + if ($$(aValue).isString()) aValue = (aValue.trim().toLowerCase() == 'true'); + } catch(e) { throw aMessage } + return __r + }, + isArray: (aMessage) => { + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not an array"; + if (defined && !$$(aValue).isArray()) throw aMessage; + return __r; + }, + toArray: (aMessage) => { + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "can't be converted to an array" + if (defined) try { aValue = String(aValue).split(",").map(r => r.trim()) } catch(e) { throw aMessage } + return __r + }, + isMap: (aMessage) => { + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not a map"; + if (defined && !$$(aValue).isMap()) throw aMessage; + return __r; + }, + toMap: (aMessage) => { + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "can't be converted to a map" + if (defined) + try { + var __f = j => { return ($$(global.jsonParse).isFunction() ? global.jsonParse(j, true) : JSON.parse(j)) } + aValue = __f(aValue) + } catch(e) { throw aMessage } + return __r + }, + isObject: (aMessage) => { + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not an object"; + if (defined && !$$(aValue).isObject()) throw aMessage; + return __r; + }, + isDate: (aMessage) => { + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not a date"; + if (defined && !$$(aValue).isDate()) throw aMessage; + return __r; + }, + toDate: (aMessage) => { + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "can't be converted to date" + if (defined) try { aValue = new Date(aValue) } catch(e) { throw aMessage } + return __r + }, + isRegExp: (aMessage) => { + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not a RegExp"; + if (defined && !$$(aValue).isRegExp()) throw aMessage; + return __r; + }, + isFunction: (aMessage) => { + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not a function"; + if (defined && !$$(aValue).isFunction()) throw aMessage; + return __r; + }, + isJavaObject: (aMessage) => { + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not a java object"; + if (defined && !isJavaObject(aValue)) throw aMessage; + return __r; + }, + isInstanceOf: (aClass, aMessage) => { + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not an instance of " + aClass; + if (defined && !(aValue instanceof aClass)) throw aMessage; + return __r; + }, + isNotNull: (aMessage) => { + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is null"; + if (defined && (aValue == null)) throw aMessage; + return __r; + }, + isUUID: (aMessage) => { + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not an UUID"; + if (defined && (!$$(aValue).isString() || aValue.match(/^\b[0-9a-f]{8}\b-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-\b[0-9a-f]{12}\b$/))) throw aMessage; + return __r; + }, + isSchema: (aSchema, aMessage, aOptions) => { + if (typeof Ajv == 'undefined') { + if (typeof loadAjv != 'undefined') + loadAjv(); + else + throw "Ajv library not loaded."; + } + + ow.loadObj(); + try { + ow.obj.schemaValidate(aSchema, aValue, aOptions); + } catch(e) { + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + " " + String(e); + throw aMessage; + } + return __r; + }, + // Generic validations + check: (aFunction, aMessage) => { + if (!$$(aFunction).isFunction() && !$$(aFunction).isString()) throw "please provide a function to check"; + var res = ($$(aFunction).isFunction() ? aFunction(aValue) : (newFn('v', 'return ' + aFunction))(aValue)); + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not ok"; + if (defined && !res) throw aMessage; + return __r; + }, + expr: (aEval, aMessage) => { + if (!$$(aEval).isString()) throw "please provide an expression"; + var res = af.eval(templify(aEval, { v: aValue })); + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not ok"; + if (defined && !res) throw aMessage; + return __r; + }, + equals: (aVal, aMessage) => { + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is equals to " + aVal; + if (defined && aValue == aVal) throw aMessage; + return __r; + } , + notEquals: (aVal, aMessage) => { + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not equals to " + aVal; + if (defined && aValue != aVal) throw aMessage; + return __r; + }, + anyOf: (aVals, aMessage) => { + if (!$$(aVals).isArray()) throw "please provide an array of values"; + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "has a value not in " + JSON.stringify(aVals); + if (defined && $$(aValue).isArray()) { + aValue.forEach((v) => { + if (aVals.indexOf(v) < 0) throw aMessage; + }); + } + return __r; + }, + oneOf: (aVals, aMessage) => { + if (!$$(aVals).isArray()) throw "please provide an array of values"; + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not one of " + JSON.stringify(aVals); + if (defined && !$$(aValue).isArray() && aVals.indexOf(aValue) < 0) throw aMessage; + return __r; + }, + + // Numeric validations + between: (aValA, aValB, aMessage) => { + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not between " + aValA + " and " + aValB; + if (defined && (aValue >= aValB || aValue <= aValA)) throw aMessage; + }, + betweenEquals: (aValA, aValB, aMessage) => { + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not between " + aValA + " and " + aValB; + if (defined && (aValue > aValB || aValue < aValA)) throw aMessage; + }, + less: (aVal, aMessage) => { + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is less than " + aVal; + if (defined && aValue >= aVal) throw aMessage; + return __r; + }, + lessEquals: (aVal, aMessage) => { + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is less or equals than " + aVal; + if (defined && aValue > aVal) throw aMessage; + return __r; + }, + greater: (aVal, aMessage) => { + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is greater than " + aVal; + if (defined && aValue <= aVal) throw aMessage; + return __r; + }, + greaterEquals: (aVal, aMessage) => { + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is greater or equals than " + aVal; + if (defined && aValue < aVal) throw aMessage; + return __r; + }, + + // String validations + notEmpty: (aMessage) => { + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is empty"; + if (defined && String(aValue) == "") throw aMessage; + return __r; + }, + empty: (aMessage) => { + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not empty"; + if (defined && String(aValue) != "") throw aMessage; + return __r; + }, + contains: (aVal, aMessage) => { + if (!$$(aVal).isString()) throw "please provide a string to check if contains"; + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "doesn't contain " + aVal; + if (defined && String(aValue).indexOf(aVal) < 0) throw aMessage; + return __r; + }, + notContains: (aVal, aMessage) => { + if (!$$(aVal).isString()) throw "please provide a string to check if not contains"; + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "contains " + aVal; + if (defined && String(aValue).indexOf(aVal) >= 0) throw aMessage; + return __r; + }, + starts: (aVal, aMessage) => { + if (!$$(aVal).isString()) throw "please provide a string to check if it starts with"; + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "doesn't start with '" + aVal + "'"; + if (defined && !(aValue.startsWith(aValu))) throw aMessage; + return __r; + }, + ends: (aVal, aMessage) => { + if (!$$(aVal).isString()) throw "please provide a string to check if it ends with"; + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "doesn't end with '" + aVal + "'"; + if (defined && !(aValue.endsWith(aVal))) throw aMessage; + return __r; + }, + notStarts: (aVal, aMessage) => { + if (!$$(aVal).isString()) throw "please provide a string to check if it not starts with"; + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "starts with '" + aVal + "'"; + if (defined && (aValue.startsWith(aValu))) throw aMessage; + return __r; + }, + notEnds: (aVal, aMessage) => { + if (!$$(aVal).isString()) throw "please provide a string to check if it not ends with"; + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "ends with '" + aVal + "'"; + if (defined && (aValue.endsWith(aVal))) throw aMessage; + return __r; + }, + regexp: (aRegExp, aMessage) => { + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "doesn't match '" + aRegExp + "'"; + if (!(aRegExp instanceof RegExp)) throw "is not a regular expression (" + aRegExp + ")"; + if (defined && !aRegExp.test(aValue)) throw aMessage; + return __r; + }, + javaRegexp: (aRegExp, aMods, aMessage) => { + if ($$(aRegExp).isUnDef() || !$$(aRegExp).isString()) throw "please provide a regular expression string"; + if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "doesn't match '" + aRegExp + "'"; + if (defined && !javaRegExp(aValue).test(aRegExp, aMods)) throw aMessage; + return __r; + } + }; + return __r; +}; diff --git a/js/openaf.js b/js/openaf.js index 4b6de384..2db890ca 100644 --- a/js/openaf.js +++ b/js/openaf.js @@ -7591,7 +7591,13 @@ OpenWrap.prototype.loadAI = function() { loadCompiledLib("owrap_ai_js"); if (isU * */ //OpenWrap.prototype.loadServer = function() { loadLib(getOpenAFJar() + "::js/owrap.server.js"); ow.server = new OpenWrap.server(); pods.declare("ow.server", ow.server); return ow.server; } -OpenWrap.prototype.loadServer = function() { loadCompiledLib("owrap_server_js"); if (isUnDef(ow.server)) { ow.server = new OpenWrap.server(); /*pods.declare("ow.server", ow.server);*/ }; return ow.server; }; +OpenWrap.prototype.loadServer = function() { + loadCompiledLib("owrap_server_js") + if (isUnDef(ow.server)) ow.server = new OpenWrap.server() + if (isUnDef(ow.server.oauth)) loadLib(getOpenAFJar() + "::js/owrap.server.oauth.js") + if (isUnDef(ow.server.oauth.authorizationServer)) loadLib(getOpenAFJar() + "::js/owrap.server.oauth.as.js") + return ow.server +} /** * * ow.loadMetrics() @@ -8829,7 +8835,7 @@ const $tb = function(aFunction) { var __openaf_rest = { urls: {}, stats: false }; const $rest = function(ops) { ow.loadObj(); - var _toptions = {}; + var _toptions = {}, oauthClient; var _rest = function(aOptions) { _toptions = _$(aOptions).isMap().default({ }); _toptions.default = _$(_toptions.default, "default").isMap().default({}); @@ -8844,8 +8850,30 @@ const $rest = function(ops) { _toptions.pass = _$(_toptions.pass, "pass").default(__); _toptions.options = _$(_toptions.options, "options").isMap().default(__) _toptions.requestHeaders = _$(_toptions.requestHeaders, "requestHeaders").isMap().default(__flags.HTTP_DEFAULT_HEADERS ? { Accept: "*/*" } : __) + // OAuth clients own authentication for the final request. + if (isDef(_toptions.auth)) { + var oauth = ow.loadServer().oauth + if (oauth.__clients.has(_toptions.auth)) oauthClient = _toptions.auth + else if (isMap(_toptions.auth) && _toptions.auth.type === "oauth2") oauthClient = oauth.client(_toptions.auth) + else throw new Error("Unsupported REST authentication") + } }; + var oauthExec = function(aFn, subFn, names, values, verb) { + var params = $a2m(names, values) + params.aVerb = verb + if (isDef(_toptions.preAction)) params = _toptions.preAction(params) || params + if (isDef(params.login) || isDef(params.pass)) throw new Error("Conflicting REST OAuth authentication") + params.options = Object.assign({}, params.options, { __oauthClient: oauthClient }) + var dispatch = () => aFn[subFn].apply(aFn, $m2a(names, params)) + if (isUnDef(_toptions.timeout) && isUnDef(_toptions.stopWhen)) return dispatch() + var result + var completed = $tb(() => { result = dispatch() }).timeout(_toptions.timeout).stopWhen(_toptions.stopWhen).exec() + if (completed !== true) throw new Error("OAuth HTTP request interrupted") + return result + } + + _rest.prototype.__check = function(aBaseURI) { // try URL based if (isDef(__openaf_rest.urls[aBaseURI])) { @@ -8905,11 +8933,17 @@ const $rest = function(ops) { } var fdef = [ "aBaseURL", "aIdxMap", "login", "pass", "conTimeout", "reqHeaders", "urlEncode", "httpClient", "retBytes", "options" ]; if (parent.__check(aBaseURI)) { - var c = _toptions.retry, error, __t; + var c = isDef(oauthClient) ? 0 : _toptions.retry, error, __t; do { error = __; try { - if (isDef(_toptions.timeout) || isDef(_toptions.stopWhen)) { + if (isDef(oauthClient)) { + var names = fdef.filter(name => name !== (aSubFn === "head" ? "retBytes" : "urlEncode")) + var values = [aBaseURI, aIdxMap, _toptions.login, _toptions.pass, _toptions.connectionTimeout, _toptions.requestHeaders] + if (aSubFn === "head") values.push(_toptions.urlEncode, _toptions.httpClient, _toptions.options) + else values.push(_toptions.httpClient, retBytes, _toptions.options) + res = oauthExec(aFn, aSubFn, names, values, aVerb) + } else if (isDef(_toptions.timeout) || isDef(_toptions.stopWhen)) { var _r = $tb(() => { if (isDef(_toptions.preAction)) { var _a = $a2m(fdef, [ aBaseURI, aIdxMap, _toptions.login, _toptions.pass, _toptions.connectionTimeout, _toptions.requestHeaders, _toptions.urlEncode, _toptions.httpClient, retBytes, _toptions.options ]); @@ -8965,7 +8999,7 @@ const $rest = function(ops) { if (_toptions.throwExceptions) { throw error; } else { - res = merge({ error: ow.obj.rest.exceptionParse(error) }, _toptions.default); + res = merge({ error: isDef(oauthClient) ? String(error.message || "OAuth request failed") : ow.obj.rest.exceptionParse(error) }, _toptions.default); } } } else { @@ -8985,11 +9019,16 @@ const $rest = function(ops) { } var fdef = [ "aBaseURL", "aIdxMap", "aDataRowMap", "login", "pass", "conTimeout", "reqHeaders", "urlEncode", "httpClient", "retBytes", "aMethod", "options" ]; if (parent.__check(aBaseURI)) { - var c = _toptions.retry, error; + var c = isDef(oauthClient) ? 0 : _toptions.retry, error; do { error = __; try { - if (isDef(_toptions.timeout) || isDef(_toptions.stopWhen)) { + if (isDef(oauthClient)) { + var names = ["upload", "jsonUpload"].indexOf(aSubFn) >= 0 ? fdef : fdef.filter(name => name !== "aMethod") + var values = [aBaseURI, aIdxMap, aDataRowMap, _toptions.login, _toptions.pass, _toptions.connectionTimeout, _toptions.requestHeaders, _toptions.urlEncode, _toptions.httpClient, retBytes, __, _toptions.options] + if (names.length !== fdef.length) values.splice(10, 1) + res = oauthExec(aFn, aSubFn, names, values, aVerb) + } else if (isDef(_toptions.timeout) || isDef(_toptions.stopWhen)) { var _r = $tb(() => { if (isDef(_toptions.preAction)) { var _a = $a2m(fdef, [ aBaseURI, aIdxMap, aDataRowMap, _toptions.login, _toptions.pass, _toptions.connectionTimeout, _toptions.requestHeaders, _toptions.urlEncode, _toptions.httpClient, retBytes, _toptions.options ]); @@ -9039,7 +9078,7 @@ const $rest = function(ops) { if (_toptions.throwExceptions) { throw error; } else { - res = merge({ error: ow.obj.rest.exceptionParse(error) }, _toptions.default); + res = merge({ error: isDef(oauthClient) ? String(error.message || "OAuth request failed") : ow.obj.rest.exceptionParse(error) }, _toptions.default); } } } else { @@ -9571,6 +9610,12 @@ const $jsonrpc = function (aOptions) { if (aOptions.debug) printErr(ansiColor("yellow,BOLD", "DEBUG: ") + ansiColor("yellow", m)) } + // Encode a MCP request metadata header value, using the Base64 sentinel for non-ASCII or sentinel-like values + const _encodeMCPHeaderValue = aValue => { + var _v = String(aValue) + if (/^[\x20-\x7E]*$/.test(_v) && !/^=\?base64\?.*\?=$/.test(_v) && _v.trim() === _v) return _v + return "=?base64?" + String(java.util.Base64.getEncoder().encodeToString(new java.lang.String(_v).getBytes("UTF-8"))) + "?=" + } const _pickHeaderCaseInsensitive = (headers, keyName) => { if (!isMap(headers)) return __ var _target = String(keyName).toLowerCase() @@ -10012,6 +10057,7 @@ const $jsonrpc = function (aOptions) { aParams = _$(aParams, "aParams").isMap().default({}) var _restOptions = clone(aOptions.options) if (isMap(aExecOptions.restOptions)) _restOptions = merge(_restOptions, aExecOptions.restOptions) + if (isDef(aOptions.__oauthClient)) _restOptions.auth = aOptions.__oauthClient _restOptions.requestHeaders = _$( _restOptions.requestHeaders, "requestHeaders" @@ -10025,7 +10071,8 @@ const $jsonrpc = function (aOptions) { if (isDef(_session.mcpSessionId) && isUnDef(_pickHeaderCaseInsensitive(_restOptions.requestHeaders, "mcp-session-id"))) { _restOptions.requestHeaders["mcp-session-id"] = _session.mcpSessionId } - if (isDef(_mcpInfo.protocolVersion) && isUnDef(_pickHeaderCaseInsensitive(_restOptions.requestHeaders, "mcp-protocol-version"))) { + var _autoVersionHeader = isUnDef(_pickHeaderCaseInsensitive(_restOptions.requestHeaders, "mcp-protocol-version")) + if (isDef(_mcpInfo.protocolVersion) && _autoVersionHeader) { _restOptions.requestHeaders["mcp-protocol-version"] = _mcpInfo.protocolVersion } // Set defaults for each phase; _configureHTTPTimeouts applies them to the underlying client. @@ -10048,13 +10095,19 @@ const $jsonrpc = function (aOptions) { _debug("jsonrpc -> " + stringify(_req, __, "")) if (isMap(aExecOptions.message)) _req = aExecOptions.message - var _requestProtocol = isMap(aParams._meta) ? aParams._meta["io.modelcontextprotocol/protocolVersion"] : __ + + // Set the modern (2026-07-28+) request metadata headers mirroring the sent body + var _reqParams = isMap(_req.params) ? _req.params : {} + var _requestProtocol = isMap(_reqParams._meta) ? _reqParams._meta["io.modelcontextprotocol/protocolVersion"] : __ if (isUnDef(_requestProtocol)) _requestProtocol = _mcpInfo.protocolVersion if (isString(_requestProtocol) && _requestProtocol >= "2026-07-28" && isString(_req.method)) { + // The header must equal the per-request version (also on the server/discover probe) + if (_autoVersionHeader) _restOptions.requestHeaders["mcp-protocol-version"] = _requestProtocol _restOptions.requestHeaders["Mcp-Method"] = _req.method - if (["tasks/get", "tasks/update", "tasks/cancel"].indexOf(_req.method) >= 0 && isString(aParams.taskId)) - _restOptions.requestHeaders["Mcp-Name"] = aParams.taskId - else if (isString(aParams.name)) _restOptions.requestHeaders["Mcp-Name"] = aParams.name + // Mcp-Name sources: core transport (name/uri) and the tasks extension (taskId) + var _nameField = ({ "tools/call": "name", "prompts/get": "name", "resources/read": "uri", "tasks/get": "taskId", "tasks/update": "taskId", "tasks/cancel": "taskId" })[_req.method] + if (isDef(_nameField) && isDef(_reqParams[_nameField]) && !isNull(_reqParams[_nameField])) + _restOptions.requestHeaders["Mcp-Name"] = _encodeMCPHeaderValue(_reqParams[_nameField]) } var _http = ow.loadObj().rest.connectionFactory() try { @@ -10145,6 +10198,7 @@ const $jsonrpc = function (aOptions) { if (_r._listenerActive) return _r if (["remote", "http", "sse"].indexOf(aOptions.type) < 0 || _mcpInfo.protocolVersion >= "2026-07-28") throw new Error("GET listener requires legacy Streamable HTTP") var opts = merge(clone(aOptions.options || {}), options || {}) + if (isDef(aOptions.__oauthClient)) opts.auth = aOptions.__oauthClient opts.requestHeaders = merge(merge((aOptions.options || {}).requestHeaders || {}, (options || {}).requestHeaders || {}), { Accept: "text/event-stream" }) if (isDef(_session.mcpSessionId)) opts.requestHeaders["mcp-session-id"] = _session.mcpSessionId if (isDef(_mcpInfo.protocolVersion)) opts.requestHeaders["mcp-protocol-version"] = _mcpInfo.protocolVersion @@ -10199,7 +10253,7 @@ const $jsonrpc = function (aOptions) { return } _r.stopListening() - if ((aOptions.type == "remote" || aOptions.type == "http" || aOptions.type == "sse") && + if (isUnDef(aOptions.__oauthClient) && (aOptions.type == "remote" || aOptions.type == "http" || aOptions.type == "sse") && isDef(aOptions.url) && isDef(_session.mcpSessionId)) { // clients that no longer need a session SHOULD explicitly terminate it; tolerate // servers that don't support DELETE (405) or have already expired the session (404) @@ -10281,6 +10335,8 @@ const $jsonrpc = function (aOptions) { * - `shared` (boolean) : Enable shared JSON-RPC connections when possible (default: false) * - `sse` (boolean) : When true, remote/http MCP requests expect Server-Sent Events responses carrying JSON-RPC payloads * - `strict` (boolean) : Enable strict MCP protocol compliance (default: true) + * - `cache` (boolean) : Opt-in response cache for server/discover, list and resources/read results honoring the server's `ttlMs`/`cacheScope` hints; "private" results are only reused for the same authorization context, and list_changed/resources/updated notifications invalidate them (default: false) + * - `cacheMax` (number) : Maximum number of cached responses when `cache` is true (default: 500) * - `clientInfo` (map) : Client information sent during initialization (default: {name: "OpenAF MCP Client", version: "1.0.0"}) * - `blacklist` (array) : Optional array of MCP tool names to hide from listTools() and block in callTool() * - `preFn` (function) : Function called before each tool execution with (toolName, toolArguments) @@ -10325,8 +10381,8 @@ const $jsonrpc = function (aOptions) { * - `url(aURL)`: Set the URL and switch to remote type * - `sh(aCommand)`: Set the command and switch to stdio type * - `initialize(clientInfo)`: Initialize the MCP connection and exchange capabilities - * - `listTools()`: Get list of available tools from the MCP server - * - `callTool(toolName, toolArguments, toolOptions)`: Execute a specific tool with given arguments and optional per-call options + * - `listTools()`: Get list of available tools from the MCP server (modern HTTP excludes tools with invalid `x-mcp-header` annotations) + * - `callTool(toolName, toolArguments, toolOptions)`: Execute a specific tool with given arguments and optional per-call options (modern HTTP mirrors `x-mcp-header` arguments in `Mcp-Param-{Name}` headers) * - `listPrompts()`: Get list of available prompts from the MCP server * - `getPrompt(promptName, promptArguments)`: Get a specific prompt with given arguments * - `toGptTools(aGptInstance, aToolNames)`: Add MCP tools to a `$gpt` instance @@ -10344,6 +10400,7 @@ const $jsonrpc = function (aOptions) { * - `cancelRequest(id, reason)`: Best-effort protocol cancellation * - `getToolUI(name)` / `getAppResource(name)` / `hasApps()`: MCP Apps metadata and ui:// resource retrieval, without executing HTML * - `exec(method, params, execOptions)`: Low-level MCP/JSON-RPC; optional `onRequestId(id)` callback in execOptions + * - `clearCache()`: Drop every response held by the opt-in response cache * - `destroy()`: Stop the client and cleanup resources * * Register sampling, elicitation and roots before legacy initialize(); only configured capabilities are advertised. @@ -10463,10 +10520,20 @@ const $mcp = function(aOptions) { }) aOptions.blacklist = _$(aOptions.blacklist, "aOptions.blacklist").isArray().default([]) aOptions.options = _$(aOptions.options, "aOptions.options").isMap().default(__) - aOptions.auth = _$(aOptions.auth, "aOptions.auth").isMap().default({}) + // Keep the borrowed client by identity so transport option merges cannot clone it. + const _sharedOAuth = isMap(aOptions.auth) && isFunction(aOptions.auth.authenticate) && + ow.loadServer().oauth.__clients.has(aOptions.auth) ? aOptions.auth : __ + aOptions.__oauthClient = _sharedOAuth + if (isDef(_sharedOAuth) && ["remote", "http", "sse"].indexOf(aOptions.type) < 0) { + throw new Error("OAuth clients require an MCP HTTP transport") + } + aOptions.auth = isDef(_sharedOAuth) ? {} : _$(aOptions.auth, "aOptions.auth").isMap().default({}) aOptions.preFn = _$(aOptions.preFn, "aOptions.preFn").isFunction().default(__) aOptions.posFn = _$(aOptions.posFn, "aOptions.posFn").isFunction().default(__) aOptions.protocolVersion = _$(aOptions.protocolVersion, "aOptions.protocolVersion").isString().default("2025-06-18") + // Opt-in response cache honoring the server's CacheableResult hints (ttlMs/cacheScope) + aOptions.cache = _$(aOptions.cache, "aOptions.cache").isBoolean().default(false) + aOptions.cacheMax = _$(aOptions.cacheMax, "aOptions.cacheMax").isNumber().default(500) // Optional client capabilities are added by handler registration below; none are enabled by default. aOptions.capabilities = _$(aOptions.capabilities, "aOptions.capabilities").isMap().default({}) @@ -10508,12 +10575,56 @@ const $mcp = function(aOptions) { const _defaultCmdDir = (isDef(__flags) && isDef(__flags.JSONRPC) && isDef(__flags.JSONRPC.cmd) && isDef(__flags.JSONRPC.cmd.defaultDir)) ? __flags.JSONRPC.cmd.defaultDir : __ const _isToolBlacklisted = toolName => _toolBlacklist[toolName] === true + // Modern (2026-07-28+) Streamable HTTP tools mirror x-mcp-header annotated arguments in Mcp-Param-{Name} headers + const _toolSchemas = {}, _rejectedTools = {} + const _clearToolSchemas = () => { + Object.keys(_toolSchemas).forEach(k => delete _toolSchemas[k]) + Object.keys(_rejectedTools).forEach(k => delete _rejectedTools[k]) + } + const _usesParamHeaders = () => _r._era == "modern" && ["remote", "http", "sse"].indexOf(aOptions.type) >= 0 const _filterToolsList = toolsRes => { if (isMap(toolsRes) && isArray(toolsRes.tools) && Object.keys(_toolBlacklist).length > 0) { toolsRes.tools = toolsRes.tools.filter(tool => !_isToolBlacklisted(tool.name)) } + + // Exclude (and remember) tools with invalid x-mcp-header annotations + if (isMap(toolsRes) && isArray(toolsRes.tools) && _usesParamHeaders()) { + ow.loadServer() + toolsRes.tools = toolsRes.tools.filter(tool => { + if (!isMap(tool) || !isString(tool.name)) return true + var _ann = ow.server.mcp.headerAnnotations(tool.inputSchema) + if (_ann.valid) { + _toolSchemas[tool.name] = tool.inputSchema + delete _rejectedTools[tool.name] + return true + } + delete _toolSchemas[tool.name] + _rejectedTools[tool.name] = _ann.error + logWarn("MCP tool '" + tool.name + "' rejected: " + _ann.error) + return false + }) + } return toolsRes } + // Returns a tool's Mcp-Param-{Name} headers for the arguments from the inputSchema learned by listTools(); + // refresh re-lists the tools first (used after a HeaderMismatch). Unlisted tools mirror no headers. + const _paramHeadersFor = (toolName, toolArguments, refresh) => { + if (!_usesParamHeaders()) return {} + if (refresh) { + delete _toolSchemas[toolName] + _cacheInvalidate("tools/list") + try { _r.listTools() } catch(e) { if (aOptions.debug) printErr(ansiColor("yellow", "MCP tools/list for Mcp-Param headers failed: " + e)) } + } + if (isDef(_rejectedTools[toolName])) throw new Error("MCP tool '" + toolName + "' was rejected: " + _rejectedTools[toolName]) + return isDef(_toolSchemas[toolName]) ? ow.server.mcp.paramHeaders(_toolSchemas[toolName], toolArguments) : {} + } + // Adds headers to per-call HTTP options; caller-supplied request headers win over the mirrored ones + const _toolRestOptions = (restOptions, headers) => { + if (!isMap(headers) || Object.keys(headers).length == 0) return restOptions + var _o = merge({}, isMap(restOptions) ? restOptions : {}) + _o.requestHeaders = merge(headers, isMap(_o.requestHeaders) ? _o.requestHeaders : {}) + return _o + } const _auth = { token: __, @@ -11027,7 +11138,10 @@ const $mcp = function(aOptions) { // MCP owns the storage transaction, refresh and identity. The helper owns this login only. if (_automaticOAuth) _reserveCallback(aOptions.auth.redirectURI) var loginOptions = merge(aOptions.auth, { - authURL: _getResolvedAuthURL(), tokenURL: tokenURL, resource: resource, tokenStore: false + authURL: _getResolvedAuthURL(), tokenURL: tokenURL, resource: resource, tokenStore: false, + authorizationServerIssuer: _auth.authorizationServerIssuer, + authorizationResponseIssuerRequired: isMap(_auth.authorizationServerMetadata) && + _auth.authorizationServerMetadata.authorization_response_iss_parameter_supported === true }) loginOptions.__callbackReservation = _callbackReservation _oauthPending = ow.server.httpd.oauth2(loginOptions) @@ -11046,29 +11160,15 @@ const $mcp = function(aOptions) { redirect_uri: aOptions.auth.redirectURI, code_verifier: _getPKCEVerifier() } else params = { grant_type: grant, client_id: clientId } - if (isDef(aOptions.auth.clientSecret) && ["none", "client_secret_basic"].indexOf(aOptions.auth.tokenEndpointAuthMethod) < 0) params.client_secret = aOptions.auth.clientSecret - if (isDef(scope)) params.scope = scope - if (isDef(audience)) params.audience = audience - if (isDef(resource)) params.resource = resource - if (isMap(aOptions.auth.extraParams)) params = merge(params, aOptions.auth.extraParams) - var tokenHttp = ow.loadObj().rest.connectionFactory() try { - tokenHttp.setThrowExceptions(false) - tokenHttp.client = tokenHttp.client.newBuilder().followRedirects(false).followSslRedirects(false) - .callTimeout(aOptions.auth.tokenTimeoutMs || 60000, java.util.concurrent.TimeUnit.MILLISECONDS).build() - var tokenTimeout = _$(aOptions.auth.tokenTimeoutMs, "auth.tokenTimeoutMs").isNumber().default(60000) - var tokenHeaders = {} - if (aOptions.auth.tokenEndpointAuthMethod == "client_secret_basic") { - tokenHeaders.Authorization = "Basic " + af.fromBytes2String(af.toBase64Bytes(af.fromString2Bytes(_urlEnc(clientId) + ":" + _urlEnc(aOptions.auth.clientSecret)))) - } - res = $rest({ httpClient: tokenHttp, requestHeaders: tokenHeaders, urlEncode: true, timeout: tokenTimeout, - readTimeout: tokenTimeout, callTimeout: tokenTimeout }).post(tokenURL, params) - if (tokenHttp.responseCode() >= 400 && isMap(res) && isDef(res.access_token)) res = {} - } - catch(e) { throw new Error("OAuth token request failed; check connectivity and provider configuration"); } - finally { - try { tokenHttp.close(); } catch(ignoreClose) {} - if (params.grant_type == "authorization_code") { _auth.authorizationCode = __; _auth.pkceVerifier = __; } + res = ow.loadServer().oauth.__exchange(Object.assign({}, aOptions.auth, { + scope: scope, resource: resource, audience: audience + }), tokenURL, params, true) + } catch(e) { + if (isDef(e.oauthError)) res = { error: e.oauthError } + else throw e + } finally { + if (params.grant_type == "authorization_code") { _auth.authorizationCode = __; _auth.pkceVerifier = __ } } } if (!isMap(res) || !isString(res.access_token) || res.access_token.length == 0) { @@ -11181,6 +11281,65 @@ const $mcp = function(aOptions) { return true } + // Opt-in response cache for CacheableResult methods. Entries are keyed by method, params and a fingerprint of + // _meta (protocol version, client capabilities and identity are request parameters too); "private" entries are + // also keyed by a fingerprint of the current authorization context so they're never reused across credentials. + // Freshness follows ttlMs from the time the request was sent. + const _MCP_CACHEABLE = ["server/discover", "tools/list", "prompts/list", "resources/list", "resources/templates/list", "resources/read"] + const _cache = {} + const _cacheKeyOf = (method, params, notification, execOptions) => { + if (!aOptions.cache || notification || _MCP_CACHEABLE.indexOf(method) < 0) return __ + if (isMap(execOptions) && (isDef(execOptions.message) || isDef(execOptions.restOptions))) return __ + var _p = isMap(params) ? merge({}, params) : {} + // MRTR retries must never be cached + if (isDef(_p.inputResponses) || isDef(_p.requestState)) return __ + var _meta = isMap(_p._meta) ? _p._meta : {} + delete _p._meta + // The params part comes first so _cacheInvalidate can match on method and params prefixes + return method + " " + stringify(_p, __, "") + " " + sha256(stringify(sortMapKeys(_meta, true), __, "")) + } + const _cacheGet = (key, authFP) => { + var _t = nowNano() + var _keys = [key + " public", key + " private " + authFP] + for (var i = 0; i < _keys.length; i++) { + var _e = _cache[_keys[i]] + if (isUnDef(_e)) continue + if (_e.expires <= _t) { + delete _cache[_keys[i]] + continue + } + // Report the remaining lifetime, never the original one + var _res = clone(_e.result) + _res.ttlMs = Math.max(0, Math.floor((_e.expires - _t) / 1000000)) + return _res + } + return __ + } + const _cachePut = (key, authFP, result, received) => { + if (!isMap(result) || isDef(result.error) || (isDef(result.resultType) && result.resultType != "complete")) return + if (!isNumber(result.ttlMs) || !isFinite(result.ttlMs) || result.ttlMs <= 0) return + var _ck = key + (result.cacheScope === "public" ? " public" : " private " + authFP) + + // Keep the cache bounded: drop expired entries first, then the one closest to expiring + var _keys = Object.keys(_cache) + if (isUnDef(_cache[_ck]) && _keys.length >= aOptions.cacheMax) { + var _t = nowNano() + _keys.forEach(k => { if (_cache[k].expires <= _t) delete _cache[k] }) + _keys = Object.keys(_cache) + if (_keys.length >= aOptions.cacheMax) { + var _drop = _keys[0] + _keys.forEach(k => { if (_cache[k].expires < _cache[_drop].expires) _drop = k }) + delete _cache[_drop] + } + } + _cache[_ck] = { result: clone(result), expires: received + Math.floor(result.ttlMs) * 1000000 } + } + const _cacheInvalidate = (method, params) => { + var _prefix = method + " " + (isDef(params) ? stringify(params, __, "") + " " : "") + Object.keys(_cache).forEach(k => { if (k.indexOf(_prefix) == 0) delete _cache[k] }) + } + const _cacheClear = () => Object.keys(_cache).forEach(k => delete _cache[k]) + const _execWithAuth = (method, params, notification, execOptions) => { execOptions = _$(execOptions, "execOptions").isMap().default({}) // Modern era (2026-07-28+): every request stamps its protocol version/capabilities/identity in @@ -11193,15 +11352,27 @@ const $mcp = function(aOptions) { "io.modelcontextprotocol/clientInfo": aOptions.clientInfo }, isMap(params._meta) ? params._meta : {}) } + var _cacheKey = isDef(_sharedOAuth) ? __ : _cacheKeyOf(method, params, notification, execOptions) var _isHttp = (aOptions.type == "remote" || aOptions.type == "http" || aOptions.type == "sse") + var _authHeaders if (_isHttp) { - var _authHeaders = _getAuthHeaders() + _authHeaders = _getAuthHeaders() if (isMap(_authHeaders)) { var _restOptions = _$(execOptions.restOptions, "execOptions.restOptions").isMap().default({}) _restOptions.requestHeaders = merge(_authHeaders, _$(_restOptions.requestHeaders, "requestHeaders").isMap().default({})) execOptions.restOptions = _restOptions } } + + // Serve a still-fresh cached response + var _authFP + if (isDef(_cacheKey)) { + _authFP = sha256(stringify(isMap(_authHeaders) ? _authHeaders : {}, __, "")) + var _hit = _cacheGet(_cacheKey, _authFP) + if (isDef(_hit)) return _hit + } + + var _received = nowNano() execOptions.diagnostics = {} var _result = _jsonrpc.exec(method, params, notification, execOptions) @@ -11216,6 +11387,7 @@ const $mcp = function(aOptions) { _jsonrpc.clearSession() try { _r.initialize() + _received = nowNano() _result = _jsonrpc.exec(method, params, notification, execOptions) } catch(e) { if (aOptions.debug) printErr(ansiColor("yellow", "MCP re-initialize after session expiry failed: " + e)) @@ -11223,6 +11395,8 @@ const $mcp = function(aOptions) { } } + // Store a cacheable complete response + if (isDef(_cacheKey)) _cachePut(_cacheKey, _authFP, _result, _received) return _result } @@ -11489,6 +11663,19 @@ const $mcp = function(aOptions) { // Responses to inbound HTTP requests and session DELETE use the same auth provider. var _originalNotification = aOptions.onNotification aOptions.onNotification = message => { + // Change notifications invalidate the related cached responses + if (isMap(message)) { + if (message.method == "notifications/tools/list_changed") { + _cacheInvalidate("tools/list") + _clearToolSchemas() + } + else if (message.method == "notifications/prompts/list_changed") _cacheInvalidate("prompts/list") + else if (message.method == "notifications/resources/list_changed") { + _cacheInvalidate("resources/list") + _cacheInvalidate("resources/templates/list") + } + else if (message.method == "notifications/resources/updated" && isMap(message.params) && isDef(message.params.uri)) _cacheInvalidate("resources/read", { uri: message.params.uri }) + } if (message.method == "notifications/resources/updated" && isMap(message.params) && isFunction(_subscriptions[message.params.uri])) _subscriptions[message.params.uri](message.params, message) if (isFunction(_originalNotification)) _originalNotification(message) } @@ -11560,6 +11747,8 @@ const $mcp = function(aOptions) { initialize: (clientInfo) => { clientInfo = _$(clientInfo, "clientInfo").isMap().default({}) clientInfo = merge(aOptions.clientInfo, clientInfo) + _cacheClear() + _clearToolSchemas() // Modern era already negotiated: there's no handshake to repeat in this era. if (_r._era == "modern") return _r @@ -11776,8 +11965,9 @@ const $mcp = function(aOptions) { var next = clone(params || {}) next.inputResponses = _answerInputRequests(inputRequired.inputRequests) if (isDef(inputRequired.requestState)) next.requestState = inputRequired.requestState + var _contHeaders = method == "tools/call" && isString(next.name) ? _paramHeadersFor(next.name, next.arguments) : {} if (method == "tools/call" && isFunction(aOptions.preFn)) aOptions.preFn(next.name, next.arguments) - var result = _execWithAuth(method, next) + var result = _execWithAuth(method, next, __, { restOptions: _toolRestOptions(__, _contHeaders) }) if (method == "tools/call" && isFunction(aOptions.posFn)) aOptions.posFn(next.name, next.arguments, result) return result }, @@ -11921,6 +12111,9 @@ const $mcp = function(aOptions) { throw new Error("MCP tool '" + toolName + "' is blacklisted.") } + // Mirror x-mcp-header annotated arguments (modern Streamable HTTP) + var _headers = _paramHeadersFor(toolName, toolArguments) + // Call pre-function if provided if (aOptions.preFn) { aOptions.preFn(toolName, toolArguments) @@ -11929,7 +12122,18 @@ const $mcp = function(aOptions) { var _res = _execWithAuth("tools/call", { name: toolName, arguments: toolArguments - }, __, { restOptions: toolOptions }) + }, __, { restOptions: _toolRestOptions(toolOptions, _headers) }) + + // On HeaderMismatch refresh the tool's inputSchema and retry once if the mirrored headers changed + if (_usesParamHeaders() && isMap(_res) && isMap(_res.error) && _res.error.code == -32020) { + var _newHeaders = _paramHeadersFor(toolName, toolArguments, true) + if (stringify(sortMapKeys(_newHeaders), __, "") != stringify(sortMapKeys(_headers), __, "")) { + _res = _execWithAuth("tools/call", { + name: toolName, + arguments: toolArguments + }, __, { restOptions: _toolRestOptions(toolOptions, _newHeaders) }) + } + } // Call post-function if provided if (aOptions.posFn) { aOptions.posFn(toolName, toolArguments, _res) @@ -12125,9 +12329,17 @@ const $mcp = function(aOptions) { return _r }, // Explicit operator authentication; never returns credentials. - authenticate: () => { _getAuthHeaders(); return _authStatus(); }, - getAuthStatus: () => _withOAuthOperation(() => { _resolveOAuthClient(true); return _automaticOAuth && isUnDef(_registration) ? _authStatus() : _withAuthStore(() => _authStatus()); }), - clearAuth: (options) => _withOAuthOperation(() => { + authenticate: () => { + if (isDef(_sharedOAuth)) { + if (_oauthDestroyed) throw new Error("MCP client destroyed") + ow.server.oauth.__clients.get(_sharedOAuth)(aOptions.url, "POST") + return _sharedOAuth.getAuthStatus() + } + _getAuthHeaders() + return _authStatus() + }, + getAuthStatus: () => isDef(_sharedOAuth) ? _sharedOAuth.getAuthStatus() : _withOAuthOperation(() => { _resolveOAuthClient(true); return _automaticOAuth && isUnDef(_registration) ? _authStatus() : _withAuthStore(() => _authStatus()); }), + clearAuth: (options) => isDef(_sharedOAuth) ? _sharedOAuth.clearAuth() : _withOAuthOperation(() => { _resolveOAuthClient(true, true) var result = _automaticOAuth && isUnDef(_registration) ? _authStatus() : _withAuthStore(() => { _resetAuth() @@ -12164,7 +12376,18 @@ const $mcp = function(aOptions) { } _releaseCallback() Object.keys(_subscriptions).forEach(k => delete _subscriptions[k]) + _cacheClear() _jsonrpc.destroy() + }, + /** + * + * $mcp.clearCache() : Map + * Drops every response held by the opt-in response cache (aOptions.cache). Returns the client. + * + */ + clearCache: () => { + _cacheClear() + return _r } } return _r diff --git a/js/openafnlinq.js b/js/openafnlinq.js index 45385226..9a82538d 100644 --- a/js/openafnlinq.js +++ b/js/openafnlinq.js @@ -232,6 +232,28 @@ var nLinq = function(anObject, aK) { where += "(" + aTmpl + ")"; }; + var countRows = rows => rows.length; + var plainPath = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/; + var fieldReader = aKey => { + if (aKey === void 0) return null; + if (!plainPath.test(aKey)) return row => $$(row).get(aKey); + if (aKey.indexOf(".") < 0) { + return row => { + if (row === null || typeof row !== "object") return $$(row).get(aKey); + return aKey in row ? row[aKey] : void 0; + }; + } + var parts = aKey.split("."); + return row => { + if (row === null || typeof row !== "object") return $$(row).get(aKey); + for (var i = 0; i < parts.length; i++) { + if (!(parts[i] in row)) return void 0; + row = row[parts[i]]; + } + return row; + }; + }; + // Main code var code = { _setState : aMap => { @@ -429,48 +451,38 @@ var nLinq = function(anObject, aK) { // Providing immediate result min : aKey => { - aKey = _$(aKey).isString().default(void 0); + var readKey = fieldReader(_$(aKey).isString().default(void 0)); var min; - code.select(r => { - var v = ($$(aKey).isDef() ? Number($$(r).get(aKey)) : Number(r)); - if (v != null && $$(v).isNumber()) { - if ($$(min).isUnDef()) { - min = r; - } else { - if ($$(aKey).isDef() && $$(min).get(aKey) > v) min = r; - if ($$(aKey).isUnDef() && min > v) min = r; - } + code.select().forEach(r => { + var v = Number(readKey === null ? r : readKey(r)); + if (Number.isFinite(v) && (min === void 0 || (readKey === null ? min : readKey(min)) > v)) { + min = r; } }); return min; }, max : aKey => { - aKey = _$(aKey).isString().default(void 0); + var readKey = fieldReader(_$(aKey).isString().default(void 0)); var max; - code.select(r => { - var v = ($$(aKey).isDef() ? Number($$(r).get(aKey)) : Number(r)); - if (v != null && $$(v).isNumber()) { - if ($$(max).isUnDef()) { - max = r; - } else { - if ($$(aKey).isDef() && $$(max).get(aKey) < v) max = r; - if ($$(aKey).isUnDef() && max < v) max = r; - } + code.select().forEach(r => { + var v = Number(readKey === null ? r : readKey(r)); + if (Number.isFinite(v) && (max === void 0 || (readKey === null ? max : readKey(max)) < v)) { + max = r; } }); return max; }, average: aKey => { - aKey = _$(aKey).isString().default(void 0); + var readKey = fieldReader(_$(aKey).isString().default(void 0)); var sum = 0, c = 0; - code.select(r => { - var v = ($$(aKey).isDef() ? Number($$(r).get(aKey)) : Number(r)); - if (v != null && $$(v).isNumber()) { + code.select().forEach(r => { + var v = Number(readKey === null ? r : readKey(r)); + if (Number.isFinite(v)) { c++; sum += v; } @@ -479,12 +491,12 @@ var nLinq = function(anObject, aK) { return (c > 0 ? sum / c : void 0); }, sum: aKey => { - aKey = _$(aKey).isString().default(void 0); + var readKey = fieldReader(_$(aKey).isString().default(void 0)); var sum = 0; - code.select(r => { - var v = ($$(aKey).isDef() ? Number($$(r).get(aKey)) : Number(r)); - if (v != null && $$(v).isNumber()) { + code.select().forEach(r => { + var v = Number(readKey === null ? r : readKey(r)); + if (Number.isFinite(v)) { sum += v; } }); @@ -492,22 +504,26 @@ var nLinq = function(anObject, aK) { return sum; }, distinct: aKey => { - aKey = _$(aKey).isString().default(void 0); - var vals = []; - - code.select(r => { - var v = ($$(aKey).isDef() ? $$(r).get(aKey) : r); - if (vals.indexOf(v) < 0) vals.push(v); + var readKey = fieldReader(_$(aKey).isString().default(void 0)); + var vals = [], seen = new Set(); + + code.select().forEach(r => { + var v = readKey === null ? r : readKey(r); + // indexOf treats each NaN as distinct; retain the original value (including -0). + if (v !== v || !seen.has(v)) { + vals.push(v); + seen.add(v); + } }); return vals; }, group : aKey => { aKey = _$(aKey).isString().default(void 0); - var vals = {}; + var vals = {}, readKey = fieldReader(aKey); - code.select(r => { - var v = ($$(aKey).isDef() ? $$(r).get(aKey) : r); + code.select().forEach(r => { + var v = readKey === null ? r : readKey(r); if (!Object.prototype.hasOwnProperty.call(vals, v)) { Object.defineProperty(vals, v, { value: [r], enumerable: true, writable: true, configurable: true }) } else { @@ -518,30 +534,18 @@ var nLinq = function(anObject, aK) { return vals }, groupBy: (aKey) => { - aKey = _$(aKey).isString().default("key") - - var ks = aKey.split(",") - var _fr = {} - - var fn = (_r, _i, m) => { - var _vs = Object.keys(_r) - _vs.forEach((v, _j) => { - Object.defineProperty(m, v, { value: {}, enumerable: true, writable: true, configurable: true }) - if (_i + 1 < ks.length) { - fn(nLinq(_r[v]).group(ks[_i + 1]), _i + 1, m[v]) - } - if (ks.length == _i + 1) { - m[v] = _r[v] - } - }) - } - - if (ks.length > 0) { - fn(code.group(ks[0]), 0, _fr) - return _fr - } else { - return [] + var keys = _$(aKey).isString().default("key").split(",") + var nest = (groups, depth) => { + // groupBy historically exposes only the string keys returned by Object.keys. + Object.getOwnPropertySymbols(groups).forEach(key => { delete groups[key] }) + if (depth < keys.length) { + Object.keys(groups).forEach(key => { + groups[key] = nest(nLinq(groups[key]).group(keys[depth]), depth + 1) + }) + } + return groups } + return nest(code.group(keys[0]), 1) }, minBy: (aKey, aField, aFnKey, aAltKey) => { return code.fnBy(aKey, v=>$$(nLinq(v).min(aField)).get(aField), _$(aFnKey).default("_min"), aAltKey) @@ -556,11 +560,11 @@ var nLinq = function(anObject, aK) { return code.fnBy(aKey, v=>nLinq(v).sum(aField), _$(aFnKey).default("_sum"), aAltKey) }, countBy: (aKey, aFnKey, aAltKey) => { - return code.fnBy(aKey, v=>nLinq(v).count(), _$(aFnKey).default("_count"), aAltKey) + return code.fnBy(aKey, countRows, _$(aFnKey).default("_count"), aAltKey) }, fnBy: (aKey, aFn, aFnKey, aAltKey) => { aKey = _$(aKey).isString().default("key") - aFn = _$(aFn).isFunction().default(v => v.length) + aFn = _$(aFn).isFunction().default(countRows) aFnKey = _$(aFnKey).isString().default("_result") aAltKey = _$(aAltKey).isString().default(aKey) @@ -594,7 +598,19 @@ var nLinq = function(anObject, aK) { } if (ks.length > 0) { - fn(code.group(ks[0]), 0, {}) + var groups + if (ks.length === 1 && aFn === countRows) { + var readKey = fieldReader(ks[0]) + groups = Object.create(null) + code.select().forEach(row => { + var key = readKey(row) + if (Object.prototype.hasOwnProperty.call(groups, key)) groups[key].length++ + else groups[key] = { length: 1 } + }) + } else { + groups = code.group(ks[0]) + } + fn(groups, 0, {}) return _fr } else { return [] @@ -633,7 +649,7 @@ var nLinq = function(anObject, aK) { at : aParam => { _$(aParam, "index").isNumber().$_(); - res = applyConditions(res, void 0, true) + res = applyConditions(res, void 0, true); return res[Number(aParam)]; }, all : (aFallback) => { res = applyConditions(res, void 0, true); return $$(res).isArray() ? res.length == anObject.length : aFallback; }, @@ -648,7 +664,7 @@ var nLinq = function(anObject, aK) { each : aFn => { _$(aFn, "each function").isFunction().$_(); - code.select(aFn); + code.select().forEach(aFn); return code; }, @@ -811,34 +827,32 @@ var nLinq = function(anObject, aK) { return code; }, sort : function() { - var ssort = ""; - res = applyConditions(res); - for(var o = 0; o < arguments.length; o++) { - var k = arguments[o]; - var rev = false; - if (k.startsWith("-")) { - rev = true; - k = k.substr(1, k.length -1); - } - - if (ssort.length > 0) ssort += " || "; else ssort = "return "; - if (rev) { - //if (k.indexOf(".") > 0 || k.indexOf("[") > 0) - // ssort += " $$(b).get(\"" + k + "\") - $$(a).get(\"" + k + "\") "; - //else - ssort += " ($$(a).get(\"" + k + "\") > $$(b).get(\"" + k + "\") ? -1 : ($$(a).get(\"" + k + "\") < $$(b).get(\"" + k + "\") ? 1 : 0)) "; + var readers = [], comparisons = []; + for (var i = 0; i < arguments.length; i++) { + var key = arguments[i]; + var descending = key.startsWith("-"); + if (descending) key = key.substr(1, key.length - 1); + + var left, right; + if (typeof key === "string" && plainPath.test(key)) { + var index = readers.length; + readers.push(fieldReader(key)); + left = "readers[" + index + "](a)"; + right = "readers[" + index + "](b)"; } else { - //if (k.indexOf(".") > 0 || k.indexOf("[") > 0) - // ssort += " $$(a).get(\"" + k + "\") - $$(b).get(\"" + k + "\") "; - //else - ssort += " ($$(a).get(\"" + k + "\") > $$(b).get(\"" + k + "\") ? 1 : ($$(a).get(\"" + k + "\") < $$(b).get(\"" + k + "\") ? -1 : 0)) "; + // Preserve the existing path syntax for complex keys. + left = '$$(a).get("' + key + '")'; + right = '$$(b).get("' + key + '")'; } + var direction = descending ? -1 : 1; + comparisons.push("(" + left + " > " + right + " ? " + direction + + " : (" + left + " < " + right + " ? " + -direction + " : 0))"); } - res = res.sort(new Function("a", "b", ssort)); - + var compare = new Function("readers", "a", "b", "return " + comparisons.join(" || ")); + res = res.sort(compare.bind(null, readers)); return code; }, assign: (aSource, aAlias, aPK, aFK, aFallback) => { @@ -902,7 +916,7 @@ var nLinq = function(anObject, aK) { }) var res - if ($$(aMap.select).isString()) res = code.tselect(new Function("elem", "index", "array", aMap.select)) + if ($$(aMap.select).isString()) res = code.select(new Function("elem", "index", "array", aMap.select)) if ($$(aMap.select).isMap()) res = code.select(aMap.select) if ($$(res).isUnDef() && $$(aMap.selector).isMap()) res = ($$(aMap.selector.func).isString() ? $$({}).set(aMap.selector.func, code[aMap.selector.func].apply(code, aMap.selector.args)) : res) @@ -912,7 +926,7 @@ var nLinq = function(anObject, aK) { }, // Main selector select : aParam => { - res = applyConditions(res, void 0, true) + res = applyConditions(res, void 0, true); // no parameters if ($$(aParam).isUnDef()) { return res; @@ -1021,7 +1035,10 @@ var nLinq = function(anObject, aK) { }) var _res - if ($$(aMap.select).isString()) _res = code.tselect(newFn("elem", "index", "array", aMap.select)) + if ($$(aMap.select).isString()) { + var compile = typeof newFn === "function" ? newFn : Function + _res = code.select(compile("elem", "index", "array", aMap.select)) + } if ($$(aMap.select).isMap()) _res = code.select(aMap.select) if ($$(_res).isUnDef() && $$(aMap.selector).isMap()) _res = ($$(aMap.selector.func).isString() ? code[aMap.selector.func].apply(code, aMap.selector.args) : _res) @@ -1045,32 +1062,32 @@ var nLinq = function(anObject, aK) { }, // OpenAF-only, explicit per-query opt-in. Filters/projections execute once before reduction. gpu: options => { - if (options !== undefined && (options === null || typeof options != "object" || Array.isArray(options))) throw new TypeError("gpu options must be a map") - code.__gpuOptions = options === undefined ? {} : options + if (options !== undefined && (options === null || typeof options != "object" || Array.isArray(options))) throw new TypeError("gpu options must be a map"); + code.__gpuOptions = options === undefined ? {} : options; if (!code.__gpuWrapped) { ["sum", "average", "min", "max"].forEach(operation => { - var original = code[operation] - code[operation] = key => key === undefined ? code._gpuAggregate(operation) : original(key) - }) - code.__gpuWrapped = true + var original = code[operation]; + code[operation] = key => key === undefined ? code._gpuAggregate(operation) : original(key); + }); + code.__gpuWrapped = true; } - return code + return code; }, _gpuAggregate: operation => { - var rows = code.select(), options = code.__gpuOptions - var fallback = () => nLinq(rows)[operation]() - if (!options || options.useGPU === false || __flags.PFOREACH.useGPU === false || /^(false|0|no|off)$/i.test(String(java.lang.System.getenv("OAF_PFOREACH_GPU")))) return fallback() - var service + var rows = code.select(), options = code.__gpuOptions; + var fallback = () => nLinq(rows)[operation](); + if (!options || options.useGPU === false || __flags.PFOREACH.useGPU === false || /^(false|0|no|off)$/i.test(String(java.lang.System.getenv("OAF_PFOREACH_GPU")))) return fallback(); + var service; try { if (typeof ow.loadGPU != "function") { - var root = getOPackPath("GPU") - if (isUnDef(root)) return fallback() - loadLib(root + "/gpu.js") + var root = getOPackPath("GPU"); + if (isUnDef(root)) return fallback(); + loadLib(root + "/gpu.js"); } - service = ow.loadGPU() + service = ow.loadGPU(); } catch(e) { return fallback(); } // Do not retry if a caller-supplied fallback throws. - return typeof service.aggregate == "function" ? service.aggregate(rows, operation, fallback, options) : fallback() + return typeof service.aggregate == "function" ? service.aggregate(rows, operation, fallback, options) : fallback(); } }; @@ -1078,4 +1095,4 @@ var nLinq = function(anObject, aK) { return code; }; -var $from = nLinq +var $from = nLinq; diff --git a/js/owrap.ai.js b/js/owrap.ai.js index 23bf4279..0acc0aeb 100644 --- a/js/owrap.ai.js +++ b/js/owrap.ai.js @@ -1005,10 +1005,11 @@ OpenWrap.ai.prototype.__gpttypes = { _applyReasoning(body, true) // Use terminal output for continuation and emit only text deltas to the callback. - var events = [], totals = {}, content = "" + var events = [], previousStats, content = "" var input = _promptResponsesInput(messages) for (var turn = 0; turn < 16; turn++) { body.input = input + if (isFunction(_r._miniACheckRequest)) _r._miniACheckRequest(body, body.model) if (isDef(_debugCh)) $ch(_debugCh).set({ _t: nowNano(), _f: "client" }, body) var response, streamError if (streaming) { @@ -1032,10 +1033,8 @@ OpenWrap.ai.prototype.__gpttypes = { } if (isDef(_debugCh)) $ch(_debugCh).set({ _t: nowNano(), _f: "llm" }, response) var stats = _captureStats(response, body) - if (stats && stats.tokens) { - Object.keys(stats.tokens).forEach(key => { totals[key] = (totals[key] || 0) + stats.tokens[key] }) - stats.tokens = clone(totals) - } + if (turn > 0) _lastStats = ow.ai.__combineRoundStats(previousStats, stats, true) + previousStats = _lastStats if (!isMap(response) || response.error != null) return response if (response.status == "failed") return merge(response, { error: { message: "OpenAI Responses request failed" } }) if (!isArray(response.output) || !["completed", "incomplete"].includes(response.status)) { @@ -1062,7 +1061,7 @@ OpenWrap.ai.prototype.__gpttypes = { var reason = response.status == "incomplete" ? (response.incomplete_details && response.incomplete_details.reason == "max_output_tokens" ? "length" : "content_filter") : (refusal.length ? "content_filter" : (calls.length ? "tool_calls" : "stop")) - if (stats) stats.finishReasons = [reason] + if (_lastStats) _lastStats.finishReasons = [reason] var prepared = reason == "tool_calls" ? _prepareToolCalls(calls, body.tools) : __ content += text if (isDef(prepared)) { @@ -1371,6 +1370,7 @@ OpenWrap.ai.prototype.__gpttypes = { } if (isDef(po.temperature)) body.temperature = po.temperature if (request.descriptor) body = _applyReasoning(merge(d.copy(aOptions.params || {}), body), transport == "responses") + if (request.descriptor && isFunction(_r._miniACheckRequest)) _r._miniACheckRequest(body, request.model) var raw = d.execution(() => _r._decisionRequest(_route(endpoint, request.model), body), "openai") return { raw: raw, stats: _captureStats(raw, body) } }, @@ -1449,6 +1449,7 @@ OpenWrap.ai.prototype.__gpttypes = { } if (isDef(temperature)) body.temperature = temperature _applyReasoning(body, toolTransport == "responses") + if (isFunction(_r._miniACheckRequest)) _r._miniACheckRequest(body, model) var raw = d.execution(() => _r._decisionRequest(_route(toolTransport == "responses" ? "responses" : "chat/completions", model), body), "openai") execution = { raw: raw, stats: _captureStats(raw, body) } } else execution = _r.rawStructuredPrompt(request) @@ -1652,6 +1653,7 @@ OpenWrap.ai.prototype.__gpttypes = { } } // Continue only the selected assistant turn and keep its calls together. + _captureStats(_res, body) var choice = isMap(_res) && isArray(_res.choices) ? _res.choices[0] : __ if (isMap(choice) && isMap(choice.message)) { var message = merge({ role: "assistant" }, choice.message) @@ -1660,12 +1662,14 @@ OpenWrap.ai.prototype.__gpttypes = { var prepared = _prepareToolCalls(message.tool_calls, body.tools) if (isDef(prepared)) { _r.conversation = _r.conversation.concat([message], _toolMessages(prepared)) - return _r.rawPrompt([], aModel, aTemperature, aJsonFlag, aTools) + var precedingStats = _lastStats + var continuation = _r.rawPrompt([], aModel, aTemperature, aJsonFlag, aTools) + _lastStats = ow.ai.__combineRoundStats(precedingStats, _lastStats) + return continuation } } if (_res.error == null) _r.conversation = _r.conversation.concat(message) } - _captureStats(_res, body) return _res }, rawPromptStream: (aPrompt, aModel, aTemperature, aJsonFlag, aTools, aOnDelta) => { @@ -1737,18 +1741,24 @@ OpenWrap.ai.prototype.__gpttypes = { if (reasoningRoute == "none") body.reasoning_effort = "none" if (isDef(_debugCh)) $ch(_debugCh).set({_t:nowNano(),_f:'client'}, merge({_t:nowNano(),_f:'client'}, body)) + // Request the final usage frame only on the official Chat endpoint. + if (aOptions.mode == "openai" && /^https:\/\/api\.openai\.com(?:\/v1)?\/?$/.test(aOptions.url)) { + body.stream_options = merge({ include_usage: true }, body.stream_options || {}) + } var events = [] var content = "" var toolCallsMap = {} var lastResponse = __ var finishReason = __ var hasOutput = false + var streamUsage var readChatStream = () => _readSseStream(_r._requestStream(_route("chat/completions", aModel), body), payload => { if (payload === "[DONE]") return true var data = isMap(payload) ? payload : jsonParse(payload, __, __, true) if (isDef(data)) { events.push(data) lastResponse = data + if (isMap(data.usage)) streamUsage = data.usage if (isArray(data.choices)) { data.choices.filter((choice, index) => (choice.index == null ? index : choice.index) === 0).forEach(choice => { if (isString(choice.finish_reason)) finishReason = choice.finish_reason @@ -1786,6 +1796,7 @@ OpenWrap.ai.prototype.__gpttypes = { if (retry == "none") { body.reasoning_effort = "none" events = [] + streamUsage = __ lastResponse = __ streamError = readChatStream() if (isUnDef(streamError) && isDef(finishReason)) _toolReasoningRoutes.set(reasoningKey, retry) @@ -1798,6 +1809,7 @@ OpenWrap.ai.prototype.__gpttypes = { return streamError } if (isDef(_debugCh)) $ch(_debugCh).set({_t:nowNano(),_f:'llm'}, { _t: nowNano(), _f: "llm", events: events }) + _captureStats(isMap(streamUsage) ? merge(lastResponse || {}, { usage: streamUsage }) : lastResponse, body) var toolCalls = Object.keys(toolCallsMap).map(k => toolCallsMap[k]) // Only a completed tool turn may execute its assembled calls. @@ -1806,7 +1818,9 @@ OpenWrap.ai.prototype.__gpttypes = { var message = { role: "assistant", content: content || null, tool_calls: toolCalls } if (isDef(prepared)) { _r.conversation = _r.conversation.concat([message], _toolMessages(prepared)) + var precedingStats = _lastStats var result = _r.rawPromptStream([], aModel, aTemperature, aJsonFlag, aTools, aOnDelta) + _lastStats = ow.ai.__combineRoundStats(precedingStats, _lastStats) if (isArray(result.events)) result.events = events.concat(result.events) if (isString(result.content)) result.content = content + result.content return result @@ -1815,7 +1829,6 @@ OpenWrap.ai.prototype.__gpttypes = { } else if (content.length > 0) { _r.conversation = _r.conversation.concat({ role: "assistant", content: content }) } - _captureStats(lastResponse, body) return { content: content, events: events, toolCalls: toolCalls, finishReason: finishReason } }, promptStream: (aPrompt, aModel, aTemperature, aJsonFlag, aTools, aOnDelta) => { @@ -1955,10 +1968,28 @@ OpenWrap.ai.prototype.__gpttypes = { return res } }, - getModelInfo: (aModelId) => { + getModelLimits: (aModelId) => { + aModelId = _$(aModelId, "aModelId").isString().default(_model) + if (/^https:\/\/openrouter\.ai(?:\/|$)/i.test(aOptions.url)) { + var response = _r._request(_route("models"), {}, "GET", 2000) + var info = isMap(response) && isArray(response.data) ? response.data.find(m => m.id === aModelId) : __ + if (!isMap(info)) return {} + var top = isMap(info.top_provider) ? info.top_provider : {} + return { + contextWindow: top.context_length > 0 ? Math.min(info.context_length || Infinity, top.context_length) : info.context_length, + maxOutputTokens: top.max_completion_tokens, + source: "OpenRouter model list" + } + } + var info = _r.getModelInfo(aModelId, 2000) + if (!isMap(info) || info.error) return {} + return { contextWindow: info.context_length, maxInputTokens: info.max_input_tokens, + maxOutputTokens: info.max_output_tokens, source: "provider metadata" } + }, + getModelInfo: (aModelId, aTimeout) => { aModelId = _$(aModelId, "aModelId").isString().default(_model) var _modelId = encodeURIComponent(aModelId) - return _r._request(_route("models/" + _modelId), {}, "GET") + return _r._request(_route("models/" + _modelId), {}, "GET", aTimeout) }, getEmbeddings: (aInput, aDimensions, aEmbeddingModel) => { aInput = _$(aInput, "aInput").$_() @@ -1979,14 +2010,14 @@ OpenWrap.ai.prototype.__gpttypes = { _captureStats(_res, body) return _res }, - _request: (aURI, aData, aVerb) => { + _request: (aURI, aData, aVerb, aTimeout) => { _$(aURI, "aURI").isString().$_() aData = _$(aData, "aData").isMap().default({}) aVerb = _$(aVerb, "aVerb").isString().default("POST") - var _h = new ow.obj.http(__, __, __, __, __, __, __, { timeout: _timeout }) + var _h = new ow.obj.http(__, __, __, __, __, __, __, { timeout: aTimeout || _timeout }) var __m = { - conTimeout : 60000, + conTimeout : aTimeout || 60000, httpClient : _h, requestHeaders: _headers("*/*") } @@ -2606,6 +2637,7 @@ OpenWrap.ai.prototype.__gpttypes = { if (isDef(_debugCh)) $ch(_debugCh).set({_t:nowNano(),_f:'client'}, merge({_t:nowNano(),_f:'client'}, body)) var _res = _r._request("models/" + aModel + ":generateContent", body) if (isDef(_debugCh)) $ch(_debugCh).set({_t:nowNano(),_f:'llm'}, merge({_t:nowNano(),_f:'llm'}, _res)) + _captureStats(_res, aModel) // Process the same candidate the prompt wrapper exposes. var candidate = isMap(_res) && isArray(_res.candidates) ? _res.candidates[0] : __ if (isMap(candidate) && candidate.finishReason == "STOP" && isMap(candidate.content) && isArray(candidate.content.parts)) { @@ -2613,10 +2645,12 @@ OpenWrap.ai.prototype.__gpttypes = { _r.conversation = _r.conversation.concat(newPrompts, [candidate.content]) if (results.length) { _r.conversation.push({ role: "user", parts: results }) - return _r.rawPrompt([], aModel, aTemperature, aJsonFlag, aTools) + var precedingStats = _lastStats + var continuation = _r.rawPrompt([], aModel, aTemperature, aJsonFlag, aTools) + _lastStats = ow.ai.__combineRoundStats(precedingStats, _lastStats) + return continuation } } - _captureStats(_res, aModel) return _res }, rawPromptStream: (aPrompt, aModel, aTemperature, aJsonFlag, aTools, aOnDelta) => { @@ -2733,7 +2767,9 @@ OpenWrap.ai.prototype.__gpttypes = { if (parts.length) _r.conversation = _r.conversation.concat(newPrompts, [{ role: "model", parts: parts }]) if (results.length) { _r.conversation.push({ role: "user", parts: results }) + var precedingStats = _lastStats var result = _r.rawPromptStream([], aModel, aTemperature, aJsonFlag, aTools, aOnDelta) + _lastStats = ow.ai.__combineRoundStats(precedingStats, _lastStats) if (isArray(result.events)) result.events = events.concat(result.events) if (isString(result.content) && result.error == null) result.content = content + result.content return result @@ -2796,12 +2832,12 @@ OpenWrap.ai.prototype.__gpttypes = { if (isDef(res.models)) res = res.models return res }, - getModelInfo: (aModelId) => { + getModelInfo: (aModelId, aTimeout) => { aModelId = _$(aModelId, "aModelId").isString().default(_model) var _modelName = aModelId if (_modelName.indexOf("models/") === 0) _modelName = _modelName.substring("models/".length) _modelName = encodeURIComponent(_modelName) - return _r._request("models/" + _modelName, {}, "GET") + return _r._request("models/" + _modelName, {}, "GET", aTimeout) }, getEmbeddings: (aInput, aDimensions, aEmbeddingModel) => { aInput = _$(aInput, "aInput").$_() @@ -2827,14 +2863,14 @@ OpenWrap.ai.prototype.__gpttypes = { _captureStats(_res, aEmbeddingModel) return _res }, - _request: (aURI, aData, aVerb) => { + _request: (aURI, aData, aVerb, aTimeout) => { _$(aURI, "aURI").isString().$_() aData = _$(aData, "aData").isMap().default({}) aVerb = _$(aVerb, "aVerb").isString().default("POST") - var _h = new ow.obj.http(__, __, __, __, __, __, __, { timeout: _timeout }) + var _h = new ow.obj.http(__, __, __, __, __, __, __, { timeout: aTimeout || _timeout }) var __m = { - conTimeout : 60000, + conTimeout : aTimeout || 60000, httpClient : _h, requestHeaders: merge(aOptions.headers, { //Authorization: "Bearer " + Packages.openaf.AFCmdBase.afc.dIP(_key), @@ -3250,6 +3286,7 @@ OpenWrap.ai.prototype.__gpttypes = { var _res = _r._request(uri, body) if (isDef(_debugCh)) $ch(_debugCh).set({_t:nowNano(),_f:'llm'}, merge({_t:nowNano(),_f:'llm'}, _res)) + _captureStats(_res, aModel) // Continue only after Ollama returns a completed assistant turn. if (isMap(_res) && _res.error == null && isMap(_res.message)) { var message = merge({ role: "assistant", content: "" }, _res.message) @@ -3257,11 +3294,13 @@ OpenWrap.ai.prototype.__gpttypes = { isArray(message.tool_calls) && message.tool_calls.length) { var results = _prepareOllamaTools(message.tool_calls, aTools).map(_ollamaToolResult) _r.conversation = _r.conversation.concat([message], results) - return _r.rawPrompt([], aModel, aTemperature, aJsonFlag, aTools) + var precedingStats = _lastStats + var continuation = _r.rawPrompt([], aModel, aTemperature, aJsonFlag, aTools) + _lastStats = ow.ai.__combineRoundStats(precedingStats, _lastStats) + return continuation } _r.conversation.push(message) } - _captureStats(_res, aModel) return _res }, rawPromptStream: (aPrompt, aModel, aTemperature, aJsonFlag, aTools, aOnDelta) => { @@ -3362,7 +3401,9 @@ OpenWrap.ai.prototype.__gpttypes = { var results = _prepareOllamaTools(streamedToolCalls, aTools).map(_ollamaToolResult) message.tool_calls = streamedToolCalls _r.conversation = _r.conversation.concat([message], results) + var precedingStats = _lastStats var result = _r.rawPromptStream([], aModel, aTemperature, aJsonFlag, aTools, aOnDelta) + _lastStats = ow.ai.__combineRoundStats(precedingStats, _lastStats) if (isArray(result.events)) result.events = events.concat(result.events) if (isString(result.content) && result.error == null) result.content = content + result.content return result @@ -3410,9 +3451,26 @@ OpenWrap.ai.prototype.__gpttypes = { return res } }, - getModelInfo: (aModelId) => { + getModelInfo: (aModelId, aTimeout) => { + aModelId = _$(aModelId, "aModelId").isString().default(_model) + return _r._request("/api/show", { model: aModelId }, "POST", aTimeout) + }, + getModelLimits: (aModelId) => { aModelId = _$(aModelId, "aModelId").isString().default(_model) - return _r._request("/api/show", { model: aModelId }) + var filename = aModelId.split("/").pop() + var canonical = filename.indexOf(":") < 0 && aModelId.indexOf("@") < 0 ? aModelId + ":latest" : aModelId + var running = _r._request("/api/ps", {}, "GET", 2000) + var loaded = isMap(running) && isArray(running.models) ? running.models.find(m => m.name === canonical || m.model === canonical) : __ + var allocated = isMap(loaded) && isNumber(loaded.context_length) && loaded.context_length > 0 ? loaded.context_length : __ + var requested = isNumber(_params.num_ctx) && _params.num_ctx > 0 ? _params.num_ctx : __ + if (isDef(requested)) { + var info = _r.getModelInfo(aModelId, 2000) + var fields = isMap(info) && isMap(info.model_info) ? info.model_info : {} + var key = String(fields["general.architecture"] || "") + ".context_length" + if (isNumber(fields[key]) && fields[key] > 0) requested = Math.min(requested, fields[key]) + return { contextWindow: requested, source: "Ollama num_ctx" } + } + return isDef(allocated) ? { contextWindow: allocated, source: "Ollama running allocation" } : {} }, getEmbeddings: (aInput, aDimensions, aEmbeddingModel) => { aInput = _$(aInput, "aInput").$_() @@ -3433,18 +3491,18 @@ OpenWrap.ai.prototype.__gpttypes = { _captureStats(_res, aEmbeddingModel) return _res }, - _request: (aURI, aData, aVerb) => { + _request: (aURI, aData, aVerb, aTimeout) => { _$(aURI, "aURI").isString().$_() aData = _$(aData, "aData").isMap().default({}) aVerb = _$(aVerb, "aVerb").isString().default("POST") if (!aURI.startsWith("/")) aURI = "/" + aURI - var _ownsClient = isUnDef(this._h) - var _h = _ownsClient ? new ow.obj.http(__, __, __, __, __, __, __, { timeout: _timeout }) : this._h + var _ownsClient = isDef(aTimeout) || isUnDef(this._h) + var _h = _ownsClient ? new ow.obj.http(__, __, __, __, __, __, __, { timeout: aTimeout || _timeout }) : this._h var __r = { - conTimeout : 60000, + conTimeout : aTimeout || 60000, httpClient : _h, requestHeaders: { Accept: "*/*" @@ -3546,6 +3604,7 @@ OpenWrap.ai.prototype.__gpttypes = { if (isDef(aResponse.usage.cache_read_input_tokens)) tokens.cacheRead = aResponse.usage.cache_read_input_tokens if (Object.keys(tokens).length > 0) stats.tokens = tokens stats.usage = aResponse.usage + stats.cacheTokensAdditional = true } if (isArray(aResponse.content)) { @@ -3929,7 +3988,10 @@ OpenWrap.ai.prototype.__gpttypes = { _r.conversation.push({ role: "assistant", content: _res.content }) if (results.length) { _r.conversation.push({ role: "user", content: results }) - return _r.rawPrompt([], aModel, _temperatureExplicit ? aTemperature : __, aJsonFlag, aTools) + var precedingStats = _lastStats + var continuation = _r.rawPrompt([], aModel, _temperatureExplicit ? aTemperature : __, aJsonFlag, aTools) + _lastStats = ow.ai.__combineRoundStats(precedingStats, _lastStats) + return continuation } } return _res @@ -4111,7 +4173,9 @@ OpenWrap.ai.prototype.__gpttypes = { { role: "assistant", content: contentBlocks }, { role: "user", content: results } ]) + var precedingStats = _lastStats var result = _r.rawPromptStream([], aModel, _temperatureExplicit ? aTemperature : __, aJsonFlag, aTools, aOnDelta) + _lastStats = ow.ai.__combineRoundStats(precedingStats, _lastStats) if (isArray(result.events)) result.events = events.concat(result.events) return result } @@ -4164,23 +4228,23 @@ OpenWrap.ai.prototype.__gpttypes = { return res } }, - getModelInfo: (aModelId) => { + getModelInfo: (aModelId, aTimeout) => { aModelId = _$(aModelId, "aModelId").isString().default(_model) var _modelId = encodeURIComponent(aModelId) - return _r._request("v1/models/" + _modelId, {}, "GET") + return _r._request("v1/models/" + _modelId, {}, "GET", aTimeout) }, getEmbeddings: (aInput, aDimensions, aEmbeddingModel) => { throw "Text embeddings not supported by Anthropic" }, - _request: (aURI, aData, aVerb) => { + _request: (aURI, aData, aVerb, aTimeout) => { _$(aURI, "aURI").isString().$_() aData = _$(aData, "aData").isMap().default({}) aVerb = _$(aVerb, "aVerb").isString().default("POST") - var _h = new ow.obj.http(__, __, __, __, __, __, __, { timeout: _timeout }) + var _h = new ow.obj.http(__, __, __, __, __, __, __, { timeout: aTimeout || _timeout }) var _reqHeaders = _anthropicHeaders("*/*") var __m = { - conTimeout : 60000, + conTimeout : aTimeout || 60000, httpClient : _h, requestHeaders: _reqHeaders } @@ -4453,6 +4517,47 @@ OpenWrap.ai.prototype.gpt.prototype.getModelInfo = function(aModelId) { } } +// Keep the most recent request available alongside aggregate tool-round usage. +OpenWrap.ai.prototype.__combineRoundStats = function(first, last, aggregate) { + var rounds = (first && first.rounds || [first]).concat(last && last.rounds || [last]) + var stats = isMap(last) ? clone(last) : isMap(first) ? clone(first) : {} + var tokens = {} + rounds.forEach(round => { + if (!isMap(round) || !isMap(round.tokens)) return + Object.keys(round.tokens).forEach(key => { + var value = round.tokens[key] + if (isNumber(value) && isFinite(value) && value >= 0) tokens[key] = (tokens[key] || 0) + value + }) + }) + if (Object.keys(tokens).length > 0) { + stats.operationTokens = tokens + if (aggregate === true) stats.tokens = tokens + } + stats.rounds = rounds.map(round => isMap(round) ? round : {}) + return stats +} + +/** + * + * ow.ai.gpt.prototype.getModelLimits(aModelId) : Map + * Returns available contextWindow, maxInputTokens and maxOutputTokens limits and their source. + * Unavailable limits are omitted. An adapter may also return the exact catalogModelId. + * + */ +OpenWrap.ai.prototype.gpt.prototype.getModelLimits = function(aModelId) { + if (isFunction(this.model.getModelLimits)) return this.model.getModelLimits(aModelId) + if (!isFunction(this.model.getModelInfo)) return {} + var info = this.model.getModelInfo(aModelId, 2000) + if (!isMap(info) || info.error) return {} + var limits = isMap(info.capabilities) && isMap(info.capabilities.limits) ? info.capabilities.limits : {} + return { + contextWindow: limits.maxContextWindowTokens || info.context_length, + maxInputTokens: limits.maxPromptTokens || info.inputTokenLimit || info.max_input_tokens, + maxOutputTokens: limits.maxOutputTokens || info.outputTokenLimit || info.max_tokens, + source: "provider metadata" + } +} + /** * * ow.ai.gpt.prototype.getEmbeddings(aInput, aDimensions, aEmbeddingModel) : Object @@ -4506,6 +4611,7 @@ OpenWrap.ai.prototype.gpt.prototype.__executeDecision = function(state, question if (isDef(request.images) && (request.strategy != "native" || !caps.inputTypes || caps.inputTypes.indexOf("image") < 0)) d.invalid() if (isDef(request.input) && (provider != "gemini" || request.strategy != "native")) d.invalid() var hook = request.strategy == "native" ? "rawDecide" : "rawStructuredPrompt" + if (isFunction(this.model._miniACheckRequest)) this.model._miniACheckRequest(request, request.model) var execution = d.execution(() => this.model[hook](request), provider) if (!execution || !d.has(execution, "raw")) d.badResponse() var raw = execution.raw, model = raw && d.text(raw.model) ? raw.model : request.model @@ -5329,9 +5435,10 @@ global.$gpt = function(aModel, aEmbeddingConfig) { * Returns the model information for aModelId (defaults to the current configured model when omitted). * */ - getModelInfo: (aModelId) => { + getModelInfo: (aModelId, aTimeout) => { return _getChat().getModelInfo(aModelId) }, + getModelLimits: (aModelId) => _getChat().getModelLimits(aModelId), /** * * $gpt.getLastStats() : Map diff --git a/js/owrap.obj.js b/js/owrap.obj.js index cea6d9ba..dad68e68 100644 --- a/js/owrap.obj.js +++ b/js/owrap.obj.js @@ -2075,9 +2075,46 @@ OpenWrap.obj.prototype.http.prototype.__exec = function(aURL, aRequestType, aIn, if (isNumber(aTimeout)) clt = clt.connectTimeout(aTimeout, java.util.concurrent.TimeUnit.MILLISECONDS) if (isNumber(options.timeout)) clt = clt.callTimeout(options.timeout, java.util.concurrent.TimeUnit.MILLISECONDS) + // Authorize the final URL and prevent authenticated follow-up requests. + var oauth = options.__oauthClient + var request = this.request, credential + if (isDef(oauth)) { + var authorize = ow.loadServer().oauth.__clients.get(oauth) + if (!isFunction(authorize) || ["Authorization", "DPoP", "Host", "Proxy-Authorization"].some(name => request.header(name) !== null) || + !this.client.interceptors().isEmpty() || !this.client.networkInterceptors().isEmpty() || + this.client.hostnameVerifier() !== Packages.okhttp3.internal.tls.OkHostnameVerifier.INSTANCE) { + throw new Error("Incompatible OAuth HTTP configuration") + } + credential = authorize(String(request.url()), String(request.method())) + if (isDef(credential.tls)) clt.sslSocketFactory(credential.tls.getSocketFactory(), credential.tls.getTrustManager()) + var authenticated = request.newBuilder().header("Authorization", credential.authorization) + if (isDef(credential.proof)) authenticated.header("DPoP", credential.proof) + request = authenticated.build() + var dispatched = new java.util.concurrent.atomic.AtomicBoolean(false) + clt.followRedirects(false).followSslRedirects(false).retryOnConnectionFailure(false) + .authenticator(Packages.okhttp3.Authenticator.NONE) + .addNetworkInterceptor(chain => { + if (!dispatched.compareAndSet(false, true)) throw new java.io.IOException("OAuth HTTP follow-up rejected") + return chain.proceed(chain.request()) + }) + } clt = clt.build() - this._response = clt.newCall(this.request).execute() + try { + this._response = clt.newCall(request).execute() + } catch(e) { + if (isDef(oauth)) throw new Error("OAuth HTTP request failed") + throw e + } + if (isDef(credential)) { + var nonces = this._response.headers("DPoP-Nonce") + if (nonces.size() === 1) credential.acceptNonce(String(nonces.get(0))) + } + if (isDef(oauth) && this._response.code() >= 400) { + var status = this._response.code() + this._response.close() + throw new Error("OAuth HTTP request failed with status " + status) + } this.outputObj = {} if (isBytes && !returnStream) { @@ -2647,6 +2684,15 @@ OpenWrap.obj.prototype.http0.prototype.close = function() { } OpenWrap.obj.prototype.rest = { + // OAuth requires the checked OkHttp request path. + __exec: function(http, url, method, body, headers, bytes, timeout, stream, options) { + if (isMap(options) && isDef(options.__oauthClient)) { + if (!(http instanceof ow.obj.http) || http.__exec !== ow.obj.http.prototype.__exec || + http.exec !== ow.obj.http.prototype.exec) throw new Error("HTTP factory does not support OAuth") + } + return http.exec(url, method, body, headers, bytes, timeout, stream, options) + }, + connectionFactory: function() { return new ow.obj.http(); @@ -2734,9 +2780,10 @@ OpenWrap.obj.prototype.rest = { } try { - res = h.exec(aURL + ow.obj.rest.writeIndexes(aIdx), "GET", __, aRequestMap, retBytes, _t, retBytes, options) + res = this.__exec(h, aURL + ow.obj.rest.writeIndexes(aIdx), "GET", __, aRequestMap, retBytes, _t, retBytes, options) return res } catch(e) { + if (isMap(options) && isDef(options.__oauthClient)) throw e e.message = "Exception " + e.message + "; error = " + stringify(h.getErrorResponse(true)); throw e; } finally { @@ -2791,9 +2838,10 @@ OpenWrap.obj.prototype.rest = { merge({"Content-Type":"application/json; charset=UTF-8"} , aRequestMap); try { - res = h.exec(aURL + ow.obj.rest.writeIndexes(aIdx), "POST", (isString(aDataRow) ? aDataRow : (urlEncode) ? ow.obj.rest.writeQuery(aDataRow) : stringify(aDataRow, __, '')), rmap, retBytes, _t, retBytes, options) + res = this.__exec(h, aURL + ow.obj.rest.writeIndexes(aIdx), "POST", (isString(aDataRow) ? aDataRow : (urlEncode) ? ow.obj.rest.writeQuery(aDataRow) : stringify(aDataRow, __, '')), rmap, retBytes, _t, retBytes, options) return res } catch(e) { + if (isMap(options) && isDef(options.__oauthClient)) throw e e.message = "Exception " + e.message + "; error = " + String(h.getErrorResponse(true)); throw e; } finally { @@ -2838,9 +2886,10 @@ OpenWrap.obj.prototype.rest = { _$(aDataRow.in, "aDataRow.in").$_(); h.upload(aDataRow.name, aDataRow.in); - res = h.exec(aURL + ow.obj.rest.writeIndexes(aIdx), aMethod, __, rmap, __, _t, retBytes, options) + res = this.__exec(h, aURL + ow.obj.rest.writeIndexes(aIdx), aMethod, __, rmap, __, _t, retBytes, options) return res } catch(e) { + if (isMap(options) && isDef(options.__oauthClient)) throw e e.message = "Exception " + e.message + "; error = " + String(h.getErrorResponse(true)); throw e; } finally { @@ -2909,9 +2958,10 @@ OpenWrap.obj.prototype.rest = { merge({"Content-Type":"application/json; charset=UTF-8"} , aRequestMap); try { - res = h.exec(aURL + ow.obj.rest.writeIndexes(aIdx), "PUT", (isString(aDataRow) ? aDataRow : (urlEncode) ? ow.obj.rest.writeQuery(aDataRow) : stringify(aDataRow, __, '')), rmap, retBytes, _t, retBytes, options) + res = this.__exec(h, aURL + ow.obj.rest.writeIndexes(aIdx), "PUT", (isString(aDataRow) ? aDataRow : (urlEncode) ? ow.obj.rest.writeQuery(aDataRow) : stringify(aDataRow, __, '')), rmap, retBytes, _t, retBytes, options) return res } catch(e) { + if (isMap(options) && isDef(options.__oauthClient)) throw e e.message = "Exception " + e.message + "; error = " + String(h.getErrorResponse(true)); throw e; } finally { @@ -2967,9 +3017,10 @@ OpenWrap.obj.prototype.rest = { merge({"Content-Type":"application/json; charset=UTF-8"} , aRequestMap); try { - res = h.exec(aURL + ow.obj.rest.writeIndexes(aIdx), "PATCH", (isString(aDataRow) ? aDataRow : (urlEncode) ? ow.obj.rest.writeQuery(aDataRow) : stringify(aDataRow, __, '')), rmap, retBytes, _t, retBytes, options) + res = this.__exec(h, aURL + ow.obj.rest.writeIndexes(aIdx), "PATCH", (isString(aDataRow) ? aDataRow : (urlEncode) ? ow.obj.rest.writeQuery(aDataRow) : stringify(aDataRow, __, '')), rmap, retBytes, _t, retBytes, options) return res } catch(e) { + if (isMap(options) && isDef(options.__oauthClient)) throw e e.message = "Exception " + e.message + "; error = " + String(h.getErrorResponse(true)); throw e; } finally { @@ -3018,9 +3069,10 @@ OpenWrap.obj.prototype.rest = { } try { - res = h.exec(aURL + ow.obj.rest.writeIndexes(aIdx), "DELETE", __, aRequestMap, retBytes, _t, retBytes, options) + res = this.__exec(h, aURL + ow.obj.rest.writeIndexes(aIdx), "DELETE", __, aRequestMap, retBytes, _t, retBytes, options) return res } catch(e) { + if (isMap(options) && isDef(options.__oauthClient)) throw e e.message = "Exception " + e.message + "; error = " + String(h.getErrorResponse(true)); throw e; } finally { @@ -3066,11 +3118,12 @@ OpenWrap.obj.prototype.rest = { } try { - var res = h.exec(aURL + ow.obj.rest.writeIndexes(aIdx), "HEAD", __, aRequestMap, __, _t, __, options) + var res = this.__exec(h, aURL + ow.obj.rest.writeIndexes(aIdx), "HEAD", __, aRequestMap, __, _t, __, options) res.contentType = "application/json; charset=UTF-8" res.response = h.responseHeaders() return res } catch(e) { + if (isMap(options) && isDef(options.__oauthClient)) throw e e.message = "Exception " + e.message + "; error = " + String(h.getErrorResponse(true)); throw e; } finally { diff --git a/js/owrap.server.js b/js/owrap.server.js index 6b77d5ea..5c3687a9 100644 --- a/js/owrap.server.js +++ b/js/owrap.server.js @@ -1752,6 +1752,253 @@ OpenWrap.server.prototype.mcp = { invalidParams : -32602 }, + // Methods whose complete results carry CacheableResult hints (ttlMs/cacheScope) in the modern era + cacheableMethods: ["server/discover", "tools/list", "prompts/list", "resources/list", "resources/templates/list", "resources/read"], + + /** + * + * ow.server.mcp.headerValue(aHeaders, aName) : String + * Returns the value of the HTTP header aName from the aHeaders map using a case-insensitive name lookup + * (HTTP header names are case-insensitive), or __ if not present. + * + */ + headerValue: function(aHeaders, aName) { + if (!isMap(aHeaders) || !isString(aName)) return __ + var _name = aName.toLowerCase() + var _key = Object.keys(aHeaders).filter(k => String(k).toLowerCase() === _name)[0] + return isDef(_key) && isDef(aHeaders[_key]) && !isNull(aHeaders[_key]) ? String(aHeaders[_key]) : __ + }, + + /** + * + * ow.server.mcp.encodeHeaderValue(aValue) : String + * Encodes aValue for a MCP request metadata header (e.g. Mcp-Name). Values that are not plain printable ASCII, + * or that already look like the Base64 sentinel, are encoded as `=?base64?{UTF-8 Base64}?=`; other values are + * returned unchanged. + * + */ + encodeHeaderValue: function(aValue) { + var _v = String(aValue) + if (/^[\x20-\x7E]*$/.test(_v) && !/^=\?base64\?.*\?=$/.test(_v) && _v.trim() === _v) return _v + return "=?base64?" + String(java.util.Base64.getEncoder().encodeToString(new java.lang.String(_v).getBytes("UTF-8"))) + "?=" + }, + + /** + * + * ow.server.mcp.decodeHeaderValue(aValue) : String + * Decodes a MCP request metadata header value: a `=?base64?{UTF-8 Base64}?=` sentinel is decoded, any other + * value is returned unchanged. Returns __ if aValue is undefined or the sentinel isn't valid Base64. + * + */ + decodeHeaderValue: function(aValue) { + if (isUnDef(aValue) || isNull(aValue)) return __ + var _v = String(aValue) + var _m = _v.match(/^=\?base64\?(.*)\?=$/) + if (!_m) return _v + try { + return String(new java.lang.String(java.util.Base64.getDecoder().decode(_m[1]), "UTF-8")) + } catch(e) { + return __ + } + }, + + /** + * + * ow.server.mcp.nameSourceOf(reqObj) : String + * Returns the request body value that the Mcp-Name header must mirror: params.name for tools/call and + * prompts/get, params.uri for resources/read, params.taskId for tasks/get, tasks/update and tasks/cancel + * (tasks extension), or __ for any other method. + * + */ + nameSourceOf: function(reqObj) { + if (!isMap(reqObj) || !isMap(reqObj.params)) return __ + // Core transport sources plus the tasks extension's taskId routing header + var _field = ({ "tools/call": "name", "prompts/get": "name", "resources/read": "uri", "tasks/get": "taskId", "tasks/update": "taskId", "tasks/cancel": "taskId" })[reqObj.method] + if (isUnDef(_field) || isUnDef(reqObj.params[_field]) || isNull(reqObj.params[_field])) return __ + return String(reqObj.params[_field]) + }, + + /** + * + * ow.server.mcp.headerMismatchError(anId, aMessage) : Map + * Builds a JSON-RPC HeaderMismatch (-32020) error response. + * + */ + headerMismatchError: function(anId, aMessage) { + return { jsonrpc: "2.0", id: isDef(anId) ? anId : null, error: { code: this.errorCodes.headerMismatch, message: aMessage } } + }, + + /** + * + * ow.server.mcp.headerAnnotations(anInputSchema) : Map + * Collects the `x-mcp-header` annotations of a tool's inputSchema (2026-07-28 Streamable HTTP custom headers). + * Returns { valid, error, params } where params is an array of { header, path, type }: header is the + * `Mcp-Param-{header}` name portion, path the chain of property names inside the tool arguments and type the + * property's JSON type. An annotation is invalid (valid false, error says why) unless it is reached only + * through `properties` keywords, is a non-empty HTTP token (RFC 9110 tchar), is case-insensitively unique and + * annotates a property of type "string", "integer" or "boolean". + * + */ + headerAnnotations: function(anInputSchema) { + var _params = [], _seen = {}, _error + + // Walk the schema; only pure "properties" chains may carry an annotation + var _walk = (node, path, pure) => { + if (isDef(_error)) return + if (isArray(node)) return node.forEach(n => _walk(n, path, false)) + if (!isMap(node)) return + if (Object.prototype.hasOwnProperty.call(node, "x-mcp-header")) { + var _h = node["x-mcp-header"] + if (!pure || path.length == 0) return _error = "x-mcp-header is only allowed on properties reached through 'properties' (at '" + path.join(".") + "')" + if (!isString(_h) || !/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(_h)) return _error = "invalid x-mcp-header value '" + _h + "' for '" + path.join(".") + "'" + if (isDef(_seen[_h.toLowerCase()])) return _error = "duplicate x-mcp-header value '" + _h + "'" + if (["string", "integer", "boolean"].indexOf(node.type) < 0) return _error = "x-mcp-header '" + _h + "' must annotate a string, integer or boolean property" + _seen[_h.toLowerCase()] = true + _params.push({ header: _h, path: path, type: node.type }) + } + Object.keys(node).forEach(k => { + if (k == "x-mcp-header") return + if (k == "properties" && isMap(node.properties)) { + Object.keys(node.properties).forEach(p => _walk(node.properties[p], path.concat([p]), pure)) + } else { + _walk(node[k], path, false) + } + }) + } + _walk(anInputSchema, [], true) + + if (isDef(_error)) return { valid: false, error: _error, params: [] } + return { valid: true, error: __, params: _params } + }, + + /** + * + * ow.server.mcp.paramValueOf(anArguments, aPath) : Object + * Returns the tool argument value at aPath (array of property names) or __ if absent or null. + * + */ + paramValueOf: function(anArguments, aPath) { + var _v = anArguments + for (var i = 0; i < aPath.length; i++) { + if (!isMap(_v) || !Object.prototype.hasOwnProperty.call(_v, aPath[i])) return __ + _v = _v[aPath[i]] + } + return (isUnDef(_v) || isNull(_v)) ? __ : _v + }, + + /** + * + * ow.server.mcp.paramHeaders(anInputSchema, anArguments) : Map + * Returns the `Mcp-Param-{Name}` request headers a client must send for a tools/call with anArguments given + * the tool's anInputSchema (strings as-is, integers in decimal, booleans as "true"/"false", Base64 sentinel + * encoded when needed). Absent or null arguments produce no header. Returns {} for invalid annotations. + * + */ + paramHeaders: function(anInputSchema, anArguments) { + var _ann = this.headerAnnotations(anInputSchema), _res = {} + if (!_ann.valid) return _res + _ann.params.forEach(p => { + var _v = this.paramValueOf(anArguments, p.path) + if (isDef(_v)) _res["Mcp-Param-" + p.header] = this.encodeHeaderValue(isBoolean(_v) ? (_v ? "true" : "false") : String(_v)) + }) + return _res + }, + + /** + * + * ow.server.mcp.validateHeaders(aHeaders, reqObj, aVersion, aTools) : Map + * Validates the 2026-07-28 Streamable HTTP request metadata headers of a modern-era request against its body: + * MCP-Protocol-Version must equal aVersion (the params._meta protocol version), Mcp-Method must equal the + * JSON-RPC method and, for the methods listed in `ow.server.mcp.nameSourceOf`, Mcp-Name (Base64 sentinel + * decoded) must equal the corresponding params.name/params.uri/params.taskId. Header values are compared + * case-sensitively. For tools/call, when aTools (an array of tool definitions, or a function returning one) + * is given, every `x-mcp-header` annotated argument present in the body must be mirrored by its + * `Mcp-Param-{Name}` header and every such header must match its argument (integers compared numerically). + * Returns a HeaderMismatch (-32020) error response map, to be sent with HTTP 400, or __ if the headers are valid. + * + */ + validateHeaders: function(aHeaders, reqObj, aVersion, aTools) { + var _id = isMap(reqObj) ? reqObj.id : __ + var _checks = [ + { header: "MCP-Protocol-Version", body: aVersion, decode: false }, + { header: "Mcp-Method", body: isMap(reqObj) ? reqObj.method : __, decode: false } + ] + var _name = this.nameSourceOf(reqObj) + if (isDef(_name)) _checks.push({ header: "Mcp-Name", body: _name, decode: true }) + + // Check each required header is present and mirrors the body + for (var i = 0; i < _checks.length; i++) { + var _c = _checks[i] + var _raw = this.headerValue(aHeaders, _c.header) + if (isUnDef(_raw)) return this.headerMismatchError(_id, "Missing required header: " + _c.header) + var _hv = _c.decode ? this.decodeHeaderValue(_raw) : _raw + if (_hv !== String(_c.body)) return this.headerMismatchError(_id, "Header mismatch: " + _c.header + " header value '" + _raw + "' does not match body value '" + _c.body + "'") + } + + // Check the custom headers declared by the called tool's x-mcp-header annotations + if (reqObj.method == "tools/call" && isDef(aTools) && isMap(reqObj.params)) { + var _tools = isFunction(aTools) ? aTools() : aTools + var _tool = isArray(_tools) ? _tools.filter(t => isMap(t) && t.name === reqObj.params.name)[0] : __ + if (isMap(_tool)) { + var _ann = this.headerAnnotations(_tool.inputSchema) + if (_ann.valid) { + for (var j = 0; j < _ann.params.length; j++) { + var _p = _ann.params[j], _hname = "Mcp-Param-" + _p.header + var _bv = this.paramValueOf(reqObj.params.arguments, _p.path) + var _hraw = this.headerValue(aHeaders, _hname) + if (isUnDef(_hraw) && isUnDef(_bv)) continue + if (isUnDef(_hraw)) return this.headerMismatchError(_id, "Missing required header: " + _hname) + if (isUnDef(_bv)) return this.headerMismatchError(_id, "Header mismatch: " + _hname + " header value '" + _hraw + "' has no corresponding body value") + if (!/^[\x20-\x7E\t]*$/.test(_hraw)) return this.headerMismatchError(_id, "Invalid characters in header: " + _hname) + var _hdec = this.decodeHeaderValue(_hraw) + var _ok = isDef(_hdec) && (_p.type == "integer" + ? (_hdec.trim().length > 0 && isNumber(_bv) && Number(_hdec) === _bv) + : _hdec === (isBoolean(_bv) ? (_bv ? "true" : "false") : String(_bv))) + if (!_ok) return this.headerMismatchError(_id, "Header mismatch: " + _hname + " header value '" + _hraw + "' does not match body value '" + _bv + "'") + } + } + } + } + return __ + }, + + /** + * + * ow.server.mcp.toolsOf(mapOfFunctions, opts) : Function + * Returns a function listing the server's tool definitions for `Mcp-Param-{Name}` validation: opts.tools (an + * array or a function returning one) when given, otherwise the tools returned by mapOfFunctions["tools/list"] + * (following nextCursor), or __ when neither is available. + * + */ + toolsOf: function(mapOfFunctions, opts) { + if (isMap(opts) && isDef(opts.tools)) return isFunction(opts.tools) ? opts.tools : () => opts.tools + if (!isMap(mapOfFunctions) || !isFunction(mapOfFunctions["tools/list"])) return __ + return () => { + var _all = [], _cursor, _pages = 0 + do { + var _res = mapOfFunctions["tools/list"](isDef(_cursor) ? { cursor: _cursor } : {}) + if (!isMap(_res) || !isArray(_res.tools)) break + _all = _all.concat(_res.tools) + _cursor = _res.nextCursor + _pages++ + } while (isDef(_cursor) && _pages < 100) + return _all + } + }, + + /** + * + * ow.server.mcp.normalizeCacheHints(aTTL, aScope) : Map + * Returns valid CacheableResult hints { ttlMs, cacheScope }: ttlMs is an integer >= 0 (default 0) and cacheScope + * is "public" or "private" (default "private"). + * + */ + normalizeCacheHints: function(aTTL, aScope) { + var _ttl = Number(aTTL) + _ttl = (isNumber(_ttl) && isFinite(_ttl) && _ttl > 0) ? Math.floor(_ttl) : 0 + return { ttlMs: _ttl, cacheScope: (aScope === "public" || aScope === "private") ? aScope : "private" } + }, + /** * * ow.server.mcp.isModern(aVersion) : boolean @@ -1853,9 +2100,11 @@ OpenWrap.server.prototype.mcp = { * ow.server.mcp.wrapResult(aBody, anEra, opts) : Map * Wraps a MCP result body per the negotiated era. Legacy eras ("legacy-initialize"/"legacy-stateless") return * aBody unchanged -- zero behavior change for existing callers. The "modern" era merges in the required - * resultType ("complete"), and, when opts.isList is true, CacheableResult fields (ttlMs, cacheScope) with - * sensible defaults (opts.ttlMs default 0, opts.cacheScope default "private"). When opts.serverInfo is given, - * it is advertised (SHOULD, per spec) as result._meta["io.modelcontextprotocol/serverInfo"]. + * resultType ("complete"), and, when opts.isList is true (any cacheable method, see + * `ow.server.mcp.cacheableMethods`) and the result is complete, CacheableResult fields (ttlMs, cacheScope) + * normalized by `ow.server.mcp.normalizeCacheHints` (opts.ttlMs default 0, opts.cacheScope default "private"). + * Interim (e.g. input_required) results carry no caching hints. When opts.serverInfo is given, it is advertised + * (SHOULD, per spec) as result._meta["io.modelcontextprotocol/serverInfo"]. * */ wrapResult: function(aBody, anEra, opts) { @@ -1863,11 +2112,8 @@ OpenWrap.server.prototype.mcp = { opts = isMap(opts) ? opts : {} // Keep nested protocol payloads opaque when adding top-level result fields. var _res = Object.assign({ resultType: "complete" }, aBody) - if (opts.isList === true) { - _res = Object.assign({ - ttlMs : isNumber(opts.ttlMs) ? opts.ttlMs : 0, - cacheScope: isString(opts.cacheScope) ? opts.cacheScope : "private" - }, _res) + if (opts.isList === true && _res.resultType == "complete") { + _res = Object.assign(this.normalizeCacheHints(opts.ttlMs, opts.cacheScope), _res) } if (isMap(opts.serverInfo)) { _res._meta = merge({ "io.modelcontextprotocol/serverInfo": opts.serverInfo }, isMap(_res._meta) ? _res._meta : {}) @@ -1877,19 +2123,21 @@ OpenWrap.server.prototype.mcp = { /** * - * ow.server.mcp.discoverResult(initData) : Map + * ow.server.mcp.discoverResult(initData, opts) : Map * Builds the mandatory server/discover response (modern era) advertising this server's supported protocol - * versions, capabilities and identity. + * versions, capabilities and identity, plus the required caching hints from the optional opts map + * ({ ttlMs, cacheScope }, normalized by `ow.server.mcp.normalizeCacheHints`; default 0 and "private"). * */ - discoverResult: function(initData) { + discoverResult: function(initData, opts) { initData = isMap(initData) ? initData : {} - return { + opts = isMap(opts) ? opts : {} + return Object.assign({ resultType : "complete", protocolVersions: this.versions.supported, capabilities : initData.capabilities || {}, serverInfo : initData.serverInfo || {} - } + }, this.normalizeCacheHints(opts.ttlMs, opts.cacheScope)) } } @@ -2221,8 +2469,11 @@ OpenWrap.server.prototype.mcp.openWorkflows = function(definitions, options) { records.put(id, text) commit() index(record) + if (isUnDef(record.phase) && isUnDef(record.claim)) delete identities[id] } + var identities = Object.create(null) var remove = id => { + delete identities[id] records.remove(id) commit() delete pending[id] @@ -2366,10 +2617,10 @@ OpenWrap.server.prototype.mcp.openWorkflows = function(definitions, options) { finish(record, "completed", output) } } - var execute = (id, record, phase, callback) => { + var execute = (id, record, phase, callback, identity) => { var output, failed = false try { - output = callback(copy(record.arguments || {}), callbackContext(record)) + output = callback(copy(record.arguments || {}), callbackContext(record), identity) } catch (e) { failed = true } finally { @@ -2462,7 +2713,8 @@ OpenWrap.server.prototype.mcp.openWorkflows = function(definitions, options) { record.claim = genUUID(true) save(id, record) running[id] = record.mode === "external" ? now() + deadline : Infinity - $doV(() => execute(id, record, phase, callback)) + var identity = identities[id] + $doV(() => execute(id, record, phase, callback, identity)) }) }) } @@ -2491,13 +2743,17 @@ OpenWrap.server.prototype.mcp.openWorkflows = function(definitions, options) { safeArguments(value[key], depth + 1) }) } - var call = (params, owner, fallback) => { + var call = (params, owner, fallback, identity) => { authorize(owner) var definition = definitions[params.name], caps = clientCaps(params) var modern = mcp.isModern(mcp.metaProtocolVersion({ params: params })) var args = params.arguments || params.input || {} if (!isMap(args)) invalid("Expected tool arguments") safeArguments(args, 0) + if (isDef(identity)) { + args = copy(args) + delete args._mcpauth + } if (definition.mode !== "inline" && (!modern || !hasTasks(caps))) { if (definition.fallback === "sync" && !isDef(params.requestState) && !isDef(params.inputResponses)) { var fallbackArgs = copy(args) @@ -2519,6 +2775,7 @@ OpenWrap.server.prototype.mcp.openWorkflows = function(definitions, options) { var record = { id: id, mode: definition.mode, owner: owner, tool: params.name, arguments: copy(args), status: "working", phase: "start", created: time, updated: time, expires: time + ttl } save(id, record) + if (isDef(identity)) identities[id] = identity return publicTask(record, "task") }) @@ -2535,7 +2792,7 @@ OpenWrap.server.prototype.mcp.openWorkflows = function(definitions, options) { }) handler = definition.resume } - var output = handler(copy(args), ctx) + var output = handler(copy(args), ctx, identity) if (!isMap(output) || output.status !== "input_required") return output if (!definition.elicitation) fail(-32603, "Elicitation is disabled for this workflow") return atomic(() => { @@ -2546,12 +2803,15 @@ OpenWrap.server.prototype.mcp.openWorkflows = function(definitions, options) { return { resultType: "input_required", requestState: token, inputRequests: inputRequests } }) } - var task = (method, params, owner) => atomic(() => { + var ownedTask = (id, owner) => { + var record = isString(id) ? get(id) : __ + if (isDef(record) && record.mode !== "inline" && record.owner === owner && record.expires > now()) return record + } + var task = (method, params, owner, identity) => atomic(() => { authorize(owner) if (!mcp.isModern(mcp.metaProtocolVersion({ params: params }))) fail(-32601, "Method not found") - var record = isMap(params) && isString(params.taskId) ? get(params.taskId) : __ - if (isUnDef(record) || record.mode === "inline" || record.owner !== owner || record.expires <= now()) - invalid("Unknown MCP task") + var record = isMap(params) ? ownedTask(params.taskId, owner) : __ + if (isUnDef(record)) invalid("Unknown MCP task") if (method === "get") return publicTask(record, "complete") if (method === "update" && record.status === "input_required") { var answers = formAnswers(record.inputRequests, params.inputResponses, false) @@ -2563,6 +2823,7 @@ OpenWrap.server.prototype.mcp.openWorkflows = function(definitions, options) { record.updated = now() delete record.inputRequests save(record.id, record) + if (isDef(identity)) identities[record.id] = identity } } if (method === "cancel" && !terminal(record.status)) { @@ -2578,6 +2839,7 @@ OpenWrap.server.prototype.mcp.openWorkflows = function(definitions, options) { } } save(record.id, record) + if (isDef(identity) && (isDef(record.phase) || isDef(record.claim))) identities[record.id] = identity } return { resultType: "complete" } }) @@ -2590,6 +2852,7 @@ OpenWrap.server.prototype.mcp.openWorkflows = function(definitions, options) { try { if (!closed) { closed = true + Object.keys(identities).forEach(id => { delete identities[id] }) store.close() } } finally { @@ -2619,23 +2882,30 @@ OpenWrap.server.prototype.mcp.openWorkflows = function(definitions, options) { extensions[extension] = {} return merge(description, { capabilities: { extensions: extensions } }) }, - bind: (methods, request, owner) => { + toolForTask: (id, owner) => atomic(() => { + authorize(owner) + var record = ownedTask(id, owner) + if (isDef(record)) return record.tool + }), + bind: (methods, request, owner, identity, resolveTool) => { // Notifications cannot start work or consume a form answer. var notifier = isUnDef(request.id) || isNull(request.id) var supplied = isArray(request.params) ? request.params[0] : request.params - if (request.method === "tools/call" && isMap(supplied) && isString(supplied.name) && own(definitions, supplied.name)) { + var tool = isMap(supplied) && isString(supplied.name) ? + (isFunction(resolveTool) ? resolveTool(supplied.name) : supplied.name) : __ + if (request.method === "tools/call" && isDef(tool) && own(definitions, tool)) { var fallback = methods["tools/call"] methods["tools/call"] = params => { if (notifier) return if (!isMap(request.params)) invalid("Expected named tool parameters") - return call(params, owner, fallback) + return call(Object.assign({}, params, { name: tool }), owner, fallback, identity) } } if (taskModes && ["tasks/get", "tasks/update", "tasks/cancel"].indexOf(request.method) >= 0) methods[request.method] = params => { if (notifier) return if (!isMap(request.params)) invalid("Expected named task parameters") - return task(request.method.substring(6), params, owner) + return task(request.method.substring(6), params, owner, identity) } return methods } @@ -2654,8 +2924,10 @@ OpenWrap.server.prototype.mcp.openWorkflows = function(definitions, options) { * `opts`.rawToolResults (default false) preserves MCP content/structuredContent/isError envelopes returned by tools. * `opts` is an optional map: { modern: false } (default). When modern is true this also serves the 2026-07-28 * stateless/per-request MCP protocol era (per-request _meta protocol version, server/discover, resultType, - * ttlMs/cacheScope on list results, UnsupportedProtocolVersionError) side-by-side with the legacy + * ttlMs/cacheScope on cacheable results, UnsupportedProtocolVersionError) side-by-side with the legacy * initialize-handshake era used above, for any request that carries a modern _meta protocol version. + * `opts`.ttlMs (default 0) and `opts`.cacheScope (default "private") set the caching hints advertised on + * server/discover, list and resources/read results in the modern era. * When modern is false (the default) behavior is 100% unchanged from previous releases. * * Example usage: @@ -2776,7 +3048,7 @@ OpenWrap.server.prototype.mcpStdio = function(initData, fnsMeta, fns, lgF, opts) } // Wraps a result per the negotiated era (no-op for legacy eras) and, for the modern era, advertises this // server's identity on every result per the spec's per-response protocol fields. - var _wrap = (aBody, isList) => ow.server.mcp.wrapResult(aBody, _era, { isList: isList === true, serverInfo: initData.serverInfo }) + var _wrap = (aBody, isList) => ow.server.mcp.wrapResult(aBody, _era, { isList: isList === true, serverInfo: initData.serverInfo, ttlMs: opts.ttlMs, cacheScope: opts.cacheScope }) var _methods = merge({ // Only agree to a requested version this server supports (and that uses the initialize handshake); @@ -2851,10 +3123,10 @@ OpenWrap.server.prototype.mcpStdio = function(initData, fnsMeta, fns, lgF, opts) return global.__a2a__.send(params.id, params.message, params.options || {}, params.context || {}) }*/ }, opts.modern ? { - "server/discover": () => ow.server.mcp.discoverResult(isDef(opts.workflows) ? opts.workflows.describe(initData) : initData) + "server/discover": () => ow.server.mcp.discoverResult(isDef(opts.workflows) ? opts.workflows.describe(initData) : initData, { ttlMs: opts.ttlMs, cacheScope: opts.cacheScope }) } : {}) if (isDef(opts.skillCatalog)) Object.keys(opts.skillCatalog.methods).forEach(method => { - _methods[method] = params => _wrap(opts.skillCatalog.methods[method](params)) + _methods[method] = params => _wrap(opts.skillCatalog.methods[method](params), ow.server.mcp.cacheableMethods.indexOf(method) >= 0) }) if (opts.modern && isDef(opts.workflows)) { var selected = _pline.method @@ -2862,7 +3134,7 @@ OpenWrap.server.prototype.mcpStdio = function(initData, fnsMeta, fns, lgF, opts) opts.workflows.bind(_methods, _pline, opts.workflowOwner) if (isFunction(_methods[selected]) && _methods[selected] !== original) { var workflow = _methods[selected] - _methods[selected] = params => _wrap(workflow(params)) + _methods[selected] = params => _wrap(workflow(params), ow.server.mcp.cacheableMethods.indexOf(selected) >= 0) } } var _res = ow.server.jsonRPC(_pline, _methods) @@ -3962,6 +4234,8 @@ OpenWrap.server.prototype.clusterChsPeersImpl = { OpenWrap.server.prototype.httpd = { __routes: {}, + __reservedRoutes: {}, + __routeLock: new java.util.concurrent.locks.ReentrantLock(), __defaultRoutes: {}, __preRoutes: {}, __servers: {}, @@ -4345,7 +4619,12 @@ OpenWrap.server.prototype.httpd = { query[k] = decodeURIComponent((eq < 0 ? "" : pair.substring(eq + 1)).replace(/\+/g, " ")) }) } catch(e) { return httpd.reply("Invalid OAuth callback", 400, "text/plain", headers); } - if (req.method !== "GET" || query.state !== state) { + // Validate issuer identification before processing either a code or an authorization error. + var expectedIssuer = aOptions.issuer || aOptions.authorizationServerIssuer + var issuerRequired = aOptions.authorizationResponseIssuerRequired === true + if (req.method !== "GET" || query.state !== state || + (issuerRequired && (!isString(expectedIssuer) || query.iss !== expectedIssuer)) || + (isString(expectedIssuer) && isDef(query.iss) && query.iss !== expectedIssuer)) { return httpd.reply("Invalid OAuth callback", 400, "text/plain", headers) } var value @@ -4373,30 +4652,7 @@ OpenWrap.server.prototype.httpd = { } finally { stop(attempt); if (pending === attempt) pending = __; } } var exchange = function(params) { - params = merge(aOptions.extraParams || {}, params) - params.client_id = aOptions.clientId - if (isDef(aOptions.clientSecret) && ["none", "client_secret_basic"].indexOf(aOptions.tokenEndpointAuthMethod) < 0) params.client_secret = aOptions.clientSecret; - ["scope", "resource", "audience"].forEach(function(k) { if (isDef(aOptions[k])) params[k] = aOptions[k]; }) - var connection = ow.loadObj().rest.connectionFactory(), response, code - try { - connection.setThrowExceptions(false) - var timeout = positive(aOptions.tokenTimeoutMs, "tokenTimeoutMs", 60000) - connection.client = connection.client.newBuilder().followRedirects(false).followSslRedirects(false) - .callTimeout(timeout, java.util.concurrent.TimeUnit.MILLISECONDS).build() - var tokenHeaders = {} - if (aOptions.tokenEndpointAuthMethod == "client_secret_basic") { - var enc = function(v) { return String(java.net.URLEncoder.encode(String(v), "UTF-8")) } - tokenHeaders.Authorization = "Basic " + af.fromBytes2String(af.toBase64Bytes(af.fromString2Bytes(enc(aOptions.clientId) + ":" + enc(aOptions.clientSecret)))) - } - response = $rest({ httpClient: connection, requestHeaders: tokenHeaders, urlEncode: true, timeout: timeout, - readTimeout: timeout, callTimeout: timeout }).post(aOptions.tokenURL, params) - code = connection.responseCode() - } catch(e) { throw new Error("OAuth token request failed; check connectivity and provider configuration"); } - finally { try { connection.close(); } catch(ignoreClose) {} } - if (code < 200 || code >= 300 || !isMap(response) || !isString(response.access_token) || !response.access_token.length) { - throw oauthError("OAuth token request failed; provider did not return an access token", isMap(response) ? response.error : __) - } - return response + return ow.server.oauth.__exchange(aOptions, aOptions.tokenURL, params, true) } var authenticate = function(fp, retrying) { if (isString(token) && expiresAt > now() + _$(aOptions.refreshWindowMs).isNumber().default(30000)) { @@ -4466,9 +4722,13 @@ OpenWrap.server.prototype.httpd = { * ]]> * */ - start: function(aPort, aHost, keyStorePath, password, errorFunction, aWebSockets, aTimeout, aImpl) { - if (isNumber(aPort) && isDef(this.__servers[aPort])) return this.__servers[aPort] + start: function(aPort, aHost, keyStorePath, password, errorFunction, aWebSockets, aTimeout, aImpl, tlsProfile) { + if (isNumber(aPort) && isDef(this.__servers[aPort])) { + if (isDef(tlsProfile)) throw new Error("OAuth TLS profile requires a dedicated listener") + return this.__servers[aPort] + } aImpl = _$(aImpl).isString().default(__flags.HTTPD_DEFAULT_IMPL) + if (isDef(tlsProfile) && (aImpl !== "java" || !isMap(tlsProfile))) throw new Error("OAuth TLS profile requires the Java listener") plugin("HTTPServer"); @@ -4514,7 +4774,7 @@ OpenWrap.server.prototype.httpd = { if (isDef(aWebSockets) && isMap(aWebSockets)) throw "WebSockets are not supported in the Java HTTPd implementation." else - hs = new HTTPd(aPort, aHost, keyStorePath, password, errorFunction, __, aTimeout, aImpl); + hs = new HTTPd(aPort, aHost, keyStorePath, password, errorFunction, __, aTimeout, aImpl, tlsProfile); break } @@ -4552,7 +4812,9 @@ OpenWrap.server.prototype.httpd = { * */ resetRoutes: function(aHTTPd) { - this.__routes[Number(aHTTPd.getPort())] = {} + var port = Number(aHTTPd.getPort()) + if (Object.keys(this.__reservedRoutes[port] || {}).length > 0) throw new Error("Cannot reset reserved HTTP routes") + this.__routes[port] = {} this.__defaultRoutes[Number(aHTTPd.getPort())] = {} this.__preRoutes[Number(aHTTPd.getPort())] = {} @@ -4586,10 +4848,12 @@ OpenWrap.server.prototype.httpd = { /** * - * ow.server.httpd.route(aHTTPd, aMapOfRoutes, aDefaultRoute, aPath, aPreRouteFunc) + * ow.server.httpd.route(aHTTPd, aMapOfRoutes, aDefaultRoute, aPath, aPreRouteFunc, reservedRoutes) * * */ - route: function(aHTTPd, aMapOfRoutes, aDefaultRoute, aPath, aPreRouteFunc) { + route: function(aHTTPd, aMapOfRoutes, aDefaultRoute, aPath, aPreRouteFunc, reservedRoutes) { aMapOfRoutes = _$(aMapOfRoutes, "aMapOfRoutes").isMap().default({}) aDefaultRoute = _$(aDefaultRoute, "aDefaultRoute").isFunction().default(function(r) { return aHTTPd.reply("", "", 401, {}) }) @@ -4623,14 +4887,26 @@ OpenWrap.server.prototype.httpd = { var aPort = Number(aHTTPd.getPort()) var aP = String(aPath); - if (isUnDef(this.__routes[aPort])) this.__routes[aPort] = {} - Object.keys(aMapOfRoutes).forEach(uri => { - parent.__routes[aPort][uri] = aMapOfRoutes[uri] - }) - //this.__routes[aPort] = aMapOfRoutes; - if (isDef(aDefaultRoute)) this.__defaultRoutes[aPort] = aDefaultRoute; - if (isDef(aPreRouteFunc)) this.__preRoutes[aPort] = aPreRouteFunc; - + // Validate the entire registration before publishing any paths. + parent.__routeLock.lock() + try { + var existing = parent.__routes[aPort] || Object.create(null) + var reserved = parent.__reservedRoutes[aPort] || Object.create(null) + var exclusive = _$(reservedRoutes, "reservedRoutes").isArray().default([]) + exclusive.forEach(uri => { + if (!isString(uri) || !isFunction(aMapOfRoutes[uri]) || Object.prototype.hasOwnProperty.call(existing, uri)) + throw new Error("HTTP route reservation conflict at " + uri) + }) + Object.keys(aMapOfRoutes).forEach(uri => { + if (reserved[uri] && existing[uri] !== aMapOfRoutes[uri]) throw new Error("HTTP route is reserved at " + uri) + }) + parent.__routes[aPort] = Object.assign(Object.create(null), existing, aMapOfRoutes) + exclusive.forEach(uri => { reserved[uri] = true }) + parent.__reservedRoutes[aPort] = reserved + if (isDef(aDefaultRoute)) parent.__defaultRoutes[aPort] = aDefaultRoute + if (isDef(aPreRouteFunc)) parent.__preRoutes[aPort] = aPreRouteFunc + } finally { parent.__routeLock.unlock() } + const cnvt2string = m => { if (Object.keys(m).indexOf("bytes") >= 0) { m.bdata = String((java.lang.String(m.bytes, "UTF-8"))) @@ -4649,6 +4925,9 @@ OpenWrap.server.prototype.httpd = { req.uri = prefURI uri = prefURI } + // Reserved endpoints route on the path while retaining the raw query for protocol validation. + var routePath = uri.split("?")[0] + if (parent.__reservedRoutes[aPort][routePath]) uri = routePath if (isFunction(parent.__preRoutes[aPort])) parent.__preRoutes[aPort](req, aHTTPd); if (isFunction(parent.__routes[aPort][uri])) { return parent.__routes[aPort][uri](req, aHTTPd); @@ -4676,7 +4955,7 @@ OpenWrap.server.prototype.httpd = { } } catch(e) { if (ow.instrumentation && ow.instrumentation.isEnabled("http")) req.__openafInstrumentationError = true - printErr("HTTPd route error: " + af.toSLON(req) + " | " + e) + printErr("HTTPd route error while handling " + req.method) } } aHTTPd.add(aPath, function(req) { @@ -4720,11 +4999,13 @@ OpenWrap.server.prototype.httpd = { * */ stop: function(aHTTPd) { + var port = Number(aHTTPd.getPort()) aHTTPd.stop(); - delete this.__routes[Number(aHTTPd.getPort())] - delete this.__defaultRoutes[Number(aHTTPd.getPort())] - delete this.__preRoutes[Number(aHTTPd.getPort())] - delete this.__servers[Number(aHTTPd.getPort())] + delete this.__reservedRoutes[port] + delete this.__routes[port] + delete this.__defaultRoutes[port] + delete this.__preRoutes[port] + delete this.__servers[port] }, /** @@ -5135,9 +5416,13 @@ OpenWrap.server.prototype.httpd = { * requests carrying a modern (2026-07-28+) per-`request` _meta protocol version are validated against * `ow.server.mcp.versions.supported` (replying with an UnsupportedProtocolVersionError otherwise), results are * wrapped with the required resultType (plus ttlMs/cacheScope for methods listed in `opts`.listMethods, default - * ["tools/list","prompts/list","resources/list","resources/templates/list"]), and the negotiated version is - * echoed back via the MCP-Protocol-Version response header. Legacy requests (the default, and everything when - * modern is false/omitted) are handled exactly as before -- zero behavior change. + * `ow.server.mcp.cacheableMethods`, using `opts`.ttlMs (default 0) and `opts`.cacheScope (default "private")), + * the MCP-Protocol-Version, Mcp-Method and Mcp-Name request headers must mirror the body (otherwise HTTP 400 with + * a HeaderMismatch -32020 error, see `ow.server.mcp.validateHeaders`; tools/call `Mcp-Param-{Name}` headers are + * checked against the `x-mcp-header` annotations of `opts`.tools, an array of tool definitions or a function + * returning one, defaulting to the result of mapOfFunctions["tools/list"]), and the negotiated version is echoed + * back via the MCP-Protocol-Version response header. Legacy requests (the default, and everything when modern is + * false/omitted) are handled exactly as before -- zero behavior change. * ]]> * */ @@ -5146,8 +5431,10 @@ OpenWrap.server.prototype.httpd = { debugFn = _$(debugFn, "debugFn").isFunction().default(() => {}) opts = _$(opts, "opts").isMap().default({}) opts.modern = _$(opts.modern, "opts.modern").isBoolean().default(false) - opts.listMethods = _$(opts.listMethods, "opts.listMethods").isArray().default(["tools/list", "prompts/list", "resources/list", "resources/templates/list"]) + opts.listMethods = _$(opts.listMethods, "opts.listMethods").isArray().default(ow.server.mcp.cacheableMethods) opts.serverInfo = _$(opts.serverInfo, "opts.serverInfo").isMap().default(__) + opts.ttlMs = _$(opts.ttlMs, "opts.ttlMs").isNumber().default(0) + opts.cacheScope = _$(opts.cacheScope, "opts.cacheScope").isString().default("private") try { if (request.method !== "POST") { @@ -5205,9 +5492,21 @@ OpenWrap.server.prototype.httpd = { logFn("Invalid JSON-RPC request: " + request.method + " " + request.uri + " - Missing required client capabilities") return ow.server.httpd.reply(ow.server.mcp.invalidParamsError(reqObj.id, "Missing required params._meta[\"io.modelcontextprotocol/clientCapabilities\"]"), 400, "application/json", {}) } + // Request metadata headers must mirror the body (Streamable HTTP, 2026-07-28) + var _hdrError = ow.server.mcp.validateHeaders(request.header, reqObj, _reqVersion, ow.server.mcp.toolsOf(mapOfFunctions, opts)) + if (isDef(_hdrError)) { + logFn("Invalid JSON-RPC request: " + request.method + " " + request.uri + " - " + _hdrError.error.message) + return ow.server.httpd.reply(_hdrError, 400, "application/json", {}) + } _respHeaders["MCP-Protocol-Version"] = _reqVersion } - if (opts.modern && isDef(opts.workflows)) opts.workflows.bind(mapOfFunctions, reqObj, opts.workflowOwner) + // Let the HTTP adapter reject an operation before any dispatch or workflow mutation. + if (isFunction(opts.authorizeRequest)) { + var denied = opts.authorizeRequest(reqObj) + if (isDef(denied)) return denied + } + if (opts.modern && isDef(opts.workflows)) + opts.workflows.bind(mapOfFunctions, reqObj, opts.workflowOwner, opts.workflowIdentity, opts.resolveWorkflowTool) // JSON-RPC notification (no id): the Streamable HTTP transport requires a bare // 202 Accepted with no body - HTTP 404 is reserved for an expired session if (isUnDef(reqObj.id) || isNull(reqObj.id)) { @@ -5231,7 +5530,7 @@ OpenWrap.server.prototype.httpd = { } try { var result = isArray(reqObj.params) ? fn.apply(null, reqObj.params) : fn(reqObj.params) - result = ow.server.mcp.wrapResult(result, _era, { isList: opts.listMethods.indexOf(reqObj.method) >= 0, serverInfo: opts.serverInfo }) + result = ow.server.mcp.wrapResult(result, _era, { isList: opts.listMethods.indexOf(reqObj.method) >= 0, serverInfo: opts.serverInfo, ttlMs: opts.ttlMs, cacheScope: opts.cacheScope }) debugFn("JSON-RPC request result: " + stringify(result)); return ow.server.httpd.reply({ jsonrpc: "2.0", @@ -5280,9 +5579,10 @@ OpenWrap.server.prototype.httpd = { * }) * ``` * - * `opts` is an optional map: { modern: false, listMethods: [...] } -- see `ow.server.httpd.replyJSONRPC` for the - * meaning of both; the same opt-in 2026-07-28 modern-era handling (version validation, resultType/ttlMs/ - * cacheScope wrapping, MCP-Protocol-Version response header) applies here, with legacy behavior (default) + * `opts` is an optional map: { modern: false, listMethods: [...], ttlMs: 0, cacheScope: "private", tools: __ } -- see + * `ow.server.httpd.replyJSONRPC` for their meaning; the same opt-in 2026-07-28 modern-era handling (version and + * request header validation, resultType/ttlMs/cacheScope wrapping, MCP-Protocol-Version response header) + * applies here, with legacy behavior (default) * left fully unchanged. * ]]> * @@ -5292,8 +5592,10 @@ OpenWrap.server.prototype.httpd = { debugFn = _$(debugFn, "debugFn").isFunction().default(function() {}) opts = _$(opts, "opts").isMap().default({}) opts.modern = _$(opts.modern, "opts.modern").isBoolean().default(false) - opts.listMethods = _$(opts.listMethods, "opts.listMethods").isArray().default(["tools/list", "prompts/list", "resources/list", "resources/templates/list"]) + opts.listMethods = _$(opts.listMethods, "opts.listMethods").isArray().default(ow.server.mcp.cacheableMethods) opts.serverInfo = _$(opts.serverInfo, "opts.serverInfo").isMap().default(__) + opts.ttlMs = _$(opts.ttlMs, "opts.ttlMs").isNumber().default(0) + opts.cacheScope = _$(opts.cacheScope, "opts.cacheScope").isString().default("private") try { debugFn("Processing MCP request: " + stringify(request)) if (request.method !== "POST") { @@ -5351,6 +5653,12 @@ OpenWrap.server.prototype.httpd = { logFn("Invalid MCP request: " + request.method + " " + request.uri + " - Missing required client capabilities") return ow.server.httpd.reply(ow.server.mcp.invalidParamsError(reqObj.id, "Missing required params._meta[\"io.modelcontextprotocol/clientCapabilities\"]"), 400, "application/json", {}) } + // Request metadata headers must mirror the body (Streamable HTTP, 2026-07-28) + var _hdrError = ow.server.mcp.validateHeaders(request.header, reqObj, _reqVersion, ow.server.mcp.toolsOf(mapOfFunctions, opts)) + if (isDef(_hdrError)) { + logFn("Invalid MCP request: " + request.method + " " + request.uri + " - " + _hdrError.error.message) + return ow.server.httpd.reply(_hdrError, 400, "application/json", {}) + } _respHeaders["MCP-Protocol-Version"] = _reqVersion } var isNotification = isUnDef(reqObj.id) || isNull(reqObj.id) @@ -5366,7 +5674,7 @@ OpenWrap.server.prototype.httpd = { } try { var result = isArray(reqObj.params) ? fn.apply(null, reqObj.params) : fn(reqObj.params) - result = ow.server.mcp.wrapResult(result, _era, { isList: opts.listMethods.indexOf(reqObj.method) >= 0, serverInfo: opts.serverInfo }) + result = ow.server.mcp.wrapResult(result, _era, { isList: opts.listMethods.indexOf(reqObj.method) >= 0, serverInfo: opts.serverInfo, ttlMs: opts.ttlMs, cacheScope: opts.cacheScope }) debugFn("MCP request result: " + stringify(result)) if (isNotification) return ow.server.httpd.reply("", 204, "text/plain", _respHeaders) return ow.server.httpd.reply({ @@ -5980,6 +6288,588 @@ OpenWrap.server.prototype.jwt = { } } +// Fixed-algorithm signature verification for resource servers. Keep legacy jwt.verify compatible. +OpenWrap.server.prototype.jwt.__publicVerifier = function(key, algorithm, clockSkew) { + var builder = Packages.io.jsonwebtoken.Jwts.parser().verifyWith(key).clockSkewSeconds(clockSkew) + builder.sig().clear().add(Packages.io.jsonwebtoken.Jwts.SIG.get().forKey(algorithm)).and() + var parser = builder.build() + return token => parser.parseSignedClaims(token) +} + +/** + * + * ow.server.httpd.oauthResourceServer(options) : Map + * + * + */ +OpenWrap.server.prototype.httpd.oauthResourceServer = function(options) { + if (!isMap(options)) throw new Error("OAuth resource server requires an options map") + + // Read only recognized configuration. Never include a value in a configuration error. + var own = (map, key) => Object.prototype.hasOwnProperty.call(map, key) + var fail = name => { throw new Error("Invalid OAuth resource server option: " + name) } + var allowed = ("issuer resource audience validation discovery metadataURL jwksURI introspectionURL " + + "discoveredEndpointOrigins scopesSupported requiredScopes algorithms clockSkew jwtProfile scopeClaim claimAllowlist " + + "accessTokenClaim accessTokenValue allowLoopbackHTTP timeoutMs maxResponseBytes maxTokenBytes jwksCacheTTL " + + "maxJwksKeys refreshCooldownMs introspectionCacheTTL introspectionCacheMax maxIntrospectionRequests " + + "introspectionAuthMethod clientId clientIdEnv clientSecretEnv clientSecretSec senderConstraint").split(" ") + Object.keys(options).forEach(name => { if (allowed.indexOf(name) < 0) fail("unknown setting") }) + var value = (name, fallback) => own(options, name) ? options[name] : fallback + var string = v => isString(v) && v.length > 0 && v.length <= 2048 && !/[\x00-\x1f\x7f]/.test(v) + var setting = (name, fallback, predicate) => { + var v = value(name, fallback) + if (!predicate(v)) fail(name) + return v + } + var choice = (name, fallback, choices) => setting(name, fallback, v => choices.indexOf(v) >= 0) + var integer = (name, fallback, minimum, maximum) => setting(name, fallback, + v => Number.isInteger(v) && v >= minimum && v <= maximum) + var list = (v, valid) => isArray(v) && v.length <= 128 && v.every(valid) + var unique = values => values.filter((x, i) => values.indexOf(x) === i) + var scopeToken = v => isString(v) && v.length > 0 && v.length <= 128 && !/[^\x21\x23-\x5b\x5d-\x7e]/.test(v) + var scopeList = (v, label) => { + if (isString(v)) v = v.split(" ").filter(s => s.length > 0) + if (!list(v, scopeToken) || v.join(" ").length > 4096) fail(label) + return unique(v) + } + var claimName = v => string(v) && ["__proto__", "constructor", "prototype"].indexOf(v) < 0 + var loopback = setting("allowLoopbackHTTP", false, isBoolean) + var parseURL = (url, name, allowQuery) => { + if (!string(url) || /[^\x21-\x7e]|["\\]/.test(url)) fail(name) + var uri + try { uri = new java.net.URI(url) } catch (e) { fail(name) } + var host = uri.getHost(), scheme = String(uri.getScheme()).toLowerCase() + if (host === null || uri.getRawUserInfo() !== null || uri.getRawFragment() !== null || + (!allowQuery && uri.getRawQuery() !== null) || uri.getPort() > 65535 || + (scheme !== "https" && !(loopback && scheme === "http" && + ["127.0.0.1", "localhost", "[::1]"].indexOf(String(host).toLowerCase()) >= 0))) fail(name) + return uri + } + var origin = uri => { + var scheme = String(uri.getScheme()).toLowerCase(), port = uri.getPort() + return scheme + "://" + String(uri.getHost()).toLowerCase() + + (port < 0 || port === (scheme === "https" ? 443 : 80) ? "" : ":" + port) + } + var authority = uri => String(uri.getScheme()) + "://" + String(uri.getRawAuthority()) + var issuer = value("issuer"), resource = value("resource") + var issuerURI = parseURL(issuer, "issuer", false), resourceURI = parseURL(resource, "resource", true) + var metadataPath = "/.well-known/oauth-protected-resource" + String(resourceURI.getRawPath()).replace(/\/$/, "") + var metadataURL = authority(resourceURI) + metadataPath + + (resourceURI.getRawQuery() === null ? "" : "?" + String(resourceURI.getRawQuery())) + var audience = setting("audience", resource, string) + var validation = choice("validation", "jwt", ["jwt", "introspection"]) + var jwtMode = validation === "jwt", discovery = setting("discovery", true, isBoolean) + var explicitMetadata = value("metadataURL") + var endpointOption = jwtMode ? "jwksURI" : "introspectionURL" + var endpoint = value(endpointOption) + if (own(options, jwtMode ? "introspectionURL" : "jwksURI")) fail(jwtMode ? "introspectionURL" : "jwksURI") + if (own(options, endpointOption)) parseURL(endpoint, endpointOption, true) + if (own(options, "metadataURL")) { + if (!discovery || isDef(endpoint)) fail("metadataURL") + parseURL(explicitMetadata, "metadataURL", true) + } + if (!discovery && isUnDef(endpoint)) fail(endpointOption) + var trustedOrigins = [origin(issuerURI)] + setting("discoveredEndpointOrigins", [], v => list(v, string)).forEach(url => { + var uri = parseURL(url, "discoveredEndpointOrigins", false) + if (["", "/"].indexOf(String(uri.getRawPath())) < 0) fail("discoveredEndpointOrigins") + trustedOrigins.push(origin(uri)) + }) + var supportedScopes = scopeList(value("scopesSupported", []), "scopesSupported") + var requiredScopes = scopeList(value("requiredScopes", []), "requiredScopes") + var algorithms = unique(setting("algorithms", ["RS256"], v => list(v, a => + ["RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512"].indexOf(a) >= 0) && v.length)) + var profile = choice("jwtProfile", "rfc9068", ["rfc9068", "keycloak", "typed", "entra-v2-delegated", "entra-v2-app"]) + var entra = profile.startsWith("entra-v2-"), entraApp = profile === "entra-v2-app" + var guid = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i + var tenant, defaultScopeClaim = "scope" + if (entra) { + var path = String(issuerURI.getRawPath()).split("/") + if (path.length !== 3 || !guid.test(path[1]) || path[2] !== "v2.0") fail("tenant-specific Entra v2 issuer") + if (!guid.test(audience) || algorithms.length !== 1 || algorithms[0] !== "RS256") fail("Entra API audience or algorithm") + tenant = path[1] + defaultScopeClaim = entraApp ? "roles" : "scp" + } + var scopeClaim = setting("scopeClaim", defaultScopeClaim, claimName) + if (entra && scopeClaim !== defaultScopeClaim) fail("scopeClaim") + if (!jwtMode && ["jwtProfile", "algorithms"].some(name => own(options, name))) fail("JWT options on introspection instance") + if (jwtMode && ["clientId", "clientIdEnv", "clientSecretEnv", "clientSecretSec", "introspectionAuthMethod", + "introspectionCacheTTL", "introspectionCacheMax", "maxIntrospectionRequests"].some(name => own(options, name))) + fail("introspection options on JWT instance") + var tokenClaim, tokenValue + if (jwtMode && profile === "typed") { + tokenClaim = setting("accessTokenClaim", __, claimName) + tokenValue = setting("accessTokenValue", __, string) + if (["iss", "aud", "sub", "scope", "client_id", "azp", "iat", "jti", scopeClaim].indexOf(tokenClaim) >= 0) fail("accessTokenClaim") + } else if (own(options, "accessTokenClaim") || own(options, "accessTokenValue")) { + fail("accessTokenClaim") + } + var claimAllowlist = unique(setting("claimAllowlist", [], v => list(v, claimName))) + var skew = integer("clockSkew", 30, 0, 300) + var timeout = integer("timeoutMs", 3000, 50, 30000) + var responseLimit = integer("maxResponseBytes", 262144, 1024, 4194304) + var tokenLimit = integer("maxTokenBytes", 16384, 256, 65536) + var keyTTL = integer("jwksCacheTTL", 300000, 100, 86400000) + var maxKeys = integer("maxJwksKeys", 64, 1, 256) + var cooldown = integer("refreshCooldownMs", 3000, 100, 60000) + var introspectionTTL = integer("introspectionCacheTTL", 0, 0, 3600000) + var maxEntries = integer("introspectionCacheMax", 256, 1, 10000) + var maxConcurrent = integer("maxIntrospectionRequests", 16, 1, 128) + var authMethod = choice("introspectionAuthMethod", "client_secret_basic", ["client_secret_basic", "client_secret_post"]) + + // Resolve introspection credentials only from trusted local configuration. + var envName = v => isString(v) && /^[A-Za-z_]/.test(v) && !/[^A-Za-z0-9_]/.test(v) + var clientId, clientSecret + if (!jwtMode) { + if (own(options, "clientId") && own(options, "clientIdEnv")) fail("clientId") + if (own(options, "clientSecretEnv") === own(options, "clientSecretSec")) fail("clientSecretEnv or clientSecretSec") + clientId = own(options, "clientIdEnv") ? getEnv(setting("clientIdEnv", __, envName)) : value("clientId") + if (!string(clientId)) fail("clientId or clientIdEnv") + if (own(options, "clientSecretEnv")) { + clientSecret = getEnv(setting("clientSecretEnv", __, envName)) + } else { + var ref = value("clientSecretSec") + if (!isMap(ref) || !claimName(ref.key) || !isString(ref.repo) || !/^[A-Za-z0-9_-]+$/.test(ref.repo) || + ref.repo === "system" || Object.keys(ref).some(k => ["key", "repo", "bucket", "lockSecret", "mainSecret", "file"].indexOf(k) < 0)) fail("clientSecretSec") + try { + var secrets = ow.server.httpd.__oauth2SecTokenStore(ref, "oauth-resource") + clientSecret = secrets.withLock(ref.key, () => secrets.load(ref.key)) + } catch (e) { fail("clientSecretSec") } + } + if (!string(clientSecret)) fail("introspection client secret reference") + } + + // Set a strict JSON policy and a private, bounded HTTP transport. + var jackson = Packages.com.fasterxml.jackson + var jsonFactory = jackson.core.JsonFactory.builder().streamReadConstraints( + jackson.core.StreamReadConstraints.builder().maxNestingDepth(32).maxNumberLength(32) + .maxStringLength(Math.max(tokenLimit, responseLimit)).build()) + .enable(jackson.core.StreamReadFeature.STRICT_DUPLICATE_DETECTION).build() + var mapper = new jackson.databind.ObjectMapper(jsonFactory).enable(jackson.databind.DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + var jsonObject = bytes => { + var utf8 = java.nio.charset.StandardCharsets.UTF_8.newDecoder() + var node = mapper.readTree(String(utf8.decode(java.nio.ByteBuffer.wrap(bytes)))) + if (node === null || !node.isObject()) throw new Error("Expected a JSON object") + return JSON.parse(String(node)) + } + var base64url = java.util.Base64.getUrlDecoder() + var unit = java.util.concurrent.TimeUnit.MILLISECONDS + var http = new Packages.okhttp3.OkHttpClient.Builder().proxy(java.net.Proxy.NO_PROXY) + .followRedirects(false).followSslRedirects(false).retryOnConnectionFailure(false) + .connectTimeout(timeout, unit).readTimeout(timeout, unit).callTimeout(timeout, unit).build() + var ms = () => Number(java.lang.System.nanoTime()) / 1000000 + var closed = new java.util.concurrent.atomic.AtomicBoolean(false) + var counters = {} + ;["authenticated", "rejected", "denied", "jwksRefreshes", "jwksFailures", "introspectionRequests", + "introspectionFailures", "introspectionMs", "cacheHits", "cacheMisses", "cacheEvictions"].forEach(name => { + counters[name] = new java.util.concurrent.atomic.LongAdder() + }) + var count = name => counters[name].increment() + var stats = () => { + var result = {} + Object.keys(counters).forEach(name => { result[name] = Number(counters[name].sum()) }) + return result + } + var fetch = (url, form, basic) => { + if (closed.get()) throw new Error("OAuth resource server is closed") + var request = new Packages.okhttp3.Request.Builder().url(url).header("Accept", "application/json") + if (isDef(form)) { + request.post(form) + if (isDef(basic)) request.header("Authorization", basic) + } + var response = http.newCall(request.build()).execute() + try { + var status = response.code() + if (status !== 200) return { status: status } + var body = response.body() + var source = body.source() + if (body.contentLength() > responseLimit || source.request(responseLimit + 1)) throw new Error("OAuth response exceeds limit") + return { status: status, body: jsonObject(source.readByteArray()) } + } finally { response.close() } + } + var discover = () => { + if (isDef(endpoint)) return endpoint + var path = String(issuerURI.getRawPath()).replace(/\/$/, ""), base = authority(issuerURI) + var urls = isDef(explicitMetadata) ? [explicitMetadata] : unique([ + base + "/.well-known/oauth-authorization-server" + path, + base + "/.well-known/openid-configuration" + path, + base + path + "/.well-known/openid-configuration" + ]) + for (var i = 0; i < urls.length; i++) { + var response = fetch(urls[i]) + if (response.status === 404 || response.status === 405) continue + if (response.status !== 200 || response.body.issuer !== issuer) throw new Error("Invalid issuer metadata") + var url = response.body[jwtMode ? "jwks_uri" : "introspection_endpoint"] + if (trustedOrigins.indexOf(origin(parseURL(url, "discovered endpoint", true))) < 0) throw new Error("Untrusted discovered endpoint") + return url + } + throw new Error("OAuth issuer metadata not found") + } + + // Cache only public keys tied to this instance's issuer and validation policy. + var lock = new java.util.concurrent.locks.ReentrantLock() + var keyState = new java.util.concurrent.atomic.AtomicReference() + var keyRetryAt = -Infinity, keyFailure = false + var keyId = (kid, alg) => JSON.stringify([kid, alg]) + var jwkParser = Packages.io.jsonwebtoken.security.Jwks.parser().build() + var curves = { ES256: "P-256", ES384: "P-384", ES512: "P-521" } + var refreshKeys = () => { + var response = fetch(discover()) + if (response.status !== 200 || !isArray(response.body.keys) || response.body.keys.length > maxKeys) throw new Error("Invalid JWKS") + var keys = Object.create(null), fingerprints = Object.create(null) + response.body.keys.forEach(jwk => { + if (!isMap(jwk) || !string(jwk.kid) || jwk.kid.length > 256 || ["d", "p", "q", "dp", "dq", "qi", "oth"].some(name => own(jwk, name)) || + (own(jwk, "use") && jwk.use !== "sig") || + (own(jwk, "key_ops") && (!isArray(jwk.key_ops) || jwk.key_ops.length !== 1 || jwk.key_ops[0] !== "verify"))) return + // Entra JWKS can contain keys restricted to a tenant. Substitute only the configured tenant. + if (entra && (!isString(jwk.issuer) || jwk.issuer.replace(/\{tenantid\}/gi, tenant) !== issuer)) return + var eligible = algorithms.filter(alg => (!own(jwk, "alg") || jwk.alg === alg) && + (jwk.kty === "RSA" && /^[RP]S/.test(alg) || jwk.kty === "EC" && jwk.crv === curves[alg] && /^ES/.test(alg))) + if (eligible.length !== 1) return + var alg = eligible[0], id = keyId(jwk.kid, alg), publicJwk + if (own(keys, id)) throw new Error("Ambiguous JWKS key ID") + if (jwk.kty === "RSA") { + if (!isString(jwk.n) || !/^[A-Za-z0-9_-]{342,1366}$/.test(jwk.n) || + !isString(jwk.e) || !/^[A-Za-z0-9_-]{1,8}$/.test(jwk.e)) throw new Error("Invalid RSA JWK") + publicJwk = { kty: "RSA", n: jwk.n, e: jwk.e } + } else { + if (!isString(jwk.x) || !isString(jwk.y) || !/^[A-Za-z0-9_-]{43,88}$/.test(jwk.x) || + !/^[A-Za-z0-9_-]{43,88}$/.test(jwk.y)) throw new Error("Invalid EC JWK") + publicJwk = { kty: "EC", crv: jwk.crv, x: jwk.x, y: jwk.y } + } + var key = jwkParser.parse(JSON.stringify(publicJwk)).toKey() + if (jwk.kty === "RSA" && (key.getModulus().bitLength() < 2048 || key.getModulus().bitLength() > 8192)) throw new Error("Invalid RSA key size") + var fingerprint = String(java.util.Base64.getEncoder().encodeToString(key.getEncoded())) + if (own(fingerprints, fingerprint) && fingerprints[fingerprint] !== alg) throw new Error("JWKS key has conflicting algorithms") + fingerprints[fingerprint] = alg + keys[id] = ow.server.jwt.__publicVerifier(key, alg, skew) + }) + return { keys: keys, until: ms() + keyTTL } + } + var unavailable = {} + var verifierFor = id => { + var current = keyState.get() + if (current !== null && current.until > ms() && own(current.keys, id)) return current.keys[id] + if (!lock.tryLock(timeout, unit)) throw unavailable + try { + if (closed.get()) throw unavailable + current = keyState.get() + var t = ms(), fresh = current !== null && current.until > t + if (fresh && own(current.keys, id)) return current.keys[id] + if (t < keyRetryAt && (fresh || keyFailure)) { + if (keyFailure) throw unavailable + return + } + count("jwksRefreshes") + keyFailure = true + try { + current = refreshKeys() + keyState.set(current) + keyFailure = false + return current.keys[id] + } finally { + if (keyFailure) count("jwksFailures") + keyRetryAt = ms() + cooldown + } + } finally { lock.unlock() } + } + + // Keep the validated token binding internal until the request proof succeeds. + var constraint = value("senderConstraint", __), proofPolicy, acceptsMtls = false + if (isDef(constraint)) { + if (!isMap(constraint) || ["required", "optional"].indexOf(constraint.mode) < 0 || + !list(constraint.methods, method => ["dpop", "mtls"].indexOf(method) >= 0) || constraint.methods.length === 0) fail("senderConstraint") + acceptsMtls = constraint.methods.indexOf("mtls") >= 0 + if (constraint.methods.indexOf("dpop") >= 0) { + proofPolicy = ow.server.oauth.__proofVerifier(Object.assign({}, constraint, { methods: ["dpop"] }), resource, loopback) + } + } + var confirmation = Symbol("OAuth confirmation") + + // Validate time and identity for both modes before creating an authenticated context. + var contextMarker = Symbol("OAuth resource context") + var contextSeal = {} + var numericDate = v => isNumber(v) && isFinite(v) && v >= 0 && v <= 8640000000000 + var safeClaim = v => isString(v) || isBoolean(v) || (isNumber(v) && isFinite(v)) + var identity = claims => { + var time = now(), leeway = jwtMode ? skew * 1000 : 0 + var audiences = isString(claims.aud) ? [claims.aud] : claims.aud + if ((!own(claims, "iss") && jwtMode || own(claims, "iss") && claims.iss !== issuer) || + !string(claims.sub) || !list(audiences, string) || audiences.indexOf(audience) < 0 || + !numericDate(claims.exp) || claims.exp * 1000 + leeway <= time || + (own(claims, "nbf") && (!numericDate(claims.nbf) || claims.nbf * 1000 - leeway > time)) || + (own(claims, "iat") && (!numericDate(claims.iat) || claims.iat * 1000 - leeway > time))) return + var binding + if (own(claims, "cnf")) { + if (!isMap(claims.cnf) || Object.keys(claims.cnf).length !== 1) return + var method = own(claims.cnf, "jkt") && isDef(proofPolicy) ? "dpop" : + own(claims.cnf, "x5t#S256") && acceptsMtls ? "mtls" : __ + var digest = claims.cnf[method === "dpop" ? "jkt" : "x5t#S256"] + if (isUnDef(method) || !isString(digest) || !/^[\w-]{43}$/.test(digest)) return + binding = { type: method, thumbprint: digest } + } + var scopes + try { scopes = scopeList(own(claims, scopeClaim) ? claims[scopeClaim] : [], "token scopes") } + catch (e) { return } + var extra = {} + claimAllowlist.forEach(name => { + if (!own(claims, name)) return + var v = claims[name] + if (safeClaim(v)) extra[name] = v + else if (list(v, safeClaim)) extra[name] = Object.freeze(v.slice()) + }) + var result = { authenticated: true, method: "oauth2", issuer: issuer, subject: claims.sub, + principal: "oauth2:" + sha256(JSON.stringify([issuer, claims.sub])), audience: Object.freeze(audiences.slice()), + scopes: Object.freeze(scopes), expiresAt: claims.exp * 1000, claims: Object.freeze(extra) } + Object.defineProperty(result, confirmation, { value: binding }) + return Object.freeze(result) + } + var jwt = token => { + var parts = token.split(".") + if (parts.length !== 3 || parts.some(p => !/^[A-Za-z0-9_-]+$/.test(p)) || parts[0].length > 4096) return + var header, claims + try { + header = jsonObject(base64url.decode(parts[0])) + if (algorithms.indexOf(header.alg) < 0 || !string(header.kid) || header.kid.length > 256 || + ["crit", "zip", "b64", "jwk", "jku", "x5u", "x5c"].some(name => own(header, name))) return + claims = jsonObject(base64url.decode(parts[1])) + } catch (e) { return } + var type = isString(header.typ) ? header.typ.toLowerCase() : "" + var typed = type === "at+jwt" || type === "application/at+jwt" + if (profile === "rfc9068" && (!typed || !numericDate(claims.iat) || !string(claims.client_id) || !string(claims.jti))) return + if (profile === "keycloak" && (!(typed || type === "jwt") || claims.typ !== "Bearer")) return + if (profile === "typed" && (!(typed || type === "jwt") || !own(claims, tokenClaim) || claims[tokenClaim] !== tokenValue)) return + + if (entra && (type !== "jwt" || claims.ver !== "2.0" || claims.tid !== tenant || + !string(claims.azp) || !guid.test(claims.azp) || !isString(claims.aud) || + (entraApp ? claims.idtyp !== "app" || own(claims, "scp") || !isArray(claims.roles) || claims.roles.length === 0 : + claims.idtyp === "app" || !isString(claims.scp) || claims.scp.trim().length === 0))) return + + // Reject invalid claims before an unknown key can cause any network activity. + if (claims.iss !== issuer || !numericDate(claims.exp) || claims.exp * 1000 + skew * 1000 <= now()) return + var audiences = isString(claims.aud) ? [claims.aud] : claims.aud + if (!list(audiences, string) || audiences.indexOf(audience) < 0) return + var verify = verifierFor(keyId(header.kid, header.alg)) + if (isUnDef(verify)) return + try { verify(token) } catch (e) { return } + return identity(claims) + } + + // Bound introspection concurrency and cache only positive results, keyed by a token digest. + var slots = new java.util.concurrent.Semaphore(maxConcurrent) + var cache = new java.util.LinkedHashMap(16, 0.75, true) + var cacheLock = new java.util.concurrent.locks.ReentrantLock() + var generation = new java.util.concurrent.atomic.AtomicLong() + var cacheAccess = fn => { + cacheLock.lock() + try { return fn() } finally { cacheLock.unlock() } + } + var discoveredIntrospection, discoveryRetry = -Infinity + var introspectionEndpoint = () => { + if (isDef(endpoint)) return endpoint + if (!lock.tryLock(timeout, unit)) throw unavailable + try { + if (closed.get()) throw unavailable + if (isDef(discoveredIntrospection) && discoveredIntrospection.until > ms()) return discoveredIntrospection.url + if (ms() < discoveryRetry) throw unavailable + try { + var url = discover() + discoveredIntrospection = { url: url, until: ms() + keyTTL } + return url + } catch (e) { + discoveryRetry = ms() + cooldown + throw unavailable + } + } finally { lock.unlock() } + } + var formEncode = v => String(java.net.URLEncoder.encode(v, "UTF-8")) + var introspect = token => { + var key, startedGeneration = Number(generation.get()) + if (introspectionTTL > 0) { + key = sha256(token) + var hit = cacheAccess(() => { + var entry = cache.get(key) + if (entry === null) return + if (entry.until > ms() && entry.context.expiresAt > now()) return entry.context + cache.remove(key) + count("cacheEvictions") + }) + if (isDef(hit)) { + count("cacheHits") + return hit + } + count("cacheMisses") + } + if (!slots.tryAcquire()) throw unavailable + var started = ms(), result + try { + var url = introspectionEndpoint() + var form = new Packages.okhttp3.FormBody.Builder().add("token", token).add("token_type_hint", "access_token") + var basic + if (authMethod === "client_secret_basic") { + var credentials = formEncode(clientId) + ":" + formEncode(clientSecret) + basic = "Basic " + String(java.util.Base64.getEncoder().encodeToString(af.fromString2Bytes(credentials))) + } else { + form.add("client_id", clientId).add("client_secret", clientSecret) + } + count("introspectionRequests") + var response = fetch(url, form.build(), basic) + if (response.status !== 200 || !isBoolean(response.body.active)) throw unavailable + if (!response.body.active || (own(response.body, "token_type") && + (!isString(response.body.token_type) || + (response.body.token_type.toLowerCase() !== "bearer" && + !(isDef(proofPolicy) && response.body.token_type.toLowerCase() === "dpop" && own(response.body, "cnf")))))) return + result = identity(response.body) + } catch (e) { + count("introspectionFailures") + throw unavailable + } finally { + counters.introspectionMs.add(Math.round(ms() - started)) + slots.release() + } + if (isDef(result) && introspectionTTL > 0 && result.expiresAt > now()) cacheAccess(() => { + if (closed.get() || Number(generation.get()) !== startedGeneration) return + cache.put(key, { context: result, until: started + introspectionTTL }) + if (cache.size() > maxEntries) { + var iterator = cache.keySet().iterator() + iterator.next() + iterator.remove() + count("cacheEvictions") + } + }) + return result + } + + // Enforce header-only bearer usage and return HTTP challenges without diagnostic secrets. + var reject = error => { + count("rejected") + return { ok: false, error: error } + } + var authenticate = request => { + if (closed.get()) return reject("unavailable") + var headers = isMap(request) && isMap(request.header) ? request.header : {} + var names = Object.keys(headers).filter(name => name.toLowerCase() === "authorization") + if (isMap(request) && isMap(request.params) && own(request.params, "access_token")) return reject("invalid_request") + if (names.length === 0) return reject("missing") + if (names.length !== 1) return reject("invalid_request") + var header = headers[names[0]] + var validHeader = isString(header) && header.length <= tokenLimit + 64 && !/[\x00-\x1f\x7f]/.test(header) + var token = validHeader ? /^(Bearer|DPoP) +([A-Za-z0-9._~+\/-]+=*)$/i.exec(header) : null + if (token === null) { + // A well-formed credential for another scheme is equivalent to a missing bearer credential. + var scheme = validHeader && /^([A-Za-z][A-Za-z0-9+.-]*) [^,]+$/.exec(header) + return reject(scheme && scheme[1].toLowerCase() !== "bearer" ? "missing" : "invalid_request") + } + var dpop = token[1].toLowerCase() === "dpop" + if (dpop && isUnDef(proofPolicy)) return reject("missing") + if (token[2].length > tokenLimit) return reject("invalid_token") + try { + var context = jwtMode ? jwt(token[2]) : introspect(token[2]) + if (closed.get()) return reject("unavailable") + if (isUnDef(context)) return reject("invalid_token") + var binding = context[confirmation], result = Object.assign({}, context) + if (isUnDef(binding)) { + if (dpop || (isDef(constraint) && constraint.mode === "required")) return reject("invalid_token") + } else if (binding.type === "dpop") { + if (!dpop) return reject("invalid_token") + var proofs = Object.keys(headers).filter(name => name.toLowerCase() === "dpop") + if (proofs.length !== 1) return reject("invalid_dpop_proof") + var proof = proofPolicy.validate(request, headers[proofs[0]], binding.thumbprint, token[2]) + if (isDef(proof.error)) return reject(proof.error) + } else { + if (dpop || String(Packages.openaf.plugins.HTTPServer.oauthPeerThumbprint(request)) !== binding.thumbprint) { + return reject("invalid_token") + } + } + if (isDef(binding)) result.senderConstraint = Object.freeze(binding) + Object.defineProperty(result, contextMarker, { value: contextSeal }) + count("authenticated") + return { ok: true, context: Object.freeze(result) } + } catch (e) { return reject("unavailable") } + } + var authorize = (context, scopes) => { + if (!context || context[contextMarker] !== contextSeal || context.expiresAt + (jwtMode ? skew * 1000 : 0) <= now()) + return { ok: false, error: "invalid_token" } + if (closed.get()) return { ok: false, error: "unavailable" } + var required = unique(requiredScopes.concat(scopeList(isUnDef(scopes) ? [] : scopes, "requiredScopes"))) + if (required.every(scope => context.scopes.indexOf(scope) >= 0)) return { ok: true } + count("denied") + return { ok: false, error: "insufficient_scope" } + } + var challenge = (error, scopes) => { + var headers = { "Cache-Control": "no-store" } + var status = { missing: 401, invalid_request: 400, invalid_token: 401, insufficient_scope: 403, invalid_dpop_proof: 401, use_dpop_nonce: 401, unavailable: 503 }[error] + if (!isNumber(status)) throw new Error("Unknown OAuth resource server failure") + if (status !== 503) { + var required = unique(requiredScopes.concat(scopeList(isUnDef(scopes) ? [] : scopes, "requiredScopes"))) + var params = ['resource_metadata="' + metadataURL + '"'] + if (error !== "missing") params.unshift('error="' + error + '"') + if (required.length > 0) params.push('scope="' + required.join(" ") + '"') + var proofChallenge = isDef(proofPolicy) && (proofPolicy.required || error === "invalid_dpop_proof" || error === "use_dpop_nonce") + headers["WWW-Authenticate"] = (proofChallenge ? "DPoP " : "Bearer ") + params.join(", ") + if (proofChallenge && isDef(proofPolicy.nonce)) headers["DPoP-Nonce"] = proofPolicy.nonce + } + return { data: "", mimetype: "text/plain", status: status, header: headers } + } + var metadata = () => { + var result = { resource: resource, authorization_servers: [issuer], bearer_methods_supported: ["header"] } + if (isDef(proofPolicy)) result.dpop_signing_alg_values_supported = ["ES256"] + if (supportedScopes.length > 0) result.scopes_supported = supportedScopes.slice() + return result + } + var invalidate = () => { + lock.lock() + try { + keyState.set(null) + keyRetryAt = discoveryRetry = -Infinity + keyFailure = false + discoveredIntrospection = __ + cacheAccess(() => { + generation.incrementAndGet() + cache.clear() + }) + } finally { lock.unlock() } + } + return { + authenticate: authenticate, authorize: authorize, challenge: challenge, metadata: metadata, + metadataURI: () => metadataURL, metadataPath: () => metadataPath, stats: stats, invalidate: invalidate, + normalizeScopes: scopes => scopeList(scopes, "scopes"), + metadataHandler: req => req.method === "GET" || req.method === "HEAD" + ? { data: req.method === "GET" ? JSON.stringify(metadata()) : "", mimetype: "application/json", status: 200, header: {} } + : { data: "", mimetype: "text/plain", status: 405, header: { Allow: "GET, HEAD" } }, + wrap: (handler, scopes) => { + if (!isFunction(handler)) throw new Error("OAuth resource server handler must be a function") + var requestedScopes = scopeList(isUnDef(scopes) ? [] : scopes, "requiredScopes") + return (request, server) => { + var auth = authenticate(request) + if (!auth.ok) return challenge(auth.error, requestedScopes) + var access = authorize(auth.context, requestedScopes) + if (!access.ok) return challenge(access.error, requestedScopes) + var headers = Object.assign({}, request.header) + Object.keys(headers).forEach(key => { + if (["authorization", "proxy-authorization", "dpop"].indexOf(key.toLowerCase()) >= 0) delete headers[key] + }) + return handler(Object.assign({}, request, { header: headers }), server, auth.context) + } + }, + close: () => { + if (!closed.compareAndSet(false, true)) return + http.dispatcher().cancelAll() + http.connectionPool().evictAll() + invalidate() + } + } +} + OpenWrap.server.prototype.httpd.browse = { /** * diff --git a/js/owrap.server.oauth.as.js b/js/owrap.server.oauth.as.js new file mode 100644 index 00000000..89720437 --- /dev/null +++ b/js/owrap.server.oauth.as.js @@ -0,0 +1,700 @@ +(function() { + var jose = Packages.io.jsonwebtoken + var unit = java.util.concurrent.TimeUnit.MILLISECONDS + var secretBytes = value => af.fromString2Bytes(value) + var digest = value => java.security.MessageDigest.getInstance("SHA-256").digest(secretBytes(value)) + var random = new java.security.SecureRandom() + var encode = java.util.Base64.getUrlEncoder().withoutPadding() + var own = (map, key) => Object.prototype.hasOwnProperty.call(map, key) + var names = value => isString(value) && /^[A-Za-z0-9._~-]{1,128}$/.test(value) + var identifier = value => isString(value) && value.length > 0 && value.length <= 2048 && !/[\x00-\x20\x7f]/.test(value) + var invalid = name => { throw new Error("Invalid OAuth issuer configuration: " + name) } + var secret = () => { + var bytes = java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, 32) + random.nextBytes(bytes) + return String(encode.encodeToString(bytes)) + } + var scopeSet = value => { + if (isString(value)) value = value.length ? value.split(" ") : [] + if (!isArray(value) || value.length > 64 || !value.every(s => isString(s) && /^[\x21\x23-\x5b\x5d-\x7e]{1,128}$/.test(s))) return + return Array.from(new Set(value)) + } + + // Persist access-token digests and their validated claims with a single writer. + function tokenStore(configuration, issuer) { + if (isUnDef(configuration) || configuration.type === "memory") { + var values = new java.util.LinkedHashMap() + return { + load: key => values.get(key), + save: (key, claims) => values.put(key, claims), + remove: key => values.remove(key), + purge: expires => { + var entries = values.values().iterator() + while (entries.hasNext()) if (entries.next().exp <= expires) entries.remove() + }, + size: () => Number(values.size()), + close: () => values.clear() + } + } + if (!isString(configuration.file) || !configuration.file.length || /[;\x00]/.test(configuration.file)) invalid("H2 file") + var file = new java.io.File(configuration.file).getCanonicalPath() + if (/[;\x00]/.test(file)) invalid("H2 file") + var ownership, lease, connection + try { + ownership = new java.io.RandomAccessFile(file + ".oauth-lock", "rw") + lease = ownership.getChannel().tryLock() + if (lease === null) throw new Error("OAuth database already in use") + var properties = new java.util.Properties() + properties.setProperty("user", "sa") + connection = new Packages.org.h2.Driver().connect("jdbc:h2:file:" + file + ";AUTO_SERVER=FALSE;LOCK_TIMEOUT=5000", properties) + var schema = connection.createStatement() + try { + schema.execute("CREATE TABLE IF NOT EXISTS oauth_access (token_id VARCHAR(43) PRIMARY KEY, expires_at BIGINT NOT NULL, claims VARCHAR(32768) NOT NULL)") + schema.execute("CREATE TABLE IF NOT EXISTS oauth_owner (owner_id INTEGER PRIMARY KEY, issuer VARCHAR(2048) NOT NULL)") + } finally { schema.close() } + var statement = connection.prepareStatement("SELECT issuer FROM oauth_owner WHERE owner_id = 1") + var recorded + try { + var row = statement.executeQuery() + try { if (row.next()) recorded = String(row.getString(1)) } + finally { row.close() } + } finally { statement.close() } + if (isDef(recorded) && recorded !== issuer) throw new Error("OAuth database belongs to another issuer") + if (isUnDef(recorded)) { + statement = connection.prepareStatement("INSERT INTO oauth_owner (owner_id, issuer) VALUES (1, ?)") + try { statement.setString(1, issuer); statement.executeUpdate() } + finally { statement.close() } + } + } catch(e) { + try { if (isDef(connection)) connection.close() } + finally { if (isDef(ownership)) ownership.close() } + throw new Error("OAuth issuer database unavailable") + } + + var execute = (sql, params, handler) => { + var query = connection.prepareStatement(sql) + try { + query.setQueryTimeout(5) + params.forEach((value, i) => { + if (isNumber(value)) query.setLong(i + 1, value) + else query.setString(i + 1, value) + }) + return handler(query) + } finally { query.close() } + } + var select = (sql, params, handler) => execute(sql, params, query => { + var row = query.executeQuery() + try { return handler(row) } finally { row.close() } + }) + var mutate = (sql, params) => execute(sql, params, query => query.executeUpdate()) + return { + load: key => select("SELECT claims FROM oauth_access WHERE token_id = ?", [key], + row => row.next() ? JSON.parse(String(row.getString(1))) : null), + save: (key, claims) => mutate("INSERT INTO oauth_access (token_id, expires_at, claims) VALUES (?, ?, ?)", + [key, claims.exp, JSON.stringify(claims)]), + remove: key => mutate("DELETE FROM oauth_access WHERE token_id = ?", [key]), + purge: expires => mutate("DELETE FROM oauth_access WHERE expires_at <= ?", [expires]), + size: () => select("SELECT COUNT(*) FROM oauth_access", [], row => { row.next(); return Number(row.getLong(1)) }), + close: () => { + try { connection.close() } + finally { ownership.close() } + } + } + } + + OpenWrap.server.prototype.oauth.authorizationServer = function(options) { + // All public endpoint URLs derive from the configured issuer. + if (!isMap(options) || !identifier(options.issuer)) invalid("issuer") + var grants = isDef(options.grants) ? options.grants : ["client_credentials"] + if (!isArray(grants) || !grants.length || new Set(grants).size !== grants.length || + !grants.every(grant => ["client_credentials", "authorization_code", "refresh_token"].indexOf(grant) >= 0)) invalid("grants") + var interactive = grants.indexOf("authorization_code") >= 0 + var refreshEnabled = grants.indexOf("refresh_token") >= 0 + if (interactive && !isFunction(options.identityProvider) || refreshEnabled && !interactive) invalid("identity or refresh grants") + var parEnabled = options.par === true || options.requirePAR === true + if (parEnabled && !interactive) invalid("PAR without an authorization endpoint") + if (isDef(options.storage) && (!isMap(options.storage) || ["memory", "h2"].indexOf(options.storage.type) < 0)) invalid("storage") + if (refreshEnabled && isDef(options.storage) && options.storage.type !== "memory") invalid("refresh storage") + var issuer = options.issuer, uri = new java.net.URI(issuer), scheme = String(uri.getScheme()) + var host = String(uri.getHost()), path = String(uri.getRawPath()).replace(/\/$/, "") + if (uri.getHost() === null || uri.getRawUserInfo() !== null || uri.getRawQuery() !== null || + uri.getRawFragment() !== null || !/^(?:\/[A-Za-z0-9._~-]+)*$/.test(path) || + String(uri.normalize().getRawPath()) !== String(uri.getRawPath()) || + (scheme !== "https" && !(options.allowLoopbackHTTP === true && scheme === "http" && + ["127.0.0.1", "localhost", "[::1]"].indexOf(host) >= 0))) invalid("issuer") + var ttl = _$(options.accessTokenTTL).isNumber().default(300) + var maximum = _$(options.maxTokens).isNumber().default(10000) + if (!Number.isInteger(ttl) || ttl < 1 || ttl > 3600 || !Number.isInteger(maximum) || maximum < 1 || maximum > 1000000) { + invalid("token limits") + } + var registration = options.registration, registrationVerifier + if (isDef(registration)) { + if (!interactive || !isMap(registration) || !isFunction(registration.allowRedirect) || + !isString(registration.initialAccessTokenEnv) || + (isDef(options.storage) && options.storage.type !== "memory")) invalid("registration") + var initialToken = getEnv(registration.initialAccessTokenEnv) + if (!isString(initialToken) || initialToken.length < 24) invalid("registration access token") + registrationVerifier = digest(initialToken) + } + var maxClients = _$(options.maxClients).isNumber().default(1024) + if (!Number.isInteger(maxClients) || maxClients < 1 || maxClients > 10000) invalid("client capacity") + var tokenFormat = options.tokenFormat || "opaque", signing = options.signingKey + if (tokenFormat !== "opaque" && tokenFormat !== "jwt") invalid("token format") + if (tokenFormat === "jwt" && (!isMap(signing) || !names(signing.id) || + !(signing.keyPair instanceof java.security.KeyPair) || + !(signing.keyPair.getPrivate() instanceof java.security.interfaces.RSAPrivateKey) || + !(signing.keyPair.getPublic() instanceof java.security.interfaces.RSAPublicKey) || + signing.keyPair.getPrivate().getModulus().bitLength() < 2048 || + signing.keyPair.getPrivate().getModulus().compareTo(signing.keyPair.getPublic().getModulus()) !== 0)) invalid("signing key") + var publicKey + if (tokenFormat === "jwt") publicKey = jose.security.Jwks.builder().key(signing.keyPair.getPublic()) + .algorithm("RS256").id(signing.id).build() + + // Validate the deployment's pre-registered resource and client policies. + if (!isMap(options.resources) || !isMap(options.clients)) invalid("clients and resources") + var resources = Object.create(null), clients = Object.create(null), allScopes = new Set() + Object.keys(options.resources).forEach(resource => { + var policy = options.resources[resource] + var scopes = isMap(policy) ? scopeSet(policy.scopes) : __ + if (!identifier(resource) || !new java.net.URI(resource).isAbsolute() || + new java.net.URI(resource).getRawFragment() !== null || isUnDef(scopes)) invalid("resource policy") + if (isDef(policy.audience) && !identifier(policy.audience)) invalid("resource audience") + resources[resource] = { audience: policy.audience || resource, scopes: scopes } + scopes.forEach(scope => allScopes.add(scope)) + }) + var addClient = (id, client, generation) => { + if (!names(id) || !isMap(client) || !isMap(client.resources) || own(clients, id) || + Object.keys(clients).length >= maxClients) invalid("client policy") + var method = client.tokenEndpointAuthMethod || "client_secret_basic" + var verifier, assertionVerifier + if (method === "private_key_jwt") { + if (!names(client.keyId) || !(client.publicKey instanceof java.security.interfaces.RSAPublicKey) || + client.publicKey.getModulus().bitLength() < 2048) invalid("client assertion key") + assertionVerifier = jose.Jwts.parser().verifyWith(client.publicKey).build() + } else if (method === "none") { + if (!interactive || client.introspection) invalid("public client authentication") + } else if (method === "tls_client_auth" || method === "self_signed_tls_client_auth") { + if (!isString(client.certificateThumbprint) || !/^[\w-]{43}$/.test(client.certificateThumbprint)) invalid("client certificate") + } else { + if (["client_secret_basic", "client_secret_post"].indexOf(method) < 0 || + !isString(client.clientSecretEnv) || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(client.clientSecretEnv)) invalid("client authentication") + var credential = getEnv(client.clientSecretEnv) + if (!isString(credential) || credential.length < 24) invalid("client secret") + verifier = digest(credential) + } + var redirects = client.redirectURIs || [] + if (!isArray(redirects) || redirects.length > 32 || !redirects.every(url => { + if (!identifier(url)) return false + try { + var redirect = new java.net.URI(url) + var redirectHost = String(redirect.getHost()) + return redirect.getHost() !== null && redirect.getRawUserInfo() === null && redirect.getRawFragment() === null && + (String(redirect.getScheme()) === "https" || (String(redirect.getScheme()) === "http" && redirect.getPort() > 0 && + ["127.0.0.1", "[::1]"].indexOf(redirectHost) >= 0)) + } catch(e) { return false } + })) invalid("client redirects") + if (redirects.length && !interactive) invalid("interactive client grants") + var sender = client.senderConstraint + if (isDef(sender) && ["dpop", "mtls"].indexOf(sender) < 0) invalid("client sender constraint") + if ((method === "tls_client_auth" || method === "self_signed_tls_client_auth") && isUnDef(sender)) sender = "mtls" + var allowed = Object.create(null) + Object.keys(client.resources).forEach(resource => { + var scopes = scopeSet(client.resources[resource]) + if (!own(resources, resource) || isUnDef(scopes) || + !scopes.every(scope => resources[resource].scopes.indexOf(scope) >= 0)) invalid("client scopes") + allowed[resource] = scopes + }) + clients[id] = { method: method, verifier: verifier, assertionVerifier: assertionVerifier, keyId: client.keyId, + resources: allowed, introspection: client.introspection === true, senderConstraint: sender, + certificateThumbprint: client.certificateThumbprint, redirects: redirects.slice(), allowRefresh: client.allowRefresh === true, + generation: generation } + } + Object.keys(options.clients).forEach(id => addClient(id, options.clients[id], "configured:" + id)) + + var lock = new java.util.concurrent.locks.ReentrantLock() + var tokens = tokenStore(options.storage, issuer), assertions = new java.util.LinkedHashMap(), state = { mounted: false, closed: false } + ow.loadObj() + var httpd = ow.server.httpd + var authRequests = new java.util.LinkedHashMap(), codes = new java.util.LinkedHashMap() + var pushedRequests = new java.util.LinkedHashMap() + var refreshTokens = new java.util.LinkedHashMap(), refreshFamilies = new java.util.LinkedHashMap() + var origin = scheme + "://" + String(uri.getRawAuthority()), resourceURL = origin + path + var dpop = ow.server.oauth.__proofVerifier({ mode: "required", methods: ["dpop"], nonceRequired: true }, + resourceURL + "/token", options.allowLoopbackHTTP === true) + var run = fn => { + if (!lock.tryLock(5000, unit)) return reply({ error: "temporarily_unavailable" }, 503) + try { + if (state.closed) return reply({ error: "temporarily_unavailable" }, 503) + return fn() + } finally { lock.unlock() } + } + var reply = (data, status, extra) => httpd.reply(data, status, "application/json", + Object.assign({ "Cache-Control": "no-store", Pragma: "no-cache" }, extra || {})) + var oauthError = (code, status) => reply({ error: code }, status || 400) + var form = req => { + var header = req.header || {} + if (req.method !== "POST" || !isString(header["content-type"]) || + !/^application\/x-www-form-urlencoded(?: *;|$)/i.test(header["content-type"]) || + String(req.uri).indexOf("?") >= 0 || !isString(req.data) || req.data.length > 16384) return + return parseForm(req.data) + } + var parseForm = data => { + if (!isString(data) || data.length > 16384) return + var values = Object.create(null) + try { + data.split("&").forEach(field => { + var eq = field.indexOf("="), decode = value => decodeURIComponent(value.replace(/\+/g, " ")) + if (eq < 1) throw new Error("Invalid form") + var name = decode(field.slice(0, eq)) + if (own(values, name)) throw new Error("Duplicate form field") + values[name] = decode(field.slice(eq + 1)) + }) + } catch(e) { return } + return values + } + var dummy = digest(secret()) + // An assertion accepted by a previous process must precede this process's issuance epoch. + var assertionEpoch = (Math.floor(now() / 1000) + 1) * 1000 + var authenticateAssertion = (id, fields) => { + var client = clients[id], assertion = fields.client_assertion + if (isUnDef(client) || client.disabled || client.method !== "private_key_jwt" || + fields.client_assertion_type !== "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" || + !isString(assertion) || assertion.length > 8192) return + var claims, expiry, jti + try { + var segments = assertion.split(".") + if (segments.length !== 3 || !segments.every(part => /^[\w-]+$/.test(part))) return + var decoded = java.util.Base64.getUrlDecoder() + var header = JSON.parse(af.fromBytes2String(decoded.decode(segments[0]))) + if (header.alg !== "RS256" || header.kid !== client.keyId || + (isDef(header.typ) && header.typ !== "client-authentication+jwt") || + ["crit", "jwk", "jku", "x5u", "x5c", "zip", "b64"].some(name => own(header, name))) return + claims = client.assertionVerifier.parseSignedClaims(assertion).getPayload() + var audience = claims.getAudience(), issued = claims.getIssuedAt() + if (claims.getExpiration() === null || issued === null || claims.getId() === null || audience === null) return + expiry = Number(claims.getExpiration().getTime()) + jti = String(claims.getId()) + if (String(claims.getIssuer()) !== id || String(claims.getSubject()) !== id || + audience.size() !== 1 || !audience.contains(issuer) || expiry <= now() || + Number(issued.getTime()) < Math.max(assertionEpoch, now() - 120000) || Number(issued.getTime()) > now() || + expiry > Number(issued.getTime()) + 120000 || !identifier(jti)) return + } catch(e) { return } + // Mounting creates one issuer with one lock. Claims are consumed across its endpoints. + var entries = assertions.entrySet().iterator(), time = now() + while (entries.hasNext()) if (Number(entries.next().getValue()) <= time) entries.remove() + var key = sha256(JSON.stringify([id, jti])) + if (assertions.containsKey(key) || assertions.size() >= maximum) return + assertions.put(key, expiry) + return { id: id, client: client } + } + var authenticate = (req, fields) => { + var header = req.header.authorization, id = fields.client_id, password = fields.client_secret + var method = "client_secret_post" + if (isDef(fields.client_assertion) || isDef(fields.client_assertion_type)) { + if (isDef(header) || isDef(password)) return + return authenticateAssertion(id, fields) + } + if (isDef(header)) { + if (isDef(password) || !isString(header) || header.length > 8192) return + var auth = /^Basic ([A-Za-z0-9+/]+=*)$/i.exec(header) + if (auth === null) return + try { + var value = af.fromBytes2String(java.util.Base64.getDecoder().decode(auth[1])) + var split = value.indexOf(":") + if (split < 0) return + var basicId = decodeURIComponent(value.slice(0, split).replace(/\+/g, " ")) + if (isDef(id) && id !== basicId) return + id = basicId + password = decodeURIComponent(value.slice(split + 1).replace(/\+/g, " ")) + method = "client_secret_basic" + } catch(e) { return } + } + var client = clients[id] + if (isDef(client) && client.disabled) return + if (isDef(client) && client.method === "none" && isUnDef(header) && isUnDef(password)) return { id: id, client: client } + if (isDef(client) && ["tls_client_auth", "self_signed_tls_client_auth"].indexOf(client.method) >= 0) { + if (isDef(header) || isDef(password) || + String(Packages.openaf.plugins.HTTPServer.oauthPeerThumbprint(req)) !== client.certificateThumbprint) return + return { id: id, client: client } + } + if (!isString(password) || !java.security.MessageDigest.isEqual(digest(password), + isDef(client) && isDef(client.verifier) ? client.verifier : dummy) || + isUnDef(client) || client.method !== method) return + return { id: id, client: client } + } + var endpoint = handler => req => run(() => { + var fields = form(req) + if (isUnDef(fields)) return oauthError("invalid_request") + var client = authenticate(req, fields) + if (isUnDef(client)) return reply({ error: "invalid_client" }, 401, { "WWW-Authenticate": 'Basic realm="oauth"' }) + try { return handler(client, fields, req) } + catch(e) { return oauthError("temporarily_unavailable", 503) } + }) + var tokenKey = value => String(encode.encodeToString(digest(value))) + + + // Issue credentials only from the intersection of client and resource policies. + var saveToken = (auth, resource, scopes, subject, confirmation, tokenType) => { + var iat = Math.floor(now() / 1000) + tokens.purge(iat) + if (tokens.size() >= maximum) return + var claims = { iss: issuer, sub: subject, aud: resources[resource].audience, + iat: iat, exp: iat + ttl, jti: secret(), client_id: auth.id, scope: scopes.join(" ") } + if (isDef(confirmation)) claims.cnf = confirmation + var token = tokenFormat === "jwt" ? String(jose.Jwts.builder().header().type("at+jwt").keyId(signing.id).and() + .claims(af.toJavaMap(claims)).signWith(signing.keyPair.getPrivate(), jose.Jwts.SIG.RS256).compact()) : secret() + tokens.save(tokenKey(token), Object.assign({ resource: resource, token_type: tokenType, clientGeneration: auth.client.generation }, claims)) + return { access_token: token, token_type: tokenType, expires_in: ttl, scope: claims.scope } + } + var expire = (map, time) => { + var entries = map.values().iterator() + while (entries.hasNext()) if (entries.next().expires <= time) entries.remove() + } + var redactFamily = family => { + family.revoked = true + family.access.forEach(key => tokens.remove(key)) + family.access = [] + } + var saveRefresh = (grant, familyId, response, refresh) => { + var time = now() + var family = refreshFamilies.get(familyId) + if (family === null) { + family = { expires: time + 86400000, revoked: false, access: [] } + refreshFamilies.put(familyId, family) + } + family.access = family.access.filter(key => { + var record = tokens.load(key) + return record !== null && record.exp * 1000 > time + }) + family.access.push(tokenKey(response.access_token)) + refreshTokens.put(tokenKey(refresh), { grant: grant, familyId: familyId, used: false, + expires: family.expires, activeUntil: Math.min(family.expires, time + 3600000) }) + response.refresh_token = refresh + } + var exchangeDelegated = (auth, fields) => { + // Redeem a single-use code or rotate the family's current refresh credential under the issuer lock. + var time = now(), isCode = fields.grant_type === "authorization_code" + expire(codes, time) + expire(refreshTokens, time) + expire(refreshFamilies, time) + var credential = isCode ? fields.code : fields.refresh_token + if (!isString(credential) || !/^[\w-]{43}$/.test(credential)) return oauthError("invalid_grant") + var key = tokenKey(credential) + var record = (isCode ? codes : refreshTokens).get(key) + if (record === null || record.grant.client !== auth.id || record.grant.generation !== auth.client.generation) return oauthError("invalid_grant") + var grant = record.grant, familyId = isCode ? __ : record.familyId + if (!isCode) { + var family = refreshFamilies.get(familyId) + if (family === null || family.revoked) return oauthError("invalid_grant") + if (record.used) { + redactFamily(family) + return oauthError("invalid_grant") + } + if (record.activeUntil <= time) return oauthError("invalid_grant") + } + if (isCode && (fields.redirect_uri !== grant.redirect || !isString(fields.code_verifier) || + !/^[A-Za-z0-9._~-]{43,128}$/.test(fields.code_verifier) || + !java.security.MessageDigest.isEqual(secretBytes(grant.challenge), + secretBytes(String(encode.encodeToString(digest(fields.code_verifier))))))) return oauthError("invalid_grant") + if (isDef(fields.audience) || (isDef(fields.resource) && fields.resource !== grant.resource)) return oauthError("invalid_target") + var scopes = isDef(fields.scope) ? scopeSet(fields.scope) : grant.scopes + if (isUnDef(scopes) || !scopes.every(scope => grant.scopes.indexOf(scope) >= 0)) return oauthError("invalid_scope") + var refresh = refreshEnabled && auth.client.allowRefresh && scopes.indexOf("offline_access") >= 0 + if (refresh && (refreshTokens.size() >= maximum || isCode && refreshFamilies.size() >= maximum)) { + return oauthError("temporarily_unavailable", 503) + } + if (isCode) codes.remove(key) + else record.used = true + var response = saveToken(auth, grant.resource, scopes, grant.subject, __, "Bearer") + if (isUnDef(response)) return oauthError("temporarily_unavailable", 503) + if (refresh) saveRefresh(Object.assign({}, grant, { scopes: scopes }), familyId || secret(), response, secret()) + return reply(response, 200) + } + var issue = endpoint((auth, fields, req) => { + if (grants.indexOf(fields.grant_type) < 0) return oauthError("unsupported_grant_type") + if (auth.client.introspection) return oauthError("unauthorized_client") + if (fields.grant_type !== "client_credentials") { + if (!auth.client.redirects.length || isDef(auth.client.senderConstraint) || isDef(req.header.dpop)) return oauthError("unauthorized_client") + return exchangeDelegated(auth, fields) + } + if (auth.client.method === "none") return oauthError("unauthorized_client") + var resource = fields.resource, allowed = auth.client.resources[resource] + if (isUnDef(allowed) || isDef(fields.audience)) return oauthError("invalid_target") + var scopes = scopeSet(fields.scope || "") + if (isUnDef(scopes) || !scopes.every(scope => allowed.indexOf(scope) >= 0)) return oauthError("invalid_scope") + + // Bind issuance to the registered client's required sender mechanism. + var confirmation, tokenType = "Bearer" + if (auth.client.senderConstraint === "dpop") { + var proof = dpop.validate(req, req.header.dpop) + if (isDef(proof.error)) return reply({ error: proof.error }, 400, { "DPoP-Nonce": dpop.nonce }) + confirmation = { jkt: proof.thumbprint } + tokenType = "DPoP" + } else if (auth.client.senderConstraint === "mtls") { + var certificate = Packages.openaf.plugins.HTTPServer.oauthPeerThumbprint(req) + if (certificate === null) return oauthError("invalid_client", 401) + confirmation = { "x5t#S256": String(certificate) } + } else if (isDef(req.header.dpop)) return oauthError("invalid_dpop_proof") + + var response = saveToken(auth, resource, scopes, "service:" + auth.id, confirmation, tokenType) + return isUnDef(response) ? oauthError("temporarily_unavailable", 503) : reply(response, 200) + }) + var htmlEscape = value => String(value).replace(/[&<>"']/g, c => "&#" + c.charCodeAt(0) + ";") + var redirect = (grant, values) => { + values.iss = issuer + if (isDef(grant.state)) values.state = grant.state + var location = grant.redirect + (grant.redirect.indexOf("?") >= 0 ? "&" : "?") + ow.obj.rest.writeQuery(values) + return reply("", 303, { Location: location, "Referrer-Policy": "no-referrer" }) + } + var identity = req => { + var verified = options.identityProvider(req) + if (!isMap(verified) || !identifier(verified.subject) || !identifier(verified.sessionId) || !isMap(verified.resources)) return + return { subject: "user:" + verified.subject, session: tokenKey(verified.sessionId), resources: verified.resources } + } + var authorizationFields = ["client_id", "redirect_uri", "response_type", "resource", "state", "scope", + "code_challenge", "code_challenge_method"] + var allowedRequest = (fields, client) => isDef(client) && !client.disabled && !client.senderConstraint && !client.introspection && + client.redirects.indexOf(fields.redirect_uri) >= 0 && isString(fields.code_challenge) && + /^[\w-]{43}$/.test(fields.code_challenge) && fields.code_challenge_method === "S256" && + (!isDef(fields.state) || identifier(fields.state)) + var parPrefix = "urn:ietf:params:oauth:request_uri:" + var pushAuthorization = endpoint((auth, fields) => { + if (!allowedRequest(fields, auth.client) || fields.response_type !== "code" || + isDef(fields.request_uri) || isDef(fields.request)) return oauthError("invalid_request") + var time = now() + expire(pushedRequests, time) + if (pushedRequests.size() >= maximum) return oauthError("temporarily_unavailable", 503) + var handle = secret(), request = Object.create(null) + authorizationFields.forEach(field => { if (isDef(fields[field])) request[field] = fields[field] }) + pushedRequests.put(tokenKey(handle), { fields: request, expires: time + 60000 }) + return reply({ request_uri: parPrefix + handle, expires_in: 60 }, 201) + }) + var authorise = req => run(() => { + // Build the consent transaction only after validating the registered redirect and PKCE parameters. + var time = now() + expire(authRequests, time) + expire(codes, time) + if (req.method === "GET") { + var query = String(req.uri).indexOf("?") + var fields = query >= 0 ? parseForm(req.uri.slice(query + 1)) : __ + if (isUnDef(fields)) return oauthError("invalid_request") + if (isDef(fields.request_uri)) { + if (!parEnabled || Object.keys(fields).length !== 2 || !isString(fields.request_uri) || + !fields.request_uri.startsWith(parPrefix) || !/^[\w-]{43}$/.test(fields.request_uri.substring(parPrefix.length))) { + return oauthError("invalid_request") + } + expire(pushedRequests, time) + var reference = tokenKey(fields.request_uri.substring(parPrefix.length)) + var pushed = pushedRequests.get(reference) + if (pushed === null || fields.client_id !== pushed.fields.client_id) return oauthError("invalid_request") + pushedRequests.remove(reference) + fields = pushed.fields + } else if (options.requirePAR === true || isDef(fields.request)) return oauthError("invalid_request") + var client = clients[fields.client_id] + if (!allowedRequest(fields, client)) return oauthError("invalid_request") + var grant = { redirect: fields.redirect_uri, state: fields.state, client: fields.client_id, + challenge: fields.code_challenge, resource: fields.resource, generation: client.generation } + if (fields.response_type !== "code") return redirect(grant, { error: "unsupported_response_type" }) + var verified = identity(req) + if (isUnDef(verified)) return reply({ error: "login_required" }, 401) + var scopes = scopeSet(fields.scope || ""), allowed = client.resources[fields.resource] + var userScopes = scopeSet(own(verified.resources, fields.resource) ? verified.resources[fields.resource] : __) + if (isUnDef(allowed) || isUnDef(userScopes)) return redirect(grant, { error: "invalid_target" }) + if (isUnDef(scopes) || !scopes.every(scope => allowed.indexOf(scope) >= 0 && userScopes.indexOf(scope) >= 0)) { + return redirect(grant, { error: "invalid_scope" }) + } + if (authRequests.size() >= maximum) return oauthError("temporarily_unavailable", 503) + var handle = secret() + grant.scopes = scopes + grant.subject = verified.subject + authRequests.put(tokenKey(handle), { grant: grant, session: verified.session, expires: time + 300000 }) + return httpd.reply("Authorize access

Authorize access

" + + "

Client " + htmlEscape(grant.client) + " requests " + htmlEscape(scopes.join(", ")) + " for " + + htmlEscape(grant.resource) + '.

' + + '
', + 200, "text/html; charset=utf-8", { "Cache-Control": "no-store", "Referrer-Policy": "no-referrer", + "Content-Security-Policy": "default-src 'none'; form-action 'self'; frame-ancestors 'none'" }) + } + if (req.method !== "POST") return reply("", 405, { Allow: "GET, POST" }) + var fields = form(req) + if (isUnDef(fields) || req.header.origin !== origin || !isString(fields.request) || + !/^[\w-]{43}$/.test(fields.request) || ["allow", "deny"].indexOf(fields.decision) < 0) return oauthError("invalid_request") + var key = tokenKey(fields.request), record = authRequests.get(key), verified = identity(req) + if (record === null || isUnDef(verified) || record.session !== verified.session || + record.grant.subject !== verified.subject || !own(clients, record.grant.client) || + clients[record.grant.client].disabled || clients[record.grant.client].generation !== record.grant.generation) { + return oauthError("invalid_request") + } + authRequests.remove(key) + if (fields.decision === "deny") return redirect(record.grant, { error: "access_denied" }) + var allowed = scopeSet(own(verified.resources, record.grant.resource) ? verified.resources[record.grant.resource] : __) + if (isUnDef(allowed) || !record.grant.scopes.every(scope => allowed.indexOf(scope) >= 0)) { + return redirect(record.grant, { error: "access_denied" }) + } + if (codes.size() >= maximum) return oauthError("temporarily_unavailable", 503) + var code = secret() + codes.put(tokenKey(code), { grant: record.grant, expires: time + 60000 }) + return redirect(record.grant, { code: code }) + }) + var inspect = endpoint((auth, fields) => { + if (!auth.client.introspection) return oauthError("unauthorized_client", 403) + var record = isString(fields.token) ? tokens.load(tokenKey(fields.token)) : null + if (record === null || record.exp <= Math.floor(now() / 1000) || !own(auth.client.resources, record.resource) || + !own(clients, record.client_id) || clients[record.client_id].disabled || + clients[record.client_id].generation !== record.clientGeneration) { + return reply({ active: false }, 200) + } + var result = Object.assign({ active: true, token_type: "Bearer" }, record) + delete result.resource + delete result.clientGeneration + return reply(result, 200) + }) + var revoke = endpoint((auth, fields) => { + if (!isString(fields.token) || !fields.token.length) return oauthError("invalid_request") + var key = tokenKey(fields.token), record = tokens.load(key) + if (record !== null && record.client_id === auth.id) tokens.remove(key) + var refresh = refreshTokens.get(key) + if (refresh !== null && refresh.grant.client === auth.id) { + var family = refreshFamilies.get(refresh.familyId) + if (family !== null) redactFamily(family) + } + return reply("", 200) + }) + var register = req => run(() => { + var header = req.header || {} + var bearer = isString(header.authorization) && header.authorization.length <= 2048 ? + /^Bearer ([A-Za-z0-9._~+\/-]+=*)$/i.exec(header.authorization) : null + if (bearer === null || !java.security.MessageDigest.isEqual(digest(bearer[1]), registrationVerifier)) { + return reply({ error: "invalid_token" }, 401, { "WWW-Authenticate": "Bearer" }) + } + if (req.method !== "POST" || !isString(req.data) || req.data.length > 16384 || + !isString(header["content-type"]) || !/^application\/json(?: *;|$)/i.test(header["content-type"])) return oauthError("invalid_client_metadata") + var metadata + try { metadata = JSON.parse(req.data) } catch(e) { return oauthError("invalid_client_metadata") } + if (!isMap(metadata) || Object.keys(metadata).some(key => ["redirect_uris", "token_endpoint_auth_method", + "grant_types", "response_types", "client_name"].indexOf(key) < 0) || + metadata.token_endpoint_auth_method !== "none" || + (isDef(metadata.grant_types) && (!isArray(metadata.grant_types) || metadata.grant_types.join(" ") !== "authorization_code")) || + (isDef(metadata.response_types) && (!isArray(metadata.response_types) || metadata.response_types.join(" ") !== "code")) || + !isArray(metadata.redirect_uris) || metadata.redirect_uris.length < 1 || metadata.redirect_uris.length > 32 || + !metadata.redirect_uris.every(uri => identifier(uri))) return oauthError("invalid_client_metadata") + if (!metadata.redirect_uris.every(uri => registration.allowRedirect(uri) === true)) return oauthError("invalid_redirect_uri") + if (Object.keys(clients).length >= maxClients) return oauthError("temporarily_unavailable", 503) + var id = secret() + try { + // Registration alone acquires no resource privileges. + addClient(id, { resources: {}, redirectURIs: metadata.redirect_uris, tokenEndpointAuthMethod: "none" }, secret()) + } catch(e) { return oauthError("invalid_redirect_uri") } + return reply({ client_id: id, redirect_uris: metadata.redirect_uris, token_endpoint_auth_method: "none", + grant_types: ["authorization_code"], response_types: ["code"] }, 201) + }) + var admin = fn => { + if (isDef(options.storage) && options.storage.type !== "memory") throw new Error("Runtime client management requires the memory issuer profile") + if (!lock.tryLock(5000, unit)) throw new Error("OAuth issuer busy") + try { + if (state.closed) throw new Error("OAuth issuer closed") + return fn() + } finally { lock.unlock() } + } + var methods = Array.from(new Set(Object.keys(clients).map(id => clients[id].method))) + var discovery = { issuer: issuer, token_endpoint: resourceURL + "/token", + introspection_endpoint: resourceURL + "/introspect", revocation_endpoint: resourceURL + "/revoke", + grant_types_supported: grants.slice(), response_types_supported: interactive ? ["code"] : [], scopes_supported: Array.from(allScopes), + token_endpoint_auth_methods_supported: isDef(registrationVerifier) ? Array.from(new Set(methods.concat("none"))) : methods } + if (methods.indexOf("private_key_jwt") >= 0) discovery.token_endpoint_auth_signing_alg_values_supported = ["RS256"] + var metadata = req => { + if (req.method !== "GET") return reply("", 405, { Allow: "GET" }) + if (state.closed) return oauthError("temporarily_unavailable", 503) + var advertised = Object.assign({}, discovery) + var activeMethods = Object.keys(clients).filter(id => !clients[id].disabled).map(id => clients[id].method) + if (isDef(registrationVerifier)) activeMethods.push("none") + advertised.token_endpoint_auth_methods_supported = Array.from(new Set(activeMethods)) + if (Object.keys(clients).some(id => !clients[id].disabled && clients[id].senderConstraint === "dpop")) { + advertised.dpop_signing_alg_values_supported = ["ES256"] + } + if (activeMethods.indexOf("private_key_jwt") >= 0) advertised.token_endpoint_auth_signing_alg_values_supported = ["RS256"] + else delete advertised.token_endpoint_auth_signing_alg_values_supported + return reply(advertised, 200) + } + var routes = Object.create(null) + routes["/.well-known/oauth-authorization-server" + path] = metadata + if (interactive) { + discovery.authorization_endpoint = resourceURL + "/authorize" + discovery.code_challenge_methods_supported = ["S256"] + discovery.authorization_response_iss_parameter_supported = true + routes[path + "/authorize"] = authorise + } + if (parEnabled) { + discovery.pushed_authorization_request_endpoint = resourceURL + "/par" + discovery.require_pushed_authorization_requests = options.requirePAR === true + routes[path + "/par"] = pushAuthorization + } + if (isDef(registrationVerifier)) { + discovery.registration_endpoint = resourceURL + "/register" + routes[path + "/register"] = register + } + routes[path + "/token"] = issue + routes[path + "/introspect"] = inspect + routes[path + "/revoke"] = revoke + if (isDef(publicKey)) { + discovery.jwks_uri = resourceURL + "/jwks" + routes[path + "/jwks"] = req => req.method === "GET" ? + reply({ keys: [JSON.parse(String(jose.security.Jwks.json(publicKey)))] }, 200) : reply("", 405, { Allow: "GET" }) + } + var routePaths = Object.keys(routes) + return Object.freeze({ + mount: server => run(() => { + if (state.mounted) throw new Error("OAuth issuer already mounted") + if (String(server.getImpl()) !== "java") throw new Error("OAuth issuer requires the Java HTTP listener") + // HTTP route reservation detects collisions under the server's route lock. + var exact = Object.create(null) + routePaths.forEach(route => { + exact[route] = req => req.uri.split("?")[0] === route ? routes[route](req) : reply("", 404) + }) + httpd.route(server, exact, httpd.getDefaultRoute(server), __, __, routePaths) + state.mounted = true + return true + }), + status: () => ({ issuer: issuer, mounted: state.mounted, closed: state.closed, tokenFormat: tokenFormat }), + admin: Object.freeze({ + createClient: (id, policy) => admin(() => { addClient(id, policy, secret()); return { clientId: id } }), + grantResource: (id, resource, grantedScopes) => admin(() => { + var scopes = scopeSet(grantedScopes) + if (!own(clients, id) || !own(resources, resource) || isUnDef(scopes) || + !scopes.every(scope => resources[resource].scopes.indexOf(scope) >= 0)) invalid("client resource policy") + clients[id].generation = secret() + clients[id].resources[resource] = scopes + }), + disableClient: id => admin(() => { + if (!own(clients, id)) return false + clients[id].disabled = true + return true + }), + deleteClient: id => admin(() => delete clients[id]), + rotateClientSecret: id => admin(() => { + if (!own(clients, id) || !isDef(clients[id].verifier) || clients[id].disabled) invalid("client secret rotation") + var fresh = secret() + clients[id].verifier = digest(fresh) + clients[id].generation = secret() + return { clientId: id, clientSecret: fresh } + }) + }), + close: () => { + lock.lock() + try { + if (state.closed) return + state.closed = true + try { tokens.close() } finally { + assertions.clear() + codes.clear() + pushedRequests.clear() + authRequests.clear() + refreshTokens.clear() + refreshFamilies.clear() + } + } finally { lock.unlock() } + } + }) + } +})() diff --git a/js/owrap.server.oauth.js b/js/owrap.server.oauth.js new file mode 100644 index 00000000..36ef9e8d --- /dev/null +++ b/js/owrap.server.oauth.js @@ -0,0 +1,624 @@ +(function() { +// Validate the authority before handing a URL to the HTTP stack. +function oauthURL(value, loopback) { + try { + var uri = new java.net.URI(value), host = String(uri.getHost()).toLowerCase() + var scheme = String(uri.getScheme()).toLowerCase() + if (uri.getHost() !== null && uri.getRawUserInfo() === null && uri.getRawFragment() === null && + (scheme === "https" || (loopback && scheme === "http" && ["127.0.0.1", "::1", "[::1]", "localhost"].indexOf(host) >= 0))) { + return Packages.okhttp3.HttpUrl.get(value) + } + } catch(e) {} + throw new Error("Invalid OAuth URL") +} + +function oauthOrigin(url) { + return String(url.scheme()) + "://" + String(url.host()) + ":" + String(url.port()) +} + +// Bound metadata reads and reject redirects before interpreting a document. +function oauthMetadata(url, tls) { + var builder = new Packages.okhttp3.OkHttpClient.Builder().followRedirects(false).followSslRedirects(false) + .retryOnConnectionFailure(false).callTimeout(10, java.util.concurrent.TimeUnit.SECONDS) + if (isDef(tls)) builder.sslSocketFactory(tls.getSocketFactory(), tls.getTrustManager()) + var client = builder.build(), response + try { + response = client.newCall(new Packages.okhttp3.Request.Builder().url(url).header("Accept", "application/json").build()).execute() + if (response.code() === 404) return + if (response.code() !== 200) throw new Error("OAuth discovery failed") + var bytes = response.body().byteStream().readNBytes(262145) + if (bytes.length > 262144) throw new Error("OAuth metadata too large") + var document = JSON.parse(String(new java.lang.String(bytes, java.nio.charset.StandardCharsets.UTF_8))) + if (!isMap(document)) throw new Error("Invalid OAuth metadata") + return document + } catch(e) { + throw new Error("OAuth discovery failed") + } finally { + if (isDef(response)) response.close() + client.connectionPool().evictAll() + } +} + +function oauthWellKnown(url, name, suffix) { + var path = String(url.encodedPath()).replace(/\/$/, "") + return url.newBuilder().encodedPath(suffix ? path + "/.well-known/" + name : "/.well-known/" + name + path) + .query(null).build() +} + +// Use JOSE for proof signing, JWK parsing and signature verification. +var jose = Packages.io.jsonwebtoken +var b64 = java.util.Base64.getUrlEncoder().withoutPadding() +var randomId = () => String(java.util.UUID.randomUUID()) +var tokenHash = token => String(b64.encodeToString(java.security.MessageDigest.getInstance("SHA-256") + .digest(af.fromString2Bytes(token)))) +var tokenTarget = (url, loopback) => String(oauthURL(url, loopback).newBuilder().query(null).build()) +var proofHeader = jwt => JSON.parse(String(new java.lang.String( + java.util.Base64.getUrlDecoder().decode(jwt.split(".")[0]), java.nio.charset.StandardCharsets.UTF_8))) +var safeNonce = value => isString(value) && /^[A-Za-z0-9._~+\/-]{1,512}={0,2}$/.test(value) + +function proofKey(options, client) { + if (!isMap(options) || options.type !== "dpop" || (isDef(options.algorithm) && options.algorithm !== "ES256") || + (isDef(options.keyPair) && !(options.keyPair instanceof java.security.KeyPair)) || + (isDef(options.keyPair) && isDef(options.keyStore))) { + throw new Error("OAuth DPoP requires one ES256 key source") + } + var pair = options.keyPair + if (isDef(options.keyStore)) { + var config = options.keyStore + if (!isMap(config) || config.type !== "sec" || !isString(config.profile) || !config.profile.length || + !isString(client.issuer) || !isString(client.resource)) throw new Error("Persistent DPoP requires an issuer, resource and key profile") + var key = "oauth-dpop-v1-" + sha256(JSON.stringify([config.profile, client.issuer, client.clientId, client.resource])) + var store = ow.server.httpd.__oauth2SecTokenStore(config, "oauth-dpop") + try { + store.withLock(key, () => { + var record = store.load(key) + if (isUnDef(record)) { + pair = ow.server.jwt.genKey("ES256") + var encoder = java.util.Base64.getEncoder() + store.save(key, { version: 1, publicKey: String(encoder.encodeToString(pair.getPublic().getEncoded())), + privateKey: String(encoder.encodeToString(pair.getPrivate().getEncoded())) }) + } else { + if (!isMap(record) || record.version !== 1 || !isString(record.publicKey) || !isString(record.privateKey) || + record.publicKey.length > 1024 || record.privateKey.length > 1024) throw new Error("Invalid DPoP key record") + var decoder = java.util.Base64.getDecoder(), factory = java.security.KeyFactory.getInstance("EC") + pair = new java.security.KeyPair(factory.generatePublic(new java.security.spec.X509EncodedKeySpec(decoder.decode(record.publicKey))), + factory.generatePrivate(new java.security.spec.PKCS8EncodedKeySpec(decoder.decode(record.privateKey)))) + } + }) + } catch(e) { throw new Error("OAuth DPoP key storage failed") } + } + if (isUnDef(pair)) pair = ow.server.jwt.genKey("ES256") + var jwk = jose.security.Jwks.builder().key(pair.getPublic()).build() + return (url, method, nonce, token) => { + var builder = jose.Jwts.builder().header().type("dpop+jwt").add("jwk", jwk).and() + .id(randomId()).claim("iat", Math.floor(now() / 1000)).claim("htm", method).claim("htu", url) + if (safeNonce(nonce)) builder.claim("nonce", nonce) + if (isDef(token)) builder.claim("ath", tokenHash(token)) + return String(builder.signWith(pair.getPrivate(), jose.Jwts.SIG.ES256).compact()) + } +} + +function proofVerifier(options, resource, loopback) { + if (!isMap(options) || ["required", "optional"].indexOf(options.mode) < 0 || + !isArray(options.methods) || options.methods.length !== 1 || options.methods[0] !== "dpop") { + throw new Error("Unsupported OAuth sender constraint policy") + } + var target = tokenTarget(resource, loopback) + var path = options.internalPath || String(oauthURL(target, loopback).encodedPath()) + var maxAge = _$(options.proofMaxAgeSeconds).isNumber().default(60) + var capacity = _$(options.replayCapacity).isNumber().default(10000) + if (!Number.isInteger(maxAge) || maxAge < 1 || maxAge > 300 || + !Number.isInteger(capacity) || capacity < 1 || capacity > 1000000 || + !isString(path) || !/^\/[A-Za-z0-9_~./-]*$/.test(path) || + !/^\/[A-Za-z0-9_~./-]*$/.test(String(oauthURL(target, loopback).encodedPath()))) { + throw new Error("Invalid OAuth DPoP proof policy") + } + var shared = options.replayStore + if (isDef(shared) && (!isMap(shared) || !isFunction(shared.claim))) throw new Error("Invalid OAuth replay store") + if (isUnDef(shared) && options.nonceRequired === false) throw new Error("Memory replay protection requires a server nonce") + var nonce = isUnDef(shared) || options.nonceRequired === true ? randomId() : __ + var replay = new java.util.LinkedHashMap(), mutex = new java.util.concurrent.locks.ReentrantLock() + var claim = (key, expiresAt) => { + if (isDef(shared)) { + var accepted = shared.claim(target, key, expiresAt) + if (!isBoolean(accepted)) throw new Error("OAuth replay store unavailable") + return accepted + } + mutex.lock() + try { + var iterator = replay.entrySet().iterator(), time = now() + while (iterator.hasNext()) { + if (Number(iterator.next().getValue()) < time) iterator.remove() + } + if (replay.containsKey(key)) return false + if (replay.size() >= capacity) throw new Error("OAuth replay store exhausted") + replay.put(key, expiresAt) + return true + } finally { mutex.unlock() } + } + return { + required: options.mode === "required", nonce: nonce, + validate: (request, proof, digest, token) => { + // Only an exact configured route can supply the public request target. + if (!isString(request.uri) || request.uri.split("?")[0] !== path || + !isString(proof) || proof.length > 4096 || !/^[\w-]+\.[\w-]+\.[\w-]+$/.test(proof)) return { error: "invalid_dpop_proof" } + var h, claims, thumb, issued + try { + h = proofHeader(proof) + if (!isMap(h) || h.typ !== "dpop+jwt" || h.alg !== "ES256" || !isMap(h.jwk) || + ["crit", "zip", "b64", "jku", "x5u", "x5c"].some(key => Object.prototype.hasOwnProperty.call(h, key)) || + h.jwk.kty !== "EC" || h.jwk.crv !== "P-256" || + !isString(h.jwk.x) || !isString(h.jwk.y) || !/^[\w-]{43}$/.test(h.jwk.x) || !/^[\w-]{43}$/.test(h.jwk.y) || + Object.keys(h.jwk).some(key => ["kty", "crv", "x", "y", "alg", "kid", "use", "key_ops"].indexOf(key) < 0) || + (isDef(h.jwk.alg) && h.jwk.alg !== "ES256")) return { error: "invalid_dpop_proof" } + var jwk = jose.security.Jwks.parser().build().parse(JSON.stringify(h.jwk)) + thumb = String(jwk.thumbprint()) + if (isDef(digest) && thumb !== digest) return { error: "invalid_dpop_proof" } + claims = jose.Jwts.parser().verifyWith(jwk.toKey()).build().parseSignedClaims(proof).getPayload() + var iat = claims.getIssuedAt() + if (iat === null) return { error: "invalid_dpop_proof" } + issued = Number(iat.getTime()) + if (issued > now() + 5000 || issued + maxAge * 1000 < now() || + String(claims.get("htm")) !== request.method || String(claims.get("htu")) !== target || + (isDef(token) ? String(claims.get("ath")) !== tokenHash(token) : claims.get("ath") !== null) || claims.getId() === null || + !/^[\x21-\x7e]{1,128}$/.test(String(claims.getId()))) return { error: "invalid_dpop_proof" } + if (isDef(nonce) && String(claims.get("nonce")) !== nonce) return { error: "use_dpop_nonce" } + } catch(e) { return { error: "invalid_dpop_proof" } } + if (!claim(sha256(JSON.stringify([thumb, String(claims.getId())])), issued + maxAge * 1000)) return { error: "invalid_dpop_proof" } + return { thumbprint: thumb } + } + } +} + +// Use an isolated client for control-plane requests, without application cookies or authentication. +function oauthExchange(options, endpoint, parameters, legacy, binding, retried, tls) { + ow.loadObj() + var timeout = _$(options.tokenTimeoutMs, "tokenTimeoutMs").isNumber().default(60000) + if (!isFinite(timeout) || timeout <= 0) throw new Error("Invalid OAuth token timeout") + var params = Object.assign({}, options.extraParams || {}, parameters, { client_id: options.clientId }) + var method = options.tokenEndpointAuthMethod || (isDef(options.clientSecret) ? "client_secret_post" : "none") + var headers = { "Content-Type": "application/x-www-form-urlencoded" } + var secret = options.clientSecret + var encode = value => String(java.net.URLEncoder.encode(String(value), "UTF-8")) + + // Only the configured authentication method may supply credentials. + delete params.client_secret + delete params.client_assertion + delete params.client_assertion_type + if (method === "client_secret_basic" || method === "client_secret_post") { + if (!isString(secret) || !secret.length) throw new Error("OAuth client authentication requires a secret") + if (method === "client_secret_post") params.client_secret = secret + else headers.Authorization = "Basic " + String(java.util.Base64.getEncoder().encodeToString( + af.fromString2Bytes(encode(options.clientId) + ":" + encode(secret)))) + } else if (method === "private_key_jwt") { + if (!isString(options.issuer) || !isString(options.keyId) || !isJavaObject(options.privateKey)) { + throw new Error("OAuth client assertion requires an issuer, key ID and private key") + } + var algorithm = options.algorithm || "RS256" + if (["RS256", "PS256", "ES256", "ML-DSA-65"].indexOf(algorithm) < 0) throw new Error("Unsupported OAuth assertion algorithm") + var time = Math.floor(now() / 1000), jwt = Packages.io.jsonwebtoken + var signing = algorithm === "ML-DSA-65" ? Packages.openaf.oauth.MLDSA65.INSTANCE : jwt.Jwts.SIG[algorithm] + params.client_assertion_type = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" + try { + params.client_assertion = String(jwt.Jwts.builder().header().type("client-authentication+jwt").keyId(options.keyId).and() + .issuer(options.clientId).subject(options.clientId).claim("aud", options.issuer).claim("iat", time) + .claim("exp", time + 60).id(String(java.util.UUID.randomUUID())) + .signWith(options.privateKey, signing).compact()) + } catch(e) { + throw new Error("OAuth client assertion signing failed for configured algorithm") + } + } else if (["tls_client_auth", "self_signed_tls_client_auth"].indexOf(method) >= 0) { + if (!(tls instanceof Packages.openaf.oauth.ClientCertificateTlsProfile)) throw new Error("OAuth client certificate is required") + } else if (method !== "none") { + throw new Error("Unsupported OAuth client authentication method") + } + + ;["scope", "resource", "audience"].forEach(key => { + if (isDef(options[key])) params[key] = options[key] + }) + + // Bind token requests to the same key used for protected resource requests. + if (isDef(binding)) headers.DPoP = binding.sign(tokenTarget(endpoint, options.allowLoopbackHTTP === true), "POST", binding.nonce) + + // Keep the configured legacy factory for the existing MCP and callback APIs. + var connection = legacy ? ow.obj.rest.connectionFactory() : new ow.obj.http() + var response, body, code + try { + var transport = connection.client.newBuilder().followRedirects(false).followSslRedirects(false) + .retryOnConnectionFailure(false).callTimeout(timeout, java.util.concurrent.TimeUnit.MILLISECONDS) + if (isDef(tls)) transport.sslSocketFactory(tls.getSocketFactory(), tls.getTrustManager()) + connection.client = transport.build() + connection.setThrowExceptions(false) + response = connection.__exec(endpoint, "POST", ow.obj.rest.writeQuery(params), headers, false, timeout, true) + code = connection.responseCode() + if (isDef(binding)) { + var nonce = connection.responseHeaders()["dpop-nonce"] + if (safeNonce(nonce)) binding.nonce = nonce + } + var bytes = response.readNBytes(262145) + if (bytes.length > 262144) throw new Error("OAuth response too large") + body = JSON.parse(String(new java.lang.String(bytes, java.nio.charset.StandardCharsets.UTF_8))) + } catch(e) { + throw new Error("OAuth token request failed; check connectivity and provider configuration") + } finally { + try { if (isDef(response)) response.close() } finally { connection.close() } + } + if (isDef(binding) && !retried && code === 400 && isMap(body) && + body.error === "use_dpop_nonce" && safeNonce(nonce)) return oauthExchange(options, endpoint, parameters, legacy, binding, true, tls) + if (code < 200 || code >= 300 || !isMap(body) || !isString(body.access_token) || !body.access_token.length) { + var error = new Error("OAuth token request failed; provider did not return an access token") + if (isMap(body) && ["invalid_client", "invalid_grant", "interaction_required", "invalid_scope", "temporarily_unavailable"].indexOf(body.error) >= 0) { + error.oauthError = body.error + } + throw error + } + return body +} + +// Claim proofs transactionally across JVMs using a dedicated PostgreSQL database. +function postgresReplayStore(options) { + if (!isMap(options) || !isString(options.url) || + !/^jdbc:postgresql:\/\/[A-Za-z0-9._:\[\]-]+\/[A-Za-z0-9_]+$/.test(options.url) || + !isString(options.user) || !isString(options.passwordEnv)) throw new Error("Invalid OAuth replay database configuration") + var password = getEnv(options.passwordEnv) + var limit = _$(options.maxEntries).isNumber().default(100000) + if (!isString(password) || !password.length || !Number.isInteger(limit) || limit < 1 || limit > 1000000) { + throw new Error("Invalid OAuth replay database credentials or capacity") + } + var local = options.allowLoopbackPlaintext === true && + /^jdbc:postgresql:\/\/(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?\//.test(options.url) + var properties = new java.util.Properties() + properties.setProperty("user", options.user) + properties.setProperty("password", password) + properties.setProperty("sslmode", local ? "disable" : "verify-full") + properties.setProperty("connectTimeout", "5") + properties.setProperty("socketTimeout", "5") + var driver = new Packages.org.postgresql.Driver(), connection + var lock = new java.util.concurrent.locks.ReentrantLock() + var closed = false + var useConnection = fn => { + if (!lock.tryLock(5000, java.util.concurrent.TimeUnit.MILLISECONDS)) throw new Error("OAuth replay database busy") + try { + if (closed) throw new Error("OAuth replay store closed") + if (isUnDef(connection) || connection.isClosed()) connection = driver.connect(options.url, properties) + return fn(connection) + } catch(e) { + if (isDef(connection)) { + try { connection.close() } catch(ignored) {} + connection = __ + } + throw new Error("OAuth replay database unavailable") + } finally { lock.unlock() } + } + var statement = (conn, sql, fn) => { + var query = conn.prepareStatement(sql) + try { query.setQueryTimeout(5); return fn(query) } finally { query.close() } + } + var execute = (conn, sql) => statement(conn, sql, query => query.execute()) + var table = "openaf_oauth_proof_replay" + useConnection(conn => { + conn.setAutoCommit(false) + try { + execute(conn, "SELECT pg_advisory_xact_lock(1285222727, 1)") + execute(conn, "CREATE TABLE IF NOT EXISTS " + table + + " (namespace VARCHAR(64) NOT NULL, proof_id VARCHAR(64) NOT NULL, expiration BIGINT NOT NULL, PRIMARY KEY (namespace, proof_id))") + execute(conn, "CREATE INDEX IF NOT EXISTS openaf_oauth_proof_replay_expiration ON " + table + " (expiration)") + conn.commit() + } finally { if (!conn.isClosed()) { conn.rollback(); conn.setAutoCommit(true) } } + }) + return Object.freeze({ + claim: (namespace, key, expiresAt) => useConnection(conn => { + if (!isString(namespace) || !isString(key) || !Number.isFinite(expiresAt)) throw new Error("Invalid OAuth replay claim") + conn.setAutoCommit(false) + try { + // Serialize cleanup and admission with a transaction-scoped lock shared by all replicas. + execute(conn, "SELECT pg_advisory_xact_lock(1285222727, 1)") + var time = statement(conn, "SELECT floor(extract(epoch from clock_timestamp()) * 1000)", query => { + var row = query.executeQuery() + try { row.next(); return Number(row.getLong(1)) } + finally { row.close() } + }) + statement(conn, "DELETE FROM " + table + " WHERE expiration <= ?", query => { + query.setLong(1, time) + query.executeUpdate() + }) + var full = statement(conn, "SELECT count(*) FROM " + table, query => { + var row = query.executeQuery() + try { row.next(); return Number(row.getLong(1)) >= limit } + finally { row.close() } + }) + if (full) throw new Error("OAuth replay capacity exhausted") + var accepted = statement(conn, "INSERT INTO " + table + " VALUES (?, ?, ?) ON CONFLICT DO NOTHING", query => { + query.setString(1, sha256(namespace)) + query.setString(2, sha256(key)) + // Retain a proof through the largest supported verification window across replicas. + query.setLong(3, Math.ceil(Math.max(expiresAt, time + 335000))) + return query.executeUpdate() === 1 + }) + conn.commit() + return accepted + } finally { if (!conn.isClosed()) { conn.rollback(); conn.setAutoCommit(true) } } + }), + close: () => { + lock.lock() + try { + closed = true + if (isDef(connection)) connection.close() + } finally { lock.unlock() } + } + }) +} + +OpenWrap.server.prototype.oauth = { + __exchange: oauthExchange, + __proofVerifier: proofVerifier, + postgresReplayStore: postgresReplayStore, + __clients: new WeakMap(), + + /** + * + * ow.server.oauth.client(options) : Object + * Creates an OAuth client for a configured issuer or token endpoint. + * + */ + client: function(options) { + options = Object.assign({}, _$(options, "OAuth options").isMap().$_()) + var oauth = this, loopback = options.allowLoopbackHTTP === true + var required = name => _$(options[name], name).isString().$_() + required("clientId") + if (isMap(options.extraParams)) { + var reserved = ["grant_type", "client_id", "client_secret", "client_assertion", "client_assertion_type", + "scope", "resource", "audience", "refresh_token", "code", "code_verifier", "redirect_uri"] + if (Object.keys(options.extraParams).some(key => reserved.indexOf(key) >= 0)) throw new Error("Reserved OAuth token parameter") + options.extraParams = Object.assign({}, options.extraParams) + } + var tls + if (isDef(options.tlsProfile)) { + if (options.tlsProfile !== "x25519mlkem768" || loopback) throw new Error("Invalid OAuth hybrid TLS profile") + try { tls = new Packages.openaf.oauth.HybridTlsProfile() } + catch(e) { throw new Error("OAuth hybrid TLS profile is unavailable") } + } + var mtls = isMap(options.senderConstraint) && options.senderConstraint.type === "mtls" + if (mtls) { + if (isDef(tls) || loopback) throw new Error("Invalid OAuth mutual TLS profile") + var profile = options.senderConstraint + var keyPassword = isString(profile.keyStorePasswordEnv) ? getEnv(profile.keyStorePasswordEnv) : __ + var trustPassword = isString(profile.trustStorePasswordEnv) ? getEnv(profile.trustStorePasswordEnv) : __ + if (!isString(profile.keyStore) || !isString(keyPassword) || + (isDef(profile.trustStore) && (!isString(profile.trustStore) || !isString(trustPassword)))) { + throw new Error("Invalid OAuth client certificate configuration") + } + try { + tls = new Packages.openaf.oauth.ClientCertificateTlsProfile(profile.keyStore, keyPassword, + isDef(profile.trustStore) ? profile.trustStore : null, isString(trustPassword) ? trustPassword : null) + } catch(e) { throw new Error("OAuth client certificate configuration failed") } + if (isUnDef(options.tokenEndpointAuthMethod)) options.tokenEndpointAuthMethod = "tls_client_auth" + } + var binding = isDef(options.senderConstraint) && !mtls ? { sign: proofKey(options.senderConstraint, options) } : __ + var resourceNonce + if ([options.clientSecret, options.clientSecretEnv, options.clientSecretSec].filter(isDef).length > 1) { + throw new Error("Configure only one OAuth client secret") + } + if (isDef(options.clientSecretEnv)) { + options.clientSecret = getEnv(required("clientSecretEnv")) + if (!isString(options.clientSecret) || !options.clientSecret.length) throw new Error("OAuth client secret is unavailable") + } + if (isDef(options.clientSecretSec)) { + var ref = options.clientSecretSec, bucket + if (!isMap(ref) || !isString(ref.key) || !isString(ref.repo) || ref.repo === "system") { + throw new Error("Invalid OAuth secret reference") + } + try { + ow.loadSec() + bucket = $sec(ref.repo, ref.bucket, ref.lockSecret, ref.mainSecret, ref.file) + options.clientSecret = bucket.get(ref.key) + if (!isString(options.clientSecret) || !options.clientSecret.length) throw new Error("Invalid secret") + } catch(e) { throw new Error("OAuth client secret is unavailable") } + finally { if (isDef(bucket)) bucket.close() } + } + var grant = options.grantType || "client_credentials" + var endpoint = isDef(options.tokenURL) ? oauthURL(options.tokenURL, loopback) : __ + var issuer = isDef(options.issuer) ? oauthURL(options.issuer, loopback) : __ + var resource = isDef(options.resource) ? oauthURL(options.resource, loopback) : __ + var checkEndpoint = url => { + if (isDef(issuer) && (issuer.query() !== null || oauthOrigin(issuer) !== oauthOrigin(url))) { + throw new Error("OAuth endpoint origin is outside the configured issuer") + } + } + if (isDef(endpoint)) checkEndpoint(endpoint) + + // Accept implicit issuer discovery only on the already selected resource origin. + var discover = needAuth => { + if (isDef(endpoint) && (!needAuth || isDef(options.authURL))) return + if (isUnDef(issuer)) { + if (isUnDef(resource)) throw new Error("OAuth discovery requires a resource or issuer") + var metadata = oauthMetadata(oauthWellKnown(resource, "oauth-protected-resource"), tls) || + oauthMetadata(resource.newBuilder().encodedPath("/.well-known/oauth-protected-resource").query(null).build(), tls) + if (!isMap(metadata) || !isString(metadata.resource) || + String(oauthURL(metadata.resource, loopback)) !== String(resource) || + !isArray(metadata.authorization_servers) || metadata.authorization_servers.length !== 1) { + throw new Error("Invalid OAuth protected resource metadata") + } + var discovered = oauthURL(metadata.authorization_servers[0], loopback) + if (oauthOrigin(discovered) !== oauthOrigin(resource)) throw new Error("OAuth discovery requires an explicit cross-origin issuer") + options.issuer = metadata.authorization_servers[0] + options.resource = metadata.resource + issuer = discovered + } + var server = oauthMetadata(oauthWellKnown(issuer, "oauth-authorization-server"), tls) || + oauthMetadata(oauthWellKnown(issuer, "openid-configuration", true), tls) + if (!isMap(server) || server.issuer !== options.issuer || + (isUnDef(endpoint) && !isString(server.token_endpoint))) { + throw new Error("Invalid OAuth authorization server metadata") + } + if (isUnDef(endpoint)) { + var tokenEndpoint = oauthURL(server.token_endpoint, loopback) + checkEndpoint(tokenEndpoint) + endpoint = tokenEndpoint + } + if (needAuth && isUnDef(options.authURL)) { + var authEndpoint = oauthURL(server.authorization_endpoint, loopback) + checkEndpoint(authEndpoint) + options.authURL = String(authEndpoint) + } + if (needAuth && server.authorization_response_iss_parameter_supported === true) options.authorizationResponseIssuerRequired = true + } + var lock = new java.util.concurrent.locks.ReentrantLock() + var cached, closed = false, retryAt = 0, persistence + var controller + + // Delegate interactive login to the existing PKCE and credential-storage controller. + var prepareController = () => { + if (isDef(controller)) return controller + discover(true) + controller = ow.server.httpd.oauth2(Object.assign({ tokenStore: false }, options, { + tokenURL: String(endpoint), interactive: options.interactive === true + })) + return controller + } + if (grant === "authorization_code") { + if (isDef(binding) || isDef(tls)) throw new Error("OAuth transport profile currently requires client credentials") + if (isDef(options.authURL)) checkEndpoint(oauthURL(options.authURL, loopback)) + if (isDef(options.authURL) && isDef(endpoint)) prepareController() + } else { + if (grant !== "client_credentials") throw new Error("Unsupported OAuth grant") + if (!mtls && !isDef(options.clientSecret) && options.tokenEndpointAuthMethod !== "private_key_jwt" || + options.tokenEndpointAuthMethod === "none") throw new Error("OAuth client credentials require confidential client authentication") + if (isDef(options.tokenStore) && options.tokenStore !== false) { + var config = options.tokenStore + if (!isMap(config) || !isString(config.profile) || !config.profile.length || isUnDef(resource) || isDef(tls) || isDef(binding)) { + throw new Error("Persistent OAuth client credentials require an explicit resource and profile with bearer authentication") + } + persistence = Object.assign({}, config) + } + } + + var withLock = fn => { + if (!lock.tryLock(60, java.util.concurrent.TimeUnit.SECONDS)) throw new Error("OAuth client is busy") + try { return fn() } finally { lock.unlock() } + } + var bind = url => { + var target = oauthURL(url, loopback) + if (isUnDef(resource)) resource = target.newBuilder().query(null).build() + var path = String(resource.encodedPath()), targetPath = String(target.encodedPath()) + if (oauthOrigin(resource) !== oauthOrigin(target) || + (targetPath !== path && !targetPath.startsWith(path.endsWith("/") ? path : path + "/")) || + /%(?:2f|5c|25)/i.test(targetPath)) throw new Error("OAuth request is outside the configured resource") + } + // Isolate persisted credentials by their exact grant and resource characteristics. + var withStore = (operation, clearing) => { + if (isUnDef(persistence)) return operation() + discover() + var scope = isString(options.scope) ? Array.from(new Set(options.scope.split(" ").filter(Boolean))).sort() : [] + var fingerprint = sha256(JSON.stringify([persistence.profile, options.issuer, String(endpoint), options.clientId, + grant, String(resource), options.audience, scope, options.tokenEndpointAuthMethod, options.keyId, options.algorithm])) + var key = "oauth-m2m-v1-" + fingerprint + var store = persistence.type === "sec" ? ow.server.httpd.__oauth2SecTokenStore(persistence, "oauth-client") : persistence + if (!["withLock", "load", "save", "clear"].every(name => isFunction(store[name]))) { + throw new Error("Invalid OAuth credential store adapter") + } + var result, called = false, completed = false, active = true, failure + try { + store.withLock(key, () => { + if (!active || called) throw new Error("OAuth store lock callback invoked more than once") + called = true + try { + if (clearing) store.clear(key) + else { + var record = store.load(key) + if (isDef(record) && (!isMap(record) || record.version !== 1 || record.fingerprint !== fingerprint || + !isMap(record.token) || record.token.token_type !== "Bearer" || + !isString(record.token.access_token) || !Number.isFinite(record.expiresAt) || + !Number.isFinite(record.renewAt) || record.renewAt > record.expiresAt)) { + throw new Error("Invalid stored OAuth credential") + } + cached = isDef(record) ? { token: record.token, expiresAt: record.expiresAt, renewAt: record.renewAt } : __ + } + } catch(e) { + failure = new Error("OAuth credential storage failed") + throw failure + } + try { + var previous = cached + result = operation() + if (!clearing && cached !== previous) { + try { store.save(key, Object.assign({ version: 1, fingerprint: fingerprint }, cached)) } + catch(e) { + cached = __ + throw new Error("OAuth credential storage write failed") + } + } + completed = true + } catch(e) { failure = e; throw e } + }) + } catch(e) { + if (isDef(failure)) throw failure + throw new Error("OAuth credential storage lock failed") + } finally { active = false } + if (!completed) throw (isDef(failure) ? failure : new Error("OAuth store lock callback must run synchronously")) + return result + } + var acquire = () => { + if (grant === "authorization_code") return prepareController().authenticate() + if (isDef(cached) && now() < cached.renewAt) return cached.token + if (now() < retryAt) throw new Error("OAuth token acquisition is temporarily unavailable") + try { + discover() + var params = { grant_type: "client_credentials" } + if (isDef(options.resource)) params.resource = options.resource + var token = oauthExchange(options, String(endpoint), params, false, binding, false, tls) + var ttl = Number(token.expires_in) * 1000 + if (!isDef(token.expires_in)) ttl = 60000 + if (!isFinite(ttl) || ttl <= 0) throw new Error("Invalid OAuth access token lifetime") + var windowMs = _$(options.refreshWindowMs, "refreshWindowMs").isNumber().default(30000) + if (!isFinite(windowMs) || windowMs < 0) throw new Error("Invalid OAuth renewal window") + var scheme = isDef(binding) ? "DPoP" : "Bearer" + if (String(token.token_type || "Bearer").toLowerCase() !== scheme.toLowerCase() || + !/^[A-Za-z0-9._~+\/-]+=*$/.test(token.access_token)) throw new Error("Invalid OAuth access token scheme or credential") + token = { access_token: token.access_token, token_type: scheme, expires_in: ttl / 1000 } + var expiresAt = now() + Math.min(ttl, 86400000) + cached = { token: token, expiresAt: expiresAt, renewAt: expiresAt - Math.min(windowMs, ttl / 2) } + return token + } catch(e) { + retryAt = now() + 1000 + throw e + } + } + var getToken = () => { + if (closed) throw new Error("OAuth client is closed") + return withStore(acquire) + } + var client = Object.freeze({ + authenticate: () => withLock(() => Object.assign({}, getToken())), + getAuthStatus: () => withLock(() => isDef(controller) ? controller.getAuthStatus() : + { authenticated: !closed && isDef(cached) && now() < cached.expiresAt, expiresAt: isDef(cached) ? cached.expiresAt : null }), + clearAuth: () => withLock(() => withStore(() => { + cached = __; retryAt = 0 + if (isDef(controller)) return controller.clearAuth() + return { authenticated: false, expiresAt: null } + }, true)), + cancel: () => { if (isDef(controller)) controller.cancel() }, + close: () => { + if (isDef(controller)) controller.cancel() + withLock(() => { closed = true; cached = __ }) + } + }) + oauth.__clients.set(client, (url, method) => withLock(() => { + bind(url) + var token = getToken(), scheme = isDef(binding) ? "DPoP" : "Bearer" + if (String(token.token_type || "Bearer").toLowerCase() !== scheme.toLowerCase() || + !/^[A-Za-z0-9._~+\/-]+=*$/.test(token.access_token)) throw new Error("Invalid OAuth access token scheme or credential") + return { + authorization: scheme + " " + token.access_token, + tls: tls, + proof: isDef(binding) ? binding.sign(tokenTarget(url, loopback), method, resourceNonce, token.access_token) : __, + acceptNonce: value => { + if (isDef(binding) && safeNonce(value)) withLock(() => { resourceNonce = value }) + } + } + })) + return client + } +} + +})() diff --git a/lib/java-util-4.118.0.jar b/lib/java-util-4.119.0.jar similarity index 50% rename from lib/java-util-4.118.0.jar rename to lib/java-util-4.119.0.jar index 62a8e583..a0508ddd 100644 Binary files a/lib/java-util-4.118.0.jar and b/lib/java-util-4.119.0.jar differ diff --git a/lib/jetty-client-12.1.15.jar b/lib/jetty-client-12.1.16.jar similarity index 88% rename from lib/jetty-client-12.1.15.jar rename to lib/jetty-client-12.1.16.jar index 4da8a0ac..02d3f5a4 100644 Binary files a/lib/jetty-client-12.1.15.jar and b/lib/jetty-client-12.1.16.jar differ diff --git a/lib/jetty-compression-common-12.1.15.jar b/lib/jetty-compression-common-12.1.16.jar similarity index 69% rename from lib/jetty-compression-common-12.1.15.jar rename to lib/jetty-compression-common-12.1.16.jar index cbe3b47e..298b3cdb 100644 Binary files a/lib/jetty-compression-common-12.1.15.jar and b/lib/jetty-compression-common-12.1.16.jar differ diff --git a/lib/jetty-http-12.1.15.jar b/lib/jetty-http-12.1.16.jar similarity index 92% rename from lib/jetty-http-12.1.15.jar rename to lib/jetty-http-12.1.16.jar index dbf7c727..a0902231 100644 Binary files a/lib/jetty-http-12.1.15.jar and b/lib/jetty-http-12.1.16.jar differ diff --git a/lib/jetty-io-12.1.15.jar b/lib/jetty-io-12.1.16.jar similarity index 91% rename from lib/jetty-io-12.1.15.jar rename to lib/jetty-io-12.1.16.jar index 2c329246..e08e2c17 100644 Binary files a/lib/jetty-io-12.1.15.jar and b/lib/jetty-io-12.1.16.jar differ diff --git a/lib/jetty-util-12.1.15.jar b/lib/jetty-util-12.1.16.jar similarity index 91% rename from lib/jetty-util-12.1.15.jar rename to lib/jetty-util-12.1.16.jar index c463039e..074d996a 100644 Binary files a/lib/jetty-util-12.1.15.jar and b/lib/jetty-util-12.1.16.jar differ diff --git a/lib/jetty-websocket-core-client-12.1.15.jar b/lib/jetty-websocket-core-client-12.1.16.jar similarity index 84% rename from lib/jetty-websocket-core-client-12.1.15.jar rename to lib/jetty-websocket-core-client-12.1.16.jar index 23a502a6..db7590d5 100644 Binary files a/lib/jetty-websocket-core-client-12.1.15.jar and b/lib/jetty-websocket-core-client-12.1.16.jar differ diff --git a/lib/jetty-websocket-core-common-12.1.15.jar b/lib/jetty-websocket-core-common-12.1.16.jar similarity index 91% rename from lib/jetty-websocket-core-common-12.1.15.jar rename to lib/jetty-websocket-core-common-12.1.16.jar index b7d07182..190d814a 100644 Binary files a/lib/jetty-websocket-core-common-12.1.15.jar and b/lib/jetty-websocket-core-common-12.1.16.jar differ diff --git a/lib/jetty-websocket-jetty-api-12.1.15.jar b/lib/jetty-websocket-jetty-api-12.1.16.jar similarity index 69% rename from lib/jetty-websocket-jetty-api-12.1.15.jar rename to lib/jetty-websocket-jetty-api-12.1.16.jar index 75566509..dbe8a052 100644 Binary files a/lib/jetty-websocket-jetty-api-12.1.15.jar and b/lib/jetty-websocket-jetty-api-12.1.16.jar differ diff --git a/lib/jetty-websocket-jetty-client-12.1.15.jar b/lib/jetty-websocket-jetty-client-12.1.16.jar similarity index 82% rename from lib/jetty-websocket-jetty-client-12.1.15.jar rename to lib/jetty-websocket-jetty-client-12.1.16.jar index 56dc387f..58671e15 100644 Binary files a/lib/jetty-websocket-jetty-client-12.1.15.jar and b/lib/jetty-websocket-jetty-client-12.1.16.jar differ diff --git a/lib/jetty-websocket-jetty-common-12.1.15.jar b/lib/jetty-websocket-jetty-common-12.1.16.jar similarity index 85% rename from lib/jetty-websocket-jetty-common-12.1.15.jar rename to lib/jetty-websocket-jetty-common-12.1.16.jar index 311b35f9..b451e56a 100644 Binary files a/lib/jetty-websocket-jetty-common-12.1.15.jar and b/lib/jetty-websocket-jetty-common-12.1.16.jar differ diff --git a/lib/jline-native-4.7.0.jar b/lib/jline-native-4.7.1.jar similarity index 60% rename from lib/jline-native-4.7.0.jar rename to lib/jline-native-4.7.1.jar index dc28dd35..bca0e67c 100644 Binary files a/lib/jline-native-4.7.0.jar and b/lib/jline-native-4.7.1.jar differ diff --git a/lib/jline-reader-4.7.0.jar b/lib/jline-reader-4.7.1.jar similarity index 91% rename from lib/jline-reader-4.7.0.jar rename to lib/jline-reader-4.7.1.jar index f0e77959..e1fdd55b 100644 Binary files a/lib/jline-reader-4.7.0.jar and b/lib/jline-reader-4.7.1.jar differ diff --git a/lib/jline-terminal-4.7.0.jar b/lib/jline-terminal-4.7.1.jar similarity index 79% rename from lib/jline-terminal-4.7.0.jar rename to lib/jline-terminal-4.7.1.jar index 9dfefe55..2a6adc33 100644 Binary files a/lib/jline-terminal-4.7.0.jar and b/lib/jline-terminal-4.7.1.jar differ diff --git a/lib/jline-terminal-jni-4.7.0.jar b/lib/jline-terminal-jni-4.7.1.jar similarity index 83% rename from lib/jline-terminal-jni-4.7.0.jar rename to lib/jline-terminal-jni-4.7.1.jar index e56f7c39..c714a6ed 100644 Binary files a/lib/jline-terminal-jni-4.7.0.jar and b/lib/jline-terminal-jni-4.7.1.jar differ diff --git a/lib/jsch-2.28.8.jar b/lib/jsch-2.28.9.jar similarity index 73% rename from lib/jsch-2.28.8.jar rename to lib/jsch-2.28.9.jar index b1e6d349..41599797 100644 Binary files a/lib/jsch-2.28.8.jar and b/lib/jsch-2.28.9.jar differ diff --git a/lib/json-io-4.118.0.jar b/lib/json-io-4.119.0.jar similarity index 57% rename from lib/json-io-4.118.0.jar rename to lib/json-io-4.119.0.jar index 8d621196..713349ce 100644 Binary files a/lib/json-io-4.118.0.jar and b/lib/json-io-4.119.0.jar differ diff --git a/lib/kotlin-stdlib-2.4.21.jar b/lib/kotlin-stdlib-2.4.21.jar deleted file mode 100644 index a7025bca..00000000 Binary files a/lib/kotlin-stdlib-2.4.21.jar and /dev/null differ diff --git a/lib/kotlin-stdlib-2.5.0.jar b/lib/kotlin-stdlib-2.5.0.jar new file mode 100644 index 00000000..c82028c4 Binary files /dev/null and b/lib/kotlin-stdlib-2.5.0.jar differ diff --git a/lib/postgresql-42.7.14.jar b/lib/postgresql-42.7.15.jar similarity index 75% rename from lib/postgresql-42.7.14.jar rename to lib/postgresql-42.7.15.jar index b7dfb8c2..26ce04ee 100644 Binary files a/lib/postgresql-42.7.14.jar and b/lib/postgresql-42.7.15.jar differ diff --git a/pom.json b/pom.json index 82a71fe1..071ea293 100644 --- a/pom.json +++ b/pom.json @@ -1 +1 @@ -{"{\"artifactId\":\"rhino\"}":{"groupId":"org.mozilla","artifactId":"rhino","version":"1.9.2"},"{\"artifactId\":\"rhino-xml\"}":{"groupId":"org.mozilla","artifactId":"rhino-xml","version":"1.9.2"},"{\"artifactId\":\"rhino-engine\"}":{"groupId":"org.mozilla","artifactId":"rhino-engine","version":"1.9.2"},"{\"artifactId\":\"asciilist-j7\"}":{"groupId":"de.vandermeer","artifactId":"asciilist-j7","version":"1.0.0"},"{\"artifactId\":\"asciitable-j7\"}":{"groupId":"de.vandermeer","artifactId":"asciitable-j7","version":"1.0.1"},"{\"artifactId\":\"commons-cli\"}":{"groupId":"commons-cli","artifactId":"commons-cli","version":"1.11.0"},"{\"artifactId\":\"commons-codec\"}":{"groupId":"commons-codec","artifactId":"commons-codec","version":"1.23.0"},"{\"artifactId\":\"commons-collections4\"}":{"groupId":"org.apache.commons","artifactId":"commons-collections4","version":"4.6.0"},"{\"artifactId\":\"commons-compress\"}":{"groupId":"org.apache.commons","artifactId":"commons-compress","version":"1.28.0"},"{\"artifactId\":\"commons-csv\"}":{"groupId":"org.apache.commons","artifactId":"commons-csv","version":"1.14.1"},"{\"artifactId\":\"commons-email\"}":{"groupId":"org.apache.commons","artifactId":"commons-email","version":"1.6.0"},"{\"artifactId\":\"commons-io\"}":{"groupId":"commons-io","artifactId":"commons-io","version":"2.22.0"},"{\"artifactId\":\"commons-lang3\"}":{"groupId":"org.apache.commons","artifactId":"commons-lang3","version":"3.22.0"},"{\"artifactId\":\"commons-logging\"}":{"groupId":"commons-logging","artifactId":"commons-logging","version":"1.4.0"},"{\"artifactId\":\"commons-math3\"}":{"groupId":"org.apache.commons","artifactId":"commons-math3","version":"3.6.1"},"{\"artifactId\":\"commons-net\"}":{"groupId":"commons-net","artifactId":"commons-net","version":"3.13.0"},"{\"artifactId\":\"googleauth\"}":{"groupId":"com.warrenstrange","artifactId":"googleauth","version":"1.5.0"},"{\"artifactId\":\"gson\"}":{"groupId":"com.google.code.gson","artifactId":"gson","version":"2.15.0"},"{\"artifactId\":\"h2\"}":{"groupId":"com.h2database","artifactId":"h2","version":"2.5.252"},"{\"artifactId\":\"jackson-annotations\"}":{"groupId":"com.fasterxml.jackson.core","artifactId":"jackson-annotations","version":"2.23"},"{\"artifactId\":\"jackson-core\"}":{"groupId":"com.fasterxml.jackson.core","artifactId":"jackson-core","version":"2.23.0"},"{\"artifactId\":\"jackson-databind\"}":{"groupId":"com.fasterxml.jackson.core","artifactId":"jackson-databind","version":"2.23.0"},"{\"artifactId\":\"jackson-dataformat-toml\"}":{"groupId":"com.fasterxml.jackson.dataformat","artifactId":"jackson-dataformat-toml","version":"2.23.0"},"{\"artifactId\":\"jansi\"}":{"groupId":"org.fusesource.jansi","artifactId":"jansi","version":"1.18"},"{\"artifactId\":\"jbsdiff\"}":{"groupId":"io.sigpipe","artifactId":"jbsdiff","version":"1.0"},"{\"artifactId\":\"jetty-client\"}":{"groupId":"org.eclipse.jetty","artifactId":"jetty-client","version":"12.1.15"},"{\"artifactId\":\"jetty-http\"}":{"groupId":"org.eclipse.jetty","artifactId":"jetty-http","version":"12.1.15"},"{\"artifactId\":\"jetty-io\"}":{"groupId":"org.eclipse.jetty","artifactId":"jetty-io","version":"12.1.15"},"{\"artifactId\":\"jetty-util\"}":{"groupId":"org.eclipse.jetty","artifactId":"jetty-util","version":"12.1.15"},"{\"artifactId\":\"jetty-compression-common\"}":{"groupId":"org.eclipse.jetty.compression","artifactId":"jetty-compression-common","version":"12.1.15"},"{\"artifactId\":\"jetty-websocket-jetty-common\"}":{"groupId":"org.eclipse.jetty.websocket","artifactId":"jetty-websocket-jetty-common","version":"12.1.15"},"{\"artifactId\":\"jetty-websocket-jetty-api\"}":{"groupId":"org.eclipse.jetty.websocket","artifactId":"jetty-websocket-jetty-api","version":"12.1.15"},"{\"artifactId\":\"jetty-websocket-jetty-client\"}":{"groupId":"org.eclipse.jetty.websocket","artifactId":"jetty-websocket-jetty-client","version":"12.1.15"},"{\"artifactId\":\"jetty-websocket-core-client\"}":{"groupId":"org.eclipse.jetty.websocket","artifactId":"jetty-websocket-core-client","version":"12.1.15"},"{\"artifactId\":\"jetty-websocket-core-common\"}":{"groupId":"org.eclipse.jetty.websocket","artifactId":"jetty-websocket-core-common","version":"12.1.15"},"{\"artifactId\":\"jna-platform\"}":{"groupId":"net.java.dev.jna","artifactId":"jna-platform","version":"5.19.1"},"{\"artifactId\":\"jna\"}":{"groupId":"net.java.dev.jna","artifactId":"jna","version":"5.19.1"},"{\"artifactId\":\"postgresql\"}":{"groupId":"org.postgresql","artifactId":"postgresql","version":"42.7.14"},"{\"artifactId\":\"snmp4j\"}":{"groupId":"org.snmp4j","artifactId":"snmp4j","version":"3.13.2"},"{\"artifactId\":\"snmp4j-agent\"}":{"groupId":"org.snmp4j","artifactId":"snmp4j-agent","version":"3.10.1"},"{\"artifactId\":\"jjwt-impl\"}":{"groupId":"io.jsonwebtoken","artifactId":"jjwt-impl","version":"0.13.0"},"{\"artifactId\":\"jjwt-api\"}":{"groupId":"io.jsonwebtoken","artifactId":"jjwt-api","version":"0.13.0"},"{\"artifactId\":\"jjwt-gson\"}":{"groupId":"io.jsonwebtoken","artifactId":"jjwt-gson","version":"0.13.0"},"{\"artifactId\":\"okhttp\"}":{"groupId":"com.squareup.okhttp3","artifactId":"okhttp","version":"5.5.1"},"{\"artifactId\":\"okhttp-jvm\"}":{"groupId":"com.squareup.okhttp3","artifactId":"okhttp-jvm","version":"5.5.1"},"{\"artifactId\":\"kotlin-stdlib\"}":{"groupId":"org.jetbrains.kotlin","artifactId":"kotlin-stdlib","version":"2.4.21"},"{\"artifactId\":\"okio\"}":{"groupId":"com.squareup.okio","artifactId":"okio","version":"3.18.2"},"{\"artifactId\":\"okio-jvm\"}":{"groupId":"com.squareup.okio","artifactId":"okio-jvm","version":"3.18.2"},"{\"artifactId\":\"dnsjava\"}":{"groupId":"dnsjava","artifactId":"dnsjava","version":"3.7.1"},"{\"artifactId\":\"slf4j-api\"}":{"groupId":"org.slf4j","artifactId":"slf4j-api","version":"2.0.20"},"{\"artifactId\":\"slf4j-nop\"}":{"groupId":"org.slf4j","artifactId":"slf4j-nop","version":"2.0.20"},"{\"artifactId\":\"jsch\"}":{"groupId":"com.github.mwiede","artifactId":"jsch","version":"2.28.8"},"{\"artifactId\":\"sql-formatter\"}":{"groupId":"com.github.vertical-blank","artifactId":"sql-formatter","version":"2.0.5"},"{\"artifactId\":\"semver4j\"}":{"groupId":"org.semver4j","artifactId":"semver4j","version":"6.1.0"},"{\"artifactId\":\"ojdbc17\"}":{"groupId":"com.oracle.database.jdbc","artifactId":"ojdbc17","version":"23.26.4.0.0"},"{\"artifactId\":\"jakarta.mail\"}":{"groupId":"com.sun.mail","artifactId":"jakarta.mail","version":"1.6.8"},"{\"artifactId\":\"json-io\"}":{"groupId":"com.cedarsoftware","artifactId":"json-io","version":"4.118.0"},"{\"artifactId\":\"java-util\"}":{"groupId":"com.cedarsoftware","artifactId":"java-util","version":"4.118.0"},"{\"artifactId\":\"jline-reader\"}":{"groupId":"org.jline","artifactId":"jline-reader","version":"4.7.0"},"{\"artifactId\":\"jline-terminal\"}":{"groupId":"org.jline","artifactId":"jline-terminal","version":"4.7.0"},"{\"artifactId\":\"jline-terminal-jni\"}":{"groupId":"org.jline","artifactId":"jline-terminal-jni","version":"4.7.0"},"{\"artifactId\":\"jline-native\"}":{"groupId":"org.jline","artifactId":"jline-native","version":"4.7.0"},"{\"artifactId\":\"jackson-jq\"}":{"groupId":"net.thisptr","artifactId":"jackson-jq","version":"1.6.5"},"{\"artifactId\":\"joni\"}":{"groupId":"org.jruby.joni","artifactId":"joni","version":"2.2.12"},"{\"artifactId\":\"jcodings\"}":{"groupId":"org.jruby.jcodings","artifactId":"jcodings","version":"1.0.67"},"{\"artifactId\":\"jakarta.xml.bind-api\"}":{"groupId":"jakarta.xml.bind","artifactId":"jakarta.xml.bind-api","version":"4.0.5"},"{\"artifactId\":\"jakarta.activation-api\"}":{"groupId":"jakarta.activation","artifactId":"jakarta.activation-api","version":"2.1.4"}} \ No newline at end of file +{"{\"artifactId\":\"rhino\"}":{"groupId":"org.mozilla","artifactId":"rhino","version":"1.9.2"},"{\"artifactId\":\"rhino-xml\"}":{"groupId":"org.mozilla","artifactId":"rhino-xml","version":"1.9.2"},"{\"artifactId\":\"rhino-engine\"}":{"groupId":"org.mozilla","artifactId":"rhino-engine","version":"1.9.2"},"{\"artifactId\":\"asciilist-j7\"}":{"groupId":"de.vandermeer","artifactId":"asciilist-j7","version":"1.0.0"},"{\"artifactId\":\"asciitable-j7\"}":{"groupId":"de.vandermeer","artifactId":"asciitable-j7","version":"1.0.1"},"{\"artifactId\":\"commons-cli\"}":{"groupId":"commons-cli","artifactId":"commons-cli","version":"1.11.0"},"{\"artifactId\":\"commons-codec\"}":{"groupId":"commons-codec","artifactId":"commons-codec","version":"1.23.0"},"{\"artifactId\":\"commons-collections4\"}":{"groupId":"org.apache.commons","artifactId":"commons-collections4","version":"4.6.0"},"{\"artifactId\":\"commons-compress\"}":{"groupId":"org.apache.commons","artifactId":"commons-compress","version":"1.28.0"},"{\"artifactId\":\"commons-csv\"}":{"groupId":"org.apache.commons","artifactId":"commons-csv","version":"1.14.1"},"{\"artifactId\":\"commons-email\"}":{"groupId":"org.apache.commons","artifactId":"commons-email","version":"1.6.0"},"{\"artifactId\":\"commons-io\"}":{"groupId":"commons-io","artifactId":"commons-io","version":"2.22.0"},"{\"artifactId\":\"commons-lang3\"}":{"groupId":"org.apache.commons","artifactId":"commons-lang3","version":"3.22.0"},"{\"artifactId\":\"commons-logging\"}":{"groupId":"commons-logging","artifactId":"commons-logging","version":"1.4.0"},"{\"artifactId\":\"commons-math3\"}":{"groupId":"org.apache.commons","artifactId":"commons-math3","version":"3.6.1"},"{\"artifactId\":\"commons-net\"}":{"groupId":"commons-net","artifactId":"commons-net","version":"3.13.0"},"{\"artifactId\":\"googleauth\"}":{"groupId":"com.warrenstrange","artifactId":"googleauth","version":"1.5.0"},"{\"artifactId\":\"gson\"}":{"groupId":"com.google.code.gson","artifactId":"gson","version":"2.15.0"},"{\"artifactId\":\"h2\"}":{"groupId":"com.h2database","artifactId":"h2","version":"2.5.252"},"{\"artifactId\":\"jackson-annotations\"}":{"groupId":"com.fasterxml.jackson.core","artifactId":"jackson-annotations","version":"2.23"},"{\"artifactId\":\"jackson-core\"}":{"groupId":"com.fasterxml.jackson.core","artifactId":"jackson-core","version":"2.23.0"},"{\"artifactId\":\"jackson-databind\"}":{"groupId":"com.fasterxml.jackson.core","artifactId":"jackson-databind","version":"2.23.0"},"{\"artifactId\":\"jackson-dataformat-toml\"}":{"groupId":"com.fasterxml.jackson.dataformat","artifactId":"jackson-dataformat-toml","version":"2.23.0"},"{\"artifactId\":\"jansi\"}":{"groupId":"org.fusesource.jansi","artifactId":"jansi","version":"1.18"},"{\"artifactId\":\"jbsdiff\"}":{"groupId":"io.sigpipe","artifactId":"jbsdiff","version":"1.0"},"{\"artifactId\":\"jetty-client\"}":{"groupId":"org.eclipse.jetty","artifactId":"jetty-client","version":"12.1.16"},"{\"artifactId\":\"jetty-http\"}":{"groupId":"org.eclipse.jetty","artifactId":"jetty-http","version":"12.1.16"},"{\"artifactId\":\"jetty-io\"}":{"groupId":"org.eclipse.jetty","artifactId":"jetty-io","version":"12.1.16"},"{\"artifactId\":\"jetty-util\"}":{"groupId":"org.eclipse.jetty","artifactId":"jetty-util","version":"12.1.16"},"{\"artifactId\":\"jetty-compression-common\"}":{"groupId":"org.eclipse.jetty.compression","artifactId":"jetty-compression-common","version":"12.1.16"},"{\"artifactId\":\"jetty-websocket-jetty-common\"}":{"groupId":"org.eclipse.jetty.websocket","artifactId":"jetty-websocket-jetty-common","version":"12.1.16"},"{\"artifactId\":\"jetty-websocket-jetty-api\"}":{"groupId":"org.eclipse.jetty.websocket","artifactId":"jetty-websocket-jetty-api","version":"12.1.16"},"{\"artifactId\":\"jetty-websocket-jetty-client\"}":{"groupId":"org.eclipse.jetty.websocket","artifactId":"jetty-websocket-jetty-client","version":"12.1.16"},"{\"artifactId\":\"jetty-websocket-core-client\"}":{"groupId":"org.eclipse.jetty.websocket","artifactId":"jetty-websocket-core-client","version":"12.1.16"},"{\"artifactId\":\"jetty-websocket-core-common\"}":{"groupId":"org.eclipse.jetty.websocket","artifactId":"jetty-websocket-core-common","version":"12.1.16"},"{\"artifactId\":\"jna-platform\"}":{"groupId":"net.java.dev.jna","artifactId":"jna-platform","version":"5.19.1"},"{\"artifactId\":\"jna\"}":{"groupId":"net.java.dev.jna","artifactId":"jna","version":"5.19.1"},"{\"artifactId\":\"postgresql\"}":{"groupId":"org.postgresql","artifactId":"postgresql","version":"42.7.15"},"{\"artifactId\":\"snmp4j\"}":{"groupId":"org.snmp4j","artifactId":"snmp4j","version":"3.13.2"},"{\"artifactId\":\"snmp4j-agent\"}":{"groupId":"org.snmp4j","artifactId":"snmp4j-agent","version":"3.10.1"},"{\"artifactId\":\"jjwt-impl\"}":{"groupId":"io.jsonwebtoken","artifactId":"jjwt-impl","version":"0.13.0"},"{\"artifactId\":\"jjwt-api\"}":{"groupId":"io.jsonwebtoken","artifactId":"jjwt-api","version":"0.13.0"},"{\"artifactId\":\"jjwt-gson\"}":{"groupId":"io.jsonwebtoken","artifactId":"jjwt-gson","version":"0.13.0"},"{\"artifactId\":\"okhttp\"}":{"groupId":"com.squareup.okhttp3","artifactId":"okhttp","version":"5.5.1"},"{\"artifactId\":\"okhttp-jvm\"}":{"groupId":"com.squareup.okhttp3","artifactId":"okhttp-jvm","version":"5.5.1"},"{\"artifactId\":\"kotlin-stdlib\"}":{"groupId":"org.jetbrains.kotlin","artifactId":"kotlin-stdlib","version":"2.5.0"},"{\"artifactId\":\"okio\"}":{"groupId":"com.squareup.okio","artifactId":"okio","version":"3.18.2"},"{\"artifactId\":\"okio-jvm\"}":{"groupId":"com.squareup.okio","artifactId":"okio-jvm","version":"3.18.2"},"{\"artifactId\":\"dnsjava\"}":{"groupId":"dnsjava","artifactId":"dnsjava","version":"3.7.1"},"{\"artifactId\":\"slf4j-api\"}":{"groupId":"org.slf4j","artifactId":"slf4j-api","version":"2.0.20"},"{\"artifactId\":\"slf4j-nop\"}":{"groupId":"org.slf4j","artifactId":"slf4j-nop","version":"2.0.20"},"{\"artifactId\":\"jsch\"}":{"groupId":"com.github.mwiede","artifactId":"jsch","version":"2.28.9"},"{\"artifactId\":\"sql-formatter\"}":{"groupId":"com.github.vertical-blank","artifactId":"sql-formatter","version":"2.0.5"},"{\"artifactId\":\"semver4j\"}":{"groupId":"org.semver4j","artifactId":"semver4j","version":"6.1.0"},"{\"artifactId\":\"ojdbc17\"}":{"groupId":"com.oracle.database.jdbc","artifactId":"ojdbc17","version":"23.26.4.0.0"},"{\"artifactId\":\"jakarta.mail\"}":{"groupId":"com.sun.mail","artifactId":"jakarta.mail","version":"1.6.8"},"{\"artifactId\":\"json-io\"}":{"groupId":"com.cedarsoftware","artifactId":"json-io","version":"4.119.0"},"{\"artifactId\":\"java-util\"}":{"groupId":"com.cedarsoftware","artifactId":"java-util","version":"4.119.0"},"{\"artifactId\":\"jline-reader\"}":{"groupId":"org.jline","artifactId":"jline-reader","version":"4.7.1"},"{\"artifactId\":\"jline-terminal\"}":{"groupId":"org.jline","artifactId":"jline-terminal","version":"4.7.1"},"{\"artifactId\":\"jline-terminal-jni\"}":{"groupId":"org.jline","artifactId":"jline-terminal-jni","version":"4.7.1"},"{\"artifactId\":\"jline-native\"}":{"groupId":"org.jline","artifactId":"jline-native","version":"4.7.1"},"{\"artifactId\":\"jackson-jq\"}":{"groupId":"net.thisptr","artifactId":"jackson-jq","version":"1.6.5"},"{\"artifactId\":\"joni\"}":{"groupId":"org.jruby.joni","artifactId":"joni","version":"2.2.12"},"{\"artifactId\":\"jcodings\"}":{"groupId":"org.jruby.jcodings","artifactId":"jcodings","version":"1.0.67"},"{\"artifactId\":\"jakarta.xml.bind-api\"}":{"groupId":"jakarta.xml.bind","artifactId":"jakarta.xml.bind-api","version":"4.0.5"},"{\"artifactId\":\"jakarta.activation-api\"}":{"groupId":"jakarta.activation","artifactId":"jakarta.activation-api","version":"2.1.4"}} \ No newline at end of file diff --git a/pom.xml b/pom.xml index 81c7cfcd..cc847afe 100644 --- a/pom.xml +++ b/pom.xml @@ -195,12 +195,12 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/ma com.cedarsoftware json-io - 4.118.0 + 4.119.0 com.cedarsoftware java-util - 4.118.0 + 4.119.0 com.h2database @@ -265,72 +265,72 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/ma org.eclipse.jetty jetty-client - 12.1.15 + 12.1.16 org.eclipse.jetty jetty-http - 12.1.15 + 12.1.16 org.eclipse.jetty jetty-io - 12.1.15 + 12.1.16 org.eclipse.jetty jetty-util - 12.1.15 + 12.1.16 org.eclipse.jetty.compression jetty-compression-common - 12.1.15 + 12.1.16 org.eclipse.jetty.websocket jetty-websocket-jetty-common - 12.1.15 + 12.1.16 org.eclipse.jetty.websocket jetty-websocket-jetty-api - 12.1.15 + 12.1.16 org.eclipse.jetty.websocket jetty-websocket-jetty-client - 12.1.15 + 12.1.16 org.eclipse.jetty.websocket jetty-websocket-core-client - 12.1.15 + 12.1.16 org.eclipse.jetty.websocket jetty-websocket-core-common - 12.1.15 + 12.1.16 org.jline jline-reader - 4.7.0 + 4.7.1 org.jline jline-terminal - 4.7.0 + 4.7.1 org.jline jline-terminal-jni - 4.7.0 + 4.7.1 org.jline jline-native - 4.7.0 + 4.7.1 net.java.dev.jna @@ -345,7 +345,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/ma org.postgresql postgresql - 42.7.14 + 42.7.15 org.snmp4j @@ -385,7 +385,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/ma org.jetbrains.kotlin kotlin-stdlib - 2.4.21 + 2.5.0 com.squareup.okio @@ -415,7 +415,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/ma com.github.mwiede jsch - 2.28.8 + 2.28.9 com.github.vertical-blank diff --git a/skills/ojob-common-jobs/SKILL.md b/skills/ojob-common-jobs/SKILL.md index 5a431017..4a3ecb2e 100644 --- a/skills/ojob-common-jobs/SKILL.md +++ b/skills/ojob-common-jobs/SKILL.md @@ -119,3 +119,13 @@ todo: ``` Run `ojob records-shortcuts.yaml`. Expect `record: 1` and `record: 2`; use `records: []` to exercise `no records`. The set job writes `payload` to `skill.records`; the conditional and producer read that named store explicitly, without relying on argument propagation between todo entries. The condition is trusted JavaScript evaluated by `ojob if`; never build it by interpolating untrusted data. `each` is the engine's producer/consumer facility, with each consumer receiving the emitted record. Business arguments on shortcuts remain under `args`. Both forms should produce the same records; check contents rather than depending on parallel output order. + + +## OAuth-protected jobs + +Use the native `oauth` map when exposing HTTP or MCP services. Set the exact +issuer and public resource URL and configure scopes for each operation. For +an OpenAF issuer, include `oJobOAuth.yaml` and call the `oauthServerStart` +shortcut with an issuer map under `oauth`. Provision machine clients with +secret references and assign each a resource audience. A certificate-bound +HTTP service also needs the Java listener's `tlsProfile` trust configuration. diff --git a/skills/openaf-javascript/references/http-process.md b/skills/openaf-javascript/references/http-process.md index 1d1d9459..34758b07 100644 --- a/skills/openaf-javascript/references/http-process.md +++ b/skills/openaf-javascript/references/http-process.md @@ -5,3 +5,13 @@ Read the selected helper in [core source](https://github.com/openaf/openaf/blob/ For HTTP, choose JSON, text, or bytes explicitly using supported methods. Verify whether errors throw or return data, where status/headers are exposed, and whether the operation is synchronous or returns an oPromise. Inspect `$fetch` options in the [additional helpers guide](https://github.com/openaf/openaf/blob/master/docs/openaf-dollar-functions.md#network-and-process-helpers). Use timeouts supported by that API, preserve authentication externally, and test a non-success response as well as valid data. For `$sh`, inspect execution and result collection methods before reading exit code, stdout, or stderr. Pass data using supported argument/input mechanisms; interpolating untrusted input into a command string invokes shell parsing. An exit code of zero does not prove a workflow succeeded: assert expected output or effects too. Test a failing command with harmless fixtures. Preserve output intended for machine parsing separately from diagnostics. + + +## OAuth for HTTP clients + +For service accounts, pass `auth: { type: "oauth2", issuer, clientId, +clientSecretEnv, resource, scope }` to `$rest()`. For reuse, initialize +`ow.loadServer()`, construct `ow.server.oauth.client(options)` and pass the +instance as `auth` to REST or MCP HTTP clients. Discovery must associate the +credentials with a trusted issuer. Keep client secrets in environment or +`$sec` references. Bind each client to one resource audience. diff --git a/skills/openaf-mcp/SKILL.md b/skills/openaf-mcp/SKILL.md index 9f159e7f..1ed8a764 100644 --- a/skills/openaf-mcp/SKILL.md +++ b/skills/openaf-mcp/SKILL.md @@ -37,6 +37,11 @@ Use [the advanced MCP guide](https://github.com/openaf/openaf/blob/master/docs/m Read [OAuth and token storage](https://github.com/openaf/openaf/blob/master/docs/mcp-oauth.md) only when needed. Bearer and client-credentials modes differ from delegated authorization-code login. For delegated callback login, use `auth.callback: true`, a registered loopback URI with an explicit port, and PKCE-compatible provider configuration. MCP persistence is opt-in through `auth.tokenStore`, for example `{ type: "sec", profile: "work" }`. Use `interactive: false` for unattended operation; never log tokens. `getAuthStatus()` is non-secret inspection; `clearAuth()` removes local credentials and does not revoke provider consent. Do not replay a mutating tool call merely because authentication failed. +For a reusable machine credential, create an `ow.server.oauth.client(options)` +and pass it as `auth` to an HTTP `$mcp()` connection. The same instance can be +used with `$rest()` for the same protected resource. Close the shared client +after all borrowers finish. Use a separate instance for each resource audience. + ## Local example Save as `dummy-tool.js` (also bundled in [assets/dummy-tool.js](assets/dummy-tool.js)): diff --git a/src/com/nwu/httpd/NanoHTTPD.java b/src/com/nwu/httpd/NanoHTTPD.java index bd169c95..d1fc40c2 100644 --- a/src/com/nwu/httpd/NanoHTTPD.java +++ b/src/com/nwu/httpd/NanoHTTPD.java @@ -784,6 +784,10 @@ private void decodeHeader(BufferedReader in, Map pre, Map pre, Map keyEntries = new ArrayList<>(); + for (String alias : Collections.list(keys.aliases())) { + if (keys.isKeyEntry(alias)) keyEntries.add(alias); + } + // One client identity per TLS context avoids ambiguous certificate selection. + if (keyEntries.size() != 1 || keys.getCertificate(keyEntries.get(0)) == null) { + throw new GeneralSecurityException("The OAuth TLS profile requires one client certificate"); + } + KeyManagerFactory managers = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + managers.init(keys, password.toCharArray()); + TrustManager[] trust = trustManagers(trustFile, trustPassword); + if (trust.length != 1 || !(trust[0] instanceof X509TrustManager)) { + throw new GeneralSecurityException("No X.509 trust manager available"); + } + trustManager = (X509TrustManager) trust[0]; + SSLContext context = SSLContext.getInstance("TLS"); + context.init(managers.getKeyManagers(), trust, null); + sockets = context.getSocketFactory(); + } + + public static TrustManager[] trustManagers(String file, String password) throws GeneralSecurityException, IOException { + TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + factory.init(file == null ? null : loadPkcs12(file, password)); + return factory.getTrustManagers(); + } + + private static KeyStore loadPkcs12(String file, String password) throws GeneralSecurityException, IOException { + KeyStore keys = KeyStore.getInstance("PKCS12"); + try (InputStream input = Files.newInputStream(Path.of(file))) { + keys.load(input, password.toCharArray()); + } + return keys; + } + + public X509TrustManager getTrustManager() { + return trustManager; + } + + public SSLSocketFactory getSocketFactory() { + return sockets; + } +} diff --git a/src/openaf/oauth/HybridTlsProfile.java b/src/openaf/oauth/HybridTlsProfile.java new file mode 100644 index 00000000..035ac89e --- /dev/null +++ b/src/openaf/oauth/HybridTlsProfile.java @@ -0,0 +1,103 @@ +package openaf.oauth; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.Socket; +import java.security.GeneralSecurityException; +import java.security.KeyStore; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509TrustManager; + +/** Isolates an RFC 10024 TLS profile from the JVM-wide TLS defaults. */ +public final class HybridTlsProfile extends SSLSocketFactory { + private static final String GROUP = "X25519MLKEM768"; + + private final X509TrustManager trustManager; + private final SSLSocketFactory delegate; + + public HybridTlsProfile() throws GeneralSecurityException, IOException { + // Use the VM's trusted roots and give the profile its own TLS session cache. + TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + factory.init((KeyStore) null); + TrustManager[] managers = factory.getTrustManagers(); + if (managers.length != 1 || !(managers[0] instanceof X509TrustManager)) { + throw new GeneralSecurityException("No default X.509 trust manager available"); + } + trustManager = (X509TrustManager) managers[0]; + SSLContext context = SSLContext.getInstance("TLSv1.3", "SunJSSE"); + context.init(null, managers, null); + delegate = context.getSocketFactory(); + + try (Socket probe = createSocket()) { + // Validate that the provider accepts the per-socket configuration. + } + } + + public SSLSocketFactory getSocketFactory() { + return this; + } + + public X509TrustManager getTrustManager() { + return trustManager; + } + + private Socket configure(Socket socket) throws IOException { + try { + SSLSocket ssl = (SSLSocket) socket; + SSLParameters parameters = ssl.getSSLParameters(); + parameters.setProtocols(new String[] { "TLSv1.3" }); + parameters.setNamedGroups(new String[] { GROUP }); + parameters.setEndpointIdentificationAlgorithm("HTTPS"); + ssl.setSSLParameters(parameters); + return ssl; + } catch (RuntimeException e) { + socket.close(); + throw new IOException("Hybrid TLS socket configuration failed", e); + } + } + + @Override + public String[] getDefaultCipherSuites() { + return delegate.getDefaultCipherSuites(); + } + + @Override + public String[] getSupportedCipherSuites() { + return delegate.getSupportedCipherSuites(); + } + + @Override + public Socket createSocket() throws IOException { + return configure(delegate.createSocket()); + } + + @Override + public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException { + return configure(delegate.createSocket(socket, host, port, autoClose)); + } + + @Override + public Socket createSocket(String host, int port) throws IOException { + return configure(delegate.createSocket(host, port)); + } + + @Override + public Socket createSocket(String host, int port, InetAddress localAddress, int localPort) throws IOException { + return configure(delegate.createSocket(host, port, localAddress, localPort)); + } + + @Override + public Socket createSocket(InetAddress host, int port) throws IOException { + return configure(delegate.createSocket(host, port)); + } + + @Override + public Socket createSocket(InetAddress host, int port, InetAddress localAddress, int localPort) throws IOException { + return configure(delegate.createSocket(host, port, localAddress, localPort)); + } +} diff --git a/src/openaf/oauth/MLDSA65.java b/src/openaf/oauth/MLDSA65.java new file mode 100644 index 00000000..5a80a8b2 --- /dev/null +++ b/src/openaf/oauth/MLDSA65.java @@ -0,0 +1,69 @@ +package openaf.oauth; + +import io.jsonwebtoken.security.KeyPairBuilder; +import io.jsonwebtoken.security.SecureRequest; +import io.jsonwebtoken.security.SignatureAlgorithm; +import io.jsonwebtoken.security.SignatureException; +import io.jsonwebtoken.security.VerifySecureDigestRequest; + +import java.io.IOException; +import java.io.InputStream; +import java.security.GeneralSecurityException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.Signature; + +/** Adapts the RFC 9964 ML-DSA-65 JWS algorithm to a JCA provider. */ +public final class MLDSA65 implements SignatureAlgorithm { + public static final MLDSA65 INSTANCE = new MLDSA65(); + + private MLDSA65() { + } + + @Override + public String getId() { + return "ML-DSA-65"; + } + + @Override + public KeyPairBuilder keyPair() { + throw new UnsupportedOperationException("Supply an ML-DSA-65 key from a JCA key provider"); + } + + @Override + public byte[] digest(SecureRequest request) { + try { + // Use pure ML-DSA with the provider's default empty context. + Signature signature = request.getProvider() == null + ? Signature.getInstance(getId()) + : Signature.getInstance(getId(), request.getProvider()); + signature.initSign(request.getKey(), request.getSecureRandom()); + update(signature, request.getPayload()); + return signature.sign(); + } catch (GeneralSecurityException | IOException e) { + throw new SignatureException("ML-DSA-65 signing failed", e); + } + } + + @Override + public boolean verify(VerifySecureDigestRequest request) { + try { + Signature signature = request.getProvider() == null + ? Signature.getInstance(getId()) + : Signature.getInstance(getId(), request.getProvider()); + signature.initVerify(request.getKey()); + update(signature, request.getPayload()); + return signature.verify(request.getDigest()); + } catch (GeneralSecurityException | IOException e) { + throw new SignatureException("ML-DSA-65 verification failed", e); + } + } + + private static void update(Signature signature, InputStream input) throws GeneralSecurityException, IOException { + byte[] buffer = new byte[4096]; + int count; + while ((count = input.read(buffer)) != -1) { + signature.update(buffer, 0, count); + } + } +} diff --git a/src/openaf/plugins/HTTPServer.java b/src/openaf/plugins/HTTPServer.java index 8a81c0cc..9de9afa6 100644 --- a/src/openaf/plugins/HTTPServer.java +++ b/src/openaf/plugins/HTTPServer.java @@ -41,6 +41,16 @@ import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; +import com.sun.net.httpserver.HttpsExchange; +import com.sun.net.httpserver.HttpsParameters; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLPeerUnverifiedException; +import java.security.MessageDigest; +import java.security.cert.Certificate; +import java.util.Base64; +import java.util.Collections; +import java.util.WeakHashMap; +import openaf.oauth.ClientCertificateTlsProfile; import com.sun.net.httpserver.HttpsConfigurator; import com.sun.net.httpserver.HttpsServer; import javax.net.ssl.SSLContext; @@ -146,6 +156,12 @@ private static void rejectRequestBody(HttpExchange exchange, RequestBodyExceptio } protected String impl; protected boolean isSecure = false; + private boolean oauthMutualTls = false; + private static final Map OAUTH_TLS_PEERS = Collections.synchronizedMap(new WeakHashMap<>()); + + public static String oauthPeerThumbprint(Scriptable request) { + return OAUTH_TLS_PEERS.get(request); + } protected Map javaHandlers = new ConcurrentHashMap<>(); protected String defaultHandler = null; @@ -431,12 +447,20 @@ public void log(Type type, long id, String message) { *
*/ @JSConstructor - public void newHTTPd(int port, Object host, String keyStorePath, Object password, Object errorFunction, Object ws, int timeout, String aImpl) throws IOException { + public void newHTTPd(int port, Object host, String keyStorePath, Object password, Object errorFunction, Object ws, int timeout, String aImpl, Object tlsProfile) throws IOException { + Scriptable profile = tlsProfile instanceof Scriptable && !(tlsProfile instanceof Undefined) ? (Scriptable) tlsProfile : null; + boolean oauthTls = profile != null; + Object requireClientAuth = oauthTls ? ScriptableObject.getProperty(profile, "clientAuth") : null; + oauthMutualTls = oauthTls && !Boolean.FALSE.equals(requireClientAuth); + if (oauthTls && (!"java".equals(aImpl) || keyStorePath == null || "undefined".equals(keyStorePath) + || password == null || password instanceof Undefined)) { + throw new IOException("OAuth TLS configuration requires a Java HTTPS listener"); + } if (port <= 0 && (!"java".equals(aImpl) || (keyStorePath != null && !keyStorePath.equals("undefined")))) { port = findRandomOpenPortOnAllLocalInterfaces(); } - if ((keyStorePath != null && !keyStorePath.equals("undefined") && password != null && !(password instanceof Undefined)) ) { + if (!oauthTls && (keyStorePath != null && !keyStorePath.equals("undefined") && password != null && !(password instanceof Undefined))) { USE_JAVA_HTTP_SERVER = false; USE_NWU2 = true; this.impl = "nwu2"; // Default to NWU2 if keyStorePath is provided @@ -455,7 +479,7 @@ public void newHTTPd(int port, Object host, String keyStorePath, Object password if (USE_JAVA_HTTP_SERVER) { // Use Java built-in HTTP server implementation - initializeJavaHttpServer(Math.max(0, port), host, keyStorePath, password, errorFunction); + initializeJavaHttpServer(Math.max(0, port), host, keyStorePath, password, errorFunction, profile); port = serverport; } else { // Use existing NWU implementation @@ -465,7 +489,7 @@ public void newHTTPd(int port, Object host, String keyStorePath, Object password id = Integer.toString(port) + this.hashCode(); } - private void initializeJavaHttpServer(int port, Object host, String keyStorePath, Object password, Object errorFunction) throws IOException { + private void initializeJavaHttpServer(int port, Object host, String keyStorePath, Object password, Object errorFunction, Scriptable tlsProfile) throws IOException { InetSocketAddress address; if (host == null || host instanceof Undefined) { address = new InetSocketAddress(port); @@ -502,8 +526,28 @@ private void initializeJavaHttpServer(int port, Object host, String keyStorePath javax.net.ssl.KeyManagerFactory kmf = javax.net.ssl.KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, passwordChars); - sslContext.init(kmf.getKeyManagers(), null, null); - javaHttpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext)); + // Client identity is established by JSSE before serving the HTTP request. + if (oauthMutualTls) { + Object file = ScriptableObject.getProperty(tlsProfile, "trustStore"); + Object passwordEnv = ScriptableObject.getProperty(tlsProfile, "trustStorePasswordEnv"); + if (!(file instanceof CharSequence) || !(passwordEnv instanceof CharSequence)) { + throw new IOException("OAuth mutual TLS requires a client trust store"); + } + String trustPassword = System.getenv(passwordEnv.toString()); + if (trustPassword == null) throw new IOException("OAuth client trust store password unavailable"); + sslContext.init(kmf.getKeyManagers(), ClientCertificateTlsProfile.trustManagers(file.toString(), trustPassword), null); + javaHttpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext) { + @Override + public void configure(HttpsParameters parameters) { + SSLParameters ssl = getSSLContext().getDefaultSSLParameters(); + ssl.setNeedClientAuth(true); + parameters.setSSLParameters(ssl); + } + }); + } else { + sslContext.init(kmf.getKeyManagers(), null, null); + javaHttpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext)); + } javaExecutor = newJavaExecutor(); javaHttpsServer.setExecutor(javaExecutor); @@ -1424,6 +1468,21 @@ private Object convertHttpExchangeToRequest(HttpExchange exchange) throws IOExce request.put("path", request, exchange.getRequestURI().getPath()); request.put("query", request, exchange.getRequestURI().getQuery()); + // The thumbprint is available only for a TLS-authenticated exchange. + if (oauthMutualTls && exchange instanceof HttpsExchange) { + try { + Certificate[] peer = ((HttpsExchange) exchange).getSSLSession().getPeerCertificates(); + if (peer.length > 0) { + byte[] digest = MessageDigest.getInstance("SHA-256").digest(peer[0].getEncoded()); + OAUTH_TLS_PEERS.put(request, Base64.getUrlEncoder().withoutPadding().encodeToString(digest)); + } + } catch (SSLPeerUnverifiedException ignored) { + // Requests without verified evidence cannot use a certificate-bound token. + } catch (java.security.GeneralSecurityException e) { + throw new IOException("Cannot obtain OAuth TLS peer identity", e); + } + } + // Headers Scriptable headers = cx.newObject((Scriptable) AFCmdBase.jse.getGlobalscope()); exchange.getRequestHeaders().forEach((key, values) -> { diff --git a/tests/autoTestAll.AI.js b/tests/autoTestAll.AI.js index 49f86e84..ef58f96a 100644 --- a/tests/autoTestAll.AI.js +++ b/tests/autoTestAll.AI.js @@ -789,7 +789,8 @@ delta: {} } ] - } + }, + { choices: [], usage: { prompt_tokens: 80, completion_tokens: 5, total_tokens: 85 } } ]); } @@ -808,15 +809,21 @@ delta: {} } ] - } + }, + { choices: [], usage: { prompt_tokens: 90, completion_tokens: 2, total_tokens: 92 } } ]); }; var res = g.rawPromptStream("use tool", "gpt-6-luna", __, false, [ "echo" ]); requests.forEach(function(body) { + ow.test.assert(body.stream_options.include_usage, true, "Official Chat requests their terminal usage frame") ow.test.assert(body.reasoning_effort, "none", "Luna native tools use the Chat Completions compatibility effort") ow.test.assert(Object.prototype.hasOwnProperty.call(body, "temperature"), false, "Streaming leaves temperature to the provider") }) + var stats = g.getLastStats() + ow.test.assert(stats.tokens.total, 92, "Legacy usage still describes the last model call") + ow.test.assert(stats.rounds.map(round => round.tokens.total), [85, 92], "Terminal usage from each native tool round") + ow.test.assert(stats.operationTokens.total, 177, "Operation usage counts each round once") ow.test.assert(res.content, "done", "Problem finishing OpenAI streaming tool recursion."); ow.test.assert(requests.length, 2, "Problem with number of OpenAI streaming tool recursion requests."); ow.test.assert(requests[1].messages.length, 3, "Problem duplicating OpenAI streaming tool recursion messages."); diff --git a/tests/autoTestAll.MCP.js b/tests/autoTestAll.MCP.js index 52a24642..76656d08 100644 --- a/tests/autoTestAll.MCP.js +++ b/tests/autoTestAll.MCP.js @@ -429,6 +429,359 @@ }); }; + // Calls replyJSONRPC directly with a synthetic HTTP request (header names as the HTTP server lowercases them) + var replyRPC = function(fns, body, header, opts) { + var r = ow.server.httpd.replyJSONRPC(__, { method: "POST", uri: "/mcp", header: header || {}, files: { postData: stringify(body, __, "") } }, fns, function() {}, function() {}, merge({ modern: true }, opts || {})) + return { status: r.status, body: jsonParse(r.data) } + } + var modernMeta = { "io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": {} } + + exports.testMCPModernServerValidatesRequestHeaders = function() { + ow.loadServer() + var fns = { + "tools/call": params => ({ content: [{ type: "text", text: "ok:" + params.name }], isError: false }), + "tools/list": () => ({ tools: [] }) + } + var call = name => ({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: name, arguments: {}, _meta: modernMeta } }) + var good = { "mcp-protocol-version": "2026-07-28", "mcp-method": "tools/call", "mcp-name": "ping" } + + // Valid headers + var res = replyRPC(fns, call("ping"), good) + ow.test.assert(res.status, 200, "Matching request headers should be accepted.") + ow.test.assert(res.body.result.content[0].text, "ok:ping", "Matching request headers should reach the method.") + res = replyRPC(fns, call("ping"), { "MCP-PROTOCOL-VERSION": "2026-07-28", "Mcp-Method": "tools/call", "MCP-NAME": "ping" }) + ow.test.assert(res.status, 200, "Header names should be matched case-insensitively.") + res = replyRPC(fns, { jsonrpc: "2.0", id: 2, method: "tools/list", params: { _meta: modernMeta } }, { "mcp-protocol-version": "2026-07-28", "mcp-method": "tools/list" }) + ow.test.assert(res.status, 200, "Mcp-Name should only be required for tools/call, prompts/get and resources/read.") + + // Missing or mismatched headers + var expectMismatch = (header, label) => { + var r = replyRPC(fns, call("ping"), header) + ow.test.assert(r.status, 400, label + " should be rejected with HTTP 400.") + ow.test.assert(r.body.error.code, -32020, label + " should use the HeaderMismatch -32020 error code.") + ow.test.assert(r.body.id, 1, label + " should keep the request id.") + return r + } + expectMismatch(merge(good, { "mcp-method": __ }), "A missing Mcp-Method header") + expectMismatch({ "mcp-protocol-version": "2026-07-28", "mcp-name": "ping" }, "An absent Mcp-Method header") + expectMismatch({ "mcp-protocol-version": "2026-07-28", "mcp-method": "tools/call" }, "An absent Mcp-Name header") + expectMismatch({ "mcp-method": "tools/call", "mcp-name": "ping" }, "An absent MCP-Protocol-Version header") + expectMismatch(merge(good, { "mcp-protocol-version": "2025-06-18" }), "A mismatched MCP-Protocol-Version header") + expectMismatch(merge(good, { "mcp-method": "Tools/Call" }), "A differently-cased Mcp-Method value") + var r = expectMismatch(merge(good, { "mcp-name": "pong" }), "A mismatched Mcp-Name header") + ow.test.assert(r.body.error.message.indexOf("Mcp-Name") >= 0, true, "HeaderMismatch should name the mismatched header.") + + // Base64 sentinel encoding + var encoded = ow.server.mcp.encodeHeaderValue("café ☕") + ow.test.assert(encoded.indexOf("=?base64?") == 0, true, "Non-ASCII names should use the Base64 sentinel.") + ow.test.assert(ow.server.mcp.decodeHeaderValue(encoded), "café ☕", "Base64 sentinel should round-trip UTF-8.") + ow.test.assert(ow.server.mcp.encodeHeaderValue("=?base64?abc?="), "=?base64?" + String(java.util.Base64.getEncoder().encodeToString(new java.lang.String("=?base64?abc?=").getBytes("UTF-8"))) + "?=", "Sentinel-like ASCII values should be encoded too.") + ow.test.assert(ow.server.mcp.encodeHeaderValue("ping"), "ping", "Plain ASCII values should stay unencoded.") + res = replyRPC(fns, call("café ☕"), merge(good, { "mcp-name": encoded })) + ow.test.assert(res.status, 200, "A Base64-encoded Mcp-Name should be decoded before comparison.") + + // Tasks extension: Mcp-Name carries params.taskId + fns["tasks/get"] = params => ({ taskId: params.taskId, status: "working" }) + var taskGet = { jsonrpc: "2.0", id: 4, method: "tasks/get", params: { taskId: "t-1", _meta: modernMeta } } + res = replyRPC(fns, taskGet, { "mcp-protocol-version": "2026-07-28", "mcp-method": "tasks/get", "mcp-name": "t-1" }) + ow.test.assert(res.status, 200, "tasks/get with Mcp-Name equal to params.taskId should be accepted.") + res = replyRPC(fns, taskGet, { "mcp-protocol-version": "2026-07-28", "mcp-method": "tasks/get", "mcp-name": "t-2" }) + ow.test.assert([res.status, res.body.error.code], [400, -32020], "tasks/get with a mismatched Mcp-Name should be rejected.") + + // replyMCP applies the same validation + var mcpRes = ow.server.httpd.replyMCP(__, { method: "POST", uri: "/mcp", header: merge(good, { "mcp-name": "pong" }), files: { postData: stringify(call("ping"), __, "") } }, fns, function() {}, function() {}, { modern: true }) + ow.test.assert([mcpRes.status, jsonParse(mcpRes.data).error.code], [400, -32020], "replyMCP should reject a mismatched Mcp-Name.") + + // Legacy era is not affected + res = replyRPC(fns, { jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "ping", arguments: {} } }, {}) + ow.test.assert(res.status, 200, "Legacy-era requests should not require the modern request headers.") + res = replyRPC(fns, call("ping"), {}, { modern: false }) + ow.test.assert(res.status, 200, "Servers that did not opt into the modern era should not validate the headers.") + } + + exports.testMCPModernCacheHints = function() { + ow.loadServer() + + // server/discover hints + var d = ow.server.mcp.discoverResult({ serverInfo: { name: "x" } }) + ow.test.assert([d.ttlMs, d.cacheScope], [0, "private"], "server/discover should default to ttlMs 0 and private scope.") + d = ow.server.mcp.discoverResult({}, { ttlMs: 60000, cacheScope: "public" }) + ow.test.assert([d.ttlMs, d.cacheScope], [60000, "public"], "server/discover should carry the configured caching hints.") + d = ow.server.mcp.discoverResult({}, { ttlMs: -5, cacheScope: "shared" }) + ow.test.assert([d.ttlMs, d.cacheScope], [0, "private"], "Invalid caching hints should normalize to 0/private.") + ow.test.assert(ow.server.mcp.normalizeCacheHints("1500.7", "public").ttlMs, 1500, "ttlMs should be an integer.") + + // Configured hints on HTTP results + var fns = { + "resources/read": params => params.uri == "ask:me" ? { resultType: "input_required", inputRequests: {} } : { contents: [{ uri: params.uri, text: "x" }] }, + "tools/call": () => ({ content: [], isError: false }), + "tools/list": () => ({ tools: [] }) + } + var opts = { ttlMs: 30000, cacheScope: "public" } + var read = uri => replyRPC(fns, { jsonrpc: "2.0", id: 1, method: "resources/read", params: { uri: uri, _meta: modernMeta } }, { "mcp-protocol-version": "2026-07-28", "mcp-method": "resources/read", "mcp-name": uri }, opts) + var res = read("data:item") + ow.test.assert(res.status, 200, "resources/read with matching headers should succeed.") + ow.test.assert([res.body.result.ttlMs, res.body.result.cacheScope], [30000, "public"], "resources/read should carry the configured caching hints.") + res = read("ask:me") + ow.test.assert(isUnDef(res.body.result.ttlMs) && isUnDef(res.body.result.cacheScope), true, "input_required results should carry no caching hints.") + res = replyRPC(fns, { jsonrpc: "2.0", id: 2, method: "tools/list", params: { _meta: modernMeta } }, { "mcp-protocol-version": "2026-07-28", "mcp-method": "tools/list" }, opts) + ow.test.assert([res.body.result.ttlMs, res.body.result.cacheScope], [30000, "public"], "tools/list should carry the configured caching hints.") + res = replyRPC(fns, { jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "t", arguments: {}, _meta: modernMeta } }, { "mcp-protocol-version": "2026-07-28", "mcp-method": "tools/call", "mcp-name": "t" }, opts) + ow.test.assert(isUnDef(res.body.result.ttlMs), true, "tools/call results should not be cacheable.") + } + + // Modern-only HTTP MCP fixture with caching hints, counting requests per method and capturing headers + var withCacheableMCPServer = function(replyOpts, testFn) { + ow.loadServer() + var port = findRandomOpenPort() + var hs = ow.server.httpd.start(port, "127.0.0.1") + var description = { serverInfo: { name: "Cacheable MCP", version: "1.0.0" }, capabilities: { tools: {}, resources: {} } } + var hits = {}, requests = [], tools = [{ name: "ping", inputSchema: { type: "object", properties: {} } }] + var count = (method, fn) => params => { + hits[method] = (hits[method] || 0) + 1 + return fn(params) + } + var rpcFns = { + "server/discover": count("server/discover", () => ow.server.mcp.discoverResult(description, replyOpts)), + "tools/list": count("tools/list", () => ({ tools: tools })), + "tools/call": count("tools/call", params => ({ content: [{ type: "text", text: "called:" + params.name }], isError: false })), + "resources/read": count("resources/read", params => ({ contents: [{ uri: params.uri, text: "v" + hits["resources/read"] }] })) + } + ow.server.httpd.route(hs, { + "/mcp": req => { + requests.push(req) + return ow.server.httpd.replyJSONRPC(hs, req, rpcFns, function() {}, function() {}, merge({ modern: true, serverInfo: description.serverInfo }, replyOpts)) + } + }) + try { + testFn({ url: "http://127.0.0.1:" + port + "/mcp", hits: hits, requests: requests, tools: tools }) + } finally { + ow.server.httpd.stop(hs) + } + } + + exports.testMCPClientSendsSpecRequestHeaders = function() { + withCacheableMCPServer({}, function(ctx) { + var client = $mcp({ type: "remote", strict: false, url: ctx.url, protocolVersion: "auto" }) + try { + client.initialize() + ow.test.assert(client.getClientInfo().era, "modern", "The server/discover probe should pass strict header validation.") + ow.test.assert(ctx.requests[0].header["mcp-protocol-version"], "2026-07-28", "The probe should send the per-request protocol version header.") + ow.test.assert(ctx.requests[0].header["mcp-method"], "server/discover", "The probe should send Mcp-Method.") + + var lastOf = method => ctx.requests.filter(req => req.header["mcp-method"] == method).pop() + ow.test.assert(client.callTool("café ☕", {}).content[0].text, "called:café ☕", "A non-ASCII tool name should pass strict header validation.") + ow.test.assert(lastOf("tools/call").header["mcp-name"], ow.server.mcp.encodeHeaderValue("café ☕"), "A non-ASCII Mcp-Name should use the Base64 sentinel.") + ow.test.assert(client.callTool("=?base64?abc?=", {}).content[0].text, "called:=?base64?abc?=", "A sentinel-like tool name should round-trip.") + ow.test.assert(client.readResource("data:item").contents[0].uri, "data:item", "resources/read should pass strict header validation.") + ow.test.assert(lastOf("resources/read").header["mcp-name"], "data:item", "resources/read should send params.uri as Mcp-Name.") + } finally { + client.destroy() + } + }) + } + + exports.testMCPClientOptInCache = function() { + withCacheableMCPServer({ ttlMs: 60000, cacheScope: "private" }, function(ctx) { + // Default: no cache + var plain = $mcp({ type: "remote", strict: false, url: ctx.url, protocolVersion: "auto" }) + try { + plain.initialize() + plain.listTools() + plain.listTools() + ow.test.assert(ctx.hits["tools/list"], 2, "Without cache:true every list call should reach the server.") + } finally { + plain.destroy() + } + + // Opt-in cache + var opts = { type: "remote", strict: false, url: ctx.url, protocolVersion: "auto", cache: true, auth: { type: "bearer", token: "a" } } + var client = $mcp(opts) + try { + client.initialize() + ctx.hits["tools/list"] = 0 + var first = client.listTools() + var second = client.listTools() + ow.test.assert(ctx.hits["tools/list"], 1, "A fresh cached tools/list should not reach the server.") + ow.test.assert(second.tools[0].name, "ping", "A cached tools/list should return the same tools.") + ow.test.assert(second.ttlMs > 0 && second.ttlMs <= first.ttlMs, true, "A cached response should report its remaining lifetime.") + + // Notifications invalidate the related entries + opts.onNotification({ jsonrpc: "2.0", method: "notifications/tools/list_changed" }) + client.listTools() + ow.test.assert(ctx.hits["tools/list"], 2, "tools/list_changed should invalidate the cached tools/list.") + ow.test.assert(client.readResource("data:item").contents[0].text, "v1", "First resources/read should reach the server.") + ow.test.assert(client.readResource("data:item").contents[0].text, "v1", "Second resources/read should come from the cache.") + opts.onNotification({ jsonrpc: "2.0", method: "notifications/resources/updated", params: { uri: "data:item" } }) + ow.test.assert(client.readResource("data:item").contents[0].text, "v2", "resources/updated should invalidate the cached resource.") + + // Private entries are not reused across authorization contexts + opts.auth.token = "b" + client.listTools() + ow.test.assert(ctx.hits["tools/list"], 3, "A private cached response should not be reused for another credential.") + + // Different request _meta (e.g. client capabilities) must not reuse an entry + var before = ctx.hits["tools/list"] + client.listTools() + ow.test.assert(ctx.hits["tools/list"], before, "An identical request should come from the cache.") + client.onElicitationRequest(() => ({ action: "decline" })) + client.listTools() + ow.test.assert(ctx.hits["tools/list"], before + 1, "A request with different client capabilities should not reuse a cached response.") + + // Explicit clear + var cleared = ctx.hits["tools/list"] + client.clearCache() + client.listTools() + ow.test.assert(ctx.hits["tools/list"], cleared + 1, "clearCache() should drop cached responses.") + + // Non-cacheable methods + client.callTool("ping", {}) + client.callTool("ping", {}) + ow.test.assert(ctx.hits["tools/call"], 2, "tools/call should never be cached.") + } finally { + client.destroy() + } + }) + + // ttlMs 0 is never cached + withCacheableMCPServer({}, function(ctx) { + var client = $mcp({ type: "remote", strict: false, url: ctx.url, protocolVersion: "auto", cache: true }) + try { + client.initialize() + client.listTools() + client.listTools() + ow.test.assert(ctx.hits["tools/list"], 2, "A ttlMs 0 response should never be cached.") + } finally { + client.destroy() + } + }) + } + + var sqlTool = (header, extra) => ({ + name: "execute_sql", + inputSchema: { + type: "object", + properties: merge({ + region: { type: "string", "x-mcp-header": header }, + query : { type: "string" } + }, extra || {}) + } + }) + + exports.testMCPHeaderAnnotations = function() { + ow.loadServer() + var m = ow.server.mcp + + // Valid annotations, including nested ones reached through properties + var ann = m.headerAnnotations({ type: "object", properties: { + region: { type: "string", "x-mcp-header": "Region" }, + opts : { type: "object", properties: { limit: { type: "integer", "x-mcp-header": "Limit" }, dry: { type: "boolean", "x-mcp-header": "Dry-Run" } } } + } }) + ow.test.assert(ann.valid, true, "Annotations reached through properties should be valid.") + ow.test.assert(ann.params.map(p => p.header + "=" + p.path.join(".")), ["Region=region", "Limit=opts.limit", "Dry-Run=opts.dry"], "Annotations should map headers to argument paths.") + ow.test.assert(m.headerAnnotations({ type: "object", properties: { q: { type: "string" } } }).params.length, 0, "Schemas without annotations should have none.") + ow.test.assert(m.headerAnnotations(__).valid, true, "A missing inputSchema has no annotations.") + + // Invalid annotations + var invalid = (schema, label) => ow.test.assert(m.headerAnnotations(schema).valid, false, label) + invalid({ type: "object", properties: { list: { type: "array", items: { type: "string", "x-mcp-header": "Item" } } } }, "Annotations under items should be invalid.") + invalid({ type: "object", properties: { v: { anyOf: [{ type: "string", "x-mcp-header": "V" }] } } }, "Annotations under anyOf should be invalid.") + invalid({ type: "object", properties: { v: { type: "string", "x-mcp-header": "Bad Name" } } }, "Non-token header names should be invalid.") + invalid({ type: "object", properties: { v: { type: "string", "x-mcp-header": "" } } }, "Empty header names should be invalid.") + invalid({ type: "object", properties: { a: { type: "string", "x-mcp-header": "Region" }, b: { type: "string", "x-mcp-header": "region" } } }, "Case-insensitive duplicates should be invalid.") + invalid({ type: "object", properties: { n: { type: "number", "x-mcp-header": "N" } } }, "Number-typed properties should be invalid.") + invalid({ type: "object", properties: { o: { type: "object", "x-mcp-header": "O" } } }, "Object-typed properties should be invalid.") + + // Value encoding (spec examples) + var schema = { type: "object", properties: { + region: { type: "string", "x-mcp-header": "Region" }, greeting: { type: "string", "x-mcp-header": "Greeting" }, + text: { type: "string", "x-mcp-header": "Text" }, val: { type: "string", "x-mcp-header": "Val" }, + count: { type: "integer", "x-mcp-header": "Count" }, dry: { type: "boolean", "x-mcp-header": "Dry" }, gone: { type: "string", "x-mcp-header": "Gone" } + } } + var h = m.paramHeaders(schema, { region: "us-west1", greeting: "Hello, 世界", text: " padded ", val: "=?base64?literal?=", count: -7, dry: false, gone: null }) + ow.test.assert(h["Mcp-Param-Region"], "us-west1", "Plain ASCII values should be sent as-is.") + ow.test.assert(h["Mcp-Param-Greeting"], "=?base64?SGVsbG8sIOS4lueVjA==?=", "Non-ASCII values should be Base64 encoded.") + ow.test.assert(h["Mcp-Param-Text"], "=?base64?IHBhZGRlZCA=?=", "Values with surrounding whitespace should be Base64 encoded.") + ow.test.assert(h["Mcp-Param-Val"], "=?base64?PT9iYXNlNjQ/bGl0ZXJhbD89?=", "Sentinel-like values should be Base64 encoded.") + ow.test.assert(m.paramHeaders(schema, { text: "line1\nline2" })["Mcp-Param-Text"], "=?base64?bGluZTEKbGluZTI=?=", "Values with control characters should be Base64 encoded.") + ow.test.assert([h["Mcp-Param-Count"], h["Mcp-Param-Dry"]], ["-7", "false"], "Integers and booleans should be serialized as decimal and true/false.") + ow.test.assert(Object.keys(h).indexOf("Mcp-Param-Gone"), -1, "Null arguments should omit the header.") + } + + exports.testMCPServerValidatesParamHeaders = function() { + ow.loadServer() + var fns = { + "tools/list": () => ({ tools: [sqlTool("Region", { limit: { type: "integer", "x-mcp-header": "Limit" } })] }), + "tools/call": params => ({ content: [{ type: "text", text: "ok" }], isError: false }) + } + var call = args => ({ jsonrpc: "2.0", id: 9, method: "tools/call", params: { name: "execute_sql", arguments: args, _meta: modernMeta } }) + var base = { "mcp-protocol-version": "2026-07-28", "mcp-method": "tools/call", "mcp-name": "execute_sql" } + var expect = (args, header, status, label, opts) => { + var r = replyRPC(fns, call(args), merge(base, header), opts) + ow.test.assert(r.status, status, label) + if (status == 400) ow.test.assert(r.body.error.code, -32020, label + " (HeaderMismatch)") + return r + } + + expect({ region: "us-west1", query: "q" }, { "mcp-param-region": "us-west1" }, 200, "Matching Mcp-Param headers should be accepted.") + expect({ region: "us-west1", query: "q" }, {}, 400, "A missing Mcp-Param header for a present argument should be rejected.") + expect({ region: "us-west1", query: "q" }, { "mcp-param-region": "eu-west1" }, 400, "A mismatched Mcp-Param header should be rejected.") + expect({ query: "q" }, { "mcp-param-region": "us-west1" }, 400, "A Mcp-Param header without a body value should be rejected.") + expect({ query: "q" }, {}, 200, "An absent argument needs no Mcp-Param header.") + expect({ region: "us-west1", limit: 42 }, { "mcp-param-region": "us-west1", "mcp-param-limit": "42.0" }, 200, "Integer headers should be compared numerically.") + expect({ region: "us-west1", limit: 42 }, { "mcp-param-region": "us-west1", "mcp-param-limit": "43" }, 400, "A different integer should be rejected.") + expect({ region: "Hello, 世界" }, { "mcp-param-region": "=?base64?SGVsbG8sIOS4lueVjA==?=" }, 200, "Base64-encoded Mcp-Param values should be decoded.") + expect({ region: "x" }, { "mcp-param-region": "x\u0001" }, 400, "Mcp-Param values with invalid characters should be rejected.") + expect({ region: "us-west1" }, { "mcp-param-region": "us-west1", "mcp-param-unknown": "z" }, 200, "Unrecognized Mcp-Param headers should be ignored.") + expect({ region: "us-west1" }, { "mcp-param-zone": "us-west1" }, 200, "Explicit opts.tools should override tools/list.", { tools: [sqlTool("Zone")] }) + } + + exports.testMCPClientMirrorsParamHeaders = function() { + withCacheableMCPServer({}, function(ctx) { + ctx.tools.length = 0 + ctx.tools.push(sqlTool("Region"), { name: "bad", inputSchema: { type: "object", properties: { a: { type: "number", "x-mcp-header": "A" } } } }) + var client = $mcp({ type: "remote", strict: false, url: ctx.url, protocolVersion: "auto" }) + try { + client.initialize() + var lastCall = () => ctx.requests.filter(req => req.header["mcp-method"] == "tools/call").pop() + + // Tools with invalid annotations are rejected + ow.test.assert(client.listTools().tools.map(t => t.name), ["execute_sql"], "Tools with invalid x-mcp-header annotations should be excluded from listTools().") + var rejected = false + try { client.callTool("bad", { a: 1 }) } catch(e) { rejected = String(e).indexOf("rejected") >= 0 } + ow.test.assert(rejected, true, "Calling a rejected tool should fail.") + + // Annotated arguments are mirrored and accepted by a strict server + var res = client.callTool("execute_sql", { region: "us-west1", query: "SELECT 1" }) + ow.test.assert(res.content[0].text, "called:execute_sql", "A mirrored Mcp-Param header should pass strict validation.") + ow.test.assert(lastCall().header["mcp-param-region"], "us-west1", "The annotated argument should be sent as Mcp-Param-Region.") + ow.test.assert(isUnDef(lastCall().header["mcp-param-query"]), true, "Non-annotated arguments should not be mirrored.") + + // A tool called before listing gets a HeaderMismatch, a schema refresh and one retry + var fresh = $mcp({ type: "remote", strict: false, url: ctx.url, protocolVersion: "auto" }) + try { + fresh.initialize() + var before = ctx.hits["tools/call"] || 0 + ow.test.assert(fresh.callTool("execute_sql", { region: "ap-south1", query: "q" }).content[0].text, "called:execute_sql", "An unlisted annotated tool should succeed after one retry.") + ow.test.assert(lastCall().header["mcp-param-region"], "ap-south1", "The retry should mirror the learned annotation.") + ow.test.assert(ctx.hits["tools/call"], before + 1, "The unlisted tool should run only once.") + } finally { + fresh.destroy() + } + + // A changed schema triggers a HeaderMismatch, a schema refresh and one retry + ctx.tools[0] = sqlTool("Zone") + var calls = ctx.hits["tools/call"] + res = client.callTool("execute_sql", { region: "eu-west1", query: "SELECT 1" }) + ow.test.assert(res.content[0].text, "called:execute_sql", "The client should retry after refreshing the tool schema.") + ow.test.assert(lastCall().header["mcp-param-zone"], "eu-west1", "The retry should use the refreshed annotation.") + ow.test.assert(ctx.hits["tools/call"], calls + 1, "The tool should run only once.") + } finally { + client.destroy() + } + }) + } + exports.testOJobTplDescRendersAllToolMetadataStrings = function() { var tf = "ojob_mcp_tpldesc_" + genUUID() + ".yaml"; diff --git a/tests/autoTestAll.MCP.yaml b/tests/autoTestAll.MCP.yaml index b6c17a79..1ceecf2d 100644 --- a/tests/autoTestAll.MCP.yaml +++ b/tests/autoTestAll.MCP.yaml @@ -100,6 +100,41 @@ jobs: to : OpenAF Test exec: args.func = args.tests.testMCPAutoClientLegacyOnlyDiscoverError + - name: MCP::modern server validates request headers + from: MCP::Init + to : OpenAF Test + exec: args.func = args.tests.testMCPModernServerValidatesRequestHeaders + + - name: MCP::modern caching hints + from: MCP::Init + to : OpenAF Test + exec: args.func = args.tests.testMCPModernCacheHints + + - name: MCP::client sends spec request headers + from: MCP::Init + to : OpenAF Test + exec: args.func = args.tests.testMCPClientSendsSpecRequestHeaders + + - name: MCP::client opt-in cache + from: MCP::Init + to : OpenAF Test + exec: args.func = args.tests.testMCPClientOptInCache + + - name: MCP::x-mcp-header annotations + from: MCP::Init + to : OpenAF Test + exec: args.func = args.tests.testMCPHeaderAnnotations + + - name: MCP::server validates Mcp-Param headers + from: MCP::Init + to : OpenAF Test + exec: args.func = args.tests.testMCPServerValidatesParamHeaders + + - name: MCP::client mirrors Mcp-Param headers + from: MCP::Init + to : OpenAF Test + exec: args.func = args.tests.testMCPClientMirrorsParamHeaders + todo: - MCP::OAuth discovery with client credentials - MCP::OAuth authorization URL includes resource and PKCE @@ -119,3 +154,10 @@ todo: - MCP::JSON-RPC stdio concurrent exec - MCP::OAuth rejects insecure endpoints and issuer mismatch - MCP::auto client legacy-only discover error + - MCP::modern server validates request headers + - MCP::modern caching hints + - MCP::client sends spec request headers + - MCP::client opt-in cache + - MCP::x-mcp-header annotations + - MCP::server validates Mcp-Param headers + - MCP::client mirrors Mcp-Param headers diff --git a/tests/autoTestAll.OAuthClient.js b/tests/autoTestAll.OAuthClient.js new file mode 100644 index 00000000..404ba196 --- /dev/null +++ b/tests/autoTestAll.OAuthClient.js @@ -0,0 +1,145 @@ +exports.testRESTClient = function() { + ow.loadServer() + var port = findRandomOpenPort() + var base = "http://127.0.0.1:" + port + var httpd = ow.server.httpd + var server = httpd.start(port, "127.0.0.1") + var tokens = new java.util.concurrent.atomic.AtomicInteger() + var unrelated = new java.util.concurrent.atomic.AtomicInteger() + var rejected = new java.util.concurrent.atomic.AtomicInteger() + + // Exercise an independently shaped token endpoint and resource metadata. + var routes = { + "/.well-known/oauth-protected-resource/reports": () => + httpd.reply({ resource: base + "/reports", authorization_servers: [base + "/issuer"] }, 200, "application/json"), + "/.well-known/oauth-authorization-server/issuer": () => + httpd.reply({ issuer: base + "/issuer", token_endpoint: base + "/token" }, 200, "application/json"), + "/token": req => { + tokens.incrementAndGet() + if (req.header.authorization !== "Basic Zml4dHVyZTpzZWNyZXQ=" || req.params.grant_type !== "client_credentials") { + return httpd.reply({ error: "invalid_client" }, 401, "application/json") + } + return httpd.reply({ access_token: "fixture-access", token_type: "Bearer", expires_in: 60 }, 200, "application/json") + }, + "/reports": req => { + if (req.header.authorization !== "Bearer fixture-access") return httpd.reply({}, 401, "application/json") + if (req.method === "HEAD") return httpd.reply("", 200, "text/plain", { "X-Fixture": "fixture" }) + return httpd.reply({ method: req.method }, 200, "application/json") + }, + "/reports/redirect": () => httpd.reply("", 302, "text/plain", { Location: base + "/unrelated" }), + "/reports/mcp": req => { + if (req.header.authorization !== "Bearer fixture-access") return httpd.reply({}, 401, "application/json") + var raw = req.files && req.files.postData || req.data + var request = isString(raw) ? JSON.parse(raw) : raw + if (!request || isUnDef(request.id)) return httpd.reply("", 202) + return httpd.reply({ jsonrpc: "2.0", id: request.id, result: { + protocolVersion: "2025-06-18", capabilities: {}, serverInfo: { name: "test", version: "1" } + } }, 200, "application/json") + }, + "/reports/reject": () => { + rejected.incrementAndGet() + return httpd.reply({ error_description: "fixture-access" }, 401, "application/json") + }, + "/unrelated": () => { + unrelated.incrementAndGet() + return httpd.reply({}, 200, "application/json") + } + } + httpd.route(server, routes) + + // Reuse a single credential and reject a different final target before dispatch. + var client = ow.server.oauth.client({ clientId: "fixture", clientSecret: "secret", + tokenEndpointAuthMethod: "client_secret_basic", allowLoopbackHTTP: true }) + try { + var rest = $rest({ auth: client, throwExceptions: true, retry: 3 }) + ow.test.assert(rest.get(base + "/reports").method, "GET") + ow.test.assert(rest.post(base + "/reports", {}).method, "POST") + ow.test.assert(isMap(rest.head(base + "/reports")), true) + ow.test.assert(Number(tokens.get()), 1) + var mcp = $mcp({ type: "remote", url: base + "/reports/mcp", auth: client }) + try { + mcp.initialize() + ow.test.assert(mcp.getAuthStatus().authenticated, true) + ow.test.assert(Number(tokens.get()), 1) + } finally { mcp.destroy() } + var rewritten = $rest({ auth: client, throwExceptions: true, preAction: args => { + args.aBaseURL = base + "/unrelated" + return args + } }) + var error + try { rewritten.get(base + "/reports") } catch(e) { error = String(e) } + ow.test.assert(isString(error) && error.indexOf("outside the configured resource") >= 0, true) + rest.get2Stream(base + "/reports/redirect").close() + ow.test.assert(Number(unrelated.get()), 0) + error = __ + try { rest.post(base + "/reports/reject", {}) } catch(e) { error = String(e) } + ow.test.assert(Number(rejected.get()), 1) + ow.test.assert(isString(error) && error.indexOf("fixture-access") < 0, true) + client.clearAuth() + var replies = parallel4Array([1, 2, 3, 4], () => $rest({ auth: client, throwExceptions: true }).get(base + "/reports")) + ow.test.assert(replies.every(reply => reply.method === "GET"), true) + ow.test.assert(Number(tokens.get()), 2) + + // A configured store coalesces reuse across independently constructed clients. + var records = Object.create(null) + var profile = { profile: "fixture", withLock: (key, fn) => fn(), load: key => records[key], + save: (key, record) => { records[key] = record }, clear: key => { delete records[key] } } + var config = { clientId: "fixture", clientSecret: "secret", tokenEndpointAuthMethod: "client_secret_basic", + allowLoopbackHTTP: true, tokenURL: base + "/token", resource: base + "/reports", tokenStore: profile } + var first = ow.server.oauth.client(config), second = ow.server.oauth.client(config) + try { + ow.test.assert(first.authenticate().access_token, second.authenticate().access_token) + ow.test.assert(Number(tokens.get()), 3) + first.clearAuth() + second.authenticate() + ow.test.assert(Number(tokens.get()), 4) + } finally { first.close(); second.close() } + } finally { + client.close() + httpd.stop(server) + } +} + +exports.testClientAssertion = function() { + ow.loadServer() + var port = findRandomOpenPort() + var base = "http://127.0.0.1:" + port + var httpd = ow.server.httpd + var server = httpd.start(port, "127.0.0.1") + + // Verify compact JWS independently from the OpenAF JWT signing path. + var check = function(algorithm, key, signatureAlgorithm) { + var received + httpd.route(server, { + "/token": req => { + received = req.params.client_assertion + return httpd.reply({ access_token: "assertion-result", token_type: "Bearer", expires_in: 60 }, 200, "application/json") + } + }) + var client = ow.server.oauth.client({ clientId: "fixture", issuer: base + "/issuer", + tokenURL: base + "/token", allowLoopbackHTTP: true, tokenEndpointAuthMethod: "private_key_jwt", + algorithm: algorithm, keyId: "fixture-key", privateKey: key.getPrivate() }) + try { + ow.test.assert(client.authenticate().access_token, "assertion-result") + var parts = received.split(".") + var decoder = java.util.Base64.getUrlDecoder() + var header = JSON.parse(af.fromBytes2String(decoder.decode(parts[0]))) + var claims = JSON.parse(af.fromBytes2String(decoder.decode(parts[1]))) + var verifier = java.security.Signature.getInstance(signatureAlgorithm) + verifier.initVerify(key.getPublic()) + verifier.update(af.fromString2Bytes(parts[0] + "." + parts[1])) + ow.test.assert(Boolean(verifier.verify(decoder.decode(parts[2]))), true) + ow.test.assert(header.alg, algorithm) + ow.test.assert(header.typ, "client-authentication+jwt") + ow.test.assert(isArray(claims.aud) ? claims.aud : [claims.aud], [base + "/issuer"]) + ow.test.assert(claims.sub, "fixture") + } finally { client.close() } + } + try { + check("RS256", ow.server.jwt.genKey("RS256"), "SHA256withRSA") + var generator + try { generator = java.security.KeyPairGenerator.getInstance("ML-DSA-65") } + catch(e) { return } + check("ML-DSA-65", generator.generateKeyPair(), "ML-DSA-65") + } finally { httpd.stop(server) } +} diff --git a/tests/autoTestAll.OAuthClient.yaml b/tests/autoTestAll.OAuthClient.yaml new file mode 100644 index 00000000..7acc9bb5 --- /dev/null +++ b/tests/autoTestAll.OAuthClient.yaml @@ -0,0 +1,18 @@ +include: +- autoTestAll.common.yaml + +jobs: + +# Exercise OAuth through public REST methods. +- name: OAuthClient::RESTClient + to: OpenAF Test + exec: args.func = require("autoTestAll.OAuthClient.js").testRESTClient + +# Verify assertion typing, audience and signature. +- name: OAuthClient::ClientAssertion + to: OpenAF Test + exec: args.func = require("autoTestAll.OAuthClient.js").testClientAssertion + +todo: +- OAuthClient::RESTClient +- OAuthClient::ClientAssertion diff --git a/tests/autoTestAll.OAuthIssuer.js b/tests/autoTestAll.OAuthIssuer.js new file mode 100644 index 00000000..12c08a5c --- /dev/null +++ b/tests/autoTestAll.OAuthIssuer.js @@ -0,0 +1,242 @@ +function exerciseIssuer(format) { + ow.loadServer() + var port = findRandomOpenPort() + var base = "http://127.0.0.1:" + port, issuer = base + "/issuer", resource = base + "/reports" + var httpd = ow.server.httpd + + // Provision separate machine and resource identities. + var key = ow.server.jwt.genKey("RS256") + var as = ow.server.oauth.authorizationServer({ issuer: issuer, allowLoopbackHTTP: true, tokenFormat: format, signingKey: { id: "fixture-signing", keyPair: key }, + clients: { + assertion: { tokenEndpointAuthMethod: "private_key_jwt", publicKey: key.getPublic(), keyId: "test-key", + resources: { [resource]: ["read"] } }, + machine: { clientSecretEnv: "OPENAF_OAUTH_TEST_SECRET", resources: { [resource]: ["read"] } }, + verifier: { clientSecretEnv: "OPENAF_OAUTH_TEST_SECRET", resources: { [resource]: [] }, introspection: true } + }, + resources: { [resource]: { scopes: ["read"] } } + }) + var hs = httpd.start(port, "127.0.0.1", __, __, __, __, 30000, "java") + var client = ow.server.oauth.client({ issuer: issuer, clientId: "machine", tokenEndpointAuthMethod: "client_secret_basic", + clientSecretEnv: "OPENAF_OAUTH_TEST_SECRET", resource: resource, scope: "read", allowLoopbackHTTP: true }) + var rs = httpd.oauthResourceServer({ issuer: issuer, resource: resource, allowLoopbackHTTP: true, + validation: "introspection", introspectionURL: issuer + "/introspect", clientId: "verifier", + clientSecretEnv: "OPENAF_OAUTH_TEST_SECRET", requiredScopes: ["read"] }) + + try { + as.mount(hs) + var metadata = $rest({ throwExceptions: true }).get(base + "/.well-known/oauth-authorization-server/issuer") + ow.test.assert(metadata.issuer, issuer) + ow.test.assert(metadata.token_endpoint, issuer + "/token") + var token = client.authenticate() + var request = { header: { authorization: "Bearer " + token.access_token } } + if (format === "jwt") { + var validator = httpd.oauthResourceServer({ issuer: issuer, resource: resource, allowLoopbackHTTP: true, + jwksURI: issuer + "/jwks", requiredScopes: ["read"] }) + try { ow.test.assert(validator.authenticate(request).ok, true) } + finally { validator.close() } + } + var auth = rs.authenticate(request) + ow.test.assert(auth.ok, true) + ow.test.assert(auth.context.subject, "service:machine") + ow.test.assert(rs.authorize(auth.context, ["read"]).ok, true) + + // Revoke as the original client and confirm the online verifier sees the change. + var http = new ow.obj.http() + try { + http.setThrowExceptions(false) + var pair = "machine:" + getEnv("OPENAF_OAUTH_TEST_SECRET") + var basic = String(java.util.Base64.getEncoder().encodeToString(af.fromString2Bytes(pair))) + var requestHeaders = { Authorization: "Basic " + basic, "Content-Type": "application/x-www-form-urlencoded" } + var invalid = http.exec(issuer + "/token", "POST", "grant_type=client_credentials&grant_type=client_credentials", requestHeaders) + ow.test.assert(invalid.responseCode, 400) + var revoked = http.exec(issuer + "/revoke", "POST", "token=" + encodeURIComponent(token.access_token), requestHeaders) + ow.test.assert(revoked.responseCode, 200) + + // An issuer-only signed assertion is consumed at most once. + sleep(1100, true) + var builder = Packages.io.jsonwebtoken.Jwts + var time = Math.floor(now() / 1000) + var jwt = String(builder.builder().header().type("client-authentication+jwt").keyId("test-key").and() + .issuer("assertion").subject("assertion").claim("aud", issuer).claim("iat", time).claim("exp", time + 60) + .id(genUUID()).signWith(key.getPrivate(), builder.SIG.RS256).compact()) + var form = ow.obj.rest.writeQuery({ grant_type: "client_credentials", client_id: "assertion", + client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", client_assertion: jwt, + resource: resource, scope: "read" }) + var formHeaders = { "Content-Type": "application/x-www-form-urlencoded" } + ow.test.assert(http.exec(issuer + "/token", "POST", form, formHeaders).responseCode, 200) + ow.test.assert(http.exec(issuer + "/token", "POST", form, formHeaders).responseCode, 401) + } finally { http.close() } + rs.invalidate() + ow.test.assert(rs.authenticate(request).ok, false) + } finally { client.close(); rs.close(); as.close(); httpd.stop(hs) } +} + +exports.testMachineIssuer = () => exerciseIssuer("opaque") +exports.testJWTIssuer = () => exerciseIssuer("jwt") + +exports.testPersistentIssuer = function() { + ow.loadServer() + var port = findRandomOpenPort() + var issuer = "http://127.0.0.1:" + port, resource = "https://api.example.org/reports" + var file = io.createTempFile("oauth-issuer-h2-", ".db") + var config = { issuer: issuer, allowLoopbackHTTP: true, storage: { type: "h2", file: file }, + resources: { [resource]: { scopes: ["read"] } }, + clients: { + machine: { clientSecretEnv: "OPENAF_OAUTH_TEST_SECRET", resources: { [resource]: ["read"] } }, + verifier: { clientSecretEnv: "OPENAF_OAUTH_TEST_SECRET", resources: { [resource]: [] }, introspection: true } + } + } + var httpd = ow.server.httpd, as, listener, client + var rs = httpd.oauthResourceServer({ issuer: issuer, resource: resource, allowLoopbackHTTP: true, + validation: "introspection", introspectionURL: issuer + "/introspect", clientId: "verifier", + clientSecretEnv: "OPENAF_OAUTH_TEST_SECRET" }) + + // Keep the database across a listener restart and verify single-writer ownership. + var start = () => { + as = ow.server.oauth.authorizationServer(config) + listener = httpd.start(port, "127.0.0.1", __, __, __, __, 30000, "java") + as.mount(listener) + } + try { + start() + var rejected = false + try { ow.server.oauth.authorizationServer(config).close() } + catch(e) { rejected = String(e).includes("database unavailable") } + ow.test.assert(rejected, true) + client = ow.server.oauth.client({ issuer: issuer, clientId: "machine", tokenEndpointAuthMethod: "client_secret_basic", + clientSecretEnv: "OPENAF_OAUTH_TEST_SECRET", resource: resource, scope: "read", allowLoopbackHTTP: true }) + var token = client.authenticate() + as.close() + httpd.stop(listener) + start() + ow.test.assert(rs.authenticate({ header: { authorization: "Bearer " + token.access_token } }).ok, true) + } finally { + if (isDef(client)) client.close() + if (isDef(as)) as.close() + if (isDef(listener)) httpd.stop(listener) + rs.close() + ;[file, file + ".oauth-lock", file + ".mv.db", file + ".trace.db"].forEach(path => { + if (io.fileExists(path)) io.rm(path) + }) + } +} + +exports.testDPoPIssuer = function() { + ow.loadServer() + var port = findRandomOpenPort() + var issuer = "http://127.0.0.1:" + port, resource = issuer + "/reports" + var httpd = ow.server.httpd + var as = ow.server.oauth.authorizationServer({ issuer: issuer, allowLoopbackHTTP: true, + clients: { + machine: { clientSecretEnv: "OPENAF_OAUTH_TEST_SECRET", resources: { [resource]: ["read"] }, senderConstraint: "dpop" }, + verifier: { clientSecretEnv: "OPENAF_OAUTH_TEST_SECRET", resources: { [resource]: [] }, introspection: true } + }, + resources: { [resource]: { scopes: ["read"] } } + }) + var listener = httpd.start(port, "127.0.0.1", __, __, __, __, 30000, "java") + var client = ow.server.oauth.client({ issuer: issuer, clientId: "machine", tokenEndpointAuthMethod: "client_secret_basic", + clientSecretEnv: "OPENAF_OAUTH_TEST_SECRET", resource: resource, scope: "read", allowLoopbackHTTP: true, + senderConstraint: { type: "dpop" } }) + var rs = httpd.oauthResourceServer({ issuer: issuer, resource: resource, allowLoopbackHTTP: true, + validation: "introspection", introspectionURL: issuer + "/introspect", clientId: "verifier", + clientSecretEnv: "OPENAF_OAUTH_TEST_SECRET", senderConstraint: { mode: "required", methods: ["dpop"] } }) + + try { + as.mount(listener) + httpd.route(listener, { + "/reports": rs.wrap((req, server, auth) => httpd.reply({ sender: auth.senderConstraint.type }, 200, "application/json")) + }) + var token = client.authenticate() + ow.test.assert(token.token_type, "DPoP") + var rest = $rest({ auth: client, throwExceptions: true }) + var challenged = false + try { rest.get(resource) } catch(e) { challenged = String(e).includes("401") } + ow.test.assert(challenged, true) + ow.test.assert(rest.get(resource).sender, "dpop") + ow.test.assert(rs.authenticate({ header: { authorization: "Bearer " + token.access_token } }).error, "invalid_token") + } finally { client.close(); rs.close(); as.close(); httpd.stop(listener) } +} + +exports.testDelegatedGrants = function() { + ow.loadServer() + var port = findRandomOpenPort() + var issuer = "http://127.0.0.1:" + port + "/issuer", resource = "https://api.example.org/reports" + var origin = "http://127.0.0.1:" + port, callback = "http://127.0.0.1:" + findRandomOpenPort() + "/callback" + var httpd = ow.server.httpd + + // Model an application-provided verified browser session. + var as = ow.server.oauth.authorizationServer({ issuer: issuer, allowLoopbackHTTP: true, + grants: ["authorization_code", "refresh_token"], requirePAR: true, + registration: { initialAccessTokenEnv: "OPENAF_OAUTH_TEST_SECRET", allowRedirect: url => url === callback }, + identityProvider: req => req.header.cookie === "fixture=verified" ? + { subject: "alice", sessionId: "fixture-session", resources: { [resource]: ["read", "offline_access"] } } : __, + resources: { [resource]: { scopes: ["read", "offline_access"] } }, + clients: { + browser: { tokenEndpointAuthMethod: "none", allowRefresh: true, redirectURIs: [callback], + resources: { [resource]: ["read", "offline_access"] } }, + verifier: { clientSecretEnv: "OPENAF_OAUTH_TEST_SECRET", resources: { [resource]: [] }, introspection: true } + } + }) + var listener = httpd.start(port, "127.0.0.1", __, __, __, __, 30000, "java") + var http = new ow.obj.http() + http.client = http.client.newBuilder().followRedirects(false).build() + http.setThrowExceptions(false) + var rs = httpd.oauthResourceServer({ issuer: issuer, resource: resource, allowLoopbackHTTP: true, + validation: "introspection", introspectionURL: issuer + "/introspect", clientId: "verifier", + clientSecretEnv: "OPENAF_OAUTH_TEST_SECRET" }) + + try { + as.mount(listener) + var verifier = "01234567890123456789012345678901234567890123456789" + var digest = java.security.MessageDigest.getInstance("SHA-256").digest(af.fromString2Bytes(verifier)) + var challenge = String(java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(digest)) + var query = { response_type: "code", client_id: "browser", redirect_uri: callback, resource: resource, + state: "fixture-state", scope: "read offline_access", code_challenge_method: "S256", code_challenge: challenge } + var form = (endpoint, data, headers) => http.exec(endpoint, "POST", ow.obj.rest.writeQuery(data), + Object.assign({ "Content-Type": "application/x-www-form-urlencoded" }, headers)) + var metadata = { redirect_uris: [callback], token_endpoint_auth_method: "none" } + var registerHeaders = { "Content-Type": "application/json" } + ow.test.assert(http.exec(issuer + "/register", "POST", JSON.stringify(metadata), registerHeaders).responseCode, 401) + registerHeaders.Authorization = "Bearer " + getEnv("OPENAF_OAUTH_TEST_SECRET") + var registered = http.exec(issuer + "/register", "POST", JSON.stringify(metadata), registerHeaders) + ow.test.assert(registered.responseCode, 201) + var dynamicId = JSON.parse(registered.response).client_id + ow.test.assert(isString(dynamicId), true) + var unapproved = JSON.parse(form(issuer + "/par", Object.assign({}, query, { client_id: dynamicId })).response) + var unapprovedUrl = issuer + "/authorize?" + ow.obj.rest.writeQuery({ client_id: dynamicId, request_uri: unapproved.request_uri }) + ow.test.assert(http.exec(unapprovedUrl, "GET", __, { Cookie: "fixture=verified" }).responseCode, 303) + ow.test.assert(String(http.responseHeaders().location).indexOf("error=invalid_target") >= 0, true) + ow.test.assert(as.admin.deleteClient(dynamicId), true) + + var push = form(issuer + "/par", query) + ow.test.assert(push.responseCode, 201) + var requestURI = JSON.parse(push.response).request_uri + var authorizeURL = issuer + "/authorize?" + ow.obj.rest.writeQuery({ client_id: "browser", request_uri: requestURI }) + var consent = http.exec(authorizeURL, "GET", __, { Cookie: "fixture=verified" }) + ow.test.assert(consent.responseCode, 200) + var handle = /name="request" value="([^"]+)"/.exec(consent.response)[1] + ow.test.assert(form(issuer + "/authorize", { request: handle, decision: "allow" }, + { Origin: "https://another.example", Cookie: "fixture=verified" }).responseCode, 400) + ow.test.assert(form(issuer + "/authorize", { request: handle, decision: "allow" }, + { Origin: origin, Cookie: "fixture=verified" }).responseCode, 303) + var location = new java.net.URI(http.responseHeaders().location) + var result = ow.server.rest.parseQuery(String(location.getRawQuery())) + ow.test.assert(result.state, "fixture-state") + ow.test.assert(result.iss, issuer) + + // Codes and refresh credentials are single-use, with family revocation after reuse. + var exchange = { client_id: "browser", grant_type: "authorization_code", redirect_uri: callback, + code: result.code, code_verifier: verifier } + var first = JSON.parse(form(issuer + "/token", exchange).response) + ow.test.assert(isString(first.refresh_token), true) + ow.test.assert(form(issuer + "/token", exchange).responseCode, 400) + var refresh = { client_id: "browser", grant_type: "refresh_token", refresh_token: first.refresh_token } + var next = JSON.parse(form(issuer + "/token", refresh).response) + ow.test.assert(isString(next.access_token), true) + var request = { header: { authorization: "Bearer " + next.access_token } } + ow.test.assert(rs.authenticate(request).context.subject, "user:alice") + ow.test.assert(form(issuer + "/token", refresh).responseCode, 400) + rs.invalidate() + ow.test.assert(rs.authenticate(request).ok, false) + } finally { http.close(); rs.close(); as.close(); httpd.stop(listener) } +} diff --git a/tests/autoTestAll.OAuthResource.js b/tests/autoTestAll.OAuthResource.js new file mode 100644 index 00000000..9c7e33e7 --- /dev/null +++ b/tests/autoTestAll.OAuthResource.js @@ -0,0 +1,293 @@ +(function() { + var eq = (actual, expected, message) => ow.test.assert(actual, expected, message) + var bearer = token => ({ header: { Authorization: "Bearer " + token } }) + var rejected = (server, token, reason, label) => eq(server.authenticate(bearer(token)).error, reason, label) + var checkThrows = (fn, label) => { + try { fn() } catch (e) { eq(true, true, label); return } + eq(false, true, label) + } + + // Serve provider metadata, keys and introspection from an isolated loopback listener. + var fixture = run => { + ow.loadServer() + var httpd = ow.server.httpd, server = httpd.start(findRandomOpenPort(), "127.0.0.1") + var root = "http://127.0.0.1:" + server.getPort(), issuer = root + "/realm", resource = root + "/nested/mcp" + var config = { issuer: issuer, resource: resource, allowLoopbackHTTP: true, clockSkew: 0 } + var state = { keyCalls: 0, tokenCalls: 0, keys: [], keyStatus: 200, introspectionStatus: 200, introspection: {} } + var keys = (kid, alg) => { + var pair = ow.server.jwt.genKey(alg || "RS256") + var publicKey = Packages.io.jsonwebtoken.security.Jwks.builder().key(pair.getPublic()).id(kid).build() + return { privateKey: pair.getPrivate(), jwk: JSON.parse(String(Packages.io.jsonwebtoken.security.Jwks.json(publicKey))) } + } + var token = (key, changes, headers, algorithm) => { + var time = Math.floor(now() / 1000) + var claims = Object.assign({ iss: issuer, aud: resource, sub: "local-sub", exp: time + 120, + iat: time, jti: "local-jti", client_id: "local-client", scope: "read write", department: "ops", + private_claim: "fixture-private" }, changes || {}) + var jws = Packages.io.jsonwebtoken.Jwts.builder() + Object.keys(claims).forEach(name => { + var value = claims[name] + if (isNull(value)) return + if (name === "aud" && isArray(value)) { + var audience = new java.util.ArrayList() + value.forEach(v => audience.add(new java.lang.String(v))) + jws.claim(name, audience) + } else jws.claim(name, value) + }) + var head = Object.assign({ kid: key.jwk.kid, typ: "at+jwt" }, headers || {}) + Object.keys(head).forEach(name => { if (!isNull(head[name])) jws.setHeaderParam(name, head[name]) }) + return String(jws.signWith(key.privateKey, Packages.io.jsonwebtoken.Jwts.SIG.get().forKey(algorithm || "RS256")).compact()) + } + var metadata = () => httpd.reply({ issuer: state.metadataIssuer || issuer, jwks_uri: state.jwksURI || root + "/jwks", + introspection_endpoint: root + "/introspect" }, 200) + httpd.route(server, { + "/.well-known/oauth-authorization-server/realm": () => state.oidc ? httpd.reply("", 404) : metadata(), + "/.well-known/openid-configuration/realm": () => httpd.reply("", 404), + "/realm/.well-known/openid-configuration": metadata, + "/jwks": () => { + state.keyCalls++ + if (state.keyDelay) sleep(state.keyDelay, true) + return httpd.reply(state.keyBody || { keys: state.keys }, state.keyStatus) + }, + "/introspect": req => { + state.tokenCalls++ + if (state.tokenDelay) sleep(state.tokenDelay, true) + state.credentials = { header: req.header.authorization, form: req.params } + return httpd.reply(state.introspection, state.introspectionStatus) + } + }) + var instances = [] + var create = options => { + var oauth = httpd.oauthResourceServer(Object.assign({}, config, options)) + instances.push(oauth) + return oauth + } + try { run({ root: root, config: config, state: state, create: create, keys: keys, token: token, server: server, httpd: httpd }) } + finally { instances.forEach(oauth => oauth.close()); httpd.stop(server) } + } + + exports.testJWTPolicy = () => fixture(f => { + var key = f.keys("a"), other = f.keys("a"), time = Math.floor(now() / 1000) + f.state.keys = [key.jwk] + var oauth = f.create({ requiredScopes: ["read"], scopesSupported: ["discover"], claimAllowlist: ["department"] }) + var token = f.token(key) + var auth = oauth.authenticate(bearer(token)) + eq(auth.ok, true, "Valid JWT") + eq(auth.context.subject, "local-sub", "Verified subject") + eq(auth.context.claims, { department: "ops" }, "Only allowlisted claims") + eq(oauth.authorize(auth.context, ["write"]).ok, true, "Global and operation scopes") + eq(oauth.authorize(auth.context, ["admin"]).error, "insufficient_scope", "Scope denial") + eq(oauth.authorize(Object.assign({}, auth.context), []).error, "invalid_token", "Cloned context has no authentication marker") + eq(oauth.authorize(f.create().authenticate(bearer(token)).context).error, "invalid_token", "Contexts are isolated by resource server") + var expectedCalls = f.state.keyCalls + ;[ + [f.token(other), "Wrong signature"], [f.token(key, { exp: time - 1 }), "Expired"], + [f.token(key, { nbf: time + 30 }), "Future nbf"], [f.token(key, { iat: time + 30 }), "Future iat"], + [f.token(key, { iss: "https://other.invalid" }), "Wrong issuer"], [f.token(key, { aud: "another" }), "Wrong audience"], + [f.token(key, { exp: null }), "Missing expiry"], [f.token(key, { sub: null }), "Missing subject"], + [f.token(key, { jti: null }), "Missing ID"], [f.token(key, { client_id: null }), "Missing client ID"], + [f.token(key, { iat: null }), "Missing issued at"], [f.token(key, {}, { typ: "JWT" }), "ID token"], + [f.token(key, { cnf: { jkt: "sender" } }), "Sender-constrained token"], + [f.token(key, {}, { jku: "http://127.0.0.1/ignored" }), "Header key URL"], + [f.token(key, {}, { kid: null }), "Missing kid"], + [f.token(key, {}, {}, "PS256"), "Unconfigured algorithm"], + [token.split(".").slice(0, 2).join(".") + ".", "Unsigned token"], + [ow.server.jwt.sign("fixture-hmac-key-material-fixture", { headers: { kid: "a" } }), "Symmetric algorithm"], + ["invalid.jwt", "Malformed JWT"], ["A".repeat(16500), "Oversized credentials"] + ].forEach(test => { + var failed = oauth.authenticate(bearer(test[0])) + eq(failed.ok, false, test[1]) + }) + eq(oauth.authenticate(bearer(f.token(key, { aud: ["other", f.config.resource] }))).ok, true, "Multiple audiences") + eq(f.state.keyCalls, expectedCalls, "Cached validation sends no provider requests") + eq(oauth.authenticate({ header: {}, params: { access_token: token } }).error, "invalid_request", "Query tokens rejected") + eq(oauth.authenticate({ header: { authorization: [token, token] } }).error, "invalid_request", "Duplicate headers rejected") + eq(oauth.authenticate({ header: {} }).error, "missing", "Missing credentials") + eq(oauth.authenticate({ header: { authorization: "Basic ZGVtbw==" } }).error, "missing", "Unsupported credential scheme") + eq(oauth.metadataURI(), f.root + "/.well-known/oauth-protected-resource/nested/mcp", "Nested metadata URL") + eq(oauth.metadata().scopes_supported, ["discover"], "Advertised scopes are independent") + eq(oauth.challenge("insufficient_scope", ["write"]).header["WWW-Authenticate"].indexOf('scope="read write"') > 0, + true, "403 includes combined requirements") + checkThrows(() => f.create({ algorithms: ["HS256"] }), "Invalid algorithm") + checkThrows(() => f.create({ allowLoopbackHTTP: false }), "Loopback HTTP must be explicit") + checkThrows(() => f.create({ issuer: "http://not-loopback.invalid" }), "Non-loopback HTTP rejected") + checkThrows(() => f.create({ discovery: false }), "Disabled discovery requires endpoint") + var kc = f.create({ jwtProfile: "keycloak" }) + eq(kc.authenticate(bearer(f.token(key, { typ: "Bearer" }, { typ: "JWT" }))).ok, true, "Keycloak access type") + rejected(kc, f.token(key, { typ: "ID" }, { typ: "JWT" }), "invalid_token", "Keycloak ID type") + var typed = f.create({ jwtProfile: "typed", accessTokenClaim: "token_use", accessTokenValue: "access" }) + eq(typed.authenticate(bearer(f.token(key, { token_use: "access" }, { typ: "JWT" }))).ok, true, "Custom access type") + rejected(typed, f.token(key, { token_use: "id" }, { typ: "JWT" }), "invalid_token", "Custom type rejects ID token") + ;["PS256", "ES256"].forEach(algorithm => { + var algorithmKey = f.keys(algorithm, algorithm) + f.state.keys = [algorithmKey.jwk] + eq(f.create({ algorithms: [algorithm] }).authenticate(bearer(f.token(algorithmKey, {}, {}, algorithm))).ok, true, + "Explicit " + algorithm + " validation") + }) + }) + + exports.testKeyLifecycle = () => fixture(f => { + var first = f.keys("first"), second = f.keys("second"), unknown = f.keys("unknown") + f.state.keys = [first.jwk] + f.state.oidc = true + var oauth = f.create({ refreshCooldownMs: 200, jwksCacheTTL: 1000, timeoutMs: 400 }) + var a = f.token(first), b = f.token(second), c = f.token(unknown) + f.state.keyDelay = 50 + var checks = parallel4Array([1, 2, 3, 4], () => oauth.authenticate(bearer(a)).ok, 4) + eq(checks, [true, true, true, true], "Concurrent initial key reads") + eq(f.state.keyCalls, 1, "Initial refresh coalesced") + rejected(oauth, c, "invalid_token", "Unknown key in cooldown") + eq(f.state.keyCalls, 1, "Unknown key cooldown suppresses fetch") + sleep(215, true) + f.state.keys = [second.jwk] + eq(oauth.authenticate(bearer(b)).ok, true, "New kid refreshes JWKS") + rejected(oauth, a, "invalid_token", "Retired key removed after rotation") + eq(f.state.keyCalls, 2, "Rotation refreshes once") + f.state.keyStatus = 503 + eq(oauth.authenticate(bearer(b)).ok, true, "Fresh trusted keys survive a provider outage") + sleep(1010, true) + rejected(oauth, b, "unavailable", "Expired cache fails closed on outage") + eq(oauth.stats().jwksFailures, 1, "Failed refresh counted") + f.state.keyStatus = 200 + f.state.keys = [first.jwk, second.jwk] + var limited = f.create({ maxJwksKeys: 1 }) + rejected(limited, b, "unavailable", "JWKS count bound") + f.state.keys = [second.jwk, second.jwk] + rejected(f.create(), b, "unavailable", "Duplicate key ID") + f.state.keys = [second.jwk] + f.state.keyDelay = 200 + rejected(f.create({ timeoutMs: 60 }), b, "unavailable", "JWKS timeout") + f.state.keyDelay = 0 + f.state.keyBody = "x".repeat(2048) + rejected(f.create({ maxResponseBytes: 1024 }), b, "unavailable", "JWKS body bound") + f.state.keyBody = null + f.state.metadataIssuer = "https://other.invalid" + rejected(f.create(), b, "unavailable", "Discovery issuer must match") + f.state.metadataIssuer = null + f.state.jwksURI = "https://not-on-allowlist.invalid/jwks" + rejected(f.create(), b, "unavailable", "Discovered endpoint origin pinned") + f.state.jwksURI = null + oauth.invalidate() + eq(oauth.authenticate(bearer(b)).ok, true, "Explicit invalidation reloads key set") + oauth.close() + rejected(oauth, b, "unavailable", "Closed instance rejects tokens") + }) + + exports.testHTTPBoundary = () => fixture(f => { + var key = f.keys("boundary"), hits = 0 + f.state.keys = [key.jwk] + var oauth = f.create({ requiredScopes: ["read"] }), routes = {} + routes["/nested/mcp"] = oauth.wrap((req, server, auth) => { + hits++ + eq(req.header.authorization, __, "Handler does not receive Authorization") + return f.httpd.reply({ subject: auth.subject }, 200) + }, ["write"]) + routes[oauth.metadataPath()] = oauth.metadataHandler + f.httpd.route(f.server, routes, __, __, __, Object.keys(routes)) + checkThrows(() => f.httpd.route(f.server, { "/nested/mcp": () => f.httpd.reply("unprotected") }), "Protected route cannot be replaced") + checkThrows(() => f.httpd.route(f.server, routes, __, __, __, [oauth.metadataPath()]), "Metadata route conflict") + checkThrows(() => f.httpd.resetRoutes(f.server), "Route reset preserves reservations") + checkThrows(() => f.create({ requiredScopes: ["newline\n"] }), "Scope control character rejected at configuration") + + var request = (path, token) => { + var builder = new Packages.okhttp3.Request.Builder().url(f.root + path) + if (isDef(token)) builder.header("Authorization", "Bearer " + token) + var response = new Packages.okhttp3.OkHttpClient().newCall(builder.build()).execute() + try { return { code: response.code(), body: String(response.body().string()) } } + finally { response.close() } + } + eq(request(oauth.metadataPath()).code, 200, "Public metadata handler") + eq(request("/nested/mcp").code, 401, "Missing credentials at protected route") + eq(request("/nested/mcp", f.token(key, { scope: "read" })).code, 403, "Missing operation scope at protected route") + eq(hits, 0, "Unauthorized requests never called the handler") + eq(request("/nested/mcp", f.token(key)).code, 200, "Generic protected HTTP handler") + eq(hits, 1, "Successful handler invocation") + eq(f.create({ resource: f.root + "/" }).metadataURI(), f.root + "/.well-known/oauth-protected-resource", "Root metadata URL") + eq(f.create({ resource: f.root + "/nested/?kind=sample" }).metadataURI(), + f.root + "/.well-known/oauth-protected-resource/nested?kind=sample", "Metadata preserves query and trims trailing slash") + }) + + exports.testEntraProfiles = () => fixture(f => { + var tenant = "00001111-aaaa-2222-bbbb-3333cccc4444", aud = "99998888-dddd-7777-eeee-6666ffff5555" + var issuer = f.root + "/" + tenant + "/v2.0", key = f.keys("entra") + var claims = { iss: issuer, aud: aud, tid: tenant, azp: "aaaa0000-bb11-cc22-dd33-eeeeee444444", ver: "2.0" } + var config = { issuer: issuer, audience: aud, jwksURI: f.root + "/jwks", discovery: false } + var login = (server, extra) => server.authenticate(bearer(f.token(key, Object.assign({}, claims, extra), { typ: "JWT" }))) + f.state.keys = [Object.assign({}, key.jwk, { issuer: f.root + "/{tenantid}/v2.0" })] + var delegated = f.create(Object.assign({}, config, { jwtProfile: "entra-v2-delegated", requiredScopes: ["mcp.read"] })) + var user = login(delegated, { scp: "mcp.read" }) + eq(user.ok, true, "Entra tenant-template key and delegated token") + eq(delegated.authorize(user.context).ok, true, "Entra delegated permissions") + eq(login(delegated, {}).ok, false, "ID tokens do not have scp") + eq(login(delegated, { scp: "mcp.read", tid: aud }).ok, false, "Wrong token tenant") + eq(login(delegated, { scp: "mcp.read", ver: "1.0" }).ok, false, "V1 token rejected by the v2 profile") + var machine = f.create(Object.assign({}, config, { jwtProfile: "entra-v2-app", requiredScopes: ["Mcp.Invoke"] })) + var app = login(machine, { idtyp: "app", roles: ["Mcp.Invoke"] }) + eq(app.ok, true, "Entra application token") + eq(machine.authorize(app.context).ok, true, "Entra application permission") + eq(login(machine, { roles: ["Mcp.Invoke"] }).ok, false, "ID token roles cannot replace the app discriminator") + eq(login(machine, { idtyp: "app", roles: ["Mcp.Invoke"], scp: "mcp.read" }).ok, false, "Reject mutually exclusive claim sets") + f.state.keys = [Object.assign({}, key.jwk, { issuer: f.root + "/" + aud + "/v2.0" })] + machine.invalidate() + eq(login(machine, { idtyp: "app", roles: ["Mcp.Invoke"] }).ok, false, "A foreign tenant key cannot validate an otherwise valid token") + checkThrows(() => f.create(Object.assign({}, config, { issuer: f.root + "/common/v2.0", jwtProfile: "entra-v2-app" })), + "Tenant must be configured") + }) + + exports.testIntrospection = () => fixture(f => { + var temp = io.createTempFile("oauth-introspection", ".yaml") + io.writeFileString(temp, "{}\n") + var ref = { repo: "oauth-fixture", key: "secret", file: temp, mainSecret: "fixture-main", lockSecret: "fixture-lock" } + var store = f.httpd.__oauth2SecTokenStore(ref, "oauth-fixture") + store.withLock(ref.key, () => store.save(ref.key, "fixture p:!")) + try { + var options = { validation: "introspection", clientId: "fixture client", clientSecretSec: ref, requiredScopes: ["read"] } + var oauth = f.create(options), token = "opaque-token" + var active = { active: true, sub: "local-sub", aud: f.config.resource, exp: Math.floor(now() / 1000) + 60, + scope: "read", token_type: "Bearer" } + f.state.introspection = active + var auth = oauth.authenticate(bearer(token)) + eq(auth.ok, true, "Active resource-bound token") + eq(auth.context.issuer, f.config.issuer, "Endpoint trust supplies omitted issuer") + eq(f.state.credentials.header, "Basic " + String(java.util.Base64.getEncoder() + .encodeToString(af.fromString2Bytes("fixture+client:fixture+p%3A%21"))), "Form-encoded client_secret_basic") + eq(oauth.authorize(auth.context, ["write"]).error, "insufficient_scope", "Scope denial after introspection") + ;[ + [{ active: false }, "Inactive token despite HTTP 200"], [{ aud: "other" }, "Wrong audience"], + [{ exp: 1 }, "Expired"], [{ exp: null }, "Invalid expiration"], [{ iss: "https://other.invalid" }, "Wrong issuer"], + [{ cnf: { jkt: "sender" } }, "Sender constraint"], [{ token_type: "DPoP" }, "Unsupported token type"] + ].forEach(test => { + f.state.introspection = Object.assign({}, active, test[0]) + rejected(oauth, token, "invalid_token", test[1]) + }) + f.state.introspection = { active: "true" } + rejected(oauth, token, "unavailable", "Malformed introspection") + f.state.introspection = active + f.state.introspectionStatus = 401 + rejected(oauth, token, "unavailable", "Credential failure") + f.state.introspectionStatus = 503 + rejected(oauth, token, "unavailable", "Endpoint unavailable") + f.state.introspectionStatus = 200 + f.state.tokenDelay = 200 + rejected(f.create(Object.assign({}, options, { timeoutMs: 65 })), token, "unavailable", "Introspection timeout") + f.state.tokenDelay = 0 + var cached = f.create(Object.assign({}, options, { introspectionCacheTTL: 250, introspectionCacheMax: 1, + introspectionURL: f.root + "/introspect", introspectionAuthMethod: "client_secret_post" })) + eq(cached.authenticate(bearer(token)).ok, true, "Post credentials") + eq(f.state.credentials.form.client_secret, "fixture p:!", "Client secret in form only") + eq(f.state.credentials.header, __, "Post omits Authorization") + f.state.introspection = { active: false } + eq(cached.authenticate(bearer(token)).ok, true, "Cached success remains valid during short TTL") + sleep(275, true) + rejected(cached, token, "invalid_token", "Revocation observed after cache TTL") + f.state.introspection = active + cached.authenticate(bearer(token)) + cached.authenticate(bearer(token + "-second")) + eq(cached.stats().cacheEvictions >= 1, true, "Bounded positive cache evicts") + cached.invalidate() + f.state.introspection = { active: false } + rejected(cached, token + "-second", "invalid_token", "Invalidation clears positive entries") + eq(oauth.stats().cacheHits, 0, "Introspection cache off by default") + } finally { io.rm(temp); io.rm(temp + ".lock") } + }) +})() diff --git a/tests/autoTestAll.OAuthResource.yaml b/tests/autoTestAll.OAuthResource.yaml new file mode 100644 index 00000000..d4e77b9e --- /dev/null +++ b/tests/autoTestAll.OAuthResource.yaml @@ -0,0 +1,36 @@ +include: +- autoTestAll.common.yaml + +jobs: + +# JWT validation and resource metadata +- name: OAuthResource::JWTPolicy + to: OpenAF Test + exec: args.func = require("autoTestAll.OAuthResource.js").testJWTPolicy + +# JWKS discovery, rotation, bounds and outages +- name: OAuthResource::KeyLifecycle + to: OpenAF Test + exec: args.func = require("autoTestAll.OAuthResource.js").testKeyLifecycle + +# Protected and public HTTP route boundaries +- name: OAuthResource::HTTPBoundary + to: OpenAF Test + exec: args.func = require("autoTestAll.OAuthResource.js").testHTTPBoundary + +# Entra tenant binding and access-token profiles +- name: OAuthResource::EntraProfiles + to: OpenAF Test + exec: args.func = require("autoTestAll.OAuthResource.js").testEntraProfiles + +# Opaque token introspection and revocation +- name: OAuthResource::Introspection + to: OpenAF Test + exec: args.func = require("autoTestAll.OAuthResource.js").testIntrospection + +todo: +- OAuthResource::JWTPolicy +- OAuthResource::KeyLifecycle +- OAuthResource::HTTPBoundary +- OAuthResource::EntraProfiles +- OAuthResource::Introspection diff --git a/tests/autoTestAll.OAuthSender.js b/tests/autoTestAll.OAuthSender.js new file mode 100644 index 00000000..70ac125d --- /dev/null +++ b/tests/autoTestAll.OAuthSender.js @@ -0,0 +1,133 @@ +exports.testDPoP = function() { + ow.loadServer() + var port = findRandomOpenPort() + var base = "http://127.0.0.1:" + port + var httpd = ow.server.httpd + var hs = httpd.start(port, "127.0.0.1", __, __, __, __, 30000, "java") + var oauth = httpd.oauthResourceServer({ issuer: base, resource: base + "/reports", + allowLoopbackHTTP: true, validation: "introspection", introspectionURL: base + "/introspect", + clientId: "resource", clientSecretEnv: "PATH", + senderConstraint: { mode: "required", methods: ["dpop"] } }) + var jose = Packages.io.jsonwebtoken + var decoder = java.util.Base64.getUrlDecoder() + var thumbprint, previous, count = new java.util.concurrent.atomic.AtomicInteger() + + // Use the issuer fixture to bind an opaque access token to the proof key. + httpd.route(hs, { + "/token": req => { + var proof = req.header.dpop + var parts = proof.split(".") + var header = JSON.parse(af.fromBytes2String(decoder.decode(parts[0]))) + var jwk = jose.security.Jwks.parser().build().parse(JSON.stringify(header.jwk)) + var claims = jose.Jwts.parser().verifyWith(jwk.toKey()).build().parseSignedClaims(proof).getPayload() + if (String(claims.get("htm")) !== "POST" || String(claims.get("htu")) !== base + "/token") return httpd.reply({}, 400) + if (String(claims.get("nonce")) !== "fixture-as") return httpd.reply({ error: "use_dpop_nonce" }, 400, + "application/json", { "DPoP-Nonce": "fixture-as" }) + thumbprint = String(jwk.thumbprint()) + return httpd.reply({ access_token: "fixture-access", token_type: "DPoP", expires_in: 60 }, 200, "application/json") + }, + "/introspect": () => httpd.reply({ active: true, iss: base, sub: "machine", aud: base + "/reports", + exp: Math.floor(now() / 1000) + 60, cnf: { jkt: thumbprint }, token_type: "DPoP" }, 200, "application/json"), + "/reports": req => { + var auth = oauth.authenticate(req) + if (!auth.ok) return oauth.challenge(auth.error) + previous = req.header.dpop + count.incrementAndGet() + return httpd.reply({ sender: auth.context.senderConstraint.type }, 200, "application/json") + } + }) + var keyFile = io.createTempFile("oauth-dpop-fixture-", ".yaml") + io.writeFileString(keyFile, "{}\n") + var clientConfig = { issuer: base, clientId: "machine", tokenURL: base + "/token", clientSecret: "secret", + resource: base + "/reports", allowLoopbackHTTP: true, senderConstraint: { type: "dpop", + keyStore: { type: "sec", profile: "machine", file: keyFile, mainSecret: "fixture-main-secret", lockSecret: "fixture-lock" } } } + var client = ow.server.oauth.client(clientConfig) + try { + var rest = $rest({ auth: client, throwExceptions: true }) + var expected = false + try { rest.get(base + "/reports") } catch(e) { expected = String(e).includes("401") } + ow.test.assert(expected, true, "First DPoP request requires a resource nonce") + ow.test.assert(rest.get(base + "/reports").sender, "dpop") + ow.test.assert(rest.get(base + "/reports").sender, "dpop") + var headers = { Authorization: "DPoP fixture-access", DPoP: previous } + ow.test.assert(oauth.authenticate({ method: "GET", uri: "/reports", header: headers }).error, "invalid_dpop_proof") + ow.test.assert(oauth.authenticate({ method: "GET", uri: "/reports", + header: { Authorization: "Bearer fixture-access" } }).error, "invalid_token") + ow.test.assert(Number(count.get()), 2) + var firstKey = thumbprint + var replacement = ow.server.oauth.client(clientConfig) + try { + replacement.authenticate() + ow.test.assert(thumbprint, firstKey) + } finally { replacement.close() } + } finally { + client.close() + oauth.close() + httpd.stop(hs) + ;[keyFile, keyFile + ".lock"].forEach(file => { if (io.fileExists(file)) io.rm(file) }) + } +} + +exports.testMutualTLS = function() { + ow.loadServer() + var dir = getEnv("OPENAF_OAUTH_TLS_DIR") + var password = getEnv("OPENAF_OAUTH_TLS_PASSWORD") + var port = findRandomOpenPort(), introspectionPort = findRandomOpenPort() + var resourceOrigin = "https://localhost:" + port, resource = resourceOrigin + "/reports" + var verifierOrigin = "http://127.0.0.1:" + introspectionPort + var httpd = ow.server.httpd + + // Determine the expected binding directly from the first fixture certificate. + var store = java.security.KeyStore.getInstance("PKCS12") + var input = new java.io.FileInputStream(dir + "/client.p12") + try { store.load(input, new java.lang.String(password).toCharArray()) } finally { input.close() } + var cert = store.getCertificate("client") + var thumb = String(java.util.Base64.getUrlEncoder().withoutPadding().encodeToString( + java.security.MessageDigest.getInstance("SHA-256").digest(cert.getEncoded()))) + + // Keep the introspection service separate from the certificate-authenticated listener. + var verifier = httpd.start(introspectionPort, "127.0.0.1", __, __, __, __, 30000, "java") + var hs = httpd.start(port, "127.0.0.1", dir + "/server.p12", password, __, __, 30000, "java", + { trustStore: dir + "/clients.p12", trustStorePasswordEnv: "OPENAF_OAUTH_TLS_PASSWORD" }) + var rs = httpd.oauthResourceServer({ issuer: verifierOrigin, resource: resource, allowLoopbackHTTP: true, + validation: "introspection", introspectionURL: verifierOrigin + "/introspect", clientId: "resource", + clientSecretEnv: "OPENAF_OAUTH_TLS_PASSWORD", senderConstraint: { mode: "required", methods: ["mtls"] } }) + httpd.route(verifier, { + "/introspect": () => httpd.reply({ active: true, sub: "machine", aud: resource, + exp: Math.floor(now() / 1000) + 60, cnf: { "x5t#S256": thumb } }, 200, "application/json") + }) + httpd.route(hs, { + "/token": () => httpd.reply({ access_token: "fixture-mtls-access", token_type: "Bearer", expires_in: 60 }, + 200, "application/json"), + "/reports": rs.wrap((req, server, auth) => httpd.reply({ sender: auth.senderConstraint.type }, 200, "application/json")) + }) + var client = name => ow.server.oauth.client({ clientId: "machine", tokenURL: resourceOrigin + "/token", resource: resource, + senderConstraint: { type: "mtls", keyStore: dir + "/" + name + ".p12", keyStorePasswordEnv: "OPENAF_OAUTH_TLS_PASSWORD", + trustStore: dir + "/server.p12", trustStorePasswordEnv: "OPENAF_OAUTH_TLS_PASSWORD" } }) + var right = client("client"), wrong = client("wrong") + try { + ow.test.assert($rest({ auth: right, throwExceptions: true }).get(resource).sender, "mtls") + var denied = false + try { $rest({ auth: wrong, throwExceptions: true }).get(resource) } + catch(e) { denied = String(e).includes("401") } + ow.test.assert(denied, true) + var forged = rs.authenticate({ method: "GET", uri: "/reports", header: { + authorization: "Bearer fixture-mtls-access", "x-client-cert-thumbprint": thumb + } }) + ow.test.assert(forged.error, "invalid_token") + } finally { right.close(); wrong.close(); rs.close(); httpd.stop(hs); httpd.stop(verifier) } +} + +exports.testPostgresReplay = function() { + ow.loadServer() + var config = { url: getEnv("OPENAF_OAUTH_REPLAY_DB"), user: "postgres", + passwordEnv: "OPENAF_OAUTH_REPLAY_PASSWORD", maxEntries: 10000, allowLoopbackPlaintext: true } + var stores = [ow.server.oauth.postgresReplayStore(config), ow.server.oauth.postgresReplayStore(config)] + try { + var namespace = "fixture-" + genUUID(), key = genUUID(), expiresAt = now() + 60000 + var claims = parallel4Array(stores, store => store.claim(namespace, key, expiresAt)) + ow.test.assert(claims.filter(Boolean).length, 1) + ow.test.assert(stores[0].claim(namespace, key, expiresAt), false) + ow.test.assert(stores[1].claim(namespace, genUUID(), expiresAt), true) + } finally { stores.forEach(store => store.close()) } +} diff --git a/tests/autoTestAll.OAuthSender.yaml b/tests/autoTestAll.OAuthSender.yaml new file mode 100644 index 00000000..4475e5a9 --- /dev/null +++ b/tests/autoTestAll.OAuthSender.yaml @@ -0,0 +1,12 @@ +include: +- autoTestAll.common.yaml + +jobs: + +# Exercise DPoP token and resource proofs with a local issuer fixture. +- name: OAuthSender::DPoP + to: OpenAF Test + exec: args.func = require("autoTestAll.OAuthSender.js").testDPoP + +todo: +- OAuthSender::DPoP diff --git a/tests/autoTestAll.Server.yaml b/tests/autoTestAll.Server.yaml index eb4ce748..a2a36c6c 100644 --- a/tests/autoTestAll.Server.yaml +++ b/tests/autoTestAll.Server.yaml @@ -3,6 +3,7 @@ include: - autoTestAll.common.yaml - autoTestAll.ServerOAuth.yaml + - autoTestAll.OAuthResource.yaml jobs: # Server tests diff --git a/tests/autoTestAll.allJobs.yaml b/tests/autoTestAll.allJobs.yaml index 886563e1..bbca6dea 100644 --- a/tests/autoTestAll.allJobs.yaml +++ b/tests/autoTestAll.allJobs.yaml @@ -3,6 +3,8 @@ include: - autoTestAll.JSONC.yaml - autoTestAll.MCPOAuth.yaml +- autoTestAll.OAuthClient.yaml +- autoTestAll.OAuthSender.yaml - autoTestAll.common.yaml - autoTestAll.Test.yaml - autoTestAll.Desktop.yaml diff --git a/tests/java/HybridOAuthTlsTest.java b/tests/java/HybridOAuthTlsTest.java new file mode 100644 index 00000000..54c6d0f9 --- /dev/null +++ b/tests/java/HybridOAuthTlsTest.java @@ -0,0 +1,70 @@ +import java.io.InputStream; +import java.net.InetAddress; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.util.concurrent.FutureTask; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLException; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLServerSocket; +import javax.net.ssl.SSLSocket; +import openaf.oauth.HybridTlsProfile; + +/** Run with a local PKCS12 localhost key and a trust store containing its certificate. */ +public class HybridOAuthTlsTest { + private static void exchange(SSLContext context, HybridTlsProfile profile, String group, boolean expected) + throws Exception { + try (SSLServerSocket listener = (SSLServerSocket) context.getServerSocketFactory() + .createServerSocket(0, 1, InetAddress.getLoopbackAddress())) { + // Restrict the peer to a single group so the handshake proves the selected policy. + SSLParameters parameters = listener.getSSLParameters(); + parameters.setNamedGroups(new String[] { group }); + parameters.setProtocols(new String[] { "TLSv1.3" }); + listener.setSSLParameters(parameters); + listener.setSoTimeout(5000); + + FutureTask peer = new FutureTask<>(() -> { + try (SSLSocket connection = (SSLSocket) listener.accept()) { + connection.setSoTimeout(5000); + connection.startHandshake(); + return true; + } catch (SSLException e) { + return false; + } + }); + Thread.ofVirtual().start(peer); + + boolean connected; + try (SSLSocket attempt = (SSLSocket) profile.createSocket("localhost", listener.getLocalPort())) { + attempt.setSoTimeout(5000); + attempt.startHandshake(); + connected = true; + } catch (SSLException e) { + connected = false; + } + if (connected != expected || peer.get(5, TimeUnit.SECONDS) != expected) { + throw new AssertionError("Unexpected handshake result for " + group); + } + } + } + + public static void main(String[] args) throws Exception { + char[] password = args[1].toCharArray(); + KeyStore keys = KeyStore.getInstance("PKCS12"); + try (InputStream input = Files.newInputStream(Path.of(args[0]))) { + keys.load(input, password); + } + KeyManagerFactory managers = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + managers.init(keys, password); + SSLContext context = SSLContext.getInstance("TLSv1.3", "SunJSSE"); + context.init(managers.getKeyManagers(), null, null); + + HybridTlsProfile profile = new HybridTlsProfile(); + exchange(context, profile, "X25519MLKEM768", true); + exchange(context, profile, "x25519", false); + System.out.println("PASS hybrid-only and classical-only handshakes"); + } +}