Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
Use HttpApi for Environment APIs & standardize authn/authz (#2858)
Julius Marmingea04c09a190ac
diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 2e84e4255..746510363 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -16,6 +16,7 @@},"dependencies": {"@effect/platform-node": "catalog:",+ "@t3tools/client-runtime": "workspace:*","@t3tools/contracts": "workspace:*","@t3tools/shared": "workspace:*","@t3tools/ssh": "workspace:*",diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.tsindex 8717c8779..d0b08c8da 100644--- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts+++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts@@ -22,7 +22,7 @@ import {ensureSshEnvironment,fetchSshEnvironmentDescriptor,fetchSshSessionState,- issueSshWebSocketToken,+ issueSshWebSocketTicket,resolveSshPasswordPrompt,} from "./methods/sshEnvironment.ts";import {@@ -62,7 +62,7 @@ export const installDesktopIpcHandlers = Effect.gen(function* () {yield* ipc.handle(fetchSshEnvironmentDescriptor);yield* ipc.handle(bootstrapSshBearerSession);yield* ipc.handle(fetchSshSessionState);- yield* ipc.handle(issueSshWebSocketToken);+ yield* ipc.handle(issueSshWebSocketTicket);yield* ipc.handle(resolveSshPasswordPrompt);yield* ipc.handle(getServerExposureState);diff --git a/apps/desktop/src/ipc/methods/sshEnvironment.test.ts b/apps/desktop/src/ipc/methods/sshEnvironment.test.tsnew file mode 100644index 000000000..fa53486d5--- /dev/null+++ b/apps/desktop/src/ipc/methods/sshEnvironment.test.ts@@ -0,0 +1,115 @@+import { assert, describe, it } from "@effect/vitest";+import { SshHttpBridgeError } from "@t3tools/ssh/errors";+import * as Cause from "effect/Cause";+import * as Effect from "effect/Effect";+import * as Exit from "effect/Exit";+import * as Layer from "effect/Layer";+import * as Option from "effect/Option";+import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";++import {+ DesktopSshEnvironmentRequestError,+ fetchSshEnvironmentDescriptor,+} from "./sshEnvironment.ts";++function jsonResponse(request: HttpClientRequest.HttpClientRequest, body: unknown, status = 200) {+ return HttpClientResponse.fromWeb(+ request,+ new Response(JSON.stringify(body), {+ status,+ headers: { "content-type": "application/json" },+ }),+ );+}++function makeHttpClientLayer(+ handler: (+ request: HttpClientRequest.HttpClientRequest,+ ) => Effect.Effect<HttpClientResponse.HttpClientResponse, never>,+) {+ return Layer.succeed(+ HttpClient.HttpClient,+ HttpClient.make((request) => handler(request)),+ );+}++describe("SSH environment IPC", () => {+ it.effect("fetches and decodes the remote environment descriptor", () => {+ const requestUrls: string[] = [];+ const layer = makeHttpClientLayer((request) =>+ Effect.sync(() => {+ requestUrls.push(request.url);+ return jsonResponse(request, {+ environmentId: "remote-env",+ label: "Remote Devbox",+ platform: { os: "linux", arch: "x64" },+ serverVersion: "1.2.3",+ capabilities: { repositoryIdentity: true },+ });+ }),+ );++ return Effect.gen(function* () {+ const descriptor = yield* fetchSshEnvironmentDescriptor.handler({+ httpBaseUrl: "http://127.0.0.1:41773/",+ });++ assert.deepEqual(descriptor, {+ environmentId: "remote-env",+ label: "Remote Devbox",+ platform: { os: "linux", arch: "x64" },+ serverVersion: "1.2.3",+ capabilities: { repositoryIdentity: true },+ });+ assert.deepEqual(requestUrls, ["http://127.0.0.1:41773/.well-known/t3/environment"]);+ }).pipe(Effect.provide(layer));+ });++ it.effect("wraps schema decode failures in a typed request error", () => {+ const layer = makeHttpClientLayer((request) =>+ Effect.succeed(jsonResponse(request, { environmentId: "remote-env" })),+ );++ return Effect.gen(function* () {+ const exit = yield* Effect.exit(+ fetchSshEnvironmentDescriptor.handler({+ httpBaseUrl: "http://127.0.0.1:41773/",+ }),+ );+ assert(Exit.isFailure(exit));+ const failure = Cause.findErrorOption(exit.cause);+ assert(Option.isSome(failure));+ const error = failure.value;++ assert.instanceOf(error, DesktopSshEnvironmentRequestError);+ assert.equal(error.operation, "fetch-environment-descriptor");+ assert.equal(error.cause instanceof SshHttpBridgeError, false);+ }).pipe(Effect.provide(layer));+ });++ it.effect("rejects non-loopback HTTP endpoints before issuing a request", () => {+ let requestCount = 0;+ const layer = makeHttpClientLayer((request) =>+ Effect.sync(() => {+ requestCount += 1;+ return jsonResponse(request, {});+ }),+ );++ return Effect.gen(function* () {+ const exit = yield* Effect.exit(+ fetchSshEnvironmentDescriptor.handler({+ httpBaseUrl: "http://remote.example.com:41773/",+ }),+ );+ assert(Exit.isFailure(exit));+ const failure = Cause.findErrorOption(exit.cause);+ assert(Option.isSome(failure));+ const error = failure.value;++ assert.instanceOf(error, DesktopSshEnvironmentRequestError);+ assert.instanceOf(error.cause, SshHttpBridgeError);+ assert.equal(requestCount, 0);+ }).pipe(Effect.provide(layer));+ });+});diff --git a/apps/desktop/src/ipc/methods/sshEnvironment.ts b/apps/desktop/src/ipc/methods/sshEnvironment.tsindex efea3dd13..9a50339c8 100644--- a/apps/desktop/src/ipc/methods/sshEnvironment.ts+++ b/apps/desktop/src/ipc/methods/sshEnvironment.ts@@ -1,3 +1,9 @@+import {+ bootstrapRemoteBearerSession,+ fetchRemoteEnvironmentDescriptor,+ fetchRemoteSessionState,+ issueRemoteWebSocketTicket,+} from "@t3tools/client-runtime";import {DesktopDiscoveredSshHostSchema,DesktopSshBearerBootstrapInputSchema,@@ -9,10 +15,12 @@ import {DesktopSshPasswordPromptCancelledType,DesktopSshPasswordPromptResolutionInputSchema,ExecutionEnvironmentDescriptor,- AuthBearerBootstrapResult,+ AuthAccessTokenResult,AuthSessionState,- AuthWebSocketTokenResult,+ AuthWebSocketTicketResult,} from "@t3tools/contracts";+import { resolveLoopbackSshHttpBaseUrl } from "@t3tools/ssh/tunnel";+import * as Data from "effect/Data";import * as Effect from "effect/Effect";import * as Schema from "effect/Schema";@@ -20,7 +28,34 @@ import * as IpcChannels from "../channels.ts";import { makeIpcMethod } from "../DesktopIpc.ts";import * as DesktopSshEnvironment from "../../ssh/DesktopSshEnvironment.ts";import * as DesktopSshPasswordPrompts from "../../ssh/DesktopSshPasswordPrompts.ts";-import * as DesktopSshRemoteApi from "../../ssh/DesktopSshRemoteApi.ts";++type DesktopSshEnvironmentRequestOperation =+ | "fetch-environment-descriptor"+ | "bootstrap-bearer-session"+ | "fetch-session-state"+ | "issue-websocket-ticket";++export class DesktopSshEnvironmentRequestError extends Data.TaggedError(+ "DesktopSshEnvironmentRequestError",+)<{+ readonly operation: DesktopSshEnvironmentRequestOperation;+ readonly cause: unknown;+}> {+ override get message() {+ return `SSH remote API request failed during ${this.operation}.`;+ }+}++const withLoopbackSshApi =+ <A, E, R>(+ operation: DesktopSshEnvironmentRequestOperation,+ use: (httpBaseUrl: string) => Effect.Effect<A, E, R>,+ ) =>+ (httpBaseUrl: string): Effect.Effect<A, DesktopSshEnvironmentRequestError, R> =>+ resolveLoopbackSshHttpBaseUrl(httpBaseUrl).pipe(+ Effect.flatMap(use),+ Effect.mapError((cause) => new DesktopSshEnvironmentRequestError({ operation, cause })),+ );export const discoverSshHosts = makeIpcMethod({channel: IpcChannels.DISCOVER_SSH_HOSTS_CHANNEL,@@ -69,21 +104,26 @@ export const fetchSshEnvironmentDescriptor = makeIpcMethod({payload: DesktopSshHttpBaseUrlInputSchema,result: ExecutionEnvironmentDescriptor,handler: Effect.fn("desktop.ipc.sshEnvironment.fetchDescriptor")(function* ({ httpBaseUrl }) {- const remoteApi = yield* DesktopSshRemoteApi.DesktopSshRemoteApi;- return yield* remoteApi.fetchEnvironmentDescriptor({ httpBaseUrl });+ return yield* withLoopbackSshApi("fetch-environment-descriptor", (resolvedHttpBaseUrl) =>+ fetchRemoteEnvironmentDescriptor({ httpBaseUrl: resolvedHttpBaseUrl }),+ )(httpBaseUrl);}),});export const bootstrapSshBearerSession = makeIpcMethod({channel: IpcChannels.BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL,payload: DesktopSshBearerBootstrapInputSchema,- result: AuthBearerBootstrapResult,+ result: AuthAccessTokenResult,handler: Effect.fn("desktop.ipc.sshEnvironment.bootstrapBearerSession")(function* ({httpBaseUrl,credential,}) {- const remoteApi = yield* DesktopSshRemoteApi.DesktopSshRemoteApi;- return yield* remoteApi.bootstrapBearerSession({ httpBaseUrl, credential });+ return yield* withLoopbackSshApi("bootstrap-bearer-session", (resolvedHttpBaseUrl) =>+ bootstrapRemoteBearerSession({+ httpBaseUrl: resolvedHttpBaseUrl,+ credential,+ }),+ )(httpBaseUrl);}),});@@ -95,21 +135,29 @@ export const fetchSshSessionState = makeIpcMethod({httpBaseUrl,bearerToken,}) {- const remoteApi = yield* DesktopSshRemoteApi.DesktopSshRemoteApi;- return yield* remoteApi.fetchSessionState({ httpBaseUrl, bearerToken });+ return yield* withLoopbackSshApi("fetch-session-state", (resolvedHttpBaseUrl) =>+ fetchRemoteSessionState({+ httpBaseUrl: resolvedHttpBaseUrl,+ bearerToken,+ }),+ )(httpBaseUrl);}),});-export const issueSshWebSocketToken = makeIpcMethod({+export const issueSshWebSocketTicket = makeIpcMethod({channel: IpcChannels.ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL,payload: DesktopSshBearerRequestInputSchema,- result: AuthWebSocketTokenResult,- handler: Effect.fn("desktop.ipc.sshEnvironment.issueWebSocketToken")(function* ({+ result: AuthWebSocketTicketResult,+ handler: Effect.fn("desktop.ipc.sshEnvironment.issueWebSocketTicket")(function* ({httpBaseUrl,bearerToken,}) {- const remoteApi = yield* DesktopSshRemoteApi.DesktopSshRemoteApi;- return yield* remoteApi.issueWebSocketToken({ httpBaseUrl, bearerToken });+ return yield* withLoopbackSshApi("issue-websocket-ticket", (resolvedHttpBaseUrl) =>+ issueRemoteWebSocketTicket({+ httpBaseUrl: resolvedHttpBaseUrl,+ bearerToken,+ }),+ )(httpBaseUrl);}),});diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex 0bc1badff..8c458db01 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -40,7 +40,6 @@ import * as DesktopAppSettings from "./settings/DesktopAppSettings.ts";import * as DesktopShellEnvironment from "./shell/DesktopShellEnvironment.ts";import * as DesktopSshEnvironment from "./ssh/DesktopSshEnvironment.ts";import * as DesktopSshPasswordPrompts from "./ssh/DesktopSshPasswordPrompts.ts";-import * as DesktopSshRemoteApi from "./ssh/DesktopSshRemoteApi.ts";import * as DesktopState from "./app/DesktopState.ts";import * as DesktopUpdates from "./updates/DesktopUpdates.ts";import * as DesktopWindow from "./window/DesktopWindow.ts";@@ -116,7 +115,7 @@ const desktopFoundationLayer = Layer.mergeAll(DesktopObservability.layer,).pipe(Layer.provideMerge(desktopEnvironmentLayer));-const desktopSshLayer = Layer.mergeAll(desktopSshEnvironmentLayer, DesktopSshRemoteApi.layer).pipe(+const desktopSshLayer = desktopSshEnvironmentLayer.pipe(Layer.provideMerge(DesktopSshPasswordPrompts.layer()),);diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.tsindex 173be8fb5..737567990 100644--- a/apps/desktop/src/preload.ts+++ b/apps/desktop/src/preload.ts@@ -66,7 +66,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {}),fetchSshSessionState: (httpBaseUrl, bearerToken) =>ipcRenderer.invoke(IpcChannels.FETCH_SSH_SESSION_STATE_CHANNEL, { httpBaseUrl, bearerToken }),- issueSshWebSocketToken: (httpBaseUrl, bearerToken) =>+ issueSshWebSocketTicket: (httpBaseUrl, bearerToken) =>ipcRenderer.invoke(IpcChannels.ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL, { httpBaseUrl, bearerToken }),onSshPasswordPrompt: (listener) => {const wrappedListener = (_event: Electron.IpcRendererEvent, request: unknown) => {diff --git a/apps/desktop/src/ssh/DesktopSshRemoteApi.test.ts b/apps/desktop/src/ssh/DesktopSshRemoteApi.test.tsdeleted file mode 100644index 8b6798d38..000000000--- a/apps/desktop/src/ssh/DesktopSshRemoteApi.test.ts+++ /dev/null@@ -1,79 +0,0 @@-import { assert, describe, it } from "@effect/vitest";-import { SshHttpBridgeError } from "@t3tools/ssh/errors";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";--import * as DesktopSshRemoteApi from "./DesktopSshRemoteApi.ts";--function jsonResponse(request: HttpClientRequest.HttpClientRequest, body: unknown, status = 200) {- return HttpClientResponse.fromWeb(- request,- new Response(JSON.stringify(body), {- status,- headers: { "content-type": "application/json" },- }),- );-}--function makeLayer(- handler: (- request: HttpClientRequest.HttpClientRequest,- ) => Effect.Effect<HttpClientResponse.HttpClientResponse>,-) {- return DesktopSshRemoteApi.layer.pipe(- Layer.provide(- Layer.succeed(- HttpClient.HttpClient,- HttpClient.make((request) => handler(request)),- ),- ),- );-}--describe("DesktopSshRemoteApi", () => {- it.effect("fetches and decodes the remote environment descriptor", () => {- const requestUrls: string[] = [];- const layer = makeLayer((request) =>- Effect.sync(() => {- requestUrls.push(request.url);- return jsonResponse(request, {- environmentId: "remote-env",- label: "Remote Devbox",- platform: { os: "linux", arch: "x64" },- serverVersion: "1.2.3",- capabilities: { repositoryIdentity: true },- });- }),- );-- return Effect.gen(function* () {- const remoteApi = yield* DesktopSshRemoteApi.DesktopSshRemoteApi;- const descriptor = yield* remoteApi.fetchEnvironmentDescriptor({- httpBaseUrl: "http://127.0.0.1:41773/",- });-- assert.equal(descriptor.label, "Remote Devbox");- assert.deepEqual(requestUrls, ["http://127.0.0.1:41773/.well-known/t3/environment"]);- }).pipe(Effect.provide(layer));- });-- it.effect("wraps schema decode failures in a typed remote api error", () => {- const layer = makeLayer((request) =>- Effect.succeed(jsonResponse(request, { environmentId: "remote-env" })),- );-- return Effect.gen(function* () {- const remoteApi = yield* DesktopSshRemoteApi.DesktopSshRemoteApi;- const error = yield* remoteApi- .fetchEnvironmentDescriptor({- httpBaseUrl: "http://127.0.0.1:41773/",- })- .pipe(Effect.flip);-- assert.instanceOf(error, DesktopSshRemoteApi.DesktopSshRemoteApiError);- assert.equal(error.operation, "fetch-environment-descriptor");- assert.equal(error.cause instanceof SshHttpBridgeError, false);- }).pipe(Effect.provide(layer));- });-});diff --git a/apps/desktop/src/ssh/DesktopSshRemoteApi.ts b/apps/desktop/src/ssh/DesktopSshRemoteApi.tsdeleted file mode 100644index fda084910..000000000--- a/apps/desktop/src/ssh/DesktopSshRemoteApi.ts+++ /dev/null@@ -1,124 +0,0 @@-import {- AuthBearerBootstrapResult,- AuthSessionState,- AuthWebSocketTokenResult,- type AuthBearerBootstrapResult as AuthBearerBootstrapResultType,- type AuthSessionState as AuthSessionStateType,- type AuthWebSocketTokenResult as AuthWebSocketTokenResultType,- ExecutionEnvironmentDescriptor,- type ExecutionEnvironmentDescriptor as ExecutionEnvironmentDescriptorType,-} from "@t3tools/contracts";-import { SshHttpBridgeError } from "@t3tools/ssh/errors";-import { fetchLoopbackSshJson } from "@t3tools/ssh/tunnel";-import * as Context from "effect/Context";-import * as Data from "effect/Data";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Schema from "effect/Schema";-import { HttpClient } from "effect/unstable/http";--export type DesktopSshRemoteApiOperation =- | "fetch-environment-descriptor"- | "bootstrap-bearer-session"- | "fetch-session-state"- | "issue-websocket-token";--export class DesktopSshRemoteApiError extends Data.TaggedError("DesktopSshRemoteApiError")<{- readonly operation: DesktopSshRemoteApiOperation;- readonly cause: SshHttpBridgeError | Schema.SchemaError;-}> {- override get message() {- return `SSH remote API request failed during ${this.operation}.`;- }-}--export interface DesktopSshRemoteApiShape {- readonly fetchEnvironmentDescriptor: (input: {- readonly httpBaseUrl: string;- }) => Effect.Effect<ExecutionEnvironmentDescriptorType, DesktopSshRemoteApiError>;- readonly bootstrapBearerSession: (input: {- readonly httpBaseUrl: string;- readonly credential: string;- }) => Effect.Effect<AuthBearerBootstrapResultType, DesktopSshRemoteApiError>;- readonly fetchSessionState: (input: {- readonly httpBaseUrl: string;- readonly bearerToken: string;- }) => Effect.Effect<AuthSessionStateType, DesktopSshRemoteApiError>;- readonly issueWebSocketToken: (input: {- readonly httpBaseUrl: string;- readonly bearerToken: string;- }) => Effect.Effect<AuthWebSocketTokenResultType, DesktopSshRemoteApiError>;-}--export class DesktopSshRemoteApi extends Context.Service<- DesktopSshRemoteApi,- DesktopSshRemoteApiShape->()("@t3tools/desktop/ssh/DesktopSshRemoteApi") {}--const decodeExecutionEnvironmentDescriptor = Schema.decodeUnknownEffect(- ExecutionEnvironmentDescriptor,-);-const decodeAuthBearerBootstrapResult = Schema.decodeUnknownEffect(AuthBearerBootstrapResult);-const decodeAuthSessionState = Schema.decodeUnknownEffect(AuthSessionState);-const decodeAuthWebSocketTokenResult = Schema.decodeUnknownEffect(AuthWebSocketTokenResult);--const mapError =- (operation: DesktopSshRemoteApiOperation) =>- (cause: SshHttpBridgeError | Schema.SchemaError): DesktopSshRemoteApiError =>- new DesktopSshRemoteApiError({ operation, cause });--const make = Effect.gen(function* () {- const httpClient = yield* HttpClient.HttpClient;- const provideHttpClient = <A, E>(effect: Effect.Effect<A, E, HttpClient.HttpClient>) =>- effect.pipe(Effect.provideService(HttpClient.HttpClient, httpClient));-- return DesktopSshRemoteApi.of({- fetchEnvironmentDescriptor: ({ httpBaseUrl }) =>- fetchLoopbackSshJson<unknown>({- httpBaseUrl,- pathname: "/.well-known/t3/environment",- }).pipe(- Effect.flatMap(decodeExecutionEnvironmentDescriptor),- Effect.mapError(mapError("fetch-environment-descriptor")),- provideHttpClient,- Effect.withSpan("desktop.sshRemoteApi.fetchEnvironmentDescriptor"),- ),- bootstrapBearerSession: ({ httpBaseUrl, credential }) =>- fetchLoopbackSshJson<unknown>({- httpBaseUrl,- pathname: "/api/auth/bootstrap/bearer",- method: "POST",- body: { credential },- }).pipe(- Effect.flatMap(decodeAuthBearerBootstrapResult),- Effect.mapError(mapError("bootstrap-bearer-session")),- provideHttpClient,- Effect.withSpan("desktop.sshRemoteApi.bootstrapBearerSession"),- ),- fetchSessionState: ({ httpBaseUrl, bearerToken }) =>- fetchLoopbackSshJson<unknown>({- httpBaseUrl,- pathname: "/api/auth/session",- bearerToken,- }).pipe(- Effect.flatMap(decodeAuthSessionState),- Effect.mapError(mapError("fetch-session-state")),- provideHttpClient,- Effect.withSpan("desktop.sshRemoteApi.fetchSessionState"),- ),- issueWebSocketToken: ({ httpBaseUrl, bearerToken }) =>- fetchLoopbackSshJson<unknown>({- httpBaseUrl,- pathname: "/api/auth/ws-token",- method: "POST",- bearerToken,- }).pipe(- Effect.flatMap(decodeAuthWebSocketTokenResult),- Effect.mapError(mapError("issue-websocket-token")),- provideHttpClient,- Effect.withSpan("desktop.sshRemoteApi.issueWebSocketToken"),- ),- });-});--export const layer = Layer.effect(DesktopSshRemoteApi, make);diff --git a/apps/mobile/src/lib/connection.test.ts b/apps/mobile/src/lib/connection.test.tsindex 42c330f23..e55d20bd1 100644--- a/apps/mobile/src/lib/connection.test.ts+++ b/apps/mobile/src/lib/connection.test.ts@@ -1,6 +1,6 @@import { describe, expect, it, vi } from "vitest";-import { redactPairingCredential } from "./connection";+import { mobileAuthClientMetadata, redactPairingCredential } from "./connection";vi.mock("./runtime", () => ({mobileRemoteHttpRuntime: {@@ -8,7 +8,21 @@ vi.mock("./runtime", () => ({},}));+vi.mock("react-native", () => ({+ Platform: {+ OS: "ios",+ },+}));+describe("mobile remote connection records", () => {+ it("identifies mobile token exchanges for authorized-client presentation", () => {+ expect(mobileAuthClientMetadata()).toEqual({+ label: "T3 Code Mobile",+ deviceType: "mobile",+ os: "iOS",+ });+ });+it("removes one-time bootstrap credentials before persisting pairing URLs", () => {expect(redactPairingCredential("https://desktop.example/#token=bootstrap-token")).toBe("https://desktop.example/",diff --git a/apps/mobile/src/lib/connection.ts b/apps/mobile/src/lib/connection.tsindex 1d11112c6..8d87fda09 100644--- a/apps/mobile/src/lib/connection.ts+++ b/apps/mobile/src/lib/connection.ts@@ -1,9 +1,10 @@-import { EnvironmentId } from "@t3tools/contracts";+import { type AuthClientPresentationMetadata, EnvironmentId } from "@t3tools/contracts";import {bootstrapRemoteBearerSession,fetchRemoteEnvironmentDescriptor,} from "@t3tools/client-runtime";import { resolveRemotePairingTarget, stripPairingTokenFromUrl } from "@t3tools/shared/remote";+import { Platform } from "react-native";import { mobileRemoteHttpRuntime } from "./runtime";export interface RemoteConnectionInput {@@ -36,6 +37,14 @@ export function redactPairingCredential(pairingUrl: string): string {}}+export function mobileAuthClientMetadata(): AuthClientPresentationMetadata {+ return {+ label: "T3 Code Mobile",+ deviceType: "mobile",+ ...(Platform.OS === "ios" ? { os: "iOS" } : Platform.OS === "android" ? { os: "Android" } : {}),+ };+}+export async function bootstrapRemoteConnection(input: RemoteConnectionInput,): Promise<SavedRemoteConnection> {@@ -53,6 +62,7 @@ export async function bootstrapRemoteConnection(bootstrapRemoteBearerSession({httpBaseUrl: target.httpBaseUrl,credential: target.credential,+ clientMetadata: mobileAuthClientMetadata(),}),);@@ -63,6 +73,6 @@ export async function bootstrapRemoteConnection(displayUrl: target.httpBaseUrl,httpBaseUrl: target.httpBaseUrl,wsBaseUrl: target.wsBaseUrl,- bearerToken: bootstrap.sessionToken,+ bearerToken: bootstrap.access_token,};}diff --git a/apps/server/src/auth/EnvironmentAuth.test.ts b/apps/server/src/auth/EnvironmentAuth.test.tsnew file mode 100644index 000000000..871ec1eab--- /dev/null+++ b/apps/server/src/auth/EnvironmentAuth.test.ts@@ -0,0 +1,261 @@+import * as NodeServices from "@effect/platform-node/NodeServices";+import { AuthAdministrativeScopes } from "@t3tools/contracts";+import { expect, it } from "@effect/vitest";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";++import type { ServerConfigShape } from "../config.ts";+import { ServerConfig } from "../config.ts";+import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";+import * as PairingGrantStore from "./PairingGrantStore.ts";+import * as EnvironmentAuth from "./EnvironmentAuth.ts";++import * as ServerSecretStore from "./ServerSecretStore.ts";++const makeServerConfigLayer = (overrides?: Partial<ServerConfigShape>) =>+ Layer.effect(+ ServerConfig,+ Effect.gen(function* () {+ const config = yield* ServerConfig;+ return {+ ...config,+ ...overrides,+ } satisfies ServerConfigShape;+ }),+ ).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-server-test-" })));++const makeEnvironmentAuthLayer = (overrides?: Partial<ServerConfigShape>) =>+ EnvironmentAuth.layer.pipe(+ Layer.provide(SqlitePersistenceMemory),+ Layer.provide(ServerSecretStore.layer),+ Layer.provide(makeServerConfigLayer(overrides)),+ );++const makeCookieRequest = (+ sessionToken: string,+): Parameters<EnvironmentAuth.EnvironmentAuthShape["authenticateHttpRequest"]>[0] =>+ ({+ cookies: {+ t3_session: sessionToken,+ },+ headers: {},+ }) as unknown as Parameters<EnvironmentAuth.EnvironmentAuthShape["authenticateHttpRequest"]>[0];++const requestMetadata = {+ deviceType: "desktop" as const,+ os: "macOS",+ browser: "Chrome",+ ipAddress: "192.168.1.23",+};++it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {+ it.effect("classifies invalid bootstrap credential failures for the HTTP boundary", () =>+ Effect.sync(() => {+ const error = EnvironmentAuth.toBootstrapExchangeError(+ new PairingGrantStore.BootstrapCredentialInvalidError({+ message: "Unknown bootstrap credential.",+ }),+ );++ expect(error._tag).toBe("ServerAuthInvalidCredentialError");+ if (error._tag === "ServerAuthInvalidCredentialError") {+ expect(error.reason).toBe("invalid_credential");+ }+ }),+ );++ it.effect("maps unexpected bootstrap failures to 500", () =>+ Effect.sync(() => {+ const error = EnvironmentAuth.toBootstrapExchangeError(+ new PairingGrantStore.BootstrapCredentialInternalError({+ message: "Failed to consume bootstrap credential.",+ cause: new Error("sqlite is unavailable"),+ }),+ );++ expect(error._tag).toBe("ServerAuthInternalError");+ expect(error.message).toBe("Failed to validate bootstrap credential.");+ }),+ );++ it.effect("issues standard pairing credentials by default", () =>+ Effect.gen(function* () {+ const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;++ const pairingCredential = yield* serverAuth.issuePairingCredential();+ const exchanged = yield* serverAuth.createBrowserSession(+ pairingCredential.credential,+ requestMetadata,+ );+ const verified = yield* serverAuth.authenticateHttpRequest(+ makeCookieRequest(exchanged.sessionToken),+ );++ expect(verified.sessionId.length).toBeGreaterThan(0);+ expect(verified.scopes).toEqual([+ "orchestration:read",+ "orchestration:operate",+ "terminal:operate",+ "review:write",+ "relay:read",+ ]);+ expect(verified.subject).toBe("one-time-token");+ }).pipe(Effect.provide(makeEnvironmentAuthLayer())),+ );++ it.effect("does not exchange ordinary pairing grants for administrative access tokens", () =>+ Effect.gen(function* () {+ const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;+ const pairingCredential = yield* serverAuth.issuePairingCredential();++ const error = yield* serverAuth+ .exchangeBootstrapCredentialForAccessToken(+ pairingCredential.credential,+ ["orchestration:read", "access:write"],+ requestMetadata,+ )+ .pipe(Effect.flip);++ expect(error._tag).toBe("ServerAuthInvalidRequestError");+ if (error._tag === "ServerAuthInvalidRequestError") {+ expect(error.reason).toBe("scope_not_granted");+ }+ }).pipe(Effect.provide(makeEnvironmentAuthLayer())),+ );++ it.effect("inherits a constrained pairing grant when token exchange omits scope", () =>+ Effect.gen(function* () {+ const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;+ const pairingCredential = yield* serverAuth.issuePairingCredential({+ scopes: ["orchestration:read"],+ });++ const token = yield* serverAuth.exchangeBootstrapCredentialForAccessToken(+ pairingCredential.credential,+ undefined,+ requestMetadata,+ );++ expect(token.scope).toBe("orchestration:read");+ }).pipe(Effect.provide(makeEnvironmentAuthLayer())),+ );++ it.effect("keeps user-issued administrative pairing links manageable", () =>+ Effect.gen(function* () {+ const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;+ const pairingCredential = yield* serverAuth.issuePairingCredential({+ scopes: AuthAdministrativeScopes,+ });+ const listedPairingLinks = yield* serverAuth.listPairingLinks();++ expect(+ listedPairingLinks.find((pairingLink) => pairingLink.id === pairingCredential.id)?.subject,+ ).toBe("one-time-token");+ }).pipe(Effect.provide(makeEnvironmentAuthLayer())),+ );++ it.effect("issues startup pairing URLs that bootstrap administrative sessions", () =>+ Effect.gen(function* () {+ const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;++ const pairingUrl = yield* serverAuth.issueStartupPairingUrl("http://127.0.0.1:3773");+ const token = new URLSearchParams(new URL(pairingUrl).hash.slice(1)).get("token");+ const listedPairingLinks = yield* serverAuth.listPairingLinks();+ expect(token).toBeTruthy();+ expect(+ listedPairingLinks.some(+ (pairingLink) => pairingLink.subject === "administrative-bootstrap",+ ),+ ).toBe(false);++ const exchanged = yield* serverAuth.createBrowserSession(token ?? "", requestMetadata);+ const verified = yield* serverAuth.authenticateHttpRequest(+ makeCookieRequest(exchanged.sessionToken),+ );++ expect(verified.scopes).toEqual([+ "orchestration:read",+ "orchestration:operate",+ "terminal:operate",+ "review:write",+ "relay:read",+ "access:read",+ "access:write",+ "relay:write",+ ]);+ expect(verified.subject).toBe("administrative-bootstrap");+ }).pipe(Effect.provide(makeEnvironmentAuthLayer())),+ );++ it.effect(+ "lists pairing links and revokes other sessions while keeping the administrative session",+ () =>+ Effect.gen(function* () {+ const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;++ const administrativeExchange = yield* serverAuth.createBrowserSession(+ "desktop-bootstrap-token",+ requestMetadata,+ );+ const administrativeSession = yield* serverAuth.authenticateHttpRequest(+ makeCookieRequest(administrativeExchange.sessionToken),+ );+ const pairingCredential = yield* serverAuth.issuePairingCredential({+ label: "Julius iPhone",+ });+ const listedPairingLinks = yield* serverAuth.listPairingLinks();+ const clientExchange = yield* serverAuth.createBrowserSession(+ pairingCredential.credential,+ {+ ...requestMetadata,+ deviceType: "mobile",+ os: "iOS",+ browser: "Safari",+ ipAddress: "192.168.1.88",+ },+ );+ const clientSession = yield* serverAuth.authenticateHttpRequest(+ makeCookieRequest(clientExchange.sessionToken),+ );+ const clientsBeforeRevoke = yield* serverAuth.listClientSessions(+ administrativeSession.sessionId,+ );+ const revokedCount = yield* serverAuth.revokeOtherClientSessions(+ administrativeSession.sessionId,+ );+ const clientsAfterRevoke = yield* serverAuth.listClientSessions(+ administrativeSession.sessionId,+ );++ expect(listedPairingLinks.map((entry) => entry.id)).toContain(pairingCredential.id);+ expect(listedPairingLinks.find((entry) => entry.id === pairingCredential.id)?.label).toBe(+ "Julius iPhone",+ );+ expect(clientsBeforeRevoke).toHaveLength(2);+ expect(+ clientsBeforeRevoke.find((entry) => entry.sessionId === administrativeSession.sessionId)+ ?.current,+ ).toBe(true);+ expect(+ clientsBeforeRevoke.find((entry) => entry.sessionId === clientSession.sessionId)?.current,+ ).toBe(false);+ expect(+ clientsBeforeRevoke.find((entry) => entry.sessionId === clientSession.sessionId)?.client+ .label,+ ).toBe("Julius iPhone");+ expect(+ clientsBeforeRevoke.find((entry) => entry.sessionId === clientSession.sessionId)?.client+ .deviceType,+ ).toBe("mobile");+ expect(revokedCount).toBe(1);+ expect(clientsAfterRevoke).toHaveLength(1);+ expect(clientsAfterRevoke[0]?.sessionId).toBe(administrativeSession.sessionId);+ }).pipe(+ Effect.provide(+ makeEnvironmentAuthLayer({+ desktopBootstrapToken: "desktop-bootstrap-token",+ }),+ ),+ ),+ );+});diff --git a/apps/server/src/auth/EnvironmentAuth.ts b/apps/server/src/auth/EnvironmentAuth.tsnew file mode 100644index 000000000..abb1f7b79--- /dev/null+++ b/apps/server/src/auth/EnvironmentAuth.ts@@ -0,0 +1,662 @@+import {+ AuthAccessTokenType,+ AuthAccessWriteScope,+ AuthAdministrativeScopes,+ AuthStandardClientScopes,+ type AuthAccessTokenResult,+ type AuthBrowserSessionResult,+ type AuthClientMetadata,+ type AuthClientSession,+ type AuthCreatePairingCredentialInput,+ type AuthEnvironmentScope,+ type AuthPairingLink,+ type AuthPairingCredentialResult,+ type AuthSessionId,+ type AuthSessionState,+ type ServerAuthDescriptor,+ type ServerAuthSessionMethod,+ type AuthWebSocketTicketResult,+} from "@t3tools/contracts";+import { encodeOAuthScope } from "@t3tools/shared/oauthScope";+import * as Context from "effect/Context";+import * as Data from "effect/Data";+import * as DateTime from "effect/DateTime";+import * as Duration from "effect/Duration";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";+import * as Option from "effect/Option";+import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";++import * as EnvironmentAuthPolicy from "./EnvironmentAuthPolicy.ts";+import * as PairingGrantStore from "./PairingGrantStore.ts";+import * as ServerSecretStore from "./ServerSecretStore.ts";+import * as SessionStore from "./SessionStore.ts";+import { layerConfig as SqlitePersistenceLayer } from "../persistence/Layers/Sqlite.ts";++export const DEFAULT_SESSION_SUBJECT = "cli-issued-session";+export const INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT = "administrative-bootstrap";++export interface IssuedPairingLink {+ readonly id: string;+ readonly credential: string;+ readonly scopes: ReadonlyArray<AuthEnvironmentScope>;+ readonly subject: string;+ readonly label?: string;+ readonly createdAt: DateTime.Utc;+ readonly expiresAt: DateTime.Utc;+}++export interface IssuedBearerSession {+ readonly sessionId: AuthSessionId;+ readonly token: string;+ readonly method: "bearer-access-token";+ readonly scopes: ReadonlyArray<AuthEnvironmentScope>;+ readonly subject: string;+ readonly client: AuthClientMetadata;+ readonly expiresAt: DateTime.Utc;+}++export interface AuthenticatedSession {+ readonly sessionId: AuthSessionId;+ readonly subject: string;+ readonly method: ServerAuthSessionMethod;+ readonly scopes: ReadonlyArray<AuthEnvironmentScope>;+ readonly expiresAt?: DateTime.DateTime;+}++export class ServerAuthInternalError extends Data.TaggedError("ServerAuthInternalError")<{+ readonly message: string;+ readonly cause?: unknown;+}> {}++export class ServerAuthInvalidCredentialError extends Data.TaggedError(+ "ServerAuthInvalidCredentialError",+)<{+ readonly reason: "missing_credential" | "invalid_credential";+ readonly cause?: unknown;+}> {}++export class ServerAuthInvalidRequestError extends Data.TaggedError(+ "ServerAuthInvalidRequestError",+)<{+ readonly reason: "invalid_scope" | "scope_not_granted";+}> {}++export class ServerAuthForbiddenOperationError extends Data.TaggedError(+ "ServerAuthForbiddenOperationError",+)<{+ readonly reason: "current_session_revoke_not_allowed";+}> {}++export interface EnvironmentAuthShape {+ readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;+ readonly getSessionState: (+ request: HttpServerRequest.HttpServerRequest,+ ) => Effect.Effect<AuthSessionState, ServerAuthInternalError>;+ readonly createBrowserSession: (+ credential: string,+ requestMetadata: AuthClientMetadata,+ ) => Effect.Effect<+ {+ readonly response: AuthBrowserSessionResult;+ readonly sessionToken: string;+ },+ ServerAuthInvalidCredentialError | ServerAuthInternalError+ >;+ readonly exchangeBootstrapCredentialForAccessToken: (+ credential: string,+ requestedScopes: ReadonlyArray<AuthEnvironmentScope> | undefined,+ requestMetadata: AuthClientMetadata,+ ) => Effect.Effect<+ AuthAccessTokenResult,+ ServerAuthInvalidCredentialError | ServerAuthInvalidRequestError | ServerAuthInternalError+ >;+ readonly createPairingLink: (input?: {+ readonly ttl?: Duration.Duration;+ readonly label?: string;+ readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;+ readonly subject?: string;+ }) => Effect.Effect<IssuedPairingLink, ServerAuthInternalError>;+ readonly issuePairingCredential: (+ input?: AuthCreatePairingCredentialInput,+ ) => Effect.Effect<AuthPairingCredentialResult, ServerAuthInternalError>;+ readonly issueStartupPairingCredential: () => Effect.Effect<+ AuthPairingCredentialResult,+ ServerAuthInternalError+ >;+ readonly listPairingLinks: (input?: {+ readonly excludeSubjects?: ReadonlyArray<string>;+ }) => Effect.Effect<ReadonlyArray<AuthPairingLink>, ServerAuthInternalError>;+ readonly revokePairingLink: (id: string) => Effect.Effect<boolean, ServerAuthInternalError>;+ readonly issueSession: (input?: {+ readonly ttl?: Duration.Duration;+ readonly subject?: string;+ readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;+ readonly label?: string;+ }) => Effect.Effect<IssuedBearerSession, ServerAuthInternalError>;+ readonly listSessions: () => Effect.Effect<+ ReadonlyArray<AuthClientSession>,+ ServerAuthInternalError+ >;+ readonly revokeSession: (+ sessionId: AuthSessionId,+ ) => Effect.Effect<boolean, ServerAuthInternalError>;+ readonly revokeOtherSessionsExcept: (+ sessionId: AuthSessionId,+ ) => Effect.Effect<number, ServerAuthInternalError>;+ readonly listClientSessions: (+ currentSessionId: AuthSessionId,+ ) => Effect.Effect<ReadonlyArray<AuthClientSession>, ServerAuthInternalError>;+ readonly revokeClientSession: (+ currentSessionId: AuthSessionId,+ targetSessionId: AuthSessionId,+ ) => Effect.Effect<boolean, ServerAuthForbiddenOperationError | ServerAuthInternalError>;+ readonly revokeOtherClientSessions: (+ currentSessionId: AuthSessionId,+ ) => Effect.Effect<number, ServerAuthInternalError>;+ readonly authenticateHttpRequest: (+ request: HttpServerRequest.HttpServerRequest,+ ) => Effect.Effect<+ AuthenticatedSession,+ ServerAuthInvalidCredentialError | ServerAuthInternalError+ >;+ readonly authenticateWebSocketUpgrade: (+ request: HttpServerRequest.HttpServerRequest,+ ) => Effect.Effect<+ AuthenticatedSession,+ ServerAuthInvalidCredentialError | ServerAuthInternalError+ >;+ readonly issueWebSocketTicket: (+ session: Pick<AuthenticatedSession, "sessionId">,+ ) => Effect.Effect<AuthWebSocketTicketResult, ServerAuthInternalError>;+ readonly issueStartupPairingUrl: (+ baseUrl: string,+ ) => Effect.Effect<string, ServerAuthInternalError>;+}++export class EnvironmentAuth extends Context.Service<EnvironmentAuth, EnvironmentAuthShape>()(+ "t3/auth/EnvironmentAuth",+) {}++type BootstrapExchangeResult = {+ readonly response: AuthBrowserSessionResult;+ readonly sessionToken: string;+};++const AUTHORIZATION_PREFIX = "Bearer ";+const WEBSOCKET_TICKET_QUERY_PARAM = "wsTicket";++const bySessionPriority = (left: AuthClientSession, right: AuthClientSession) => {+ const leftCanManage = left.scopes.includes(AuthAccessWriteScope);+ const rightCanManage = right.scopes.includes(AuthAccessWriteScope);+ if (leftCanManage !== rightCanManage) {+ return leftCanManage ? -1 : 1;+ }+ if (left.connected !== right.connected) {+ return left.connected ? -1 : 1;+ }+ return right.issuedAt.epochMilliseconds - left.issuedAt.epochMilliseconds;+};++const toInternalError =+ (message: string) =>+ (cause: unknown): ServerAuthInternalError =>+ new ServerAuthInternalError({ message, cause });++export function toBootstrapExchangeError(+ cause: PairingGrantStore.BootstrapCredentialError,+): ServerAuthInvalidCredentialError | ServerAuthInternalError {+ if (cause._tag === "BootstrapCredentialInternalError") {+ return new ServerAuthInternalError({+ message: "Failed to validate bootstrap credential.",+ cause,+ });+ }++ return new ServerAuthInvalidCredentialError({+ reason: "invalid_credential",+ cause,+ });+}++const mapSessionVerificationErrors = <A, R>(+ effect: Effect.Effect<A, SessionStore.SessionCredentialError, R>,+): Effect.Effect<A, ServerAuthInvalidCredentialError | ServerAuthInternalError, R> =>+ effect.pipe(+ Effect.catchTags({+ SessionCredentialInvalidError: (cause) =>+ Effect.fail(new ServerAuthInvalidCredentialError({ reason: "invalid_credential", cause })),+ SessionCredentialInternalError: (cause) =>+ Effect.fail(+ new ServerAuthInternalError({+ message: "Failed to validate session credential.",+ cause,+ }),+ ),+ }),+ );++function parseBearerToken(request: HttpServerRequest.HttpServerRequest): string | null {+ const header = request.headers["authorization"];+ if (typeof header !== "string" || !header.startsWith(AUTHORIZATION_PREFIX)) {+ return null;+ }+ const token = header.slice(AUTHORIZATION_PREFIX.length).trim();+ return token.length > 0 ? token : null;+}++export const make = Effect.fn("makeEnvironmentAuth")(function* () {+ const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;+ const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;+ const sessions = yield* SessionStore.SessionStore;+ const descriptor = yield* policy.getDescriptor();++ const authenticateToken = (+ token: string,+ ): Effect.Effect<+ AuthenticatedSession,+ ServerAuthInvalidCredentialError | ServerAuthInternalError+ > =>+ sessions.verify(token).pipe(+ Effect.tapErrorTag("SessionCredentialInvalidError", (cause) =>+ Effect.logWarning("Rejected authenticated session credential.").pipe(+ Effect.annotateLogs({+ reason: cause.message,+ }),+ ),+ ),+ Effect.map((session) => ({+ sessionId: session.sessionId,+ subject: session.subject,+ method: session.method,+ scopes: session.scopes,+ ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),+ })),+ mapSessionVerificationErrors,+ );++ const authenticateRequest = (request: HttpServerRequest.HttpServerRequest) => {+ const cookieToken = request.cookies[sessions.cookieName];+ const bearerToken = parseBearerToken(request);+ const credential = cookieToken ?? bearerToken;+ if (!credential) {+ return Effect.fail(new ServerAuthInvalidCredentialError({ reason: "missing_credential" }));+ }+ return authenticateToken(credential);+ };++ const getSessionState: EnvironmentAuthShape["getSessionState"] = (request) =>+ authenticateRequest(request).pipe(+ Effect.map(+ (session) =>+ ({+ authenticated: true,+ auth: descriptor,+ scopes: session.scopes,+ sessionMethod: session.method,+ ...(session.expiresAt ? { expiresAt: DateTime.toUtc(session.expiresAt) } : {}),+ }) satisfies AuthSessionState,+ ),+ Effect.catchTag("ServerAuthInvalidCredentialError", () =>+ Effect.succeed({+ authenticated: false,+ auth: descriptor,+ } satisfies AuthSessionState),+ ),+ Effect.withSpan("EnvironmentAuth.getSessionState"),+ );++ const createBrowserSession: EnvironmentAuthShape["createBrowserSession"] = (+ credential,+ requestMetadata,+ ) =>+ bootstrapCredentials.consume(credential).pipe(+ Effect.mapError(toBootstrapExchangeError),+ Effect.flatMap((grant) =>+ sessions+ .issue({+ method: "browser-session-cookie",+ subject: grant.subject,+ scopes: grant.scopes,+ client: {+ ...requestMetadata,+ ...(grant.label ? { label: grant.label } : {}),+ },+ })+ .pipe(+ Effect.mapError(+ (cause) =>+ new ServerAuthInternalError({+ message: "Failed to issue authenticated session.",+ cause,+ }),+ ),+ ),+ ),+ Effect.map(+ (session) =>+ ({+ response: {+ authenticated: true,+ scopes: session.scopes,+ sessionMethod: session.method,+ expiresAt: DateTime.toUtc(session.expiresAt),+ } satisfies AuthBrowserSessionResult,+ sessionToken: session.token,+ }) satisfies BootstrapExchangeResult,+ ),+ Effect.withSpan("EnvironmentAuth.createBrowserSession"),+ );++ const exchangeBootstrapCredentialForAccessToken: EnvironmentAuthShape["exchangeBootstrapCredentialForAccessToken"] =+ (credential, requestedScopes, requestMetadata) =>+ bootstrapCredentials.consume(credential).pipe(+ Effect.mapError(toBootstrapExchangeError),+ Effect.flatMap((grant) =>+ Effect.gen(function* () {+ const grantedScopes = requestedScopes ?? grant.scopes;+ if (!grantedScopes.every((scope) => grant.scopes.includes(scope))) {+ return yield* new ServerAuthInvalidRequestError({+ reason: "scope_not_granted",+ });+ }+ return yield* sessions+ .issue({+ method: "bearer-access-token",+ subject: grant.subject,+ scopes: grantedScopes,+ client: {+ ...requestMetadata,+ ...(grant.label ? { label: grant.label } : {}),+ },+ })+ .pipe(+ Effect.mapError(+ (cause) =>+ new ServerAuthInternalError({+ message: "Failed to issue authenticated access token.",+ cause,+ }),+ ),+ );+ }),+ ),+ Effect.flatMap((session) =>+ DateTime.now.pipe(+ Effect.map(+ (now) =>+ ({+ access_token: session.token,+ issued_token_type: AuthAccessTokenType,+ token_type: "Bearer",+ expires_in: Math.max(+ 0,+ Math.floor(+ (session.expiresAt.epochMilliseconds - now.epochMilliseconds) / 1000,+ ),+ ),+ scope: encodeOAuthScope(session.scopes),+ }) satisfies AuthAccessTokenResult,+ ),+ ),+ ),+ Effect.withSpan("EnvironmentAuth.exchangeBootstrapCredentialForAccessToken"),+ );++ const issuePairingCredentialForSubject = (input: {+ readonly scopes: ReadonlyArray<AuthEnvironmentScope>;+ readonly subject: string;+ readonly label?: string;+ }) =>+ createPairingLink({+ scopes: input.scopes,+ subject: input.subject,+ ...(input.label ? { label: input.label } : {}),+ }).pipe(+ Effect.map(+ (issued) =>+ ({+ id: issued.id,+ credential: issued.credential,+ ...(issued.label ? { label: issued.label } : {}),+ expiresAt: issued.expiresAt,+ }) satisfies AuthPairingCredentialResult,+ ),+ );++ const createPairingLink: EnvironmentAuthShape["createPairingLink"] = Effect.fn(+ "EnvironmentAuth.createPairingLink",+ )(+ function* (input) {+ const createdAt = yield* DateTime.now;+ const issued = yield* bootstrapCredentials.issueOneTimeToken({+ scopes: input?.scopes ?? AuthStandardClientScopes,+ subject: input?.subject ?? "one-time-token",+ ...(input?.ttl ? { ttl: input.ttl } : {}),+ ...(input?.label ? { label: input.label } : {}),+ });+ return {+ id: issued.id,+ credential: issued.credential,+ scopes: input?.scopes ?? AuthStandardClientScopes,+ subject: input?.subject ?? "one-time-token",+ ...(issued.label ? { label: issued.label } : {}),+ createdAt: DateTime.toUtc(createdAt),+ expiresAt: DateTime.toUtc(issued.expiresAt),+ } satisfies IssuedPairingLink;+ },+ Effect.mapError(toInternalError("Failed to create pairing link.")),+ );++ const listPairingLinks: EnvironmentAuthShape["listPairingLinks"] = (input) =>+ bootstrapCredentials.listActive().pipe(+ Effect.map((pairingLinks) => {+ const excludedSubjects = input?.excludeSubjects ?? [+ INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,+ ];+ return pairingLinks+ .filter((pairingLink) => !excludedSubjects.includes(pairingLink.subject))+ .toSorted(+ (left, right) => right.createdAt.epochMilliseconds - left.createdAt.epochMilliseconds,+ );+ }),+ Effect.mapError(toInternalError("Failed to list pairing links.")),+ Effect.withSpan("EnvironmentAuth.listPairingLinks"),+ );++ const revokePairingLink: EnvironmentAuthShape["revokePairingLink"] = (id) =>+ bootstrapCredentials+ .revoke(id)+ .pipe(+ Effect.mapError(toInternalError("Failed to revoke pairing link.")),+ Effect.withSpan("EnvironmentAuth.revokePairingLink"),+ );++ const issueSession: EnvironmentAuthShape["issueSession"] = (input) =>+ sessions+ .issue({+ subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,+ method: "bearer-access-token",+ scopes: input?.scopes ?? AuthAdministrativeScopes,+ client: {+ ...(input?.label ? { label: input.label } : {}),+ deviceType: "bot",+ },+ ...(input?.ttl ? { ttl: input.ttl } : {}),+ })+ .pipe(+ Effect.map(+ (issued) =>+ ({+ sessionId: issued.sessionId,+ token: issued.token,+ method: "bearer-access-token",+ scopes: issued.scopes,+ subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,+ client: issued.client,+ expiresAt: DateTime.toUtc(issued.expiresAt),+ }) satisfies IssuedBearerSession,+ ),+ Effect.mapError(toInternalError("Failed to issue session token.")),+ Effect.withSpan("EnvironmentAuth.issueSession"),+ );++ const listSessions: EnvironmentAuthShape["listSessions"] = () =>+ sessions.listActive().pipe(+ Effect.map((activeSessions) => activeSessions.toSorted(bySessionPriority)),+ Effect.mapError(toInternalError("Failed to list sessions.")),+ Effect.withSpan("EnvironmentAuth.listSessions"),+ );++ const revokeSession: EnvironmentAuthShape["revokeSession"] = (sessionId) =>+ sessions+ .revoke(sessionId)+ .pipe(+ Effect.mapError(toInternalError("Failed to revoke session.")),+ Effect.withSpan("EnvironmentAuth.revokeSession"),+ );++ const revokeOtherSessionsExcept: EnvironmentAuthShape["revokeOtherSessionsExcept"] = (+ sessionId,+ ) =>+ sessions+ .revokeAllExcept(sessionId)+ .pipe(+ Effect.mapError(toInternalError("Failed to revoke other sessions.")),+ Effect.withSpan("EnvironmentAuth.revokeOtherSessionsExcept"),+ );++ const issuePairingCredential: EnvironmentAuthShape["issuePairingCredential"] = (input) =>+ issuePairingCredentialForSubject({+ scopes: input?.scopes ?? AuthStandardClientScopes,+ subject: "one-time-token",+ ...(input?.label ? { label: input.label } : {}),+ }).pipe(Effect.withSpan("EnvironmentAuth.issuePairingCredential"));++ const issueStartupPairingCredential: EnvironmentAuthShape["issueStartupPairingCredential"] = () =>+ issuePairingCredentialForSubject({+ scopes: AuthAdministrativeScopes,+ subject: INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,+ }).pipe(Effect.withSpan("EnvironmentAuth.issueStartupPairingCredential"));++ const listClientSessions: EnvironmentAuthShape["listClientSessions"] = (currentSessionId) =>+ listSessions().pipe(+ Effect.map((clientSessions) =>+ clientSessions.map(+ (clientSession): AuthClientSession => ({+ ...clientSession,+ current: clientSession.sessionId === currentSessionId,+ }),+ ),+ ),+ Effect.withSpan("EnvironmentAuth.listClientSessions"),+ );++ const revokeClientSession: EnvironmentAuthShape["revokeClientSession"] = Effect.fn(+ "EnvironmentAuth.revokeClientSession",+ )(function* (currentSessionId, targetSessionId) {+ if (currentSessionId === targetSessionId) {+ return yield* new ServerAuthForbiddenOperationError({+ reason: "current_session_revoke_not_allowed",+ });+ }+ return yield* revokeSession(targetSessionId);+ });++ const revokeOtherClientSessions: EnvironmentAuthShape["revokeOtherClientSessions"] = (+ currentSessionId,+ ) =>+ revokeOtherSessionsExcept(currentSessionId).pipe(+ Effect.withSpan("EnvironmentAuth.revokeOtherClientSessions"),+ );++ const issueStartupPairingUrl: EnvironmentAuthShape["issueStartupPairingUrl"] = (baseUrl) =>+ issueStartupPairingCredential().pipe(+ Effect.map((issued) => {+ const url = new URL(baseUrl);+ url.pathname = "/pair";+ url.searchParams.delete("token");+ url.hash = new URLSearchParams([["token", issued.credential]]).toString();+ return url.toString();+ }),+ Effect.withSpan("EnvironmentAuth.issueStartupPairingUrl"),+ );++ const issueWebSocketTicket: EnvironmentAuthShape["issueWebSocketTicket"] = (session) =>+ sessions.issueWebSocketToken(session.sessionId).pipe(+ Effect.mapError(+ (cause) =>+ new ServerAuthInternalError({+ message: "Failed to issue websocket token.",+ cause,+ }),+ ),+ Effect.map(+ (issued) =>+ ({+ ticket: issued.token,+ expiresAt: DateTime.toUtc(issued.expiresAt),+ }) satisfies AuthWebSocketTicketResult,+ ),+ Effect.withSpan("EnvironmentAuth.issueWebSocketTicket"),+ );++ const authenticateHttpRequest: EnvironmentAuthShape["authenticateHttpRequest"] = (request) =>+ authenticateRequest(request).pipe(Effect.withSpan("EnvironmentAuth.authenticateHttpRequest"));++ const authenticateWebSocketUpgrade: EnvironmentAuthShape["authenticateWebSocketUpgrade"] =+ Effect.fn("EnvironmentAuth.authenticateWebSocketUpgrade")(function* (request) {+ const requestUrl = HttpServerRequest.toURL(request);+ if (Option.isSome(requestUrl)) {+ const websocketTicket = requestUrl.value.searchParams.get(WEBSOCKET_TICKET_QUERY_PARAM);+ if (websocketTicket && websocketTicket.trim().length > 0) {+ return yield* sessions.verifyWebSocketToken(websocketTicket).pipe(+ Effect.map((session) => ({+ sessionId: session.sessionId,+ subject: session.subject,+ method: session.method,+ scopes: session.scopes,+ ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),+ })),+ mapSessionVerificationErrors,+ );+ }+ }++ return yield* authenticateRequest(request);+ });++ return {+ getDescriptor: () =>+ Effect.succeed(descriptor).pipe(Effect.withSpan("EnvironmentAuth.getDescriptor")),+ getSessionState,+ createBrowserSession,+ exchangeBootstrapCredentialForAccessToken,+ createPairingLink,+ issuePairingCredential,+ issueStartupPairingCredential,+ listPairingLinks,+ revokePairingLink,+ issueSession,+ listSessions,+ revokeSession,+ revokeOtherSessionsExcept,+ listClientSessions,+ revokeClientSession,+ revokeOtherClientSessions,+ authenticateHttpRequest,+ authenticateWebSocketUpgrade,+ issueWebSocketTicket,+ issueStartupPairingUrl,+ } satisfies EnvironmentAuthShape;+});++export const layer = Layer.effect(EnvironmentAuth, make()).pipe(+ Layer.provideMerge(PairingGrantStore.layer),+ Layer.provideMerge(SessionStore.layer),+ Layer.provideMerge(EnvironmentAuthPolicy.layer),+);++export const storageLayer = Layer.mergeAll(ServerSecretStore.layer, SqlitePersistenceLayer);++export const runtimeLayer = layer.pipe(Layer.provideMerge(storageLayer));diff --git a/apps/server/src/auth/EnvironmentAuthAdmin.test.ts b/apps/server/src/auth/EnvironmentAuthAdmin.test.tsnew file mode 100644index 000000000..44c28dea4--- /dev/null+++ b/apps/server/src/auth/EnvironmentAuthAdmin.test.ts@@ -0,0 +1,125 @@+import * as NodeServices from "@effect/platform-node/NodeServices";+import { expect, it } from "@effect/vitest";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";++import type { ServerConfigShape } from "../config.ts";+import { ServerConfig } from "../config.ts";+import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";+import * as EnvironmentAuth from "./EnvironmentAuth.ts";+import * as ServerSecretStore from "./ServerSecretStore.ts";+import * as SessionStore from "./SessionStore.ts";++const makeServerConfigLayer = (+ overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,+) =>+ Layer.effect(+ ServerConfig,+ Effect.gen(function* () {+ const config = yield* ServerConfig;+ return {+ ...config,+ ...overrides,+ } satisfies ServerConfigShape;+ }),+ ).pipe(+ Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-control-plane-test-" })),+ );++const makeEnvironmentAuthLayer = (+ overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,+) =>+ EnvironmentAuth.layer.pipe(+ Layer.provideMerge(ServerSecretStore.layer),+ Layer.provideMerge(SqlitePersistenceMemory),+ Layer.provide(makeServerConfigLayer(overrides)),+ );++it.layer(NodeServices.layer)("EnvironmentAuth administrative operations", (it) => {+ it.effect("creates, lists, and revokes client pairing links", () =>+ Effect.gen(function* () {+ const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;++ const created = yield* environmentAuth.createPairingLink({+ scopes: ["orchestration:read"],+ subject: "one-time-token",+ label: "CI phone",+ });+ const listedBeforeRevoke = yield* environmentAuth.listPairingLinks();+ const revoked = yield* environmentAuth.revokePairingLink(created.id);+ const listedAfterRevoke = yield* environmentAuth.listPairingLinks();++ expect(created.scopes).toEqual(["orchestration:read"]);+ expect(created.credential.length).toBeGreaterThan(0);+ expect(listedBeforeRevoke).toHaveLength(1);+ expect(listedBeforeRevoke[0]?.id).toBe(created.id);+ expect(listedBeforeRevoke[0]?.label).toBe("CI phone");+ expect(listedBeforeRevoke[0]?.credential).toBe(created.credential);+ expect(revoked).toBe(true);+ expect(listedAfterRevoke).toHaveLength(0);+ }).pipe(Effect.provide(makeEnvironmentAuthLayer())),+ );++ it.effect("issues bearer access token sessions without exposing raw tokens", () =>+ Effect.gen(function* () {+ const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;+ const sessionCredentials = yield* SessionStore.SessionStore;++ const issued = yield* environmentAuth.issueSession({+ label: "deploy-bot",+ });+ const verified = yield* sessionCredentials.verify(issued.token);+ const listedBeforeRevoke = yield* environmentAuth.listSessions();+ const revoked = yield* environmentAuth.revokeSession(issued.sessionId);+ const listedAfterRevoke = yield* environmentAuth.listSessions();++ expect(issued.method).toBe("bearer-access-token");+ expect(issued.scopes).toEqual([+ "orchestration:read",+ "orchestration:operate",+ "terminal:operate",+ "review:write",+ "relay:read",+ "access:read",+ "access:write",+ "relay:write",+ ]);+ expect(issued.client.deviceType).toBe("bot");+ expect(issued.client.label).toBe("deploy-bot");+ expect(verified.sessionId).toBe(issued.sessionId);+ expect(verified.scopes).toEqual([+ "orchestration:read",+ "orchestration:operate",+ "terminal:operate",+ "review:write",+ "relay:read",+ "access:read",+ "access:write",+ "relay:write",+ ]);+ expect(verified.method).toBe("bearer-access-token");+ expect(listedBeforeRevoke).toHaveLength(1);+ expect(listedBeforeRevoke[0]?.sessionId).toBe(issued.sessionId);+ expect("token" in (listedBeforeRevoke[0] ?? {})).toBe(false);+ expect(revoked).toBe(true);+ expect(listedAfterRevoke).toHaveLength(0);+ }).pipe(Effect.provide(makeEnvironmentAuthLayer())),+ );++ it.effect("surfaces lastConnectedAt through the listed session view", () =>+ Effect.gen(function* () {+ const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;+ const sessionCredentials = yield* SessionStore.SessionStore;++ const issued = yield* environmentAuth.issueSession({+ label: "remote-ipad",+ });+ const beforeConnect = yield* environmentAuth.listSessions();+ yield* sessionCredentials.markConnected(issued.sessionId);+ const afterConnect = yield* environmentAuth.listSessions();++ expect(beforeConnect[0]?.lastConnectedAt).toBeNull();+ expect(afterConnect[0]?.lastConnectedAt).not.toBeNull();+ }).pipe(Effect.provide(makeEnvironmentAuthLayer())),+ );+});diff --git a/apps/server/src/auth/Layers/ServerAuthPolicy.test.ts b/apps/server/src/auth/EnvironmentAuthPolicy.test.tssimilarity index 74%rename from apps/server/src/auth/Layers/ServerAuthPolicy.test.tsrename to apps/server/src/auth/EnvironmentAuthPolicy.test.tsindex fcc56686d..c9f5dc623 100644--- a/apps/server/src/auth/Layers/ServerAuthPolicy.test.ts+++ b/apps/server/src/auth/EnvironmentAuthPolicy.test.ts@@ -3,13 +3,12 @@ import { expect, it } from "@effect/vitest";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";-import type { ServerConfigShape } from "../../config.ts";-import { ServerConfig } from "../../config.ts";-import { ServerAuthPolicy } from "../Services/ServerAuthPolicy.ts";-import { ServerAuthPolicyLive } from "./ServerAuthPolicy.ts";+import type { ServerConfigShape } from "../config.ts";+import { ServerConfig } from "../config.ts";+import * as EnvironmentAuthPolicy from "./EnvironmentAuthPolicy.ts";-const makeServerAuthPolicyLayer = (overrides?: Partial<ServerConfigShape>) =>- ServerAuthPolicyLive.pipe(+const makeEnvironmentAuthPolicyLayer = (overrides?: Partial<ServerConfigShape>) =>+ EnvironmentAuthPolicy.layer.pipe(Layer.provide(Layer.effect(ServerConfig,@@ -26,10 +25,10 @@ const makeServerAuthPolicyLayer = (overrides?: Partial<ServerConfigShape>) =>),);-it.layer(NodeServices.layer)("ServerAuthPolicyLive", (it) => {+it.layer(NodeServices.layer)("EnvironmentAuthPolicy.layer", (it) => {it.effect("uses desktop-managed-local policy for desktop mode", () =>Effect.gen(function* () {- const policy = yield* ServerAuthPolicy;+ const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;const descriptor = yield* policy.getDescriptor();expect(descriptor.policy).toBe("desktop-managed-local");@@ -37,7 +36,7 @@ it.layer(NodeServices.layer)("ServerAuthPolicyLive", (it) => {expect(descriptor.sessionCookieName).toBe("t3_session_3773");}).pipe(Effect.provide(- makeServerAuthPolicyLayer({+ makeEnvironmentAuthPolicyLayer({mode: "desktop",port: 3773,}),@@ -47,14 +46,14 @@ it.layer(NodeServices.layer)("ServerAuthPolicyLive", (it) => {it.effect("uses remote-reachable policy for desktop mode when bound beyond loopback", () =>Effect.gen(function* () {- const policy = yield* ServerAuthPolicy;+ const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;const descriptor = yield* policy.getDescriptor();expect(descriptor.policy).toBe("remote-reachable");expect(descriptor.bootstrapMethods).toEqual(["desktop-bootstrap", "one-time-token"]);}).pipe(Effect.provide(- makeServerAuthPolicyLayer({+ makeEnvironmentAuthPolicyLayer({mode: "desktop",host: "0.0.0.0",}),@@ -64,7 +63,7 @@ it.layer(NodeServices.layer)("ServerAuthPolicyLive", (it) => {it.effect("uses loopback-browser policy for loopback web hosts", () =>Effect.gen(function* () {- const policy = yield* ServerAuthPolicy;+ const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;const descriptor = yield* policy.getDescriptor();expect(descriptor.policy).toBe("loopback-browser");@@ -72,7 +71,7 @@ it.layer(NodeServices.layer)("ServerAuthPolicyLive", (it) => {expect(descriptor.sessionCookieName).toBe("t3_session");}).pipe(Effect.provide(- makeServerAuthPolicyLayer({+ makeEnvironmentAuthPolicyLayer({mode: "web",host: "127.0.0.1",}),@@ -82,14 +81,14 @@ it.layer(NodeServices.layer)("ServerAuthPolicyLive", (it) => {it.effect("uses remote-reachable policy for wildcard web hosts", () =>Effect.gen(function* () {- const policy = yield* ServerAuthPolicy;+ const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;const descriptor = yield* policy.getDescriptor();expect(descriptor.policy).toBe("remote-reachable");expect(descriptor.bootstrapMethods).toEqual(["one-time-token"]);}).pipe(Effect.provide(- makeServerAuthPolicyLayer({+ makeEnvironmentAuthPolicyLayer({mode: "web",host: "0.0.0.0",}),@@ -99,13 +98,13 @@ it.layer(NodeServices.layer)("ServerAuthPolicyLive", (it) => {it.effect("uses remote-reachable policy for non-loopback web hosts", () =>Effect.gen(function* () {- const policy = yield* ServerAuthPolicy;+ const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;const descriptor = yield* policy.getDescriptor();expect(descriptor.policy).toBe("remote-reachable");}).pipe(Effect.provide(- makeServerAuthPolicyLayer({+ makeEnvironmentAuthPolicyLayer({mode: "web",host: "192.168.1.50",}),diff --git a/apps/server/src/auth/Layers/ServerAuthPolicy.ts b/apps/server/src/auth/EnvironmentAuthPolicy.tssimilarity index 53%rename from apps/server/src/auth/Layers/ServerAuthPolicy.tsrename to apps/server/src/auth/EnvironmentAuthPolicy.tsindex 2c000bc18..3968ddb25 100644--- a/apps/server/src/auth/Layers/ServerAuthPolicy.ts+++ b/apps/server/src/auth/EnvironmentAuthPolicy.ts@@ -1,13 +1,22 @@import type { ServerAuthDescriptor } from "@t3tools/contracts";+import * as Context from "effect/Context";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";-import { ServerConfig } from "../../config.ts";-import { ServerAuthPolicy, type ServerAuthPolicyShape } from "../Services/ServerAuthPolicy.ts";-import { resolveSessionCookieName } from "../utils.ts";-import { isLoopbackHost, isWildcardHost } from "../../startupAccess.ts";+import { ServerConfig } from "../config.ts";+import { resolveSessionCookieName } from "./utils.ts";+import { isLoopbackHost, isWildcardHost } from "../startupAccess.ts";-export const makeServerAuthPolicy = Effect.gen(function* () {+export interface EnvironmentAuthPolicyShape {+ readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;+}++export class EnvironmentAuthPolicy extends Context.Service<+ EnvironmentAuthPolicy,+ EnvironmentAuthPolicyShape+>()("t3/auth/EnvironmentAuthPolicy") {}++export const make = Effect.fn("makeEnvironmentAuthPolicy")(function* () {const config = yield* ServerConfig;const isRemoteReachable = isWildcardHost(config.host) || !isLoopbackHost(config.host);@@ -30,7 +39,7 @@ export const makeServerAuthPolicy = Effect.gen(function* () {const descriptor: ServerAuthDescriptor = {policy,bootstrapMethods,- sessionMethods: ["browser-session-cookie", "bearer-session-token"],+ sessionMethods: ["browser-session-cookie", "bearer-access-token"],sessionCookieName: resolveSessionCookieName({mode: config.mode,port: config.port,@@ -38,8 +47,9 @@ export const makeServerAuthPolicy = Effect.gen(function* () {};return {- getDescriptor: () => Effect.succeed(descriptor),- } satisfies ServerAuthPolicyShape;+ getDescriptor: () =>+ Effect.succeed(descriptor).pipe(Effect.withSpan("EnvironmentAuthPolicy.getDescriptor")),+ } satisfies EnvironmentAuthPolicyShape;});-export const ServerAuthPolicyLive = Layer.effect(ServerAuthPolicy, makeServerAuthPolicy);+export const layer = Layer.effect(EnvironmentAuthPolicy, make());diff --git a/apps/server/src/auth/Layers/AuthControlPlane.test.ts b/apps/server/src/auth/Layers/AuthControlPlane.test.tsdeleted file mode 100644index 23ea4e979..000000000--- a/apps/server/src/auth/Layers/AuthControlPlane.test.ts+++ /dev/null@@ -1,112 +0,0 @@-import * as NodeServices from "@effect/platform-node/NodeServices";-import { expect, it } from "@effect/vitest";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";--import type { ServerConfigShape } from "../../config.ts";-import { ServerConfig } from "../../config.ts";-import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";-import { ServerSecretStoreLive } from "./ServerSecretStore.ts";-import { SessionCredentialServiceLive } from "./SessionCredentialService.ts";-import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";-import { AuthControlPlane } from "../Services/AuthControlPlane.ts";-import { makeAuthControlPlane } from "./AuthControlPlane.ts";-import { SessionCredentialService } from "../Services/SessionCredentialService.ts";--const makeServerConfigLayer = (- overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,-) =>- Layer.effect(- ServerConfig,- Effect.gen(function* () {- const config = yield* ServerConfig;- return {- ...config,- ...overrides,- } satisfies ServerConfigShape;- }),- ).pipe(- Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-control-plane-test-" })),- );--const makeAuthControlPlaneLayer = (- overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,-) =>- Layer.effect(AuthControlPlane, makeAuthControlPlane).pipe(- Layer.provideMerge(BootstrapCredentialServiceLive),- Layer.provideMerge(SessionCredentialServiceLive),- Layer.provideMerge(ServerSecretStoreLive),- Layer.provideMerge(SqlitePersistenceMemory),- Layer.provide(makeServerConfigLayer(overrides)),- );--it.layer(NodeServices.layer)("AuthControlPlane", (it) => {- it.effect("creates, lists, and revokes client pairing links", () =>- Effect.gen(function* () {- const authControlPlane = yield* AuthControlPlane;-- const created = yield* authControlPlane.createPairingLink({- role: "client",- subject: "one-time-token",- label: "CI phone",- });- const listedBeforeRevoke = yield* authControlPlane.listPairingLinks({ role: "client" });- const revoked = yield* authControlPlane.revokePairingLink(created.id);- const listedAfterRevoke = yield* authControlPlane.listPairingLinks({ role: "client" });-- expect(created.role).toBe("client");- expect(created.credential.length).toBeGreaterThan(0);- expect(listedBeforeRevoke).toHaveLength(1);- expect(listedBeforeRevoke[0]?.id).toBe(created.id);- expect(listedBeforeRevoke[0]?.label).toBe("CI phone");- expect(listedBeforeRevoke[0]?.credential).toBe(created.credential);- expect(revoked).toBe(true);- expect(listedAfterRevoke).toHaveLength(0);- }).pipe(Effect.provide(makeAuthControlPlaneLayer())),- );-- it.effect("issues bearer sessions and lists them without exposing raw tokens", () =>- Effect.gen(function* () {- const authControlPlane = yield* AuthControlPlane;- const sessionCredentials = yield* SessionCredentialService;-- const issued = yield* authControlPlane.issueSession({- label: "deploy-bot",- });- const verified = yield* sessionCredentials.verify(issued.token);- const listedBeforeRevoke = yield* authControlPlane.listSessions();- const revoked = yield* authControlPlane.revokeSession(issued.sessionId);- const listedAfterRevoke = yield* authControlPlane.listSessions();-- expect(issued.method).toBe("bearer-session-token");- expect(issued.role).toBe("owner");- expect(issued.client.deviceType).toBe("bot");- expect(issued.client.label).toBe("deploy-bot");- expect(verified.sessionId).toBe(issued.sessionId);- expect(verified.role).toBe("owner");- expect(verified.method).toBe("bearer-session-token");- expect(listedBeforeRevoke).toHaveLength(1);- expect(listedBeforeRevoke[0]?.sessionId).toBe(issued.sessionId);- expect("token" in (listedBeforeRevoke[0] ?? {})).toBe(false);- expect(revoked).toBe(true);- expect(listedAfterRevoke).toHaveLength(0);- }).pipe(Effect.provide(makeAuthControlPlaneLayer())),- );-- it.effect("surfaces lastConnectedAt through the listed session view", () =>- Effect.gen(function* () {- const authControlPlane = yield* AuthControlPlane;- const sessionCredentials = yield* SessionCredentialService;-- const issued = yield* authControlPlane.issueSession({- label: "remote-ipad",- });- const beforeConnect = yield* authControlPlane.listSessions();- yield* sessionCredentials.markConnected(issued.sessionId);- const afterConnect = yield* authControlPlane.listSessions();-- expect(beforeConnect[0]?.lastConnectedAt).toBeNull();- expect(afterConnect[0]?.lastConnectedAt).not.toBeNull();- }).pipe(Effect.provide(makeAuthControlPlaneLayer())),- );-});diff --git a/apps/server/src/auth/Layers/AuthControlPlane.ts b/apps/server/src/auth/Layers/AuthControlPlane.tsdeleted file mode 100644index 6c42cd2db..000000000--- a/apps/server/src/auth/Layers/AuthControlPlane.ts+++ /dev/null@@ -1,186 +0,0 @@-import type { AuthClientSession, AuthPairingLink } from "@t3tools/contracts";-import * as DateTime from "effect/DateTime";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";--import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";-import { ServerSecretStoreLive } from "./ServerSecretStore.ts";-import { SessionCredentialServiceLive } from "./SessionCredentialService.ts";-import { BootstrapCredentialService } from "../Services/BootstrapCredentialService.ts";-import { SessionCredentialService } from "../Services/SessionCredentialService.ts";-import { layerConfig as SqlitePersistenceLayerLive } from "../../persistence/Layers/Sqlite.ts";-import {- AuthControlPlane,- AuthControlPlaneError,- DEFAULT_SESSION_SUBJECT,-} from "../Services/AuthControlPlane.ts";-import type {- AuthControlPlaneShape,- IssuedBearerSession,- IssuedPairingLink,-} from "../Services/AuthControlPlane.ts";--const bySessionPriority = (left: AuthClientSession, right: AuthClientSession) => {- if (left.role !== right.role) {- return left.role === "owner" ? -1 : 1;- }- if (left.connected !== right.connected) {- return left.connected ? -1 : 1;- }- return right.issuedAt.epochMilliseconds - left.issuedAt.epochMilliseconds;-};--const toAuthControlPlaneError =- (message: string) =>- (cause: unknown): AuthControlPlaneError =>- new AuthControlPlaneError({- message,- cause,- });--export const makeAuthControlPlane = Effect.gen(function* () {- const bootstrapCredentials = yield* BootstrapCredentialService;- const sessions = yield* SessionCredentialService;-- const createPairingLink: AuthControlPlaneShape["createPairingLink"] = (input) =>- Effect.gen(function* () {- const createdAt = yield* DateTime.now;- const issued = yield* bootstrapCredentials.issueOneTimeToken({- role: input?.role ?? "client",- subject: input?.subject ?? "one-time-token",- ...(input?.ttl ? { ttl: input.ttl } : {}),- ...(input?.label ? { label: input.label } : {}),- });- return {- id: issued.id,- credential: issued.credential,- role: input?.role ?? "client",- subject: input?.subject ?? "one-time-token",- ...(issued.label ? { label: issued.label } : {}),- createdAt: DateTime.toUtc(createdAt),- expiresAt: DateTime.toUtc(issued.expiresAt),- } satisfies IssuedPairingLink;- }).pipe(Effect.mapError(toAuthControlPlaneError("Failed to create pairing link.")));-- const listPairingLinks: AuthControlPlaneShape["listPairingLinks"] = (input) =>- bootstrapCredentials.listActive().pipe(- Effect.map((pairingLinks) => {- const activeLinks: Array<AuthPairingLink> = [];- for (const pairingLink of pairingLinks) {- if (input?.role && pairingLink.role !== input.role) {- continue;- }- if (input?.excludeSubjects?.includes(pairingLink.subject)) {- continue;- }- activeLinks.push(- pairingLink.label- ? ({- id: pairingLink.id,- credential: pairingLink.credential,- role: pairingLink.role,- subject: pairingLink.subject,- label: pairingLink.label,- createdAt: pairingLink.createdAt,- expiresAt: pairingLink.expiresAt,- } satisfies AuthPairingLink)- : ({- id: pairingLink.id,- credential: pairingLink.credential,- role: pairingLink.role,- subject: pairingLink.subject,- createdAt: pairingLink.createdAt,- expiresAt: pairingLink.expiresAt,- } satisfies AuthPairingLink),- );- }- return activeLinks.toSorted(- (left, right) => right.createdAt.epochMilliseconds - left.createdAt.epochMilliseconds,- );- }),- Effect.mapError(toAuthControlPlaneError("Failed to list pairing links.")),- );-- const revokePairingLink: AuthControlPlaneShape["revokePairingLink"] = (id) =>- bootstrapCredentials- .revoke(id)- .pipe(Effect.mapError(toAuthControlPlaneError("Failed to revoke pairing link.")));-- const issueSession: AuthControlPlaneShape["issueSession"] = (input) =>- sessions- .issue({- subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,- method: "bearer-session-token",- role: input?.role ?? "owner",- client: {- ...(input?.label ? { label: input.label } : {}),- deviceType: "bot",- },- ...(input?.ttl ? { ttl: input.ttl } : {}),- })- .pipe(- Effect.flatMap((issued) => {- if (issued.method !== "bearer-session-token") {- return Effect.fail(- new AuthControlPlaneError({- message: "CLI session issuance produced an unexpected session method.",- }),- );- }-- return Effect.succeed({- sessionId: issued.sessionId,- token: issued.token,- method: "bearer-session-token" as const,- role: issued.role,- subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,- client: issued.client,- expiresAt: DateTime.toUtc(issued.expiresAt),- } satisfies IssuedBearerSession);- }),- Effect.mapError(toAuthControlPlaneError("Failed to issue session token.")),- );-- const listSessions: AuthControlPlaneShape["listSessions"] = () =>- sessions.listActive().pipe(- Effect.map((activeSessions) => activeSessions.toSorted(bySessionPriority)),- Effect.mapError(toAuthControlPlaneError("Failed to list sessions.")),- );-- const revokeSession: AuthControlPlaneShape["revokeSession"] = (sessionId) =>- sessions- .revoke(sessionId)- .pipe(Effect.mapError(toAuthControlPlaneError("Failed to revoke session.")));-- const revokeOtherSessionsExcept: AuthControlPlaneShape["revokeOtherSessionsExcept"] = (- sessionId,- ) =>- sessions- .revokeAllExcept(sessionId)- .pipe(Effect.mapError(toAuthControlPlaneError("Failed to revoke other sessions.")));-- return {- createPairingLink,- listPairingLinks,- revokePairingLink,- issueSession,- listSessions,- revokeSession,- revokeOtherSessionsExcept,- } satisfies AuthControlPlaneShape;-});--export const AuthCoreLive = Layer.mergeAll(- BootstrapCredentialServiceLive,- SessionCredentialServiceLive,-);--export const AuthStorageLive = Layer.mergeAll(ServerSecretStoreLive, SqlitePersistenceLayerLive);--export const AuthRuntimeLive = AuthCoreLive.pipe(Layer.provideMerge(AuthStorageLive));--export const AuthControlPlaneLive = Layer.effect(AuthControlPlane, makeAuthControlPlane);--export const AuthControlPlaneRuntimeLive = AuthControlPlaneLive.pipe(- Layer.provideMerge(AuthRuntimeLive),-);diff --git a/apps/server/src/auth/Layers/ServerAuth.test.ts b/apps/server/src/auth/Layers/ServerAuth.test.tsdeleted file mode 100644index 748f4ded7..000000000--- a/apps/server/src/auth/Layers/ServerAuth.test.ts+++ /dev/null@@ -1,183 +0,0 @@-import * as NodeServices from "@effect/platform-node/NodeServices";-import { expect, it } from "@effect/vitest";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";--import type { ServerConfigShape } from "../../config.ts";-import { ServerConfig } from "../../config.ts";-import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";-import { BootstrapCredentialError } from "../Services/BootstrapCredentialService.ts";-import { ServerAuth, type ServerAuthShape } from "../Services/ServerAuth.ts";-import { ServerAuthLive, toBootstrapExchangeAuthError } from "./ServerAuth.ts";-import { ServerSecretStoreLive } from "./ServerSecretStore.ts";--const makeServerConfigLayer = (overrides?: Partial<ServerConfigShape>) =>- Layer.effect(- ServerConfig,- Effect.gen(function* () {- const config = yield* ServerConfig;- return {- ...config,- ...overrides,- } satisfies ServerConfigShape;- }),- ).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-server-test-" })));--const makeServerAuthLayer = (overrides?: Partial<ServerConfigShape>) =>- ServerAuthLive.pipe(- Layer.provide(SqlitePersistenceMemory),- Layer.provide(ServerSecretStoreLive),- Layer.provide(makeServerConfigLayer(overrides)),- );--const makeCookieRequest = (- sessionToken: string,-): Parameters<ServerAuthShape["authenticateHttpRequest"]>[0] =>- ({- cookies: {- t3_session: sessionToken,- },- headers: {},- }) as unknown as Parameters<ServerAuthShape["authenticateHttpRequest"]>[0];--const requestMetadata = {- deviceType: "desktop" as const,- os: "macOS",- browser: "Chrome",- ipAddress: "192.168.1.23",-};--it.layer(NodeServices.layer)("ServerAuthLive", (it) => {- it.effect("maps invalid bootstrap credential failures to 401", () =>- Effect.sync(() => {- const error = toBootstrapExchangeAuthError(- new BootstrapCredentialError({- message: "Unknown bootstrap credential.",- status: 401,- }),- );-- expect(error.status).toBe(401);- expect(error.message).toBe("Invalid bootstrap credential.");- }),- );-- it.effect("maps unexpected bootstrap failures to 500", () =>- Effect.sync(() => {- const error = toBootstrapExchangeAuthError(- new BootstrapCredentialError({- message: "Failed to consume bootstrap credential.",- status: 500,- cause: new Error("sqlite is unavailable"),- }),- );-- expect(error.status).toBe(500);- expect(error.message).toBe("Failed to validate bootstrap credential.");- }),- );-- it.effect("issues client pairing credentials by default", () =>- Effect.gen(function* () {- const serverAuth = yield* ServerAuth;-- const pairingCredential = yield* serverAuth.issuePairingCredential();- const exchanged = yield* serverAuth.exchangeBootstrapCredential(- pairingCredential.credential,- requestMetadata,- );- const verified = yield* serverAuth.authenticateHttpRequest(- makeCookieRequest(exchanged.sessionToken),- );-- expect(verified.sessionId.length).toBeGreaterThan(0);- expect(verified.role).toBe("client");- expect(verified.subject).toBe("one-time-token");- }).pipe(Effect.provide(makeServerAuthLayer())),- );-- it.effect("issues startup pairing URLs that bootstrap owner sessions", () =>- Effect.gen(function* () {- const serverAuth = yield* ServerAuth;-- const pairingUrl = yield* serverAuth.issueStartupPairingUrl("http://127.0.0.1:3773");- const token = new URLSearchParams(new URL(pairingUrl).hash.slice(1)).get("token");- const listedPairingLinks = yield* serverAuth.listPairingLinks();- expect(token).toBeTruthy();- expect(- listedPairingLinks.some((pairingLink) => pairingLink.subject === "owner-bootstrap"),- ).toBe(false);-- const exchanged = yield* serverAuth.exchangeBootstrapCredential(token ?? "", requestMetadata);- const verified = yield* serverAuth.authenticateHttpRequest(- makeCookieRequest(exchanged.sessionToken),- );-- expect(verified.role).toBe("owner");- expect(verified.subject).toBe("owner-bootstrap");- }).pipe(Effect.provide(makeServerAuthLayer())),- );-- it.effect("lists pairing links and revokes other client sessions while keeping the owner", () =>- Effect.gen(function* () {- const serverAuth = yield* ServerAuth;-- const ownerExchange = yield* serverAuth.exchangeBootstrapCredential(- "desktop-bootstrap-token",- requestMetadata,- );- const ownerSession = yield* serverAuth.authenticateHttpRequest(- makeCookieRequest(ownerExchange.sessionToken),- );- const pairingCredential = yield* serverAuth.issuePairingCredential({- label: "Julius iPhone",- });- const listedPairingLinks = yield* serverAuth.listPairingLinks();- const clientExchange = yield* serverAuth.exchangeBootstrapCredential(- pairingCredential.credential,- {- ...requestMetadata,- deviceType: "mobile",- os: "iOS",- browser: "Safari",- ipAddress: "192.168.1.88",- },- );- const clientSession = yield* serverAuth.authenticateHttpRequest(- makeCookieRequest(clientExchange.sessionToken),- );- const clientsBeforeRevoke = yield* serverAuth.listClientSessions(ownerSession.sessionId);- const revokedCount = yield* serverAuth.revokeOtherClientSessions(ownerSession.sessionId);- const clientsAfterRevoke = yield* serverAuth.listClientSessions(ownerSession.sessionId);-- expect(listedPairingLinks.map((entry) => entry.id)).toContain(pairingCredential.id);- expect(listedPairingLinks.find((entry) => entry.id === pairingCredential.id)?.label).toBe(- "Julius iPhone",- );- expect(clientsBeforeRevoke).toHaveLength(2);- expect(- clientsBeforeRevoke.find((entry) => entry.sessionId === ownerSession.sessionId)?.current,- ).toBe(true);- expect(- clientsBeforeRevoke.find((entry) => entry.sessionId === clientSession.sessionId)?.current,- ).toBe(false);- expect(- clientsBeforeRevoke.find((entry) => entry.sessionId === clientSession.sessionId)?.client- .label,- ).toBe("Julius iPhone");- expect(- clientsBeforeRevoke.find((entry) => entry.sessionId === clientSession.sessionId)?.client- .deviceType,- ).toBe("mobile");- expect(revokedCount).toBe(1);- expect(clientsAfterRevoke).toHaveLength(1);- expect(clientsAfterRevoke[0]?.sessionId).toBe(ownerSession.sessionId);- }).pipe(- Effect.provide(- makeServerAuthLayer({- desktopBootstrapToken: "desktop-bootstrap-token",- }),- ),- ),- );-});diff --git a/apps/server/src/auth/Layers/ServerAuth.ts b/apps/server/src/auth/Layers/ServerAuth.tsdeleted file mode 100644index 238475aca..000000000--- a/apps/server/src/auth/Layers/ServerAuth.ts+++ /dev/null@@ -1,398 +0,0 @@-import {- type AuthBearerBootstrapResult,- type AuthClientSession,- type AuthBootstrapResult,- type AuthPairingCredentialResult,- type AuthSessionState,- type AuthWebSocketTokenResult,-} from "@t3tools/contracts";-import * as DateTime from "effect/DateTime";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Option from "effect/Option";-import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";--import { AuthControlPlane } from "../Services/AuthControlPlane.ts";-import { ServerAuthPolicyLive } from "./ServerAuthPolicy.ts";-import { BootstrapCredentialService } from "../Services/BootstrapCredentialService.ts";-import { BootstrapCredentialError } from "../Services/BootstrapCredentialService.ts";-import { ServerAuthPolicy } from "../Services/ServerAuthPolicy.ts";-import {- ServerAuth,- type AuthenticatedSession,- AuthError,- type ServerAuthShape,-} from "../Services/ServerAuth.ts";-import {- SessionCredentialError,- SessionCredentialService,-} from "../Services/SessionCredentialService.ts";-import { AuthControlPlaneLive, AuthCoreLive } from "./AuthControlPlane.ts";--type BootstrapExchangeResult = {- readonly response: AuthBootstrapResult;- readonly sessionToken: string;-};--const AUTHORIZATION_PREFIX = "Bearer ";-const WEBSOCKET_TOKEN_QUERY_PARAM = "wsToken";--export function toBootstrapExchangeAuthError(cause: BootstrapCredentialError): AuthError {- if (cause.status === 500) {- return new AuthError({- message: "Failed to validate bootstrap credential.",- status: 500,- cause,- });- }-- return new AuthError({- message: "Invalid bootstrap credential.",- status: 401,- cause,- });-}--function parseBearerToken(request: HttpServerRequest.HttpServerRequest): string | null {- const header = request.headers["authorization"];- if (typeof header !== "string" || !header.startsWith(AUTHORIZATION_PREFIX)) {- return null;- }- const token = header.slice(AUTHORIZATION_PREFIX.length).trim();- return token.length > 0 ? token : null;-}--export const makeServerAuth = Effect.gen(function* () {- const policy = yield* ServerAuthPolicy;- const bootstrapCredentials = yield* BootstrapCredentialService;- const authControlPlane = yield* AuthControlPlane;- const sessions = yield* SessionCredentialService;- const descriptor = yield* policy.getDescriptor();-- const authenticateToken = (token: string): Effect.Effect<AuthenticatedSession, AuthError> =>- sessions.verify(token).pipe(- Effect.tapError((cause: SessionCredentialError) =>- Effect.logWarning("Rejected authenticated session credential.").pipe(- Effect.annotateLogs({- reason: cause.message,- }),- ),- ),- Effect.map((session) => ({- sessionId: session.sessionId,- subject: session.subject,- method: session.method,- role: session.role,- ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),- })),- Effect.mapError(- (cause) =>- new AuthError({- message: "Unauthorized request.",- status: 401,- cause,- }),- ),- );-- const authenticateRequest = (request: HttpServerRequest.HttpServerRequest) => {- const cookieToken = request.cookies[sessions.cookieName];- const bearerToken = parseBearerToken(request);- const credential = cookieToken ?? bearerToken;- if (!credential) {- return Effect.fail(- new AuthError({- message: "Authentication required.",- status: 401,- }),- );- }- return authenticateToken(credential);- };-- const getSessionState: ServerAuthShape["getSessionState"] = (request) =>- authenticateRequest(request).pipe(- Effect.map(- (session) =>- ({- authenticated: true,- auth: descriptor,- role: session.role,- sessionMethod: session.method,- ...(session.expiresAt ? { expiresAt: DateTime.toUtc(session.expiresAt) } : {}),- }) satisfies AuthSessionState,- ),- Effect.catchTag("AuthError", () =>- Effect.succeed({- authenticated: false,- auth: descriptor,- } satisfies AuthSessionState),- ),- );-- const exchangeBootstrapCredential: ServerAuthShape["exchangeBootstrapCredential"] = (- credential,- requestMetadata,- ) =>- bootstrapCredentials.consume(credential).pipe(- Effect.mapError(toBootstrapExchangeAuthError),- Effect.flatMap((grant) =>- sessions- .issue({- method: "browser-session-cookie",- subject: grant.subject,- role: grant.role,- client: {- ...requestMetadata,- ...(grant.label ? { label: grant.label } : {}),- },- })- .pipe(- Effect.mapError(- (cause) =>- new AuthError({- message: "Failed to issue authenticated session.",- cause,- }),- ),- ),- ),- Effect.map(- (session) =>- ({- response: {- authenticated: true,- role: session.role,- sessionMethod: session.method,- expiresAt: DateTime.toUtc(session.expiresAt),- } satisfies AuthBootstrapResult,- sessionToken: session.token,- }) satisfies BootstrapExchangeResult,- ),- );-- const exchangeBootstrapCredentialForBearerSession: ServerAuthShape["exchangeBootstrapCredentialForBearerSession"] =- (credential, requestMetadata) =>- bootstrapCredentials.consume(credential).pipe(- Effect.mapError(toBootstrapExchangeAuthError),- Effect.flatMap((grant) =>- sessions- .issue({- method: "bearer-session-token",- subject: grant.subject,- role: grant.role,- client: {- ...requestMetadata,- ...(grant.label ? { label: grant.label } : {}),- },- })- .pipe(- Effect.mapError(- (cause) =>- new AuthError({- message: "Failed to issue authenticated session.",- cause,- }),- ),- ),- ),- Effect.map(- (session) =>- ({- authenticated: true,- role: session.role,- sessionMethod: "bearer-session-token",- expiresAt: DateTime.toUtc(session.expiresAt),- sessionToken: session.token,- }) satisfies AuthBearerBootstrapResult,- ),- );-- const issuePairingCredential: ServerAuthShape["issuePairingCredential"] = (input) =>- authControlPlane- .createPairingLink({- role: input?.role ?? "client",- subject: input?.role === "owner" ? "owner-bootstrap" : "one-time-token",- ...(input?.label ? { label: input.label } : {}),- })- .pipe(- Effect.mapError(- (cause) =>- new AuthError({- message: "Failed to issue pairing credential.",- cause,- }),- ),- Effect.map(- (issued) =>- ({- id: issued.id,- credential: issued.credential,- ...(issued.label ? { label: issued.label } : {}),- expiresAt: issued.expiresAt,- }) satisfies AuthPairingCredentialResult,- ),- );-- const listPairingLinks: ServerAuthShape["listPairingLinks"] = () =>- authControlPlane- .listPairingLinks({- role: "client",- excludeSubjects: ["owner-bootstrap"],- })- .pipe(- Effect.mapError(- (cause) =>- new AuthError({- message: "Failed to load pairing links.",- cause,- }),- ),- );-- const revokePairingLink: ServerAuthShape["revokePairingLink"] = (id) =>- authControlPlane.revokePairingLink(id).pipe(- Effect.mapError(- (cause) =>- new AuthError({- message: "Failed to revoke pairing link.",- cause,- }),- ),- );-- const listClientSessions: ServerAuthShape["listClientSessions"] = (currentSessionId) =>- authControlPlane.listSessions().pipe(- Effect.mapError(- (cause) =>- new AuthError({- message: "Failed to load paired clients.",- cause,- }),- ),- Effect.map((clientSessions) =>- clientSessions.map(- (clientSession): AuthClientSession => ({- ...clientSession,- current: clientSession.sessionId === currentSessionId,- }),- ),- ),- );-- const revokeClientSession: ServerAuthShape["revokeClientSession"] = (- currentSessionId,- targetSessionId,- ) =>- Effect.gen(function* () {- if (currentSessionId === targetSessionId) {- return yield* new AuthError({- message: "Use revoke other clients to keep the current owner session active.",- status: 403,- });- }- return yield* authControlPlane.revokeSession(targetSessionId).pipe(- Effect.mapError(- (cause) =>- new AuthError({- message: "Failed to revoke client session.",- cause,- }),- ),- );- });-- const revokeOtherClientSessions: ServerAuthShape["revokeOtherClientSessions"] = (- currentSessionId,- ) =>- authControlPlane.revokeOtherSessionsExcept(currentSessionId).pipe(- Effect.mapError(- (cause) =>- new AuthError({- message: "Failed to revoke other client sessions.",- cause,- }),- ),- );-- const issueStartupPairingUrl: ServerAuthShape["issueStartupPairingUrl"] = (baseUrl) =>- issuePairingCredential({ role: "owner" }).pipe(- Effect.map((issued) => {- const url = new URL(baseUrl);- url.pathname = "/pair";- url.searchParams.delete("token");- url.hash = new URLSearchParams([["token", issued.credential]]).toString();- return url.toString();- }),- );-- const issueWebSocketToken: ServerAuthShape["issueWebSocketToken"] = (session) =>- sessions.issueWebSocketToken(session.sessionId).pipe(- Effect.mapError(- (cause) =>- new AuthError({- message: "Failed to issue websocket token.",- cause,- }),- ),- Effect.map(- (issued) =>- ({- token: issued.token,- expiresAt: DateTime.toUtc(issued.expiresAt),- }) satisfies AuthWebSocketTokenResult,- ),- );-- const authenticateWebSocketUpgrade: ServerAuthShape["authenticateWebSocketUpgrade"] = (request) =>- Effect.gen(function* () {- const requestUrl = HttpServerRequest.toURL(request);- if (Option.isSome(requestUrl)) {- const websocketToken = requestUrl.value.searchParams.get(WEBSOCKET_TOKEN_QUERY_PARAM);- if (websocketToken && websocketToken.trim().length > 0) {- return yield* sessions.verifyWebSocketToken(websocketToken).pipe(- Effect.map((session) => ({- sessionId: session.sessionId,- subject: session.subject,- method: session.method,- role: session.role,- ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),- })),- Effect.mapError(- (cause) =>- new AuthError({- message: "Unauthorized request.",- status: 401,- cause,- }),- ),- );- }- }-- return yield* authenticateRequest(request);- });-- return {- getDescriptor: () => Effect.succeed(descriptor),- getSessionState,- exchangeBootstrapCredential,- exchangeBootstrapCredentialForBearerSession,- issuePairingCredential,- listPairingLinks,- revokePairingLink,- listClientSessions,- revokeClientSession,- revokeOtherClientSessions,- authenticateHttpRequest: authenticateRequest,- authenticateWebSocketUpgrade,- issueWebSocketToken,- issueStartupPairingUrl,- } satisfies ServerAuthShape;-});--export const ServerAuthLive = Layer.effect(ServerAuth, makeServerAuth).pipe(- Layer.provideMerge(AuthControlPlaneLive),- Layer.provideMerge(AuthCoreLive),- Layer.provideMerge(ServerAuthPolicyLive),-);diff --git a/apps/server/src/auth/Layers/ServerSecretStore.ts b/apps/server/src/auth/Layers/ServerSecretStore.tsdeleted file mode 100644index d80242280..000000000--- a/apps/server/src/auth/Layers/ServerSecretStore.ts+++ /dev/null@@ -1,152 +0,0 @@-import * as Crypto from "node:crypto";--import * as Effect from "effect/Effect";-import * as FileSystem from "effect/FileSystem";-import * as Layer from "effect/Layer";-import * as Path from "effect/Path";-import * as Predicate from "effect/Predicate";-import * as PlatformError from "effect/PlatformError";--import { ServerConfig } from "../../config.ts";-import {- SecretStoreError,- ServerSecretStore,- type ServerSecretStoreShape,-} from "../Services/ServerSecretStore.ts";--export const makeServerSecretStore = Effect.gen(function* () {- const fileSystem = yield* FileSystem.FileSystem;- const path = yield* Path.Path;- const serverConfig = yield* ServerConfig;-- yield* fileSystem.makeDirectory(serverConfig.secretsDir, { recursive: true });- yield* fileSystem.chmod(serverConfig.secretsDir, 0o700).pipe(- Effect.mapError(- (cause) =>- new SecretStoreError({- message: `Failed to secure secrets directory ${serverConfig.secretsDir}.`,- cause,- }),- ),- );-- const resolveSecretPath = (name: string) => path.join(serverConfig.secretsDir, `${name}.bin`);-- const isPlatformError = (u: unknown): u is PlatformError.PlatformError =>- Predicate.isTagged(u, "PlatformError");-- const get: ServerSecretStoreShape["get"] = (name) =>- fileSystem.readFile(resolveSecretPath(name)).pipe(- Effect.map((bytes) => Uint8Array.from(bytes)),- Effect.catch((cause) =>- cause.reason._tag === "NotFound"- ? Effect.succeed(null)- : Effect.fail(- new SecretStoreError({- message: `Failed to read secret ${name}.`,- cause,- }),- ),- ),- );-- const set: ServerSecretStoreShape["set"] = (name, value) => {- const secretPath = resolveSecretPath(name);- const tempPath = `${secretPath}.${Crypto.randomUUID()}.tmp`;- return Effect.gen(function* () {- yield* fileSystem.writeFile(tempPath, value);- yield* fileSystem.chmod(tempPath, 0o600);- yield* fileSystem.rename(tempPath, secretPath);- yield* fileSystem.chmod(secretPath, 0o600);- }).pipe(- Effect.catch((cause) =>- fileSystem.remove(tempPath).pipe(- Effect.ignore,- Effect.flatMap(() =>- Effect.fail(- new SecretStoreError({- message: `Failed to persist secret ${name}.`,- cause,- }),- ),- ),- ),- ),- );- };-- const create: ServerSecretStoreShape["set"] = (name, value) => {- const secretPath = resolveSecretPath(name);- return Effect.scoped(- Effect.gen(function* () {- const file = yield* fileSystem.open(secretPath, {- flag: "wx",- mode: 0o600,- });- yield* file.writeAll(value);- yield* file.sync;- yield* fileSystem.chmod(secretPath, 0o600);- }),- ).pipe(- Effect.mapError(- (cause) =>- new SecretStoreError({- message: `Failed to persist secret ${name}.`,- cause,- }),- ),- );- };-- const getOrCreateRandom: ServerSecretStoreShape["getOrCreateRandom"] = (name, bytes) =>- get(name).pipe(- Effect.flatMap((existing) => {- if (existing) {- return Effect.succeed(existing);- }-- const generated = Crypto.randomBytes(bytes);- return create(name, generated).pipe(- Effect.as(Uint8Array.from(generated)),- Effect.catchTag("SecretStoreError", (error) =>- isPlatformError(error.cause) && error.cause.reason._tag === "AlreadyExists"- ? get(name).pipe(- Effect.flatMap((created) =>- created !== null- ? Effect.succeed(created)- : Effect.fail(- new SecretStoreError({- message: `Failed to read secret ${name} after concurrent creation.`,- }),- ),- ),- )- : Effect.fail(error),- ),- );- }),- );-- const remove: ServerSecretStoreShape["remove"] = (name) =>- fileSystem.remove(resolveSecretPath(name)).pipe(- Effect.catch((cause) =>- cause.reason._tag === "NotFound"- ? Effect.void- : Effect.fail(- new SecretStoreError({- message: `Failed to remove secret ${name}.`,- cause,- }),- ),- ),- );-- return {- get,- set,- getOrCreateRandom,- remove,- } satisfies ServerSecretStoreShape;-});--export const ServerSecretStoreLive = Layer.effect(ServerSecretStore, makeServerSecretStore);diff --git a/apps/server/src/auth/Layers/BootstrapCredentialService.test.ts b/apps/server/src/auth/PairingGrantStore.test.tssimilarity index 69%rename from apps/server/src/auth/Layers/BootstrapCredentialService.test.tsrename to apps/server/src/auth/PairingGrantStore.test.tsindex 110dae843..0c33a753f 100644--- a/apps/server/src/auth/Layers/BootstrapCredentialService.test.ts+++ b/apps/server/src/auth/PairingGrantStore.test.ts@@ -5,11 +5,10 @@ import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import * as TestClock from "effect/testing/TestClock";-import type { ServerConfigShape } from "../../config.ts";-import { ServerConfig } from "../../config.ts";-import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";-import { BootstrapCredentialService } from "../Services/BootstrapCredentialService.ts";-import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";+import type { ServerConfigShape } from "../config.ts";+import { ServerConfig } from "../config.ts";+import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";+import * as PairingGrantStore from "./PairingGrantStore.ts";const makeServerConfigLayer = (overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,@@ -27,44 +26,50 @@ const makeServerConfigLayer = (Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-bootstrap-test-" })),);-const makeBootstrapCredentialLayer = (+const makePairingGrantStoreLayer = (overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,) =>- BootstrapCredentialServiceLive.pipe(+ PairingGrantStore.layer.pipe(Layer.provide(SqlitePersistenceMemory),Layer.provide(makeServerConfigLayer(overrides)),);-it.layer(NodeServices.layer)("BootstrapCredentialServiceLive", (it) => {+it.layer(NodeServices.layer)("PairingGrantStore.layer", (it) => {it.effect("issues pairing tokens in a short manual-entry format", () =>Effect.gen(function* () {- const bootstrapCredentials = yield* BootstrapCredentialService;+ const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;const issued = yield* bootstrapCredentials.issueOneTimeToken();expect(issued.credential).toMatch(/^[23456789ABCDEFGHJKLMNPQRSTUVWXYZ]{12}$/);- }).pipe(Effect.provide(makeBootstrapCredentialLayer())),+ }).pipe(Effect.provide(makePairingGrantStoreLayer())),);it.effect("issues one-time bootstrap tokens that can only be consumed once", () =>Effect.gen(function* () {- const bootstrapCredentials = yield* BootstrapCredentialService;+ const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;const issued = yield* bootstrapCredentials.issueOneTimeToken({ label: "Julius iPhone" });const first = yield* bootstrapCredentials.consume(issued.credential);const second = yield* Effect.flip(bootstrapCredentials.consume(issued.credential));expect(first.method).toBe("one-time-token");- expect(first.role).toBe("client");+ expect(first.scopes).toEqual([+ "orchestration:read",+ "orchestration:operate",+ "terminal:operate",+ "review:write",+ "relay:read",+ ]);expect(first.subject).toBe("one-time-token");expect(first.label).toBe("Julius iPhone");expect(issued.label).toBe("Julius iPhone");- expect(second._tag).toBe("BootstrapCredentialError");+ expect(second._tag).toBe("BootstrapCredentialInvalidError");expect(second.message).toContain("Unknown bootstrap credential");- }).pipe(Effect.provide(makeBootstrapCredentialLayer())),+ }).pipe(Effect.provide(makePairingGrantStoreLayer())),);it.effect("atomically consumes a one-time token when multiple requests race", () =>Effect.gen(function* () {- const bootstrapCredentials = yield* BootstrapCredentialService;+ const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;const token = yield* bootstrapCredentials.issueOneTimeToken();const results = yield* Effect.all(Array.from({ length: 8 }, () =>@@ -81,26 +86,34 @@ it.layer(NodeServices.layer)("BootstrapCredentialServiceLive", (it) => {expect(successes).toHaveLength(1);expect(failures).toHaveLength(7);for (const failure of failures) {- expect(failure.failure._tag).toBe("BootstrapCredentialError");+ expect(failure.failure._tag).toBe("BootstrapCredentialInvalidError");expect(failure.failure.message).toContain("Unknown bootstrap credential");}- }).pipe(Effect.provide(makeBootstrapCredentialLayer())),+ }).pipe(Effect.provide(makePairingGrantStoreLayer())),);it.effect("seeds the desktop bootstrap credential as a one-time grant", () =>Effect.gen(function* () {- const bootstrapCredentials = yield* BootstrapCredentialService;+ const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;const first = yield* bootstrapCredentials.consume("desktop-bootstrap-token");const second = yield* Effect.flip(bootstrapCredentials.consume("desktop-bootstrap-token"));expect(first.method).toBe("desktop-bootstrap");- expect(first.role).toBe("owner");+ expect(first.scopes).toEqual([+ "orchestration:read",+ "orchestration:operate",+ "terminal:operate",+ "review:write",+ "relay:read",+ "access:read",+ "access:write",+ "relay:write",+ ]);expect(first.subject).toBe("desktop-bootstrap");- expect(second._tag).toBe("BootstrapCredentialError");- expect(second.status).toBe(401);+ expect(second._tag).toBe("BootstrapCredentialInvalidError");}).pipe(Effect.provide(- makeBootstrapCredentialLayer({+ makePairingGrantStoreLayer({desktopBootstrapToken: "desktop-bootstrap-token",}),),@@ -109,18 +122,17 @@ it.layer(NodeServices.layer)("BootstrapCredentialServiceLive", (it) => {it.effect("reports seeded desktop bootstrap credentials as expired after their ttl", () =>Effect.gen(function* () {- const bootstrapCredentials = yield* BootstrapCredentialService;+ const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;yield* TestClock.adjust(Duration.minutes(6));const expired = yield* Effect.flip(bootstrapCredentials.consume("desktop-bootstrap-token"));- expect(expired._tag).toBe("BootstrapCredentialError");- expect(expired.status).toBe(401);+ expect(expired._tag).toBe("BootstrapCredentialInvalidError");expect(expired.message).toContain("Bootstrap credential expired");}).pipe(Effect.provide(Layer.merge(- makeBootstrapCredentialLayer({+ makePairingGrantStoreLayer({desktopBootstrapToken: "desktop-bootstrap-token",}),TestClock.layer(),@@ -131,9 +143,11 @@ it.layer(NodeServices.layer)("BootstrapCredentialServiceLive", (it) => {it.effect("lists and revokes active pairing links", () =>Effect.gen(function* () {- const bootstrapCredentials = yield* BootstrapCredentialService;+ const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;const first = yield* bootstrapCredentials.issueOneTimeToken();- const second = yield* bootstrapCredentials.issueOneTimeToken({ role: "owner" });+ const second = yield* bootstrapCredentials.issueOneTimeToken({+ scopes: ["orchestration:read", "access:write"],+ });const activeBeforeRevoke = yield* bootstrapCredentials.listActive();expect(activeBeforeRevoke.map((entry) => entry.id)).toContain(first.id);@@ -147,7 +161,7 @@ it.layer(NodeServices.layer)("BootstrapCredentialServiceLive", (it) => {expect(activeAfterRevoke.map((entry) => entry.id)).not.toContain(first.id);expect(activeAfterRevoke.map((entry) => entry.id)).toContain(second.id);expect(revokedConsume.message).toContain("no longer available");- expect(revokedConsume.status).toBe(401);- }).pipe(Effect.provide(makeBootstrapCredentialLayer())),+ expect(revokedConsume._tag).toBe("BootstrapCredentialInvalidError");+ }).pipe(Effect.provide(makePairingGrantStoreLayer())),);});diff --git a/apps/server/src/auth/Layers/BootstrapCredentialService.ts b/apps/server/src/auth/PairingGrantStore.tssimilarity index 59%rename from apps/server/src/auth/Layers/BootstrapCredentialService.tsrename to apps/server/src/auth/PairingGrantStore.tsindex 394a20dc6..4fcc133eb 100644--- a/apps/server/src/auth/Layers/BootstrapCredentialService.ts+++ b/apps/server/src/auth/PairingGrantStore.ts@@ -1,5 +1,13 @@-import type { AuthPairingLink } from "@t3tools/contracts";+import {+ AuthAdministrativeScopes,+ AuthStandardClientScopes,+ type AuthEnvironmentScope,+ type AuthPairingLink,+ type ServerAuthBootstrapMethod,+} from "@t3tools/contracts";+import * as Context from "effect/Context";import * as Crypto from "effect/Crypto";+import * as Data from "effect/Data";import * as DateTime from "effect/DateTime";import * as Duration from "effect/Duration";import * as Effect from "effect/Effect";@@ -9,17 +17,71 @@ import * as Ref from "effect/Ref";import * as Stream from "effect/Stream";import * as Option from "effect/Option";-import { ServerConfig } from "../../config.ts";-import { AuthPairingLinkRepositoryLive } from "../../persistence/Layers/AuthPairingLinks.ts";-import { AuthPairingLinkRepository } from "../../persistence/Services/AuthPairingLinks.ts";-import {- BootstrapCredentialError,- BootstrapCredentialService,- type BootstrapCredentialChange,- type BootstrapCredentialServiceShape,- type BootstrapGrant,- type IssuedBootstrapCredential,-} from "../Services/BootstrapCredentialService.ts";+import { ServerConfig } from "../config.ts";+import { AuthPairingLinkRepositoryLive } from "../persistence/Layers/AuthPairingLinks.ts";+import { AuthPairingLinkRepository } from "../persistence/Services/AuthPairingLinks.ts";++export interface BootstrapGrant {+ readonly method: ServerAuthBootstrapMethod;+ readonly scopes: ReadonlyArray<AuthEnvironmentScope>;+ readonly subject: string;+ readonly label?: string;+ readonly expiresAt: DateTime.DateTime;+}++export class BootstrapCredentialInvalidError extends Data.TaggedError(+ "BootstrapCredentialInvalidError",+)<{+ readonly message: string;+}> {}++export class BootstrapCredentialInternalError extends Data.TaggedError(+ "BootstrapCredentialInternalError",+)<{+ readonly message: string;+ readonly cause?: unknown;+}> {}++export type BootstrapCredentialError =+ | BootstrapCredentialInvalidError+ | BootstrapCredentialInternalError;++export interface IssuedBootstrapCredential {+ readonly id: string;+ readonly credential: string;+ readonly label?: string;+ readonly expiresAt: DateTime.Utc;+}++export type BootstrapCredentialChange =+ | {+ readonly type: "pairingLinkUpserted";+ readonly pairingLink: AuthPairingLink;+ }+ | {+ readonly type: "pairingLinkRemoved";+ readonly id: string;+ };++export interface PairingGrantStoreShape {+ readonly issueOneTimeToken: (input?: {+ readonly ttl?: Duration.Duration;+ readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;+ readonly subject?: string;+ readonly label?: string;+ }) => Effect.Effect<IssuedBootstrapCredential, BootstrapCredentialInternalError>;+ readonly listActive: () => Effect.Effect<+ ReadonlyArray<AuthPairingLink>,+ BootstrapCredentialInternalError+ >;+ readonly streamChanges: Stream.Stream<BootstrapCredentialChange>;+ readonly revoke: (id: string) => Effect.Effect<boolean, BootstrapCredentialInternalError>;+ readonly consume: (credential: string) => Effect.Effect<BootstrapGrant, BootstrapCredentialError>;+}++export class PairingGrantStore extends Context.Service<PairingGrantStore, PairingGrantStoreShape>()(+ "t3/auth/PairingGrantStore",+) {}interface StoredBootstrapGrant extends BootstrapGrant {readonly remainingUses: number | "unbounded";@@ -39,32 +101,42 @@ type ConsumeResult =const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);const PAIRING_TOKEN_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";const PAIRING_TOKEN_LENGTH = 12;+const PAIRING_TOKEN_REJECTION_LIMIT =+ Math.floor(256 / PAIRING_TOKEN_ALPHABET.length) * PAIRING_TOKEN_ALPHABET.length;-const generatePairingToken = (): string => {- const randomBytes = crypto.getRandomValues(new Uint8Array(PAIRING_TOKEN_LENGTH));+const invalidBootstrapCredentialError = (message: string) =>+ new BootstrapCredentialInvalidError({+ message,+ });- return Array.from(randomBytes, (value) => PAIRING_TOKEN_ALPHABET[value & 31]).join("");-};+const internalBootstrapCredentialError = (message: string, cause: unknown) =>+ new BootstrapCredentialInternalError({+ message,+ cause,+ });-export const makeBootstrapCredentialService = Effect.gen(function* () {+export const make = Effect.fn("makePairingGrantStore")(function* () {const crypto = yield* Crypto.Crypto;const config = yield* ServerConfig;const pairingLinks = yield* AuthPairingLinkRepository;const seededGrantsRef = yield* Ref.make(new Map<string, StoredBootstrapGrant>());const changesPubSub = yield* PubSub.unbounded<BootstrapCredentialChange>();-- const invalidBootstrapCredentialError = (message: string) =>- new BootstrapCredentialError({- message,- status: 401,- });-- const internalBootstrapCredentialError = (message: string, cause: unknown) =>- new BootstrapCredentialError({- message,- status: 500,- cause,- });+ const generatePairingToken = Effect.gen(function* () {+ let credential = "";+ while (credential.length < PAIRING_TOKEN_LENGTH) {+ const bytes = yield* crypto.randomBytes(PAIRING_TOKEN_LENGTH);+ for (const byte of bytes) {+ if (byte >= PAIRING_TOKEN_REJECTION_LIMIT) {+ continue;+ }+ credential += PAIRING_TOKEN_ALPHABET[byte % PAIRING_TOKEN_ALPHABET.length]!;+ if (credential.length === PAIRING_TOKEN_LENGTH) {+ return credential;+ }+ }+ }+ return credential;+ });const seedGrant = (credential: string, grant: StoredBootstrapGrant) =>Ref.update(seededGrantsRef, (current) => {@@ -89,7 +161,7 @@ export const makeBootstrapCredentialService = Effect.gen(function* () {const now = yield* DateTime.now;yield* seedGrant(config.desktopBootstrapToken, {method: "desktop-bootstrap",- role: "owner",+ scopes: AuthAdministrativeScopes,subject: "desktop-bootstrap",expiresAt: DateTime.add(now, {milliseconds: Duration.toMillis(DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES),@@ -101,8 +173,10 @@ export const makeBootstrapCredentialService = Effect.gen(function* () {const toBootstrapCredentialError = (message: string) => (cause: unknown) =>internalBootstrapCredentialError(message, cause);- const listActive: BootstrapCredentialServiceShape["listActive"] = () =>- Effect.gen(function* () {+ const listActive: PairingGrantStoreShape["listActive"] = Effect.fn(+ "PairingGrantStore.listActive",+ )(+ function* () {const now = yield* DateTime.now;const rows = yield* pairingLinks.listActive({ now });@@ -111,7 +185,7 @@ export const makeBootstrapCredentialService = Effect.gen(function* () {? ({id: row.id,credential: row.credential,- role: row.role,+ scopes: row.scopes,subject: row.subject,label: row.label,createdAt: row.createdAt,@@ -120,16 +194,18 @@ export const makeBootstrapCredentialService = Effect.gen(function* () {: ({id: row.id,credential: row.credential,- role: row.role,+ scopes: row.scopes,subject: row.subject,createdAt: row.createdAt,expiresAt: row.expiresAt,} satisfies AuthPairingLink),);- }).pipe(Effect.mapError(toBootstrapCredentialError("Failed to load active pairing links.")));+ },+ Effect.mapError(toBootstrapCredentialError("Failed to load active pairing links.")),+ );- const revoke: BootstrapCredentialServiceShape["revoke"] = (id) =>- Effect.gen(function* () {+ const revoke: PairingGrantStoreShape["revoke"] = Effect.fn("PairingGrantStore.revoke")(+ function* (id) {const revokedAt = yield* DateTime.now;const revoked = yield* pairingLinks.revoke({id,@@ -139,12 +215,16 @@ export const makeBootstrapCredentialService = Effect.gen(function* () {yield* emitRemoved(id);}return revoked;- }).pipe(Effect.mapError(toBootstrapCredentialError("Failed to revoke pairing link.")));+ },+ Effect.mapError(toBootstrapCredentialError("Failed to revoke pairing link.")),+ );- const issueOneTimeToken: BootstrapCredentialServiceShape["issueOneTimeToken"] = (input) =>- Effect.gen(function* () {+ const issueOneTimeToken: PairingGrantStoreShape["issueOneTimeToken"] = Effect.fn(+ "PairingGrantStore.issueOneTimeToken",+ )(+ function* (input) {const id = yield* crypto.randomUUIDv4;- const credential = generatePairingToken();+ const credential = yield* generatePairingToken;const ttl = input?.ttl ?? DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES;const now = yield* DateTime.now;const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) });@@ -158,7 +238,7 @@ export const makeBootstrapCredentialService = Effect.gen(function* () {id,credential,method: "one-time-token",- role: input?.role ?? "client",+ scopes: input?.scopes ?? AuthStandardClientScopes,subject: input?.subject ?? "one-time-token",label: input?.label ?? null,createdAt: now,@@ -167,17 +247,19 @@ export const makeBootstrapCredentialService = Effect.gen(function* () {yield* emitUpsert({id,credential,- role: input?.role ?? "client",+ scopes: input?.scopes ?? AuthStandardClientScopes,subject: input?.subject ?? "one-time-token",...(input?.label ? { label: input.label } : {}),createdAt: now,expiresAt,});return issued;- }).pipe(Effect.mapError(toBootstrapCredentialError("Failed to issue pairing credential.")));+ },+ Effect.mapError(toBootstrapCredentialError("Failed to issue pairing credential.")),+ );- const consume: BootstrapCredentialServiceShape["consume"] = (credential) =>- Effect.gen(function* () {+ const consume: PairingGrantStoreShape["consume"] = Effect.fn("PairingGrantStore.consume")(+ function* (credential) {const now = yield* DateTime.now;const seededResult: ConsumeResult = yield* Ref.modify(seededGrantsRef,@@ -224,7 +306,7 @@ export const makeBootstrapCredentialService = Effect.gen(function* () {_tag: "success",grant: {method: grant.method,- role: grant.role,+ scopes: grant.scopes,subject: grant.subject,...(grant.label ? { label: grant.label } : {}),expiresAt: grant.expiresAt,@@ -252,7 +334,7 @@ export const makeBootstrapCredentialService = Effect.gen(function* () {yield* emitRemoved(consumed.value.id);return {method: consumed.value.method,- role: consumed.value.role,+ scopes: consumed.value.scopes,subject: consumed.value.subject,...(consumed.value.label ? { label: consumed.value.label } : {}),expiresAt: consumed.value.expiresAt,@@ -279,13 +361,14 @@ export const makeBootstrapCredentialService = Effect.gen(function* () {}return yield* invalidBootstrapCredentialError("Bootstrap credential is no longer available.");- }).pipe(- Effect.mapError((cause) =>- cause instanceof BootstrapCredentialError- ? cause- : internalBootstrapCredentialError("Failed to consume bootstrap credential.", cause),- ),- );+ },+ Effect.mapError((cause) =>+ cause._tag === "BootstrapCredentialInvalidError" ||+ cause._tag === "BootstrapCredentialInternalError"+ ? cause+ : internalBootstrapCredentialError("Failed to consume bootstrap credential.", cause),+ ),+ );return {issueOneTimeToken,@@ -295,10 +378,9 @@ export const makeBootstrapCredentialService = Effect.gen(function* () {},revoke,consume,- } satisfies BootstrapCredentialServiceShape;+ } satisfies PairingGrantStoreShape;});-export const BootstrapCredentialServiceLive = Layer.effect(- BootstrapCredentialService,- makeBootstrapCredentialService,-).pipe(Layer.provideMerge(AuthPairingLinkRepositoryLive));+export const layer = Layer.effect(PairingGrantStore, make()).pipe(+ Layer.provideMerge(AuthPairingLinkRepositoryLive),+);diff --git a/apps/server/src/auth/Layers/ServerSecretStore.test.ts b/apps/server/src/auth/ServerSecretStore.test.tssimilarity index 89%rename from apps/server/src/auth/Layers/ServerSecretStore.test.tsrename to apps/server/src/auth/ServerSecretStore.test.tsindex 30b5a9d35..93339f4d4 100644--- a/apps/server/src/auth/Layers/ServerSecretStore.test.ts+++ b/apps/server/src/auth/ServerSecretStore.test.ts@@ -8,15 +8,14 @@ import * as Layer from "effect/Layer";import * as Ref from "effect/Ref";import * as PlatformError from "effect/PlatformError";-import { ServerConfig } from "../../config.ts";-import { SecretStoreError, ServerSecretStore } from "../Services/ServerSecretStore.ts";-import { ServerSecretStoreLive } from "./ServerSecretStore.ts";+import { ServerConfig } from "../config.ts";+import * as ServerSecretStore from "./ServerSecretStore.ts";const makeServerConfigLayer = () =>ServerConfig.layerTest(process.cwd(), { prefix: "t3-secret-store-test-" });const makeServerSecretStoreLayer = () =>- Layer.provide(ServerSecretStoreLive, makeServerConfigLayer());+ Layer.provide(ServerSecretStore.layer, makeServerConfigLayer());const PermissionDeniedFileSystemLayer = Layer.effect(FileSystem.FileSystem,@@ -40,7 +39,7 @@ const PermissionDeniedFileSystemLayer = Layer.effect().pipe(Layer.provide(NodeServices.layer));const makePermissionDeniedSecretStoreLayer = () =>- ServerSecretStoreLive.pipe(+ ServerSecretStore.layer.pipe(Layer.provide(makeServerConfigLayer()),Layer.provideMerge(PermissionDeniedFileSystemLayer),);@@ -67,7 +66,7 @@ const RenameFailureFileSystemLayer = Layer.effect().pipe(Layer.provide(NodeServices.layer));const makeRenameFailureSecretStoreLayer = () =>- ServerSecretStoreLive.pipe(+ ServerSecretStore.layer.pipe(Layer.provide(makeServerConfigLayer()),Layer.provideMerge(RenameFailureFileSystemLayer),);@@ -94,7 +93,7 @@ const RemoveFailureFileSystemLayer = Layer.effect().pipe(Layer.provide(NodeServices.layer));const makeRemoveFailureSecretStoreLayer = () =>- ServerSecretStoreLive.pipe(+ ServerSecretStore.layer.pipe(Layer.provide(makeServerConfigLayer()),Layer.provideMerge(RemoveFailureFileSystemLayer),);@@ -140,15 +139,15 @@ const ConcurrentReadMissFileSystemLayer = Layer.effect().pipe(Layer.provide(NodeServices.layer));const makeConcurrentCreateSecretStoreLayer = () =>- ServerSecretStoreLive.pipe(+ ServerSecretStore.layer.pipe(Layer.provide(makeServerConfigLayer()),Layer.provideMerge(ConcurrentReadMissFileSystemLayer),);-it.layer(NodeServices.layer)("ServerSecretStoreLive", (it) => {+it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {it.effect("returns null when a secret file does not exist", () =>Effect.gen(function* () {- const secretStore = yield* ServerSecretStore;+ const secretStore = yield* ServerSecretStore.ServerSecretStore;const secret = yield* secretStore.get("missing-secret");@@ -158,7 +157,7 @@ it.layer(NodeServices.layer)("ServerSecretStoreLive", (it) => {it.effect("reuses an existing secret instead of regenerating it", () =>Effect.gen(function* () {- const secretStore = yield* ServerSecretStore;+ const secretStore = yield* ServerSecretStore.ServerSecretStore;const first = yield* secretStore.getOrCreateRandom("session-signing-key", 32);const second = yield* secretStore.getOrCreateRandom("session-signing-key", 32);@@ -169,7 +168,7 @@ it.layer(NodeServices.layer)("ServerSecretStoreLive", (it) => {it.effect("returns the persisted secret when concurrent creators race", () =>Effect.gen(function* () {- const secretStore = yield* ServerSecretStore;+ const secretStore = yield* ServerSecretStore.ServerSecretStore;const [first, second] = yield* Effect.all([@@ -207,9 +206,9 @@ it.layer(NodeServices.layer)("ServerSecretStoreLive", (it) => {}),).pipe(Layer.provide(NodeServices.layer));- const secretStore = yield* Effect.service(ServerSecretStore).pipe(+ const secretStore = yield* Effect.service(ServerSecretStore.ServerSecretStore).pipe(Effect.provide(- ServerSecretStoreLive.pipe(+ ServerSecretStore.layer.pipe(Layer.provide(makeServerConfigLayer()),Layer.provideMerge(recordingFileSystemLayer),),@@ -227,11 +226,11 @@ it.layer(NodeServices.layer)("ServerSecretStoreLive", (it) => {it.effect("propagates read failures other than missing-file errors", () =>Effect.gen(function* () {- const secretStore = yield* ServerSecretStore;+ const secretStore = yield* ServerSecretStore.ServerSecretStore;const error = yield* Effect.flip(secretStore.getOrCreateRandom("session-signing-key", 32));- expect(error).toBeInstanceOf(SecretStoreError);+ expect(error).toBeInstanceOf(ServerSecretStore.SecretStoreError);expect(error.message).toContain("Failed to read secret session-signing-key.");expect(error.cause).toBeInstanceOf(PlatformError.PlatformError);expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("PermissionDenied");@@ -240,13 +239,13 @@ it.layer(NodeServices.layer)("ServerSecretStoreLive", (it) => {it.effect("propagates write failures instead of treating them as success", () =>Effect.gen(function* () {- const secretStore = yield* ServerSecretStore;+ const secretStore = yield* ServerSecretStore.ServerSecretStore;const error = yield* Effect.flip(secretStore.set("session-signing-key", Uint8Array.from([1, 2, 3])),);- expect(error).toBeInstanceOf(SecretStoreError);+ expect(error).toBeInstanceOf(ServerSecretStore.SecretStoreError);expect(error.message).toContain("Failed to persist secret session-signing-key.");expect(error.cause).toBeInstanceOf(PlatformError.PlatformError);expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("PermissionDenied");@@ -255,11 +254,11 @@ it.layer(NodeServices.layer)("ServerSecretStoreLive", (it) => {it.effect("propagates remove failures other than missing-file errors", () =>Effect.gen(function* () {- const secretStore = yield* ServerSecretStore;+ const secretStore = yield* ServerSecretStore.ServerSecretStore;const error = yield* Effect.flip(secretStore.remove("session-signing-key"));- expect(error).toBeInstanceOf(SecretStoreError);+ expect(error).toBeInstanceOf(ServerSecretStore.SecretStoreError);expect(error.message).toContain("Failed to remove secret session-signing-key.");expect(error.cause).toBeInstanceOf(PlatformError.PlatformError);expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("PermissionDenied");diff --git a/apps/server/src/auth/ServerSecretStore.ts b/apps/server/src/auth/ServerSecretStore.tsnew file mode 100644index 000000000..93dcc95aa--- /dev/null+++ b/apps/server/src/auth/ServerSecretStore.ts@@ -0,0 +1,193 @@+import * as Context from "effect/Context";+import * as Crypto from "effect/Crypto";+import * as Data from "effect/Data";+import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";+import * as Layer from "effect/Layer";+import * as Path from "effect/Path";+import * as Predicate from "effect/Predicate";+import * as PlatformError from "effect/PlatformError";++import { ServerConfig } from "../config.ts";++export class SecretStoreError extends Data.TaggedError("SecretStoreError")<{+ readonly message: string;+ readonly cause?: unknown;+}> {}++export interface ServerSecretStoreShape {+ readonly get: (name: string) => Effect.Effect<Uint8Array | null, SecretStoreError>;+ readonly set: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;+ readonly getOrCreateRandom: (+ name: string,+ bytes: number,+ ) => Effect.Effect<Uint8Array, SecretStoreError>;+ readonly remove: (name: string) => Effect.Effect<void, SecretStoreError>;+}++export class ServerSecretStore extends Context.Service<ServerSecretStore, ServerSecretStoreShape>()(+ "t3/auth/ServerSecretStore",+) {}++export const make = Effect.fn("makeServerSecretStore")(function* () {+ const crypto = yield* Crypto.Crypto;+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const serverConfig = yield* ServerConfig;++ yield* fileSystem.makeDirectory(serverConfig.secretsDir, { recursive: true });+ yield* fileSystem.chmod(serverConfig.secretsDir, 0o700).pipe(+ Effect.mapError(+ (cause) =>+ new SecretStoreError({+ message: `Failed to secure secrets directory ${serverConfig.secretsDir}.`,+ cause,+ }),+ ),+ );++ const resolveSecretPath = (name: string) => path.join(serverConfig.secretsDir, `${name}.bin`);++ const isPlatformError = (u: unknown): u is PlatformError.PlatformError =>+ Predicate.isTagged(u, "PlatformError");++ const get: ServerSecretStoreShape["get"] = (name) =>+ fileSystem.readFile(resolveSecretPath(name)).pipe(+ Effect.map((bytes) => Uint8Array.from(bytes)),+ Effect.catch((cause) =>+ cause.reason._tag === "NotFound"+ ? Effect.succeed(null)+ : Effect.fail(+ new SecretStoreError({+ message: `Failed to read secret ${name}.`,+ cause,+ }),+ ),+ ),+ Effect.withSpan("ServerSecretStore.get"),+ );++ const set: ServerSecretStoreShape["set"] = (name, value) => {+ const secretPath = resolveSecretPath(name);+ return crypto.randomUUIDv4.pipe(+ Effect.mapError(+ (cause) =>+ new SecretStoreError({+ message: `Failed to create temporary path for secret ${name}.`,+ cause,+ }),+ ),+ Effect.flatMap((uuid) => {+ const tempPath = `${secretPath}.${uuid}.tmp`;+ return Effect.gen(function* () {+ yield* fileSystem.writeFile(tempPath, value);+ yield* fileSystem.chmod(tempPath, 0o600);+ yield* fileSystem.rename(tempPath, secretPath);+ yield* fileSystem.chmod(secretPath, 0o600);+ }).pipe(+ Effect.catch((cause) =>+ fileSystem.remove(tempPath).pipe(+ Effect.ignore,+ Effect.flatMap(() =>+ Effect.fail(+ new SecretStoreError({+ message: `Failed to persist secret ${name}.`,+ cause,+ }),+ ),+ ),+ ),+ ),+ );+ }),+ Effect.withSpan("ServerSecretStore.set"),+ );+ };++ const create: ServerSecretStoreShape["set"] = (name, value) => {+ const secretPath = resolveSecretPath(name);+ return Effect.scoped(+ Effect.gen(function* () {+ const file = yield* fileSystem.open(secretPath, {+ flag: "wx",+ mode: 0o600,+ });+ yield* file.writeAll(value);+ yield* file.sync;+ yield* fileSystem.chmod(secretPath, 0o600);+ }),+ ).pipe(+ Effect.mapError(+ (cause) =>+ new SecretStoreError({+ message: `Failed to persist secret ${name}.`,+ cause,+ }),+ ),+ );+ };++ const getOrCreateRandom: ServerSecretStoreShape["getOrCreateRandom"] = (name, bytes) =>+ get(name).pipe(+ Effect.flatMap((existing) => {+ if (existing) {+ return Effect.succeed(existing);+ }++ return crypto.randomBytes(bytes).pipe(+ Effect.mapError(+ (cause) =>+ new SecretStoreError({+ message: `Failed to generate random bytes for secret ${name}.`,+ cause,+ }),+ ),+ Effect.flatMap((generated) =>+ create(name, generated).pipe(+ Effect.as(Uint8Array.from(generated)),+ Effect.catchTag("SecretStoreError", (error) =>+ isPlatformError(error.cause) && error.cause.reason._tag === "AlreadyExists"+ ? get(name).pipe(+ Effect.flatMap((created) =>+ created !== null+ ? Effect.succeed(created)+ : Effect.fail(+ new SecretStoreError({+ message: `Failed to read secret ${name} after concurrent creation.`,+ }),+ ),+ ),+ )+ : Effect.fail(error),+ ),+ ),+ ),+ );+ }),+ Effect.withSpan("ServerSecretStore.getOrCreateRandom"),+ );++ const remove: ServerSecretStoreShape["remove"] = (name) =>+ fileSystem.remove(resolveSecretPath(name)).pipe(+ Effect.catch((cause) =>+ cause.reason._tag === "NotFound"+ ? Effect.void+ : Effect.fail(+ new SecretStoreError({+ message: `Failed to remove secret ${name}.`,+ cause,+ }),+ ),+ ),+ Effect.withSpan("ServerSecretStore.remove"),+ );++ return {+ get,+ set,+ getOrCreateRandom,+ remove,+ } satisfies ServerSecretStoreShape;+});++export const layer = Layer.effect(ServerSecretStore, make());diff --git a/apps/server/src/auth/Services/AuthControlPlane.ts b/apps/server/src/auth/Services/AuthControlPlane.tsdeleted file mode 100644index f71c6e32e..000000000--- a/apps/server/src/auth/Services/AuthControlPlane.ts+++ /dev/null@@ -1,73 +0,0 @@-import type {- AuthClientMetadata,- AuthClientSession,- AuthPairingLink,- AuthSessionId,-} from "@t3tools/contracts";-import * as Data from "effect/Data";-import * as DateTime from "effect/DateTime";-import * as Duration from "effect/Duration";-import * as Effect from "effect/Effect";-import * as Context from "effect/Context";-import type { SessionRole } from "./SessionCredentialService.ts";--export const DEFAULT_SESSION_SUBJECT = "cli-issued-session";--export interface IssuedPairingLink {- readonly id: string;- readonly credential: string;- readonly role: SessionRole;- readonly subject: string;- readonly label?: string;- readonly createdAt: DateTime.Utc;- readonly expiresAt: DateTime.Utc;-}--export interface IssuedBearerSession {- readonly sessionId: AuthSessionId;- readonly token: string;- readonly method: "bearer-session-token";- readonly role: SessionRole;- readonly subject: string;- readonly client: AuthClientMetadata;- readonly expiresAt: DateTime.Utc;-}--export class AuthControlPlaneError extends Data.TaggedError("AuthControlPlaneError")<{- readonly message: string;- readonly cause?: unknown;-}> {}--export interface AuthControlPlaneShape {- readonly createPairingLink: (input?: {- readonly ttl?: Duration.Duration;- readonly label?: string;- readonly role?: SessionRole;- readonly subject?: string;- }) => Effect.Effect<IssuedPairingLink, AuthControlPlaneError>;- readonly listPairingLinks: (input?: {- readonly role?: SessionRole;- readonly excludeSubjects?: ReadonlyArray<string>;- }) => Effect.Effect<ReadonlyArray<AuthPairingLink>, AuthControlPlaneError>;- readonly revokePairingLink: (id: string) => Effect.Effect<boolean, AuthControlPlaneError>;- readonly issueSession: (input?: {- readonly ttl?: Duration.Duration;- readonly subject?: string;- readonly role?: SessionRole;- readonly label?: string;- }) => Effect.Effect<IssuedBearerSession, AuthControlPlaneError>;- readonly listSessions: () => Effect.Effect<- ReadonlyArray<AuthClientSession>,- AuthControlPlaneError- >;- readonly revokeSession: (- sessionId: AuthSessionId,- ) => Effect.Effect<boolean, AuthControlPlaneError>;- readonly revokeOtherSessionsExcept: (- sessionId: AuthSessionId,- ) => Effect.Effect<number, AuthControlPlaneError>;-}--export class AuthControlPlane extends Context.Service<AuthControlPlane, AuthControlPlaneShape>()(- "t3/auth/Services/AuthControlPlane",-) {}diff --git a/apps/server/src/auth/Services/BootstrapCredentialService.ts b/apps/server/src/auth/Services/BootstrapCredentialService.tsdeleted file mode 100644index 70dd1d5ae..000000000--- a/apps/server/src/auth/Services/BootstrapCredentialService.ts+++ /dev/null@@ -1,61 +0,0 @@-import type { AuthPairingLink, ServerAuthBootstrapMethod } from "@t3tools/contracts";-import * as Data from "effect/Data";-import * as DateTime from "effect/DateTime";-import * as Duration from "effect/Duration";-import * as Context from "effect/Context";-import type * as Effect from "effect/Effect";-import type * as Stream from "effect/Stream";--export type BootstrapCredentialRole = "owner" | "client";--export interface BootstrapGrant {- readonly method: ServerAuthBootstrapMethod;- readonly role: BootstrapCredentialRole;- readonly subject: string;- readonly label?: string;- readonly expiresAt: DateTime.DateTime;-}--export class BootstrapCredentialError extends Data.TaggedError("BootstrapCredentialError")<{- readonly message: string;- readonly status?: 401 | 500;- readonly cause?: unknown;-}> {}--export interface IssuedBootstrapCredential {- readonly id: string;- readonly credential: string;- readonly label?: string;- readonly expiresAt: DateTime.Utc;-}--export type BootstrapCredentialChange =- | {- readonly type: "pairingLinkUpserted";- readonly pairingLink: AuthPairingLink;- }- | {- readonly type: "pairingLinkRemoved";- readonly id: string;- };--export interface BootstrapCredentialServiceShape {- readonly issueOneTimeToken: (input?: {- readonly ttl?: Duration.Duration;- readonly role?: BootstrapCredentialRole;- readonly subject?: string;- readonly label?: string;- }) => Effect.Effect<IssuedBootstrapCredential, BootstrapCredentialError>;- readonly listActive: () => Effect.Effect<- ReadonlyArray<AuthPairingLink>,- BootstrapCredentialError- >;- readonly streamChanges: Stream.Stream<BootstrapCredentialChange>;- readonly revoke: (id: string) => Effect.Effect<boolean, BootstrapCredentialError>;- readonly consume: (credential: string) => Effect.Effect<BootstrapGrant, BootstrapCredentialError>;-}--export class BootstrapCredentialService extends Context.Service<- BootstrapCredentialService,- BootstrapCredentialServiceShape->()("t3/auth/Services/BootstrapCredentialService") {}diff --git a/apps/server/src/auth/Services/ServerAuth.ts b/apps/server/src/auth/Services/ServerAuth.tsdeleted file mode 100644index 3ea93b77f..000000000--- a/apps/server/src/auth/Services/ServerAuth.ts+++ /dev/null@@ -1,86 +0,0 @@-import type {- AuthBearerBootstrapResult,- AuthBootstrapResult,- AuthClientMetadata,- AuthClientSession,- AuthCreatePairingCredentialInput,- AuthPairingLink,- AuthPairingCredentialResult,- AuthSessionId,- AuthSessionState,- ServerAuthDescriptor,- ServerAuthSessionMethod,- AuthWebSocketTokenResult,-} from "@t3tools/contracts";-import * as Data from "effect/Data";-import * as DateTime from "effect/DateTime";-import * as Context from "effect/Context";-import type * as Effect from "effect/Effect";-import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";-import type { SessionRole } from "./SessionCredentialService.ts";--export interface AuthenticatedSession {- readonly sessionId: AuthSessionId;- readonly subject: string;- readonly method: ServerAuthSessionMethod;- readonly role: SessionRole;- readonly expiresAt?: DateTime.DateTime;-}--export class AuthError extends Data.TaggedError("AuthError")<{- readonly message: string;- readonly status?: 400 | 401 | 403 | 500;- readonly cause?: unknown;-}> {}--export interface ServerAuthShape {- readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;- readonly getSessionState: (- request: HttpServerRequest.HttpServerRequest,- ) => Effect.Effect<AuthSessionState, never>;- readonly exchangeBootstrapCredential: (- credential: string,- requestMetadata: AuthClientMetadata,- ) => Effect.Effect<- {- readonly response: AuthBootstrapResult;- readonly sessionToken: string;- },- AuthError- >;- readonly exchangeBootstrapCredentialForBearerSession: (- credential: string,- requestMetadata: AuthClientMetadata,- ) => Effect.Effect<AuthBearerBootstrapResult, AuthError>;- readonly issuePairingCredential: (- input?: AuthCreatePairingCredentialInput & {- readonly role?: SessionRole;- },- ) => Effect.Effect<AuthPairingCredentialResult, AuthError>;- readonly listPairingLinks: () => Effect.Effect<ReadonlyArray<AuthPairingLink>, AuthError>;- readonly revokePairingLink: (id: string) => Effect.Effect<boolean, AuthError>;- readonly listClientSessions: (- currentSessionId: AuthSessionId,- ) => Effect.Effect<ReadonlyArray<AuthClientSession>, AuthError>;- readonly revokeClientSession: (- currentSessionId: AuthSessionId,- targetSessionId: AuthSessionId,- ) => Effect.Effect<boolean, AuthError>;- readonly revokeOtherClientSessions: (- currentSessionId: AuthSessionId,- ) => Effect.Effect<number, AuthError>;- readonly authenticateHttpRequest: (- request: HttpServerRequest.HttpServerRequest,- ) => Effect.Effect<AuthenticatedSession, AuthError>;- readonly authenticateWebSocketUpgrade: (- request: HttpServerRequest.HttpServerRequest,- ) => Effect.Effect<AuthenticatedSession, AuthError>;- readonly issueWebSocketToken: (- session: AuthenticatedSession,- ) => Effect.Effect<AuthWebSocketTokenResult, AuthError>;- readonly issueStartupPairingUrl: (baseUrl: string) => Effect.Effect<string, AuthError>;-}--export class ServerAuth extends Context.Service<ServerAuth, ServerAuthShape>()(- "t3/auth/Services/ServerAuth",-) {}diff --git a/apps/server/src/auth/Services/ServerAuthPolicy.ts b/apps/server/src/auth/Services/ServerAuthPolicy.tsdeleted file mode 100644index 5d9ef68cf..000000000--- a/apps/server/src/auth/Services/ServerAuthPolicy.ts+++ /dev/null@@ -1,11 +0,0 @@-import type { ServerAuthDescriptor } from "@t3tools/contracts";-import * as Context from "effect/Context";-import type * as Effect from "effect/Effect";--export interface ServerAuthPolicyShape {- readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;-}--export class ServerAuthPolicy extends Context.Service<ServerAuthPolicy, ServerAuthPolicyShape>()(- "t3/auth/Services/ServerAuthPolicy",-) {}diff --git a/apps/server/src/auth/Services/ServerSecretStore.ts b/apps/server/src/auth/Services/ServerSecretStore.tsdeleted file mode 100644index f5c6f6dfe..000000000--- a/apps/server/src/auth/Services/ServerSecretStore.ts+++ /dev/null@@ -1,22 +0,0 @@-import * as Data from "effect/Data";-import * as Context from "effect/Context";-import type * as Effect from "effect/Effect";--export class SecretStoreError extends Data.TaggedError("SecretStoreError")<{- readonly message: string;- readonly cause?: unknown;-}> {}--export interface ServerSecretStoreShape {- readonly get: (name: string) => Effect.Effect<Uint8Array | null, SecretStoreError>;- readonly set: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;- readonly getOrCreateRandom: (- name: string,- bytes: number,- ) => Effect.Effect<Uint8Array, SecretStoreError>;- readonly remove: (name: string) => Effect.Effect<void, SecretStoreError>;-}--export class ServerSecretStore extends Context.Service<ServerSecretStore, ServerSecretStoreShape>()(- "t3/auth/Services/ServerSecretStore",-) {}diff --git a/apps/server/src/auth/Services/SessionCredentialService.ts b/apps/server/src/auth/Services/SessionCredentialService.tsdeleted file mode 100644index 7dc049c91..000000000--- a/apps/server/src/auth/Services/SessionCredentialService.ts+++ /dev/null@@ -1,91 +0,0 @@-import type {- AuthClientMetadata,- AuthClientSession,- AuthSessionId,- ServerAuthSessionMethod,-} from "@t3tools/contracts";-import * as Data from "effect/Data";-import * as DateTime from "effect/DateTime";-import * as Duration from "effect/Duration";-import * as Context from "effect/Context";-import type * as Effect from "effect/Effect";-import type * as Stream from "effect/Stream";--export type SessionRole = "owner" | "client";--export interface IssuedSession {- readonly sessionId: AuthSessionId;- readonly token: string;- readonly method: ServerAuthSessionMethod;- readonly client: AuthClientMetadata;- readonly expiresAt: DateTime.DateTime;- readonly role: SessionRole;-}--export interface VerifiedSession {- readonly sessionId: AuthSessionId;- readonly token: string;- readonly method: ServerAuthSessionMethod;- readonly client: AuthClientMetadata;- readonly expiresAt?: DateTime.DateTime;- readonly subject: string;- readonly role: SessionRole;-}--export type SessionCredentialChange =- | {- readonly type: "clientUpserted";- readonly clientSession: AuthClientSession;- }- | {- readonly type: "clientRemoved";- readonly sessionId: AuthSessionId;- };--export class SessionCredentialError extends Data.TaggedError("SessionCredentialError")<{- readonly message: string;- readonly cause?: unknown;-}> {}--export interface SessionCredentialServiceShape {- readonly cookieName: string;- readonly issue: (input?: {- readonly ttl?: Duration.Duration;- readonly subject?: string;- readonly method?: ServerAuthSessionMethod;- readonly role?: SessionRole;- readonly client?: AuthClientMetadata;- }) => Effect.Effect<IssuedSession, SessionCredentialError>;- readonly verify: (token: string) => Effect.Effect<VerifiedSession, SessionCredentialError>;- readonly issueWebSocketToken: (- sessionId: AuthSessionId,- input?: {- readonly ttl?: Duration.Duration;- },- ) => Effect.Effect<- {- readonly token: string;- readonly expiresAt: DateTime.DateTime;- },- SessionCredentialError- >;- readonly verifyWebSocketToken: (- token: string,- ) => Effect.Effect<VerifiedSession, SessionCredentialError>;- readonly listActive: () => Effect.Effect<- ReadonlyArray<AuthClientSession>,- SessionCredentialError- >;- readonly streamChanges: Stream.Stream<SessionCredentialChange>;- readonly revoke: (sessionId: AuthSessionId) => Effect.Effect<boolean, SessionCredentialError>;- readonly revokeAllExcept: (- sessionId: AuthSessionId,- ) => Effect.Effect<number, SessionCredentialError>;- readonly markConnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;- readonly markDisconnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;-}--export class SessionCredentialService extends Context.Service<- SessionCredentialService,- SessionCredentialServiceShape->()("t3/auth/Services/SessionCredentialService") {}diff --git a/apps/server/src/auth/Layers/SessionCredentialService.test.ts b/apps/server/src/auth/SessionStore.test.tssimilarity index 58%rename from apps/server/src/auth/Layers/SessionCredentialService.test.tsrename to apps/server/src/auth/SessionStore.test.tsindex 5609c2fde..00abd6b99 100644--- a/apps/server/src/auth/Layers/SessionCredentialService.test.ts+++ b/apps/server/src/auth/SessionStore.test.ts@@ -5,12 +5,13 @@ import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import * as TestClock from "effect/testing/TestClock";-import type { ServerConfigShape } from "../../config.ts";-import { ServerConfig } from "../../config.ts";-import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";-import { SessionCredentialService } from "../Services/SessionCredentialService.ts";-import { ServerSecretStoreLive } from "./ServerSecretStore.ts";-import { SessionCredentialServiceLive } from "./SessionCredentialService.ts";+import type { ServerConfigShape } from "../config.ts";+import { ServerConfig } from "../config.ts";+import { PersistenceSqlError } from "../persistence/Errors.ts";+import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";+import { AuthSessionRepository } from "../persistence/Services/AuthSessions.ts";+import * as SessionStore from "./SessionStore.ts";+import * as ServerSecretStore from "./ServerSecretStore.ts";const makeServerConfigLayer = (overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,@@ -26,22 +27,46 @@ const makeServerConfigLayer = (}),).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-session-test-" })));-const makeSessionCredentialLayer = (+const makeSessionStoreLayer = (overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,) =>- SessionCredentialServiceLive.pipe(+ SessionStore.layer.pipe(Layer.provide(SqlitePersistenceMemory),- Layer.provide(ServerSecretStoreLive),+ Layer.provide(ServerSecretStore.layer),Layer.provide(makeServerConfigLayer(overrides)),);-it.layer(NodeServices.layer)("SessionCredentialServiceLive", (it) => {+const repositoryFailure = new PersistenceSqlError({+ operation: "AuthSessionRepository.getById:query",+ detail: "sqlite is unavailable",+});++const failingSessionLookupRepositoryLayer = Layer.succeed(AuthSessionRepository, {+ create: () => Effect.void,+ getById: () => Effect.fail(repositoryFailure),+ listActive: () => Effect.succeed([]),+ revoke: () => Effect.succeed(false),+ revokeAllExcept: () => Effect.succeed([]),+ setLastConnectedAt: () => Effect.void,+});++const failingSessionLookupCredentialLayer = Layer.effect(+ SessionStore.SessionStore,+ SessionStore.make(),+).pipe(+ Layer.provide(failingSessionLookupRepositoryLayer),+ Layer.provide(ServerSecretStore.layer),+ Layer.provide(SqlitePersistenceMemory),+ Layer.provide(makeServerConfigLayer()),+);++it.layer(NodeServices.layer)("SessionStore.layer", (it) => {it.effect("issues and verifies signed browser session tokens", () =>Effect.gen(function* () {- const sessions = yield* SessionCredentialService;+ const sessions = yield* SessionStore.SessionStore;const issued = yield* sessions.issue({subject: "desktop-bootstrap",- role: "owner",+ scopes: ["orchestration:read", "access:write"],client: {label: "Desktop app",deviceType: "desktop",@@ -54,41 +79,65 @@ it.layer(NodeServices.layer)("SessionCredentialServiceLive", (it) => {expect(verified.method).toBe("browser-session-cookie");expect(verified.subject).toBe("desktop-bootstrap");- expect(verified.role).toBe("owner");+ expect(verified.scopes).toEqual(["orchestration:read", "access:write"]);expect(verified.client.label).toBe("Desktop app");expect(verified.client.browser).toBe("Electron");expect(verified.expiresAt?.toString()).toBe(issued.expiresAt.toString());- }).pipe(Effect.provide(makeSessionCredentialLayer())),+ }).pipe(Effect.provide(makeSessionStoreLayer())),);it.effect("rejects malformed session tokens", () =>Effect.gen(function* () {- const sessions = yield* SessionCredentialService;+ const sessions = yield* SessionStore.SessionStore;const error = yield* Effect.flip(sessions.verify("not-a-session-token"));- expect(error._tag).toBe("SessionCredentialError");+ expect(error._tag).toBe("SessionCredentialInvalidError");expect(error.message).toContain("Malformed session token");- }).pipe(Effect.provide(makeSessionCredentialLayer())),+ }).pipe(Effect.provide(makeSessionStoreLayer())),+ );+ it.effect("preserves repository failures while verifying session and websocket credentials", () =>+ Effect.gen(function* () {+ const sessions = yield* SessionStore.SessionStore;+ const issued = yield* sessions.issue({+ method: "bearer-access-token",+ subject: "repository-failure",+ });+ const websocket = yield* sessions.issueWebSocketToken(issued.sessionId);++ const sessionError = yield* Effect.flip(sessions.verify(issued.token));+ const websocketError = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token));++ expect(sessionError._tag).toBe("SessionCredentialInternalError");+ expect(websocketError._tag).toBe("SessionCredentialInternalError");+ expect(sessionError.cause).toBe(repositoryFailure);+ expect(websocketError.cause).toBe(repositoryFailure);+ }).pipe(Effect.provide(failingSessionLookupCredentialLayer)),);it.effect("verifies session tokens against the Effect clock", () =>Effect.gen(function* () {- const sessions = yield* SessionCredentialService;+ const sessions = yield* SessionStore.SessionStore;const issued = yield* sessions.issue({- method: "bearer-session-token",+ method: "bearer-access-token",subject: "test-clock",});const verified = yield* sessions.verify(issued.token);- expect(verified.method).toBe("bearer-session-token");+ expect(verified.method).toBe("bearer-access-token");expect(verified.subject).toBe("test-clock");- expect(verified.role).toBe("client");- }).pipe(Effect.provide(Layer.merge(makeSessionCredentialLayer(), TestClock.layer()))),+ expect(verified.scopes).toEqual([+ "orchestration:read",+ "orchestration:operate",+ "terminal:operate",+ "review:write",+ "relay:read",+ ]);+ }).pipe(Effect.provide(Layer.merge(makeSessionStoreLayer(), TestClock.layer()))),);it.effect("rejects websocket tokens once the parent session has expired", () =>Effect.gen(function* () {- const sessions = yield* SessionCredentialService;+ const sessions = yield* SessionStore.SessionStore;const issued = yield* sessions.issue({- method: "bearer-session-token",+ method: "bearer-access-token",subject: "short-lived",ttl: Duration.seconds(1),});@@ -98,15 +147,15 @@ it.layer(NodeServices.layer)("SessionCredentialServiceLive", (it) => {const error = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token));expect(error.message).toContain("expired");- }).pipe(Effect.provide(Layer.merge(makeSessionCredentialLayer(), TestClock.layer()))),+ }).pipe(Effect.provide(Layer.merge(makeSessionStoreLayer(), TestClock.layer()))),);it.effect("lists active sessions, tracks connectivity, and revokes other sessions", () =>Effect.gen(function* () {- const sessions = yield* SessionCredentialService;- const owner = yield* sessions.issue({+ const sessions = yield* SessionStore.SessionStore;+ const administrative = yield* sessions.issue({subject: "desktop-bootstrap",- role: "owner",+ scopes: ["orchestration:read", "access:write"],client: {label: "Desktop app",deviceType: "desktop",@@ -116,7 +165,7 @@ it.layer(NodeServices.layer)("SessionCredentialServiceLive", (it) => {});const client = yield* sessions.issue({subject: "one-time-token",- role: "client",+ scopes: ["orchestration:read"],client: {label: "Julius iPhone",deviceType: "mobile",@@ -128,7 +177,7 @@ it.layer(NodeServices.layer)("SessionCredentialServiceLive", (it) => {yield* sessions.markConnected(client.sessionId);const beforeRevoke = yield* sessions.listActive();- const revokedCount = yield* sessions.revokeAllExcept(owner.sessionId);+ const revokedCount = yield* sessions.revokeAllExcept(administrative.sessionId);const afterRevoke = yield* sessions.listActive();const revokedClient = yield* Effect.flip(sessions.verify(client.token));@@ -140,21 +189,22 @@ it.layer(NodeServices.layer)("SessionCredentialServiceLive", (it) => {"Julius iPhone",);expect(- beforeRevoke.find((entry) => entry.sessionId === owner.sessionId)?.client.deviceType,+ beforeRevoke.find((entry) => entry.sessionId === administrative.sessionId)?.client+ .deviceType,).toBe("desktop");expect(revokedCount).toBe(1);expect(afterRevoke).toHaveLength(1);- expect(afterRevoke[0]?.sessionId).toBe(owner.sessionId);+ expect(afterRevoke[0]?.sessionId).toBe(administrative.sessionId);expect(revokedClient.message).toContain("revoked");- }).pipe(Effect.provide(makeSessionCredentialLayer())),+ }).pipe(Effect.provide(makeSessionStoreLayer())),);it.effect("persists lastConnectedAt on first connect and updates it after reconnect", () =>Effect.gen(function* () {- const sessions = yield* SessionCredentialService;+ const sessions = yield* SessionStore.SessionStore;const issued = yield* sessions.issue({subject: "reconnect-test",- method: "bearer-session-token",+ method: "bearer-access-token",});const beforeConnect = yield* sessions.listActive();@@ -188,6 +238,6 @@ it.layer(NodeServices.layer)("SessionCredentialServiceLive", (it) => {expect(afterReconnect[0]?.connected).toBe(true);expect(afterReconnect[0]?.lastConnectedAt).not.toBeNull();expect(afterReconnect[0]?.lastConnectedAt?.toString()).not.toBe(firstConnectedAt?.toString());- }).pipe(Effect.provide(Layer.merge(makeSessionCredentialLayer(), TestClock.layer()))),+ }).pipe(Effect.provide(Layer.merge(makeSessionStoreLayer(), TestClock.layer()))),);});diff --git a/apps/server/src/auth/Layers/SessionCredentialService.ts b/apps/server/src/auth/SessionStore.tssimilarity index 63%rename from apps/server/src/auth/Layers/SessionCredentialService.tsrename to apps/server/src/auth/SessionStore.tsindex 7d06c40da..83f38c6b6 100644--- a/apps/server/src/auth/Layers/SessionCredentialService.ts+++ b/apps/server/src/auth/SessionStore.ts@@ -1,6 +1,16 @@-import { AuthSessionId, type AuthClientMetadata, type AuthClientSession } from "@t3tools/contracts";+import {+ AuthSessionId,+ AuthStandardClientScopes,+ AuthEnvironmentScopes,+ type AuthClientMetadata,+ type AuthClientSession,+ type AuthEnvironmentScope,+ type ServerAuthSessionMethod,+} from "@t3tools/contracts";import * as Clock from "effect/Clock";+import * as Context from "effect/Context";import * as Crypto from "effect/Crypto";+import * as Data from "effect/Data";import * as DateTime from "effect/DateTime";import * as Duration from "effect/Duration";import * as Effect from "effect/Effect";@@ -11,25 +21,106 @@ import * as Schema from "effect/Schema";import * as Stream from "effect/Stream";import * as Option from "effect/Option";-import { ServerConfig } from "../../config.ts";-import { AuthSessionRepositoryLive } from "../../persistence/Layers/AuthSessions.ts";-import { AuthSessionRepository } from "../../persistence/Services/AuthSessions.ts";-import { ServerSecretStore } from "../Services/ServerSecretStore.ts";-import {- SessionCredentialError,- SessionCredentialService,- type IssuedSession,- type SessionCredentialChange,- type SessionCredentialServiceShape,- type VerifiedSession,-} from "../Services/SessionCredentialService.ts";+import { ServerConfig } from "../config.ts";+import { AuthSessionRepositoryLive } from "../persistence/Layers/AuthSessions.ts";+import { AuthSessionRepository } from "../persistence/Services/AuthSessions.ts";+import * as ServerSecretStore from "./ServerSecretStore.ts";import {base64UrlDecodeUtf8,base64UrlEncode,resolveSessionCookieName,signPayload,timingSafeEqualBase64Url,-} from "../utils.ts";+} from "./utils.ts";++export interface IssuedSession {+ readonly sessionId: AuthSessionId;+ readonly token: string;+ readonly method: ServerAuthSessionMethod;+ readonly client: AuthClientMetadata;+ readonly expiresAt: DateTime.DateTime;+ readonly scopes: ReadonlyArray<AuthEnvironmentScope>;+}++export interface VerifiedSession {+ readonly sessionId: AuthSessionId;+ readonly token: string;+ readonly method: ServerAuthSessionMethod;+ readonly client: AuthClientMetadata;+ readonly expiresAt?: DateTime.DateTime;+ readonly subject: string;+ readonly scopes: ReadonlyArray<AuthEnvironmentScope>;+}++export type SessionCredentialChange =+ | {+ readonly type: "clientUpserted";+ readonly clientSession: AuthClientSession;+ }+ | {+ readonly type: "clientRemoved";+ readonly sessionId: AuthSessionId;+ };++export class SessionCredentialInvalidError extends Data.TaggedError(+ "SessionCredentialInvalidError",+)<{+ readonly message: string;+ readonly cause?: unknown;+}> {}++export class SessionCredentialInternalError extends Data.TaggedError(+ "SessionCredentialInternalError",+)<{+ readonly message: string;+ readonly cause?: unknown;+}> {}++export type SessionCredentialError = SessionCredentialInvalidError | SessionCredentialInternalError;++export interface SessionStoreShape {+ readonly cookieName: string;+ readonly issue: (input?: {+ readonly ttl?: Duration.Duration;+ readonly subject?: string;+ readonly method?: ServerAuthSessionMethod;+ readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;+ readonly client?: AuthClientMetadata;+ }) => Effect.Effect<IssuedSession, SessionCredentialInternalError>;+ readonly verify: (token: string) => Effect.Effect<VerifiedSession, SessionCredentialError>;+ readonly issueWebSocketToken: (+ sessionId: AuthSessionId,+ input?: {+ readonly ttl?: Duration.Duration;+ },+ ) => Effect.Effect<+ {+ readonly token: string;+ readonly expiresAt: DateTime.DateTime;+ },+ SessionCredentialInternalError+ >;+ readonly verifyWebSocketToken: (+ token: string,+ ) => Effect.Effect<VerifiedSession, SessionCredentialError>;+ readonly listActive: () => Effect.Effect<+ ReadonlyArray<AuthClientSession>,+ SessionCredentialInternalError+ >;+ readonly streamChanges: Stream.Stream<SessionCredentialChange>;+ readonly revoke: (+ sessionId: AuthSessionId,+ ) => Effect.Effect<boolean, SessionCredentialInternalError>;+ readonly revokeAllExcept: (+ sessionId: AuthSessionId,+ ) => Effect.Effect<number, SessionCredentialInternalError>;+ readonly markConnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;+ readonly markDisconnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;+}++export class SessionStore extends Context.Service<SessionStore, SessionStoreShape>()(+ "t3/auth/SessionStore",+) {}const SIGNING_SECRET_NAME = "server-signing-key";const DEFAULT_SESSION_TTL = Duration.days(30);@@ -40,8 +131,8 @@ const SessionClaims = Schema.Struct({kind: Schema.Literal("session"),sid: AuthSessionId,sub: Schema.String,- role: Schema.Literals(["owner", "client"]),- method: Schema.Literals(["browser-session-cookie", "bearer-session-token"]),+ scopes: AuthEnvironmentScopes,+ method: Schema.Literals(["browser-session-cookie", "bearer-access-token"]),iat: Schema.Number,exp: Schema.Number,});@@ -90,10 +181,16 @@ function toAuthClientSession(input: Omit<AuthClientSession, "current">): AuthCli};}-export const makeSessionCredentialService = Effect.gen(function* () {+const toSessionCredentialInternalError = (message: string) => (cause: unknown) =>+ new SessionCredentialInternalError({+ message,+ cause,+ });++export const make = Effect.fn("makeSessionStore")(function* () {const crypto = yield* Crypto.Crypto;const serverConfig = yield* ServerConfig;- const secretStore = yield* ServerSecretStore;+ const secretStore = yield* ServerSecretStore.ServerSecretStore;const authSessions = yield* AuthSessionRepository;const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);const connectedSessionsRef = yield* Ref.make(new Map<string, number>());@@ -103,12 +200,6 @@ export const makeSessionCredentialService = Effect.gen(function* () {port: serverConfig.port,});- const toSessionCredentialError = (message: string) => (cause: unknown) =>- new SessionCredentialError({- message,- cause,- });-const emitUpsert = (clientSession: AuthClientSession) =>PubSub.publish(changesPubSub, {type: "clientUpserted",@@ -133,7 +224,7 @@ export const makeSessionCredentialService = Effect.gen(function* () {toAuthClientSession({sessionId: row.value.sessionId,subject: row.value.subject,- role: row.value.role,+ scopes: row.value.scopes,method: row.value.method,client: toClientMetadata(row.value.client),issuedAt: row.value.issuedAt,@@ -144,7 +235,7 @@ export const makeSessionCredentialService = Effect.gen(function* () {);});- const markConnected: SessionCredentialServiceShape["markConnected"] = (sessionId) =>+ const markConnected: SessionStoreShape["markConnected"] = (sessionId) =>Ref.modify(connectedSessionsRef, (current) => {const next = new Map(current);const wasDisconnected = !next.has(sessionId);@@ -175,9 +266,10 @@ export const makeSessionCredentialService = Effect.gen(function* () {}),),),+ Effect.withSpan("SessionStore.markConnected"),);- const markDisconnected: SessionCredentialServiceShape["markDisconnected"] = (sessionId) =>+ const markDisconnected: SessionStoreShape["markDisconnected"] = (sessionId) =>Ref.update(connectedSessionsRef, (current) => {const next = new Map(current);const remaining = (next.get(sessionId) ?? 0) - 1;@@ -200,11 +292,12 @@ export const makeSessionCredentialService = Effect.gen(function* () {}),),),+ Effect.withSpan("SessionStore.markDisconnected"),);const encodeClaims = Schema.encodeEffect(Schema.fromJsonString(SessionClaims));- const issue: SessionCredentialServiceShape["issue"] = (input) =>- Effect.gen(function* () {+ const issue: SessionStoreShape["issue"] = Effect.fn("SessionStore.issue")(+ function* (input) {const sessionId = AuthSessionId.make(yield* crypto.randomUUIDv4);const issuedAt = yield* DateTime.now;const expiresAt = DateTime.add(issuedAt, {@@ -215,7 +308,7 @@ export const makeSessionCredentialService = Effect.gen(function* () {kind: "session",sid: sessionId,sub: input?.subject ?? "browser",- role: input?.role ?? "client",+ scopes: input?.scopes ?? AuthStandardClientScopes,method: input?.method ?? "browser-session-cookie",iat: issuedAt.epochMilliseconds,exp: expiresAt.epochMilliseconds,@@ -224,7 +317,8 @@ export const makeSessionCredentialService = Effect.gen(function* () {const encodedPayload = yield* encodeClaims(claims).pipe(Effect.map(base64UrlEncode),Effect.mapError(- (cause) => new SessionCredentialError({ message: "Failed to encode claims", cause }),+ (cause) =>+ new SessionCredentialInternalError({ message: "Failed to encode claims", cause }),),);const signature = signPayload(encodedPayload, signingSecret);@@ -232,7 +326,7 @@ export const makeSessionCredentialService = Effect.gen(function* () {yield* authSessions.create({sessionId,subject: claims.sub,- role: claims.role,+ scopes: claims.scopes,method: claims.method,client: {label: client.label ?? null,@@ -249,7 +343,7 @@ export const makeSessionCredentialService = Effect.gen(function* () {toAuthClientSession({sessionId,subject: claims.sub,- role: claims.role,+ scopes: claims.scopes,method: claims.method,client,issuedAt,@@ -265,22 +359,24 @@ export const makeSessionCredentialService = Effect.gen(function* () {method: claims.method,client,expiresAt: expiresAt,- role: claims.role,+ scopes: claims.scopes,} satisfies IssuedSession;- }).pipe(Effect.mapError(toSessionCredentialError("Failed to issue session credential.")));+ },+ Effect.mapError(toSessionCredentialInternalError("Failed to issue session credential.")),+ );- const verify: SessionCredentialServiceShape["verify"] = (token) =>- Effect.gen(function* () {+ const verify: SessionStoreShape["verify"] = Effect.fn("SessionStore.verify")(+ function* (token) {const [encodedPayload, signature] = token.split(".");if (!encodedPayload || !signature) {- return yield* new SessionCredentialError({+ return yield* new SessionCredentialInvalidError({message: "Malformed session token.",});}const expectedSignature = signPayload(encodedPayload, signingSecret);if (!timingSafeEqualBase64Url(signature, expectedSignature)) {- return yield* new SessionCredentialError({+ return yield* new SessionCredentialInvalidError({message: "Invalid session token signature.",});}@@ -288,7 +384,7 @@ export const makeSessionCredentialService = Effect.gen(function* () {const claims = yield* decodeSessionClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(Effect.mapError((cause) =>- new SessionCredentialError({+ new SessionCredentialInvalidError({message: "Invalid session token payload.",cause,}),@@ -297,26 +393,26 @@ export const makeSessionCredentialService = Effect.gen(function* () {const now = yield* Clock.currentTimeMillis;if (claims.exp <= now) {- return yield* new SessionCredentialError({+ return yield* new SessionCredentialInvalidError({message: "Session token expired.",});}const row = yield* authSessions.getById({ sessionId: claims.sid });if (Option.isNone(row)) {- return yield* new SessionCredentialError({+ return yield* new SessionCredentialInvalidError({message: "Unknown session token.",});}if (row.value.revokedAt !== null) {- return yield* new SessionCredentialError({+ return yield* new SessionCredentialInvalidError({message: "Session token revoked.",});}const expiresAt = DateTime.make(claims.exp);if (Option.isNone(expiresAt)) {- return yield* new SessionCredentialError({+ return yield* new SessionCredentialInvalidError({message: "Invalid `exp` claim",});}@@ -328,25 +424,24 @@ export const makeSessionCredentialService = Effect.gen(function* () {client: toClientMetadata(row.value.client),expiresAt: expiresAt.value,subject: claims.sub,- role: claims.role,+ scopes: claims.scopes,} satisfies VerifiedSession;- }).pipe(- Effect.mapError((cause) =>- cause instanceof SessionCredentialError- ? cause- : new SessionCredentialError({- message: "Failed to verify session credential.",- cause,- }),- ),- );+ },+ Effect.mapError((cause) =>+ cause._tag === "SessionCredentialInvalidError"+ ? cause+ : new SessionCredentialInternalError({+ message: "Failed to verify session credential.",+ cause,+ }),+ ),+ );const encodeWsClaims = Schema.encodeEffect(Schema.fromJsonString(WebSocketClaims));- const issueWebSocketToken: SessionCredentialServiceShape["issueWebSocketToken"] = (- sessionId,- input,- ) =>- Effect.gen(function* () {+ const issueWebSocketToken: SessionStoreShape["issueWebSocketToken"] = Effect.fn(+ "SessionStore.issueWebSocketToken",+ )(+ function* (sessionId, input) {const issuedAt = yield* DateTime.now;const expiresAt = DateTime.add(issuedAt, {milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL),@@ -361,7 +456,8 @@ export const makeSessionCredentialService = Effect.gen(function* () {const encodedPayload = yield* encodeWsClaims(claims).pipe(Effect.map(base64UrlEncode),Effect.mapError(- (cause) => new SessionCredentialError({ message: "Failed to encode claims", cause }),+ (cause) =>+ new SessionCredentialInternalError({ message: "Failed to encode claims", cause }),),);const signature = signPayload(encodedPayload, signingSecret);@@ -369,20 +465,24 @@ export const makeSessionCredentialService = Effect.gen(function* () {token: `${encodedPayload}.${signature}`,expiresAt,};- }).pipe(Effect.mapError(toSessionCredentialError("Failed to issue websocket token.")));+ },+ Effect.mapError(toSessionCredentialInternalError("Failed to issue websocket token.")),+ );- const verifyWebSocketToken: SessionCredentialServiceShape["verifyWebSocketToken"] = (token) =>- Effect.gen(function* () {+ const verifyWebSocketToken: SessionStoreShape["verifyWebSocketToken"] = Effect.fn(+ "SessionStore.verifyWebSocketToken",+ )(+ function* (token) {const [encodedPayload, signature] = token.split(".");if (!encodedPayload || !signature) {- return yield* new SessionCredentialError({+ return yield* new SessionCredentialInvalidError({message: "Malformed websocket token.",});}const expectedSignature = signPayload(encodedPayload, signingSecret);if (!timingSafeEqualBase64Url(signature, expectedSignature)) {- return yield* new SessionCredentialError({+ return yield* new SessionCredentialInvalidError({message: "Invalid websocket token signature.",});}@@ -390,7 +490,7 @@ export const makeSessionCredentialService = Effect.gen(function* () {const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(Effect.mapError((cause) =>- new SessionCredentialError({+ new SessionCredentialInvalidError({message: "Invalid websocket token payload.",cause,}),@@ -399,24 +499,24 @@ export const makeSessionCredentialService = Effect.gen(function* () {const now = yield* Clock.currentTimeMillis;if (claims.exp <= now) {- return yield* new SessionCredentialError({+ return yield* new SessionCredentialInvalidError({message: "Websocket token expired.",});}const row = yield* authSessions.getById({ sessionId: claims.sid });if (Option.isNone(row)) {- return yield* new SessionCredentialError({+ return yield* new SessionCredentialInvalidError({message: "Unknown websocket session.",});}if (row.value.expiresAt.epochMilliseconds <= now) {- return yield* new SessionCredentialError({+ return yield* new SessionCredentialInvalidError({message: "Websocket session expired.",});}if (row.value.revokedAt !== null) {- return yield* new SessionCredentialError({+ return yield* new SessionCredentialInvalidError({message: "Websocket session revoked.",});}@@ -428,21 +528,21 @@ export const makeSessionCredentialService = Effect.gen(function* () {client: toClientMetadata(row.value.client),expiresAt: row.value.expiresAt,subject: row.value.subject,- role: row.value.role,+ scopes: row.value.scopes,} satisfies VerifiedSession;- }).pipe(- Effect.mapError((cause) =>- cause instanceof SessionCredentialError- ? cause- : new SessionCredentialError({- message: "Failed to verify websocket token.",- cause,- }),- ),- );+ },+ Effect.mapError((cause) =>+ cause._tag === "SessionCredentialInvalidError"+ ? cause+ : new SessionCredentialInternalError({+ message: "Failed to verify websocket token.",+ cause,+ }),+ ),+ );- const listActive: SessionCredentialServiceShape["listActive"] = () =>- Effect.gen(function* () {+ const listActive: SessionStoreShape["listActive"] = Effect.fn("SessionStore.listActive")(+ function* () {const now = yield* DateTime.now;const connectedSessions = yield* Ref.get(connectedSessionsRef);const rows = yield* authSessions.listActive({ now });@@ -451,7 +551,7 @@ export const makeSessionCredentialService = Effect.gen(function* () {toAuthClientSession({sessionId: row.sessionId,subject: row.subject,- role: row.role,+ scopes: row.scopes,method: row.method,client: toClientMetadata(row.client),issuedAt: row.issuedAt,@@ -460,10 +560,12 @@ export const makeSessionCredentialService = Effect.gen(function* () {connected: connectedSessions.has(row.sessionId),}),);- }).pipe(Effect.mapError(toSessionCredentialError("Failed to list active sessions.")));+ },+ Effect.mapError(toSessionCredentialInternalError("Failed to list active sessions.")),+ );- const revoke: SessionCredentialServiceShape["revoke"] = (sessionId) =>- Effect.gen(function* () {+ const revoke: SessionStoreShape["revoke"] = Effect.fn("SessionStore.revoke")(+ function* (sessionId) {const revokedAt = yield* DateTime.now;const revoked = yield* authSessions.revoke({sessionId,@@ -478,10 +580,14 @@ export const makeSessionCredentialService = Effect.gen(function* () {yield* emitRemoved(sessionId);}return revoked;- }).pipe(Effect.mapError(toSessionCredentialError("Failed to revoke session.")));+ },+ Effect.mapError(toSessionCredentialInternalError("Failed to revoke session.")),+ );- const revokeAllExcept: SessionCredentialServiceShape["revokeAllExcept"] = (sessionId) =>- Effect.gen(function* () {+ const revokeAllExcept: SessionStoreShape["revokeAllExcept"] = Effect.fn(+ "SessionStore.revokeAllExcept",+ )(+ function* (sessionId) {const revokedAt = yield* DateTime.now;const revokedSessionIds = yield* authSessions.revokeAllExcept({currentSessionId: sessionId,@@ -505,7 +611,9 @@ export const makeSessionCredentialService = Effect.gen(function* () {);}return revokedSessionIds.length;- }).pipe(Effect.mapError(toSessionCredentialError("Failed to revoke other sessions.")));+ },+ Effect.mapError(toSessionCredentialInternalError("Failed to revoke other sessions.")),+ );return {cookieName,@@ -521,10 +629,9 @@ export const makeSessionCredentialService = Effect.gen(function* () {revokeAllExcept,markConnected,markDisconnected,- } satisfies SessionCredentialServiceShape;+ } satisfies SessionStoreShape;});-export const SessionCredentialServiceLive = Layer.effect(- SessionCredentialService,- makeSessionCredentialService,-).pipe(Layer.provideMerge(AuthSessionRepositoryLive));+export const layer = Layer.effect(SessionStore, make()).pipe(+ Layer.provideMerge(AuthSessionRepositoryLive),+);diff --git a/apps/server/src/auth/http.ts b/apps/server/src/auth/http.tsindex 670ff5abb..b36c8dd64 100644--- a/apps/server/src/auth/http.ts+++ b/apps/server/src/auth/http.ts@@ -1,265 +1,371 @@import {- type AuthBearerBootstrapResult,- AuthBootstrapInput,- AuthCreatePairingCredentialInput,- AuthRevokeClientSessionInput,- AuthRevokePairingLinkInput,- type AuthWebSocketTokenResult,+ AuthAccessReadScope,+ AuthAccessWriteScope,+ AuthStandardClientScopes,+ AuthOrchestrationOperateScope,+ AuthOrchestrationReadScope,+ AuthRelayReadScope,+ AuthRelayWriteScope,+ AuthReviewWriteScope,+ AuthTerminalOperateScope,+ EnvironmentAuthInvalidError,+ type EnvironmentAuthInvalidReason,+ EnvironmentHttpApi,+ EnvironmentInternalError,+ type EnvironmentInternalErrorReason,+ EnvironmentOperationForbiddenError,+ EnvironmentRequestInvalidError,+ type EnvironmentRequestInvalidReason,+ EnvironmentScopeRequiredError,+ EnvironmentAuthenticatedAuth,+ EnvironmentAuthenticatedPrincipal,} from "@t3tools/contracts";+import type { AuthEnvironmentScope } from "@t3tools/contracts";+import { parseAllowedOAuthScope } from "@t3tools/shared/oauthScope";+import { causeErrorTag } from "@t3tools/shared/observability";import * as DateTime from "effect/DateTime";import * as Effect from "effect/Effect";-import * as Schema from "effect/Schema";-import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";+import * as Layer from "effect/Layer";+import * as Cookies from "effect/unstable/http/Cookies";+import * as HttpEffect from "effect/unstable/http/HttpEffect";+import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http";+import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";-import { AuthError, ServerAuth } from "./Services/ServerAuth.ts";-import { SessionCredentialService } from "./Services/SessionCredentialService.ts";+import * as EnvironmentAuth from "./EnvironmentAuth.ts";+import * as SessionStore from "./SessionStore.ts";import { deriveAuthClientMetadata } from "./utils.ts";-import { browserApiCorsHeaders } from "../httpCors.ts";-export const respondToAuthError = (error: AuthError) =>- Effect.gen(function* () {- if ((error.status ?? 500) >= 500) {- yield* Effect.logError("auth route failed", {- message: error.message,- cause: error.cause,- });- }- return HttpServerResponse.jsonUnsafe(- {- error: error.message,- },- { status: error.status ?? 500, headers: browserApiCorsHeaders },- );- });+export const currentEnvironmentTraceId = Effect.currentParentSpan.pipe(+ Effect.map((span) => span.traceId),+ Effect.orElseSucceed(() => "unavailable"),+);-export const authSessionRouteLayer = HttpRouter.add(- "GET",- "/api/auth/session",- Effect.gen(function* () {+export function annotateEnvironmentRequest(endpoint: string) {+ return Effect.gen(function* () {const request = yield* HttpServerRequest.HttpServerRequest;- const serverAuth = yield* ServerAuth;- const session = yield* serverAuth.getSessionState(request);- return HttpServerResponse.jsonUnsafe(session, {- status: 200,- headers: browserApiCorsHeaders,+ const url = HttpServerRequest.toURL(request);+ const traceId = yield* currentEnvironmentTraceId;++ yield* Effect.addFinalizer((exit) =>+ exit._tag === "Failure"+ ? Effect.logWarning("environment api request failed", {+ endpoint,+ traceId,+ errorTag: causeErrorTag(exit.cause),+ cause: exit.cause,+ })+ : Effect.void,+ );+ yield* Effect.annotateLogsScoped({ "environment.endpoint": endpoint, traceId });+ yield* Effect.annotateCurrentSpan({+ "environment.endpoint": endpoint,+ "http.request.method": request.method,+ "url.path": url._tag === "Some" ? url.value.pathname : "unknown",});- }),-);+ });+}-const PairingCredentialRequestHeaders = Schema.Struct({- "content-length": Schema.optionalKey(Schema.String),- "content-type": Schema.optionalKey(Schema.String),- "transfer-encoding": Schema.optionalKey(Schema.String),-});+export function failEnvironmentAuthInvalid(reason: EnvironmentAuthInvalidReason) {+ return currentEnvironmentTraceId.pipe(+ Effect.flatMap((traceId) =>+ Effect.fail(new EnvironmentAuthInvalidError({ code: "auth_invalid", reason, traceId })),+ ),+ );+}-function hasRequestBody(headers: typeof PairingCredentialRequestHeaders.Type) {- const contentLengthHeader = headers["content-length"];- if (typeof contentLengthHeader === "string") {- const contentLength = Number.parseInt(contentLengthHeader, 10);- if (Number.isFinite(contentLength)) {- return contentLength > 0;- }- }- return typeof headers["transfer-encoding"] === "string";+export function failEnvironmentInvalidRequest(reason: EnvironmentRequestInvalidReason) {+ return currentEnvironmentTraceId.pipe(+ Effect.flatMap((traceId) =>+ Effect.fail(new EnvironmentRequestInvalidError({ code: "invalid_request", reason, traceId })),+ ),+ );}-export const authBootstrapRouteLayer = HttpRouter.add(- "POST",- "/api/auth/bootstrap",- Effect.gen(function* () {- const request = yield* HttpServerRequest.HttpServerRequest;- const serverAuth = yield* ServerAuth;- const sessions = yield* SessionCredentialService;- const payload = yield* HttpServerRequest.schemaBodyJson(AuthBootstrapInput).pipe(- Effect.mapError(- (cause) =>- new AuthError({- message: "Invalid bootstrap payload.",- status: 400,- cause,- }),+export function failEnvironmentScopeRequired(requiredScope: AuthEnvironmentScope) {+ return currentEnvironmentTraceId.pipe(+ Effect.flatMap((traceId) =>+ Effect.fail(+ new EnvironmentScopeRequiredError({+ code: "insufficient_scope",+ requiredScope,+ traceId,+ }),),- );- const result = yield* serverAuth.exchangeBootstrapCredential(- payload.credential,- deriveAuthClientMetadata({ request }),- );-- return yield* HttpServerResponse.jsonUnsafe(result.response, {- status: 200,- headers: browserApiCorsHeaders,- }).pipe(- HttpServerResponse.setCookie(sessions.cookieName, result.sessionToken, {- expires: DateTime.toDate(result.response.expiresAt),- httpOnly: true,- path: "/",- sameSite: "lax",- }),- );- }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),-);+ ),+ );+}-export const authBearerBootstrapRouteLayer = HttpRouter.add(- "POST",- "/api/auth/bootstrap/bearer",- Effect.gen(function* () {- const request = yield* HttpServerRequest.HttpServerRequest;- const serverAuth = yield* ServerAuth;- const payload = yield* HttpServerRequest.schemaBodyJson(AuthBootstrapInput).pipe(- Effect.mapError(- (cause) =>- new AuthError({- message: "Invalid bootstrap payload.",- status: 400,- cause,- }),+function failEnvironmentOperationForbidden(reason: "current_session_revoke_not_allowed") {+ return currentEnvironmentTraceId.pipe(+ Effect.flatMap((traceId) =>+ Effect.fail(+ new EnvironmentOperationForbiddenError({+ code: "operation_forbidden",+ reason,+ traceId,+ }),),- );- const result = yield* serverAuth.exchangeBootstrapCredentialForBearerSession(- payload.credential,- deriveAuthClientMetadata({ request }),- );- return HttpServerResponse.jsonUnsafe(result satisfies AuthBearerBootstrapResult, {- status: 200,- headers: browserApiCorsHeaders,- });- }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),-);--export const authWebSocketTokenRouteLayer = HttpRouter.add(- "POST",- "/api/auth/ws-token",- Effect.gen(function* () {- const request = yield* HttpServerRequest.HttpServerRequest;- const serverAuth = yield* ServerAuth;- const session = yield* serverAuth.authenticateHttpRequest(request);- const result = yield* serverAuth.issueWebSocketToken(session);- return HttpServerResponse.jsonUnsafe(result satisfies AuthWebSocketTokenResult, {- status: 200,- headers: browserApiCorsHeaders,- });- }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),-);+ ),+ );+}-export const authPairingCredentialRouteLayer = HttpRouter.add(- "POST",- "/api/auth/pairing-token",- Effect.gen(function* () {- const serverAuth = yield* ServerAuth;- const request = yield* HttpServerRequest.HttpServerRequest;- const session = yield* serverAuth.authenticateHttpRequest(request);- if (session.role !== "owner") {- return yield* new AuthError({- message: "Only owner sessions can create pairing credentials.",- status: 403,+export function failEnvironmentInternal(reason: EnvironmentInternalErrorReason, error?: unknown) {+ return Effect.gen(function* () {+ const traceId = yield* currentEnvironmentTraceId;+ if (error !== undefined) {+ yield* Effect.logError("environment api operation failed", {+ reason,+ traceId,+ cause: error,});}- const headers = yield* HttpServerRequest.schemaHeaders(PairingCredentialRequestHeaders).pipe(- Effect.mapError(- (cause) =>- new AuthError({- message: "Invalid pairing credential request headers.",- status: 400,- cause,- }),- ),- );- const payload = hasRequestBody(headers)- ? yield* HttpServerRequest.schemaBodyJson(AuthCreatePairingCredentialInput).pipe(- Effect.mapError(- (cause) =>- new AuthError({- message: "Invalid pairing credential payload.",- status: 400,- cause,- }),- ),- )- : {};- const result = yield* serverAuth.issuePairingCredential(payload);- return HttpServerResponse.jsonUnsafe(result, { status: 200 });- }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),-);+ return yield* new EnvironmentInternalError({ code: "internal_error", reason, traceId });+ });+}-const authenticateOwnerSession = Effect.gen(function* () {- const request = yield* HttpServerRequest.HttpServerRequest;- const serverAuth = yield* ServerAuth;- const session = yield* serverAuth.authenticateHttpRequest(request);- if (session.role !== "owner") {- return yield* new AuthError({- message: "Only owner sessions can manage network access.",- status: 403,- });+export const requireEnvironmentScope = Effect.fn("environment.auth.requireScope")(function* (+ scope: AuthEnvironmentScope,+) {+ const session = yield* EnvironmentAuthenticatedPrincipal;+ if (!session.scopes.has(scope)) {+ return yield* failEnvironmentScopeRequired(scope);}- return { serverAuth, session } as const;+ return session;});-export const authPairingLinksRouteLayer = HttpRouter.add(- "GET",- "/api/auth/pairing-links",+export const environmentAuthenticatedAuthLayer = Layer.effect(+ EnvironmentAuthenticatedAuth,Effect.gen(function* () {- const { serverAuth } = yield* authenticateOwnerSession;- const pairingLinks = yield* serverAuth.listPairingLinks();- return HttpServerResponse.jsonUnsafe(pairingLinks, { status: 200 });- }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),-);--export const authPairingLinksRevokeRouteLayer = HttpRouter.add(- "POST",- "/api/auth/pairing-links/revoke",- Effect.gen(function* () {- const { serverAuth } = yield* authenticateOwnerSession;- const payload = yield* HttpServerRequest.schemaBodyJson(AuthRevokePairingLinkInput).pipe(- Effect.mapError(- (cause) =>- new AuthError({- message: "Invalid revoke pairing link payload.",- status: 400,- cause,+ const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;+ return (httpEffect) =>+ Effect.gen(function* () {+ const request = yield* HttpServerRequest.HttpServerRequest;+ const session = yield* serverAuth.authenticateHttpRequest(request).pipe(+ Effect.catchTags({+ ServerAuthInvalidCredentialError: (error) => failEnvironmentAuthInvalid(error.reason),+ ServerAuthInternalError: (error) => failEnvironmentInternal("internal_error", error),}),- ),- );- const revoked = yield* serverAuth.revokePairingLink(payload.id);- return HttpServerResponse.jsonUnsafe({ revoked }, { status: 200 });- }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),+ );+ return yield* httpEffect.pipe(+ Effect.provideService(EnvironmentAuthenticatedPrincipal, {+ ...session,+ scopes: new Set(session.scopes),+ }),+ );+ });+ }),);-export const authClientsRouteLayer = HttpRouter.add(- "GET",- "/api/auth/clients",- Effect.gen(function* () {- const { serverAuth, session } = yield* authenticateOwnerSession;- const clients = yield* serverAuth.listClientSessions(session.sessionId);- return HttpServerResponse.jsonUnsafe(clients, { status: 200 });- }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),-);+export const authHttpApiLayer = HttpApiBuilder.group(+ EnvironmentHttpApi,+ "auth",+ Effect.fnUntraced(function* (handlers) {+ const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;+ const sessions = yield* SessionStore.SessionStore;-export const authClientsRevokeRouteLayer = HttpRouter.add(- "POST",- "/api/auth/clients/revoke",- Effect.gen(function* () {- const { serverAuth, session } = yield* authenticateOwnerSession;- const payload = yield* HttpServerRequest.schemaBodyJson(AuthRevokeClientSessionInput).pipe(- Effect.mapError(- (cause) =>- new AuthError({- message: "Invalid revoke client payload.",- status: 400,- cause,- }),- ),- );- const revoked = yield* serverAuth.revokeClientSession(session.sessionId, payload.sessionId);- return HttpServerResponse.jsonUnsafe({ revoked }, { status: 200 });- }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),-);+ return handlers+ .handle(+ "session",+ Effect.fn("environment.auth.session")(+ function* (args) {+ yield* annotateEnvironmentRequest(args.endpoint.name);+ const request = yield* HttpServerRequest.HttpServerRequest;+ return yield* serverAuth.getSessionState(request);+ },+ Effect.catchTag("ServerAuthInternalError", (error) =>+ failEnvironmentInternal("internal_error", error),+ ),+ ),+ )+ .handle(+ "browserSession",+ Effect.fn("environment.auth.browserSession")(+ function* (args) {+ yield* annotateEnvironmentRequest(args.endpoint.name);+ const request = yield* HttpServerRequest.HttpServerRequest;+ const result = yield* serverAuth.createBrowserSession(+ args.payload.credential,+ deriveAuthClientMetadata({ request }),+ );+ const sessionCookies = yield* Effect.fromResult(+ Cookies.set(Cookies.empty, sessions.cookieName, result.sessionToken, {+ expires: DateTime.toDate(result.response.expiresAt),+ httpOnly: true,+ path: "/",+ sameSite: "lax",+ }),+ ).pipe(Effect.catch(() => failEnvironmentInternal("browser_session_cookie_failed")));-export const authClientsRevokeOthersRouteLayer = HttpRouter.add(- "POST",- "/api/auth/clients/revoke-others",- Effect.gen(function* () {- const { serverAuth, session } = yield* authenticateOwnerSession;- const revokedCount = yield* serverAuth.revokeOtherClientSessions(session.sessionId);- return HttpServerResponse.jsonUnsafe({ revokedCount }, { status: 200 });- }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),+ yield* HttpEffect.appendPreResponseHandler((_request, response) =>+ Effect.succeed(HttpServerResponse.mergeCookies(response, sessionCookies)),+ );+ return result.response;+ },+ Effect.catchTags({+ ServerAuthInvalidCredentialError: (error) => failEnvironmentAuthInvalid(error.reason),+ ServerAuthInternalError: (error) =>+ failEnvironmentInternal("browser_session_issuance_failed", error),+ }),+ ),+ )+ .handle(+ "token",+ Effect.fn("environment.auth.token")(+ function* (args) {+ yield* annotateEnvironmentRequest(args.endpoint.name);+ const request = yield* HttpServerRequest.HttpServerRequest;+ const requestedScopes =+ args.payload.scope === undefined+ ? undefined+ : parseAllowedOAuthScope({+ value: args.payload.scope,+ allowedScopes: new Set<AuthEnvironmentScope>([+ AuthOrchestrationReadScope,+ AuthOrchestrationOperateScope,+ AuthTerminalOperateScope,+ AuthReviewWriteScope,+ AuthAccessReadScope,+ AuthAccessWriteScope,+ AuthRelayReadScope,+ AuthRelayWriteScope,+ ]),+ });+ if (requestedScopes === null)+ return yield* failEnvironmentInvalidRequest("invalid_scope");+ return yield* serverAuth.exchangeBootstrapCredentialForAccessToken(+ args.payload.subject_token,+ requestedScopes,+ deriveAuthClientMetadata({+ request,+ presented: {+ ...(args.payload.client_label ? { label: args.payload.client_label } : {}),+ ...(args.payload.client_device_type+ ? { deviceType: args.payload.client_device_type }+ : {}),+ ...(args.payload.client_os ? { os: args.payload.client_os } : {}),+ },+ }),+ );+ },+ Effect.catchTags({+ ServerAuthInvalidCredentialError: (error) => failEnvironmentAuthInvalid(error.reason),+ ServerAuthInvalidRequestError: (error) => failEnvironmentInvalidRequest(error.reason),+ ServerAuthInternalError: (error) =>+ failEnvironmentInternal("access_token_issuance_failed", error),+ }),+ ),+ )+ .handle(+ "webSocketTicket",+ Effect.fn("environment.auth.webSocketTicket")(+ function* (args) {+ yield* annotateEnvironmentRequest(args.endpoint.name);+ const session = yield* EnvironmentAuthenticatedPrincipal;+ return yield* serverAuth.issueWebSocketTicket(session);+ },+ Effect.catchTag("ServerAuthInternalError", (error) =>+ failEnvironmentInternal("websocket_ticket_issuance_failed", error),+ ),+ ),+ )+ .handle(+ "pairingCredential",+ Effect.fn("environment.auth.pairingCredential")(+ function* (args) {+ yield* annotateEnvironmentRequest(args.endpoint.name);+ const session = yield* requireEnvironmentScope(AuthAccessWriteScope);+ const delegatedScopes = args.payload.scopes ?? AuthStandardClientScopes;+ if (+ delegatedScopes.length === 0 ||+ new Set<AuthEnvironmentScope>(delegatedScopes).size !== delegatedScopes.length+ ) {+ return yield* failEnvironmentInvalidRequest("invalid_scope");+ }+ for (const delegatedScope of delegatedScopes) {+ if (!session.scopes.has(delegatedScope)) {+ return yield* failEnvironmentScopeRequired(delegatedScope);+ }+ }+ return yield* serverAuth.issuePairingCredential(args.payload);+ },+ Effect.catchTag("ServerAuthInternalError", (error) =>+ failEnvironmentInternal("pairing_credential_issuance_failed", error),+ ),+ ),+ )+ .handle(+ "pairingLinks",+ Effect.fn("environment.auth.pairingLinks")(+ function* (args) {+ yield* annotateEnvironmentRequest(args.endpoint.name);+ yield* requireEnvironmentScope(AuthAccessReadScope);+ return yield* serverAuth.listPairingLinks();+ },+ Effect.catchTag("ServerAuthInternalError", (error) =>+ failEnvironmentInternal("pairing_links_load_failed", error),+ ),+ ),+ )+ .handle(+ "revokePairingLink",+ Effect.fn("environment.auth.revokePairingLink")(+ function* (args) {+ yield* annotateEnvironmentRequest(args.endpoint.name);+ yield* requireEnvironmentScope(AuthAccessWriteScope);+ const revoked = yield* serverAuth.revokePairingLink(args.payload.id);+ return { revoked };+ },+ Effect.catchTag("ServerAuthInternalError", (error) =>+ failEnvironmentInternal("pairing_link_revoke_failed", error),+ ),+ ),+ )+ .handle(+ "clients",+ Effect.fn("environment.auth.clients")(+ function* (args) {+ yield* annotateEnvironmentRequest(args.endpoint.name);+ const session = yield* requireEnvironmentScope(AuthAccessReadScope);+ return yield* serverAuth.listClientSessions(session.sessionId);+ },+ Effect.catchTag("ServerAuthInternalError", (error) =>+ failEnvironmentInternal("client_sessions_load_failed", error),+ ),+ ),+ )+ .handle(+ "revokeClient",+ Effect.fn("environment.auth.revokeClient")(+ function* (args) {+ yield* annotateEnvironmentRequest(args.endpoint.name);+ const session = yield* requireEnvironmentScope(AuthAccessWriteScope);+ const revoked = yield* serverAuth.revokeClientSession(+ session.sessionId,+ args.payload.sessionId,+ );+ return { revoked };+ },+ Effect.catchTags({+ ServerAuthForbiddenOperationError: (error) =>+ failEnvironmentOperationForbidden(error.reason),+ ServerAuthInternalError: (error) =>+ failEnvironmentInternal("client_session_revoke_failed", error),+ }),+ ),+ )+ .handle(+ "revokeOtherClients",+ Effect.fn("environment.auth.revokeOtherClients")(+ function* (args) {+ yield* annotateEnvironmentRequest(args.endpoint.name);+ const session = yield* requireEnvironmentScope(AuthAccessWriteScope);+ const revokedCount = yield* serverAuth.revokeOtherClientSessions(session.sessionId);+ return { revokedCount };+ },+ Effect.catchTag("ServerAuthInternalError", (error) =>+ failEnvironmentInternal("client_session_revoke_failed", error),+ ),+ ),+ );+ }),);diff --git a/apps/server/src/auth/utils.test.ts b/apps/server/src/auth/utils.test.tsindex e7a540d81..578c7f79a 100644--- a/apps/server/src/auth/utils.test.ts+++ b/apps/server/src/auth/utils.test.ts@@ -23,4 +23,32 @@ describe("deriveAuthClientMetadata", () => {os: "macOS",});});++ it("applies client-presented display identity without replacing transport metadata", () => {+ const metadata = deriveAuthClientMetadata({+ request: {+ headers: {+ "user-agent":+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 Chrome/136.0.7103.93 Electron/36.3.2 Safari/537.36",+ },+ source: {+ remoteAddress: "::ffff:192.168.213.72",+ },+ } as never,+ presented: {+ label: "T3 Code Mobile",+ deviceType: "mobile",+ os: "iOS",+ },+ });++ expect(metadata).toMatchObject({+ label: "T3 Code Mobile",+ browser: "Electron",+ deviceType: "mobile",+ ipAddress: "192.168.213.72",+ os: "iOS",+ });+ expect(metadata.userAgent).toContain("Electron/36.3.2");+ });});diff --git a/apps/server/src/auth/utils.ts b/apps/server/src/auth/utils.tsindex 2c76a81f6..26b4ae4c4 100644--- a/apps/server/src/auth/utils.ts+++ b/apps/server/src/auth/utils.ts@@ -1,4 +1,8 @@-import type { AuthClientMetadata, AuthClientMetadataDeviceType } from "@t3tools/contracts";+import type {+ AuthClientMetadata,+ AuthClientMetadataDeviceType,+ AuthClientPresentationMetadata,+} from "@t3tools/contracts";import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";import * as Crypto from "node:crypto";@@ -115,17 +119,17 @@ function readRemoteAddressFromSource(source: unknown): string | undefined {export function deriveAuthClientMetadata(input: {readonly request: HttpServerRequest.HttpServerRequest;- readonly label?: string;+ readonly presented?: AuthClientPresentationMetadata;}): AuthClientMetadata {const userAgent = normalizeNonEmptyString(input.request.headers["user-agent"]);const ipAddress = readRemoteAddressFromSource(input.request.source);- const os = inferOs(userAgent);+ const os = input.presented?.os ?? inferOs(userAgent);const browser = inferBrowser(userAgent);return {- ...(input.label ? { label: input.label } : {}),+ ...(input.presented?.label ? { label: input.presented.label } : {}),...(ipAddress ? { ipAddress } : {}),...(userAgent ? { userAgent } : {}),- deviceType: inferDeviceType(userAgent),+ deviceType: input.presented?.deviceType ?? inferDeviceType(userAgent),...(os ? { os } : {}),...(browser ? { browser } : {}),};diff --git a/apps/server/src/bin.test.ts b/apps/server/src/bin.test.tsindex fbf6d80c5..2cd8bb68c 100644--- a/apps/server/src/bin.test.ts+++ b/apps/server/src/bin.test.ts@@ -6,12 +6,15 @@ import { join } from "node:path";import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";import * as NodeServices from "@effect/platform-node/NodeServices";+import { EnvironmentOrchestrationHttpApi } from "@t3tools/contracts";import * as NetService from "@t3tools/shared/Net";import { assert, it } from "@effect/vitest";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import * as HttpRouter from "effect/unstable/http/HttpRouter";import * as HttpServer from "effect/unstable/http/HttpServer";+import * as HttpApi from "effect/unstable/httpapi/HttpApi";+import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";import * as CliError from "effect/unstable/cli/CliError";import * as TestConsole from "effect/testing/TestConsole";import { Command } from "effect/unstable/cli";@@ -20,10 +23,7 @@ import { cli } from "./bin.ts";import { deriveServerPaths, ServerConfig, type ServerConfigShape } from "./config.ts";import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";-import {- orchestrationDispatchRouteLayer,- orchestrationSnapshotRouteLayer,-} from "./orchestration/http.ts";+import { orchestrationHttpApiLayer } from "./orchestration/http.ts";import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";import { RepositoryIdentityResolverLive } from "./project/Layers/RepositoryIdentityResolver.ts";import {@@ -31,10 +31,12 @@ import {persistServerRuntimeState,} from "./serverRuntimeState.ts";import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts";-import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";-import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts";+import * as ServerSecretStore from "./auth/ServerSecretStore.ts";+import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";+import { environmentAuthenticatedAuthLayer } from "./auth/http.ts";const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);+class ProjectCliHttpApi extends HttpApi.make("environment").add(EnvironmentOrchestrationHttpApi) {}const runCli = (args: ReadonlyArray<string>) => Command.runWith(cli, { version: "0.0.0" })(args);const runCliWithRuntime = (args: ReadonlyArray<string>) =>@@ -105,18 +107,18 @@ const readPersistedSnapshot = (baseDir: string) =>const withLiveProjectCliServer = <A, E, R>(baseDir: string, run: () => Effect.Effect<A, E, R>) =>Effect.gen(function* () {const config = yield* makeCliTestServerConfig(baseDir);- const routesLayer = Layer.mergeAll(- orchestrationSnapshotRouteLayer,- orchestrationDispatchRouteLayer,+ const routesLayer = HttpApiBuilder.layer(ProjectCliHttpApi).pipe(+ Layer.provide(orchestrationHttpApiLayer),+ Layer.provide(environmentAuthenticatedAuthLayer),);const appLayer = HttpRouter.serve(routesLayer, {disableListenLog: true,disableLogger: true,}).pipe(Layer.provideMerge(- ServerAuthLive.pipe(+ EnvironmentAuth.layer.pipe(Layer.provideMerge(SqlitePersistenceLayerLive),- Layer.provide(ServerSecretStoreLive),+ Layer.provide(ServerSecretStore.layer),),),Layer.provideMerge(makeProjectPersistenceLayer(config)),@@ -214,7 +216,7 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {const issued = JSON.parse(issuedOutput.output) as {readonly sessionId: string;readonly token: string;- readonly role: string;+ readonly scopes: ReadonlyArray<string>;};const listedOutput = yield* captureStdout(runCli(["auth", "session", "list", "--base-dir", baseDir, "--json"]),@@ -223,15 +225,33 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {const listed = JSON.parse(listedOutput.output) as ReadonlyArray<{readonly sessionId: string;readonly token?: string;- readonly role: string;+ readonly scopes: ReadonlyArray<string>;}>;assert.equal(typeof issued.sessionId, "string");assert.equal(typeof issued.token, "string");- assert.equal(issued.role, "owner");+ assert.deepEqual(issued.scopes, [+ "orchestration:read",+ "orchestration:operate",+ "terminal:operate",+ "review:write",+ "relay:read",+ "access:read",+ "access:write",+ "relay:write",+ ]);assert.equal(listed.length, 1);assert.equal(listed[0]?.sessionId, issued.sessionId);- assert.equal(listed[0]?.role, "owner");+ assert.deepEqual(listed[0]?.scopes, [+ "orchestration:read",+ "orchestration:operate",+ "terminal:operate",+ "review:write",+ "relay:read",+ "access:read",+ "access:write",+ "relay:write",+ ]);assert.equal("token" in (listed[0] ?? {}), false);}),);diff --git a/apps/server/src/cli/auth.ts b/apps/server/src/cli/auth.tsindex d54731b4a..4f1fc4887 100644--- a/apps/server/src/cli/auth.ts+++ b/apps/server/src/cli/auth.ts@@ -1,4 +1,8 @@-import { AuthSessionId } from "@t3tools/contracts";+import {+ AuthAdministrativeScopes,+ AuthSessionId,+ AuthStandardClientScopes,+} from "@t3tools/contracts";import * as Console from "effect/Console";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";@@ -6,9 +10,8 @@ import * as Option from "effect/Option";import * as References from "effect/References";import { Argument, Command, Flag, GlobalFlag } from "effect/unstable/cli";-import { AuthControlPlaneRuntimeLive } from "../auth/Layers/AuthControlPlane.ts";-import { AuthControlPlane } from "../auth/Services/AuthControlPlane.ts";-import type { AuthControlPlaneShape } from "../auth/Services/AuthControlPlane.ts";+import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";+import {formatIssuedPairingCredential,formatIssuedSession,@@ -23,9 +26,9 @@ import {resolveCliAuthConfig,} from "./config.ts";-const runWithAuthControlPlane = <A, E>(+const runWithEnvironmentAuth = <A, E>(flags: CliAuthLocationFlags,- run: (authControlPlane: AuthControlPlaneShape) => Effect.Effect<A, E>,+ run: (environmentAuth: EnvironmentAuth.EnvironmentAuthShape) => Effect.Effect<A, E>,options?: {readonly quietLogs?: boolean;},@@ -35,11 +38,11 @@ const runWithAuthControlPlane = <A, E>(const config = yield* resolveCliAuthConfig(flags, logLevel);const minimumLogLevel = options?.quietLogs ? "Error" : config.logLevel;return yield* Effect.gen(function* () {- const authControlPlane = yield* AuthControlPlane;- return yield* run(authControlPlane);+ const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;+ return yield* run(environmentAuth);}).pipe(Effect.provide(- Layer.mergeAll(AuthControlPlaneRuntimeLive).pipe(+ Layer.mergeAll(EnvironmentAuth.runtimeLayer).pipe(Layer.provide(Layer.succeed(ServerConfig, config)),Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),),@@ -58,11 +61,6 @@ const jsonFlag = Flag.boolean("json").pipe(Flag.withDefault(false),);-const sessionRoleFlag = Flag.choice("role", ["owner", "client"]).pipe(- Flag.withDescription("Role for the issued bearer session."),- Flag.withDefault("owner"),-);-const labelFlag = Flag.string("label").pipe(Flag.withDescription("Optional human-readable label."),Flag.optional,@@ -92,12 +90,12 @@ const pairingCreateCommand = Command.make("create", {}).pipe(Command.withDescription("Issue a new client pairing token."),Command.withHandler((flags) =>- runWithAuthControlPlane(+ runWithEnvironmentAuth(flags,- (authControlPlane) =>+ (environmentAuth) =>Effect.gen(function* () {- const issued = yield* authControlPlane.createPairingLink({- role: "client",+ const issued = yield* environmentAuth.createPairingLink({+ scopes: AuthStandardClientScopes,subject: "one-time-token",...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}),...(Option.isSome(flags.label) ? { label: flags.label.value } : {}),@@ -121,11 +119,13 @@ const pairingListCommand = Command.make("list", {}).pipe(Command.withDescription("List active client pairing tokens without revealing their secrets."),Command.withHandler((flags) =>- runWithAuthControlPlane(+ runWithEnvironmentAuth(flags,- (authControlPlane) =>+ (environmentAuth) =>Effect.gen(function* () {- const pairingLinks = yield* authControlPlane.listPairingLinks({ role: "client" });+ const pairingLinks = yield* environmentAuth.listPairingLinks({+ excludeSubjects: [EnvironmentAuth.INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT],+ });yield* Console.log(formatPairingCredentialList(pairingLinks, { json: flags.json }));}),{@@ -141,9 +141,9 @@ const pairingRevokeCommand = Command.make("revoke", {}).pipe(Command.withDescription("Revoke an active client pairing token."),Command.withHandler((flags) =>- runWithAuthControlPlane(flags, (authControlPlane) =>+ runWithEnvironmentAuth(flags, (environmentAuth) =>Effect.gen(function* () {- const revoked = yield* authControlPlane.revokePairingLink(flags.id);+ const revoked = yield* environmentAuth.revokePairingLink(flags.id);yield* Console.log(revoked? `Revoked pairing credential ${flags.id}.\n`@@ -162,20 +162,19 @@ const pairingCommand = Command.make("pairing").pipe(const sessionIssueCommand = Command.make("issue", {...authLocationFlags,ttl: ttlFlag,- role: sessionRoleFlag,label: labelFlag,subject: subjectFlag,tokenOnly: tokenOnlyFlag,json: jsonFlag,}).pipe(- Command.withDescription("Issue a bearer session token for headless or remote clients."),+ Command.withDescription("Issue a scoped bearer access token for headless or remote clients."),Command.withHandler((flags) =>- runWithAuthControlPlane(+ runWithEnvironmentAuth(flags,- (authControlPlane) =>+ (environmentAuth) =>Effect.gen(function* () {- const issued = yield* authControlPlane.issueSession({- role: flags.role,+ const issued = yield* environmentAuth.issueSession({+ scopes: AuthAdministrativeScopes,...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}),...(Option.isSome(flags.label) ? { label: flags.label.value } : {}),...(Option.isSome(flags.subject) ? { subject: flags.subject.value } : {}),@@ -200,11 +199,11 @@ const sessionListCommand = Command.make("list", {}).pipe(Command.withDescription("List active sessions without revealing bearer tokens."),Command.withHandler((flags) =>- runWithAuthControlPlane(+ runWithEnvironmentAuth(flags,- (authControlPlane) =>+ (environmentAuth) =>Effect.gen(function* () {- const sessions = yield* authControlPlane.listSessions();+ const sessions = yield* environmentAuth.listSessions();yield* Console.log(formatSessionList(sessions, { json: flags.json }));}),{@@ -223,9 +222,9 @@ const sessionRevokeCommand = Command.make("revoke", {}).pipe(Command.withDescription("Revoke an active session."),Command.withHandler((flags) =>- runWithAuthControlPlane(flags, (authControlPlane) =>+ runWithEnvironmentAuth(flags, (environmentAuth) =>Effect.gen(function* () {- const revoked = yield* authControlPlane.revokeSession(flags.sessionId);+ const revoked = yield* environmentAuth.revokeSession(flags.sessionId);yield* Console.log(revoked? `Revoked session ${flags.sessionId}.\n`diff --git a/apps/server/src/cli/project.ts b/apps/server/src/cli/project.tsindex 05e96160c..95e9ed7f3 100644--- a/apps/server/src/cli/project.ts+++ b/apps/server/src/cli/project.ts@@ -1,6 +1,9 @@import {CommandId,- OrchestrationReadModel,+ AuthAdministrativeScopes,+ EnvironmentHttpApi,+ EnvironmentHttpCommonError,+ type OrchestrationReadModel,ProjectId,type ClientOrchestrationCommand,} from "@t3tools/contracts";@@ -18,16 +21,11 @@ import * as Path from "effect/Path";import * as References from "effect/References";import * as Schema from "effect/Schema";import { Argument, Command, Flag, GlobalFlag } from "effect/unstable/cli";-import {- FetchHttpClient,- HttpClient,- HttpClientRequest,- HttpClientResponse,-} from "effect/unstable/http";--import { AuthControlPlaneRuntimeLive } from "../auth/Layers/AuthControlPlane.ts";-import { AuthControlPlane } from "../auth/Services/AuthControlPlane.ts";-import type { AuthControlPlaneShape } from "../auth/Services/AuthControlPlane.ts";+import { FetchHttpClient, HttpClient, HttpClientError } from "effect/unstable/http";+import * as HttpApiClient from "effect/unstable/httpapi/HttpApiClient";++import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";+import { ServerConfig, type ServerConfigShape } from "../config.ts";import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts";import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts";@@ -78,50 +76,53 @@ const ProjectCliRuntimeLive = Layer.mergeAll();const PROJECT_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(1);-const OrchestrationHttpErrorResponse = Schema.Struct({- error: Schema.String,-});-+const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);const withProjectCliSessionToken = <A, E, R>(- authControlPlane: AuthControlPlaneShape,+ environmentAuth: EnvironmentAuth.EnvironmentAuthShape,run: (token: string) => Effect.Effect<A, E, R>,) =>Effect.acquireUseRelease(- authControlPlane.issueSession({- role: "owner",+ environmentAuth.issueSession({+ scopes: AuthAdministrativeScopes,label: "t3 project cli",}),(issued) => run(issued.token),- (issued) => authControlPlane.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),+ (issued) => environmentAuth.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),);const withProjectCliLiveServerTimeout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>effect.pipe(Effect.timeout(PROJECT_CLI_LIVE_SERVER_TIMEOUT));-const runLiveServerRequest = <A, E extends Error, R>(- request: HttpClientRequest.HttpClientRequest,- handle: (response: HttpClientResponse.HttpClientResponse) => Effect.Effect<A, E, R>,-) =>- Effect.gen(function* () {- const httpClient = yield* HttpClient.HttpClient;- const response = yield* httpClient.execute(request);- return yield* handle(response);- }).pipe(withProjectCliLiveServerTimeout);--const decodeOrchestrationReadModelResponse = (response: HttpClientResponse.HttpClientResponse) =>- HttpClientResponse.schemaBodyJson(OrchestrationReadModel)(response);--const readErrorMessageFromResponse = (response: HttpClientResponse.HttpClientResponse) =>- HttpClientResponse.schemaBodyJson(OrchestrationHttpErrorResponse)(response).pipe(- Effect.map((body) => body.error),- Effect.catch(() => Effect.succeed(null)),- Effect.map((body) => {- if (typeof body === "string" && body.trim().length > 0) {- return body;- }- return `Server request failed with status ${response.status}.`;+const failLiveServerRequest = (cause: unknown) => {+ if (isEnvironmentHttpCommonError(cause)) {+ return Effect.fail(+ new ProjectCommandError({+ message: `Server request failed (${cause.code}, trace ${cause.traceId}).`,+ }),+ );+ }+ if (HttpClientError.isHttpClientError(cause) && cause.response !== undefined) {+ return Effect.fail(+ new ProjectCommandError({+ message: `Server request failed with undeclared status ${cause.response.status}.`,+ }),+ );+ }+ return Effect.fail(+ new ProjectCommandError({+ message: `Failed to call running server: ${String(cause)}.`,}),);+};++const makeLiveServerClient = (origin: string) =>+ Effect.gen(function* () {+ const httpClient = yield* HttpClient.HttpClient;+ return yield* HttpApiClient.makeWith(EnvironmentHttpApi, {+ baseUrl: origin,+ httpClient,+ });+ });const normalizeWorkspaceRootForProjectCommand = Effect.fn("normalizeWorkspaceRootForProjectCommand",@@ -193,42 +194,25 @@ const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (});const fetchLiveOrchestrationSnapshot = (origin: string, bearerToken: string) =>- runLiveServerRequest(- HttpClientRequest.get(`${origin}/api/orchestration/snapshot`).pipe(- HttpClientRequest.acceptJson,- HttpClientRequest.bearerToken(bearerToken),- ),- HttpClientResponse.matchStatus({- "2xx": decodeOrchestrationReadModelResponse,- orElse: (response) =>- readErrorMessageFromResponse(response).pipe(- Effect.flatMap((message) => Effect.fail(new ProjectCommandError({ message }))),- ),- }),- );+ Effect.gen(function* () {+ const client = yield* makeLiveServerClient(origin);+ return yield* client.orchestration.snapshot({+ headers: { authorization: `Bearer ${bearerToken}` },+ });+ }).pipe(withProjectCliLiveServerTimeout, Effect.catch(failLiveServerRequest));const dispatchLiveOrchestrationCommand = (origin: string,bearerToken: string,command: ProjectCliDispatchCommand,) =>- HttpClientRequest.post(`${origin}/api/orchestration/dispatch`).pipe(- HttpClientRequest.acceptJson,- HttpClientRequest.bearerToken(bearerToken),- HttpClientRequest.bodyJson(command),- Effect.flatMap((request) =>- runLiveServerRequest(- request,- HttpClientResponse.matchStatus({- "2xx": () => Effect.void,- orElse: (response) =>- readErrorMessageFromResponse(response).pipe(- Effect.flatMap((message) => Effect.fail(new ProjectCommandError({ message }))),- ),- }),- ),- ),- );+ Effect.gen(function* () {+ const client = yield* makeLiveServerClient(origin);+ yield* client.orchestration.dispatch({+ headers: { authorization: `Bearer ${bearerToken}` },+ payload: command,+ } as Parameters<typeof client.orchestration.dispatch>[0]);+ }).pipe(withProjectCliLiveServerTimeout, Effect.catch(failLiveServerRequest));const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;@@ -236,13 +220,13 @@ const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {});const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecutionMode")(- function* (authControlPlane: AuthControlPlaneShape, config: ServerConfigShape) {+ function* (environmentAuth: EnvironmentAuth.EnvironmentAuthShape, config: ServerConfigShape) {const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);if (Option.isNone(runtimeState)) {return Option.none<{ readonly origin: string }>();}- const attempt = withProjectCliSessionToken(authControlPlane, (token) =>+ const attempt = withProjectCliSessionToken(environmentAuth, (token) =>fetchLiveOrchestrationSnapshot(runtimeState.value.origin, token).pipe(Effect.as({origin: runtimeState.value.origin,@@ -279,11 +263,11 @@ const runProjectMutation = Effect.fn("runProjectMutation")(function* (const minimumLogLevel = config.logLevel;return yield* Effect.gen(function* () {- const authControlPlane = yield* AuthControlPlane;- const liveMode = yield* tryResolveLiveProjectExecutionMode(authControlPlane, config);+ const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;+ const liveMode = yield* tryResolveLiveProjectExecutionMode(environmentAuth, config);if (Option.isSome(liveMode)) {- return yield* withProjectCliSessionToken(authControlPlane, (token) =>+ return yield* withProjectCliSessionToken(environmentAuth, (token) =>Effect.gen(function* () {const snapshot = yield* fetchLiveOrchestrationSnapshot(liveMode.value.origin, token);const output = yield* run({@@ -314,7 +298,7 @@ const runProjectMutation = Effect.fn("runProjectMutation")(function* (}).pipe(Effect.provide(offlineRuntimeLayer));}).pipe(Effect.provide(- Layer.mergeAll(AuthControlPlaneRuntimeLive, WorkspacePathsLive).pipe(+ Layer.mergeAll(EnvironmentAuth.runtimeLayer, WorkspacePathsLive).pipe(Layer.provideMerge(FetchHttpClient.layer),Layer.provide(Layer.succeed(ServerConfig, config)),Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),diff --git a/apps/server/src/cliAuthFormat.test.ts b/apps/server/src/cliAuthFormat.test.tsindex 3ffaf6fba..a428adc7b 100644--- a/apps/server/src/cliAuthFormat.test.ts+++ b/apps/server/src/cliAuthFormat.test.ts@@ -13,7 +13,7 @@ it("formats issued pairing credentials with the secret and optional pair URL", ({id: "pairing-1",credential: "secret-pairing-token",- role: "client",+ scopes: ["orchestration:read"],subject: "one-time-token",createdAt: DateTime.makeUnsafe("2026-04-08T09:00:00.000Z"),expiresAt: DateTime.makeUnsafe("2026-04-08T10:00:00.000Z"),@@ -33,7 +33,7 @@ it("formats pairing listings without exposing the secret token", () => {credential: "secret-pairing-token",subject: "one-time-token",label: "Phone",- role: "client",+ scopes: ["orchestration:read"],createdAt: DateTime.makeUnsafe("2026-04-08T09:00:00.000Z"),expiresAt: DateTime.makeUnsafe("2026-04-08T10:00:00.000Z"),},@@ -50,8 +50,8 @@ it("formats issued sessions with the bearer token but omits tokens from listings{sessionId: "session-1" as never,token: "secret-session-token",- method: "bearer-session-token",- role: "owner",+ method: "bearer-access-token",+ scopes: ["orchestration:read", "access:write"],subject: "cli-issued-session",client: {label: "deploy-bot",@@ -66,8 +66,8 @@ it("formats issued sessions with the bearer token but omits tokens from listings[{sessionId: "session-1" as never,- method: "bearer-session-token",- role: "owner",+ method: "bearer-access-token",+ scopes: ["orchestration:read", "access:write"],subject: "cli-issued-session",client: {label: "deploy-bot",diff --git a/apps/server/src/cliAuthFormat.ts b/apps/server/src/cliAuthFormat.tsindex 4078860ff..2ef5ba10a 100644--- a/apps/server/src/cliAuthFormat.ts+++ b/apps/server/src/cliAuthFormat.ts@@ -1,7 +1,7 @@import type { AuthClientMetadata, AuthClientSession, AuthPairingLink } from "@t3tools/contracts";import * as DateTime from "effect/DateTime";-import type { IssuedBearerSession, IssuedPairingLink } from "./auth/Services/AuthControlPlane.ts";+import type { IssuedBearerSession, IssuedPairingLink } from "./auth/EnvironmentAuth.ts";const newline = "\n";@@ -47,7 +47,7 @@ export function formatIssuedPairingCredential(id: credential.id,credential: credential.credential,...(credential.label ? { label: credential.label } : {}),- role: credential.role,+ scopes: credential.scopes,expiresAt: toIsoString(credential.expiresAt),...(pairUrl ? { pairUrl } : {}),},@@ -77,7 +77,7 @@ export function formatPairingCredentialList(credentials.map((credential) => ({id: credential.id,...(credential.label ? { label: credential.label } : {}),- role: credential.role,+ scopes: credential.scopes,createdAt: toIsoString(credential.createdAt),expiresAt: toIsoString(credential.expiresAt),})),@@ -95,7 +95,7 @@ export function formatPairingCredentialList(.map((credential) =>[`${credential.id}${credential.label ? ` (${credential.label})` : ""}`,- ` role: ${credential.role}`,+ ` scopes: ${credential.scopes.join(" ")}`,` created: ${toIsoString(credential.createdAt)}`,` expires: ${toIsoString(credential.expiresAt)}`,].join(newline),@@ -121,7 +121,7 @@ export function formatIssuedSession(sessionId: session.sessionId,token: session.token,method: session.method,- role: session.role,+ scopes: session.scopes,subject: session.subject,client: session.client,expiresAt: toIsoString(session.expiresAt),@@ -133,7 +133,8 @@ export function formatIssuedSession(return ([- `Issued ${session.role} bearer session ${session.sessionId}.`,+ `Issued bearer access token ${session.sessionId}.`,+ `Scopes: ${session.scopes.join(" ")}`,`Token: ${session.token}`,`Subject: ${session.subject}`,`Client: ${formatClientMetadata(session.client)}`,@@ -153,7 +154,7 @@ export function formatSessionList(sessions.map((session) => ({sessionId: session.sessionId,method: session.method,- role: session.role,+ scopes: session.scopes,subject: session.subject,client: session.client,connected: session.connected,@@ -174,7 +175,8 @@ export function formatSessionList(sessions.map((session) =>[- `${session.sessionId} [${session.role}]${session.connected ? " connected" : ""}`,+ `${session.sessionId}${session.connected ? " connected" : ""}`,+ ` scopes: ${session.scopes.join(" ")}`,` method: ${session.method}`,` subject: ${session.subject}`,` client: ${formatClientMetadata(session.client)}`,diff --git a/apps/server/src/http.ts b/apps/server/src/http.tsindex f287b4c59..0e521ecca 100644--- a/apps/server/src/http.ts+++ b/apps/server/src/http.ts@@ -1,4 +1,9 @@import Mime from "@effect/platform-node/Mime";+import {+ AuthOrchestrationOperateScope,+ AuthOrchestrationReadScope,+ EnvironmentHttpApi,+} from "@t3tools/contracts";import { decodeOtlpTraceRecords } from "@t3tools/shared/observability";import * as Data from "effect/Data";import * as Effect from "effect/Effect";@@ -13,7 +18,9 @@ import {HttpRouter,HttpServerResponse,HttpServerRequest,+ HttpServerRespondable,} from "effect/unstable/http";+import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";import { OtlpTracer } from "effect/unstable/observability";import {@@ -25,14 +32,15 @@ import { resolveAttachmentPathById } from "./attachmentStore.ts";import { resolveStaticDir, ServerConfig } from "./config.ts";import { BrowserTraceCollector } from "./observability/Services/BrowserTraceCollector.ts";import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver.ts";-import { ServerAuth } from "./auth/Services/ServerAuth.ts";-import { respondToAuthError } from "./auth/http.ts";-import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";+import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";import {- browserApiCorsAllowedHeaders,- browserApiCorsAllowedMethods,- browserApiCorsHeaders,-} from "./httpCors.ts";+ annotateEnvironmentRequest,+ failEnvironmentScopeRequired,+ failEnvironmentAuthInvalid,+ failEnvironmentInternal,+} from "./auth/http.ts";+import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";+import { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods } from "./httpCors.ts";const PROJECT_FAVICON_CACHE_CONTROL = "public, max-age=3600";const FALLBACK_PROJECT_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></svg>`;@@ -40,8 +48,8 @@ const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);export const browserApiCorsLayer = HttpRouter.cors({- allowedMethods: [...browserApiCorsAllowedMethods],- allowedHeaders: [...browserApiCorsAllowedHeaders],+ allowedMethods: browserApiCorsAllowedMethods,+ allowedHeaders: browserApiCorsAllowedHeaders,maxAge: 600,});@@ -61,23 +69,35 @@ export function resolveDevRedirectUrl(devUrl: URL, requestUrl: URL): string {return redirectUrl.toString();}-const requireAuthenticatedRequest = Effect.gen(function* () {- const request = yield* HttpServerRequest.HttpServerRequest;- const serverAuth = yield* ServerAuth;- yield* serverAuth.authenticateHttpRequest(request);-});--export const serverEnvironmentRouteLayer = HttpRouter.add(- "GET",- "/.well-known/t3/environment",+const authenticateRawRouteWithScope = (+ scope: typeof AuthOrchestrationReadScope | typeof AuthOrchestrationOperateScope,+) =>Effect.gen(function* () {- const descriptor = yield* Effect.service(ServerEnvironment).pipe(- Effect.flatMap((serverEnvironment) => serverEnvironment.getDescriptor),+ const request = yield* HttpServerRequest.HttpServerRequest;+ const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;+ const session = yield* serverAuth.authenticateHttpRequest(request).pipe(+ Effect.catchTags({+ ServerAuthInvalidCredentialError: (error) => failEnvironmentAuthInvalid(error.reason),+ ServerAuthInternalError: (error) => failEnvironmentInternal("internal_error", error),+ }),+ );+ if (!session.scopes.includes(scope)) {+ return yield* failEnvironmentScopeRequired(scope);+ }+ });++export const serverEnvironmentHttpApiLayer = HttpApiBuilder.group(+ EnvironmentHttpApi,+ "metadata",+ Effect.fnUntraced(function* (handlers) {+ const serverEnvironment = yield* ServerEnvironment;+ return handlers.handle(+ "descriptor",+ Effect.fn("environment.metadata.descriptor")(function* (args) {+ yield* annotateEnvironmentRequest(args.endpoint.name);+ return yield* serverEnvironment.getDescriptor;+ }),);- return HttpServerResponse.jsonUnsafe(descriptor, {- status: 200,- headers: browserApiCorsHeaders,- });}),);@@ -90,7 +110,7 @@ export const otlpTracesProxyRouteLayer = HttpRouter.add("POST",OTLP_TRACES_PROXY_PATH,Effect.gen(function* () {- yield* requireAuthenticatedRequest;+ yield* authenticateRawRouteWithScope(AuthOrchestrationOperateScope);const request = yield* HttpServerRequest.HttpServerRequest;const config = yield* ServerConfig;const otlpTracesUrl = config.otlpTracesUrl;@@ -132,14 +152,20 @@ export const otlpTracesProxyRouteLayer = HttpRouter.add(Effect.succeed(HttpServerResponse.text("Trace export failed.", { status: 502 })),),);- }).pipe(Effect.catchTag("AuthError", respondToAuthError)),+ }).pipe(+ Effect.catchTags({+ EnvironmentAuthInvalidError: HttpServerRespondable.toResponse,+ EnvironmentInternalError: HttpServerRespondable.toResponse,+ EnvironmentScopeRequiredError: HttpServerRespondable.toResponse,+ }),+ ),);export const attachmentsRouteLayer = HttpRouter.add("GET",`${ATTACHMENTS_ROUTE_PREFIX}/*`,Effect.gen(function* () {- yield* requireAuthenticatedRequest;+ yield* authenticateRawRouteWithScope(AuthOrchestrationReadScope);const request = yield* HttpServerRequest.HttpServerRequest;const url = HttpServerRequest.toURL(request);if (Option.isNone(url)) {@@ -188,14 +214,20 @@ export const attachmentsRouteLayer = HttpRouter.add(Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),),);- }).pipe(Effect.catchTag("AuthError", respondToAuthError)),+ }).pipe(+ Effect.catchTags({+ EnvironmentAuthInvalidError: HttpServerRespondable.toResponse,+ EnvironmentInternalError: HttpServerRespondable.toResponse,+ EnvironmentScopeRequiredError: HttpServerRespondable.toResponse,+ }),+ ),);export const projectFaviconRouteLayer = HttpRouter.add("GET","/api/project-favicon",Effect.gen(function* () {- yield* requireAuthenticatedRequest;+ yield* authenticateRawRouteWithScope(AuthOrchestrationReadScope);const request = yield* HttpServerRequest.HttpServerRequest;const url = HttpServerRequest.toURL(request);if (Option.isNone(url)) {@@ -229,7 +261,13 @@ export const projectFaviconRouteLayer = HttpRouter.add(Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),),);- }).pipe(Effect.catchTag("AuthError", respondToAuthError)),+ }).pipe(+ Effect.catchTags({+ EnvironmentAuthInvalidError: HttpServerRespondable.toResponse,+ EnvironmentInternalError: HttpServerRespondable.toResponse,+ EnvironmentScopeRequiredError: HttpServerRespondable.toResponse,+ }),+ ),);export const staticAndDevRouteLayer = HttpRouter.add(diff --git a/apps/server/src/orchestration/http.ts b/apps/server/src/orchestration/http.tsindex aaf3a3a10..a148f9847 100644--- a/apps/server/src/orchestration/http.ts+++ b/apps/server/src/orchestration/http.ts@@ -1,95 +1,59 @@import {- ClientOrchestrationCommand,- OrchestrationDispatchCommandError,- OrchestrationGetSnapshotError,- type OrchestrationReadModel,+ AuthOrchestrationOperateScope,+ AuthOrchestrationReadScope,+ EnvironmentHttpApi,} from "@t3tools/contracts";import * as Effect from "effect/Effect";-import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";+import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";-import { ServerAuth } from "../auth/Services/ServerAuth.ts";import { normalizeDispatchCommand } from "./Normalizer.ts";+import {+ annotateEnvironmentRequest,+ failEnvironmentInternal,+ failEnvironmentInvalidRequest,+ requireEnvironmentScope,+} from "../auth/http.ts";import { OrchestrationEngineService } from "./Services/OrchestrationEngine.ts";import { ProjectionSnapshotQuery } from "./Services/ProjectionSnapshotQuery.ts";-const respondToOrchestrationHttpError = (- error: OrchestrationDispatchCommandError | OrchestrationGetSnapshotError,-) =>- Effect.gen(function* () {- if (error._tag === "OrchestrationGetSnapshotError") {- yield* Effect.logError("orchestration http route failed", {- message: error.message,- cause: error.cause,- });- return HttpServerResponse.jsonUnsafe({ error: error.message }, { status: 500 });- }-- return HttpServerResponse.jsonUnsafe({ error: error.message }, { status: 400 });- });--const authenticateOwnerSession = Effect.gen(function* () {- const request = yield* HttpServerRequest.HttpServerRequest;- const serverAuth = yield* ServerAuth;- const session = yield* serverAuth.authenticateHttpRequest(request);- if (session.role !== "owner") {- return yield* new OrchestrationDispatchCommandError({- message: "Only owner sessions can manage projects.",- });- }- return session;-});--export const orchestrationSnapshotRouteLayer = HttpRouter.add(- "GET",- "/api/orchestration/snapshot",- Effect.gen(function* () {- yield* authenticateOwnerSession;+export const orchestrationHttpApiLayer = HttpApiBuilder.group(+ EnvironmentHttpApi,+ "orchestration",+ Effect.fnUntraced(function* (handlers) {const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;- const snapshot = yield* projectionSnapshotQuery.getSnapshot().pipe(- Effect.mapError(- (cause) =>- new OrchestrationGetSnapshotError({- message: "Failed to load orchestration snapshot.",- cause,- }),- ),- );- return HttpServerResponse.jsonUnsafe(snapshot satisfies OrchestrationReadModel, {- status: 200,- });- }).pipe(- Effect.catchTags({- OrchestrationDispatchCommandError: respondToOrchestrationHttpError,- OrchestrationGetSnapshotError: respondToOrchestrationHttpError,- }),- ),-);--export const orchestrationDispatchRouteLayer = HttpRouter.add(- "POST",- "/api/orchestration/dispatch",- Effect.gen(function* () {- yield* authenticateOwnerSession;const orchestrationEngine = yield* OrchestrationEngineService;- const command = yield* HttpServerRequest.schemaBodyJson(ClientOrchestrationCommand).pipe(- Effect.mapError(- (cause) =>- new OrchestrationDispatchCommandError({- message: "Invalid orchestration command payload.",- cause,- }),- ),- );- const normalizedCommand = yield* normalizeDispatchCommand(command);- const result = yield* orchestrationEngine.dispatch(normalizedCommand).pipe(- Effect.mapError(- (cause) =>- new OrchestrationDispatchCommandError({- message: "Failed to dispatch orchestration command.",- cause,- }),- ),- );- return HttpServerResponse.jsonUnsafe(result, { status: 200 });- }).pipe(Effect.catchTag("OrchestrationDispatchCommandError", respondToOrchestrationHttpError)),++ return handlers+ .handle(+ "snapshot",+ Effect.fn("environment.orchestration.snapshot")(function* (args) {+ yield* annotateEnvironmentRequest(args.endpoint.name);+ yield* requireEnvironmentScope(AuthOrchestrationReadScope);+ return yield* projectionSnapshotQuery+ .getSnapshot()+ .pipe(+ Effect.catch((cause) =>+ failEnvironmentInternal("orchestration_snapshot_failed", cause),+ ),+ );+ }),+ )+ .handle(+ "dispatch",+ Effect.fn("environment.orchestration.dispatch")(function* (args) {+ yield* annotateEnvironmentRequest(args.endpoint.name);+ yield* requireEnvironmentScope(AuthOrchestrationOperateScope);+ const normalizedCommand = yield* normalizeDispatchCommand(args.payload).pipe(+ Effect.catch(() => failEnvironmentInvalidRequest("invalid_command")),+ );+ return yield* orchestrationEngine+ .dispatch(normalizedCommand)+ .pipe(+ Effect.catch((cause) =>+ failEnvironmentInternal("orchestration_dispatch_failed", cause),+ ),+ );+ }),+ );+ }),);diff --git a/apps/server/src/persistence/Layers/AuthPairingLinks.ts b/apps/server/src/persistence/Layers/AuthPairingLinks.tsindex 15c572ad0..7519c65c1 100644--- a/apps/server/src/persistence/Layers/AuthPairingLinks.ts+++ b/apps/server/src/persistence/Layers/AuthPairingLinks.ts@@ -38,7 +38,7 @@ const makeAuthPairingLinkRepository = Effect.gen(function* () {id,credential,method,- role,+ scopes,subject,label,created_at,@@ -50,7 +50,7 @@ const makeAuthPairingLinkRepository = Effect.gen(function* () {${input.id},${input.credential},${input.method},- ${input.role},+ ${JSON.stringify(input.scopes)},${input.subject},${input.label},${input.createdAt},@@ -76,7 +76,7 @@ const makeAuthPairingLinkRepository = Effect.gen(function* () {id AS "id",credential AS "credential",method AS "method",- role AS "role",+ scopes AS "scopes",subject AS "subject",label AS "label",created_at AS "createdAt",@@ -95,7 +95,7 @@ const makeAuthPairingLinkRepository = Effect.gen(function* () {id AS "id",credential AS "credential",method AS "method",- role AS "role",+ scopes AS "scopes",subject AS "subject",label AS "label",created_at AS "createdAt",@@ -133,7 +133,7 @@ const makeAuthPairingLinkRepository = Effect.gen(function* () {id AS "id",credential AS "credential",method AS "method",- role AS "role",+ scopes AS "scopes",subject AS "subject",label AS "label",created_at AS "createdAt",diff --git a/apps/server/src/persistence/Layers/AuthSessions.ts b/apps/server/src/persistence/Layers/AuthSessions.tsindex 6774e79c8..ab84e3fa0 100644--- a/apps/server/src/persistence/Layers/AuthSessions.ts+++ b/apps/server/src/persistence/Layers/AuthSessions.ts@@ -1,4 +1,4 @@-import { AuthSessionId } from "@t3tools/contracts";+import { AuthEnvironmentScopes, AuthSessionId, ServerAuthSessionMethod } from "@t3tools/contracts";import * as SqlClient from "effect/unstable/sql/SqlClient";import * as SqlSchema from "effect/unstable/sql/SqlSchema";import * as Effect from "effect/Effect";@@ -26,8 +26,8 @@ import {const AuthSessionDbRow = Schema.Struct({sessionId: AuthSessionId,subject: Schema.String,- role: Schema.Literals(["owner", "client"]),- method: Schema.Literals(["browser-session-cookie", "bearer-session-token"]),+ scopes: Schema.fromJsonString(AuthEnvironmentScopes),+ method: ServerAuthSessionMethod,clientLabel: Schema.NullOr(Schema.String),clientIpAddress: Schema.NullOr(Schema.String),clientUserAgent: Schema.NullOr(Schema.String),@@ -44,7 +44,7 @@ function toAuthSessionRecord(row: typeof AuthSessionDbRow.Type): AuthSessionRecoreturn {sessionId: row.sessionId,subject: row.subject,- role: row.role,+ scopes: row.scopes,method: row.method,client: {label: row.clientLabel,@@ -78,7 +78,7 @@ const makeAuthSessionRepository = Effect.gen(function* () {INSERT INTO auth_sessions (session_id,subject,- role,+ scopes,method,client_label,client_ip_address,@@ -93,7 +93,7 @@ const makeAuthSessionRepository = Effect.gen(function* () {VALUES (${input.sessionId},${input.subject},- ${input.role},+ ${JSON.stringify(input.scopes)},${input.method},${input.client.label},${input.client.ipAddress},@@ -116,7 +116,7 @@ const makeAuthSessionRepository = Effect.gen(function* () {SELECTsession_id AS "sessionId",subject AS "subject",- role AS "role",+ scopes AS "scopes",method AS "method",client_label AS "clientLabel",client_ip_address AS "clientIpAddress",@@ -141,7 +141,7 @@ const makeAuthSessionRepository = Effect.gen(function* () {SELECTsession_id AS "sessionId",subject AS "subject",- role AS "role",+ scopes AS "scopes",method AS "method",client_label AS "clientLabel",client_ip_address AS "clientIpAddress",diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.tsindex cc5024d5f..9524deae8 100644--- a/apps/server/src/persistence/Migrations.ts+++ b/apps/server/src/persistence/Migrations.ts@@ -43,6 +43,7 @@ import Migration0027 from "./Migrations/027_ProviderSessionRuntimeInstanceId.ts"import Migration0028 from "./Migrations/028_ProjectionThreadSessionInstanceId.ts";import Migration0029 from "./Migrations/029_ProjectionThreadDetailOrderingIndexes.ts";import Migration0030 from "./Migrations/030_ProjectionThreadShellArchiveIndexes.ts";+import Migration0031 from "./Migrations/031_AuthAuthorizationScopes.ts";/*** Migration loader with all migrations defined inline.@@ -85,6 +86,7 @@ export const migrationEntries = [[28, "ProjectionThreadSessionInstanceId", Migration0028],[29, "ProjectionThreadDetailOrderingIndexes", Migration0029],[30, "ProjectionThreadShellArchiveIndexes", Migration0030],+ [31, "AuthAuthorizationScopes", Migration0031],] as const;export const makeMigrationLoader = (throughId?: number) =>diff --git a/apps/server/src/persistence/Migrations/031_AuthAuthorizationScopes.test.ts b/apps/server/src/persistence/Migrations/031_AuthAuthorizationScopes.test.tsnew file mode 100644index 000000000..cb50dc2c6--- /dev/null+++ b/apps/server/src/persistence/Migrations/031_AuthAuthorizationScopes.test.ts@@ -0,0 +1,80 @@+import { assert, it } from "@effect/vitest";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";+import * as SqlClient from "effect/unstable/sql/SqlClient";++import { runMigrations } from "../Migrations.ts";+import * as NodeSqliteClient from "../NodeSqliteClient.ts";++const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));++layer("031_AuthAuthorizationScopes", (it) => {+ it.effect("invalidates role-based auth records and installs scoped auth tables", () =>+ Effect.gen(function* () {+ const sql = yield* SqlClient.SqlClient;++ yield* runMigrations({ toMigrationInclusive: 30 });++ yield* sql`+ INSERT INTO auth_pairing_links (+ id,+ credential,+ method,+ role,+ subject,+ created_at,+ expires_at+ )+ VALUES (+ 'link-owner',+ 'bootstrap-owner',+ 'desktop-bootstrap',+ 'owner',+ 'desktop',+ '2026-05-29T00:00:00.000Z',+ '2026-05-29T01:00:00.000Z'+ )+ `;+ yield* sql`+ INSERT INTO auth_sessions (+ session_id,+ subject,+ role,+ method,+ issued_at,+ expires_at+ )+ VALUES (+ 'session-owner',+ 'desktop',+ 'owner',+ 'browser-session-cookie',+ '2026-05-29T00:00:00.000Z',+ '2026-05-29T01:00:00.000Z'+ )+ `;++ yield* runMigrations({ toMigrationInclusive: 31 });++ const pairingColumns = yield* sql<{ readonly name: string }>`+ PRAGMA table_info(auth_pairing_links)+ `;+ const sessionColumns = yield* sql<{ readonly name: string }>`+ PRAGMA table_info(auth_sessions)+ `;+ const pairingRows = yield* sql<{ readonly id: string }>`+ SELECT id FROM auth_pairing_links+ `;+ const sessionRows = yield* sql<{ readonly sessionId: string }>`+ SELECT session_id AS "sessionId" FROM auth_sessions+ `;++ assert.isTrue(pairingColumns.some((column) => column.name === "scopes"));+ assert.isFalse(pairingColumns.some((column) => column.name === "role"));+ assert.isTrue(sessionColumns.some((column) => column.name === "scopes"));+ assert.isFalse(sessionColumns.some((column) => column.name === "role"));+ assert.deepStrictEqual(pairingRows, []);+ assert.deepStrictEqual(sessionRows, []);+ }),+ );+});diff --git a/apps/server/src/persistence/Migrations/031_AuthAuthorizationScopes.ts b/apps/server/src/persistence/Migrations/031_AuthAuthorizationScopes.tsnew file mode 100644index 000000000..59f9f9695--- /dev/null+++ b/apps/server/src/persistence/Migrations/031_AuthAuthorizationScopes.ts@@ -0,0 +1,57 @@+import * as Effect from "effect/Effect";+import * as SqlClient from "effect/unstable/sql/SqlClient";++/**+ * This is an intentional alpha cutover: role-bearing credentials and sessions+ * cannot safely be assigned new capabilities implicitly.+ */+export default Effect.gen(function* () {+ const sql = yield* SqlClient.SqlClient;++ yield* sql`DROP TABLE IF EXISTS auth_pairing_links`;+ yield* sql`DROP TABLE IF EXISTS auth_sessions`;++ yield* sql`+ CREATE TABLE auth_pairing_links (+ id TEXT PRIMARY KEY,+ credential TEXT NOT NULL UNIQUE,+ method TEXT NOT NULL,+ scopes TEXT NOT NULL,+ subject TEXT NOT NULL,+ label TEXT,+ created_at TEXT NOT NULL,+ expires_at TEXT NOT NULL,+ consumed_at TEXT,+ revoked_at TEXT+ )+ `;++ yield* sql`+ CREATE INDEX idx_auth_pairing_links_active+ ON auth_pairing_links(revoked_at, consumed_at, expires_at)+ `;++ yield* sql`+ CREATE TABLE auth_sessions (+ session_id TEXT PRIMARY KEY,+ subject TEXT NOT NULL,+ scopes TEXT NOT NULL,+ method TEXT NOT NULL,+ client_label TEXT,+ client_ip_address TEXT,+ client_user_agent TEXT,+ client_device_type TEXT NOT NULL DEFAULT 'unknown',+ client_os TEXT,+ client_browser TEXT,+ issued_at TEXT NOT NULL,+ expires_at TEXT NOT NULL,+ last_connected_at TEXT,+ revoked_at TEXT+ )+ `;++ yield* sql`+ CREATE INDEX idx_auth_sessions_active+ ON auth_sessions(revoked_at, expires_at, issued_at)+ `;+});diff --git a/apps/server/src/persistence/Services/AuthPairingLinks.ts b/apps/server/src/persistence/Services/AuthPairingLinks.tsindex c81ce51a3..16a9c4035 100644--- a/apps/server/src/persistence/Services/AuthPairingLinks.ts+++ b/apps/server/src/persistence/Services/AuthPairingLinks.ts@@ -2,6 +2,7 @@ import * as Option from "effect/Option";import * as Schema from "effect/Schema";import * as Context from "effect/Context";import type * as Effect from "effect/Effect";+import { AuthEnvironmentScopes } from "@t3tools/contracts";import type { AuthPairingLinkRepositoryError } from "../Errors.ts";@@ -9,7 +10,7 @@ export const AuthPairingLinkRecord = Schema.Struct({id: Schema.String,credential: Schema.String,method: Schema.Literals(["desktop-bootstrap", "one-time-token"]),- role: Schema.Literals(["owner", "client"]),+ scopes: Schema.fromJsonString(AuthEnvironmentScopes),subject: Schema.String,label: Schema.NullOr(Schema.String),createdAt: Schema.DateTimeUtcFromString,@@ -23,7 +24,7 @@ export const CreateAuthPairingLinkInput = Schema.Struct({id: Schema.String,credential: Schema.String,method: Schema.Literals(["desktop-bootstrap", "one-time-token"]),- role: Schema.Literals(["owner", "client"]),+ scopes: AuthEnvironmentScopes,subject: Schema.String,label: Schema.NullOr(Schema.String),createdAt: Schema.DateTimeUtcFromString,diff --git a/apps/server/src/persistence/Services/AuthSessions.ts b/apps/server/src/persistence/Services/AuthSessions.tsindex a92573f9f..c08956bdd 100644--- a/apps/server/src/persistence/Services/AuthSessions.ts+++ b/apps/server/src/persistence/Services/AuthSessions.ts@@ -1,4 +1,9 @@-import { AuthClientMetadataDeviceType, AuthSessionId } from "@t3tools/contracts";+import {+ AuthClientMetadataDeviceType,+ AuthEnvironmentScopes,+ AuthSessionId,+ ServerAuthSessionMethod,+} from "@t3tools/contracts";import * as Option from "effect/Option";import * as Schema from "effect/Schema";import * as Context from "effect/Context";@@ -19,8 +24,8 @@ export type AuthSessionClientMetadataRecord = typeof AuthSessionClientMetadataReexport const AuthSessionRecord = Schema.Struct({sessionId: AuthSessionId,subject: Schema.String,- role: Schema.Literals(["owner", "client"]),- method: Schema.Literals(["browser-session-cookie", "bearer-session-token"]),+ scopes: AuthEnvironmentScopes,+ method: ServerAuthSessionMethod,client: AuthSessionClientMetadataRecord,issuedAt: Schema.DateTimeUtcFromString,expiresAt: Schema.DateTimeUtcFromString,@@ -32,8 +37,8 @@ export type AuthSessionRecord = typeof AuthSessionRecord.Type;export const CreateAuthSessionInput = Schema.Struct({sessionId: AuthSessionId,subject: Schema.String,- role: Schema.Literals(["owner", "client"]),- method: Schema.Literals(["browser-session-cookie", "bearer-session-token"]),+ scopes: AuthEnvironmentScopes,+ method: ServerAuthSessionMethod,client: AuthSessionClientMetadataRecord,issuedAt: Schema.DateTimeUtcFromString,expiresAt: Schema.DateTimeUtcFromString,diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.tsindex ae920aeb8..7cd9efe5f 100644--- a/apps/server/src/server.test.ts+++ b/apps/server/src/server.test.ts@@ -3,6 +3,9 @@ import * as NodeSocket from "@effect/platform-node/NodeSocket";import * as NodeServices from "@effect/platform-node/NodeServices";import {+ AuthAccessTokenType,+ AuthEnvironmentBootstrapTokenType,+ AuthTokenExchangeGrantType,CommandId,DEFAULT_SERVER_SETTINGS,EnvironmentId,@@ -46,6 +49,7 @@ import {HttpClient,HttpRouter,HttpServer,+ UrlParams,} from "effect/unstable/http";import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";import { RpcClient, RpcSerialization } from "effect/unstable/rpc";@@ -114,8 +118,8 @@ import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";import * as GitWorkflowService from "./git/GitWorkflowService.ts";import * as ReviewService from "./review/ReviewService.ts";import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";-import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";-import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts";+import * as ServerSecretStore from "./auth/ServerSecretStore.ts";+import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";@@ -215,7 +219,10 @@ const browserOtlpTracingLayer = Layer.mergeAll();const makeAuthTestLayer = () =>- ServerAuthLive.pipe(Layer.provide(SqlitePersistenceMemory), Layer.provide(ServerSecretStoreLive));+ EnvironmentAuth.layer.pipe(+ Layer.provide(SqlitePersistenceMemory),+ Layer.provide(ServerSecretStore.layer),+ );const makeBrowserOtlpPayload = (spanName: string) =>Effect.gen(function* () {@@ -799,7 +806,7 @@ const bootstrapBrowserSession = (},) =>Effect.gen(function* () {- const response = yield* HttpClient.post("/api/auth/bootstrap", {+ const response = yield* HttpClient.post("/api/auth/browser-session", {headers: options?.headers,body: yield* HttpBody.json({ credential }),});@@ -815,23 +822,46 @@ const bootstrapBrowserSession = (};});-const bootstrapBearerSession = (+const exchangeAccessToken = (credential = defaultDesktopBootstrapToken,options?: {readonly headers?: Record<string, string>;+ readonly scope?: string;+ readonly clientMetadata?: {+ readonly label?: string;+ readonly deviceType?: string;+ readonly os?: string;+ };},) =>Effect.gen(function* () {- const response = yield* HttpClient.post("/api/auth/bootstrap/bearer", {+ const response = yield* HttpClient.post("/oauth/token", {headers: options?.headers,- body: yield* HttpBody.json({ credential }),+ body: HttpBody.urlParams(+ UrlParams.fromInput({+ grant_type: AuthTokenExchangeGrantType,+ subject_token: credential,+ subject_token_type: AuthEnvironmentBootstrapTokenType,+ requested_token_type: AuthAccessTokenType,+ scope:+ options?.scope ??+ "orchestration:read orchestration:operate terminal:operate review:write relay:read access:read access:write relay:write",+ ...(options?.clientMetadata?.label ? { client_label: options.clientMetadata.label } : {}),+ ...(options?.clientMetadata?.deviceType+ ? { client_device_type: options.clientMetadata.deviceType }+ : {}),+ ...(options?.clientMetadata?.os ? { client_os: options.clientMetadata.os } : {}),+ }),+ ),});const body = (yield* response.json) as {- readonly authenticated: boolean;- readonly sessionMethod: string;- readonly expiresAt: string;- readonly sessionToken?: string;- readonly error?: string;+ readonly access_token?: string;+ readonly issued_token_type?: string;+ readonly token_type?: string;+ readonly expires_in?: number;+ readonly scope?: string;+ readonly _tag?: string;+ readonly message?: string;};return {response,@@ -863,20 +893,20 @@ const getAuthenticatedSessionCookieHeader = (credential = defaultDesktopBootstraconst getAuthenticatedBearerSessionToken = (credential = defaultDesktopBootstrapToken) =>Effect.gen(function* () {- const { response, body } = yield* bootstrapBearerSession(credential);+ const { response, body } = yield* exchangeAccessToken(credential);if (response.status !== 200) {return yield* new AuthenticationGetterError({message: `Expected bearer bootstrap response to succeed, got ${response.status}`,});}- if (!body.sessionToken) {+ if (!body.access_token) {return yield* new AuthenticationGetterError({- message: "Expected bearer bootstrap response to include a session token.",+ message: "Expected token exchange response to include an access token.",});}- return body.sessionToken;+ return body.access_token;});const extractSessionTokenFromSetCookie = (cookieHeader: string): string => {@@ -895,8 +925,16 @@ const splitHeaderTokens = (value: string | null) =>.filter((token) => token.length > 0).toSorted();-const assertBrowserApiCorsHeaders = (headers: Readonly<Record<string, string | undefined>>) => {+const assertBrowserApiCorsResponseHeaders = (+ headers: Readonly<Record<string, string | undefined>>,+) => {assert.equal(headers["access-control-allow-origin"], "*");+};++const assertBrowserApiCorsPreflightHeaders = (+ headers: Readonly<Record<string, string | undefined>>,+) => {+ assertBrowserApiCorsResponseHeaders(headers);assert.deepEqual(splitHeaderTokens(headers["access-control-allow-methods"] ?? null), ["GET","OPTIONS",@@ -1039,7 +1077,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {const body = (yield* response.json) as typeof testEnvironmentDescriptor;assert.equal(response.status, 200);- assertBrowserApiCorsHeaders(response.headers);+ assertBrowserApiCorsResponseHeaders(response.headers);assert.deepEqual(body, testEnvironmentDescriptor);}).pipe(Effect.provide(NodeHttpServer.layerTest)),);@@ -1063,10 +1101,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {assert.equal(body.authenticated, false);assert.equal(body.auth.policy, "desktop-managed-local");assert.deepEqual(body.auth.bootstrapMethods, ["desktop-bootstrap"]);- assert.deepEqual(body.auth.sessionMethods, [- "browser-session-cookie",- "bearer-session-token",- ]);+ assert.deepEqual(body.auth.sessionMethods, ["browser-session-cookie", "bearer-access-token"]);assert.isTrue(body.auth.sessionCookieName.startsWith("t3_session_"));}).pipe(Effect.provide(NodeHttpServer.layerTest)),);@@ -1103,56 +1138,134 @@ it.layer(NodeServices.layer)("server router seam", (it) => {}).pipe(Effect.provide(NodeHttpServer.layerTest)),);- it.effect(- "bootstraps a bearer session and authenticates the session endpoint via authorization header",- () =>- Effect.gen(function* () {- yield* buildAppUnderTest();+ it.effect("exchanges a bootstrap grant for a scoped bearer access token", () =>+ Effect.gen(function* () {+ yield* buildAppUnderTest();- const { response: bootstrapResponse, body: bootstrapBody } =- yield* bootstrapBearerSession();+ const { response: bootstrapResponse, body: tokenBody } = yield* exchangeAccessToken();- assert.equal(bootstrapResponse.status, 200);- assert.equal(bootstrapBody.authenticated, true);- assert.equal(bootstrapBody.sessionMethod, "bearer-session-token");- assert.equal(typeof bootstrapBody.sessionToken, "string");- assert.isTrue((bootstrapBody.sessionToken?.length ?? 0) > 0);+ assert.equal(bootstrapResponse.status, 200);+ assert.equal(tokenBody.issued_token_type, AuthAccessTokenType);+ assert.equal(tokenBody.token_type, "Bearer");+ assert.equal(+ tokenBody.scope,+ "orchestration:read orchestration:operate terminal:operate review:write relay:read access:read access:write relay:write",+ );+ assert.equal(typeof tokenBody.access_token, "string");+ assert.isTrue((tokenBody.access_token?.length ?? 0) > 0);- const sessionResponse = yield* HttpClient.get("/api/auth/session", {- headers: {- authorization: `Bearer ${bootstrapBody.sessionToken ?? ""}`,- },- });- const sessionBody = (yield* sessionResponse.json) as {- readonly authenticated: boolean;- readonly sessionMethod?: string;- };+ const sessionResponse = yield* HttpClient.get("/api/auth/session", {+ headers: {+ authorization: `Bearer ${tokenBody.access_token ?? ""}`,+ },+ });+ const sessionBody = (yield* sessionResponse.json) as {+ readonly authenticated: boolean;+ readonly sessionMethod?: string;+ readonly scopes?: ReadonlyArray<string>;+ };- assert.equal(sessionResponse.status, 200);- assert.equal(sessionBody.authenticated, true);- assert.equal(sessionBody.sessionMethod, "bearer-session-token");- }).pipe(Effect.provide(NodeHttpServer.layerTest)),+ assert.equal(sessionResponse.status, 200);+ assert.equal(sessionBody.authenticated, true);+ assert.equal(sessionBody.sessionMethod, "bearer-access-token");+ assert.deepEqual(sessionBody.scopes, [+ "orchestration:read",+ "orchestration:operate",+ "terminal:operate",+ "review:write",+ "relay:read",+ "access:read",+ "access:write",+ "relay:write",+ ]);+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),);- it.effect("issues short-lived websocket tokens for authenticated bearer sessions", () =>+ it.effect("issues short-lived websocket tickets for authenticated bearer sessions", () =>Effect.gen(function* () {yield* buildAppUnderTest();const bearerToken = yield* getAuthenticatedBearerSessionToken();- const wsTokenResponse = yield* HttpClient.post("/api/auth/ws-token", {+ const wsTicketResponse = yield* HttpClient.post("/api/auth/websocket-ticket", {headers: {authorization: `Bearer ${bearerToken}`,},});- const wsTokenBody = (yield* wsTokenResponse.json) as {- readonly token: string;+ const wsTicketBody = (yield* wsTicketResponse.json) as {+ readonly ticket: string;readonly expiresAt: string;};- assert.equal(wsTokenResponse.status, 200);- assert.equal(typeof wsTokenBody.token, "string");- assert.isTrue(wsTokenBody.token.length > 0);- assert.equal(typeof wsTokenBody.expiresAt, "string");+ assert.equal(wsTicketResponse.status, 200);+ assert.equal(typeof wsTicketBody.ticket, "string");+ assert.isTrue(wsTicketBody.ticket.length > 0);+ assert.equal(typeof wsTicketBody.expiresAt, "string");+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),+ );++ it.effect("does not allow management-only access tokens to operate the environment", () =>+ Effect.gen(function* () {+ yield* buildAppUnderTest();++ const { response: exchangeResponse, body: tokenBody } = yield* exchangeAccessToken(+ defaultDesktopBootstrapToken,+ { scope: "access:write" },+ );+ assert.equal(exchangeResponse.status, 200);+ assert.equal(tokenBody.scope, "access:write");+ assert.isDefined(tokenBody.access_token);++ const overbroadPairingResponse = yield* HttpClient.post("/api/auth/pairing-token", {+ headers: {+ authorization: `Bearer ${tokenBody.access_token ?? ""}`,+ },+ body: yield* HttpBody.json({}),+ });+ const overbroadPairingBody = (yield* overbroadPairingResponse.json) as {+ readonly requiredScope: string;+ };+ const pairingResponse = yield* HttpClient.post("/api/auth/pairing-token", {+ headers: {+ authorization: `Bearer ${tokenBody.access_token ?? ""}`,+ },+ body: yield* HttpBody.json({ scopes: ["access:write"] }),+ });+ const wsTicketResponse = yield* HttpClient.post("/api/auth/websocket-ticket", {+ headers: {+ authorization: `Bearer ${tokenBody.access_token ?? ""}`,+ },+ });+ const wsTicketBody = (yield* wsTicketResponse.json) as { readonly ticket: string };+ const faviconResponse = yield* HttpClient.get("/api/project-favicon?cwd=/tmp", {+ headers: {+ authorization: `Bearer ${tokenBody.access_token ?? ""}`,+ },+ });+ const faviconBody = (yield* faviconResponse.json) as {+ readonly _tag: string;+ readonly code: string;+ readonly requiredScope: string;+ readonly traceId: string;+ };++ assert.equal(overbroadPairingResponse.status, 403);+ assert.equal(overbroadPairingBody.requiredScope, "orchestration:read");+ assert.equal(pairingResponse.status, 200);+ assert.equal(wsTicketResponse.status, 200);+ assert.equal(faviconResponse.status, 403);+ assert.equal(faviconBody._tag, "EnvironmentScopeRequiredError");+ assert.equal(faviconBody.code, "insufficient_scope");+ assert.equal(faviconBody.requiredScope, "orchestration:read");+ assert.equal(typeof faviconBody.traceId, "string");++ const wsUrl = `${yield* getWsServerUrl("/ws", { authenticated: false })}?wsTicket=${encodeURIComponent(wsTicketBody.ticket)}`;+ const rpcError = yield* Effect.flip(+ Effect.scoped(withWsRpcClient(wsUrl, (client) => client[WS_METHODS.serverGetConfig]({}))),+ );+ assert.equal(rpcError._tag, "EnvironmentAuthorizationError");+ if (rpcError._tag === "EnvironmentAuthorizationError") {+ assert.equal(rpcError.requiredScope, "orchestration:read");+ }}).pipe(Effect.provide(NodeHttpServer.layerTest)),);@@ -1161,7 +1274,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {yield* buildAppUnderTest();const origin = crossOriginClientOrigin;- const { response: bootstrapResponse, body: bootstrapBody } = yield* bootstrapBearerSession(+ const { response: bootstrapResponse, body: tokenBody } = yield* exchangeAccessToken(defaultDesktopBootstrapToken,{headers: { origin },@@ -1169,13 +1282,13 @@ it.layer(NodeServices.layer)("server router seam", (it) => {);assert.equal(bootstrapResponse.status, 200);- assertBrowserApiCorsHeaders(bootstrapResponse.headers);- assert.equal(bootstrapBody.authenticated, true);- assert.equal(typeof bootstrapBody.sessionToken, "string");+ assertBrowserApiCorsResponseHeaders(bootstrapResponse.headers);+ assert.equal(tokenBody.token_type, "Bearer");+ assert.equal(typeof tokenBody.access_token, "string");const sessionResponse = yield* HttpClient.get("/api/auth/session", {headers: {- authorization: `Bearer ${bootstrapBody.sessionToken ?? ""}`,+ authorization: `Bearer ${tokenBody.access_token ?? ""}`,origin,},});@@ -1185,33 +1298,33 @@ it.layer(NodeServices.layer)("server router seam", (it) => {};assert.equal(sessionResponse.status, 200);- assertBrowserApiCorsHeaders(sessionResponse.headers);+ assertBrowserApiCorsResponseHeaders(sessionResponse.headers);assert.equal(sessionBody.authenticated, true);- assert.equal(sessionBody.sessionMethod, "bearer-session-token");+ assert.equal(sessionBody.sessionMethod, "bearer-access-token");- const wsTokenResponse = yield* HttpClient.post("/api/auth/ws-token", {+ const wsTicketResponse = yield* HttpClient.post("/api/auth/websocket-ticket", {headers: {- authorization: `Bearer ${bootstrapBody.sessionToken ?? ""}`,+ authorization: `Bearer ${tokenBody.access_token ?? ""}`,origin,},});- const wsTokenBody = (yield* wsTokenResponse.json) as {- readonly token: string;+ const wsTicketBody = (yield* wsTicketResponse.json) as {+ readonly ticket: string;};- assert.equal(wsTokenResponse.status, 200);- assertBrowserApiCorsHeaders(wsTokenResponse.headers);- assert.equal(typeof wsTokenBody.token, "string");+ assert.equal(wsTicketResponse.status, 200);+ assertBrowserApiCorsResponseHeaders(wsTicketResponse.headers);+ assert.equal(typeof wsTicketBody.ticket, "string");}).pipe(Effect.provide(NodeHttpServer.layerTest)),);it.effect(- "responds to remote auth websocket-token preflight requests with authorization CORS headers",+ "responds to remote auth websocket-ticket preflight requests with authorization CORS headers",() =>Effect.gen(function* () {yield* buildAppUnderTest();- const response = yield* HttpClient.options("/api/auth/ws-token", {+ const response = yield* HttpClient.options("/api/auth/websocket-ticket", {headers: {origin: crossOriginClientOrigin,"access-control-request-method": "POST",@@ -1220,26 +1333,93 @@ it.layer(NodeServices.layer)("server router seam", (it) => {});assert.equal(response.status, 204);- assertBrowserApiCorsHeaders(response.headers);+ assertBrowserApiCorsPreflightHeaders(response.headers);}).pipe(Effect.provide(NodeHttpServer.layerTest)),);- it.effect("includes CORS headers on remote websocket-token auth failures", () =>+ it.effect("includes CORS headers on remote websocket-ticket auth failures", () =>Effect.gen(function* () {yield* buildAppUnderTest();- const response = yield* HttpClient.post("/api/auth/ws-token", {+ const response = yield* HttpClient.post("/api/auth/websocket-ticket", {headers: {origin: crossOriginClientOrigin,},});const body = (yield* response.json) as {- readonly error?: string;+ readonly _tag?: string;+ readonly code?: string;+ readonly reason?: string;+ readonly traceId?: string;};assert.equal(response.status, 401);- assertBrowserApiCorsHeaders(response.headers);- assert.equal(body.error, "Authentication required.");+ assertBrowserApiCorsResponseHeaders(response.headers);+ assert.equal(body._tag, "EnvironmentAuthInvalidError");+ assert.equal(body.code, "auth_invalid");+ assert.equal(body.reason, "missing_credential");+ assert.equal(typeof body.traceId, "string");+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),+ );++ it.effect("persists token exchange client display metadata for authorized-client listings", () =>+ Effect.gen(function* () {+ yield* buildAppUnderTest({+ config: {+ host: "0.0.0.0",+ },+ });++ const ownerCookie = yield* getAuthenticatedSessionCookieHeader();+ const pairingResponse = yield* HttpClient.post("/api/auth/pairing-token", {+ headers: {+ cookie: ownerCookie,+ },+ body: yield* HttpBody.json({}),+ });+ const pairingBody = (yield* pairingResponse.json) as {+ readonly credential: string;+ };++ const { response } = yield* exchangeAccessToken(pairingBody.credential, {+ headers: {+ "user-agent": "undici",+ },+ scope: "orchestration:read orchestration:operate terminal:operate review:write relay:read",+ clientMetadata: {+ label: "T3 Code Mobile",+ deviceType: "mobile",+ os: "iOS",+ },+ });++ const clientsResponse = yield* HttpClient.get("/api/auth/clients", {+ headers: {+ cookie: ownerCookie,+ },+ });+ const clients = (yield* clientsResponse.json) as ReadonlyArray<{+ readonly current: boolean;+ readonly client: {+ readonly label?: string;+ readonly deviceType: string;+ readonly ipAddress?: string;+ readonly os?: string;+ readonly userAgent?: string;+ };+ }>;+ const mobileClient = clients.find((client) => !client.current);++ assert.equal(pairingResponse.status, 200);+ assert.equal(response.status, 200);+ assert.equal(clientsResponse.status, 200);+ assert.deepInclude(mobileClient?.client, {+ label: "T3 Code Mobile",+ deviceType: "mobile",+ os: "iOS",+ ipAddress: "127.0.0.1",+ userAgent: "undici",+ });}).pipe(Effect.provide(NodeHttpServer.layerTest)),);@@ -1251,6 +1431,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {headers: {cookie: yield* getAuthenticatedSessionCookieHeader(),},+ body: yield* HttpBody.json({}),});const body = (yield* response.json) as {readonly credential: string;@@ -1270,16 +1451,61 @@ it.layer(NodeServices.layer)("server router seam", (it) => {}).pipe(Effect.provide(NodeHttpServer.layerTest)),);+ it.effect("issues pairing credentials for bearer sessions with access management scope", () =>+ Effect.gen(function* () {+ yield* buildAppUnderTest();++ const bearerToken = yield* getAuthenticatedBearerSessionToken();+ const response = yield* HttpClient.post("/api/auth/pairing-token", {+ headers: {+ authorization: `Bearer ${bearerToken}`,+ },+ body: yield* HttpBody.json({ label: "Hosted web" }),+ });+ const body = (yield* response.json) as {+ readonly credential: string;+ readonly label?: string;+ };++ assert.equal(response.status, 200);+ assert.isTrue(body.credential.length > 0);+ assert.equal(body.label, "Hosted web");+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),+ );++ it.effect("rejects pairing credentials with an empty scope grant", () =>+ Effect.gen(function* () {+ yield* buildAppUnderTest();++ const response = yield* HttpClient.post("/api/auth/pairing-token", {+ headers: {+ cookie: yield* getAuthenticatedSessionCookieHeader(),+ },+ body: yield* HttpBody.json({ scopes: [] }),+ });+ const body = (yield* response.json) as {+ readonly code: string;+ readonly reason: string;+ };++ assert.equal(response.status, 400);+ assert.equal(body.code, "invalid_request");+ assert.equal(body.reason, "invalid_scope");+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),+ );+it.effect("rejects unauthenticated pairing credential requests", () =>Effect.gen(function* () {yield* buildAppUnderTest();- const response = yield* HttpClient.post("/api/auth/pairing-token");+ const response = yield* HttpClient.post("/api/auth/pairing-token", {+ body: yield* HttpBody.json({}),+ });assert.equal(response.status, 401);}).pipe(Effect.provide(NodeHttpServer.layerTest)),);- it.effect("lists and revokes pairing links for owner sessions", () =>+ it.effect("lists and revokes pairing links for access management sessions", () =>Effect.gen(function* () {yield* buildAppUnderTest({config: {@@ -1292,6 +1518,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {headers: {cookie: ownerCookie,},+ body: yield* HttpBody.json({}),});const createdBody = (yield* createdResponse.json) as {readonly id: string;@@ -1324,7 +1551,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {}).pipe(Effect.provide(NodeHttpServer.layerTest)),);- it.effect("rejects pairing credential requests from non-owner paired sessions", () =>+ it.effect("rejects pairing credential requests without access management scope", () =>Effect.gen(function* () {yield* buildAppUnderTest({config: {@@ -1336,6 +1563,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {headers: {cookie: yield* getAuthenticatedSessionCookieHeader(),},+ body: yield* HttpBody.json({}),});const ownerBody = (yield* ownerResponse.json) as {readonly credential: string;@@ -1347,17 +1575,24 @@ it.layer(NodeServices.layer)("server router seam", (it) => {headers: {cookie: pairedSessionCookie,},+ body: yield* HttpBody.json({}),});const pairedBody = (yield* pairedResponse.json) as {- readonly error: string;+ readonly _tag: string;+ readonly code: string;+ readonly requiredScope: string;+ readonly traceId: string;};assert.equal(pairedResponse.status, 403);- assert.equal(pairedBody.error, "Only owner sessions can create pairing credentials.");+ assert.equal(pairedBody._tag, "EnvironmentScopeRequiredError");+ assert.equal(pairedBody.code, "insufficient_scope");+ assert.equal(pairedBody.requiredScope, "access:write");+ assert.equal(typeof pairedBody.traceId, "string");}).pipe(Effect.provide(NodeHttpServer.layerTest)),);- it.effect("lists paired clients and revokes other sessions while keeping the owner", () =>+ it.effect("lists paired clients and revokes other sessions while keeping the administrator", () =>Effect.gen(function* () {yield* buildAppUnderTest({config: {@@ -1429,9 +1664,13 @@ it.layer(NodeServices.layer)("server router seam", (it) => {headers: {cookie: pairedSessionCookieHeader,},+ body: yield* HttpBody.json({}),});const pairedClientPairingBody = (yield* pairedClientPairingResponse.json) as {- readonly error: string;+ readonly _tag: string;+ readonly code: string;+ readonly reason: string;+ readonly traceId: string;};assert.equal(listBeforeResponse.status, 200);@@ -1452,7 +1691,69 @@ it.layer(NodeServices.layer)("server router seam", (it) => {assert.lengthOf(clientsAfter, 1);assert.equal(clientsAfter[0]?.current, true);assert.equal(pairedClientPairingResponse.status, 401);- assert.equal(pairedClientPairingBody.error, "Unauthorized request.");+ assert.equal(pairedClientPairingBody._tag, "EnvironmentAuthInvalidError");+ assert.equal(pairedClientPairingBody.code, "auth_invalid");+ assert.equal(pairedClientPairingBody.reason, "invalid_credential");+ assert.equal(typeof pairedClientPairingBody.traceId, "string");+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),+ );++ it.effect("separates access inventory reads from credential management writes", () =>+ Effect.gen(function* () {+ yield* buildAppUnderTest({+ config: {+ host: "0.0.0.0",+ },+ });++ const ownerCookie = yield* getAuthenticatedSessionCookieHeader();+ const issueScopedSession = Effect.fnUntraced(function* (+ scope: "access:read" | "access:write",+ ) {+ const pairingResponse = yield* HttpClient.post("/api/auth/pairing-token", {+ headers: {+ cookie: ownerCookie,+ },+ body: yield* HttpBody.json({ scopes: [scope] }),+ });+ assert.equal(pairingResponse.status, 200);+ const pairingBody = (yield* pairingResponse.json) as {+ readonly credential: string;+ };+ return yield* getAuthenticatedSessionCookieHeader(pairingBody.credential);+ });++ const readCookie = yield* issueScopedSession("access:read");+ const readListResponse = yield* HttpClient.get("/api/auth/clients", {+ headers: {+ cookie: readCookie,+ },+ });+ const readWriteResponse = yield* HttpClient.post("/api/auth/pairing-token", {+ headers: {+ cookie: readCookie,+ },+ body: yield* HttpBody.json({}),+ });+ const readWriteBody = (yield* readWriteResponse.json) as {+ readonly requiredScope: string;+ };++ const writeCookie = yield* issueScopedSession("access:write");+ const writeListResponse = yield* HttpClient.get("/api/auth/clients", {+ headers: {+ cookie: writeCookie,+ },+ });+ const writeListBody = (yield* writeListResponse.json) as {+ readonly requiredScope: string;+ };++ assert.equal(readListResponse.status, 200);+ assert.equal(readWriteResponse.status, 403);+ assert.equal(readWriteBody.requiredScope, "access:write");+ assert.equal(writeListResponse.status, 403);+ assert.equal(writeListBody.requiredScope, "access:read");}).pipe(Effect.provide(NodeHttpServer.layerTest)),);@@ -1469,6 +1770,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {headers: {cookie: ownerCookie,},+ body: yield* HttpBody.json({}),});const pairingBody = (yield* pairingResponse.json) as {readonly credential: string;@@ -1499,6 +1801,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {headers: {cookie: pairedSessionCookie,},+ body: yield* HttpBody.json({}),});assert.equal(revokeResponse.status, 200);@@ -1515,10 +1818,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {assert.equal(first.response.status, 200);assert.equal(second.response.status, 401);- assert.equal(- (second.body as { readonly error?: string }).error,- "Invalid bootstrap credential.",- );+ assert.equal((second.body as { readonly _tag?: string })._tag, "EnvironmentAuthInvalidError");+ assert.equal((second.body as { readonly code?: string }).code, "auth_invalid");+ assert.equal((second.body as { readonly reason?: string }).reason, "invalid_credential");}).pipe(Effect.provide(NodeHttpServer.layerTest)),);@@ -1594,15 +1896,15 @@ it.layer(NodeServices.layer)("server router seam", (it) => {yield* buildAppUnderTest();const bearerToken = yield* getAuthenticatedBearerSessionToken();- const wsTokenResponse = yield* HttpClient.post("/api/auth/ws-token", {+ const wsTicketResponse = yield* HttpClient.post("/api/auth/websocket-ticket", {headers: {authorization: `Bearer ${bearerToken}`,},});- const wsTokenBody = (yield* wsTokenResponse.json) as {- readonly token: string;+ const wsTicketBody = (yield* wsTicketResponse.json) as {+ readonly ticket: string;};- const wsUrl = `${yield* getWsServerUrl("/ws", { authenticated: false })}?wsToken=${encodeURIComponent(wsTokenBody.token)}`;+ const wsUrl = `${yield* getWsServerUrl("/ws", { authenticated: false })}?wsTicket=${encodeURIComponent(wsTicketBody.ticket)}`;const response = yield* Effect.scoped(withWsRpcClient(wsUrl, (client) => client[WS_METHODS.serverGetConfig]({})),diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex 13516c772..5c0bbb842 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -1,13 +1,15 @@+import { EnvironmentHttpApi } from "@t3tools/contracts";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import { FetchHttpClient, HttpRouter, HttpServer } from "effect/unstable/http";+import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";import { ServerConfig } from "./config.ts";import {attachmentsRouteLayer,otlpTracesProxyRouteLayer,projectFaviconRouteLayer,- serverEnvironmentRouteLayer,+ serverEnvironmentHttpApiLayer,staticAndDevRouteLayer,browserApiCorsLayer,} from "./http.ts";@@ -62,20 +64,9 @@ import * as SourceControlRepositoryService from "./sourceControl/SourceControlReimport { ProjectSetupScriptRunnerLive } from "./project/Layers/ProjectSetupScriptRunner.ts";import { ObservabilityLive } from "./observability/Layers/Observability.ts";import { ServerEnvironmentLive } from "./environment/Layers/ServerEnvironment.ts";-import {- authBearerBootstrapRouteLayer,- authBootstrapRouteLayer,- authClientsRevokeOthersRouteLayer,- authClientsRevokeRouteLayer,- authClientsRouteLayer,- authPairingLinksRevokeRouteLayer,- authPairingLinksRouteLayer,- authPairingCredentialRouteLayer,- authSessionRouteLayer,- authWebSocketTokenRouteLayer,-} from "./auth/http.ts";-import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";-import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts";+import { authHttpApiLayer, environmentAuthenticatedAuthLayer } from "./auth/http.ts";+import * as ServerSecretStore from "./auth/ServerSecretStore.ts";+import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";@@ -85,10 +76,7 @@ import {makePersistedServerRuntimeState,persistServerRuntimeState,} from "./serverRuntimeState.ts";-import {- orchestrationDispatchRouteLayer,- orchestrationSnapshotRouteLayer,-} from "./orchestration/http.ts";+import { orchestrationHttpApiLayer } from "./orchestration/http.ts";import * as NetService from "@t3tools/shared/Net";import { disableTailscaleServe, ensureTailscaleServe } from "@t3tools/tailscale";@@ -238,9 +226,9 @@ const WorkspaceLayerLive = Layer.mergeAll(WorkspaceFileSystemLayerLive,);-const AuthLayerLive = ServerAuthLive.pipe(+const AuthLayerLive = EnvironmentAuth.layer.pipe(Layer.provideMerge(PersistenceLayerLive),- Layer.provide(ServerSecretStoreLive),+ Layer.provide(ServerSecretStore.layer),);const ProviderRuntimeLayerLive = ProviderSessionReaperLive.pipe(@@ -301,22 +289,15 @@ const RuntimeServicesLive = ServerRuntimeStartupLive.pipe();export const makeRoutesLayer = Layer.mergeAll(- authBearerBootstrapRouteLayer,- authBootstrapRouteLayer,- authClientsRevokeOthersRouteLayer,- authClientsRevokeRouteLayer,- authClientsRouteLayer,- authPairingLinksRevokeRouteLayer,- authPairingLinksRouteLayer,- authPairingCredentialRouteLayer,- authSessionRouteLayer,- authWebSocketTokenRouteLayer,+ HttpApiBuilder.layer(EnvironmentHttpApi).pipe(+ Layer.provide(authHttpApiLayer),+ Layer.provide(orchestrationHttpApiLayer),+ Layer.provide(serverEnvironmentHttpApiLayer),+ Layer.provide(environmentAuthenticatedAuthLayer),+ ),attachmentsRouteLayer,- orchestrationDispatchRouteLayer,- orchestrationSnapshotRouteLayer,otlpTracesProxyRouteLayer,projectFaviconRouteLayer,- serverEnvironmentRouteLayer,staticAndDevRouteLayer,websocketRpcRouteLayer,).pipe(Layer.provide(browserApiCorsLayer));diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.tsindex c069623ca..8c41e28b7 100644--- a/apps/server/src/serverRuntimeStartup.ts+++ b/apps/server/src/serverRuntimeStartup.ts@@ -32,7 +32,7 @@ import { ServerLifecycleEvents } from "./serverLifecycleEvents.ts";import { ServerSettingsService } from "./serverSettings.ts";import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts";-import { ServerAuth } from "./auth/Services/ServerAuth.ts";+import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";import { ProviderSessionReaper } from "./provider/Services/ProviderSessionReaper.ts";import {formatHeadlessServeOutput,@@ -244,7 +244,7 @@ export const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {const resolveStartupBrowserTarget = Effect.gen(function* () {const serverConfig = yield* ServerConfig;- const serverAuth = yield* ServerAuth;+ const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;const localUrl = `http://localhost:${serverConfig.port}`;const bindUrl =serverConfig.host && !isWildcardHost(serverConfig.host)diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.tsindex 5ea2e0381..2ccbb121b 100644--- a/apps/server/src/serverSettings.ts+++ b/apps/server/src/serverSettings.ts@@ -47,8 +47,7 @@ import { ServerConfig } from "./config.ts";import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct";import { fromJsonStringPretty, fromLenientJson } from "@t3tools/shared/schemaJson";import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";-import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";-import { ServerSecretStore } from "./auth/Services/ServerSecretStore.ts";+import * as ServerSecretStore from "./auth/ServerSecretStore.ts";const encodeServerSettings = Schema.encodeEffect(ServerSettings);const encodeServerSettingsJson = Schema.encodeUnknownEffect(fromJsonStringPretty(ServerSettings));@@ -257,7 +256,7 @@ const makeServerSettings = Effect.gen(function* () {const { settingsPath } = yield* ServerConfig;const fs = yield* FileSystem.FileSystem;const pathService = yield* Path.Path;- const secretStore = yield* ServerSecretStore;+ const secretStore = yield* ServerSecretStore.ServerSecretStore;const writeSemaphore = yield* Semaphore.make(1);const cacheKey = "settings" as const;const changesPubSub = yield* PubSub.unbounded<ServerSettings>();@@ -580,5 +579,5 @@ const makeServerSettings = Effect.gen(function* () {});export const ServerSettingsLive = Layer.effect(ServerSettingsService, makeServerSettings).pipe(- Layer.provide(ServerSecretStoreLive),+ Layer.provide(ServerSecretStore.layer),);diff --git a/apps/server/src/startupAccess.ts b/apps/server/src/startupAccess.tsindex d3b6898d7..7a03dafae 100644--- a/apps/server/src/startupAccess.ts+++ b/apps/server/src/startupAccess.ts@@ -5,7 +5,7 @@ import * as Effect from "effect/Effect";import { HttpServer } from "effect/unstable/http";import { ServerConfig } from "./config.ts";-import { ServerAuth } from "./auth/Services/ServerAuth.ts";+import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";export interface HeadlessServeAccessInfo {readonly connectionString: string;@@ -133,12 +133,12 @@ export const formatHeadlessServeOutput = (accessInfo: HeadlessServeAccessInfo):export const issueHeadlessServeAccessInfo = Effect.fn("issueHeadlessServeAccessInfo")(function* () {const serverConfig = yield* ServerConfig;const httpServer = yield* HttpServer.HttpServer;- const serverAuth = yield* ServerAuth;+ const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;const connectionString = resolveHeadlessConnectionString(serverConfig.host,resolveListeningPort(httpServer.address, serverConfig.port),);- const issued = yield* serverAuth.issuePairingCredential({ role: "owner" });+ const issued = yield* serverAuth.issueStartupPairingCredential();return {connectionString,diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex 1d0af00e3..da8e3f694 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -11,7 +11,14 @@ import * as Schema from "effect/Schema";import * as Stream from "effect/Stream";import {DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL,+ AuthOrchestrationOperateScope,+ AuthOrchestrationReadScope,+ AuthReviewWriteScope,+ AuthTerminalOperateScope,+ AuthAccessReadScope,+ AuthAccessStreamError,type AuthAccessStreamEvent,+ type AuthEnvironmentScope,AuthSessionId,CommandId,EventId,@@ -29,6 +36,7 @@ import {ProjectWriteFileError,OrchestrationReplayEventsError,FilesystemBrowseError,+ EnvironmentAuthorizationError,ThreadId,type TerminalAttachStreamEvent,type TerminalError,@@ -38,7 +46,7 @@ import {WsRpcGroup,} from "@t3tools/contracts";import { clamp } from "effect/Number";-import { HttpRouter, HttpServerRequest } from "effect/unstable/http";+import { HttpRouter, HttpServerRequest, HttpServerRespondable } from "effect/unstable/http";import { RpcSerialization, RpcServer } from "effect/unstable/rpc";import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery.ts";@@ -49,9 +57,9 @@ import { normalizeDispatchCommand } from "./orchestration/Normalizer.ts";import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts";import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";import {- observeRpcEffect,- observeRpcStream,- observeRpcStreamEffect,+ observeRpcEffect as instrumentRpcEffect,+ observeRpcStream as instrumentRpcStream,+ observeRpcStreamEffect as instrumentRpcStreamEffect,} from "./observability/RpcInstrumentation.ts";import { ProviderRegistry } from "./provider/Services/ProviderRegistry.ts";import * as ProviderMaintenanceRunner from "./provider/providerMaintenanceRunner.ts";@@ -69,7 +77,8 @@ import { ReviewService } from "./review/ReviewService.ts";import { ProjectSetupScriptRunner } from "./project/Services/ProjectSetupScriptRunner.ts";import { RepositoryIdentityResolver } from "./project/Services/RepositoryIdentityResolver.ts";import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";-import { ServerAuth } from "./auth/Services/ServerAuth.ts";+import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";+import type { AuthenticatedSession } from "./auth/EnvironmentAuth.ts";import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";@@ -84,15 +93,9 @@ import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";import * as VcsDriverRegistry from "./vcs/VcsDriverRegistry.ts";import * as VcsProjectConfig from "./vcs/VcsProjectConfig.ts";import * as VcsProcess from "./vcs/VcsProcess.ts";-import {- BootstrapCredentialService,- type BootstrapCredentialChange,-} from "./auth/Services/BootstrapCredentialService.ts";-import {- SessionCredentialService,- type SessionCredentialChange,-} from "./auth/Services/SessionCredentialService.ts";-import { respondToAuthError } from "./auth/http.ts";+import * as PairingGrantStore from "./auth/PairingGrantStore.ts";+import * as SessionStore from "./auth/SessionStore.ts";+import { failEnvironmentAuthInvalid, failEnvironmentInternal } from "./auth/http.ts";const isOrchestrationDispatchCommandError = Schema.is(OrchestrationDispatchCommandError);const isWorkspacePathOutsideRootError = Schema.is(WorkspacePathOutsideRootError);@@ -122,8 +125,62 @@ function isThreadDetailEvent(event: OrchestrationEvent): event is Extract<const PROVIDER_STATUS_DEBOUNCE_MS = 200;+const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([+ [ORCHESTRATION_WS_METHODS.dispatchCommand, AuthOrchestrationOperateScope],+ [ORCHESTRATION_WS_METHODS.getTurnDiff, AuthOrchestrationReadScope],+ [ORCHESTRATION_WS_METHODS.getFullThreadDiff, AuthOrchestrationReadScope],+ [ORCHESTRATION_WS_METHODS.replayEvents, AuthOrchestrationReadScope],+ [ORCHESTRATION_WS_METHODS.subscribeShell, AuthOrchestrationReadScope],+ [ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot, AuthOrchestrationReadScope],+ [ORCHESTRATION_WS_METHODS.subscribeThread, AuthOrchestrationReadScope],+ [WS_METHODS.serverGetConfig, AuthOrchestrationReadScope],+ [WS_METHODS.serverRefreshProviders, AuthOrchestrationOperateScope],+ [WS_METHODS.serverUpdateProvider, AuthOrchestrationOperateScope],+ [WS_METHODS.serverUpsertKeybinding, AuthOrchestrationOperateScope],+ [WS_METHODS.serverRemoveKeybinding, AuthOrchestrationOperateScope],+ [WS_METHODS.serverGetSettings, AuthOrchestrationReadScope],+ [WS_METHODS.serverUpdateSettings, AuthOrchestrationOperateScope],+ [WS_METHODS.serverDiscoverSourceControl, AuthOrchestrationReadScope],+ [WS_METHODS.serverGetTraceDiagnostics, AuthOrchestrationReadScope],+ [WS_METHODS.serverGetProcessDiagnostics, AuthOrchestrationReadScope],+ [WS_METHODS.serverGetProcessResourceHistory, AuthOrchestrationReadScope],+ [WS_METHODS.serverSignalProcess, AuthOrchestrationOperateScope],+ [WS_METHODS.sourceControlLookupRepository, AuthOrchestrationReadScope],+ [WS_METHODS.sourceControlCloneRepository, AuthOrchestrationOperateScope],+ [WS_METHODS.sourceControlPublishRepository, AuthOrchestrationOperateScope],+ [WS_METHODS.projectsSearchEntries, AuthOrchestrationReadScope],+ [WS_METHODS.projectsWriteFile, AuthOrchestrationOperateScope],+ [WS_METHODS.shellOpenInEditor, AuthOrchestrationOperateScope],+ [WS_METHODS.filesystemBrowse, AuthOrchestrationReadScope],+ [WS_METHODS.subscribeVcsStatus, AuthOrchestrationReadScope],+ [WS_METHODS.vcsRefreshStatus, AuthOrchestrationReadScope],+ [WS_METHODS.vcsPull, AuthOrchestrationOperateScope],+ [WS_METHODS.gitRunStackedAction, AuthOrchestrationOperateScope],+ [WS_METHODS.gitResolvePullRequest, AuthOrchestrationOperateScope],+ [WS_METHODS.gitPreparePullRequestThread, AuthOrchestrationOperateScope],+ [WS_METHODS.vcsListRefs, AuthOrchestrationReadScope],+ [WS_METHODS.vcsCreateWorktree, AuthOrchestrationOperateScope],+ [WS_METHODS.vcsRemoveWorktree, AuthOrchestrationOperateScope],+ [WS_METHODS.vcsCreateRef, AuthOrchestrationOperateScope],+ [WS_METHODS.vcsSwitchRef, AuthOrchestrationOperateScope],+ [WS_METHODS.vcsInit, AuthOrchestrationOperateScope],+ [WS_METHODS.reviewGetDiffPreview, AuthReviewWriteScope],+ [WS_METHODS.terminalOpen, AuthTerminalOperateScope],+ [WS_METHODS.terminalAttach, AuthTerminalOperateScope],+ [WS_METHODS.terminalWrite, AuthTerminalOperateScope],+ [WS_METHODS.terminalResize, AuthTerminalOperateScope],+ [WS_METHODS.terminalClear, AuthTerminalOperateScope],+ [WS_METHODS.terminalRestart, AuthTerminalOperateScope],+ [WS_METHODS.terminalClose, AuthTerminalOperateScope],+ [WS_METHODS.subscribeTerminalEvents, AuthTerminalOperateScope],+ [WS_METHODS.subscribeTerminalMetadata, AuthTerminalOperateScope],+ [WS_METHODS.subscribeServerConfig, AuthOrchestrationReadScope],+ [WS_METHODS.subscribeServerLifecycle, AuthOrchestrationReadScope],+ [WS_METHODS.subscribeAuthAccess, AuthAccessReadScope],+]);+function toAuthAccessStreamEvent(- change: BootstrapCredentialChange | SessionCredentialChange,+ change: PairingGrantStore.BootstrapCredentialChange | SessionStore.SessionCredentialChange,revision: number,currentSessionId: AuthSessionId,): AuthAccessStreamEvent {@@ -162,9 +219,10 @@ function toAuthAccessStreamEvent(}}-const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>+const makeWsRpcLayer = (currentSession: AuthenticatedSession) =>WsRpcGroup.toLayer(Effect.gen(function* () {+ const currentSessionId = currentSession.sessionId;const crypto = yield* Crypto.Crypto;const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;const orchestrationEngine = yield* OrchestrationEngineService;@@ -187,7 +245,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>const projectSetupScriptRunner = yield* ProjectSetupScriptRunner;const repositoryIdentityResolver = yield* RepositoryIdentityResolver;const serverEnvironment = yield* ServerEnvironment;- const serverAuth = yield* ServerAuth;+ const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;const sourceControlDiscovery = yield* SourceControlDiscoveryLayer.SourceControlDiscovery;const automaticGitFetchInterval = serverSettings.getSettings.pipe(Effect.map((settings) => settings.automaticGitFetchInterval),@@ -198,10 +256,70 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>),);const sourceControlRepositories = yield* SourceControlRepositoryService;- const bootstrapCredentials = yield* BootstrapCredentialService;- const sessions = yield* SessionCredentialService;+ const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;+ const sessions = yield* SessionStore.SessionStore;const processDiagnostics = yield* ProcessDiagnostics.ProcessDiagnostics;const processResourceMonitor = yield* ProcessResourceMonitor.ProcessResourceMonitor;+ const authorizationError = (requiredScope: AuthEnvironmentScope) =>+ new EnvironmentAuthorizationError({+ message: `The authenticated token is missing required scope: ${requiredScope}.`,+ requiredScope,+ });+ const authorizeEffect = <A, E, R>(+ requiredScope: AuthEnvironmentScope,+ effect: Effect.Effect<A, E, R>,+ ): Effect.Effect<A, E | EnvironmentAuthorizationError, R> =>+ currentSession.scopes.includes(requiredScope)+ ? effect+ : Effect.fail(authorizationError(requiredScope));+ const authorizeStream = <A, E, R>(+ requiredScope: AuthEnvironmentScope,+ stream: Stream.Stream<A, E, R>,+ ): Stream.Stream<A, E | EnvironmentAuthorizationError, R> =>+ currentSession.scopes.includes(requiredScope)+ ? stream+ : Stream.fail(authorizationError(requiredScope));+ const requiredScopeForMethod = (method: string): AuthEnvironmentScope => {+ const requiredScope = RPC_REQUIRED_SCOPE.get(method);+ if (requiredScope === undefined) {+ throw new Error(`RPC method ${method} has no declared authorization scope.`);+ }+ return requiredScope;+ };+ const observeRpcEffect = <A, E, R>(+ method: string,+ effect: Effect.Effect<A, E, R>,+ traceAttributes?: Readonly<Record<string, unknown>>,+ ) =>+ instrumentRpcEffect(+ method,+ authorizeEffect(requiredScopeForMethod(method), effect),+ traceAttributes,+ );+ const observeRpcStream = <A, E, R>(+ method: string,+ stream: Stream.Stream<A, E, R>,+ traceAttributes?: Readonly<Record<string, unknown>>,+ ) =>+ instrumentRpcStream(+ method,+ authorizeStream(requiredScopeForMethod(method), stream),+ traceAttributes,+ );+ const observeRpcStreamEffect = <A, StreamError, StreamContext, EffectError, EffectContext>(+ method: string,+ effect: Effect.Effect<+ Stream.Stream<A, StreamError, StreamContext>,+ EffectError,+ EffectContext+ >,+ traceAttributes?: Readonly<Record<string, unknown>>,+ ) =>+ instrumentRpcStreamEffect(+ method,+ authorizeEffect(requiredScopeForMethod(method), effect),+ traceAttributes,+ );const toDispatchCommandError = (cause: unknown, fallbackMessage: string) =>isOrchestrationDispatchCommandError(cause)? cause@@ -220,9 +338,16 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>const loadAuthAccessSnapshot = () =>Effect.all({- pairingLinks: serverAuth.listPairingLinks().pipe(Effect.orDie),- clientSessions: serverAuth.listClientSessions(currentSessionId).pipe(Effect.orDie),- });+ pairingLinks: serverAuth.listPairingLinks(),+ clientSessions: serverAuth.listClientSessions(currentSessionId),+ }).pipe(+ Effect.mapError(+ (error) =>+ new AuthAccessStreamError({+ message: error.message,+ }),+ ),+ );const appendSetupScriptActivity = (input: {readonly threadId: ThreadId;@@ -1258,7 +1383,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>const initialSnapshot = yield* loadAuthAccessSnapshot();const revisionRef = yield* Ref.make(1);const accessChanges: Stream.Stream<- BootstrapCredentialChange | SessionCredentialChange+ PairingGrantStore.BootstrapCredentialChange | SessionStore.SessionCredentialChange> = Stream.merge(bootstrapCredentials.streamChanges, sessions.streamChanges);const liveEvents: Stream.Stream<AuthAccessStreamEvent> = accessChanges.pipe(@@ -1294,14 +1419,19 @@ export const websocketRpcRouteLayer = Layer.unwrap("/ws",Effect.gen(function* () {const request = yield* HttpServerRequest.HttpServerRequest;- const serverAuth = yield* ServerAuth;- const sessions = yield* SessionCredentialService;- const session = yield* serverAuth.authenticateWebSocketUpgrade(request);+ const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;+ const sessions = yield* SessionStore.SessionStore;+ const session = yield* serverAuth.authenticateWebSocketUpgrade(request).pipe(+ Effect.catchTags({+ ServerAuthInvalidCredentialError: (error) => failEnvironmentAuthInvalid(error.reason),+ ServerAuthInternalError: (error) => failEnvironmentInternal("internal_error", error),+ }),+ );const rpcWebSocketHttpEffect = yield* RpcServer.toHttpEffectWebsocket(WsRpcGroup, {disableTracing: true,}).pipe(Effect.provide(- makeWsRpcLayer(session.sessionId).pipe(+ makeWsRpcLayer(session).pipe(Layer.provideMerge(RpcSerialization.layerJson),Layer.provide(ProviderMaintenanceRunner.layer),Layer.provide(@@ -1333,7 +1463,12 @@ export const websocketRpcRouteLayer = Layer.unwrap(() => rpcWebSocketHttpEffect,() => sessions.markDisconnected(session.sessionId),);- }).pipe(Effect.catchTag("AuthError", respondToAuthError)),+ }).pipe(+ Effect.catchTags({+ EnvironmentAuthInvalidError: HttpServerRespondable.toResponse,+ EnvironmentInternalError: HttpServerRespondable.toResponse,+ }),+ ),),),);diff --git a/apps/web/package.json b/apps/web/package.jsonindex 9ef17991e..c16a8893e 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -43,6 +43,7 @@"zustand": "^5.0.11"},"devDependencies": {+ "@effect/platform-node": "catalog:","@rolldown/plugin-babel": "^0.2.0","@tailwindcss/vite": "^4.0.0","@tanstack/router-plugin": "^1.161.0",@@ -51,7 +52,7 @@"@types/react-dom": "~19.2.3","@vercel/config": "^0.3.0","@vitejs/plugin-react": "^6.0.0",- "@vitest/browser-playwright": "^4.0.18",+ "@vitest/browser-playwright": "catalog:","babel-plugin-react-compiler": "1.0.0","msw": "2.12.11","playwright": "^1.58.2",diff --git a/apps/web/src/authBootstrap.test.ts b/apps/web/src/authBootstrap.test.tsindex e6f08f147..3f00e5947 100644--- a/apps/web/src/authBootstrap.test.ts+++ b/apps/web/src/authBootstrap.test.ts@@ -1,15 +1,17 @@-import type { DesktopBridge } from "@t3tools/contracts";+import {+ AuthSessionState as AuthSessionStateSchema,+ EnvironmentAuthInvalidError,+ type AuthBrowserSessionResult,+ type AuthCreatePairingCredentialInput,+ type AuthSessionState,+ type DesktopBridge,+} from "@t3tools/contracts";+import * as DateTime from "effect/DateTime";+import * as Effect from "effect/Effect";+import * as Schema from "effect/Schema";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-function jsonResponse(body: unknown, init?: ResponseInit) {- return new Response(JSON.stringify(body), {- headers: {- "content-type": "application/json",- },- status: 200,- ...init,- });-}+import { installEnvironmentHttpTest } from "../test/environmentHttpTest";type TestWindow = {location: URL;@@ -19,6 +21,42 @@ type TestWindow = {desktopBridge?: DesktopBridge;};+const LOOPBACK_AUTH = {+ policy: "loopback-browser",+ bootstrapMethods: ["one-time-token"],+ sessionMethods: ["browser-session-cookie"],+ sessionCookieName: "t3_session",+} as const;++const DESKTOP_AUTH = {+ policy: "desktop-managed-local",+ bootstrapMethods: ["desktop-bootstrap"],+ sessionMethods: ["browser-session-cookie"],+ sessionCookieName: "t3_session",+} as const;++const SESSION_EXPIRES_AT = DateTime.makeUnsafe("2026-04-05T00:00:00.000Z");+const encodeAuthSessionState = Schema.encodeSync(AuthSessionStateSchema);++const unauthenticatedSession = (auth: AuthSessionState["auth"]): AuthSessionState => ({+ authenticated: false,+ auth,+});++const authenticatedSession = (auth: AuthSessionState["auth"]): AuthSessionState => ({+ authenticated: true,+ auth,+ sessionMethod: "browser-session-cookie",+ expiresAt: SESSION_EXPIRES_AT,+});++const browserSession = (scopes: AuthBrowserSessionResult["scopes"]): AuthBrowserSessionResult => ({+ authenticated: true,+ scopes,+ sessionMethod: "browser-session-cookie",+ expiresAt: SESSION_EXPIRES_AT,+});+function installTestBrowser(url: string) {const testWindow: TestWindow = {location: new URL(url),@@ -35,8 +73,36 @@ function installTestBrowser(url: string) {return testWindow;}-function sessionResponse(body: unknown, init?: ResponseInit) {- return jsonResponse(body, init);+function sequence<A>(...values: ReadonlyArray<A>) {+ let index = 0;+ return () => values[Math.min(index++, values.length - 1)]!;+}++let disposeHttpTest: (() => Promise<void>) | undefined;++async function installAuthApi(input: {+ readonly session?: () => AuthSessionState;+ readonly browserSession?: (+ credential: string,+ ) => Effect.Effect<AuthBrowserSessionResult, EnvironmentAuthInvalidError>;+ readonly pairingCredential?: (payload: AuthCreatePairingCredentialInput) => Effect.Effect<{+ readonly id: string;+ readonly credential: string;+ readonly label?: string;+ readonly expiresAt: DateTime.Utc;+ }>;+}) {+ const testApi = await installEnvironmentHttpTest({+ ...(input.session ? { session: () => Effect.succeed(input.session!()) } : {}),+ ...(input.browserSession+ ? { browserSession: (payload) => input.browserSession!(payload.credential) }+ : {}),+ ...(input.pairingCredential+ ? { pairingCredential: (payload) => input.pairingCredential!(payload) }+ : {}),+ });+ disposeHttpTest = testApi.dispose;+ return testApi;}describe("resolveInitialServerAuthGateState", () => {@@ -47,6 +113,8 @@ describe("resolveInitialServerAuthGateState", () => {});afterEach(async () => {+ await disposeHttpTest?.();+ disposeHttpTest = undefined;const { __resetServerAuthBootstrapForTests } = await import("./environments/primary");__resetServerAuthBootstrapForTests();vi.unstubAllEnvs();@@ -55,40 +123,14 @@ describe("resolveInitialServerAuthGateState", () => {});it("reuses an in-flight silent bootstrap attempt", async () => {- const fetchMock = vi- .fn<typeof fetch>()- .mockResolvedValueOnce(- sessionResponse({- authenticated: false,- auth: {- policy: "desktop-managed-local",- bootstrapMethods: ["desktop-bootstrap"],- sessionMethods: ["browser-session-cookie"],- sessionCookieName: "t3_session",- },- }),- )- .mockResolvedValueOnce(- jsonResponse({- authenticated: true,- sessionMethod: "browser-session-cookie",- expiresAt: "2026-04-05T00:00:00.000Z",- }),- )- .mockResolvedValueOnce(- sessionResponse({- authenticated: true,- auth: {- policy: "loopback-browser",- bootstrapMethods: ["one-time-token"],- sessionMethods: ["browser-session-cookie"],- sessionCookieName: "t3_session",- },- sessionMethod: "browser-session-cookie",- expiresAt: "2026-04-05T00:00:00.000Z",- }),- );- vi.stubGlobal("fetch", fetchMock);+ const nextSession = sequence(+ unauthenticatedSession(DESKTOP_AUTH),+ authenticatedSession(DESKTOP_AUTH),+ );+ const testApi = await installAuthApi({+ session: nextSession,+ browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])),+ });const testWindow = installTestBrowser("http://localhost/");testWindow.desktopBridge = {@@ -104,90 +146,45 @@ describe("resolveInitialServerAuthGateState", () => {await Promise.all([resolveInitialServerAuthGateState(), resolveInitialServerAuthGateState()]);- expect(fetchMock).toHaveBeenCalledTimes(3);- expect(fetchMock.mock.calls[0]?.[0]).toBe("http://localhost:3773/api/auth/session");- expect(fetchMock.mock.calls[1]?.[0]).toBe("http://localhost:3773/api/auth/bootstrap");- expect(fetchMock.mock.calls[2]?.[0]).toBe("http://localhost:3773/api/auth/session");+ expect(testApi.calls.session).toBe(2);+ expect(testApi.calls.browserSession).toEqual([{ credential: "desktop-bootstrap-token" }]);});- it("uses https fetch urls when the primary environment uses wss", async () => {- const fetchMock = vi.fn<typeof fetch>().mockResolvedValueOnce(- sessionResponse({- authenticated: false,- auth: {- policy: "loopback-browser",- bootstrapMethods: ["one-time-token"],- sessionMethods: ["browser-session-cookie"],- sessionCookieName: "t3_session",- },- }),- );- vi.stubGlobal("fetch", fetchMock);+ it("uses https urls when the primary environment uses wss", async () => {+ await installAuthApi({ session: () => unauthenticatedSession(LOOPBACK_AUTH) });vi.stubEnv("VITE_HTTP_URL", "https://remote.example.com");vi.stubEnv("VITE_WS_URL", "wss://remote.example.com");- const { resolveInitialServerAuthGateState } = await import("./environments/primary");+ const { resolveInitialServerAuthGateState, resolvePrimaryEnvironmentHttpUrl } =+ await import("./environments/primary");await expect(resolveInitialServerAuthGateState()).resolves.toEqual({status: "requires-auth",- auth: {- policy: "loopback-browser",- bootstrapMethods: ["one-time-token"],- sessionMethods: ["browser-session-cookie"],- sessionCookieName: "t3_session",- },- });-- expect(fetchMock).toHaveBeenCalledWith("https://remote.example.com/api/auth/session", {- credentials: "include",+ auth: LOOPBACK_AUTH,});+ expect(resolvePrimaryEnvironmentHttpUrl("/api/auth/session")).toBe(+ "https://remote.example.com/api/auth/session",+ );});it("uses the current origin as an auth proxy base for local dev environments", async () => {- const fetchMock = vi.fn<typeof fetch>().mockResolvedValueOnce(- sessionResponse({- authenticated: false,- auth: {- policy: "loopback-browser",- bootstrapMethods: ["one-time-token"],- sessionMethods: ["browser-session-cookie"],- sessionCookieName: "t3_session",- },- }),- );- vi.stubGlobal("fetch", fetchMock);+ await installAuthApi({ session: () => unauthenticatedSession(LOOPBACK_AUTH) });installTestBrowser("http://localhost:5735/");- const { resolveInitialServerAuthGateState } = await import("./environments/primary");+ const { resolveInitialServerAuthGateState, resolvePrimaryEnvironmentHttpUrl } =+ await import("./environments/primary");await expect(resolveInitialServerAuthGateState()).resolves.toEqual({status: "requires-auth",- auth: {- policy: "loopback-browser",- bootstrapMethods: ["one-time-token"],- sessionMethods: ["browser-session-cookie"],- sessionCookieName: "t3_session",- },- });-- expect(fetchMock).toHaveBeenCalledWith("http://localhost:5735/api/auth/session", {- credentials: "include",+ auth: LOOPBACK_AUTH,});+ expect(resolvePrimaryEnvironmentHttpUrl("/api/auth/session")).toBe(+ "http://localhost:5735/api/auth/session",+ );});it("uses the vite proxy for desktop-managed loopback auth requests during local dev", async () => {- const fetchMock = vi.fn<typeof fetch>().mockResolvedValueOnce(- sessionResponse({- authenticated: false,- auth: {- policy: "desktop-managed-local",- bootstrapMethods: ["desktop-bootstrap"],- sessionMethods: ["browser-session-cookie"],- sessionCookieName: "t3_session",- },- }),- );- vi.stubGlobal("fetch", fetchMock);+ await installAuthApi({ session: () => unauthenticatedSession(DESKTOP_AUTH) });vi.stubEnv("VITE_DEV_SERVER_URL", "http://127.0.0.1:5733");const testWindow = installTestBrowser("http://127.0.0.1:5733/");@@ -199,47 +196,25 @@ describe("resolveInitialServerAuthGateState", () => {}),} as DesktopBridge;- const { resolveInitialServerAuthGateState } = await import("./environments/primary");+ const { resolveInitialServerAuthGateState, resolvePrimaryEnvironmentHttpUrl } =+ await import("./environments/primary");await expect(resolveInitialServerAuthGateState()).resolves.toEqual({status: "requires-auth",- auth: {- policy: "desktop-managed-local",- bootstrapMethods: ["desktop-bootstrap"],- sessionMethods: ["browser-session-cookie"],- sessionCookieName: "t3_session",- },- });-- expect(fetchMock).toHaveBeenCalledWith("http://127.0.0.1:5733/api/auth/session", {- credentials: "include",+ auth: DESKTOP_AUTH,});+ expect(resolvePrimaryEnvironmentHttpUrl("/api/auth/session")).toBe(+ "http://127.0.0.1:5733/api/auth/session",+ );});it("returns a requires-auth state instead of throwing when no bootstrap credential exists", async () => {- const fetchMock = vi.fn<typeof fetch>().mockResolvedValueOnce(- sessionResponse({- authenticated: false,- auth: {- policy: "loopback-browser",- bootstrapMethods: ["one-time-token"],- sessionMethods: ["browser-session-cookie"],- sessionCookieName: "t3_session",- },- }),- );- vi.stubGlobal("fetch", fetchMock);-+ await installAuthApi({ session: () => unauthenticatedSession(LOOPBACK_AUTH) });const { resolveInitialServerAuthGateState } = await import("./environments/primary");await expect(resolveInitialServerAuthGateState()).resolves.toEqual({status: "requires-auth",- auth: {- policy: "loopback-browser",- bootstrapMethods: ["one-time-token"],- sessionMethods: ["browser-session-cookie"],- sessionCookieName: "t3_session",- },+ auth: LOOPBACK_AUTH,});});@@ -251,15 +226,10 @@ describe("resolveInitialServerAuthGateState", () => {.mockResolvedValueOnce(new Response("Bad Gateway", { status: 502 })).mockResolvedValueOnce(new Response("Bad Gateway", { status: 502 })).mockResolvedValueOnce(- sessionResponse({- authenticated: false,- auth: {- policy: "loopback-browser",- bootstrapMethods: ["one-time-token"],- sessionMethods: ["browser-session-cookie"],- sessionCookieName: "t3_session",- },- }),+ new Response(+ JSON.stringify(encodeAuthSessionState(unauthenticatedSession(LOOPBACK_AUTH))),+ { status: 200, headers: { "content-type": "application/json" } },+ ),);vi.stubGlobal("fetch", fetchMock);@@ -270,12 +240,7 @@ describe("resolveInitialServerAuthGateState", () => {await expect(gateStatePromise).resolves.toEqual({status: "requires-auth",- auth: {- policy: "loopback-browser",- bootstrapMethods: ["one-time-token"],- sessionMethods: ["browser-session-cookie"],- sessionCookieName: "t3_session",- },+ auth: LOOPBACK_AUTH,});expect(fetchMock).toHaveBeenCalledTimes(4);});@@ -298,136 +263,60 @@ describe("resolveInitialServerAuthGateState", () => {});it("allows manual token submission after the initial auth check requires pairing", async () => {- const fetchMock = vi- .fn<typeof fetch>()- .mockResolvedValueOnce(- sessionResponse({- authenticated: false,- auth: {- policy: "loopback-browser",- bootstrapMethods: ["one-time-token"],- sessionMethods: ["browser-session-cookie"],- sessionCookieName: "t3_session",- },- }),- )- .mockResolvedValueOnce(- jsonResponse({- authenticated: true,- sessionMethod: "browser-session-cookie",- expiresAt: "2026-04-05T00:00:00.000Z",- }),- )- .mockResolvedValueOnce(- sessionResponse({- authenticated: true,- auth: {- policy: "loopback-browser",- bootstrapMethods: ["one-time-token"],- sessionMethods: ["browser-session-cookie"],- sessionCookieName: "t3_session",- },- sessionMethod: "browser-session-cookie",- expiresAt: "2026-04-05T00:00:00.000Z",- }),- );- vi.stubGlobal("fetch", fetchMock);- installTestBrowser("http://localhost/");-+ const nextSession = sequence(+ unauthenticatedSession(LOOPBACK_AUTH),+ authenticatedSession(LOOPBACK_AUTH),+ );+ const testApi = await installAuthApi({+ session: nextSession,+ browserSession: () => Effect.succeed(browserSession(["orchestration:read"])),+ });const { resolveInitialServerAuthGateState, submitServerAuthCredential } =await import("./environments/primary");await expect(resolveInitialServerAuthGateState()).resolves.toEqual({status: "requires-auth",- auth: {- policy: "loopback-browser",- bootstrapMethods: ["one-time-token"],- sessionMethods: ["browser-session-cookie"],- sessionCookieName: "t3_session",- },+ auth: LOOPBACK_AUTH,});await expect(submitServerAuthCredential("retry-token")).resolves.toBeUndefined();await expect(resolveInitialServerAuthGateState()).resolves.toEqual({status: "authenticated",});- expect(fetchMock).toHaveBeenCalledTimes(3);+ expect(testApi.calls.browserSession).toEqual([{ credential: "retry-token" }]);+ expect(testApi.calls.session).toBe(2);});it("surfaces a friendly error message when an invalid pairing token is submitted", async () => {- const fetchMock = vi.fn<typeof fetch>().mockResolvedValueOnce(- jsonResponse(- {- error: "Invalid bootstrap credential.",- },- {- status: 401,- },- ),- );- vi.stubGlobal("fetch", fetchMock);+ const testApi = await installAuthApi({+ browserSession: () =>+ Effect.fail(+ new EnvironmentAuthInvalidError({+ code: "auth_invalid",+ reason: "invalid_credential",+ traceId: "trace-invalid-credential",+ }),+ ),+ });const { submitServerAuthCredential } = await import("./environments/primary");await expect(submitServerAuthCredential("bad-token")).rejects.toThrow("Invalid pairing token. Check the token and try again.",);- expect(fetchMock).toHaveBeenCalledWith("http://localhost/api/auth/bootstrap", {- body: JSON.stringify({ credential: "bad-token" }),- credentials: "include",- headers: {- "content-type": "application/json",- },- method: "POST",- });+ expect(testApi.calls.browserSession).toEqual([{ credential: "bad-token" }]);});it("waits for the authenticated session to become observable after silent desktop bootstrap", async () => {vi.useFakeTimers();- const fetchMock = vi- .fn<typeof fetch>()- .mockResolvedValueOnce(- sessionResponse({- authenticated: false,- auth: {- policy: "desktop-managed-local",- bootstrapMethods: ["desktop-bootstrap"],- sessionMethods: ["browser-session-cookie"],- sessionCookieName: "t3_session",- },- }),- )- .mockResolvedValueOnce(- jsonResponse({- authenticated: true,- sessionMethod: "browser-session-cookie",- expiresAt: "2026-04-05T00:00:00.000Z",- }),- )- .mockResolvedValueOnce(- sessionResponse({- authenticated: false,- auth: {- policy: "desktop-managed-local",- bootstrapMethods: ["desktop-bootstrap"],- sessionMethods: ["browser-session-cookie"],- sessionCookieName: "t3_session",- },- }),- )- .mockResolvedValueOnce(- sessionResponse({- authenticated: true,- auth: {- policy: "desktop-managed-local",- bootstrapMethods: ["desktop-bootstrap"],- sessionMethods: ["browser-session-cookie"],- sessionCookieName: "t3_session",- },- sessionMethod: "browser-session-cookie",- expiresAt: "2026-04-05T00:00:00.000Z",- }),- );- vi.stubGlobal("fetch", fetchMock);+ const nextSession = sequence(+ unauthenticatedSession(DESKTOP_AUTH),+ unauthenticatedSession(DESKTOP_AUTH),+ authenticatedSession(DESKTOP_AUTH),+ );+ const testApi = await installAuthApi({+ session: nextSession,+ browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])),+ });const testWindow = installTestBrowser("http://localhost/");testWindow.desktopBridge = {@@ -444,43 +333,14 @@ describe("resolveInitialServerAuthGateState", () => {const gateStatePromise = resolveInitialServerAuthGateState();await vi.advanceTimersByTimeAsync(100);- await expect(gateStatePromise).resolves.toEqual({- status: "authenticated",- });- expect(fetchMock).toHaveBeenCalledTimes(4);- expect(fetchMock.mock.calls[2]?.[0]).toBe("http://localhost:3773/api/auth/session");- expect(fetchMock.mock.calls[3]?.[0]).toBe("http://localhost:3773/api/auth/session");+ await expect(gateStatePromise).resolves.toEqual({ status: "authenticated" });+ expect(testApi.calls.session).toBe(3);});it("memoizes the authenticated gate state after the first successful read", async () => {- const fetchMock = vi- .fn<typeof fetch>()- .mockResolvedValueOnce(- sessionResponse({- authenticated: true,- auth: {- policy: "loopback-browser",- bootstrapMethods: ["one-time-token"],- sessionMethods: ["browser-session-cookie"],- sessionCookieName: "t3_session",- },- sessionMethod: "browser-session-cookie",- expiresAt: "2026-04-05T00:00:00.000Z",- }),- )- .mockResolvedValueOnce(- sessionResponse({- authenticated: false,- auth: {- policy: "loopback-browser",- bootstrapMethods: ["one-time-token"],- sessionMethods: ["browser-session-cookie"],- sessionCookieName: "t3_session",- },- }),- );- vi.stubGlobal("fetch", fetchMock);-+ const testApi = await installAuthApi({+ session: sequence(authenticatedSession(LOOPBACK_AUTH), unauthenticatedSession(LOOPBACK_AUTH)),+ });const { resolveInitialServerAuthGateState } = await import("./environments/primary");await expect(resolveInitialServerAuthGateState()).resolves.toEqual({@@ -489,35 +349,33 @@ describe("resolveInitialServerAuthGateState", () => {await expect(resolveInitialServerAuthGateState()).resolves.toEqual({status: "authenticated",});- expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(testApi.calls.session).toBe(1);});it("creates a pairing credential from the authenticated auth endpoint", async () => {- const fetchMock = vi.fn<typeof fetch>().mockResolvedValueOnce(- jsonResponse({- id: "pairing-link-1",- credential: "pairing-token",- label: "Julius iPhone",- expiresAt: "2026-04-05T00:00:00.000Z",- }),- );- vi.stubGlobal("fetch", fetchMock);-+ const testApi = await installAuthApi({+ pairingCredential: (payload) =>+ Effect.succeed({+ id: "pairing-link-1",+ credential: "pairing-token",+ ...(payload.label === undefined ? {} : { label: payload.label }),+ expiresAt: SESSION_EXPIRES_AT,+ }),+ });const { createServerPairingCredential } = await import("./environments/primary");- await expect(createServerPairingCredential("Julius iPhone")).resolves.toEqual({+ const credential = await createServerPairingCredential({+ label: "Julius iPhone",+ scopes: ["orchestration:read"],+ });+ expect(credential).toMatchObject({id: "pairing-link-1",credential: "pairing-token",label: "Julius iPhone",- expiresAt: "2026-04-05T00:00:00.000Z",- });- expect(fetchMock).toHaveBeenCalledWith("http://localhost/api/auth/pairing-token", {- body: JSON.stringify({ label: "Julius iPhone" }),- credentials: "include",- headers: {- "content-type": "application/json",- },- method: "POST",});+ expect(DateTime.formatIso(credential.expiresAt)).toBe("2026-04-05T00:00:00.000Z");+ expect(testApi.calls.pairingCredential).toEqual([+ { label: "Julius iPhone", scopes: ["orchestration:read"] },+ ]);});});diff --git a/apps/web/src/components/ChatView.browser.tsx b/apps/web/src/components/ChatView.browser.tsxindex d4eb3da32..e490ff986 100644--- a/apps/web/src/components/ChatView.browser.tsx+++ b/apps/web/src/components/ChatView.browser.tsx@@ -194,7 +194,7 @@ function createBaseServerConfig(): ServerConfig {auth: {policy: "loopback-browser",bootstrapMethods: ["one-time-token"],- sessionMethods: ["browser-session-cookie", "bearer-session-token"],+ sessionMethods: ["browser-session-cookie", "bearer-access-token"],sessionCookieName: "t3_session",},cwd: "/repo/project",diff --git a/apps/web/src/components/KeybindingsToast.browser.tsx b/apps/web/src/components/KeybindingsToast.browser.tsxindex 4320f6ecf..63715f201 100644--- a/apps/web/src/components/KeybindingsToast.browser.tsx+++ b/apps/web/src/components/KeybindingsToast.browser.tsx@@ -96,7 +96,7 @@ function createBaseServerConfig(): ServerConfig {auth: {policy: "loopback-browser",bootstrapMethods: ["one-time-token"],- sessionMethods: ["browser-session-cookie", "bearer-session-token"],+ sessionMethods: ["browser-session-cookie", "bearer-access-token"],sessionCookieName: "t3_session",},cwd: "/repo/project",diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsxindex 8549b42b5..b9aa9ce6c 100644--- a/apps/web/src/components/settings/ConnectionsSettings.tsx+++ b/apps/web/src/components/settings/ConnectionsSettings.tsx@@ -9,7 +9,18 @@ import {} from "lucide-react";import { type ReactNode, memo, useCallback, useEffect, useMemo, useState } from "react";import {+ AuthAccessReadScope,+ AuthAccessWriteScope,+ AuthAdministrativeScopes,+ AuthOrchestrationOperateScope,+ AuthOrchestrationReadScope,+ AuthRelayReadScope,+ AuthRelayWriteScope,+ AuthReviewWriteScope,+ AuthStandardClientScopes,+ AuthTerminalOperateScope,type AuthClientSession,+ type AuthEnvironmentScope,type AuthPairingLink,type AdvertisedEndpoint,type DesktopDiscoveredSshHost,@@ -31,6 +42,7 @@ import {useRelativeTimeTick,} from "./settingsLayout";import { Input } from "../ui/input";+import { Checkbox } from "../ui/checkbox";import {Dialog,DialogClose,@@ -75,11 +87,11 @@ import { getPairingTokenFromUrl, setPairingTokenOnUrl } from "../../pairingUrl";import { readHostedPairingRequest } from "../../hostedPairing";import {createServerPairingCredential,- fetchSessionState,revokeOtherServerClientSessions,revokeServerClientSession,revokeServerPairingLink,isLoopbackHostname,+ usePrimarySessionState,type ServerClientSessionRecord,type ServerPairingLinkRecord,} from "~/environments/primary";@@ -114,6 +126,97 @@ function formatAccessTimestamp(value: string): string {return accessTimestampFormatter.format(parsed);}+const PAIRING_SCOPE_OPTIONS: ReadonlyArray<{+ readonly scope: AuthEnvironmentScope;+ readonly title: string;+ readonly description: string;+}> = [+ {+ scope: AuthOrchestrationReadScope,+ title: "View environment",+ description: "Read threads, status, diffs, and configuration.",+ },+ {+ scope: AuthOrchestrationOperateScope,+ title: "Operate tasks",+ description: "Start tasks and perform changes in the environment.",+ },+ {+ scope: AuthTerminalOperateScope,+ title: "Use terminals",+ description: "Create terminals and send input to running shells.",+ },+ {+ scope: AuthReviewWriteScope,+ title: "Write reviews",+ description: "Create comments while reviewing changes.",+ },+ {+ scope: AuthAccessReadScope,+ title: "View access",+ description: "Inspect pairing links and authorized clients.",+ },+ {+ scope: AuthAccessWriteScope,+ title: "Manage access",+ description: "Issue and revoke credentials for other clients.",+ },+ {+ scope: AuthRelayReadScope,+ title: "View relay",+ description: "Inspect managed relay connectivity.",+ },+ {+ scope: AuthRelayWriteScope,+ title: "Manage relay",+ description: "Change managed tunnel connectivity.",+ },+];++function AccessScopeSummary({+ scopes,+ label,+}: {+ readonly scopes: ReadonlyArray<AuthEnvironmentScope>;+ readonly label: string;+}) {+ const scopeCountLabel = `${scopes.length} ${scopes.length === 1 ? "scope" : "scopes"}`;++ return (+ <Popover>+ <PopoverTrigger+ openOnHover+ delay={250}+ closeDelay={100}+ render={+ <button+ type="button"+ aria-label={`${label}: show ${scopeCountLabel}`}+ className="cursor-help underline decoration-border underline-offset-2 outline-hidden hover:text-foreground focus-visible:text-foreground"+ />+ }+ >+ {scopeCountLabel}+ </PopoverTrigger>+ <PopoverPopup+ side="top"+ align="start"+ tooltipStyle+ className="w-max max-w-80 whitespace-normal"+ >+ <p className="mb-1 font-medium">Granted scopes</p>+ <div className="flex flex-col gap-0.5">+ {scopes.map((scope) => (+ <code key={scope} className="font-mono text-foreground/85">+ {scope}+ </code>+ ))}+ </div>+ </PopoverPopup>+ </Popover>+ );+}+type ConnectionStatusDotProps = {tooltipText?: string | null;dotClassName: string;@@ -629,8 +732,7 @@ const PairingLinkListRow = memo(function PairingLinkListRow({const expiresAbsolute = formatAccessTimestamp(pairingLink.expiresAt);- const roleLabel = pairingLink.role === "owner" ? "Owner" : "Client";- const primaryLabel = pairingLink.label ?? `${roleLabel} link`;+ const primaryLabel = pairingLink.label ?? "Pairing link";const defaultEndpointCopyOption =endpointCopyOptions.find((option) => option.key === defaultEndpointKey) ??endpointCopyOptions[0] ??@@ -759,7 +861,9 @@ const PairingLinkListRow = memo(function PairingLinkListRow({</Popover></div><p className="text-xs text-muted-foreground" title={expiresAbsolute}>- {[roleLabel, formatExpiresInLabel(pairingLink.expiresAt, nowMs)].join(" · ")}+ {formatExpiresInLabel(pairingLink.expiresAt, nowMs)}+ <span aria-hidden> · </span>+ <AccessScopeSummary scopes={pairingLink.scopes} label="Pairing link scopes" /></p>{shareablePairingUrl === null ? (<p className="text-[11px] text-muted-foreground/70">@@ -900,7 +1004,6 @@ const ConnectedClientListRow = memo(function ConnectedClientListRow({: lastConnectedAt? `Last connected at ${formatAccessTimestamp(lastConnectedAt)}`: "Not connected yet.";- const roleLabel = clientSession.role === "owner" ? "Owner" : "Client";const deviceInfoBits = [clientSession.client.deviceType !== "unknown"? clientSession.client.deviceType[0]?.toUpperCase() + clientSession.client.deviceType.slice(1)@@ -932,7 +1035,13 @@ const ConnectedClientListRow = memo(function ConnectedClientListRow({) : null}</div><p className="text-xs text-muted-foreground">- {[roleLabel, ...deviceInfoBits].join(" · ")}+ {deviceInfoBits.length > 0 ? (+ <>+ {deviceInfoBits.join(" · ")}+ <span aria-hidden> · </span>+ </>+ ) : null}+ <AccessScopeSummary scopes={clientSession.scopes} label="Client scopes" /></p></div><div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">@@ -965,13 +1074,17 @@ const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHeaderActio}: AuthorizedClientsHeaderActionProps) {const [dialogOpen, setDialogOpen] = useState(false);const [pairingLabel, setPairingLabel] = useState("");+ const [pairingScopes, setPairingScopes] = useState<ReadonlyArray<AuthEnvironmentScope>>([+ ...AuthStandardClientScopes,+ ]);const [isCreatingPairingLink, setIsCreatingPairingLink] = useState(false);const handleCreatePairingLink = useCallback(async () => {setIsCreatingPairingLink(true);try {- await createServerPairingCredential(pairingLabel);+ await createServerPairingCredential({ label: pairingLabel, scopes: pairingScopes });setPairingLabel("");+ setPairingScopes([...AuthStandardClientScopes]);setDialogOpen(false);} catch (error) {const message = error instanceof Error ? error.message : "Failed to create pairing URL.";@@ -985,7 +1098,13 @@ const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHeaderActio} finally {setIsCreatingPairingLink(false);}- }, [pairingLabel]);+ }, [pairingLabel, pairingScopes]);++ const togglePairingScope = useCallback((scope: AuthEnvironmentScope, checked: boolean) => {+ setPairingScopes((current) =>+ checked ? [...current, scope] : current.filter((currentScope) => currentScope !== scope),+ );+ }, []);return (<div className="flex items-center gap-2">@@ -1005,6 +1124,7 @@ const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHeaderActiosetDialogOpen(open);if (!open) {setPairingLabel("");+ setPairingScopes([...AuthStandardClientScopes]);}}}>@@ -1016,7 +1136,7 @@ const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHeaderActio</Button>}/>- <DialogPopup className="max-w-sm">+ <DialogPopup className="max-w-md"><DialogHeader><DialogTitle>Create pairing link</DialogTitle><DialogDescription>@@ -1024,7 +1144,7 @@ const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHeaderActioauthorized client.</DialogDescription></DialogHeader>- <DialogPanel>+ <DialogPanel className="space-y-5"><label className="block"><span className="mb-1.5 block text-xs font-medium text-foreground">Client label (optional)@@ -1037,6 +1157,62 @@ const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHeaderActioautoFocus/></label>+ <section className="space-y-3">+ <div className="flex items-center justify-between gap-3">+ <div>+ <h3 className="text-xs font-medium text-foreground">Permissions</h3>+ <p className="text-xs text-muted-foreground">+ Limit what the paired client can do.+ </p>+ </div>+ <div className="flex gap-1">+ <Button+ size="xs"+ variant="outline"+ disabled={isCreatingPairingLink}+ onClick={() => setPairingScopes([AuthOrchestrationReadScope])}+ >+ Read only+ </Button>+ <Button+ size="xs"+ variant="outline"+ disabled={isCreatingPairingLink}+ onClick={() => setPairingScopes([...AuthStandardClientScopes])}+ >+ Standard+ </Button>+ </div>+ </div>+ <div className="divide-y divide-border/60 rounded-lg border border-input bg-muted/25">+ {PAIRING_SCOPE_OPTIONS.map(({ scope, title, description }) => (+ <label+ key={scope}+ className="flex cursor-pointer items-start gap-3 px-3 py-2.5 transition-colors hover:bg-muted/40"+ >+ <Checkbox+ className="mt-0.5"+ checked={pairingScopes.includes(scope)}+ disabled={isCreatingPairingLink}+ onCheckedChange={(checked) => togglePairingScope(scope, checked === true)}+ />+ <span className="min-w-0">+ <span className="block text-xs font-medium text-foreground">{title}</span>+ <span className="block text-xs leading-snug text-muted-foreground">+ {description}+ </span>+ </span>+ </label>+ ))}+ </div>+ {pairingScopes.length === 0 ? (+ <p className="text-xs text-destructive">Select at least one permission.</p>+ ) : pairingScopes.includes(AuthAccessWriteScope) ? (+ <p className="text-xs text-warning">+ This client can create or revoke access for other devices.+ </p>+ ) : null}+ </section></DialogPanel><DialogFooter variant="bare"><Button@@ -1046,7 +1222,10 @@ const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHeaderActio>Cancel</Button>- <Button disabled={isCreatingPairingLink} onClick={() => void handleCreatePairingLink()}>+ <Button+ disabled={isCreatingPairingLink || pairingScopes.length === 0}+ onClick={() => void handleCreatePairingLink()}+ >{isCreatingPairingLink ? "Creating…" : "Create link"}</Button></DialogFooter>@@ -1290,14 +1469,12 @@ function SavedBackendListRow({: connectionState === "error"? "bg-destructive": "bg-muted-foreground/40";- const roleLabel = runtime?.role ? (runtime.role === "owner" ? "Owner" : "Client") : null;const descriptorLabel = runtime?.descriptor?.label ?? null;const displayLabel = descriptorLabel ?? record.label;const statusTooltip = getSavedBackendStatusTooltip(runtime, record, nowMs);const versionMismatch = resolveServerConfigVersionMismatch(runtime?.serverConfig);const metadataBits = [record.desktopSsh ? `SSH ${formatDesktopSshTarget(record.desktopSsh)}` : null,- roleLabel,record.lastConnectedAt? `Last connected ${formatAccessTimestamp(record.lastConnectedAt)}`: null,@@ -1317,8 +1494,14 @@ function SavedBackendListRow({/><h3 className="text-sm font-medium text-foreground">{displayLabel}</h3></div>- {metadataBits.length > 0 ? (- <p className="text-xs text-muted-foreground">{metadataBits.join(" · ")}</p>+ {metadataBits.length > 0 || runtime?.scopes ? (+ <p className="text-xs text-muted-foreground">+ {metadataBits.length > 0 ? metadataBits.join(" · ") : null}+ {metadataBits.length > 0 && runtime?.scopes ? <span aria-hidden> · </span> : null}+ {runtime?.scopes ? (+ <AccessScopeSummary scopes={runtime.scopes} label="Granted scopes" />+ ) : null}+ </p>) : null}{versionMismatch ? (<p className="flex items-center gap-1 text-warning text-xs">@@ -1401,12 +1584,13 @@ const DesktopSshHostRow = memo(function DesktopSshHostRow({export function ConnectionsSettings() {const desktopBridge = window.desktopBridge;- const [currentSessionRole, setCurrentSessionRole] = useState<"owner" | "client" | null>(- desktopBridge ? "owner" : null,- );- const [currentAuthPolicy, setCurrentAuthPolicy] = useState<- "desktop-managed-local" | "loopback-browser" | "remote-reachable" | "unsafe-no-auth" | null- >(desktopBridge ? null : null);+ const primarySessionState = usePrimarySessionState();+ const currentSessionScopes = desktopBridge+ ? AuthAdministrativeScopes+ : primarySessionState.data?.authenticated+ ? (primarySessionState.data.scopes ?? null)+ : null;+ const currentAuthPolicy = desktopBridge ? null : (primarySessionState.data?.auth.policy ?? null);const savedEnvironmentsById = useSavedEnvironmentRegistryStore((state) => state.byId);const savedEnvironmentIds = useMemo(() =>@@ -1516,7 +1700,7 @@ export function ConnectionsSettings() {const setDefaultAdvertisedEndpointKey = useUiStateStore((state) => state.setDefaultAdvertisedEndpointKey,);- const canManageLocalBackend = currentSessionRole === "owner";+ const canManageLocalBackend = currentSessionScopes?.includes(AuthAccessWriteScope) ?? false;const isLocalBackendNetworkAccessible = desktopBridge? desktopServerExposureState?.mode === "network-accessible": currentAuthPolicy === "remote-reachable";@@ -1929,30 +2113,6 @@ export function ConnectionsSettings() {savedBackendMode,]);- useEffect(() => {- if (desktopBridge) {- setCurrentSessionRole("owner");- return;- }-- let cancelled = false;- void fetchSessionState()- .then((session) => {- if (cancelled) return;- setCurrentSessionRole(session.authenticated ? (session.role ?? null) : null);- setCurrentAuthPolicy(session.auth.policy);- })- .catch(() => {- if (cancelled) return;- setCurrentSessionRole(null);- setCurrentAuthPolicy(null);- });-- return () => {- cancelled = true;- };- }, [desktopBridge]);-useEffect(() => {if (!canManageLocalBackend) return;@@ -2065,10 +2225,7 @@ export function ConnectionsSettings() {setDesktopAdvertisedEndpoints([]);setDesktopServerExposureError(null);}, [canManageLocalBackend]);- const visibleDesktopPairingLinks = useMemo(- () => desktopPairingLinks.filter((pairingLink) => pairingLink.role === "client"),- [desktopPairingLinks],- );+ const visibleDesktopPairingLinks = desktopPairingLinks;const tailscaleHttpsEndpoint = useMemo(() => desktopAdvertisedEndpoints.find(isTailscaleHttpsEndpoint) ?? null,[desktopAdvertisedEndpoints],@@ -2650,8 +2807,8 @@ export function ConnectionsSettings() {) : (<SettingsSection title="Local backend access"><SettingsRow- title="Owner tools"- description="Pairing links and client-session management are only available to owner sessions for this backend."+ title="Administrative access"+ description="Pairing links and client-session management require the access:write scope for this backend."/></SettingsSection>)}diff --git a/apps/web/src/components/settings/SettingsPanels.browser.tsx b/apps/web/src/components/settings/SettingsPanels.browser.tsxindex 34f24006e..9427a91f9 100644--- a/apps/web/src/components/settings/SettingsPanels.browser.tsx+++ b/apps/web/src/components/settings/SettingsPanels.browser.tsx@@ -3,6 +3,7 @@ import "../../index.css";import {type AuthAccessStreamEvent,type AuthAccessSnapshot,+ type AuthEnvironmentScope,AuthSessionId,DEFAULT_SERVER_SETTINGS,EnvironmentId,@@ -217,7 +218,7 @@ function createBaseServerConfig(): ServerConfig {auth: {policy: "loopback-browser",bootstrapMethods: ["one-time-token"],- sessionMethods: ["browser-session-cookie", "bearer-session-token"],+ sessionMethods: ["browser-session-cookie", "bearer-access-token"],sessionCookieName: "t3_session",},cwd: "/repo/project",@@ -286,7 +287,7 @@ function createEmptyProcessResourceHistoryResult(): ServerProcessResourceHistoryfunction makePairingLink(input: {readonly id: string;readonly credential: string;- readonly role: "owner" | "client";+ readonly scopes: ReadonlyArray<AuthEnvironmentScope>;readonly subject: string;readonly label?: string;readonly createdAt: string;@@ -302,7 +303,7 @@ function makePairingLink(input: {function makeClientSession(input: {readonly sessionId: string;readonly subject: string;- readonly role: "owner" | "client";+ readonly scopes: ReadonlyArray<AuthEnvironmentScope>;readonly method: "browser-session-cookie";readonly client?: {readonly label?: string;@@ -394,26 +395,26 @@ const createDesktopBridgeStub = (overrides?: {},}),bootstrapSshBearerSession: vi.fn().mockResolvedValue({- authenticated: true,- role: "owner",- sessionMethod: "bearer-session-token",- expiresAt: "2026-05-01T12:00:00.000Z",- sessionToken: "ssh-bearer-token",+ access_token: "ssh-bearer-token",+ issued_token_type: "urn:ietf:params:oauth:token-type:access_token",+ token_type: "Bearer",+ expires_in: 3_600,+ scope: "orchestration:read orchestration:operate terminal:operate review:write relay:read",}),fetchSshSessionState: vi.fn().mockResolvedValue({authenticated: true,auth: {policy: "remote-reachable",bootstrapMethods: ["one-time-token"],- sessionMethods: ["browser-session-cookie", "bearer-session-token"],+ sessionMethods: ["browser-session-cookie", "bearer-access-token"],sessionCookieName: "t3_session",},- role: "owner",- sessionMethod: "bearer-session-token",+ scopes: ["orchestration:read", "access:write"],+ sessionMethod: "bearer-access-token",expiresAt: "2026-05-01T12:00:00.000Z",}),- issueSshWebSocketToken: vi.fn().mockResolvedValue({- token: "ssh-ws-token",+ issueSshWebSocketTicket: vi.fn().mockResolvedValue({+ ticket: "ssh-ws-ticket",expiresAt: "2026-05-01T12:05:00.000Z",}),onSshPasswordPrompt: vi.fn(() => () => {}),@@ -508,7 +509,7 @@ describe("GeneralSettingsPanel observability", () => {makeClientSession({sessionId: "session-owner",subject: "browser-owner",- role: "owner",+ scopes: ["orchestration:read", "access:write"],method: "browser-session-cookie",client: {label: "Chrome on Mac",@@ -531,7 +532,7 @@ describe("GeneralSettingsPanel observability", () => {JSON.stringify({authenticated: true,auth: createBaseServerConfig().auth,- role: "owner",+ scopes: ["orchestration:read", "access:write"],sessionMethod: "browser-session-cookie",expiresAt: "2036-05-07T00:00:00.000Z",}),@@ -776,7 +777,7 @@ describe("GeneralSettingsPanel observability", () => {makeClientSession({sessionId: "session-owner",subject: "desktop-bootstrap",- role: "owner",+ scopes: ["orchestration:read", "access:write"],method: "browser-session-cookie",client: {label: "This Mac",@@ -805,7 +806,7 @@ describe("GeneralSettingsPanel observability", () => {makePairingLink({id: "pairing-link-1",credential: "pairing-token",- role: "client",+ scopes: ["orchestration:read"],subject: "one-time-token",label: "Julius iPhone",createdAt: "2036-04-07T00:00:00.000Z",@@ -817,7 +818,7 @@ describe("GeneralSettingsPanel observability", () => {makeClientSession({sessionId: "session-client",subject: "one-time-token",- role: "client",+ scopes: ["orchestration:read"],method: "browser-session-cookie",client: {label: "Julius iPhone",@@ -867,12 +868,22 @@ describe("GeneralSettingsPanel observability", () => {await expect.element(page.getByText("This Mac")).toBeInTheDocument();await page.getByRole("button", { name: "Create link", exact: true }).click();await expect.element(page.getByText("Create pairing link")).toBeInTheDocument();+ await expect.element(page.getByRole("checkbox", { name: /View environment/ })).toBeChecked();+ await expect.element(page.getByRole("checkbox", { name: /Operate tasks/ })).toBeChecked();+ await page.getByRole("button", { name: "Read only", exact: true }).click();+ await expect.element(page.getByRole("checkbox", { name: /View environment/ })).toBeChecked();+ await expect.element(page.getByRole("checkbox", { name: /Operate tasks/ })).not.toBeChecked();await page.getByRole("button", { name: "Create link", exact: true }).click();authAccessHarness.emitPairingLinkUpserted(pairingLinks[0]!);authAccessHarness.emitClientUpserted(clientSessions[1]!);await expect- .element(page.getByText("Client · Mobile · iOS · Safari · 192.168.1.88"))+ .element(page.getByRole("button", { name: "Pairing link scopes: show 1 scope" }))+ .toBeInTheDocument();+ await expect+ .element(page.getByText("Mobile · iOS · Safari · 192.168.1.88")).toBeInTheDocument();+ await page.getByRole("button", { name: "Client scopes: show 1 scope" }).click();+ await expect.element(page.getByText("orchestration:read", { exact: true })).toBeInTheDocument();await expect.element(page.getByRole("button", { name: /^Copy pairing URL for:/ })).toBeInTheDocument();@@ -893,7 +904,7 @@ describe("GeneralSettingsPanel observability", () => {makeClientSession({sessionId: "session-owner",subject: "desktop-bootstrap",- role: "owner",+ scopes: ["orchestration:read", "access:write"],method: "browser-session-cookie",client: {label: "This Mac",@@ -909,7 +920,7 @@ describe("GeneralSettingsPanel observability", () => {makeClientSession({sessionId: "session-client",subject: "one-time-token",- role: "client",+ scopes: ["orchestration:read"],method: "browser-session-cookie",client: {label: "Julius iPhone",diff --git a/apps/web/src/environments/primary/auth.ts b/apps/web/src/environments/primary/auth.tsindex 9a7e39a02..40bd277fc 100644--- a/apps/web/src/environments/primary/auth.ts+++ b/apps/web/src/environments/primary/auth.ts@@ -1,21 +1,25 @@import type {- AuthBootstrapInput,- AuthBootstrapResult,+ AuthBrowserSessionResult,AuthClientMetadata,- AuthCreatePairingCredentialInput,+ AuthEnvironmentScope,AuthPairingCredentialResult,- AuthRevokeClientSessionInput,- AuthRevokePairingLinkInput,AuthSessionId,AuthSessionState,} from "@t3tools/contracts";+import { EnvironmentHttpCommonError } from "@t3tools/contracts";+import type { EnvironmentHttpCommonError as EnvironmentHttpCommonErrorType } from "@t3tools/contracts";+import * as DateTime from "effect/DateTime";+import * as Effect from "effect/Effect";+import * as Schema from "effect/Schema";+import { HttpClientError } from "effect/unstable/http";import {getPairingTokenFromUrl,stripPairingTokenFromUrl as stripPairingTokenUrl,} from "../../pairingUrl";-import { resolvePrimaryEnvironmentHttpUrl } from "./target";+import { PrimaryEnvironmentHttpClient } from "./httpClient";+import { runPrimaryHttp } from "../../lib/runtime";import * as Data from "effect/Data";import * as Predicate from "effect/Predicate";@@ -25,11 +29,12 @@ export class BootstrapHttpError extends Data.TaggedError("BootstrapHttpError")<{}> {}const isBootstrapHttpError = (u: unknown): u is BootstrapHttpError =>Predicate.isTagged(u, "BootstrapHttpError");+const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);export interface ServerPairingLinkRecord {readonly id: string;readonly credential: string;- readonly role: "owner" | "client";+ readonly scopes: ReadonlyArray<AuthEnvironmentScope>;readonly subject: string;readonly label?: string;readonly createdAt: string;@@ -39,8 +44,8 @@ export interface ServerPairingLinkRecord {export interface ServerClientSessionRecord {readonly sessionId: AuthSessionId;readonly subject: string;- readonly role: "owner" | "client";- readonly method: "browser-session-cookie" | "bearer-session-token";+ readonly scopes: ReadonlyArray<AuthEnvironmentScope>;+ readonly method: "browser-session-cookie" | "bearer-access-token";readonly client: AuthClientMetadata;readonly issuedAt: string;readonly expiresAt: string;@@ -93,79 +98,97 @@ function getDesktopBootstrapCredential(): string | null {export async function fetchSessionState(): Promise<AuthSessionState> {return retryTransientBootstrap(async () => {- const response = await fetch(resolvePrimaryEnvironmentHttpUrl("/api/auth/session"), {- credentials: "include",- });- if (!response.ok) {+ try {+ return await runPrimaryHttp(+ PrimaryEnvironmentHttpClient.pipe(+ Effect.flatMap((client) => client.auth.session({ headers: {} })),+ ),+ );+ } catch (error) {+ const status = readHttpApiStatus(error);throw new BootstrapHttpError({- message: `Failed to load server auth session state (${response.status}).`,- status: response.status,+ message: `Failed to load server auth session state (${status ?? "unknown"}).`,+ status: status ?? 500,});}- return (await response.json()) as AuthSessionState;});}-async function readErrorMessage(response: Response, fallbackMessage: string): Promise<string> {- const text = await response.text();- return text || fallbackMessage;+function readHttpApiStatus(error: unknown): number | null {+ if (isEnvironmentHttpCommonError(error)) {+ return readEnvironmentHttpErrorStatus(error);+ }+ return HttpClientError.isHttpClientError(error) && error.response !== undefined+ ? error.response.status+ : null;}-const INVALID_BOOTSTRAP_CREDENTIAL_MESSAGES = new Set([- "Invalid bootstrap credential.",- "Unknown bootstrap credential.",-]);--function parseBootstrapErrorMessage(message: string): string {- const trimmed = message.trim();- if (trimmed.length === 0) {- return "";+function readEnvironmentHttpErrorStatus(error: EnvironmentHttpCommonErrorType): number {+ switch (error._tag) {+ case "EnvironmentRequestInvalidError":+ return 400;+ case "EnvironmentAuthInvalidError":+ return 401;+ case "EnvironmentScopeRequiredError":+ case "EnvironmentOperationForbiddenError":+ return 403;+ case "EnvironmentInternalError":+ return 500;}+}- try {- const parsed = JSON.parse(trimmed) as {- error?: unknown;- };- if (typeof parsed.error === "string" && parsed.error.trim().length > 0) {- return parsed.error.trim();- }- } catch {- // Not JSON; fall back to plain text.+function readHttpApiErrorMessage(error: unknown, fallbackMessage: string): string {+ if (!isEnvironmentHttpCommonError(error)) {+ return fallbackMessage;+ }+ switch (error._tag) {+ case "EnvironmentAuthInvalidError":+ return error.reason === "missing_credential"+ ? "Authentication required."+ : "Invalid bootstrap credential.";+ case "EnvironmentRequestInvalidError":+ return error.reason === "invalid_scope"+ ? "Requested token scope is invalid."+ : "Requested scope exceeds the bootstrap credential grant.";+ case "EnvironmentScopeRequiredError":+ return `The authenticated token is missing required scope: ${error.requiredScope}.`;+ case "EnvironmentOperationForbiddenError":+ return "This operation is not allowed for the current session.";+ case "EnvironmentInternalError":+ return fallbackMessage;}-- return trimmed;}+const INVALID_BOOTSTRAP_CREDENTIAL_MESSAGES = new Set([+ "Invalid bootstrap credential.",+ "Unknown bootstrap credential.",+]);+function toFriendlyBootstrapErrorMessage(status: number, message: string): string {- const parsedMessage = parseBootstrapErrorMessage(message);- if (status === 401 && INVALID_BOOTSTRAP_CREDENTIAL_MESSAGES.has(parsedMessage)) {+ const trimmedMessage = message.trim();+ if (status === 401 && INVALID_BOOTSTRAP_CREDENTIAL_MESSAGES.has(trimmedMessage)) {return "Invalid pairing token. Check the token and try again.";}- return parsedMessage;+ return trimmedMessage;}-async function exchangeBootstrapCredential(credential: string): Promise<AuthBootstrapResult> {+async function exchangeBootstrapCredential(credential: string): Promise<AuthBrowserSessionResult> {return retryTransientBootstrap(async () => {- const payload: AuthBootstrapInput = { credential };- const response = await fetch(resolvePrimaryEnvironmentHttpUrl("/api/auth/bootstrap"), {- body: JSON.stringify(payload),- credentials: "include",- headers: {- "content-type": "application/json",- },- method: "POST",- });-- if (!response.ok) {- const message = toFriendlyBootstrapErrorMessage(response.status, await response.text());+ try {+ return await runPrimaryHttp(+ PrimaryEnvironmentHttpClient.pipe(+ Effect.flatMap((client) => client.auth.browserSession({ payload: { credential } })),+ ),+ );+ } catch (error) {+ const status = readHttpApiStatus(error) ?? 500;+ const message = toFriendlyBootstrapErrorMessage(status, readHttpApiErrorMessage(error, ""));throw new BootstrapHttpError({- message: message || `Failed to bootstrap auth session (${response.status}).`,- status: response.status,+ message: message || `Failed to bootstrap auth session (${status}).`,+ status,});}-- return (await response.json()) as AuthBootstrapResult;});}@@ -266,57 +289,93 @@ export async function submitServerAuthCredential(credential: string): Promise<vostripPairingTokenFromUrl();}-export async function createServerPairingCredential(- label?: string,-): Promise<AuthPairingCredentialResult> {- const trimmedLabel = label?.trim();- const payload: AuthCreatePairingCredentialInput = trimmedLabel ? { label: trimmedLabel } : {};- const response = await fetch(resolvePrimaryEnvironmentHttpUrl("/api/auth/pairing-token"), {- body: JSON.stringify(payload),- credentials: "include",- headers: {- "content-type": "application/json",- },- method: "POST",- });-- if (!response.ok) {+export async function createServerPairingCredential(input?: {+ readonly label?: string;+ readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;+}): Promise<AuthPairingCredentialResult> {+ const trimmedLabel = input?.label?.trim();+ try {+ return await runPrimaryHttp(+ PrimaryEnvironmentHttpClient.pipe(+ Effect.flatMap((client) =>+ client.auth.pairingCredential({+ headers: {},+ payload: {+ ...(trimmedLabel ? { label: trimmedLabel } : {}),+ ...(input?.scopes ? { scopes: input.scopes } : {}),+ },+ }),+ ),+ ),+ );+ } catch (error) {throw new Error(- await readErrorMessage(response, `Failed to create pairing credential (${response.status}).`),+ readHttpApiErrorMessage(+ error,+ `Failed to create pairing credential (${readHttpApiStatus(error) ?? "unknown"}).`,+ ),+ { cause: error },);}-- return (await response.json()) as AuthPairingCredentialResult;}export async function listServerPairingLinks(): Promise<ReadonlyArray<ServerPairingLinkRecord>> {- const response = await fetch(resolvePrimaryEnvironmentHttpUrl("/api/auth/pairing-links"), {- credentials: "include",- });-- if (!response.ok) {+ try {+ const pairingLinks = await runPrimaryHttp(+ PrimaryEnvironmentHttpClient.pipe(+ Effect.flatMap((client) => client.auth.pairingLinks({ headers: {} })),+ ),+ );+ return pairingLinks.map((pairingLink) => {+ const timestamps = {+ createdAt: DateTime.formatIso(pairingLink.createdAt),+ expiresAt: DateTime.formatIso(pairingLink.expiresAt),+ };+ if (pairingLink.label === undefined) {+ return {+ id: pairingLink.id,+ credential: pairingLink.credential,+ scopes: pairingLink.scopes,+ subject: pairingLink.subject,+ createdAt: timestamps.createdAt,+ expiresAt: timestamps.expiresAt,+ };+ }+ return {+ id: pairingLink.id,+ credential: pairingLink.credential,+ scopes: pairingLink.scopes,+ subject: pairingLink.subject,+ label: pairingLink.label,+ createdAt: timestamps.createdAt,+ expiresAt: timestamps.expiresAt,+ };+ });+ } catch (error) {throw new Error(- await readErrorMessage(response, `Failed to load pairing links (${response.status}).`),+ readHttpApiErrorMessage(+ error,+ `Failed to load pairing links (${readHttpApiStatus(error) ?? "unknown"}).`,+ ),+ { cause: error },);}-- return (await response.json()) as ReadonlyArray<ServerPairingLinkRecord>;}export async function revokeServerPairingLink(id: string): Promise<void> {- const payload: AuthRevokePairingLinkInput = { id };- const response = await fetch(resolvePrimaryEnvironmentHttpUrl("/api/auth/pairing-links/revoke"), {- body: JSON.stringify(payload),- credentials: "include",- headers: {- "content-type": "application/json",- },- method: "POST",- });-- if (!response.ok) {+ try {+ await runPrimaryHttp(+ PrimaryEnvironmentHttpClient.pipe(+ Effect.flatMap((client) => client.auth.revokePairingLink({ headers: {}, payload: { id } })),+ ),+ );+ } catch (error) {throw new Error(- await readErrorMessage(response, `Failed to revoke pairing link (${response.status}).`),+ readHttpApiErrorMessage(+ error,+ `Failed to revoke pairing link (${readHttpApiStatus(error) ?? "unknown"}).`,+ ),+ { cause: error },);}}@@ -324,57 +383,75 @@ export async function revokeServerPairingLink(id: string): Promise<void> {export async function listServerClientSessions(): Promise<ReadonlyArray<ServerClientSessionRecord>> {- const response = await fetch(resolvePrimaryEnvironmentHttpUrl("/api/auth/clients"), {- credentials: "include",- });-- if (!response.ok) {+ try {+ const clientSessions = await runPrimaryHttp(+ PrimaryEnvironmentHttpClient.pipe(+ Effect.flatMap((client) => client.auth.clients({ headers: {} })),+ ),+ );+ return clientSessions.map((clientSession) => ({+ sessionId: clientSession.sessionId,+ subject: clientSession.subject,+ scopes: clientSession.scopes,+ method: clientSession.method,+ client: clientSession.client,+ issuedAt: DateTime.formatIso(clientSession.issuedAt),+ expiresAt: DateTime.formatIso(clientSession.expiresAt),+ lastConnectedAt:+ clientSession.lastConnectedAt === null+ ? null+ : DateTime.formatIso(clientSession.lastConnectedAt),+ connected: clientSession.connected,+ current: clientSession.current,+ }));+ } catch (error) {throw new Error(- await readErrorMessage(response, `Failed to load paired clients (${response.status}).`),+ readHttpApiErrorMessage(+ error,+ `Failed to load paired clients (${readHttpApiStatus(error) ?? "unknown"}).`,+ ),+ { cause: error },);}-- return (await response.json()) as ReadonlyArray<ServerClientSessionRecord>;}export async function revokeServerClientSession(sessionId: AuthSessionId): Promise<void> {- const payload: AuthRevokeClientSessionInput = { sessionId };- const response = await fetch(resolvePrimaryEnvironmentHttpUrl("/api/auth/clients/revoke"), {- body: JSON.stringify(payload),- credentials: "include",- headers: {- "content-type": "application/json",- },- method: "POST",- });-- if (!response.ok) {+ try {+ await runPrimaryHttp(+ PrimaryEnvironmentHttpClient.pipe(+ Effect.flatMap((client) =>+ client.auth.revokeClient({ headers: {}, payload: { sessionId } }),+ ),+ ),+ );+ } catch (error) {throw new Error(- await readErrorMessage(response, `Failed to revoke client session (${response.status}).`),+ readHttpApiErrorMessage(+ error,+ `Failed to revoke client session (${readHttpApiStatus(error) ?? "unknown"}).`,+ ),+ { cause: error },);}}export async function revokeOtherServerClientSessions(): Promise<number> {- const response = await fetch(- resolvePrimaryEnvironmentHttpUrl("/api/auth/clients/revoke-others"),- {- credentials: "include",- method: "POST",- },- );-- if (!response.ok) {+ try {+ const result = await runPrimaryHttp(+ PrimaryEnvironmentHttpClient.pipe(+ Effect.flatMap((client) => client.auth.revokeOtherClients({ headers: {} })),+ ),+ );+ return result.revokedCount;+ } catch (error) {throw new Error(- await readErrorMessage(- response,- `Failed to revoke other client sessions (${response.status}).`,+ readHttpApiErrorMessage(+ error,+ `Failed to revoke other client sessions (${readHttpApiStatus(error) ?? "unknown"}).`,),+ { cause: error },);}-- const result = (await response.json()) as { revokedCount?: number };- return result.revokedCount ?? 0;}export async function resolveInitialServerAuthGateState(): Promise<ServerAuthGateState> {diff --git a/apps/web/src/environments/primary/bootstrap.test.ts b/apps/web/src/environments/primary/bootstrap.test.tsindex 6081e425e..d92c25876 100644--- a/apps/web/src/environments/primary/bootstrap.test.ts+++ b/apps/web/src/environments/primary/bootstrap.test.ts@@ -1,25 +1,18 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { EnvironmentId } from "@t3tools/contracts";+import { EnvironmentId, type ExecutionEnvironmentDescriptor } from "@t3tools/contracts";+import * as Effect from "effect/Effect";import {getPrimaryKnownEnvironment,+ resolvePrimaryEnvironmentHttpUrl,resolveInitialPrimaryEnvironmentDescriptor,resetPrimaryEnvironmentDescriptorForTests,writePrimaryEnvironmentDescriptor,} from ".";--function jsonResponse(body: unknown, init?: ResponseInit) {- return new Response(JSON.stringify(body), {- headers: {- "content-type": "application/json",- },- status: 200,- ...init,- });-}+import { installEnvironmentHttpTest } from "../../../test/environmentHttpTest";const BASE_ENVIRONMENT = {- environmentId: "environment-local",+ environmentId: EnvironmentId.make("environment-local"),label: "Local environment",platform: {os: "darwin",@@ -29,7 +22,17 @@ const BASE_ENVIRONMENT = {capabilities: {repositoryIdentity: true,},-};+} satisfies ExecutionEnvironmentDescriptor;++let disposeHttpTest: (() => Promise<void>) | undefined;++async function installDescriptorApi() {+ const testApi = await installEnvironmentHttpTest({+ descriptor: () => Effect.succeed(BASE_ENVIRONMENT),+ });+ disposeHttpTest = testApi.dispose;+ return testApi;+}function installTestBrowser(url: string) {vi.stubGlobal("window", {@@ -47,7 +50,9 @@ describe("environmentBootstrap", () => {installTestBrowser("http://localhost/");});- afterEach(() => {+ afterEach(async () => {+ await disposeHttpTest?.();+ disposeHttpTest = undefined;resetPrimaryEnvironmentDescriptorForTests();vi.unstubAllEnvs();vi.useRealTimers();@@ -88,35 +93,35 @@ describe("environmentBootstrap", () => {});it("reuses an in-flight descriptor bootstrap request", async () => {- const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(jsonResponse(BASE_ENVIRONMENT));- vi.stubGlobal("fetch", fetchMock);+ const testApi = await installDescriptorApi();await Promise.all([resolveInitialPrimaryEnvironmentDescriptor(),resolveInitialPrimaryEnvironmentDescriptor(),]);- expect(fetchMock).toHaveBeenCalledTimes(1);- expect(fetchMock).toHaveBeenCalledWith("http://localhost/.well-known/t3/environment");+ expect(testApi.calls.descriptor).toBe(1);});it("uses https descriptor urls when the primary environment uses wss", async () => {- const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(jsonResponse(BASE_ENVIRONMENT));- vi.stubGlobal("fetch", fetchMock);vi.stubEnv("VITE_HTTP_URL", "https://remote.example.com");vi.stubEnv("VITE_WS_URL", "wss://remote.example.com");+ await installDescriptorApi();await expect(resolveInitialPrimaryEnvironmentDescriptor()).resolves.toEqual(BASE_ENVIRONMENT);- expect(fetchMock).toHaveBeenCalledWith("https://remote.example.com/.well-known/t3/environment");+ expect(resolvePrimaryEnvironmentHttpUrl("/.well-known/t3/environment")).toBe(+ "https://remote.example.com/.well-known/t3/environment",+ );});it("derives the websocket url when only VITE_HTTP_URL is configured", async () => {- const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(jsonResponse(BASE_ENVIRONMENT));- vi.stubGlobal("fetch", fetchMock);vi.stubEnv("VITE_HTTP_URL", "https://remote.example.com");+ await installDescriptorApi();await expect(resolveInitialPrimaryEnvironmentDescriptor()).resolves.toEqual(BASE_ENVIRONMENT);- expect(fetchMock).toHaveBeenCalledWith("https://remote.example.com/.well-known/t3/environment");+ expect(resolvePrimaryEnvironmentHttpUrl("/.well-known/t3/environment")).toBe(+ "https://remote.example.com/.well-known/t3/environment",+ );expect(getPrimaryKnownEnvironment()?.target).toEqual({httpBaseUrl: "https://remote.example.com/",wsBaseUrl: "wss://remote.example.com/",@@ -124,12 +129,13 @@ describe("environmentBootstrap", () => {});it("derives the http url when only VITE_WS_URL is configured", async () => {- const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(jsonResponse(BASE_ENVIRONMENT));- vi.stubGlobal("fetch", fetchMock);vi.stubEnv("VITE_WS_URL", "wss://remote.example.com");+ await installDescriptorApi();await expect(resolveInitialPrimaryEnvironmentDescriptor()).resolves.toEqual(BASE_ENVIRONMENT);- expect(fetchMock).toHaveBeenCalledWith("https://remote.example.com/.well-known/t3/environment");+ expect(resolvePrimaryEnvironmentHttpUrl("/.well-known/t3/environment")).toBe(+ "https://remote.example.com/.well-known/t3/environment",+ );expect(getPrimaryKnownEnvironment()?.target).toEqual({httpBaseUrl: "https://remote.example.com/",wsBaseUrl: "wss://remote.example.com/",@@ -137,17 +143,16 @@ describe("environmentBootstrap", () => {});it("uses the current origin as the descriptor base for local dev environments", async () => {- const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(jsonResponse(BASE_ENVIRONMENT));- vi.stubGlobal("fetch", fetchMock);installTestBrowser("http://localhost:5735/");+ await installDescriptorApi();await expect(resolveInitialPrimaryEnvironmentDescriptor()).resolves.toEqual(BASE_ENVIRONMENT);- expect(fetchMock).toHaveBeenCalledWith("http://localhost:5735/.well-known/t3/environment");+ expect(resolvePrimaryEnvironmentHttpUrl("/.well-known/t3/environment")).toBe(+ "http://localhost:5735/.well-known/t3/environment",+ );});it("uses the vite proxy for desktop-managed loopback descriptor requests during local dev", async () => {- const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(jsonResponse(BASE_ENVIRONMENT));- vi.stubGlobal("fetch", fetchMock);vi.stubEnv("VITE_DEV_SERVER_URL", "http://127.0.0.1:5733");vi.stubGlobal("window", {location: new URL("http://127.0.0.1:5733/"),@@ -163,8 +168,11 @@ describe("environmentBootstrap", () => {}),},});+ await installDescriptorApi();await expect(resolveInitialPrimaryEnvironmentDescriptor()).resolves.toEqual(BASE_ENVIRONMENT);- expect(fetchMock).toHaveBeenCalledWith("http://127.0.0.1:5733/.well-known/t3/environment");+ expect(resolvePrimaryEnvironmentHttpUrl("/.well-known/t3/environment")).toBe(+ "http://127.0.0.1:5733/.well-known/t3/environment",+ );});});diff --git a/apps/web/src/environments/primary/context.ts b/apps/web/src/environments/primary/context.tsindex dea1683c4..db4406ece 100644--- a/apps/web/src/environments/primary/context.ts+++ b/apps/web/src/environments/primary/context.ts@@ -4,13 +4,15 @@ import {type KnownEnvironment,} from "@t3tools/client-runtime";import type { EnvironmentId, ExecutionEnvironmentDescriptor } from "@t3tools/contracts";+import * as Effect from "effect/Effect";+import { HttpClientError } from "effect/unstable/http";import { create } from "zustand";import { BootstrapHttpError, retryTransientBootstrap } from "./auth";+import { PrimaryEnvironmentHttpClient } from "./httpClient";-import { readPrimaryEnvironmentTarget, resolvePrimaryEnvironmentHttpUrl } from "./target";--const SERVER_ENVIRONMENT_DESCRIPTOR_PATH = "/.well-known/t3/environment";+import { runPrimaryHttp } from "../../lib/runtime";+import { readPrimaryEnvironmentTarget } from "./target";interface PrimaryEnvironmentBootstrapState {readonly descriptor: ExecutionEnvironmentDescriptor | null;@@ -48,17 +50,22 @@ function createPrimaryKnownEnvironment(input: {async function fetchPrimaryEnvironmentDescriptor(): Promise<ExecutionEnvironmentDescriptor> {return retryTransientBootstrap(async () => {- const response = await fetch(- resolvePrimaryEnvironmentHttpUrl(SERVER_ENVIRONMENT_DESCRIPTOR_PATH),- );- if (!response.ok) {+ let descriptor: ExecutionEnvironmentDescriptor;+ try {+ descriptor = await runPrimaryHttp(+ PrimaryEnvironmentHttpClient.pipe(Effect.flatMap((client) => client.metadata.descriptor())),+ );+ } catch (error) {+ const status =+ HttpClientError.isHttpClientError(error) && error.response !== undefined+ ? error.response.status+ : 500;throw new BootstrapHttpError({- message: `Failed to load server environment descriptor (${response.status}).`,- status: response.status,+ message: `Failed to load server environment descriptor (${status}).`,+ status,});}- const descriptor = (await response.json()) as ExecutionEnvironmentDescriptor;writePrimaryEnvironmentDescriptor(descriptor);return descriptor;});diff --git a/apps/web/src/environments/primary/httpClient.ts b/apps/web/src/environments/primary/httpClient.tsnew file mode 100644index 000000000..d9404b4b8--- /dev/null+++ b/apps/web/src/environments/primary/httpClient.ts@@ -0,0 +1,20 @@+import { makeEnvironmentHttpApiClient } from "@t3tools/client-runtime";+import * as Context from "effect/Context";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";++import { resolvePrimaryEnvironmentHttpUrl } from "./target";++export type PrimaryEnvironmentHttpClientShape = Effect.Success<+ ReturnType<typeof makeEnvironmentHttpApiClient>+>;++export class PrimaryEnvironmentHttpClient extends Context.Service<+ PrimaryEnvironmentHttpClient,+ PrimaryEnvironmentHttpClientShape+>()("@t3tools/web/environments/primary/httpClient/PrimaryEnvironmentHttpClient") {}++export const primaryEnvironmentHttpClientLive = Layer.effect(+ PrimaryEnvironmentHttpClient,+ Effect.suspend(() => makeEnvironmentHttpApiClient(resolvePrimaryEnvironmentHttpUrl("/"))),+);diff --git a/apps/web/src/environments/primary/index.ts b/apps/web/src/environments/primary/index.tsindex 2614164b6..6856b9ac5 100644--- a/apps/web/src/environments/primary/index.ts+++ b/apps/web/src/environments/primary/index.ts@@ -32,4 +32,6 @@ export {__resetServerAuthBootstrapForTests,} from "./auth";+export { refreshPrimarySessionState, usePrimarySessionState } from "./sessionState";+export { resolvePrimaryEnvironmentHttpUrl, isLoopbackHostname } from "./target";diff --git a/apps/web/src/environments/primary/sessionState.ts b/apps/web/src/environments/primary/sessionState.tsnew file mode 100644index 000000000..9312646cc--- /dev/null+++ b/apps/web/src/environments/primary/sessionState.ts@@ -0,0 +1,37 @@+import { useAtomValue } from "@effect/atom-react";+import * as Cause from "effect/Cause";+import * as Effect from "effect/Effect";+import * as Option from "effect/Option";+import { AsyncResult, Atom } from "effect/unstable/reactivity";+import { useCallback } from "react";++import { appAtomRegistry } from "../../rpc/atomRegistry";+import { fetchSessionState } from "./auth";++const primarySessionStateAtom = Atom.make(Effect.promise(fetchSessionState)).pipe(+ Atom.swr({ staleTime: 5_000, revalidateOnMount: true }),+ Atom.setIdleTTL(5 * 60_000),+ Atom.withLabel("primary-environment:session"),+);++export function refreshPrimarySessionState(): void {+ appAtomRegistry.refresh(primarySessionStateAtom);+}++export function usePrimarySessionState() {+ const result = useAtomValue(primarySessionStateAtom);+ const refresh = useCallback(() => {+ refreshPrimarySessionState();+ }, []);+ let error: string | null = null;+ if (result._tag === "Failure") {+ const cause = Cause.squash(result.cause);+ error = cause instanceof Error ? cause.message : "Could not read environment session.";+ }+ return {+ data: Option.getOrNull(AsyncResult.value(result)),+ error,+ isPending: result.waiting,+ refresh,+ };+}diff --git a/apps/web/src/environments/runtime/catalog.ts b/apps/web/src/environments/runtime/catalog.tsindex 7ece1ccb0..5d1c95605 100644--- a/apps/web/src/environments/runtime/catalog.ts+++ b/apps/web/src/environments/runtime/catalog.ts@@ -1,6 +1,6 @@import { getKnownEnvironmentHttpBaseUrl } from "@t3tools/client-runtime";import type {- AuthSessionRole,+ AuthEnvironmentScope,EnvironmentId,ExecutionEnvironmentDescriptor,PersistedSavedEnvironmentRecord,@@ -272,7 +272,7 @@ export interface SavedEnvironmentRuntimeState {readonly authState: SavedEnvironmentAuthState;readonly lastError: string | null;readonly lastErrorAt: string | null;- readonly role: AuthSessionRole | null;+ readonly scopes: ReadonlyArray<AuthEnvironmentScope> | null;readonly descriptor: ExecutionEnvironmentDescriptor | null;readonly serverConfig: ServerConfig | null;readonly connectedAt: string | null;@@ -295,7 +295,7 @@ const DEFAULT_SAVED_ENVIRONMENT_RUNTIME_STATE: SavedEnvironmentRuntimeState = ObauthState: "unknown",lastError: null,lastErrorAt: null,- role: null,+ scopes: null,descriptor: null,serverConfig: null,connectedAt: null,diff --git a/apps/web/src/environments/runtime/service.addSavedEnvironment.test.ts b/apps/web/src/environments/runtime/service.addSavedEnvironment.test.tsindex 7e847780e..df4d504fd 100644--- a/apps/web/src/environments/runtime/service.addSavedEnvironment.test.ts+++ b/apps/web/src/environments/runtime/service.addSavedEnvironment.test.ts@@ -1,13 +1,15 @@-import { EnvironmentId } from "@t3tools/contracts";+import { EnvironmentAuthInvalidError, EnvironmentId } from "@t3tools/contracts";+import * as Schema from "effect/Schema";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+const decodeEnvironmentAuthInvalidError = Schema.decodeUnknownSync(EnvironmentAuthInvalidError);+let mockSavedRecords: Array<Record<string, unknown>> = [];const mockResolveRemotePairingTarget = vi.fn();const mockFetchRemoteEnvironmentDescriptor = vi.fn();const mockBootstrapRemoteBearerSession = vi.fn();const mockFetchRemoteSessionState = vi.fn();-const mockIsRemoteEnvironmentAuthHttpError = vi.fn((_: unknown) => false);const mockResolveRemoteWebSocketConnectionUrl = vi.fn();const mockRemoteHttpRunPromise = vi.fn((effect: Promise<unknown>) => effect);const mockBootstrapSshBearerSession = vi.fn();@@ -128,7 +130,6 @@ vi.mock("@t3tools/client-runtime", async (importOriginal) => {})),fetchRemoteEnvironmentDescriptor: mockFetchRemoteEnvironmentDescriptor,fetchRemoteSessionState: mockFetchRemoteSessionState,- isRemoteEnvironmentAuthHttpError: mockIsRemoteEnvironmentAuthHttpError,resolveRemoteWebSocketConnectionUrl: mockResolveRemoteWebSocketConnectionUrl,};});@@ -153,7 +154,7 @@ describe("addSavedEnvironment", () => {fetchSshEnvironmentDescriptor: mockFetchSshEnvironmentDescriptor,bootstrapSshBearerSession: mockBootstrapSshBearerSession,fetchSshSessionState: mockFetchSshSessionState,- issueSshWebSocketToken: vi.fn(),+ issueSshWebSocketTicket: vi.fn(),},});mockResolveRemotePairingTarget.mockImplementation(@@ -176,24 +177,23 @@ describe("addSavedEnvironment", () => {label: "Remote environment",});mockBootstrapRemoteBearerSession.mockResolvedValue({- sessionToken: "bearer-token",- role: "owner",+ access_token: "bearer-token",+ scope: "orchestration:read orchestration:operate terminal:operate review:write relay:read",});mockFetchRemoteSessionState.mockResolvedValue({authenticated: true,- role: "owner",+ scopes: ["orchestration:read", "access:write"],});- mockIsRemoteEnvironmentAuthHttpError.mockReturnValue(false);mockResolveRemoteWebSocketConnectionUrl.mockResolvedValue(- "wss://remote.example.com/?wsToken=remote-token",+ "wss://remote.example.com/?wsTicket=remote-token",);mockFetchSshEnvironmentDescriptor.mockResolvedValue({environmentId: EnvironmentId.make("environment-1"),label: "Remote environment",});mockBootstrapSshBearerSession.mockResolvedValue({- sessionToken: "ssh-bearer-token",- role: "owner",+ access_token: "ssh-bearer-token",+ scope: "orchestration:read orchestration:operate terminal:operate review:write relay:read",});mockPersistSavedEnvironmentRecord.mockResolvedValue(undefined);mockWriteSavedEnvironmentBearerToken.mockResolvedValue(false);@@ -202,7 +202,7 @@ describe("addSavedEnvironment", () => {mockRemoveSavedEnvironmentBearerToken.mockResolvedValue(undefined);mockFetchSshSessionState.mockResolvedValue({authenticated: true,- role: "owner",+ scopes: ["orchestration:read", "access:write"],});mockCreateEnvironmentConnection.mockImplementation((input: { knownEnvironment: { environmentId: EnvironmentId }; client: unknown }) => ({@@ -381,18 +381,18 @@ describe("addSavedEnvironment", () => {mockWriteSavedEnvironmentBearerToken.mockResolvedValue(true);mockBootstrapSshBearerSession.mockResolvedValueOnce({- sessionToken: "ssh-bearer-token",- role: "owner",+ access_token: "ssh-bearer-token",+ scope: "orchestration:read orchestration:operate terminal:operate review:write relay:read",}).mockResolvedValueOnce({- sessionToken: "ssh-bearer-token-2",- role: "owner",+ access_token: "ssh-bearer-token-2",+ scope: "orchestration:read orchestration:operate terminal:operate review:write relay:read",});mockFetchSshSessionState.mockRejectedValueOnce(new Error("[ssh_http:401] Unauthorized")).mockResolvedValueOnce({authenticated: true,- role: "owner",+ scopes: ["orchestration:read", "access:write"],});const { connectDesktopSshEnvironment, resetEnvironmentServiceForTests } =@@ -418,14 +418,13 @@ describe("addSavedEnvironment", () => {it("does not attempt desktop ssh bearer recovery for non-ssh saved environments", async () => {mockWriteSavedEnvironmentBearerToken.mockResolvedValue(true);- const authError = {- status: 401,- message: "Unauthorized",- };+ const authError = decodeEnvironmentAuthInvalidError({+ _tag: "EnvironmentAuthInvalidError",+ code: "auth_invalid",+ reason: "invalid_credential",+ traceId: "trace-auth-test",+ });mockFetchRemoteSessionState.mockRejectedValueOnce(authError);- mockIsRemoteEnvironmentAuthHttpError.mockImplementation(- (error: unknown) => error === authError,- );const { addSavedEnvironment, resetEnvironmentServiceForTests } = await import("./service");@@ -450,18 +449,18 @@ describe("addSavedEnvironment", () => {mockWriteSavedEnvironmentBearerToken.mockResolvedValue(true);mockBootstrapSshBearerSession.mockResolvedValueOnce({- sessionToken: "ssh-bearer-token",- role: "owner",+ access_token: "ssh-bearer-token",+ scope: "orchestration:read orchestration:operate terminal:operate review:write relay:read",}).mockResolvedValueOnce({- sessionToken: "ssh-bearer-token-2",- role: "owner",+ access_token: "ssh-bearer-token-2",+ scope: "orchestration:read orchestration:operate terminal:operate review:write relay:read",});mockFetchSshSessionState.mockRejectedValueOnce(new Error("[ssh_http:401] Unauthorized")).mockResolvedValueOnce({authenticated: true,- role: "owner",+ scopes: ["orchestration:read", "access:write"],});const createdConnections: Array<{@@ -745,7 +744,7 @@ describe("addSavedEnvironment", () => {);let resolveSessionState!: (value: {readonly authenticated: true;- readonly role: "owner";+ readonly scopes: ReadonlyArray<"orchestration:read" | "access:write">;}) => void;mockFetchRemoteSessionState.mockReturnValue(new Promise((resolve) => {@@ -768,7 +767,7 @@ describe("addSavedEnvironment", () => {await disconnectSavedEnvironment(EnvironmentId.make("environment-1"));resolveSessionState({authenticated: true,- role: "owner",+ scopes: ["orchestration:read", "access:write"],});await expect(reconnectPromise).resolves.toBeUndefined();diff --git a/apps/web/src/environments/runtime/service.savedEnvironments.test.ts b/apps/web/src/environments/runtime/service.savedEnvironments.test.tsindex d47a6109a..103001e91 100644--- a/apps/web/src/environments/runtime/service.savedEnvironments.test.ts+++ b/apps/web/src/environments/runtime/service.savedEnvironments.test.ts@@ -222,7 +222,7 @@ describe("saved environment startup", () => {mockFetchRemoteSessionState.mockResolvedValue({authenticated: true,- role: "owner",+ scopes: ["orchestration:read", "access:write"],});mockGetSavedEnvironmentRecord.mockImplementation((environmentId: EnvironmentId) =>environmentId === savedRecord.environmentId ? savedRecord : null,diff --git a/apps/web/src/environments/runtime/service.threadSubscriptions.test.ts b/apps/web/src/environments/runtime/service.threadSubscriptions.test.tsindex 0ce5f51d9..003334458 100644--- a/apps/web/src/environments/runtime/service.threadSubscriptions.test.ts+++ b/apps/web/src/environments/runtime/service.threadSubscriptions.test.ts@@ -153,7 +153,6 @@ vi.mock("@t3tools/client-runtime", async (importOriginal) => {...actual,createWsRpcClient: vi.fn(() => stubWsClient),fetchRemoteSessionState: mockFetchRemoteSessionState,- isRemoteEnvironmentAuthHttpError: vi.fn(() => false),resolveRemoteWebSocketConnectionUrl: mockResolveRemoteWebSocketConnectionUrl,};});@@ -304,7 +303,7 @@ describe("retainThreadDetailSubscription", () => {mockReadSavedEnvironmentBearerToken.mockResolvedValue(null);mockFetchRemoteSessionState.mockResolvedValue({authenticated: true,- role: "client",+ scopes: ["orchestration:read"],});mockConnectionReconnects.length = 0;});diff --git a/apps/web/src/environments/runtime/service.ts b/apps/web/src/environments/runtime/service.tsindex fff048304..406a855d3 100644--- a/apps/web/src/environments/runtime/service.ts+++ b/apps/web/src/environments/runtime/service.ts@@ -1,5 +1,6 @@import {- type AuthSessionRole,+ AuthEnvironmentScope,+ AuthStandardClientScopes,type DesktopSshEnvironmentBootstrap,type DesktopSshEnvironmentTarget,type EnvironmentId,@@ -7,6 +8,7 @@ import {type OrchestrationShellSnapshot,type OrchestrationShellStreamEvent,type ServerConfig,+ EnvironmentAuthInvalidError,ThreadId,} from "@t3tools/contracts";import {@@ -15,12 +17,12 @@ import {bootstrapRemoteBearerSession,fetchRemoteEnvironmentDescriptor,fetchRemoteSessionState,- isRemoteEnvironmentAuthHttpError,resolveRemoteWebSocketConnectionUrl,} from "@t3tools/client-runtime";import { type QueryClient } from "@tanstack/react-query";import { Throttler } from "@tanstack/react-pacer";+import * as Schema from "effect/Schema";import {createKnownEnvironment,getKnownEnvironmentWsBaseUrl,@@ -76,6 +78,8 @@ import {deriveLogicalProjectKeyFromSettings,derivePhysicalProjectKey,} from "../../logicalProject";++const decodeIssuedBearerScopes = Schema.decodeUnknownSync(Schema.Array(AuthEnvironmentScope));import { getClientSettings } from "~/hooks/useSettings";import { subscribeTerminalMetadata, terminalSessionManager } from "../../terminalSessionState";import { resetWsReconnectBackoff } from "~/rpc/wsConnectionState";@@ -99,6 +103,7 @@ type ThreadDetailSubscriptionEntry = {};const environmentConnections = new Map<EnvironmentId, EnvironmentConnection>();+const isEnvironmentAuthInvalidError = Schema.is(EnvironmentAuthInvalidError);function isSavedEnvironmentConnectionCancelledError(error: unknown,@@ -738,6 +743,10 @@ async function bootstrapDesktopSshBearerSession(httpBaseUrl: string, credential:return await getDesktopSshBridge().bootstrapSshBearerSession(httpBaseUrl, credential);}+function readIssuedBearerScopes(scope: string): ReadonlyArray<AuthEnvironmentScope> {+ return decodeIssuedBearerScopes(scope.split(" "));+}+async function fetchDesktopSshSessionState(httpBaseUrl: string, bearerToken: string) {return await getDesktopSshBridge().fetchSshSessionState(httpBaseUrl, bearerToken);}@@ -747,9 +756,9 @@ async function resolveDesktopSshWebSocketConnectionUrl(httpBaseUrl: string,bearerToken: string,) {- const issued = await getDesktopSshBridge().issueSshWebSocketToken(httpBaseUrl, bearerToken);+ const issued = await getDesktopSshBridge().issueSshWebSocketTicket(httpBaseUrl, bearerToken);const url = new URL(wsBaseUrl, window.location.origin);- url.searchParams.set("wsToken", issued.token);+ url.searchParams.set("wsTicket", issued.ticket);return url.toString();}@@ -799,7 +808,7 @@ async function prepareSavedEnvironmentRecordForConnection(async function issueDesktopSshBearerSession(record: SavedEnvironmentRecord): Promise<{readonly record: SavedEnvironmentRecord;readonly bearerToken: string;- readonly role: AuthSessionRole | null;+ readonly scopes: ReadonlyArray<AuthEnvironmentScope> | null;}> {const registrySnapshot = snapshotSavedEnvironmentRegistry([record.environmentId]);const prepared = await prepareSavedEnvironmentRecordForConnection(record, {@@ -827,7 +836,7 @@ async function issueDesktopSshBearerSession(record: SavedEnvironmentRecord): Pro});const didPersistBearerToken = await writeSavedEnvironmentBearerToken(prepared.record.environmentId,- bearerSession.sessionToken,+ bearerSession.access_token,);if (!didPersistBearerToken) {await persistSavedEnvironmentRegistryRollback(registrySnapshot);@@ -836,8 +845,8 @@ async function issueDesktopSshBearerSession(record: SavedEnvironmentRecord): Proreturn {record: prepared.record,- bearerToken: bearerSession.sessionToken,- role: bearerSession.role ?? null,+ bearerToken: bearerSession.access_token,+ scopes: readIssuedBearerScopes(bearerSession.scope),};}@@ -1214,7 +1223,7 @@ async function refreshSavedEnvironmentMetadata(environmentId: EnvironmentId,bearerToken: string,client: WsRpcClient,- roleHint?: AuthSessionRole | null,+ scopeHint?: ReadonlyArray<AuthEnvironmentScope> | null,configHint?: ServerConfig | null,): Promise<void> {const record = getSavedEnvironmentRecord(environmentId);@@ -1238,7 +1247,7 @@ async function refreshSavedEnvironmentMetadata(authState: sessionState.authenticated ? "authenticated" : "requires-auth",descriptor: serverConfig.environment,serverConfig,- role: sessionState.authenticated ? (sessionState.role ?? roleHint ?? null) : null,+ scopes: sessionState.authenticated ? (sessionState.scopes ?? scopeHint ?? null) : null,});useSavedEnvironmentRegistryStore.getState()@@ -1311,7 +1320,7 @@ async function ensureSavedEnvironmentConnection(options?: {readonly client?: WsRpcClient;readonly bearerToken?: string;- readonly role?: AuthSessionRole | null;+ readonly scopes?: ReadonlyArray<AuthEnvironmentScope> | null;readonly serverConfig?: ServerConfig | null;},): Promise<EnvironmentConnection> {@@ -1330,7 +1339,7 @@ async function ensureSavedEnvironmentConnection(isCurrent: attempt.isCurrent,promise: Promise.resolve().then(async () => {let activeRecord = record;- let roleHint = options?.role ?? null;+ let scopeHint = options?.scopes ?? null;let bearerToken =options?.bearerToken ?? (await readSavedEnvironmentBearerToken(record.environmentId));if (!bearerToken) {@@ -1338,11 +1347,11 @@ async function ensureSavedEnvironmentConnection(const issued = await issueDesktopSshBearerSession(record);activeRecord = issued.record;bearerToken = issued.bearerToken;- roleHint = issued.role;+ scopeHint = [...AuthStandardClientScopes];} else {useSavedEnvironmentRuntimeStore.getState().patch(record.environmentId, {authState: "requires-auth",- role: null,+ scopes: null,connectionState: "disconnected",lastError: "Saved environment is missing its saved credential. Pair it again.",lastErrorAt: isoNow(),@@ -1409,13 +1418,13 @@ async function ensureSavedEnvironmentConnection(activeRecord.environmentId,activeBearerToken,client,- roleHint,+ scopeHint,initialServerConfig,);} catch (error) {const isAuthError = activeRecord.desktopSsh? isSshHttpAuthError(error, 401)- : isRemoteEnvironmentAuthHttpError(error) && error.status === 401;+ : isEnvironmentAuthInvalidError(error);if (!isAuthError) {throw error;}@@ -1429,12 +1438,12 @@ async function ensureSavedEnvironmentConnection(const issued = await issueDesktopSshBearerSession(activeRecord);activeRecord = issued.record;bearerToken = issued.bearerToken;- roleHint = issued.role;+ scopeHint = [...AuthStandardClientScopes];await connection.dispose().catch(() => undefined);pendingSavedEnvironmentConnections.delete(activeRecord.environmentId);return await ensureSavedEnvironmentConnection(activeRecord, {bearerToken,- role: roleHint,+ scopes: scopeHint,serverConfig: options?.serverConfig ?? null,});}@@ -1638,7 +1647,7 @@ export async function reconnectSavedEnvironment(environmentId: EnvironmentId): Pawait removeConnection(environmentId).catch(() => false);await ensureSavedEnvironmentConnection(issued.record, {bearerToken: issued.bearerToken,- role: issued.role,+ scopes: [...AuthStandardClientScopes],});return;} catch (recoveryError) {@@ -1714,7 +1723,7 @@ export async function addSavedEnvironment(input: {await persistSavedEnvironmentRecord(record);const didPersistBearerToken = await writeSavedEnvironmentBearerToken(environmentId,- bearerSession.sessionToken,+ bearerSession.access_token,);if (!didPersistBearerToken) {await persistSavedEnvironmentRegistryRollback(registrySnapshot);@@ -1726,8 +1735,8 @@ export async function addSavedEnvironment(input: {}await removeConnection(environmentId).catch(() => false);await ensureSavedEnvironmentConnection(record, {- bearerToken: bearerSession.sessionToken,- role: bearerSession.role,+ bearerToken: bearerSession.access_token,+ scopes: readIssuedBearerScopes(bearerSession.scope),});return record;}diff --git a/apps/web/src/lib/runtime.ts b/apps/web/src/lib/runtime.tsindex 3d5c42607..8c1f0f0a5 100644--- a/apps/web/src/lib/runtime.ts+++ b/apps/web/src/lib/runtime.ts@@ -1,5 +1,39 @@import * as ManagedRuntime from "effect/ManagedRuntime";+import type * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";+import { FetchHttpClient } from "effect/unstable/http";import { remoteHttpClientLayer } from "@t3tools/client-runtime";+import {+ PrimaryEnvironmentHttpClient,+ primaryEnvironmentHttpClientLive,+} from "../environments/primary/httpClient";export const remoteHttpRuntime = ManagedRuntime.make(remoteHttpClientLayer(globalThis.fetch));++const primaryHttpRuntime = ManagedRuntime.make(+ primaryEnvironmentHttpClientLive.pipe(+ Layer.provide(+ Layer.mergeAll(+ remoteHttpClientLayer((input, init) => globalThis.fetch(input, init)),+ Layer.succeed(FetchHttpClient.RequestInit, { credentials: "include" }),+ ),+ ),+ ),+);++export type PrimaryHttpEffectRunner = <A, E>(+ effect: Effect.Effect<A, E, PrimaryEnvironmentHttpClient>,+) => Promise<A>;++const livePrimaryHttpRunner: PrimaryHttpEffectRunner = (effect) =>+ primaryHttpRuntime.runPromise(effect);++let primaryHttpRunner = livePrimaryHttpRunner;++export const runPrimaryHttp = <A, E>(effect: Effect.Effect<A, E, PrimaryEnvironmentHttpClient>) =>+ primaryHttpRunner(effect);++export function __setPrimaryHttpRunnerForTests(runner?: PrimaryHttpEffectRunner): void {+ primaryHttpRunner = runner ?? livePrimaryHttpRunner;+}diff --git a/apps/web/src/localApi.test.ts b/apps/web/src/localApi.test.tsindex bc912231d..22e61204d 100644--- a/apps/web/src/localApi.test.ts+++ b/apps/web/src/localApi.test.ts@@ -202,8 +202,8 @@ function makeDesktopBridge(overrides: Partial<DesktopBridge> = {}): DesktopBridgfetchSshSessionState: async () => {throw new Error("fetchSshSessionState not implemented in test");},- issueSshWebSocketToken: async () => {- throw new Error("issueSshWebSocketToken not implemented in test");+ issueSshWebSocketTicket: async () => {+ throw new Error("issueSshWebSocketTicket not implemented in test");},onSshPasswordPrompt: () => () => undefined,resolveSshPasswordPrompt: async () => undefined,@@ -289,7 +289,7 @@ const baseServerConfig: ServerConfig = {auth: {policy: "loopback-browser",bootstrapMethods: ["one-time-token"],- sessionMethods: ["browser-session-cookie", "bearer-session-token"],+ sessionMethods: ["browser-session-cookie", "bearer-access-token"],sessionCookieName: "t3_session",},cwd: "/tmp/workspace",diff --git a/apps/web/src/rpc/serverState.test.ts b/apps/web/src/rpc/serverState.test.tsindex 506ef84ee..c6abda778 100644--- a/apps/web/src/rpc/serverState.test.ts+++ b/apps/web/src/rpc/serverState.test.ts@@ -76,7 +76,7 @@ const baseServerConfig: ServerConfig = {auth: {policy: "loopback-browser",bootstrapMethods: ["one-time-token"],- sessionMethods: ["browser-session-cookie", "bearer-session-token"],+ sessionMethods: ["browser-session-cookie", "bearer-access-token"],sessionCookieName: "t3_session",},cwd: "/tmp/workspace",diff --git a/apps/web/test/authHttpHandlers.ts b/apps/web/test/authHttpHandlers.tsindex 6ff158fc6..a888f7fa5 100644--- a/apps/web/test/authHttpHandlers.ts+++ b/apps/web/test/authHttpHandlers.ts@@ -1,11 +1,27 @@import {+ AuthSessionId,+ EnvironmentAuthenticatedAuth,+ EnvironmentAuthenticatedPrincipal,+ EnvironmentAuthHttpApi,EnvironmentId,+ EnvironmentMetadataHttpApi,+ type AuthEnvironmentScope,type ExecutionEnvironmentDescriptor,type ServerAuthDescriptor,} from "@t3tools/contracts";-import { HttpResponse, http } from "msw";+import * as DateTime from "effect/DateTime";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";+import { HttpRouter, HttpServer } from "effect/unstable/http";+import * as HttpApi from "effect/unstable/httpapi/HttpApi";+import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";+import { http } from "msw";-const TEST_SESSION_EXPIRES_AT = "2026-05-01T12:00:00.000Z";+const BrowserEnvironmentHttpApi = HttpApi.make("browserEnvironment")+ .add(EnvironmentMetadataHttpApi)+ .add(EnvironmentAuthHttpApi);++const TEST_SESSION_EXPIRES_AT = DateTime.makeUnsafe("2026-05-01T12:00:00.000Z");const TEST_ENVIRONMENT_DESCRIPTOR: ExecutionEnvironmentDescriptor = {environmentId: EnvironmentId.make("environment-local"),label: "Local environment",@@ -19,23 +35,69 @@ const TEST_ENVIRONMENT_DESCRIPTOR: ExecutionEnvironmentDescriptor = {},};+const unexpectedEndpoint = (endpoint: string) =>+ Effect.die(new Error(`Unexpected browser environment HTTP endpoint: ${endpoint}`));+export function createAuthenticatedSessionHandlers(getAuthDescriptor: () => ServerAuthDescriptor) {- return [- http.get("*/.well-known/t3/environment", () => HttpResponse.json(TEST_ENVIRONMENT_DESCRIPTOR)),- http.get("*/api/auth/session", () =>- HttpResponse.json({- authenticated: true,- auth: getAuthDescriptor(),- sessionMethod: "browser-session-cookie",+ const authenticatedAuthLayer = Layer.succeed(EnvironmentAuthenticatedAuth, (httpEffect) =>+ httpEffect.pipe(+ Effect.provideService(EnvironmentAuthenticatedPrincipal, {+ sessionId: AuthSessionId.make("browser-session"),+ subject: "browser-client",+ method: "browser-session-cookie",+ scopes: new Set<AuthEnvironmentScope>(),expiresAt: TEST_SESSION_EXPIRES_AT,}),),- http.post("*/api/auth/bootstrap", () =>- HttpResponse.json({- authenticated: true,- sessionMethod: "browser-session-cookie",- expiresAt: TEST_SESSION_EXPIRES_AT,- }),+ );+ const metadataLayer = HttpApiBuilder.group(BrowserEnvironmentHttpApi, "metadata", (handlers) =>+ handlers.handle("descriptor", () => Effect.succeed(TEST_ENVIRONMENT_DESCRIPTOR)),+ );+ const authLayer = HttpApiBuilder.group(BrowserEnvironmentHttpApi, "auth", (handlers) =>+ handlers+ .handle("session", () =>+ Effect.succeed({+ authenticated: true,+ auth: getAuthDescriptor(),+ sessionMethod: "browser-session-cookie",+ expiresAt: TEST_SESSION_EXPIRES_AT,+ }),+ )+ .handle("browserSession", () =>+ Effect.succeed({+ authenticated: true,+ scopes: [+ "orchestration:read",+ "orchestration:operate",+ "terminal:operate",+ "review:write",+ "relay:read",+ ],+ sessionMethod: "browser-session-cookie",+ expiresAt: TEST_SESSION_EXPIRES_AT,+ }),+ )+ .handle("token", () => unexpectedEndpoint("auth.token"))+ .handle("webSocketTicket", () => unexpectedEndpoint("auth.webSocketTicket"))+ .handle("pairingCredential", () => unexpectedEndpoint("auth.pairingCredential"))+ .handle("pairingLinks", () => unexpectedEndpoint("auth.pairingLinks"))+ .handle("revokePairingLink", () => unexpectedEndpoint("auth.revokePairingLink"))+ .handle("clients", () => unexpectedEndpoint("auth.clients"))+ .handle("revokeClient", () => unexpectedEndpoint("auth.revokeClient"))+ .handle("revokeOtherClients", () => unexpectedEndpoint("auth.revokeOtherClients")),+ ).pipe(Layer.provide(authenticatedAuthLayer));+ const { handler } = HttpRouter.toWebHandler(+ HttpApiBuilder.layer(BrowserEnvironmentHttpApi).pipe(+ Layer.provide(metadataLayer),+ Layer.provide(authLayer),+ Layer.provide(authenticatedAuthLayer),+ Layer.provide(HttpServer.layerServices),),+ { disableLogger: true },+ );++ return [+ http.all("*/.well-known/t3/environment", ({ request }) => handler(request)),+ http.all("*/api/auth/*", ({ request }) => handler(request)),] as const;}diff --git a/apps/web/test/environmentHttpTest.ts b/apps/web/test/environmentHttpTest.tsnew file mode 100644index 000000000..ce43faacc--- /dev/null+++ b/apps/web/test/environmentHttpTest.ts@@ -0,0 +1,136 @@+import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";+import {+ AuthSessionId,+ EnvironmentAuthenticatedAuth,+ EnvironmentAuthenticatedPrincipal,+ EnvironmentHttpApi,+ type AuthBrowserSessionRequest,+ type AuthBrowserSessionResult,+ type AuthCreatePairingCredentialInput,+ type AuthEnvironmentScope,+ type AuthPairingCredentialResult,+ type AuthSessionState,+ type ExecutionEnvironmentDescriptor,+ type EnvironmentAuthInvalidError,+} from "@t3tools/contracts";+import * as DateTime from "effect/DateTime";+import type * as Context from "effect/Context";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";+import * as ManagedRuntime from "effect/ManagedRuntime";+import { HttpApiTest } from "effect/unstable/httpapi";+import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";++import { PrimaryEnvironmentHttpClient } from "../src/environments/primary/httpClient";+import { __setPrimaryHttpRunnerForTests } from "../src/lib/runtime";++type BrowserSessionHandler = (+ payload: AuthBrowserSessionRequest,+) => Effect.Effect<AuthBrowserSessionResult, EnvironmentAuthInvalidError>;++interface EnvironmentHttpTestScenario {+ readonly descriptor?: () => Effect.Effect<ExecutionEnvironmentDescriptor>;+ readonly session?: () => Effect.Effect<AuthSessionState>;+ readonly browserSession?: BrowserSessionHandler;+ readonly pairingCredential?: (+ payload: AuthCreatePairingCredentialInput,+ ) => Effect.Effect<AuthPairingCredentialResult>;+}++export interface EnvironmentHttpTestCalls {+ descriptor: number;+ session: number;+ browserSession: Array<AuthBrowserSessionRequest>;+ pairingCredential: Array<AuthCreatePairingCredentialInput>;+}++const unexpectedEndpoint = (endpoint: string) =>+ Effect.die(new Error(`Unexpected environment HTTP endpoint: ${endpoint}`));++const authenticatedAuth: Context.Service.Shape<typeof EnvironmentAuthenticatedAuth> = (+ httpEffect,+) =>+ httpEffect.pipe(+ Effect.provideService(EnvironmentAuthenticatedPrincipal, {+ sessionId: AuthSessionId.make("test-session"),+ subject: "test-client",+ method: "browser-session-cookie",+ scopes: new Set<AuthEnvironmentScope>(),+ expiresAt: DateTime.makeUnsafe("2026-05-01T12:00:00.000Z"),+ }),+ );++export async function installEnvironmentHttpTest(scenario: EnvironmentHttpTestScenario) {+ const calls: EnvironmentHttpTestCalls = {+ descriptor: 0,+ session: 0,+ browserSession: [],+ pairingCredential: [],+ };++ const client = await Effect.runPromise(+ HttpApiTest.groups(EnvironmentHttpApi, ["metadata", "auth"]).pipe(+ Effect.provide([+ NodeHttpServer.layerHttpServices,+ HttpApiBuilder.group(EnvironmentHttpApi, "metadata", (handlers) =>+ handlers.handle(+ "descriptor",+ Effect.fn("test.environment.metadata.descriptor")(function* () {+ calls.descriptor += 1;+ return yield* scenario.descriptor?.() ?? unexpectedEndpoint("metadata.descriptor");+ }),+ ),+ ),+ HttpApiBuilder.group(EnvironmentHttpApi, "auth", (handlers) =>+ handlers+ .handle(+ "session",+ Effect.fn("test.environment.auth.session")(function* () {+ calls.session += 1;+ return yield* scenario.session?.() ?? unexpectedEndpoint("auth.session");+ }),+ )+ .handle(+ "browserSession",+ Effect.fn("test.environment.auth.browserSession")(function* ({ payload }) {+ calls.browserSession.push(payload);+ return yield* (+ scenario.browserSession?.(payload) ?? unexpectedEndpoint("auth.browserSession")+ );+ }),+ )+ .handle("token", () => unexpectedEndpoint("auth.token"))+ .handle("webSocketTicket", () => unexpectedEndpoint("auth.webSocketTicket"))+ .handle(+ "pairingCredential",+ Effect.fn("test.environment.auth.pairingCredential")(function* ({ payload }) {+ calls.pairingCredential.push(payload);+ return yield* (+ scenario.pairingCredential?.(payload) ??+ unexpectedEndpoint("auth.pairingCredential")+ );+ }),+ )+ .handle("pairingLinks", () => unexpectedEndpoint("auth.pairingLinks"))+ .handle("revokePairingLink", () => unexpectedEndpoint("auth.revokePairingLink"))+ .handle("clients", () => unexpectedEndpoint("auth.clients"))+ .handle("revokeClient", () => unexpectedEndpoint("auth.revokeClient"))+ .handle("revokeOtherClients", () => unexpectedEndpoint("auth.revokeOtherClients")),+ ),+ ]),+ Effect.provideService(EnvironmentAuthenticatedAuth, authenticatedAuth),+ Effect.scoped,+ ),+ );++ const runtime = ManagedRuntime.make(Layer.succeed(PrimaryEnvironmentHttpClient, client));+ __setPrimaryHttpRunnerForTests((effect) => runtime.runPromise(effect));++ return {+ calls,+ async dispose() {+ __setPrimaryHttpRunnerForTests();+ await runtime.dispose();+ },+ };+}diff --git a/bun.lock b/bun.lockindex 29c544443..f5accdb8e 100644--- a/bun.lock+++ b/bun.lock@@ -20,6 +20,7 @@"version": "0.0.24","dependencies": {"@effect/platform-node": "catalog:",+ "@t3tools/client-runtime": "workspace:*","@t3tools/contracts": "workspace:*","@t3tools/shared": "workspace:*","@t3tools/ssh": "workspace:*",@@ -179,6 +180,7 @@"zustand": "^5.0.11",},"devDependencies": {+ "@effect/platform-node": "catalog:","@rolldown/plugin-babel": "^0.2.0","@tailwindcss/vite": "^4.0.0","@tanstack/router-plugin": "^1.161.0",@@ -187,7 +189,7 @@"@types/react-dom": "~19.2.3","@vercel/config": "^0.3.0","@vitejs/plugin-react": "^6.0.0",- "@vitest/browser-playwright": "^4.0.18",+ "@vitest/browser-playwright": "catalog:","babel-plugin-react-compiler": "1.0.0","msw": "2.12.11","playwright": "^1.58.2",@@ -345,10 +347,11 @@"@types/bun": "^1.3.11","@types/node": "^24.10.13","@typescript/native-preview": "7.0.0-dev.20260527.2",+ "@vitest/browser-playwright": "4.1.0","effect": "4.0.0-beta.73","tsdown": "^0.20.3","typescript": "~6.0.3",- "vitest": "^4.0.0",+ "vitest": "4.1.0",},"packages": {"@adobe/css-tools": ["@adobe/[email protected]", "", {}, "sha512-6OzddxPio9UiWTCemp4N8cYLV2ZN1ncRnV1cVGtve7dhPOtRkleRyx32GQCYSwDYgaHU3USMm84tNsvKzRCa1Q=="],diff --git a/docs/environment-auth.md b/docs/environment-auth.mdnew file mode 100644index 000000000..af92bcb47--- /dev/null+++ b/docs/environment-auth.md@@ -0,0 +1,113 @@+# Environment Authentication Profile++The environment server and the relay use separate credentials, issuers, and trust+boundaries. They intentionally use a similar OAuth-shaped model so that permission+checks and token exchange behavior can be audited against established concepts.++## Authorization Model++Environment authorization is capability-based. A session carries zero or more+OAuth-style scope strings:++| Scope | Permission |+| ----------------------- | ------------------------------------------------------------------------ |+| `orchestration:read` | Read snapshots, status, events, configuration, and filesystem/VCS state. |+| `orchestration:operate` | Dispatch user operations and mutate environment-side workspace state. |+| `terminal:operate` | Create, attach, input, resize, clear, restart, and terminate terminals. |+| `review:write` | Read review diff previews used to compose review feedback. |+| `access:read` | Inspect pairing links and client sessions. |+| `access:write` | Create or revoke pairing links and client sessions. |+| `relay:read` | Inspect managed relay connectivity. |+| `relay:write` | Link, configure, or unlink managed relay connectivity. |++Ordinary pairing links grant the four client-operation scopes and read access to+managed relay connectivity:+`orchestration:read orchestration:operate terminal:operate review:write relay:read`.+The desktop bootstrap credential and command-line administrative bootstrap+credentials additionally grant `access:read access:write relay:write`.++## Authentication Flows++### Browser Session++`POST /api/auth/browser-session` consumes a one-time bootstrap credential and creates a+browser session cookie. The cookie is an HTTP transport adapter for the same+scoped session model; the response never exposes the session secret to browser+JavaScript.++### Bearer Access Token++Non-browser clients use `POST /oauth/token` with an+`application/x-www-form-urlencoded` body:++```text+grant_type=urn:ietf:params:oauth:grant-type:token-exchange+subject_token=<bootstrap credential>+subject_token_type=urn:t3:params:oauth:token-type:environment-bootstrap+requested_token_type=urn:ietf:params:oauth:token-type:access_token+scope=orchestration:read orchestration:operate terminal:operate review:write relay:read+```++Clients may additionally submit `client_label`, `client_device_type`, and+`client_os` extension parameters so the authorized-clients UI can identify the+device that established the session. These are presentation hints only; the+environment derives transport metadata such as IP address and user agent from+the request and does not use these fields for authorization.++The response has the token-exchange shape:++```json+{+ "access_token": "<opaque session token>",+ "issued_token_type": "urn:ietf:params:oauth:token-type:access_token",+ "token_type": "Bearer",+ "expires_in": 3600,+ "scope": "orchestration:read orchestration:operate terminal:operate review:write relay:read"+}+```++Requested scopes must be a subset of the one-time bootstrap credential grant.+An ordinary paired client therefore cannot exchange its grant for+`access:read`, `access:write`, or `relay:write`.++### WebSocket Ticket++`POST /api/auth/websocket-ticket` accepts any authenticated session and returns+a short-lived, single-purpose WebSocket ticket. This keeps bearer tokens and+browser cookies out of WebSocket URLs while allowing the socket handshake to+authenticate. The ticket carries its session's scopes; each RPC method then+enforces `orchestration:read`, `orchestration:operate`, `terminal:operate`,+`review:write`, or `access:read` as appropriate. Review feedback submission+currently dispatches an orchestration operation, so clients performing it also+need `orchestration:operate`. Creating a ticket is not+authorization to call every RPC method.++## Standards Alignment++- Bearer access tokens are used through the `Authorization: Bearer` scheme from+ RFC 6750.+- The token endpoint profiles the request and response vocabulary from OAuth 2.0+ Token Exchange (RFC 8693), including `subject_token`, `requested_token_type`,+ `access_token`, `issued_token_type`, and `token_type`.+- Scope values follow the OAuth 2.0 scope model from RFC 6749: space-delimited,+ unordered capabilities with subset checking during exchange.++This is intentionally not a general-purpose OAuth authorization server. The+environment bootstrap token type is private, the bootstrap cookie and WebSocket+connection-token routes are product-specific adapters, and the API returns its+typed `HttpApi` errors rather than implementing every OAuth error response+surface.++## Upgrade Behavior++Migration `031_AuthAuthorizationScopes` is a hard cutover from role-bearing auth+records to scoped records. It deletes existing pairing links and sessions while+leaving non-authentication environment state unchanged. Upgraded clients must+pair again; old `owner` or `client` credentials are never silently mapped to new+capabilities.++## Relay Boundary++Relay-managed tunnels use their own tokens and keys. The relay can reuse scope+parsing and token-exchange conventions, but an environment access token is not a+relay token and cannot be presented to the relay.diff --git a/package.json b/package.jsonindex 8bd251ce3..9b2aedf10 100644--- a/package.json+++ b/package.json@@ -24,7 +24,8 @@"@typescript/native-preview": "7.0.0-dev.20260527.2","tsdown": "^0.20.3","typescript": "~6.0.3",- "vitest": "^4.0.0"+ "@vitest/browser-playwright": "4.1.0",+ "vitest": "4.1.0"}},"type": "module",diff --git a/packages/client-runtime/src/remote.test.ts b/packages/client-runtime/src/remote.test.tsindex c832f4f38..27c0ce927 100644--- a/packages/client-runtime/src/remote.test.ts+++ b/packages/client-runtime/src/remote.test.ts@@ -2,19 +2,23 @@ import { describe, expect, it } from "@effect/vitest";import * as Duration from "effect/Duration";import * as Effect from "effect/Effect";import * as Fiber from "effect/Fiber";+import * as Schema from "effect/Schema";import * as TestClock from "effect/testing/TestClock";-import { HttpClient } from "effect/unstable/http";+import { EnvironmentAuthInvalidError } from "@t3tools/contracts";import {bootstrapRemoteBearerSession,fetchRemoteEnvironmentDescriptor,fetchRemoteSessionState,- issueRemoteWebSocketToken,+ issueRemoteWebSocketTicket,remoteHttpClientLayer,+ RemoteEnvironmentAuthInvalidJsonError,RemoteEnvironmentAuthTimeoutError,resolveRemoteWebSocketConnectionUrl,} from "./remote.ts";+const isEnvironmentAuthInvalidError = Schema.is(EnvironmentAuthInvalidError);+type FetchCall = readonly [input: RequestInfo | URL, init: RequestInit];const recordedFetch = (...responses: ReadonlyArray<Response>) => {@@ -42,10 +46,7 @@ const hangingFetch = () => {return { fetchFn, calls };};-const provideRemoteHttp =- (fetchFn: typeof fetch) =>- <A, E, R>(effect: Effect.Effect<A, E, R | HttpClient.HttpClient>) =>- effect.pipe(Effect.provide(remoteHttpClientLayer(fetchFn)));+const provideRemoteHttp = (fetchFn: typeof fetch) => Effect.provide(remoteHttpClientLayer(fetchFn));const expectFetchCall = (calls: ReadonlyArray<FetchCall>,@@ -90,11 +91,12 @@ describe("remote", () => {const fetch = recordedFetch(Response.json({- authenticated: true,- role: "client",- sessionMethod: "bearer-session-token",- expiresAt: "2026-05-01T12:00:00.000Z",- sessionToken: "bearer-token",+ access_token: "bearer-token",+ issued_token_type: "urn:ietf:params:oauth:token-type:access_token",+ token_type: "Bearer",+ expires_in: 3600,+ scope:+ "orchestration:read orchestration:operate terminal:operate review:write relay:read",},{ status: 200 },),@@ -106,16 +108,80 @@ describe("remote", () => {}).pipe(provideRemoteHttp(fetch.fetchFn));expect(result).toMatchObject({- sessionMethod: "bearer-session-token",- sessionToken: "bearer-token",+ token_type: "Bearer",+ access_token: "bearer-token",+ scope: "orchestration:read orchestration:operate terminal:operate review:write relay:read",});expectFetchCall(fetch.calls, 1, {- url: "https://remote.example.com/api/auth/bootstrap/bearer",+ url: "https://remote.example.com/oauth/token",method: "POST",headers: {- "content-type": "application/json",+ "content-type": "application/x-www-form-urlencoded",},- body: `{"credential":"pairing-token"}`,+ body: "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Atoken-exchange&subject_token=pairing-token&subject_token_type=urn%3At3%3Aparams%3Aoauth%3Atoken-type%3Aenvironment-bootstrap&requested_token_type=urn%3Aietf%3Aparams%3Aoauth%3Atoken-type%3Aaccess_token",+ });+ }),+ );++ it.effect("submits optional client display metadata during bearer token exchange", () =>+ Effect.gen(function* () {+ const fetch = recordedFetch(+ Response.json(+ {+ access_token: "bearer-token",+ issued_token_type: "urn:ietf:params:oauth:token-type:access_token",+ token_type: "Bearer",+ expires_in: 3600,+ scope:+ "orchestration:read orchestration:operate terminal:operate review:write relay:read",+ },+ { status: 200 },+ ),+ );++ yield* bootstrapRemoteBearerSession({+ httpBaseUrl: "https://remote.example.com/",+ credential: "pairing-token",+ clientMetadata: {+ label: "T3 Code Mobile",+ deviceType: "mobile",+ os: "iOS",+ },+ }).pipe(provideRemoteHttp(fetch.fetchFn));++ expectFetchCall(fetch.calls, 1, {+ url: "https://remote.example.com/oauth/token",+ method: "POST",+ body: "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Atoken-exchange&subject_token=pairing-token&subject_token_type=urn%3At3%3Aparams%3Aoauth%3Atoken-type%3Aenvironment-bootstrap&requested_token_type=urn%3Aietf%3Aparams%3Aoauth%3Atoken-type%3Aaccess_token&client_label=T3+Code+Mobile&client_device_type=mobile&client_os=iOS",+ });+ }),+ );++ it.effect("allows a client to explicitly narrow a pairing grant", () =>+ Effect.gen(function* () {+ const fetch = recordedFetch(+ Response.json(+ {+ access_token: "read-only-token",+ issued_token_type: "urn:ietf:params:oauth:token-type:access_token",+ token_type: "Bearer",+ expires_in: 3600,+ scope: "orchestration:read",+ },+ { status: 200 },+ ),+ );++ yield* bootstrapRemoteBearerSession({+ httpBaseUrl: "https://remote.example.com/",+ credential: "pairing-token",+ scopes: ["orchestration:read"],+ }).pipe(provideRemoteHttp(fetch.fetchFn));++ expectFetchCall(fetch.calls, 1, {+ url: "https://remote.example.com/oauth/token",+ method: "POST",+ body: "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Atoken-exchange&subject_token=pairing-token&subject_token_type=urn%3At3%3Aparams%3Aoauth%3Atoken-type%3Aenvironment-bootstrap&requested_token_type=urn%3Aietf%3Aparams%3Aoauth%3Atoken-type%3Aaccess_token&scope=orchestration%3Aread",});}),);@@ -144,18 +210,24 @@ describe("remote", () => {auth: {policy: "remote-reachable",bootstrapMethods: ["one-time-token"],- sessionMethods: ["browser-session-cookie", "bearer-session-token"],+ sessionMethods: ["browser-session-cookie", "bearer-access-token"],sessionCookieName: "t3_session",},- role: "client",- sessionMethod: "bearer-session-token",+ scopes: [+ "orchestration:read",+ "orchestration:operate",+ "terminal:operate",+ "review:write",+ "relay:read",+ ],+ sessionMethod: "bearer-access-token",expiresAt: "2026-05-01T12:00:00.000Z",},{ status: 200 },),Response.json({- token: "ws-token",+ ticket: "ws-ticket",expiresAt: "2026-05-01T12:05:00.000Z",},{ status: 200 },@@ -176,15 +248,21 @@ describe("remote", () => {}).pipe(provideRemoteHttp(fetch.fetchFn));expect(session).toMatchObject({authenticated: true,- role: "client",+ scopes: [+ "orchestration:read",+ "orchestration:operate",+ "terminal:operate",+ "review:write",+ "relay:read",+ ],});- const token = yield* issueRemoteWebSocketToken({+ const token = yield* issueRemoteWebSocketTicket({httpBaseUrl: "https://remote.example.com/",bearerToken: "bearer-token",}).pipe(provideRemoteHttp(fetch.fetchFn));expect(token).toMatchObject({- token: "ws-token",+ ticket: "ws-ticket",});expectFetchCall(fetch.calls, 1, {@@ -199,7 +277,7 @@ describe("remote", () => {},});expectFetchCall(fetch.calls, 3, {- url: "https://remote.example.com/api/auth/ws-token",+ url: "https://remote.example.com/api/auth/websocket-ticket",method: "POST",headers: {authorization: "Bearer bearer-token",@@ -227,25 +305,82 @@ describe("remote", () => {}).pipe(Effect.provide(TestClock.layer())),);- it.effect("mints a websocket url that targets the rpc route with a short-lived ws token", () =>+ it.effect("revives declared typed errors from remote auth failures", () =>Effect.gen(function* () {const fetch = recordedFetch(Response.json({- token: "ws-token",- expiresAt: "2026-05-01T12:05:00.000Z",+ _tag: "EnvironmentAuthInvalidError",+ code: "auth_invalid",+ reason: "missing_credential",+ traceId: "trace-auth-test",+ },+ { status: 401 },+ ),+ );++ const error = yield* issueRemoteWebSocketTicket({+ httpBaseUrl: "https://remote.example.com/",+ bearerToken: "expired-token",+ }).pipe(provideRemoteHttp(fetch.fetchFn), Effect.flip);++ expect(isEnvironmentAuthInvalidError(error)).toBe(true);+ if (isEnvironmentAuthInvalidError(error)) {+ expect(error.reason).toBe("missing_credential");+ expect(error.traceId).toBe("trace-auth-test");+ }+ }),+ );++ it.effect("classifies malformed successful remote auth responses as invalid responses", () =>+ Effect.gen(function* () {+ const fetch = recordedFetch(+ Response.json(+ {+ access_token: "",+ issued_token_type: "urn:ietf:params:oauth:token-type:access_token",+ token_type: "Bearer",+ expires_in: 3600,+ scope:+ "orchestration:read orchestration:operate terminal:operate review:write relay:read",},{ status: 200 },),);- const url = yield* resolveRemoteWebSocketConnectionUrl({- wsBaseUrl: "wss://remote.example.com/",+ const error = yield* bootstrapRemoteBearerSession({httpBaseUrl: "https://remote.example.com/",- bearerToken: "bearer-token",- }).pipe(provideRemoteHttp(fetch.fetchFn));+ credential: "pairing-token",+ }).pipe(provideRemoteHttp(fetch.fetchFn), Effect.flip);- expect(url).toBe("wss://remote.example.com/ws?wsToken=ws-token");+ expect(error).toBeInstanceOf(RemoteEnvironmentAuthInvalidJsonError);+ expect(error.message).toBe(+ "Remote auth endpoint returned an invalid response from https://remote.example.com/oauth/token.",+ );}),);++ it.effect(+ "mints a websocket url that targets the rpc route with a short-lived websocket ticket",+ () =>+ Effect.gen(function* () {+ const fetch = recordedFetch(+ Response.json(+ {+ ticket: "ws-ticket",+ expiresAt: "2026-05-01T12:05:00.000Z",+ },+ { status: 200 },+ ),+ );++ const url = yield* resolveRemoteWebSocketConnectionUrl({+ wsBaseUrl: "wss://remote.example.com/",+ httpBaseUrl: "https://remote.example.com/",+ bearerToken: "bearer-token",+ }).pipe(provideRemoteHttp(fetch.fetchFn));++ expect(url).toBe("wss://remote.example.com/ws?wsTicket=ws-ticket");+ }),+ );});diff --git a/packages/client-runtime/src/remote.ts b/packages/client-runtime/src/remote.tsindex 34dc5aef2..cc8ef361b 100644--- a/packages/client-runtime/src/remote.ts+++ b/packages/client-runtime/src/remote.ts@@ -1,30 +1,31 @@+import {+ AuthAccessTokenType,+ type AuthClientPresentationMetadata,+ AuthEnvironmentBootstrapTokenType,+ AuthTokenExchangeGrantType,+ type AuthEnvironmentScope,+ EnvironmentHttpApi,+ EnvironmentHttpCommonError,+} from "@t3tools/contracts";+import { encodeOAuthScope } from "@t3tools/shared/oauthScope";import type {- AuthBearerBootstrapResult,- AuthSessionState,- AuthWebSocketTokenResult,- ExecutionEnvironmentDescriptor,+ EnvironmentAuthInvalidError,+ EnvironmentInternalError,+ EnvironmentOperationForbiddenError,+ EnvironmentRequestInvalidError,+ EnvironmentScopeRequiredError,} from "@t3tools/contracts";-import { decodeJsonResult } from "@t3tools/shared/schemaJson";import * as Data from "effect/Data";import * as Duration from "effect/Duration";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import * as Option from "effect/Option";-import * as Result from "effect/Result";import * as Schema from "effect/Schema";-import { identity } from "effect/Function";-import {- FetchHttpClient,- HttpClient,- HttpClientRequest,- HttpClientResponse,-} from "effect/unstable/http";+import { FetchHttpClient, HttpClient, HttpClientError } from "effect/unstable/http";+import * as HttpApiClient from "effect/unstable/httpapi/HttpApiClient";const DEFAULT_REMOTE_REQUEST_TIMEOUT_MS = 10_000;-const RemoteAuthErrorBody = Schema.Struct({- error: Schema.optional(Schema.String),-});-const decodeRemoteAuthErrorBody = decodeJsonResult(RemoteAuthErrorBody);+const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);const remoteEndpointUrl = (httpBaseUrl: string, pathname: string): string => {const url = new URL(httpBaseUrl);@@ -34,6 +35,14 @@ const remoteEndpointUrl = (httpBaseUrl: string, pathname: string): string => {return url.toString();};+const remoteApiBaseUrl = (httpBaseUrl: string): string => {+ const url = new URL(httpBaseUrl);+ url.pathname = "/";+ url.search = "";+ url.hash = "";+ return url.toString();+};+export class RemoteEnvironmentAuthFetchError extends Data.TaggedError("RemoteEnvironmentAuthFetchError",)<{@@ -41,13 +50,6 @@ export class RemoteEnvironmentAuthFetchError extends Data.TaggedError(readonly cause: unknown;}> {}-export class RemoteEnvironmentAuthResponseReadError extends Data.TaggedError(- "RemoteEnvironmentAuthResponseReadError",-)<{- readonly message: string;- readonly cause: unknown;-}> {}-export class RemoteEnvironmentAuthInvalidJsonError extends Data.TaggedError("RemoteEnvironmentAuthInvalidJsonError",)<{@@ -55,14 +57,19 @@ export class RemoteEnvironmentAuthInvalidJsonError extends Data.TaggedError(readonly cause: unknown;}> {}-export class RemoteEnvironmentAuthHttpError extends Data.TaggedError(- "RemoteEnvironmentAuthHttpError",+export class RemoteEnvironmentAuthUndeclaredStatusError extends Data.TaggedError(+ "RemoteEnvironmentAuthUndeclaredStatusError",)<{readonly message: string;readonly status: number;+ readonly requestUrl: string;}> {- constructor(message: string, status: number) {- super({ message, status });+ constructor(requestUrl: string, status: number) {+ super({+ message: `Remote auth endpoint ${requestUrl} returned undeclared status ${status}.`,+ requestUrl,+ status,+ });}}@@ -83,87 +90,67 @@ export class RemoteEnvironmentAuthTimeoutError extends Data.TaggedError(}export type RemoteEnvironmentAuthError =+ | EnvironmentRequestInvalidError+ | EnvironmentAuthInvalidError+ | EnvironmentScopeRequiredError+ | EnvironmentOperationForbiddenError+ | EnvironmentInternalError| RemoteEnvironmentAuthFetchError- | RemoteEnvironmentAuthResponseReadError| RemoteEnvironmentAuthInvalidJsonError- | RemoteEnvironmentAuthHttpError+ | RemoteEnvironmentAuthUndeclaredStatusError| RemoteEnvironmentAuthTimeoutError;-export const isRemoteEnvironmentAuthHttpError = (- error: unknown,-): error is RemoteEnvironmentAuthHttpError => error instanceof RemoteEnvironmentAuthHttpError;--const readRemoteAuthErrorMessage = (- response: HttpClientResponse.HttpClientResponse,- fallbackMessage: string,-): Effect.Effect<string, RemoteEnvironmentAuthResponseReadError> =>- response.text.pipe(- Effect.mapError(- (cause) =>- new RemoteEnvironmentAuthResponseReadError({- message: "Remote auth endpoint returned an unreadable error response.",- cause,- }),- ),- Effect.map((text) => {- if (!text) {- return fallbackMessage;- }-- const decoded = decodeRemoteAuthErrorBody(text);- if (Result.isSuccess(decoded) && decoded.success.error) {- return decoded.success.error;- }-- return text;- }),- );--const readRemoteJson = <T>(- response: HttpClientResponse.HttpClientResponse,- requestUrl: string,-): Effect.Effect<T, RemoteEnvironmentAuthInvalidJsonError> =>- response.json.pipe(- Effect.mapError(- (cause) =>- new RemoteEnvironmentAuthInvalidJsonError({- message: `Remote auth endpoint returned invalid JSON from ${requestUrl}.`,- cause,- }),- ),- Effect.map((value) => value as T),- );-export const remoteHttpClientLayer = (fetchFn: typeof globalThis.fetch,): Layer.Layer<HttpClient.HttpClient> =>FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetchFn)));-const fetchRemoteJson = Effect.fn("clientRuntime.remote.fetchRemoteJson")(function* <T>(input: {- readonly httpBaseUrl: string;- readonly pathname: string;- readonly method?: "GET" | "POST";- readonly bearerToken?: string;- readonly body?: unknown;- readonly timeoutMs?: number;-}) {- const requestUrl = remoteEndpointUrl(input.httpBaseUrl, input.pathname);- const method = input.method ?? "GET";- const timeoutMs = input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS;- const request = HttpClientRequest.make(method)(requestUrl).pipe(- input.bearerToken ? HttpClientRequest.bearerToken(input.bearerToken) : identity,- input.body !== undefined ? HttpClientRequest.bodyJsonUnsafe(input.body) : identity,+const failRemoteRequest = (+ requestUrl: string,+ cause: unknown,+): Effect.Effect<never, RemoteEnvironmentAuthError> => {+ if (cause instanceof RemoteEnvironmentAuthTimeoutError) {+ return Effect.fail(cause);+ }+ if (isEnvironmentHttpCommonError(cause)) {+ return Effect.fail(cause);+ }+ if (Schema.isSchemaError(cause)) {+ return Effect.fail(+ new RemoteEnvironmentAuthInvalidJsonError({+ message: `Remote auth endpoint returned an invalid response from ${requestUrl}.`,+ cause,+ }),+ );+ }+ if (HttpClientError.isHttpClientError(cause) && cause.response !== undefined) {+ const response = cause.response;+ if (response.status < 200 || response.status >= 300) {+ return Effect.fail(+ new RemoteEnvironmentAuthUndeclaredStatusError(requestUrl, response.status),+ );+ }+ return Effect.fail(+ new RemoteEnvironmentAuthInvalidJsonError({+ message: `Remote auth endpoint returned an invalid response from ${requestUrl}.`,+ cause,+ }),+ );+ }+ return Effect.fail(+ new RemoteEnvironmentAuthFetchError({+ message: `Failed to fetch remote auth endpoint ${requestUrl} (${String(cause)}).`,+ cause,+ }),);+};- const client = yield* HttpClient.HttpClient;- const response = yield* client.execute(request).pipe(- Effect.mapError(- (cause) =>- new RemoteEnvironmentAuthFetchError({- message: `Failed to fetch remote auth endpoint ${requestUrl} (${String(cause)}).`,- cause,- }),- ),+const executeRemoteRequest = <A, E, R>(+ requestUrl: string,+ timeoutMs: number,+ request: Effect.Effect<A, E, R>,+): Effect.Effect<A, RemoteEnvironmentAuthError, R> =>+ request.pipe(Effect.timeoutOption(Duration.millis(timeoutMs)),Effect.flatMap(Option.match({@@ -171,38 +158,46 @@ const fetchRemoteJson = Effect.fn("clientRuntime.remote.fetchRemoteJson")(functionSome: Effect.succeed,}),),+ Effect.catch((cause) => failRemoteRequest(requestUrl, cause)),);- if (response.status < 200 || response.status >= 300) {- return yield* readRemoteAuthErrorMessage(- response,- `Remote auth request failed (${response.status}).`,- ).pipe(- Effect.flatMap((message) =>- Effect.fail(new RemoteEnvironmentAuthHttpError(message, response.status)),- ),- );- }-- return yield* readRemoteJson<T>(response, requestUrl);-});+export const makeEnvironmentHttpApiClient = (httpBaseUrl: string) =>+ Effect.gen(function* () {+ const httpClient = yield* HttpClient.HttpClient;+ return yield* HttpApiClient.makeWith(EnvironmentHttpApi, {+ httpClient,+ baseUrl: remoteApiBaseUrl(httpBaseUrl),+ });+ });export const bootstrapRemoteBearerSession = Effect.fn("clientRuntime.remote.bootstrapRemoteBearerSession",)(function* (input: {readonly httpBaseUrl: string;readonly credential: string;+ readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;+ readonly clientMetadata?: AuthClientPresentationMetadata;readonly timeoutMs?: number;}) {- return yield* fetchRemoteJson<AuthBearerBootstrapResult>({- httpBaseUrl: input.httpBaseUrl,- pathname: "/api/auth/bootstrap/bearer",- method: "POST",- ...(input.timeoutMs ? { timeoutMs: input.timeoutMs } : {}),- body: {- credential: input.credential,- },- });+ const client = yield* makeEnvironmentHttpApiClient(input.httpBaseUrl);+ return yield* executeRemoteRequest(+ remoteEndpointUrl(input.httpBaseUrl, "/oauth/token"),+ input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,+ client.auth.token({+ payload: {+ grant_type: AuthTokenExchangeGrantType,+ subject_token: input.credential,+ subject_token_type: AuthEnvironmentBootstrapTokenType,+ requested_token_type: AuthAccessTokenType,+ ...(input.scopes ? { scope: encodeOAuthScope(input.scopes) } : {}),+ ...(input.clientMetadata?.label ? { client_label: input.clientMetadata.label } : {}),+ ...(input.clientMetadata?.deviceType+ ? { client_device_type: input.clientMetadata.deviceType }+ : {}),+ ...(input.clientMetadata?.os ? { client_os: input.clientMetadata.os } : {}),+ },+ }),+ );});export const fetchRemoteSessionState = Effect.fn("clientRuntime.remote.fetchRemoteSessionState")(@@ -211,39 +206,47 @@ export const fetchRemoteSessionState = Effect.fn("clientRuntime.remote.fetchRemoreadonly bearerToken: string;readonly timeoutMs?: number;}) {- return yield* fetchRemoteJson<AuthSessionState>({- httpBaseUrl: input.httpBaseUrl,- pathname: "/api/auth/session",- bearerToken: input.bearerToken,- ...(input.timeoutMs ? { timeoutMs: input.timeoutMs } : {}),- });+ const client = yield* makeEnvironmentHttpApiClient(input.httpBaseUrl);+ return yield* executeRemoteRequest(+ remoteEndpointUrl(input.httpBaseUrl, "/api/auth/session"),+ input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,+ client.auth.session({+ headers: {+ authorization: `Bearer ${input.bearerToken}`,+ },+ }),+ );},);export const fetchRemoteEnvironmentDescriptor = Effect.fn("clientRuntime.remote.fetchRemoteEnvironmentDescriptor",)(function* (input: { readonly httpBaseUrl: string; readonly timeoutMs?: number }) {- return yield* fetchRemoteJson<ExecutionEnvironmentDescriptor>({- httpBaseUrl: input.httpBaseUrl,- pathname: "/.well-known/t3/environment",- ...(input.timeoutMs ? { timeoutMs: input.timeoutMs } : {}),- });+ const client = yield* makeEnvironmentHttpApiClient(input.httpBaseUrl);+ return yield* executeRemoteRequest(+ remoteEndpointUrl(input.httpBaseUrl, "/.well-known/t3/environment"),+ input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,+ client.metadata.descriptor(),+ );});-export const issueRemoteWebSocketToken = Effect.fn(- "clientRuntime.remote.issueRemoteWebSocketToken",+export const issueRemoteWebSocketTicket = Effect.fn(+ "clientRuntime.remote.issueRemoteWebSocketTicket",)(function* (input: {readonly httpBaseUrl: string;readonly bearerToken: string;readonly timeoutMs?: number;}) {- return yield* fetchRemoteJson<AuthWebSocketTokenResult>({- httpBaseUrl: input.httpBaseUrl,- pathname: "/api/auth/ws-token",- method: "POST",- bearerToken: input.bearerToken,- ...(input.timeoutMs ? { timeoutMs: input.timeoutMs } : {}),- });+ const client = yield* makeEnvironmentHttpApiClient(input.httpBaseUrl);+ return yield* executeRemoteRequest(+ remoteEndpointUrl(input.httpBaseUrl, "/api/auth/websocket-ticket"),+ input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,+ client.auth.webSocketTicket({+ headers: {+ authorization: `Bearer ${input.bearerToken}`,+ },+ }),+ );});export const resolveRemoteWebSocketConnectionUrl = Effect.fn(@@ -254,7 +257,7 @@ export const resolveRemoteWebSocketConnectionUrl = Effect.fn(readonly bearerToken: string;readonly timeoutMs?: number;}) {- const issued = yield* issueRemoteWebSocketToken({+ const issued = yield* issueRemoteWebSocketTicket({httpBaseUrl: input.httpBaseUrl,bearerToken: input.bearerToken,...(input.timeoutMs ? { timeoutMs: input.timeoutMs } : {}),@@ -264,6 +267,6 @@ export const resolveRemoteWebSocketConnectionUrl = Effect.fn(if (url.pathname === "" || url.pathname === "/") {url.pathname = "/ws";}- url.searchParams.set("wsToken", issued.token);+ url.searchParams.set("wsTicket", issued.ticket);return url.toString();});diff --git a/packages/client-runtime/src/wsTransport.test.ts b/packages/client-runtime/src/wsTransport.test.tsindex cc1c2e3d8..1933c3e03 100644--- a/packages/client-runtime/src/wsTransport.test.ts+++ b/packages/client-runtime/src/wsTransport.test.ts@@ -170,13 +170,13 @@ describe("WsTransport", () => {});it("supports async websocket url providers", async () => {- const transport = createTransport(async () => "wss://remote.example.com/?wsToken=dynamic");+ const transport = createTransport(async () => "wss://remote.example.com/?wsTicket=dynamic");await waitFor(() => {expect(sockets).toHaveLength(1);});- expect(getSocket().url).toBe("wss://remote.example.com/ws?wsToken=dynamic");+ expect(getSocket().url).toBe("wss://remote.example.com/ws?wsTicket=dynamic");await transport.dispose();});diff --git a/packages/contracts/src/auth.ts b/packages/contracts/src/auth.tsindex 8439d12b0..2b062fc2d 100644--- a/packages/contracts/src/auth.ts+++ b/packages/contracts/src/auth.ts@@ -1,4 +1,5 @@import * as Schema from "effect/Schema";+import * as HttpApiSchema from "effect/unstable/httpapi/HttpApiSchema";import { AuthSessionId, TrimmedNonEmptyString } from "./baseSchemas.ts";@@ -60,17 +61,56 @@ export type ServerAuthBootstrapMethod = typeof ServerAuthBootstrapMethod.Type;* Current methods:* - `browser-session-cookie`: cookie-backed browser session, used by the web* app after bootstrap/pairing- * - `bearer-session-token`: token-based session suitable for non-cookie or+ * - `bearer-access-token`: scoped token suitable for non-cookie or* non-browser clients*/export const ServerAuthSessionMethod = Schema.Literals(["browser-session-cookie",- "bearer-session-token",+ "bearer-access-token",]);export type ServerAuthSessionMethod = typeof ServerAuthSessionMethod.Type;-export const AuthSessionRole = Schema.Literals(["owner", "client"]);-export type AuthSessionRole = typeof AuthSessionRole.Type;+export const AuthOrchestrationReadScope = "orchestration:read" as const;+export const AuthOrchestrationOperateScope = "orchestration:operate" as const;+export const AuthTerminalOperateScope = "terminal:operate" as const;+export const AuthReviewWriteScope = "review:write" as const;+export const AuthAccessReadScope = "access:read" as const;+export const AuthAccessWriteScope = "access:write" as const;+export const AuthRelayReadScope = "relay:read" as const;+export const AuthRelayWriteScope = "relay:write" as const;+export const AuthEnvironmentScope = Schema.Literals([+ AuthOrchestrationReadScope,+ AuthOrchestrationOperateScope,+ AuthTerminalOperateScope,+ AuthReviewWriteScope,+ AuthAccessReadScope,+ AuthAccessWriteScope,+ AuthRelayReadScope,+ AuthRelayWriteScope,+]);+export type AuthEnvironmentScope = typeof AuthEnvironmentScope.Type;+export const AuthEnvironmentScopes = Schema.Array(AuthEnvironmentScope);+export type AuthEnvironmentScopes = typeof AuthEnvironmentScopes.Type;++export const AuthStandardClientScopes = [+ AuthOrchestrationReadScope,+ AuthOrchestrationOperateScope,+ AuthTerminalOperateScope,+ AuthReviewWriteScope,+ AuthRelayReadScope,+] as const;+export const AuthAdministrativeScopes = [+ ...AuthStandardClientScopes,+ AuthAccessReadScope,+ AuthAccessWriteScope,+ AuthRelayWriteScope,+] as const;++export const AuthTokenExchangeGrantType =+ "urn:ietf:params:oauth:grant-type:token-exchange" as const;+export const AuthAccessTokenType = "urn:ietf:params:oauth:token-type:access_token" as const;+export const AuthEnvironmentBootstrapTokenType =+ "urn:t3:params:oauth:token-type:environment-bootstrap" as const;/*** Server-advertised auth capabilities for a specific execution environment.@@ -100,33 +140,61 @@ export const ServerAuthDescriptor = Schema.Struct({});export type ServerAuthDescriptor = typeof ServerAuthDescriptor.Type;-export const AuthBootstrapInput = Schema.Struct({+export const AuthBrowserSessionRequest = Schema.Struct({credential: TrimmedNonEmptyString,});-export type AuthBootstrapInput = typeof AuthBootstrapInput.Type;+export type AuthBrowserSessionRequest = typeof AuthBrowserSessionRequest.Type;-export const AuthBootstrapResult = Schema.Struct({+export const AuthBrowserSessionResult = Schema.Struct({authenticated: Schema.Literal(true),- role: AuthSessionRole,+ scopes: AuthEnvironmentScopes,sessionMethod: ServerAuthSessionMethod,expiresAt: Schema.DateTimeUtc,});-export type AuthBootstrapResult = typeof AuthBootstrapResult.Type;+export type AuthBrowserSessionResult = typeof AuthBrowserSessionResult.Type;-export const AuthBearerBootstrapResult = Schema.Struct({- authenticated: Schema.Literal(true),- role: AuthSessionRole,- sessionMethod: Schema.Literal("bearer-session-token"),- expiresAt: Schema.DateTimeUtc,- sessionToken: TrimmedNonEmptyString,+export const AuthClientMetadataDeviceType = Schema.Literals([+ "desktop",+ "mobile",+ "tablet",+ "bot",+ "unknown",+]);+export type AuthClientMetadataDeviceType = typeof AuthClientMetadataDeviceType.Type;++export const AuthClientPresentationMetadata = Schema.Struct({+ label: Schema.optionalKey(TrimmedNonEmptyString),+ deviceType: Schema.optionalKey(AuthClientMetadataDeviceType),+ os: Schema.optionalKey(TrimmedNonEmptyString),+});+export type AuthClientPresentationMetadata = typeof AuthClientPresentationMetadata.Type;++export const AuthTokenExchangeRequest = Schema.Struct({+ grant_type: Schema.Literal(AuthTokenExchangeGrantType),+ subject_token: TrimmedNonEmptyString,+ subject_token_type: Schema.Literal(AuthEnvironmentBootstrapTokenType),+ requested_token_type: Schema.Literal(AuthAccessTokenType),+ scope: Schema.optionalKey(TrimmedNonEmptyString),+ client_label: Schema.optionalKey(TrimmedNonEmptyString),+ client_device_type: Schema.optionalKey(AuthClientMetadataDeviceType),+ client_os: Schema.optionalKey(TrimmedNonEmptyString),+}).pipe(HttpApiSchema.asFormUrlEncoded());+export type AuthTokenExchangeRequest = typeof AuthTokenExchangeRequest.Type;++export const AuthAccessTokenResult = Schema.Struct({+ access_token: TrimmedNonEmptyString,+ issued_token_type: Schema.Literal(AuthAccessTokenType),+ token_type: Schema.Literal("Bearer"),+ expires_in: Schema.Number,+ scope: TrimmedNonEmptyString,});-export type AuthBearerBootstrapResult = typeof AuthBearerBootstrapResult.Type;+export type AuthAccessTokenResult = typeof AuthAccessTokenResult.Type;-export const AuthWebSocketTokenResult = Schema.Struct({- token: TrimmedNonEmptyString,+export const AuthWebSocketTicketResult = Schema.Struct({+ ticket: TrimmedNonEmptyString,expiresAt: Schema.DateTimeUtc,});-export type AuthWebSocketTokenResult = typeof AuthWebSocketTokenResult.Type;+export type AuthWebSocketTicketResult = typeof AuthWebSocketTicketResult.Type;export const AuthPairingCredentialResult = Schema.Struct({id: TrimmedNonEmptyString,@@ -139,7 +207,7 @@ export type AuthPairingCredentialResult = typeof AuthPairingCredentialResult.Typexport const AuthPairingLink = Schema.Struct({id: TrimmedNonEmptyString,credential: TrimmedNonEmptyString,- role: AuthSessionRole,+ scopes: AuthEnvironmentScopes,subject: TrimmedNonEmptyString,label: Schema.optionalKey(TrimmedNonEmptyString),createdAt: Schema.DateTimeUtc,@@ -147,15 +215,6 @@ export const AuthPairingLink = Schema.Struct({});export type AuthPairingLink = typeof AuthPairingLink.Type;-export const AuthClientMetadataDeviceType = Schema.Literals([- "desktop",- "mobile",- "tablet",- "bot",- "unknown",-]);-export type AuthClientMetadataDeviceType = typeof AuthClientMetadataDeviceType.Type;-export const AuthClientMetadata = Schema.Struct({label: Schema.optionalKey(TrimmedNonEmptyString),ipAddress: Schema.optionalKey(TrimmedNonEmptyString),@@ -169,7 +228,7 @@ export type AuthClientMetadata = typeof AuthClientMetadata.Type;export const AuthClientSession = Schema.Struct({sessionId: AuthSessionId,subject: TrimmedNonEmptyString,- role: AuthSessionRole,+ scopes: AuthEnvironmentScopes,method: ServerAuthSessionMethod,client: AuthClientMetadata,issuedAt: Schema.DateTimeUtc,@@ -214,6 +273,21 @@ export const AuthAccessStreamPairingLinkRemovedEvent = Schema.Struct({export type AuthAccessStreamPairingLinkRemovedEvent =typeof AuthAccessStreamPairingLinkRemovedEvent.Type;+export class AuthAccessStreamError extends Schema.TaggedErrorClass<AuthAccessStreamError>()(+ "AuthAccessStreamError",+ {+ message: Schema.String,+ },+) {}++export class EnvironmentAuthorizationError extends Schema.TaggedErrorClass<EnvironmentAuthorizationError>()(+ "EnvironmentAuthorizationError",+ {+ message: Schema.String,+ requiredScope: AuthEnvironmentScope,+ },+) {}+export const AuthAccessStreamClientUpsertedEvent = Schema.Struct({version: Schema.Literal(1),revision: Schema.Number,@@ -253,13 +327,14 @@ export type AuthRevokeClientSessionInput = typeof AuthRevokeClientSessionInput.Texport const AuthCreatePairingCredentialInput = Schema.Struct({label: Schema.optionalKey(TrimmedNonEmptyString),+ scopes: Schema.optionalKey(AuthEnvironmentScopes),});export type AuthCreatePairingCredentialInput = typeof AuthCreatePairingCredentialInput.Type;export const AuthSessionState = Schema.Struct({authenticated: Schema.Boolean,auth: ServerAuthDescriptor,- role: Schema.optionalKey(AuthSessionRole),+ scopes: Schema.optionalKey(AuthEnvironmentScopes),sessionMethod: Schema.optionalKey(ServerAuthSessionMethod),expiresAt: Schema.optionalKey(Schema.DateTimeUtc),});diff --git a/packages/contracts/src/environmentHttp.ts b/packages/contracts/src/environmentHttp.tsnew file mode 100644index 000000000..93189f62a--- /dev/null+++ b/packages/contracts/src/environmentHttp.ts@@ -0,0 +1,325 @@+import * as Context from "effect/Context";+import type * as DateTime from "effect/DateTime";+import * as Schema from "effect/Schema";+import * as HttpApi from "effect/unstable/httpapi/HttpApi";+import * as HttpApiEndpoint from "effect/unstable/httpapi/HttpApiEndpoint";+import * as HttpApiGroup from "effect/unstable/httpapi/HttpApiGroup";+import * as HttpApiMiddleware from "effect/unstable/httpapi/HttpApiMiddleware";+import * as HttpServerRespondable from "effect/unstable/http/HttpServerRespondable";+import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";++import {+ AuthAccessTokenResult,+ AuthBrowserSessionRequest,+ AuthBrowserSessionResult,+ AuthClientSession,+ AuthCreatePairingCredentialInput,+ AuthPairingCredentialResult,+ AuthPairingLink,+ AuthRevokeClientSessionInput,+ AuthRevokePairingLinkInput,+ AuthEnvironmentScope,+ AuthTokenExchangeRequest,+ AuthSessionState,+ AuthWebSocketTicketResult,+ ServerAuthSessionMethod,+} from "./auth.ts";+import { AuthSessionId, TrimmedNonEmptyString } from "./baseSchemas.ts";+import { ExecutionEnvironmentDescriptor } from "./environment.ts";+import {+ ClientOrchestrationCommand,+ DispatchResult,+ OrchestrationReadModel,+} from "./orchestration.ts";++const OptionalBearerHeaders = Schema.Struct({+ authorization: Schema.optionalKey(Schema.String),+});++export const EnvironmentRequestInvalidReason = Schema.Literals([+ "invalid_scope",+ "scope_not_granted",+ "invalid_command",+]);+export type EnvironmentRequestInvalidReason = typeof EnvironmentRequestInvalidReason.Type;++export const EnvironmentAuthInvalidReason = Schema.Literals([+ "missing_credential",+ "invalid_credential",+]);+export type EnvironmentAuthInvalidReason = typeof EnvironmentAuthInvalidReason.Type;++export const EnvironmentOperationForbiddenReason = Schema.Literals([+ "current_session_revoke_not_allowed",+]);+export type EnvironmentOperationForbiddenReason = typeof EnvironmentOperationForbiddenReason.Type;++export const EnvironmentInternalErrorReason = Schema.Literals([+ "bootstrap_validation_failed",+ "browser_session_issuance_failed",+ "browser_session_cookie_failed",+ "access_token_issuance_failed",+ "websocket_ticket_issuance_failed",+ "pairing_credential_issuance_failed",+ "pairing_links_load_failed",+ "pairing_link_revoke_failed",+ "client_sessions_load_failed",+ "client_session_revoke_failed",+ "orchestration_snapshot_failed",+ "orchestration_dispatch_failed",+ "internal_error",+]);+export type EnvironmentInternalErrorReason = typeof EnvironmentInternalErrorReason.Type;++export class EnvironmentRequestInvalidError extends Schema.TaggedErrorClass<EnvironmentRequestInvalidError>()(+ "EnvironmentRequestInvalidError",+ {+ code: Schema.Literal("invalid_request"),+ reason: EnvironmentRequestInvalidReason,+ traceId: TrimmedNonEmptyString,+ },+ { httpApiStatus: 400 },+) {+ [HttpServerRespondable.symbol]() {+ return HttpServerResponse.schemaJson(EnvironmentRequestInvalidError)(this, { status: 400 });+ }+}++export class EnvironmentAuthInvalidError extends Schema.TaggedErrorClass<EnvironmentAuthInvalidError>()(+ "EnvironmentAuthInvalidError",+ {+ code: Schema.Literal("auth_invalid"),+ reason: EnvironmentAuthInvalidReason,+ traceId: TrimmedNonEmptyString,+ },+ { httpApiStatus: 401 },+) {+ [HttpServerRespondable.symbol]() {+ return HttpServerResponse.schemaJson(EnvironmentAuthInvalidError)(this, { status: 401 });+ }+}++export class EnvironmentScopeRequiredError extends Schema.TaggedErrorClass<EnvironmentScopeRequiredError>()(+ "EnvironmentScopeRequiredError",+ {+ code: Schema.Literal("insufficient_scope"),+ requiredScope: AuthEnvironmentScope,+ traceId: TrimmedNonEmptyString,+ },+ { httpApiStatus: 403 },+) {+ [HttpServerRespondable.symbol]() {+ return HttpServerResponse.schemaJson(EnvironmentScopeRequiredError)(this, { status: 403 });+ }+}++export class EnvironmentOperationForbiddenError extends Schema.TaggedErrorClass<EnvironmentOperationForbiddenError>()(+ "EnvironmentOperationForbiddenError",+ {+ code: Schema.Literal("operation_forbidden"),+ reason: EnvironmentOperationForbiddenReason,+ traceId: TrimmedNonEmptyString,+ },+ { httpApiStatus: 403 },+) {+ [HttpServerRespondable.symbol]() {+ return HttpServerResponse.schemaJson(EnvironmentOperationForbiddenError)(this, { status: 403 });+ }+}++export class EnvironmentInternalError extends Schema.TaggedErrorClass<EnvironmentInternalError>()(+ "EnvironmentInternalError",+ {+ code: Schema.Literal("internal_error"),+ reason: EnvironmentInternalErrorReason,+ traceId: TrimmedNonEmptyString,+ },+ { httpApiStatus: 500 },+) {+ [HttpServerRespondable.symbol]() {+ return HttpServerResponse.schemaJson(EnvironmentInternalError)(this, { status: 500 });+ }+}++export const EnvironmentHttpCommonError = Schema.Union([+ EnvironmentRequestInvalidError,+ EnvironmentAuthInvalidError,+ EnvironmentScopeRequiredError,+ EnvironmentOperationForbiddenError,+ EnvironmentInternalError,+]);+export type EnvironmentHttpCommonError = typeof EnvironmentHttpCommonError.Type;++const EnvironmentAuthenticationErrors = [+ EnvironmentAuthInvalidError,+ EnvironmentInternalError,+] as const;+const EnvironmentSessionCreationErrors = [+ EnvironmentAuthInvalidError,+ EnvironmentInternalError,+] as const;+const EnvironmentTokenExchangeErrors = [+ EnvironmentRequestInvalidError,+ EnvironmentAuthInvalidError,+ EnvironmentInternalError,+] as const;+const EnvironmentScopedOperationErrors = [+ EnvironmentScopeRequiredError,+ EnvironmentInternalError,+] as const;+const EnvironmentPairingCredentialErrors = [+ EnvironmentRequestInvalidError,+ ...EnvironmentScopedOperationErrors,+] as const;+const EnvironmentSessionRevokeErrors = [+ EnvironmentScopeRequiredError,+ EnvironmentOperationForbiddenError,+ EnvironmentInternalError,+] as const;+const EnvironmentOrchestrationSnapshotErrors = [+ EnvironmentScopeRequiredError,+ EnvironmentInternalError,+] as const;+const EnvironmentOrchestrationDispatchErrors = [+ EnvironmentRequestInvalidError,+ EnvironmentScopeRequiredError,+ EnvironmentInternalError,+] as const;++export interface EnvironmentSessionPrincipalShape {+ readonly sessionId: AuthSessionId;+ readonly subject: string;+ readonly method: ServerAuthSessionMethod;+ readonly scopes: ReadonlySet<AuthEnvironmentScope>;+ readonly expiresAt?: DateTime.DateTime;+}++export class EnvironmentAuthenticatedPrincipal extends Context.Service<+ EnvironmentAuthenticatedPrincipal,+ EnvironmentSessionPrincipalShape+>()("@t3tools/contracts/environmentHttp/EnvironmentAuthenticatedPrincipal") {}++export class EnvironmentAuthenticatedAuth extends HttpApiMiddleware.Service<+ EnvironmentAuthenticatedAuth,+ { provides: EnvironmentAuthenticatedPrincipal }+>()("EnvironmentAuthenticatedAuth", {+ error: EnvironmentAuthenticationErrors,+}) {}++export const AuthPairingLinkRevokeResult = Schema.Struct({+ revoked: Schema.Boolean,+});+export type AuthPairingLinkRevokeResult = typeof AuthPairingLinkRevokeResult.Type;++export const AuthClientSessionRevokeResult = Schema.Struct({+ revoked: Schema.Boolean,+});+export type AuthClientSessionRevokeResult = typeof AuthClientSessionRevokeResult.Type;++export const AuthOtherClientSessionsRevokeResult = Schema.Struct({+ revokedCount: Schema.Number,+});+export type AuthOtherClientSessionsRevokeResult = typeof AuthOtherClientSessionsRevokeResult.Type;++export class EnvironmentMetadataHttpApi extends HttpApiGroup.make("metadata").add(+ HttpApiEndpoint.get("descriptor", "/.well-known/t3/environment", {+ success: ExecutionEnvironmentDescriptor,+ }),+) {}++export class EnvironmentAuthHttpApi extends HttpApiGroup.make("auth")+ .add(+ HttpApiEndpoint.get("session", "/api/auth/session", {+ headers: OptionalBearerHeaders,+ success: AuthSessionState,+ error: [EnvironmentInternalError],+ }),+ )+ .add(+ HttpApiEndpoint.post("browserSession", "/api/auth/browser-session", {+ payload: AuthBrowserSessionRequest,+ success: AuthBrowserSessionResult,+ error: EnvironmentSessionCreationErrors,+ }),+ )+ .add(+ HttpApiEndpoint.post("token", "/oauth/token", {+ payload: AuthTokenExchangeRequest,+ success: AuthAccessTokenResult,+ error: EnvironmentTokenExchangeErrors,+ }),+ )+ .add(+ HttpApiEndpoint.post("webSocketTicket", "/api/auth/websocket-ticket", {+ headers: OptionalBearerHeaders,+ success: AuthWebSocketTicketResult,+ error: [EnvironmentInternalError],+ }).middleware(EnvironmentAuthenticatedAuth),+ )+ .add(+ HttpApiEndpoint.post("pairingCredential", "/api/auth/pairing-token", {+ headers: OptionalBearerHeaders,+ payload: AuthCreatePairingCredentialInput,+ success: AuthPairingCredentialResult,+ error: EnvironmentPairingCredentialErrors,+ }).middleware(EnvironmentAuthenticatedAuth),+ )+ .add(+ HttpApiEndpoint.get("pairingLinks", "/api/auth/pairing-links", {+ headers: OptionalBearerHeaders,+ success: Schema.Array(AuthPairingLink),+ error: EnvironmentScopedOperationErrors,+ }).middleware(EnvironmentAuthenticatedAuth),+ )+ .add(+ HttpApiEndpoint.post("revokePairingLink", "/api/auth/pairing-links/revoke", {+ headers: OptionalBearerHeaders,+ payload: AuthRevokePairingLinkInput,+ success: AuthPairingLinkRevokeResult,+ error: EnvironmentScopedOperationErrors,+ }).middleware(EnvironmentAuthenticatedAuth),+ )+ .add(+ HttpApiEndpoint.get("clients", "/api/auth/clients", {+ headers: OptionalBearerHeaders,+ success: Schema.Array(AuthClientSession),+ error: EnvironmentScopedOperationErrors,+ }).middleware(EnvironmentAuthenticatedAuth),+ )+ .add(+ HttpApiEndpoint.post("revokeClient", "/api/auth/clients/revoke", {+ headers: OptionalBearerHeaders,+ payload: AuthRevokeClientSessionInput,+ success: AuthClientSessionRevokeResult,+ error: EnvironmentSessionRevokeErrors,+ }).middleware(EnvironmentAuthenticatedAuth),+ )+ .add(+ HttpApiEndpoint.post("revokeOtherClients", "/api/auth/clients/revoke-others", {+ headers: OptionalBearerHeaders,+ success: AuthOtherClientSessionsRevokeResult,+ error: EnvironmentScopedOperationErrors,+ }).middleware(EnvironmentAuthenticatedAuth),+ ) {}++export class EnvironmentOrchestrationHttpApi extends HttpApiGroup.make("orchestration")+ .add(+ HttpApiEndpoint.get("snapshot", "/api/orchestration/snapshot", {+ headers: OptionalBearerHeaders,+ success: OrchestrationReadModel,+ error: EnvironmentOrchestrationSnapshotErrors,+ }).middleware(EnvironmentAuthenticatedAuth),+ )+ .add(+ HttpApiEndpoint.post("dispatch", "/api/orchestration/dispatch", {+ headers: OptionalBearerHeaders,+ payload: ClientOrchestrationCommand,+ success: DispatchResult,+ error: EnvironmentOrchestrationDispatchErrors,+ }).middleware(EnvironmentAuthenticatedAuth),+ ) {}++export class EnvironmentHttpApi extends HttpApi.make("environment")+ .add(EnvironmentMetadataHttpApi)+ .add(EnvironmentAuthHttpApi)+ .add(EnvironmentOrchestrationHttpApi) {}diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.tsindex 50d533b62..bf26014c4 100644--- a/packages/contracts/src/index.ts+++ b/packages/contracts/src/index.ts@@ -1,6 +1,7 @@export * from "./baseSchemas.ts";export * from "./auth.ts";export * from "./environment.ts";+export * from "./environmentHttp.ts";export * from "./desktopBootstrap.ts";export * from "./remoteAccess.ts";export * from "./ipc.ts";diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.tsindex d643ccd2d..684974fca 100644--- a/packages/contracts/src/ipc.ts+++ b/packages/contracts/src/ipc.ts@@ -66,7 +66,7 @@ import type {OrchestrationThreadStreamItem,} from "./orchestration.ts";import { EnvironmentId } from "./baseSchemas.ts";-import { AuthBearerBootstrapResult, AuthSessionState, AuthWebSocketTokenResult } from "./auth.ts";+import { AuthAccessTokenResult, AuthSessionState, AuthWebSocketTicketResult } from "./auth.ts";import { AdvertisedEndpoint } from "./remoteAccess.ts";import { EditorId } from "./editor.ts";import { ExecutionEnvironmentDescriptor } from "./environment.ts";@@ -394,12 +394,12 @@ export interface DesktopBridge {bootstrapSshBearerSession: (httpBaseUrl: string,credential: string,- ) => Promise<AuthBearerBootstrapResult>;+ ) => Promise<AuthAccessTokenResult>;fetchSshSessionState: (httpBaseUrl: string, bearerToken: string) => Promise<AuthSessionState>;- issueSshWebSocketToken: (+ issueSshWebSocketTicket: (httpBaseUrl: string,bearerToken: string,- ) => Promise<AuthWebSocketTokenResult>;+ ) => Promise<AuthWebSocketTicketResult>;onSshPasswordPrompt: (listener: (request: DesktopSshPasswordPromptRequest) => void) => () => void;resolveSshPasswordPrompt: (requestId: string, password: string | null) => Promise<void>;getServerExposureState: () => Promise<DesktopServerExposureState>;diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.tsindex 41f6a696d..814e403b6 100644--- a/packages/contracts/src/rpc.ts+++ b/packages/contracts/src/rpc.ts@@ -3,7 +3,11 @@ import * as Rpc from "effect/unstable/rpc/Rpc";import * as RpcGroup from "effect/unstable/rpc/RpcGroup";import { ExternalLauncherError, LaunchEditorInput } from "./editor.ts";-import { AuthAccessStreamEvent } from "./auth.ts";+import {+ AuthAccessStreamError,+ AuthAccessStreamEvent,+ EnvironmentAuthorizationError,+} from "./auth.ts";import {FilesystemBrowseInput,FilesystemBrowseResult,@@ -179,19 +183,19 @@ export const WS_METHODS = {export const WsServerUpsertKeybindingRpc = Rpc.make(WS_METHODS.serverUpsertKeybinding, {payload: ServerUpsertKeybindingInput,success: ServerUpsertKeybindingResult,- error: KeybindingsConfigError,+ error: Schema.Union([KeybindingsConfigError, EnvironmentAuthorizationError]),});export const WsServerRemoveKeybindingRpc = Rpc.make(WS_METHODS.serverRemoveKeybinding, {payload: ServerRemoveKeybindingInput,success: ServerRemoveKeybindingResult,- error: KeybindingsConfigError,+ error: Schema.Union([KeybindingsConfigError, EnvironmentAuthorizationError]),});export const WsServerGetConfigRpc = Rpc.make(WS_METHODS.serverGetConfig, {payload: Schema.Struct({}),success: ServerConfig,- error: Schema.Union([KeybindingsConfigError, ServerSettingsError]),+ error: Schema.Union([KeybindingsConfigError, ServerSettingsError, EnvironmentAuthorizationError]),});export const WsServerRefreshProvidersRpc = Rpc.make(WS_METHODS.serverRefreshProviders, {@@ -205,39 +209,43 @@ export const WsServerRefreshProvidersRpc = Rpc.make(WS_METHODS.serverRefreshProvinstanceId: Schema.optional(ProviderInstanceId),}),success: ServerProviderUpdatedPayload,+ error: EnvironmentAuthorizationError,});export const WsServerUpdateProviderRpc = Rpc.make(WS_METHODS.serverUpdateProvider, {payload: ServerProviderUpdateInput,success: ServerProviderUpdatedPayload,- error: ServerProviderUpdateError,+ error: Schema.Union([ServerProviderUpdateError, EnvironmentAuthorizationError]),});export const WsServerGetSettingsRpc = Rpc.make(WS_METHODS.serverGetSettings, {payload: Schema.Struct({}),success: ServerSettings,- error: ServerSettingsError,+ error: Schema.Union([ServerSettingsError, EnvironmentAuthorizationError]),});export const WsServerUpdateSettingsRpc = Rpc.make(WS_METHODS.serverUpdateSettings, {payload: Schema.Struct({ patch: ServerSettingsPatch }),success: ServerSettings,- error: ServerSettingsError,+ error: Schema.Union([ServerSettingsError, EnvironmentAuthorizationError]),});export const WsServerDiscoverSourceControlRpc = Rpc.make(WS_METHODS.serverDiscoverSourceControl, {payload: Schema.Struct({}),success: SourceControlDiscoveryResult,+ error: EnvironmentAuthorizationError,});export const WsServerGetTraceDiagnosticsRpc = Rpc.make(WS_METHODS.serverGetTraceDiagnostics, {payload: Schema.Struct({}),success: ServerTraceDiagnosticsResult,+ error: EnvironmentAuthorizationError,});export const WsServerGetProcessDiagnosticsRpc = Rpc.make(WS_METHODS.serverGetProcessDiagnostics, {payload: Schema.Struct({}),success: ServerProcessDiagnosticsResult,+ error: EnvironmentAuthorizationError,});export const WsServerGetProcessResourceHistoryRpc = Rpc.make(@@ -245,12 +253,14 @@ export const WsServerGetProcessResourceHistoryRpc = Rpc.make({payload: ServerProcessResourceHistoryInput,success: ServerProcessResourceHistoryResult,+ error: EnvironmentAuthorizationError,},);export const WsServerSignalProcessRpc = Rpc.make(WS_METHODS.serverSignalProcess, {payload: ServerSignalProcessInput,success: ServerSignalProcessResult,+ error: EnvironmentAuthorizationError,});export const WsSourceControlLookupRepositoryRpc = Rpc.make(@@ -258,14 +268,14 @@ export const WsSourceControlLookupRepositoryRpc = Rpc.make({payload: SourceControlRepositoryLookupInput,success: SourceControlRepositoryInfo,- error: SourceControlRepositoryError,+ error: Schema.Union([SourceControlRepositoryError, EnvironmentAuthorizationError]),},);export const WsSourceControlCloneRepositoryRpc = Rpc.make(WS_METHODS.sourceControlCloneRepository, {payload: SourceControlCloneRepositoryInput,success: SourceControlCloneRepositoryResult,- error: SourceControlRepositoryError,+ error: Schema.Union([SourceControlRepositoryError, EnvironmentAuthorizationError]),});export const WsSourceControlPublishRepositoryRpc = Rpc.make(@@ -273,103 +283,103 @@ export const WsSourceControlPublishRepositoryRpc = Rpc.make({payload: SourceControlPublishRepositoryInput,success: SourceControlPublishRepositoryResult,- error: SourceControlRepositoryError,+ error: Schema.Union([SourceControlRepositoryError, EnvironmentAuthorizationError]),},);export const WsProjectsSearchEntriesRpc = Rpc.make(WS_METHODS.projectsSearchEntries, {payload: ProjectSearchEntriesInput,success: ProjectSearchEntriesResult,- error: ProjectSearchEntriesError,+ error: Schema.Union([ProjectSearchEntriesError, EnvironmentAuthorizationError]),});export const WsProjectsWriteFileRpc = Rpc.make(WS_METHODS.projectsWriteFile, {payload: ProjectWriteFileInput,success: ProjectWriteFileResult,- error: ProjectWriteFileError,+ error: Schema.Union([ProjectWriteFileError, EnvironmentAuthorizationError]),});export const WsShellOpenInEditorRpc = Rpc.make(WS_METHODS.shellOpenInEditor, {payload: LaunchEditorInput,- error: ExternalLauncherError,+ error: Schema.Union([ExternalLauncherError, EnvironmentAuthorizationError]),});export const WsFilesystemBrowseRpc = Rpc.make(WS_METHODS.filesystemBrowse, {payload: FilesystemBrowseInput,success: FilesystemBrowseResult,- error: FilesystemBrowseError,+ error: Schema.Union([FilesystemBrowseError, EnvironmentAuthorizationError]),});export const WsSubscribeVcsStatusRpc = Rpc.make(WS_METHODS.subscribeVcsStatus, {payload: VcsStatusInput,success: VcsStatusStreamEvent,- error: GitManagerServiceError,+ error: Schema.Union([GitManagerServiceError, EnvironmentAuthorizationError]),stream: true,});export const WsVcsPullRpc = Rpc.make(WS_METHODS.vcsPull, {payload: VcsPullInput,success: VcsPullResult,- error: GitCommandError,+ error: Schema.Union([GitCommandError, EnvironmentAuthorizationError]),});export const WsVcsRefreshStatusRpc = Rpc.make(WS_METHODS.vcsRefreshStatus, {payload: VcsStatusInput,success: VcsStatusResult,- error: GitManagerServiceError,+ error: Schema.Union([GitManagerServiceError, EnvironmentAuthorizationError]),});export const WsGitRunStackedActionRpc = Rpc.make(WS_METHODS.gitRunStackedAction, {payload: GitRunStackedActionInput,success: GitActionProgressEvent,- error: GitManagerServiceError,+ error: Schema.Union([GitManagerServiceError, EnvironmentAuthorizationError]),stream: true,});export const WsGitResolvePullRequestRpc = Rpc.make(WS_METHODS.gitResolvePullRequest, {payload: GitPullRequestRefInput,success: GitResolvePullRequestResult,- error: GitManagerServiceError,+ error: Schema.Union([GitManagerServiceError, EnvironmentAuthorizationError]),});export const WsGitPreparePullRequestThreadRpc = Rpc.make(WS_METHODS.gitPreparePullRequestThread, {payload: GitPreparePullRequestThreadInput,success: GitPreparePullRequestThreadResult,- error: GitManagerServiceError,+ error: Schema.Union([GitManagerServiceError, EnvironmentAuthorizationError]),});export const WsVcsListRefsRpc = Rpc.make(WS_METHODS.vcsListRefs, {payload: VcsListRefsInput,success: VcsListRefsResult,- error: GitCommandError,+ error: Schema.Union([GitCommandError, EnvironmentAuthorizationError]),});export const WsVcsCreateWorktreeRpc = Rpc.make(WS_METHODS.vcsCreateWorktree, {payload: VcsCreateWorktreeInput,success: VcsCreateWorktreeResult,- error: GitCommandError,+ error: Schema.Union([GitCommandError, EnvironmentAuthorizationError]),});export const WsVcsRemoveWorktreeRpc = Rpc.make(WS_METHODS.vcsRemoveWorktree, {payload: VcsRemoveWorktreeInput,- error: GitCommandError,+ error: Schema.Union([GitCommandError, EnvironmentAuthorizationError]),});export const WsVcsCreateRefRpc = Rpc.make(WS_METHODS.vcsCreateRef, {payload: VcsCreateRefInput,success: VcsCreateRefResult,- error: GitCommandError,+ error: Schema.Union([GitCommandError, EnvironmentAuthorizationError]),});export const WsVcsSwitchRefRpc = Rpc.make(WS_METHODS.vcsSwitchRef, {payload: VcsSwitchRefInput,success: VcsSwitchRefResult,- error: GitCommandError,+ error: Schema.Union([GitCommandError, EnvironmentAuthorizationError]),});export const WsVcsInitRpc = Rpc.make(WS_METHODS.vcsInit, {payload: VcsInitInput,- error: VcsError,+ error: Schema.Union([VcsError, EnvironmentAuthorizationError]),});/**@@ -380,46 +390,46 @@ export const WsVcsInitRpc = Rpc.make(WS_METHODS.vcsInit, {export const WsReviewGetDiffPreviewRpc = Rpc.make(WS_METHODS.reviewGetDiffPreview, {payload: ReviewDiffPreviewInput,success: ReviewDiffPreviewResult,- error: ReviewDiffPreviewError,+ error: Schema.Union([ReviewDiffPreviewError, EnvironmentAuthorizationError]),});export const WsTerminalOpenRpc = Rpc.make(WS_METHODS.terminalOpen, {payload: TerminalOpenInput,success: TerminalSessionSnapshot,- error: TerminalError,+ error: Schema.Union([TerminalError, EnvironmentAuthorizationError]),});export const WsTerminalAttachRpc = Rpc.make(WS_METHODS.terminalAttach, {payload: TerminalAttachInput,success: TerminalAttachStreamEvent,- error: TerminalError,+ error: Schema.Union([TerminalError, EnvironmentAuthorizationError]),stream: true,});export const WsTerminalWriteRpc = Rpc.make(WS_METHODS.terminalWrite, {payload: TerminalWriteInput,- error: TerminalError,+ error: Schema.Union([TerminalError, EnvironmentAuthorizationError]),});export const WsTerminalResizeRpc = Rpc.make(WS_METHODS.terminalResize, {payload: TerminalResizeInput,- error: TerminalError,+ error: Schema.Union([TerminalError, EnvironmentAuthorizationError]),});export const WsTerminalClearRpc = Rpc.make(WS_METHODS.terminalClear, {payload: TerminalClearInput,- error: TerminalError,+ error: Schema.Union([TerminalError, EnvironmentAuthorizationError]),});export const WsTerminalRestartRpc = Rpc.make(WS_METHODS.terminalRestart, {payload: TerminalRestartInput,success: TerminalSessionSnapshot,- error: TerminalError,+ error: Schema.Union([TerminalError, EnvironmentAuthorizationError]),});export const WsTerminalCloseRpc = Rpc.make(WS_METHODS.terminalClose, {payload: TerminalCloseInput,- error: TerminalError,+ error: Schema.Union([TerminalError, EnvironmentAuthorizationError]),});export const WsOrchestrationDispatchCommandRpc = Rpc.make(@@ -427,14 +437,14 @@ export const WsOrchestrationDispatchCommandRpc = Rpc.make({payload: ClientOrchestrationCommand,success: OrchestrationRpcSchemas.dispatchCommand.output,- error: OrchestrationDispatchCommandError,+ error: Schema.Union([OrchestrationDispatchCommandError, EnvironmentAuthorizationError]),},);export const WsOrchestrationGetTurnDiffRpc = Rpc.make(ORCHESTRATION_WS_METHODS.getTurnDiff, {payload: OrchestrationGetTurnDiffInput,success: OrchestrationRpcSchemas.getTurnDiff.output,- error: OrchestrationGetTurnDiffError,+ error: Schema.Union([OrchestrationGetTurnDiffError, EnvironmentAuthorizationError]),});export const WsOrchestrationGetFullThreadDiffRpc = Rpc.make(@@ -442,14 +452,14 @@ export const WsOrchestrationGetFullThreadDiffRpc = Rpc.make({payload: OrchestrationGetFullThreadDiffInput,success: OrchestrationRpcSchemas.getFullThreadDiff.output,- error: OrchestrationGetFullThreadDiffError,+ error: Schema.Union([OrchestrationGetFullThreadDiffError, EnvironmentAuthorizationError]),},);export const WsOrchestrationReplayEventsRpc = Rpc.make(ORCHESTRATION_WS_METHODS.replayEvents, {payload: OrchestrationReplayEventsInput,success: OrchestrationRpcSchemas.replayEvents.output,- error: OrchestrationReplayEventsError,+ error: Schema.Union([OrchestrationReplayEventsError, EnvironmentAuthorizationError]),});export const WsOrchestrationGetArchivedShellSnapshotRpc = Rpc.make(@@ -457,14 +467,14 @@ export const WsOrchestrationGetArchivedShellSnapshotRpc = Rpc.make({payload: OrchestrationRpcSchemas.getArchivedShellSnapshot.input,success: OrchestrationRpcSchemas.getArchivedShellSnapshot.output,- error: OrchestrationGetSnapshotError,+ error: Schema.Union([OrchestrationGetSnapshotError, EnvironmentAuthorizationError]),},);export const WsOrchestrationSubscribeShellRpc = Rpc.make(ORCHESTRATION_WS_METHODS.subscribeShell, {payload: OrchestrationRpcSchemas.subscribeShell.input,success: OrchestrationRpcSchemas.subscribeShell.output,- error: OrchestrationGetSnapshotError,+ error: Schema.Union([OrchestrationGetSnapshotError, EnvironmentAuthorizationError]),stream: true,});@@ -473,7 +483,7 @@ export const WsOrchestrationSubscribeThreadRpc = Rpc.make({payload: OrchestrationRpcSchemas.subscribeThread.input,success: OrchestrationRpcSchemas.subscribeThread.output,- error: OrchestrationGetSnapshotError,+ error: Schema.Union([OrchestrationGetSnapshotError, EnvironmentAuthorizationError]),stream: true,},);@@ -481,31 +491,35 @@ export const WsOrchestrationSubscribeThreadRpc = Rpc.make(export const WsSubscribeTerminalEventsRpc = Rpc.make(WS_METHODS.subscribeTerminalEvents, {payload: Schema.Struct({}),success: TerminalEvent,+ error: EnvironmentAuthorizationError,stream: true,});export const WsSubscribeTerminalMetadataRpc = Rpc.make(WS_METHODS.subscribeTerminalMetadata, {payload: Schema.Struct({}),success: TerminalMetadataStreamEvent,+ error: EnvironmentAuthorizationError,stream: true,});export const WsSubscribeServerConfigRpc = Rpc.make(WS_METHODS.subscribeServerConfig, {payload: Schema.Struct({}),success: ServerConfigStreamEvent,- error: Schema.Union([KeybindingsConfigError, ServerSettingsError]),+ error: Schema.Union([KeybindingsConfigError, ServerSettingsError, EnvironmentAuthorizationError]),stream: true,});export const WsSubscribeServerLifecycleRpc = Rpc.make(WS_METHODS.subscribeServerLifecycle, {payload: Schema.Struct({}),success: ServerLifecycleStreamEvent,+ error: EnvironmentAuthorizationError,stream: true,});export const WsSubscribeAuthAccessRpc = Rpc.make(WS_METHODS.subscribeAuthAccess, {payload: Schema.Struct({}),success: AuthAccessStreamEvent,+ error: Schema.Union([AuthAccessStreamError, EnvironmentAuthorizationError]),stream: true,});diff --git a/packages/shared/package.json b/packages/shared/package.jsonindex 9a38b19bb..622523db7 100644--- a/packages/shared/package.json+++ b/packages/shared/package.json@@ -79,6 +79,10 @@"types": "./src/remote.ts","import": "./src/remote.ts"},+ "./oauthScope": {+ "types": "./src/oauthScope.ts",+ "import": "./src/oauthScope.ts"+ },"./searchRanking": {"types": "./src/searchRanking.ts","import": "./src/searchRanking.ts"diff --git a/packages/shared/src/oauthScope.test.ts b/packages/shared/src/oauthScope.test.tsnew file mode 100644index 000000000..7b0033d98--- /dev/null+++ b/packages/shared/src/oauthScope.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from "vitest";++import { encodeOAuthScope, parseAllowedOAuthScope, parseOAuthScope } from "./oauthScope.ts";++describe("OAuth scopes", () => {+ it("parses an RFC 6749 space-delimited scope set without duplicating permissions", () => {+ expect(parseOAuthScope("orchestration:read access:write orchestration:read")).toEqual([+ "orchestration:read",+ "access:write",+ ]);+ });++ it("rejects whitespace that is not the SP delimiter or introduces empty tokens", () => {+ expect(parseOAuthScope("orchestration:read\taccess:write")).toBeNull();+ expect(parseOAuthScope("orchestration:read access:write")).toBeNull();+ });++ it("encodes and restricts requested scopes to the allowed capability set", () => {+ expect(encodeOAuthScope(["orchestration:read", "access:write"])).toBe(+ "orchestration:read access:write",+ );+ expect(+ parseAllowedOAuthScope({+ value: "orchestration:read access:write",+ allowedScopes: new Set(["orchestration:read", "access:write"] as const),+ }),+ ).toEqual(["orchestration:read", "access:write"]);+ expect(+ parseAllowedOAuthScope({+ value: "orchestration:read relay:write",+ allowedScopes: new Set(["orchestration:read", "access:write"] as const),+ }),+ ).toBeNull();+ });+});diff --git a/packages/shared/src/oauthScope.ts b/packages/shared/src/oauthScope.tsnew file mode 100644index 000000000..7016e4928--- /dev/null+++ b/packages/shared/src/oauthScope.ts@@ -0,0 +1,40 @@+const OAUTH_SCOPE_TOKEN = /^[\u0021\u0023-\u005b\u005d-\u007e]+$/u;++/**+ * Decodes an RFC 6749 `scope` value as a set while preserving first-seen order.+ */+export function parseOAuthScope(value: string): ReadonlyArray<string> | null {+ if (value.length === 0) {+ return null;+ }++ const scopes = value.split(" ");+ if (scopes.some((scope) => !OAUTH_SCOPE_TOKEN.test(scope))) {+ return null;+ }++ return [...new Set(scopes)];+}++export function encodeOAuthScope(scopes: ReadonlyArray<string>): string {+ const encoded = scopes.join(" ");+ const parsed = parseOAuthScope(encoded);+ if (parsed === null || parsed.length !== scopes.length) {+ throw new Error("OAuth scopes must be non-empty, valid, and unique.");+ }+ return encoded;+}++export function parseAllowedOAuthScope<Scope extends string>(input: {+ readonly value: string;+ readonly allowedScopes: ReadonlySet<Scope>;+}): ReadonlyArray<Scope> | null {+ const scopes = parseOAuthScope(input.value);+ if (+ scopes === null ||+ !scopes.every((scope): scope is Scope => input.allowedScopes.has(scope as Scope))+ ) {+ return null;+ }+ return scopes;+}diff --git a/packages/shared/src/observability.test.ts b/packages/shared/src/observability.test.tsindex 2943bf46a..57537b63e 100644--- a/packages/shared/src/observability.test.ts+++ b/packages/shared/src/observability.test.ts@@ -1,6 +1,7 @@import { assert, describe, it } from "@effect/vitest";import * as NodeServices from "@effect/platform-node/NodeServices";import * as Arr from "effect/Array";+import * as Cause from "effect/Cause";import * as Effect from "effect/Effect";import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";@@ -12,12 +13,27 @@ import * as Schema from "effect/Schema";import * as Tracer from "effect/Tracer";import {+ causeErrorTag,compactTraceAttributes,makeLocalFileTracer,makeTraceSink,type TraceRecord,} from "./observability.ts";+describe("causeErrorTag", () => {+ it("reports the tagged failure value instead of the Cause reason wrapper", () => {+ assert.equal(+ causeErrorTag(Cause.fail({ _tag: "ServerAuthInvalidCredentialError" })),+ "ServerAuthInvalidCredentialError",+ );+ });++ it("reports structural cause kinds when no typed failure exists", () => {+ assert.equal(causeErrorTag(Cause.die(new Error("unexpected"))), "Die");+ assert.equal(causeErrorTag(Cause.interrupt()), "Interrupt");+ });+});+const TraceRecordLine = Schema.Struct({name: Schema.String,spanId: Schema.String,diff --git a/packages/shared/src/observability.ts b/packages/shared/src/observability.tsindex 1fd75cf4a..68d4985db 100644--- a/packages/shared/src/observability.ts+++ b/packages/shared/src/observability.ts@@ -73,6 +73,22 @@ export interface OtlpTraceRecord extends BaseTraceRecord {export type TraceRecord = EffectTraceRecord | OtlpTraceRecord;+function taggedErrorName(error: unknown): string {+ return typeof error === "object" && error !== null && "_tag" in error+ ? String(error._tag)+ : error instanceof Error+ ? error.name+ : typeof error;+}++export function causeErrorTag(cause: Cause.Cause<unknown>): string {+ const failure = Cause.findErrorOption(cause);+ if (Option.isSome(failure)) {+ return taggedErrorName(failure.value);+ }+ return cause.reasons[0]?._tag ?? "Empty";+}+export interface TraceSinkOptions {readonly filePath: string;readonly maxBytes: number;diff --git a/packages/ssh/src/tunnel.test.ts b/packages/ssh/src/tunnel.test.tsindex 80e684d86..0c223c796 100644--- a/packages/ssh/src/tunnel.test.ts+++ b/packages/ssh/src/tunnel.test.ts@@ -293,7 +293,7 @@ describe("ssh tunnel scripts", () => {makeSuccessfulProcess(`{"id": "88941235-6ed5-4184-a2ff-5339e2075958","credential": "LCL4R2TPHDKQ",- "role": "client",+ "scopes": ["orchestration:read"],"expiresAt": "2026-04-29T01:01:20.994Z"}@@ -321,7 +321,7 @@ describe("ssh tunnel scripts", () => {{"id": "88941235-6ed5-4184-a2ff-5339e2075958","credential": "LCL4R2TPHDKQ",- "role": "client",+ "scopes": ["orchestration:read"],"expiresAt": "2026-04-29T01:01:20.994Z"}diff --git a/packages/ssh/src/tunnel.ts b/packages/ssh/src/tunnel.tsindex 0de48b572..88a30960e 100644--- a/packages/ssh/src/tunnel.ts+++ b/packages/ssh/src/tunnel.ts@@ -160,13 +160,8 @@ const RemotePairingResult = Schema.Struct({credential: Schema.String,});-const RemoteHttpError = Schema.Struct({- error: Schema.optional(Schema.String),-});-const decodeRemoteLaunchResult = Schema.decodeEffect(fromLenientJson(RemoteLaunchResult));const decodeRemotePairingResult = Schema.decodeEffect(fromLenientJson(RemotePairingResult));-const decodeRemoteHttpError = Schema.decodeEffect(Schema.fromJsonString(RemoteHttpError));const decodeRemoteJsonOutput = <A, E>(stdout: string,@@ -991,92 +986,27 @@ function isLoopbackHostname(hostname: string): boolean {return normalized === "127.0.0.1" || normalized === "::1" || normalized === "localhost";}-function resolveLoopbackSshHttpUrl(- rawHttpBaseUrl: unknown,- pathname: string,-): Effect.Effect<URL, SshHttpBridgeError> {- return Effect.try({- try: () => {- if (typeof rawHttpBaseUrl !== "string" || rawHttpBaseUrl.trim().length === 0) {- throw new Error("Invalid SSH forwarded http base URL.");- }- const baseUrl = new URL(rawHttpBaseUrl);- if (!isLoopbackHostname(baseUrl.hostname)) {- throw new Error("SSH desktop bridge only supports loopback forwarded URLs.");- }- const url = new URL(baseUrl.toString());- url.pathname = pathname;- url.search = "";- url.hash = "";- return url;- },- catch: (cause) =>- new SshHttpBridgeError({- message: cause instanceof Error ? cause.message : "Invalid SSH forwarded http base URL.",- cause,- }),- });-}--export const fetchLoopbackSshJson = Effect.fn("ssh/tunnel.fetchLoopbackSshJson")(function* <- T,->(input: {- readonly httpBaseUrl: unknown;- readonly pathname: string;- readonly method?: "GET" | "POST";- readonly bearerToken?: unknown;- readonly body?: unknown;-}): Effect.fn.Return<T, SshHttpBridgeError, HttpClient.HttpClient> {- const requestUrl = yield* resolveLoopbackSshHttpUrl(input.httpBaseUrl, input.pathname);- const bearerToken =- typeof input.bearerToken === "string" && input.bearerToken.trim().length > 0- ? input.bearerToken- : null;-- const request = (- input.method === "POST"- ? HttpClientRequest.post(requestUrl.toString())- : HttpClientRequest.get(requestUrl.toString())- ).pipe(- input.body === undefined ? (req) => req : HttpClientRequest.bodyJsonUnsafe(input.body),- bearerToken- ? HttpClientRequest.setHeader("authorization", `Bearer ${bearerToken}`)- : (req) => req,- );- const client = yield* HttpClient.HttpClient;- const response = yield* client.execute(request).pipe(- Effect.mapError(- (cause) =>+export const resolveLoopbackSshHttpBaseUrl = Effect.fn("ssh/tunnel.resolveLoopbackSshHttpBaseUrl")(+ function* (rawHttpBaseUrl: unknown): Effect.fn.Return<string, SshHttpBridgeError> {+ return yield* Effect.try({+ try: () => {+ if (typeof rawHttpBaseUrl !== "string" || rawHttpBaseUrl.trim().length === 0) {+ throw new Error("Invalid SSH forwarded http base URL.");+ }+ const baseUrl = new URL(rawHttpBaseUrl);+ if (!isLoopbackHostname(baseUrl.hostname)) {+ throw new Error("SSH desktop bridge only supports loopback forwarded URLs.");+ }+ return baseUrl.toString();+ },+ catch: (cause) =>new SshHttpBridgeError({- message: `Failed to reach SSH forwarded endpoint ${requestUrl.toString()}.`,+ message: cause instanceof Error ? cause.message : "Invalid SSH forwarded http base URL.",cause,}),- ),- );- if (response.status < 200 || response.status >= 300) {- const text = yield* response.text.pipe(Effect.catch(() => Effect.succeed("")));- const parsedError = yield* decodeRemoteHttpError(text).pipe(- Effect.catch(() => Effect.succeed(null)),- );- const message =- parsedError?.error && parsedError.error.trim().length > 0- ? parsedError.error- : text || `SSH forwarded request failed (${response.status}).`;- return yield* new SshHttpBridgeError({- status: response.status,- message: `[ssh_http:${response.status}] ${message} (${input.method ?? "GET"} ${requestUrl.toString()})`,});- }- return (yield* response.json.pipe(- Effect.mapError(- (cause) =>- new SshHttpBridgeError({- message: `SSH forwarded endpoint ${requestUrl.toString()} returned invalid JSON.`,- cause,- }),- ),- )) as T;-});+ },+);const reserveLocalTunnelPort = Effect.fn("ssh/tunnel.reserveLocalTunnelPort")(function* () {const net = yield* NetService.NetService;