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

main
ts 185 lines 6.58 KB
Raw
1 import type { TokensCreateRequestPoliciesItemPermissionGroupsItemMeta } from "@distilled.cloud/cloudflare/accounts";
2 import { PERMISSION_GROUPS_BY_NAME, type PermissionGroupName } from "./PermissionGroups.ts";
3
4 /**
5 * Resource keys recognized by Cloudflare API token policies.
6 *
7 * Cloudflare requires the account ID to be embedded directly in the resource
8 * key (e.g. `com.cloudflare.api.account.<accountId>`); pass the fully-qualified
9 * key — no rewriting is performed.
10 *
11 * Individual-Worker roles (e.g. `"Individual Workers Editor"`) take a
12 * `com.cloudflare.edge.worker.script.<workerId>` key, where `<workerId>` is the
13 * Worker's script tag (the Worker's `workerId` attribute). Cloudflare only
14 * accepts it nested under the account key, and only on account-owned tokens.
15 *
16 * @see https://developers.cloudflare.com/fundamentals/api/reference/permissions/
17 */
18 export type ResourceKey =
19 | `com.cloudflare.api.account.${string}`
20 | `com.cloudflare.api.account.zone.${string}`
21 | `com.cloudflare.edge.r2.bucket.${string}`
22 | `com.cloudflare.edge.worker.script.${string}`
23 | (string & {});
24
25 /**
26 * A permission group reference: either a typed Cloudflare permission-group
27 * name (resolved against the static catalog) or an explicit `{ id }` for
28 * names that aren't in the catalog or have multiple scopes.
29 */
30 export type PermissionGroupRef = PermissionGroupName | { id: string; meta?: PermissionGroupMeta };
31
32 /**
33 * Descriptive attributes of a permission group, as Cloudflare documents them
34 * on token policies. Optional; Cloudflare does not store them on the token.
35 */
36 export type PermissionGroupMeta = TokensCreateRequestPoliciesItemPermissionGroupsItemMeta;
37
38 /**
39 * Value of a resource entry in an {@link Policy}. Usually `"*"`, but
40 * account-owned tokens must nest zone resources under the account resource —
41 * e.g. `{ "com.cloudflare.api.account.<id>": { "com.cloudflare.api.account.zone.*": "*" } }`
42 * — so a nested object is also allowed.
43 */
44 export type ResourceScope = string | { [K in ResourceKey]?: string };
45
46 export interface Policy {
47 effect: "allow" | "deny";
48 permissionGroups: PermissionGroupRef[];
49 resources: { [K in ResourceKey]?: ResourceScope };
50 }
51
52 export interface Condition {
53 requestIp?: {
54 in?: string[];
55 notIn?: string[];
56 };
57 }
58
59 export type Props = {
60 /**
61 * Token name. Defaults to a generated physical name based on the
62 * resource's logical id, app name, and stage.
63 */
64 name?: string;
65 /**
66 * The Cloudflare account ID that owns this token. Defaults to the
67 * account ID resolved from the ambient {@link CloudflareEnvironment}.
68 */
69 accountId?: string;
70 /**
71 * Access policies attached to the token. Cloudflare requires at least one
72 * policy on a token; if you omit `policies` here, the policies must instead
73 * be contributed by bindings (see {@link ApiTokenBinding}).
74 */
75 policies?: Policy[];
76 /** ISO 8601 expiration timestamp. */
77 expiresOn?: string;
78 /** ISO 8601 "not before" timestamp. */
79 notBefore?: string;
80 /** Optional usage conditions (e.g. IP allowlist). */
81 condition?: Condition;
82 };
83
84 /**
85 * Binding contract for {@link AccountApiToken} / {@link UserApiToken}.
86 *
87 * A binding contributes additional access policies to the token. This lets a
88 * downstream resource (e.g. a runtime capability that needs to call a specific
89 * Cloudflare API) create a token and attach exactly the policies it requires,
90 * without the token's owner having to enumerate them up front.
91 *
92 * Binding-contributed policies are merged with any `policies` passed directly
93 * as props; the union must contain at least one policy.
94 */
95 export type ApiTokenBinding = {
96 /** Access policies to attach to the token. */
97 policies?: Policy[];
98 };
99
100 /**
101 * Collect the policies a token should be created with: those passed directly
102 * as props, plus those contributed by bindings.
103 */
104 export const collectPolicies = (
105 props: Policy[] | undefined,
106 bindings: { data: ApiTokenBinding }[],
107 ): Policy[] => [...(props ?? []), ...bindings.flatMap((binding) => binding.data.policies ?? [])];
108
109 export type ResolvedPolicy = {
110 effect: "allow" | "deny";
111 permissionGroups: { id: string; meta?: PermissionGroupMeta }[];
112 resources: Record<string, ResourceScope>;
113 };
114
115 export const resolvePermissionGroup = (ref: PermissionGroupRef) => {
116 if (typeof ref === "string") {
117 const group = PERMISSION_GROUPS_BY_NAME[ref];
118 if (!group) {
119 // Should be unreachable due to the typed union, but guard anyway in
120 // case Cloudflare retires a name we still have in the catalog.
121 throw new Error(
122 `Unknown Cloudflare permission group: "${ref}". Pass an explicit { id } instead.`,
123 );
124 }
125 return { id: group.id };
126 }
127 return ref.meta ? { id: ref.id, meta: ref.meta } : { id: ref.id };
128 };
129
130 const resolveResources = (resources: Policy["resources"]): Record<string, ResourceScope> => {
131 const out: Record<string, ResourceScope> = {};
132 for (const [key, value] of Object.entries(resources)) {
133 if (value === undefined) continue;
134 out[key] = value;
135 }
136 return out;
137 };
138
139 export const resolvePolicies = (policies: Policy[]): ResolvedPolicy[] =>
140 policies.map((policy) => ({
141 effect: policy.effect,
142 permissionGroups: policy.permissionGroups.map(resolvePermissionGroup),
143 resources: resolveResources(policy.resources),
144 }));
145
146 /**
147 * Find a `com.cloudflare.edge.worker.script.*` key placed at the top level of
148 * a policy's resources. Cloudflare answers those with a 500 that distilled
149 * retries indefinitely, so callers reject them up front.
150 */
151 export const findTopLevelWorkerScriptKey = (policies: ResolvedPolicy[]): string | undefined =>
152 policies
153 .flatMap((policy) => Object.keys(policy.resources))
154 .find((key) => key.startsWith("com.cloudflare.edge.worker.script."));
155
156 export const policyFingerprint = (policies: ResolvedPolicy[]): string =>
157 JSON.stringify(
158 policies.map((p) => ({
159 effect: p.effect,
160 permissionGroups: [...p.permissionGroups]
161 .map((g) => ({ id: g.id, meta: g.meta ?? null }))
162 .sort((a, b) => a.id.localeCompare(b.id)),
163 resources: Object.keys(p.resources)
164 .sort()
165 .map((k) => [k, p.resources[k]]),
166 })),
167 );
168
169 export const conditionFingerprint = (condition: Condition | undefined): string =>
170 JSON.stringify({
171 in: [...(condition?.requestIp?.in ?? [])].sort(),
172 notIn: [...(condition?.requestIp?.notIn ?? [])].sort(),
173 });
174
175 export const buildConditionPayload = (condition: Condition | undefined) =>
176 condition
177 ? {
178 requestIp: condition.requestIp
179 ? {
180 in: condition.requestIp.in,
181 notIn: condition.requestIp.notIn,
182 }
183 : undefined,
184 }
185 : undefined;