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 { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import { isResolved } from "alchemy/Diff"; |
| 4 | import * as Provider from "alchemy/Provider"; |
| 5 | import { Resource } from "alchemy/Resource"; |
| 6 | import * as Data from "effect/Data"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import type { Providers } from "./Providers.ts"; |
| 9 | |
| 10 | /** Organization roles supported by Neon; availability depends on the organization. */ |
| 11 | export type OrganizationRole = "admin" | "member" | "editor" | "viewer" | "collaborator"; |
| 12 | |
| 13 | export interface OrganizationMemberRoleProps { |
| 14 | /** Existing Neon organization ID. Restore and remove this control before changing its identity. */ |
| 15 | orgId: string; |
| 16 | /** Existing membership ID, not a user ID or email. Remove this control before changing the member. */ |
| 17 | memberId: string; |
| 18 | /** Desired organization role. The legacy member role is equivalent to editor. No membership is created or invited. */ |
| 19 | role: OrganizationRole; |
| 20 | } |
| 21 | |
| 22 | /** Durable ownership and restore evidence, persisted by the engine before reconciliation. */ |
| 23 | export interface GovernanceRoleBaseline<Role> { |
| 24 | /** Resource generation that captured the original role. */ |
| 25 | instanceId: string; |
| 26 | /** Fully qualified logical resource identity. */ |
| 27 | fqn: string; |
| 28 | /** User identity captured with the existing membership. */ |
| 29 | userId: string; |
| 30 | /** Exact role before this resource first managed it. */ |
| 31 | originalRole: Role; |
| 32 | /** Last successfully persisted managed role, never inferred from input properties. */ |
| 33 | managedRole: Role; |
| 34 | } |
| 35 | |
| 36 | export interface OrganizationMemberRoleAttributes { |
| 37 | /** Organization containing the membership. */ |
| 38 | orgId: string; |
| 39 | /** Existing membership controlled by this resource. */ |
| 40 | memberId: string; |
| 41 | /** Observed organization role. */ |
| 42 | role: OrganizationRole; |
| 43 | /** Original role and ownership evidence required for safe restoration. */ |
| 44 | baseline: GovernanceRoleBaseline<OrganizationRole>; |
| 45 | } |
| 46 | |
| 47 | export interface OrganizationMemberRole extends Resource< |
| 48 | "Neon.OrganizationMemberRole", |
| 49 | OrganizationMemberRoleProps, |
| 50 | OrganizationMemberRoleAttributes, |
| 51 | never, |
| 52 | Providers |
| 53 | > {} |
| 54 | |
| 55 | /** |
| 56 | * Manage the role of an existing organization member, never their membership. |
| 57 | * Existing roles require explicit adoption. Destruction restores the captured |
| 58 | * original role, but refuses to overwrite a role changed outside this resource. |
| 59 | * A complete bounded organization-member listing can prove that a removed |
| 60 | * membership needs no restoration; listing failures never count as absence. |
| 61 | * Self changes are refused, including restoration, to avoid self-demotion. |
| 62 | * Neon enforces organization-admin authorization and organization role availability. |
| 63 | * |
| 64 | * The engine persists the adoption snapshot before reconciliation. Supply resolved |
| 65 | * IDs and role values on first deployment; an unresolved first deployment fails |
| 66 | * before mutation because this engine has no provider checkpoint API. Keep the |
| 67 | * state: a lost baseline cannot be reconstructed from desired props. An ambiguous |
| 68 | * interrupted write fails closed and requires operator reconciliation of state. |
| 69 | * Role mutations have no compare-and-swap API; do not edit the same role concurrently. |
| 70 | * |
| 71 | * ### Manage an existing member |
| 72 | * **Example:** Explicitly adopt a consenting member's role |
| 73 | * ```typescript |
| 74 | * const role = yield* Neon.OrganizationMemberRole("DeveloperRole", { |
| 75 | * orgId: "org-example", |
| 76 | * memberId: authorizedMemberId, |
| 77 | * role: "editor", |
| 78 | * }).pipe(Alchemy.adopt(true)); |
| 79 | * ``` |
| 80 | * |
| 81 | * @resource |
| 82 | * @product Organization |
| 83 | */ |
| 84 | export const OrganizationMemberRole = Resource<OrganizationMemberRole>( |
| 85 | "Neon.OrganizationMemberRole", |
| 86 | ); |
| 87 | |
| 88 | export class GovernanceRoleSafetyError extends Data.TaggedError("NeonGovernanceRoleSafetyError")<{ |
| 89 | message: string; |
| 90 | }> {} |
| 91 | |
| 92 | /** Validate scope without performing cloud I/O. @internal */ |
| 93 | export const validateGovernanceScope = (scope: { orgId: string; memberId: string } | undefined) => |
| 94 | typeof scope?.orgId === "string" && |
| 95 | scope.orgId.trim().length > 0 && |
| 96 | typeof scope.memberId === "string" && |
| 97 | scope.memberId.trim().length > 0 |
| 98 | ? Effect.void |
| 99 | : Effect.fail( |
| 100 | new GovernanceRoleSafetyError({ |
| 101 | message: "An explicit organization ID and existing membership ID are required", |
| 102 | }), |
| 103 | ); |
| 104 | |
| 105 | /** Runtime validation also guards persisted state and unrecognized SDK enum values. @internal */ |
| 106 | export const validateOrganizationRole = (role: OrganizationRole) => |
| 107 | role === "admin" || |
| 108 | role === "member" || |
| 109 | role === "editor" || |
| 110 | role === "viewer" || |
| 111 | role === "collaborator" |
| 112 | ? Effect.void |
| 113 | : Effect.fail( |
| 114 | new GovernanceRoleSafetyError({ |
| 115 | message: "Unsupported organization role", |
| 116 | }), |
| 117 | ); |
| 118 | |
| 119 | /** Check persisted ownership independently of desired properties. @internal */ |
| 120 | export const requireGovernanceBaseline = <Role>( |
| 121 | baseline: GovernanceRoleBaseline<Role> | undefined, |
| 122 | owner: { fqn: string; instanceId: string }, |
| 123 | ) => |
| 124 | baseline && |
| 125 | baseline.fqn === owner.fqn && |
| 126 | baseline.instanceId === owner.instanceId && |
| 127 | baseline.userId |
| 128 | ? Effect.succeed(baseline) |
| 129 | : Effect.fail( |
| 130 | new GovernanceRoleSafetyError({ |
| 131 | message: |
| 132 | "Missing or foreign durable role baseline; use a resolved initial declaration and explicit adoption, never reconstruct a lost baseline from props", |
| 133 | }), |
| 134 | ); |
| 135 | |
| 136 | /** Observe-before-write guard; a completed restoration is idempotent. @internal */ |
| 137 | export const governanceRoleTransition = <Role>( |
| 138 | baseline: GovernanceRoleBaseline<Role>, |
| 139 | observed: Role, |
| 140 | desired: Role, |
| 141 | restoring = false, |
| 142 | ) => { |
| 143 | if (restoring && observed === baseline.originalRole) return Effect.succeed(false); |
| 144 | if (observed !== baseline.managedRole) { |
| 145 | return Effect.fail( |
| 146 | new GovernanceRoleSafetyError({ |
| 147 | message: |
| 148 | "Observed role differs from the last persisted managed role; refusing an out-of-band edit or ambiguous interrupted write", |
| 149 | }), |
| 150 | ); |
| 151 | } |
| 152 | return Effect.succeed(observed !== desired); |
| 153 | }; |
| 154 | |
| 155 | const normalizeOrganizationRole = (role: OrganizationRole) => (role === "member" ? "editor" : role); |
| 156 | |
| 157 | /** Neon treats member as a legacy spelling of editor. @internal */ |
| 158 | export const sameOrganizationRole = (a: OrganizationRole, b: OrganizationRole) => |
| 159 | normalizeOrganizationRole(a) === normalizeOrganizationRole(b); |
| 160 | |
| 161 | /** Preserve original spellings while comparing equivalent organization roles. @internal */ |
| 162 | export const organizationRoleTransition = ( |
| 163 | baseline: GovernanceRoleBaseline<OrganizationRole>, |
| 164 | observed: OrganizationRole, |
| 165 | desired: OrganizationRole, |
| 166 | restoring = false, |
| 167 | ) => |
| 168 | governanceRoleTransition( |
| 169 | { |
| 170 | ...baseline, |
| 171 | originalRole: normalizeOrganizationRole(baseline.originalRole), |
| 172 | managedRole: normalizeOrganizationRole(baseline.managedRole), |
| 173 | }, |
| 174 | normalizeOrganizationRole(observed), |
| 175 | normalizeOrganizationRole(desired), |
| 176 | restoring, |
| 177 | ); |
| 178 | |
| 179 | /** Never mutate the authenticated actor, including during restoration. @internal */ |
| 180 | export const validateGovernanceActor = (userId: string, actorId: string) => |
| 181 | userId && actorId && userId !== actorId |
| 182 | ? Effect.void |
| 183 | : Effect.fail( |
| 184 | new GovernanceRoleSafetyError({ |
| 185 | message: |
| 186 | "Cannot manage the current actor's role or a membership without a verified user identity", |
| 187 | }), |
| 188 | ); |
| 189 | |
| 190 | const request = (scope: { orgId: string; memberId: string }) => ({ |
| 191 | org_id: scope.orgId, |
| 192 | member_id: scope.memberId, |
| 193 | }); |
| 194 | |
| 195 | /** Complete membership evidence for cleanup; failed or truncated listings never prove absence. @internal */ |
| 196 | export const listGovernanceOrganizationMembers = Effect.fn(function* (orgId: string) { |
| 197 | const members: Neon.Member[] = []; |
| 198 | const seen = new Set<string>(); |
| 199 | let cursor: string | undefined; |
| 200 | for (let page = 0; page < 10; page++) { |
| 201 | const response = yield* Neon.getOrganizationMembers({ |
| 202 | org_id: orgId, |
| 203 | cursor, |
| 204 | limit: 100, |
| 205 | }); |
| 206 | for (const { member } of response.members) { |
| 207 | if (member.org_id !== orgId) { |
| 208 | return yield* new GovernanceRoleSafetyError({ |
| 209 | message: "Organization member listing returned a different organization", |
| 210 | }); |
| 211 | } |
| 212 | members.push(member); |
| 213 | } |
| 214 | const next = response.pagination?.next; |
| 215 | if (next === undefined) return members; |
| 216 | if (!next || seen.has(next)) { |
| 217 | return yield* new GovernanceRoleSafetyError({ |
| 218 | message: "Organization membership listing returned an invalid or repeated cursor", |
| 219 | }); |
| 220 | } |
| 221 | seen.add(next); |
| 222 | cursor = next; |
| 223 | } |
| 224 | return yield* new GovernanceRoleSafetyError({ |
| 225 | message: |
| 226 | "Organization membership listing exceeded its bounded pagination limit; absence is unproven", |
| 227 | }); |
| 228 | }); |
| 229 | |
| 230 | const validateObservedMember = Effect.fn(function* ( |
| 231 | scope: { orgId: string; memberId: string }, |
| 232 | member: Neon.Member, |
| 233 | ) { |
| 234 | if (member.id !== scope.memberId || member.org_id !== scope.orgId || !member.user_id) { |
| 235 | return yield* new GovernanceRoleSafetyError({ |
| 236 | message: "Organization membership identity does not match the requested scope", |
| 237 | }); |
| 238 | } |
| 239 | yield* validateOrganizationRole(member.role); |
| 240 | return member; |
| 241 | }); |
| 242 | |
| 243 | const observe = Effect.fn(function* (scope: { orgId: string; memberId: string }) { |
| 244 | yield* validateGovernanceScope(scope); |
| 245 | return yield* validateObservedMember(scope, yield* Neon.getOrganizationMember(request(scope))); |
| 246 | }); |
| 247 | |
| 248 | const validateScope = ( |
| 249 | scope: { orgId: string; memberId: string }, |
| 250 | output: OrganizationMemberRoleAttributes, |
| 251 | ) => |
| 252 | scope.orgId === output.orgId && scope.memberId === output.memberId |
| 253 | ? Effect.void |
| 254 | : Effect.fail( |
| 255 | new GovernanceRoleSafetyError({ |
| 256 | message: "Membership identity changed without replacement", |
| 257 | }), |
| 258 | ); |
| 259 | |
| 260 | const verifyBaseline = Effect.fn(function* ( |
| 261 | output: OrganizationMemberRoleAttributes | undefined, |
| 262 | owner: { fqn: string; instanceId: string }, |
| 263 | ) { |
| 264 | const baseline = yield* requireGovernanceBaseline(output?.baseline, owner); |
| 265 | yield* validateOrganizationRole(baseline.originalRole); |
| 266 | yield* validateOrganizationRole(baseline.managedRole); |
| 267 | return baseline; |
| 268 | }); |
| 269 | |
| 270 | export const OrganizationMemberRoleProvider = () => |
| 271 | Provider.succeed(OrganizationMemberRole, { |
| 272 | nuke: { skip: true }, |
| 273 | stables: ["orgId", "memberId"], |
| 274 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 275 | if (!isResolved(news)) return; |
| 276 | yield* validateGovernanceScope(news); |
| 277 | yield* validateOrganizationRole(news.role); |
| 278 | const previous = output ?? olds; |
| 279 | if (news.orgId !== previous.orgId || news.memberId !== previous.memberId) { |
| 280 | return yield* new GovernanceRoleSafetyError({ |
| 281 | message: |
| 282 | "Restore and remove the existing role control before changing its membership identity; the new membership requires a separate durable adoption snapshot", |
| 283 | }); |
| 284 | } |
| 285 | }), |
| 286 | read: Effect.fn(function* ({ olds, output, fqn, instanceId }) { |
| 287 | const scope = output ?? olds; |
| 288 | yield* validateGovernanceScope(scope); |
| 289 | const baseline = output ? yield* verifyBaseline(output, { fqn, instanceId }) : undefined; |
| 290 | const member = yield* observe(scope); |
| 291 | if (output && baseline) { |
| 292 | if (member.user_id !== baseline.userId) { |
| 293 | return yield* new GovernanceRoleSafetyError({ |
| 294 | message: "Membership user changed; refusing to reuse the captured baseline", |
| 295 | }); |
| 296 | } |
| 297 | yield* organizationRoleTransition(baseline, member.role, member.role); |
| 298 | return { ...output, role: member.role }; |
| 299 | } |
| 300 | return Unowned({ |
| 301 | orgId: scope.orgId, |
| 302 | memberId: scope.memberId, |
| 303 | role: member.role, |
| 304 | baseline: { |
| 305 | fqn, |
| 306 | instanceId, |
| 307 | userId: member.user_id, |
| 308 | originalRole: member.role, |
| 309 | managedRole: member.role, |
| 310 | }, |
| 311 | }); |
| 312 | }), |
| 313 | reconcile: Effect.fn(function* ({ news, output, fqn, instanceId }) { |
| 314 | yield* validateGovernanceScope(news); |
| 315 | yield* validateOrganizationRole(news.role); |
| 316 | const baseline = yield* verifyBaseline(output, { fqn, instanceId }); |
| 317 | if (!output) |
| 318 | return yield* new GovernanceRoleSafetyError({ |
| 319 | message: "A persisted adoption snapshot is required before changing an organization role", |
| 320 | }); |
| 321 | yield* validateScope(news, output); |
| 322 | const member = yield* observe(news); |
| 323 | if (member.user_id !== baseline.userId) |
| 324 | return yield* new GovernanceRoleSafetyError({ |
| 325 | message: "Membership user changed", |
| 326 | }); |
| 327 | if (yield* organizationRoleTransition(baseline, member.role, news.role)) { |
| 328 | yield* validateGovernanceActor(member.user_id, (yield* Neon.getCurrentUserInfo({})).id); |
| 329 | yield* Neon.updateOrganizationMember({ |
| 330 | ...request(news), |
| 331 | role: news.role, |
| 332 | }); |
| 333 | } |
| 334 | const current = yield* observe(news); |
| 335 | if (current.user_id !== baseline.userId || !sameOrganizationRole(current.role, news.role)) { |
| 336 | return yield* new GovernanceRoleSafetyError({ |
| 337 | message: "Organization role did not converge; retaining the original baseline", |
| 338 | }); |
| 339 | } |
| 340 | return { |
| 341 | orgId: news.orgId, |
| 342 | memberId: news.memberId, |
| 343 | role: current.role, |
| 344 | baseline: { ...baseline, managedRole: current.role }, |
| 345 | }; |
| 346 | }), |
| 347 | delete: Effect.fn(function* ({ output, fqn, instanceId }) { |
| 348 | const baseline = yield* verifyBaseline(output, { fqn, instanceId }); |
| 349 | yield* validateGovernanceScope(output); |
| 350 | // getOrganizationMember has no typed missing-member error in the SDK. |
| 351 | const listed = (yield* listGovernanceOrganizationMembers(output.orgId)).find( |
| 352 | (member) => member.id === output.memberId, |
| 353 | ); |
| 354 | if (!listed) return; |
| 355 | const member = yield* validateObservedMember(output, listed); |
| 356 | if (member.user_id !== baseline.userId) |
| 357 | return yield* new GovernanceRoleSafetyError({ |
| 358 | message: "Membership user changed", |
| 359 | }); |
| 360 | if (yield* organizationRoleTransition(baseline, member.role, baseline.originalRole, true)) { |
| 361 | yield* validateGovernanceActor(member.user_id, (yield* Neon.getCurrentUserInfo({})).id); |
| 362 | yield* Neon.updateOrganizationMember({ |
| 363 | ...request(output), |
| 364 | role: baseline.originalRole, |
| 365 | }); |
| 366 | const restored = yield* observe(output); |
| 367 | if ( |
| 368 | restored.user_id !== baseline.userId || |
| 369 | !sameOrganizationRole(restored.role, baseline.originalRole) |
| 370 | ) { |
| 371 | return yield* new GovernanceRoleSafetyError({ |
| 372 | message: "Original organization role was not restored", |
| 373 | }); |
| 374 | } |
| 375 | } |
| 376 | }), |
| 377 | }); |