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, 04:45 UTC
| 1 | import crypto from "node:crypto"; |
| 2 | import * as intel from "@distilled.cloud/cloudflare/intel"; |
| 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 Effect from "effect/Effect"; |
| 8 | import * as Predicate from "effect/Predicate"; |
| 9 | import * as Stream from "effect/Stream"; |
| 10 | import { CloudflareEnvironment } from "../CloudflareEnvironment.ts"; |
| 11 | import type { Providers } from "../Providers.ts"; |
| 12 | |
| 13 | const TypeId = "Cloudflare.Intel.IndicatorFeed" as const; |
| 14 | type TypeId = typeof TypeId; |
| 15 | |
| 16 | export interface IndicatorFeedProps { |
| 17 | /** |
| 18 | * The name of the indicator feed. Not unique on Cloudflare's side, but |
| 19 | * used as the cold-state recovery identity, so keep it unique within the |
| 20 | * account. If omitted, a unique name is generated from the app, stage, |
| 21 | * and logical ID. |
| 22 | * @default ${app}-${stage}-${id} |
| 23 | */ |
| 24 | name?: string; |
| 25 | /** |
| 26 | * Human-readable description of the feed. |
| 27 | */ |
| 28 | description?: string; |
| 29 | /** |
| 30 | * Whether the indicator feed can be attributed to a provider (consumers |
| 31 | * see who published it). |
| 32 | * @default false |
| 33 | */ |
| 34 | isAttributable?: boolean; |
| 35 | /** |
| 36 | * Whether the indicator feed data can be downloaded by consumers. |
| 37 | * @default false |
| 38 | */ |
| 39 | isDownloadable?: boolean; |
| 40 | /** |
| 41 | * Whether the indicator feed is exposed to customers (publicly listed). |
| 42 | * @default false |
| 43 | */ |
| 44 | isPublic?: boolean; |
| 45 | /** |
| 46 | * Inline STIX 2.x content for the feed's snapshot. When provided, the |
| 47 | * content is uploaded via the snapshot endpoint whenever it changes |
| 48 | * (tracked by content hash). Cloudflare processes uploads asynchronously |
| 49 | * — see the `latestUploadStatus` attribute. |
| 50 | */ |
| 51 | snapshot?: string; |
| 52 | } |
| 53 | |
| 54 | export interface IndicatorFeedAttributes { |
| 55 | /** The server-assigned numeric identifier for the indicator feed. */ |
| 56 | feedId: number; |
| 57 | /** The Cloudflare account the feed belongs to. */ |
| 58 | accountId: string; |
| 59 | /** The name of the indicator feed. */ |
| 60 | name: string; |
| 61 | /** The description of the indicator feed. */ |
| 62 | description: string | undefined; |
| 63 | /** Whether the feed can be attributed to a provider. */ |
| 64 | isAttributable: boolean; |
| 65 | /** Whether the feed data can be downloaded by consumers. */ |
| 66 | isDownloadable: boolean; |
| 67 | /** Whether the feed is exposed to customers. */ |
| 68 | isPublic: boolean; |
| 69 | /** When the feed was created. */ |
| 70 | createdOn: string | undefined; |
| 71 | /** When the feed was last modified. */ |
| 72 | modifiedOn: string | undefined; |
| 73 | /** |
| 74 | * Status of the latest snapshot upload (`Mirroring`, `Unifying`, |
| 75 | * `Loading`, `Provisioning`, `Complete`, or `Error`), if any. |
| 76 | */ |
| 77 | latestUploadStatus: string | undefined; |
| 78 | /** |
| 79 | * SHA-256 hash of the last snapshot content uploaded by this provider. |
| 80 | * Used to skip re-uploading unchanged content. |
| 81 | */ |
| 82 | snapshotHash: string | undefined; |
| 83 | } |
| 84 | |
| 85 | export type IndicatorFeed = Resource< |
| 86 | TypeId, |
| 87 | IndicatorFeedProps, |
| 88 | IndicatorFeedAttributes, |
| 89 | never, |
| 90 | Providers |
| 91 | >; |
| 92 | |
| 93 | /** |
| 94 | * A Cloudflare custom Indicator Feed (Cloudforce One threat intelligence). |
| 95 | * |
| 96 | * Indicator feeds let approved accounts publish their own threat-intel |
| 97 | * indicators (domains, IPs, URLs) that consumer accounts can subscribe to |
| 98 | * via Gateway or download directly. Creating feeds requires the account to |
| 99 | * be approved as a feed provider (a Cloudforce One entitlement) — without |
| 100 | * it, creation fails with the typed `IndicatorFeedsNotEntitled` error. |
| 101 | * |
| 102 | * :::warning |
| 103 | * Cloudflare's API exposes **no delete endpoint** for indicator feeds. |
| 104 | * Destroying this resource orphans the feed on Cloudflare's side (a warning |
| 105 | * is logged). To avoid leaking feeds across deployments, the provider |
| 106 | * adopts an existing feed with the same name instead of creating a |
| 107 | * duplicate. |
| 108 | * ::: |
| 109 | * ### Creating a Feed |
| 110 | * **Example:** Basic feed |
| 111 | * ```typescript |
| 112 | * const feed = yield* Cloudflare.Intel.IndicatorFeed("threat-feed", { |
| 113 | * description: "Indicators observed by our honeypots", |
| 114 | * }); |
| 115 | * ``` |
| 116 | * |
| 117 | * **Example:** Public, downloadable feed |
| 118 | * ```typescript |
| 119 | * const feed = yield* Cloudflare.Intel.IndicatorFeed("public-feed", { |
| 120 | * name: "acme-public-indicators", |
| 121 | * description: "Acme Corp public threat indicators", |
| 122 | * isPublic: true, |
| 123 | * isDownloadable: true, |
| 124 | * isAttributable: true, |
| 125 | * }); |
| 126 | * ``` |
| 127 | * |
| 128 | * ### Publishing Indicators |
| 129 | * **Example:** Upload a STIX 2.x snapshot inline |
| 130 | * ```typescript |
| 131 | * const feed = yield* Cloudflare.Intel.IndicatorFeed("threat-feed", { |
| 132 | * description: "Indicators observed by our honeypots", |
| 133 | * snapshot: JSON.stringify({ |
| 134 | * type: "bundle", |
| 135 | * id: "bundle--0a242344-3c0b-4fdb-9f59-3e8c4a4f6b3a", |
| 136 | * objects: [], |
| 137 | * }), |
| 138 | * }); |
| 139 | * ``` |
| 140 | * |
| 141 | * ### Sharing a Feed |
| 142 | * **Example:** Grant another account access |
| 143 | * ```typescript |
| 144 | * yield* Cloudflare.Intel.IndicatorFeedPermission("partner-access", { |
| 145 | * feedId: feed.feedId, |
| 146 | * accountTag: "023e105f4ecef8ad9ca31a8372d0c353", |
| 147 | * }); |
| 148 | * ``` |
| 149 | * |
| 150 | * @see https://developers.cloudflare.com/security-center/indicator-feeds/ |
| 151 | * |
| 152 | * @resource |
| 153 | * @product Intel |
| 154 | * @category Observability & Analytics |
| 155 | */ |
| 156 | export const IndicatorFeed = Resource<IndicatorFeed>(TypeId); |
| 157 | |
| 158 | /** |
| 159 | * Returns true if the given value is an IndicatorFeed resource. |
| 160 | */ |
| 161 | export const isIndicatorFeed = (value: unknown): value is IndicatorFeed => |
| 162 | Predicate.hasProperty(value, "Type") && value.Type === TypeId; |
| 163 | |
| 164 | export const IndicatorFeedProvider = () => |
| 165 | Provider.succeed(IndicatorFeed, { |
| 166 | stables: ["feedId", "accountId", "createdOn"], |
| 167 | |
| 168 | // Account collection — enumerate every indicator feed owned by the |
| 169 | // ambient account. The list endpoint returns a thin row (no |
| 170 | // `latestUploadStatus`), so hydrate each id via `getFeed` to produce the |
| 171 | // exact `read` Attributes shape. Accounts without the Cloudforce One feed |
| 172 | // entitlement are rejected with the typed `Forbidden` tag — treat that as |
| 173 | // an empty collection rather than failing the enumeration. |
| 174 | list: Effect.fn(function* () { |
| 175 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 176 | const ids = yield* intel.listIndicatorFeeds.pages({ accountId }).pipe( |
| 177 | Stream.runCollect, |
| 178 | Effect.map((chunk) => |
| 179 | Array.from(chunk).flatMap((page) => |
| 180 | (page.result ?? []).map((f) => f.id).filter((id): id is number => id != null), |
| 181 | ), |
| 182 | ), |
| 183 | Effect.catchTag("Forbidden", () => Effect.succeed([] as number[])), |
| 184 | ); |
| 185 | const rows = yield* Effect.forEach( |
| 186 | ids, |
| 187 | (feedId) => |
| 188 | getFeed(accountId, feedId).pipe( |
| 189 | Effect.map((observed) => |
| 190 | observed ? toAttributes(observed, accountId, undefined) : undefined, |
| 191 | ), |
| 192 | // A feed may vanish between list and get, or the account may |
| 193 | // lack access to an individual feed — skip either case. |
| 194 | Effect.catchTag("Forbidden", () => Effect.undefined), |
| 195 | ), |
| 196 | { concurrency: 10 }, |
| 197 | ); |
| 198 | return rows.filter((row): row is IndicatorFeedAttributes => row !== undefined); |
| 199 | }), |
| 200 | |
| 201 | diff: Effect.fn(function* ({ news, output }) { |
| 202 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 203 | if (!isResolved(news)) return undefined; |
| 204 | // Feeds cannot move between accounts (and cannot be deleted, so a |
| 205 | // replacement would orphan the old feed) — but a different target |
| 206 | // account still means a different physical resource. |
| 207 | if ((output?.accountId ?? accountId) !== accountId) { |
| 208 | return { action: "replace" } as const; |
| 209 | } |
| 210 | return undefined; |
| 211 | }), |
| 212 | |
| 213 | read: Effect.fn(function* ({ id, output, olds }) { |
| 214 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 215 | const acct = output?.accountId ?? accountId; |
| 216 | |
| 217 | if (output?.feedId !== undefined) { |
| 218 | const observed = yield* getFeed(acct, output.feedId); |
| 219 | return observed ? toAttributes(observed, acct, output.snapshotHash) : undefined; |
| 220 | } |
| 221 | // Cold read — recover from lost state by matching the deterministic |
| 222 | // physical name. Names are not unique on Cloudflare's side; an exact |
| 223 | // match on our generated/explicit name is the best identity we have. |
| 224 | const name = yield* createFeedName(id, olds?.name); |
| 225 | const match = yield* findByName(acct, name); |
| 226 | if (match?.id != null) { |
| 227 | const observed = yield* getFeed(acct, match.id); |
| 228 | return observed ? toAttributes(observed, acct, undefined) : undefined; |
| 229 | } |
| 230 | return undefined; |
| 231 | }), |
| 232 | |
| 233 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 234 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 235 | const name = yield* createFeedName(id, news.name); |
| 236 | |
| 237 | // Observe — the feedId cached on `output` is a hint, not a |
| 238 | // guarantee. Because feeds can never be deleted, a missing cache |
| 239 | // falls back to a lookup by name so reruns adopt the existing feed |
| 240 | // instead of leaking a duplicate. |
| 241 | let observed = |
| 242 | output?.feedId !== undefined |
| 243 | ? yield* getFeed(output.accountId ?? accountId, output.feedId) |
| 244 | : undefined; |
| 245 | if (!observed) { |
| 246 | const match = yield* findByName(accountId, name); |
| 247 | if (match?.id != null) { |
| 248 | observed = yield* getFeed(accountId, match.id); |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | // Ensure — greenfield: create the feed with name + description; the |
| 253 | // visibility flags are only settable via update, so fall through to |
| 254 | // the sync step with the freshly observed state. |
| 255 | if (!observed) { |
| 256 | const created = yield* intel.createIndicatorFeed({ |
| 257 | accountId, |
| 258 | name, |
| 259 | description: news.description, |
| 260 | }); |
| 261 | if (created.id == null) { |
| 262 | // The create response is fully optional in the API schema; fall |
| 263 | // back to the by-name lookup for the id we just created. |
| 264 | const match = yield* findByName(accountId, name); |
| 265 | observed = match?.id != null ? yield* getFeed(accountId, match.id) : undefined; |
| 266 | } else { |
| 267 | observed = yield* getFeed(accountId, created.id); |
| 268 | } |
| 269 | } |
| 270 | if (!observed || observed.id == null) { |
| 271 | return yield* intel.IndicatorFeedNotFound.make({ |
| 272 | code: 0, |
| 273 | message: `Indicator feed "${name}" was not observable after creation`, |
| 274 | }); |
| 275 | } |
| 276 | const feedId = observed.id; |
| 277 | |
| 278 | // Sync — diff observed cloud state against desired settings and |
| 279 | // apply only when dirty. |
| 280 | const desired = { |
| 281 | name, |
| 282 | description: news.description, |
| 283 | isAttributable: news.isAttributable ?? false, |
| 284 | isDownloadable: news.isDownloadable ?? false, |
| 285 | isPublic: news.isPublic ?? false, |
| 286 | }; |
| 287 | const dirty = |
| 288 | (observed.name ?? undefined) !== desired.name || |
| 289 | (news.description !== undefined && |
| 290 | (observed.description ?? undefined) !== desired.description) || |
| 291 | (observed.isAttributable ?? false) !== desired.isAttributable || |
| 292 | (observed.isDownloadable ?? false) !== desired.isDownloadable || |
| 293 | (observed.isPublic ?? false) !== desired.isPublic; |
| 294 | if (dirty) { |
| 295 | yield* intel.updateIndicatorFeed({ |
| 296 | accountId, |
| 297 | feedId, |
| 298 | ...desired, |
| 299 | }); |
| 300 | } |
| 301 | |
| 302 | // Sync snapshot — upload inline STIX content whenever its hash |
| 303 | // differs from what we last uploaded. Uploads are processed |
| 304 | // asynchronously by Cloudflare (see `latestUploadStatus`). |
| 305 | let snapshotHash = output?.snapshotHash; |
| 306 | if (news.snapshot !== undefined) { |
| 307 | const hash = yield* sha256(news.snapshot); |
| 308 | if (hash !== output?.snapshotHash) { |
| 309 | yield* intel.putIndicatorFeedSnapshot({ |
| 310 | accountId, |
| 311 | feedId, |
| 312 | source: news.snapshot, |
| 313 | }); |
| 314 | } |
| 315 | snapshotHash = hash; |
| 316 | } |
| 317 | |
| 318 | const final = yield* getFeed(accountId, feedId); |
| 319 | if (!final) { |
| 320 | return yield* intel.IndicatorFeedNotFound.make({ |
| 321 | code: 0, |
| 322 | message: `Indicator feed ${feedId} disappeared during reconcile`, |
| 323 | }); |
| 324 | } |
| 325 | return toAttributes(final, accountId, snapshotHash); |
| 326 | }), |
| 327 | |
| 328 | delete: Effect.fn(function* ({ output }) { |
| 329 | // Cloudflare's API has no delete endpoint for indicator feeds — the |
| 330 | // feed is orphaned on the account. Reconcile adopts same-named feeds, |
| 331 | // so re-creating this resource later reuses the orphan. |
| 332 | yield* Effect.logWarning( |
| 333 | `Cloudflare indicator feeds cannot be deleted via the API — ` + |
| 334 | `feed ${output.feedId} ("${output.name}") on account ` + |
| 335 | `${output.accountId} is left in place.`, |
| 336 | ); |
| 337 | }), |
| 338 | }); |
| 339 | |
| 340 | type ObservedFeed = intel.GetIndicatorFeedResponse; |
| 341 | |
| 342 | /** |
| 343 | * Read a feed by id, mapping "gone" — Cloudflare answers HTTP 403 with |
| 344 | * "Feed N does not exist or this account does not have access", surfaced |
| 345 | * as the typed `IndicatorFeedNotFound` — to `undefined`. |
| 346 | */ |
| 347 | const getFeed = (accountId: string, feedId: number) => |
| 348 | intel.getIndicatorFeed({ accountId, feedId }).pipe( |
| 349 | Effect.map((f): ObservedFeed | undefined => f), |
| 350 | Effect.catchTag("IndicatorFeedNotFound", () => Effect.undefined), |
| 351 | ); |
| 352 | |
| 353 | /** |
| 354 | * Find a feed by exact name. The list endpoint has no filter, so match |
| 355 | * client-side; if several feeds carry the same name, pick the oldest for |
| 356 | * determinism. |
| 357 | */ |
| 358 | const findByName = (accountId: string, name: string) => |
| 359 | intel.listIndicatorFeeds.items({ accountId }).pipe( |
| 360 | Stream.filter((f) => f.name === name), |
| 361 | Stream.runCollect, |
| 362 | Effect.map((chunk) => |
| 363 | Array.from(chunk) |
| 364 | .sort((a, b) => (a.createdOn ?? "").localeCompare(b.createdOn ?? "")) |
| 365 | .at(0), |
| 366 | ), |
| 367 | ); |
| 368 | |
| 369 | const createFeedName = (id: string, name: string | undefined) => |
| 370 | Effect.gen(function* () { |
| 371 | return name ?? (yield* createPhysicalName({ id, lowercase: true })); |
| 372 | }); |
| 373 | |
| 374 | const sha256 = (content: string) => |
| 375 | Effect.sync(() => crypto.createHash("sha256").update(content).digest("hex")); |
| 376 | |
| 377 | const toAttributes = ( |
| 378 | feed: ObservedFeed, |
| 379 | accountId: string, |
| 380 | snapshotHash: string | undefined, |
| 381 | ): IndicatorFeedAttributes => ({ |
| 382 | feedId: feed.id ?? 0, |
| 383 | accountId, |
| 384 | name: feed.name ?? "", |
| 385 | description: feed.description ?? undefined, |
| 386 | isAttributable: feed.isAttributable ?? false, |
| 387 | isDownloadable: feed.isDownloadable ?? false, |
| 388 | isPublic: feed.isPublic ?? false, |
| 389 | createdOn: feed.createdOn ?? undefined, |
| 390 | modifiedOn: feed.modifiedOn ?? undefined, |
| 391 | latestUploadStatus: feed.latestUploadStatus ?? undefined, |
| 392 | snapshotHash, |
| 393 | }); |