@flash-tunnel/adapter-cloudflare 0.0.0-stage → 0.0.1

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 flash-tunnel
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,86 @@
1
+ import { DnsRecordType, DnsRecordSpec, DnsAdapter, TunnelAdapter } from '@flash-tunnel/types';
2
+
3
+ interface CloudflareApiOptions {
4
+ apiToken: string;
5
+ apiBase?: string;
6
+ fetcher?: typeof fetch;
7
+ }
8
+ interface CloudflareAccount {
9
+ id: string;
10
+ name: string;
11
+ }
12
+ interface CloudflareZone {
13
+ id: string;
14
+ name: string;
15
+ status: string;
16
+ }
17
+ interface CloudflareTunnel {
18
+ id: string;
19
+ name: string;
20
+ status: string;
21
+ connections?: Array<{
22
+ id: string;
23
+ }>;
24
+ token?: string;
25
+ }
26
+ interface CloudflareDnsRecord {
27
+ id: string;
28
+ name: string;
29
+ type: DnsRecordType;
30
+ content: string;
31
+ proxied: boolean;
32
+ comment?: string;
33
+ }
34
+ declare class CloudflareApi {
35
+ private readonly apiToken;
36
+ private readonly apiBase;
37
+ private readonly fetcher;
38
+ constructor(options: CloudflareApiOptions);
39
+ request<T>(method: string, path: string, body?: unknown): Promise<T>;
40
+ verifyToken(): Promise<void>;
41
+ listAccounts(): Promise<CloudflareAccount[]>;
42
+ resolveAccountId(preferred?: string): Promise<string>;
43
+ listZones(name?: string): Promise<CloudflareZone[]>;
44
+ resolveZone(zone: string): Promise<CloudflareZone>;
45
+ createTunnel(accountId: string, name: string): Promise<CloudflareTunnel>;
46
+ getTunnel(accountId: string, tunnelId: string): Promise<CloudflareTunnel>;
47
+ getTunnelToken(accountId: string, tunnelId: string): Promise<string>;
48
+ putIngress(accountId: string, tunnelId: string, ingress: unknown[]): Promise<void>;
49
+ cleanupConnections(accountId: string, tunnelId: string): Promise<void>;
50
+ deleteTunnel(accountId: string, tunnelId: string): Promise<void>;
51
+ listDnsRecords(zoneId: string, query?: {
52
+ name?: string;
53
+ comment?: string;
54
+ }): Promise<CloudflareDnsRecord[]>;
55
+ createDnsRecord(zoneId: string, spec: DnsRecordSpec): Promise<CloudflareDnsRecord>;
56
+ deleteDnsRecord(zoneId: string, recordId: string): Promise<void>;
57
+ }
58
+
59
+ interface CloudflareDnsOptions {
60
+ apiToken: string;
61
+ zoneId?: string;
62
+ apiBase?: string;
63
+ fetcher?: typeof fetch;
64
+ }
65
+ declare function createCloudflareDns(options: CloudflareDnsOptions): DnsAdapter;
66
+
67
+ interface CloudflareTunnelOptions {
68
+ cloudflaredPath?: string;
69
+ accountId?: string;
70
+ apiToken?: string;
71
+ apiBase?: string;
72
+ originRequest?: {
73
+ httpHostHeader?: string;
74
+ noTLSVerify?: boolean;
75
+ };
76
+ fetcher?: typeof fetch;
77
+ }
78
+ declare function createCloudflareTunnel(options?: CloudflareTunnelOptions): TunnelAdapter;
79
+ declare const cloudflareTunnel: TunnelAdapter;
80
+
81
+ declare const CLOUDFLARE_DNS_ADAPTER_ID = "cloudflare";
82
+ declare const CLOUDFLARE_TUNNEL_ADAPTER_ID = "cloudflare";
83
+ declare const CLOUDFLARE_API_BASE = "https://api.cloudflare.com/client/v4";
84
+
85
+ export { CLOUDFLARE_API_BASE, CLOUDFLARE_DNS_ADAPTER_ID, CLOUDFLARE_TUNNEL_ADAPTER_ID, CloudflareApi, cloudflareTunnel, createCloudflareDns, createCloudflareTunnel };
86
+ export type { CloudflareAccount, CloudflareDnsOptions, CloudflareDnsRecord, CloudflareTunnel, CloudflareTunnelOptions, CloudflareZone };
@@ -0,0 +1,86 @@
1
+ import { DnsRecordType, DnsRecordSpec, DnsAdapter, TunnelAdapter } from '@flash-tunnel/types';
2
+
3
+ interface CloudflareApiOptions {
4
+ apiToken: string;
5
+ apiBase?: string;
6
+ fetcher?: typeof fetch;
7
+ }
8
+ interface CloudflareAccount {
9
+ id: string;
10
+ name: string;
11
+ }
12
+ interface CloudflareZone {
13
+ id: string;
14
+ name: string;
15
+ status: string;
16
+ }
17
+ interface CloudflareTunnel {
18
+ id: string;
19
+ name: string;
20
+ status: string;
21
+ connections?: Array<{
22
+ id: string;
23
+ }>;
24
+ token?: string;
25
+ }
26
+ interface CloudflareDnsRecord {
27
+ id: string;
28
+ name: string;
29
+ type: DnsRecordType;
30
+ content: string;
31
+ proxied: boolean;
32
+ comment?: string;
33
+ }
34
+ declare class CloudflareApi {
35
+ private readonly apiToken;
36
+ private readonly apiBase;
37
+ private readonly fetcher;
38
+ constructor(options: CloudflareApiOptions);
39
+ request<T>(method: string, path: string, body?: unknown): Promise<T>;
40
+ verifyToken(): Promise<void>;
41
+ listAccounts(): Promise<CloudflareAccount[]>;
42
+ resolveAccountId(preferred?: string): Promise<string>;
43
+ listZones(name?: string): Promise<CloudflareZone[]>;
44
+ resolveZone(zone: string): Promise<CloudflareZone>;
45
+ createTunnel(accountId: string, name: string): Promise<CloudflareTunnel>;
46
+ getTunnel(accountId: string, tunnelId: string): Promise<CloudflareTunnel>;
47
+ getTunnelToken(accountId: string, tunnelId: string): Promise<string>;
48
+ putIngress(accountId: string, tunnelId: string, ingress: unknown[]): Promise<void>;
49
+ cleanupConnections(accountId: string, tunnelId: string): Promise<void>;
50
+ deleteTunnel(accountId: string, tunnelId: string): Promise<void>;
51
+ listDnsRecords(zoneId: string, query?: {
52
+ name?: string;
53
+ comment?: string;
54
+ }): Promise<CloudflareDnsRecord[]>;
55
+ createDnsRecord(zoneId: string, spec: DnsRecordSpec): Promise<CloudflareDnsRecord>;
56
+ deleteDnsRecord(zoneId: string, recordId: string): Promise<void>;
57
+ }
58
+
59
+ interface CloudflareDnsOptions {
60
+ apiToken: string;
61
+ zoneId?: string;
62
+ apiBase?: string;
63
+ fetcher?: typeof fetch;
64
+ }
65
+ declare function createCloudflareDns(options: CloudflareDnsOptions): DnsAdapter;
66
+
67
+ interface CloudflareTunnelOptions {
68
+ cloudflaredPath?: string;
69
+ accountId?: string;
70
+ apiToken?: string;
71
+ apiBase?: string;
72
+ originRequest?: {
73
+ httpHostHeader?: string;
74
+ noTLSVerify?: boolean;
75
+ };
76
+ fetcher?: typeof fetch;
77
+ }
78
+ declare function createCloudflareTunnel(options?: CloudflareTunnelOptions): TunnelAdapter;
79
+ declare const cloudflareTunnel: TunnelAdapter;
80
+
81
+ declare const CLOUDFLARE_DNS_ADAPTER_ID = "cloudflare";
82
+ declare const CLOUDFLARE_TUNNEL_ADAPTER_ID = "cloudflare";
83
+ declare const CLOUDFLARE_API_BASE = "https://api.cloudflare.com/client/v4";
84
+
85
+ export { CLOUDFLARE_API_BASE, CLOUDFLARE_DNS_ADAPTER_ID, CLOUDFLARE_TUNNEL_ADAPTER_ID, CloudflareApi, cloudflareTunnel, createCloudflareDns, createCloudflareTunnel };
86
+ export type { CloudflareAccount, CloudflareDnsOptions, CloudflareDnsRecord, CloudflareTunnel, CloudflareTunnelOptions, CloudflareZone };
package/dist/index.mjs ADDED
@@ -0,0 +1,610 @@
1
+ import { AdapterError } from '@flash-tunnel/types';
2
+ import { spawnSync, spawn } from 'node:child_process';
3
+ import process from 'node:process';
4
+ import { sleep, stripAnsi } from '@flash-tunnel/utils';
5
+
6
+ function mapError(status, envelope) {
7
+ const first = envelope.errors?.[0];
8
+ const cfCode = first?.code;
9
+ let code = "CLOUDFLARE_API_ERROR";
10
+ if (cfCode === 81057) {
11
+ code = "RECORD_CONFLICT";
12
+ } else if (status === 401 || status === 403) {
13
+ code = "AUTH_INVALID";
14
+ } else if (status === 404) {
15
+ code = "NOT_FOUND";
16
+ } else if (status === 429) {
17
+ code = "RATE_LIMITED";
18
+ }
19
+ return new AdapterError(first?.message ?? `Cloudflare API responded with ${status}`, {
20
+ code,
21
+ retriable: status === 429 || status >= 500,
22
+ details: { status, cfCode }
23
+ });
24
+ }
25
+ class CloudflareApi {
26
+ apiToken;
27
+ apiBase;
28
+ fetcher;
29
+ constructor(options) {
30
+ this.apiToken = options.apiToken;
31
+ this.apiBase = options.apiBase ?? "https://api.cloudflare.com/client/v4";
32
+ this.fetcher = options.fetcher ?? fetch;
33
+ }
34
+ async request(method, path, body) {
35
+ let response;
36
+ try {
37
+ response = await this.fetcher(`${this.apiBase}${path}`, {
38
+ method,
39
+ headers: {
40
+ "authorization": `Bearer ${this.apiToken}`,
41
+ "content-type": "application/json"
42
+ },
43
+ body: body === void 0 ? void 0 : JSON.stringify(body),
44
+ signal: AbortSignal.timeout(15e3)
45
+ });
46
+ } catch (error) {
47
+ throw new AdapterError("Cloudflare API request failed", {
48
+ code: "CLOUDFLARE_API_ERROR",
49
+ retriable: true,
50
+ cause: error
51
+ });
52
+ }
53
+ const text = await response.text();
54
+ let envelope = {};
55
+ if (text) {
56
+ try {
57
+ envelope = JSON.parse(text);
58
+ } catch {
59
+ throw new AdapterError("Cloudflare API returned invalid JSON", {
60
+ code: "CLOUDFLARE_API_ERROR",
61
+ details: { status: response.status }
62
+ });
63
+ }
64
+ }
65
+ if (!response.ok || envelope.success === false) {
66
+ throw mapError(response.status, envelope);
67
+ }
68
+ return envelope.result;
69
+ }
70
+ async verifyToken() {
71
+ const result = await this.request("GET", "/user/tokens/verify");
72
+ if (result?.status !== "active") {
73
+ throw new AdapterError("Cloudflare API token is not active", {
74
+ code: "AUTH_INVALID",
75
+ hint: "Create a token with Account Cloudflare Tunnel Edit and Zone DNS Edit"
76
+ });
77
+ }
78
+ }
79
+ async listAccounts() {
80
+ return this.request("GET", "/accounts?per_page=50");
81
+ }
82
+ async resolveAccountId(preferred) {
83
+ if (preferred) {
84
+ return preferred;
85
+ }
86
+ const accounts = await this.listAccounts();
87
+ if (accounts.length === 1 && accounts[0]) {
88
+ return accounts[0].id;
89
+ }
90
+ throw new AdapterError("Cannot determine the Cloudflare account id", {
91
+ code: "ACCOUNT_NOT_FOUND",
92
+ hint: "Set CLOUDFLARE_ACCOUNT_ID or providers.cloudflare.accountId",
93
+ details: { accounts: accounts.map((account) => account.name) }
94
+ });
95
+ }
96
+ async listZones(name) {
97
+ const query = new URLSearchParams({ per_page: "50" });
98
+ if (name) {
99
+ query.set("name", name);
100
+ }
101
+ return this.request("GET", `/zones?${query.toString()}`);
102
+ }
103
+ async resolveZone(zone) {
104
+ const zones = await this.listZones(zone);
105
+ const match = zones.find((item) => item.name === zone);
106
+ if (!match) {
107
+ throw new AdapterError(`Zone "${zone}" was not found`, {
108
+ code: "ZONE_NOT_FOUND",
109
+ hint: "Check domain.zone, or set CLOUDFLARE_ZONE_ID"
110
+ });
111
+ }
112
+ if (match.status !== "active") {
113
+ throw new AdapterError(`Zone "${zone}" is ${match.status}`, {
114
+ code: "ZONE_NOT_ACTIVE",
115
+ hint: "Wait for the zone to become active in Cloudflare"
116
+ });
117
+ }
118
+ return match;
119
+ }
120
+ async createTunnel(accountId, name) {
121
+ return this.request("POST", `/accounts/${accountId}/cfd_tunnel`, {
122
+ name,
123
+ config_src: "cloudflare"
124
+ });
125
+ }
126
+ async getTunnel(accountId, tunnelId) {
127
+ return this.request("GET", `/accounts/${accountId}/cfd_tunnel/${tunnelId}`);
128
+ }
129
+ async getTunnelToken(accountId, tunnelId) {
130
+ const result = await this.request(
131
+ "GET",
132
+ `/accounts/${accountId}/cfd_tunnel/${tunnelId}/token`
133
+ );
134
+ if (typeof result === "string") {
135
+ return result;
136
+ }
137
+ if (result?.token) {
138
+ return result.token;
139
+ }
140
+ throw new AdapterError("Cloudflare did not return a tunnel token", {
141
+ code: "TUNNEL_CREATE_FAILED"
142
+ });
143
+ }
144
+ async putIngress(accountId, tunnelId, ingress) {
145
+ await this.request("PUT", `/accounts/${accountId}/cfd_tunnel/${tunnelId}/configurations`, {
146
+ config: { ingress }
147
+ });
148
+ }
149
+ async cleanupConnections(accountId, tunnelId) {
150
+ await this.request("DELETE", `/accounts/${accountId}/cfd_tunnel/${tunnelId}/connections`);
151
+ }
152
+ async deleteTunnel(accountId, tunnelId) {
153
+ await this.request("DELETE", `/accounts/${accountId}/cfd_tunnel/${tunnelId}`);
154
+ }
155
+ async listDnsRecords(zoneId, query = {}) {
156
+ const params = new URLSearchParams({ per_page: "100" });
157
+ if (query.name) {
158
+ params.set("name", query.name);
159
+ }
160
+ if (query.comment) {
161
+ params.set("comment", query.comment);
162
+ }
163
+ return this.request("GET", `/zones/${zoneId}/dns_records?${params.toString()}`);
164
+ }
165
+ async createDnsRecord(zoneId, spec) {
166
+ return this.request("POST", `/zones/${zoneId}/dns_records`, {
167
+ type: spec.type,
168
+ name: spec.name,
169
+ content: spec.content,
170
+ proxied: spec.proxied ?? false,
171
+ ttl: spec.ttl ?? 1,
172
+ comment: spec.comment
173
+ });
174
+ }
175
+ async deleteDnsRecord(zoneId, recordId) {
176
+ await this.request("DELETE", `/zones/${zoneId}/dns_records/${recordId}`);
177
+ }
178
+ }
179
+
180
+ const OWNED_COMMENT_PREFIX = "flash-tunnel:";
181
+ function isOwned(comment) {
182
+ return comment?.startsWith(OWNED_COMMENT_PREFIX) ?? false;
183
+ }
184
+ function toRef(provider, zoneId, record) {
185
+ return {
186
+ provider,
187
+ zoneId,
188
+ recordId: record.id,
189
+ name: record.name,
190
+ type: record.type,
191
+ content: record.content,
192
+ proxied: record.proxied
193
+ };
194
+ }
195
+ function createCloudflareDns(options) {
196
+ const api = new CloudflareApi(options);
197
+ const zoneIds = /* @__PURE__ */ new Map();
198
+ async function zoneIdFor(zone) {
199
+ if (options.zoneId) {
200
+ return options.zoneId;
201
+ }
202
+ const cached = zoneIds.get(zone);
203
+ if (cached) {
204
+ return cached;
205
+ }
206
+ const resolved = await api.resolveZone(zone);
207
+ zoneIds.set(zone, resolved.id);
208
+ return resolved.id;
209
+ }
210
+ return {
211
+ kind: "dns",
212
+ id: "cloudflare",
213
+ apiVersion: 1,
214
+ capabilities: {
215
+ recordTypes: ["CNAME", "A", "AAAA", "TXT"],
216
+ proxied: true,
217
+ ttl: true,
218
+ comment: true,
219
+ lookupByName: true
220
+ },
221
+ async preflight(_ctx, target) {
222
+ await api.verifyToken();
223
+ const zoneId = await zoneIdFor(target.zone);
224
+ const existing = await api.listDnsRecords(zoneId, { name: target.name });
225
+ const conflicts = existing.filter((record) => !isOwned(record.comment));
226
+ if (conflicts.length > 0 && !target.overwrite) {
227
+ throw new AdapterError(`DNS record "${target.name}" already exists`, {
228
+ code: "RECORD_CONFLICT",
229
+ hint: "Use a different subdomain, or pass --overwrite to replace a non-flash-tunnel record",
230
+ details: { records: conflicts.map((record) => record.id) }
231
+ });
232
+ }
233
+ },
234
+ async ensure(_ctx, spec) {
235
+ const zoneId = await zoneIdFor(spec.zone);
236
+ const existing = await api.listDnsRecords(zoneId, { name: spec.name });
237
+ for (const record of existing) {
238
+ if (spec.overwrite || isOwned(record.comment)) {
239
+ await api.deleteDnsRecord(zoneId, record.id).catch(() => {
240
+ });
241
+ }
242
+ }
243
+ try {
244
+ const record = await api.createDnsRecord(zoneId, spec);
245
+ return toRef("cloudflare", zoneId, record);
246
+ } catch (error) {
247
+ if (error instanceof AdapterError && error.code === "RECORD_CONFLICT") {
248
+ const current = await api.listDnsRecords(zoneId, { name: spec.name });
249
+ const owned = current.filter((record2) => isOwned(record2.comment));
250
+ if (owned.length === 0) {
251
+ throw error;
252
+ }
253
+ for (const record2 of owned) {
254
+ await api.deleteDnsRecord(zoneId, record2.id);
255
+ }
256
+ const record = await api.createDnsRecord(zoneId, spec);
257
+ return toRef("cloudflare", zoneId, record);
258
+ }
259
+ throw error;
260
+ }
261
+ },
262
+ async remove(_ctx, ref) {
263
+ try {
264
+ await api.deleteDnsRecord(ref.zoneId, ref.recordId);
265
+ } catch (error) {
266
+ if (error instanceof AdapterError && error.code === "NOT_FOUND") {
267
+ return;
268
+ }
269
+ throw error;
270
+ }
271
+ },
272
+ async find(_ctx, query) {
273
+ const zoneId = await zoneIdFor(query.zone);
274
+ const records = await api.listDnsRecords(zoneId, {
275
+ name: query.name,
276
+ comment: query.comment
277
+ });
278
+ return records.map((record) => toRef("cloudflare", zoneId, record));
279
+ }
280
+ };
281
+ }
282
+
283
+ const ADAPTER_ID = "cloudflare";
284
+ const QUICK_URL_PATTERN = /https:\/\/[a-z0-9-]+\.trycloudflare\.com/;
285
+ function createCloudflareTunnel(options = {}) {
286
+ const cloudflaredPath = options.cloudflaredPath ?? "cloudflared";
287
+ const api = options.apiToken ? new CloudflareApi({
288
+ apiToken: options.apiToken,
289
+ apiBase: options.apiBase,
290
+ fetcher: options.fetcher
291
+ }) : void 0;
292
+ let childProcess;
293
+ let output = [];
294
+ let exitInfo;
295
+ let publicUrl;
296
+ let active;
297
+ let accountId;
298
+ let plannedMode = "quick";
299
+ function reset() {
300
+ childProcess = void 0;
301
+ output = [];
302
+ exitInfo = void 0;
303
+ publicUrl = void 0;
304
+ active = void 0;
305
+ }
306
+ function requireApi() {
307
+ if (!api) {
308
+ throw new AdapterError("Named tunnels require CLOUDFLARE_API_TOKEN", {
309
+ code: "AUTH_INVALID",
310
+ hint: "Set CLOUDFLARE_API_TOKEN, or use --mode quick for a temporary domain"
311
+ });
312
+ }
313
+ return api;
314
+ }
315
+ function ensureCloudflared() {
316
+ const check = spawnSync(cloudflaredPath, ["--version"], {
317
+ encoding: "utf8",
318
+ shell: process.platform === "win32",
319
+ timeout: 1e4,
320
+ windowsHide: true
321
+ });
322
+ if (check.error || check.status !== 0) {
323
+ throw new AdapterError(`Cannot run cloudflared at "${cloudflaredPath}"`, {
324
+ code: "PROCESS_SPAWN_FAILED",
325
+ hint: "Install cloudflared or set providers.cloudflare.cloudflaredPath",
326
+ cause: check.error
327
+ });
328
+ }
329
+ return `${check.stdout ?? ""}${check.stderr ?? ""}`.trim();
330
+ }
331
+ function capture(chunk, hooks) {
332
+ const text = stripAnsi(chunk.toString());
333
+ for (const line of text.split(/\r?\n/)) {
334
+ if (!line) {
335
+ continue;
336
+ }
337
+ output.push(line);
338
+ if (output.length > 200) {
339
+ output.shift();
340
+ }
341
+ hooks.onLog?.(line, "stderr");
342
+ const match = QUICK_URL_PATTERN.exec(line);
343
+ if (match?.[0]) {
344
+ publicUrl = match[0];
345
+ }
346
+ }
347
+ }
348
+ async function resolveAccountId() {
349
+ if (accountId) {
350
+ return accountId;
351
+ }
352
+ accountId = await requireApi().resolveAccountId(options.accountId);
353
+ return accountId;
354
+ }
355
+ async function rollbackTunnel(accountIdValue, tunnelId) {
356
+ const client = requireApi();
357
+ await client.cleanupConnections(accountIdValue, tunnelId).catch(() => {
358
+ });
359
+ await client.deleteTunnel(accountIdValue, tunnelId).catch(() => {
360
+ });
361
+ }
362
+ return {
363
+ kind: "tunnel",
364
+ id: ADAPTER_ID,
365
+ apiVersion: 1,
366
+ capabilities: {
367
+ modes: ["named", "quick"],
368
+ publicHostname: "both",
369
+ requiresDns: false,
370
+ dns: {
371
+ type: "CNAME",
372
+ targetFrom: "handle",
373
+ proxied: true,
374
+ providerAffinity: ["cloudflare"]
375
+ },
376
+ concurrent: true
377
+ },
378
+ async preflight(ctx, { mode }) {
379
+ plannedMode = mode;
380
+ const version = ensureCloudflared();
381
+ const match = /cloudflared version (\d{4})\.(\d+)/i.exec(version);
382
+ if (match && Number(match[1]) < 2024) {
383
+ ctx.logger.warn(
384
+ `cloudflared ${match[1]}.${match[2]} is old; upgrade to a recent release for reliable tunnels`
385
+ );
386
+ }
387
+ if (mode === "named") {
388
+ const client = requireApi();
389
+ await client.verifyToken();
390
+ await resolveAccountId();
391
+ }
392
+ },
393
+ async provision(_ctx, spec) {
394
+ reset();
395
+ if (plannedMode === "quick") {
396
+ return {
397
+ provider: ADAPTER_ID,
398
+ tunnelId: "quick",
399
+ name: spec.name,
400
+ secrets: {},
401
+ meta: { mode: "quick", localUrl: spec.localUrl }
402
+ };
403
+ }
404
+ if (spec.hostname === void 0) {
405
+ throw new AdapterError("Named tunnel requires a hostname", {
406
+ code: "TUNNEL_CREATE_FAILED",
407
+ hint: "Set domain.zone (and optionally domain.subdomain) in flash-tunnel.ts"
408
+ });
409
+ }
410
+ const client = requireApi();
411
+ const accountIdValue = await resolveAccountId();
412
+ const tunnel = await client.createTunnel(accountIdValue, spec.name);
413
+ const token = tunnel.token ?? await client.getTunnelToken(accountIdValue, tunnel.id);
414
+ const originRequest = options.originRequest && Object.keys(options.originRequest).length > 0 ? options.originRequest : void 0;
415
+ const ingress = [
416
+ {
417
+ hostname: spec.hostname,
418
+ service: spec.localUrl,
419
+ ...originRequest ? { originRequest } : {}
420
+ },
421
+ { service: "http_status:404" }
422
+ ];
423
+ try {
424
+ await client.putIngress(accountIdValue, tunnel.id, ingress);
425
+ } catch (error) {
426
+ await rollbackTunnel(accountIdValue, tunnel.id);
427
+ throw error;
428
+ }
429
+ const handle = {
430
+ provider: ADAPTER_ID,
431
+ tunnelId: tunnel.id,
432
+ name: spec.name,
433
+ publicUrl: `https://${spec.hostname}`,
434
+ dns: {
435
+ type: "CNAME",
436
+ target: `${tunnel.id}.cfargotunnel.com`,
437
+ proxied: true
438
+ },
439
+ secrets: { token },
440
+ meta: {
441
+ mode: "named",
442
+ accountId: accountIdValue,
443
+ hostname: spec.hostname,
444
+ localUrl: spec.localUrl
445
+ }
446
+ };
447
+ active = {
448
+ handle,
449
+ accountId: accountIdValue,
450
+ mode: "named",
451
+ resource: tunnel
452
+ };
453
+ return handle;
454
+ },
455
+ async start(_ctx, handle, hooks) {
456
+ const localUrl = handle.meta?.localUrl;
457
+ const named = handle.meta?.mode === "named";
458
+ if (!localUrl) {
459
+ throw new AdapterError("Missing local URL for tunnel", {
460
+ code: "PROCESS_SPAWN_FAILED"
461
+ });
462
+ }
463
+ const args = named ? ["--no-autoupdate", "tunnel", "run"] : ["--no-autoupdate", "tunnel", "--url", localUrl];
464
+ const child = spawn(cloudflaredPath, args, {
465
+ shell: process.platform === "win32",
466
+ stdio: ["ignore", "pipe", "pipe"],
467
+ windowsHide: true,
468
+ detached: process.platform !== "win32",
469
+ env: named && handle.secrets.token ? { ...process.env, TUNNEL_TOKEN: handle.secrets.token } : process.env
470
+ });
471
+ childProcess = child;
472
+ if (child.pid) {
473
+ handle.meta = { ...handle.meta, processPid: String(child.pid) };
474
+ }
475
+ child.stderr?.on("data", (chunk) => capture(chunk, hooks));
476
+ child.stdout?.on("data", (chunk) => capture(chunk, hooks));
477
+ child.once("exit", (code, signal) => {
478
+ exitInfo = { code, signal };
479
+ hooks.onExit?.({ code, signal });
480
+ });
481
+ },
482
+ async waitReady(_ctx, handle, timeoutMs) {
483
+ const startedAt = Date.now();
484
+ const named = handle.meta?.mode === "named";
485
+ while (Date.now() - startedAt < timeoutMs) {
486
+ if (named) {
487
+ const client = requireApi();
488
+ const accountIdValue = handle.meta?.accountId;
489
+ if (!accountIdValue) {
490
+ throw new AdapterError("Missing account id for named tunnel", {
491
+ code: "TUNNEL_NOT_CONNECTED"
492
+ });
493
+ }
494
+ try {
495
+ const tunnel = await client.getTunnel(accountIdValue, handle.tunnelId);
496
+ const connections = tunnel.connections?.length ?? 0;
497
+ if (tunnel.status === "healthy" && connections > 0) {
498
+ if (handle.publicUrl) {
499
+ publicUrl = handle.publicUrl;
500
+ }
501
+ return { state: "connected", connections, publicUrl: handle.publicUrl };
502
+ }
503
+ } catch (error) {
504
+ if (exitInfo) {
505
+ throw new AdapterError(
506
+ `cloudflared exited before the tunnel was ready (code ${exitInfo.code ?? "null"})${output.length ? `
507
+ ${output.slice(-10).join("\n")}` : ""}`,
508
+ { code: "TUNNEL_NOT_CONNECTED", retriable: true, cause: error }
509
+ );
510
+ }
511
+ }
512
+ } else if (publicUrl) {
513
+ handle.publicUrl = publicUrl;
514
+ return { state: "connected", connections: 1, publicUrl };
515
+ }
516
+ if (exitInfo) {
517
+ throw new AdapterError(
518
+ `cloudflared exited before the tunnel was ready (code ${exitInfo.code ?? "null"})${output.length ? `
519
+ ${output.slice(-10).join("\n")}` : ""}`,
520
+ { code: "TUNNEL_NOT_CONNECTED", retriable: true }
521
+ );
522
+ }
523
+ await sleep(named ? 1e3 : 150);
524
+ }
525
+ throw new AdapterError(`Timed out after ${timeoutMs}ms waiting for the tunnel`, {
526
+ code: "TUNNEL_NOT_CONNECTED",
527
+ retriable: true,
528
+ hint: "Check that outbound UDP 7844 is reachable, or retry"
529
+ });
530
+ },
531
+ async stop() {
532
+ const child = childProcess;
533
+ if (!child?.pid || child.exitCode !== null) {
534
+ childProcess = void 0;
535
+ return;
536
+ }
537
+ if (process.platform === "win32") {
538
+ spawnSync("taskkill", ["/PID", String(child.pid), "/T", "/F"], {
539
+ stdio: "ignore",
540
+ windowsHide: true
541
+ });
542
+ } else {
543
+ try {
544
+ process.kill(-child.pid, "SIGTERM");
545
+ } catch {
546
+ child.kill("SIGTERM");
547
+ }
548
+ }
549
+ await sleep(100);
550
+ childProcess = void 0;
551
+ },
552
+ async deprovision() {
553
+ const current = active;
554
+ if (!current) {
555
+ reset();
556
+ return;
557
+ }
558
+ if (current.mode === "named") {
559
+ const client = requireApi();
560
+ const accountIdValue = current.accountId;
561
+ const tunnelId = current.handle.tunnelId;
562
+ if (accountIdValue) {
563
+ await client.cleanupConnections(accountIdValue, tunnelId).catch(() => {
564
+ });
565
+ try {
566
+ await client.deleteTunnel(accountIdValue, tunnelId);
567
+ } catch (error) {
568
+ const retryable = error instanceof AdapterError && /active connection|connections/i.test(error.message);
569
+ if (!retryable) {
570
+ if (error instanceof AdapterError && error.code === "NOT_FOUND") {
571
+ reset();
572
+ return;
573
+ }
574
+ throw error;
575
+ }
576
+ await client.cleanupConnections(accountIdValue, tunnelId).catch(() => {
577
+ });
578
+ await client.deleteTunnel(accountIdValue, tunnelId);
579
+ }
580
+ }
581
+ }
582
+ reset();
583
+ },
584
+ async status(_ctx, handle) {
585
+ const named = handle.meta?.mode === "named";
586
+ if (!named || !handle.meta?.accountId) {
587
+ return {
588
+ state: handle.publicUrl ? "connected" : "starting",
589
+ connections: handle.publicUrl ? 1 : 0,
590
+ publicUrl: handle.publicUrl
591
+ };
592
+ }
593
+ const client = requireApi();
594
+ const tunnel = await client.getTunnel(handle.meta.accountId, handle.tunnelId);
595
+ const connections = tunnel.connections?.length ?? 0;
596
+ return {
597
+ state: tunnel.status === "healthy" ? "connected" : "starting",
598
+ connections,
599
+ publicUrl: handle.publicUrl
600
+ };
601
+ }
602
+ };
603
+ }
604
+ const cloudflareTunnel = createCloudflareTunnel();
605
+
606
+ const CLOUDFLARE_DNS_ADAPTER_ID = "cloudflare";
607
+ const CLOUDFLARE_TUNNEL_ADAPTER_ID = "cloudflare";
608
+ const CLOUDFLARE_API_BASE = "https://api.cloudflare.com/client/v4";
609
+
610
+ export { CLOUDFLARE_API_BASE, CLOUDFLARE_DNS_ADAPTER_ID, CLOUDFLARE_TUNNEL_ADAPTER_ID, CloudflareApi, cloudflareTunnel, createCloudflareDns, createCloudflareTunnel };
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "@flash-tunnel/adapter-cloudflare",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "type": "module",
4
+ "version": "0.0.1",
5
+ "license": "MIT",
6
+ "homepage": "https://github.com/flash-tunnel/flash-tunnel#readme",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/flash-tunnel/flash-tunnel.git"
10
+ },
11
+ "bugs": {
12
+ "url": "https://github.com/flash-tunnel/flash-tunnel/issues"
13
+ },
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.mts",
17
+ "import": "./dist/index.mjs",
18
+ "default": "./dist/index.mjs"
19
+ }
20
+ },
21
+ "main": "./dist/index.mjs",
22
+ "types": "./dist/index.d.mts",
23
+ "files": [
24
+ "dist"
25
+ ],
26
+ "engines": {
27
+ "node": ">=22.14.0"
28
+ },
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "dependencies": {
33
+ "@flash-tunnel/types": "0.0.1",
34
+ "@flash-tunnel/utils": "0.0.1"
35
+ },
36
+ "scripts": {
37
+ "stub": "unbuild --stub",
38
+ "build": "unbuild",
39
+ "typecheck": "tsc --noEmit"
40
+ }
6
41
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.