The open-source agent harness - the runtime layer that turns an LLM into a working agent.
AGE-1621: Add user auth API stubs and config (#63)
Heer Ambavi4e48e9deaf79
diff --git a/fern/openapi/openapi.json b/fern/openapi/openapi.jsonindex 8d329a496..37041cf84 100644--- a/fern/openapi/openapi.json+++ b/fern/openapi/openapi.json@@ -203,6 +203,28 @@},"type": "object"},+ "AuthMeResponse": {+ "properties": {+ "role": {+ "$ref": "#/components/schemas/AuthRole"+ },+ "user_ref": {+ "type": "string"+ }+ },+ "required": [+ "user_ref",+ "role"+ ],+ "type": "object"+ },+ "AuthRole": {+ "enum": [+ "admin",+ "user"+ ],+ "type": "string"+ },"BaseMCPAuthRequiredEvent": {"properties": {"created_at": {@@ -1378,20 +1400,6 @@],"type": "object"},- "McpOAuthCallbackSuccess": {- "properties": {- "success": {- "enum": [- true- ],- "type": "boolean"- }- },- "required": [- "success"- ],- "type": "object"- },"McpServerDcrAuth": {"additionalProperties": false,"properties": {@@ -3246,6 +3254,143 @@},"openapi": "3.1.0","paths": {+ "/api/v1/auth/callback": {+ "get": {+ "description": "Browser-redirect target hit by the identity provider after login, never called directly by SDK consumers. In local/single-binary mode, redirects straight back into the app.",+ "parameters": [+ {+ "description": "Authorization code, present when the user granted consent.",+ "in": "query",+ "name": "code",+ "required": false,+ "schema": {+ "description": "Authorization code, present when the user granted consent.",+ "minLength": 1,+ "type": "string"+ }+ },+ {+ "description": "Opaque token; correlates this callback to its pending login. Always present, success or error.",+ "in": "query",+ "name": "state",+ "required": true,+ "schema": {+ "description": "Opaque token; correlates this callback to its pending login. Always present, success or error.",+ "minLength": 1,+ "type": "string"+ }+ },+ {+ "description": "Error code from the identity provider, present instead of `code` if the user denied consent.",+ "in": "query",+ "name": "error",+ "required": false,+ "schema": {+ "description": "Error code from the identity provider, present instead of `code` if the user denied consent.",+ "type": "string"+ }+ },+ {+ "in": "query",+ "name": "error_description",+ "required": false,+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "302": {+ "description": "Redirect back into the app on success, or to /login?error=... on failure."+ }+ },+ "summary": "Login callback",+ "tags": [+ "Auth"+ ],+ "x-fern-ignore": true+ }+ },+ "/api/v1/auth/login": {+ "get": {+ "description": "Redirects the browser to the configured identity provider. In local/single-binary mode, redirects straight back into the app — there is nothing to log into.",+ "parameters": [+ {+ "description": "Path to return to after login. Must be a same-origin relative path; anything else falls back to \"/\".",+ "in": "query",+ "name": "return_to",+ "required": false,+ "schema": {+ "description": "Path to return to after login. Must be a same-origin relative path; anything else falls back to \"/\".",+ "type": "string"+ }+ }+ ],+ "responses": {+ "302": {+ "description": "Redirect to the IdP authorization endpoint."+ }+ },+ "summary": "Start the login flow",+ "tags": [+ "Auth"+ ],+ "x-fern-ignore": true+ }+ },+ "/api/v1/auth/logout": {+ "post": {+ "description": "Ends the local harness session only — does not hit the IdP end-session endpoint. A no-op in local/single-binary mode, since there is no real session to clear.",+ "responses": {+ "204": {+ "description": "Session cookie cleared."+ }+ },+ "summary": "Clear the local session",+ "tags": [+ "Auth"+ ],+ "x-fern-sdk-group-name": [+ "auth"+ ],+ "x-fern-sdk-method-name": "logout"+ }+ },+ "/api/v1/auth/me": {+ "get": {+ "description": "Returns the fixed local identity in local/single-binary mode; otherwise the caller's verified identity.",+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AuthMeResponse"+ }+ }+ },+ "description": "The caller's identity."+ },+ "401": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "Not authenticated."+ }+ },+ "summary": "Get the current identity",+ "tags": [+ "Auth"+ ],+ "x-fern-sdk-group-name": [+ "auth"+ ],+ "x-fern-sdk-method-name": "me"+ }+ },"/api/v1/capabilities": {"get": {"description": "Report optional runtime capabilities available for this tenant.",@@ -3300,34 +3445,34 @@"get": {"parameters": [{- "description": "Opaque token; correlates this callback to its pending authorization.",+ "description": "Authorization code, present when the user granted consent.","in": "query",- "name": "state",- "required": true,+ "name": "code",+ "required": false,"schema": {- "description": "Opaque token; correlates this callback to its pending authorization.",+ "description": "Authorization code, present when the user granted consent.","minLength": 1,"type": "string"}},{- "description": "Authorization code, present when the user granted consent.",+ "description": "Opaque token; correlates this callback to its pending login. Always present, success or error.","in": "query",- "name": "code",- "required": false,+ "name": "state",+ "required": true,"schema": {- "description": "Authorization code, present when the user granted consent.",+ "description": "Opaque token; correlates this callback to its pending login. Always present, success or error.","minLength": 1,"type": "string"}},{- "description": "OAuth error code, present instead of `code` if the user denied consent or the IdP errored.",+ "description": "Error code from the identity provider, present instead of `code` if the user denied consent.","in": "query","name": "error","required": false,"schema": {- "description": "OAuth error code, present instead of `code` if the user denied consent or the IdP errored.",+ "description": "Error code from the identity provider, present instead of `code` if the user denied consent.","type": "string"}},@@ -3345,7 +3490,18 @@"content": {"application/json": {"schema": {- "$ref": "#/components/schemas/McpOAuthCallbackSuccess"+ "properties": {+ "success": {+ "enum": [+ true+ ],+ "type": "boolean"+ }+ },+ "required": [+ "success"+ ],+ "type": "object"}}},diff --git a/packages/sdk/.fern/metadata.json b/packages/sdk/.fern/metadata.jsonindex f5fe89838..f750a2858 100644--- a/packages/sdk/.fern/metadata.json+++ b/packages/sdk/.fern/metadata.json@@ -27,9 +27,10 @@"streamType": "web","useDefaultRequestParameterValues": true},- "originGitCommit": "5a96f5b12e75f7092b45ab8e8e74216603898fdd",+ "originGitCommit": "7d0c801e20eea2050de9b248836faf98f5425c43","originGitCommitIsDirty": true,- "invokedBy": "manual",+ "invokedBy": "ci","requestedVersion": "0.0.0",+ "ciProvider": "github","sdkVersion": "0.0.0"}diff --git a/packages/sdk/README.md b/packages/sdk/README.mdindex e0a20eea1..db6b370a3 100644--- a/packages/sdk/README.md+++ b/packages/sdk/README.md@@ -109,9 +109,9 @@ for await (const item of response) {This SDK supports direct imports of subpackage clients, which allows JavaScript bundlers to tree-shake and include only the imported subpackage code. This results in much smaller bundle sizes.```typescript-import { ServerClient } from 'trueforge/server';+import { AuthClient } from 'trueforge/auth';-const client = new ServerClient({...});+const client = new AuthClient({...});```### Additional Headersdiff --git a/packages/sdk/package.json b/packages/sdk/package.jsonindex 9000eda14..be118f369 100644--- a/packages/sdk/package.json+++ b/packages/sdk/package.json@@ -29,6 +29,17 @@},"default": "./dist/cjs/serialization/index.js"},+ "./auth": {+ "import": {+ "types": "./dist/esm/api/resources/auth/exports.d.mts",+ "default": "./dist/esm/api/resources/auth/exports.mjs"+ },+ "require": {+ "types": "./dist/cjs/api/resources/auth/exports.d.ts",+ "default": "./dist/cjs/api/resources/auth/exports.js"+ },+ "default": "./dist/cjs/api/resources/auth/exports.js"+ },"./server": {"import": {"types": "./dist/esm/api/resources/server/exports.d.mts",diff --git a/packages/sdk/reference.md b/packages/sdk/reference.mdindex 48b2e544e..677489b7b 100644--- a/packages/sdk/reference.md+++ b/packages/sdk/reference.md@@ -1,4 +1,115 @@# Reference+## Auth+<details><summary><code>client.auth.<a href="/src/api/resources/auth/client/Client.ts">logout</a>() -> void</code></summary>+<dl>+<dd>++#### 📝 Description++<dl>+<dd>++<dl>+<dd>++Ends the local harness session only — does not hit the IdP end-session endpoint. A no-op in local/single-binary mode, since there is no real session to clear.+</dd>+</dl>+</dd>+</dl>++#### 🔌 Usage++<dl>+<dd>++<dl>+<dd>++```typescript+await client.auth.logout();++```+</dd>+</dl>+</dd>+</dl>++#### ⚙️ Parameters++<dl>+<dd>++<dl>+<dd>++**requestOptions:** `AuthClient.RequestOptions`++</dd>+</dl>+</dd>+</dl>+++</dd>+</dl>+</details>++<details><summary><code>client.auth.<a href="/src/api/resources/auth/client/Client.ts">me</a>() -> TrueForge.AuthMeResponse</code></summary>+<dl>+<dd>++#### 📝 Description++<dl>+<dd>++<dl>+<dd>++Returns the fixed local identity in local/single-binary mode; otherwise the caller's verified identity.+</dd>+</dl>+</dd>+</dl>++#### 🔌 Usage++<dl>+<dd>++<dl>+<dd>++```typescript+await client.auth.me();++```+</dd>+</dl>+</dd>+</dl>++#### ⚙️ Parameters++<dl>+<dd>++<dl>+<dd>++**requestOptions:** `AuthClient.RequestOptions`++</dd>+</dl>+</dd>+</dl>+++</dd>+</dl>+</details>+## Server<details><summary><code>client.server.<a href="/src/api/resources/server/client/Client.ts">getCapabilities</a>() -> TrueForge.GetCapabilitiesResponse</code></summary><dl>diff --git a/packages/sdk/src/Client.ts b/packages/sdk/src/Client.tsindex 31c4b0a32..c8d5a9fac 100644--- a/packages/sdk/src/Client.ts+++ b/packages/sdk/src/Client.ts@@ -1,5 +1,6 @@// This file was auto-generated by Fern from our API Definition.+import { AuthClient } from "./api/resources/auth/client/Client.js";import { McpServersClient } from "./api/resources/mcpServers/client/Client.js";import { ModelsClient } from "./api/resources/models/client/Client.js";import { ServerClient } from "./api/resources/server/client/Client.js";@@ -18,6 +19,7 @@ export declare namespace TrueForge {export class TrueForge {protected readonly _options: NormalizedClientOptions<TrueForge.Options>;+ protected _auth: AuthClient | undefined;protected _server: ServerClient | undefined;protected _mcpServers: McpServersClient | undefined;protected _models: ModelsClient | undefined;@@ -29,6 +31,10 @@ export class TrueForge {this._options = normalizeClientOptions(options);}+ public get auth(): AuthClient {+ return (this._auth ??= new AuthClient(this._options));+ }+public get server(): ServerClient {return (this._server ??= new ServerClient(this._options));}diff --git a/packages/sdk/src/api/resources/auth/client/Client.ts b/packages/sdk/src/api/resources/auth/client/Client.tsnew file mode 100644index 000000000..d00559e8c--- /dev/null+++ b/packages/sdk/src/api/resources/auth/client/Client.ts@@ -0,0 +1,144 @@+// This file was auto-generated by Fern from our API Definition.++import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js";+import { type NormalizedClientOptions, normalizeClientOptions } from "../../../../BaseClient.js";+import { mergeHeaders } from "../../../../core/headers.js";+import * as core from "../../../../core/index.js";+import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js";+import * as errors from "../../../../errors/index.js";+import * as serializers from "../../../../serialization/index.js";+import * as TrueForge from "../../../index.js";++export declare namespace AuthClient {+ export type Options = BaseClientOptions;++ export interface RequestOptions extends BaseRequestOptions {}+}++export class AuthClient {+ protected readonly _options: NormalizedClientOptions<AuthClient.Options>;++ constructor(options: AuthClient.Options) {+ this._options = normalizeClientOptions(options);+ }++ /**+ * Ends the local harness session only — does not hit the IdP end-session endpoint. A no-op in local/single-binary mode, since there is no real session to clear.+ *+ * @param {AuthClient.RequestOptions} requestOptions - Request-specific configuration.+ *+ * @throws {@link errors.TrueForgeError}+ * @throws {@link errors.TrueForgeTimeoutError}+ *+ * @example+ * await client.auth.logout()+ */+ public logout(requestOptions?: AuthClient.RequestOptions): core.HttpResponsePromise<void> {+ return core.HttpResponsePromise.fromPromise(this.__logout(requestOptions));+ }++ private async __logout(requestOptions?: AuthClient.RequestOptions): Promise<core.WithRawResponse<void>> {+ const _headers: core.Fetcher.Args["headers"] = mergeHeaders(this._options?.headers, requestOptions?.headers);+ const _response = await (this._options.fetcher ?? core.fetcher)({+ url: core.url.join(+ (await core.Supplier.get(this._options.baseUrl)) ??+ (await core.Supplier.get(this._options.environment)),+ "api/v1/auth/logout",+ ),+ method: "POST",+ headers: _headers,+ queryString: core.url.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,+ abortSignal: requestOptions?.abortSignal,+ fetchFn: this._options?.fetch,+ logging: this._options.logging,+ });+ if (_response.ok) {+ return { data: undefined, rawResponse: _response.rawResponse };+ }++ if (_response.error.reason === "status-code") {+ throw new errors.TrueForgeError({+ statusCode: _response.error.statusCode,+ body: _response.error.body,+ rawResponse: _response.rawResponse,+ });+ }++ return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/api/v1/auth/logout");+ }++ /**+ * Returns the fixed local identity in local/single-binary mode; otherwise the caller's verified identity.+ *+ * @param {AuthClient.RequestOptions} requestOptions - Request-specific configuration.+ *+ * @throws {@link TrueForge.UnauthorizedError}+ * @throws {@link errors.TrueForgeError}+ * @throws {@link errors.TrueForgeTimeoutError}+ *+ * @example+ * await client.auth.me()+ */+ public me(requestOptions?: AuthClient.RequestOptions): core.HttpResponsePromise<TrueForge.AuthMeResponse> {+ return core.HttpResponsePromise.fromPromise(this.__me(requestOptions));+ }++ private async __me(+ requestOptions?: AuthClient.RequestOptions,+ ): Promise<core.WithRawResponse<TrueForge.AuthMeResponse>> {+ const _headers: core.Fetcher.Args["headers"] = mergeHeaders(this._options?.headers, requestOptions?.headers);+ const _response = await (this._options.fetcher ?? core.fetcher)({+ url: core.url.join(+ (await core.Supplier.get(this._options.baseUrl)) ??+ (await core.Supplier.get(this._options.environment)),+ "api/v1/auth/me",+ ),+ method: "GET",+ headers: _headers,+ queryString: core.url.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,+ abortSignal: requestOptions?.abortSignal,+ fetchFn: this._options?.fetch,+ logging: this._options.logging,+ });+ if (_response.ok) {+ return {+ data: serializers.AuthMeResponse.parseOrThrow(_response.body, {+ unrecognizedObjectKeys: "passthrough",+ allowUnrecognizedUnionMembers: true,+ allowUnrecognizedEnumValues: true,+ skipValidation: true,+ breadcrumbsPrefix: ["response"],+ }),+ rawResponse: _response.rawResponse,+ };+ }++ if (_response.error.reason === "status-code") {+ switch (_response.error.statusCode) {+ case 401:+ throw new TrueForge.UnauthorizedError(+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {+ unrecognizedObjectKeys: "passthrough",+ allowUnrecognizedUnionMembers: true,+ allowUnrecognizedEnumValues: true,+ skipValidation: true,+ breadcrumbsPrefix: ["response"],+ }),+ _response.rawResponse,+ );+ default:+ throw new errors.TrueForgeError({+ statusCode: _response.error.statusCode,+ body: _response.error.body,+ rawResponse: _response.rawResponse,+ });+ }+ }++ return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/api/v1/auth/me");+ }+}diff --git a/packages/sdk/src/api/resources/auth/client/index.ts b/packages/sdk/src/api/resources/auth/client/index.tsnew file mode 100644index 000000000..cb0ff5c3b--- /dev/null+++ b/packages/sdk/src/api/resources/auth/client/index.ts@@ -0,0 +1 @@+export {};diff --git a/packages/sdk/src/api/resources/auth/exports.ts b/packages/sdk/src/api/resources/auth/exports.tsnew file mode 100644index 000000000..2e97f0e93--- /dev/null+++ b/packages/sdk/src/api/resources/auth/exports.ts@@ -0,0 +1,4 @@+// This file was auto-generated by Fern from our API Definition.++export { AuthClient } from "./client/Client.js";+export * from "./client/index.js";diff --git a/packages/sdk/src/api/resources/auth/index.ts b/packages/sdk/src/api/resources/auth/index.tsnew file mode 100644index 000000000..914b8c3c7--- /dev/null+++ b/packages/sdk/src/api/resources/auth/index.ts@@ -0,0 +1 @@+export * from "./client/index.js";diff --git a/packages/sdk/src/api/resources/index.ts b/packages/sdk/src/api/resources/index.tsindex 73368c63a..f708829ee 100644--- a/packages/sdk/src/api/resources/index.ts+++ b/packages/sdk/src/api/resources/index.ts@@ -1,3 +1,4 @@+export * as auth from "./auth/index.js";export * from "./mcpServers/client/requests/index.js";export * as mcpServers from "./mcpServers/index.js";export * as models from "./models/index.js";diff --git a/packages/sdk/src/api/types/AuthMeResponse.ts b/packages/sdk/src/api/types/AuthMeResponse.tsnew file mode 100644index 000000000..c68ca9132--- /dev/null+++ b/packages/sdk/src/api/types/AuthMeResponse.ts@@ -0,0 +1,8 @@+// This file was auto-generated by Fern from our API Definition.++import type * as TrueForge from "../index.js";++export interface AuthMeResponse {+ role: TrueForge.AuthRole;+ userRef: string;+}diff --git a/packages/sdk/src/api/types/AuthRole.ts b/packages/sdk/src/api/types/AuthRole.tsnew file mode 100644index 000000000..738757338--- /dev/null+++ b/packages/sdk/src/api/types/AuthRole.ts@@ -0,0 +1,7 @@+// This file was auto-generated by Fern from our API Definition.++export const AuthRole = {+ Admin: "admin",+ User: "user",+} as const;+export type AuthRole = (typeof AuthRole)[keyof typeof AuthRole];diff --git a/packages/sdk/src/api/types/index.ts b/packages/sdk/src/api/types/index.tsindex d5c6e2d3a..fcbbb3349 100644--- a/packages/sdk/src/api/types/index.ts+++ b/packages/sdk/src/api/types/index.ts@@ -8,6 +8,8 @@ export * from "./ApprovalAllow.js";export * from "./ApprovalDecision.js";export * from "./ApprovalDeny.js";export * from "./AskUserQuestionsConfig.js";+export * from "./AuthMeResponse.js";+export * from "./AuthRole.js";export * from "./BaseMcpAuthRequiredEvent.js";export * from "./BaseThreadDoneEvent.js";export * from "./CallerSuppliedModelProvider.js";diff --git a/packages/sdk/src/serialization/types/AuthMeResponse.ts b/packages/sdk/src/serialization/types/AuthMeResponse.tsnew file mode 100644index 000000000..e47c5b9a5--- /dev/null+++ b/packages/sdk/src/serialization/types/AuthMeResponse.ts@@ -0,0 +1,19 @@+// This file was auto-generated by Fern from our API Definition.++import type * as TrueForge from "../../api/index.js";+import * as core from "../../core/index.js";+import type * as serializers from "../index.js";+import { AuthRole } from "./AuthRole.js";++export const AuthMeResponse: core.serialization.ObjectSchema<serializers.AuthMeResponse.Raw, TrueForge.AuthMeResponse> =+ core.serialization.object({+ role: AuthRole,+ userRef: core.serialization.property("user_ref", core.serialization.string()),+ });++export declare namespace AuthMeResponse {+ export interface Raw {+ role: AuthRole.Raw;+ user_ref: string;+ }+}diff --git a/packages/sdk/src/serialization/types/AuthRole.ts b/packages/sdk/src/serialization/types/AuthRole.tsnew file mode 100644index 000000000..9b64cbf46--- /dev/null+++ b/packages/sdk/src/serialization/types/AuthRole.ts@@ -0,0 +1,12 @@+// This file was auto-generated by Fern from our API Definition.++import type * as TrueForge from "../../api/index.js";+import * as core from "../../core/index.js";+import type * as serializers from "../index.js";++export const AuthRole: core.serialization.Schema<serializers.AuthRole.Raw, TrueForge.AuthRole> =+ core.serialization.enum_(["admin", "user"]);++export declare namespace AuthRole {+ export type Raw = "admin" | "user";+}diff --git a/packages/sdk/src/serialization/types/index.ts b/packages/sdk/src/serialization/types/index.tsindex d5c6e2d3a..fcbbb3349 100644--- a/packages/sdk/src/serialization/types/index.ts+++ b/packages/sdk/src/serialization/types/index.ts@@ -8,6 +8,8 @@ export * from "./ApprovalAllow.js";export * from "./ApprovalDecision.js";export * from "./ApprovalDeny.js";export * from "./AskUserQuestionsConfig.js";+export * from "./AuthMeResponse.js";+export * from "./AuthRole.js";export * from "./BaseMcpAuthRequiredEvent.js";export * from "./BaseThreadDoneEvent.js";export * from "./CallerSuppliedModelProvider.js";diff --git a/packages/sdk/tests/wire/auth.test.ts b/packages/sdk/tests/wire/auth.test.tsnew file mode 100644index 000000000..e7bed7104--- /dev/null+++ b/packages/sdk/tests/wire/auth.test.ts@@ -0,0 +1,45 @@+// This file was auto-generated by Fern from our API Definition.++import * as TrueForgeTypes from "../../src/api/index";+import { TrueForge } from "../../src/Client";+import { mockServerPool } from "../mock-server/MockServerPool";++describe("AuthClient", () => {+ test("logout", async () => {+ const server = mockServerPool.createServer();+ const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });++ server.mockEndpoint().post("/api/v1/auth/logout").respondWith().statusCode(200).build();++ const response = await client.auth.logout();+ expect(response).toEqual(undefined);+ });++ test("me (1)", async () => {+ const server = mockServerPool.createServer();+ const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });++ const rawResponseBody = { role: "admin", user_ref: "user_ref" };++ server.mockEndpoint().get("/api/v1/auth/me").respondWith().statusCode(200).jsonBody(rawResponseBody).build();++ const response = await client.auth.me();+ expect(response).toEqual({+ role: "admin",+ userRef: "user_ref",+ });+ });++ test("me (2)", async () => {+ const server = mockServerPool.createServer();+ const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });++ const rawResponseBody = { error: { message: "message" } };++ server.mockEndpoint().get("/api/v1/auth/me").respondWith().statusCode(401).jsonBody(rawResponseBody).build();++ await expect(async () => {+ return await client.auth.me();+ }).rejects.toThrow(TrueForgeTypes.UnauthorizedError);+ });+});diff --git a/packages/server/.env.example b/packages/server/.env.exampleindex e362b144b..a7e49cb9a 100644--- a/packages/server/.env.example+++ b/packages/server/.env.example@@ -52,7 +52,21 @@ PORT=8790# `docker-compose.yml` overrides this to redis://redis:6379 for the server container.REDIS_URL=redis://localhost:6379-# Resumable turn stream settings. All are optional.+# Redis request/reply peering knobs (STANDALONE=false only). All optional.+# Max ms to wait for a peer executor's reply before failing with 424. Default 60000.+# REDIS_REQUEST_REPLY_TIMEOUT_MS=60000+# How often this process refreshes its peering heartbeat key. Default 5000.+# REDIS_REQUEST_REPLY_HEARTBEAT_INTERVAL_MS=5000+# TTL for reply values so abandoned reply keys are reclaimed. Default 120000.+# REDIS_REQUEST_REPLY_REPLY_TTL_MS=120000+# Sleep between reply poll attempts while waiting on a peer. Default 500.+# REDIS_REQUEST_REPLY_POLL_INTERVAL_MS=500++# Turn execution and resumable stream settings. All optional.+# Max seconds a single turn may run before cancellation. Default 600 (10 minutes).+# SERVER_EXECUTION_TIMEOUT_SECONDS=600+# Max seconds to wait for turn cancellation + connection drain on SIGTERM/SIGINT. Default 30.+# GRACEFUL_TIMEOUT_SECONDS=30# Active stream TTL defaults to SERVER_EXECUTION_TIMEOUT_SECONDS + 300.# TURN_STREAM_TTL_SECONDS=900# Completed streams remain available for 5 minutes by default.@@ -60,14 +74,23 @@ REDIS_URL=redis://localhost:6379# A subscribe request stays open for 10 minutes by default.# TURN_SUBSCRIBE_TIMEOUT_MS=600000+# PUBLIC_BASE_URL — origin of the fixed callback routes for server OIDC and+# MCP OAuth/DCR. Optional; defaults to http://localhost:${PORT}.+# PUBLIC_BASE_URL=http://localhost:8790+# ----------------------------------------------------------------------------# MCP OAuth (DCR). PUBLIC_BASE_URL is the origin of the fixed callback route-# {PUBLIC_BASE_URL}/api/v1/mcp-servers/oauth/callback (not trimmed). Optional;-# defaults to http://localhost:${PORT}. OAUTH_CLIENT_NAME is the RFC 7591-# client_name on the consent screen (default: truefoundry-harness).+MCP knobs.# ----------------------------------------------------------------------------# PUBLIC_BASE_URL=http://localhost:8790-# OAUTH_CLIENT_NAME=truefoundry-harness+# Client name used for Dynamic Client Registration (DCR) of MCP servers.+# This is the client name shown on authorization-server consent screens.+# Optional; defaults to truefoundry-harness.+# MCP_DCR_OAUTH_CLIENT_NAME=truefoundry-harness++# MCP client timeouts. All optional.+# Max ms for one MCP request. Default 240000 (4 minutes).+# MCP_REQUEST_TIMEOUT_MS=240000+# Max ms for an MCP transport connection. Default 30000.+# MCP_CONNECT_TIMEOUT_MS=30000# ---------------------------------------------------------------------------# Sandbox process knobs. Provider identity/credentials are configured via@@ -96,3 +119,11 @@ POSTGRES_PORT=5432# Shared by the app pool and migrations. Optional, defaults to 60000 each.# POSTGRES_STATEMENT_TIMEOUT_MS=60000# POSTGRES_IDLE_IN_TRANSACTION_SESSION_TIMEOUT_MS=60000++# ---------------------------------------------------------------------------+# OIDC (used when STANDALONE=false). All three must be set together, or all+# left unset. Unset = fixed local admin identity (no IdP). Ignored in standalone.+# ---------------------------------------------------------------------------+# OIDC_ISSUER_URL=https://your-tenant.example.com/oauth2/default+# OIDC_CLIENT_ID=+# OIDC_CLIENT_SECRET=diff --git a/packages/server/.env.test b/packages/server/.env.testindex b7d1080f3..531d915db 100644--- a/packages/server/.env.test+++ b/packages/server/.env.test@@ -6,4 +6,4 @@ POSTGRES_DB=testPOSTGRES_HOST=localhostPOSTGRES_PORT=5432PUBLIC_BASE_URL=https://harness.example.com-OAUTH_CLIENT_NAME=truefoundry-harness+MCP_DCR_OAUTH_CLIENT_NAME=truefoundry-harnessdiff --git a/packages/server/src/apis/auth.ts b/packages/server/src/apis/auth.tsnew file mode 100644index 000000000..4ee25fe77--- /dev/null+++ b/packages/server/src/apis/auth.ts@@ -0,0 +1,51 @@+/**+ * Auth API (mounted at /api/v1/auth).+ *+ * For the no-identity-provider (local/single-binary) case,+ * `/me` always succeeds with a fixed local identity.+ */+import { OpenAPIHono } from '@hono/zod-openapi';+import { isOidcConfigured } from '../config';+import { authLoginRoute, authLogoutRoute, authMeRoute, oAuthCallbackRoute } from '../routes/authRoutes';+import type { AuthMeResponse } from '../schemas/auth';++/** Fixed identity used when no identity provider is configured. */+const LOCAL_USER: AuthMeResponse = {+ user_ref: 'trueforge-default',+ role: 'admin',+};++export function createAuthRouter() {+ const router = new OpenAPIHono();++ router.openapi(authLoginRoute, c => {+ if (!isOidcConfigured()) {+ return c.redirect('/', 302);+ }+ // TODO: Implement the actual login redirect to the identity provider.+ return c.redirect('/', 302);+ });++ router.openapi(oAuthCallbackRoute, c => {+ if (!isOidcConfigured()) {+ return c.redirect('/', 302);+ }+ // TODO: Implement the actual OIDC callback (code exchange, session cookie).+ return c.redirect('/', 302);+ });++ router.openapi(authLogoutRoute, c => {+ // No real session in either mode yet — always a no-op.+ return c.body(null, 204);+ });++ router.openapi(authMeRoute, c => {+ if (!isOidcConfigured()) {+ return c.json(LOCAL_USER, 200);+ }+ // TODO: Resolve the caller's verified identity from their session cookie.+ return c.json({ error: { message: 'Not authenticated' } }, 401);+ });++ return router;+}diff --git a/packages/server/src/apis/mcpServers.ts b/packages/server/src/apis/mcpServers.tsindex 4686dbc55..ac8e936dc 100644--- a/packages/server/src/apis/mcpServers.ts+++ b/packages/server/src/apis/mcpServers.ts@@ -94,7 +94,7 @@ export function createSettingsMcpServersRouter(deps: SettingsMcpServersRouterDepserverId: params.serverId,mcpServerUrl: params.mcpServerUrl,mcpServerName: params.mcpServerName,- clientName: configuration.OAUTH_CLIENT_NAME,+ clientName: configuration.MCP_DCR_OAUTH_CLIENT_NAME,}),MCP_DCR_REGISTRATION_TIMEOUT_MS,`DCR client registration for MCP server "${params.mcpServerName}"`,@@ -175,7 +175,7 @@ export function createSettingsMcpServersRouter(deps: SettingsMcpServersRouterDepname,store: deps.mcpServerStore,tokenStore: deps.tokenStore,- clientName: configuration.OAUTH_CLIENT_NAME,+ clientName: configuration.MCP_DCR_OAUTH_CLIENT_NAME,});if (connection === undefined) {return c.json({ error: { message: `MCP server not found: ${name}` } }, 404);@@ -245,7 +245,7 @@ export function createMcpServersRouter(deps: McpServersRouterDeps) {serverId: record.id,mcpServerUrl: record.manifest.url,mcpServerName: record.name,- clientName: configuration.OAUTH_CLIENT_NAME,+ clientName: configuration.MCP_DCR_OAUTH_CLIENT_NAME,...(redirectUrl !== undefined ? { redirectUrl } : {}),});const authStatus: McpAuthStatus = isMcpAuthRequired(result)diff --git a/packages/server/src/apis/turns.ts b/packages/server/src/apis/turns.tsindex 4dd6b2cc0..693bee6ca 100644--- a/packages/server/src/apis/turns.ts+++ b/packages/server/src/apis/turns.ts@@ -109,7 +109,7 @@ function createTurnResolver(deps: {name,store: mcpServerStore,tokenStore,- clientName: configuration.OAUTH_CLIENT_NAME,+ clientName: configuration.MCP_DCR_OAUTH_CLIENT_NAME,});if (connection === undefined) {throw new HTTPException(422, {diff --git a/packages/server/src/app.ts b/packages/server/src/app.tsindex b3268309b..322502dfd 100644--- a/packages/server/src/app.ts+++ b/packages/server/src/app.ts@@ -7,6 +7,7 @@ import type { Context } from 'hono';import { HTTPException } from 'hono/http-exception';import type { RedisClientType } from 'redis';import type { Logger } from 'winston';+import { createAuthRouter } from './apis/auth';import { createCapabilitiesRouter } from './apis/capabilities';import { createMcpOAuthRouter } from './apis/mcpOAuth';import { createMcpServersRouter } from './apis/mcpServers';@@ -72,6 +73,7 @@ export function createServerApp(deps: ServerDeps) {app.get('/healthz', c => c.text('OK!'));+ app.route('/api/v1/auth', createAuthRouter());app.route('/api/v1/capabilities', createCapabilitiesRouter({ sandboxProviderStore: deps.sandboxProviderStore }));app.route('/api/v1/models', createModelsRouter(deps.modelProviderStore));app.route(diff --git a/packages/server/src/config.ts b/packages/server/src/config.tsindex f1dd7dea6..836cbf14b 100644--- a/packages/server/src/config.ts+++ b/packages/server/src/config.ts@@ -205,10 +205,36 @@ function resolvePublicBaseUrl(port: number): string {return `http://localhost:${String(port)}`;}+function resolveOIDCConfig(): OIDCConfig | undefined {+ const issuerUrl = getEnv('OIDC_ISSUER_URL');+ const clientId = getEnv('OIDC_CLIENT_ID');+ const clientSecret = getEnv('OIDC_CLIENT_SECRET');++ if (!issuerUrl && !clientId && !clientSecret) {+ return undefined;+ }+ if (!issuerUrl || !clientId || !clientSecret) {+ throw new Error(+ 'OIDC_ISSUER_URL, OIDC_CLIENT_ID, and OIDC_CLIENT_SECRET must all be set together, or all left unset ' ++ '(unset = fixed local admin identity, no IdP).',+ );+ }+ return { OIDC_ISSUER_URL: issuerUrl, OIDC_CLIENT_ID: clientId, OIDC_CLIENT_SECRET: clientSecret };+}+// ============================================================================// CONFIGURATION TYPES// ============================================================================+export interface OIDCConfig {+ /** e.g. an Okta custom authorization server, or an Azure AD tenant's v2.0 endpoint. Env: `OIDC_ISSUER_URL`. */+ OIDC_ISSUER_URL: string;+ /** Env: `OIDC_CLIENT_ID`. */+ OIDC_CLIENT_ID: string;+ /** Env: `OIDC_CLIENT_SECRET`. */+ OIDC_CLIENT_SECRET: string;+}+export interface SharedServerConfiguration {/** HTTP port the server listens on. Env: `PORT`. */PORT: number;@@ -255,10 +281,11 @@ export interface SharedServerConfiguration {*/PUBLIC_BASE_URL: string;/**- * RFC 7591 client_name shown on authorization-server consent screens.- * Env: `OAUTH_CLIENT_NAME`. Default: "truefoundry-harness".+ * Client name used for Dynamic Client Registration (DCR) of MCP servers.+ * This is the client name shown on authorization-server consent screens.+ * Env: `MCP_DCR_OAUTH_CLIENT_NAME`. Default: "truefoundry-harness".*/- OAUTH_CLIENT_NAME: string;+ MCP_DCR_OAUTH_CLIENT_NAME: string;/*** Max bytes for a single file download out of the sandbox.* Env: `SANDBOX_FILE_MAX_BYTES_FOR_DOWNLOAD`. Default 20 MB (same as gateway).@@ -353,6 +380,12 @@ export type DistributedServerConfiguration = SharedServerConfiguration & {POSTGRES_IDLE_IN_TRANSACTION_SESSION_TIMEOUT_MS: number;/** Peering URL shared by all replicas. Env: `REDIS_URL`. Default `redis://localhost:6379`. */REDIS_URL: string;+ /**+ * OIDC configuration for server authentication.+ * Undefined = every request resolves to a fixed+ * local admin identity instead of a real IdP session.+ */+ OIDC: OIDCConfig | undefined;};export type ServerConfiguration = StandaloneServerConfiguration | DistributedServerConfiguration;@@ -395,7 +428,8 @@ const shared: SharedServerConfiguration = {raw: getEnv('MCP_CONNECT_TIMEOUT_MS'),defaultValue: 30 * 1000,}),- OAUTH_CLIENT_NAME: getEnv('OAUTH_CLIENT_NAME', { defaultValue: 'truefoundry-harness' }) ?? 'truefoundry-harness',+ MCP_DCR_OAUTH_CLIENT_NAME:+ getEnv('MCP_DCR_OAUTH_CLIENT_NAME', { defaultValue: 'truefoundry-harness' }) ?? 'truefoundry-harness',SANDBOX_FILE_MAX_BYTES_FOR_DOWNLOAD: parsePositiveInt({envKey: 'SANDBOX_FILE_MAX_BYTES_FOR_DOWNLOAD',raw: getEnv('SANDBOX_FILE_MAX_BYTES_FOR_DOWNLOAD'),@@ -470,6 +504,12 @@ const configuration: ServerConfiguration = standalonedefaultValue: 60_000,}),REDIS_URL: resolveRedisUrl(),+ OIDC: resolveOIDCConfig(),};+/** True when a real identity provider is configured */+export function isOidcConfigured(): boolean {+ return !configuration.STANDALONE && configuration.OIDC !== undefined;+}+export default configuration;diff --git a/packages/server/src/routes/authRoutes.ts b/packages/server/src/routes/authRoutes.tsnew file mode 100644index 000000000..00d0fdbed--- /dev/null+++ b/packages/server/src/routes/authRoutes.ts@@ -0,0 +1,79 @@+/**+ * Auth route definitions (mounted at /api/v1/auth). Handlers in apis/auth.ts.+ *+ * `login`/`callback` are browser-redirect targets, never called by SDK+ * consumers — both carry `x-fern-ignore`, the same convention used for the+ * MCP OAuth callback in mcpOAuthRoutes.ts. `me`/`logout` are real JSON+ * endpoints and generate normally.+ */+import { createRoute } from '@hono/zod-openapi';+import { AuthLoginQuerySchema, AuthMeResponseSchema, OAuthCallbackQuerySchema } from '../schemas/auth';+import { RequestErrorResponseSchema } from '../schemas/errors';++const AUTH_TAG = 'Auth';++export const authLoginRoute = createRoute({+ method: 'get',+ path: '/login',+ tags: [AUTH_TAG],+ summary: 'Start the login flow',+ description:+ 'Redirects the browser to the configured identity provider. In local/single-binary mode, redirects straight ' ++ 'back into the app — there is nothing to log into.',+ 'x-fern-ignore': true,+ request: { query: AuthLoginQuerySchema },+ responses: {+ 302: { description: 'Redirect to the IdP authorization endpoint.' },+ },+});++export const oAuthCallbackRoute = createRoute({+ method: 'get',+ path: '/callback',+ tags: [AUTH_TAG],+ summary: 'Login callback',+ description:+ 'Browser-redirect target hit by the identity provider after login, never called directly by SDK consumers. ' ++ 'In local/single-binary mode, redirects straight back into the app.',+ 'x-fern-ignore': true,+ request: { query: OAuthCallbackQuerySchema },+ responses: {+ 302: { description: 'Redirect back into the app on success, or to /login?error=... on failure.' },+ },+});++export const authLogoutRoute = createRoute({+ method: 'post',+ path: '/logout',+ tags: [AUTH_TAG],+ summary: 'Clear the local session',+ description:+ 'Ends the local harness session only — does not hit the IdP end-session endpoint. A no-op in local/single-binary ' ++ 'mode, since there is no real session to clear.',+ 'x-fern-sdk-group-name': ['auth'],+ 'x-fern-sdk-method-name': 'logout',+ responses: {+ 204: { description: 'Session cookie cleared.' },+ },+});++export const authMeRoute = createRoute({+ method: 'get',+ path: '/me',+ tags: [AUTH_TAG],+ summary: 'Get the current identity',+ description:+ "Returns the fixed local identity in local/single-binary mode; otherwise the caller's verified identity.",+ 'x-fern-sdk-group-name': ['auth'],+ 'x-fern-sdk-method-name': 'me',+ responses: {+ 200: {+ content: { 'application/json': { schema: AuthMeResponseSchema } },+ description: "The caller's identity.",+ },+ 401: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'Not authenticated.',+ },+ },+});diff --git a/packages/server/src/routes/mcpOAuthRoutes.ts b/packages/server/src/routes/mcpOAuthRoutes.tsindex cd2d644cd..9e7c40758 100644--- a/packages/server/src/routes/mcpOAuthRoutes.ts+++ b/packages/server/src/routes/mcpOAuthRoutes.ts@@ -1,24 +1,9 @@-import { createRoute, z } from '@hono/zod-openapi';+import { createRoute } from '@hono/zod-openapi';+import { OAuthCallbackQuerySchema, OAuthCallbackSuccessSchema } from '../schemas/auth';import { RequestErrorResponseSchema } from '../schemas/errors';const MCP_OAUTH_TAG = 'MCP OAuth';-const McpOAuthCallbackQuerySchema = z.object({- state: z.string().min(1).describe('Opaque token; correlates this callback to its pending authorization.'),- code: z.string().min(1).optional().describe('Authorization code, present when the user granted consent.'),- error: z- .string()- .optional()- .describe('OAuth error code, present instead of `code` if the user denied consent or the IdP errored.'),- error_description: z.string().optional(),-});--const McpOAuthCallbackSuccessSchema = z- .object({- success: z.literal(true),- })- .openapi('McpOAuthCallbackSuccess');-export const mcpOAuthCallbackRoute = createRoute({method: 'get',path: '/callback',@@ -27,11 +12,11 @@ export const mcpOAuthCallbackRoute = createRoute({// Browser-redirect target hit directly by the authorization server, never called by SDK.'x-fern-ignore': true,request: {- query: McpOAuthCallbackQuerySchema,+ query: OAuthCallbackQuerySchema,},responses: {200: {- content: { 'application/json': { schema: McpOAuthCallbackSuccessSchema } },+ content: { 'application/json': { schema: OAuthCallbackSuccessSchema } },description: 'Token exchanged successfully and no `redirect_url` was given at authorize time.',},302: {diff --git a/packages/server/src/schemas/auth.ts b/packages/server/src/schemas/auth.tsnew file mode 100644index 000000000..f243ec248--- /dev/null+++ b/packages/server/src/schemas/auth.ts@@ -0,0 +1,37 @@+/** Auth wire schemas. */+import { z } from '@hono/zod-openapi';++export const AuthRoleSchema = z.enum(['admin', 'user']).openapi('AuthRole');++export const AuthMeResponseSchema = z+ .object({+ user_ref: z.string(),+ role: AuthRoleSchema,+ })+ .openapi('AuthMeResponse');++export type AuthMeResponse = z.infer<typeof AuthMeResponseSchema>;++export const AuthLoginQuerySchema = z.object({+ return_to: z+ .string()+ .optional()+ .describe('Path to return to after login. Must be a same-origin relative path; anything else falls back to "/".'),+});++export const OAuthCallbackQuerySchema = z.object({+ code: z.string().min(1).optional().describe('Authorization code, present when the user granted consent.'),+ state: z+ .string()+ .min(1)+ .describe('Opaque token; correlates this callback to its pending login. Always present, success or error.'),+ error: z+ .string()+ .optional()+ .describe('Error code from the identity provider, present instead of `code` if the user denied consent.'),+ error_description: z.string().optional(),+});++export const OAuthCallbackSuccessSchema = z.object({+ success: z.literal(true),+});diff --git a/packages/server/tests/unit/apis/auth.test.ts b/packages/server/tests/unit/apis/auth.test.tsnew file mode 100644index 000000000..bb05fa4f5--- /dev/null+++ b/packages/server/tests/unit/apis/auth.test.ts@@ -0,0 +1,41 @@+import { createAuthRouter } from '../../../src/apis/auth';++describe('auth router (no identity provider configured)', () => {+ it('GET /me returns the fixed local identity', async () => {+ const router = createAuthRouter();++ const res = await router.request('/me');++ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({+ user_ref: 'trueforge-default',+ role: 'admin',+ });+ });++ it('GET /login redirects home — there is nothing to log into', async () => {+ const router = createAuthRouter();++ const res = await router.request('/login', { redirect: 'manual' });++ expect(res.status).toBe(302);+ expect(res.headers.get('location')).toBe('/');+ });++ it('GET /callback redirects home — there is nothing to complete', async () => {+ const router = createAuthRouter();++ const res = await router.request('/callback?state=abc', { redirect: 'manual' });++ expect(res.status).toBe(302);+ expect(res.headers.get('location')).toBe('/');+ });++ it('POST /logout is a no-op 204 — there is no real session to clear', async () => {+ const router = createAuthRouter();++ const res = await router.request('/logout', { method: 'POST' });++ expect(res.status).toBe(204);+ });+});