@myrialabs/clopen 0.3.18 → 0.3.20
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/backend/chat/stream-manager.ts +11 -1
- package/backend/database/migrations/039_create_file_audit_log.ts +45 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/file-audit-log-queries.test.ts +377 -0
- package/backend/database/queries/file-audit-log-queries.ts +184 -0
- package/backend/database/queries/index.ts +2 -1
- package/backend/db-client/drivers/mongodb.ts +52 -0
- package/backend/db-client/drivers/mysql.ts +168 -11
- package/backend/db-client/drivers/postgres.ts +182 -19
- package/backend/db-client/drivers/redis.ts +27 -0
- package/backend/db-client/drivers/sqlite.ts +66 -0
- package/backend/db-client/drivers/types.ts +13 -0
- package/backend/engine/install-recipes.ts +1 -109
- package/backend/http/files-upload.ts +84 -3
- package/backend/preview/browser/browser-preview-service.ts +44 -11
- package/backend/snapshot/snapshot-service.ts +82 -52
- package/backend/tunnel/tunnel-config.ts +76 -209
- package/backend/utils/client-ip.test.ts +55 -0
- package/backend/utils/client-ip.ts +42 -0
- package/backend/utils/ws.ts +6 -3
- package/backend/ws/auth/login.test.ts +271 -0
- package/backend/ws/auth/login.ts +36 -3
- package/backend/ws/auth/users.ts +3 -2
- package/backend/ws/db-client/schema.ts +14 -0
- package/backend/ws/db-client/structure.ts +120 -0
- package/backend/ws/files/path-access.test.ts +60 -1
- package/backend/ws/files/path-access.ts +21 -0
- package/backend/ws/snapshot/restore.ts +34 -29
- package/backend/ws/system-tools/install.ts +0 -1
- package/backend/ws/system-tools/status.ts +3 -4
- package/backend/ws/tunnel/config.ts +17 -25
- package/backend/ws/tunnel/operations.ts +63 -68
- package/dist/assets/{main-CaqEjA6B.js → main-72Z_L-nD.js} +224 -223
- package/dist/assets/main-ClADBkFf.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +2 -1
- package/shared/types/db-client/query.ts +9 -0
- package/shared/utils/ws-client.ts +188 -38
- package/backend/tunnel/cloudflared/binary.ts +0 -171
- package/backend/tunnel/cloudflared/index.ts +0 -24
- package/backend/tunnel/cloudflared/tunnel.ts +0 -444
- package/backend/tunnel/global-tunnel-manager.ts +0 -687
- package/backend/tunnel/project-tunnel-manager.ts +0 -264
- package/dist/assets/main-6cCq8H0w.css +0 -1
|
@@ -196,6 +196,64 @@ function decodeBinaryMessage(buffer: ArrayBuffer): { action: string; payload: an
|
|
|
196
196
|
return { action, payload };
|
|
197
197
|
}
|
|
198
198
|
|
|
199
|
+
// ============================================================================
|
|
200
|
+
// HTTP Request Resilience
|
|
201
|
+
// ============================================================================
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* An in-flight `http()` request, tracked so it can survive a transport hiccup.
|
|
205
|
+
*
|
|
206
|
+
* The browser WebSocket can silently lose a frame when the connection drops
|
|
207
|
+
* but `onclose` has not fired yet, or when the socket is "open" yet actually
|
|
208
|
+
* dead (a black-holed tunnel/network). When that happens to a request frame the
|
|
209
|
+
* server never replies, and the request used to just hang until its 30s
|
|
210
|
+
* timeout. We keep the request here so it can be re-sent on reconnect.
|
|
211
|
+
*/
|
|
212
|
+
interface PendingHttpRequest {
|
|
213
|
+
action: string;
|
|
214
|
+
/** Full wire payload `{ requestId, data }` — re-sent verbatim on resend. */
|
|
215
|
+
payload: any;
|
|
216
|
+
/** Whether the request was actually flushed to an OPEN socket. */
|
|
217
|
+
sent: boolean;
|
|
218
|
+
/** Number of automatic recovery attempts already spent. */
|
|
219
|
+
attempts: number;
|
|
220
|
+
/** (Re)arm the per-request timeout clock. */
|
|
221
|
+
arm: () => void;
|
|
222
|
+
/** Tear down: clear timeout, unsubscribe the response listener, drop from map. */
|
|
223
|
+
cleanup: () => void;
|
|
224
|
+
/** Settle the request as failed (used when the client is torn down). */
|
|
225
|
+
fail: (err: Error) => void;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Verbs that mark an action as a side-effect-free read, safe to auto-resend. */
|
|
229
|
+
const IDEMPOTENT_VERB_PREFIXES = [
|
|
230
|
+
'list',
|
|
231
|
+
'read',
|
|
232
|
+
'get',
|
|
233
|
+
'browse',
|
|
234
|
+
'search',
|
|
235
|
+
'fetch',
|
|
236
|
+
'load',
|
|
237
|
+
'status',
|
|
238
|
+
'info',
|
|
239
|
+
'check',
|
|
240
|
+
'exists',
|
|
241
|
+
'count',
|
|
242
|
+
'query'
|
|
243
|
+
];
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Is this action safe to transparently re-send after a reconnect?
|
|
247
|
+
*
|
|
248
|
+
* Only reads qualify. Re-sending a mutation (create/write/delete/…) whose
|
|
249
|
+
* response was lost in a hiccup could double-apply it, so anything that is not
|
|
250
|
+
* a recognised read verb is treated as non-idempotent and never auto-resent.
|
|
251
|
+
*/
|
|
252
|
+
function isIdempotentHttpAction(action: string): boolean {
|
|
253
|
+
const verb = (action.split(':').pop() || '').toLowerCase();
|
|
254
|
+
return IDEMPOTENT_VERB_PREFIXES.some((p) => verb.startsWith(p));
|
|
255
|
+
}
|
|
256
|
+
|
|
199
257
|
// ============================================================================
|
|
200
258
|
// WebSocket Client
|
|
201
259
|
// ============================================================================
|
|
@@ -215,6 +273,11 @@ export class WSClient<TAPI extends { client: any; server: any }> {
|
|
|
215
273
|
private shouldReconnect = true;
|
|
216
274
|
private hasConnectedBefore = false;
|
|
217
275
|
|
|
276
|
+
/** In-flight HTTP requests, keyed by requestId, for resend-on-reconnect. */
|
|
277
|
+
private pendingHttpRequests = new Map<string, PendingHttpRequest>();
|
|
278
|
+
/** Prevents a heal-reconnect stampede when many requests time out at once. */
|
|
279
|
+
private healingReconnect = false;
|
|
280
|
+
|
|
218
281
|
/** Current context (synced with server) */
|
|
219
282
|
private context: {
|
|
220
283
|
userId: string | null;
|
|
@@ -312,12 +375,28 @@ export class WSClient<TAPI extends { client: any; server: any }> {
|
|
|
312
375
|
}
|
|
313
376
|
}
|
|
314
377
|
|
|
315
|
-
//
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
378
|
+
// A fresh socket is live again — clear the heal guard so future
|
|
379
|
+
// dead-connection recoveries can fire.
|
|
380
|
+
this.healingReconnect = false;
|
|
381
|
+
|
|
382
|
+
// Flush queued fire-and-forget messages AFTER context + room
|
|
383
|
+
// re-joins are synced. Drain into a local array first so a send
|
|
384
|
+
// that re-queues (socket died mid-flush) can't spin this loop.
|
|
385
|
+
const queued = this.messageQueue;
|
|
386
|
+
this.messageQueue = [];
|
|
387
|
+
for (const msg of queued) {
|
|
388
|
+
this.sendRaw(msg.action, msg.payload);
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
// Re-deliver in-flight HTTP requests that the previous socket may
|
|
392
|
+
// have swallowed. Reads (idempotent) are always safe to resend;
|
|
393
|
+
// non-idempotent requests are only resent if they were never
|
|
394
|
+
// actually delivered (so the server has not seen them yet).
|
|
395
|
+
for (const entry of this.pendingHttpRequests.values()) {
|
|
396
|
+
if (entry.sent && !isIdempotentHttpAction(entry.action)) continue;
|
|
397
|
+
entry.sent = true;
|
|
398
|
+
this.sendRaw(entry.action, entry.payload);
|
|
399
|
+
entry.arm();
|
|
321
400
|
}
|
|
322
401
|
|
|
323
402
|
// Resolve waitUntilConnected() callers AFTER everything is ready
|
|
@@ -457,7 +536,11 @@ export class WSClient<TAPI extends { client: any; server: any }> {
|
|
|
457
536
|
action: TEvent,
|
|
458
537
|
payload: TAPI['client'][TEvent]
|
|
459
538
|
): void {
|
|
460
|
-
|
|
539
|
+
// Gate on the real socket state, not the manually-tracked `isConnected`
|
|
540
|
+
// flag. There is a window where the socket is already CLOSING/CLOSED but
|
|
541
|
+
// `onclose` has not run yet (`isConnected` still true); sending then would
|
|
542
|
+
// be silently dropped by sendRaw and the caller would hang. Queue instead.
|
|
543
|
+
if (this.isSocketOpen()) {
|
|
461
544
|
this.sendRaw(action as string, payload);
|
|
462
545
|
} else {
|
|
463
546
|
// Queue message for sending when connected
|
|
@@ -466,12 +549,22 @@ export class WSClient<TAPI extends { client: any; server: any }> {
|
|
|
466
549
|
}
|
|
467
550
|
}
|
|
468
551
|
|
|
552
|
+
/** True only when the underlying socket is genuinely OPEN and writable. */
|
|
553
|
+
private isSocketOpen(): boolean {
|
|
554
|
+
return !!this.ws && this.ws.readyState === WebSocket.OPEN;
|
|
555
|
+
}
|
|
556
|
+
|
|
469
557
|
/**
|
|
470
558
|
* Send raw message (JSON or Binary based on payload content)
|
|
471
559
|
*/
|
|
472
560
|
private sendRaw(action: string, payload: any): void {
|
|
473
|
-
if (!this.
|
|
474
|
-
|
|
561
|
+
if (!this.isSocketOpen()) {
|
|
562
|
+
// Socket not writable — re-queue instead of dropping so the message is
|
|
563
|
+
// delivered after (re)connect. Dropping here is what made ws.http()
|
|
564
|
+
// callers hang until their timeout. The onopen flush drains into a
|
|
565
|
+
// local array, so re-queuing during a flush cannot spin the loop.
|
|
566
|
+
debug.log('websocket', 'Socket not ready, re-queuing:', action);
|
|
567
|
+
this.messageQueue.push({ action, payload });
|
|
475
568
|
return;
|
|
476
569
|
}
|
|
477
570
|
|
|
@@ -479,15 +572,17 @@ export class WSClient<TAPI extends { client: any; server: any }> {
|
|
|
479
572
|
if (isBinaryAction(action, payload)) {
|
|
480
573
|
// Send as binary message
|
|
481
574
|
const binaryMessage = encodeBinaryMessage(action, payload);
|
|
482
|
-
this.ws
|
|
575
|
+
this.ws!.send(binaryMessage);
|
|
483
576
|
debug.log('websocket', 'Sent binary:', action, `(${binaryMessage.byteLength} bytes)`);
|
|
484
577
|
} else {
|
|
485
578
|
// Send as JSON message
|
|
486
|
-
this.ws
|
|
579
|
+
this.ws!.send(JSON.stringify({ action, payload }));
|
|
487
580
|
debug.log('websocket', 'Sent JSON:', action);
|
|
488
581
|
}
|
|
489
582
|
} catch (err) {
|
|
490
|
-
|
|
583
|
+
// The socket died mid-send — re-queue for delivery after reconnect.
|
|
584
|
+
debug.error('websocket', 'Send error, re-queuing:', err);
|
|
585
|
+
this.messageQueue.push({ action, payload });
|
|
491
586
|
}
|
|
492
587
|
}
|
|
493
588
|
|
|
@@ -549,6 +644,13 @@ export class WSClient<TAPI extends { client: any; server: any }> {
|
|
|
549
644
|
this.messageQueue = [];
|
|
550
645
|
this.isConnected = false;
|
|
551
646
|
|
|
647
|
+
// Fail any in-flight HTTP requests — no socket will come back to answer
|
|
648
|
+
// them after an explicit disconnect (page unload / HMR dispose).
|
|
649
|
+
for (const entry of [...this.pendingHttpRequests.values()]) {
|
|
650
|
+
entry.fail(new Error('WebSocket disconnected'));
|
|
651
|
+
}
|
|
652
|
+
this.pendingHttpRequests.clear();
|
|
653
|
+
|
|
552
654
|
debug.log('websocket', 'Disconnected and cleaned up');
|
|
553
655
|
}
|
|
554
656
|
|
|
@@ -761,6 +863,14 @@ export class WSClient<TAPI extends { client: any; server: any }> {
|
|
|
761
863
|
* - If `success: true` → returns `data` directly
|
|
762
864
|
* - If `success: false` → throws Error with `error` message
|
|
763
865
|
* - Timeout → throws Error
|
|
866
|
+
*
|
|
867
|
+
* Resilience: the request is tracked in `pendingHttpRequests` and survives a
|
|
868
|
+
* transport hiccup. If the socket drops, idempotent reads (and any request
|
|
869
|
+
* never actually delivered) are re-sent automatically on reconnect, and a
|
|
870
|
+
* read that times out against a seemingly-open-but-dead socket forces one
|
|
871
|
+
* heal-reconnect + retry before giving up. This is what stops sporadic
|
|
872
|
+
* "Request timeout: files:list-tree (30000ms)" errors that used to need a
|
|
873
|
+
* manual Retry.
|
|
764
874
|
*/
|
|
765
875
|
http<TAction extends keyof TAPI['client']>(
|
|
766
876
|
action: TAction,
|
|
@@ -771,23 +881,68 @@ export class WSClient<TAPI extends { client: any; server: any }> {
|
|
|
771
881
|
? TData
|
|
772
882
|
: any
|
|
773
883
|
> {
|
|
774
|
-
const
|
|
884
|
+
const actionStr = action as string;
|
|
885
|
+
const responseAction = `${actionStr}:response` as any;
|
|
775
886
|
// Generate unique request ID to match request with response
|
|
776
|
-
const requestId = `${
|
|
887
|
+
const requestId = `${actionStr}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
|
|
888
|
+
const payload = { requestId, data: data || {} };
|
|
889
|
+
// Reads can be safely re-sent; mutations can only be re-sent if they were
|
|
890
|
+
// never delivered (tracked via `entry.sent`).
|
|
891
|
+
const idempotent = isIdempotentHttpAction(actionStr);
|
|
892
|
+
// Up to this many automatic heal-reconnect retries for idempotent reads.
|
|
893
|
+
const MAX_HEAL_ATTEMPTS = 2;
|
|
777
894
|
|
|
778
895
|
return new Promise((resolve, reject) => {
|
|
779
896
|
let unsubResponse: (() => void) | null = null;
|
|
780
897
|
let timeoutId: ReturnType<typeof setTimeout> | null = null;
|
|
781
898
|
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
899
|
+
const entry: PendingHttpRequest = {
|
|
900
|
+
action: actionStr,
|
|
901
|
+
payload,
|
|
902
|
+
sent: false,
|
|
903
|
+
attempts: 0,
|
|
904
|
+
arm: () => {
|
|
905
|
+
if (timeout <= 0) return;
|
|
906
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
907
|
+
timeoutId = setTimeout(onTimeout, timeout);
|
|
908
|
+
},
|
|
909
|
+
cleanup: () => {
|
|
910
|
+
unsubResponse?.();
|
|
911
|
+
if (timeoutId) {
|
|
912
|
+
clearTimeout(timeoutId);
|
|
913
|
+
timeoutId = null;
|
|
914
|
+
}
|
|
915
|
+
this.pendingHttpRequests.delete(requestId);
|
|
916
|
+
},
|
|
917
|
+
fail: (err: Error) => {
|
|
918
|
+
entry.cleanup();
|
|
919
|
+
reject(err);
|
|
788
920
|
}
|
|
789
921
|
};
|
|
790
922
|
|
|
923
|
+
// Timeout handler — for idempotent reads, try to heal a dead-but-open
|
|
924
|
+
// socket and retry instead of failing outright.
|
|
925
|
+
const onTimeout = () => {
|
|
926
|
+
if (idempotent && entry.attempts < MAX_HEAL_ATTEMPTS) {
|
|
927
|
+
entry.attempts++;
|
|
928
|
+
debug.warn(
|
|
929
|
+
'websocket',
|
|
930
|
+
`Request stalled, healing connection and retrying: ${actionStr} (attempt ${entry.attempts})`
|
|
931
|
+
);
|
|
932
|
+
entry.arm();
|
|
933
|
+
// If the socket still claims to be open, it is likely black-holed
|
|
934
|
+
// — force a reconnect (guarded against a stampede). The onopen
|
|
935
|
+
// resend loop will re-send this request on the fresh socket.
|
|
936
|
+
if (this.isSocketOpen() && !this.healingReconnect) {
|
|
937
|
+
this.healingReconnect = true;
|
|
938
|
+
this.reconnect();
|
|
939
|
+
}
|
|
940
|
+
return;
|
|
941
|
+
}
|
|
942
|
+
entry.cleanup();
|
|
943
|
+
reject(new Error(`Request timeout: ${actionStr} (${timeout}ms)`));
|
|
944
|
+
};
|
|
945
|
+
|
|
791
946
|
// Response handler - unwrap { success, data, error } response
|
|
792
947
|
const handleResponse = (response: any) => {
|
|
793
948
|
// Only handle response that matches this request ID
|
|
@@ -795,7 +950,7 @@ export class WSClient<TAPI extends { client: any; server: any }> {
|
|
|
795
950
|
return; // Ignore responses for other requests
|
|
796
951
|
}
|
|
797
952
|
|
|
798
|
-
cleanup();
|
|
953
|
+
entry.cleanup();
|
|
799
954
|
|
|
800
955
|
// Check if response has success field
|
|
801
956
|
if (response && typeof response === 'object' && 'success' in response) {
|
|
@@ -812,24 +967,19 @@ export class WSClient<TAPI extends { client: any; server: any }> {
|
|
|
812
967
|
}
|
|
813
968
|
};
|
|
814
969
|
|
|
815
|
-
//
|
|
816
|
-
if (timeout > 0) {
|
|
817
|
-
timeoutId = setTimeout(() => {
|
|
818
|
-
cleanup();
|
|
819
|
-
reject(new Error(`Request timeout: ${action as string} (${timeout}ms)`));
|
|
820
|
-
}, timeout);
|
|
821
|
-
}
|
|
822
|
-
|
|
823
|
-
// Register response listener
|
|
970
|
+
// Register response listener + track the request, then deliver.
|
|
824
971
|
unsubResponse = this.on(responseAction, handleResponse);
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
972
|
+
this.pendingHttpRequests.set(requestId, entry);
|
|
973
|
+
entry.arm();
|
|
974
|
+
|
|
975
|
+
// Deliver directly (not via the fire-and-forget queue) so resend on
|
|
976
|
+
// reconnect is driven solely by `pendingHttpRequests` — no double-send.
|
|
977
|
+
if (this.isSocketOpen()) {
|
|
978
|
+
entry.sent = true;
|
|
979
|
+
this.sendRaw(actionStr, payload);
|
|
980
|
+
}
|
|
981
|
+
// If not open, the request stays pending and the onopen resend loop
|
|
982
|
+
// delivers it once the socket is back.
|
|
833
983
|
});
|
|
834
984
|
}
|
|
835
985
|
}
|
|
@@ -1,171 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Cloudflared Binary Manager
|
|
3
|
-
*
|
|
4
|
-
* Handles resolving and managing the cloudflared binary.
|
|
5
|
-
*
|
|
6
|
-
* Primary install path is ~/.clopen/bin/cloudflared (.clopen-dev in dev), which
|
|
7
|
-
* the System Tools installer downloads from GitHub releases. A system-wide
|
|
8
|
-
* cloudflared (e.g. brew, apt) is also honored via PATH so users who already
|
|
9
|
-
* have it on their machine don't have to install through clopen.
|
|
10
|
-
*
|
|
11
|
-
* installBinary() is kept for programmatic use (CLI, one-off scripts) but
|
|
12
|
-
* the server never auto-downloads — tunnel flows fail with a pointer to
|
|
13
|
-
* Settings → System Tools when the binary is missing.
|
|
14
|
-
*/
|
|
15
|
-
|
|
16
|
-
import { existsSync, mkdirSync, createWriteStream, chmodSync, unlinkSync, renameSync } from 'fs';
|
|
17
|
-
import { join, dirname } from 'path';
|
|
18
|
-
import { platform, arch } from 'os';
|
|
19
|
-
import { execFileSync } from 'child_process';
|
|
20
|
-
import { getClopenDir } from '../../utils/paths';
|
|
21
|
-
import { resolveBinary } from '../../utils/cli';
|
|
22
|
-
import { debug } from '$shared/utils/logger';
|
|
23
|
-
|
|
24
|
-
const RELEASE_BASE = 'https://github.com/cloudflare/cloudflared/releases/';
|
|
25
|
-
|
|
26
|
-
/** Platform-specific download filenames */
|
|
27
|
-
const LINUX_FILES: Record<string, string> = {
|
|
28
|
-
arm64: 'cloudflared-linux-arm64',
|
|
29
|
-
arm: 'cloudflared-linux-arm',
|
|
30
|
-
x64: 'cloudflared-linux-amd64',
|
|
31
|
-
ia32: 'cloudflared-linux-386'
|
|
32
|
-
};
|
|
33
|
-
|
|
34
|
-
const MACOS_FILES: Record<string, string> = {
|
|
35
|
-
arm64: 'cloudflared-darwin-arm64.tgz',
|
|
36
|
-
x64: 'cloudflared-darwin-amd64.tgz'
|
|
37
|
-
};
|
|
38
|
-
|
|
39
|
-
const WINDOWS_FILES: Record<string, string> = {
|
|
40
|
-
x64: 'cloudflared-windows-amd64.exe',
|
|
41
|
-
ia32: 'cloudflared-windows-386.exe'
|
|
42
|
-
};
|
|
43
|
-
|
|
44
|
-
/** Get the path where the cloudflared binary should be stored */
|
|
45
|
-
export function getBinaryPath(): string {
|
|
46
|
-
const binDir = join(getClopenDir(), 'bin');
|
|
47
|
-
const name = platform() === 'win32' ? 'cloudflared.exe' : 'cloudflared';
|
|
48
|
-
return join(binDir, name);
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
/** Check if binary exists */
|
|
52
|
-
export function isBinaryInstalled(): boolean {
|
|
53
|
-
return existsSync(getBinaryPath());
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
/**
|
|
57
|
-
* Resolve an executable cloudflared binary. Prefers the System Tools install
|
|
58
|
-
* under ~/.clopen/bin; falls back to any cloudflared on PATH so users who
|
|
59
|
-
* installed it via brew/apt/winget don't have to reinstall via clopen.
|
|
60
|
-
* Returns null when nothing is found.
|
|
61
|
-
*/
|
|
62
|
-
export function resolveCloudflaredBinary(): string | null {
|
|
63
|
-
const managed = getBinaryPath();
|
|
64
|
-
if (existsSync(managed)) return managed;
|
|
65
|
-
return resolveBinary('cloudflared');
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
/** Download a file via HTTPS, following redirects */
|
|
69
|
-
function download(url: string, to: string, redirect = 0): Promise<string> {
|
|
70
|
-
if (redirect > 10) {
|
|
71
|
-
return Promise.reject(new Error('Too many redirects'));
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
const dir = dirname(to);
|
|
75
|
-
if (!existsSync(dir)) {
|
|
76
|
-
mkdirSync(dir, { recursive: true });
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
return new Promise((resolve, reject) => {
|
|
80
|
-
const protocol = url.startsWith('https') ? require('https') : require('http');
|
|
81
|
-
|
|
82
|
-
const request = protocol.get(url, (res: any) => {
|
|
83
|
-
const redirectCodes = [301, 302, 303, 307, 308];
|
|
84
|
-
if (redirectCodes.includes(res.statusCode) && res.headers.location) {
|
|
85
|
-
request.destroy();
|
|
86
|
-
resolve(download(res.headers.location, to, redirect + 1));
|
|
87
|
-
return;
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
|
|
91
|
-
const file = createWriteStream(to);
|
|
92
|
-
file.on('finish', () => file.close(() => resolve(to)));
|
|
93
|
-
file.on('error', (err: Error) => {
|
|
94
|
-
try { unlinkSync(to); } catch { /* ignore */ }
|
|
95
|
-
reject(err);
|
|
96
|
-
});
|
|
97
|
-
res.pipe(file);
|
|
98
|
-
} else {
|
|
99
|
-
request.destroy();
|
|
100
|
-
reject(new Error(`HTTP ${res.statusCode} downloading cloudflared`));
|
|
101
|
-
}
|
|
102
|
-
});
|
|
103
|
-
|
|
104
|
-
request.on('error', (err: Error) => reject(err));
|
|
105
|
-
request.end();
|
|
106
|
-
});
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
/** Get the download URL for current platform/arch */
|
|
110
|
-
function getDownloadUrl(version = 'latest'): string {
|
|
111
|
-
const base = version === 'latest'
|
|
112
|
-
? `${RELEASE_BASE}latest/download/`
|
|
113
|
-
: `${RELEASE_BASE}download/${version}/`;
|
|
114
|
-
|
|
115
|
-
const os = platform();
|
|
116
|
-
const a = arch();
|
|
117
|
-
|
|
118
|
-
if (os === 'linux') {
|
|
119
|
-
const file = LINUX_FILES[a];
|
|
120
|
-
if (!file) throw new Error(`Unsupported Linux architecture: ${a}`);
|
|
121
|
-
return base + file;
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
if (os === 'darwin') {
|
|
125
|
-
const file = MACOS_FILES[a];
|
|
126
|
-
if (!file) throw new Error(`Unsupported macOS architecture: ${a}`);
|
|
127
|
-
return base + file;
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
if (os === 'win32') {
|
|
131
|
-
const file = WINDOWS_FILES[a];
|
|
132
|
-
if (!file) throw new Error(`Unsupported Windows architecture: ${a}`);
|
|
133
|
-
return base + file;
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
throw new Error(`Unsupported platform: ${os}`);
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
/** Install cloudflared binary for the current platform */
|
|
140
|
-
export async function installBinary(version = 'latest'): Promise<string> {
|
|
141
|
-
const binPath = getBinaryPath();
|
|
142
|
-
const url = getDownloadUrl(version);
|
|
143
|
-
const os = platform();
|
|
144
|
-
|
|
145
|
-
debug.log('tunnel', `Downloading cloudflared from ${url}`);
|
|
146
|
-
|
|
147
|
-
if (os === 'darwin') {
|
|
148
|
-
// macOS: download .tgz, extract, rename
|
|
149
|
-
const tgzPath = `${binPath}.tgz`;
|
|
150
|
-
await download(url, tgzPath);
|
|
151
|
-
execFileSync('tar', ['-xzf', tgzPath], { cwd: dirname(binPath), stdio: 'pipe' });
|
|
152
|
-
unlinkSync(tgzPath);
|
|
153
|
-
// tar extracts as "cloudflared" in the same directory
|
|
154
|
-
const extractedPath = join(dirname(binPath), 'cloudflared');
|
|
155
|
-
if (extractedPath !== binPath && existsSync(extractedPath)) {
|
|
156
|
-
renameSync(extractedPath, binPath);
|
|
157
|
-
}
|
|
158
|
-
} else if (os === 'linux') {
|
|
159
|
-
await download(url, binPath);
|
|
160
|
-
chmodSync(binPath, '755');
|
|
161
|
-
} else if (os === 'win32') {
|
|
162
|
-
await download(url, binPath);
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
if (!existsSync(binPath)) {
|
|
166
|
-
throw new Error('Binary was not created after installation');
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
debug.log('tunnel', `Cloudflared binary installed at: ${binPath}`);
|
|
170
|
-
return binPath;
|
|
171
|
-
}
|
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Cloudflared Module
|
|
3
|
-
*
|
|
4
|
-
* Custom replacement for the `cloudflared` npm package.
|
|
5
|
-
* Provides binary management and tunnel process control.
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
export { getBinaryPath, isBinaryInstalled, installBinary, resolveCloudflaredBinary } from './binary';
|
|
9
|
-
export {
|
|
10
|
-
CloudflaredTunnel,
|
|
11
|
-
CloudflaredMissingError,
|
|
12
|
-
type ConnectionInfo,
|
|
13
|
-
type LoginHandle,
|
|
14
|
-
type LoginCallbacks,
|
|
15
|
-
type LoginOptions,
|
|
16
|
-
type CreateTunnelOptions,
|
|
17
|
-
type CreateTunnelResult,
|
|
18
|
-
type DeleteTunnelOptions,
|
|
19
|
-
type DeleteTunnelResult,
|
|
20
|
-
type RouteDnsOptions,
|
|
21
|
-
type RouteDnsResult,
|
|
22
|
-
type ListTunnelsOptions,
|
|
23
|
-
type TunnelListEntry
|
|
24
|
-
} from './tunnel';
|