@homeflare/alchemy 0.48.0 → 0.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/README.md +11 -0
  2. package/dist/cloudflare/cloudflared-tunnel-api.d.ts +87 -0
  3. package/dist/cloudflare/cloudflared-tunnel-api.d.ts.map +1 -0
  4. package/dist/cloudflare/cloudflared-tunnel-form.d.ts +49 -0
  5. package/dist/cloudflare/cloudflared-tunnel-form.d.ts.map +1 -0
  6. package/dist/cloudflare/cloudflared-tunnel-harness.d.ts +45 -0
  7. package/dist/cloudflare/cloudflared-tunnel-harness.d.ts.map +1 -0
  8. package/dist/cloudflare/cloudflared-tunnel-lifecycle.d.ts +21 -0
  9. package/dist/cloudflare/cloudflared-tunnel-lifecycle.d.ts.map +1 -0
  10. package/dist/cloudflare/cloudflared-tunnel.d.ts +39 -0
  11. package/dist/cloudflare/cloudflared-tunnel.d.ts.map +1 -0
  12. package/dist/cloudflare/fake-access.d.ts +40 -0
  13. package/dist/cloudflare/fake-access.d.ts.map +1 -0
  14. package/dist/cloudflare/fake-mesh.d.ts +7 -2
  15. package/dist/cloudflare/fake-mesh.d.ts.map +1 -1
  16. package/dist/cloudflare/fake-tunnel.d.ts +48 -0
  17. package/dist/cloudflare/fake-tunnel.d.ts.map +1 -0
  18. package/dist/cloudflare/index.d.ts +15 -4
  19. package/dist/cloudflare/index.d.ts.map +1 -1
  20. package/dist/cloudflare/index.js +518 -7
  21. package/dist/cloudflare/index.js.map +15 -4
  22. package/dist/cloudflare/providers.d.ts +1 -1
  23. package/dist/cloudflare/providers.d.ts.map +1 -1
  24. package/dist/cloudflare/saas-oidc-api.d.ts +88 -0
  25. package/dist/cloudflare/saas-oidc-api.d.ts.map +1 -0
  26. package/dist/cloudflare/saas-oidc-consumer.d.ts +22 -0
  27. package/dist/cloudflare/saas-oidc-consumer.d.ts.map +1 -0
  28. package/dist/cloudflare/saas-oidc-error.d.ts +22 -0
  29. package/dist/cloudflare/saas-oidc-error.d.ts.map +1 -0
  30. package/dist/cloudflare/saas-oidc-form.d.ts +48 -0
  31. package/dist/cloudflare/saas-oidc-form.d.ts.map +1 -0
  32. package/dist/cloudflare/saas-oidc-harness.d.ts +50 -0
  33. package/dist/cloudflare/saas-oidc-harness.d.ts.map +1 -0
  34. package/dist/cloudflare/saas-oidc-lifecycle.d.ts +14 -0
  35. package/dist/cloudflare/saas-oidc-lifecycle.d.ts.map +1 -0
  36. package/dist/cloudflare/saas-oidc-props.d.ts +139 -0
  37. package/dist/cloudflare/saas-oidc-props.d.ts.map +1 -0
  38. package/dist/cloudflare/saas-oidc-team.d.ts +9 -0
  39. package/dist/cloudflare/saas-oidc-team.d.ts.map +1 -0
  40. package/dist/cloudflare/saas-oidc-wire.d.ts +58 -0
  41. package/dist/cloudflare/saas-oidc-wire.d.ts.map +1 -0
  42. package/dist/cloudflare/saas-oidc.d.ts +36 -0
  43. package/dist/cloudflare/saas-oidc.d.ts.map +1 -0
  44. package/dist/talos/cluster-adapter-errors.d.ts.map +1 -1
  45. package/dist/talos/cluster-adapter.d.ts +2 -1
  46. package/dist/talos/cluster-adapter.d.ts.map +1 -1
  47. package/dist/talos/index.js +19 -8
  48. package/dist/talos/index.js.map +6 -6
  49. package/dist/talos/mint-temp-file.d.ts.map +1 -1
  50. package/dist/talos/talosctl.d.ts +29 -0
  51. package/dist/talos/talosctl.d.ts.map +1 -1
  52. package/docs/cloudflared-tunnel.md +136 -0
  53. package/docs/credentials.md +1 -1
  54. package/docs/ownership.md +3 -2
  55. package/docs/saas-oidc.md +185 -0
  56. package/docs/talos-openbao-adapter.md +3 -2
  57. package/docs/upstream-conformance-families.md +1 -1
  58. package/docs/upstream-conformance.md +3 -0
  59. package/package.json +1 -1
  60. package/src/cloudflare/cloudflared-tunnel-api.ts +150 -0
  61. package/src/cloudflare/cloudflared-tunnel-edges.test.ts +179 -0
  62. package/src/cloudflare/cloudflared-tunnel-form.ts +78 -0
  63. package/src/cloudflare/cloudflared-tunnel-harness.ts +126 -0
  64. package/src/cloudflare/cloudflared-tunnel-lifecycle.ts +146 -0
  65. package/src/cloudflare/cloudflared-tunnel-state.test.ts +104 -0
  66. package/src/cloudflare/cloudflared-tunnel.test.ts +164 -0
  67. package/src/cloudflare/cloudflared-tunnel.ts +116 -0
  68. package/src/cloudflare/fake-access.ts +196 -0
  69. package/src/cloudflare/fake-mesh.ts +6 -3
  70. package/src/cloudflare/fake-tunnel.ts +148 -0
  71. package/src/cloudflare/index.ts +27 -4
  72. package/src/cloudflare/providers.ts +16 -3
  73. package/src/cloudflare/saas-oidc-api.ts +224 -0
  74. package/src/cloudflare/saas-oidc-consumer.ts +35 -0
  75. package/src/cloudflare/saas-oidc-error.ts +52 -0
  76. package/src/cloudflare/saas-oidc-form.test.ts +227 -0
  77. package/src/cloudflare/saas-oidc-form.ts +190 -0
  78. package/src/cloudflare/saas-oidc-harness.ts +140 -0
  79. package/src/cloudflare/saas-oidc-lifecycle.ts +150 -0
  80. package/src/cloudflare/saas-oidc-parse-error.test.ts +180 -0
  81. package/src/cloudflare/saas-oidc-props.ts +147 -0
  82. package/src/cloudflare/saas-oidc-read.test.ts +85 -0
  83. package/src/cloudflare/saas-oidc-stable.test.ts +38 -0
  84. package/src/cloudflare/saas-oidc-state.test.ts +128 -0
  85. package/src/cloudflare/saas-oidc-team.test.ts +88 -0
  86. package/src/cloudflare/saas-oidc-team.ts +70 -0
  87. package/src/cloudflare/saas-oidc-wire.ts +116 -0
  88. package/src/cloudflare/saas-oidc.test.ts +201 -0
  89. package/src/cloudflare/saas-oidc.ts +107 -0
  90. package/src/talos/cluster-adapter-errors.ts +2 -1
  91. package/src/talos/cluster-adapter-move.test.ts +2 -0
  92. package/src/talos/cluster-adapter.ts +2 -1
  93. package/src/talos/mint-temp-file.test.ts +44 -0
  94. package/src/talos/mint-temp-file.ts +16 -4
  95. package/src/talos/talosctl-probe-kill.test.ts +56 -0
  96. package/src/talos/talosctl.test.ts +54 -1
  97. package/src/talos/talosctl.ts +34 -2
@@ -0,0 +1,164 @@
1
+ /**
2
+ * CloudflaredTunnelProvider against a fake Cloudflare (fake-tunnel.ts), its handlers called the way
3
+ * the engine calls them.
4
+ *
5
+ * ⛔ THE ASSERTION THAT MATTERS MOST: no lifecycle handler ever requests `/token`, and nothing the
6
+ * provider returns contains the tunnel token — even though the fake puts one on every wire object.
7
+ */
8
+ import { describe, expect, test } from 'bun:test';
9
+ import { Unowned } from 'alchemy/AdoptPolicy';
10
+ import type { StackServices } from 'alchemy/Stack';
11
+ import * as Effect from 'effect/Effect';
12
+ import type * as Layer from 'effect/Layer';
13
+ import {
14
+ diff,
15
+ extra,
16
+ ids,
17
+ read,
18
+ reconcile,
19
+ run,
20
+ stored,
21
+ tokenReads,
22
+ writes,
23
+ } from './cloudflared-tunnel-harness.ts';
24
+ import { FAKE_ACCOUNT, FAKE_API_TOKEN } from './fake-mesh.ts';
25
+ import { fakeTunnels } from './fake-tunnel.ts';
26
+ import { providers } from './providers.ts';
27
+
28
+ // ⛔ Compile-time: a stack's `providers` must be `Layer<…, never, StackServices>`.
29
+ type Built = Layer.Success<ReturnType<typeof providers>>;
30
+ const _stackShaped: Layer.Layer<Built, never, StackServices> = providers();
31
+ void _stackShaped;
32
+
33
+ const props = { name: 'k8s-admin' };
34
+
35
+ describe('CloudflaredTunnelProvider', () => {
36
+ test('create sends config_src cloudflare and no secret, and the attributes carry no token', async () => {
37
+ const fake = fakeTunnels();
38
+ const out = await run(fake, (p) => reconcile(p, props));
39
+ const post = fake.seen.find((s) => s.method === 'POST');
40
+ expect(post?.body).toEqual({ name: 'k8s-admin', config_src: 'cloudflare' });
41
+ expect(out).toMatchObject({ name: 'k8s-admin', accountId: FAKE_ACCOUNT });
42
+ expect(Object.keys(out).sort()).toEqual(['accountId', 'id', 'name']);
43
+ expect(JSON.stringify(out)).not.toContain('fake-tunnel-token');
44
+ expect(tokenReads(fake)).toBe(0);
45
+ expect(new Set(fake.auth)).toEqual(new Set([`Bearer ${FAKE_API_TOKEN}`]));
46
+ });
47
+
48
+ test('read with state refreshes by id; without state it adopts by exact name, Unowned', async () => {
49
+ const fake = fakeTunnels();
50
+ fake.seed({ name: 'k8s-admin-old' });
51
+ fake.seed({ name: 'k8s-admin-older' });
52
+ const tunnel = fake.seed({ name: 'k8s-admin', status: 'healthy' });
53
+ const [owned, probe] = await run(fake, (p) =>
54
+ Effect.gen(function* () {
55
+ const output = stored(FAKE_ACCOUNT, { id: tunnel.id });
56
+ return [yield* read(p, props, output), yield* read(p, props)] as const;
57
+ }),
58
+ );
59
+ expect(Unowned.is(owned)).toBe(false);
60
+ expect(owned).toMatchObject({ id: tunnel.id, name: 'k8s-admin' });
61
+ expect(Unowned.is(probe)).toBe(true);
62
+ expect(probe).toMatchObject({ id: tunnel.id, name: 'k8s-admin' });
63
+ expect(tokenReads(fake)).toBe(0);
64
+ expect(writes(fake)).toEqual([]);
65
+ });
66
+
67
+ test('adopting twice is idempotent: the second reconcile over the adopted row writes nothing', async () => {
68
+ const fake = fakeTunnels();
69
+ const tunnel = fake.seed({ name: 'k8s-admin', status: 'healthy' });
70
+ const [first, second] = await run(fake, (p) =>
71
+ Effect.gen(function* () {
72
+ const adopted = yield* read(p, props);
73
+ expect(Unowned.is(adopted)).toBe(true);
74
+ const first = yield* reconcile(p, props, adopted);
75
+ return [first, yield* reconcile(p, props, first)] as const;
76
+ }),
77
+ );
78
+ expect(first).toEqual(second);
79
+ expect(first.id).toBe(tunnel.id);
80
+ expect(writes(fake)).toEqual([]);
81
+ expect(tokenReads(fake)).toBe(0);
82
+ });
83
+
84
+ test('a rename is a PATCH on the same id', async () => {
85
+ const fake = fakeTunnels();
86
+ const [first, second] = await run(fake, (p) =>
87
+ Effect.gen(function* () {
88
+ const first = yield* reconcile(p, props);
89
+ return [first, yield* reconcile(p, { name: 'k8s-admin-2' }, first)] as const;
90
+ }),
91
+ );
92
+ expect(second.id).toBe(first.id);
93
+ expect(second.name).toBe('k8s-admin-2');
94
+ expect(writes(fake)).toEqual(['POST', 'PATCH']);
95
+ expect(fake.seen.find((s) => s.method === 'PATCH')?.body).toEqual({ name: 'k8s-admin-2' });
96
+ });
97
+
98
+ test('an unchanged tunnel costs no write', async () => {
99
+ const fake = fakeTunnels();
100
+ await run(fake, (p) => Effect.flatMap(reconcile(p, props), (out) => reconcile(p, props, out)));
101
+ expect(writes(fake)).toEqual(['POST']);
102
+ });
103
+
104
+ test('a tunnel deleted out of band is created again', async () => {
105
+ const fake = fakeTunnels();
106
+ const [first, second] = await run(fake, (p) =>
107
+ Effect.gen(function* () {
108
+ const first = yield* reconcile(p, props);
109
+ const tunnel = fake.tunnels.get(first.id);
110
+ if (tunnel !== undefined) tunnel.deleted_at = '2026-10-09T02:00:00Z';
111
+ return [first, yield* reconcile(p, props, first)] as const;
112
+ }),
113
+ );
114
+ expect(second.id).not.toBe(first.id);
115
+ expect(fake.live()).toHaveLength(1);
116
+ });
117
+
118
+ test('delete removes the tunnel by id, and deleting it again sends nothing', async () => {
119
+ const fake = fakeTunnels();
120
+ await run(fake, (p) =>
121
+ Effect.gen(function* () {
122
+ const output = yield* reconcile(p, props);
123
+ yield* p.delete({ ...ids, ...extra, olds: props, output });
124
+ yield* p.delete({ ...ids, ...extra, olds: props, output });
125
+ }),
126
+ );
127
+ expect(fake.live()).toHaveLength(0);
128
+ expect(writes(fake)).toEqual(['POST', 'DELETE']);
129
+ expect(tokenReads(fake)).toBe(0);
130
+ });
131
+
132
+ test('diff reads the account from the provider environment', async () => {
133
+ const fake = fakeTunnels();
134
+ const plan = (p: Parameters<typeof diff>[0]) => diff(p, props, props, stored(FAKE_ACCOUNT));
135
+ expect(await run(fake, plan)).toBeUndefined();
136
+ expect(await run(fake, plan, '00000000000000000000000000000002')).toEqual({
137
+ action: 'replace',
138
+ });
139
+ const renamed = await run(fake, (p) =>
140
+ diff(p, { name: 'k8s-admin-2' }, props, stored(FAKE_ACCOUNT)),
141
+ );
142
+ expect(renamed).toEqual({ action: 'update' });
143
+ });
144
+
145
+ test('an invalid declaration fails the PLAN', async () => {
146
+ const fake = fakeTunnels();
147
+ const failure = await run(fake, (p) =>
148
+ Effect.flip(diff(p, { name: 'k8s-admin ' }, props, stored(FAKE_ACCOUNT))),
149
+ );
150
+ expect(String(failure)).toContain('whitespace');
151
+ expect(fake.seen).toHaveLength(0);
152
+ });
153
+
154
+ test('list is empty and nuke skips it: Alchemy Tunnel already enumerates these', async () => {
155
+ const fake = fakeTunnels();
156
+ fake.seed({ name: 'k8s-admin' });
157
+ const [listed, nuke] = await run(fake, (p) =>
158
+ Effect.map(p.list(), (rows) => [rows, p.nuke] as const),
159
+ );
160
+ expect(listed).toEqual([]);
161
+ expect(nuke).toEqual({ skip: true });
162
+ expect(fake.seen).toHaveLength(0);
163
+ });
164
+ });
@@ -0,0 +1,116 @@
1
+ /**
2
+ * `Cloudflare.CloudflaredTunnel` — a Cloudflare Tunnel (the cloudflared kind, `cfd_tunnel`),
3
+ * declared without its connector token ever touching Alchemy state. Usage: docs/cloudflared-tunnel.md.
4
+ *
5
+ * 🔴 WHY THIS EXISTS ALONGSIDE `Cloudflare.Tunnel.Tunnel`. Alchemy beta.81's resource stores the
6
+ * token as a `Redacted` attribute, and the state encoder writes it out in plaintext. See
7
+ * cloudflared-tunnel-form.ts, which also says what this resource leaves to other declarations.
8
+ *
9
+ * ★ REMOVAL POLICY: `retain` BY DEFAULT — see the ★ on `CloudflaredTunnel` below.
10
+ */
11
+ import { Credentials } from '@distilled.cloud/cloudflare/Credentials';
12
+ import * as Cloudflare from 'alchemy/Cloudflare';
13
+ import { isResolved } from 'alchemy/Diff';
14
+ import * as Provider from 'alchemy/Provider';
15
+ import { Resource, type ResourceClass } from 'alchemy/Resource';
16
+ import * as Context from 'effect/Context';
17
+ import * as Effect from 'effect/Effect';
18
+ import * as HttpClient from 'effect/http/HttpClient';
19
+ import {
20
+ type CloudflaredTunnelAttributes,
21
+ type CloudflaredTunnelProps,
22
+ diffCloudflaredTunnel,
23
+ validateCloudflaredTunnel,
24
+ } from './cloudflared-tunnel-form.ts';
25
+ import {
26
+ deleteCloudflaredTunnel,
27
+ readCloudflaredTunnel,
28
+ reconcileCloudflaredTunnel,
29
+ } from './cloudflared-tunnel-lifecycle.ts';
30
+ import type { Providers } from './providers.ts';
31
+
32
+ export interface CloudflaredTunnel extends Resource<
33
+ 'Cloudflare.CloudflaredTunnel',
34
+ CloudflaredTunnelProps,
35
+ CloudflaredTunnelAttributes,
36
+ never,
37
+ Providers
38
+ > {}
39
+
40
+ /**
41
+ * ★ `defaultRemovalPolicy: 'retain'`, LIKE EVERY KIT RESOURCE WHOSE DELETION BREAKS ITS CONSUMERS
42
+ * (MeshNode, the `Bao.*` families, `R2BucketLock`; the reasoning is written once in
43
+ * proxmox/resource.ts). Deleting a tunnel drops its remote configuration (ingress rules) and
44
+ * orphans every DNS record that targets `<id>.cfargotunnel.com`, and a new tunnel has a new id
45
+ * and a new token. So dropping the declaration, or `alchemy destroy`, leaves the tunnel live.
46
+ * ⚠️ IT ALSO SKIPS THE OLD TUNNEL'S DELETE IN AN ACCOUNT-CHANGE REPLACE (create-first), which
47
+ * leaves the old tunnel live and unmanaged (Apply.ts, `deleteOldGenerations`, beta.81).
48
+ * ⛔ `delete` STAYS FULLY IMPLEMENTED. Retain is Terraform's `prevent_destroy`, not a stub: it runs
49
+ * the moment a declaration opts in with `.pipe(RemovalPolicy.destroy())`.
50
+ */
51
+ export const CloudflaredTunnel: ResourceClass<CloudflaredTunnel> = Resource<CloudflaredTunnel>(
52
+ 'Cloudflare.CloudflaredTunnel',
53
+ { defaultRemovalPolicy: 'retain' },
54
+ );
55
+
56
+ /** What every call below needs: the account, credentials and HTTP — Alchemy's own trio. */
57
+ export type CloudflaredTunnelServices =
58
+ | Cloudflare.CloudflareEnvironment
59
+ | Credentials
60
+ | HttpClient.HttpClient;
61
+
62
+ /** The account id, resolved the way every `alchemy/Cloudflare` provider resolves it. */
63
+ const accountId = Effect.gen(function* () {
64
+ const resolved = yield* yield* Cloudflare.CloudflareEnvironment;
65
+ return resolved.accountId;
66
+ });
67
+
68
+ /**
69
+ * ★ `Provider.effect`, CAPTURING THE THREE SERVICES AT BUILD, exactly as `MeshNodeProvider` does
70
+ * (mesh-node.ts says why): correct whether or not the stack also merges `Cloudflare.providers()`.
71
+ */
72
+ export const CloudflaredTunnelProvider = () =>
73
+ Provider.effect(
74
+ CloudflaredTunnel,
75
+ Effect.gen(function* () {
76
+ const services = Context.make(
77
+ Cloudflare.CloudflareEnvironment,
78
+ yield* Cloudflare.CloudflareEnvironment,
79
+ ).pipe(
80
+ Context.add(Credentials, yield* Credentials),
81
+ Context.add(HttpClient.HttpClient, yield* HttpClient.HttpClient),
82
+ );
83
+ const run = <A, E>(effect: Effect.Effect<A, E, CloudflaredTunnelServices>) =>
84
+ Effect.provideContext(effect, services);
85
+
86
+ return CloudflaredTunnel.Provider.of({
87
+ stables: ['id', 'accountId'],
88
+ /**
89
+ * ⛔ EMPTY, AND `nuke.skip`. Alchemy's own `Cloudflare.Tunnel.Tunnel` already lists every
90
+ * `cfd_tunnel` in the account for `alchemy unsafe nuke` (and fetches each token to do
91
+ * it); a second listing here would make nuke delete each tunnel twice. `read` does not
92
+ * depend on this.
93
+ */
94
+ list: () => Effect.succeed([]),
95
+ nuke: { skip: true },
96
+ /** ⛔ Validate at plan time too, so a bad declaration never reaches a replace. */
97
+ diff: ({ news, output }) =>
98
+ run(
99
+ Effect.gen(function* () {
100
+ const invalid = isResolved(news) ? validateCloudflaredTunnel(news) : undefined;
101
+ if (invalid !== undefined) return yield* Effect.fail(invalid);
102
+ return diffCloudflaredTunnel(news, output, yield* accountId);
103
+ }),
104
+ ),
105
+ read: ({ olds, output }) =>
106
+ run(Effect.flatMap(accountId, (account) => readCloudflaredTunnel(account, olds, output))),
107
+ reconcile: ({ news, output }) =>
108
+ run(
109
+ Effect.flatMap(accountId, (account) =>
110
+ reconcileCloudflaredTunnel(account, news, output),
111
+ ),
112
+ ),
113
+ delete: ({ output }) => run(deleteCloudflaredTunnel(output)),
114
+ });
115
+ }),
116
+ );
@@ -0,0 +1,196 @@
1
+ /**
2
+ * A fake Cloudflare Access applications API for the SaasOidcApplication tests — an in-memory
3
+ * `fetch` handed to Effect's real FetchHttpClient (see fake-mesh.ts, which this mirrors), so the
4
+ * tests exercise distilled's real path assembly, body encoding and envelope decoding AND the raw
5
+ * read in saas-oidc-api.ts.
6
+ *
7
+ * ⛔ TEST-ONLY, AND NO NETWORK. No provider imports this file. Any request outside
8
+ * `/accounts/<FAKE_ACCOUNT>/access/apps` throws, so a mis-wired test fails instead of reaching a
9
+ * real API. Every credential-looking value is a placeholder.
10
+ * ★ THE WIRE IS CLOUDFLARE'S, snake_case: `saas_app`, `client_id`, `redirect_uris`… The create
11
+ * response carries `saas_app.client_secret` (the SDK schema's own doc: "only returned on POST
12
+ * request"); a GET and a PUT never do. So a test that asserts the secret appears nowhere is
13
+ * asserting against a fake that does hand it out once.
14
+ * ★ THE LIST IS PAGES OF TWO by default, so every name lookup walks more than one page.
15
+ * ★ THE ORGANIZATION READ (`GET /access/organizations`, the pre-create team check) answers with the
16
+ * fake's own team by default; `org` makes it answer a different domain, a 403 in either of the
17
+ * two shapes a token without the permission can get (code 10000 and 10001, see
18
+ * saas-oidc-team.ts), or a 404.
19
+ * ★ `malformed` makes the named calls answer a 2xx body the SDK's STRICT validation cannot decode,
20
+ * with `FAKE_CLIENT_SECRET` planted in it, so a test can force `CloudflareParseError` and look
21
+ * for the secret in what this package throws. ⚠️ ONLY THE CALLS rc.13 TYPES CAN BE MADE TO FAIL:
22
+ * a create or update response decodes against `S.Unknown` (zero_trust.ts:35025, :210218), which
23
+ * accepts anything, so those two are not offered here (saas-oidc-parse-error.test.ts reaches them
24
+ * through the `sdkWrites` seam instead). `list` fails by answering an object where an array is
25
+ * expected, `delete` and `org` by answering a number where the schema wants a string.
26
+ */
27
+ import { FAKE_ACCOUNT, fakeFailure } from './fake-mesh.ts';
28
+
29
+ export const TEAM = 'example.cloudflareaccess.com';
30
+ /** ⚠️ A placeholder, not a credential. Tests assert it is stored and logged nowhere. */
31
+ export const FAKE_CLIENT_SECRET = 'fake-client-secret-0123456789abcdef';
32
+
33
+ export type FakeApp = {
34
+ id: string;
35
+ aud: string;
36
+ type: string;
37
+ name: string;
38
+ session_duration: string;
39
+ policies: string[];
40
+ saas_app?: Record<string, unknown> | undefined;
41
+ };
42
+
43
+ export type Seen = { readonly method: string; readonly path: string; readonly body: unknown };
44
+
45
+ /** The calls `malformed` can corrupt: `get` is the raw read, the rest are SDK calls. */
46
+ export type FakeOp = 'get' | 'list' | 'delete' | 'org';
47
+ /** How the organization read answers; an object names the `auth_domain` it returns. */
48
+ export type FakeOrg =
49
+ | 'matching'
50
+ | 'unauthorized'
51
+ | 'forbidden'
52
+ | 'not_found'
53
+ | { authDomain: string };
54
+
55
+ export type FakeOptions = {
56
+ readonly perPage?: number;
57
+ readonly team?: string;
58
+ readonly org?: FakeOrg;
59
+ readonly malformed?: ReadonlyArray<FakeOp>;
60
+ };
61
+
62
+ const ok = (result: unknown, extra: Record<string, unknown> = {}) =>
63
+ Response.json({ success: true, errors: [], messages: [], result, ...extra });
64
+
65
+ /** The wire shape of an app: no `client_secret`, and `domain` as Cloudflare derives it. */
66
+ const wire = (app: FakeApp, team: string) => {
67
+ const clientId = app.saas_app?.['client_id'];
68
+ const { saas_app: saas, ...rest } = app;
69
+ const { client_secret: _secret, ...publicSaas } = saas ?? {};
70
+ return {
71
+ ...rest,
72
+ domain: typeof clientId === 'string' ? `${team}/cdn-cgi/access/sso/oidc/${clientId}` : 'x.test',
73
+ created_at: '2026-10-09T00:00:00Z',
74
+ updated_at: '2026-10-09T00:00:00Z',
75
+ policies: app.policies.map((id, i) => ({ id, precedence: i + 1 })),
76
+ ...(saas === undefined ? {} : { saas_app: publicSaas }),
77
+ };
78
+ };
79
+
80
+ /**
81
+ * A 2xx `result` the typed decoders reject (`id` and `auth_domain` are numbers, and it is not an
82
+ * array), carrying the secret where a create puts it.
83
+ */
84
+ const garbage = () => ({
85
+ id: 12345,
86
+ auth_domain: 12345,
87
+ client_secret: FAKE_CLIENT_SECRET,
88
+ saas_app: { client_secret: FAKE_CLIENT_SECRET },
89
+ });
90
+
91
+ const orgBody = (org: FakeOrg, team: string): Response => {
92
+ if (org === 'unauthorized') return fakeFailure(403, 10000, 'Authentication error');
93
+ if (org === 'forbidden') return fakeFailure(403, 10001, 'Method not allowed for token');
94
+ if (org === 'not_found') return fakeFailure(404, 12004, 'access.api.error.not_found');
95
+ const authDomain = org === 'matching' ? team : org.authDomain;
96
+ return ok({ auth_domain: authDomain, name: 'team', session_duration: '24h' });
97
+ };
98
+
99
+ export const fakeAccess = (options: FakeOptions = {}) => {
100
+ const team = options.team ?? TEAM;
101
+ const broken = (op: FakeOp): boolean => options.malformed?.includes(op) ?? false;
102
+ const apps = new Map<string, FakeApp>();
103
+ const seen: Seen[] = [];
104
+ let next = 1;
105
+
106
+ const seed = (app: Partial<FakeApp> & { name: string }): FakeApp => {
107
+ const n = String(next++).padStart(12, '0');
108
+ const full: FakeApp = {
109
+ id: `00000000-0000-4000-8000-${n}`,
110
+ aud: `aud-${n}`,
111
+ type: 'saas',
112
+ session_duration: '24h',
113
+ policies: [],
114
+ ...app,
115
+ };
116
+ if (full.type === 'saas' && full.saas_app?.['client_id'] === undefined) {
117
+ full.saas_app = { auth_type: 'oidc', client_id: `client-${n}`, ...full.saas_app };
118
+ }
119
+ apps.set(full.id, full);
120
+ return full;
121
+ };
122
+
123
+ const route = (method: string, url: URL, body: Record<string, unknown>): Response => {
124
+ const prefix = `/client/v4/accounts/${FAKE_ACCOUNT}/access/apps`;
125
+ if (
126
+ url.host === 'api.example.com' &&
127
+ url.pathname === prefix.replace(/apps$/, 'organizations')
128
+ ) {
129
+ if (method !== 'GET') throw new Error(`fake-access: unexpected ${method} ${url.pathname}`);
130
+ return broken('org') ? ok(garbage()) : orgBody(options.org ?? 'matching', team);
131
+ }
132
+ if (url.host !== 'api.example.com' || !url.pathname.startsWith(prefix)) {
133
+ throw new Error(`fake-access: unexpected request ${method} ${url.href}`);
134
+ }
135
+ const id = url.pathname.slice(prefix.length).split('/').filter(Boolean)[0];
136
+ if (id === undefined && method === 'GET') {
137
+ if (broken('list')) return ok(garbage());
138
+ const page = Number(url.searchParams.get('page') ?? '1');
139
+ const perPage = Number(url.searchParams.get('per_page') ?? options.perPage ?? 2);
140
+ const all = [...apps.values()];
141
+ const slice = all.slice((page - 1) * perPage, page * perPage);
142
+ return ok(
143
+ slice.map((app) => wire(app, team)),
144
+ {
145
+ result_info: { page, per_page: perPage, count: slice.length, total_count: all.length },
146
+ },
147
+ );
148
+ }
149
+ if (id === undefined && method === 'POST') {
150
+ const app = seed({
151
+ name: String(body['name']),
152
+ type: String(body['type']),
153
+ policies: (body['policies'] as string[] | undefined) ?? [],
154
+ saas_app: body['saas_app'] as Record<string, unknown> | undefined,
155
+ });
156
+ // ⛔ The one response that hands the secret out, as the API does on POST.
157
+ const created = wire(app, team) as Record<string, unknown>;
158
+ created['saas_app'] = {
159
+ ...(created['saas_app'] as object),
160
+ client_secret: FAKE_CLIENT_SECRET,
161
+ };
162
+ return ok(created);
163
+ }
164
+ const app = id === undefined ? undefined : apps.get(id);
165
+ if (app === undefined) return fakeFailure(404, 12006, 'access.api.error.unknown_application');
166
+ if (method === 'GET') {
167
+ return broken('get') ? new Response(`not json ${FAKE_CLIENT_SECRET}`) : ok(wire(app, team));
168
+ }
169
+ if (method === 'PUT') {
170
+ app.name = String(body['name']);
171
+ app.policies = (body['policies'] as string[] | undefined) ?? [];
172
+ app.saas_app = { ...app.saas_app, ...(body['saas_app'] as Record<string, unknown>) };
173
+ return ok(wire(app, team));
174
+ }
175
+ if (method === 'DELETE') {
176
+ if (broken('delete')) return ok(garbage());
177
+ apps.delete(app.id);
178
+ return ok({ id: app.id });
179
+ }
180
+ throw new Error(`fake-access: unexpected ${method} ${url.pathname}`);
181
+ };
182
+
183
+ const fetch = (async (input: string | URL | Request, init?: RequestInit) => {
184
+ const request =
185
+ input instanceof Request ? new Request(input, init) : new Request(String(input), init);
186
+ const url = new URL(request.url);
187
+ const text = await request.text();
188
+ const body = text.length === 0 ? {} : (JSON.parse(text) as Record<string, unknown>);
189
+ seen.push({ method: request.method, path: `${url.pathname}${url.search}`, body });
190
+ return route(request.method, url, body);
191
+ }) as typeof globalThis.fetch;
192
+
193
+ return { apps, fetch, seed, seen, team };
194
+ };
195
+
196
+ export type FakeAccess = ReturnType<typeof fakeAccess>;
@@ -37,7 +37,7 @@ export type FakeNode = {
37
37
 
38
38
  export type Seen = { readonly method: string; readonly path: string; readonly body: unknown };
39
39
 
40
- const ok = (result: unknown, extra: Record<string, unknown> = {}) =>
40
+ export const ok = (result: unknown, extra: Record<string, unknown> = {}) =>
41
41
  Response.json({ success: true, errors: [], messages: [], result, ...extra });
42
42
 
43
43
  export const fakeFailure = (status: number, code: number, message: string) =>
@@ -153,7 +153,7 @@ export type FakeMesh = ReturnType<typeof fakeMesh>;
153
153
 
154
154
  /** distilled Credentials + the real FetchHttpClient over the fake — what a Bun script provides. */
155
155
  export const fakeClientLayer = (
156
- fake: FakeMesh,
156
+ fake: { readonly fetch: typeof globalThis.fetch },
157
157
  credentials: Layer.Layer<Credentials> = fromApiToken({
158
158
  apiToken: FAKE_API_TOKEN,
159
159
  apiBaseUrl: FAKE_BASE,
@@ -166,7 +166,10 @@ export const fakeClientLayer = (
166
166
  );
167
167
 
168
168
  /** …plus the account, as Alchemy's CloudflareEnvironment hands it to a provider. */
169
- export const fakeProviderLayer = (fake: FakeMesh, accountId: string = FAKE_ACCOUNT) =>
169
+ export const fakeProviderLayer = (
170
+ fake: { readonly fetch: typeof globalThis.fetch },
171
+ accountId: string = FAKE_ACCOUNT,
172
+ ) =>
170
173
  Layer.mergeAll(
171
174
  fakeClientLayer(fake),
172
175
  Layer.succeed(
@@ -0,0 +1,148 @@
1
+ /**
2
+ * A fake Cloudflare `cfd_tunnel` API for the CloudflaredTunnel tests — an in-memory `fetch` handed
3
+ * to Effect's real FetchHttpClient, the same way fake-mesh.ts does it, so the tests exercise
4
+ * distilled's real path assembly, query and body encoding, envelope decoding and error matching.
5
+ *
6
+ * ⛔ TEST-ONLY, AND NO NETWORK. No provider imports this file. Any request outside
7
+ * `/accounts/<FAKE_ACCOUNT>/cfd_tunnel` or `/accounts/<FAKE_ACCOUNT>/tunnels` throws, so a
8
+ * mis-wired test fails instead of reaching a real API.
9
+ * ★ THE FAKE HANDS OUT A TOKEN ON EVERY SURFACE IT CAN: a `token` field on the create response and
10
+ * on every wire object (worst case: if Cloudflare ever adds one to the documented shape), and the
11
+ * `/token` endpoint. The tests then prove none of it reaches an attribute, a state row or a
12
+ * request log. The SDK's decoder drops fields outside its schema; the provider must not depend on
13
+ * that alone.
14
+ * ★ THE NAME FILTER IS A SUBSTRING MATCH, as in fake-mesh.ts, so the client's exact re-check is
15
+ * exercised. `/tunnels` honours `tun_types` and `is_deleted` as the SDK documents them, and
16
+ * answers pages of two by default.
17
+ */
18
+ import { FAKE_ACCOUNT, type Seen, fakeFailure, ok } from './fake-mesh.ts';
19
+
20
+ export type FakeTunnel = {
21
+ id: string;
22
+ name: string;
23
+ tun_type: string;
24
+ config_src: string;
25
+ status: string;
26
+ token: string;
27
+ deleted_at: string | null;
28
+ /** The fake refuses a DELETE while this is set, as the SDK doc says it must ("no active connections"). */
29
+ connected: boolean;
30
+ };
31
+
32
+ const wire = (tunnel: FakeTunnel) => ({
33
+ id: tunnel.id,
34
+ account_tag: FAKE_ACCOUNT,
35
+ config_src: tunnel.config_src,
36
+ created_at: '2026-10-09T00:00:00Z',
37
+ deleted_at: tunnel.deleted_at,
38
+ name: tunnel.name,
39
+ status: tunnel.status,
40
+ tun_type: tunnel.tun_type,
41
+ token: tunnel.token,
42
+ });
43
+
44
+ export type FakeTunnelOptions = {
45
+ readonly perPage?: number;
46
+ /** Return a Response to answer the POST with it instead (e.g. `fakeFailure(409, 1013, …)`). */
47
+ readonly onCreate?: (name: string) => Response | void;
48
+ /** Return a Response to answer the DELETE with it instead (e.g. the tunnel vanishing mid-delete). */
49
+ readonly onDelete?: (id: string) => Response | void;
50
+ };
51
+
52
+ export const fakeTunnels = (options: FakeTunnelOptions = {}) => {
53
+ const tunnels = new Map<string, FakeTunnel>();
54
+ const seen: Seen[] = [];
55
+ const auth: string[] = [];
56
+ let next = 1;
57
+ const live = () => [...tunnels.values()].filter((t) => t.deleted_at === null);
58
+
59
+ const seed = (tunnel: Partial<FakeTunnel> & { name: string }): FakeTunnel => {
60
+ const id = tunnel.id ?? `00000000-0000-4000-9000-${String(next++).padStart(12, '0')}`;
61
+ const full: FakeTunnel = {
62
+ id,
63
+ tun_type: 'cfd_tunnel',
64
+ config_src: 'cloudflare',
65
+ status: 'inactive',
66
+ token: `fake-tunnel-token-${id}`,
67
+ deleted_at: null,
68
+ connected: false,
69
+ ...tunnel,
70
+ };
71
+ tunnels.set(id, full);
72
+ return full;
73
+ };
74
+
75
+ const list = (url: URL): Response => {
76
+ const filter = url.searchParams.get('name') ?? '';
77
+ const types = (url.searchParams.get('tun_types') ?? '').split(',').filter(Boolean);
78
+ const isDeleted = url.searchParams.get('is_deleted');
79
+ const page = Number(url.searchParams.get('page') ?? '1');
80
+ const perPage = Number(url.searchParams.get('per_page') ?? options.perPage ?? 2);
81
+ const hits = [...tunnels.values()]
82
+ .filter((t) => types.length === 0 || types.includes(t.tun_type))
83
+ .filter((t) => isDeleted === null || (t.deleted_at !== null) === (isDeleted === 'true'))
84
+ .filter((t) => t.name.includes(filter));
85
+ const slice = hits.slice((page - 1) * perPage, page * perPage);
86
+ return ok(slice.map(wire), { result_info: { page, per_page: perPage, count: slice.length } });
87
+ };
88
+
89
+ const route = (method: string, url: URL, body: Record<string, unknown>): Response => {
90
+ const base = `/client/v4/accounts/${FAKE_ACCOUNT}`;
91
+ if (url.host !== 'api.example.com' || !url.pathname.startsWith(base)) {
92
+ throw new Error(`fake-tunnel: unexpected request ${method} ${url.href}`);
93
+ }
94
+ const rest = url.pathname.slice(base.length);
95
+ if (rest === '/tunnels' && method === 'GET') return list(url);
96
+ if (!rest.startsWith('/cfd_tunnel')) {
97
+ throw new Error(`fake-tunnel: unexpected ${method} ${url.pathname}`);
98
+ }
99
+ const [id, sub] = rest.slice('/cfd_tunnel'.length).split('/').filter(Boolean);
100
+ if (id === undefined && method === 'POST') {
101
+ const name = String(body['name']);
102
+ const override = options.onCreate?.(name);
103
+ if (override !== undefined) return override;
104
+ if (live().some((t) => t.name === name)) {
105
+ return fakeFailure(409, 1013, 'tunnel with name already exists');
106
+ }
107
+ const tunnel = seed({ name, config_src: String(body['config_src'] ?? 'local') });
108
+ return ok(wire(tunnel));
109
+ }
110
+ const tunnel = id === undefined ? undefined : tunnels.get(id);
111
+ if (tunnel === undefined) return fakeFailure(404, 1002, 'Tunnel not found');
112
+ if (sub === 'token' && method === 'GET') return ok(tunnel.token);
113
+ if (sub !== undefined) throw new Error(`fake-tunnel: unexpected ${method} ${url.pathname}`);
114
+ if (method === 'GET') return ok(wire(tunnel));
115
+ if (method === 'PATCH') {
116
+ const name = String(body['name']);
117
+ if (live().some((other) => other.name === name && other.id !== tunnel.id)) {
118
+ return fakeFailure(409, 1013, 'tunnel with name already exists');
119
+ }
120
+ tunnel.name = name;
121
+ return ok(wire(tunnel));
122
+ }
123
+ if (method === 'DELETE') {
124
+ const override = options.onDelete?.(tunnel.id);
125
+ if (override !== undefined) return override;
126
+ if (tunnel.deleted_at !== null) return fakeFailure(404, 1002, 'Tunnel not found');
127
+ if (tunnel.connected) return fakeFailure(400, 1000, 'tunnel has active connections');
128
+ tunnel.deleted_at = '2026-10-09T01:00:00Z';
129
+ return ok(wire(tunnel));
130
+ }
131
+ throw new Error(`fake-tunnel: unexpected ${method} ${url.pathname}`);
132
+ };
133
+
134
+ const fetch = (async (input: string | URL | Request, init?: RequestInit) => {
135
+ const request =
136
+ input instanceof Request ? new Request(input, init) : new Request(String(input), init);
137
+ const url = new URL(request.url);
138
+ const text = await request.text();
139
+ const body = text.length === 0 ? {} : (JSON.parse(text) as Record<string, unknown>);
140
+ seen.push({ method: request.method, path: `${url.pathname}${url.search}`, body });
141
+ auth.push(request.headers.get('authorization') ?? '');
142
+ return route(request.method, url, body);
143
+ }) as typeof globalThis.fetch;
144
+
145
+ return { auth, fetch, live, tunnels, seed, seen };
146
+ };
147
+
148
+ export type FakeTunnels = ReturnType<typeof fakeTunnels>;