@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

main
ts 251 lines 10.7 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
3 import { findZoneByName } from "@alchemy.run/cloudflare/Zone/lookup";
4 import { describe, expect } from "@alchemy.run/test";
5 import * as Test from "@alchemy.run/test/Alchemy";
6 import * as fraud from "@distilled.cloud/cloudflare/fraud";
7 import * as Provider from "alchemy/Provider";
8 import * as Effect from "effect/Effect";
9 import { MinimumLogLevel } from "effect/References";
10 import * as Schedule from "effect/Schedule";
11 const { test } = Test.make({ providers: Cloudflare.providers() });
12
13 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
14
15 const zoneName = process.env.CLOUDFLARE_TEST_DNS_ZONE_NAME ?? "alchemy-test-2.us";
16
17 // Fraud Detection (User Profiles) is a beta, subscription-gated product.
18 // On the standard testing zone any meaningful PUT (writing `user_profiles`,
19 // non-empty `username_expressions`, or `authentication_settings`) fails with
20 // Cloudflare error code 10400 — "A fraud detection subscription is required"
21 // — surfaced as the typed `FraudDetectionNotEntitled` error. The full
22 // write lifecycle test below is gated behind an entitled zone via env.
23 const entitled = !!process.env.CLOUDFLARE_TEST_FRAUD_DETECTION;
24
25 const resolveZoneId = Effect.gen(function* () {
26 const { accountId } = yield* yield* CloudflareEnvironment;
27 const zone = yield* findZoneByName({ accountId, name: zoneName });
28 if (!zone) {
29 return yield* Effect.die(new Error(`zone "${zoneName}" not found in account`));
30 }
31 return zone.id;
32 });
33
34 // The scoped API token the test harness mints propagates eventually-
35 // consistently across Cloudflare's edge — ride out 403 blips (`Forbidden`,
36 // declared in the distilled error union) on out-of-band verification calls.
37 const getSettings = (zoneId: string) =>
38 fraud.getFraud({ zoneId }).pipe(
39 Effect.retry({
40 while: (e) => e._tag === "Forbidden",
41 schedule: Schedule.exponential("500 millis"),
42 times: 8,
43 }),
44 );
45
46 // Both cases mutate the same zone-level fraud-detection settings singleton; run them serially so they don't corrupt each other's captured baseline under the global concurrent test config.
47 describe.sequential(
48 "DetectionSettings",
49 {
50 tags: ["provider:cloudflare", "provider:cloudflare:fraud", "provider:cloudflare:zone", "live"],
51 },
52 () => {
53 test.provider(
54 "adopts the zone singleton without writing and restores nothing on destroy",
55 (stack) =>
56 Effect.gen(function* () {
57 const zoneId = yield* resolveZoneId;
58
59 yield* stack.destroy();
60
61 const before = yield* getSettings(zoneId);
62
63 // 1. Create — adopt the singleton with no settings set: reconcile
64 // observes but never PUTs.
65 const adopted = yield* stack.deploy(
66 Effect.gen(function* () {
67 return yield* Cloudflare.Fraud.DetectionSettings("Fraud", { zoneId });
68 }),
69 );
70 expect(adopted.zoneId).toEqual(zoneId);
71 // The snapshot captured the pre-management state.
72 expect(adopted.initialSettings.userProfiles ?? null).toEqual(before.userProfiles ?? null);
73 expect(adopted.initialSettings.usernameExpressions ?? null).toEqual(
74 before.usernameExpressions ?? null,
75 );
76
77 const afterDeploy = yield* getSettings(zoneId);
78 expect(afterDeploy.userProfiles ?? null).toEqual(before.userProfiles ?? null);
79 expect(afterDeploy.usernameExpressions ?? null).toEqual(
80 before.usernameExpressions ?? null,
81 );
82
83 // 2. In-place update — set `usernameExpressions` to the value the
84 // zone already has: reconcile diffs observed vs desired and
85 // skips the PUT (which would otherwise require a subscription).
86 const updated = yield* stack.deploy(
87 Effect.gen(function* () {
88 return yield* Cloudflare.Fraud.DetectionSettings("Fraud", {
89 zoneId,
90 usernameExpressions: [...(before.usernameExpressions ?? [])],
91 });
92 }),
93 );
94 expect(updated.zoneId).toEqual(zoneId);
95 expect(updated.usernameExpressions ?? []).toEqual(before.usernameExpressions ?? []);
96 // The initial snapshot stays sticky across updates.
97 expect(updated.initialSettings.userProfiles ?? null).toEqual(before.userProfiles ?? null);
98
99 // 3. Destroy — nothing was written, so nothing is restored and the
100 // live settings are untouched.
101 yield* stack.destroy();
102
103 const afterDestroy = yield* getSettings(zoneId);
104 expect(afterDestroy.userProfiles ?? null).toEqual(before.userProfiles ?? null);
105 expect(afterDestroy.usernameExpressions ?? null).toEqual(
106 before.usernameExpressions ?? null,
107 );
108 }).pipe(logLevel),
109 { timeout: 120_000 },
110 );
111
112 // Unentitlement probe — pins the typed FraudDetectionNotEntitled rejection (code 10400)
113 // and skips on entitled zones, where the PUT would succeed and mutate live settings.
114 test.provider.skipIf(entitled)(
115 "surfaces the typed FraudDetectionNotEntitled error on unentitled zones",
116 (stack) =>
117 Effect.gen(function* () {
118 const zoneId = yield* resolveZoneId;
119
120 yield* stack.destroy();
121
122 // Writing `user_profiles` (even "disabled") requires a fraud
123 // detection subscription — the distilled PUT must fail with the
124 // typed entitlement tag (Cloudflare error code 10400). Reads on the
125 // same zone succeed, proving the gate is on writes, not the token.
126 const error = yield* fraud.putFraud({ zoneId, userProfiles: "disabled" }).pipe(
127 Effect.retry({
128 while: (e) => e._tag === "Forbidden",
129 schedule: Schedule.exponential("500 millis"),
130 times: 8,
131 }),
132 Effect.flip,
133 );
134 expect(error._tag).toEqual("FraudDetectionNotEntitled");
135
136 const settings = yield* getSettings(zoneId);
137 expect(settings.userProfiles ?? "disabled").toEqual(settings.userProfiles ?? "disabled");
138
139 yield* stack.destroy();
140 }).pipe(logLevel),
141 { timeout: 120_000 },
142 );
143
144 // Requires a zone with a Fraud Detection (beta) subscription — unentitled zones fail with
145 // the typed FraudDetectionNotEntitled (code 10400). Unlock with CLOUDFLARE_TEST_FRAUD_DETECTION=1.
146 test.provider.skipIf(!entitled)(
147 "manages fraud detection settings and restores them on destroy",
148 (stack) =>
149 Effect.gen(function* () {
150 const zoneId = yield* resolveZoneId;
151
152 yield* stack.destroy();
153
154 const original = yield* getSettings(zoneId);
155
156 const expression = 'lookup_json_string(http.request.body.raw, "username")';
157
158 yield* Effect.gen(function* () {
159 // 1. Create — enable user profiles with one username expression.
160 const created = yield* stack.deploy(
161 Effect.gen(function* () {
162 return yield* Cloudflare.Fraud.DetectionSettings("Fraud", {
163 zoneId,
164 userProfiles: "enabled",
165 usernameExpressions: [expression],
166 });
167 }),
168 );
169 expect(created.zoneId).toEqual(zoneId);
170 expect(created.userProfiles).toEqual("enabled");
171 expect(created.usernameExpressions).toEqual([expression]);
172 expect(created.initialSettings.userProfiles ?? null).toEqual(
173 original.userProfiles ?? null,
174 );
175
176 const live1 = yield* getSettings(zoneId);
177 expect(live1.userProfiles).toEqual("enabled");
178 expect(live1.usernameExpressions).toEqual([expression]);
179
180 // 2. In-place update — add authentication outcome classification;
181 // same singleton (same zoneId), sticky snapshot.
182 const updated = yield* stack.deploy(
183 Effect.gen(function* () {
184 return yield* Cloudflare.Fraud.DetectionSettings("Fraud", {
185 zoneId,
186 userProfiles: "enabled",
187 usernameExpressions: [expression],
188 authenticationSettings: {
189 successCriteria: { kind: "status_code", statusCodes: [200] },
190 failureCriteria: { kind: "status_code", statusCodes: [401, 403] },
191 },
192 });
193 }),
194 );
195 expect(updated.authenticationSettings?.successCriteria).toEqual({
196 kind: "status_code",
197 statusCodes: [200],
198 });
199 expect(updated.initialSettings.userProfiles ?? null).toEqual(
200 original.userProfiles ?? null,
201 );
202
203 const live2 = yield* getSettings(zoneId);
204 expect(live2.authenticationSettings?.successCriteria?.statusCodes).toEqual([200]);
205
206 // 3. Destroy — the managed fields are restored to the snapshot.
207 yield* stack.destroy();
208
209 const after = yield* getSettings(zoneId);
210 expect(after.userProfiles ?? null).toEqual(original.userProfiles ?? null);
211 expect(after.usernameExpressions ?? null).toEqual(original.usernameExpressions ?? null);
212 }).pipe(
213 Effect.ensuring(
214 fraud
215 .putFraud({
216 zoneId,
217 userProfiles: original.userProfiles === "enabled" ? "enabled" : "disabled",
218 usernameExpressions: [...(original.usernameExpressions ?? [])],
219 })
220 .pipe(Effect.ignore),
221 ),
222 );
223
224 yield* stack.destroy();
225 }).pipe(logLevel),
226 { timeout: 240_000 },
227 );
228
229 // Canonical `list()` test (zone-scoped singleton): there is no account-wide
230 // API for this per-zone setting, so `list()` enumerates every zone via
231 // `listAllZones` and reads the singleton in each. `getFraud` is a read and
232 // never trips the entitlement gate (which lives on `putFraud`), so this
233 // read-only assertion always runs. Assert the result is non-empty and
234 // contains the standing test zone.
235 test.provider("list enumerates the settings across all zones", (stack) =>
236 Effect.gen(function* () {
237 const zoneId = yield* resolveZoneId;
238
239 const provider = yield* Provider.findProvider(Cloudflare.Fraud.DetectionSettings);
240 const all = yield* provider.list();
241
242 expect(all.length).toBeGreaterThan(0);
243 expect(all.some((s) => s.zoneId === zoneId)).toBe(true);
244
245 // `stack` is unused here (the singleton always exists on every zone),
246 // but keep the destroy bookend so the harness state stays clean.
247 yield* stack.destroy();
248 }).pipe(logLevel),
249 );
250 },
251 );