Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PeerLinks.testkit.ts

211 lines8.1 KB

1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import {
4 EnvironmentHttpApi,
5 EnvironmentId,
6 type AuthMcpClientAccess,
7 type ExecutionEnvironmentDescriptor,
8} from "@t3tools/contracts";
9import * as Context from "effect/Context";
10import * as Effect from "effect/Effect";
11import * as Layer from "effect/Layer";
12import * as Ref from "effect/Ref";
13import * as FetchHttpClient from "effect/http/FetchHttpClient";
14import * as HttpRouter from "effect/http/HttpRouter";
15import * as HttpServer from "effect/http/HttpServer";
16import * as HttpServerRequest from "effect/http/HttpServerRequest";
17import * as HttpApi from "effect/http-api/HttpApi";
18import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
19​
20import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
21import * as AuthHttp from "../auth/http.ts";
22import * as McpOAuth from "../auth/McpOAuth.ts";
23import * as McpOAuthHttp from "../auth/mcpOAuthHttp.ts";
24import type * as SqlClient from "effect/sql/SqlClient";
25import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
26import * as CloudLink from "../cloud/CloudLink.ts";
27import * as ServerConfig from "../config.ts";
28import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
29import * as ServerHttp from "../http.ts";
30import * as McpHttpServer from "../mcp/McpHttpServer.ts";
31import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts";
32import * as Sqlite from "../persistence/Sqlite.ts";
33import * as PeerLinks from "./PeerLinks.ts";
34import * as ServerSettings from "../serverSettings.ts";
35import * as PeerMcpClient from "./PeerMcpClient.ts";
36import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
37​
38class PeerTestApi extends HttpApi.make("environment")
39 .add(EnvironmentHttpApi.groups.metadata)
40 .add(EnvironmentHttpApi.groups.mcpOAuth) {}
41​
42export const descriptorOf = (
43 environmentId: string,
44 label: string,
45 capabilities: Partial<ExecutionEnvironmentDescriptor["capabilities"]> = {},
46): ExecutionEnvironmentDescriptor => ({
47 environmentId: EnvironmentId.make(environmentId),
48 label,
49 platform: { os: "linux", arch: "x64" },
50 serverVersion: "0.0.0-test",
51 capabilities: {
52 repositoryIdentity: true,
53 mcpModeLimitHeader: true,
54 linkFence: true,
55 ...capabilities,
56 },
57});
58​
59/**
60 * The environment a link points at, as it runs: its descriptor, MCP OAuth,
61 * and `/mcp` with `tools` behind the real client authenticator, on a real
62 * socket. The descriptor can be swapped, as when its address comes to answer
63 * as another environment, and every bearer it receives is recorded.
64 */
65export const servePeer = <E, R>(
66 initial: ExecutionEnvironmentDescriptor,
67 tools: Layer.Layer<never, E, R>,
68) =>
69 Effect.gen(function* () {
70 const descriptor = yield* Ref.make(initial);
71 const bearers = yield* Ref.make<ReadonlyArray<string>>([]);
72 const probes = yield* Ref.make(0);
73 const layerEnvironment = Layer.succeed(ServerEnvironment.ServerEnvironment, {
74 getEnvironmentId: Ref.get(descriptor).pipe(Effect.map((current) => current.environmentId)),
75 getDescriptor: Ref.get(descriptor),
76 });
77 const authContext = yield* EnvironmentAuth.layer.pipe(
78 Layer.provide(ManagedPolicy.layerTest()),
79 Layer.provideMerge(ServerSettings.layerTest({ linkedEnvironmentsEnabled: true })),
80 Layer.provide(Sqlite.layerMemory),
81 Layer.provideMerge(ServerSecretStore.layer),
82 Layer.provideMerge(ServerEnvironment.layerIdentity),
83 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-peer-link-peer-" })),
84 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
85 Layer.fresh,
86 Layer.build,
87 );
88 const layerRecordBearers = HttpRouter.middleware(
89 (httpEffect) =>
90 Effect.gen(function* () {
91 const request = yield* HttpServerRequest.HttpServerRequest;
92 if (request.url.startsWith("/.well-known/t3/environment")) {
93 yield* Ref.update(probes, (count) => count + 1);
94 }
95 const authorization = request.headers.authorization;
96 if (authorization !== undefined) {
97 yield* Ref.update(bearers, (seen) => [...seen, authorization]);
98 }
99 return yield* httpEffect;
100 }),
101 { global: true },
102 );
103 const layerRoutes = Layer.mergeAll(
104 HttpApiBuilder.layer(PeerTestApi).pipe(
105 Layer.provide(
106 McpOAuthHttp.layer.pipe(
107 Layer.provide(McpOAuth.layer),
108 Layer.provide(
109 Layer.mock(CloudLink.CloudLink)({
110 linkState: () =>
111 Effect.succeed({
112 linked: false,
113 cloudUserId: null,
114 relayUrl: null,
115 relayIssuer: null,
116 publishAgentActivity: false,
117 }),
118 }),
119 ),
120 ),
121 ),
122 Layer.provide(ServerHttp.layerServerEnvironmentHttpApi),
123 Layer.provide(AuthHttp.layerAuthenticatedAuth),
124 ),
125 McpHttpServer.layerMcpTransport(tools).pipe(
126 Layer.provide(
127 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
128 resolve: () => Effect.undefined,
129 }),
130 ),
131 Layer.provide(McpOAuth.layerMcpClientAuthenticator),
132 ),
133 ).pipe(
134 Layer.provide(layerRecordBearers),
135 Layer.provide(layerEnvironment),
136 Layer.provide(Layer.succeedContext(authContext)),
137 );
138 // Fresh, so the peer never shares a toolkit or MCP server with the
139 // environment that links to it in the same test.
140 yield* HttpRouter.serve(layerRoutes, { disableListenLog: true, disableLogger: true }).pipe(
141 Layer.fresh,
142 Layer.build,
143 );
144 const address = (yield* HttpServer.HttpServer).address;
145 if (address._tag === "UnixPathAddress") return yield* Effect.die("expected a TCP address");
146 const url = `http://127.0.0.1:${address.port}`;
147 const auth = Context.get(authContext, EnvironmentAuth.EnvironmentAuth);
148 return {
149 url,
150 auth,
151 /** Its settings, as for turning its Linked environments beta off. */
152 settings: Context.get(authContext, ServerSettings.ServerSettingsService),
153 descriptor,
154 bearers,
155 /** How often its descriptor was asked for, as a probe of whether it answers. */
156 probes,
157 /** The sessions linking created there, which its Connections lists. */
158 linkedSessions: auth
159 .listSessions()
160 .pipe(
161 Effect.map((sessions) =>
162 sessions.filter((session) => session.client.label?.startsWith("T3 Code · ")),
163 ),
164 ),
165 };
166 });
167​
168export type ServedPeer = Effect.Success<ReturnType<typeof servePeer>>;
169​
170/**
171 * The environment that links: its own database and secret store, reaching
172 * peers over plain HTTP. Provide it to anything built on its links.
173 */
174export const layerLinkingEnvironment = <E = never>(
175 descriptor: ExecutionEnvironmentDescriptor,
176 secrets: typeof ServerSecretStore.layer = ServerSecretStore.layer,
177 database: Layer.Layer<
178 SqlClient.SqlClient,
179 E | Layer.Error<typeof Sqlite.layerMemory>
180 > = Sqlite.layerMemory,
181) =>
182 PeerMcpClient.layer.pipe(
183 Layer.provideMerge(PeerLinks.layer),
184 Layer.provideMerge(ServerSettings.layerTest({ linkedEnvironmentsEnabled: true })),
185 Layer.provideMerge(database),
186 Layer.provide(Layer.mergeAll(secrets, FetchHttpClient.layer)),
187 // Services that act for this environment, such as delegation, name it too.
188 Layer.provideMerge(
189 Layer.succeed(ServerEnvironment.ServerEnvironment, {
190 getEnvironmentId: Effect.succeed(descriptor.environmentId),
191 getDescriptor: Effect.succeed(descriptor),
192 }),
193 ),
194 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-peer-link-here-" })),
195 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
196 Layer.fresh,
197 );
198​
199/** Links `links` to `peer` with a fresh pairing code from it. */
200export const linkTo = (
201 links: PeerLinks.PeerLinks["Service"],
202 peer: ServedPeer,
203 access: AuthMcpClientAccess = "auto",
204) =>
205 peer.auth
206 .issuePairingCredential()
207 .pipe(
208 Effect.flatMap((pairing) =>
209 links.link({ url: peer.url, pairingCode: pairing.credential, access }),
210 ),
211 );