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 magicTransit from "@distilled.cloud/cloudflare/magic-transit"; |
| 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 Effect from "effect/Effect"; |
| 7 | import * as Predicate from "effect/Predicate"; |
| 8 | import * as Redacted from "effect/Redacted"; |
| 9 | import { CloudflareEnvironment } from "../CloudflareEnvironment.ts"; |
| 10 | import type { Providers } from "../Providers.ts"; |
| 11 | import type { MagicTunnelBgp, MagicTunnelHealthCheck } from "./GreTunnel.ts"; |
| 12 | |
| 13 | const TypeId = "Cloudflare.MagicTransit.IpsecTunnel" as const; |
| 14 | type TypeId = typeof TypeId; |
| 15 | |
| 16 | export interface IpsecTunnelProps { |
| 17 | /** |
| 18 | * The name of the IPsec tunnel. Cannot share a name with other tunnels. |
| 19 | * Immutable in practice — changing it triggers a replacement. |
| 20 | */ |
| 21 | name: string; |
| 22 | /** |
| 23 | * The IP address assigned to the Cloudflare side of the IPsec tunnel |
| 24 | * (a Cloudflare anycast IP allocated to the account). |
| 25 | */ |
| 26 | cloudflareEndpoint: string; |
| 27 | /** |
| 28 | * The IP address assigned to the customer side of the IPsec tunnel. Not |
| 29 | * required, but must be set for proactive traceroutes to work. |
| 30 | */ |
| 31 | customerEndpoint?: string; |
| 32 | /** |
| 33 | * A 31-bit prefix (/31 in CIDR notation) from RFC1918 private space; one |
| 34 | * host for each side of the tunnel. |
| 35 | */ |
| 36 | interfaceAddress: string; |
| 37 | /** |
| 38 | * A /127 IPv6 prefix from within the account's `virtual_subnet6` space. |
| 39 | */ |
| 40 | interfaceAddress6?: string; |
| 41 | /** |
| 42 | * An optional description of the IPsec tunnel. |
| 43 | */ |
| 44 | description?: string; |
| 45 | /** |
| 46 | * Pre-shared key for the tunnel. Write-only — Cloudflare never returns |
| 47 | * it, so the value is carried in state. When omitted, Cloudflare leaves |
| 48 | * the tunnel without a PSK until one is generated via the dashboard/API. |
| 49 | */ |
| 50 | psk?: Redacted.Redacted<string>; |
| 51 | /** |
| 52 | * If `true`, IPsec replay protection is supported in the |
| 53 | * Cloudflare-to-customer direction. |
| 54 | * @default false |
| 55 | */ |
| 56 | replayProtection?: boolean; |
| 57 | /** |
| 58 | * Tunnel health-check configuration. |
| 59 | */ |
| 60 | healthCheck?: MagicTunnelHealthCheck; |
| 61 | /** |
| 62 | * BGP configuration for the tunnel. |
| 63 | */ |
| 64 | bgp?: MagicTunnelBgp; |
| 65 | /** |
| 66 | * Custom remote identities for IKE negotiation. |
| 67 | */ |
| 68 | customRemoteIdentities?: { |
| 69 | /** Identifier of the FQDN remote identity. */ |
| 70 | fqdnId?: string; |
| 71 | }; |
| 72 | /** |
| 73 | * True if automatic stateful return routing should be enabled. Requires |
| 74 | * the `coupler_integration` account flag. |
| 75 | * @default false |
| 76 | */ |
| 77 | automaticReturnRouting?: boolean; |
| 78 | } |
| 79 | |
| 80 | export interface IpsecTunnelAttributes { |
| 81 | /** Cloudflare-assigned identifier of the IPsec tunnel. */ |
| 82 | tunnelId: string; |
| 83 | /** The Cloudflare account the tunnel belongs to. */ |
| 84 | accountId: string; |
| 85 | /** The name of the tunnel. */ |
| 86 | name: string; |
| 87 | /** The IP address on the Cloudflare side of the tunnel. */ |
| 88 | cloudflareEndpoint: string; |
| 89 | /** The IP address on the customer side of the tunnel, if set. */ |
| 90 | customerEndpoint: string | undefined; |
| 91 | /** The /31 interface address of the tunnel. */ |
| 92 | interfaceAddress: string; |
| 93 | /** The /127 IPv6 interface address, if configured. */ |
| 94 | interfaceAddress6: string | undefined; |
| 95 | /** The tunnel description, if set. */ |
| 96 | description: string | undefined; |
| 97 | /** |
| 98 | * The pre-shared key as configured. Write-only on Cloudflare's side — |
| 99 | * this is the value from props, carried in state, never read back. |
| 100 | */ |
| 101 | psk: Redacted.Redacted<string> | undefined; |
| 102 | /** Whether the tunnel allows a null cipher (`ENCR_NULL`) in Phase 2. */ |
| 103 | allowNullCipher: boolean | undefined; |
| 104 | /** Whether replay protection is enabled. */ |
| 105 | replayProtection: boolean | undefined; |
| 106 | /** ISO8601 creation timestamp. */ |
| 107 | createdOn: string | undefined; |
| 108 | /** ISO8601 last-modified timestamp. */ |
| 109 | modifiedOn: string | undefined; |
| 110 | } |
| 111 | |
| 112 | export type IpsecTunnel = Resource< |
| 113 | TypeId, |
| 114 | IpsecTunnelProps, |
| 115 | IpsecTunnelAttributes, |
| 116 | never, |
| 117 | Providers |
| 118 | >; |
| 119 | |
| 120 | /** |
| 121 | * A Magic Transit / Magic WAN IPsec tunnel between Cloudflare and a |
| 122 | * customer device. |
| 123 | * |
| 124 | * Requires a Magic Transit or Magic WAN subscription on the account — |
| 125 | * accounts that are not onboarded receive a typed |
| 126 | * `MagicTransitNotOnboarded` error (Cloudflare code 1012). |
| 127 | * |
| 128 | * The tunnel `name` is unique per account and immutable in practice — |
| 129 | * changing it triggers a replacement. The `psk` is write-only: Cloudflare |
| 130 | * never returns it, so the configured value is carried in state. |
| 131 | * ### Creating an IPsec tunnel |
| 132 | * **Example:** Basic tunnel with a provided PSK |
| 133 | * ```typescript |
| 134 | * const tunnel = yield* Cloudflare.MagicTransit.IpsecTunnel("branch", { |
| 135 | * name: "branch-ipsec-1", |
| 136 | * cloudflareEndpoint: "203.0.113.1", |
| 137 | * customerEndpoint: "198.51.100.1", |
| 138 | * interfaceAddress: "10.213.0.10/31", |
| 139 | * psk: yield* Config.Redacted("IPSEC_PSK"), |
| 140 | * }); |
| 141 | * ``` |
| 142 | * |
| 143 | * **Example:** Tunnel with replay protection and health checks |
| 144 | * ```typescript |
| 145 | * const tunnel = yield* Cloudflare.MagicTransit.IpsecTunnel("branch", { |
| 146 | * name: "branch-ipsec-1", |
| 147 | * cloudflareEndpoint: "203.0.113.1", |
| 148 | * interfaceAddress: "10.213.0.10/31", |
| 149 | * replayProtection: true, |
| 150 | * healthCheck: { enabled: true, rate: "mid" }, |
| 151 | * }); |
| 152 | * ``` |
| 153 | * |
| 154 | * @see https://developers.cloudflare.com/magic-wan/reference/tunnels/ |
| 155 | * |
| 156 | * @resource |
| 157 | * @product Magic Transit |
| 158 | * @category Network |
| 159 | */ |
| 160 | export const IpsecTunnel = Resource<IpsecTunnel>(TypeId); |
| 161 | |
| 162 | /** |
| 163 | * Returns true if the given value is an IpsecTunnel resource. |
| 164 | */ |
| 165 | export const isIpsecTunnel = (value: unknown): value is IpsecTunnel => |
| 166 | Predicate.hasProperty(value, "Type") && value.Type === TypeId; |
| 167 | |
| 168 | export const IpsecTunnelProvider = () => |
| 169 | Provider.succeed(IpsecTunnel, { |
| 170 | stables: ["tunnelId", "accountId", "createdOn"], |
| 171 | |
| 172 | diff: Effect.fn(function* ({ olds, news }) { |
| 173 | if (!isResolved(news)) return undefined; |
| 174 | if (olds === undefined) return undefined; |
| 175 | // The tunnel name is unique routing identity; renames are rejected. |
| 176 | if (olds.name !== news.name) return { action: "replace" } as const; |
| 177 | return undefined; |
| 178 | }), |
| 179 | |
| 180 | read: Effect.fn(function* ({ output, olds }) { |
| 181 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 182 | const acct = output?.accountId ?? accountId; |
| 183 | |
| 184 | if (output?.tunnelId) { |
| 185 | const observed = yield* getTunnel(acct, output.tunnelId); |
| 186 | // The PSK is write-only — carry the persisted value forward. |
| 187 | if (observed) return toAttributes(observed, acct, output.psk); |
| 188 | } |
| 189 | // Cold read — tunnel names are unique per account. Tunnels carry no |
| 190 | // ownership markers; report as Unowned so takeover is gated behind |
| 191 | // the adopt policy. |
| 192 | const name = output?.name ?? olds?.name; |
| 193 | if (name) { |
| 194 | const observed = yield* findByName(acct, name); |
| 195 | if (observed) { |
| 196 | return Unowned(toAttributes(observed, acct, output?.psk)); |
| 197 | } |
| 198 | } |
| 199 | return undefined; |
| 200 | }), |
| 201 | |
| 202 | reconcile: Effect.fn(function* ({ news, olds, output }) { |
| 203 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 204 | |
| 205 | // Observe — the id on `output` is a hint; fall through to the |
| 206 | // unique-name lookup when it is gone. |
| 207 | let observed = output?.tunnelId ? yield* getTunnel(accountId, output.tunnelId) : undefined; |
| 208 | if (!observed) { |
| 209 | observed = yield* findByName(accountId, news.name); |
| 210 | } |
| 211 | |
| 212 | const psk = news.psk ? Redacted.value(news.psk) : undefined; |
| 213 | |
| 214 | // Ensure — create when missing. |
| 215 | if (!observed) { |
| 216 | const created = yield* magicTransit.createIpsecTunnel({ |
| 217 | accountId, |
| 218 | xMagicNewHcTarget: true, |
| 219 | name: news.name, |
| 220 | cloudflareEndpoint: news.cloudflareEndpoint, |
| 221 | customerEndpoint: news.customerEndpoint, |
| 222 | interfaceAddress: news.interfaceAddress, |
| 223 | interfaceAddress6: news.interfaceAddress6, |
| 224 | description: news.description, |
| 225 | psk, |
| 226 | replayProtection: news.replayProtection, |
| 227 | automaticReturnRouting: news.automaticReturnRouting, |
| 228 | customRemoteIdentities: news.customRemoteIdentities, |
| 229 | bgp: toBgpRequest(news.bgp), |
| 230 | healthCheck: toHealthCheckRequest(news.healthCheck), |
| 231 | }); |
| 232 | return toAttributes(created, accountId, news.psk); |
| 233 | } |
| 234 | |
| 235 | // Sync — diff observed cloud state against desired; the update API |
| 236 | // is a full PUT, so send everything, but skip the call on a no-op. |
| 237 | // The PSK cannot be observed: it is dirty when the desired value |
| 238 | // differs from the last-applied props. |
| 239 | const oldPsk = olds?.psk ? Redacted.value(olds.psk) : undefined; |
| 240 | const pskDirty = psk !== undefined && psk !== oldPsk; |
| 241 | if (dirty(observed, news) || pskDirty) { |
| 242 | const updated = yield* magicTransit.updateIpsecTunnel({ |
| 243 | accountId, |
| 244 | ipsecTunnelId: observed.id, |
| 245 | xMagicNewHcTarget: true, |
| 246 | name: news.name, |
| 247 | cloudflareEndpoint: news.cloudflareEndpoint, |
| 248 | customerEndpoint: news.customerEndpoint, |
| 249 | interfaceAddress: news.interfaceAddress, |
| 250 | interfaceAddress6: news.interfaceAddress6, |
| 251 | description: news.description, |
| 252 | psk: pskDirty ? psk : undefined, |
| 253 | replayProtection: news.replayProtection, |
| 254 | automaticReturnRouting: news.automaticReturnRouting, |
| 255 | customRemoteIdentities: news.customRemoteIdentities, |
| 256 | bgp: toBgpRequest(news.bgp), |
| 257 | healthCheck: toHealthCheckRequest(news.healthCheck), |
| 258 | }); |
| 259 | observed = |
| 260 | updated.modifiedIpsecTunnel ?? (yield* getTunnel(accountId, observed.id)) ?? observed; |
| 261 | } |
| 262 | |
| 263 | return toAttributes(observed, accountId, news.psk); |
| 264 | }), |
| 265 | |
| 266 | delete: Effect.fn(function* ({ output }) { |
| 267 | yield* magicTransit |
| 268 | .deleteIpsecTunnel({ |
| 269 | accountId: output.accountId, |
| 270 | ipsecTunnelId: output.tunnelId, |
| 271 | xMagicNewHcTarget: true, |
| 272 | }) |
| 273 | .pipe(Effect.catchTag("IpsecTunnelNotFound", () => Effect.void)); |
| 274 | }), |
| 275 | |
| 276 | // Account-scoped collection. The list API returns the full tunnel set in |
| 277 | // a single response (non-paginated). The PSK is write-only and never |
| 278 | // returned, so it is `undefined` here — matching `read`'s cold-read shape. |
| 279 | list: Effect.fn(function* () { |
| 280 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 281 | return yield* magicTransit.listIpsecTunnels({ accountId, xMagicNewHcTarget: true }).pipe( |
| 282 | Effect.map((r) => |
| 283 | (r.ipsecTunnels ?? []).map((tunnel) => toAttributes(tunnel, accountId, undefined)), |
| 284 | ), |
| 285 | // Accounts that aren't onboarded onto Magic Transit (code 1012) |
| 286 | // or lack the entitlement can't enumerate tunnels — treat as none. |
| 287 | Effect.catchTag( |
| 288 | ["MagicTransitNotOnboarded", "Forbidden"], |
| 289 | (): Effect.Effect<IpsecTunnelAttributes[]> => Effect.succeed([]), |
| 290 | ), |
| 291 | ); |
| 292 | }), |
| 293 | }); |
| 294 | |
| 295 | interface ObservedIpsecTunnel { |
| 296 | id: string; |
| 297 | name: string; |
| 298 | cloudflareEndpoint: string; |
| 299 | interfaceAddress: string; |
| 300 | customerEndpoint?: string | null; |
| 301 | interfaceAddress6?: string | null; |
| 302 | description?: string | null; |
| 303 | allowNullCipher?: boolean | null; |
| 304 | replayProtection?: boolean | null; |
| 305 | healthCheck?: { |
| 306 | direction?: string | null; |
| 307 | enabled?: boolean | null; |
| 308 | rate?: string | null; |
| 309 | target?: { effective?: string | null; saved?: string | null } | string | null; |
| 310 | type?: string | null; |
| 311 | } | null; |
| 312 | createdOn?: string | null; |
| 313 | modifiedOn?: string | null; |
| 314 | } |
| 315 | |
| 316 | /** |
| 317 | * Read a tunnel by id, mapping "gone" (`IpsecTunnelNotFound`, Cloudflare |
| 318 | * error code 1032) to `undefined`. |
| 319 | */ |
| 320 | const getTunnel = (accountId: string, ipsecTunnelId: string) => |
| 321 | magicTransit.getIpsecTunnel({ accountId, ipsecTunnelId, xMagicNewHcTarget: true }).pipe( |
| 322 | Effect.map((r): ObservedIpsecTunnel | undefined => r.ipsecTunnel ?? undefined), |
| 323 | Effect.catchTag("IpsecTunnelNotFound", () => Effect.undefined), |
| 324 | ); |
| 325 | |
| 326 | /** |
| 327 | * Find a tunnel by exact name. Names are unique per account, so at most |
| 328 | * one tunnel can match. |
| 329 | */ |
| 330 | const findByName = (accountId: string, name: string) => |
| 331 | magicTransit |
| 332 | .listIpsecTunnels({ accountId, xMagicNewHcTarget: true }) |
| 333 | .pipe( |
| 334 | Effect.map((r): ObservedIpsecTunnel | undefined => |
| 335 | (r.ipsecTunnels ?? []).find((t) => t.name === name), |
| 336 | ), |
| 337 | ); |
| 338 | |
| 339 | const toBgpRequest = (bgp: MagicTunnelBgp | undefined) => |
| 340 | bgp |
| 341 | ? { |
| 342 | customerAsn: bgp.customerAsn, |
| 343 | extraPrefixes: bgp.extraPrefixes, |
| 344 | md5Key: bgp.md5Key ? Redacted.value(bgp.md5Key) : undefined, |
| 345 | } |
| 346 | : undefined; |
| 347 | |
| 348 | const toHealthCheckRequest = (hc: MagicTunnelHealthCheck | undefined) => |
| 349 | hc |
| 350 | ? { |
| 351 | enabled: hc.enabled, |
| 352 | direction: hc.direction, |
| 353 | rate: hc.rate, |
| 354 | type: hc.type, |
| 355 | target: hc.target ? { saved: hc.target } : undefined, |
| 356 | } |
| 357 | : undefined; |
| 358 | |
| 359 | const observedHealthTarget = ( |
| 360 | healthCheck: ObservedIpsecTunnel["healthCheck"], |
| 361 | ): string | undefined => { |
| 362 | const target = healthCheck?.target; |
| 363 | if (typeof target === "string") return target; |
| 364 | return target?.saved ?? undefined; |
| 365 | }; |
| 366 | |
| 367 | const dirty = (observed: ObservedIpsecTunnel, news: IpsecTunnelProps): boolean => |
| 368 | observed.cloudflareEndpoint !== news.cloudflareEndpoint || |
| 369 | observed.interfaceAddress !== news.interfaceAddress || |
| 370 | (news.customerEndpoint !== undefined && |
| 371 | (observed.customerEndpoint ?? undefined) !== news.customerEndpoint) || |
| 372 | (news.interfaceAddress6 !== undefined && |
| 373 | (observed.interfaceAddress6 ?? undefined) !== news.interfaceAddress6) || |
| 374 | (news.description !== undefined && (observed.description ?? undefined) !== news.description) || |
| 375 | (news.replayProtection !== undefined && |
| 376 | (observed.replayProtection ?? false) !== news.replayProtection) || |
| 377 | healthCheckDirty(observed.healthCheck, news.healthCheck); |
| 378 | |
| 379 | const healthCheckDirty = ( |
| 380 | observed: ObservedIpsecTunnel["healthCheck"], |
| 381 | desired: MagicTunnelHealthCheck | undefined, |
| 382 | ): boolean => { |
| 383 | if (desired === undefined) return false; |
| 384 | const hc = observed ?? {}; |
| 385 | return ( |
| 386 | (desired.enabled !== undefined && (hc.enabled ?? undefined) !== desired.enabled) || |
| 387 | (desired.direction !== undefined && (hc.direction ?? undefined) !== desired.direction) || |
| 388 | (desired.rate !== undefined && (hc.rate ?? undefined) !== desired.rate) || |
| 389 | (desired.type !== undefined && (hc.type ?? undefined) !== desired.type) || |
| 390 | (desired.target !== undefined && observedHealthTarget(hc) !== desired.target) |
| 391 | ); |
| 392 | }; |
| 393 | |
| 394 | const toAttributes = ( |
| 395 | tunnel: ObservedIpsecTunnel, |
| 396 | accountId: string, |
| 397 | psk: Redacted.Redacted<string> | undefined, |
| 398 | ): IpsecTunnelAttributes => ({ |
| 399 | tunnelId: tunnel.id, |
| 400 | accountId, |
| 401 | name: tunnel.name, |
| 402 | cloudflareEndpoint: tunnel.cloudflareEndpoint, |
| 403 | customerEndpoint: tunnel.customerEndpoint ?? undefined, |
| 404 | interfaceAddress: tunnel.interfaceAddress, |
| 405 | interfaceAddress6: tunnel.interfaceAddress6 ?? undefined, |
| 406 | description: tunnel.description ?? undefined, |
| 407 | psk, |
| 408 | allowNullCipher: tunnel.allowNullCipher ?? undefined, |
| 409 | replayProtection: tunnel.replayProtection ?? undefined, |
| 410 | createdOn: tunnel.createdOn ?? undefined, |
| 411 | modifiedOn: tunnel.modifiedOn ?? undefined, |
| 412 | }); |