@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 120 lines 4.57 KB
Raw
1 import * as Binding from "alchemy/Binding";
2 import type { RuntimeContext } from "alchemy/RuntimeContext";
3 import * as Data from "effect/Data";
4 import * as Effect from "effect/Effect";
5 import * as FetchHttpClient from "effect/http/FetchHttpClient";
6 import * as HttpClient from "effect/http/HttpClient";
7 import type * as HttpClientError from "effect/http/HttpClientError";
8 import * as HttpClientRequest from "effect/http/HttpClientRequest";
9 import type * as HttpClientResponse from "effect/http/HttpClientResponse";
10 import * as Layer from "effect/Layer";
11 import * as Redacted from "effect/Redacted";
12 import type * as Scope from "effect/Scope";
13 import { backendEnvKey, backendString, bindBackendEnvironment } from "./BackendConnection.ts";
14 import type { DataApi } from "./DataApi.ts";
15
16 export class DataApiRequestError extends Data.TaggedError("DataApiRequestError")<{
17 message: string;
18 }> {}
19
20 export interface QueryDataApiClient {
21 /** Bound public PostgREST endpoint. */
22 baseUrl: Effect.Effect<string, never, RuntimeContext>;
23 /** Execute a relative PostgREST request with this caller's token, never an admin key. */
24 execute: (
25 request: HttpClientRequest.HttpClientRequest,
26 token: Redacted.Redacted<string>,
27 ) => Effect.Effect<
28 HttpClientResponse.HttpClientResponse,
29 HttpClientError.HttpClientError | DataApiRequestError,
30 RuntimeContext | Scope.Scope
31 >;
32 }
33
34 /**
35 * Query Neon Data API (PostgREST) over HTTP from a Function, Worker, or Lambda
36 * using an explicitly supplied caller token. Supports reads, writes and database
37 * function calls; this binding does not provision database grants or RLS policies.
38 *
39 * This is a low-level Effect HTTP client, not a SQL driver or a fluent query
40 * builder. Browser applications can use Neon's `@neondatabase/neon-js` or
41 * `@neondatabase/postgrest-js` SDK directly with the public Data API URL.
42 *
43 * Relative URLs cannot redirect the authorization header to another origin.
44 * Requests do not follow redirects, and response bodies remain request-scoped.
45 *
46 * ### Forward end-user authorization
47 * **Example:** Query rows under the caller's RLS identity
48 * ```typescript
49 * const data = yield* Neon.QueryDataApi(dataApi);
50 * // In the request handler, after obtaining the caller's token:
51 * const response = yield* data.execute(HttpClientRequest.get("todos?select=*"), token);
52 * ```
53 *
54 * @binding
55 * @product Data API
56 */
57 export interface QueryDataApi extends Binding.Service<
58 QueryDataApi,
59 "Neon.QueryDataApi",
60 (dataApi: DataApi) => Effect.Effect<QueryDataApiClient>
61 > {}
62 export const QueryDataApi = Binding.Service<QueryDataApi>("Neon.QueryDataApi");
63
64 /** Data API transport, with the host and HTTP client encapsulated at initialization. */
65 export const QueryDataApiHttp = Layer.effect(
66 QueryDataApi,
67 Effect.gen(function* () {
68 const http = yield* HttpClient.HttpClient;
69 return Effect.fn(function* (dataApi: DataApi) {
70 const key = backendEnvKey(dataApi.FQN, "DATA_API_URL");
71 yield* bindBackendEnvironment(`Neon.QueryDataApi:${dataApi.FQN}`, {
72 [key]: dataApi.url,
73 });
74 const baseUrl = backendString(key);
75 return {
76 baseUrl,
77 execute: Effect.fn(function* (
78 request: HttpClientRequest.HttpClientRequest,
79 token: Redacted.Redacted<string>,
80 ) {
81 if (!Redacted.value(token))
82 return yield* new DataApiRequestError({
83 message: "An end-user token is required",
84 });
85 const base = (yield* baseUrl).replace(/\/$/, "") + "/";
86 const target = yield* Effect.try({
87 try: () => new URL(request.url.replace(/^\/(?!\/)/, ""), base),
88 catch: () =>
89 new DataApiRequestError({
90 message: "Invalid relative Data API URL",
91 }),
92 });
93 const origin = yield* Effect.sync(() => new URL(base));
94 if (
95 target.origin !== origin.origin ||
96 !target.pathname.startsWith(origin.pathname) ||
97 target.username ||
98 target.password
99 ) {
100 return yield* new DataApiRequestError({
101 message: "Data API request must stay within its bound endpoint",
102 });
103 }
104 return yield* http
105 .execute(
106 request.pipe(
107 HttpClientRequest.setUrl(target.href),
108 HttpClientRequest.bearerToken(token),
109 ),
110 )
111 .pipe(
112 Effect.provideService(FetchHttpClient.RequestInit, {
113 redirect: "manual",
114 }),
115 );
116 }),
117 } satisfies QueryDataApiClient;
118 });
119 }),
120 );