@linxin666/dsh-remote-bridge 0.4.13 → 0.4.14
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/README.i18n.yaml +2 -2
- package/README.md +13 -8
- package/README.zh.md +13 -8
- package/lib/client.js +112 -90
- package/lib/client.js.map +1 -1
- package/lib/index.js +873 -65
- package/lib/types/client/PairPanel.d.ts +7 -0
- package/lib/types/client/locales.d.ts +13 -10
- package/lib/types/core/connection.d.ts +41 -0
- package/lib/types/core/devices.d.ts +60 -7
- package/lib/types/core/protocol.d.ts +22 -0
- package/lib/types/core/push.d.ts +19 -1
- package/lib/types/host/relay-bridge-connector.d.ts +19 -0
- package/lib/types/host/relay-connector.d.ts +4 -0
- package/lib/types/host/relay-control.d.ts +77 -6
- package/lib/types/host/relay-registry.d.ts +12 -3
- package/lib/types/host/relay-secondary.d.ts +209 -0
- package/lib/types/host/relay.d.ts +1 -1
- package/lib/types/host/routes.d.ts +5 -0
- package/lib/types/index.d.ts +65 -3
- package/package.json +1 -1
- package/src/client/PairPanel.tsx +21 -0
- package/src/client/locales.ts +19 -15
- package/src/client/panel.module.css +32 -0
- package/src/core/connection.ts +110 -0
- package/src/core/devices.ts +141 -17
- package/src/core/protocol.ts +24 -0
- package/src/core/push.ts +20 -1
- package/src/host/relay-bridge-connector.ts +68 -2
- package/src/host/relay-connector.ts +9 -2
- package/src/host/relay-control.ts +98 -7
- package/src/host/relay-registry.ts +17 -5
- package/src/host/relay-secondary.ts +478 -0
- package/src/host/relay.ts +1 -1
- package/src/host/routes.ts +10 -0
- package/src/index.ts +270 -35
package/lib/index.js
CHANGED
|
@@ -294,6 +294,34 @@ function pushOf(value, log) {
|
|
|
294
294
|
registeredAt: typeof row.registeredAt === "number" ? row.registeredAt : 0
|
|
295
295
|
};
|
|
296
296
|
}
|
|
297
|
+
/**
|
|
298
|
+
* Read one row's `relay` block.
|
|
299
|
+
*
|
|
300
|
+
* Dropped rather than quarantined for the reason `pushOf` is: one unreadable grant
|
|
301
|
+
* is not a reason to un-pair every phone, and the row keeps its identity and simply
|
|
302
|
+
* carries no admission. The two fields are the whole block — a grant text and the
|
|
303
|
+
* epoch second it arrived in — so anything else on that object is discarded instead
|
|
304
|
+
* of being handed on to a claim body.
|
|
305
|
+
* @param value - the raw `relay` field of a row.
|
|
306
|
+
* @param log - where a dropped block is reported.
|
|
307
|
+
* @returns the grant, or undefined when there is none to read.
|
|
308
|
+
*/
|
|
309
|
+
function relayOf(value, log) {
|
|
310
|
+
if (value === void 0) return void 0;
|
|
311
|
+
if (typeof value !== "object" || value === null) {
|
|
312
|
+
log("a device row carries an unreadable relay block; ignoring it and keeping the row");
|
|
313
|
+
return;
|
|
314
|
+
}
|
|
315
|
+
const row = value;
|
|
316
|
+
if (typeof row.grant !== "string" || row.grant === "" || typeof row.receivedAt !== "number" || !Number.isFinite(row.receivedAt)) {
|
|
317
|
+
log("a device row carries an unreadable relay block; ignoring it and keeping the row");
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
return {
|
|
321
|
+
grant: row.grant,
|
|
322
|
+
receivedAt: row.receivedAt
|
|
323
|
+
};
|
|
324
|
+
}
|
|
297
325
|
function isStoredDevice(value) {
|
|
298
326
|
if (typeof value !== "object" || value === null) return false;
|
|
299
327
|
const row = value;
|
|
@@ -443,6 +471,53 @@ var DeviceRoster = class {
|
|
|
443
471
|
return false;
|
|
444
472
|
}
|
|
445
473
|
/**
|
|
474
|
+
* Record the relay grant one device just handed over (schema 4).
|
|
475
|
+
*
|
|
476
|
+
* A grant the phone resends replaces the one on the row: the account service
|
|
477
|
+
* reissues them periodically, and the newest text is the one the second meeting
|
|
478
|
+
* point will verify against the current plan. Nothing else on the row moves, so a
|
|
479
|
+
* grant that arrives between two reconnects cannot disturb a push registration.
|
|
480
|
+
* @param deviceId - the device that sent `relay.grant`.
|
|
481
|
+
* @param grant - the grant text as the account service issued it.
|
|
482
|
+
* @returns false when no such device is paired.
|
|
483
|
+
*/
|
|
484
|
+
async setRelayGrant(deviceId, grant) {
|
|
485
|
+
const receivedAt = Math.floor(this.#now() / 1e3);
|
|
486
|
+
for (const [hash, row] of this.#devices) {
|
|
487
|
+
if (row.deviceId !== deviceId) continue;
|
|
488
|
+
this.#devices.set(hash, {
|
|
489
|
+
...row,
|
|
490
|
+
relay: {
|
|
491
|
+
grant,
|
|
492
|
+
receivedAt
|
|
493
|
+
}
|
|
494
|
+
});
|
|
495
|
+
await this.#persist();
|
|
496
|
+
return true;
|
|
497
|
+
}
|
|
498
|
+
return false;
|
|
499
|
+
}
|
|
500
|
+
/**
|
|
501
|
+
* @returns the relay grant this bridge claims with, or undefined when no row
|
|
502
|
+
* holds one.
|
|
503
|
+
*
|
|
504
|
+
* The newest one wins, because one host holds one lease at the second meeting
|
|
505
|
+
* point and the phone that most recently handed a grant over is the one whose
|
|
506
|
+
* subscription is being claimed. A pairing with several phones of mixed tiers is
|
|
507
|
+
* then the accepted asymmetry the design names: the host is admitted while at
|
|
508
|
+
* least one paired phone holds a tier that is, and the free-tier phone simply
|
|
509
|
+
* keeps using the market edge.
|
|
510
|
+
*/
|
|
511
|
+
relayGrant() {
|
|
512
|
+
let newest;
|
|
513
|
+
for (const row of this.#devices.values()) {
|
|
514
|
+
const held = row.relay;
|
|
515
|
+
if (held === void 0) continue;
|
|
516
|
+
if (newest === void 0 || held.receivedAt > newest.receivedAt) newest = held;
|
|
517
|
+
}
|
|
518
|
+
return newest;
|
|
519
|
+
}
|
|
520
|
+
/**
|
|
446
521
|
* Forget one Live Activity token the phone no longer holds.
|
|
447
522
|
*
|
|
448
523
|
* APNs answers 410 (or 400 `BadDeviceToken`) for the token of a card the app
|
|
@@ -491,15 +566,8 @@ var DeviceRoster = class {
|
|
|
491
566
|
for (const [hash, row] of this.#devices) {
|
|
492
567
|
const registration = row.push;
|
|
493
568
|
if (registration === void 0 || registration.deviceToken !== deviceToken) continue;
|
|
494
|
-
const {
|
|
495
|
-
this.#devices.set(hash,
|
|
496
|
-
tokenHash,
|
|
497
|
-
deviceId,
|
|
498
|
-
pubKey,
|
|
499
|
-
fingerprint,
|
|
500
|
-
createdAt,
|
|
501
|
-
lastSeenAt
|
|
502
|
-
});
|
|
569
|
+
const { push: _dropped, ...rest } = row;
|
|
570
|
+
this.#devices.set(hash, rest);
|
|
503
571
|
await this.#persist();
|
|
504
572
|
return true;
|
|
505
573
|
}
|
|
@@ -557,15 +625,20 @@ var DeviceRoster = class {
|
|
|
557
625
|
this.#devices.delete(row.tokenHash);
|
|
558
626
|
rows += 1;
|
|
559
627
|
}
|
|
560
|
-
if (survivor.push !== void 0) continue;
|
|
561
628
|
let newest;
|
|
629
|
+
let newestGrant;
|
|
562
630
|
for (const row of held) {
|
|
563
|
-
if (row === survivor
|
|
564
|
-
if (newest === void 0 || row.push.registeredAt > newest.registeredAt) newest = row.push;
|
|
631
|
+
if (row === survivor) continue;
|
|
632
|
+
if (row.push !== void 0 && (newest === void 0 || row.push.registeredAt > newest.registeredAt)) newest = row.push;
|
|
633
|
+
if (row.relay !== void 0 && (newestGrant === void 0 || row.relay.receivedAt > newestGrant.receivedAt)) newestGrant = row.relay;
|
|
565
634
|
}
|
|
566
|
-
|
|
635
|
+
const push = survivor.push ?? newest;
|
|
636
|
+
const relay = survivor.relay ?? newestGrant;
|
|
637
|
+
if (push === survivor.push && relay === survivor.relay) continue;
|
|
638
|
+
this.#devices.set(survivor.tokenHash, {
|
|
567
639
|
...survivor,
|
|
568
|
-
push:
|
|
640
|
+
...push === void 0 ? {} : { push },
|
|
641
|
+
...relay === void 0 ? {} : { relay }
|
|
569
642
|
});
|
|
570
643
|
}
|
|
571
644
|
const holders = /* @__PURE__ */ new Map();
|
|
@@ -624,13 +697,15 @@ var DeviceRoster = class {
|
|
|
624
697
|
return;
|
|
625
698
|
}
|
|
626
699
|
const declared = parsed.version;
|
|
627
|
-
if (typeof declared === "number" && declared !==
|
|
700
|
+
if (typeof declared === "number" && declared !== 4) this.#log(`device roster ${this.#file} is schema ${declared}; reading it as 4`);
|
|
628
701
|
for (const row of rows) {
|
|
629
|
-
const { push: raw, ...rest } = row;
|
|
702
|
+
const { push: raw, relay: rawRelay, ...rest } = row;
|
|
630
703
|
const push = pushOf(raw, this.#log);
|
|
631
|
-
|
|
704
|
+
const relay = relayOf(rawRelay, this.#log);
|
|
705
|
+
this.#devices.set(row.tokenHash, {
|
|
632
706
|
...rest,
|
|
633
|
-
push
|
|
707
|
+
...push === void 0 ? {} : { push },
|
|
708
|
+
...relay === void 0 ? {} : { relay }
|
|
634
709
|
});
|
|
635
710
|
}
|
|
636
711
|
this.#log(`device roster ${this.#file}: ${rows.length} paired device(s)`);
|
|
@@ -666,7 +741,7 @@ var DeviceRoster = class {
|
|
|
666
741
|
mode: 448
|
|
667
742
|
});
|
|
668
743
|
const payload = JSON.stringify({
|
|
669
|
-
version:
|
|
744
|
+
version: 4,
|
|
670
745
|
devices: [...this.#devices.values()]
|
|
671
746
|
}, null, 2);
|
|
672
747
|
const temporary = `${this.#file}.${process.pid}.${randomBase64Url(6)}.tmp`;
|
|
@@ -732,6 +807,14 @@ const METHOD_USAGE_BALANCE = "usage.balance";
|
|
|
732
807
|
const METHOD_USAGE_STATS = "usage.stats";
|
|
733
808
|
const METHOD_UI_EVENT = "ui.event";
|
|
734
809
|
const METHOD_UI_LIST = "ui.list";
|
|
810
|
+
/**
|
|
811
|
+
* 一条配对连接把手机从账号服务换到的中继授权交给宿主。
|
|
812
|
+
*
|
|
813
|
+
* 它是这条通道唯一的写动作:授权落进那台设备自己的名册行,随后宿主拿它去第二
|
|
814
|
+
* 会合点申领租约。宿主不认识账号——它只会看到「准了」或「不准」,绝不会从这一帧
|
|
815
|
+
* 里读出用户是谁。只在配了第二会合点的宿主上是这个方法(见 {@link CAP_RELAY_TIER})。
|
|
816
|
+
*/
|
|
817
|
+
const METHOD_RELAY_GRANT = "relay.grant";
|
|
735
818
|
/** Server-pushed topics of protocol v1. */
|
|
736
819
|
const TOPIC_SESSION_DELTA = "session.delta";
|
|
737
820
|
const TOPIC_APPROVAL_REQUEST = "approval.request";
|
|
@@ -925,6 +1008,20 @@ const CAP_UI = "ui.v1";
|
|
|
925
1008
|
*/
|
|
926
1009
|
const CAP_UI_LIST = "ui.list.v1";
|
|
927
1010
|
/**
|
|
1011
|
+
* 宿主配了第二会合点时,在 `hello` 的 `capabilities` 里公告的能力名。
|
|
1012
|
+
*
|
|
1013
|
+
* 它是这条通道的全部门槛,而且门槛落在宿主这一侧:一个配了第二会合点的宿主才
|
|
1014
|
+
* 公告这个名字、才收 {@link METHOD_RELAY_GRANT},客户端读到它之后才把授权发过来。
|
|
1015
|
+
* 不配第二会合点的宿主——也就是缺省配置的每一台——公告表里没有这个名字,
|
|
1016
|
+
* `relay.grant` 对它仍是 `unknown-method`,名册里也不会因此多出一个块:缺省
|
|
1017
|
+
* 宿主的握手与名册与这条通道出现之前逐字相同。
|
|
1018
|
+
*
|
|
1019
|
+
* 正因为它是**条件**公告,{@link MINOR} 不随它抬格:minor 描述的是这个协议本身,
|
|
1020
|
+
* 而缺省宿主在线路上读不到任何新东西(设计冻结在 21)。客户端因此按名字判断而不是
|
|
1021
|
+
* 按 minor 判断:读不到这个名字就什么都不发。
|
|
1022
|
+
*/
|
|
1023
|
+
const CAP_RELAY_TIER = "relay.tier.v1";
|
|
1024
|
+
/**
|
|
928
1025
|
* Capability a client declares in `hello`'s `cap` array to be answered with
|
|
929
1026
|
* byte-level increments instead of the whole roster or the whole board.
|
|
930
1027
|
*
|
|
@@ -1117,7 +1214,8 @@ const KNOWN_METHODS = /* @__PURE__ */ new Set([
|
|
|
1117
1214
|
METHOD_USAGE_BALANCE,
|
|
1118
1215
|
METHOD_USAGE_STATS,
|
|
1119
1216
|
METHOD_UI_EVENT,
|
|
1120
|
-
METHOD_UI_LIST
|
|
1217
|
+
METHOD_UI_LIST,
|
|
1218
|
+
METHOD_RELAY_GRANT
|
|
1121
1219
|
]);
|
|
1122
1220
|
/** Refusal codes the bridge itself raises (DSH failures cross as their own code). */
|
|
1123
1221
|
const CODE_UNPAIRED = "unpaired";
|
|
@@ -2922,6 +3020,15 @@ var EventSequence = class {
|
|
|
2922
3020
|
/** The only deep-link form this channel emits. */
|
|
2923
3021
|
const PUSH_DEEP_LINK_PREFIX = "whale://session/";
|
|
2924
3022
|
/**
|
|
3023
|
+
* The one category a delivery may name (§28.4).
|
|
3024
|
+
*
|
|
3025
|
+
* A banner draws a button only where a category it knows is named, so this is the
|
|
3026
|
+
* identifier the client registered statically for the two approval answers. It is
|
|
3027
|
+
* the client's name rather than this bridge's: the bridge writes it verbatim and
|
|
3028
|
+
* holds no second opinion about what a button says.
|
|
3029
|
+
*/
|
|
3030
|
+
const PUSH_APPROVAL_CATEGORY = "dev.dsh.Whale.category.approval";
|
|
3031
|
+
/**
|
|
2925
3032
|
* The status line each event carries.
|
|
2926
3033
|
*
|
|
2927
3034
|
* Fixed strings on purpose: a body built out of host text would be session
|
|
@@ -2955,7 +3062,9 @@ function isDeadPushToken(failure) {
|
|
|
2955
3062
|
*
|
|
2956
3063
|
* Pure, and exported so the shape can be asserted without a sender: the keys
|
|
2957
3064
|
* are the contract, and the absence of any body text is the property that
|
|
2958
|
-
* matters most.
|
|
3065
|
+
* matters most. One key is conditional — an approval names the category the
|
|
3066
|
+
* client registered, because naming it is the only thing that makes a banner
|
|
3067
|
+
* draw a button, and every other event omits it so a banner stays buttonless.
|
|
2959
3068
|
* @param event - what happened.
|
|
2960
3069
|
* @param sessionId - the session it happened to.
|
|
2961
3070
|
* @param labels - the name and workspace short name, when the bridge holds them.
|
|
@@ -2968,7 +3077,8 @@ function buildPushNotification(event, sessionId, labels = {}) {
|
|
|
2968
3077
|
title: labels.title !== void 0 && labels.title !== "" ? labels.title : PUSH_BODY[event],
|
|
2969
3078
|
body: PUSH_BODY[event]
|
|
2970
3079
|
},
|
|
2971
|
-
sound: "default"
|
|
3080
|
+
sound: "default",
|
|
3081
|
+
...event === "approval" ? { category: PUSH_APPROVAL_CATEGORY } : {}
|
|
2972
3082
|
},
|
|
2973
3083
|
...labels.workspace === void 0 || labels.workspace === "" ? {} : { w: labels.workspace },
|
|
2974
3084
|
s: sessionId,
|
|
@@ -5770,6 +5880,7 @@ var BridgeConnection = class {
|
|
|
5770
5880
|
if (frame.m === "usage.stats" && !this.declares("usage.stats.v1")) return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`);
|
|
5771
5881
|
if (frame.m === "ui.event" && !this.declares("ui.v1")) return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`);
|
|
5772
5882
|
if (frame.m === "ui.list" && !this.declares("ui.list.v1")) return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`);
|
|
5883
|
+
if (frame.m === "relay.grant" && this.#options.relay === void 0) return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`);
|
|
5773
5884
|
if (!this.paired && !UNPAIRED_METHODS.has(frame.m)) return refusal(CODE_UNPAIRED, "this connection is not paired");
|
|
5774
5885
|
if (!builtIn) return await this.#extension(frame);
|
|
5775
5886
|
switch (frame.m) {
|
|
@@ -5794,6 +5905,7 @@ var BridgeConnection = class {
|
|
|
5794
5905
|
case METHOD_QUESTION_LIST: return this.#questionList(frame.p);
|
|
5795
5906
|
case METHOD_UI_EVENT: return this.#uiEvent(frame.p);
|
|
5796
5907
|
case METHOD_UI_LIST: return this.#uiList(frame.p);
|
|
5908
|
+
case METHOD_RELAY_GRANT: return await this.#relayGrant(frame.p);
|
|
5797
5909
|
case METHOD_PUSH_REGISTER: return await this.#pushRegister(frame.p);
|
|
5798
5910
|
case METHOD_USAGE_SESSION: return await this.#usageSession(frame.p);
|
|
5799
5911
|
case METHOD_USAGE_BALANCE: return await this.#usageBalance(frame.p);
|
|
@@ -5861,6 +5973,7 @@ var BridgeConnection = class {
|
|
|
5861
5973
|
*/
|
|
5862
5974
|
#servedCapabilities() {
|
|
5863
5975
|
const capabilities = [...SERVED_CAPABILITIES];
|
|
5976
|
+
if (this.#options.relay !== void 0) capabilities.push(CAP_RELAY_TIER);
|
|
5864
5977
|
for (const capability of this.#options.extensions?.capabilities() ?? []) if (!capabilities.includes(capability)) capabilities.push(capability);
|
|
5865
5978
|
return capabilities;
|
|
5866
5979
|
}
|
|
@@ -5869,6 +5982,7 @@ var BridgeConnection = class {
|
|
|
5869
5982
|
this.#capabilities = capabilitiesOf(payload.cap);
|
|
5870
5983
|
this.#transport.frameDeflate?.(this.#capabilities.has(CAP_FRAME_DEFLATE));
|
|
5871
5984
|
this.#options.onDeclare?.(this);
|
|
5985
|
+
const relayOrigin = this.#options.relay?.origin();
|
|
5872
5986
|
return {
|
|
5873
5987
|
ok: true,
|
|
5874
5988
|
r: {
|
|
@@ -5877,7 +5991,8 @@ var BridgeConnection = class {
|
|
|
5877
5991
|
server: SERVER_ID,
|
|
5878
5992
|
capabilities: this.#servedCapabilities(),
|
|
5879
5993
|
resume: "snapshot",
|
|
5880
|
-
auth: this.paired ? "paired" : "unpaired"
|
|
5994
|
+
auth: this.paired ? "paired" : "unpaired",
|
|
5995
|
+
...relayOrigin === void 0 ? {} : { relay: { origin: relayOrigin } }
|
|
5881
5996
|
}
|
|
5882
5997
|
};
|
|
5883
5998
|
}
|
|
@@ -5911,6 +6026,9 @@ var BridgeConnection = class {
|
|
|
5911
6026
|
const enrollment = await this.#options.roster.enroll(devicePubKey);
|
|
5912
6027
|
if (enrollment === void 0) return refusal(CODE_INVALID_ARGS, "devicePubKey is not a P-256 SPKI public key");
|
|
5913
6028
|
this.#deviceId = enrollment.deviceId;
|
|
6029
|
+
try {
|
|
6030
|
+
this.#options.onDeviceEnrolled?.();
|
|
6031
|
+
} catch {}
|
|
5914
6032
|
return {
|
|
5915
6033
|
ok: true,
|
|
5916
6034
|
r: {
|
|
@@ -7217,6 +7335,46 @@ var BridgeConnection = class {
|
|
|
7217
7335
|
};
|
|
7218
7336
|
}
|
|
7219
7337
|
/**
|
|
7338
|
+
* The body of `relay.grant`: one device hands its relay tier grant over.
|
|
7339
|
+
*
|
|
7340
|
+
* A write, and the only one this channel has. The grant lands in the sending
|
|
7341
|
+
* device's own roster row (schema 4), beside the identity it already proved, so
|
|
7342
|
+
* revoking the device withdraws the admission with it and no second table exists.
|
|
7343
|
+
* The host then asks the second meeting point to refresh its lease, and that ask
|
|
7344
|
+
* is fired rather than awaited: a phone hands a fresh grant over precisely when a
|
|
7345
|
+
* claim was just refused, and this frame must not hang on a meeting point that
|
|
7346
|
+
* stopped answering. The roster row is what the next claim reads, so the ask
|
|
7347
|
+
* never depends on this answer reaching the client first.
|
|
7348
|
+
*
|
|
7349
|
+
* The answer is `{ok:true}` and nothing else. There is deliberately no echo, no
|
|
7350
|
+
* tier and no "admitted" flag: the tier is decided out of band by the meeting
|
|
7351
|
+
* point, this bridge never learns it, and a field claiming one would be a lie the
|
|
7352
|
+
* client might render.
|
|
7353
|
+
* @param payload - `{grant}`.
|
|
7354
|
+
*/
|
|
7355
|
+
async #relayGrant(payload) {
|
|
7356
|
+
const relay = this.#options.relay;
|
|
7357
|
+
if (relay === void 0) return refusal(CODE_UNKNOWN_METHOD, `unknown method ${METHOD_RELAY_GRANT}`);
|
|
7358
|
+
const grant = payload.grant;
|
|
7359
|
+
if (typeof grant !== "string" || grant === "") return refusal(CODE_INVALID_ARGS, "grant must be the string the account service issued");
|
|
7360
|
+
const deviceId = this.#deviceId;
|
|
7361
|
+
if (deviceId === void 0) return refusal(CODE_UNPAIRED, "this connection is not paired");
|
|
7362
|
+
try {
|
|
7363
|
+
if (!await this.#options.roster.setRelayGrant(deviceId, grant)) return refusal(CODE_INTERNAL, "this connection names no paired device");
|
|
7364
|
+
try {
|
|
7365
|
+
relay.grantLanded();
|
|
7366
|
+
} catch (error) {
|
|
7367
|
+
this.#options.log(`the second meeting point could not re-claim: ${failureText(error)}`);
|
|
7368
|
+
}
|
|
7369
|
+
} catch (error) {
|
|
7370
|
+
return refusal(CODE_INTERNAL, `could not write the device roster: ${failureText(error)}`);
|
|
7371
|
+
}
|
|
7372
|
+
return {
|
|
7373
|
+
ok: true,
|
|
7374
|
+
r: { ok: true }
|
|
7375
|
+
};
|
|
7376
|
+
}
|
|
7377
|
+
/**
|
|
7220
7378
|
* 答一次 `usage.session`:一条会话的上下文窗口与下一次请求的组成估算。
|
|
7221
7379
|
*
|
|
7222
7380
|
* 两个读数各有自己的来源,也各有自己的缺席方式:`contextWindow` 只在宿主
|
|
@@ -10344,7 +10502,7 @@ var ApnsSender = class {
|
|
|
10344
10502
|
* The account service the App already signs into: one deployment, one hostname, so
|
|
10345
10503
|
* an operator with no relay of their own configures nothing at all.
|
|
10346
10504
|
*/
|
|
10347
|
-
const RELAY_DEFAULT_URL = "https://account.
|
|
10505
|
+
const RELAY_DEFAULT_URL = "https://account.chatwithai.icu";
|
|
10348
10506
|
/** The environment variable that moves the relay to another deployment. */
|
|
10349
10507
|
const RELAY_ENV = { url: "DSH_REMOTE_BRIDGE_RELAY_URL" };
|
|
10350
10508
|
/** The one path a delivery is posted to. */
|
|
@@ -10539,7 +10697,7 @@ function pushRouteOf(localKey, relayArmed) {
|
|
|
10539
10697
|
*/
|
|
10540
10698
|
function pushChannelLine(description) {
|
|
10541
10699
|
if (description.route === "direct") return `push: direct (APNs key ${description.keyId ?? "?"} of team ${description.teamId ?? "?"})`;
|
|
10542
|
-
if (description.route === "relay") return `push: relay (${description.relayUrl ?? "https://account.
|
|
10700
|
+
if (description.route === "relay") return `push: relay (${description.relayUrl ?? "https://account.chatwithai.icu"})`;
|
|
10543
10701
|
return `push: off (no APNs key on this machine and no paired device holds a relay token)`;
|
|
10544
10702
|
}
|
|
10545
10703
|
/**
|
|
@@ -11219,6 +11377,9 @@ function makePairTokenHandler(deps) {
|
|
|
11219
11377
|
res.end();
|
|
11220
11378
|
return;
|
|
11221
11379
|
}
|
|
11380
|
+
try {
|
|
11381
|
+
deps.onPairTokenIssued?.();
|
|
11382
|
+
} catch {}
|
|
11222
11383
|
const ticket = deps.pairing.issueToken();
|
|
11223
11384
|
const url = `ws://${req.headers.host ?? "127.0.0.1"}${WS_PATH}?token=${ticket.value}`;
|
|
11224
11385
|
const discovered = (deps.pairOrigin ?? (() => discoverPairOrigin({
|
|
@@ -32859,6 +33020,16 @@ var LanForwarder = class {
|
|
|
32859
33020
|
*
|
|
32860
33021
|
* Frames mirror `market/worker/src/relay-bridge.js`: control frames are JSON
|
|
32861
33022
|
* text, payload frames are `[kind:u8][streamId:u32be][payload]`.
|
|
33023
|
+
*
|
|
33024
|
+
* Flow control runs one way only, object to connector. A pause closes the
|
|
33025
|
+
* object's window on one stream: this half stops sending that stream's payload
|
|
33026
|
+
* frames and stops reading the upstream (a response body, a WebSocket socket),
|
|
33027
|
+
* so the backlog waits in the kernel instead of in this process. A resume opens
|
|
33028
|
+
* it again. A stream being abandoned arrives as close -- the frame this contract
|
|
33029
|
+
* already used for a phone cancel -- and cancel is accepted as the same thing,
|
|
33030
|
+
* because that is the name the frozen contract gives it. An object too old to
|
|
33031
|
+
* send any of them leaves this half exactly as it was, and a frame this half has
|
|
33032
|
+
* never heard of is ignored rather than answered.
|
|
32862
33033
|
*/
|
|
32863
33034
|
/** The upgrade carries the lease secret here, never in the URL. */
|
|
32864
33035
|
const BRIDGE_AUTH_HEADER = "authorization";
|
|
@@ -33074,7 +33245,11 @@ var RelayBridgeConnector = class {
|
|
|
33074
33245
|
stateValue = { state: "idle" };
|
|
33075
33246
|
attempts = 0;
|
|
33076
33247
|
disposed = false;
|
|
33248
|
+
/** HTTP streams still uploading: the request the object's frames feed. */
|
|
33077
33249
|
requests = /* @__PURE__ */ new Map();
|
|
33250
|
+
/** HTTP streams whose head already arrived: the upstream response body a
|
|
33251
|
+
* pause holds back and a stream being abandoned destroys. */
|
|
33252
|
+
responses = /* @__PURE__ */ new Map();
|
|
33078
33253
|
peers = /* @__PURE__ */ new Map();
|
|
33079
33254
|
options;
|
|
33080
33255
|
constructor(options) {
|
|
@@ -33214,6 +33389,13 @@ var RelayBridgeConnector = class {
|
|
|
33214
33389
|
this.peers.get(id)?.close(typeof frame.code === "number" ? frame.code : 1e3, String(frame.reason ?? ""));
|
|
33215
33390
|
this.peers.delete(id);
|
|
33216
33391
|
return;
|
|
33392
|
+
case "pause":
|
|
33393
|
+
this.pauseStream(id);
|
|
33394
|
+
return;
|
|
33395
|
+
case "resume":
|
|
33396
|
+
this.resumeStream(id);
|
|
33397
|
+
return;
|
|
33398
|
+
case "cancel":
|
|
33217
33399
|
case "close": {
|
|
33218
33400
|
const peer = this.peers.get(id);
|
|
33219
33401
|
if (peer !== void 0) {
|
|
@@ -33221,6 +33403,11 @@ var RelayBridgeConnector = class {
|
|
|
33221
33403
|
peer.close(1e3, String(frame.reason ?? "closed"));
|
|
33222
33404
|
return;
|
|
33223
33405
|
}
|
|
33406
|
+
const response = this.responses.get(id);
|
|
33407
|
+
if (response !== void 0) {
|
|
33408
|
+
this.responses.delete(id);
|
|
33409
|
+
response.destroy();
|
|
33410
|
+
}
|
|
33224
33411
|
const request = this.requests.get(id);
|
|
33225
33412
|
if (request !== void 0) {
|
|
33226
33413
|
this.requests.delete(id);
|
|
@@ -33228,9 +33415,20 @@ var RelayBridgeConnector = class {
|
|
|
33228
33415
|
}
|
|
33229
33416
|
return;
|
|
33230
33417
|
}
|
|
33231
|
-
default:
|
|
33418
|
+
default: return;
|
|
33232
33419
|
}
|
|
33233
33420
|
}
|
|
33421
|
+
/** Close the object's window on one stream: a paused response body emits no
|
|
33422
|
+
* more data events and a paused socket leaves its bytes in the kernel. */
|
|
33423
|
+
pauseStream(id) {
|
|
33424
|
+
this.responses.get(id)?.pause();
|
|
33425
|
+
this.peers.get(id)?.pause();
|
|
33426
|
+
}
|
|
33427
|
+
/** Reopen that window. */
|
|
33428
|
+
resumeStream(id) {
|
|
33429
|
+
this.responses.get(id)?.resume();
|
|
33430
|
+
this.peers.get(id)?.resume();
|
|
33431
|
+
}
|
|
33234
33432
|
/**
|
|
33235
33433
|
* Answer one bridged stream with 404 without dialing anything: the refusal is
|
|
33236
33434
|
* complete here, so a non-whitelisted path costs the upstream nothing.
|
|
@@ -33273,6 +33471,7 @@ var RelayBridgeConnector = class {
|
|
|
33273
33471
|
headers: bridgeUpstreamHeaders(frame.headers, host)
|
|
33274
33472
|
}, (response) => {
|
|
33275
33473
|
this.requests.delete(id);
|
|
33474
|
+
this.responses.set(id, response);
|
|
33276
33475
|
this.sendText(JSON.stringify({
|
|
33277
33476
|
t: "res",
|
|
33278
33477
|
id,
|
|
@@ -33283,13 +33482,18 @@ var RelayBridgeConnector = class {
|
|
|
33283
33482
|
response.on("data", (chunk) => {
|
|
33284
33483
|
this.sendChunk(encodeChunk(HTTP_BODY, id, chunk));
|
|
33285
33484
|
});
|
|
33485
|
+
response.on("close", () => {
|
|
33486
|
+
this.responses.delete(id);
|
|
33487
|
+
});
|
|
33286
33488
|
response.on("end", () => {
|
|
33489
|
+
this.responses.delete(id);
|
|
33287
33490
|
this.sendText(JSON.stringify({
|
|
33288
33491
|
t: "fin",
|
|
33289
33492
|
id
|
|
33290
33493
|
}));
|
|
33291
33494
|
});
|
|
33292
33495
|
response.on("error", (error) => {
|
|
33496
|
+
this.responses.delete(id);
|
|
33293
33497
|
this.sendText(JSON.stringify({
|
|
33294
33498
|
t: "fail",
|
|
33295
33499
|
id,
|
|
@@ -33373,6 +33577,12 @@ var RelayBridgeConnector = class {
|
|
|
33373
33577
|
},
|
|
33374
33578
|
binary: (body) => {
|
|
33375
33579
|
if (!peer.closed) dialed.socket.write(encodeBridgeFrame(2, body));
|
|
33580
|
+
},
|
|
33581
|
+
pause: () => {
|
|
33582
|
+
dialed.socket.pause();
|
|
33583
|
+
},
|
|
33584
|
+
resume: () => {
|
|
33585
|
+
dialed.socket.resume();
|
|
33376
33586
|
}
|
|
33377
33587
|
};
|
|
33378
33588
|
const parse = createBridgeFrameParser((incoming) => {
|
|
@@ -33456,6 +33666,10 @@ var RelayBridgeConnector = class {
|
|
|
33456
33666
|
}
|
|
33457
33667
|
/** Drop every stream this socket carried: the object re-opens them. */
|
|
33458
33668
|
teardown() {
|
|
33669
|
+
for (const [id, response] of this.responses) {
|
|
33670
|
+
this.responses.delete(id);
|
|
33671
|
+
response.destroy();
|
|
33672
|
+
}
|
|
33459
33673
|
for (const [id, request] of this.requests) {
|
|
33460
33674
|
this.requests.delete(id);
|
|
33461
33675
|
request.destroy();
|
|
@@ -33533,14 +33747,62 @@ function rawHeaderPairs(raw) {
|
|
|
33533
33747
|
for (let index = 0; index + 1 < raw.length; index += 2) pairs.push([raw[index], raw[index + 1]]);
|
|
33534
33748
|
return pairs;
|
|
33535
33749
|
}
|
|
33750
|
+
/**
|
|
33751
|
+
* One endpoint of a control-plane base.
|
|
33752
|
+
*
|
|
33753
|
+
* The base arrives from a hand-written profile YAML, so its trailing slashes
|
|
33754
|
+
* are trimmed instead of doubling the separator this adds.
|
|
33755
|
+
* @param endpoint - the path below the base.
|
|
33756
|
+
* @param controlUrl - the base; undefined means the shipped market apex.
|
|
33757
|
+
* @returns the absolute endpoint URL.
|
|
33758
|
+
*/
|
|
33759
|
+
function relayControlEndpointOf(endpoint, controlUrl) {
|
|
33760
|
+
return (controlUrl ?? "https://dsh-market.com/api/relay").replace(/\/+$/, "") + "/" + endpoint;
|
|
33761
|
+
}
|
|
33762
|
+
/** The default lease endpoints (market apex, never a relay hostname). */
|
|
33763
|
+
const RELAY_CLAIM_URL = relayControlEndpointOf("claim");
|
|
33764
|
+
const RELAY_RELEASE_URL = relayControlEndpointOf("release");
|
|
33765
|
+
/**
|
|
33766
|
+
* The control plane's refusal code for a claim whose grant does not reach the
|
|
33767
|
+
* tier this meeting point admits. It is not an authentication answer — the id
|
|
33768
|
+
* and secret verified — so it is graded apart from `auth-failed`.
|
|
33769
|
+
*/
|
|
33770
|
+
const RELAY_TIER_REQUIRED = "tier-required";
|
|
33771
|
+
/**
|
|
33772
|
+
* The control plane's refusal code for a grant it will not vouch for: a bad
|
|
33773
|
+
* signature, the wrong scope, or — the case that is not an error at all — a grant
|
|
33774
|
+
* that has simply reached the end of its 30 days.
|
|
33775
|
+
*
|
|
33776
|
+
* It shares {@link RELAY_TIER_REQUIRED}'s branch because it is the same kind of
|
|
33777
|
+
* fact: the id and the secret are fine, the admission this host was given is not,
|
|
33778
|
+
* and the repair is a fresh grant (which the phone hands over) or another
|
|
33779
|
+
* evaluation after the plan or the clock moved. `auth-failed` stays the one
|
|
33780
|
+
* terminal 403.
|
|
33781
|
+
*/
|
|
33782
|
+
const RELAY_GRANT_INVALID = "grant-invalid";
|
|
33783
|
+
/**
|
|
33784
|
+
* How long a claim refused for its admission (`tier-required` or
|
|
33785
|
+
* `grant-invalid`) waits before the next attempt: six hours.
|
|
33786
|
+
*
|
|
33787
|
+
* Deliberately outside {@link CLAIM_RETRY_MAX_MS}. That cap exists because a
|
|
33788
|
+
* spent rate-limit budget is counted over one 300-second window, so retrying
|
|
33789
|
+
* faster lands inside the same spent window. An admission refusal is not a
|
|
33790
|
+
* window: it is a fact about the plan or about the grant's own 30-day lifetime.
|
|
33791
|
+
* Six hours is the interval the lease refresh itself runs on, so a downgrade is
|
|
33792
|
+
* noticed at the next refresh, while an upgrade needs no wait at all: the phone
|
|
33793
|
+
* hands the new grant over (`relay.tier.v1`) and that re-claims immediately.
|
|
33794
|
+
*/
|
|
33795
|
+
const CLAIM_TIER_REQUIRED_DELAY_MS = 216e5;
|
|
33536
33796
|
/** Build the claim body (an absent value is omitted, never sent as null). */
|
|
33537
33797
|
function relayClaimBody(request) {
|
|
33798
|
+
const grant = request.grant;
|
|
33538
33799
|
return JSON.stringify({
|
|
33539
33800
|
id: request.id,
|
|
33540
33801
|
secret: request.secret,
|
|
33541
33802
|
new_secret: request.newSecret,
|
|
33542
33803
|
origin: { port: request.port },
|
|
33543
|
-
plugin: request.pluginVersion === void 0 ? void 0 : { version: request.pluginVersion }
|
|
33804
|
+
plugin: request.pluginVersion === void 0 ? void 0 : { version: request.pluginVersion },
|
|
33805
|
+
...typeof grant === "string" && grant !== "" ? { grant } : {}
|
|
33544
33806
|
});
|
|
33545
33807
|
}
|
|
33546
33808
|
/** The tunnel of one accepted claim, or undefined when it carries none. */
|
|
@@ -33618,7 +33880,7 @@ async function claimRelayLease(request, options = {}) {
|
|
|
33618
33880
|
const fetchFn = options.fetchFn ?? fetch;
|
|
33619
33881
|
let response;
|
|
33620
33882
|
try {
|
|
33621
|
-
response = await fetchFn(options.url ??
|
|
33883
|
+
response = await fetchFn(options.url ?? RELAY_CLAIM_URL, {
|
|
33622
33884
|
method: "PUT",
|
|
33623
33885
|
headers: { "content-type": "application/json" },
|
|
33624
33886
|
body: relayClaimBody(request)
|
|
@@ -33649,7 +33911,7 @@ async function claimRelayLease(request, options = {}) {
|
|
|
33649
33911
|
* marked active, which the 90-day GC recovers.
|
|
33650
33912
|
*/
|
|
33651
33913
|
async function releaseRelayLease(identity, options = {}) {
|
|
33652
|
-
await (options.fetchFn ?? fetch)(options.url ??
|
|
33914
|
+
await (options.fetchFn ?? fetch)(options.url ?? RELAY_RELEASE_URL, {
|
|
33653
33915
|
method: "POST",
|
|
33654
33916
|
headers: { "content-type": "application/json" },
|
|
33655
33917
|
body: JSON.stringify({
|
|
@@ -33662,7 +33924,11 @@ async function releaseRelayLease(identity, options = {}) {
|
|
|
33662
33924
|
* Grade one failed claim into a retry decision.
|
|
33663
33925
|
*
|
|
33664
33926
|
* `403 auth-failed` is terminal: the id belongs to another secret and no
|
|
33665
|
-
* number of retries can take it back.
|
|
33927
|
+
* number of retries can take it back. The two admission 403s —
|
|
33928
|
+
* `tier-required` and `grant-invalid` — are the ones that are not: the id and
|
|
33929
|
+
* the secret verified and only the admission is missing, so both retry on the
|
|
33930
|
+
* same fixed wait ({@link CLAIM_TIER_REQUIRED_DELAY_MS}) that the cap below
|
|
33931
|
+
* deliberately does not clamp. Everything else retries on a capped
|
|
33666
33932
|
* exponential backoff, with the control plane's own `retryAfterMs` (a 502
|
|
33667
33933
|
* names it) raising the floor so a retry cannot land inside a known outage.
|
|
33668
33934
|
* @param outcome - the refused attempt.
|
|
@@ -33671,12 +33937,19 @@ async function releaseRelayLease(identity, options = {}) {
|
|
|
33671
33937
|
*/
|
|
33672
33938
|
function relayClaimRetryOf(outcome, attempt, options = {}) {
|
|
33673
33939
|
const base = options.baseDelayMs ?? 5e3;
|
|
33674
|
-
const max = options.maxDelayMs ??
|
|
33675
|
-
if (outcome.status === 403)
|
|
33676
|
-
|
|
33677
|
-
|
|
33678
|
-
|
|
33679
|
-
|
|
33940
|
+
const max = options.maxDelayMs ?? 3e5;
|
|
33941
|
+
if (outcome.status === 403) {
|
|
33942
|
+
if (outcome.error === "tier-required" || outcome.error === "grant-invalid") return {
|
|
33943
|
+
retry: true,
|
|
33944
|
+
delayMs: CLAIM_TIER_REQUIRED_DELAY_MS,
|
|
33945
|
+
refreshIdentity: false
|
|
33946
|
+
};
|
|
33947
|
+
return {
|
|
33948
|
+
retry: false,
|
|
33949
|
+
delayMs: 0,
|
|
33950
|
+
refreshIdentity: false
|
|
33951
|
+
};
|
|
33952
|
+
}
|
|
33680
33953
|
const backoff = Math.min(base * 2 ** attempt, max);
|
|
33681
33954
|
return {
|
|
33682
33955
|
retry: true,
|
|
@@ -34523,7 +34796,7 @@ var RelayConnectorPair = class {
|
|
|
34523
34796
|
if (this.disposed) return void 0;
|
|
34524
34797
|
this.clearTimer();
|
|
34525
34798
|
this.setState({ state: "claiming" });
|
|
34526
|
-
const claimFn = this.options.claim ?? ((request) => claimRelayLease(request));
|
|
34799
|
+
const claimFn = this.options.claim ?? ((request) => claimRelayLease(request, { url: relayControlEndpointOf("claim", this.options.controlUrl) }));
|
|
34527
34800
|
let outcome;
|
|
34528
34801
|
try {
|
|
34529
34802
|
outcome = await claimFn({
|
|
@@ -34571,7 +34844,7 @@ var RelayConnectorPair = class {
|
|
|
34571
34844
|
* phone's bookmark, and the tunnel behind it survives.
|
|
34572
34845
|
*/
|
|
34573
34846
|
async release() {
|
|
34574
|
-
const releaseFn = this.options.release ?? ((identity) => releaseRelayLease(identity));
|
|
34847
|
+
const releaseFn = this.options.release ?? ((identity) => releaseRelayLease(identity, { url: relayControlEndpointOf("release", this.options.controlUrl) }));
|
|
34575
34848
|
try {
|
|
34576
34849
|
await releaseFn(this.identity);
|
|
34577
34850
|
} catch {}
|
|
@@ -34641,11 +34914,34 @@ var RelayConnectorPair = class {
|
|
|
34641
34914
|
} catch {}
|
|
34642
34915
|
}
|
|
34643
34916
|
};
|
|
34644
|
-
|
|
34917
|
+
//#endregion
|
|
34918
|
+
//#region src/host/relay-registry.ts
|
|
34919
|
+
/**
|
|
34920
|
+
* Relay registry client: a stable `https://<id>.dsh-market.com` origin in
|
|
34921
|
+
* front of the plugin-managed quick tunnel, so a paired phone keeps one
|
|
34922
|
+
* bookmark and one cookie context across `dsh web` restarts.
|
|
34923
|
+
*
|
|
34924
|
+
* The plugin mints an id + secret on first run and persists them per profile
|
|
34925
|
+
* under `$DSH_HOME/remote-web-ui-registry/`; every tunnel (re)start
|
|
34926
|
+
* re-registers the current quick URL with the market worker. Registration is
|
|
34927
|
+
* best-effort: a registry outage never blocks the tunnel — the QR just falls
|
|
34928
|
+
* back to the raw quick URL for that session (the pre-relay behavior).
|
|
34929
|
+
*
|
|
34930
|
+
* Not to be confused with `./relay.ts`, the bridge's own APNs push sender: the
|
|
34931
|
+
* relay in this file is the Cloudflare-side one that fronts the tunnel. The
|
|
34932
|
+
* persisted directory and file names below keep their historical spelling on
|
|
34933
|
+
* purpose, so an existing profile keeps the identity it already paired with.
|
|
34934
|
+
*/
|
|
34935
|
+
/** The market worker's registration endpoints (dsh-market.com edge API). */
|
|
34936
|
+
const RELAY_REGISTER_URL = relayControlEndpointOf("register");
|
|
34937
|
+
const RELAY_UNREGISTER_URL = relayControlEndpointOf("unregister");
|
|
34645
34938
|
/**
|
|
34646
34939
|
* The public origin template: one stable single-label subdomain per
|
|
34647
34940
|
* registration id. Single label on purpose — Universal SSL covers exactly
|
|
34648
34941
|
* one subdomain level, so a two-level hostname would get no certificate.
|
|
34942
|
+
*
|
|
34943
|
+
* This constant is the one home of the shipped default suffix; a self-hosted
|
|
34944
|
+
* meeting point sets `relayPublicSuffix` and the hostname template follows.
|
|
34649
34945
|
*/
|
|
34650
34946
|
const RELAY_BASE_SUFFIX = ".dsh-market.com";
|
|
34651
34947
|
const RELAY_ID_RE = /^[a-z0-9]{16}$/;
|
|
@@ -34740,9 +35036,12 @@ async function unregisterRelay(identity, endpoint = RELAY_UNREGISTER_URL, fetchF
|
|
|
34740
35036
|
/**
|
|
34741
35037
|
* The stable relay base for one identity — the origin the QR and the phone
|
|
34742
35038
|
* bookmark use while (or after) the registration is accepted.
|
|
35039
|
+
* @param identity - the registration identity.
|
|
35040
|
+
* @param publicSuffix - the configured suffix; undefined means the shipped one.
|
|
35041
|
+
* @returns the origin, with no path of its own.
|
|
34743
35042
|
*/
|
|
34744
|
-
function relayBaseOf(identity) {
|
|
34745
|
-
return `https://${identity.id}${
|
|
35043
|
+
function relayBaseOf(identity, publicSuffix = RELAY_BASE_SUFFIX) {
|
|
35044
|
+
return `https://${identity.id}${publicSuffix}`;
|
|
34746
35045
|
}
|
|
34747
35046
|
/**
|
|
34748
35047
|
* Registration loop with capped exponential backoff. Re-registration happens
|
|
@@ -34764,7 +35063,7 @@ var RelayRegistrar = class {
|
|
|
34764
35063
|
}
|
|
34765
35064
|
/** The stable relay base for the QR while registered. */
|
|
34766
35065
|
get baseUrl() {
|
|
34767
|
-
return relayBaseOf(this.identity);
|
|
35066
|
+
return relayBaseOf(this.identity, this.options.publicSuffix);
|
|
34768
35067
|
}
|
|
34769
35068
|
/** The last registration failure detail (undefined while healthy). */
|
|
34770
35069
|
get error() {
|
|
@@ -34779,7 +35078,7 @@ var RelayRegistrar = class {
|
|
|
34779
35078
|
}
|
|
34780
35079
|
this.setState({ state: "registering" });
|
|
34781
35080
|
try {
|
|
34782
|
-
const response = await (this.options.fetchFn ?? fetch)(this.options.registerUrl ??
|
|
35081
|
+
const response = await (this.options.fetchFn ?? fetch)(this.options.registerUrl ?? RELAY_REGISTER_URL, {
|
|
34783
35082
|
method: "PUT",
|
|
34784
35083
|
headers: { "content-type": "application/json" },
|
|
34785
35084
|
body: registrationBody(this.identity, target)
|
|
@@ -34839,6 +35138,372 @@ var RelayRegistrar = class {
|
|
|
34839
35138
|
}
|
|
34840
35139
|
};
|
|
34841
35140
|
//#endregion
|
|
35141
|
+
//#region src/host/relay-secondary.ts
|
|
35142
|
+
/**
|
|
35143
|
+
* The second meeting point: the self-hosted relay a configured host keeps beside
|
|
35144
|
+
* the market edge.
|
|
35145
|
+
*
|
|
35146
|
+
* One relay identity serves both meetings — the id and the secret are minted once
|
|
35147
|
+
* for this profile and never re-minted for a second endpoint — but everything else
|
|
35148
|
+
* about the two halves is separate: their own claim, their own lease, their own
|
|
35149
|
+
* connector and their own release. That separation is the reason this file exists.
|
|
35150
|
+
* A second meeting point that refuses, times out or is switched off in the provider
|
|
35151
|
+
* console must leave the lease that already serves the phone over `dsh-market.com`
|
|
35152
|
+
* exactly as it stands, and the reverse holds as well.
|
|
35153
|
+
*
|
|
35154
|
+
* The half is off unless the mount is configured with both halves of a meeting
|
|
35155
|
+
* point — a control-plane base and the public suffix its origin is built from —
|
|
35156
|
+
* and {@link relaySecondaryOf} is the one place that decides it. A host that
|
|
35157
|
+
* configures nothing therefore never constructs this object, never dials anything
|
|
35158
|
+
* and never writes a grant into its roster, which is what keeps the default
|
|
35159
|
+
* behaviour of `hello`, the roster and the network byte for byte what it was.
|
|
35160
|
+
*
|
|
35161
|
+
* The grant is the phone's, not this bridge's ({@link DeviceRoster.setRelayGrant}):
|
|
35162
|
+
* this half only reads whatever the newest row holds and presents it to the second
|
|
35163
|
+
* control plane. It learns "admitted" or "not admitted" and never learns a tier, a
|
|
35164
|
+
* user or an account.
|
|
35165
|
+
*
|
|
35166
|
+
* A held lease is re-claimed every six hours ({@link SECONDARY_CLAIM_REFRESH_MS}),
|
|
35167
|
+
* because the relay only admits a connector whose lease was claimed inside the last
|
|
35168
|
+
* 24 hours — so what `hello` announces is a lease the relay admits right now, not one
|
|
35169
|
+
* this host once obtained. The market edge has no such loop: its claim follows the
|
|
35170
|
+
* plugin's own lifecycle events, and a default host keeps behaving exactly as it did.
|
|
35171
|
+
*/
|
|
35172
|
+
/**
|
|
35173
|
+
* The refusal codes that say this instance holds no second lease at all.
|
|
35174
|
+
*
|
|
35175
|
+
* `tier-required` is the entitlement answer, `grant-invalid` the grant the account
|
|
35176
|
+
* service will not vouch for (an expired 30-day grant is this one), `auth-failed`
|
|
35177
|
+
* the id that belongs to another secret on this meeting point. Every other refusal
|
|
35178
|
+
* is transient by nature (a rate limit, an upstream outage, a socket that never
|
|
35179
|
+
* answered) and keeps the announcement: the lease the relay already recorded runs
|
|
35180
|
+
* on its own 24-hour clock and the connector behind it is still up, so withdrawing
|
|
35181
|
+
* the origin on a failed refresh would flap a working phone path back to the market
|
|
35182
|
+
* edge.
|
|
35183
|
+
*/
|
|
35184
|
+
const SECOND_LEASE_REFUSED = /* @__PURE__ */ new Set([
|
|
35185
|
+
RELAY_TIER_REQUIRED,
|
|
35186
|
+
RELAY_GRANT_INVALID,
|
|
35187
|
+
"auth-failed"
|
|
35188
|
+
]);
|
|
35189
|
+
/**
|
|
35190
|
+
* The subset of those refusals that also releases the lease and stops the connector.
|
|
35191
|
+
*
|
|
35192
|
+
* Exactly the two admission refusals: the host no longer has anything the relay
|
|
35193
|
+
* admits, so the lease row it may still hold is withdrawn and the connector that
|
|
35194
|
+
* would re-dial with it is stopped. `auth-failed` is deliberately NOT here — the
|
|
35195
|
+
* release would be refused by the same credential check, so the only thing left to
|
|
35196
|
+
* do is stop announcing, which the withdrawal above already did.
|
|
35197
|
+
*/
|
|
35198
|
+
const SECOND_LEASE_RELEASED = /* @__PURE__ */ new Set([RELAY_TIER_REQUIRED, RELAY_GRANT_INVALID]);
|
|
35199
|
+
/**
|
|
35200
|
+
* How a refused connector attach reads in the bridge runner's state line.
|
|
35201
|
+
*
|
|
35202
|
+
* The connector reports the status it was refused with (`refused with 403`), never
|
|
35203
|
+
* the body, so `lease-stale` — the relay's answer to a lease nobody claimed inside
|
|
35204
|
+
* the 24-hour window — cannot be read by name from this side. A credential refusal
|
|
35205
|
+
* reads the same way (`401`), and both are repaired by the same act: claim again
|
|
35206
|
+
* with the identity the connector presents.
|
|
35207
|
+
*/
|
|
35208
|
+
const ATTACH_REFUSED_RE = /(?:refused with|upgrade answered)\s+40[13]\b/;
|
|
35209
|
+
/**
|
|
35210
|
+
* Where the second connector records its state
|
|
35211
|
+
* (`$DSH_HOME/remote-web-ui-relay-bridge-secondary.json`).
|
|
35212
|
+
*
|
|
35213
|
+
* Its own file, never the first half's: two connectors that wrote one record would
|
|
35214
|
+
* each overwrite the other's state, and the record exists precisely to say which
|
|
35215
|
+
* meeting point served which lease.
|
|
35216
|
+
* @param home - the DSH home (a test seam).
|
|
35217
|
+
* @returns the absolute record path.
|
|
35218
|
+
*/
|
|
35219
|
+
function relaySecondaryBridgeStateFile(home = dshHome()) {
|
|
35220
|
+
return join(home, "remote-web-ui-relay-bridge-secondary.json");
|
|
35221
|
+
}
|
|
35222
|
+
/**
|
|
35223
|
+
* The second meeting point one configuration names, or undefined.
|
|
35224
|
+
*
|
|
35225
|
+
* Both halves are required and neither has a default: an origin cannot be built
|
|
35226
|
+
* from a control-plane base alone, and a control plane cannot be reached from a
|
|
35227
|
+
* suffix alone. A profile that names only one of them therefore has no second
|
|
35228
|
+
* meeting point at all rather than half of one, which keeps every consumer of this
|
|
35229
|
+
* answer able to treat "undefined" as "this host has one meeting point".
|
|
35230
|
+
* @param config - the resolved bridge configuration (read structurally).
|
|
35231
|
+
* @returns the meeting point, or undefined when this host has none.
|
|
35232
|
+
*/
|
|
35233
|
+
function relaySecondaryOf(config) {
|
|
35234
|
+
const controlUrl = config.relaySecondaryControlUrl?.trim();
|
|
35235
|
+
const suffix = config.relaySecondaryPublicSuffix?.trim();
|
|
35236
|
+
if (controlUrl === void 0 || controlUrl === "") return void 0;
|
|
35237
|
+
if (suffix === void 0 || suffix === "") return void 0;
|
|
35238
|
+
return {
|
|
35239
|
+
controlUrl,
|
|
35240
|
+
publicSuffix: suffix.startsWith(".") ? suffix : "." + suffix
|
|
35241
|
+
};
|
|
35242
|
+
}
|
|
35243
|
+
/**
|
|
35244
|
+
* The origin this host announces for its second meeting point.
|
|
35245
|
+
*
|
|
35246
|
+
* Built from the identity and the configured suffix, never from the hostname a
|
|
35247
|
+
* claim answered with: the id is the one this host has held since it minted its
|
|
35248
|
+
* identity, while the suffix is the operator's statement of where that identity's
|
|
35249
|
+
* second meeting point is. Whether it is announced at all is a different question —
|
|
35250
|
+
* {@link RelaySecondaryHalf.origin} answers it, and only while a fresh lease is held.
|
|
35251
|
+
* @param identity - the one relay identity both meetings share.
|
|
35252
|
+
* @param publicSuffix - the configured suffix, leading dot included.
|
|
35253
|
+
* @returns the `wss://` origin the greeting carries.
|
|
35254
|
+
*/
|
|
35255
|
+
function relaySecondaryOriginOf(identity, publicSuffix) {
|
|
35256
|
+
return "wss://" + identity.id + publicSuffix;
|
|
35257
|
+
}
|
|
35258
|
+
/**
|
|
35259
|
+
* Own the second meeting point's lease: claim it once per port and grant, follow
|
|
35260
|
+
* the grant the phone hands over, and answer the origin `hello` announces.
|
|
35261
|
+
*
|
|
35262
|
+
* Built on {@link RelayConnectorPair} on purpose — the claim/retry/release
|
|
35263
|
+
* lifecycle is the same one the market edge runs — but with its own injected claim
|
|
35264
|
+
* (which adds the grant) and its own connector and release, so the two halves share
|
|
35265
|
+
* the identity and nothing else.
|
|
35266
|
+
*/
|
|
35267
|
+
var RelaySecondaryHalf = class {
|
|
35268
|
+
#options;
|
|
35269
|
+
#pair;
|
|
35270
|
+
/** Whether this instance currently holds a lease at the second meeting point. */
|
|
35271
|
+
#held = false;
|
|
35272
|
+
/** The `port|grant` key of the last claim this half started. */
|
|
35273
|
+
#claimedFor;
|
|
35274
|
+
/** The canceller of the running six-hour refresh, while there is one. */
|
|
35275
|
+
#stopRefresh;
|
|
35276
|
+
/** The endpoint the running connector dials; undefined while no connector runs. */
|
|
35277
|
+
#bridgeEndpoint;
|
|
35278
|
+
#disposed = false;
|
|
35279
|
+
constructor(options) {
|
|
35280
|
+
this.#options = options;
|
|
35281
|
+
const claim = options.claim ?? (async (request) => await claimRelayLease(request, { url: relayControlEndpointOf("claim", options.controlUrl) }));
|
|
35282
|
+
this.#pair = new RelayConnectorPair(options.identity, {
|
|
35283
|
+
claim: async (request) => {
|
|
35284
|
+
const grant = options.grant();
|
|
35285
|
+
return await claim({
|
|
35286
|
+
...request,
|
|
35287
|
+
...grant === void 0 ? {} : { grant }
|
|
35288
|
+
});
|
|
35289
|
+
},
|
|
35290
|
+
release: options.release ?? (async (identity) => {
|
|
35291
|
+
await releaseRelayLease(identity, { url: relayControlEndpointOf("release", options.controlUrl) });
|
|
35292
|
+
}),
|
|
35293
|
+
...options.startBridge === void 0 ? {} : { startBridge: (start) => {
|
|
35294
|
+
const endpoint = start.claim.bridge?.endpoint;
|
|
35295
|
+
if (endpoint !== void 0 && endpoint === this.#bridgeEndpoint) return;
|
|
35296
|
+
this.#bridgeEndpoint = endpoint;
|
|
35297
|
+
options.startBridge?.(start);
|
|
35298
|
+
} },
|
|
35299
|
+
...options.stopBridge === void 0 ? {} : { stopBridge: () => {
|
|
35300
|
+
this.#bridgeEndpoint = void 0;
|
|
35301
|
+
options.stopBridge?.();
|
|
35302
|
+
} },
|
|
35303
|
+
...options.baseDelayMs === void 0 ? {} : { baseDelayMs: options.baseDelayMs },
|
|
35304
|
+
...options.maxDelayMs === void 0 ? {} : { maxDelayMs: options.maxDelayMs },
|
|
35305
|
+
...options.timerFn === void 0 ? {} : { timerFn: options.timerFn },
|
|
35306
|
+
onState: (state) => {
|
|
35307
|
+
this.#observe(state);
|
|
35308
|
+
}
|
|
35309
|
+
});
|
|
35310
|
+
}
|
|
35311
|
+
/** The lease half's current state (the market edge's own vocabulary). */
|
|
35312
|
+
get state() {
|
|
35313
|
+
return this.#pair.state;
|
|
35314
|
+
}
|
|
35315
|
+
/**
|
|
35316
|
+
* Claim the second meeting point once for the current port and grant.
|
|
35317
|
+
*
|
|
35318
|
+
* One claim per `port|grant` pair: a settings sync re-plans with the same key and
|
|
35319
|
+
* must not turn into a claim per plan, while a settled port or a grant the phone
|
|
35320
|
+
* just handed over is a genuinely new fact and claims again.
|
|
35321
|
+
* @returns whether a claim was started.
|
|
35322
|
+
*/
|
|
35323
|
+
claim() {
|
|
35324
|
+
if (this.#disposed) return false;
|
|
35325
|
+
const port = this.#options.port();
|
|
35326
|
+
if (port === void 0) return false;
|
|
35327
|
+
const key = this.#keyOf(port);
|
|
35328
|
+
if (this.#claimedFor === key) return false;
|
|
35329
|
+
this.#claimedFor = key;
|
|
35330
|
+
this.#logFailure(this.#start(port));
|
|
35331
|
+
return true;
|
|
35332
|
+
}
|
|
35333
|
+
/**
|
|
35334
|
+
* A grant just landed in the roster: claim again right away.
|
|
35335
|
+
*
|
|
35336
|
+
* Unconditional on purpose — a phone that resends the grant it already handed over
|
|
35337
|
+
* is asking this host to try again, and the pending wait (which may be the
|
|
35338
|
+
* six-hour one a downgrade armed) is cleared by the claim itself.
|
|
35339
|
+
* @returns when this attempt settled, so a suite can drive it deterministically.
|
|
35340
|
+
*/
|
|
35341
|
+
async grantReceived() {
|
|
35342
|
+
if (this.#disposed) return;
|
|
35343
|
+
const port = this.#options.port();
|
|
35344
|
+
if (port === void 0) return;
|
|
35345
|
+
this.#claimedFor = this.#keyOf(port);
|
|
35346
|
+
await this.#start(port);
|
|
35347
|
+
}
|
|
35348
|
+
/**
|
|
35349
|
+
* The second connector could not attach, so the lease it presents is claimed again.
|
|
35350
|
+
*
|
|
35351
|
+
* This is the stale-lease repair. The relay refuses a connector whose lease nobody
|
|
35352
|
+
* has claimed inside the 24-hour window (`403 lease-stale`), which the six-hour
|
|
35353
|
+
* refresh is meant to prevent — a suspended process, a long offline stretch or a
|
|
35354
|
+
* clock that jumped can still produce one, and the repair is exactly one claim with
|
|
35355
|
+
* the identity the connector was already presenting.
|
|
35356
|
+
*
|
|
35357
|
+
* Only a *refusal* counts: a dial timeout or a dropped socket is the connector's own
|
|
35358
|
+
* backoff to sort out, and asking the control plane about it every 30 seconds would
|
|
35359
|
+
* turn a network blip into a claim storm. Only a held lease counts too — once a
|
|
35360
|
+
* refusal has told this half it holds nothing, its own wait (six hours, or none at
|
|
35361
|
+
* all for a terminal answer) decides when to try again.
|
|
35362
|
+
* @param error - the failure the bridge runner reported for its connector.
|
|
35363
|
+
*/
|
|
35364
|
+
connectorFailed(error) {
|
|
35365
|
+
if (this.#disposed || !this.#held) return;
|
|
35366
|
+
if (!ATTACH_REFUSED_RE.test(error)) return;
|
|
35367
|
+
const port = this.#options.port();
|
|
35368
|
+
if (port === void 0) return;
|
|
35369
|
+
this.#claimedFor = this.#keyOf(port);
|
|
35370
|
+
this.#logFailure(this.#start(port));
|
|
35371
|
+
}
|
|
35372
|
+
/**
|
|
35373
|
+
* The origin this host may announce right now, or undefined.
|
|
35374
|
+
*
|
|
35375
|
+
* Announcement follows the lease, not the configuration: an advertised meeting
|
|
35376
|
+
* point whose origin nobody serves is worse than no advertisement at all.
|
|
35377
|
+
* @returns `wss://<id><suffix>` while a lease is held.
|
|
35378
|
+
*/
|
|
35379
|
+
origin() {
|
|
35380
|
+
return this.#held ? relaySecondaryOriginOf(this.#options.identity, this.#options.publicSuffix) : void 0;
|
|
35381
|
+
}
|
|
35382
|
+
/**
|
|
35383
|
+
* Release the second lease and stop its connector.
|
|
35384
|
+
*
|
|
35385
|
+
* This never touches the first half: it releases against the second control plane
|
|
35386
|
+
* only and stops the connector this object was handed.
|
|
35387
|
+
*/
|
|
35388
|
+
async release() {
|
|
35389
|
+
this.#held = false;
|
|
35390
|
+
this.#stopRefreshNow();
|
|
35391
|
+
await this.#pair.release();
|
|
35392
|
+
}
|
|
35393
|
+
/** Stop retrying and drop the connector (plugin teardown, or the relay turned off). */
|
|
35394
|
+
dispose() {
|
|
35395
|
+
this.#disposed = true;
|
|
35396
|
+
this.#held = false;
|
|
35397
|
+
this.#stopRefreshNow();
|
|
35398
|
+
this.#pair.dispose();
|
|
35399
|
+
}
|
|
35400
|
+
/**
|
|
35401
|
+
* Fire one claim attempt without letting its failure escape.
|
|
35402
|
+
*
|
|
35403
|
+
* A claim is a network round trip, so a failure is one line in the log and never an
|
|
35404
|
+
* unhandled rejection — the same exit the market edge's claimer takes.
|
|
35405
|
+
* @param attempt - the claim being fired.
|
|
35406
|
+
*/
|
|
35407
|
+
#logFailure(attempt) {
|
|
35408
|
+
attempt.catch((error) => {
|
|
35409
|
+
this.#options.log?.("the second meeting point claim did not land: " + (error instanceof Error ? error.message : String(error)));
|
|
35410
|
+
});
|
|
35411
|
+
}
|
|
35412
|
+
/**
|
|
35413
|
+
* The key one claim is deduplicated on: the settled port plus the grant in force.
|
|
35414
|
+
* @param port - the ingress gate port a claim reports.
|
|
35415
|
+
* @returns the key.
|
|
35416
|
+
*/
|
|
35417
|
+
#keyOf(port) {
|
|
35418
|
+
return String(port) + "|" + (this.#options.grant() ?? "");
|
|
35419
|
+
}
|
|
35420
|
+
/** One claim attempt for one settled port. */
|
|
35421
|
+
async #start(port) {
|
|
35422
|
+
const version = this.#options.pluginVersion?.();
|
|
35423
|
+
await this.#pair.start({
|
|
35424
|
+
port,
|
|
35425
|
+
...version === void 0 ? {} : { pluginVersion: version }
|
|
35426
|
+
});
|
|
35427
|
+
}
|
|
35428
|
+
/**
|
|
35429
|
+
* Follow the lease lifecycle: this is the one place that decides what `hello`
|
|
35430
|
+
* announces and what the relay is told when a lease ends.
|
|
35431
|
+
* @param state - the state the pair just moved to.
|
|
35432
|
+
*/
|
|
35433
|
+
#observe(state) {
|
|
35434
|
+
if (state.state === "claimed") {
|
|
35435
|
+
this.#held = true;
|
|
35436
|
+
this.#armRefresh();
|
|
35437
|
+
} else if (state.state === "idle") {
|
|
35438
|
+
this.#held = false;
|
|
35439
|
+
this.#stopRefreshNow();
|
|
35440
|
+
} else if (state.state === "failed" && SECOND_LEASE_REFUSED.has(state.error)) {
|
|
35441
|
+
this.#held = false;
|
|
35442
|
+
this.#stopRefreshNow();
|
|
35443
|
+
if (SECOND_LEASE_RELEASED.has(state.error)) this.#releaseSecondLease();
|
|
35444
|
+
}
|
|
35445
|
+
try {
|
|
35446
|
+
this.#options.onState?.(state);
|
|
35447
|
+
} catch {}
|
|
35448
|
+
}
|
|
35449
|
+
/**
|
|
35450
|
+
* Start the six-hour refresh, once.
|
|
35451
|
+
*
|
|
35452
|
+
* It runs exactly while this half holds a lease: the relay's own window is 24 hours,
|
|
35453
|
+
* the design's refresh interval is six, and a half that was told it holds nothing
|
|
35454
|
+
* leaves the retry to the decision that refusal produced.
|
|
35455
|
+
*/
|
|
35456
|
+
#armRefresh() {
|
|
35457
|
+
if (this.#stopRefresh !== void 0 || this.#disposed) return;
|
|
35458
|
+
const ms = this.#options.refreshMs ?? 216e5;
|
|
35459
|
+
const start = this.#options.refreshTimer ?? ((tick, every) => {
|
|
35460
|
+
const timer = setInterval(tick, every);
|
|
35461
|
+
timer.unref?.();
|
|
35462
|
+
return () => {
|
|
35463
|
+
clearInterval(timer);
|
|
35464
|
+
};
|
|
35465
|
+
});
|
|
35466
|
+
this.#stopRefresh = start(() => {
|
|
35467
|
+
this.#logFailure(this.#refresh());
|
|
35468
|
+
}, ms);
|
|
35469
|
+
}
|
|
35470
|
+
/** Cancel the refresh, if one is running. */
|
|
35471
|
+
#stopRefreshNow() {
|
|
35472
|
+
const stop = this.#stopRefresh;
|
|
35473
|
+
if (stop === void 0) return;
|
|
35474
|
+
this.#stopRefresh = void 0;
|
|
35475
|
+
try {
|
|
35476
|
+
stop();
|
|
35477
|
+
} catch (error) {
|
|
35478
|
+
this.#options.log?.("the second meeting point refresh could not be cancelled: " + (error instanceof Error ? error.message : String(error)));
|
|
35479
|
+
}
|
|
35480
|
+
}
|
|
35481
|
+
/** One periodic refresh: claim the lease the relay is about to consider stale. */
|
|
35482
|
+
async #refresh() {
|
|
35483
|
+
if (this.#disposed || !this.#held) return;
|
|
35484
|
+
const port = this.#options.port();
|
|
35485
|
+
if (port === void 0) return;
|
|
35486
|
+
this.#claimedFor = this.#keyOf(port);
|
|
35487
|
+
await this.#start(port);
|
|
35488
|
+
}
|
|
35489
|
+
/** Release the second lease, best effort; a failure only leaves a row for the GC. */
|
|
35490
|
+
async #releaseSecondLease() {
|
|
35491
|
+
try {
|
|
35492
|
+
await this.#pair.release();
|
|
35493
|
+
} catch (error) {
|
|
35494
|
+
this.#options.log?.("the second meeting point lease could not be released: " + (error instanceof Error ? error.message : String(error)));
|
|
35495
|
+
}
|
|
35496
|
+
}
|
|
35497
|
+
};
|
|
35498
|
+
/**
|
|
35499
|
+
* Build the second meeting point half.
|
|
35500
|
+
* @param options - the identity, the meeting point and the mount's seams.
|
|
35501
|
+
* @returns the half, ready to claim.
|
|
35502
|
+
*/
|
|
35503
|
+
function createRelaySecondaryHalf(options) {
|
|
35504
|
+
return new RelaySecondaryHalf(options);
|
|
35505
|
+
}
|
|
35506
|
+
//#endregion
|
|
34842
35507
|
//#region src/host/tunnel-plan.ts
|
|
34843
35508
|
/**
|
|
34844
35509
|
* Pure planner for the settings-sync tunnel branch: given the resolved
|
|
@@ -35497,7 +36162,11 @@ function resolveBridgeConfig(raw, env = process.env) {
|
|
|
35497
36162
|
ingressSync: booleanField(fields, "ingressSync", false),
|
|
35498
36163
|
cfApiToken: optionalTextField(fields, "cfApiToken"),
|
|
35499
36164
|
cfAccountId: optionalTextField(fields, "cfAccountId"),
|
|
35500
|
-
cfTunnelId: optionalTextField(fields, "cfTunnelId")
|
|
36165
|
+
cfTunnelId: optionalTextField(fields, "cfTunnelId"),
|
|
36166
|
+
relayControlUrl: optionalTextField(fields, "relayControlUrl") ?? "https://dsh-market.com/api/relay",
|
|
36167
|
+
relayPublicSuffix: optionalTextField(fields, "relayPublicSuffix") ?? ".dsh-market.com",
|
|
36168
|
+
relaySecondaryControlUrl: optionalTextField(fields, "relaySecondaryControlUrl"),
|
|
36169
|
+
relaySecondaryPublicSuffix: optionalTextField(fields, "relaySecondaryPublicSuffix")
|
|
35501
36170
|
};
|
|
35502
36171
|
}
|
|
35503
36172
|
/**
|
|
@@ -35585,7 +36254,7 @@ function bridgeWiringPlanOf(facts) {
|
|
|
35585
36254
|
return {
|
|
35586
36255
|
awaitPort: gatePort === void 0,
|
|
35587
36256
|
tunnel: gatePort === void 0 && config.autoTunnel ? void 0 : tunnelPlanOf(config, gatePort),
|
|
35588
|
-
claim: config.relay && gatePort !== void 0,
|
|
36257
|
+
claim: config.relay && gatePort !== void 0 && (facts.remoteArmed !== false || tunnelPlanOf(config, gatePort).mode !== "off"),
|
|
35589
36258
|
forward: forwardPlanOf(config.lanBind, facts.startupHost, capability),
|
|
35590
36259
|
ingress: ingressInputOf({
|
|
35591
36260
|
enabled: true,
|
|
@@ -35694,11 +36363,15 @@ function relayAnnounceTargetOf(facts) {
|
|
|
35694
36363
|
*
|
|
35695
36364
|
* 注册上去的 URL 就是隧道的目标,而隧道的目标是入站闸门,所以这一行只透出
|
|
35696
36365
|
* `/ios/v1`:announcer 不会把宿主的路由表暴露给公网。
|
|
35697
|
-
* @param options - 身份来源(懒读,只有真要注册时才碰 DSH home
|
|
36366
|
+
* @param options - 身份来源(懒读,只有真要注册时才碰 DSH home)、会合点地址与失败落点。
|
|
35698
36367
|
* @returns announcer 本身。
|
|
35699
36368
|
*/
|
|
35700
36369
|
function createRelayAnnouncer(options) {
|
|
35701
|
-
const build = options.registrar ?? ((identity, onState) => new RelayRegistrar(identity, onState
|
|
36370
|
+
const build = options.registrar ?? ((identity, onState) => new RelayRegistrar(identity, onState, {
|
|
36371
|
+
registerUrl: relayControlEndpointOf("register", options.controlUrl),
|
|
36372
|
+
unregisterUrl: relayControlEndpointOf("unregister", options.controlUrl),
|
|
36373
|
+
publicSuffix: options.publicSuffix
|
|
36374
|
+
}));
|
|
35702
36375
|
let registrar;
|
|
35703
36376
|
let attempted;
|
|
35704
36377
|
let registered;
|
|
@@ -36065,25 +36738,58 @@ function existingRelayIdentityOf(profile, log) {
|
|
|
36065
36738
|
*/
|
|
36066
36739
|
async function retireStaleRelayHalfOf(parts) {
|
|
36067
36740
|
try {
|
|
36068
|
-
await unregisterRelay(parts.identity);
|
|
36741
|
+
await unregisterRelay(parts.identity, relayControlEndpointOf("unregister", parts.controlUrl));
|
|
36069
36742
|
} catch (error) {
|
|
36070
36743
|
parts.log?.("the previous relay registration could not be withdrawn: " + (error instanceof Error ? error.message : String(error)));
|
|
36071
36744
|
}
|
|
36072
36745
|
try {
|
|
36073
|
-
await releaseRelayLease(parts.identity);
|
|
36746
|
+
await releaseRelayLease(parts.identity, { url: relayControlEndpointOf("release", parts.controlUrl) });
|
|
36074
36747
|
} catch (error) {
|
|
36075
36748
|
parts.log?.("the previous relay lease could not be released: " + (error instanceof Error ? error.message : String(error)));
|
|
36076
36749
|
}
|
|
36077
36750
|
}
|
|
36078
36751
|
/**
|
|
36079
36752
|
* 租约状态的一行日志文本。
|
|
36753
|
+
*
|
|
36754
|
+
* `idle` 与 `claiming` 是每次尝试前的内部过渡态,不产生控制台输出;只保留可观测结果
|
|
36755
|
+
* (`claimed` 与 `failed`)。
|
|
36080
36756
|
* @param state - 租约半区此刻的状态。
|
|
36081
|
-
* @returns
|
|
36757
|
+
* @returns 一行可读的状态,或 undefined(无需打印的过渡态)。
|
|
36082
36758
|
*/
|
|
36083
36759
|
function relayStateLine(state) {
|
|
36084
36760
|
if (state.state === "claimed") return "claimed " + state.mode + " " + state.hostname;
|
|
36085
36761
|
if (state.state === "failed") return "failed " + state.error;
|
|
36086
|
-
|
|
36762
|
+
}
|
|
36763
|
+
/**
|
|
36764
|
+
* 桥连接器状态的一行日志文本。
|
|
36765
|
+
*
|
|
36766
|
+
* `idle` 与 `dialing` 是重连过程的内部过渡态,只保留 `connected` 与 `failed`。
|
|
36767
|
+
* @param state - 桥连接器此刻的状态。
|
|
36768
|
+
* @returns 一行可读的状态,或 undefined(无需打印的过渡态)。
|
|
36769
|
+
*/
|
|
36770
|
+
function relayBridgeStateLine(state) {
|
|
36771
|
+
if (state.state === "connected") return "connected " + state.instance;
|
|
36772
|
+
if (state.state === "failed") return "failed " + state.error;
|
|
36773
|
+
}
|
|
36774
|
+
/**
|
|
36775
|
+
* 为状态回调套一层去重与过渡态过滤:忽略 undefined 行,且连续完全相同的行只打一次。
|
|
36776
|
+
*
|
|
36777
|
+
* 后台指数退避重试在网络不通或上游故障(如 `cf-api-unavailable`)时会反复经历
|
|
36778
|
+
* `claiming -> failed`;过滤过渡态并对结果行去重后,同一故障只报告一次,恢复为
|
|
36779
|
+
* `claimed` 时再正常输出。
|
|
36780
|
+
* @param prefix - 日志前缀(如 `'relay lease: '`)。
|
|
36781
|
+
* @param lineOf - 状态到文本行的映射,返回 undefined 表示忽略该状态。
|
|
36782
|
+
* @param log - 底层日志函数。
|
|
36783
|
+
* @returns 状态观察回调。
|
|
36784
|
+
*/
|
|
36785
|
+
function createDedupedStateLogger(prefix, lineOf, log) {
|
|
36786
|
+
let lastLine;
|
|
36787
|
+
return (state) => {
|
|
36788
|
+
const line = lineOf(state);
|
|
36789
|
+
if (line === void 0 || line === lastLine) return;
|
|
36790
|
+
lastLine = line;
|
|
36791
|
+
log(prefix + line);
|
|
36792
|
+
};
|
|
36087
36793
|
}
|
|
36088
36794
|
/**
|
|
36089
36795
|
* Mount the bridge.
|
|
@@ -36235,6 +36941,34 @@ function applyImpl(ctx, config) {
|
|
|
36235
36941
|
});
|
|
36236
36942
|
const extensions = new RemoteBridgeRegistry();
|
|
36237
36943
|
const offlineClaimTtlMs = offlineClaimTtl();
|
|
36944
|
+
/**
|
|
36945
|
+
* 第二会合点在协议面上的两处接线:`hello` 的公告与 `relay.grant` 的收帧。
|
|
36946
|
+
*
|
|
36947
|
+
* 只有「配了第二会合点」且「relay 开着」的宿主才有这一面;两种条件缺一,握手就
|
|
36948
|
+
* 与这条通道出现之前逐字相同:能力表里没有那个名字,应答里没有那个键,
|
|
36949
|
+
* `relay.grant` 仍是 `unknown-method`,名册上也不会多出一个块。
|
|
36950
|
+
*
|
|
36951
|
+
* 真正申领的那一半在下面的入站栈里建(它要等端口落定),而 hub 比它建得早,
|
|
36952
|
+
* 所以这里只放一个活引用:两处接线都按调用时刻取,从不捕获一份快照。
|
|
36953
|
+
*/
|
|
36954
|
+
const secondaryWiring = relaySecondaryOf(settings);
|
|
36955
|
+
const liveSecondary = {};
|
|
36956
|
+
const relayFace = secondaryWiring === void 0 || !settings.relay ? void 0 : {
|
|
36957
|
+
origin: () => liveSecondary.half?.origin(),
|
|
36958
|
+
grantLanded: () => {
|
|
36959
|
+
liveSecondary.half?.grantReceived().catch((error) => {
|
|
36960
|
+
log("the second meeting point claim did not land: " + (error instanceof Error ? error.message : String(error)));
|
|
36961
|
+
});
|
|
36962
|
+
}
|
|
36963
|
+
};
|
|
36964
|
+
const liveIngress = {};
|
|
36965
|
+
/** 用户在本进程内主动请求过配对码或完成了设备配对。 */
|
|
36966
|
+
let pairingRequested = false;
|
|
36967
|
+
const isRemoteArmed = () => pairingRequested || roster.devices().length > 0;
|
|
36968
|
+
const wakeRelay = () => {
|
|
36969
|
+
pairingRequested = true;
|
|
36970
|
+
liveIngress.armRelay?.();
|
|
36971
|
+
};
|
|
36238
36972
|
const hub = new BridgeHub({
|
|
36239
36973
|
extensions,
|
|
36240
36974
|
gateway: ctx.typertGateway,
|
|
@@ -36257,12 +36991,15 @@ function applyImpl(ctx, config) {
|
|
|
36257
36991
|
onPushRegistered: () => {
|
|
36258
36992
|
watchers.sync();
|
|
36259
36993
|
},
|
|
36994
|
+
...relayFace === void 0 ? {} : { relay: relayFace },
|
|
36995
|
+
onDeviceEnrolled: () => {
|
|
36996
|
+
wakeRelay();
|
|
36997
|
+
},
|
|
36260
36998
|
now: () => Date.now(),
|
|
36261
36999
|
clientTimeZone: localTimeZone,
|
|
36262
37000
|
log
|
|
36263
37001
|
});
|
|
36264
37002
|
if (typeof ctx.provide === "function") ctx.provide(REMOTE_BRIDGE_SERVICE, createRemoteBridgeFace(extensions, hub));
|
|
36265
|
-
const liveIngress = {};
|
|
36266
37003
|
/**
|
|
36267
37004
|
* 桥自己此刻的公网入口:顺序由 {@link livePublicOriginOf} 一处算清——租约的稳定
|
|
36268
37005
|
* 子域名只在后面确实有人服务时优先,快速隧道的注册还没落地时退回隧道 running 的
|
|
@@ -36289,11 +37026,15 @@ function applyImpl(ctx, config) {
|
|
|
36289
37026
|
pairing,
|
|
36290
37027
|
log,
|
|
36291
37028
|
realtime: realtimeOrigin,
|
|
36292
|
-
lan: lanOrigin
|
|
37029
|
+
lan: lanOrigin,
|
|
37030
|
+
onPairTokenIssued: () => {
|
|
37031
|
+
wakeRelay();
|
|
37032
|
+
}
|
|
36293
37033
|
}));
|
|
36294
37034
|
log(`protocol v1 listening on ${WS_PATH}`);
|
|
36295
37035
|
roster.load().then(() => {
|
|
36296
37036
|
watchers.sync();
|
|
37037
|
+
if (roster.devices().length > 0) liveIngress.armRelay?.();
|
|
36297
37038
|
}).catch(() => void 0).finally(() => {
|
|
36298
37039
|
log(pushChannelLine(pushChannelDescription()));
|
|
36299
37040
|
});
|
|
@@ -36316,18 +37057,24 @@ function applyImpl(ctx, config) {
|
|
|
36316
37057
|
ctx.effect(() => {
|
|
36317
37058
|
const forwarder = new LanForwarder();
|
|
36318
37059
|
liveIngress.forward = () => forwarder.snapshot();
|
|
37060
|
+
liveIngress.armRelay = () => {
|
|
37061
|
+
if (disposed || gatePort === void 0 || !settings.relay) return;
|
|
37062
|
+
ensureRelay();
|
|
37063
|
+
claimer?.claim(gatePort, tunnel.info.url);
|
|
37064
|
+
roster.load().then(() => secondary?.claim()).catch(() => void 0);
|
|
37065
|
+
liveIngress.pair = relayPair;
|
|
37066
|
+
};
|
|
36319
37067
|
const tunnel = new TunnelManager();
|
|
36320
37068
|
const ingress = new IngressSync();
|
|
36321
37069
|
const namedConnector = createNamedRelayConnector();
|
|
36322
|
-
const runner = createRelayBridgeRunner({ onState: (
|
|
36323
|
-
log("relay bridge: " + state.state + (state.state === "failed" ? " " + state.error : ""));
|
|
36324
|
-
} });
|
|
37070
|
+
const runner = createRelayBridgeRunner({ onState: createDedupedStateLogger("relay bridge: ", relayBridgeStateLine, log) });
|
|
36325
37071
|
const cleaner = createLegacyBlockCleaner({
|
|
36326
37072
|
profile: () => settings.profile,
|
|
36327
37073
|
log
|
|
36328
37074
|
});
|
|
36329
37075
|
let plan;
|
|
36330
37076
|
let relayPair;
|
|
37077
|
+
let secondary;
|
|
36331
37078
|
let claimer;
|
|
36332
37079
|
let relayIdentity;
|
|
36333
37080
|
/**
|
|
@@ -36341,11 +37088,24 @@ function applyImpl(ctx, config) {
|
|
|
36341
37088
|
};
|
|
36342
37089
|
const announcer = createRelayAnnouncer({
|
|
36343
37090
|
identity: identityOf,
|
|
37091
|
+
controlUrl: settings.relayControlUrl,
|
|
37092
|
+
publicSuffix: settings.relayPublicSuffix,
|
|
36344
37093
|
log
|
|
36345
37094
|
});
|
|
36346
37095
|
const relayHalf = createRelayHalfSwitch({
|
|
36347
37096
|
announcer,
|
|
36348
|
-
pair: () =>
|
|
37097
|
+
pair: () => {
|
|
37098
|
+
const halves = [relayPair, secondary].filter((half) => half !== void 0);
|
|
37099
|
+
if (halves.length === 0) return void 0;
|
|
37100
|
+
return {
|
|
37101
|
+
async release() {
|
|
37102
|
+
for (const half of halves) await half.release();
|
|
37103
|
+
},
|
|
37104
|
+
dispose() {
|
|
37105
|
+
for (const half of halves) half.dispose();
|
|
37106
|
+
}
|
|
37107
|
+
};
|
|
37108
|
+
},
|
|
36349
37109
|
log
|
|
36350
37110
|
});
|
|
36351
37111
|
liveIngress.registered = () => announcer.registered;
|
|
@@ -36383,9 +37143,8 @@ function applyImpl(ctx, config) {
|
|
|
36383
37143
|
},
|
|
36384
37144
|
log
|
|
36385
37145
|
}),
|
|
36386
|
-
|
|
36387
|
-
|
|
36388
|
-
}
|
|
37146
|
+
controlUrl: settings.relayControlUrl,
|
|
37147
|
+
onState: createDedupedStateLogger("relay lease: ", relayStateLine, log)
|
|
36389
37148
|
});
|
|
36390
37149
|
claimer = createLeaseClaimer({
|
|
36391
37150
|
start: async (input) => {
|
|
@@ -36396,6 +37155,42 @@ function applyImpl(ctx, config) {
|
|
|
36396
37155
|
},
|
|
36397
37156
|
log
|
|
36398
37157
|
});
|
|
37158
|
+
ensureSecondary(identity);
|
|
37159
|
+
};
|
|
37160
|
+
/**
|
|
37161
|
+
* 建第二个会合点的租约半区:配了它才建,建一次,与第一半区共用同一份身份。
|
|
37162
|
+
*
|
|
37163
|
+
* 它读的是名册里最新的那条授权(第一半区从不读它),连接器、释放与退避全部自成
|
|
37164
|
+
* 一套:这条半区无论怎么失败,市场边缘那条租约与连接器都不受影响。
|
|
37165
|
+
* @param identity - 本 profile 的 relay 身份(两个会合点必须是同一个对象)。
|
|
37166
|
+
*/
|
|
37167
|
+
const ensureSecondary = (identity) => {
|
|
37168
|
+
if (secondary !== void 0 || secondaryWiring === void 0) return;
|
|
37169
|
+
const secondaryRunner = createRelayBridgeRunner({
|
|
37170
|
+
stateFile: relaySecondaryBridgeStateFile(),
|
|
37171
|
+
onState: (state) => {
|
|
37172
|
+
log("relay secondary bridge: " + state.state + (state.state === "failed" ? " " + state.error : ""));
|
|
37173
|
+
if (state.state === "failed") secondary?.connectorFailed(state.error);
|
|
37174
|
+
}
|
|
37175
|
+
});
|
|
37176
|
+
secondary = createRelaySecondaryHalf({
|
|
37177
|
+
identity,
|
|
37178
|
+
controlUrl: secondaryWiring.controlUrl,
|
|
37179
|
+
publicSuffix: secondaryWiring.publicSuffix,
|
|
37180
|
+
grant: () => roster.relayGrant()?.grant,
|
|
37181
|
+
port: () => gatePort,
|
|
37182
|
+
pluginVersion: () => readPluginVersion(),
|
|
37183
|
+
startBridge: (start) => {
|
|
37184
|
+
secondaryRunner.start(start);
|
|
37185
|
+
},
|
|
37186
|
+
stopBridge: () => {
|
|
37187
|
+
secondaryRunner.stop();
|
|
37188
|
+
},
|
|
37189
|
+
onState: (state) => {
|
|
37190
|
+
log("relay secondary lease: " + relayStateLine(state));
|
|
37191
|
+
}
|
|
37192
|
+
});
|
|
37193
|
+
liveSecondary.half = secondary;
|
|
36399
37194
|
};
|
|
36400
37195
|
let gate;
|
|
36401
37196
|
let gatePort;
|
|
@@ -36435,7 +37230,8 @@ function applyImpl(ctx, config) {
|
|
|
36435
37230
|
gatePort: port,
|
|
36436
37231
|
...startup?.host === void 0 ? {} : { startupHost: startup.host },
|
|
36437
37232
|
candidates: lanIPv4Addresses(),
|
|
36438
|
-
wildcardSupported: wildcardBindSupported()
|
|
37233
|
+
wildcardSupported: wildcardBindSupported(),
|
|
37234
|
+
remoteArmed: isRemoteArmed()
|
|
36439
37235
|
});
|
|
36440
37236
|
plan = next.tunnel;
|
|
36441
37237
|
if (next.tunnel === void 0) log("autoTunnel is on but the web server port is not bound yet — the quick tunnel starts once it settles");
|
|
@@ -36457,8 +37253,11 @@ function applyImpl(ctx, config) {
|
|
|
36457
37253
|
mode: next.tunnel?.mode,
|
|
36458
37254
|
url: tunnel.info.url
|
|
36459
37255
|
});
|
|
36460
|
-
|
|
36461
|
-
|
|
37256
|
+
if (next.claim) {
|
|
37257
|
+
ensureRelay();
|
|
37258
|
+
claimer?.claim(port, tunnel.info.url);
|
|
37259
|
+
roster.load().then(() => secondary?.claim()).catch(() => void 0);
|
|
37260
|
+
}
|
|
36462
37261
|
} else relayHalf.off();
|
|
36463
37262
|
applyForward(next.forward, wsPort, port);
|
|
36464
37263
|
ingress.schedule(next.ingress);
|
|
@@ -36501,6 +37300,7 @@ function applyImpl(ctx, config) {
|
|
|
36501
37300
|
log("relay is off at mount — withdrawing the registration the previous mount left and releasing its lease");
|
|
36502
37301
|
retireStaleRelayHalfOf({
|
|
36503
37302
|
identity,
|
|
37303
|
+
controlUrl: settings.relayControlUrl,
|
|
36504
37304
|
log
|
|
36505
37305
|
});
|
|
36506
37306
|
};
|
|
@@ -36520,11 +37320,19 @@ function applyImpl(ctx, config) {
|
|
|
36520
37320
|
liveIngress.tunnel = void 0;
|
|
36521
37321
|
liveIngress.registered = void 0;
|
|
36522
37322
|
liveIngress.forward = void 0;
|
|
37323
|
+
liveIngress.armRelay = void 0;
|
|
36523
37324
|
relayHalf.dispose();
|
|
37325
|
+
const connectors = [relayPair, secondary].filter((half) => half !== void 0);
|
|
36524
37326
|
disposeBridgeStack({
|
|
36525
37327
|
ingress,
|
|
36526
37328
|
forwarder,
|
|
36527
|
-
...
|
|
37329
|
+
...connectors.length === 0 ? {} : { connectors: { dispose: () => {
|
|
37330
|
+
for (const half of connectors) try {
|
|
37331
|
+
half.dispose();
|
|
37332
|
+
} catch (error) {
|
|
37333
|
+
log("a relay half did not release cleanly: " + (error instanceof Error ? error.message : String(error)));
|
|
37334
|
+
}
|
|
37335
|
+
} } },
|
|
36528
37336
|
tunnel,
|
|
36529
37337
|
...gate === void 0 ? {} : { gate }
|
|
36530
37338
|
}, log);
|
|
@@ -36544,4 +37352,4 @@ function applyImpl(ctx, config) {
|
|
|
36544
37352
|
*/
|
|
36545
37353
|
const apply = mountOnce("@linxin666/dsh-remote-bridge", applyImpl);
|
|
36546
37354
|
//#endregion
|
|
36547
|
-
export { EFFORT_PATH, OFFLINE_CLAIM_TTL_ENV, PORT_SETTLE_RETRY_MS, ROSTER_PATH, TURN_END_QUIET_MAX_ENV, apply, bridgeWiringPlanOf, createLeaseClaimer, createLegacyBlockCleaner, createPortSettleRetry, createRelayAnnouncer, createRelayHalfSwitch, disposeBridgeStack, inject, lanBasesOf, lanBindCapabilityOf, lanBindFrameOf, lanOriginOf, leaseConnectorSeams, leaseConnectorWants, livePublicOriginOf, name, offlineClaimTtl, relayAnnounceTargetOf, resolveBridgeConfig, retireStaleRelayHalfOf, turnEndQuietMaxWait };
|
|
37355
|
+
export { EFFORT_PATH, OFFLINE_CLAIM_TTL_ENV, PORT_SETTLE_RETRY_MS, ROSTER_PATH, TURN_END_QUIET_MAX_ENV, apply, bridgeWiringPlanOf, createDedupedStateLogger, createLeaseClaimer, createLegacyBlockCleaner, createPortSettleRetry, createRelayAnnouncer, createRelayHalfSwitch, disposeBridgeStack, inject, lanBasesOf, lanBindCapabilityOf, lanBindFrameOf, lanOriginOf, leaseConnectorSeams, leaseConnectorWants, livePublicOriginOf, name, offlineClaimTtl, relayAnnounceTargetOf, relayBridgeStateLine, relayStateLine, resolveBridgeConfig, retireStaleRelayHalfOf, turnEndQuietMaxWait };
|