From a1514d7c830c9621750de474c9cccdf70a657649 Mon Sep 17 00:00:00 2001 From: Makisuo Date: Mon, 16 Nov 2026 15:17:01 +0100 Subject: [PATCH 1/6] feat: MCP server so a user's agent can read and answer messages for them Hazel is now an OAuth 2.1 authorization server for MCP clients (discovery, dynamic client registration, PKCE S256 codes, rotating refresh tokens) and accepts personal access tokens. POST /mcp exposes tools to list orgs and channels, read, search, list notifications, send, reply in thread, edit, delete and react, all as the user through the existing RPCs and object calls. Messages an agent writes or edits get a message_agent_marks row in the same write, stamped from the verified token (CurrentAgent on the invoke principal). It streams only to viewers in the author's organization, so chat shows "via " there while Connect viewers from other orgs and chat-sync copies see a plain message. Users approve agents on a consent page (/oauth/authorize) and manage grants and tokens in My Settings > Agents. Co-Authored-By: Claude Opus 5.5 --- apps/backend/src/http.ts | 2 + apps/backend/src/routes/agent-access.http.ts | 132 +++ apps/backend/src/routes/agent-oauth.ts | 263 ++++++ apps/backend/src/routes/mcp.http.test.ts | 377 +++++++++ apps/backend/src/routes/mcp.ts | 782 ++++++++++++++++++ apps/backend/src/rpc/handlers/messages.ts | 4 + apps/backend/src/services/agent-access.ts | 391 +++++++++ apps/backend/src/worker/http.ts | 13 +- .../src/worker/objects/agent-marks.test.ts | 285 +++++++ .../src/worker/objects/call-receivers.ts | 15 +- .../src/worker/objects/channel/agent-marks.ts | 55 ++ .../worker/objects/channel/api-messages.ts | 36 + apps/backend/src/worker/objects/org/agent.ts | 112 +++ apps/backend/src/worker/objects/principal.ts | 42 +- .../worker/objects/sources/channel-source.ts | 16 + apps/backend/src/worker/objects/user/agent.ts | 50 ++ apps/web-foldkit/src/chat/message/parts.ts | 18 +- apps/web-foldkit/src/chat/messages.gallery.ts | 1 + apps/web-foldkit/src/core/db/collections.ts | 3 + .../src/page/chat/channel/model.ts | 2 + .../web-foldkit/src/page/chat/channel/page.ts | 1 + .../src/page/chat/channel/subscription.ts | 6 + apps/web-foldkit/src/page/chat/derive.ts | 3 + apps/web-foldkit/src/page/chat/lookup-data.ts | 16 + apps/web-foldkit/src/page/chat/lookups.ts | 6 + apps/web-foldkit/src/page/chat/rows.ts | 2 + .../src/page/my-settings/agents/command.ts | 73 ++ .../src/page/my-settings/agents/index.ts | 12 + .../src/page/my-settings/agents/message.ts | 29 + .../src/page/my-settings/agents/model.ts | 44 + .../src/page/my-settings/agents/update.ts | 110 +++ .../src/page/my-settings/agents/view.ts | 277 +++++++ .../web-foldkit/src/page/my-settings/pages.ts | 2 + .../src/page/oauth-authorize/command.ts | 71 ++ .../src/page/oauth-authorize/index.ts | 12 + .../src/page/oauth-authorize/message.ts | 17 + .../src/page/oauth-authorize/model.ts | 61 ++ .../src/page/oauth-authorize/update.ts | 102 +++ .../src/page/oauth-authorize/view.ts | 162 ++++ apps/web-foldkit/src/page/registry.ts | 2 + apps/web-foldkit/src/route.test.ts | 16 + apps/web-foldkit/src/route.ts | 47 ++ apps/web-foldkit/src/shell/sidebars.ts | 3 + .../directory/0005_agent_access/migration.sql | 44 + packages/db/snapshots/channel.json | 88 +- packages/db/snapshots/directory.json | 305 ++++++- packages/db/src/migrations.generated.ts | 18 + packages/db/src/stores.ts | 5 + packages/db/src/tables/agents.ts | 104 +++ packages/db/src/tables/index.ts | 1 + packages/domain/src/http/agent-access.ts | 181 ++++ packages/domain/src/http/api.ts | 2 + packages/domain/src/http/index.ts | 2 + packages/domain/src/models/index.ts | 1 + .../src/models/message-agent-mark-model.ts | 22 + packages/schema/src/ids.ts | 16 + 56 files changed, 4448 insertions(+), 14 deletions(-) create mode 100644 apps/backend/src/routes/agent-access.http.ts create mode 100644 apps/backend/src/routes/agent-oauth.ts create mode 100644 apps/backend/src/routes/mcp.http.test.ts create mode 100644 apps/backend/src/routes/mcp.ts create mode 100644 apps/backend/src/services/agent-access.ts create mode 100644 apps/backend/src/worker/objects/agent-marks.test.ts create mode 100644 apps/backend/src/worker/objects/channel/agent-marks.ts create mode 100644 apps/backend/src/worker/objects/org/agent.ts create mode 100644 apps/backend/src/worker/objects/user/agent.ts create mode 100644 apps/web-foldkit/src/page/my-settings/agents/command.ts create mode 100644 apps/web-foldkit/src/page/my-settings/agents/index.ts create mode 100644 apps/web-foldkit/src/page/my-settings/agents/message.ts create mode 100644 apps/web-foldkit/src/page/my-settings/agents/model.ts create mode 100644 apps/web-foldkit/src/page/my-settings/agents/update.ts create mode 100644 apps/web-foldkit/src/page/my-settings/agents/view.ts create mode 100644 apps/web-foldkit/src/page/oauth-authorize/command.ts create mode 100644 apps/web-foldkit/src/page/oauth-authorize/index.ts create mode 100644 apps/web-foldkit/src/page/oauth-authorize/message.ts create mode 100644 apps/web-foldkit/src/page/oauth-authorize/model.ts create mode 100644 apps/web-foldkit/src/page/oauth-authorize/update.ts create mode 100644 apps/web-foldkit/src/page/oauth-authorize/view.ts create mode 100644 packages/db/migrations/directory/0005_agent_access/migration.sql create mode 100644 packages/db/src/tables/agents.ts create mode 100644 packages/domain/src/http/agent-access.ts create mode 100644 packages/domain/src/models/message-agent-mark-model.ts diff --git a/apps/backend/src/http.ts b/apps/backend/src/http.ts index 420a8d36e..26eafa9b2 100644 --- a/apps/backend/src/http.ts +++ b/apps/backend/src/http.ts @@ -1,6 +1,7 @@ import { Layer } from "effect" import { HttpApiBuilder } from "effect/http-api" import { HazelApi } from "./api" +import { HttpAgentAccessLive } from "./routes/agent-access.http" import { HttpApiV1BotsLive, HttpApiV1IntegrationsLive, HttpMessagesApiLive } from "./routes/api-v1" import { HttpKlipyLive } from "./routes/klipy.http" import { HttpBotCommandsLive } from "./routes/bot-commands.http" @@ -22,6 +23,7 @@ export const HttpApiRoutes = HttpApiBuilder.layer(HazelApi).pipe( Layer.provide(HttpBotCommandsLive), Layer.provide(HttpIntegrationLive), Layer.provide(HttpT3CodeLive), + Layer.provide(HttpAgentAccessLive), Layer.provide(HttpIntegrationCommandLive), Layer.provide(HttpIntegrationResourceLive), Layer.provide(HttpIncomingWebhookLive), diff --git a/apps/backend/src/routes/agent-access.http.ts b/apps/backend/src/routes/agent-access.http.ts new file mode 100644 index 000000000..edb3bba6a --- /dev/null +++ b/apps/backend/src/routes/agent-access.http.ts @@ -0,0 +1,132 @@ +/** + * Agent access for the signed-in user (`@hazel/domain/http` `AgentAccessGroup`): the OAuth consent + * page's lookups and answer, and the settings page's grants and personal tokens. The OAuth protocol + * endpoints are raw routes (`./agent-oauth.ts`). + */ +import { HttpApiBuilder } from "effect/http-api" +import { CurrentUser, InternalServerError } from "@hazel/domain" +import { + AgentClientInfo, + AgentClientInvalidError, + AgentGrantInfo, + AgentGrantNotFoundError, + AgentGrantsResponse, + AuthorizeAgentResponse, + CreateAgentTokenResponse, + parseAgentScopes, +} from "@hazel/domain/http" +import type { schema } from "@hazel/db" +import { DateTime, Effect, Option } from "effect" +import { HazelApi } from "../api" +import { AgentAccess } from "../services/agent-access" +import { agentOAuthConfig, mcpResourceUrl } from "./agent-oauth" + +const internal = (message: string) => (cause: unknown) => + Effect.logError(message, { cause }).pipe( + Effect.andThen(Effect.fail(new InternalServerError({ message }))), + ) + +const toGrantInfo = (grant: schema.AgentGrant) => + new AgentGrantInfo({ + id: grant.id, + kind: grant.kind, + name: grant.name, + scopes: parseAgentScopes(grant.scopes.join(" ")), + createdAt: DateTime.fromDateUnsafe(grant.createdAt), + lastUsedAt: grant.lastUsedAt === null ? null : DateTime.fromDateUnsafe(grant.lastUsedAt), + }) + +const invalidClient = () => + new AgentClientInvalidError({ message: "This sign-in link is invalid or its app is unknown" }) + +/** Appends `params` to a redirect URI, keeping its own query. */ +const withParams = (uri: string, params: Record) => { + const url = new URL(uri) + for (const [key, value] of Object.entries(params)) + if (value !== undefined) url.searchParams.set(key, value) + return url.toString() +} + +export const HttpAgentAccessLive = HttpApiBuilder.group(HazelApi, "agentAccess", (handlers) => + Effect.gen(function* () { + const access = yield* AgentAccess + const { apiOrigin } = yield* agentOAuthConfig.pipe(Effect.orDie) + + return handlers + .handle("getAgentClient", ({ params, query }) => + Effect.gen(function* () { + const client = yield* access.clientFor(params.clientId, query.redirect_uri) + if (Option.isNone(client)) return yield* invalidClient() + return new AgentClientInfo({ + id: client.value.id, + name: client.value.clientName, + clientUri: client.value.clientUri, + logoUri: client.value.logoUri, + redirectHost: new URL(query.redirect_uri).host || query.redirect_uri, + }) + }).pipe(Effect.catchTag("DatabaseError", internal("Could not load the agent client"))), + ) + .handle("authorizeAgent", ({ payload }) => + Effect.gen(function* () { + const user = yield* CurrentUser.Context + const client = yield* access.clientFor(payload.clientId, payload.redirectUri) + if (Option.isNone(client)) return yield* invalidClient() + // From here the client's redirect URI is trusted: errors go back to it (RFC 6749 §4.1.2.1). + const back = (params: Record) => + new AuthorizeAgentResponse({ + redirectTo: withParams(payload.redirectUri, { + ...params, + state: payload.state, + iss: apiOrigin, + }), + }) + if (!payload.approve) return back({ error: "access_denied" }) + if (payload.codeChallengeMethod !== "S256" || payload.codeChallenge.length < 43) + return back({ + error: "invalid_request", + error_description: "PKCE with S256 is required", + }) + const code = yield* access.createCode({ + clientId: client.value.id, + userId: user.id, + redirectUri: payload.redirectUri, + codeChallenge: payload.codeChallenge, + scopes: parseAgentScopes(payload.scope), + }) + yield* Effect.annotateCurrentSpan({ "agent.client_id": client.value.id }) + return back({ code }) + }).pipe(Effect.catchTag("DatabaseError", internal("Could not authorize the agent"))), + ) + .handle("listAgentGrants", () => + Effect.gen(function* () { + const user = yield* CurrentUser.Context + const grants = yield* access.listGrants(user.id) + return new AgentGrantsResponse({ + grants: grants.map(toGrantInfo), + mcpUrl: mcpResourceUrl(apiOrigin), + }) + }).pipe(Effect.catchTag("DatabaseError", internal("Could not list agent grants"))), + ) + .handle("revokeAgentGrant", ({ params }) => + Effect.gen(function* () { + const user = yield* CurrentUser.Context + const revoked = yield* access.revokeGrant(user.id, params.grantId) + if (!revoked) return yield* new AgentGrantNotFoundError({ grantId: params.grantId }) + }).pipe(Effect.catchTag("DatabaseError", internal("Could not revoke the agent grant"))), + ) + .handle("createAgentToken", ({ payload }) => + Effect.gen(function* () { + const user = yield* CurrentUser.Context + const created = yield* access.createPersonalToken({ + userId: user.id, + name: payload.name.trim(), + scopes: payload.scopes, + }) + return new CreateAgentTokenResponse({ + grant: toGrantInfo(created.grant), + token: created.token, + }) + }).pipe(Effect.catchTag("DatabaseError", internal("Could not create the token"))), + ) + }), +) diff --git a/apps/backend/src/routes/agent-oauth.ts b/apps/backend/src/routes/agent-oauth.ts new file mode 100644 index 000000000..b543abec7 --- /dev/null +++ b/apps/backend/src/routes/agent-oauth.ts @@ -0,0 +1,263 @@ +/** + * Hazel as the OAuth 2.1 authorization server of its MCP server (`routes/mcp.ts`), the routes the + * MCP authorization spec asks for: + * + * - `GET /.well-known/oauth-protected-resource[/mcp]` (RFC 9728): the resource and its server; + * - `GET /.well-known/oauth-authorization-server` (RFC 8414): the endpoints below; + * - `POST /oauth/register` (RFC 7591): public clients register themselves (no secret, PKCE); + * - `GET /oauth/authorize`: sends the browser to the web app's consent page, which answers through + * `agentAccess.authorizeAgent` (`agent-access.http.ts`) with the code; + * - `POST /oauth/token`: `authorization_code` (PKCE S256) and `refresh_token` grants. + * + * The token endpoint answers RFC 6749 errors as JSON; nothing here reads a cookie. + */ +import { Config, Effect, Option, Schema } from "effect" +import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http" +import { AgentClientId } from "@hazel/schema" +import { AgentAccess, isAllowedRedirectUri, OAuthProtocolError } from "../services/agent-access" +import { ALL_AGENT_SCOPES } from "@hazel/domain/http" + +const originOf = (url: string) => new URL(url).origin + +/** The api's public origin and the web app's, as the metadata and redirects name them. */ +export const agentOAuthConfig = Effect.gen(function* () { + return { + apiOrigin: originOf(yield* Config.String("API_BASE_URL")), + frontendUrl: (yield* Config.String("FRONTEND_URL")).replace(/\/$/, ""), + } +}) + +/** The MCP server's URL: the resource tokens are issued for. */ +export const mcpResourceUrl = (apiOrigin: string) => `${apiOrigin}/mcp` + +/** Where a 401 from `/mcp` points clients (`WWW-Authenticate: Bearer resource_metadata=…`). */ +export const protectedResourceMetadataUrl = (apiOrigin: string) => + `${apiOrigin}/.well-known/oauth-protected-resource` + +const NO_STORE = { "Cache-Control": "no-store", Pragma: "no-cache" } +/** Metadata and registration are read by clients from any origin. */ +const OPEN_CORS = { "Access-Control-Allow-Origin": "*" } + +const oauthError = (error: string, description: string, status = 400) => + HttpServerResponse.jsonUnsafe( + { error, error_description: description }, + { status, headers: { ...NO_STORE, ...OPEN_CORS } }, + ) + +const decodeClientId = Schema.decodeUnknownOption(AgentClientId) + +const RegistrationRequest = Schema.Struct({ + client_name: Schema.optional(Schema.String), + redirect_uris: Schema.Array(Schema.String), + client_uri: Schema.optional(Schema.String), + logo_uri: Schema.optional(Schema.String), + token_endpoint_auth_method: Schema.optional(Schema.String), + grant_types: Schema.optional(Schema.Array(Schema.String)), + response_types: Schema.optional(Schema.Array(Schema.String)), + scope: Schema.optional(Schema.String), +}) +const decodeRegistration = Schema.decodeUnknownOption(RegistrationRequest) + +/** At most this many redirect URIs per client, and this long a name (it is shown in chat). */ +const MAX_REDIRECT_URIS = 10 +const MAX_CLIENT_NAME = 80 + +const httpsOrNull = (value: string | undefined) => { + if (value === undefined) return null + try { + return new URL(value).protocol === "https:" ? value : null + } catch { + return null + } +} + +const readBody = Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest + return yield* request.text.pipe(Effect.orElseSucceed(() => "")) +}) + +/** A form body (`application/x-www-form-urlencoded`), or JSON for lenient clients. */ +const readParams = Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest + const body = yield* readBody + if ((request.headers["content-type"] ?? "").includes("application/json")) { + try { + const parsed = JSON.parse(body) as Record + return new Map( + Object.entries(parsed).flatMap(([k, v]) => (typeof v === "string" ? [[k, v] as const] : [])), + ) + } catch { + return new Map() + } + } + return new Map(new URLSearchParams(body)) +}) + +export const AgentOAuthRoutes = HttpRouter.use((router) => + Effect.gen(function* () { + const access = yield* AgentAccess + const { apiOrigin, frontendUrl } = yield* agentOAuthConfig + + const resourceMetadata = HttpServerResponse.jsonUnsafe( + { + resource: mcpResourceUrl(apiOrigin), + authorization_servers: [apiOrigin], + scopes_supported: ALL_AGENT_SCOPES, + bearer_methods_supported: ["header"], + resource_name: "Hazel", + }, + { headers: { ...OPEN_CORS, "Cache-Control": "public, max-age=3600" } }, + ) + yield* router.add("GET", "/.well-known/oauth-protected-resource", Effect.succeed(resourceMetadata)) + yield* router.add( + "GET", + "/.well-known/oauth-protected-resource/mcp", + Effect.succeed(resourceMetadata), + ) + + yield* router.add( + "GET", + "/.well-known/oauth-authorization-server", + Effect.succeed( + HttpServerResponse.jsonUnsafe( + { + issuer: apiOrigin, + authorization_endpoint: `${apiOrigin}/oauth/authorize`, + token_endpoint: `${apiOrigin}/oauth/token`, + registration_endpoint: `${apiOrigin}/oauth/register`, + response_types_supported: ["code"], + grant_types_supported: ["authorization_code", "refresh_token"], + code_challenge_methods_supported: ["S256"], + token_endpoint_auth_methods_supported: ["none"], + scopes_supported: ALL_AGENT_SCOPES, + }, + { headers: { ...OPEN_CORS, "Cache-Control": "public, max-age=3600" } }, + ), + ), + ) + + yield* router.add( + "POST", + "/oauth/register", + Effect.gen(function* () { + const body = yield* readBody + let json: unknown + try { + json = JSON.parse(body) + } catch { + return oauthError("invalid_client_metadata", "The body is not JSON") + } + const registration = decodeRegistration(json) + if (Option.isNone(registration)) + return oauthError("invalid_client_metadata", "redirect_uris is required") + const meta = registration.value + if (meta.redirect_uris.length === 0 || meta.redirect_uris.length > MAX_REDIRECT_URIS) + return oauthError( + "invalid_redirect_uri", + `Register 1 to ${MAX_REDIRECT_URIS} redirect URIs`, + ) + const bad = meta.redirect_uris.find((uri) => !isAllowedRedirectUri(uri)) + if (bad !== undefined) + return oauthError("invalid_redirect_uri", `Not an allowed redirect URI: ${bad}`) + if ( + meta.token_endpoint_auth_method !== undefined && + meta.token_endpoint_auth_method !== "none" + ) + return oauthError( + "invalid_client_metadata", + "Only public clients (token_endpoint_auth_method=none, PKCE) are supported", + ) + const clientName = (meta.client_name ?? "").trim().slice(0, MAX_CLIENT_NAME) || "MCP client" + const created = yield* access.registerClient({ + clientName, + redirectUris: meta.redirect_uris, + clientUri: httpsOrNull(meta.client_uri), + logoUri: httpsOrNull(meta.logo_uri), + }) + return HttpServerResponse.jsonUnsafe( + { + client_id: created.id, + client_id_issued_at: Math.floor(created.createdAt.getTime() / 1000), + client_name: clientName, + redirect_uris: meta.redirect_uris, + token_endpoint_auth_method: "none", + grant_types: ["authorization_code", "refresh_token"], + response_types: ["code"], + }, + { status: 201, headers: { ...NO_STORE, ...OPEN_CORS } }, + ) + }).pipe( + Effect.catchTag("DatabaseError", (error) => + Effect.logError("Agent client registration failed", { error: error.message }).pipe( + Effect.as(oauthError("server_error", "Registration is unavailable", 503)), + ), + ), + Effect.withSpan("AgentOAuth.register"), + ), + ) + + // The consent page lives in the web app; it checks the client and redirect URI itself + // (`getAgentClient`), so a bad request is shown there, never redirected to. + yield* router.add( + "GET", + "/oauth/authorize", + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest + const search = new URL(request.url, apiOrigin).search + return HttpServerResponse.redirect(`${frontendUrl}/oauth/authorize${search}`, { + status: 302, + headers: { "Cache-Control": "no-store" }, + }) + }), + ) + + yield* router.add( + "POST", + "/oauth/token", + Effect.gen(function* () { + const params = yield* readParams + const grantType = params.get("grant_type") + const clientId = params.get("client_id") ?? "" + if (Option.isNone(decodeClientId(clientId))) + return oauthError("invalid_client", "client_id is missing or unknown", 401) + const tokens = + grantType === "authorization_code" + ? yield* access.exchangeCode({ + code: params.get("code") ?? "", + clientId, + redirectUri: params.get("redirect_uri") ?? "", + codeVerifier: params.get("code_verifier") ?? "", + }) + : grantType === "refresh_token" + ? yield* access.refresh({ + refreshToken: params.get("refresh_token") ?? "", + clientId, + }) + : yield* new OAuthProtocolError({ + error: "unsupported_grant_type", + description: "Use authorization_code or refresh_token", + }) + return HttpServerResponse.jsonUnsafe( + { + access_token: tokens.accessToken, + token_type: "Bearer", + expires_in: tokens.expiresInSeconds, + refresh_token: tokens.refreshToken, + scope: tokens.scopes.join(" "), + }, + { headers: { ...NO_STORE, ...OPEN_CORS } }, + ) + }).pipe( + Effect.catchTag("OAuthProtocolError", (error) => + Effect.succeed(oauthError(error.error, error.description)), + ), + Effect.catchTag("DatabaseError", (error) => + Effect.logError("Agent token exchange failed", { error: error.message }).pipe( + Effect.as(oauthError("server_error", "The token endpoint is unavailable", 503)), + ), + ), + Effect.withSpan("AgentOAuth.token"), + ), + ) + }), +) diff --git a/apps/backend/src/routes/mcp.http.test.ts b/apps/backend/src/routes/mcp.http.test.ts new file mode 100644 index 000000000..e87a1a14f --- /dev/null +++ b/apps/backend/src/routes/mcp.http.test.ts @@ -0,0 +1,377 @@ +/** + * Hazel's MCP server end to end, on node SQLite (`makeTestObjects`): an MCP client discovers the + * OAuth metadata, registers, exchanges a PKCE code, calls tools as the user (a message it sends is + * marked as the agent's), refreshes, and loses access when the user revokes it. Personal tokens + * work the same; a read-only one has no write tools. + */ +import { createHash } from "node:crypto" +import { NodeHttpPlatform, NodeServices } from "@effect/platform-node" +import { SQLite, schema } from "@hazel/db" +import type { AgentClientId, ChannelId, OrganizationId, UserId } from "@hazel/schema" +import { ConfigProvider, Context, Effect, Layer, type Scope } from "effect" +import { HttpRouter } from "effect/http" +import { describe, expect, it } from "vitest" +import { AgentAccess } from "../services/agent-access" +import { Directory } from "../services/directory" +import { RateLimiterAllowAll } from "../services/rate-limiter" +import { channelTarget, orgTarget } from "../worker/objects/kinds" +import { ObjectStubs } from "../worker/objects/protocol" +import { makeTestObjects, type TestObject } from "../worker/objects/testing" +import { AgentOAuthRoutes } from "./agent-oauth" +import { McpRoute } from "./mcp" + +const uuid = () => crypto.randomUUID() +const API = "https://api.hazel.test" +const base64Url = (bytes: Buffer) => bytes.toString("base64url") +const verifier = "a-pkce-code-verifier-that-is-long-enough-to-be-valid-0123456789" +const challenge = base64Url(createHash("sha256").update(verifier).digest()) + +const run = (effect: Effect.Effect) => + Effect.runPromise(Effect.scoped(effect) as Effect.Effect) + +/** An org with alice in one public channel, the directory rows the api Worker reads, and the routes. */ +const makeWorld = Effect.gen(function* () { + const objects = yield* makeTestObjects + const orgId = uuid() as OrganizationId + const alice = uuid() as UserId + const channelId = uuid() as ChannelId + const org = yield* objects.get(orgTarget(orgId)) + const db = org.storage.db + db.prepare(`INSERT INTO organizations (id, name, slug) VALUES (?, 'Acme', 'acme')`).run(orgId) + db.prepare( + `INSERT INTO organization_members (id, organizationId, userId, role) VALUES (?, ?, ?, 'member')`, + ).run(uuid(), orgId, alice) + db.prepare( + `INSERT INTO channels (id, name, type, organizationId) VALUES (?, 'general', 'public', ?)`, + ).run(channelId, orgId) + db.prepare( + `INSERT INTO channel_members (channelId, userId, isMuted, notificationCount) VALUES (?, ?, 0, 2)`, + ).run(channelId, alice) + db.prepare(`INSERT INTO channel_access (userId, channelId, organizationId) VALUES (?, ?, ?)`).run( + alice, + channelId, + orgId, + ) + const channel = yield* objects.get(channelTarget(channelId)) + yield* channel.applyEffect({ + objectId: channelId, + kind: "channel.setViewers", + payload: { + organizationId: orgId, + conversationId: null, + viewers: [{ userId: alice, organizationId: orgId, role: "member" }], + bots: [], + }, + key: `viewers:${channelId}`, + sender: { kind: "org", id: orgId }, + }) + const directory = Context.get(objects.directory, Directory) + yield* directory.upsertChannel({ channelId, organizationId: orgId, hostChannelId: null, deletedAt: null }) + yield* directory.upsertOrg({ id: orgId, slug: "acme", name: "Acme", deletedAt: null }) + yield* directory.upsertMembership({ userId: alice, organizationId: orgId, deletedAt: null }) + yield* directory.db.run( + SQLite.insertInto(schema.usersTable).values({ + id: alice, + externalId: `ext-${alice}`, + email: "alice@example.com", + firstName: "Alice", + lastName: "Liddell", + }), + ) + + const services = Layer.mergeAll( + AgentAccess.layer.pipe(Layer.provide(Layer.succeedContext(objects.directory))), + Layer.succeedContext(objects.directory), + Layer.succeed(ObjectStubs, objects.stubs), + RateLimiterAllowAll, + ConfigProvider.layer( + ConfigProvider.fromUnknown({ API_BASE_URL: API, FRONTEND_URL: "https://app.hazel.test" }), + ), + ) + const app = Layer.mergeAll(AgentOAuthRoutes, McpRoute).pipe( + Layer.provideMerge(services), + Layer.provideMerge(HttpRouter.layer), + Layer.provideMerge(NodeServices.layer), + Layer.provideMerge(NodeHttpPlatform.layer), + ) + const { handler, dispose } = HttpRouter.toWebHandler(app as never, { disableLogger: true }) + yield* Effect.addFinalizer(() => Effect.promise(() => dispose())) + const fetch = (path: string, init: RequestInit = {}) => + Effect.promise(() => + handler(new Request(`${API}${path}`, init), Context.empty() as Context.Context), + ) + const access = Context.get( + yield* Layer.build(AgentAccess.layer.pipe(Layer.provide(Layer.succeedContext(objects.directory)))), + AgentAccess, + ) + return { objects, orgId, alice, channelId, channel, fetch, access } +}).pipe(Effect.orDie) + +type World = Effect.Success + +const json = (response: Response) => Effect.promise(() => response.json() as Promise) + +const form = (params: Record) => ({ + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams(params).toString(), +}) + +let nextId = 1 +const mcp = (world: World, token: string, method: string, params?: Record) => + world + .fetch("/mcp", { + method: "POST", + headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, + body: JSON.stringify({ jsonrpc: "2.0", id: nextId++, method, ...(params ? { params } : {}) }), + }) + .pipe(Effect.flatMap(json)) + +const callTool = (world: World, token: string, name: string, args: Record = {}) => + mcp(world, token, "tools/call", { name, arguments: args }).pipe(Effect.map((response) => response.result)) + +const messagesIn = (object: TestObject) => + object.storage.db + .prepare(`SELECT id, authorId, content FROM messages ORDER BY createdAt`) + .all() as Array<{ + id: string + authorId: string + content: string + }> + +describe("MCP server", () => { + it("OAuth: discover, register, exchange, act, refresh, revoke", () => + run( + Effect.gen(function* () { + const world = yield* makeWorld + + // Unauthenticated: 401 pointing at the resource metadata. + const anonymous = yield* world.fetch("/mcp", { method: "POST", body: "{}" }) + expect(anonymous.status).toBe(401) + expect(anonymous.headers.get("www-authenticate")).toContain( + `resource_metadata="${API}/.well-known/oauth-protected-resource"`, + ) + const resource = yield* json(yield* world.fetch("/.well-known/oauth-protected-resource")) + expect(resource).toMatchObject({ resource: `${API}/mcp`, authorization_servers: [API] }) + const server = yield* json(yield* world.fetch("/.well-known/oauth-authorization-server")) + expect(server).toMatchObject({ + token_endpoint: `${API}/oauth/token`, + registration_endpoint: `${API}/oauth/register`, + code_challenge_methods_supported: ["S256"], + }) + + // Registration: a script redirect is refused; a loopback one is fine. + const refused = yield* world.fetch("/oauth/register", { + method: "POST", + body: JSON.stringify({ client_name: "Evil", redirect_uris: ["javascript:alert(1)"] }), + }) + expect(refused.status).toBe(400) + const registered = yield* json( + yield* world.fetch("/oauth/register", { + method: "POST", + body: JSON.stringify({ + client_name: "Claude", + redirect_uris: ["http://127.0.0.1:33418/callback"], + }), + }), + ) + const clientId = registered.client_id as AgentClientId + + // The authorize endpoint hands the browser to the web app's consent page. + const authorize = yield* world.fetch(`/oauth/authorize?client_id=${clientId}&state=s`) + expect(authorize.status).toBe(302) + expect(authorize.headers.get("location")).toBe( + `https://app.hazel.test/oauth/authorize?client_id=${clientId}&state=s`, + ) + + // The consent page's approval (a loopback redirect matches any port). + const redirectUri = "http://127.0.0.1:50123/callback" + expect((yield* world.access.clientFor(clientId, redirectUri))._tag).toBe("Some") + expect((yield* world.access.clientFor(clientId, "https://evil.test/cb"))._tag).toBe("None") + const code = yield* world.access.createCode({ + clientId, + userId: world.alice, + redirectUri, + codeChallenge: challenge, + scopes: ["messages:read", "messages:write"], + }) + + const exchange = (params: Record) => world.fetch("/oauth/token", form(params)) + const wrongVerifier = yield* exchange({ + grant_type: "authorization_code", + code, + client_id: clientId, + redirect_uri: redirectUri, + code_verifier: "wrong", + }) + expect(wrongVerifier.status).toBe(400) + expect((yield* json(wrongVerifier)).error).toBe("invalid_grant") + + // The failed attempt spent the code; a fresh one exchanges. + const code2 = yield* world.access.createCode({ + clientId, + userId: world.alice, + redirectUri, + codeChallenge: challenge, + scopes: ["messages:read", "messages:write"], + }) + const tokens = yield* json( + yield* exchange({ + grant_type: "authorization_code", + code: code2, + client_id: clientId, + redirect_uri: redirectUri, + code_verifier: verifier, + }), + ) + expect(tokens).toMatchObject({ + token_type: "Bearer", + expires_in: 3600, + scope: "messages:read messages:write", + }) + const replay = yield* exchange({ + grant_type: "authorization_code", + code: code2, + client_id: clientId, + redirect_uri: redirectUri, + code_verifier: verifier, + }) + expect((yield* json(replay)).error).toBe("invalid_grant") + + // MCP: initialize, list tools, act. + const init = yield* mcp(world, tokens.access_token, "initialize", { + protocolVersion: "2025-06-18", + capabilities: {}, + clientInfo: { name: "test", version: "1" }, + }) + expect(init.result.protocolVersion).toBe("2025-06-18") + expect(init.result.serverInfo.name).toBe("hazel") + const listed = yield* mcp(world, tokens.access_token, "tools/list") + expect(listed.result.tools.map((tool: { name: string }) => tool.name)).toContain( + "send_message", + ) + + const channels = yield* callTool(world, tokens.access_token, "list_channels") + expect(channels.structuredContent.channels).toEqual([ + { + id: world.channelId, + organization_id: world.orgId, + name: "general", + type: "public", + unread_count: 2, + }, + ]) + + const sent = yield* callTool(world, tokens.access_token, "send_message", { + channel_id: world.channelId, + content: "On it, will send the doc by 5", + }) + expect(sent.isError).toBeUndefined() + expect(sent.structuredContent.message.author).toEqual({ + id: world.alice, + name: "Alice Liddell", + }) + const [message] = messagesIn(world.channel) + expect(message).toMatchObject({ + authorId: world.alice, + content: "On it, will send the doc by 5", + }) + expect( + world.channel.storage.db.prepare(`SELECT id, agentName FROM message_agent_marks`).all(), + ).toEqual([{ id: message!.id, agentName: "Claude" }]) + + const read = yield* callTool(world, tokens.access_token, "read_messages", { + channel_id: world.channelId, + }) + expect(read.structuredContent.messages.map((m: { content: string }) => m.content)).toEqual([ + "On it, will send the doc by 5", + ]) + + // A tool failure is a tool result, not a protocol error. + const bad = yield* callTool(world, tokens.access_token, "send_message", { + channel_id: "not-a-uuid", + content: "x", + }) + expect(bad.isError).toBe(true) + + // Refresh rotates: the old refresh token is spent. + const refreshed = yield* json( + yield* exchange({ + grant_type: "refresh_token", + refresh_token: tokens.refresh_token, + client_id: clientId, + }), + ) + expect(refreshed.access_token).not.toBe(tokens.access_token) + const reused = yield* exchange({ + grant_type: "refresh_token", + refresh_token: tokens.refresh_token, + client_id: clientId, + }) + expect((yield* json(reused)).error).toBe("invalid_grant") + + // Revoking the grant ends every token at once. + const [grant] = yield* world.access.listGrants(world.alice) + expect(grant).toMatchObject({ kind: "oauth", name: "Claude" }) + expect(yield* world.access.revokeGrant(world.alice, grant!.id)).toBe(true) + const after = yield* world.fetch("/mcp", { + method: "POST", + headers: { authorization: `Bearer ${refreshed.access_token}` }, + body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }), + }) + expect(after.status).toBe(401) + }), + )) + + it("personal tokens: a read-only one cannot write; edits stay on the user's own messages", () => + run( + Effect.gen(function* () { + const world = yield* makeWorld + const readOnly = yield* world.access.createPersonalToken({ + userId: world.alice, + name: "Reader", + scopes: ["messages:read"], + }) + expect(readOnly.token.startsWith("hzl_pat_")).toBe(true) + const listed = yield* mcp(world, readOnly.token, "tools/list") + const names = listed.result.tools.map((tool: { name: string }) => tool.name) + expect(names).toContain("read_messages") + expect(names).not.toContain("send_message") + const refused = yield* callTool(world, readOnly.token, "send_message", { + channel_id: world.channelId, + content: "hi", + }) + expect(refused.isError).toBe(true) + expect(messagesIn(world.channel)).toEqual([]) + + // Someone else's message: the agent may not edit it. + const bob = uuid() as UserId + world.channel.storage.db + .prepare( + `INSERT INTO messages (id, channelId, authorId, content) VALUES (?, ?, ?, 'bob says hi')`, + ) + .run(uuid(), world.channelId, bob) + const writer = yield* world.access.createPersonalToken({ + userId: world.alice, + name: "Writer", + scopes: ["messages:read", "messages:write"], + }) + const [bobs] = messagesIn(world.channel) + const edit = yield* callTool(world, writer.token, "edit_message", { + channel_id: world.channelId, + message_id: bobs!.id, + content: "hijacked", + }) + expect(edit.isError).toBe(true) + expect(messagesIn(world.channel)[0]!.content).toBe("bob says hi") + + // Notifications are a JSON-RPC notification: 202, no body. + const note = yield* world.fetch("/mcp", { + method: "POST", + headers: { authorization: `Bearer ${writer.token}` }, + body: JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }), + }) + expect(note.status).toBe(202) + }), + )) +}) diff --git a/apps/backend/src/routes/mcp.ts b/apps/backend/src/routes/mcp.ts new file mode 100644 index 000000000..930cce077 --- /dev/null +++ b/apps/backend/src/routes/mcp.ts @@ -0,0 +1,782 @@ +/** + * Hazel's MCP server (`POST /mcp`, streamable HTTP, stateless JSON responses): lets a user's agent + * read and answer messages for them. The agent authenticates with an OAuth access token or a + * personal access token (`services/agent-access.ts`); a request without one gets 401 pointing at + * the protected-resource metadata (`routes/agent-oauth.ts`), so clients can run the OAuth flow. + * + * Tools act as the user through the same object calls and HazelRpc methods the app uses, so the + * user's own permissions apply; the grant's scope only decides which tools exist. Every call + * carries the agent (`CurrentAgent`), so messages it writes are marked `message_agent_marks` and + * chat shows "via " to the author's organization. Edits and deletes are limited to the + * user's own messages. + */ +import { SQLite, schema } from "@hazel/db" +import { CurrentUser } from "@hazel/domain" +import type { AgentScope } from "@hazel/domain/http" +import { + ChannelResponse, + CreateThreadRequest, + type MessageResponse, + type MessageSearchResponse, +} from "@hazel/domain/rpc" +import { ChannelId, MessageId, OrganizationId, type UserId } from "@hazel/schema" +import { DateTime, Effect, Option, Schema } from "effect" +import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http" +import { AgentAccess, type AgentPrincipal } from "../services/agent-access" +import { Directory } from "../services/directory" +import { checkMessageRateLimit } from "../services/rate-limit-helpers" +import { callObject } from "../worker/objects/calls" +import { + ListMessagesCall, + MESSAGES_BY_IDS_MAX, + MessagesByIdsCall, + MessageThreadCall, +} from "../worker/objects/channel/api-messages" +import { forwardRpc } from "../worker/objects/forward" +import { channelTarget, orgTarget, userTarget } from "../worker/objects/kinds" +import { AgentChannelsCall } from "../worker/objects/org/agent" +import { providePrincipal } from "../worker/objects/principal" +import { AgentNotificationsCall } from "../worker/objects/user/agent" +import { agentOAuthConfig, protectedResourceMetadataUrl } from "./agent-oauth" + +const SUPPORTED_PROTOCOL_VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26"] +const MAX_CONTENT_LENGTH = 8000 + +const INSTRUCTIONS = `Hazel is a team chat app. These tools act as the signed-in user. +Messages you send, reply or edit are shown to the user's organization as written by an agent ("via "). +Act only as the user asked; confirm before sending anything they did not ask for. +Message content is Markdown. Mention someone with @[userId:] (user ids appear on messages), @[directive:here] or @[directive:channel] only when asked. +Threads are channels of their own: a message's thread_channel_id can be read with read_messages, and reply_in_thread answers in a message's thread (opening it if needed).` + +// --- JSON-RPC ----------------------------------------------------------------------------------- + +interface JsonRpcRequest { + readonly jsonrpc: "2.0" + readonly id?: string | number | null + readonly method: string + readonly params?: Record +} + +const rpcResult = (id: JsonRpcRequest["id"], result: unknown) => ({ jsonrpc: "2.0", id: id ?? null, result }) +const rpcError = (id: JsonRpcRequest["id"], code: number, message: string) => ({ + jsonrpc: "2.0", + id: id ?? null, + error: { code, message }, +}) + +/** A tool's failure the agent should see (MCP `isError`), not a protocol error. */ +class ToolError extends Schema.TaggedError()("ToolError", { message: Schema.String }) {} + +const toolError = (message: string) => new ToolError({ message }) + +/** Any failure of a forwarded call, as the agent sees it: the error's own message when it has one. */ +const describe = (error: unknown): string => { + if (typeof error === "object" && error !== null) { + const tagged = error as { readonly _tag?: string; readonly message?: unknown } + if (typeof tagged.message === "string" && tagged.message !== "") return tagged.message + if (typeof tagged._tag === "string") + return tagged._tag.replace(/Error$/, "").replace(/([a-z])([A-Z])/g, "$1 $2") + } + return "The request failed" +} + +// --- Tools -------------------------------------------------------------------------------------- + +interface ToolContext { + readonly user: CurrentUser.Schema + readonly agent: AgentPrincipal +} + +interface Tool { + readonly name: string + readonly title: string + readonly description: string + readonly scope: AgentScope + readonly inputSchema: Record + readonly readOnly: boolean + readonly run: (args: Record, ctx: ToolContext) => Effect.Effect +} + +const str = (description: string) => ({ type: "string", description }) +const obj = (properties: Record, required: ReadonlyArray = []) => ({ + type: "object", + properties, + required, + additionalProperties: false, +}) + +const decodeChannelId = Schema.decodeUnknownOption(ChannelId) +const decodeMessageId = Schema.decodeUnknownOption(MessageId) +const decodeOrgId = Schema.decodeUnknownOption(OrganizationId) + +const argChannel = (args: Record, key = "channel_id") => + Option.match(decodeChannelId(args[key]), { + onNone: () => Effect.fail(toolError(`${key} must be a channel id (UUID)`)), + onSome: Effect.succeed, + }) +const argMessage = (args: Record, key = "message_id") => + Option.match(decodeMessageId(args[key]), { + onNone: () => Effect.fail(toolError(`${key} must be a message id (UUID)`)), + onSome: Effect.succeed, + }) +const optMessage = (args: Record, key: string) => + args[key] === undefined || args[key] === null ? Effect.succeed(null) : argMessage(args, key) +const argContent = (args: Record) => { + const content = typeof args.content === "string" ? args.content.trim() : "" + if (content === "") return Effect.fail(toolError("content must not be empty")) + if (content.length > MAX_CONTENT_LENGTH) + return Effect.fail(toolError(`content is longer than ${MAX_CONTENT_LENGTH} characters`)) + return Effect.succeed(content) +} +const argLimit = (args: Record, fallback: number, max: number) => { + const value = typeof args.limit === "number" ? Math.floor(args.limit) : fallback + return Math.max(1, Math.min(value, max)) +} + +/** The channel's index row: its org and the `ChannelObject` holding its messages (a Connect mount's host). */ +const channelInfo = (channelId: ChannelId) => + Effect.gen(function* () { + const index = yield* (yield* Directory).channel(channelId).pipe(Effect.orDie) + if (Option.isNone(index) || index.value.deletedAt !== null) + return yield* toolError(`No channel ${channelId}`) + return { + organizationId: index.value.organizationId, + host: channelTarget(index.value.hostChannelId ?? channelId), + } + }) + +/** Display names for user ids, from the directory. */ +const namesOf = (ids: Iterable) => + Effect.gen(function* () { + const unique = [...new Set(ids)].slice(0, 100) + if (unique.length === 0) return new Map() + const rows = yield* (yield* Directory).db + .run( + SQLite.from(schema.usersTable) + .select("id", "firstName", "lastName") + .where(($) => [$.id.in_(...(unique as Array))]), + ) + .pipe(Effect.orDie) + return new Map(rows.map((row) => [row.id as string, `${row.firstName} ${row.lastName}`.trim()])) + }) + +const MENTION = /@\[userId:([0-9a-f-]{36})\]/gi + +interface MessageLike { + readonly id: string + readonly authorId: string + readonly content: string + readonly createdAt: Date | DateTime.Utc + readonly updatedAt: Date | DateTime.Utc | null + readonly replyToMessageId: string | null + readonly threadChannelId: string | null + readonly channelId: string +} + +/** Messages as the agent reads them: author names, mentions shown as `@Name (userId)`. */ +const present = (messages: ReadonlyArray) => + Effect.gen(function* () { + const ids: Array = [] + for (const message of messages) { + ids.push(message.authorId) + for (const match of message.content.matchAll(MENTION)) ids.push(match[1]!) + } + const names = yield* namesOf(ids) + const iso = (at: Date | DateTime.Utc) => + at instanceof Date ? at.toISOString() : DateTime.formatIso(at) + const ms = (at: Date | DateTime.Utc) => + at instanceof Date ? at.getTime() : DateTime.toEpochMillis(at) + return messages.map((message) => ({ + id: message.id, + channel_id: message.channelId, + author: { id: message.authorId, name: names.get(message.authorId) ?? "Unknown" }, + content: message.content.replace( + MENTION, + (whole, id: string) => `@${names.get(id) ?? "someone"} (${whole})`, + ), + created_at: iso(message.createdAt), + ...(message.updatedAt !== null && ms(message.updatedAt) > ms(message.createdAt) + ? { edited_at: iso(message.updatedAt) } + : {}), + ...(message.replyToMessageId === null ? {} : { reply_to_message_id: message.replyToMessageId }), + ...(message.threadChannelId === null ? {} : { thread_channel_id: message.threadChannelId }), + })) + }) + +/** The user's own message in its channel; edits and deletes go no further. */ +const ownMessage = (ctx: ToolContext, host: ReturnType, messageId: MessageId) => + Effect.gen(function* () { + const found = yield* callObject(MessagesByIdsCall, host, { + userId: ctx.user.id, + ids: [messageId], + }).pipe(Effect.mapError((error) => toolError(describe(error)))) + const message = found[0] + if (message === undefined) return yield* toolError(`No message ${messageId} in this channel`) + if (message.authorId !== ctx.user.id) + return yield* toolError("Agents can only edit or delete the user's own messages") + return message + }) + +const forward = ( + target: Parameters[0], + tag: Parameters[1], + payload: unknown, +) => forwardRpc(target, tag, payload).pipe(Effect.mapError((error) => toolError(describe(error)))) + +const rateLimited = (ctx: ToolContext) => + checkMessageRateLimit(ctx.user.id).pipe(Effect.mapError((error) => toolError(describe(error)))) + +const sendIn = ( + ctx: ToolContext, + channelId: ChannelId, + content: string, + replyToMessageId: MessageId | null, +) => + Effect.gen(function* () { + const { host } = yield* channelInfo(channelId) + yield* rateLimited(ctx) + const response = yield* forward(host, "message.create", { + channelId, + content, + authorId: ctx.user.id, + deletedAt: null, + embeds: null, + replyToMessageId, + threadChannelId: null, + }) + return { sent: true, message: (yield* present([response.data]))[0] } + }) + +const tools: ReadonlyArray = [ + { + name: "list_organizations", + title: "List organizations", + description: "The organizations (workspaces) the user belongs to.", + scope: "messages:read", + readOnly: true, + inputSchema: obj({}), + run: (_args, ctx) => + Effect.gen(function* () { + const directory = yield* Directory + const ids = yield* directory.organizationsOf(ctx.user.id).pipe(Effect.orDie) + const orgs = yield* Effect.forEach(ids, (id) => directory.org(id).pipe(Effect.orDie)) + return { + organizations: orgs.flatMap((org) => + Option.isSome(org) && org.value.deletedAt === null + ? [{ id: org.value.id, name: org.value.name, slug: org.value.slug }] + : [], + ), + } + }), + }, + { + name: "list_channels", + title: "List channels", + description: + "Channels and direct messages the user can read, with unread counts. Omit organization_id to list every organization's.", + scope: "messages:read", + readOnly: true, + inputSchema: obj({ organization_id: str("Only this organization's channels") }), + run: (args, ctx) => + Effect.gen(function* () { + const directory = yield* Directory + const orgIds = + args.organization_id === undefined + ? yield* directory.organizationsOf(ctx.user.id).pipe(Effect.orDie) + : Option.match(decodeOrgId(args.organization_id), { + onNone: () => [], + onSome: (id) => [id], + }) + if (orgIds.length === 0) return yield* toolError("No such organization") + const lists = yield* Effect.forEach(orgIds, (organizationId) => + callObject(AgentChannelsCall, orgTarget(organizationId), { userId: ctx.user.id }).pipe( + Effect.map((channels) => channels.map((channel) => ({ ...channel, organizationId }))), + Effect.mapError((error) => toolError(describe(error))), + ), + ) + return { + channels: lists.flat().map((channel) => ({ + id: channel.id, + organization_id: channel.organizationId, + name: + channel.type === "direct" || channel.type === "single" + ? channel.members.join(", ") || channel.name + : channel.name, + type: channel.type, + unread_count: channel.unreadCount, + ...(channel.isMuted ? { muted: true } : {}), + })), + } + }), + }, + { + name: "read_messages", + title: "Read messages", + description: + "A channel's (or thread's) messages, oldest first, newest at the end. Page back with before_message_id (the oldest id you have).", + scope: "messages:read", + readOnly: true, + inputSchema: obj( + { + channel_id: str("The channel or thread channel id"), + limit: { type: "integer", minimum: 1, maximum: 100, description: "How many (default 30)" }, + before_message_id: str("Only messages older than this one"), + }, + ["channel_id"], + ), + run: (args, ctx) => + Effect.gen(function* () { + const channelId = yield* argChannel(args) + const before = yield* optMessage(args, "before_message_id") + const { host } = yield* channelInfo(channelId) + const page = yield* callObject(ListMessagesCall, host, { + userId: ctx.user.id, + channelId, + startingAfter: before, + endingBefore: null, + limit: argLimit(args, 30, 100), + }).pipe(Effect.mapError((error) => toolError(describe(error)))) + return { + messages: yield* present([...page.messages].reverse()), + has_older: page.hasMore, + } + }), + }, + { + name: "search_messages", + title: "Search messages", + description: + "Full-text search over messages the user can read, newest first. Omit organization_id to search every organization.", + scope: "messages:read", + readOnly: true, + inputSchema: obj( + { + query: str("Words to find (all must appear, prefix match)"), + organization_id: str("Only this organization"), + channel_id: str("Only this channel"), + limit: { type: "integer", minimum: 1, maximum: 50, description: "How many (default 20)" }, + }, + ["query"], + ), + run: (args, ctx) => + Effect.gen(function* () { + const query = typeof args.query === "string" ? args.query.slice(0, 500) : "" + const limit = argLimit(args, 20, 50) + const channelId = args.channel_id === undefined ? undefined : yield* argChannel(args) + const directory = yield* Directory + const orgIds = + channelId !== undefined + ? [(yield* channelInfo(channelId)).organizationId] + : args.organization_id !== undefined + ? Option.toArray(decodeOrgId(args.organization_id)) + : yield* directory.organizationsOf(ctx.user.id).pipe(Effect.orDie) + const pages = yield* Effect.forEach(orgIds, (organizationId) => + forward(orgTarget(organizationId), "message.search", { + organizationId, + query, + limit, + ...(channelId === undefined ? {} : { channelId }), + }), + ) + const hits = pages + .flatMap((page) => page.results) + .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime()) + .slice(0, limit) + const names = yield* namesOf(hits.map((hit) => hit.authorId)) + return { + results: hits.map((hit) => ({ + message_id: hit.messageId, + channel_id: hit.channelId, + author: { id: hit.authorId, name: names.get(hit.authorId) ?? "Unknown" }, + created_at: hit.createdAt.toISOString(), + snippet: hit.snippet, + })), + ...(pages.some((page) => page.indexing) + ? { note: "Search is still indexing; results may be incomplete" } + : {}), + } + }), + }, + { + name: "list_notifications", + title: "List notifications", + description: + "The user's notifications (mentions, replies, direct messages), newest first, with each message's content.", + scope: "messages:read", + readOnly: true, + inputSchema: obj({ + unread_only: { type: "boolean", description: "Only unread ones (default true)" }, + limit: { type: "integer", minimum: 1, maximum: 50, description: "How many (default 20)" }, + }), + run: (args, ctx) => + Effect.gen(function* () { + const notifications = yield* callObject(AgentNotificationsCall, userTarget(ctx.user.id), { + unreadOnly: args.unread_only !== false, + limit: argLimit(args, 20, 50), + }).pipe(Effect.mapError((error) => toolError(describe(error)))) + // The messages, one call per channel. + const byChannel = new Map>() + for (const n of notifications) { + if (n.channelId === null || n.messageId === null) continue + const ids = byChannel.get(n.channelId) ?? [] + if (ids.length < MESSAGES_BY_IDS_MAX) ids.push(n.messageId) + byChannel.set(n.channelId, ids) + } + const fetched = yield* Effect.forEach([...byChannel], ([channelId, ids]) => + channelInfo(channelId).pipe( + Effect.flatMap(({ host }) => + callObject(MessagesByIdsCall, host, { userId: ctx.user.id, ids }), + ), + // A channel the user lost access to, or a deleted one: its notifications show without content. + Effect.orElseSucceed(() => []), + ), + ) + const messages = new Map( + (yield* present(fetched.flat())).map((message) => [message.id, message] as const), + ) + return { + notifications: notifications.map((n) => ({ + reason: n.reason, + read: n.read, + created_at: n.createdAt.toISOString(), + channel_id: n.channelId, + message: + n.messageId === null ? null : (messages.get(n.messageId) ?? { id: n.messageId }), + })), + } + }), + }, + { + name: "send_message", + title: "Send message", + description: + "Post a message as the user in a channel, direct message or thread channel. Use reply_to_message_id to quote-reply a message inline.", + scope: "messages:write", + readOnly: false, + inputSchema: obj( + { + channel_id: str("Where to post"), + content: str("Markdown text"), + reply_to_message_id: str("Reply to this message (inline quote)"), + }, + ["channel_id", "content"], + ), + run: (args, ctx) => + Effect.gen(function* () { + const channelId = yield* argChannel(args) + const content = yield* argContent(args) + const replyTo = yield* optMessage(args, "reply_to_message_id") + return yield* sendIn(ctx, channelId, content, replyTo) + }), + }, + { + name: "reply_in_thread", + title: "Reply in thread", + description: "Answer a message in its thread, opening the thread if it has none yet.", + scope: "messages:write", + readOnly: false, + inputSchema: obj( + { + channel_id: str("The channel the message is in"), + message_id: str("The message to answer"), + content: str("Markdown text"), + }, + ["channel_id", "message_id", "content"], + ), + run: (args, ctx) => + Effect.gen(function* () { + const channelId = yield* argChannel(args) + const messageId = yield* argMessage(args) + const content = yield* argContent(args) + const { host, organizationId } = yield* channelInfo(channelId) + const existing = yield* callObject(MessageThreadCall, host, { + userId: ctx.user.id, + messageId, + }).pipe(Effect.mapError((error) => toolError(describe(error)))) + const threadId = + existing ?? + (yield* forward( + orgTarget(organizationId), + "channel.createThread", + new CreateThreadRequest({ messageId, channelId, organizationId }), + )).data.id + return { thread_channel_id: threadId, ...(yield* sendIn(ctx, threadId, content, null)) } + }), + }, + { + name: "edit_message", + title: "Edit message", + description: "Change the text of one of the user's own messages.", + scope: "messages:write", + readOnly: false, + inputSchema: obj( + { + channel_id: str("The message's channel"), + message_id: str("The message"), + content: str("New Markdown text"), + }, + ["channel_id", "message_id", "content"], + ), + run: (args, ctx) => + Effect.gen(function* () { + const channelId = yield* argChannel(args) + const messageId = yield* argMessage(args) + const content = yield* argContent(args) + const { host } = yield* channelInfo(channelId) + yield* ownMessage(ctx, host, messageId) + yield* rateLimited(ctx) + const response = yield* forward(host, "message.update", { + id: messageId, + channelId, + content, + }) + return { edited: true, message: (yield* present([response.data]))[0] } + }), + }, + { + name: "delete_message", + title: "Delete message", + description: "Delete one of the user's own messages. Ask the user first.", + scope: "messages:write", + readOnly: false, + inputSchema: obj({ channel_id: str("The message's channel"), message_id: str("The message") }, [ + "channel_id", + "message_id", + ]), + run: (args, ctx) => + Effect.gen(function* () { + const channelId = yield* argChannel(args) + const messageId = yield* argMessage(args) + const { host } = yield* channelInfo(channelId) + yield* ownMessage(ctx, host, messageId) + yield* rateLimited(ctx) + yield* forward(host, "message.delete", { id: messageId, channelId }) + return { deleted: true } + }), + }, + { + name: "toggle_reaction", + title: "Toggle reaction", + description: "Add an emoji reaction as the user, or remove it if the user already reacted with it.", + scope: "messages:write", + readOnly: false, + inputSchema: obj( + { + channel_id: str("The message's channel"), + message_id: str("The message"), + emoji: str("A unicode emoji, e.g. 👍"), + }, + ["channel_id", "message_id", "emoji"], + ), + run: (args, ctx) => + Effect.gen(function* () { + const channelId = yield* argChannel(args) + const messageId = yield* argMessage(args) + const emoji = typeof args.emoji === "string" ? args.emoji.trim() : "" + if (emoji === "" || emoji.length > 50) return yield* toolError("emoji must be one emoji") + const { host } = yield* channelInfo(channelId) + const response = yield* forward<{ readonly wasCreated: boolean }>( + host, + "messageReaction.toggle", + { + messageId, + channelId, + emoji, + }, + ) + return { reacted: response.wasCreated } + }), + }, +] + +const toolsFor = (scopes: ReadonlyArray) => tools.filter((tool) => scopes.includes(tool.scope)) + +const toolListing = (scopes: ReadonlyArray) => + toolsFor(scopes).map((tool) => ({ + name: tool.name, + title: tool.title, + description: tool.description, + inputSchema: tool.inputSchema, + annotations: { + title: tool.title, + readOnlyHint: tool.readOnly, + destructiveHint: tool.name === "delete_message", + openWorldHint: false, + }, + })) + +const callTool = (params: Record | undefined, ctx: ToolContext) => + Effect.gen(function* () { + const name = typeof params?.name === "string" ? params.name : "" + const args = ( + typeof params?.arguments === "object" && params.arguments !== null ? params.arguments : {} + ) as Record + const tool = tools.find((candidate) => candidate.name === name) + if (tool === undefined) return yield* toolError(`Unknown tool ${name}`) + if (!ctx.agent.scopes.includes(tool.scope)) + return yield* toolError(`This connection is read-only; ${name} needs write access`) + return yield* tool + .run(args, ctx) + .pipe( + Effect.withSpan("Mcp.tool", { + attributes: { "mcp.tool": name, "agent.grant_id": ctx.agent.grantId }, + }), + ) + }).pipe( + Effect.map((result) => ({ + content: [{ type: "text", text: JSON.stringify(result, null, 2) }], + structuredContent: result, + })), + Effect.catchTag("ToolError", (error) => + Effect.succeed({ content: [{ type: "text", text: error.message }], isError: true }), + ), + ) + +const handle = (request: JsonRpcRequest, ctx: ToolContext) => + Effect.gen(function* () { + switch (request.method) { + case "initialize": { + const requested = request.params?.protocolVersion + const protocolVersion = + typeof requested === "string" && SUPPORTED_PROTOCOL_VERSIONS.includes(requested) + ? requested + : SUPPORTED_PROTOCOL_VERSIONS[0] + return rpcResult(request.id, { + protocolVersion, + capabilities: { tools: { listChanged: false } }, + serverInfo: { name: "hazel", title: "Hazel", version: "1.0.0" }, + instructions: INSTRUCTIONS, + }) + } + case "ping": + return rpcResult(request.id, {}) + case "tools/list": + return rpcResult(request.id, { tools: toolListing(ctx.agent.scopes) }) + case "tools/call": + return rpcResult(request.id, yield* callTool(request.params, ctx)) + default: + return rpcError(request.id, -32601, `Method not found: ${request.method}`) + } + }) + +const isRequest = (value: unknown): value is JsonRpcRequest => + typeof value === "object" && + value !== null && + (value as { jsonrpc?: unknown }).jsonrpc === "2.0" && + typeof (value as { method?: unknown }).method === "string" + +/** A notification (no id) gets no answer. */ +const isNotification = (request: JsonRpcRequest) => request.id === undefined + +const loadUser = (userId: UserId) => + Effect.gen(function* () { + const row = yield* (yield* Directory).db.first( + SQLite.from(schema.usersTable) + .select() + .where(($) => [$.id.eq(userId), $.deletedAt.isNull()]), + ) + return Option.map( + row, + (user) => + new CurrentUser.Schema({ + id: user.id, + role: "member", + avatarUrl: user.avatarUrl ?? undefined, + firstName: user.firstName, + lastName: user.lastName, + email: user.email, + isOnboarded: user.isOnboarded, + timezone: user.timezone, + settings: user.settings, + }), + ) + }) + +export const McpRoute = HttpRouter.use((router) => + Effect.gen(function* () { + const access = yield* AgentAccess + const { apiOrigin } = yield* agentOAuthConfig + const unauthorized = (description: string) => + HttpServerResponse.jsonUnsafe( + { error: "invalid_token", error_description: description }, + { + status: 401, + headers: { + "WWW-Authenticate": `Bearer resource_metadata="${protectedResourceMetadataUrl(apiOrigin)}", error="invalid_token"`, + }, + }, + ) + + const notAllowed = Effect.succeed( + HttpServerResponse.text("This MCP server answers POST only", { + status: 405, + headers: { Allow: "POST" }, + }), + ) + yield* router.add("GET", "/mcp", notAllowed) + yield* router.add("DELETE", "/mcp", notAllowed) + + yield* router.add( + "POST", + "/mcp", + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest + const authorization = request.headers.authorization ?? "" + const token = authorization.startsWith("Bearer ") ? authorization.slice(7).trim() : "" + if (token === "") return unauthorized("Sign in to use Hazel") + const agent = yield* access.authenticate(token) + if (Option.isNone(agent)) return unauthorized("The token is invalid, expired or revoked") + const user = yield* loadUser(agent.value.userId) + if (Option.isNone(user)) return unauthorized("The user is gone") + yield* Effect.annotateCurrentSpan({ + "agent.grant_id": agent.value.grantId, + "user.id": user.value.id, + }) + + const body = yield* request.text.pipe(Effect.orElseSucceed(() => "")) + let parsed: unknown + try { + parsed = JSON.parse(body) + } catch { + return HttpServerResponse.jsonUnsafe(rpcError(null, -32700, "Parse error"), { + status: 400, + }) + } + const batch = Array.isArray(parsed) + const items = (batch ? parsed : [parsed]) as ReadonlyArray + const ctx: ToolContext = { user: user.value, agent: agent.value } + const principal = { + user: user.value, + botScopes: null, + agent: { grantId: agent.value.grantId, name: agent.value.name }, + } + const responses = yield* Effect.forEach(items, (item) => + !isRequest(item) + ? Effect.succeed(rpcError(null, -32600, "Invalid request")) + : isNotification(item) + ? Effect.succeed(null) + : handle(item, ctx).pipe( + providePrincipal(principal), + Effect.provideService(CurrentUser.Context, user.value), + ), + ) + const answers = responses.filter((response) => response !== null) + if (answers.length === 0) return HttpServerResponse.empty({ status: 202 }) + return HttpServerResponse.jsonUnsafe(batch ? answers : answers[0], { + headers: { "Cache-Control": "no-store" }, + }) + }).pipe( + Effect.catchTag("DatabaseError", (error) => + Effect.logError("MCP request failed", { error: error.message }).pipe( + Effect.as( + HttpServerResponse.jsonUnsafe(rpcError(null, -32603, "Hazel is unavailable"), { + status: 503, + }), + ), + ), + ), + Effect.withSpan("Mcp.request"), + ), + ) + }), +) diff --git a/apps/backend/src/rpc/handlers/messages.ts b/apps/backend/src/rpc/handlers/messages.ts index 7b09e9f2e..0e73a0265 100644 --- a/apps/backend/src/rpc/handlers/messages.ts +++ b/apps/backend/src/rpc/handlers/messages.ts @@ -19,6 +19,7 @@ import { HtmlRenders, htmlRenderIdsOf } from "../../services/html-renders" import { checkMessageRateLimit } from "../../services/rate-limit-helpers" import { SqlClient } from "effect/sql/SqlClient" import { channelOrganization, emitMessageEvent } from "../../worker/objects/channel/message-events" +import { deleteAgentMark, markAgentWrite } from "../../worker/objects/channel/agent-marks" import { BotGatewayEffects } from "../../worker/objects/effects/bot-gateway-effects" import { enqueueEffect } from "../../worker/objects/effects/registry" import { StorageEffects } from "../../worker/objects/effects/storage-effects" @@ -121,6 +122,7 @@ export const MessageRpcLive = MessageRpcs.toLayer( createdMessage, htmlRenderIdsOf(createdMessage.embeds), ) + yield* markAgentWrite(createdMessage) yield* emitMessageEvent({ _tag: "MessageCreated", message: createdMessage }) const txid = yield* generateTransactionId() @@ -157,6 +159,7 @@ export const MessageRpcLive = MessageRpcs.toLayer( [...before].filter((renderId) => !after.has(renderId)), ) } + yield* markAgentWrite(updatedMessage) yield* emitMessageEvent({ _tag: "MessageUpdated", message: updatedMessage }) const txid = yield* generateTransactionId() @@ -177,6 +180,7 @@ export const MessageRpcLive = MessageRpcs.toLayer( yield* messagePolicy.canDelete(id) const existing = yield* messageRepo.findById(id) yield* messageRepo.deleteById(id) + yield* deleteAgentMark(id) // Its reactions and pins go with it (no foreign keys in the object's SQLite). yield* db.run( SQLite.deleteFrom(schema.messageReactionsTable).where(($) => [ diff --git a/apps/backend/src/services/agent-access.ts b/apps/backend/src/services/agent-access.ts new file mode 100644 index 000000000..f9d3f9a63 --- /dev/null +++ b/apps/backend/src/services/agent-access.ts @@ -0,0 +1,391 @@ +/** + * Agent access over the directory (D1): Hazel as an OAuth 2.1 authorization server for MCP clients + * (dynamic registration, PKCE S256 authorization codes, rotating refresh tokens), personal access + * tokens, and resolving a bearer token to the user and grant it acts for (`routes/mcp.ts`). + * + * Only SHA-256 hashes of codes and tokens are stored. D1 has no transactions, so each step is one + * statement and a code is claimed (`redeemedAt`) before anything is issued for it: a replayed code + * finds it claimed. A half-finished exchange leaves at most a grant without tokens, which the user + * sees and can revoke. + */ +import { SQLite, schema } from "@hazel/db" +import { type AgentScope, parseAgentScopes } from "@hazel/domain/http" +import type { AgentClientId, AgentGrantId, UserId } from "@hazel/schema" +import { Context, Effect, Layer, Option, Schema } from "effect" +import { Base64Url, Hex } from "effect/encoding" +import { Directory } from "./directory" + +/** How long an access token lives; clients refresh after. */ +export const ACCESS_TOKEN_TTL_MS = 60 * 60 * 1000 +/** How long a refresh token lives unused; each refresh issues a new one. */ +export const REFRESH_TOKEN_TTL_MS = 90 * 24 * 60 * 60 * 1000 +/** How long an authorization code may wait for its exchange. */ +export const AUTH_CODE_TTL_MS = 5 * 60 * 1000 +/** Throttle for `lastUsedAt` writes: at most one per grant per this interval. */ +const LAST_USED_RESOLUTION_MS = 5 * 60 * 1000 + +const PREFIX = { access: "hzl_oat_", refresh: "hzl_ort_", personal: "hzl_pat_", code: "hzl_code_" } as const + +const randomSecret = () => { + const bytes = new Uint8Array(32) + crypto.getRandomValues(bytes) + return Base64Url.encode(bytes) +} + +export const sha256Hex = (value: string) => + Effect.promise(async () => { + const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value)) + return Hex.encode(new Uint8Array(digest)) + }) + +const sha256Base64Url = (value: string) => + Effect.promise(async () => { + const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value)) + return Base64Url.encode(new Uint8Array(digest)) + }) + +const newSecret = (kind: keyof typeof PREFIX) => + Effect.gen(function* () { + const value = `${PREFIX[kind]}${randomSecret()}` + return { value, hash: yield* sha256Hex(value) } + }) + +/** An agent token is one of ours by its prefix (others go to the session/bot paths). */ +export const isAgentToken = (token: string) => + token.startsWith(PREFIX.access) || token.startsWith(PREFIX.personal) + +/** An OAuth error for the token endpoint (RFC 6749 §5.2). */ +export class OAuthProtocolError extends Schema.TaggedError()("OAuthProtocolError", { + error: Schema.String, + description: Schema.String, +}) {} + +const invalidGrant = (description: string) => new OAuthProtocolError({ error: "invalid_grant", description }) + +const isLoopback = (url: URL) => + url.protocol === "http:" && + (url.hostname === "127.0.0.1" || url.hostname === "[::1]" || url.hostname === "localhost") + +const FORBIDDEN_SCHEMES = new Set(["javascript:", "data:", "file:", "blob:", "vbscript:"]) + +/** + * A redirect URI a client may register: https, http on loopback (CLI clients), or a native app's + * private-use scheme (`cursor://…`), never a script scheme, never a fragment. + */ +export const isAllowedRedirectUri = (uri: string) => { + try { + const url = new URL(uri) + if (url.hash !== "") return false + if (url.protocol === "https:") return true + if (url.protocol === "http:") return isLoopback(url) + return /^[a-z][a-z0-9+.-]*:$/.test(url.protocol) && !FORBIDDEN_SCHEMES.has(url.protocol) + } catch { + return false + } +} + +/** RFC 8252 §7.3: a loopback redirect matches whatever port the client opened. */ +export const redirectMatches = (registered: string, given: string) => { + if (registered === given) return true + try { + const a = new URL(registered) + const b = new URL(given) + return ( + isLoopback(a) && + isLoopback(b) && + a.hostname === b.hostname && + a.pathname === b.pathname && + a.search === b.search + ) + } catch { + return false + } +} + +export interface IssuedTokens { + readonly accessToken: string + readonly refreshToken: string + readonly expiresInSeconds: number + readonly scopes: ReadonlyArray +} + +/** Who a verified agent token acts for. */ +export interface AgentPrincipal { + readonly userId: UserId + readonly grantId: AgentGrantId + readonly name: string + readonly scopes: ReadonlyArray +} + +const toScopes = (scopes: ReadonlyArray) => parseAgentScopes(scopes.join(" ")) + +export class AgentAccess extends Context.Service()("@hazel/backend/AgentAccess", { + make: Effect.gen(function* () { + const directory = yield* Directory + const db = directory.db + + const client = (clientId: AgentClientId) => + db.first( + SQLite.from(schema.agentClientsTable) + .select() + .where(($) => [$.id.eq(clientId)]), + ) + + /** The client, when `redirectUri` is one it registered. */ + const clientFor = (clientId: AgentClientId, redirectUri: string) => + client(clientId).pipe( + Effect.map( + Option.filter((row) => row.redirectUris.some((uri) => redirectMatches(uri, redirectUri))), + ), + ) + + const registerClient = (input: { + readonly clientName: string + readonly redirectUris: ReadonlyArray + readonly clientUri: string | null + readonly logoUri: string | null + }) => + db + .run( + SQLite.insertInto(schema.agentClientsTable) + .values({ + clientName: input.clientName, + redirectUris: [...input.redirectUris], + clientUri: input.clientUri, + logoUri: input.logoUri, + }) + .returning("id", "createdAt"), + ) + .pipe(Effect.map((rows) => rows[0]!)) + + const createCode = (input: { + readonly clientId: AgentClientId + readonly userId: UserId + readonly redirectUri: string + readonly codeChallenge: string + readonly scopes: ReadonlyArray + }) => + Effect.gen(function* () { + const code = yield* newSecret("code") + yield* db.run( + SQLite.insertInto(schema.agentAuthCodesTable).values({ + codeHash: code.hash, + clientId: input.clientId, + userId: input.userId, + redirectUri: input.redirectUri, + codeChallenge: input.codeChallenge, + scopes: [...input.scopes], + expiresAt: new Date(Date.now() + AUTH_CODE_TTL_MS), + }), + ) + return code.value + }) + + const issueTokens = (grantId: AgentGrantId, scopes: ReadonlyArray) => + Effect.gen(function* () { + const access = yield* newSecret("access") + const refresh = yield* newSecret("refresh") + const now = Date.now() + yield* db.run( + SQLite.insertInto(schema.agentTokensTable).values({ + tokenHash: access.hash, + grantId, + kind: "access", + expiresAt: new Date(now + ACCESS_TOKEN_TTL_MS), + }), + ) + yield* db.run( + SQLite.insertInto(schema.agentTokensTable).values({ + tokenHash: refresh.hash, + grantId, + kind: "refresh", + expiresAt: new Date(now + REFRESH_TOKEN_TTL_MS), + }), + ) + return { + accessToken: access.value, + refreshToken: refresh.value, + expiresInSeconds: ACCESS_TOKEN_TTL_MS / 1000, + scopes, + } satisfies IssuedTokens + }) + + /** `grant_type=authorization_code`: claim the code, check it, open a grant and issue tokens. */ + const exchangeCode = (input: { + readonly code: string + readonly clientId: string + readonly redirectUri: string + readonly codeVerifier: string + }) => + Effect.gen(function* () { + const codeHash = yield* sha256Hex(input.code) + const claimed = yield* db.first( + SQLite.update(schema.agentAuthCodesTable) + .set({ redeemedAt: new Date() }) + .where(($) => [ + $.codeHash.eq(codeHash), + $.redeemedAt.isNull(), + $.expiresAt.gt(new Date()), + ]) + .returning("clientId", "userId", "redirectUri", "codeChallenge", "scopes"), + ) + if (Option.isNone(claimed)) return yield* invalidGrant("The code is invalid, expired or used") + const code = claimed.value + if (code.clientId !== input.clientId) + return yield* invalidGrant("The code belongs to another client") + if (code.redirectUri !== input.redirectUri) + return yield* invalidGrant("redirect_uri does not match") + if ((yield* sha256Base64Url(input.codeVerifier)) !== code.codeChallenge) + return yield* invalidGrant("code_verifier does not match") + + const registered = yield* client(code.clientId) + if (Option.isNone(registered)) return yield* invalidGrant("The client is gone") + const scopes = toScopes(code.scopes) + const grant = yield* db + .run( + SQLite.insertInto(schema.agentGrantsTable) + .values({ + userId: code.userId, + kind: "oauth", + clientId: code.clientId, + name: registered.value.clientName, + scopes: [...scopes], + }) + .returning("id"), + ) + .pipe(Effect.map((rows) => rows[0]!)) + return yield* issueTokens(grant.id, scopes) + }).pipe(Effect.withSpan("AgentAccess.exchangeCode")) + + const liveGrant = (grantId: AgentGrantId) => + db.first( + SQLite.from(schema.agentGrantsTable) + .select() + .where(($) => [$.id.eq(grantId), $.revokedAt.isNull()]), + ) + + /** `grant_type=refresh_token`: rotate; the old refresh token is spent. */ + const refresh = (input: { readonly refreshToken: string; readonly clientId: string }) => + Effect.gen(function* () { + const tokenHash = yield* sha256Hex(input.refreshToken) + const spent = yield* db.first( + SQLite.deleteFrom(schema.agentTokensTable) + .where(($) => [ + $.tokenHash.eq(tokenHash), + $.kind.eq("refresh"), + $.expiresAt.gt(new Date()), + ]) + .returning("grantId"), + ) + if (Option.isNone(spent)) + return yield* invalidGrant("The refresh token is invalid or expired") + const grant = yield* liveGrant(spent.value.grantId) + if (Option.isNone(grant) || grant.value.clientId !== input.clientId) + return yield* invalidGrant("The grant was revoked") + return yield* issueTokens(grant.value.id, toScopes(grant.value.scopes)) + }).pipe(Effect.withSpan("AgentAccess.refresh")) + + /** The user and grant a bearer token acts for: a live access or personal token of a live grant. */ + const authenticate = (token: string) => + Effect.gen(function* () { + if (!isAgentToken(token)) return Option.none() + const tokenHash = yield* sha256Hex(token) + const row = yield* db.first( + SQLite.from(schema.agentTokensTable) + .select() + .where(($) => [$.tokenHash.eq(tokenHash)]), + ) + if (Option.isNone(row) || row.value.kind === "refresh") return Option.none() + if (row.value.expiresAt !== null && row.value.expiresAt.getTime() <= Date.now()) + return Option.none() + const grant = yield* liveGrant(row.value.grantId) + if (Option.isNone(grant)) return Option.none() + const lastUsed = grant.value.lastUsedAt?.getTime() ?? 0 + if (Date.now() - lastUsed > LAST_USED_RESOLUTION_MS) { + yield* db + .run( + SQLite.update(schema.agentGrantsTable) + .set({ lastUsedAt: new Date() }) + .where(($) => [$.id.eq(grant.value.id)]), + ) + .pipe(Effect.ignore) + } + return Option.some({ + userId: grant.value.userId, + grantId: grant.value.id, + name: grant.value.name, + scopes: toScopes(grant.value.scopes), + }) + }).pipe(Effect.withSpan("AgentAccess.authenticate")) + + const listGrants = (userId: UserId) => + db.run( + SQLite.from(schema.agentGrantsTable) + .select() + .where(($) => [$.userId.eq(userId), $.revokedAt.isNull()]) + .orderBy(($) => [[$.createdAt, "desc"]]), + ) + + /** Revoke the user's grant and drop its tokens; false when it is not theirs or already gone. */ + const revokeGrant = (userId: UserId, grantId: AgentGrantId) => + Effect.gen(function* () { + const revoked = yield* db.run( + SQLite.update(schema.agentGrantsTable) + .set({ revokedAt: new Date() }) + .where(($) => [$.id.eq(grantId), $.userId.eq(userId), $.revokedAt.isNull()]) + .returning("id"), + ) + if (revoked.length === 0) return false + yield* db.run( + SQLite.deleteFrom(schema.agentTokensTable).where(($) => [$.grantId.eq(grantId)]), + ) + return true + }) + + const createPersonalToken = (input: { + readonly userId: UserId + readonly name: string + readonly scopes: ReadonlyArray + }) => + Effect.gen(function* () { + const grant = yield* db + .run( + SQLite.insertInto(schema.agentGrantsTable) + .values({ + userId: input.userId, + kind: "token", + clientId: null, + name: input.name, + scopes: [...input.scopes], + }) + .returning(), + ) + .pipe(Effect.map((rows) => rows[0]!)) + const secret = yield* newSecret("personal") + yield* db.run( + SQLite.insertInto(schema.agentTokensTable).values({ + tokenHash: secret.hash, + grantId: grant.id, + kind: "personal", + expiresAt: null, + }), + ) + return { grant, token: secret.value } + }) + + return { + client, + clientFor, + registerClient, + createCode, + exchangeCode, + refresh, + authenticate, + listGrants, + revokeGrant, + createPersonalToken, + } as const + }), +}) { + static readonly layer = Layer.effect(this, this.make) +} diff --git a/apps/backend/src/worker/http.ts b/apps/backend/src/worker/http.ts index 24c82b47e..8cd71f342 100644 --- a/apps/backend/src/worker/http.ts +++ b/apps/backend/src/worker/http.ts @@ -16,6 +16,9 @@ import { workerObjectStubs } from "./objects/stubs" import { makeSyncRoute } from "./sync-route" import { makeLiveRoute } from "./live-route" import { HtmlRenderRoute } from "./html-render-route" +import { AgentOAuthRoutes } from "../routes/agent-oauth" +import { McpRoute } from "../routes/mcp" +import { AgentAccess } from "../services/agent-access" import { workerLiveObjectStubs } from "./live/message-live-object" import type { BotGatewayNamespace } from "../services/bot-gateway-transport" import { directoryBinding, requestPlatformLive } from "./platform" @@ -46,7 +49,13 @@ export const buildApp = ( // `AppServicesLive`'s error and requirement channels to `unknown`. makeRoutes( workerRpcServer(env), - Layer.mergeAll(makeSyncRoute(env), makeLiveRoute(env), HtmlRenderRoute), + Layer.mergeAll( + makeSyncRoute(env), + makeLiveRoute(env), + HtmlRenderRoute, + AgentOAuthRoutes, + McpRoute, + ), ).pipe( Layer.provide(AppAuthorizationLive), Layer.provide(AppServicesLive), @@ -57,6 +66,8 @@ export const buildApp = ( // HTTP routes that reach objects or the directory (presence, bot commands). Layer.provideMerge(workerObjectStubs(env)), Layer.provideMerge(workerLiveObjectStubs(env)), + // Agent access (OAuth for MCP clients, personal tokens) over the directory. + Layer.provideMerge(AgentAccess.layer), Layer.provideMerge(Layer.suspend(() => Directory.layerD1(directoryBinding(env)))), ) as unknown as Layer.Layer, ), diff --git a/apps/backend/src/worker/objects/agent-marks.test.ts b/apps/backend/src/worker/objects/agent-marks.test.ts new file mode 100644 index 000000000..bc3a78099 --- /dev/null +++ b/apps/backend/src/worker/objects/agent-marks.test.ts @@ -0,0 +1,285 @@ +/** + * Agent marks on the objects (node SQLite): a message written through Hazel's MCP server (the + * call carries `CurrentAgent`) gets a `message_agent_marks` row in the same write, streamed only + * to viewers of the author's organization: in a Connect channel the other org's viewers get the + * message without the mark. The user's own messages carry none; deleting drops the mark. + */ +import { SQLite, schema } from "@hazel/db" +import { CurrentUser } from "@hazel/domain" +import type { + AgentGrantId, + ChannelId, + ConnectInviteId, + MessageId, + OrganizationId, + UserId, +} from "@hazel/schema" +import { makeFakeSocket, type FakeSocket } from "@hazel/sync-do/testing" +import { Cause, Effect, Exit, type Scope } from "effect" +import { describe, expect, it } from "vitest" +import { decodeExit, encodePayload, type HazelRpcTag, rpcFor } from "../../rpc/dispatch" +import { Directory } from "../../services/directory" +import { channelTarget, orgTarget } from "./kinds" +import { type AgentActor, encodeInvokePrincipal } from "./principal" +import { makeTestObjects, type TestObject, type TestObjects } from "./testing" + +const uuid = () => crypto.randomUUID() + +const userOf = (id: string) => + new CurrentUser.Schema({ + id: id as UserId, + role: "member", + email: `${id}@example.com`, + isOnboarded: true, + timezone: null, + settings: null, + }) + +const AGENT: AgentActor = { grantId: uuid() as AgentGrantId, name: "Claude" } + +const call = ( + object: TestObject, + objectId: string, + tag: HazelRpcTag, + payload: unknown, + user: string, + agent: AgentActor | null = null, +) => + Effect.gen(function* () { + const rpc = yield* rpcFor(tag) + const response = yield* object.invoke({ + objectId, + tag, + payload: yield* encodePayload(rpc, payload), + principal: yield* encodeInvokePrincipal({ user: userOf(user), botScopes: null, agent }), + }) + return yield* decodeExit(rpc, structuredClone(response).exit) + }) + +const ok = (exit: Exit.Exit) => { + if (Exit.isFailure(exit)) throw new Error(Cause.pretty(exit.cause)) + return exit.value as any +} + +const run = (effect: Effect.Effect) => + Effect.runPromise(Effect.scoped(effect) as Effect.Effect) + +const directoryUser = (objects: TestObjects, id: UserId, firstName: string) => + Effect.flatMap(Directory, (directory) => + directory.db.run( + SQLite.insertInto(schema.usersTable).values({ + id, + externalId: `ext-${id}`, + email: `${id}@example.com`, + firstName, + lastName: "Last", + }), + ), + ).pipe(Effect.provideContext(objects.directory), Effect.orDie) + +const rows = (object: TestObject, query: string, ...params: Array) => + object.storage.db.prepare(query).all(...params) as Array + +const upserts = (socket: FakeSocket, table: string) => + socket + .frames() + .filter((frame) => frame._tag === "Rows" && frame.table === table) + .flatMap((frame) => frame.upserts as Array>) + +const deletes = (socket: FakeSocket, table: string) => + socket + .frames() + .filter((frame) => frame._tag === "Rows" && frame.table === table) + .flatMap((frame) => (frame.deletes ?? []) as Array) + +const messagePayload = (channelId: ChannelId, authorId: UserId, content: string) => ({ + channelId, + content, + embeds: null, + replyToMessageId: null, + threadChannelId: null, + authorId, + deletedAt: null, +}) + +const makeOrg = (objects: TestObjects, name: string, slug: string, owner: UserId) => + Effect.gen(function* () { + const id = uuid() as OrganizationId + const object = yield* objects.get(orgTarget(id)) + ok( + yield* call( + object, + id, + "organization.create", + { name, slug, logoUrl: null, settings: null, isPublic: false }, + owner, + ), + ) + return { id, object } + }) + +/** Org A (a1) shares a private channel with org B (b1). */ +const makeSharedChannel = Effect.gen(function* () { + const objects = yield* makeTestObjects + const [a1, b1] = [uuid(), uuid()] as Array + yield* directoryUser(objects, a1, "Ada") + yield* directoryUser(objects, b1, "Bea") + const a = yield* makeOrg(objects, "Acme", "acme", a1) + const b = yield* makeOrg(objects, "Beta", "beta", b1) + const hostChannelId = uuid() as ChannelId + ok( + yield* call( + a.object, + a.id, + "channel.create", + { + id: hostChannelId, + name: "partners", + icon: null, + type: "private", + organizationId: a.id, + parentChannelId: null, + sectionId: null, + }, + a1, + ), + ) + const created = ok( + yield* call( + a.object, + a.id, + "connectShare.invite.create", + { channelId: hostChannelId, target: { kind: "slug", value: "beta" }, allowGuestMemberAdds: true }, + a1, + ), + ) + ok( + yield* call( + b.object, + b.id, + "connectShare.invite.accept", + { inviteId: created.data.id as ConnectInviteId, guestOrganizationId: b.id }, + b1, + ), + ) + const host = yield* objects.get(channelTarget(hostChannelId)) + return { a, b, a1, b1, hostChannelId, host } +}) + +describe("agent marks", () => { + it("marks an agent's message for the author's org only, not for Connect viewers", () => + run( + Effect.gen(function* () { + const { a, a1, b1, hostChannelId, host } = yield* makeSharedChannel + const a1Socket = makeFakeSocket() + const b1Socket = makeFakeSocket() + expect(yield* host.adopt(a1Socket, { userId: a1, expiresAt: null })).toBe("accepted") + expect(yield* host.adopt(b1Socket, { userId: b1, expiresAt: null })).toBe("accepted") + yield* host.onMessage(a1Socket, JSON.stringify({ _tag: "Hello", since: null })) + yield* host.onMessage(b1Socket, JSON.stringify({ _tag: "Hello", since: null })) + a1Socket.clear() + b1Socket.clear() + + // The user's own message: no mark. + ok( + yield* call( + host, + hostChannelId, + "message.create", + messagePayload(hostChannelId, a1, "by hand"), + a1, + ), + ) + expect(rows(host, `SELECT id FROM message_agent_marks`)).toEqual([]) + + // Through the agent: marked in the same write, with the author's org. + const sent = ok( + yield* call( + host, + hostChannelId, + "message.create", + messagePayload(hostChannelId, a1, "drafted by Claude"), + a1, + AGENT, + ), + ) + const messageId = sent.data.id as MessageId + expect( + rows( + host, + `SELECT id, organizationId, authorId, grantId, agentName FROM message_agent_marks`, + ), + ).toEqual([ + { + id: messageId, + organizationId: a.id, + authorId: a1, + grantId: AGENT.grantId, + agentName: "Claude", + }, + ]) + + // Both see the message; only a1 (Acme) sees the mark. + expect(upserts(a1Socket, "messages").map((row) => row.content)).toEqual([ + "by hand", + "drafted by Claude", + ]) + expect(upserts(b1Socket, "messages").map((row) => row.content)).toEqual([ + "by hand", + "drafted by Claude", + ]) + expect(upserts(a1Socket, "message_agent_marks").map((row) => row.id)).toEqual([messageId]) + expect(upserts(b1Socket, "message_agent_marks")).toEqual([]) + + // A fresh snapshot agrees. + const b1Again = makeFakeSocket() + expect(yield* host.adopt(b1Again, { userId: b1, expiresAt: null })).toBe("accepted") + yield* host.onMessage(b1Again, JSON.stringify({ _tag: "Hello", since: null })) + expect(upserts(b1Again, "messages").length).toBe(2) + expect(upserts(b1Again, "message_agent_marks")).toEqual([]) + + // Deleting the message drops its mark. + a1Socket.clear() + ok( + yield* call( + host, + hostChannelId, + "message.delete", + { id: messageId, channelId: hostChannelId }, + a1, + ), + ) + expect(rows(host, `SELECT id FROM message_agent_marks`)).toEqual([]) + expect(deletes(a1Socket, "message_agent_marks").length).toBe(1) + }), + )) + + it("an agent's edit marks a message the user wrote", () => + run( + Effect.gen(function* () { + const { a1, hostChannelId, host } = yield* makeSharedChannel + const sent = ok( + yield* call( + host, + hostChannelId, + "message.create", + messagePayload(hostChannelId, a1, "typo"), + a1, + ), + ) + ok( + yield* call( + host, + hostChannelId, + "message.update", + { id: sent.data.id, channelId: hostChannelId, content: "fixed" }, + a1, + AGENT, + ), + ) + expect(rows(host, `SELECT id, agentName FROM message_agent_marks`)).toEqual([ + { id: sent.data.id, agentName: "Claude" }, + ]) + }), + )) +}) diff --git a/apps/backend/src/worker/objects/call-receivers.ts b/apps/backend/src/worker/objects/call-receivers.ts index e3fe7eb7e..92669c419 100644 --- a/apps/backend/src/worker/objects/call-receivers.ts +++ b/apps/backend/src/worker/objects/call-receivers.ts @@ -17,7 +17,16 @@ import type { IntegrationTokenService } from "../../services/integration-token-s import type { IntegrationBotService } from "../../services/integrations/integration-bot-service" import type { WebhookBotService } from "../../services/webhook-bot-service" import { type AnyObjectCall, type CallRequest, type CallResponse, exitCodec, payloadCodec } from "./calls" -import { listMessages, ListMessagesCall, messageThread, MessageThreadCall } from "./channel/api-messages" +import { + listMessages, + ListMessagesCall, + messagesByIds, + MessagesByIdsCall, + messageThread, + MessageThreadCall, +} from "./channel/api-messages" +import { agentChannels, AgentChannelsCall } from "./org/agent" +import { agentNotifications, AgentNotificationsCall } from "./user/agent" import { liveAccess, LiveAccessCall } from "./channel/live-access" import { bootstrap, @@ -125,6 +134,7 @@ export const callReceivers: Record> = receiver(GitHubInstallationCall, githubInstallation), receiver(OrganizationProfileCall, () => organizationProfile()), receiver(ListChannelsCall, listChannels), + receiver(AgentChannelsCall, agentChannels), receiver(IsOrgAdminCall, isOrgAdmin), receiver(RedeemBotInstallGrantCall, redeemBotInstallGrant), receiver(BotInstallRegionCall, botInstallRegion), @@ -136,8 +146,9 @@ export const callReceivers: Record> = receiver(ListMessagesCall, listMessages), receiver(MessageThreadCall, messageThread), receiver(LiveAccessCall, liveAccess), + receiver(MessagesByIdsCall, messagesByIds), ]), - user: byName([]), + user: byName([receiver(AgentNotificationsCall, agentNotifications)]), // Its own bootstrap and alarm work, and webhook deliveries (`docs/customers/tech-design.md` §5). customers: byName([ receiver(CustomersBootstrapCall, bootstrap), diff --git a/apps/backend/src/worker/objects/channel/agent-marks.ts b/apps/backend/src/worker/objects/channel/agent-marks.ts new file mode 100644 index 000000000..914cbf057 --- /dev/null +++ b/apps/backend/src/worker/objects/channel/agent-marks.ts @@ -0,0 +1,55 @@ +/** + * `message_agent_marks`: which messages an agent wrote for their author (Hazel's MCP server). The + * message handlers call these inside their write's transaction, so a mark commits with its message. + * The mark names the author's organization (their `channel_viewers` row, which in a Connect channel + * differs from the host's), and the sync source streams it only to viewers of that organization. + */ +import { Database, SQLite, schema } from "@hazel/db" +import type { MessageId } from "@hazel/schema" +import { Effect, Option } from "effect" +import { CurrentAgent } from "../principal" +import { channelOrganization, type MessageRow } from "./message-events" + +/** Mark `message` as written by the current agent; nothing for the user's own calls. */ +export const markAgentWrite = (message: MessageRow) => + Effect.gen(function* () { + const agent = yield* Effect.serviceOption(CurrentAgent) + if (Option.isNone(agent)) return + const db = yield* Database.Database + const viewer = yield* db.first( + SQLite.from(schema.channelViewersTable) + .select() + .where(($) => [$.userId.eq(message.authorId)]), + ) + const organizationId = Option.isSome(viewer) + ? Option.some(viewer.value.organizationId) + : yield* channelOrganization + if (Option.isNone(organizationId)) { + return yield* Effect.logWarning("Agent write in a channel with no organization", { + messageId: message.id, + }) + } + const row = { + id: message.id, + channelId: message.channelId, + organizationId: organizationId.value, + authorId: message.authorId, + grantId: agent.value.grantId, + agentName: agent.value.name, + } + yield* db.run( + SQLite.insertInto(schema.messageAgentMarksTable) + .values(row) + .onConflictDoUpdate({ + target: ["id"], + set: { grantId: row.grantId, agentName: row.agentName, updatedAt: new Date() }, + }), + ) + }).pipe(Effect.withSpan("AgentMarks.markWrite")) + +/** Drop a deleted message's mark. */ +export const deleteAgentMark = (messageId: MessageId) => + Effect.gen(function* () { + const db = yield* Database.Database + yield* db.run(SQLite.deleteFrom(schema.messageAgentMarksTable).where(($) => [$.id.eq(messageId)])) + }) diff --git a/apps/backend/src/worker/objects/channel/api-messages.ts b/apps/backend/src/worker/objects/channel/api-messages.ts index 3baf68c97..2928542d3 100644 --- a/apps/backend/src/worker/objects/channel/api-messages.ts +++ b/apps/backend/src/worker/objects/channel/api-messages.ts @@ -112,3 +112,39 @@ export const messageThread = Effect.fn("ChannelObject.messageThread")( }, Effect.catchTag("DatabaseError", (error) => Effect.die(error)), ) + +/** The most messages one `channel.messagesByIds` returns (DO SQLite binds at most 100 parameters). */ +export const MESSAGES_BY_IDS_MAX = 50 + +export const MessagesByIdsCall = defineCall("channel.messagesByIds", "channel", { + payload: Schema.Struct({ userId: UserId, ids: Schema.Array(MessageId) }), + success: Schema.Array(Message.Schema), + error: UnauthorizedError, +}) + +/** Messages by id, for a viewer of the channel (the MCP server's notifications and lookups). */ +export const messagesByIds = Effect.fn("ChannelObject.messagesByIds")( + function* (payload: typeof MessagesByIdsCall.payload.Type) { + const db = yield* Database.Database + const viewer = yield* db.first( + SQLite.from(schema.channelViewersTable) + .select("userId") + .where(($) => [$.userId.eq(payload.userId)]) + .limit(1), + ) + if (Option.isNone(viewer)) { + return yield* new UnauthorizedError({ + message: "You can't read this channel", + detail: "messagesByIds", + }) + } + const ids = payload.ids.slice(0, MESSAGES_BY_IDS_MAX) + if (ids.length === 0) return [] + return yield* db.run( + SQLite.from(schema.messagesTable) + .select() + .where(($) => [$.id.in_(...ids), $.deletedAt.isNull()]), + ) + }, + Effect.catchTag("DatabaseError", (error) => Effect.die(error)), +) diff --git a/apps/backend/src/worker/objects/org/agent.ts b/apps/backend/src/worker/objects/org/agent.ts new file mode 100644 index 000000000..7332f0bf1 --- /dev/null +++ b/apps/backend/src/worker/objects/org/agent.ts @@ -0,0 +1,112 @@ +/** + * What Hazel's MCP server (`routes/mcp.ts`) reads of an `OrgObject` for an agent acting as a user: + * the channels the user can open here (their `channel_access`, threads aside), with unread counts, + * and for direct messages who else is in them. + */ +import { Database, SQLite, schema } from "@hazel/db" +import { UnauthorizedError } from "@hazel/domain" +import { ChannelId, UserId } from "@hazel/schema" +import { Effect, Option, Schema } from "effect" +import { defineCall } from "../calls" +import { requireOrganizationId } from "./integrations" + +export const AgentChannel = Schema.Struct({ + id: ChannelId, + name: Schema.String, + type: Schema.Literals(["public", "private", "direct", "single"]), + unreadCount: Schema.Number, + isMuted: Schema.Boolean, + /** For direct messages: the other members' names. */ + members: Schema.Array(Schema.String), +}) +export type AgentChannel = typeof AgentChannel.Type + +export const AgentChannelsCall = defineCall("org.agentChannels", "org", { + payload: Schema.Struct({ userId: UserId }), + success: Schema.Array(AgentChannel), + error: UnauthorizedError, +}) + +const DmMemberRow = Schema.Struct({ + channelId: Schema.String, + firstName: Schema.String, + lastName: Schema.String, +}) + +export const agentChannels = Effect.fn("OrgObject.agentChannels")( + function* (payload: typeof AgentChannelsCall.payload.Type) { + const organizationId = yield* requireOrganizationId + const db = yield* Database.Database + const member = yield* db.first( + SQLite.from(schema.organizationMembersTable) + .select("id") + .where(($) => [ + $.organizationId.eq(organizationId), + $.userId.eq(payload.userId), + $.deletedAt.isNull(), + ]) + .limit(1), + ) + if (Option.isNone(member)) { + return yield* new UnauthorizedError({ + message: "You are not a member of this organization", + detail: `organizationId=${organizationId}`, + }) + } + // Joins, not `IN` lists: a Durable Object binds at most 100 parameters. + const channels = yield* db.run( + SQLite.from(schema.channelAccessTable, "ca") + .innerJoin(schema.channelsTable, "c", (ca, c) => + SQLite.and(c.id.eq(ca.channelId), c.deletedAt.isNull()), + ) + .leftJoin(schema.channelMembersTable, "cm", (ca, cm) => + SQLite.and(cm.channelId.eq(ca.channelId), cm.userId.eq(ca.userId), cm.deletedAt.isNull()), + ) + .select(($) => ({ + id: $.c.id, + name: $.c.name, + type: $.c.type, + notificationCount: $.cm.notificationCount, + isMuted: $.cm.isMuted, + })) + .where(($) => [ + $.organizationId.eq(organizationId), + $.userId.eq(payload.userId), + $.c.type.in_("public", "private", "direct", "single"), + ]), + ) + const dmMembers = yield* db.query( + Database.sql`SELECT cm."channelId" AS "channelId", u."firstName" AS "firstName", u."lastName" AS "lastName" + FROM "channel_members" cm + JOIN "channels" c ON c."id" = cm."channelId" AND c."type" IN ('direct', 'single') AND c."deletedAt" IS NULL + JOIN "channel_access" ca ON ca."channelId" = cm."channelId" AND ca."userId" = ${payload.userId} + JOIN "users" u ON u."id" = cm."userId" + WHERE cm."userId" != ${payload.userId} AND cm."deletedAt" IS NULL`, + DmMemberRow, + ) + const membersOf = new Map>() + for (const row of dmMembers) { + const names = membersOf.get(row.channelId) ?? [] + names.push(`${row.firstName} ${row.lastName}`.trim()) + membersOf.set(row.channelId, names) + } + yield* Effect.annotateCurrentSpan({ "org.agent_channels": channels.length }) + return channels + .flatMap((channel) => + channel.type === "thread" + ? [] + : [ + { + id: channel.id, + name: channel.name, + type: channel.type, + unreadCount: channel.notificationCount ?? 0, + isMuted: channel.isMuted ?? false, + members: membersOf.get(channel.id) ?? [], + }, + ], + ) + .sort((a, b) => a.name.localeCompare(b.name)) + }, + Effect.catchTag("DatabaseError", (error) => Effect.die(error)), +) diff --git a/apps/backend/src/worker/objects/principal.ts b/apps/backend/src/worker/objects/principal.ts index 72e855a48..b9e6f3481 100644 --- a/apps/backend/src/worker/objects/principal.ts +++ b/apps/backend/src/worker/objects/principal.ts @@ -4,8 +4,22 @@ */ import { CurrentUser } from "@hazel/domain" import { ApiScope, CurrentBotScopes } from "@hazel/domain/scopes" -import { UserId } from "@hazel/schema" -import { Effect, Option, Schema } from "effect" +import { AgentGrantId, UserId } from "@hazel/schema" +import { Context, Effect, Option, Schema } from "effect" + +/** + * The agent a user's call came through (Hazel's MCP server, `routes/mcp`): the grant and the name + * chat shows. Writes made with it are marked (`message_agent_marks`). Only the api Worker sets it, + * from a verified agent token; a client cannot. + */ +export const AgentActor = Schema.Struct({ + grantId: AgentGrantId, + name: Schema.String, +}) +export type AgentActor = typeof AgentActor.Type + +/** Provided while a call runs for an agent; absent for the user's own calls. */ +export class CurrentAgent extends Context.Service()("CurrentAgent") {} /** * An RPC's principal: the resolved `CurrentUser` (null for the public methods, which carry no @@ -14,6 +28,7 @@ import { Effect, Option, Schema } from "effect" export const InvokePrincipal = Schema.Struct({ user: Schema.NullOr(CurrentUser.Schema), botScopes: Schema.NullOr(Schema.Array(ApiScope)), + agent: Schema.optional(Schema.NullOr(AgentActor)), }) export type InvokePrincipal = typeof InvokePrincipal.Type @@ -29,26 +44,37 @@ export const currentInvokePrincipal = Effect.gen(function* () { const botScopes = yield* Effect.serviceOption(CurrentBotScopes) const scopes = Option.flatten(botScopes) const user = Option.getOrNull(current) + const agent = yield* Effect.serviceOption(CurrentAgent) return { // The bot-token path provides a plain object; the schema encodes only the class. user: user === null || user instanceof CurrentUser.Schema ? user : new CurrentUser.Schema(user), botScopes: Option.isSome(scopes) ? [...scopes.value] : null, + agent: Option.getOrNull(agent), } satisfies InvokePrincipal }) -/** Provide `principal` the way the api's `AuthMiddleware` does: `CurrentUser`, and a bot's scopes. */ +/** + * Provide `principal` the way the api's `AuthMiddleware` does: `CurrentUser`, a bot's scopes, and + * the agent it came through. + */ export const providePrincipal = (principal: InvokePrincipal) => - (effect: Effect.Effect) => - (principal.user === null - ? effect - : effect.pipe(Effect.provideService(CurrentUser.Context, principal.user)) - ).pipe( + (effect: Effect.Effect) => { + const withUser = + principal.user === null + ? effect + : effect.pipe(Effect.provideService(CurrentUser.Context, principal.user)) + const withAgent = + principal.agent === undefined || principal.agent === null + ? withUser + : withUser.pipe(Effect.provideService(CurrentAgent, principal.agent)) + return withAgent.pipe( Effect.provideService( CurrentBotScopes, principal.botScopes === null ? Option.none() : Option.some(new Set(principal.botScopes)), ), ) as Effect.Effect> + } /** * A sync socket's principal, kept small (it rides in the socket attachment, 2 KiB max): the user diff --git a/apps/backend/src/worker/objects/sources/channel-source.ts b/apps/backend/src/worker/objects/sources/channel-source.ts index 5b6a0b371..b82f04eff 100644 --- a/apps/backend/src/worker/objects/sources/channel-source.ts +++ b/apps/backend/src/worker/objects/sources/channel-source.ts @@ -49,12 +49,27 @@ const pins = toViewers(schema.pinnedMessagesTable, false) const attachments = toViewers(schema.attachmentsTable, true) const messageLinks = toViewers(schema.chatSyncMessageLinksTable, true) +/** + * Agent marks go only to viewers of the author's organization: in a Connect channel, viewers from + * the other organizations see the message without it. + */ +const agentMarks = { + table: schema.messageAgentMarksTable, + visible: (p, $) => [ + SQLite.sql + .cond`EXISTS (SELECT 1 FROM "channel_viewers" v WHERE v."userId" = ${p.userId} AND v."organizationId" = ${$.organizationId!})`, + ], + dependsOn: ["channel_viewers"], + affectedPrincipals: userIdsOf, +} satisfies SyncTableSpec + export const channelSyncTables: ReadonlyArray> = [ messages, reactions, pins, attachments, messageLinks, + agentMarks, toViewers(schema.typingIndicatorsTable, false), ] @@ -64,6 +79,7 @@ const dependents = [ { spec: pins, column: "messageId" }, { spec: attachments, column: "messageId" }, { spec: messageLinks, column: "hazelMessageId" }, + { spec: agentMarks, column: "id" }, ] as const /** Strictly older than `cursor` in `(createdAt, id)` order. */ diff --git a/apps/backend/src/worker/objects/user/agent.ts b/apps/backend/src/worker/objects/user/agent.ts new file mode 100644 index 000000000..f21992897 --- /dev/null +++ b/apps/backend/src/worker/objects/user/agent.ts @@ -0,0 +1,50 @@ +/** + * What Hazel's MCP server (`routes/mcp.ts`) reads of a `UserObject` for an agent acting as its + * user: their notifications (mentions, replies, direct messages), newest first. + */ +import { Database, SQLite, schema } from "@hazel/db" +import { ChannelId, MessageId, NotificationId } from "@hazel/schema" +import { Effect, Schema } from "effect" +import { defineCall } from "../calls" + +export const AgentNotification = Schema.Struct({ + id: NotificationId, + channelId: Schema.NullOr(ChannelId), + messageId: Schema.NullOr(MessageId), + reason: Schema.NullOr(Schema.String), + createdAt: Schema.Date, + read: Schema.Boolean, +}) +export type AgentNotification = typeof AgentNotification.Type + +export const AgentNotificationsCall = defineCall("user.agentNotifications", "user", { + payload: Schema.Struct({ unreadOnly: Schema.Boolean, limit: Schema.Number }), + success: Schema.Array(AgentNotification), + error: Schema.Never, +}) + +export const agentNotifications = Effect.fn("UserObject.agentNotifications")( + function* (payload: typeof AgentNotificationsCall.payload.Type) { + const db = yield* Database.Database + const rows = yield* db.run( + SQLite.from(schema.notificationsTable) + .select() + .where(($) => [ + payload.unreadOnly ? $.readAt.isNull() : undefined, + $.resourceType.eq("message"), + ]) + .orderBy(($) => [[$.createdAt, "desc"]]) + .limit(Math.max(1, Math.min(payload.limit, 100))), + ) + return rows.map((row) => ({ + id: row.id, + channelId: + row.targetedResourceType === "channel" ? (row.targetedResourceId as ChannelId | null) : null, + messageId: row.resourceId as MessageId | null, + reason: row.reason, + createdAt: row.createdAt, + read: row.readAt !== null, + })) + }, + Effect.catchTag("DatabaseError", (error) => Effect.die(error)), +) diff --git a/apps/web-foldkit/src/chat/message/parts.ts b/apps/web-foldkit/src/chat/message/parts.ts index e8017d7c2..82f1923ab 100644 --- a/apps/web-foldkit/src/chat/message/parts.ts +++ b/apps/web-foldkit/src/chat/message/parts.ts @@ -1,7 +1,7 @@ import type { ChildAttribute, Html, HtmlBuilder } from "foldkit/html" import { formatDistanceToNowStrict } from "date-fns" import { cx } from "~/utils/cx" -import { IconChevronRight, IconDiscord, IconPin } from "../../icons" +import { IconChevronRight, IconDiscord, IconPin, IconSparkles } from "../../icons" import { avatar } from "../../ui/avatar" import { badge } from "../../ui/badge" import type { MessageRow, ReplyPreview, ThreadPreview } from "../../page/chat/rows" @@ -16,6 +16,21 @@ export const formatTime = (ms: number) => { return `${pad(date.getHours())}:${pad(date.getMinutes())}` } +/** + * "via ": the message was written by an agent for its author over Hazel's MCP server. Shown + * only to the author's own organization (the mark never syncs elsewhere). + */ +const agentBadge = (h: HtmlBuilder, agentName: string, authorName: string): Html => + h.span( + [ + h.Class( + "inline-flex items-center gap-1 rounded-sm bg-secondary px-1.5 py-0.5 text-xs/4 font-medium text-muted-fg", + ), + h.Attribute("title", `Written by ${agentName}, an AI agent acting for ${authorName}`), + ], + [IconSparkles(h, { className: "size-3" }), `via ${agentName}`], + ) + /** `Message.Header`; `statusEmoji` is the tooltip-wrapped status trigger (or nothing). */ export const headerView = (h: HtmlBuilder, row: MessageRow, statusEmoji: Html): Html => { const { message, author } = row @@ -47,6 +62,7 @@ export const headerView = (h: HtmlBuilder, row: MessageRow, statusEmoji: H : row.isDiscordSynced ? badge(h, { intent: "secondary" }, ["Synced from Discord"]) : h.empty, + row.agentName === null ? h.empty : agentBadge(h, row.agentName, author.displayName), h.span([h.Class("text-muted-fg text-xs")], isEdited ? [time, " (edited)"] : [time]), message.isPinned ? h.span( diff --git a/apps/web-foldkit/src/chat/messages.gallery.ts b/apps/web-foldkit/src/chat/messages.gallery.ts index 256137873..08b8cce00 100644 --- a/apps/web-foldkit/src/chat/messages.gallery.ts +++ b/apps/web-foldkit/src/chat/messages.gallery.ts @@ -108,6 +108,7 @@ const row = (options: { hasAuthor: true, status: null, isDiscordSynced: false, + agentName: null, reply: null, thread: null, attachments: options.attachments ?? [], diff --git a/apps/web-foldkit/src/core/db/collections.ts b/apps/web-foldkit/src/core/db/collections.ts index 533f861a5..345b877e4 100644 --- a/apps/web-foldkit/src/core/db/collections.ts +++ b/apps/web-foldkit/src/core/db/collections.ts @@ -15,6 +15,7 @@ import { IntegrationConnection, JsonDate, Message, + MessageAgentMark, MessageReaction, Notification, Organization, @@ -122,6 +123,8 @@ export const userOrganizationCollection = createEffectCollection( export const organizationCollection = orgCollection("organizations", Organization.Schema) export const messageCollection = channelCollectionOf("messages", Message.Schema) export const messageReactionCollection = channelCollectionOf("message_reactions", MessageReaction.Schema) +/** Messages an agent wrote for their author (the author's organization only). */ +export const messageAgentMarkCollection = channelCollectionOf("message_agent_marks", MessageAgentMark.Schema) export const pinnedMessageCollection = channelCollectionOf("pinned_messages", PinnedMessage.Schema) export const notificationCollection = syncedCollection("notifications", Notification.Schema, userSources) export const userCollection = orgCollection("users", User.Schema) diff --git a/apps/web-foldkit/src/page/chat/channel/model.ts b/apps/web-foldkit/src/page/chat/channel/model.ts index 335c62a2e..f84da7e69 100644 --- a/apps/web-foldkit/src/page/chat/channel/model.ts +++ b/apps/web-foldkit/src/page/chat/channel/model.ts @@ -18,6 +18,7 @@ import { BotInfo, ChannelMemberInfo, CustomEmojiInfo, + AgentMarkInfo, Lookups, PinnedInfo, PresenceInfo, @@ -208,6 +209,7 @@ export const Message = defineMessageUnion({ UpdatedCustomEmojis: { customEmojis: Schema.Array(CustomEmojiInfo) }, UpdatedAttachments: { attachments: Schema.Array(AttachmentInfo) }, UpdatedDiscordSynced: { messageIds: Schema.Array(MessageId) }, + UpdatedAgentMarks: { marks: Schema.Array(AgentMarkInfo) }, UpdatedThreadChannels: { channels: Schema.Array(ThreadChannelInfo) }, UpdatedThreadMessages: { messages: Schema.Array(ThreadMessageInfo) }, UpdatedReplyTargets: { targets: Schema.Array(ReplyTarget) }, diff --git a/apps/web-foldkit/src/page/chat/channel/page.ts b/apps/web-foldkit/src/page/chat/channel/page.ts index b44188cc9..4a57fdf95 100644 --- a/apps/web-foldkit/src/page/chat/channel/page.ts +++ b/apps/web-foldkit/src/page/chat/channel/page.ts @@ -519,6 +519,7 @@ export const update = (model: Model, message: Message, shared: Shared | null = n ), UpdatedAttachments: ({ attachments }) => withLookup(model, "attachments", attachments), UpdatedDiscordSynced: ({ messageIds }) => withLookup(model, "discordSyncedIds", messageIds), + UpdatedAgentMarks: ({ marks }) => withLookup(model, "agentMarks", marks), UpdatedThreadChannels: ({ channels }) => withLookup(model, "threadChannels", channels), UpdatedThreadMessages: ({ messages }) => withLookup(model, "threadMessages", messages), UpdatedReplyTargets: ({ targets }) => withLookup(model, "replyTargets", targets), diff --git a/apps/web-foldkit/src/page/chat/channel/subscription.ts b/apps/web-foldkit/src/page/chat/channel/subscription.ts index c4f3758bd..fed3e9a55 100644 --- a/apps/web-foldkit/src/page/chat/channel/subscription.ts +++ b/apps/web-foldkit/src/page/chat/channel/subscription.ts @@ -16,6 +16,7 @@ import { attachmentsStream, botsStream, customEmojisStream, + agentMarksStream, discordSyncedStream, membersStream, pinnedStream, @@ -198,6 +199,11 @@ const chat = Subscription.make()((entry) => ({ dependenciesToStream: ({ channelId }) => discordSyncedStream(channelId, (messageIds) => Message.UpdatedDiscordSynced({ messageIds })), }), + chatAgentMarks: entry(byChannel, { + modelToDependencies: channelOf, + dependenciesToStream: ({ channelId }) => + agentMarksStream(channelId, (marks) => Message.UpdatedAgentMarks({ marks })), + }), chatThreadChannels: entry( { threadIds: Schema.Array(ChannelId) }, { diff --git a/apps/web-foldkit/src/page/chat/derive.ts b/apps/web-foldkit/src/page/chat/derive.ts index be4119920..9f826900a 100644 --- a/apps/web-foldkit/src/page/chat/derive.ts +++ b/apps/web-foldkit/src/page/chat/derive.ts @@ -52,6 +52,7 @@ export interface DeriveContext { readonly emojiUrls: ReadonlyMap readonly attachmentsByMessage: ReadonlyMap> readonly discordSynced: ReadonlySet + readonly agentNames: ReadonlyMap readonly threadNames: ReadonlyMap readonly threadMessages: ReadonlyMap> readonly replyTargets: ReadonlyMap @@ -105,6 +106,7 @@ export const toDeriveContext = ( emojiUrls: new Map(lookups.customEmojis.map((emoji) => [emoji.name, emoji.imageUrl])), attachmentsByMessage: groupBy(lookups.attachments, (attachment) => attachment.messageId), discordSynced: new Set(lookups.discordSyncedIds), + agentNames: new Map(lookups.agentMarks.map((mark) => [mark.id, mark.agentName])), threadNames: new Map(lookups.threadChannels.map((channel) => [channel.id, channel.name])), threadMessages: groupBy(lookups.threadMessages, (message) => message.channelId), replyTargets: byKey(lookups.replyTargets, (target) => target.id), @@ -344,6 +346,7 @@ export const messageRowData = ( hasAuthor: user !== null, status: statusOf(context, message.authorId), isDiscordSynced: context.discordSynced.has(message.id), + agentName: context.agentNames.get(message.id) ?? null, reply: replyOf(context, message.replyToMessageId), thread: threadOf(context, message.threadChannelId), attachments: context.attachmentsByMessage.get(message.id) ?? NO_ATTACHMENTS, diff --git a/apps/web-foldkit/src/page/chat/lookup-data.ts b/apps/web-foldkit/src/page/chat/lookup-data.ts index 039e0916e..ada0350ed 100644 --- a/apps/web-foldkit/src/page/chat/lookup-data.ts +++ b/apps/web-foldkit/src/page/chat/lookup-data.ts @@ -10,6 +10,7 @@ import { chatSyncConnectionCollection, chatSyncMessageLinkCollection, customEmojiCollection, + messageAgentMarkCollection, messageCollection, pinnedMessageCollection, typingIndicatorCollection, @@ -19,6 +20,7 @@ import { import { getAttachmentUrl } from "~/utils/attachment-url" import { liveQueryStream } from "../../data/live-query" import { + type AgentMarkInfo, type AttachmentInfo, type AttachmentRow, type BotInfo, @@ -130,6 +132,20 @@ export const discordSyncedStream = ( (rows) => toMessage(rows.map((row) => row.hazelMessageId)), ) +/** The channel's agent-written messages (`message_agent_marks`). */ +export const agentMarksStream = ( + channelId: ChannelId, + toMessage: (marks: ReadonlyArray) => M, +) => + liveQueryStream( + (q) => + q + .from({ mark: messageAgentMarkCollection }) + .where(({ mark }) => eq(mark.channelId, channelId)) + .select(({ mark }) => ({ id: mark.id, agentName: mark.agentName })), + (rows) => toMessage(rows), + ) + /** Thread names for `InlineThreadPreview`. */ export const threadChannelsStream = ( threadIds: ReadonlyArray, diff --git a/apps/web-foldkit/src/page/chat/lookups.ts b/apps/web-foldkit/src/page/chat/lookups.ts index 89fce9d65..1a2bbbaee 100644 --- a/apps/web-foldkit/src/page/chat/lookups.ts +++ b/apps/web-foldkit/src/page/chat/lookups.ts @@ -72,6 +72,10 @@ export type CustomEmojiInfo = typeof CustomEmojiInfo.Type export const BotInfo = Schema.Struct({ userId: UserId, name: Schema.String }) export type BotInfo = typeof BotInfo.Type +/** A message an agent wrote for its author, and the agent's name. */ +export const AgentMarkInfo = Schema.Struct({ id: MessageId, agentName: Schema.String }) +export type AgentMarkInfo = typeof AgentMarkInfo.Type + /** Everything the rows are derived from, besides messages and reactions. */ export const Lookups = Schema.Struct({ users: Schema.Array(UserInfo), @@ -80,6 +84,7 @@ export const Lookups = Schema.Struct({ customEmojis: Schema.Array(CustomEmojiInfo), attachments: Schema.Array(AttachmentInfo), discordSyncedIds: Schema.Array(MessageId), + agentMarks: Schema.Array(AgentMarkInfo), threadChannels: Schema.Array(ThreadChannelInfo), threadMessages: Schema.Array(ThreadMessageInfo), replyTargets: Schema.Array(ReplyTarget), @@ -93,6 +98,7 @@ export const emptyLookups: Lookups = { customEmojis: [], attachments: [], discordSyncedIds: [], + agentMarks: [], threadChannels: [], threadMessages: [], replyTargets: [], diff --git a/apps/web-foldkit/src/page/chat/rows.ts b/apps/web-foldkit/src/page/chat/rows.ts index dbd9d0976..af254a01f 100644 --- a/apps/web-foldkit/src/page/chat/rows.ts +++ b/apps/web-foldkit/src/page/chat/rows.ts @@ -146,6 +146,8 @@ export const MessageRowData = Schema.Struct({ hasAuthor: Schema.Boolean, status: Schema.NullOr(StatusEmoji), isDiscordSynced: Schema.Boolean, + /** The agent that wrote the message for its author (Hazel's MCP server), if one did. */ + agentName: Schema.NullOr(Schema.String), reply: Schema.NullOr(ReplyPreview), thread: Schema.NullOr(ThreadPreview), attachments: Schema.Array(AttachmentInfo), diff --git a/apps/web-foldkit/src/page/my-settings/agents/command.ts b/apps/web-foldkit/src/page/my-settings/agents/command.ts new file mode 100644 index 000000000..61e67392f --- /dev/null +++ b/apps/web-foldkit/src/page/my-settings/agents/command.ts @@ -0,0 +1,73 @@ +import type { AgentGrantInfo, AgentScope } from "@hazel/domain/http" +import { AgentGrantId } from "@hazel/schema" +import { DateTime, Effect, Schema } from "effect" +import { Command } from "foldkit" +import { catchCommon } from "../../../data/actions" +import { HazelApiClient } from "../../../rpc" +import { CopyTarget, Message } from "./message" +import { type Grant, TokenAccess } from "./model" + +const toGrant = (grant: AgentGrantInfo): Grant => ({ + id: grant.id, + kind: grant.kind, + name: grant.name, + scopes: grant.scopes, + createdAtMs: DateTime.toEpochMillis(grant.createdAt), + lastUsedAtMs: grant.lastUsedAt === null ? null : DateTime.toEpochMillis(grant.lastUsedAt), +}) + +export const FetchGrants = Command.define("FetchAgentGrants", { + messages: [Message.SucceededFetchGrants, Message.FailedFetchGrants], + execute: HazelApiClient.use((client) => client.agentAccess.listAgentGrants()).pipe( + Effect.map((response) => + Message.SucceededFetchGrants({ grants: response.grants.map(toGrant), mcpUrl: response.mcpUrl }), + ), + catchCommon((reason) => Message.FailedFetchGrants({ reason })), + ), +}) + +export const RevokeGrant = Command.define("RevokeAgentGrant", { + args: { grantId: AgentGrantId }, + messages: [Message.SucceededRevoke, Message.FailedRevoke], + execute: ({ grantId }) => + HazelApiClient.use((client) => client.agentAccess.revokeAgentGrant({ params: { grantId } })).pipe( + Effect.as(Message.SucceededRevoke({ grantId })), + // Already gone: the list drops it all the same. + Effect.catchTags({ + AgentGrantNotFoundError: () => Effect.succeed(Message.SucceededRevoke({ grantId })), + }), + catchCommon((reason) => Message.FailedRevoke({ reason })), + ), +}) + +const scopesOf = (access: TokenAccess): Array => + access === "write" ? ["messages:read", "messages:write"] : ["messages:read"] + +export const CreateToken = Command.define("CreateAgentToken", { + args: { name: Schema.String, access: TokenAccess }, + messages: [Message.SucceededCreateToken, Message.FailedCreateToken], + execute: ({ name, access }) => + HazelApiClient.use((client) => + client.agentAccess.createAgentToken({ payload: { name, scopes: scopesOf(access) } }), + ).pipe( + Effect.map((response) => + Message.SucceededCreateToken({ + token: { name: response.grant.name, token: response.token }, + grant: toGrant(response.grant), + }), + ), + catchCommon((reason) => Message.FailedCreateToken({ reason })), + ), +}) + +export const CopyText = Command.define("CopyAgentText", { + args: { target: CopyTarget, text: Schema.String }, + messages: [Message.SucceededCopy, Message.FailedCopy], + execute: ({ target, text }) => + Effect.tryPromise(() => navigator.clipboard.writeText(text)).pipe( + Effect.match({ + onSuccess: () => Message.SucceededCopy({ target }), + onFailure: () => Message.FailedCopy({ target }), + }), + ), +}) diff --git a/apps/web-foldkit/src/page/my-settings/agents/index.ts b/apps/web-foldkit/src/page/my-settings/agents/index.ts new file mode 100644 index 000000000..9fbf2169b --- /dev/null +++ b/apps/web-foldkit/src/page/my-settings/agents/index.ts @@ -0,0 +1,12 @@ +import { definePage } from "../../contract" +import { Message } from "./message" +import { Model } from "./model" +import { init, update } from "./update" +import { view } from "./view" + +/** `/$orgSlug/my-settings/agents`: the agents (MCP OAuth apps, personal tokens) that may act for the user. */ +export const page = definePage( + "MySettingsAgents", + { Model, Message }, + { routes: ["MySettingsAgents"], key: ({ orgSlug }) => orgSlug, init, update, view }, +) diff --git a/apps/web-foldkit/src/page/my-settings/agents/message.ts b/apps/web-foldkit/src/page/my-settings/agents/message.ts new file mode 100644 index 000000000..36ae61f7c --- /dev/null +++ b/apps/web-foldkit/src/page/my-settings/agents/message.ts @@ -0,0 +1,29 @@ +import { AgentGrantId } from "@hazel/schema" +import { Schema } from "effect" +import { defineMessageUnion } from "foldkit/message" +import { CommonReason } from "~/lib/error-messages" +import { CreatedToken, Grant, TokenAccess } from "./model" + +export const CopyTarget = Schema.Literals(["McpUrl", "Token"]) +export type CopyTarget = typeof CopyTarget.Type + +export const Message = defineMessageUnion({ + SucceededFetchGrants: { grants: Schema.Array(Grant), mcpUrl: Schema.String }, + FailedFetchGrants: { reason: CommonReason }, + ClickedRetry: {}, + ClickedRevoke: { grantId: AgentGrantId }, + ClickedCancelRevoke: {}, + ClickedConfirmRevoke: { grantId: AgentGrantId }, + SucceededRevoke: { grantId: AgentGrantId }, + FailedRevoke: { reason: CommonReason }, + ChangedTokenName: { value: Schema.String }, + SelectedTokenAccess: { access: TokenAccess }, + ClickedCreateToken: {}, + SucceededCreateToken: { token: CreatedToken, grant: Grant }, + FailedCreateToken: { reason: CommonReason }, + ClickedDismissToken: {}, + ClickedCopy: { target: CopyTarget, text: Schema.String }, + SucceededCopy: { target: CopyTarget }, + FailedCopy: { target: CopyTarget }, +}) +export type Message = typeof Message.Type diff --git a/apps/web-foldkit/src/page/my-settings/agents/model.ts b/apps/web-foldkit/src/page/my-settings/agents/model.ts new file mode 100644 index 000000000..e97c2f1de --- /dev/null +++ b/apps/web-foldkit/src/page/my-settings/agents/model.ts @@ -0,0 +1,44 @@ +import { AgentScope } from "@hazel/domain/http" +import { AgentGrantId } from "@hazel/schema" +import { Schema } from "effect" +import { defineTaggedUnion } from "foldkit/schema" +import { CommonReason } from "~/lib/error-messages" + +/** One agent that may act for the user, as the page lists it. */ +export const Grant = Schema.Struct({ + id: AgentGrantId, + kind: Schema.Literals(["oauth", "token"]), + name: Schema.String, + scopes: Schema.Array(AgentScope), + createdAtMs: Schema.Number, + lastUsedAtMs: Schema.NullOr(Schema.Number), +}) +export type Grant = typeof Grant.Type + +export const Grants = defineTaggedUnion({ + Loading: {}, + Loaded: { grants: Schema.Array(Grant), mcpUrl: Schema.String }, + Failed: { reason: CommonReason }, +}) +export type Grants = typeof Grants.Type + +/** A new token's access: read only, or read and write. */ +export const TokenAccess = Schema.Literals(["read", "write"]) +export type TokenAccess = typeof TokenAccess.Type + +/** A token just created: shown once, then gone (only its hash is kept). */ +export const CreatedToken = Schema.Struct({ name: Schema.String, token: Schema.String }) +export type CreatedToken = typeof CreatedToken.Type + +export const Model = Schema.Struct({ + orgSlug: Schema.String, + grants: Grants, + tokenName: Schema.String, + tokenAccess: TokenAccess, + isCreating: Schema.Boolean, + createdToken: Schema.NullOr(CreatedToken), + /** The grant whose Revoke was pressed once and waits for confirmation. */ + confirmingRevoke: Schema.NullOr(AgentGrantId), + revoking: Schema.NullOr(AgentGrantId), +}) +export type Model = typeof Model.Type diff --git a/apps/web-foldkit/src/page/my-settings/agents/update.ts b/apps/web-foldkit/src/page/my-settings/agents/update.ts new file mode 100644 index 000000000..b2a9b4597 --- /dev/null +++ b/apps/web-foldkit/src/page/my-settings/agents/update.ts @@ -0,0 +1,110 @@ +import { modifyFields } from "foldkit/struct" +import { commonMessage } from "~/lib/error-messages" +import { errorToast, successToast } from "../../../data/actions" +import type { RouteOf } from "../../../route" +import type { PageReturn } from "../../contract" +import { PageOutMessage } from "../../out-message" +import { CopyText, CreateToken, FetchGrants, RevokeGrant } from "./command" +import { Message } from "./message" +import { Grants, type Model } from "./model" + +type Return = PageReturn + +export const init = (route: RouteOf<"MySettingsAgents">): Return => ({ + model: { + orgSlug: route.orgSlug, + grants: Grants.Loading(), + tokenName: "", + tokenAccess: "write", + isCreating: false, + createdToken: null, + confirmingRevoke: null, + revoking: null, + }, + commands: [FetchGrants()], +}) + +const toast = ( + model: Model, + request: Parameters[0]["toast"], +): Return => ({ + model, + outMessage: PageOutMessage.RequestedToast({ toast: request }), +}) + +export const update = (model: Model, message: Message): Return => + Message.match(message, { + SucceededFetchGrants: ({ grants, mcpUrl }) => ({ + model: modifyFields(model, { grants: () => Grants.Loaded({ grants, mcpUrl }) }), + }), + FailedFetchGrants: ({ reason }) => ({ + model: modifyFields(model, { grants: () => Grants.Failed({ reason }) }), + }), + ClickedRetry: () => ({ + model: modifyFields(model, { grants: () => Grants.Loading() }), + commands: [FetchGrants()], + }), + ClickedRevoke: ({ grantId }) => + model.revoking !== null + ? { model } + : { model: modifyFields(model, { confirmingRevoke: () => grantId }) }, + ClickedCancelRevoke: () => ({ model: modifyFields(model, { confirmingRevoke: () => null }) }), + ClickedConfirmRevoke: ({ grantId }) => + model.revoking !== null + ? { model } + : { + model: modifyFields(model, { confirmingRevoke: () => null, revoking: () => grantId }), + commands: [RevokeGrant({ grantId })], + }, + SucceededRevoke: ({ grantId }) => + toast( + modifyFields(model, { + revoking: () => null, + grants: (grants) => + grants._tag === "Loaded" + ? Grants.Loaded({ + mcpUrl: grants.mcpUrl, + grants: grants.grants.filter((grant) => grant.id !== grantId), + }) + : grants, + }), + successToast("Agent disconnected"), + ), + FailedRevoke: ({ reason }) => + toast( + modifyFields(model, { revoking: () => null }), + errorToast("Couldn't disconnect the agent", commonMessage(reason).title), + ), + ChangedTokenName: ({ value }) => ({ model: modifyFields(model, { tokenName: () => value }) }), + SelectedTokenAccess: ({ access }) => ({ model: modifyFields(model, { tokenAccess: () => access }) }), + ClickedCreateToken: () => { + const name = model.tokenName.trim() + return model.isCreating || name.length === 0 + ? { model } + : { + model: modifyFields(model, { isCreating: () => true }), + commands: [CreateToken({ name, access: model.tokenAccess })], + } + }, + SucceededCreateToken: ({ token, grant }) => ({ + model: modifyFields(model, { + isCreating: () => false, + tokenName: () => "", + createdToken: () => token, + grants: (grants) => + grants._tag === "Loaded" + ? Grants.Loaded({ mcpUrl: grants.mcpUrl, grants: [grant, ...grants.grants] }) + : grants, + }), + }), + FailedCreateToken: ({ reason }) => + toast( + modifyFields(model, { isCreating: () => false }), + errorToast("Couldn't create the token", commonMessage(reason).title), + ), + ClickedDismissToken: () => ({ model: modifyFields(model, { createdToken: () => null }) }), + ClickedCopy: ({ target, text }) => ({ model, commands: [CopyText({ target, text })] }), + SucceededCopy: ({ target }) => + toast(model, successToast(target === "Token" ? "Token copied" : "MCP URL copied")), + FailedCopy: () => toast(model, errorToast("Couldn't copy to the clipboard")), + }) diff --git a/apps/web-foldkit/src/page/my-settings/agents/view.ts b/apps/web-foldkit/src/page/my-settings/agents/view.ts new file mode 100644 index 000000000..18a686f96 --- /dev/null +++ b/apps/web-foldkit/src/page/my-settings/agents/view.ts @@ -0,0 +1,277 @@ +import { formatDistanceStrict } from "date-fns" +import { Submodel } from "foldkit" +import type { Html, HtmlBuilder } from "foldkit/html" +import { commonMessage } from "~/lib/error-messages" +import { IconCopy } from "../../../icons" +import { badge } from "../../../ui/badge" +import { button } from "../../../ui/button" +import { loader } from "../../../ui/loader" +import { textField } from "../../../ui/text-field" +import type { PageViewInputs } from "../../contract" +import { divider, pageHeader, settingsRow } from "../shared" +import { Message } from "./message" +import { type CreatedToken, type Grant, Grants, type Model, type TokenAccess } from "./model" + +const ago = (ms: number, nowMs: number) => formatDistanceStrict(ms, Math.max(ms, nowMs), { addSuffix: true }) + +const copyButton = (h: HtmlBuilder, target: "McpUrl" | "Token", text: string, label: string): Html => + button(h, { intent: "outline", size: "sm", onPress: Message.ClickedCopy({ target, text }) }, [ + IconCopy(h, { className: "size-4" }), + label, + ]) + +const codeBox = (h: HtmlBuilder, text: string): Html => + h.code( + [ + h.Class( + "min-w-0 flex-1 truncate rounded-md border border-border bg-secondary/50 px-3 py-1.5 font-mono text-fg text-xs", + ), + ], + [text], + ) + +const connectSection = (h: HtmlBuilder, mcpUrl: string): Html => + settingsRow( + h, + { + title: "Connect an agent", + description: "Let an AI agent read your messages and answer people for you.", + }, + h.div( + [h.Class("flex max-w-xl flex-col gap-3")], + [ + h.div( + [h.Class("flex items-center gap-2")], + [codeBox(h, mcpUrl), copyButton(h, "McpUrl", mcpUrl, "Copy")], + ), + h.p( + [h.Class("text-muted-fg text-xs")], + [ + "Add Hazel as a remote MCP server in Claude, ChatGPT, Cursor or another agent using this URL, and sign in when asked. For clients that take a header instead, create a personal token below and send ", + h.code([h.Class("font-mono text-fg")], ["Authorization: Bearer "]), + ".", + ], + ), + h.p( + [h.Class("text-muted-fg text-xs")], + [ + `Messages an agent sends show "via " next to your name for people in your organization.`, + ], + ), + ], + ), + ) + +const createdTokenBanner = (h: HtmlBuilder, created: CreatedToken): Html => + h.div( + [h.Class("flex max-w-xl flex-col gap-3 rounded-xl border border-border bg-bg p-4"), h.Role("status")], + [ + h.p([h.Class("font-medium text-fg text-sm")], [`Token "${created.name}" created`]), + h.p([h.Class("text-muted-fg text-xs")], ["Copy it now. You won't be able to see it again."]), + h.div( + [h.Class("flex items-center gap-2")], + [codeBox(h, created.token), copyButton(h, "Token", created.token, "Copy")], + ), + h.div( + [], + [ + button(h, { intent: "plain", size: "sm", onPress: Message.ClickedDismissToken() }, [ + "Done", + ]), + ], + ), + ], + ) + +const ACCESS_OPTIONS: ReadonlyArray<{ + readonly access: TokenAccess + readonly label: string + readonly hint: string +}> = [ + { access: "write", label: "Read & write", hint: "Read, send, reply, react, edit" }, + { access: "read", label: "Read only", hint: "Read channels and messages" }, +] + +const accessOption = ( + h: HtmlBuilder, + model: Model, + option: (typeof ACCESS_OPTIONS)[number], +): Html => { + const isSelected = model.tokenAccess === option.access + return h.keyed("button")( + option.access, + [ + h.Type("button"), + h.Role("radio"), + h.AriaChecked(isSelected), + h.OnClick(Message.SelectedTokenAccess({ access: option.access })), + h.Class( + `flex flex-1 flex-col items-start rounded-lg border px-3 py-2 text-left transition-colors duration-150 focus:outline-none focus-visible:ring-2 focus-visible:ring-primary ${ + isSelected ? "border-primary bg-primary/5" : "border-border hover:bg-secondary/50" + }`, + ), + ], + [ + h.span([h.Class("font-medium text-fg text-sm")], [option.label]), + h.span([h.Class("text-muted-fg text-xs")], [option.hint]), + ], + ) +} + +const createSection = (h: HtmlBuilder, model: Model): Html => + settingsRow( + h, + { title: "Personal tokens", description: "For agents that take a token instead of signing in." }, + h.div( + [h.Class("flex max-w-xl flex-col gap-3")], + [ + ...(model.createdToken === null ? [] : [createdTokenBanner(h, model.createdToken)]), + textField( + h, + { + id: "agent-token-name", + value: model.tokenName, + onInput: (value) => Message.ChangedTokenName({ value }), + isDisabled: model.isCreating, + }, + (field) => [ + field.label(["Name"]), + field.input({ placeholder: "e.g. Claude Code on my laptop" }), + ], + ), + h.div( + [h.Class("flex gap-2"), h.Role("radiogroup"), h.AriaLabel("Access")], + ACCESS_OPTIONS.map((option) => accessOption(h, model, option)), + ), + h.div( + [], + [ + button( + h, + { + intent: "primary", + size: "sm", + isDisabled: model.isCreating || model.tokenName.trim().length === 0, + onPress: Message.ClickedCreateToken(), + }, + [model.isCreating ? "Creating..." : "Create token"], + ), + ], + ), + ], + ), + ) + +const grantRow = (h: HtmlBuilder, model: Model, grant: Grant, nowMs: number): Html => { + const isConfirming = model.confirmingRevoke === grant.id + const isRevoking = model.revoking === grant.id + const canWrite = grant.scopes.includes("messages:write") + const used = grant.lastUsedAtMs === null ? "never used" : `last used ${ago(grant.lastUsedAtMs, nowMs)}` + return h.keyed("li")( + grant.id, + [h.Class("flex items-center gap-4 px-4 py-3")], + [ + h.div( + [h.Class("min-w-0 flex-1")], + [ + h.div( + [h.Class("flex items-center gap-2")], + [ + h.span([h.Class("truncate font-medium text-fg text-sm")], [grant.name]), + badge(h, { intent: "secondary" }, [ + grant.kind === "oauth" ? "OAuth app" : "Personal token", + ]), + ], + ), + h.p( + [h.Class("text-muted-fg text-xs")], + [ + `${canWrite ? "Read & write" : "Read only"} · added ${ago(grant.createdAtMs, nowMs)} · ${used}`, + ], + ), + ], + ), + isConfirming + ? h.div( + [h.Class("flex items-center gap-2")], + [ + button( + h, + { intent: "plain", size: "sm", onPress: Message.ClickedCancelRevoke() }, + ["Cancel"], + ), + button( + h, + { + intent: "danger", + size: "sm", + onPress: Message.ClickedConfirmRevoke({ grantId: grant.id }), + }, + ["Disconnect"], + ), + ], + ) + : button( + h, + { + intent: "outline", + size: "sm", + isDisabled: model.revoking !== null, + onPress: Message.ClickedRevoke({ grantId: grant.id }), + }, + [isRevoking ? "Disconnecting..." : "Revoke"], + ), + ], + ) +} + +const grantsSection = ( + h: HtmlBuilder, + model: Model, + grants: ReadonlyArray, + nowMs: number, +): Html => + settingsRow( + h, + { title: "Connected agents", description: "Revoking one stops it at once." }, + grants.length === 0 + ? h.p([h.Class("text-muted-fg text-sm")], ["No agents yet."]) + : h.ul( + [ + h.Class( + "flex max-w-xl flex-col divide-y divide-border rounded-xl border border-border bg-bg", + ), + ], + grants.map((grant) => grantRow(h, model, grant, nowMs)), + ), + ) + +export const view = Submodel.defineView((model, { shared }, h) => + h.div( + [h.Class("flex flex-col gap-6 px-4 lg:px-8")], + [ + pageHeader(h, "Agents", "AI agents that can read and answer messages for you."), + ...Grants.match>(model.grants, { + Loading: () => [loader(h, { className: "size-5" })], + Failed: ({ reason }) => [ + h.p([h.Class("text-danger text-sm"), h.Role("alert")], [commonMessage(reason).title]), + h.div( + [], + [ + button(h, { intent: "outline", size: "sm", onPress: Message.ClickedRetry() }, [ + "Try again", + ]), + ], + ), + ], + Loaded: ({ grants, mcpUrl }) => [ + connectSection(h, mcpUrl), + divider(h), + createSection(h, model), + divider(h), + grantsSection(h, model, grants, shared.nowMs), + ], + }), + ], + ), +) diff --git a/apps/web-foldkit/src/page/my-settings/pages.ts b/apps/web-foldkit/src/page/my-settings/pages.ts index b16ac1483..3b0be45ee 100644 --- a/apps/web-foldkit/src/page/my-settings/pages.ts +++ b/apps/web-foldkit/src/page/my-settings/pages.ts @@ -1,3 +1,4 @@ +import * as MySettingsAgents from "./agents" import * as MySettingsAppearance from "./appearance" import * as MySettingsDesktop from "./desktop" import * as MySettingsKeybinds from "./keybinds" @@ -7,6 +8,7 @@ import * as MySettingsProfile from "./profile" /** The user's own settings pages: their own chunk, loaded with the first of their routes (`../registry.ts`). */ export const pages = [ + MySettingsAgents.page, MySettingsAppearance.page, MySettingsDesktop.page, MySettingsKeybinds.page, diff --git a/apps/web-foldkit/src/page/oauth-authorize/command.ts b/apps/web-foldkit/src/page/oauth-authorize/command.ts new file mode 100644 index 000000000..43cdffdda --- /dev/null +++ b/apps/web-foldkit/src/page/oauth-authorize/command.ts @@ -0,0 +1,71 @@ +import { AgentClientId } from "@hazel/schema" +import { Effect, Schema } from "effect" +import { Command } from "foldkit" +import { load } from "foldkit/navigation" +import { catchCommon } from "../../data/actions" +import { signInHref } from "../../route" +import { HazelApiClient } from "../../rpc" +import { Message } from "./message" + +export const FetchAgentClient = Command.define("FetchAgentClient", { + args: { clientId: AgentClientId, redirectUri: Schema.String }, + messages: [Message.SucceededFetchClient, Message.FoundInvalidRequest, Message.FailedFetchClient], + execute: ({ clientId, redirectUri }) => + HazelApiClient.use((client) => + client.agentAccess.getAgentClient({ params: { clientId }, query: { redirect_uri: redirectUri } }), + ).pipe( + Effect.map((client) => + Message.SucceededFetchClient({ + client: { + id: client.id, + name: client.name, + clientUri: client.clientUri, + logoUri: client.logoUri, + redirectHost: client.redirectHost, + }, + }), + ), + Effect.catchTags({ + AgentClientInvalidError: () => Effect.succeed(Message.FoundInvalidRequest()), + }), + catchCommon((reason) => Message.FailedFetchClient({ reason })), + ), +}) + +/** Approve or deny; either way the backend answers with the client's redirect, which the browser loads. */ +export const AuthorizeAgent = Command.define("AuthorizeAgent", { + args: { + clientId: AgentClientId, + redirectUri: Schema.String, + codeChallenge: Schema.String, + codeChallengeMethod: Schema.String, + scope: Schema.NullOr(Schema.String), + state: Schema.NullOr(Schema.String), + approve: Schema.Boolean, + }, + messages: [Message.LeftPage, Message.FailedAuthorize], + execute: ({ scope, state, ...request }) => + HazelApiClient.use((client) => + client.agentAccess.authorizeAgent({ + payload: { + ...request, + ...(scope === null ? {} : { scope }), + ...(state === null ? {} : { state }), + }, + }), + ).pipe( + Effect.flatMap(({ redirectTo }) => load(redirectTo)), + Effect.as(Message.LeftPage()), + Effect.catchTags({ + AgentClientInvalidError: () => Effect.succeed(Message.FailedAuthorize({ reason: "Invalid" })), + }), + catchCommon((reason) => Message.FailedAuthorize({ reason })), + ), +}) + +/** Sign in, then come back to this link. */ +export const RedirectToAuthorizeSignIn = Command.define("RedirectToAuthorizeSignIn", { + args: { returnTo: Schema.String }, + messages: [Message.LeftPage], + execute: ({ returnTo }) => load(signInHref(returnTo)).pipe(Effect.as(Message.LeftPage())), +}) diff --git a/apps/web-foldkit/src/page/oauth-authorize/index.ts b/apps/web-foldkit/src/page/oauth-authorize/index.ts new file mode 100644 index 000000000..393e0dbff --- /dev/null +++ b/apps/web-foldkit/src/page/oauth-authorize/index.ts @@ -0,0 +1,12 @@ +import { definePage } from "../contract" +import { Message } from "./message" +import { Model } from "./model" +import { init, update } from "./update" +import { view } from "./view" + +/** `/oauth/authorize`: an agent (an MCP client) asks to act for the signed-in user in Hazel. */ +export const page = definePage( + "OAuthAuthorize", + { Model, Message }, + { routes: ["OAuthAuthorize"], init, update, view }, +) diff --git a/apps/web-foldkit/src/page/oauth-authorize/message.ts b/apps/web-foldkit/src/page/oauth-authorize/message.ts new file mode 100644 index 000000000..08bafb3df --- /dev/null +++ b/apps/web-foldkit/src/page/oauth-authorize/message.ts @@ -0,0 +1,17 @@ +import { defineMessageUnion } from "foldkit/message" +import { CommonReason } from "~/lib/error-messages" +import { ApproveFailure, ClientSummary } from "./model" + +export const Message = defineMessageUnion({ + SucceededFetchClient: { client: ClientSummary }, + FoundInvalidRequest: {}, + FailedFetchClient: { reason: CommonReason }, + ClickedRetryRequest: {}, + ClickedSignIn: {}, + ClickedApprove: {}, + ClickedDeny: {}, + FailedAuthorize: { reason: ApproveFailure }, + /** The browser is loading the client's redirect or sign-in. */ + LeftPage: {}, +}) +export type Message = typeof Message.Type diff --git a/apps/web-foldkit/src/page/oauth-authorize/model.ts b/apps/web-foldkit/src/page/oauth-authorize/model.ts new file mode 100644 index 000000000..b01371bde --- /dev/null +++ b/apps/web-foldkit/src/page/oauth-authorize/model.ts @@ -0,0 +1,61 @@ +import { AgentScope } from "@hazel/domain/http" +import { AgentClientId } from "@hazel/schema" +import { Schema } from "effect" +import { defineTaggedUnion } from "foldkit/schema" +import { CommonReason } from "~/lib/error-messages" + +/** What the consent page shows about the client asking for access. */ +export const ClientSummary = Schema.Struct({ + id: AgentClientId, + name: Schema.String, + clientUri: Schema.NullOr(Schema.String), + logoUri: Schema.NullOr(Schema.String), + redirectHost: Schema.String, +}) +export type ClientSummary = typeof ClientSummary.Type + +/** The link's OAuth parameters, once they check out (authorization code with S256 PKCE). */ +export const Request = Schema.Struct({ + clientId: AgentClientId, + redirectUri: Schema.String, + codeChallenge: Schema.String, + codeChallengeMethod: Schema.String, + scope: Schema.NullOr(Schema.String), + state: Schema.NullOr(Schema.String), + scopes: Schema.Array(AgentScope), +}) +export type Request = typeof Request.Type + +/** + * `agentAccess.getAgentClient`. `Invalid` is a link that cannot be honoured: parameters missing, an + * unknown client, or a redirect it never registered. It never sends the browser anywhere. + */ +export const Lookup = defineTaggedUnion({ + Loading: {}, + Loaded: { client: ClientSummary }, + Invalid: {}, + Failed: { reason: CommonReason }, +}) +export type Lookup = typeof Lookup.Type + +export const ApproveFailure = Schema.Union([Schema.Literal("Invalid"), CommonReason]) +export type ApproveFailure = typeof ApproveFailure.Type + +/** Approving (or denying) stays in flight until the browser leaves for the client's redirect. */ +export const Approval = defineTaggedUnion({ + Idle: {}, + Approving: {}, + Denying: {}, + Leaving: {}, + Failed: { reason: ApproveFailure }, +}) +export type Approval = typeof Approval.Type + +export const Model = Schema.Struct({ + /** This link, to come back to after signing in. */ + returnTo: Schema.String, + request: Schema.NullOr(Request), + lookup: Lookup, + approval: Approval, +}) +export type Model = typeof Model.Type diff --git a/apps/web-foldkit/src/page/oauth-authorize/update.ts b/apps/web-foldkit/src/page/oauth-authorize/update.ts new file mode 100644 index 000000000..6b50e0e30 --- /dev/null +++ b/apps/web-foldkit/src/page/oauth-authorize/update.ts @@ -0,0 +1,102 @@ +import { parseAgentScopes } from "@hazel/domain/http" +import { AgentClientId } from "@hazel/schema" +import { Option, Schema } from "effect" +import { modifyFields } from "foldkit/struct" +import { hrefOf, type RouteOf } from "../../route" +import type { PageReturn } from "../contract" +import { AuthorizeAgent, FetchAgentClient, RedirectToAuthorizeSignIn } from "./command" +import { Message } from "./message" +import { Approval, Lookup, type Model, type Request } from "./model" + +type Return = PageReturn + +const decodeClientId = Schema.decodeUnknownOption(AgentClientId) + +/** The link's parameters; `null` when one is missing or malformed (only `code` with S256 PKCE). */ +export const requestOf = (route: RouteOf<"OAuthAuthorize">): Request | null => { + const clientId = Option.flatMap(route.clientId, decodeClientId) + const method = Option.getOrElse(route.codeChallengeMethod, () => "S256") + if ( + Option.isNone(clientId) || + Option.isNone(route.redirectUri) || + Option.isNone(route.codeChallenge) || + Option.getOrNull(route.responseType) !== "code" || + method !== "S256" + ) + return null + const scope = Option.getOrNull(route.scope) + return { + clientId: clientId.value, + redirectUri: route.redirectUri.value, + codeChallenge: route.codeChallenge.value, + codeChallengeMethod: method, + scope, + state: Option.getOrNull(route.state), + scopes: parseAgentScopes(scope), + } +} + +const fetchOf = (request: Request) => + FetchAgentClient({ clientId: request.clientId, redirectUri: request.redirectUri }) + +export const init = (route: RouteOf<"OAuthAuthorize">): Return => { + const request = requestOf(route) + const base = { returnTo: hrefOf(route), request, approval: Approval.Idle() } + return request === null + ? { model: { ...base, lookup: Lookup.Invalid() } } + : { model: { ...base, lookup: Lookup.Loading() }, commands: [fetchOf(request)] } +} + +const isBusy = (model: Model) => + model.approval._tag === "Approving" || + model.approval._tag === "Denying" || + model.approval._tag === "Leaving" + +const authorize = (model: Model, approve: boolean): Return => + isBusy(model) || model.request === null || model.lookup._tag !== "Loaded" + ? { model } + : { + model: modifyFields(model, { + approval: () => (approve ? Approval.Approving() : Approval.Denying()), + }), + commands: [ + AuthorizeAgent({ + clientId: model.request.clientId, + redirectUri: model.request.redirectUri, + codeChallenge: model.request.codeChallenge, + codeChallengeMethod: model.request.codeChallengeMethod, + scope: model.request.scope, + state: model.request.state, + approve, + }), + ], + } + +export const update = (model: Model, message: Message): Return => + Message.match(message, { + SucceededFetchClient: ({ client }) => ({ + model: modifyFields(model, { lookup: () => Lookup.Loaded({ client }) }), + }), + FoundInvalidRequest: () => ({ model: modifyFields(model, { lookup: () => Lookup.Invalid() }) }), + FailedFetchClient: ({ reason }) => ({ + model: modifyFields(model, { lookup: () => Lookup.Failed({ reason }) }), + }), + ClickedRetryRequest: () => + model.lookup._tag !== "Failed" || model.request === null + ? { model } + : { + model: modifyFields(model, { lookup: () => Lookup.Loading() }), + commands: [fetchOf(model.request)], + }, + ClickedSignIn: () => ({ + model: modifyFields(model, { approval: () => Approval.Leaving() }), + commands: [RedirectToAuthorizeSignIn({ returnTo: model.returnTo })], + }), + ClickedApprove: () => authorize(model, true), + // Only once the client checked out: an unverified redirect is never followed. + ClickedDeny: () => authorize(model, false), + FailedAuthorize: ({ reason }) => ({ + model: modifyFields(model, { approval: () => Approval.Failed({ reason }) }), + }), + LeftPage: () => ({ model: modifyFields(model, { approval: () => Approval.Leaving() }) }), + }) diff --git a/apps/web-foldkit/src/page/oauth-authorize/view.ts b/apps/web-foldkit/src/page/oauth-authorize/view.ts new file mode 100644 index 000000000..10ae1835c --- /dev/null +++ b/apps/web-foldkit/src/page/oauth-authorize/view.ts @@ -0,0 +1,162 @@ +import type { AgentScope } from "@hazel/domain/http" +import { Submodel } from "foldkit" +import type { Html, HtmlBuilder } from "foldkit/html" +import { commonMessage, failureMessage, type UserErrorMessage } from "~/lib/error-messages" +import { IconCheck } from "../../icons" +import { AppRoute, hrefOf } from "../../route" +import { avatar } from "../../ui/avatar" +import { button } from "../../ui/button" +import { loader } from "../../ui/loader" +import { authError, authFrame, authHeading } from "../auth/layout" +import { isSessionLoading, type PageViewInputs, type Shared } from "../contract" +import { Message } from "./message" +import { type ApproveFailure, type ClientSummary, Lookup, type Model } from "./model" + +/** What each scope lets the agent do, in the user's words. */ +const SCOPE_ABILITIES: Readonly>> = { + "messages:read": ["Read your channels, direct messages and threads", "See messages that mention you"], + "messages:write": [ + "Send messages and replies as you", + "React to messages", + "Edit and delete messages it sent", + ], +} + +const homeLink = (h: HtmlBuilder): Html => + h.a( + [h.Class("text-fg text-sm underline underline-offset-2"), h.Href(hrefOf(AppRoute.Root()))], + ["Go to Hazel"], + ) + +const approveFailureMessage = (reason: ApproveFailure): UserErrorMessage => + failureMessage(reason, { + Invalid: { title: "This link is no longer valid", description: "Start again from your agent." }, + }) + +const abilities = (h: HtmlBuilder, scopes: ReadonlyArray): Html => + h.ul( + [h.Class("mb-4 flex flex-col gap-2 rounded-lg border border-border p-3")], + scopes + .flatMap((scope) => SCOPE_ABILITIES[scope]) + .map((ability) => + h.li( + [h.Class("flex items-start gap-2 text-fg text-sm")], + [IconCheck(h, { className: "mt-0.5 size-4 shrink-0 text-muted-fg" }), ability], + ), + ), + ) + +const actions = (h: HtmlBuilder, model: Model, shared: Shared): Html => { + const isLeaving = model.approval._tag === "Leaving" + if (shared.currentUser === null) + return button( + h, + { + intent: "primary", + className: "w-full", + isDisabled: isLeaving, + onPress: Message.ClickedSignIn(), + }, + ["Sign in to continue"], + ) + const isApproving = model.approval._tag === "Approving" + const isDenying = model.approval._tag === "Denying" + const isBusy = isApproving || isDenying || isLeaving + return h.div( + [h.Class("mt-6 flex flex-col gap-2")], + [ + button( + h, + { + intent: "primary", + className: "w-full", + isDisabled: isBusy, + onPress: Message.ClickedApprove(), + }, + isApproving ? [loader(h, { className: "size-4" }), "Allowing..."] : ["Allow"], + ), + button( + h, + { intent: "plain", className: "w-full", isDisabled: isBusy, onPress: Message.ClickedDeny() }, + ["Deny"], + ), + ], + ) +} + +const request = ( + h: HtmlBuilder, + model: Model, + client: ClientSummary, + shared: Shared, +): ReadonlyArray => [ + avatar(h, { src: client.logoUri, seed: client.name, size: "xl", className: "mb-6" }), + authHeading( + h, + `Connect ${client.name}`, + `${client.name} wants to act for you in Hazel. It will be able to:`, + ), + abilities(h, model.request?.scopes ?? []), + h.p( + [h.Class("mb-2 text-muted-fg text-xs")], + [ + `Messages it sends are shown as written by an agent ("via ${client.name}") to people in your organization.`, + ], + ), + h.p( + [h.Class("text-muted-fg text-xs")], + [ + "You'll return to ", + h.span([h.Class("font-medium text-fg")], [client.redirectHost]), + ". You can disconnect it any time in My Settings → Agents.", + ], + ), + actions(h, model, shared), + ...(model.approval._tag === "Failed" + ? [authError(h, approveFailureMessage(model.approval.reason)) ?? h.empty] + : []), +] + +export const view = Submodel.defineView((model, { shared }, h) => + authFrame( + h, + shared.nowMs, + isSessionLoading(shared) + ? [loader(h, { className: "size-6" })] + : Lookup.match(model.lookup, { + Loading: () => [loader(h, { className: "size-6" })], + Loaded: ({ client }) => request(h, model, client, shared), + Invalid: () => [ + authHeading( + h, + "This link is invalid", + "It may be incomplete, or the agent that sent you here isn't registered with Hazel. Start again from your agent.", + ), + homeLink(h), + ], + // Looking the client up needs a session: a signed-out visitor signs in and comes back. + Failed: ({ reason }) => + reason === "SignedOut" && shared.currentUser === null + ? [ + authHeading( + h, + "Sign in to connect your agent", + "You'll come back here afterwards.", + ), + actions(h, model, shared), + ] + : [ + authHeading(h, "Couldn't load this request", commonMessage(reason).title), + button( + h, + { + intent: "outline", + className: "w-full", + onPress: Message.ClickedRetryRequest(), + }, + ["Try again"], + ), + ], + }), + ), +) diff --git a/apps/web-foldkit/src/page/registry.ts b/apps/web-foldkit/src/page/registry.ts index ac401fc4c..c0f68e197 100644 --- a/apps/web-foldkit/src/page/registry.ts +++ b/apps/web-foldkit/src/page/registry.ts @@ -6,6 +6,7 @@ import type { Resources } from "../rpc" import { AppRoute, isCustomersRoute, isMySettingsRoute, isSettingsRoute } from "../route" import * as Auth from "./auth" import * as BotInstall from "./bot-install" +import * as OAuthAuthorize from "./oauth-authorize" import * as ChatChannel from "./chat/channel" import * as ChatIndex from "./chat-index" import type { PageHost, PageMessageBase, PageSlotBase, PageStep, PageViewInputs, Shared } from "./contract" @@ -41,6 +42,7 @@ export const pages = [ Join.page, Invite.page, BotInstall.page, + OAuthAuthorize.page, ] type AreaPage = diff --git a/apps/web-foldkit/src/route.test.ts b/apps/web-foldkit/src/route.test.ts index c2411bc6c..42db6cce5 100644 --- a/apps/web-foldkit/src/route.test.ts +++ b/apps/web-foldkit/src/route.test.ts @@ -321,6 +321,21 @@ describe("hrefOf", () => { "/oauth/bot-install", ], ], + OAuthAuthorize: [ + [ + AppRoute.OAuthAuthorize({ + clientId: Option.some(orgId), + redirectUri: Option.some("http://127.0.0.1:5000/cb"), + responseType: Option.some("code"), + codeChallenge: Option.some("abc"), + codeChallengeMethod: Option.some("S256"), + scope: Option.some("messages:read messages:write"), + state: Option.some("s1"), + resource: Option.none(), + }), + `/oauth/authorize?client_id=${orgId}&redirect_uri=http%3A%2F%2F127.0.0.1%3A5000%2Fcb&response_type=code&code_challenge=abc&code_challenge_method=S256&scope=messages%3Aread+messages%3Awrite&state=s1`, + ], + ], AuthDesktop: [[AppRoute.AuthDesktop({ attempt: Option.some("a1") }), "/auth/desktop?attempt=a1"]], Onboarding: [ [AppRoute.Onboarding({ orgId: Option.none(), step: none }), "/onboarding"], @@ -376,6 +391,7 @@ describe("hrefOf", () => { ], MySettingsAppearance: [[AppRoute.MySettingsAppearance({ orgSlug }), "/hazel/my-settings"]], MySettingsProfile: [[AppRoute.MySettingsProfile({ orgSlug }), "/hazel/my-settings/profile"]], + MySettingsAgents: [[AppRoute.MySettingsAgents({ orgSlug }), "/hazel/my-settings/agents"]], MySettingsLinkedAccounts: [ [ AppRoute.MySettingsLinkedAccounts({ diff --git a/apps/web-foldkit/src/route.ts b/apps/web-foldkit/src/route.ts index a9240340e..3f5fda54a 100644 --- a/apps/web-foldkit/src/route.ts +++ b/apps/web-foldkit/src/route.ts @@ -36,6 +36,20 @@ export const AppRoute = defineRouteUnion({ redirectUri: Schema.Option(Schema.String), state: Schema.Option(Schema.String), }, + /** + * Hazel's MCP OAuth consent page (`GET /oauth/authorize` on the api redirects here with the same + * query): an agent asks to act for the signed-in user. + */ + OAuthAuthorize: { + clientId: Schema.Option(Schema.String), + redirectUri: Schema.Option(Schema.String), + responseType: Schema.Option(Schema.String), + codeChallenge: Schema.Option(Schema.String), + codeChallengeMethod: Schema.Option(Schema.String), + scope: Schema.Option(Schema.String), + state: Schema.Option(Schema.String), + resource: Schema.Option(Schema.String), + }, /** `?orgId=&step=` (`validateSearch` in `onboarding/index.tsx`). */ Onboarding: { orgId: Schema.Option(OrganizationId), step: Schema.Option(Schema.String) }, OnboardingSetupOrganization: { orgId: Schema.Option(OrganizationId) }, @@ -51,6 +65,8 @@ export const AppRoute = defineRouteUnion({ ChannelSettingsConnect: { orgSlug: Schema.String, channelId: ChannelId }, MySettingsAppearance: { orgSlug: Schema.String }, MySettingsProfile: { orgSlug: Schema.String }, + /** The agents (MCP OAuth apps and personal tokens) that may act for the user. */ + MySettingsAgents: { orgSlug: Schema.String }, /** The OAuth callback redirect's `?connection_status=&provider=&error_code=`. */ MySettingsLinkedAccounts: { orgSlug: Schema.String, @@ -129,6 +145,25 @@ const BotInstallQuery = Schema.Struct({ redirectUri: Schema.OptionFromOptional(Schema.String), state: Schema.OptionFromOptional(Schema.String), }).pipe(Schema.encodeKeys({ botId: "bot_id", redirectUri: "redirect_uri" })) +/** OAuth's snake_case parameters; the page checks them (a bad link is a page state, not a 404). */ +const OAuthAuthorizeQuery = Schema.Struct({ + clientId: Schema.OptionFromOptional(Schema.String), + redirectUri: Schema.OptionFromOptional(Schema.String), + responseType: Schema.OptionFromOptional(Schema.String), + codeChallenge: Schema.OptionFromOptional(Schema.String), + codeChallengeMethod: Schema.OptionFromOptional(Schema.String), + scope: Schema.OptionFromOptional(Schema.String), + state: Schema.OptionFromOptional(Schema.String), + resource: Schema.OptionFromOptional(Schema.String), +}).pipe( + Schema.encodeKeys({ + clientId: "client_id", + redirectUri: "redirect_uri", + responseType: "response_type", + codeChallenge: "code_challenge", + codeChallengeMethod: "code_challenge_method", + }), +) const OrgIdQuery = Schema.Struct({ orgId: Schema.OptionFromOptional(OrganizationId) }) const OnboardingQuery = Schema.Struct({ orgId: Schema.OptionFromOptional(OrganizationId), @@ -191,6 +226,12 @@ const routers = { query(BotInstallQuery), Route.mapTo(AppRoute.BotInstall), ), + OAuthAuthorize: pipe( + literal("oauth"), + slash(literal("authorize")), + query(OAuthAuthorizeQuery), + Route.mapTo(AppRoute.OAuthAuthorize), + ), Onboarding: pipe(literal("onboarding"), query(OnboardingQuery), Route.mapTo(AppRoute.Onboarding)), OnboardingSetupOrganization: pipe( literal("onboarding"), @@ -218,6 +259,7 @@ const routers = { ChannelSettingsConnect: pipe(channelSettings("connect"), Route.mapTo(AppRoute.ChannelSettingsConnect)), MySettingsAppearance: pipe(orgPath("my-settings"), Route.mapTo(AppRoute.MySettingsAppearance)), MySettingsProfile: pipe(orgPath("my-settings", "profile"), Route.mapTo(AppRoute.MySettingsProfile)), + MySettingsAgents: pipe(orgPath("my-settings", "agents"), Route.mapTo(AppRoute.MySettingsAgents)), MySettingsLinkedAccounts: pipe( orgPath("my-settings", "linked-accounts"), query(LinkedAccountsCallbackQuery), @@ -342,6 +384,7 @@ export const urlToAppRoute = Route.parseUrlWithFallback( routers.Join, routers.Invite, routers.BotInstall, + routers.OAuthAuthorize, routers.Onboarding, routers.OnboardingSetupOrganization, routers.SelectOrganization, @@ -356,6 +399,7 @@ export const urlToAppRoute = Route.parseUrlWithFallback( routers.ChannelSettingsConnect, routers.MySettingsAppearance, routers.MySettingsProfile, + routers.MySettingsAgents, routers.MySettingsLinkedAccounts, routers.MySettingsNotifications, routers.MySettingsDesktop, @@ -428,6 +472,7 @@ export const isPublicRoute = AppRoute.isAnyOf([ "Join", "Invite", "BotInstall", + "OAuthAuthorize", "NotFound", ]) @@ -452,6 +497,7 @@ export const isSettingsRoute = AppRoute.isAnyOf([ export const isMySettingsRoute = AppRoute.isAnyOf([ "MySettingsAppearance", "MySettingsProfile", + "MySettingsAgents", "MySettingsLinkedAccounts", "MySettingsNotifications", "MySettingsDesktop", @@ -537,6 +583,7 @@ export const titleOf = (route: AppRoute): string => { Join: () => "Join", Invite: () => "Invitation", BotInstall: () => "Install an app", + OAuthAuthorize: () => "Connect an agent", Onboarding: () => "Welcome", OnboardingSetupOrganization: () => "Welcome", SelectOrganization: () => "Select a workspace", diff --git a/apps/web-foldkit/src/shell/sidebars.ts b/apps/web-foldkit/src/shell/sidebars.ts index 45f91157f..2ed79e9d1 100644 --- a/apps/web-foldkit/src/shell/sidebars.ts +++ b/apps/web-foldkit/src/shell/sidebars.ts @@ -13,6 +13,7 @@ import { IconMsgs, IconPaintbrush, IconShop, + IconSparkles, IconThread, IconUser, IconUsers, @@ -173,6 +174,7 @@ export const mySettingsSidebar = ( const appearance = hrefOf(AppRoute.MySettingsAppearance({ orgSlug })) const profile = hrefOf(AppRoute.MySettingsProfile({ orgSlug })) const linkedAccounts = linkedAccountsHref(orgSlug) + const agents = hrefOf(AppRoute.MySettingsAgents({ orgSlug })) const notifications = hrefOf(AppRoute.MySettingsNotifications({ orgSlug })) const desktop = hrefOf(AppRoute.MySettingsDesktop({ orgSlug })) const keybinds = hrefOf(AppRoute.MySettingsKeybinds({ orgSlug })) @@ -199,6 +201,7 @@ export const mySettingsSidebar = ( onRoutes(route, "MySettingsLinkedAccounts"), IconArrowPath, ), + item("Agents", agents, onRoutes(route, "MySettingsAgents"), IconSparkles), item( "Notifications", notifications, diff --git a/packages/db/migrations/directory/0005_agent_access/migration.sql b/packages/db/migrations/directory/0005_agent_access/migration.sql new file mode 100644 index 000000000..baaf57dea --- /dev/null +++ b/packages/db/migrations/directory/0005_agent_access/migration.sql @@ -0,0 +1,44 @@ +CREATE TABLE IF NOT EXISTS "agent_auth_codes" ( + "codeHash" text PRIMARY KEY NOT NULL, + "clientId" text NOT NULL, + "userId" text NOT NULL, + "redirectUri" text NOT NULL, + "codeChallenge" text NOT NULL, + "scopes" text NOT NULL, + "expiresAt" text NOT NULL, + "redeemedAt" text, + "createdAt" text NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%f', 'now')) +); +--> statement-breakpoint +CREATE TABLE IF NOT EXISTS "agent_clients" ( + "id" text PRIMARY KEY NOT NULL DEFAULT (lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))), 2) || '-' || substr('89ab', 1 + (abs(random()) % 4), 1) || substr(lower(hex(randomblob(2))), 2) || '-' || lower(hex(randomblob(6)))), + "clientName" text NOT NULL, + "redirectUris" text NOT NULL, + "clientUri" text, + "logoUri" text, + "createdAt" text NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%f', 'now')) +); +--> statement-breakpoint +CREATE TABLE IF NOT EXISTS "agent_grants" ( + "id" text PRIMARY KEY NOT NULL DEFAULT (lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))), 2) || '-' || substr('89ab', 1 + (abs(random()) % 4), 1) || substr(lower(hex(randomblob(2))), 2) || '-' || lower(hex(randomblob(6)))), + "userId" text NOT NULL, + "kind" text NOT NULL, + "clientId" text, + "name" text NOT NULL, + "scopes" text NOT NULL, + "createdAt" text NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%f', 'now')), + "lastUsedAt" text, + "revokedAt" text +); +--> statement-breakpoint +CREATE TABLE IF NOT EXISTS "agent_tokens" ( + "tokenHash" text PRIMARY KEY NOT NULL, + "grantId" text NOT NULL, + "kind" text NOT NULL, + "expiresAt" text, + "createdAt" text NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%f', 'now')) +); +--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "agent_grants_user_idx" ON "agent_grants" ("userId"); +--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "agent_tokens_grant_idx" ON "agent_tokens" ("grantId"); diff --git a/packages/db/snapshots/channel.json b/packages/db/snapshots/channel.json index 0392139bf..e5d3a968d 100644 --- a/packages/db/snapshots/channel.json +++ b/packages/db/snapshots/channel.json @@ -1,5 +1,5 @@ { - "migration": "0002_channel_bot_region", + "migration": "0003_agent_access", "entities": [ { "kind": "table", @@ -36,6 +36,13 @@ "columns": ["id"] } }, + { + "kind": "table", + "name": "message_agent_marks", + "primaryKey": { + "columns": ["id"] + } + }, { "kind": "table", "name": "message_reactions", @@ -433,6 +440,78 @@ "notNull": false, "default": null }, + { + "kind": "column", + "table": "message_agent_marks", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null + }, + { + "kind": "column", + "table": "message_agent_marks", + "name": "channelId", + "position": 1, + "type": "text", + "notNull": true, + "default": null + }, + { + "kind": "column", + "table": "message_agent_marks", + "name": "organizationId", + "position": 2, + "type": "text", + "notNull": true, + "default": null + }, + { + "kind": "column", + "table": "message_agent_marks", + "name": "authorId", + "position": 3, + "type": "text", + "notNull": true, + "default": null + }, + { + "kind": "column", + "table": "message_agent_marks", + "name": "grantId", + "position": 4, + "type": "text", + "notNull": true, + "default": null + }, + { + "kind": "column", + "table": "message_agent_marks", + "name": "agentName", + "position": 5, + "type": "text", + "notNull": true, + "default": null + }, + { + "kind": "column", + "table": "message_agent_marks", + "name": "createdAt", + "position": 6, + "type": "text", + "notNull": true, + "default": "(strftime('%Y-%m-%d %H:%M:%f', 'now'))" + }, + { + "kind": "column", + "table": "message_agent_marks", + "name": "updatedAt", + "position": 7, + "type": "text", + "notNull": false, + "default": null + }, { "kind": "column", "table": "message_reactions", @@ -795,6 +874,13 @@ "unique": false, "columns": ["\"rootHazelMessageId\""] }, + { + "kind": "index", + "table": "message_agent_marks", + "name": "message_agent_marks_channel_idx", + "unique": false, + "columns": ["\"channelId\""] + }, { "kind": "index", "table": "message_reactions", diff --git a/packages/db/snapshots/directory.json b/packages/db/snapshots/directory.json index d2c167913..a489307df 100644 --- a/packages/db/snapshots/directory.json +++ b/packages/db/snapshots/directory.json @@ -1,6 +1,34 @@ { - "migration": "0004_push_device_tokens", + "migration": "0005_agent_access", "entities": [ + { + "kind": "table", + "name": "agent_auth_codes", + "primaryKey": { + "columns": ["codeHash"] + } + }, + { + "kind": "table", + "name": "agent_clients", + "primaryKey": { + "columns": ["id"] + } + }, + { + "kind": "table", + "name": "agent_grants", + "primaryKey": { + "columns": ["id"] + } + }, + { + "kind": "table", + "name": "agent_tokens", + "primaryKey": { + "columns": ["tokenHash"] + } + }, { "kind": "table", "name": "auth_credentials", @@ -153,6 +181,267 @@ "columns": ["namespace", "attempt_id"] } }, + { + "kind": "column", + "table": "agent_auth_codes", + "name": "codeHash", + "position": 0, + "type": "text", + "notNull": true, + "default": null + }, + { + "kind": "column", + "table": "agent_auth_codes", + "name": "clientId", + "position": 1, + "type": "text", + "notNull": true, + "default": null + }, + { + "kind": "column", + "table": "agent_auth_codes", + "name": "userId", + "position": 2, + "type": "text", + "notNull": true, + "default": null + }, + { + "kind": "column", + "table": "agent_auth_codes", + "name": "redirectUri", + "position": 3, + "type": "text", + "notNull": true, + "default": null + }, + { + "kind": "column", + "table": "agent_auth_codes", + "name": "codeChallenge", + "position": 4, + "type": "text", + "notNull": true, + "default": null + }, + { + "kind": "column", + "table": "agent_auth_codes", + "name": "scopes", + "position": 5, + "type": "text", + "notNull": true, + "default": null + }, + { + "kind": "column", + "table": "agent_auth_codes", + "name": "expiresAt", + "position": 6, + "type": "text", + "notNull": true, + "default": null + }, + { + "kind": "column", + "table": "agent_auth_codes", + "name": "redeemedAt", + "position": 7, + "type": "text", + "notNull": false, + "default": null + }, + { + "kind": "column", + "table": "agent_auth_codes", + "name": "createdAt", + "position": 8, + "type": "text", + "notNull": true, + "default": "(strftime('%Y-%m-%d %H:%M:%f', 'now'))" + }, + { + "kind": "column", + "table": "agent_clients", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": "(lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))), 2) || '-' || substr('89ab', 1 + (abs(random()) % 4), 1) || substr(lower(hex(randomblob(2))), 2) || '-' || lower(hex(randomblob(6))))" + }, + { + "kind": "column", + "table": "agent_clients", + "name": "clientName", + "position": 1, + "type": "text", + "notNull": true, + "default": null + }, + { + "kind": "column", + "table": "agent_clients", + "name": "redirectUris", + "position": 2, + "type": "text", + "notNull": true, + "default": null + }, + { + "kind": "column", + "table": "agent_clients", + "name": "clientUri", + "position": 3, + "type": "text", + "notNull": false, + "default": null + }, + { + "kind": "column", + "table": "agent_clients", + "name": "logoUri", + "position": 4, + "type": "text", + "notNull": false, + "default": null + }, + { + "kind": "column", + "table": "agent_clients", + "name": "createdAt", + "position": 5, + "type": "text", + "notNull": true, + "default": "(strftime('%Y-%m-%d %H:%M:%f', 'now'))" + }, + { + "kind": "column", + "table": "agent_grants", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": "(lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))), 2) || '-' || substr('89ab', 1 + (abs(random()) % 4), 1) || substr(lower(hex(randomblob(2))), 2) || '-' || lower(hex(randomblob(6))))" + }, + { + "kind": "column", + "table": "agent_grants", + "name": "userId", + "position": 1, + "type": "text", + "notNull": true, + "default": null + }, + { + "kind": "column", + "table": "agent_grants", + "name": "kind", + "position": 2, + "type": "text", + "notNull": true, + "default": null + }, + { + "kind": "column", + "table": "agent_grants", + "name": "clientId", + "position": 3, + "type": "text", + "notNull": false, + "default": null + }, + { + "kind": "column", + "table": "agent_grants", + "name": "name", + "position": 4, + "type": "text", + "notNull": true, + "default": null + }, + { + "kind": "column", + "table": "agent_grants", + "name": "scopes", + "position": 5, + "type": "text", + "notNull": true, + "default": null + }, + { + "kind": "column", + "table": "agent_grants", + "name": "createdAt", + "position": 6, + "type": "text", + "notNull": true, + "default": "(strftime('%Y-%m-%d %H:%M:%f', 'now'))" + }, + { + "kind": "column", + "table": "agent_grants", + "name": "lastUsedAt", + "position": 7, + "type": "text", + "notNull": false, + "default": null + }, + { + "kind": "column", + "table": "agent_grants", + "name": "revokedAt", + "position": 8, + "type": "text", + "notNull": false, + "default": null + }, + { + "kind": "column", + "table": "agent_tokens", + "name": "tokenHash", + "position": 0, + "type": "text", + "notNull": true, + "default": null + }, + { + "kind": "column", + "table": "agent_tokens", + "name": "grantId", + "position": 1, + "type": "text", + "notNull": true, + "default": null + }, + { + "kind": "column", + "table": "agent_tokens", + "name": "kind", + "position": 2, + "type": "text", + "notNull": true, + "default": null + }, + { + "kind": "column", + "table": "agent_tokens", + "name": "expiresAt", + "position": 3, + "type": "text", + "notNull": false, + "default": null + }, + { + "kind": "column", + "table": "agent_tokens", + "name": "createdAt", + "position": 4, + "type": "text", + "notNull": true, + "default": "(strftime('%Y-%m-%d %H:%M:%f', 'now'))" + }, { "kind": "column", "table": "auth_credentials", @@ -1989,6 +2278,20 @@ "notNull": true, "default": null }, + { + "kind": "index", + "table": "agent_grants", + "name": "agent_grants_user_idx", + "unique": false, + "columns": ["\"userId\""] + }, + { + "kind": "index", + "table": "agent_tokens", + "name": "agent_tokens_grant_idx", + "unique": false, + "columns": ["\"grantId\""] + }, { "kind": "index", "table": "auth_credentials", diff --git a/packages/db/src/migrations.generated.ts b/packages/db/src/migrations.generated.ts index 023b2764b..c16d43283 100644 --- a/packages/db/src/migrations.generated.ts +++ b/packages/db/src/migrations.generated.ts @@ -96,6 +96,17 @@ export const generatedMigrations: Record(), + clientUri: SQLite.nullable(SQLite.text), + logoUri: SQLite.nullable(SQLite.text), + createdAt: SQLite.column(timestamptz, { defaultExpr: SQLite.timestampNow }), + }, + primaryKey: ["id"], +}) +export type AgentClient = SQLite.SelectRowOf + +export const agentGrantKindEnum = textEnum(["oauth", "token"]) + +/** + * One agent a user let act for them: an approved OAuth client (`kind = "oauth"`) or a personal + * access token (`kind = "token"`). Revoking it ends every token it issued. + */ +export const agentGrantsTable = SQLite.table("agent_grants", { + columns: { + id: SQLite.column(uuid(AgentGrantId), { defaultExpr: randomUuid }), + userId: uuid(UserId), + kind: agentGrantKindEnum, + clientId: SQLite.nullable(uuid(AgentClientId)), + /** What the user and chat see: the client's name, or the token's label. */ + name: SQLite.text, + scopes: jsonb(), + createdAt: SQLite.column(timestamptz, { defaultExpr: SQLite.timestampNow }), + lastUsedAt: SQLite.nullable(timestamptz), + revokedAt: SQLite.nullable(timestamptz), + }, + primaryKey: ["id"], + indexes: [SQLite.index("agent_grants_user_idx", ["userId"])], +}) +export type AgentGrant = SQLite.SelectRowOf + +export const agentTokenKindEnum = textEnum(["access", "refresh", "personal"]) + +/** A bearer credential of a grant, by its SHA-256 hex. `expiresAt` null: until revoked. */ +export const agentTokensTable = SQLite.table("agent_tokens", { + columns: { + tokenHash: varchar(64), + grantId: uuid(AgentGrantId), + kind: agentTokenKindEnum, + expiresAt: SQLite.nullable(timestamptz), + createdAt: SQLite.column(timestamptz, { defaultExpr: SQLite.timestampNow }), + }, + primaryKey: ["tokenHash"], + indexes: [SQLite.index("agent_tokens_grant_idx", ["grantId"])], +}) +export type AgentToken = SQLite.SelectRowOf + +/** An authorization code (the consent page's approval), redeemed once at `POST /oauth/token`. */ +export const agentAuthCodesTable = SQLite.table("agent_auth_codes", { + columns: { + codeHash: varchar(64), + clientId: uuid(AgentClientId), + userId: uuid(UserId), + redirectUri: SQLite.text, + codeChallenge: SQLite.text, + scopes: jsonb(), + expiresAt: timestamptz, + redeemedAt: SQLite.nullable(timestamptz), + createdAt: SQLite.column(timestamptz, { defaultExpr: SQLite.timestampNow }), + }, + primaryKey: ["codeHash"], +}) +export type AgentAuthCode = SQLite.SelectRowOf + +/** + * A message an agent wrote (or last edited) for its author, keyed by the message's id. Written in + * the same transaction as the message by `message.create` / `message.update` when the call came + * through the MCP server. Synced only to viewers in `organizationId` (the author's organization): + * Connect viewers from other organizations, and chat-sync copies, never see it. + */ +export const messageAgentMarksTable = SQLite.table("message_agent_marks", { + columns: { + id: uuid(MessageId), + channelId: uuid(ChannelId), + organizationId: uuid(OrganizationId), + authorId: uuid(UserId), + grantId: uuid(AgentGrantId), + agentName: SQLite.text, + createdAt: SQLite.column(timestamptz, { defaultExpr: SQLite.timestampNow }), + updatedAt: SQLite.nullable(timestamptz), + }, + primaryKey: ["id"], + indexes: [SQLite.index("message_agent_marks_channel_idx", ["channelId"])], +}) +export type MessageAgentMark = SQLite.SelectRowOf diff --git a/packages/db/src/tables/index.ts b/packages/db/src/tables/index.ts index cfcbd4dea..ec35ea717 100644 --- a/packages/db/src/tables/index.ts +++ b/packages/db/src/tables/index.ts @@ -1,6 +1,7 @@ // Every Hazel table as an effect-orm SQLite definition: the query builder reads them, and // `renderStoreSchema` (`../schema-ddl.ts`) writes their DDL. +export * from "./agents" export * from "./attachments" export * from "./auth" export * from "./bot-commands" diff --git a/packages/domain/src/http/agent-access.ts b/packages/domain/src/http/agent-access.ts new file mode 100644 index 000000000..ab68625e3 --- /dev/null +++ b/packages/domain/src/http/agent-access.ts @@ -0,0 +1,181 @@ +/** + * Agent access: a user lets an agent act for them through Hazel's MCP server (`POST /mcp`). Agents + * connect with OAuth (Hazel is the authorization server; the consent page calls `authorizeAgent`) + * or with a personal access token. Every agent is a grant the user lists and revokes here. + * + * Messages an agent writes are marked in chat ("via ") for the author's own organization. + * + * The OAuth protocol endpoints themselves (`/.well-known/*`, `/oauth/register`, `/oauth/token`) + * are raw routes in the api Worker (`routes/agent-oauth.ts`), not part of this group. + */ +import { HttpApiEndpoint, HttpApiGroup, OpenApi } from "effect/http-api" +import { Schema } from "effect" +import { AgentClientId, AgentGrantId } from "@hazel/schema" +import * as CurrentUser from "../current-user" +import { InternalServerError, UnauthorizedError } from "../errors" +import { RequiredScopes } from "../scopes/required-scopes" + +/** What an agent may do: read only, or read and write (send, reply, react, edit, delete). */ +export const AgentScope = Schema.Literals(["messages:read", "messages:write"]) +export type AgentScope = typeof AgentScope.Type + +export const ALL_AGENT_SCOPES: ReadonlyArray = ["messages:read", "messages:write"] + +/** Parse an OAuth `scope` string; unknown scopes are dropped, none means every scope. */ +export const parseAgentScopes = (scope: string | null | undefined): ReadonlyArray => { + const requested = (scope ?? "").split(/\s+/).filter((s): s is AgentScope => Schema.is(AgentScope)(s)) + return requested.length === 0 ? ALL_AGENT_SCOPES : [...new Set(requested)] +} + +export class AgentClientInfo extends Schema.Class("AgentClientInfo")({ + id: AgentClientId, + name: Schema.String, + clientUri: Schema.NullOr(Schema.String), + logoUri: Schema.NullOr(Schema.String), + /** The redirect URI's host, shown on the consent page ("you will return to …"). */ + redirectHost: Schema.String, +}) {} + +export class AgentGrantInfo extends Schema.Class("AgentGrantInfo")({ + id: AgentGrantId, + kind: Schema.Literals(["oauth", "token"]), + name: Schema.String, + scopes: Schema.Array(AgentScope), + createdAt: Schema.DateTimeUtcFromString, + lastUsedAt: Schema.NullOr(Schema.DateTimeUtcFromString), +}) {} + +export class AgentGrantsResponse extends Schema.Class("AgentGrantsResponse")({ + grants: Schema.Array(AgentGrantInfo), + /** The MCP server's URL, to paste into an agent's config. */ + mcpUrl: Schema.String, +}) {} + +export class AuthorizeAgentRequest extends Schema.Class("AuthorizeAgentRequest")({ + clientId: AgentClientId, + redirectUri: Schema.String, + codeChallenge: Schema.String, + codeChallengeMethod: Schema.String, + scope: Schema.optional(Schema.String), + state: Schema.optional(Schema.String), + /** Approve, or deny (the client is sent `error=access_denied`). */ + approve: Schema.Boolean, +}) {} + +export class AuthorizeAgentResponse extends Schema.Class("AuthorizeAgentResponse")({ + /** Where the consent page sends the browser next: the client's redirect URI with the result. */ + redirectTo: Schema.String, +}) {} + +export class CreateAgentTokenRequest extends Schema.Class("CreateAgentTokenRequest")( + { + name: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(80)), + scopes: Schema.Array(AgentScope).check(Schema.isMinLength(1)), + }, +) {} + +export class CreateAgentTokenResponse extends Schema.Class( + "CreateAgentTokenResponse", +)({ + grant: AgentGrantInfo, + /** Shown once; only its hash is kept. */ + token: Schema.String, +}) {} + +/** The client is unknown, or the redirect URI is not one it registered; never redirected to. */ +export class AgentClientInvalidError extends Schema.TaggedError()( + "AgentClientInvalidError", + { message: Schema.String }, + { httpApiStatus: 400 }, +) {} + +export class AgentGrantNotFoundError extends Schema.TaggedError()( + "AgentGrantNotFoundError", + { grantId: AgentGrantId }, + { httpApiStatus: 404 }, +) {} + +export class AgentAccessGroup extends HttpApiGroup.make("agentAccess") + .add( + HttpApiEndpoint.get("getAgentClient", `/clients/:clientId`, { + params: { clientId: AgentClientId }, + query: { redirect_uri: Schema.String }, + success: AgentClientInfo, + error: [AgentClientInvalidError, UnauthorizedError, InternalServerError], + }) + .middleware(CurrentUser.Authorization) + .annotateMerge( + OpenApi.annotations({ + title: "Get Agent Client", + description: + "The OAuth client a consent page asks about, checked against its redirect URI.", + summary: "Get agent client", + }), + ) + .annotate(RequiredScopes, []), + ) + .add( + HttpApiEndpoint.post("authorizeAgent", `/authorize`, { + payload: AuthorizeAgentRequest, + success: AuthorizeAgentResponse, + error: [AgentClientInvalidError, UnauthorizedError, InternalServerError], + }) + .middleware(CurrentUser.Authorization) + .annotateMerge( + OpenApi.annotations({ + title: "Authorize Agent", + description: + "The consent page's answer: on approval issues an authorization code for the client's redirect URI.", + summary: "Authorize agent", + }), + ) + .annotate(RequiredScopes, []), + ) + .add( + HttpApiEndpoint.get("listAgentGrants", `/grants`, { + success: AgentGrantsResponse, + error: [UnauthorizedError, InternalServerError], + }) + .middleware(CurrentUser.Authorization) + .annotateMerge( + OpenApi.annotations({ + title: "List Agent Grants", + description: "The agents (OAuth apps and personal tokens) that may act for you.", + summary: "List agent grants", + }), + ) + .annotate(RequiredScopes, []), + ) + .add( + HttpApiEndpoint.delete("revokeAgentGrant", `/grants/:grantId`, { + params: { grantId: AgentGrantId }, + success: Schema.Void, + error: [AgentGrantNotFoundError, UnauthorizedError, InternalServerError], + }) + .middleware(CurrentUser.Authorization) + .annotateMerge( + OpenApi.annotations({ + title: "Revoke Agent Grant", + description: "Stop an agent acting for you; its tokens stop working at once.", + summary: "Revoke agent grant", + }), + ) + .annotate(RequiredScopes, []), + ) + .add( + HttpApiEndpoint.post("createAgentToken", `/tokens`, { + payload: CreateAgentTokenRequest, + success: CreateAgentTokenResponse, + error: [UnauthorizedError, InternalServerError], + }) + .middleware(CurrentUser.Authorization) + .annotateMerge( + OpenApi.annotations({ + title: "Create Personal Access Token", + description: "A token an agent puts in its MCP config to act for you.", + summary: "Create personal access token", + }), + ) + .annotate(RequiredScopes, []), + ) + .prefix("/agent-access") {} diff --git a/packages/domain/src/http/api.ts b/packages/domain/src/http/api.ts index 6a07acbe5..1b6fd2453 100644 --- a/packages/domain/src/http/api.ts +++ b/packages/domain/src/http/api.ts @@ -1,4 +1,5 @@ import { HttpApi, OpenApi } from "effect/http-api" +import { AgentAccessGroup } from "./agent-access" import { IntegrationsApiGroup as ApiV1IntegrationsApiGroup } from "./api-v1/integrations" import { MessagesApiGroup } from "./api-v1/messages" import { BotsApiGroup as ApiV1BotsApiGroup } from "./api-v1/bots" @@ -23,6 +24,7 @@ export class HazelApi extends HttpApi.make("HazelApp") .add(RootGroup) .add(IntegrationGroup) .add(T3CodeGroup) + .add(AgentAccessGroup) .add(IntegrationCommandGroup) .add(IntegrationResourceGroup) .add(IncomingWebhookGroup) diff --git a/packages/domain/src/http/index.ts b/packages/domain/src/http/index.ts index a84545ead..c8a885d5a 100644 --- a/packages/domain/src/http/index.ts +++ b/packages/domain/src/http/index.ts @@ -24,5 +24,7 @@ export * from "./uploads" export * as Uploads from "./uploads" export * from "./webhooks" export * as Webhooks from "./webhooks" +export * from "./agent-access" +export * as AgentAccess from "./agent-access" export * from "./t3code" export * as T3Code from "./t3code" diff --git a/packages/domain/src/models/index.ts b/packages/domain/src/models/index.ts index 8fd8fcb73..7cd7763ba 100644 --- a/packages/domain/src/models/index.ts +++ b/packages/domain/src/models/index.ts @@ -30,6 +30,7 @@ export * as OrganizationMember from "./organization-member-model" export * as Organization from "./organization-model" export * as PinnedMessage from "./pinned-message-model" export * as RssSubscription from "./rss-subscription-model" +export * as MessageAgentMark from "./message-agent-mark-model" export * as TypingIndicator from "./typing-indicator-model" export * as Theme from "./theme-model" export * as User from "./user-model" diff --git a/packages/domain/src/models/message-agent-mark-model.ts b/packages/domain/src/models/message-agent-mark-model.ts new file mode 100644 index 000000000..16c39fd0b --- /dev/null +++ b/packages/domain/src/models/message-agent-mark-model.ts @@ -0,0 +1,22 @@ +import { AgentGrantId, ChannelId, MessageId, OrganizationId, UserId } from "@hazel/schema" +import { Schema as S } from "effect" +import * as M from "./utils" +import { JsonDate } from "./utils" + +/** + * A message an agent wrote (or last edited) for its author over Hazel's MCP server; `id` is the + * message's id. Synced only to the author's own organization. + */ +class Model extends M.Class("MessageAgentMark")({ + id: MessageId, + channelId: ChannelId, + organizationId: OrganizationId, + authorId: UserId, + grantId: AgentGrantId, + agentName: S.String, + createdAt: M.Generated(JsonDate), + updatedAt: M.Generated(S.NullOr(JsonDate)), +}) {} + +export const { Insert, Update, Schema, Create, Patch } = M.expose(Model) +export type Type = typeof Schema.Type diff --git a/packages/schema/src/ids.ts b/packages/schema/src/ids.ts index 97f1abb0e..286db6e90 100644 --- a/packages/schema/src/ids.ts +++ b/packages/schema/src/ids.ts @@ -433,3 +433,19 @@ export const CustomerMetricDefinitionId = Schema.String.check(Schema.isUUID()) title: "Customer Metric Definition ID", }) export type CustomerMetricDefinitionId = Schema.Schema.Type + +export const AgentClientId = Schema.String.check(Schema.isUUID()) + .pipe(Schema.brand("@HazelChat/AgentClientId")) + .annotate({ + description: "The ID of an MCP OAuth client registered with Hazel", + title: "Agent Client ID", + }) +export type AgentClientId = Schema.Schema.Type + +export const AgentGrantId = Schema.String.check(Schema.isUUID()) + .pipe(Schema.brand("@HazelChat/AgentGrantId")) + .annotate({ + description: "The ID of a user's grant letting an agent act for them (OAuth or personal token)", + title: "Agent Grant ID", + }) +export type AgentGrantId = Schema.Schema.Type From 8eb67d8f37cf48c41d30e1c189fd7d8d68ebdb19 Mon Sep 17 00:00:00 2001 From: Makisuo Date: Mon, 16 Nov 2026 15:24:08 +0100 Subject: [PATCH 2/6] feat(mcp): let agents upload files and set the user's status - upload_file: a file's content inline (base64 or text, up to 10 MB), stored server-side and completed in one call. - create_upload_url: a presigned PUT (15 min) for files on disk or too big to inline; send_message checks the file is in the bucket before completing it. - send_message takes attachment_ids (up to 10), content optional with files. - set_status: emoji, message, expiry and presence (online/away/busy/dnd), or clear. Active content types (HTML, SVG...) are stored as application/octet-stream, as for the web app. The attachment row is created through a helper shared with the presign route (services/attachment-uploads.ts); ObjectStorage gains put and exists. The consent page now lists files and status, and no longer says edits are limited to messages the agent sent (they are limited to the user's own). Co-Authored-By: Claude Opus 5.5 --- apps/backend/src/routes/mcp.http.test.ts | 126 ++++++- apps/backend/src/routes/mcp.ts | 308 +++++++++++++++++- apps/backend/src/routes/uploads.http.ts | 38 +-- .../src/services/attachment-uploads.ts | 42 +++ apps/backend/src/services/object-storage.ts | 36 +- .../src/page/my-settings/agents/view.ts | 2 +- .../src/page/oauth-authorize/view.ts | 4 +- 7 files changed, 504 insertions(+), 52 deletions(-) create mode 100644 apps/backend/src/services/attachment-uploads.ts diff --git a/apps/backend/src/routes/mcp.http.test.ts b/apps/backend/src/routes/mcp.http.test.ts index e87a1a14f..43b523d50 100644 --- a/apps/backend/src/routes/mcp.http.test.ts +++ b/apps/backend/src/routes/mcp.http.test.ts @@ -13,8 +13,9 @@ import { HttpRouter } from "effect/http" import { describe, expect, it } from "vitest" import { AgentAccess } from "../services/agent-access" import { Directory } from "../services/directory" +import { ObjectStorage } from "../services/object-storage" import { RateLimiterAllowAll } from "../services/rate-limiter" -import { channelTarget, orgTarget } from "../worker/objects/kinds" +import { channelTarget, orgTarget, userTarget } from "../worker/objects/kinds" import { ObjectStubs } from "../worker/objects/protocol" import { makeTestObjects, type TestObject } from "../worker/objects/testing" import { AgentOAuthRoutes } from "./agent-oauth" @@ -79,7 +80,19 @@ const makeWorld = Effect.gen(function* () { }), ) + // The bucket: what `put` stored, and what a presigned PUT would have. + const bucket = new Map() + const storage = Layer.succeed(ObjectStorage)({ + presignPut: (key: string, options: { contentType: string }) => + Effect.succeed(`https://bucket.test/${key}?type=${encodeURIComponent(options.contentType)}`), + put: (key: string, bytes: Uint8Array, contentType: string) => + Effect.sync(() => { + bucket.set(key, { bytes, contentType }) + }), + exists: (key: string) => Effect.succeed(bucket.has(key)), + } as never) const services = Layer.mergeAll( + storage, AgentAccess.layer.pipe(Layer.provide(Layer.succeedContext(objects.directory))), Layer.succeedContext(objects.directory), Layer.succeed(ObjectStubs, objects.stubs), @@ -104,7 +117,7 @@ const makeWorld = Effect.gen(function* () { yield* Layer.build(AgentAccess.layer.pipe(Layer.provide(Layer.succeedContext(objects.directory)))), AgentAccess, ) - return { objects, orgId, alice, channelId, channel, fetch, access } + return { objects, orgId, alice, channelId, channel, fetch, access, bucket } }).pipe(Effect.orDie) type World = Effect.Success @@ -374,4 +387,113 @@ describe("MCP server", () => { expect(note.status).toBe(202) }), )) + + it("files: upload inline or through a URL, then post them; set and clear the status", () => + run( + Effect.gen(function* () { + const world = yield* makeWorld + const { token } = yield* world.access.createPersonalToken({ + userId: world.alice, + name: "Claude Code", + scopes: ["messages:read", "messages:write"], + }) + const attachments = () => + world.channel.storage.db + .prepare( + `SELECT id, fileName, fileSize, status, messageId, uploadedBy FROM attachments`, + ) + .all() as Array> + + // Inline: stored, complete, then attached to the message. + const uploaded = yield* callTool(world, token, "upload_file", { + channel_id: world.channelId, + file_name: "notes.txt", + text: "hello file", + }) + expect(uploaded.isError).toBeUndefined() + const inlineId = uploaded.structuredContent.attachment_id + expect(uploaded.structuredContent).toMatchObject({ size: 10, content_type: "text/plain" }) + expect(new TextDecoder().decode(world.bucket.get(inlineId)!.bytes)).toBe("hello file") + expect(attachments()).toEqual([ + expect.objectContaining({ + id: inlineId, + fileName: "notes.txt", + status: "complete", + uploadedBy: world.alice, + }), + ]) + + // Active content is stored as a download, never as HTML. + const html = yield* callTool(world, token, "upload_file", { + channel_id: world.channelId, + file_name: "page.html", + content_base64: Buffer.from("").toString("base64"), + }) + expect(html.structuredContent.content_type).toBe("application/octet-stream") + + // Through a URL: refused until the bytes are in the bucket. + const url = yield* callTool(world, token, "create_upload_url", { + channel_id: world.channelId, + file_name: "demo.png", + file_size: 3, + }) + const urlId = url.structuredContent.attachment_id + expect(url.structuredContent).toMatchObject({ + method: "PUT", + headers: { "Content-Type": "image/png" }, + }) + const early = yield* callTool(world, token, "send_message", { + channel_id: world.channelId, + attachment_ids: [urlId], + }) + expect(early.isError).toBe(true) + world.bucket.set(urlId, { bytes: new Uint8Array([1, 2, 3]), contentType: "image/png" }) + + const sent = yield* callTool(world, token, "send_message", { + channel_id: world.channelId, + content: "Here you go", + attachment_ids: [inlineId, urlId], + }) + expect(sent.isError).toBeUndefined() + const messageId = sent.structuredContent.message.id + const linked = attachments().filter((row) => row.messageId === messageId) + expect(linked.map((row) => row.id).sort()).toEqual([inlineId, urlId].sort()) + expect(linked.every((row) => row.status === "complete")).toBe(true) + + // Too big is refused before anything is created. + const huge = yield* callTool(world, token, "create_upload_url", { + channel_id: world.channelId, + file_name: "huge.bin", + file_size: 50 * 1024 * 1024, + }) + expect(huge.isError).toBe(true) + + // Status: set with an expiry and a presence, then clear. + const user = yield* world.objects.get(userTarget(world.alice)) + const status = () => + user.storage.db + .prepare( + `SELECT status, statusEmoji, customMessage, statusExpiresAt FROM user_presence_status`, + ) + .get() as Record + const set = yield* callTool(world, token, "set_status", { + emoji: "🌴", + message: "Out until Monday", + expires_in_minutes: 60, + presence: "away", + }) + expect(set.isError).toBeUndefined() + expect(status()).toMatchObject({ + status: "away", + statusEmoji: "🌴", + customMessage: "Out until Monday", + }) + expect(status().statusExpiresAt).not.toBeNull() + const cleared = yield* callTool(world, token, "set_status", { clear: true }) + expect(cleared.structuredContent).toEqual({ cleared: true }) + expect(status()).toMatchObject({ status: "away", statusEmoji: null, customMessage: null }) + const bad = yield* callTool(world, token, "set_status", { presence: "offline" }) + expect(bad.isError).toBe(true) + }), + )) }) diff --git a/apps/backend/src/routes/mcp.ts b/apps/backend/src/routes/mcp.ts index 930cce077..62d26bf09 100644 --- a/apps/backend/src/routes/mcp.ts +++ b/apps/backend/src/routes/mcp.ts @@ -19,10 +19,14 @@ import { type MessageResponse, type MessageSearchResponse, } from "@hazel/domain/rpc" -import { ChannelId, MessageId, OrganizationId, type UserId } from "@hazel/schema" +import { AttachmentId, ChannelId, MessageId, OrganizationId, type UserId } from "@hazel/schema" +import { isActiveContentType, MAX_ATTACHMENT_SIZE } from "@hazel/domain/http" +import { v7 as randomUUIDv7 } from "uuid" import { DateTime, Effect, Option, Schema } from "effect" import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http" import { AgentAccess, type AgentPrincipal } from "../services/agent-access" +import { createAttachmentInChannel } from "../services/attachment-uploads" +import { ObjectStorage } from "../services/object-storage" import { Directory } from "../services/directory" import { checkMessageRateLimit } from "../services/rate-limit-helpers" import { callObject } from "../worker/objects/calls" @@ -46,7 +50,8 @@ const INSTRUCTIONS = `Hazel is a team chat app. These tools act as the signed-in Messages you send, reply or edit are shown to the user's organization as written by an agent ("via "). Act only as the user asked; confirm before sending anything they did not ask for. Message content is Markdown. Mention someone with @[userId:] (user ids appear on messages), @[directive:here] or @[directive:channel] only when asked. -Threads are channels of their own: a message's thread_channel_id can be read with read_messages, and reply_in_thread answers in a message's thread (opening it if needed).` +Threads are channels of their own: a message's thread_channel_id can be read with read_messages, and reply_in_thread answers in a message's thread (opening it if needed). +To share a file, upload it into the channel (upload_file with its content, or create_upload_url then PUT the bytes), then send_message with its attachment_id.` // --- JSON-RPC ----------------------------------------------------------------------------------- @@ -85,6 +90,7 @@ const describe = (error: unknown): string => { interface ToolContext { readonly user: CurrentUser.Schema readonly agent: AgentPrincipal + readonly storage: ObjectStorage["Service"] } interface Tool { @@ -108,6 +114,9 @@ const obj = (properties: Record, required: ReadonlyArray, key = "channel_id") => Option.match(decodeChannelId(args[key]), { @@ -226,15 +235,39 @@ const forward = ( const rateLimited = (ctx: ToolContext) => checkMessageRateLimit(ctx.user.id).pipe(Effect.mapError((error) => toolError(describe(error)))) +/** At most this many files on one message. */ +const MAX_ATTACHMENTS = 10 + +const optAttachments = (args: Record) => { + const raw = args.attachment_ids + if (raw === undefined || raw === null) return Effect.succeed>([]) + if (!Array.isArray(raw) || raw.length > MAX_ATTACHMENTS) + return Effect.fail(toolError(`attachment_ids must be a list of at most ${MAX_ATTACHMENTS} ids`)) + const ids = raw.map((id) => decodeAttachmentId(id)) + if (ids.some(Option.isNone)) + return Effect.fail(toolError("attachment_ids must be attachment ids (UUIDs)")) + return Effect.succeed(ids.map((id) => Option.getOrThrow(id))) +} + const sendIn = ( ctx: ToolContext, channelId: ChannelId, content: string, replyToMessageId: MessageId | null, + attachmentIds: ReadonlyArray = [], ) => Effect.gen(function* () { const { host } = yield* channelInfo(channelId) yield* rateLimited(ctx) + // A presigned upload is finished once its file is in the bucket; mark it complete then. + for (const id of attachmentIds) { + const stored = yield* ctx.storage + .exists(id) + .pipe(Effect.mapError((error) => toolError(error.message))) + if (!stored) + return yield* toolError(`File ${id} is not uploaded yet: PUT it to its upload_url first`) + yield* forward(host, "attachment.complete", { id, channelId }) + } const response = yield* forward(host, "message.create", { channelId, content, @@ -243,10 +276,77 @@ const sendIn = ( embeds: null, replyToMessageId, threadChannelId: null, + ...(attachmentIds.length === 0 ? {} : { attachmentIds: [...attachmentIds] }), }) - return { sent: true, message: (yield* present([response.data]))[0] } + return { + sent: true, + message: (yield* present([response.data]))[0], + ...(attachmentIds.length === 0 ? {} : { attachment_ids: attachmentIds }), + } }) +/** The content type a file is stored with; active types (HTML, SVG…) only as a download. */ +const storedContentType = (fileName: string, given: unknown) => { + const type = typeof given === "string" && given.trim() !== "" ? given.trim() : guessContentType(fileName) + return isActiveContentType(type) ? "application/octet-stream" : type +} + +const EXTENSION_TYPES: Record = { + png: "image/png", + jpg: "image/jpeg", + jpeg: "image/jpeg", + gif: "image/gif", + webp: "image/webp", + pdf: "application/pdf", + txt: "text/plain", + md: "text/markdown", + csv: "text/csv", + json: "application/json", + zip: "application/zip", + mp4: "video/mp4", + mov: "video/quicktime", + mp3: "audio/mpeg", + wav: "audio/wav", +} + +const guessContentType = (fileName: string) => + EXTENSION_TYPES[fileName.split(".").pop()?.toLowerCase() ?? ""] ?? "application/octet-stream" + +const argFileName = (args: Record) => { + const name = typeof args.file_name === "string" ? args.file_name.trim().replace(/[\\/]/g, "_") : "" + if (name === "" || name.length > 255) + return Effect.fail(toolError("file_name must be 1 to 255 characters")) + return Effect.succeed(name) +} + +/** The `uploading` row in the channel (the channel refuses a user who cannot see it). */ +const startUpload = (ctx: ToolContext, channelId: ChannelId, fileName: string, fileSize: number) => + Effect.gen(function* () { + if (fileSize < 1 || fileSize > MAX_ATTACHMENT_SIZE) + return yield* toolError(`Files must be 1 byte to ${MAX_ATTACHMENT_SIZE / 1024 / 1024} MB`) + const { organizationId } = yield* channelInfo(channelId) + const id = AttachmentId.make(randomUUIDv7()) + yield* createAttachmentInChannel({ + id, + organizationId, + channelId, + uploadedBy: ctx.user.id, + fileName, + fileSize, + }).pipe(Effect.mapError((error) => toolError(describe(error)))) + return id + }) + +const decodeBase64 = (value: string) => { + try { + return Option.some(Uint8Array.from(atob(value.replace(/\s+/g, "")), (char) => char.charCodeAt(0))) + } catch { + return Option.none>() + } +} + +const PRESENCE = ["online", "away", "busy", "dnd"] as const + const tools: ReadonlyArray = [ { name: "list_organizations", @@ -456,17 +556,121 @@ const tools: ReadonlyArray = [ inputSchema: obj( { channel_id: str("Where to post"), - content: str("Markdown text"), + content: str("Markdown text (may be empty when sending files)"), reply_to_message_id: str("Reply to this message (inline quote)"), + attachment_ids: { + type: "array", + items: { type: "string" }, + maxItems: MAX_ATTACHMENTS, + description: + "Files to attach, from upload_file or create_upload_url in this same channel", + }, }, - ["channel_id", "content"], + ["channel_id"], ), run: (args, ctx) => Effect.gen(function* () { const channelId = yield* argChannel(args) - const content = yield* argContent(args) + const attachmentIds = yield* optAttachments(args) + const content = + attachmentIds.length > 0 && (args.content === undefined || args.content === "") + ? "" + : yield* argContent(args) const replyTo = yield* optMessage(args, "reply_to_message_id") - return yield* sendIn(ctx, channelId, content, replyTo) + return yield* sendIn(ctx, channelId, content, replyTo, attachmentIds) + }), + }, + { + name: "upload_file", + title: "Upload file", + description: + "Upload a file (up to 10 MB) into a channel from its content: base64 for any file, or text for a text file. Returns an attachment_id; post it with send_message's attachment_ids. For large files or files on disk, use create_upload_url instead.", + scope: "messages:write", + readOnly: false, + inputSchema: obj( + { + channel_id: str("The channel (or thread channel) the file will be posted in"), + file_name: str("The file's name, e.g. report.pdf"), + content_base64: str("The file's bytes, base64-encoded"), + text: str("The file's content as text (instead of content_base64)"), + content_type: str("MIME type; guessed from the file name when omitted"), + }, + ["channel_id", "file_name"], + ), + run: (args, ctx) => + Effect.gen(function* () { + const channelId = yield* argChannel(args) + const fileName = yield* argFileName(args) + const bytes = + typeof args.content_base64 === "string" + ? yield* Option.match(decodeBase64(args.content_base64), { + onNone: () => Effect.fail(toolError("content_base64 is not valid base64")), + onSome: Effect.succeed, + }) + : typeof args.text === "string" + ? new TextEncoder().encode(args.text) + : yield* toolError("Give content_base64 or text") + // Text with no type and an unknown extension is plain text. + const contentType = storedContentType( + fileName, + args.content_type ?? + (typeof args.content_base64 !== "string" && + guessContentType(fileName) === "application/octet-stream" + ? "text/plain" + : undefined), + ) + const id = yield* startUpload(ctx, channelId, fileName, bytes.byteLength) + const { host } = yield* channelInfo(channelId) + yield* ctx.storage.put(id, bytes as Uint8Array, contentType).pipe( + Effect.tapError(() => + forward(host, "attachment.fail", { id, channelId, reason: "MCP upload failed" }).pipe( + Effect.ignore, + ), + ), + Effect.mapError((error) => toolError(error.message)), + ) + yield* forward(host, "attachment.complete", { id, channelId }) + return { + attachment_id: id, + file_name: fileName, + size: bytes.byteLength, + content_type: contentType, + } + }), + }, + { + name: "create_upload_url", + title: "Create upload URL", + description: + "For a file on disk or too big to inline (up to 10 MB): returns an upload_url valid for 15 minutes. PUT the raw bytes there with the given headers (e.g. curl -X PUT -H 'Content-Type: …' --data-binary @file ''), then post attachment_id with send_message's attachment_ids.", + scope: "messages:write", + readOnly: false, + inputSchema: obj( + { + channel_id: str("The channel (or thread channel) the file will be posted in"), + file_name: str("The file's name, e.g. demo.mp4"), + file_size: { type: "integer", minimum: 1, description: "Size in bytes" }, + content_type: str("MIME type; guessed from the file name when omitted"), + }, + ["channel_id", "file_name", "file_size"], + ), + run: (args, ctx) => + Effect.gen(function* () { + const channelId = yield* argChannel(args) + const fileName = yield* argFileName(args) + const fileSize = typeof args.file_size === "number" ? Math.floor(args.file_size) : 0 + const contentType = storedContentType(fileName, args.content_type) + const id = yield* startUpload(ctx, channelId, fileName, fileSize) + const uploadUrl = yield* ctx.storage + .presignPut(id, { contentType, expiresIn: UPLOAD_URL_TTL_SECONDS }) + .pipe(Effect.mapError((error) => toolError(error.message))) + return { + attachment_id: id, + upload_url: uploadUrl, + method: "PUT", + headers: { "Content-Type": contentType }, + expires_in_seconds: UPLOAD_URL_TTL_SECONDS, + } }), }, { @@ -554,6 +758,81 @@ const tools: ReadonlyArray = [ return { deleted: true } }), }, + { + name: "set_status", + title: "Set status", + description: + 'Set the user\'s status: an emoji and message (e.g. 🌴 "Out until Monday"), optionally clearing itself after some minutes, and/or their presence (online, away, busy, dnd). clear: true removes the emoji and message.', + scope: "messages:write", + readOnly: false, + inputSchema: obj({ + emoji: str("One emoji, e.g. 🌴"), + message: str("Up to 100 characters"), + expires_in_minutes: { + type: "integer", + minimum: 1, + maximum: 43200, + description: "Clear the status after this long", + }, + presence: { + type: "string", + enum: [...PRESENCE], + description: "online, away, busy or dnd (do not disturb)", + }, + clear: { type: "boolean", description: "Remove the emoji and message" }, + }), + run: (args, ctx) => + Effect.gen(function* () { + const target = userTarget(ctx.user.id) + const presence = + args.presence === undefined + ? undefined + : (PRESENCE.find((value) => value === args.presence) ?? + (yield* toolError("presence must be online, away, busy or dnd"))) + if (args.clear === true) { + yield* forward(target, "userPresenceStatus.clearStatus", {}) + if (presence !== undefined) + yield* forward(target, "userPresenceStatus.update", { status: presence }) + return { cleared: true, ...(presence === undefined ? {} : { presence }) } + } + const emoji = + typeof args.emoji === "string" && args.emoji.trim() !== "" ? args.emoji.trim() : undefined + const message = + typeof args.message === "string" && args.message.trim() !== "" + ? args.message.trim() + : undefined + if (emoji !== undefined && emoji.length > 32) + return yield* toolError("emoji must be one emoji") + if (message !== undefined && message.length > 100) + return yield* toolError("message must be at most 100 characters") + if (emoji === undefined && message === undefined && presence === undefined) + return yield* toolError("Give an emoji, a message, a presence, or clear: true") + const minutes = + typeof args.expires_in_minutes === "number" + ? Math.floor(args.expires_in_minutes) + : undefined + const expiresAt = + minutes === undefined + ? null + : new Date(Date.now() + Math.min(Math.max(minutes, 1), 43200) * 60_000) + const custom = emoji !== undefined || message !== undefined + yield* forward(target, "userPresenceStatus.update", { + ...(presence === undefined ? {} : { status: presence }), + ...(custom + ? { + statusEmoji: emoji ?? null, + customMessage: message ?? null, + statusExpiresAt: expiresAt, + } + : {}), + }) + return { + ...(custom ? { emoji: emoji ?? null, message: message ?? null } : {}), + ...(custom && expiresAt !== null ? { expires_at: expiresAt.toISOString() } : {}), + ...(presence === undefined ? {} : { presence }), + } + }), + }, { name: "toggle_reaction", title: "Toggle reaction", @@ -615,13 +894,11 @@ const callTool = (params: Record | undefined, ctx: ToolContext) if (tool === undefined) return yield* toolError(`Unknown tool ${name}`) if (!ctx.agent.scopes.includes(tool.scope)) return yield* toolError(`This connection is read-only; ${name} needs write access`) - return yield* tool - .run(args, ctx) - .pipe( - Effect.withSpan("Mcp.tool", { - attributes: { "mcp.tool": name, "agent.grant_id": ctx.agent.grantId }, - }), - ) + return yield* tool.run(args, ctx).pipe( + Effect.withSpan("Mcp.tool", { + attributes: { "mcp.tool": name, "agent.grant_id": ctx.agent.grantId }, + }), + ) }).pipe( Effect.map((result) => ({ content: [{ type: "text", text: JSON.stringify(result, null, 2) }], @@ -695,6 +972,7 @@ const loadUser = (userId: UserId) => export const McpRoute = HttpRouter.use((router) => Effect.gen(function* () { const access = yield* AgentAccess + const storage = yield* ObjectStorage const { apiOrigin } = yield* agentOAuthConfig const unauthorized = (description: string) => HttpServerResponse.jsonUnsafe( @@ -744,7 +1022,7 @@ export const McpRoute = HttpRouter.use((router) => } const batch = Array.isArray(parsed) const items = (batch ? parsed : [parsed]) as ReadonlyArray - const ctx: ToolContext = { user: user.value, agent: agent.value } + const ctx: ToolContext = { user: user.value, agent: agent.value, storage } const principal = { user: user.value, botScopes: null, diff --git a/apps/backend/src/routes/uploads.http.ts b/apps/backend/src/routes/uploads.http.ts index 49e4b50d7..1734027a1 100644 --- a/apps/backend/src/routes/uploads.http.ts +++ b/apps/backend/src/routes/uploads.http.ts @@ -20,10 +20,9 @@ import { AttachmentPolicy } from "../policies/attachment-policy" import { ObjectStorage } from "../services/object-storage" import { checkAvatarRateLimit } from "../services/rate-limit-helpers" import { Directory } from "../services/directory" -import { AttachmentEffects, type CreateAttachmentPayload } from "../worker/objects/channel/attachments" -import { WORKER_SENDER } from "../worker/objects/effects/registry" +import { createAttachmentInChannel } from "../services/attachment-uploads" import { callObject } from "../worker/objects/calls" -import { channelTarget, orgTarget } from "../worker/objects/kinds" +import { orgTarget } from "../worker/objects/kinds" import { IsOrgAdminCall } from "../worker/objects/org/api-v1" import { ObjectStubs } from "../worker/objects/protocol" @@ -67,34 +66,6 @@ export const HttpUploadsLive = HttpApiBuilder.group(HazelApi, "uploads", (handle } }) - /** Create the `uploading` row in the channel's `ChannelObject` (a Connect mount's host). */ - const createAttachmentInChannel = Effect.fn("Uploads.createAttachment")(function* ( - payload: CreateAttachmentPayload, - ) { - const index = yield* directory - .channel(payload.channelId) - .pipe(withRemapDbErrors("ChannelIndex", "select")) - const hostId = Option.match(index, { - onNone: () => payload.channelId, - onSome: (row) => row.hostChannelId ?? payload.channelId, - }) - const kind = AttachmentEffects.createAttachment - const result = yield* stubs - .get(channelTarget(hostId)) - .applyEffect({ - objectId: hostId, - kind: kind.name, - payload: yield* Schema.encodeEffect(kind.payload)(payload).pipe(Effect.orDie), - key: `attachment:${payload.id}`, - sender: WORKER_SENDER, - }) - .pipe(Effect.mapError(() => new UploadError({ message: "The channel is unreachable" }))) - if (result._tag === "Rejected") { - yield* Effect.logWarning("Attachment upload refused", { message: result.message }) - return yield* new UploadError({ message: "You can't upload to this channel" }) - } - }) - return handlers.handle( "presign", Effect.fn(function* ({ payload }) { @@ -399,7 +370,10 @@ export const HttpUploadsLive = HttpApiBuilder.group(HazelApi, "uploads", (handle uploadedBy: user.id, fileName, fileSize: req.fileSize, - }) + }).pipe( + Effect.provideService(ObjectStubs, stubs), + Effect.provideService(Directory, directory), + ) // Generate presigned URL const uploadUrl = yield* storage diff --git a/apps/backend/src/services/attachment-uploads.ts b/apps/backend/src/services/attachment-uploads.ts new file mode 100644 index 000000000..db656f3d2 --- /dev/null +++ b/apps/backend/src/services/attachment-uploads.ts @@ -0,0 +1,42 @@ +/** + * Starting an attachment upload: the `uploading` row in the channel's `ChannelObject` (a Connect + * mount's host), which refuses a writer who cannot see the channel. Shared by the web app's + * presigned uploads (`routes/uploads.http.ts`) and the MCP server's file tools (`routes/mcp.ts`). + */ +import { withRemapDbErrors } from "@hazel/domain" +import { UploadError } from "@hazel/domain/http" +import { Effect, Option, Schema } from "effect" +import { AttachmentEffects, type CreateAttachmentPayload } from "../worker/objects/channel/attachments" +import { WORKER_SENDER } from "../worker/objects/effects/registry" +import { channelTarget } from "../worker/objects/kinds" +import { ObjectStubs } from "../worker/objects/protocol" +import { Directory } from "./directory" + +export const createAttachmentInChannel = Effect.fn("Uploads.createAttachment")(function* ( + payload: CreateAttachmentPayload, +) { + const directory = yield* Directory + const stubs = yield* ObjectStubs + const index = yield* directory + .channel(payload.channelId) + .pipe(withRemapDbErrors("ChannelIndex", "select")) + const hostId = Option.match(index, { + onNone: () => payload.channelId, + onSome: (row) => row.hostChannelId ?? payload.channelId, + }) + const kind = AttachmentEffects.createAttachment + const result = yield* stubs + .get(channelTarget(hostId)) + .applyEffect({ + objectId: hostId, + kind: kind.name, + payload: yield* Schema.encodeEffect(kind.payload)(payload).pipe(Effect.orDie), + key: `attachment:${payload.id}`, + sender: WORKER_SENDER, + }) + .pipe(Effect.mapError(() => new UploadError({ message: "The channel is unreachable" }))) + if (result._tag === "Rejected") { + yield* Effect.logWarning("Attachment upload refused", { message: result.message }) + return yield* new UploadError({ message: "You can't upload to this channel" }) + } +}) diff --git a/apps/backend/src/services/object-storage.ts b/apps/backend/src/services/object-storage.ts index b954034f3..ed6a8b97f 100644 --- a/apps/backend/src/services/object-storage.ts +++ b/apps/backend/src/services/object-storage.ts @@ -32,6 +32,40 @@ export class ObjectStorage extends Context.Service()("ObjectStora region, }) + const urlOf = (key: string) => + new URL(`${endpoint}/${bucket}/${key.split("/").map(encodeURIComponent).join("/")}`) + + /** Store `body` at `key` from the server (the MCP server's `upload_file`). */ + const put = Effect.fn("ObjectStorage.put")(function* ( + key: string, + body: Uint8Array, + contentType: string, + ) { + const response = yield* Effect.tryPromise({ + try: () => + client.fetch(urlOf(key).toString(), { + method: "PUT", + headers: { "Content-Type": contentType }, + body, + aws: { allHeaders: true }, + }), + catch: (cause) => new ObjectStorageError({ message: "Failed to store the file", cause }), + }) + if (!response.ok) + return yield* new ObjectStorageError({ + message: `The bucket refused the file (${response.status})`, + }) + }) + + /** Whether an object is stored at `key` (an upload through a presigned URL finished). */ + const exists = Effect.fn("ObjectStorage.exists")(function* (key: string) { + const response = yield* Effect.tryPromise({ + try: () => client.fetch(urlOf(key).toString(), { method: "HEAD" }), + catch: (cause) => new ObjectStorageError({ message: "Failed to check the file", cause }), + }) + return response.ok + }) + const presignPut = Effect.fn("ObjectStorage.presignPut")(function* ( key: string, options: PresignPutOptions, @@ -52,7 +86,7 @@ export class ObjectStorage extends Context.Service()("ObjectStora return signed.url }) - return { presignPut } as const + return { presignPut, put, exists } as const }), }) { static readonly layer = Layer.effect(this, this.make) diff --git a/apps/web-foldkit/src/page/my-settings/agents/view.ts b/apps/web-foldkit/src/page/my-settings/agents/view.ts index 18a686f96..6ca3869c5 100644 --- a/apps/web-foldkit/src/page/my-settings/agents/view.ts +++ b/apps/web-foldkit/src/page/my-settings/agents/view.ts @@ -88,7 +88,7 @@ const ACCESS_OPTIONS: ReadonlyArray<{ readonly label: string readonly hint: string }> = [ - { access: "write", label: "Read & write", hint: "Read, send, reply, react, edit" }, + { access: "write", label: "Read & write", hint: "Read, send, share files, react, edit, set status" }, { access: "read", label: "Read only", hint: "Read channels and messages" }, ] diff --git a/apps/web-foldkit/src/page/oauth-authorize/view.ts b/apps/web-foldkit/src/page/oauth-authorize/view.ts index 10ae1835c..d5f598359 100644 --- a/apps/web-foldkit/src/page/oauth-authorize/view.ts +++ b/apps/web-foldkit/src/page/oauth-authorize/view.ts @@ -17,8 +17,10 @@ const SCOPE_ABILITIES: Readonly>> = { "messages:read": ["Read your channels, direct messages and threads", "See messages that mention you"], "messages:write": [ "Send messages and replies as you", + "Share files in your channels", "React to messages", - "Edit and delete messages it sent", + "Edit and delete your messages", + "Set your status", ], } From 88ef9d357ea5d576ad41ac5ee09dddc43131d318 Mon Sep 17 00:00:00 2001 From: Makisuo Date: Mon, 16 Nov 2026 16:31:55 +0100 Subject: [PATCH 3/6] fix: lint, CI and review findings on agent access Lint (CI's typecheck job runs oxlint): no non-null assertions, no conditional empty-object spreads, schema-parsed tools/call params and JSON token bodies, named result types, Foldkit command names matching their ids. Review: - reply_in_thread posts to a new thread by its own object, not waiting for the directory to publish it - a user whose sign-in is deactivated loses their agents - /mcp refuses bodies over 14 MB before parsing - a reused refresh token ends its grant (RFC 9700 4.14.2): spent tokens are kept as kind "spent" - a missing upload (404) is told apart from a bucket error, and a file stored through a presigned URL is held to 10 MB - agent marks: the open thread's marks load too, a late result from the previous channel is ignored, and a change of attribution starts a new message group so its badge shows - agents settings: one new token at a time (the shown secret is not replaced), names capped at 80 Also fixes two pre-existing failures on main: image-viewer.ts lint (the swipe pager ignores swipes once its slide has left the page; no empty children array) and the mobile org-switch story, which #494 changed to land on the channel list. Co-Authored-By: Claude Opus 5.5 --- apps/backend/src/routes/agent-oauth.ts | 6 +- apps/backend/src/routes/mcp.http.test.ts | 41 ++- apps/backend/src/routes/mcp.ts | 262 ++++++++++++------ apps/backend/src/services/agent-access.ts | 58 +++- apps/backend/src/services/object-storage.ts | 16 +- apps/web-foldkit/src/chat/image-viewer.ts | 21 +- .../src/page/chat/channel/model.ts | 2 +- .../web-foldkit/src/page/chat/channel/page.ts | 4 +- .../src/page/chat/channel/subscription.ts | 21 +- apps/web-foldkit/src/page/chat/derive.ts | 27 +- apps/web-foldkit/src/page/chat/lookup-data.ts | 6 +- .../src/page/my-settings/agents/command.ts | 8 +- .../src/page/my-settings/agents/model.ts | 10 + .../src/page/my-settings/agents/update.ts | 20 +- .../src/page/my-settings/agents/view.ts | 6 +- .../src/page/oauth-authorize/command.ts | 6 +- .../src/page/oauth-authorize/view.ts | 4 +- .../web-foldkit/src/shell/shell.story.test.ts | 5 +- packages/db/src/tables/agents.ts | 6 +- 19 files changed, 368 insertions(+), 161 deletions(-) diff --git a/apps/backend/src/routes/agent-oauth.ts b/apps/backend/src/routes/agent-oauth.ts index b543abec7..753d08059 100644 --- a/apps/backend/src/routes/agent-oauth.ts +++ b/apps/backend/src/routes/agent-oauth.ts @@ -45,6 +45,8 @@ const oauthError = (error: string, description: string, status = 400) => ) const decodeClientId = Schema.decodeUnknownOption(AgentClientId) +/** A JSON token request's string fields (other values are not OAuth parameters). */ +const decodeJsonParams = Schema.decodeUnknownOption(Schema.Record(Schema.String, Schema.String)) const RegistrationRequest = Schema.Struct({ client_name: Schema.optional(Schema.String), @@ -82,9 +84,9 @@ const readParams = Effect.gen(function* () { const body = yield* readBody if ((request.headers["content-type"] ?? "").includes("application/json")) { try { - const parsed = JSON.parse(body) as Record + const parsed = decodeJsonParams(JSON.parse(body)) return new Map( - Object.entries(parsed).flatMap(([k, v]) => (typeof v === "string" ? [[k, v] as const] : [])), + Option.match(parsed, { onNone: () => [], onSome: (params) => Object.entries(params) }), ) } catch { return new Map() diff --git a/apps/backend/src/routes/mcp.http.test.ts b/apps/backend/src/routes/mcp.http.test.ts index 43b523d50..f8ff5e476 100644 --- a/apps/backend/src/routes/mcp.http.test.ts +++ b/apps/backend/src/routes/mcp.http.test.ts @@ -8,7 +8,7 @@ import { createHash } from "node:crypto" import { NodeHttpPlatform, NodeServices } from "@effect/platform-node" import { SQLite, schema } from "@hazel/db" import type { AgentClientId, ChannelId, OrganizationId, UserId } from "@hazel/schema" -import { ConfigProvider, Context, Effect, Layer, type Scope } from "effect" +import { ConfigProvider, Context, Effect, Layer, Option, type Scope } from "effect" import { HttpRouter } from "effect/http" import { describe, expect, it } from "vitest" import { AgentAccess } from "../services/agent-access" @@ -89,7 +89,10 @@ const makeWorld = Effect.gen(function* () { Effect.sync(() => { bucket.set(key, { bytes, contentType }) }), - exists: (key: string) => Effect.succeed(bucket.has(key)), + storedSize: (key: string) => { + const stored = bucket.get(key) + return Effect.succeed(stored === undefined ? Option.none() : Option.some(stored.bytes.byteLength)) + }, } as never) const services = Layer.mergeAll( storage, @@ -136,7 +139,11 @@ const mcp = (world: World, token: string, method: string, params?: Record { client_id: clientId, }) expect((yield* json(reused)).error).toBe("invalid_grant") + // Reusing a spent refresh token ends the grant: the chain refreshed from it stops too. + const stolen = yield* world.fetch("/mcp", { + method: "POST", + headers: { authorization: `Bearer ${refreshed.access_token}` }, + body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }), + }) + expect(stolen.status).toBe(401) + expect(yield* world.access.listGrants(world.alice)).toEqual([]) + + // Sign in again for the rest. + const code3 = yield* world.access.createCode({ + clientId, + userId: world.alice, + redirectUri, + codeChallenge: challenge, + scopes: ["messages:read", "messages:write"], + }) + const again = yield* json( + yield* exchange({ + grant_type: "authorization_code", + code: code3, + client_id: clientId, + redirect_uri: redirectUri, + code_verifier: verifier, + }), + ) // Revoking the grant ends every token at once. const [grant] = yield* world.access.listGrants(world.alice) @@ -329,7 +362,7 @@ describe("MCP server", () => { expect(yield* world.access.revokeGrant(world.alice, grant!.id)).toBe(true) const after = yield* world.fetch("/mcp", { method: "POST", - headers: { authorization: `Bearer ${refreshed.access_token}` }, + headers: { authorization: `Bearer ${again.access_token}` }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }), }) expect(after.status).toBe(401) diff --git a/apps/backend/src/routes/mcp.ts b/apps/backend/src/routes/mcp.ts index 62d26bf09..24d713e2c 100644 --- a/apps/backend/src/routes/mcp.ts +++ b/apps/backend/src/routes/mcp.ts @@ -17,6 +17,7 @@ import { ChannelResponse, CreateThreadRequest, type MessageResponse, + type MessageSearchPayload, type MessageSearchResponse, } from "@hazel/domain/rpc" import { AttachmentId, ChannelId, MessageId, OrganizationId, type UserId } from "@hazel/schema" @@ -45,6 +46,13 @@ import { agentOAuthConfig, protectedResourceMetadataUrl } from "./agent-oauth" const SUPPORTED_PROTOCOL_VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26"] const MAX_CONTENT_LENGTH = 8000 +/** The largest JSON-RPC body read: a 10 MB file as base64 (4/3) and room for the envelope. */ +const MAX_REQUEST_BYTES = 14 * 1024 * 1024 + +const tooLarge = HttpServerResponse.jsonUnsafe( + { jsonrpc: "2.0", id: null, error: { code: -32600, message: "The request is too large" } }, + { status: 413 }, +) const INSTRUCTIONS = `Hazel is a team chat app. These tools act as the signed-in user. Messages you send, reply or edit are shown to the user's organization as written by an agent ("via "). @@ -115,6 +123,12 @@ const decodeChannelId = Schema.decodeUnknownOption(ChannelId) const decodeMessageId = Schema.decodeUnknownOption(MessageId) const decodeOrgId = Schema.decodeUnknownOption(OrganizationId) const decodeAttachmentId = Schema.decodeUnknownOption(AttachmentId) +const decodeCallParams = Schema.decodeUnknownOption( + Schema.Struct({ + name: Schema.String, + arguments: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)), + }), +) /** How long a `create_upload_url` URL stays valid. */ const UPLOAD_URL_TTL_SECONDS = 15 * 60 @@ -182,34 +196,87 @@ interface MessageLike { readonly channelId: string } +/** A message as a tool returns it. */ +interface PresentedMessage { + readonly id: string + readonly channel_id: string + readonly author: { readonly id: string; readonly name: string } + readonly content: string + readonly created_at: string + edited_at?: string + reply_to_message_id?: string + thread_channel_id?: string +} + +interface SentResult { + readonly sent: true + readonly message: PresentedMessage | undefined + attachment_ids?: ReadonlyArray +} + +interface ListedChannel { + readonly id: string + readonly organization_id: string + readonly name: string + readonly type: string + readonly unread_count: number + muted?: true +} + +interface SearchResult { + readonly results: ReadonlyArray + note?: string +} + +/** `userPresenceStatus.update`'s payload, as far as `set_status` sets it. */ +interface StatusUpdate { + status?: (typeof PRESENCE)[number] + statusEmoji?: string | null + customMessage?: string | null + statusExpiresAt?: Date | null +} + +interface StatusResult { + cleared?: true + presence?: (typeof PRESENCE)[number] + emoji?: string | null + message?: string | null + expires_at?: string +} + /** Messages as the agent reads them: author names, mentions shown as `@Name (userId)`. */ const present = (messages: ReadonlyArray) => Effect.gen(function* () { const ids: Array = [] for (const message of messages) { ids.push(message.authorId) - for (const match of message.content.matchAll(MENTION)) ids.push(match[1]!) + for (const match of message.content.matchAll(MENTION)) { + const mentioned = match[1] + if (mentioned !== undefined) ids.push(mentioned) + } } const names = yield* namesOf(ids) const iso = (at: Date | DateTime.Utc) => at instanceof Date ? at.toISOString() : DateTime.formatIso(at) const ms = (at: Date | DateTime.Utc) => at instanceof Date ? at.getTime() : DateTime.toEpochMillis(at) - return messages.map((message) => ({ - id: message.id, - channel_id: message.channelId, - author: { id: message.authorId, name: names.get(message.authorId) ?? "Unknown" }, - content: message.content.replace( - MENTION, - (whole, id: string) => `@${names.get(id) ?? "someone"} (${whole})`, - ), - created_at: iso(message.createdAt), - ...(message.updatedAt !== null && ms(message.updatedAt) > ms(message.createdAt) - ? { edited_at: iso(message.updatedAt) } - : {}), - ...(message.replyToMessageId === null ? {} : { reply_to_message_id: message.replyToMessageId }), - ...(message.threadChannelId === null ? {} : { thread_channel_id: message.threadChannelId }), - })) + return messages.map((message) => { + const shown: PresentedMessage = { + id: message.id, + channel_id: message.channelId, + author: { id: message.authorId, name: names.get(message.authorId) ?? "Unknown" }, + content: message.content.replace( + MENTION, + (whole, id: string) => `@${names.get(id) ?? "someone"} (${whole})`, + ), + created_at: iso(message.createdAt), + } + if (message.updatedAt !== null && ms(message.updatedAt) > ms(message.createdAt)) + shown.edited_at = iso(message.updatedAt) + if (message.replyToMessageId !== null) shown.reply_to_message_id = message.replyToMessageId + if (message.threadChannelId !== null) shown.thread_channel_id = message.threadChannelId + return shown + }) }) /** The user's own message in its channel; edits and deletes go no further. */ @@ -255,17 +322,25 @@ const sendIn = ( content: string, replyToMessageId: MessageId | null, attachmentIds: ReadonlyArray = [], + knownHost?: ReturnType, ) => Effect.gen(function* () { - const { host } = yield* channelInfo(channelId) + const host = knownHost ?? (yield* channelInfo(channelId)).host yield* rateLimited(ctx) // A presigned upload is finished once its file is in the bucket; mark it complete then. for (const id of attachmentIds) { const stored = yield* ctx.storage - .exists(id) + .storedSize(id) .pipe(Effect.mapError((error) => toolError(error.message))) - if (!stored) + if (Option.isNone(stored)) return yield* toolError(`File ${id} is not uploaded yet: PUT it to its upload_url first`) + // A presigned PUT does not bound the body: the limit is checked on what was stored. + if (stored.value > MAX_ATTACHMENT_SIZE) { + yield* forward(host, "attachment.fail", { id, channelId, reason: "Larger than 10 MB" }).pipe( + Effect.ignore, + ) + return yield* toolError(`File ${id} is larger than 10 MB`) + } yield* forward(host, "attachment.complete", { id, channelId }) } const response = yield* forward(host, "message.create", { @@ -276,13 +351,11 @@ const sendIn = ( embeds: null, replyToMessageId, threadChannelId: null, - ...(attachmentIds.length === 0 ? {} : { attachmentIds: [...attachmentIds] }), + attachmentIds: [...attachmentIds], }) - return { - sent: true, - message: (yield* present([response.data]))[0], - ...(attachmentIds.length === 0 ? {} : { attachment_ids: attachmentIds }), - } + const sent: SentResult = { sent: true, message: (yield* present([response.data]))[0] } + if (attachmentIds.length > 0) sent.attachment_ids = attachmentIds + return sent }) /** The content type a file is stored with; active types (HTML, SVG…) only as a download. */ @@ -291,26 +364,26 @@ const storedContentType = (fileName: string, given: unknown) => { return isActiveContentType(type) ? "application/octet-stream" : type } -const EXTENSION_TYPES: Record = { - png: "image/png", - jpg: "image/jpeg", - jpeg: "image/jpeg", - gif: "image/gif", - webp: "image/webp", - pdf: "application/pdf", - txt: "text/plain", - md: "text/markdown", - csv: "text/csv", - json: "application/json", - zip: "application/zip", - mp4: "video/mp4", - mov: "video/quicktime", - mp3: "audio/mpeg", - wav: "audio/wav", -} +const EXTENSION_TYPES = new Map([ + ["png", "image/png"], + ["jpg", "image/jpeg"], + ["jpeg", "image/jpeg"], + ["gif", "image/gif"], + ["webp", "image/webp"], + ["pdf", "application/pdf"], + ["txt", "text/plain"], + ["md", "text/markdown"], + ["csv", "text/csv"], + ["json", "application/json"], + ["zip", "application/zip"], + ["mp4", "video/mp4"], + ["mov", "video/quicktime"], + ["mp3", "audio/mpeg"], + ["wav", "audio/wav"], +]) const guessContentType = (fileName: string) => - EXTENSION_TYPES[fileName.split(".").pop()?.toLowerCase() ?? ""] ?? "application/octet-stream" + EXTENSION_TYPES.get(fileName.split(".").pop()?.toLowerCase() ?? "") ?? "application/octet-stream" const argFileName = (args: Record) => { const name = typeof args.file_name === "string" ? args.file_name.trim().replace(/[\\/]/g, "_") : "" @@ -395,17 +468,20 @@ const tools: ReadonlyArray = [ ), ) return { - channels: lists.flat().map((channel) => ({ - id: channel.id, - organization_id: channel.organizationId, - name: - channel.type === "direct" || channel.type === "single" - ? channel.members.join(", ") || channel.name - : channel.name, - type: channel.type, - unread_count: channel.unreadCount, - ...(channel.isMuted ? { muted: true } : {}), - })), + channels: lists.flat().map((channel) => { + const shown: ListedChannel = { + id: channel.id, + organization_id: channel.organizationId, + name: + channel.type === "direct" || channel.type === "single" + ? channel.members.join(", ") || channel.name + : channel.name, + type: channel.type, + unread_count: channel.unreadCount, + } + if (channel.isMuted) shown.muted = true + return shown + }), } }), }, @@ -470,20 +546,19 @@ const tools: ReadonlyArray = [ : args.organization_id !== undefined ? Option.toArray(decodeOrgId(args.organization_id)) : yield* directory.organizationsOf(ctx.user.id).pipe(Effect.orDie) - const pages = yield* Effect.forEach(orgIds, (organizationId) => - forward(orgTarget(organizationId), "message.search", { - organizationId, - query, - limit, - ...(channelId === undefined ? {} : { channelId }), - }), - ) + const pages = yield* Effect.forEach(orgIds, (organizationId) => { + const search: MessageSearchPayload = + channelId === undefined + ? { organizationId, query, limit } + : { organizationId, query, limit, channelId } + return forward(orgTarget(organizationId), "message.search", search) + }) const hits = pages .flatMap((page) => page.results) .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime()) .slice(0, limit) const names = yield* namesOf(hits.map((hit) => hit.authorId)) - return { + const found: SearchResult = { results: hits.map((hit) => ({ message_id: hit.messageId, channel_id: hit.channelId, @@ -491,10 +566,10 @@ const tools: ReadonlyArray = [ created_at: hit.createdAt.toISOString(), snippet: hit.snippet, })), - ...(pages.some((page) => page.indexing) - ? { note: "Search is still indexing; results may be incomplete" } - : {}), } + if (pages.some((page) => page.indexing)) + found.note = "Search is still indexing; results may be incomplete" + return found }), }, { @@ -704,7 +779,12 @@ const tools: ReadonlyArray = [ "channel.createThread", new CreateThreadRequest({ messageId, channelId, organizationId }), )).data.id - return { thread_channel_id: threadId, ...(yield* sendIn(ctx, threadId, content, null)) } + // A thread is a channel of its own object. A new one may not be in the directory yet + // (its index row is published after `channel.createThread` answers), so no lookup. + return { + thread_channel_id: threadId, + ...(yield* sendIn(ctx, threadId, content, null, [], channelTarget(threadId))), + } }), }, { @@ -793,7 +873,9 @@ const tools: ReadonlyArray = [ yield* forward(target, "userPresenceStatus.clearStatus", {}) if (presence !== undefined) yield* forward(target, "userPresenceStatus.update", { status: presence }) - return { cleared: true, ...(presence === undefined ? {} : { presence }) } + const cleared: StatusResult = { cleared: true } + if (presence !== undefined) cleared.presence = presence + return cleared } const emoji = typeof args.emoji === "string" && args.emoji.trim() !== "" ? args.emoji.trim() : undefined @@ -816,21 +898,22 @@ const tools: ReadonlyArray = [ ? null : new Date(Date.now() + Math.min(Math.max(minutes, 1), 43200) * 60_000) const custom = emoji !== undefined || message !== undefined - yield* forward(target, "userPresenceStatus.update", { - ...(presence === undefined ? {} : { status: presence }), - ...(custom - ? { - statusEmoji: emoji ?? null, - customMessage: message ?? null, - statusExpiresAt: expiresAt, - } - : {}), - }) - return { - ...(custom ? { emoji: emoji ?? null, message: message ?? null } : {}), - ...(custom && expiresAt !== null ? { expires_at: expiresAt.toISOString() } : {}), - ...(presence === undefined ? {} : { presence }), + const update: StatusUpdate = {} + const result: StatusResult = {} + if (presence !== undefined) { + update.status = presence + result.presence = presence + } + if (custom) { + update.statusEmoji = emoji ?? null + update.customMessage = message ?? null + update.statusExpiresAt = expiresAt + result.emoji = emoji ?? null + result.message = message ?? null + if (expiresAt !== null) result.expires_at = expiresAt.toISOString() } + yield* forward(target, "userPresenceStatus.update", update) + return result }), }, { @@ -886,10 +969,10 @@ const toolListing = (scopes: ReadonlyArray) => const callTool = (params: Record | undefined, ctx: ToolContext) => Effect.gen(function* () { - const name = typeof params?.name === "string" ? params.name : "" - const args = ( - typeof params?.arguments === "object" && params.arguments !== null ? params.arguments : {} - ) as Record + const call = decodeCallParams(params) + if (Option.isNone(call)) return yield* toolError("tools/call needs a tool name") + const name = call.value.name + const args = call.value.arguments ?? {} const tool = tools.find((candidate) => candidate.name === name) if (tool === undefined) return yield* toolError(`Unknown tool ${name}`) if (!ctx.agent.scopes.includes(tool.scope)) @@ -950,7 +1033,8 @@ const loadUser = (userId: UserId) => const row = yield* (yield* Directory).db.first( SQLite.from(schema.usersTable) .select() - .where(($) => [$.id.eq(userId), $.deletedAt.isNull()]), + // A user whose sign-in was deactivated loses their agents too. + .where(($) => [$.id.eq(userId), $.deletedAt.isNull(), $.authActive.eq(true)]), ) return Option.map( row, @@ -1011,7 +1095,11 @@ export const McpRoute = HttpRouter.use((router) => "user.id": user.value.id, }) + // `upload_file` carries a file of up to 10 MB as base64; nothing larger is read. + const declared = Number(request.headers["content-length"] ?? "0") + if (declared > MAX_REQUEST_BYTES) return tooLarge const body = yield* request.text.pipe(Effect.orElseSucceed(() => "")) + if (body.length > MAX_REQUEST_BYTES) return tooLarge let parsed: unknown try { parsed = JSON.parse(body) diff --git a/apps/backend/src/services/agent-access.ts b/apps/backend/src/services/agent-access.ts index f9d3f9a63..55a54d9ea 100644 --- a/apps/backend/src/services/agent-access.ts +++ b/apps/backend/src/services/agent-access.ts @@ -117,6 +117,14 @@ export interface AgentPrincipal { readonly scopes: ReadonlyArray } +/** The row an `INSERT … RETURNING` wrote; none is a broken invariant. */ +const returnedRow = (rows: ReadonlyArray) => { + const row = rows[0] + return row === undefined + ? Effect.die(new Error("INSERT … RETURNING returned no row")) + : Effect.succeed(row) +} + const toScopes = (scopes: ReadonlyArray) => parseAgentScopes(scopes.join(" ")) export class AgentAccess extends Context.Service()("@hazel/backend/AgentAccess", { @@ -156,7 +164,7 @@ export class AgentAccess extends Context.Service()("@hazel/backend/ }) .returning("id", "createdAt"), ) - .pipe(Effect.map((rows) => rows[0]!)) + .pipe(Effect.flatMap(returnedRow)) const createCode = (input: { readonly clientId: AgentClientId @@ -253,7 +261,7 @@ export class AgentAccess extends Context.Service()("@hazel/backend/ }) .returning("id"), ) - .pipe(Effect.map((rows) => rows[0]!)) + .pipe(Effect.flatMap(returnedRow)) return yield* issueTokens(grant.id, scopes) }).pipe(Effect.withSpan("AgentAccess.exchangeCode")) @@ -264,12 +272,29 @@ export class AgentAccess extends Context.Service()("@hazel/backend/ .where(($) => [$.id.eq(grantId), $.revokedAt.isNull()]), ) - /** `grant_type=refresh_token`: rotate; the old refresh token is spent. */ + /** End a grant: no new tokens, and every token it issued stops working. */ + const endGrant = (grantId: AgentGrantId) => + Effect.gen(function* () { + yield* db.run( + SQLite.update(schema.agentGrantsTable) + .set({ revokedAt: new Date() }) + .where(($) => [$.id.eq(grantId), $.revokedAt.isNull()]), + ) + yield* db.run( + SQLite.deleteFrom(schema.agentTokensTable).where(($) => [$.grantId.eq(grantId)]), + ) + }) + + /** + * `grant_type=refresh_token`: rotate. The old refresh token is kept as `spent`; presenting it + * again means it leaked (whoever refreshed first holds the live chain), so the grant ends. + */ const refresh = (input: { readonly refreshToken: string; readonly clientId: string }) => Effect.gen(function* () { const tokenHash = yield* sha256Hex(input.refreshToken) - const spent = yield* db.first( - SQLite.deleteFrom(schema.agentTokensTable) + const claimed = yield* db.first( + SQLite.update(schema.agentTokensTable) + .set({ kind: "spent" }) .where(($) => [ $.tokenHash.eq(tokenHash), $.kind.eq("refresh"), @@ -277,9 +302,22 @@ export class AgentAccess extends Context.Service()("@hazel/backend/ ]) .returning("grantId"), ) - if (Option.isNone(spent)) + if (Option.isNone(claimed)) { + const reused = yield* db.first( + SQLite.from(schema.agentTokensTable) + .select("grantId") + .where(($) => [$.tokenHash.eq(tokenHash), $.kind.eq("spent")]), + ) + if (Option.isSome(reused)) { + yield* Effect.logWarning("Agent refresh token reused; ending its grant", { + grantId: reused.value.grantId, + }) + yield* endGrant(reused.value.grantId) + return yield* invalidGrant("The refresh token was already used; sign in again") + } return yield* invalidGrant("The refresh token is invalid or expired") - const grant = yield* liveGrant(spent.value.grantId) + } + const grant = yield* liveGrant(claimed.value.grantId) if (Option.isNone(grant) || grant.value.clientId !== input.clientId) return yield* invalidGrant("The grant was revoked") return yield* issueTokens(grant.value.id, toScopes(grant.value.scopes)) @@ -295,7 +333,9 @@ export class AgentAccess extends Context.Service()("@hazel/backend/ .select() .where(($) => [$.tokenHash.eq(tokenHash)]), ) - if (Option.isNone(row) || row.value.kind === "refresh") return Option.none() + // Only access and personal tokens authenticate (never a refresh or spent one). + if (Option.isNone(row) || (row.value.kind !== "access" && row.value.kind !== "personal")) + return Option.none() if (row.value.expiresAt !== null && row.value.expiresAt.getTime() <= Date.now()) return Option.none() const grant = yield* liveGrant(row.value.grantId) @@ -360,7 +400,7 @@ export class AgentAccess extends Context.Service()("@hazel/backend/ }) .returning(), ) - .pipe(Effect.map((rows) => rows[0]!)) + .pipe(Effect.flatMap(returnedRow)) const secret = yield* newSecret("personal") yield* db.run( SQLite.insertInto(schema.agentTokensTable).values({ diff --git a/apps/backend/src/services/object-storage.ts b/apps/backend/src/services/object-storage.ts index ed6a8b97f..4781c5049 100644 --- a/apps/backend/src/services/object-storage.ts +++ b/apps/backend/src/services/object-storage.ts @@ -1,5 +1,5 @@ import { AwsClient } from "aws4fetch" -import { Config, Context, Effect, Layer, Redacted, Schema } from "effect" +import { Config, Context, Effect, Layer, Option, Redacted, Schema } from "effect" export class ObjectStorageError extends Schema.TaggedError()("ObjectStorageError", { message: Schema.String, @@ -57,13 +57,19 @@ export class ObjectStorage extends Context.Service()("ObjectStora }) }) - /** Whether an object is stored at `key` (an upload through a presigned URL finished). */ - const exists = Effect.fn("ObjectStorage.exists")(function* (key: string) { + /** + * The size of the object stored at `key`, none when there is none (a presigned upload not + * made yet). Any other answer from the bucket is an error, not "missing". + */ + const storedSize = Effect.fn("ObjectStorage.storedSize")(function* (key: string) { const response = yield* Effect.tryPromise({ try: () => client.fetch(urlOf(key).toString(), { method: "HEAD" }), catch: (cause) => new ObjectStorageError({ message: "Failed to check the file", cause }), }) - return response.ok + if (response.status === 404) return Option.none() + if (!response.ok) + return yield* new ObjectStorageError({ message: `The bucket answered ${response.status}` }) + return Option.some(Number(response.headers.get("content-length") ?? "0")) }) const presignPut = Effect.fn("ObjectStorage.presignPut")(function* ( @@ -86,7 +92,7 @@ export class ObjectStorage extends Context.Service()("ObjectStora return signed.url }) - return { presignPut, put, exists } as const + return { presignPut, put, storedSize } as const }), }) { static readonly layer = Layer.effect(this, this.make) diff --git a/apps/web-foldkit/src/chat/image-viewer.ts b/apps/web-foldkit/src/chat/image-viewer.ts index 08e238790..6d00cd61c 100644 --- a/apps/web-foldkit/src/chat/image-viewer.ts +++ b/apps/web-foldkit/src/chat/image-viewer.ts @@ -254,13 +254,14 @@ const NativeImageViewerModal = Mount.defineStream("ImageViewerNativeModal", { /** The phone shell's swipe pages the native viewer (`platform/system-ui.ts`), where it has one. */ const NativeSwipePager = Mount.defineStream("ImageViewerSwipePager", { messages: [Intent.PressedClose, Intent.PressedSelect, Intent.Swiped], - execute: () => + execute: ({ element }) => Stream.callback((queue) => acquire( () => - systemUi()?.setSwipePager?.((step) => - Queue.offerUnsafe(queue, Intent.Swiped({ step })), - ) ?? NO_RELEASE, + systemUi()?.setSwipePager?.((step) => { + // A swipe landing after this slide left the page belongs to the next slide's pager. + if (element.isConnected) Queue.offerUnsafe(queue, Intent.Swiped({ step })) + }) ?? NO_RELEASE, ).pipe(Effect.flatMap(() => Effect.never)), ), }) @@ -531,14 +532,10 @@ export const imageViewerView = (h: HtmlBuilder, inputs: ImageViewerInputs< ...(isNative && hasMany && systemUi()?.setSwipePager !== undefined ? [ // Remounted on every slide, so a swipe steps from the slide on view. - h.keyed("span")( - `swipe:${selectedIndex}`, - [ - h.Class("hidden"), - h.OnMount(Mount.mapMessage(NativeSwipePager(), toMessage)), - ], - [], - ), + h.keyed("span")(`swipe:${selectedIndex}`, [ + h.Class("hidden"), + h.OnMount(Mount.mapMessage(NativeSwipePager(), toMessage)), + ]), ] : []), h.div( diff --git a/apps/web-foldkit/src/page/chat/channel/model.ts b/apps/web-foldkit/src/page/chat/channel/model.ts index f84da7e69..c6dc930ef 100644 --- a/apps/web-foldkit/src/page/chat/channel/model.ts +++ b/apps/web-foldkit/src/page/chat/channel/model.ts @@ -209,7 +209,7 @@ export const Message = defineMessageUnion({ UpdatedCustomEmojis: { customEmojis: Schema.Array(CustomEmojiInfo) }, UpdatedAttachments: { attachments: Schema.Array(AttachmentInfo) }, UpdatedDiscordSynced: { messageIds: Schema.Array(MessageId) }, - UpdatedAgentMarks: { marks: Schema.Array(AgentMarkInfo) }, + UpdatedAgentMarks: { channelId: ChannelId, marks: Schema.Array(AgentMarkInfo) }, UpdatedThreadChannels: { channels: Schema.Array(ThreadChannelInfo) }, UpdatedThreadMessages: { messages: Schema.Array(ThreadMessageInfo) }, UpdatedReplyTargets: { targets: Schema.Array(ReplyTarget) }, diff --git a/apps/web-foldkit/src/page/chat/channel/page.ts b/apps/web-foldkit/src/page/chat/channel/page.ts index 4a57fdf95..cf0f76e54 100644 --- a/apps/web-foldkit/src/page/chat/channel/page.ts +++ b/apps/web-foldkit/src/page/chat/channel/page.ts @@ -519,7 +519,9 @@ export const update = (model: Model, message: Message, shared: Shared | null = n ), UpdatedAttachments: ({ attachments }) => withLookup(model, "attachments", attachments), UpdatedDiscordSynced: ({ messageIds }) => withLookup(model, "discordSyncedIds", messageIds), - UpdatedAgentMarks: ({ marks }) => withLookup(model, "agentMarks", marks), + // A late result from the channel just left must not replace the new channel's marks. + UpdatedAgentMarks: ({ channelId, marks }) => + channelId === model.channelId ? withLookup(model, "agentMarks", marks) : { model }, UpdatedThreadChannels: ({ channels }) => withLookup(model, "threadChannels", channels), UpdatedThreadMessages: ({ messages }) => withLookup(model, "threadMessages", messages), UpdatedReplyTargets: ({ targets }) => withLookup(model, "replyTargets", targets), diff --git a/apps/web-foldkit/src/page/chat/channel/subscription.ts b/apps/web-foldkit/src/page/chat/channel/subscription.ts index fed3e9a55..67acfb5e8 100644 --- a/apps/web-foldkit/src/page/chat/channel/subscription.ts +++ b/apps/web-foldkit/src/page/chat/channel/subscription.ts @@ -199,11 +199,22 @@ const chat = Subscription.make()((entry) => ({ dependenciesToStream: ({ channelId }) => discordSyncedStream(channelId, (messageIds) => Message.UpdatedDiscordSynced({ messageIds })), }), - chatAgentMarks: entry(byChannel, { - modelToDependencies: channelOf, - dependenciesToStream: ({ channelId }) => - agentMarksStream(channelId, (marks) => Message.UpdatedAgentMarks({ marks })), - }), + // The channel's marks and the open thread's: the thread panel's rows read the same lookup. + chatAgentMarks: entry( + { channelId: ChannelId, threadChannelId: Schema.NullOr(ChannelId) }, + { + modelToDependencies: ({ model }) => ({ + channelId: model.channelId, + threadChannelId: + model.threadPanel?.creation === "Created" ? model.threadPanel.threadChannelId : null, + }), + dependenciesToStream: ({ channelId, threadChannelId }) => + agentMarksStream( + threadChannelId === null ? [channelId] : [channelId, threadChannelId], + (marks) => Message.UpdatedAgentMarks({ channelId, marks }), + ), + }, + ), chatThreadChannels: entry( { threadIds: Schema.Array(ChannelId) }, { diff --git a/apps/web-foldkit/src/page/chat/derive.ts b/apps/web-foldkit/src/page/chat/derive.ts index 9f826900a..6774d53eb 100644 --- a/apps/web-foldkit/src/page/chat/derive.ts +++ b/apps/web-foldkit/src/page/chat/derive.ts @@ -40,6 +40,13 @@ import { const GROUP_THRESHOLD_MS = 3 * 60 * 1000 +/** + * Both written the same way (by hand, or by the same agent): a change starts a new group, since + * the "via " badge is in the group's header. + */ +const sameAttribution = (context: DeriveContext, a: { readonly id: string }, b: { readonly id: string }) => + context.agentNames.get(a.id) === context.agentNames.get(b.id) + const toGroupPosition = (isGroupStart: boolean, isGroupEnd: boolean): GroupPosition => isGroupStart && isGroupEnd ? "standalone" : isGroupStart ? "start" : isGroupEnd ? "end" : "middle" @@ -380,11 +387,13 @@ export const toDisplayRows = ( previous === null || message.authorId !== previous.authorId || message.createdAtMs - previous.createdAtMs > GROUP_THRESHOLD_MS || - previous.replyToMessageId !== null + previous.replyToMessageId !== null || + !sameAttribution(context, message, previous) const isGroupEnd = next === null || message.authorId !== next.authorId || - next.createdAtMs - message.createdAtMs > GROUP_THRESHOLD_MS + next.createdAtMs - message.createdAtMs > GROUP_THRESHOLD_MS || + !sameAttribution(context, message, next) const date = new Date(message.createdAtMs).toDateString() if (date !== lastDate) { @@ -419,7 +428,11 @@ const sharedRow = (old: DisplayRow | undefined, data: MessageRowData): MessageRo : { _tag: "MessageRow", ...data } /** `ThreadMessageListContent`'s grouping (oldest first). */ -const threadGroupPositionAt = (messages: ReadonlyArray, index: number): GroupPosition => { +const threadGroupPositionAt = ( + messages: ReadonlyArray, + index: number, + context: DeriveContext, +): GroupPosition => { const message = messages[index]! const previous = index > 0 ? messages[index - 1]! : null const next = index < messages.length - 1 ? messages[index + 1]! : null @@ -427,11 +440,13 @@ const threadGroupPositionAt = (messages: ReadonlyArray, index: numb previous === null || message.authorId !== previous.authorId || message.createdAtMs - previous.createdAtMs > GROUP_THRESHOLD_MS || - previous.replyToMessageId !== null + previous.replyToMessageId !== null || + !sameAttribution(context, message, previous) const isEnd = next === null || message.authorId !== next.authorId || - next.createdAtMs - message.createdAtMs > GROUP_THRESHOLD_MS + next.createdAtMs - message.createdAtMs > GROUP_THRESHOLD_MS || + !sameAttribution(context, message, next) return toGroupPosition(isStart, isEnd) } @@ -449,7 +464,7 @@ export const toThreadRows = ( sharedRow(previousByKey.get(message.id), { ...messageRowData( message, - threadGroupPositionAt(messagesOldestFirst, index), + threadGroupPositionAt(messagesOldestFirst, index, context), NO_REACTIONS, context, ), diff --git a/apps/web-foldkit/src/page/chat/lookup-data.ts b/apps/web-foldkit/src/page/chat/lookup-data.ts index ada0350ed..8f6fcf17b 100644 --- a/apps/web-foldkit/src/page/chat/lookup-data.ts +++ b/apps/web-foldkit/src/page/chat/lookup-data.ts @@ -132,16 +132,16 @@ export const discordSyncedStream = ( (rows) => toMessage(rows.map((row) => row.hazelMessageId)), ) -/** The channel's agent-written messages (`message_agent_marks`). */ +/** Agent-written messages (`message_agent_marks`) in `channelIds`: a channel and its open thread. */ export const agentMarksStream = ( - channelId: ChannelId, + channelIds: ReadonlyArray, toMessage: (marks: ReadonlyArray) => M, ) => liveQueryStream( (q) => q .from({ mark: messageAgentMarkCollection }) - .where(({ mark }) => eq(mark.channelId, channelId)) + .where(({ mark }) => inArray(mark.channelId, [...channelIds])) .select(({ mark }) => ({ id: mark.id, agentName: mark.agentName })), (rows) => toMessage(rows), ) diff --git a/apps/web-foldkit/src/page/my-settings/agents/command.ts b/apps/web-foldkit/src/page/my-settings/agents/command.ts index 61e67392f..eeb733302 100644 --- a/apps/web-foldkit/src/page/my-settings/agents/command.ts +++ b/apps/web-foldkit/src/page/my-settings/agents/command.ts @@ -16,7 +16,7 @@ const toGrant = (grant: AgentGrantInfo): Grant => ({ lastUsedAtMs: grant.lastUsedAt === null ? null : DateTime.toEpochMillis(grant.lastUsedAt), }) -export const FetchGrants = Command.define("FetchAgentGrants", { +export const FetchAgentGrants = Command.define("FetchAgentGrants", { messages: [Message.SucceededFetchGrants, Message.FailedFetchGrants], execute: HazelApiClient.use((client) => client.agentAccess.listAgentGrants()).pipe( Effect.map((response) => @@ -26,7 +26,7 @@ export const FetchGrants = Command.define("FetchAgentGrants", { ), }) -export const RevokeGrant = Command.define("RevokeAgentGrant", { +export const RevokeAgentGrant = Command.define("RevokeAgentGrant", { args: { grantId: AgentGrantId }, messages: [Message.SucceededRevoke, Message.FailedRevoke], execute: ({ grantId }) => @@ -43,7 +43,7 @@ export const RevokeGrant = Command.define("RevokeAgentGrant", { const scopesOf = (access: TokenAccess): Array => access === "write" ? ["messages:read", "messages:write"] : ["messages:read"] -export const CreateToken = Command.define("CreateAgentToken", { +export const CreateAgentToken = Command.define("CreateAgentToken", { args: { name: Schema.String, access: TokenAccess }, messages: [Message.SucceededCreateToken, Message.FailedCreateToken], execute: ({ name, access }) => @@ -60,7 +60,7 @@ export const CreateToken = Command.define("CreateAgentToken", { ), }) -export const CopyText = Command.define("CopyAgentText", { +export const CopyAgentText = Command.define("CopyAgentText", { args: { target: CopyTarget, text: Schema.String }, messages: [Message.SucceededCopy, Message.FailedCopy], execute: ({ target, text }) => diff --git a/apps/web-foldkit/src/page/my-settings/agents/model.ts b/apps/web-foldkit/src/page/my-settings/agents/model.ts index e97c2f1de..96f79846e 100644 --- a/apps/web-foldkit/src/page/my-settings/agents/model.ts +++ b/apps/web-foldkit/src/page/my-settings/agents/model.ts @@ -42,3 +42,13 @@ export const Model = Schema.Struct({ revoking: Schema.NullOr(AgentGrantId), }) export type Model = typeof Model.Type + +/** The longest token name the API takes (`CreateAgentTokenRequest`). */ +export const TOKEN_NAME_MAX = 80 + +/** + * A token may be created with a name, and once the one on show is dismissed: its secret is + * shown only once, so a second creation must not replace it. + */ +export const canCreateToken = (model: Model) => + !model.isCreating && model.createdToken === null && model.tokenName.trim().length > 0 diff --git a/apps/web-foldkit/src/page/my-settings/agents/update.ts b/apps/web-foldkit/src/page/my-settings/agents/update.ts index b2a9b4597..4dae70fbd 100644 --- a/apps/web-foldkit/src/page/my-settings/agents/update.ts +++ b/apps/web-foldkit/src/page/my-settings/agents/update.ts @@ -4,9 +4,9 @@ import { errorToast, successToast } from "../../../data/actions" import type { RouteOf } from "../../../route" import type { PageReturn } from "../../contract" import { PageOutMessage } from "../../out-message" -import { CopyText, CreateToken, FetchGrants, RevokeGrant } from "./command" +import { CopyAgentText, CreateAgentToken, FetchAgentGrants, RevokeAgentGrant } from "./command" import { Message } from "./message" -import { Grants, type Model } from "./model" +import { canCreateToken, Grants, type Model, TOKEN_NAME_MAX } from "./model" type Return = PageReturn @@ -21,7 +21,7 @@ export const init = (route: RouteOf<"MySettingsAgents">): Return => ({ confirmingRevoke: null, revoking: null, }, - commands: [FetchGrants()], + commands: [FetchAgentGrants()], }) const toast = ( @@ -42,7 +42,7 @@ export const update = (model: Model, message: Message): Return => }), ClickedRetry: () => ({ model: modifyFields(model, { grants: () => Grants.Loading() }), - commands: [FetchGrants()], + commands: [FetchAgentGrants()], }), ClickedRevoke: ({ grantId }) => model.revoking !== null @@ -54,7 +54,7 @@ export const update = (model: Model, message: Message): Return => ? { model } : { model: modifyFields(model, { confirmingRevoke: () => null, revoking: () => grantId }), - commands: [RevokeGrant({ grantId })], + commands: [RevokeAgentGrant({ grantId })], }, SucceededRevoke: ({ grantId }) => toast( @@ -75,15 +75,17 @@ export const update = (model: Model, message: Message): Return => modifyFields(model, { revoking: () => null }), errorToast("Couldn't disconnect the agent", commonMessage(reason).title), ), - ChangedTokenName: ({ value }) => ({ model: modifyFields(model, { tokenName: () => value }) }), + ChangedTokenName: ({ value }) => ({ + model: modifyFields(model, { tokenName: () => value.slice(0, TOKEN_NAME_MAX) }), + }), SelectedTokenAccess: ({ access }) => ({ model: modifyFields(model, { tokenAccess: () => access }) }), ClickedCreateToken: () => { const name = model.tokenName.trim() - return model.isCreating || name.length === 0 + return !canCreateToken(model) ? { model } : { model: modifyFields(model, { isCreating: () => true }), - commands: [CreateToken({ name, access: model.tokenAccess })], + commands: [CreateAgentToken({ name, access: model.tokenAccess })], } }, SucceededCreateToken: ({ token, grant }) => ({ @@ -103,7 +105,7 @@ export const update = (model: Model, message: Message): Return => errorToast("Couldn't create the token", commonMessage(reason).title), ), ClickedDismissToken: () => ({ model: modifyFields(model, { createdToken: () => null }) }), - ClickedCopy: ({ target, text }) => ({ model, commands: [CopyText({ target, text })] }), + ClickedCopy: ({ target, text }) => ({ model, commands: [CopyAgentText({ target, text })] }), SucceededCopy: ({ target }) => toast(model, successToast(target === "Token" ? "Token copied" : "MCP URL copied")), FailedCopy: () => toast(model, errorToast("Couldn't copy to the clipboard")), diff --git a/apps/web-foldkit/src/page/my-settings/agents/view.ts b/apps/web-foldkit/src/page/my-settings/agents/view.ts index 6ca3869c5..f2bab0208 100644 --- a/apps/web-foldkit/src/page/my-settings/agents/view.ts +++ b/apps/web-foldkit/src/page/my-settings/agents/view.ts @@ -10,7 +10,7 @@ import { textField } from "../../../ui/text-field" import type { PageViewInputs } from "../../contract" import { divider, pageHeader, settingsRow } from "../shared" import { Message } from "./message" -import { type CreatedToken, type Grant, Grants, type Model, type TokenAccess } from "./model" +import { canCreateToken, type CreatedToken, type Grant, Grants, type Model, type TokenAccess } from "./model" const ago = (ms: number, nowMs: number) => formatDistanceStrict(ms, Math.max(ms, nowMs), { addSuffix: true }) @@ -132,7 +132,7 @@ const createSection = (h: HtmlBuilder, model: Model): Html => id: "agent-token-name", value: model.tokenName, onInput: (value) => Message.ChangedTokenName({ value }), - isDisabled: model.isCreating, + isDisabled: model.isCreating || model.createdToken !== null, }, (field) => [ field.label(["Name"]), @@ -151,7 +151,7 @@ const createSection = (h: HtmlBuilder, model: Model): Html => { intent: "primary", size: "sm", - isDisabled: model.isCreating || model.tokenName.trim().length === 0, + isDisabled: !canCreateToken(model), onPress: Message.ClickedCreateToken(), }, [model.isCreating ? "Creating..." : "Create token"], diff --git a/apps/web-foldkit/src/page/oauth-authorize/command.ts b/apps/web-foldkit/src/page/oauth-authorize/command.ts index 43cdffdda..cecfb7efb 100644 --- a/apps/web-foldkit/src/page/oauth-authorize/command.ts +++ b/apps/web-foldkit/src/page/oauth-authorize/command.ts @@ -47,11 +47,7 @@ export const AuthorizeAgent = Command.define("AuthorizeAgent", { execute: ({ scope, state, ...request }) => HazelApiClient.use((client) => client.agentAccess.authorizeAgent({ - payload: { - ...request, - ...(scope === null ? {} : { scope }), - ...(state === null ? {} : { state }), - }, + payload: { ...request, scope: scope ?? undefined, state: state ?? undefined }, }), ).pipe( Effect.flatMap(({ redirectTo }) => load(redirectTo)), diff --git a/apps/web-foldkit/src/page/oauth-authorize/view.ts b/apps/web-foldkit/src/page/oauth-authorize/view.ts index d5f598359..b6261f035 100644 --- a/apps/web-foldkit/src/page/oauth-authorize/view.ts +++ b/apps/web-foldkit/src/page/oauth-authorize/view.ts @@ -13,7 +13,7 @@ import { Message } from "./message" import { type ApproveFailure, type ClientSummary, Lookup, type Model } from "./model" /** What each scope lets the agent do, in the user's words. */ -const SCOPE_ABILITIES: Readonly>> = { +const SCOPE_ABILITIES = { "messages:read": ["Read your channels, direct messages and threads", "See messages that mention you"], "messages:write": [ "Send messages and replies as you", @@ -22,7 +22,7 @@ const SCOPE_ABILITIES: Readonly>> = { "Edit and delete your messages", "Set your status", ], -} +} satisfies Readonly>> const homeLink = (h: HtmlBuilder): Html => h.a( diff --git a/apps/web-foldkit/src/shell/shell.story.test.ts b/apps/web-foldkit/src/shell/shell.story.test.ts index ec6ccb21f..5ccdc9b6b 100644 --- a/apps/web-foldkit/src/shell/shell.story.test.ts +++ b/apps/web-foldkit/src/shell/shell.story.test.ts @@ -118,7 +118,8 @@ describe("org switcher", () => { expect(mobile.orgSwitcher.selectedKeys).toEqual([hazelOrg.id]) }) - // B2: the "Single" menu selects the clicked key before the shell folds its OutMessage. + // B2: the "Single" menu selects the clicked key before the shell folds its OutMessage. A phone + // lands on the channel list, not the org home (#494). test("another organization navigates to its slug", () => { story( runMobile, @@ -127,7 +128,7 @@ describe("org switcher", () => { message(orgSwitcher(clicked(otherOrgId, mobile.orgSwitcherEntries))), expectOutMessage( PageOutMessage.RequestedNavigation({ - route: AppRoute.OrgHome({ orgSlug: "acme" }), + route: AppRoute.ChatIndex({ orgSlug: "acme" }), replace: false, }), ), diff --git a/packages/db/src/tables/agents.ts b/packages/db/src/tables/agents.ts index d964c8dcf..d41e5c7e0 100644 --- a/packages/db/src/tables/agents.ts +++ b/packages/db/src/tables/agents.ts @@ -48,7 +48,11 @@ export const agentGrantsTable = SQLite.table("agent_grants", { }) export type AgentGrant = SQLite.SelectRowOf -export const agentTokenKindEnum = textEnum(["access", "refresh", "personal"]) +/** + * `spent`: a refresh token already exchanged, kept until it would have expired so a second use is + * seen as the theft it is (RFC 9700 §4.14.2) and ends the grant. + */ +export const agentTokenKindEnum = textEnum(["access", "refresh", "personal", "spent"]) /** A bearer credential of a grant, by its SHA-256 hex. `expiresAt` null: until revoked. */ export const agentTokensTable = SQLite.table("agent_tokens", { From f126049270008083084455fa243a243e83643e75 Mon Sep 17 00:00:00 2001 From: Makisuo Date: Mon, 16 Nov 2026 16:48:28 +0100 Subject: [PATCH 4/6] fix(mcp): refresh claims last, create-only upload URLs, byte-capped bodies - refresh issues the new tokens before marking the presented one spent (D1 has no transactions): a failure before the claim leaves it usable for a retry instead of reading as reuse and ending the grant; losing the claim to a concurrent refresh drops the tokens just issued - create_upload_url signs If-None-Match: * into the URL and upload_file sends it: the bucket (R2, MinIO) refuses a second PUT to the key, so a file cannot be replaced after send_message checked it - /mcp reads its body chunk by chunk and stops past 14 MB of actual bytes, with or without Content-Length Co-Authored-By: Claude Opus 5.5 --- apps/backend/src/routes/mcp.http.test.ts | 15 +++++ apps/backend/src/routes/mcp.ts | 44 +++++++++++--- apps/backend/src/services/agent-access.ts | 64 +++++++++++++-------- apps/backend/src/services/object-storage.ts | 12 +++- 4 files changed, 102 insertions(+), 33 deletions(-) diff --git a/apps/backend/src/routes/mcp.http.test.ts b/apps/backend/src/routes/mcp.http.test.ts index f8ff5e476..1bfe5de01 100644 --- a/apps/backend/src/routes/mcp.http.test.ts +++ b/apps/backend/src/routes/mcp.http.test.ts @@ -411,6 +411,21 @@ describe("MCP server", () => { expect(edit.isError).toBe(true) expect(messagesIn(world.channel)[0]!.content).toBe("bob says hi") + // A body past the cap is refused while it streams, with no Content-Length to go by. + const huge = new Uint8Array(15 * 1024 * 1024).fill(32) + const oversized = yield* world.fetch("/mcp", { + method: "POST", + headers: { authorization: `Bearer ${writer.token}` }, + body: new ReadableStream({ + start: (controller) => { + controller.enqueue(huge) + controller.close() + }, + }), + duplex: "half", + } as RequestInit) + expect(oversized.status).toBe(413) + // Notifications are a JSON-RPC notification: 202, no body. const note = yield* world.fetch("/mcp", { method: "POST", diff --git a/apps/backend/src/routes/mcp.ts b/apps/backend/src/routes/mcp.ts index 24d713e2c..aad138980 100644 --- a/apps/backend/src/routes/mcp.ts +++ b/apps/backend/src/routes/mcp.ts @@ -23,7 +23,7 @@ import { import { AttachmentId, ChannelId, MessageId, OrganizationId, type UserId } from "@hazel/schema" import { isActiveContentType, MAX_ATTACHMENT_SIZE } from "@hazel/domain/http" import { v7 as randomUUIDv7 } from "uuid" -import { DateTime, Effect, Option, Schema } from "effect" +import { DateTime, Effect, Option, Schema, Stream } from "effect" import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http" import { AgentAccess, type AgentPrincipal } from "../services/agent-access" import { createAttachmentInChannel } from "../services/attachment-uploads" @@ -49,6 +49,36 @@ const MAX_CONTENT_LENGTH = 8000 /** The largest JSON-RPC body read: a 10 MB file as base64 (4/3) and room for the envelope. */ const MAX_REQUEST_BYTES = 14 * 1024 * 1024 +class BodyTooLarge extends Schema.TaggedError()("BodyTooLarge", {}) {} + +/** + * The body as text, read chunk by chunk and abandoned past `MAX_REQUEST_BYTES` actual bytes (a + * missing or false `Content-Length` cannot get more read); none when too large, "" when unreadable. + */ +const readCapped = (request: HttpServerRequest.HttpServerRequest) => + request.stream.pipe( + Stream.runFoldEffect( + () => ({ chunks: new Array(), size: 0 }), + (acc, chunk: Uint8Array) => { + const size = acc.size + chunk.byteLength + if (size > MAX_REQUEST_BYTES) return Effect.fail(new BodyTooLarge()) + acc.chunks.push(chunk) + return Effect.succeed({ chunks: acc.chunks, size }) + }, + ), + Effect.map(({ chunks, size }) => { + const bytes = new Uint8Array(size) + let offset = 0 + for (const chunk of chunks) { + bytes.set(chunk, offset) + offset += chunk.byteLength + } + return Option.some(new TextDecoder().decode(bytes)) + }), + Effect.catchTag("BodyTooLarge", () => Effect.succeed(Option.none())), + Effect.orElseSucceed(() => Option.some("")), + ) + const tooLarge = HttpServerResponse.jsonUnsafe( { jsonrpc: "2.0", id: null, error: { code: -32600, message: "The request is too large" } }, { status: 413 }, @@ -717,7 +747,7 @@ const tools: ReadonlyArray = [ name: "create_upload_url", title: "Create upload URL", description: - "For a file on disk or too big to inline (up to 10 MB): returns an upload_url valid for 15 minutes. PUT the raw bytes there with the given headers (e.g. curl -X PUT -H 'Content-Type: …' --data-binary @file ''), then post attachment_id with send_message's attachment_ids.", + "For a file on disk or too big to inline (up to 10 MB): returns an upload_url valid for 15 minutes. PUT the raw bytes there with the given headers (e.g. curl -X PUT -H 'Content-Type: …' -H 'If-None-Match: *' --data-binary @file ''); the URL stores one file and cannot replace it, then post attachment_id with send_message's attachment_ids.", scope: "messages:write", readOnly: false, inputSchema: obj( @@ -737,13 +767,13 @@ const tools: ReadonlyArray = [ const contentType = storedContentType(fileName, args.content_type) const id = yield* startUpload(ctx, channelId, fileName, fileSize) const uploadUrl = yield* ctx.storage - .presignPut(id, { contentType, expiresIn: UPLOAD_URL_TTL_SECONDS }) + .presignPut(id, { contentType, expiresIn: UPLOAD_URL_TTL_SECONDS, createOnly: true }) .pipe(Effect.mapError((error) => toolError(error.message))) return { attachment_id: id, upload_url: uploadUrl, method: "PUT", - headers: { "Content-Type": contentType }, + headers: { "Content-Type": contentType, "If-None-Match": "*" }, expires_in_seconds: UPLOAD_URL_TTL_SECONDS, } }), @@ -1098,11 +1128,11 @@ export const McpRoute = HttpRouter.use((router) => // `upload_file` carries a file of up to 10 MB as base64; nothing larger is read. const declared = Number(request.headers["content-length"] ?? "0") if (declared > MAX_REQUEST_BYTES) return tooLarge - const body = yield* request.text.pipe(Effect.orElseSucceed(() => "")) - if (body.length > MAX_REQUEST_BYTES) return tooLarge + const body = yield* readCapped(request) + if (Option.isNone(body)) return tooLarge let parsed: unknown try { - parsed = JSON.parse(body) + parsed = JSON.parse(body.value) } catch { return HttpServerResponse.jsonUnsafe(rpcError(null, -32700, "Parse error"), { status: 400, diff --git a/apps/backend/src/services/agent-access.ts b/apps/backend/src/services/agent-access.ts index 55a54d9ea..d22f9e16b 100644 --- a/apps/backend/src/services/agent-access.ts +++ b/apps/backend/src/services/agent-access.ts @@ -288,39 +288,55 @@ export class AgentAccess extends Context.Service()("@hazel/backend/ /** * `grant_type=refresh_token`: rotate. The old refresh token is kept as `spent`; presenting it * again means it leaked (whoever refreshed first holds the live chain), so the grant ends. + * + * D1 has no transactions, so the claim is the last write: the new tokens are issued first, and + * a failure before the claim leaves the presented token usable for a retry. Losing the claim + * to a concurrent refresh of the same token drops the tokens just issued. */ const refresh = (input: { readonly refreshToken: string; readonly clientId: string }) => Effect.gen(function* () { const tokenHash = yield* sha256Hex(input.refreshToken) - const claimed = yield* db.first( + const presented = yield* db.first( + SQLite.from(schema.agentTokensTable) + .select("grantId", "kind", "expiresAt") + .where(($) => [$.tokenHash.eq(tokenHash)]), + ) + if (Option.isSome(presented) && presented.value.kind === "spent") { + yield* Effect.logWarning("Agent refresh token reused; ending its grant", { + grantId: presented.value.grantId, + }) + yield* endGrant(presented.value.grantId) + return yield* invalidGrant("The refresh token was already used; sign in again") + } + if ( + Option.isNone(presented) || + presented.value.kind !== "refresh" || + presented.value.expiresAt === null || + presented.value.expiresAt.getTime() <= Date.now() + ) + return yield* invalidGrant("The refresh token is invalid or expired") + const grant = yield* liveGrant(presented.value.grantId) + if (Option.isNone(grant) || grant.value.clientId !== input.clientId) + return yield* invalidGrant("The grant was revoked") + + const issued = yield* issueTokens(grant.value.id, toScopes(grant.value.scopes)) + const claimed = yield* db.run( SQLite.update(schema.agentTokensTable) .set({ kind: "spent" }) - .where(($) => [ - $.tokenHash.eq(tokenHash), - $.kind.eq("refresh"), - $.expiresAt.gt(new Date()), - ]) - .returning("grantId"), + .where(($) => [$.tokenHash.eq(tokenHash), $.kind.eq("refresh")]) + .returning("tokenHash"), ) - if (Option.isNone(claimed)) { - const reused = yield* db.first( - SQLite.from(schema.agentTokensTable) - .select("grantId") - .where(($) => [$.tokenHash.eq(tokenHash), $.kind.eq("spent")]), + if (claimed.length === 0) { + const lost = yield* Effect.all([ + sha256Hex(issued.accessToken), + sha256Hex(issued.refreshToken), + ]) + yield* db.run( + SQLite.deleteFrom(schema.agentTokensTable).where(($) => [$.tokenHash.in_(...lost)]), ) - if (Option.isSome(reused)) { - yield* Effect.logWarning("Agent refresh token reused; ending its grant", { - grantId: reused.value.grantId, - }) - yield* endGrant(reused.value.grantId) - return yield* invalidGrant("The refresh token was already used; sign in again") - } - return yield* invalidGrant("The refresh token is invalid or expired") + return yield* invalidGrant("The refresh token was already used") } - const grant = yield* liveGrant(claimed.value.grantId) - if (Option.isNone(grant) || grant.value.clientId !== input.clientId) - return yield* invalidGrant("The grant was revoked") - return yield* issueTokens(grant.value.id, toScopes(grant.value.scopes)) + return issued }).pipe(Effect.withSpan("AgentAccess.refresh")) /** The user and grant a bearer token acts for: a live access or personal token of a live grant. */ diff --git a/apps/backend/src/services/object-storage.ts b/apps/backend/src/services/object-storage.ts index 4781c5049..a49d396ba 100644 --- a/apps/backend/src/services/object-storage.ts +++ b/apps/backend/src/services/object-storage.ts @@ -10,6 +10,11 @@ export interface PresignPutOptions { readonly contentType: string /** Seconds until the URL expires. */ readonly expiresIn: number + /** + * Sign `If-None-Match: *` into the URL: the PUT must send it, and the bucket refuses it (412) + * once an object is at the key, so the URL cannot replace a file after it was checked. + */ + readonly createOnly?: boolean } /** @@ -45,7 +50,8 @@ export class ObjectStorage extends Context.Service()("ObjectStora try: () => client.fetch(urlOf(key).toString(), { method: "PUT", - headers: { "Content-Type": contentType }, + // The key is a fresh attachment id: never replace what is there. + headers: { "Content-Type": contentType, "If-None-Match": "*" }, body, aws: { allHeaders: true }, }), @@ -82,7 +88,9 @@ export class ObjectStorage extends Context.Service()("ObjectStora try: () => client.sign(url.toString(), { method: "PUT", - headers: { "Content-Type": options.contentType }, + headers: options.createOnly + ? { "Content-Type": options.contentType, "If-None-Match": "*" } + : { "Content-Type": options.contentType }, // `allHeaders` signs Content-Type too (aws4fetch skips it by default): the PUT must send // the type the handler checked, so a refused type cannot be stored after all. aws: { signQuery: true, allHeaders: true }, From e3d27c86884da76ecb6eb8a50e79547b95373243 Mon Sep 17 00:00:00 2001 From: Makisuo Date: Mon, 16 Nov 2026 16:54:25 +0100 Subject: [PATCH 5/6] test(mcp): pin the create-only upload URL The storage fake records presignPut's options; create_upload_url must sign createOnly and hand the agent If-None-Match: * (Maple review F1). Co-Authored-By: Claude Opus 5.5 --- apps/backend/src/routes/mcp.http.test.ts | 25 +++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/apps/backend/src/routes/mcp.http.test.ts b/apps/backend/src/routes/mcp.http.test.ts index 1bfe5de01..3e053ca43 100644 --- a/apps/backend/src/routes/mcp.http.test.ts +++ b/apps/backend/src/routes/mcp.http.test.ts @@ -13,7 +13,7 @@ import { HttpRouter } from "effect/http" import { describe, expect, it } from "vitest" import { AgentAccess } from "../services/agent-access" import { Directory } from "../services/directory" -import { ObjectStorage } from "../services/object-storage" +import { ObjectStorage, type PresignPutOptions } from "../services/object-storage" import { RateLimiterAllowAll } from "../services/rate-limiter" import { channelTarget, orgTarget, userTarget } from "../worker/objects/kinds" import { ObjectStubs } from "../worker/objects/protocol" @@ -82,9 +82,13 @@ const makeWorld = Effect.gen(function* () { // The bucket: what `put` stored, and what a presigned PUT would have. const bucket = new Map() + const presigned = new Map() const storage = Layer.succeed(ObjectStorage)({ - presignPut: (key: string, options: { contentType: string }) => - Effect.succeed(`https://bucket.test/${key}?type=${encodeURIComponent(options.contentType)}`), + presignPut: (key: string, options: PresignPutOptions) => + Effect.sync(() => { + presigned.set(key, options) + return `https://bucket.test/${key}?type=${encodeURIComponent(options.contentType)}` + }), put: (key: string, bytes: Uint8Array, contentType: string) => Effect.sync(() => { bucket.set(key, { bytes, contentType }) @@ -120,7 +124,7 @@ const makeWorld = Effect.gen(function* () { yield* Layer.build(AgentAccess.layer.pipe(Layer.provide(Layer.succeedContext(objects.directory)))), AgentAccess, ) - return { objects, orgId, alice, channelId, channel, fetch, access, bucket } + return { objects, orgId, alice, channelId, channel, fetch, access, bucket, presigned } }).pipe(Effect.orDie) type World = Effect.Success @@ -486,9 +490,16 @@ describe("MCP server", () => { file_size: 3, }) const urlId = url.structuredContent.attachment_id - expect(url.structuredContent).toMatchObject({ - method: "PUT", - headers: { "Content-Type": "image/png" }, + // Create-only: signed with If-None-Match: *, which the agent is told to send. + expect(url.structuredContent).toMatchObject({ method: "PUT" }) + expect(url.structuredContent.headers).toEqual({ + "Content-Type": "image/png", + "If-None-Match": "*", + }) + expect(world.presigned.get(urlId)).toEqual({ + contentType: "image/png", + expiresIn: 900, + createOnly: true, }) const early = yield* callTool(world, token, "send_message", { channel_id: world.channelId, From 1ac322518367b8b07cd64c021ea3363d33e3fc31 Mon Sep 17 00:00:00 2001 From: Makisuo Date: Mon, 16 Nov 2026 16:59:01 +0100 Subject: [PATCH 6/6] fix(mcp): a concurrent refresh ends the grant; no length is no size - losing the refresh claim to a concurrent use of the same token is reuse: the grant ends with the winner's tokens, as a sequential reuse does - storedSize fails when the bucket's HEAD has no valid Content-Length instead of reading it as 0 bytes, which would pass the 10 MB check Co-Authored-By: Claude Opus 5.5 --- apps/backend/src/routes/mcp.http.test.ts | 35 +++++++++++++++++++-- apps/backend/src/services/agent-access.ts | 15 +++++---- apps/backend/src/services/object-storage.ts | 6 +++- 3 files changed, 45 insertions(+), 11 deletions(-) diff --git a/apps/backend/src/routes/mcp.http.test.ts b/apps/backend/src/routes/mcp.http.test.ts index 3e053ca43..9ade28105 100644 --- a/apps/backend/src/routes/mcp.http.test.ts +++ b/apps/backend/src/routes/mcp.http.test.ts @@ -8,7 +8,7 @@ import { createHash } from "node:crypto" import { NodeHttpPlatform, NodeServices } from "@effect/platform-node" import { SQLite, schema } from "@hazel/db" import type { AgentClientId, ChannelId, OrganizationId, UserId } from "@hazel/schema" -import { ConfigProvider, Context, Effect, Layer, Option, type Scope } from "effect" +import { ConfigProvider, Context, Effect, Exit, Layer, Option, type Scope } from "effect" import { HttpRouter } from "effect/http" import { describe, expect, it } from "vitest" import { AgentAccess } from "../services/agent-access" @@ -360,13 +360,44 @@ describe("MCP server", () => { }), ) + // Two refreshes of one token at once end the grant, whichever wins. + const racedTokens = yield* json( + yield* exchange({ + grant_type: "refresh_token", + refresh_token: again.refresh_token, + client_id: clientId, + }), + ) + const refreshOnce = Effect.exit( + world.access.refresh({ refreshToken: racedTokens.refresh_token, clientId }), + ) + const raced = yield* Effect.all([refreshOnce, refreshOnce], { concurrency: "unbounded" }) + expect(raced.filter(Exit.isFailure).length).toBeGreaterThanOrEqual(1) + expect(yield* world.access.listGrants(world.alice)).toEqual([]) + const code4 = yield* world.access.createCode({ + clientId, + userId: world.alice, + redirectUri, + codeChallenge: challenge, + scopes: ["messages:read", "messages:write"], + }) + const fresh = yield* json( + yield* exchange({ + grant_type: "authorization_code", + code: code4, + client_id: clientId, + redirect_uri: redirectUri, + code_verifier: verifier, + }), + ) + // Revoking the grant ends every token at once. const [grant] = yield* world.access.listGrants(world.alice) expect(grant).toMatchObject({ kind: "oauth", name: "Claude" }) expect(yield* world.access.revokeGrant(world.alice, grant!.id)).toBe(true) const after = yield* world.fetch("/mcp", { method: "POST", - headers: { authorization: `Bearer ${again.access_token}` }, + headers: { authorization: `Bearer ${fresh.access_token}` }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }), }) expect(after.status).toBe(401) diff --git a/apps/backend/src/services/agent-access.ts b/apps/backend/src/services/agent-access.ts index d22f9e16b..9e1338bed 100644 --- a/apps/backend/src/services/agent-access.ts +++ b/apps/backend/src/services/agent-access.ts @@ -327,14 +327,13 @@ export class AgentAccess extends Context.Service()("@hazel/backend/ .returning("tokenHash"), ) if (claimed.length === 0) { - const lost = yield* Effect.all([ - sha256Hex(issued.accessToken), - sha256Hex(issued.refreshToken), - ]) - yield* db.run( - SQLite.deleteFrom(schema.agentTokensTable).where(($) => [$.tokenHash.in_(...lost)]), - ) - return yield* invalidGrant("The refresh token was already used") + // Two refreshes of one token at once: the same reuse, decided by timing. End the grant + // (the winner's tokens with it), as a sequential reuse does. + yield* Effect.logWarning("Agent refresh token used concurrently; ending its grant", { + grantId: grant.value.id, + }) + yield* endGrant(grant.value.id) + return yield* invalidGrant("The refresh token was already used; sign in again") } return issued }).pipe(Effect.withSpan("AgentAccess.refresh")) diff --git a/apps/backend/src/services/object-storage.ts b/apps/backend/src/services/object-storage.ts index a49d396ba..4fa375d61 100644 --- a/apps/backend/src/services/object-storage.ts +++ b/apps/backend/src/services/object-storage.ts @@ -75,7 +75,11 @@ export class ObjectStorage extends Context.Service()("ObjectStora if (response.status === 404) return Option.none() if (!response.ok) return yield* new ObjectStorageError({ message: `The bucket answered ${response.status}` }) - return Option.some(Number(response.headers.get("content-length") ?? "0")) + // The size check rests on it: no length is an error, never "0 bytes". + const size = Number(response.headers.get("content-length") ?? Number.NaN) + if (!Number.isFinite(size) || size < 0) + return yield* new ObjectStorageError({ message: "The bucket gave no valid Content-Length" }) + return Option.some(size) }) const presignPut = Effect.fn("ObjectStorage.presignPut")(function* (