@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, 06:00 UTC

main
ts 207 lines 6.96 KB
Raw
1 import * as turso from "@distilled.cloud/turso/turso";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { deepEqual, isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Redacted from "effect/Redacted";
10 import { organization } from "./Credentials.ts";
11 import type { Providers } from "./Providers.ts";
12
13 export class ApiTokenUnexpectedResponse extends Data.TaggedError("ApiTokenUnexpectedResponse")<{
14 readonly message: string;
15 readonly cause?: unknown;
16 }> {}
17
18 /**
19 * A permission granted to a group-scoped API token. `read-only` and
20 * `full-access` are presets that expand to individual scopes.
21 */
22 export type ApiTokenScope =
23 | "read"
24 | "db:create"
25 | "db:delete"
26 | "db:configure"
27 | "db:mint-token"
28 | "db:rotate-creds"
29 | "group:configure"
30 | "group:mint-token"
31 | "group:rotate-creds"
32 | "read-only"
33 | "full-access";
34
35 export interface ApiTokenProps {
36 /**
37 * Token name, unique within your account. If omitted, a unique name is
38 * generated from the stack, stage, and logical ID.
39 */
40 name?: string;
41 /**
42 * Restrict the token to one group of the organization (e.g.
43 * `group.name`). Requires `scopes`. Omit for an organization-scoped token.
44 */
45 group?: string;
46 /**
47 * Permissions of a group-scoped token. Required (and non-empty) when
48 * `group` is set. `db:mint-token` issues new SQL tokens;
49 * `db:rotate-creds` invalidates every SQL token of a database.
50 */
51 scopes?: ApiTokenScope[];
52 }
53
54 export interface ApiTokenAttributes {
55 /** Token ID. */
56 id: string;
57 /** Token name. */
58 name: string;
59 /** The organization slug the token is restricted to. */
60 organization: string;
61 /** The group the token is restricted to, if group-scoped. */
62 group: string | undefined;
63 /** The expanded scopes of a group-scoped token. */
64 scopes: string[];
65 /** The Platform API token, sent as `Authorization: Bearer <token>`. */
66 token: Redacted.Redacted<string>;
67 }
68
69 export type ApiToken = Resource<
70 "Turso.ApiToken",
71 ApiTokenProps,
72 ApiTokenAttributes,
73 never,
74 Providers
75 >;
76
77 /**
78 * A Turso API token. It lets an app create and delete groups and databases.
79 * To run SQL, use a {@link DatabaseToken} instead. Limit it to one group
80 * with `group` and `scopes` to give an app only the access it needs.
81 *
82 * Turso only shows the token once, when it's created, so Alchemy stores it
83 * in state as a `Redacted` value. Changing a prop creates a new token, and
84 * destroying it cancels the token.
85 * @see https://docs.turso.tech/api-reference/tokens/create
86 *
87 * ### Creating a Token
88 * **Example:** Token for the whole organization
89 * ```typescript
90 * const token = yield* Turso.ApiToken("Ci", {});
91 * ```
92 *
93 * **Example:** Token that can only create databases in one group
94 * ```typescript
95 * const token = yield* Turso.ApiToken("Tenants", {
96 * group: group.name,
97 * scopes: ["read", "db:create", "db:delete", "db:mint-token"],
98 * });
99 * ```
100 *
101 * @resource
102 * @product API Token
103 */
104 export const ApiToken = Resource<ApiToken>("Turso.ApiToken");
105
106 const tokenName = (id: string, name: string | undefined) =>
107 name ? Effect.succeed(name) : createPhysicalName({ id, maxLength: 64, delimiter: "-" });
108
109 export const ApiTokenProvider = () =>
110 Provider.effect(
111 ApiToken,
112 Effect.gen(function* () {
113 const observe = (name: string) =>
114 turso
115 .listAPITokens({})
116 .pipe(Effect.map(({ tokens }) => (tokens ?? []).find((t) => t.name === name)));
117
118 const revoke = (name: string) =>
119 turso.revokeAPIToken({ tokenName: name }).pipe(
120 Effect.asVoid,
121 Effect.catchTag("NotFound", () => Effect.void),
122 );
123
124 return {
125 stables: ["id", "name", "organization", "group", "scopes", "token"],
126 diff: Effect.fn(function* ({ id, olds, news, output }) {
127 if (!isResolved(news)) return undefined;
128 const name = output?.name ?? (yield* tokenName(id, olds?.name));
129 // Turso tokens are immutable: any change mints a new one.
130 if (
131 (news.name !== undefined && news.name !== name) ||
132 news.group !== olds?.group ||
133 !deepEqual(news.scopes ?? [], olds?.scopes ?? [])
134 ) {
135 // A pinned name can't be held by two tokens at once.
136 return {
137 action: "replace",
138 deleteFirst: news.name !== undefined && news.name === name,
139 } as const;
140 }
141 }),
142 read: Effect.fn(function* ({ id, olds, output, previous }) {
143 const name = output?.name ?? (yield* tokenName(id, olds?.name));
144 const observed = yield* observe(name);
145 if (!observed) return undefined;
146 if (output !== undefined && output.id === observed.id) return output;
147 // The generation a delete-first replacement is about to revoke.
148 if (previous !== undefined && previous.id === observed.id) return previous;
149 // The secret is only revealed at creation, so a token we have no
150 // state for can't be adopted with its value — reconcile re-mints.
151 return Unowned({
152 id: observed.id ?? "",
153 name,
154 organization: observed.organization ?? "",
155 group: observed.group,
156 scopes: observed.scopes ?? [],
157 token: Redacted.make(""),
158 });
159 }),
160 reconcile: Effect.fn(function* ({ id, news, output, session }) {
161 const org = output?.organization ?? (yield* organization);
162 const name = output?.name ?? (yield* tokenName(id, news.name));
163
164 // Observe
165 const observed = yield* observe(name);
166 if (
167 observed &&
168 output &&
169 Redacted.value(output.token) !== "" &&
170 output.id === observed.id
171 ) {
172 return output;
173 }
174
175 // Ensure — a token we hold no secret for (a lost create, or an
176 // adoption) is revoked and re-minted.
177 if (observed) {
178 yield* session.note(`Re-minting API token ${name}...`);
179 yield* revoke(name);
180 }
181 const created = yield* turso.createAPIToken({
182 tokenName: name,
183 organization: org,
184 group: news.group,
185 scopes: news.scopes,
186 });
187 if (!created.token || !created.id) {
188 return yield* new ApiTokenUnexpectedResponse({
189 message: `Turso returned no token for ${name}`,
190 });
191 }
192 const minted = yield* observe(name);
193 return {
194 id: created.id,
195 name,
196 organization: minted?.organization ?? org,
197 group: minted?.group ?? news.group,
198 scopes: minted?.scopes ?? [],
199 token: created.token,
200 };
201 }),
202 delete: Effect.fn(function* ({ output }) {
203 yield* revoke(output.name);
204 }),
205 };
206 }),
207 );