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
| 1 | import * as Neon from "@distilled.cloud/neon"; |
| 2 | import { OwnedBySomeoneElse, unownedUnlessPrevious } from "alchemy/AdoptPolicy"; |
| 3 | import { isResolved } from "alchemy/Diff"; |
| 4 | import type { Input } from "alchemy/Input"; |
| 5 | import * as Provider from "alchemy/Provider"; |
| 6 | import { Resource } from "alchemy/Resource"; |
| 7 | import { isPlainData } from "alchemy/Util/data"; |
| 8 | import { arrayEquals } from "alchemy/Util/equal"; |
| 9 | import * as Data from "effect/Data"; |
| 10 | import * as Effect from "effect/Effect"; |
| 11 | import * as Equal from "effect/Equal"; |
| 12 | import type * as Redacted from "effect/Redacted"; |
| 13 | import { InvalidBranchScope, resolveBranchScope, type BranchScope } from "./BranchScope.ts"; |
| 14 | import type { Providers } from "./Providers.ts"; |
| 15 | |
| 16 | /** Unspecified settings are preserved. Removing previously managed settings requires an explicit reset value. */ |
| 17 | export type AuthProps = BranchScope & { |
| 18 | /** Database containing neon_auth. Omission preserves the existing database; changing its identity replaces the integration. */ |
| 19 | database?: string; |
| 20 | /** Application name shown in authentication emails. */ |
| 21 | name?: string; |
| 22 | /** Permit localhost origins; explicitly set false in production. */ |
| 23 | allowLocalhost?: boolean; |
| 24 | /** Supported managed email/password settings, using Neon's wire field names. */ |
| 25 | emailAndPassword?: Omit< |
| 26 | Neon.UpdateNeonAuthEmailAndPasswordConfigRequest, |
| 27 | "project_id" | "branch_id" |
| 28 | >; |
| 29 | /** Managed SMTP or shared email settings. Passwords must be redacted. */ |
| 30 | emailProvider?: |
| 31 | | Neon.SharedEmailServer |
| 32 | | (Omit<Neon.StandardEmailServer, "password"> & { |
| 33 | password?: Redacted.Redacted<string>; |
| 34 | }); |
| 35 | /** Managed magic-link settings. */ |
| 36 | magicLink?: Omit<Neon.UpdateNeonAuthMagicLinkPluginRequest, "project_id" | "branch_id">; |
| 37 | /** Managed organization plugin settings; does not configure Neon organizations. */ |
| 38 | organization?: Omit<Neon.UpdateNeonAuthOrganizationPluginRequest, "project_id" | "branch_id">; |
| 39 | /** Managed phone-number plugin settings. */ |
| 40 | phoneNumber?: Omit<Neon.UpdateNeonAuthPhoneNumberPluginRequest, "project_id" | "branch_id">; |
| 41 | /** Managed webhook settings. */ |
| 42 | webhook?: Omit<Neon.UpdateNeonAuthWebhookConfigRequest, "project_id" | "branch_id">; |
| 43 | }; |
| 44 | |
| 45 | export interface AuthAttributes { |
| 46 | /** Neon project identity. */ |
| 47 | projectId: string; |
| 48 | /** Branch identity; destruction never follows a parent branch. */ |
| 49 | branchId: string; |
| 50 | /** Database holding authentication state. */ |
| 51 | database: string; |
| 52 | /** Public managed Better Auth service URL. */ |
| 53 | baseUrl: string; |
| 54 | /** Public JWKS endpoint for signature verification. */ |
| 55 | jwksUrl: string; |
| 56 | /** Application name observed from Neon. */ |
| 57 | name: string | undefined; |
| 58 | } |
| 59 | |
| 60 | export interface Auth extends Resource<"Neon.Auth", AuthProps, AuthAttributes, never, Providers> {} |
| 61 | |
| 62 | /** |
| 63 | * Own the managed Better Auth integration on one branch. This is distinct from |
| 64 | * Alchemy's deployment authentication provider. Existing or inherited singleton |
| 65 | * integrations require explicit adoption. Users and sessions are runtime data. |
| 66 | * OAuth providers and trusted origins are owned only by their child resources. |
| 67 | * Disabling Auth preserves the neon_auth database schema. Neon refuses to enable |
| 68 | * it again while that schema exists; this provider never drops user identity data |
| 69 | * to recreate an externally disabled integration. |
| 70 | * |
| 71 | * ### Enable managed authentication |
| 72 | * **Example:** Email and password authentication |
| 73 | * ```typescript |
| 74 | * const auth = yield* Neon.Auth("Auth", { |
| 75 | * branch, |
| 76 | * allowLocalhost: false, |
| 77 | * emailAndPassword: { enabled: true, require_email_verification: true }, |
| 78 | * }); |
| 79 | * yield* Neon.AuthTrustedDomain("SiteOrigin", { auth, domain: site.url }); |
| 80 | * ``` |
| 81 | * |
| 82 | * @resource |
| 83 | * @product Auth |
| 84 | */ |
| 85 | export const Auth = Resource<Auth>("Neon.Auth"); |
| 86 | |
| 87 | export class InvalidManagedAuth extends Data.TaggedError("InvalidManagedAuth")<{ |
| 88 | message: string; |
| 89 | }> {} |
| 90 | |
| 91 | /** @internal */ |
| 92 | export const authRequest = (scope: { projectId: string; branchId: string }) => ({ |
| 93 | project_id: scope.projectId, |
| 94 | branch_id: scope.branchId, |
| 95 | }); |
| 96 | |
| 97 | /** Resolve identity independently of unrelated unresolved settings. @internal */ |
| 98 | export const authPlanScope = Effect.fn(function* (news: Input<BranchScope>) { |
| 99 | if ( |
| 100 | "branch" in news && |
| 101 | news.branch !== undefined && |
| 102 | "project" in news && |
| 103 | news.project !== undefined |
| 104 | ) { |
| 105 | return yield* new InvalidBranchScope({ |
| 106 | message: "Specify exactly one of branch or project", |
| 107 | }); |
| 108 | } |
| 109 | if ("branch" in news && news.branch !== undefined) { |
| 110 | const branch = news.branch; |
| 111 | if ( |
| 112 | "projectId" in branch && |
| 113 | "branchId" in branch && |
| 114 | isResolved(branch.projectId) && |
| 115 | isResolved(branch.branchId) |
| 116 | ) { |
| 117 | return yield* resolveBranchScope({ |
| 118 | branch: { projectId: branch.projectId, branchId: branch.branchId }, |
| 119 | }); |
| 120 | } |
| 121 | } else if ("project" in news && news.project !== undefined) { |
| 122 | const project = news.project; |
| 123 | if ("projectId" in project && isResolved(project.projectId)) { |
| 124 | return yield* resolveBranchScope({ |
| 125 | project: { projectId: project.projectId }, |
| 126 | }); |
| 127 | } |
| 128 | } |
| 129 | return undefined; |
| 130 | }); |
| 131 | |
| 132 | /** Find omitted managed fields without inspecting secret values. @internal */ |
| 133 | export const removedAuthSettings = ( |
| 134 | olds: object | undefined, |
| 135 | news: object, |
| 136 | fields: readonly string[], |
| 137 | ): string[] => { |
| 138 | if (!olds || !isPlainData(news)) return []; |
| 139 | return fields.flatMap((key) => { |
| 140 | const oldValue = Reflect.get(olds, key); |
| 141 | const newValue = Reflect.get(news, key); |
| 142 | if (oldValue === undefined) return []; |
| 143 | if (newValue === undefined) return [key]; |
| 144 | if ( |
| 145 | isPlainData(oldValue) && |
| 146 | isPlainData(newValue) && |
| 147 | !Array.isArray(oldValue) && |
| 148 | !Array.isArray(newValue) && |
| 149 | Reflect.get(oldValue, "type") === Reflect.get(newValue, "type") |
| 150 | ) { |
| 151 | return removedAuthSettings(oldValue, newValue, Object.keys(oldValue)).map( |
| 152 | (field) => `${key}.${field}`, |
| 153 | ); |
| 154 | } |
| 155 | return []; |
| 156 | }); |
| 157 | }; |
| 158 | |
| 159 | const managedAuthFields = [ |
| 160 | "name", |
| 161 | "allowLocalhost", |
| 162 | "emailAndPassword", |
| 163 | "emailProvider", |
| 164 | "magicLink", |
| 165 | "organization", |
| 166 | "phoneNumber", |
| 167 | "webhook", |
| 168 | ] as const; |
| 169 | |
| 170 | const validateAuthRemoval = (olds: AuthProps | undefined, news: Input<AuthProps>) => { |
| 171 | const removed = removedAuthSettings(olds, news, managedAuthFields); |
| 172 | return removed.length === 0 |
| 173 | ? Effect.void |
| 174 | : Effect.fail( |
| 175 | new InvalidManagedAuth({ |
| 176 | message: `Cannot remove managed Auth settings: ${removed.join(", ")}; set explicit reset values instead`, |
| 177 | }), |
| 178 | ); |
| 179 | }; |
| 180 | |
| 181 | /** Compare only explicitly managed fields, never serialize secrets. @internal */ |
| 182 | export const authSettingsMatch = (observed: object, desired: object) => |
| 183 | Object.entries(desired).every( |
| 184 | ([key, value]) => |
| 185 | value === undefined || |
| 186 | (Array.isArray(value) |
| 187 | ? arrayEquals(Reflect.get(observed, key), value) |
| 188 | : Equal.equals(Reflect.get(observed, key), value)), |
| 189 | ); |
| 190 | |
| 191 | const observeAuth = (scope: { projectId: string; branchId: string }) => |
| 192 | Neon.getNeonAuth(authRequest(scope)).pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 193 | |
| 194 | const attributes = Effect.fn(function* ( |
| 195 | scope: { projectId: string; branchId: string }, |
| 196 | observed: Neon.NeonAuthIntegration, |
| 197 | ) { |
| 198 | if (observed.auth_provider !== "better_auth" || !observed.base_url) { |
| 199 | return yield* new InvalidManagedAuth({ |
| 200 | message: "The branch must expose a managed Better Auth integration and base URL", |
| 201 | }); |
| 202 | } |
| 203 | return { |
| 204 | ...scope, |
| 205 | database: observed.db_name, |
| 206 | baseUrl: observed.base_url, |
| 207 | jwksUrl: observed.jwks_url, |
| 208 | name: observed.name, |
| 209 | } satisfies AuthAttributes; |
| 210 | }); |
| 211 | |
| 212 | export const AuthProvider = () => |
| 213 | Provider.succeed(Auth, { |
| 214 | stables: ["projectId", "branchId", "database"], |
| 215 | diff: Effect.fn(function* ({ olds, news, output }) { |
| 216 | yield* validateAuthRemoval(olds, news); |
| 217 | const scope = yield* authPlanScope(news); |
| 218 | if ( |
| 219 | output && |
| 220 | (!scope || scope.projectId !== output.projectId || scope.branchId !== output.branchId) |
| 221 | ) { |
| 222 | return { action: "replace", deleteFirst: true } as const; |
| 223 | } |
| 224 | if (!isResolved(news)) return; |
| 225 | const resolved = scope ?? (yield* resolveBranchScope(news)); |
| 226 | const previous = output ?? (yield* resolveBranchScope(olds)); |
| 227 | if ( |
| 228 | resolved.projectId !== previous.projectId || |
| 229 | resolved.branchId !== previous.branchId || |
| 230 | (news.database ?? output?.database ?? olds.database) !== (output?.database ?? olds.database) |
| 231 | ) { |
| 232 | return { action: "replace", deleteFirst: true } as const; |
| 233 | } |
| 234 | if (!output) return; |
| 235 | const request = authRequest(resolved); |
| 236 | const observed = yield* observeAuth(resolved); |
| 237 | if (!observed) return { action: "update" } as const; |
| 238 | if (news.name !== undefined && news.name !== observed.name) |
| 239 | return { action: "update" } as const; |
| 240 | if ( |
| 241 | news.allowLocalhost !== undefined && |
| 242 | (yield* Neon.getNeonAuthAllowLocalhost(request)).allow_localhost !== news.allowLocalhost |
| 243 | ) |
| 244 | return { action: "update" } as const; |
| 245 | if ( |
| 246 | news.emailAndPassword !== undefined && |
| 247 | !authSettingsMatch( |
| 248 | yield* Neon.getNeonAuthEmailAndPasswordConfig(request), |
| 249 | news.emailAndPassword, |
| 250 | ) |
| 251 | ) |
| 252 | return { action: "update" } as const; |
| 253 | if ( |
| 254 | news.emailProvider !== undefined && |
| 255 | !authSettingsMatch(yield* Neon.getNeonAuthEmailProvider(request), news.emailProvider) |
| 256 | ) |
| 257 | return { action: "update" } as const; |
| 258 | if ( |
| 259 | news.magicLink !== undefined || |
| 260 | news.organization !== undefined || |
| 261 | news.phoneNumber !== undefined |
| 262 | ) { |
| 263 | const current = yield* Neon.getNeonAuthPluginConfigs(request); |
| 264 | if ( |
| 265 | (news.magicLink !== undefined && |
| 266 | !authSettingsMatch(current.magic_link ?? {}, news.magicLink)) || |
| 267 | (news.organization !== undefined && |
| 268 | !authSettingsMatch(current.organization ?? {}, news.organization)) || |
| 269 | (news.phoneNumber !== undefined && |
| 270 | !authSettingsMatch(current.phone_number ?? {}, news.phoneNumber)) |
| 271 | ) |
| 272 | return { action: "update" } as const; |
| 273 | } |
| 274 | if ( |
| 275 | news.webhook !== undefined && |
| 276 | !authSettingsMatch(yield* Neon.getNeonAuthWebhookConfig(request), news.webhook) |
| 277 | ) |
| 278 | return { action: "update" } as const; |
| 279 | }), |
| 280 | read: Effect.fn(function* ({ olds, output, previous }) { |
| 281 | if ( |
| 282 | !output && |
| 283 | !(olds?.branch?.projectId && olds.branch.branchId) && |
| 284 | !olds?.project?.projectId |
| 285 | ) |
| 286 | return undefined; |
| 287 | const scope = output ?? (yield* resolveBranchScope(olds)); |
| 288 | const observed = yield* observeAuth(scope); |
| 289 | if (!observed) return undefined; |
| 290 | const attrs = yield* attributes(scope, observed); |
| 291 | return output ? attrs : unownedUnlessPrevious(attrs, previous, "database"); |
| 292 | }), |
| 293 | reconcile: Effect.fn(function* ({ news, output, olds }) { |
| 294 | yield* validateAuthRemoval(olds, news); |
| 295 | const scope = yield* resolveBranchScope(news); |
| 296 | const database = news.database ?? output?.database; |
| 297 | if ( |
| 298 | output && |
| 299 | (scope.projectId !== output.projectId || |
| 300 | scope.branchId !== output.branchId || |
| 301 | database !== output.database) |
| 302 | ) { |
| 303 | return yield* new InvalidManagedAuth({ |
| 304 | message: |
| 305 | "Auth identity changed without replacement; refusing to mutate either integration", |
| 306 | }); |
| 307 | } |
| 308 | const request = authRequest(scope); |
| 309 | let observed = yield* observeAuth(scope); |
| 310 | if (observed && !output) { |
| 311 | return yield* new OwnedBySomeoneElse({ |
| 312 | message: "Existing Auth requires explicit adoption", |
| 313 | resourceType: "Neon.Auth", |
| 314 | }); |
| 315 | } |
| 316 | if (!observed) { |
| 317 | yield* Neon.createNeonAuth({ |
| 318 | ...request, |
| 319 | auth_provider: "better_auth", |
| 320 | database_name: database, |
| 321 | }).pipe( |
| 322 | Effect.catchTag( |
| 323 | "Conflict", |
| 324 | Effect.fn(function* (error) { |
| 325 | const raced = yield* observeAuth(scope); |
| 326 | if (!raced) return yield* error; |
| 327 | if (!output) { |
| 328 | return yield* new OwnedBySomeoneElse({ |
| 329 | message: |
| 330 | "Auth integration appeared during creation; explicit adoption is required", |
| 331 | resourceType: "Neon.Auth", |
| 332 | }); |
| 333 | } |
| 334 | }), |
| 335 | ), |
| 336 | ); |
| 337 | observed = yield* Neon.getNeonAuth(request); |
| 338 | } |
| 339 | yield* attributes(scope, observed); |
| 340 | if (news.database !== undefined && observed.db_name !== news.database) { |
| 341 | return yield* new InvalidManagedAuth({ |
| 342 | message: "Existing Auth uses a different database; replace the integration explicitly", |
| 343 | }); |
| 344 | } |
| 345 | if (news.name !== undefined && news.name !== observed.name) { |
| 346 | yield* Neon.updateNeonAuthConfig({ ...request, name: news.name }); |
| 347 | } |
| 348 | if (news.allowLocalhost !== undefined) { |
| 349 | const current = yield* Neon.getNeonAuthAllowLocalhost(request); |
| 350 | if (current.allow_localhost !== news.allowLocalhost) { |
| 351 | yield* Neon.updateNeonAuthAllowLocalhost({ |
| 352 | ...request, |
| 353 | allow_localhost: news.allowLocalhost, |
| 354 | }); |
| 355 | } |
| 356 | } |
| 357 | if (news.emailAndPassword !== undefined) { |
| 358 | const current = yield* Neon.getNeonAuthEmailAndPasswordConfig(request); |
| 359 | if (!authSettingsMatch(current, news.emailAndPassword)) { |
| 360 | yield* Neon.updateNeonAuthEmailAndPasswordConfig({ |
| 361 | ...request, |
| 362 | ...news.emailAndPassword, |
| 363 | }); |
| 364 | } |
| 365 | } |
| 366 | if (news.emailProvider !== undefined) { |
| 367 | const current = yield* Neon.getNeonAuthEmailProvider(request); |
| 368 | // SMTP passwords may be masked on read, so reassert an explicitly managed secret. |
| 369 | if ( |
| 370 | (news.emailProvider.type === "standard" && news.emailProvider.password !== undefined) || |
| 371 | !authSettingsMatch(current, news.emailProvider) |
| 372 | ) { |
| 373 | yield* Neon.updateNeonAuthEmailProvider({ |
| 374 | ...request, |
| 375 | body: news.emailProvider, |
| 376 | }); |
| 377 | } |
| 378 | } |
| 379 | if ( |
| 380 | news.magicLink !== undefined || |
| 381 | news.organization !== undefined || |
| 382 | news.phoneNumber !== undefined |
| 383 | ) { |
| 384 | const current = yield* Neon.getNeonAuthPluginConfigs(request); |
| 385 | if ( |
| 386 | news.magicLink !== undefined && |
| 387 | !authSettingsMatch(current.magic_link ?? {}, news.magicLink) |
| 388 | ) { |
| 389 | yield* Neon.updateNeonAuthMagicLinkPlugin({ |
| 390 | ...request, |
| 391 | ...news.magicLink, |
| 392 | }); |
| 393 | } |
| 394 | if ( |
| 395 | news.organization !== undefined && |
| 396 | !authSettingsMatch(current.organization ?? {}, news.organization) |
| 397 | ) { |
| 398 | yield* Neon.updateNeonAuthOrganizationPlugin({ |
| 399 | ...request, |
| 400 | ...news.organization, |
| 401 | }); |
| 402 | } |
| 403 | if ( |
| 404 | news.phoneNumber !== undefined && |
| 405 | !authSettingsMatch(current.phone_number ?? {}, news.phoneNumber) |
| 406 | ) { |
| 407 | yield* Neon.updateNeonAuthPhoneNumberPlugin({ |
| 408 | ...request, |
| 409 | ...news.phoneNumber, |
| 410 | }); |
| 411 | } |
| 412 | } |
| 413 | if (news.webhook !== undefined) { |
| 414 | const current = yield* Neon.getNeonAuthWebhookConfig(request); |
| 415 | if (!authSettingsMatch(current, news.webhook)) { |
| 416 | yield* Neon.updateNeonAuthWebhookConfig({ |
| 417 | ...request, |
| 418 | ...news.webhook, |
| 419 | }); |
| 420 | } |
| 421 | } |
| 422 | return yield* attributes(scope, yield* Neon.getNeonAuth(request)); |
| 423 | }), |
| 424 | delete: Effect.fn(function* ({ output }) { |
| 425 | if (yield* observeAuth(output)) { |
| 426 | yield* Neon.disableNeonAuth(authRequest(output)).pipe( |
| 427 | Effect.catchTag("NotFound", () => Effect.void), |
| 428 | ); |
| 429 | } |
| 430 | }), |
| 431 | }); |