The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as turso from "@distilled.cloud/turso/turso"; |
| 2 | import { deepEqual } from "alchemy/Diff"; |
| 3 | import * as Provider from "alchemy/Provider"; |
| 4 | import { Resource } from "alchemy/Resource"; |
| 5 | import * as Clock from "effect/Clock"; |
| 6 | import * as Data from "effect/Data"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Redacted from "effect/Redacted"; |
| 9 | import { organization } from "./Credentials.ts"; |
| 10 | import type { Providers } from "./Providers.ts"; |
| 11 | |
| 12 | export class DatabaseTokenUnexpectedResponse extends Data.TaggedError( |
| 13 | "DatabaseTokenUnexpectedResponse", |
| 14 | )<{ |
| 15 | readonly message: string; |
| 16 | readonly cause?: unknown; |
| 17 | }> {} |
| 18 | |
| 19 | /** Access level of a Turso SQL auth token. */ |
| 20 | export type TokenAuthorization = "full-access" | "read-only"; |
| 21 | |
| 22 | /** Props shared by {@link DatabaseToken} and {@link GroupToken}. */ |
| 23 | export interface SqlTokenProps { |
| 24 | /** |
| 25 | * Access level granted by the token. |
| 26 | * @default "full-access" |
| 27 | */ |
| 28 | authorization?: TokenAuthorization; |
| 29 | /** |
| 30 | * Token lifetime, e.g. `"2w"`, `"7d"`, `"1h30m"`. Omit for a token that |
| 31 | * never expires. An expired token is re-minted on the next deploy. |
| 32 | */ |
| 33 | expiration?: string; |
| 34 | /** |
| 35 | * Databases this token may `ATTACH` for reading (requires `allowAttach` |
| 36 | * on those databases). Not supported on AWS-hosted databases. |
| 37 | */ |
| 38 | readAttach?: string[]; |
| 39 | } |
| 40 | |
| 41 | /** Attributes shared by {@link DatabaseToken} and {@link GroupToken}. */ |
| 42 | export interface SqlTokenAttributes { |
| 43 | /** The token (a JWT), sent as `Authorization: Bearer <token>`. */ |
| 44 | token: Redacted.Redacted<string>; |
| 45 | /** The organization slug the token belongs to. */ |
| 46 | organization: string; |
| 47 | /** Access level granted by the token. */ |
| 48 | authorization: TokenAuthorization; |
| 49 | /** Expiry as epoch milliseconds, or `undefined` for a non-expiring token. */ |
| 50 | expiresAt: number | undefined; |
| 51 | } |
| 52 | |
| 53 | export interface DatabaseTokenProps extends SqlTokenProps { |
| 54 | /** Name of the database the token grants access to (e.g. `db.name`). */ |
| 55 | database: string; |
| 56 | } |
| 57 | |
| 58 | export interface DatabaseTokenAttributes extends SqlTokenAttributes { |
| 59 | /** Name of the database the token grants access to. */ |
| 60 | database: string; |
| 61 | /** UUID of the database the token was minted for. */ |
| 62 | dbId: string; |
| 63 | } |
| 64 | |
| 65 | export type DatabaseToken = Resource< |
| 66 | "Turso.DatabaseToken", |
| 67 | DatabaseTokenProps, |
| 68 | DatabaseTokenAttributes, |
| 69 | never, |
| 70 | Providers |
| 71 | >; |
| 72 | |
| 73 | /** |
| 74 | * A token that lets an app run SQL on one Turso database. Workers and |
| 75 | * Lambdas should use {@link Connect}, which creates one for you. Use |
| 76 | * `DatabaseToken` for anything else, such as a container or a CI job. |
| 77 | * |
| 78 | * You can't cancel a single token. Changing a prop creates a new token, but |
| 79 | * the old one keeps working until it expires. Destroying the resource doesn't |
| 80 | * stop it either. Give tokens you share an `expiration`, or cancel every token |
| 81 | * for the database with `turso db tokens invalidate`. |
| 82 | * @see https://docs.turso.tech/api-reference/databases/create-token |
| 83 | * |
| 84 | * ### Creating a Token |
| 85 | * **Example:** Full-access token |
| 86 | * ```typescript |
| 87 | * const token = yield* Turso.DatabaseToken("Token", { |
| 88 | * database: db.name, |
| 89 | * }); |
| 90 | * ``` |
| 91 | * |
| 92 | * **Example:** Read-only token that expires after two weeks |
| 93 | * ```typescript |
| 94 | * const token = yield* Turso.DatabaseToken("ReadOnly", { |
| 95 | * database: db.name, |
| 96 | * authorization: "read-only", |
| 97 | * expiration: "2w", |
| 98 | * }); |
| 99 | * ``` |
| 100 | * |
| 101 | * @resource |
| 102 | * @product Database |
| 103 | */ |
| 104 | export const DatabaseToken = Resource<DatabaseToken>("Turso.DatabaseToken"); |
| 105 | |
| 106 | /** Decode a Turso JWT's `exp` claim (seconds) to epoch milliseconds. */ |
| 107 | export const tokenExpiry = (token: Redacted.Redacted<string>): number | undefined => { |
| 108 | const payload = Redacted.value(token).split(".")[1]; |
| 109 | if (!payload) return undefined; |
| 110 | try { |
| 111 | const claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as { |
| 112 | exp?: number; |
| 113 | }; |
| 114 | return typeof claims.exp === "number" ? claims.exp * 1000 : undefined; |
| 115 | } catch { |
| 116 | return undefined; |
| 117 | } |
| 118 | }; |
| 119 | |
| 120 | /** Re-mint a token that expires within the hour. */ |
| 121 | const RENEW_WITHIN_MS = 60 * 60 * 1000; |
| 122 | |
| 123 | /** |
| 124 | * `diff` for SQL tokens: an unchanged token that is about to expire still |
| 125 | * needs an update, so the deploy re-mints it. |
| 126 | */ |
| 127 | export const diffSqlToken = Effect.fn(function* ({ |
| 128 | output, |
| 129 | }: { |
| 130 | output: SqlTokenAttributes | undefined; |
| 131 | }) { |
| 132 | if (output?.expiresAt === undefined) return undefined; |
| 133 | const now = yield* Clock.currentTimeMillis; |
| 134 | return output.expiresAt - now <= RENEW_WITHIN_MS ? ({ action: "update" } as const) : undefined; |
| 135 | }); |
| 136 | |
| 137 | /** Whether a previously minted token can be kept as-is. */ |
| 138 | export const isTokenCurrent = Effect.fn(function* ( |
| 139 | output: SqlTokenAttributes | undefined, |
| 140 | olds: SqlTokenProps | undefined, |
| 141 | news: SqlTokenProps, |
| 142 | ) { |
| 143 | if (output === undefined || olds === undefined) return false; |
| 144 | if ( |
| 145 | (news.authorization ?? "full-access") !== (olds.authorization ?? "full-access") || |
| 146 | news.expiration !== olds.expiration || |
| 147 | !deepEqual(news.readAttach ?? [], olds.readAttach ?? []) |
| 148 | ) { |
| 149 | return false; |
| 150 | } |
| 151 | if (output.expiresAt === undefined) return true; |
| 152 | // Re-mint a token that expires within the hour, so a deploy never hands |
| 153 | // consumers a token about to lapse. |
| 154 | const now = yield* Clock.currentTimeMillis; |
| 155 | return output.expiresAt - now > RENEW_WITHIN_MS; |
| 156 | }); |
| 157 | |
| 158 | export const DatabaseTokenProvider = () => |
| 159 | Provider.effect( |
| 160 | DatabaseToken, |
| 161 | Effect.gen(function* () { |
| 162 | return { |
| 163 | stables: ["organization"], |
| 164 | diff: diffSqlToken, |
| 165 | reconcile: Effect.fn(function* ({ news, olds, output }) { |
| 166 | const org = output?.organization ?? (yield* organization); |
| 167 | |
| 168 | // Observe — the token is bound to the database's UUID, so a |
| 169 | // database replaced under the same name invalidates it. |
| 170 | const { database } = yield* turso.getDatabase({ |
| 171 | organizationSlug: org, |
| 172 | databaseName: news.database, |
| 173 | }); |
| 174 | const dbId = database?.DbId ?? ""; |
| 175 | if ( |
| 176 | output !== undefined && |
| 177 | output.database === news.database && |
| 178 | output.dbId === dbId && |
| 179 | (yield* isTokenCurrent(output, olds, news)) |
| 180 | ) { |
| 181 | return output; |
| 182 | } |
| 183 | |
| 184 | // Ensure — mint. |
| 185 | const authorization = news.authorization ?? "full-access"; |
| 186 | const { jwt } = yield* turso.createDatabaseToken({ |
| 187 | organizationSlug: org, |
| 188 | databaseName: news.database, |
| 189 | authorization, |
| 190 | expiration: news.expiration, |
| 191 | permissions: news.readAttach |
| 192 | ? { read_attach: { databases: news.readAttach } } |
| 193 | : undefined, |
| 194 | }); |
| 195 | if (!jwt) { |
| 196 | return yield* new DatabaseTokenUnexpectedResponse({ |
| 197 | message: `Turso returned no token for ${news.database}`, |
| 198 | }); |
| 199 | } |
| 200 | return { |
| 201 | token: jwt, |
| 202 | organization: org, |
| 203 | authorization, |
| 204 | expiresAt: tokenExpiry(jwt), |
| 205 | database: news.database, |
| 206 | dbId, |
| 207 | }; |
| 208 | }), |
| 209 | // Turso cannot revoke a single token; it simply stops being tracked. |
| 210 | delete: () => Effect.void, |
| 211 | }; |
| 212 | }), |
| 213 | ); |