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

main
ts 232 lines 8.33 KB
Raw
1 import * as Neon from "@distilled.cloud/neon";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { 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 { resolveBranchScope, type BranchScope, type ResolvedBranchScope } from "./BranchScope.ts";
11 import type { Providers } from "./Providers.ts";
12
13 export type CredentialScope = Neon.CredentialScope;
14
15 export type CredentialProps = BranchScope & {
16 /** Stable customer label. Omit to generate an ownership-qualified name. Explicit labels require delete-first replacement when scopes change. */
17 name?: string;
18 /** Branch-lineage permissions. Request storage:read explicitly for S3 reads; current data-plane behavior differs from the documented write-implies-read contract. Changes replace the credential. */
19 scopes: CredentialScope[];
20 };
21
22 export interface CredentialAttributes extends ResolvedBranchScope {
23 /** Opaque credential identifier, also the S3 access-key ID. */
24 tokenId: string;
25 /** Stable customer label. */
26 name: string;
27 /** Granted scopes, including any platform-added capabilities. */
28 scopes: string[];
29 /** Branch service bearer token, never the deployment account key. */
30 apiToken: Redacted.Redacted<string>;
31 /** S3 signing secret. */
32 s3SecretAccessKey: Redacted.Redacted<string>;
33 /** Issuance time. */
34 createdAt: string;
35 }
36
37 export interface Credential extends Resource<
38 "Neon.Credential",
39 CredentialProps,
40 CredentialAttributes,
41 never,
42 Providers
43 > {}
44
45 /**
46 * A customer-managed branch service credential. Credentials authorize their branch
47 * and descendants, not individual buckets. Reconciliation reveals existing secrets;
48 * it never rotates a credential. Unrecoverable legacy secrets require explicit action.
49 *
50 * ### Creating a Credential
51 * **Example:** Read-only storage access from an external application
52 * ```typescript
53 * const credential = yield* Neon.Credential("Reader", {
54 * branch,
55 * scopes: ["storage:read"],
56 * });
57 * ```
58 *
59 * @resource
60 * @product Credential
61 */
62 export const Credential = Resource<Credential>("Neon.Credential");
63
64 export class CredentialRecoveryError extends Data.TaggedError("CredentialRecoveryError")<{
65 message: string;
66 }> {}
67
68 const sameScopes = (a: readonly string[], b: readonly string[]) =>
69 [...new Set(a)].sort().join("\n") === [...new Set(b)].sort().join("\n");
70
71 const requestScope = (scope: ResolvedBranchScope) => ({
72 project_id: scope.projectId,
73 branch_id: scope.branchId,
74 });
75
76 const findCredential = Effect.fn(function* (
77 scope: ResolvedBranchScope,
78 name: string,
79 tokenId?: string,
80 ) {
81 const { credentials } = yield* Neon.listCredentials(requestScope(scope));
82 const matches = credentials.filter(
83 (credential) =>
84 !credential.revoked_at &&
85 credential.principal_type === "user" &&
86 (credential.branch_id === undefined || credential.branch_id === scope.branchId) &&
87 (tokenId ? credential.token_id === tokenId : credential.name === name),
88 );
89 if (matches.length > 1) {
90 return yield* new CredentialRecoveryError({
91 message: `Ambiguous credential label ${name}; refusing to choose a token`,
92 });
93 }
94 return matches[0];
95 });
96
97 const hydrateCredential = Effect.fn(function* (
98 scope: ResolvedBranchScope,
99 metadata: Neon.CredentialMeta,
100 ) {
101 const secret = yield* Neon.revealCredential({
102 ...requestScope(scope),
103 token_id: metadata.token_id,
104 }).pipe(
105 Effect.catchTag("Conflict", () =>
106 Effect.fail(
107 new CredentialRecoveryError({
108 message:
109 "Credential secrets cannot be revealed; explicitly rotate or replace this legacy credential",
110 }),
111 ),
112 ),
113 );
114 return {
115 ...scope,
116 tokenId: metadata.token_id,
117 name: metadata.name ?? "",
118 scopes: metadata.scopes,
119 apiToken: Redacted.isRedacted(secret.api_token)
120 ? secret.api_token
121 : Redacted.make(secret.api_token),
122 s3SecretAccessKey: Redacted.isRedacted(secret.s3_secret_access_key)
123 ? secret.s3_secret_access_key
124 : Redacted.make(secret.s3_secret_access_key),
125 createdAt: metadata.created_at,
126 } satisfies CredentialAttributes;
127 });
128
129 export const CredentialProvider = () =>
130 Provider.succeed(Credential, {
131 stables: ["projectId", "branchId", "name"],
132 diff: Effect.fn(function* ({ news, output }) {
133 if (!isResolved(news) || !output) return;
134 const scope = yield* resolveBranchScope(news);
135 if (
136 scope.projectId !== output.projectId ||
137 scope.branchId !== output.branchId ||
138 (news.name !== undefined && news.name !== output.name) ||
139 !sameScopes(news.scopes, output.scopes)
140 ) {
141 return {
142 action: "replace",
143 deleteFirst:
144 news.name !== undefined &&
145 news.name === output.name &&
146 scope.projectId === output.projectId &&
147 scope.branchId === output.branchId,
148 };
149 }
150 }),
151 read: Effect.fn(function* ({ id, olds, output, previous }) {
152 if (!output && !olds?.branch && !olds?.project) return undefined;
153 const scope = output ?? (yield* resolveBranchScope(olds!));
154 const name =
155 output?.name ?? olds?.name ?? (yield* createPhysicalName({ id, maxLength: 100 }));
156 const metadata = yield* findCredential(scope, name, output?.tokenId);
157 if (!metadata) return undefined;
158 const attrs = yield* hydrateCredential(scope, metadata);
159 // The generation a replacement is replacing is ours.
160 return !output && olds?.name !== undefined && attrs.tokenId !== previous?.tokenId
161 ? Unowned(attrs)
162 : attrs;
163 }),
164 reconcile: Effect.fn(function* ({ id, news, output }) {
165 const scope = yield* resolveBranchScope(news);
166 const name = news.name ?? output?.name ?? (yield* createPhysicalName({ id, maxLength: 100 }));
167 let metadata = yield* findCredential(scope, name, output?.tokenId);
168 if (!metadata && output) metadata = yield* findCredential(scope, name);
169 if (!metadata) {
170 const created = yield* Neon.createCredential({
171 ...requestScope(scope),
172 name,
173 scopes: news.scopes,
174 principal_type: "user",
175 });
176 return {
177 ...scope,
178 name,
179 tokenId: created.token_id,
180 scopes: created.scopes,
181 apiToken: Redacted.isRedacted(created.api_token)
182 ? created.api_token
183 : Redacted.make(created.api_token),
184 s3SecretAccessKey: Redacted.isRedacted(created.s3_secret_access_key)
185 ? created.s3_secret_access_key
186 : Redacted.make(created.s3_secret_access_key),
187 createdAt: created.created_at,
188 };
189 }
190 if (!sameScopes(metadata.scopes, news.scopes)) {
191 return yield* new CredentialRecoveryError({
192 message:
193 "Observed credential scopes differ from desired scopes; replace rather than rotate or adopt broader access",
194 });
195 }
196 return yield* hydrateCredential(scope, metadata);
197 }),
198 delete: Effect.fn(function* ({ output }) {
199 yield* Neon.revokeCredential({
200 ...requestScope(output),
201 token_id: output.tokenId,
202 }).pipe(Effect.catchTag("NotFound", () => Effect.void));
203 }),
204 });
205
206 /** Validate an override against the target branch's actual ancestry and required scope. */
207 export const validateCredential = Effect.fn(function* (
208 credential: Pick<CredentialAttributes, "projectId" | "branchId" | "scopes">,
209 target: ResolvedBranchScope,
210 required: CredentialScope,
211 ) {
212 if (credential.projectId !== target.projectId || !credential.scopes.includes(required)) {
213 return yield* new CredentialRecoveryError({
214 message: "Credential project or scope does not authorize this binding",
215 });
216 }
217 let branchId: string | undefined = target.branchId;
218 const seen = new Set<string>();
219 while (branchId) {
220 if (branchId === credential.branchId) return;
221 if (seen.has(branchId)) break;
222 seen.add(branchId);
223 const response: Neon.GetProjectBranchResponse = yield* Neon.getProjectBranch({
224 project_id: target.projectId,
225 branch_id: branchId,
226 });
227 branchId = response.branch.parent_id;
228 }
229 return yield* new CredentialRecoveryError({
230 message: "Credential branch is not the target branch or an ancestor",
231 });
232 });