@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/src/core/connection.ts
CHANGED
|
@@ -104,6 +104,7 @@ import {
|
|
|
104
104
|
METHOD_SESSION_SNAPSHOT,
|
|
105
105
|
METHOD_SESSION_TITLES,
|
|
106
106
|
METHOD_SESSION_UNARCHIVE,
|
|
107
|
+
METHOD_RELAY_GRANT,
|
|
107
108
|
METHOD_UI_EVENT,
|
|
108
109
|
METHOD_UI_LIST,
|
|
109
110
|
METHOD_SESSION_UNPIN,
|
|
@@ -116,6 +117,7 @@ import {
|
|
|
116
117
|
METHOD_USAGE_SESSION,
|
|
117
118
|
METHOD_USAGE_STATS,
|
|
118
119
|
METHOD_WORKSPACE_LIST,
|
|
120
|
+
CAP_RELAY_TIER,
|
|
119
121
|
MINOR,
|
|
120
122
|
PROTO,
|
|
121
123
|
SERVED_CAPABILITIES,
|
|
@@ -185,6 +187,34 @@ export interface BridgeTransport {
|
|
|
185
187
|
frameDeflate?(declared: boolean): void
|
|
186
188
|
}
|
|
187
189
|
|
|
190
|
+
/**
|
|
191
|
+
* 第二会合点在协议面上的那一半:一条公告与一次收帧。
|
|
192
|
+
*
|
|
193
|
+
* 只有配了第二会合点的宿主才提供这个面,而它存在与否就是 `relay.tier.v1` 这个
|
|
194
|
+
* 能力名与 `relay.grant` 这个方法存在与否——没有它,握手与应答与今天逐字相同。
|
|
195
|
+
* 宿主侧的动作(写名册、去第二会合点申领)全在插件半区,core 里只留这两处接线,
|
|
196
|
+
* 所以一个不认识的宿主不会因为这里多了一层而改变任何一帧。
|
|
197
|
+
*/
|
|
198
|
+
export interface RelayTierFace {
|
|
199
|
+
/**
|
|
200
|
+
* 这次握手要在 `hello.r.relay` 里公告的会合点,或 undefined(此刻没有可公告的)。
|
|
201
|
+
*
|
|
202
|
+
* 公告的含义是「这台宿主此刻确实持有一份中继承认的、按 6 小时周期刷新的租约」,
|
|
203
|
+
* 而不是「它曾经申到过一次」:公告出去的是「拨这个地址」,而一个没有有效租约的
|
|
204
|
+
* 地址背后没有人服务。还没申到、降级被拒、grant 过期、主动释放,四种情况都回
|
|
205
|
+
* undefined,于是一条连接的下一个世代自己退回市场边缘,不需要服务端推送任何东西。
|
|
206
|
+
* @returns `wss://<id><suffix>`,或 undefined。
|
|
207
|
+
*/
|
|
208
|
+
origin(): string | undefined
|
|
209
|
+
/**
|
|
210
|
+
* 一条新授权已经落进名册行:第二会合点要立刻重新申领一次。
|
|
211
|
+
*
|
|
212
|
+
* 调用发生在名册写完之后,所以插件半区读到的就是这条授权。它是**触发**而不是
|
|
213
|
+
* 等待:`relay.grant` 的应答不等那一次网络往返,申领失败由半区自己的退避收着。
|
|
214
|
+
*/
|
|
215
|
+
grantLanded(): void
|
|
216
|
+
}
|
|
217
|
+
|
|
188
218
|
export interface BridgeConnectionOptions {
|
|
189
219
|
readonly gateway: BridgeGateway
|
|
190
220
|
readonly pairing: PairingService
|
|
@@ -272,6 +302,11 @@ export interface BridgeConnectionOptions {
|
|
|
272
302
|
* read the host's own answer.
|
|
273
303
|
*/
|
|
274
304
|
readonly turnEndQuiet?: TurnEndQuietGate
|
|
305
|
+
/**
|
|
306
|
+
* 第二会合点(`relay.tier.v1`)。缺省就是没有第二会合点:`hello` 不带
|
|
307
|
+
* `relay` 键、能力表里没有那个名字、`relay.grant` 仍是 `unknown-method`。
|
|
308
|
+
*/
|
|
309
|
+
readonly relay?: RelayTierFace
|
|
275
310
|
/**
|
|
276
311
|
* Called after a registration changed the device table.
|
|
277
312
|
*
|
|
@@ -282,6 +317,15 @@ export interface BridgeConnectionOptions {
|
|
|
282
317
|
* `push.register` into a failure.
|
|
283
318
|
*/
|
|
284
319
|
readonly onPushRegistered?: () => void
|
|
320
|
+
/**
|
|
321
|
+
* Called after `pair.finish` admits a device into the roster.
|
|
322
|
+
*
|
|
323
|
+
* A machine that started with no paired devices defers claiming its relay
|
|
324
|
+
* lease until a remote device is actually paired (or a pairing code is
|
|
325
|
+
* requested); guarded at the call site so background relay work never fails
|
|
326
|
+
* the pairing response.
|
|
327
|
+
*/
|
|
328
|
+
readonly onDeviceEnrolled?: () => void
|
|
285
329
|
}
|
|
286
330
|
|
|
287
331
|
/** A device the connection proved itself to be, resolved from the upgrade request. */
|
|
@@ -1026,6 +1070,11 @@ export class BridgeConnection {
|
|
|
1026
1070
|
if (frame.m === METHOD_UI_LIST && !this.declares(CAP_UI_LIST)) {
|
|
1027
1071
|
return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
|
|
1028
1072
|
}
|
|
1073
|
+
// 第二会合点只在配了它的宿主上存在:没有这个面时这一帧与它出现之前逐字一样是
|
|
1074
|
+
// `unknown-method`,名册上也不会为它多出一块授权。
|
|
1075
|
+
if (frame.m === METHOD_RELAY_GRANT && this.#options.relay === undefined) {
|
|
1076
|
+
return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
|
|
1077
|
+
}
|
|
1029
1078
|
// Unconditional: a loopback Host buys nothing here. Without a device token
|
|
1030
1079
|
// only the handshake and the two pairing steps run.
|
|
1031
1080
|
if (!this.paired && !UNPAIRED_METHODS.has(frame.m)) return refusal(CODE_UNPAIRED, 'this connection is not paired')
|
|
@@ -1056,6 +1105,7 @@ export class BridgeConnection {
|
|
|
1056
1105
|
case METHOD_QUESTION_LIST: return this.#questionList(frame.p)
|
|
1057
1106
|
case METHOD_UI_EVENT: return this.#uiEvent(frame.p)
|
|
1058
1107
|
case METHOD_UI_LIST: return this.#uiList(frame.p)
|
|
1108
|
+
case METHOD_RELAY_GRANT: return await this.#relayGrant(frame.p)
|
|
1059
1109
|
case METHOD_PUSH_REGISTER: return await this.#pushRegister(frame.p)
|
|
1060
1110
|
case METHOD_USAGE_SESSION: return await this.#usageSession(frame.p)
|
|
1061
1111
|
case METHOD_USAGE_BALANCE: return await this.#usageBalance(frame.p)
|
|
@@ -1126,6 +1176,10 @@ export class BridgeConnection {
|
|
|
1126
1176
|
*/
|
|
1127
1177
|
#servedCapabilities(): string[] {
|
|
1128
1178
|
const capabilities = [...SERVED_CAPABILITIES]
|
|
1179
|
+
// 第二会合点是条件能力:配了它才公告,所以它不在 {@link SERVED_CAPABILITIES}
|
|
1180
|
+
// 里(那张表是每条连接逐字相同的开头),而是紧跟其后追加——没配它的宿主因此
|
|
1181
|
+
// 仍然答出那张表本身。
|
|
1182
|
+
if (this.#options.relay !== undefined) capabilities.push(CAP_RELAY_TIER)
|
|
1129
1183
|
for (const capability of this.#options.extensions?.capabilities() ?? []) {
|
|
1130
1184
|
if (!capabilities.includes(capability)) capabilities.push(capability)
|
|
1131
1185
|
}
|
|
@@ -1142,6 +1196,9 @@ export class BridgeConnection {
|
|
|
1142
1196
|
// The hub replays anything this client can now receive but missed: a phone
|
|
1143
1197
|
// that connected after a question was raised has no other way to learn of it.
|
|
1144
1198
|
this.#options.onDeclare?.(this)
|
|
1199
|
+
// 第二会合点的公告。钩子缺省存在与否就是「这台宿主有没有第二个会合点」,因此
|
|
1200
|
+
// 没有它、或它此刻答不出地址时,这个键整个不出现——应答与今天逐字相同。
|
|
1201
|
+
const relayOrigin = this.#options.relay?.origin()
|
|
1145
1202
|
return {
|
|
1146
1203
|
ok: true,
|
|
1147
1204
|
r: {
|
|
@@ -1151,6 +1208,7 @@ export class BridgeConnection {
|
|
|
1151
1208
|
capabilities: this.#servedCapabilities(),
|
|
1152
1209
|
resume: 'snapshot',
|
|
1153
1210
|
auth: this.paired ? 'paired' : 'unpaired',
|
|
1211
|
+
...(relayOrigin === undefined ? {} : { relay: { origin: relayOrigin } }),
|
|
1154
1212
|
},
|
|
1155
1213
|
}
|
|
1156
1214
|
}
|
|
@@ -1191,6 +1249,11 @@ export class BridgeConnection {
|
|
|
1191
1249
|
const enrollment = await this.#options.roster.enroll(devicePubKey)
|
|
1192
1250
|
if (enrollment === undefined) return refusal(CODE_INVALID_ARGS, 'devicePubKey is not a P-256 SPKI public key')
|
|
1193
1251
|
this.#deviceId = enrollment.deviceId
|
|
1252
|
+
try {
|
|
1253
|
+
this.#options.onDeviceEnrolled?.()
|
|
1254
|
+
} catch {
|
|
1255
|
+
// Relay lease activation is background work and must never fail pairing.
|
|
1256
|
+
}
|
|
1194
1257
|
return { ok: true, r: { deviceToken: enrollment.deviceToken, deviceId: enrollment.deviceId } }
|
|
1195
1258
|
}
|
|
1196
1259
|
|
|
@@ -2505,6 +2568,53 @@ export class BridgeConnection {
|
|
|
2505
2568
|
return { ok: true, r: { ok: true } }
|
|
2506
2569
|
}
|
|
2507
2570
|
|
|
2571
|
+
/**
|
|
2572
|
+
* The body of `relay.grant`: one device hands its relay tier grant over.
|
|
2573
|
+
*
|
|
2574
|
+
* A write, and the only one this channel has. The grant lands in the sending
|
|
2575
|
+
* device's own roster row (schema 4), beside the identity it already proved, so
|
|
2576
|
+
* revoking the device withdraws the admission with it and no second table exists.
|
|
2577
|
+
* The host then asks the second meeting point to refresh its lease, and that ask
|
|
2578
|
+
* is fired rather than awaited: a phone hands a fresh grant over precisely when a
|
|
2579
|
+
* claim was just refused, and this frame must not hang on a meeting point that
|
|
2580
|
+
* stopped answering. The roster row is what the next claim reads, so the ask
|
|
2581
|
+
* never depends on this answer reaching the client first.
|
|
2582
|
+
*
|
|
2583
|
+
* The answer is `{ok:true}` and nothing else. There is deliberately no echo, no
|
|
2584
|
+
* tier and no "admitted" flag: the tier is decided out of band by the meeting
|
|
2585
|
+
* point, this bridge never learns it, and a field claiming one would be a lie the
|
|
2586
|
+
* client might render.
|
|
2587
|
+
* @param payload - `{grant}`.
|
|
2588
|
+
*/
|
|
2589
|
+
async #relayGrant(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
|
|
2590
|
+
const relay = this.#options.relay
|
|
2591
|
+
// Unreachable through the dispatcher (the gate above refuses first), and kept
|
|
2592
|
+
// because this handler reads its own precondition rather than trusting it.
|
|
2593
|
+
if (relay === undefined) return refusal(CODE_UNKNOWN_METHOD, `unknown method ${METHOD_RELAY_GRANT}`)
|
|
2594
|
+
const grant = payload.grant
|
|
2595
|
+
if (typeof grant !== 'string' || grant === '') {
|
|
2596
|
+
return refusal(CODE_INVALID_ARGS, 'grant must be the string the account service issued')
|
|
2597
|
+
}
|
|
2598
|
+
const deviceId = this.#deviceId
|
|
2599
|
+
if (deviceId === undefined) return refusal(CODE_UNPAIRED, 'this connection is not paired')
|
|
2600
|
+
try {
|
|
2601
|
+
const stored = await this.#options.roster.setRelayGrant(deviceId, grant)
|
|
2602
|
+
if (!stored) return refusal(CODE_INTERNAL, 'this connection names no paired device')
|
|
2603
|
+
try {
|
|
2604
|
+
relay.grantLanded()
|
|
2605
|
+
} catch (error) {
|
|
2606
|
+
// The re-claim is this bridge's own background work and may never turn a
|
|
2607
|
+
// grant the roster already holds into a failure of this frame.
|
|
2608
|
+
this.#options.log(`the second meeting point could not re-claim: ${failureText(error)}`)
|
|
2609
|
+
}
|
|
2610
|
+
} catch (error) {
|
|
2611
|
+
// A grant that never reached the disk is an admission the host does not
|
|
2612
|
+
// have, so the client has to be told instead of assuming it landed.
|
|
2613
|
+
return refusal(CODE_INTERNAL, `could not write the device roster: ${failureText(error)}`)
|
|
2614
|
+
}
|
|
2615
|
+
return { ok: true, r: { ok: true } }
|
|
2616
|
+
}
|
|
2617
|
+
|
|
2508
2618
|
/**
|
|
2509
2619
|
* 答一次 `usage.session`:一条会话的上下文窗口与下一次请求的组成估算。
|
|
2510
2620
|
*
|
package/src/core/devices.ts
CHANGED
|
@@ -25,14 +25,15 @@ export const DEVICE_ID_BYTES = 12
|
|
|
25
25
|
*
|
|
26
26
|
* 1 carried the six identity fields only; 2 adds the optional `push` block per
|
|
27
27
|
* row (§28); 3 adds the optional `relayToken` inside that block, the credential the
|
|
28
|
-
* hosted relay signs a delivery for instead of a local Apple key
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
*
|
|
28
|
+
* hosted relay signs a delivery for instead of a local Apple key; 4 adds the
|
|
29
|
+
* optional `relay` block beside it, the tier grant the phone handed over and when
|
|
30
|
+
* this bridge received it. Every step is additive, so an older file reads as-is:
|
|
31
|
+
* no row loses a field, every paired phone stays paired, and the file is rewritten
|
|
32
|
+
* as the current version the next time anything is written. The reader therefore
|
|
33
|
+
* accepts any version whose row table validates rather than quarantining a file it
|
|
34
|
+
* merely does not recognise — a downgrade must never un-pair every phone.
|
|
34
35
|
*/
|
|
35
|
-
export const ROSTER_VERSION =
|
|
36
|
+
export const ROSTER_VERSION = 4
|
|
36
37
|
|
|
37
38
|
/** The APNs environments a device may register for. */
|
|
38
39
|
export type PushEnvironment = 'sandbox' | 'production'
|
|
@@ -82,6 +83,27 @@ export interface PushRegistration {
|
|
|
82
83
|
readonly registeredAt: number
|
|
83
84
|
}
|
|
84
85
|
|
|
86
|
+
/**
|
|
87
|
+
* One device's relay tier grant (schema 4).
|
|
88
|
+
*
|
|
89
|
+
* The App obtains it from the account service and hands it over through
|
|
90
|
+
* `relay.grant`. This bridge never mints, parses or reissues it: it keeps the text
|
|
91
|
+
* and presents it in its next claim to the second meeting point, which decides the
|
|
92
|
+
* entitlement out of band and answers the host with a lease or a refusal. Nothing
|
|
93
|
+
* about the account crosses the wire back — the host learns "admitted" or "not",
|
|
94
|
+
* never who the phone is.
|
|
95
|
+
*
|
|
96
|
+
* It is a fact about the phone that gave it, so it lives in that phone's row and
|
|
97
|
+
* disappears with the row when the phone is revoked; it never becomes a second
|
|
98
|
+
* identity of the bridge's own.
|
|
99
|
+
*/
|
|
100
|
+
export interface RelayGrant {
|
|
101
|
+
/** The grant text, exactly as the account service issued it. */
|
|
102
|
+
readonly grant: string
|
|
103
|
+
/** When this bridge received it, in epoch seconds. */
|
|
104
|
+
readonly receivedAt: number
|
|
105
|
+
}
|
|
106
|
+
|
|
85
107
|
/** One device a notification can be addressed to. */
|
|
86
108
|
export interface PushTargetView {
|
|
87
109
|
readonly deviceId: string
|
|
@@ -103,6 +125,14 @@ export interface DeviceRecord {
|
|
|
103
125
|
* every phone that predates the channel.
|
|
104
126
|
*/
|
|
105
127
|
readonly push?: PushRegistration
|
|
128
|
+
/**
|
|
129
|
+
* The device's relay tier grant, absent until it calls `relay.grant`.
|
|
130
|
+
*
|
|
131
|
+
* A row without it is a phone whose host may still claim the second meeting
|
|
132
|
+
* point — a bridged lease needs no grant at the market edge — it just cannot be
|
|
133
|
+
* admitted to a tier that requires one.
|
|
134
|
+
*/
|
|
135
|
+
readonly relay?: RelayGrant
|
|
106
136
|
}
|
|
107
137
|
|
|
108
138
|
/** A roster row plus the one field that never leaves the file. */
|
|
@@ -178,6 +208,33 @@ function pushOf(value: unknown, log: (message: string) => void): PushRegistratio
|
|
|
178
208
|
}
|
|
179
209
|
}
|
|
180
210
|
|
|
211
|
+
/**
|
|
212
|
+
* Read one row's `relay` block.
|
|
213
|
+
*
|
|
214
|
+
* Dropped rather than quarantined for the reason `pushOf` is: one unreadable grant
|
|
215
|
+
* is not a reason to un-pair every phone, and the row keeps its identity and simply
|
|
216
|
+
* carries no admission. The two fields are the whole block — a grant text and the
|
|
217
|
+
* epoch second it arrived in — so anything else on that object is discarded instead
|
|
218
|
+
* of being handed on to a claim body.
|
|
219
|
+
* @param value - the raw `relay` field of a row.
|
|
220
|
+
* @param log - where a dropped block is reported.
|
|
221
|
+
* @returns the grant, or undefined when there is none to read.
|
|
222
|
+
*/
|
|
223
|
+
function relayOf(value: unknown, log: (message: string) => void): RelayGrant | undefined {
|
|
224
|
+
if (value === undefined) return undefined
|
|
225
|
+
if (typeof value !== 'object' || value === null) {
|
|
226
|
+
log('a device row carries an unreadable relay block; ignoring it and keeping the row')
|
|
227
|
+
return undefined
|
|
228
|
+
}
|
|
229
|
+
const row = value as Record<string, unknown>
|
|
230
|
+
if (typeof row.grant !== 'string' || row.grant === ''
|
|
231
|
+
|| typeof row.receivedAt !== 'number' || !Number.isFinite(row.receivedAt)) {
|
|
232
|
+
log('a device row carries an unreadable relay block; ignoring it and keeping the row')
|
|
233
|
+
return undefined
|
|
234
|
+
}
|
|
235
|
+
return { grant: row.grant, receivedAt: row.receivedAt }
|
|
236
|
+
}
|
|
237
|
+
|
|
181
238
|
function isStoredDevice(value: unknown): value is StoredDevice {
|
|
182
239
|
if (typeof value !== 'object' || value === null) return false
|
|
183
240
|
const row = value as Record<string, unknown>
|
|
@@ -334,6 +391,52 @@ export class DeviceRoster {
|
|
|
334
391
|
return false
|
|
335
392
|
}
|
|
336
393
|
|
|
394
|
+
/**
|
|
395
|
+
* Record the relay grant one device just handed over (schema 4).
|
|
396
|
+
*
|
|
397
|
+
* A grant the phone resends replaces the one on the row: the account service
|
|
398
|
+
* reissues them periodically, and the newest text is the one the second meeting
|
|
399
|
+
* point will verify against the current plan. Nothing else on the row moves, so a
|
|
400
|
+
* grant that arrives between two reconnects cannot disturb a push registration.
|
|
401
|
+
* @param deviceId - the device that sent `relay.grant`.
|
|
402
|
+
* @param grant - the grant text as the account service issued it.
|
|
403
|
+
* @returns false when no such device is paired.
|
|
404
|
+
*/
|
|
405
|
+
async setRelayGrant(deviceId: string, grant: string): Promise<boolean> {
|
|
406
|
+
// Epoch seconds, not milliseconds: the block crosses to the phone as the
|
|
407
|
+
// protocol's own timestamps do, and a reader comparing it with a claim time
|
|
408
|
+
// would otherwise disagree by three orders of magnitude.
|
|
409
|
+
const receivedAt = Math.floor(this.#now() / 1000)
|
|
410
|
+
for (const [hash, row] of this.#devices) {
|
|
411
|
+
if (row.deviceId !== deviceId) continue
|
|
412
|
+
this.#devices.set(hash, { ...row, relay: { grant, receivedAt } })
|
|
413
|
+
await this.#persist()
|
|
414
|
+
return true
|
|
415
|
+
}
|
|
416
|
+
return false
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/**
|
|
420
|
+
* @returns the relay grant this bridge claims with, or undefined when no row
|
|
421
|
+
* holds one.
|
|
422
|
+
*
|
|
423
|
+
* The newest one wins, because one host holds one lease at the second meeting
|
|
424
|
+
* point and the phone that most recently handed a grant over is the one whose
|
|
425
|
+
* subscription is being claimed. A pairing with several phones of mixed tiers is
|
|
426
|
+
* then the accepted asymmetry the design names: the host is admitted while at
|
|
427
|
+
* least one paired phone holds a tier that is, and the free-tier phone simply
|
|
428
|
+
* keeps using the market edge.
|
|
429
|
+
*/
|
|
430
|
+
relayGrant(): RelayGrant | undefined {
|
|
431
|
+
let newest: RelayGrant | undefined
|
|
432
|
+
for (const row of this.#devices.values()) {
|
|
433
|
+
const held = row.relay
|
|
434
|
+
if (held === undefined) continue
|
|
435
|
+
if (newest === undefined || held.receivedAt > newest.receivedAt) newest = held
|
|
436
|
+
}
|
|
437
|
+
return newest
|
|
438
|
+
}
|
|
439
|
+
|
|
337
440
|
/**
|
|
338
441
|
* Forget one Live Activity token the phone no longer holds.
|
|
339
442
|
*
|
|
@@ -378,8 +481,10 @@ export class DeviceRoster {
|
|
|
378
481
|
for (const [hash, row] of this.#devices) {
|
|
379
482
|
const registration = row.push
|
|
380
483
|
if (registration === undefined || registration.deviceToken !== deviceToken) continue
|
|
381
|
-
|
|
382
|
-
|
|
484
|
+
// Only the push block goes: a dead APNs token says nothing about the relay
|
|
485
|
+
// grant the same phone handed over, which rides its own block on this row.
|
|
486
|
+
const { push: _dropped, ...rest } = row
|
|
487
|
+
this.#devices.set(hash, rest)
|
|
383
488
|
await this.#persist()
|
|
384
489
|
return true
|
|
385
490
|
}
|
|
@@ -437,15 +542,25 @@ export class DeviceRoster {
|
|
|
437
542
|
this.#devices.delete(row.tokenHash)
|
|
438
543
|
rows += 1
|
|
439
544
|
}
|
|
440
|
-
if (survivor.push !== undefined) continue
|
|
441
545
|
// A survivor that never registered takes the newest registration one of
|
|
442
|
-
// its dropped rows carried: same phone, same install, same tokens.
|
|
546
|
+
// its dropped rows carried: same phone, same install, same tokens. The
|
|
547
|
+
// relay grant follows the same rule for the same reason — collapsing rows
|
|
548
|
+
// must not withdraw an admission the phone already handed over.
|
|
443
549
|
let newest: PushRegistration | undefined
|
|
550
|
+
let newestGrant: RelayGrant | undefined
|
|
444
551
|
for (const row of held) {
|
|
445
|
-
if (row === survivor
|
|
446
|
-
if (newest === undefined || row.push.registeredAt > newest.registeredAt) newest = row.push
|
|
552
|
+
if (row === survivor) continue
|
|
553
|
+
if (row.push !== undefined && (newest === undefined || row.push.registeredAt > newest.registeredAt)) newest = row.push
|
|
554
|
+
if (row.relay !== undefined && (newestGrant === undefined || row.relay.receivedAt > newestGrant.receivedAt)) newestGrant = row.relay
|
|
447
555
|
}
|
|
448
|
-
|
|
556
|
+
const push = survivor.push ?? newest
|
|
557
|
+
const relay = survivor.relay ?? newestGrant
|
|
558
|
+
if (push === survivor.push && relay === survivor.relay) continue
|
|
559
|
+
this.#devices.set(survivor.tokenHash, {
|
|
560
|
+
...survivor,
|
|
561
|
+
...(push === undefined ? {} : { push }),
|
|
562
|
+
...(relay === undefined ? {} : { relay }),
|
|
563
|
+
})
|
|
449
564
|
}
|
|
450
565
|
const holders = new Map<string, StoredDevice[]>()
|
|
451
566
|
for (const row of this.#devices.values()) {
|
|
@@ -511,10 +626,19 @@ export class DeviceRoster {
|
|
|
511
626
|
for (const row of rows) {
|
|
512
627
|
// The raw block is re-read per row instead of trusted from the guard, so a
|
|
513
628
|
// row that carries an unreadable token keeps its identity and loses only
|
|
514
|
-
// its notification.
|
|
515
|
-
|
|
629
|
+
// its notification. The relay grant takes the same route: a block this
|
|
630
|
+
// reader cannot trust costs the row its admission, never its pairing.
|
|
631
|
+
const { push: raw, relay: rawRelay, ...rest } = row as StoredDevice & {
|
|
632
|
+
readonly push?: unknown
|
|
633
|
+
readonly relay?: unknown
|
|
634
|
+
}
|
|
516
635
|
const push = pushOf(raw, this.#log)
|
|
517
|
-
|
|
636
|
+
const relay = relayOf(rawRelay, this.#log)
|
|
637
|
+
this.#devices.set(row.tokenHash, {
|
|
638
|
+
...rest,
|
|
639
|
+
...(push === undefined ? {} : { push }),
|
|
640
|
+
...(relay === undefined ? {} : { relay }),
|
|
641
|
+
})
|
|
518
642
|
}
|
|
519
643
|
this.#log(`device roster ${this.#file}: ${rows.length} paired device(s)`)
|
|
520
644
|
const compacted = this.#compact()
|
package/src/core/protocol.ts
CHANGED
|
@@ -49,6 +49,14 @@ export const METHOD_USAGE_STATS = 'usage.stats'
|
|
|
49
49
|
// 协议 §35 追加的两个方法:一条卡上的动作回来,以及一张全局卡表的对账读。
|
|
50
50
|
export const METHOD_UI_EVENT = 'ui.event'
|
|
51
51
|
export const METHOD_UI_LIST = 'ui.list'
|
|
52
|
+
/**
|
|
53
|
+
* 一条配对连接把手机从账号服务换到的中继授权交给宿主。
|
|
54
|
+
*
|
|
55
|
+
* 它是这条通道唯一的写动作:授权落进那台设备自己的名册行,随后宿主拿它去第二
|
|
56
|
+
* 会合点申领租约。宿主不认识账号——它只会看到「准了」或「不准」,绝不会从这一帧
|
|
57
|
+
* 里读出用户是谁。只在配了第二会合点的宿主上是这个方法(见 {@link CAP_RELAY_TIER})。
|
|
58
|
+
*/
|
|
59
|
+
export const METHOD_RELAY_GRANT = 'relay.grant'
|
|
52
60
|
|
|
53
61
|
/** Server-pushed topics of protocol v1. */
|
|
54
62
|
export const TOPIC_SESSION_DELTA = 'session.delta'
|
|
@@ -282,6 +290,21 @@ export const CAP_UI = 'ui.v1'
|
|
|
282
290
|
*/
|
|
283
291
|
export const CAP_UI_LIST = 'ui.list.v1'
|
|
284
292
|
|
|
293
|
+
/**
|
|
294
|
+
* 宿主配了第二会合点时,在 `hello` 的 `capabilities` 里公告的能力名。
|
|
295
|
+
*
|
|
296
|
+
* 它是这条通道的全部门槛,而且门槛落在宿主这一侧:一个配了第二会合点的宿主才
|
|
297
|
+
* 公告这个名字、才收 {@link METHOD_RELAY_GRANT},客户端读到它之后才把授权发过来。
|
|
298
|
+
* 不配第二会合点的宿主——也就是缺省配置的每一台——公告表里没有这个名字,
|
|
299
|
+
* `relay.grant` 对它仍是 `unknown-method`,名册里也不会因此多出一个块:缺省
|
|
300
|
+
* 宿主的握手与名册与这条通道出现之前逐字相同。
|
|
301
|
+
*
|
|
302
|
+
* 正因为它是**条件**公告,{@link MINOR} 不随它抬格:minor 描述的是这个协议本身,
|
|
303
|
+
* 而缺省宿主在线路上读不到任何新东西(设计冻结在 21)。客户端因此按名字判断而不是
|
|
304
|
+
* 按 minor 判断:读不到这个名字就什么都不发。
|
|
305
|
+
*/
|
|
306
|
+
export const CAP_RELAY_TIER = 'relay.tier.v1'
|
|
307
|
+
|
|
285
308
|
/**
|
|
286
309
|
* Capability a client declares in `hello`'s `cap` array to be answered with
|
|
287
310
|
* byte-level increments instead of the whole roster or the whole board.
|
|
@@ -486,6 +509,7 @@ export const KNOWN_METHODS: ReadonlySet<string> = new Set([
|
|
|
486
509
|
METHOD_USAGE_STATS,
|
|
487
510
|
METHOD_UI_EVENT,
|
|
488
511
|
METHOD_UI_LIST,
|
|
512
|
+
METHOD_RELAY_GRANT,
|
|
489
513
|
])
|
|
490
514
|
|
|
491
515
|
/** Refusal codes the bridge itself raises (DSH failures cross as their own code). */
|
package/src/core/push.ts
CHANGED
|
@@ -51,6 +51,15 @@ export const PUSH_GLOBAL_PER_MINUTE = 30
|
|
|
51
51
|
export const PUSH_WORKSPACE_LIMIT = 512
|
|
52
52
|
/** The only deep-link form this channel emits. */
|
|
53
53
|
export const PUSH_DEEP_LINK_PREFIX = 'whale://session/'
|
|
54
|
+
/**
|
|
55
|
+
* The one category a delivery may name (§28.4).
|
|
56
|
+
*
|
|
57
|
+
* A banner draws a button only where a category it knows is named, so this is the
|
|
58
|
+
* identifier the client registered statically for the two approval answers. It is
|
|
59
|
+
* the client's name rather than this bridge's: the bridge writes it verbatim and
|
|
60
|
+
* holds no second opinion about what a button says.
|
|
61
|
+
*/
|
|
62
|
+
export const PUSH_APPROVAL_CATEGORY = 'dev.dsh.Whale.category.approval'
|
|
54
63
|
|
|
55
64
|
/**
|
|
56
65
|
* The status line each event carries.
|
|
@@ -87,6 +96,13 @@ export interface PushNotification {
|
|
|
87
96
|
readonly aps: {
|
|
88
97
|
readonly alert: { readonly title: string; readonly body: string }
|
|
89
98
|
readonly sound: 'default'
|
|
99
|
+
/**
|
|
100
|
+
* The client's registered category, named only by an approval.
|
|
101
|
+
*
|
|
102
|
+
* Absent for every other event rather than empty: an absent key is a banner
|
|
103
|
+
* with no buttons, and an empty one would be a second way to say it.
|
|
104
|
+
*/
|
|
105
|
+
readonly category?: string
|
|
90
106
|
}
|
|
91
107
|
/** Workspace short name; absent when this bridge cannot resolve one. */
|
|
92
108
|
readonly w?: string
|
|
@@ -198,7 +214,9 @@ export interface PushNotifierOptions {
|
|
|
198
214
|
*
|
|
199
215
|
* Pure, and exported so the shape can be asserted without a sender: the keys
|
|
200
216
|
* are the contract, and the absence of any body text is the property that
|
|
201
|
-
* matters most.
|
|
217
|
+
* matters most. One key is conditional — an approval names the category the
|
|
218
|
+
* client registered, because naming it is the only thing that makes a banner
|
|
219
|
+
* draw a button, and every other event omits it so a banner stays buttonless.
|
|
202
220
|
* @param event - what happened.
|
|
203
221
|
* @param sessionId - the session it happened to.
|
|
204
222
|
* @param labels - the name and workspace short name, when the bridge holds them.
|
|
@@ -210,6 +228,7 @@ export function buildPushNotification(event: PushEvent, sessionId: string, label
|
|
|
210
228
|
aps: {
|
|
211
229
|
alert: { title: named ? labels.title as string : PUSH_BODY[event], body: PUSH_BODY[event] },
|
|
212
230
|
sound: 'default',
|
|
231
|
+
...(event === 'approval' ? { category: PUSH_APPROVAL_CATEGORY } : {}),
|
|
213
232
|
},
|
|
214
233
|
...(labels.workspace === undefined || labels.workspace === '' ? {} : { w: labels.workspace }),
|
|
215
234
|
s: sessionId,
|
|
@@ -30,6 +30,16 @@
|
|
|
30
30
|
*
|
|
31
31
|
* Frames mirror `market/worker/src/relay-bridge.js`: control frames are JSON
|
|
32
32
|
* text, payload frames are `[kind:u8][streamId:u32be][payload]`.
|
|
33
|
+
*
|
|
34
|
+
* Flow control runs one way only, object to connector. A pause closes the
|
|
35
|
+
* object's window on one stream: this half stops sending that stream's payload
|
|
36
|
+
* frames and stops reading the upstream (a response body, a WebSocket socket),
|
|
37
|
+
* so the backlog waits in the kernel instead of in this process. A resume opens
|
|
38
|
+
* it again. A stream being abandoned arrives as close -- the frame this contract
|
|
39
|
+
* already used for a phone cancel -- and cancel is accepted as the same thing,
|
|
40
|
+
* because that is the name the frozen contract gives it. An object too old to
|
|
41
|
+
* send any of them leaves this half exactly as it was, and a frame this half has
|
|
42
|
+
* never heard of is ignored rather than answered.
|
|
33
43
|
*/
|
|
34
44
|
|
|
35
45
|
import { randomBytes } from 'node:crypto'
|
|
@@ -320,6 +330,11 @@ interface BridgePeer {
|
|
|
320
330
|
close: (code: number, reason: string) => void
|
|
321
331
|
text: (body: string) => void
|
|
322
332
|
binary: (body: Buffer) => void
|
|
333
|
+
/** Stop reading the upstream socket: the object's window on this stream is
|
|
334
|
+
* closed, so the backlog waits there rather than in this process. */
|
|
335
|
+
pause: () => void
|
|
336
|
+
/** Start reading it again. */
|
|
337
|
+
resume: () => void
|
|
323
338
|
}
|
|
324
339
|
|
|
325
340
|
/**
|
|
@@ -333,7 +348,11 @@ export class RelayBridgeConnector {
|
|
|
333
348
|
private stateValue: RelayBridgeState = { state: 'idle' }
|
|
334
349
|
private attempts = 0
|
|
335
350
|
private disposed = false
|
|
351
|
+
/** HTTP streams still uploading: the request the object's frames feed. */
|
|
336
352
|
private readonly requests = new Map<number, http.ClientRequest>()
|
|
353
|
+
/** HTTP streams whose head already arrived: the upstream response body a
|
|
354
|
+
* pause holds back and a stream being abandoned destroys. */
|
|
355
|
+
private readonly responses = new Map<number, http.IncomingMessage>()
|
|
337
356
|
private readonly peers = new Map<number, BridgePeer>()
|
|
338
357
|
|
|
339
358
|
private readonly options: RelayBridgeConnectorOptions
|
|
@@ -478,6 +497,16 @@ export class RelayBridgeConnector {
|
|
|
478
497
|
this.peers.get(id)?.close(typeof frame.code === 'number' ? frame.code : 1000, String(frame.reason ?? ''))
|
|
479
498
|
this.peers.delete(id)
|
|
480
499
|
return
|
|
500
|
+
case 'pause':
|
|
501
|
+
this.pauseStream(id)
|
|
502
|
+
return
|
|
503
|
+
case 'resume':
|
|
504
|
+
this.resumeStream(id)
|
|
505
|
+
return
|
|
506
|
+
// A stream being abandoned under either spelling reaches one release path:
|
|
507
|
+
// close is what this contract already sent for a phone cancel, and cancel
|
|
508
|
+
// is what the frozen frame vocabulary calls the same thing.
|
|
509
|
+
case 'cancel':
|
|
481
510
|
case 'close': {
|
|
482
511
|
const peer = this.peers.get(id)
|
|
483
512
|
if (peer !== undefined) {
|
|
@@ -485,6 +514,11 @@ export class RelayBridgeConnector {
|
|
|
485
514
|
peer.close(1000, String(frame.reason ?? 'closed'))
|
|
486
515
|
return
|
|
487
516
|
}
|
|
517
|
+
const response = this.responses.get(id)
|
|
518
|
+
if (response !== undefined) {
|
|
519
|
+
this.responses.delete(id)
|
|
520
|
+
response.destroy()
|
|
521
|
+
}
|
|
488
522
|
const request = this.requests.get(id)
|
|
489
523
|
if (request !== undefined) {
|
|
490
524
|
this.requests.delete(id)
|
|
@@ -493,9 +527,25 @@ export class RelayBridgeConnector {
|
|
|
493
527
|
return
|
|
494
528
|
}
|
|
495
529
|
default:
|
|
530
|
+
// A frame this build has never heard of: an older half ignores what a
|
|
531
|
+
// newer one adds, so there is nothing here to answer.
|
|
532
|
+
return
|
|
496
533
|
}
|
|
497
534
|
}
|
|
498
535
|
|
|
536
|
+
/** Close the object's window on one stream: a paused response body emits no
|
|
537
|
+
* more data events and a paused socket leaves its bytes in the kernel. */
|
|
538
|
+
private pauseStream(id: number): void {
|
|
539
|
+
this.responses.get(id)?.pause()
|
|
540
|
+
this.peers.get(id)?.pause()
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
/** Reopen that window. */
|
|
544
|
+
private resumeStream(id: number): void {
|
|
545
|
+
this.responses.get(id)?.resume()
|
|
546
|
+
this.peers.get(id)?.resume()
|
|
547
|
+
}
|
|
548
|
+
|
|
499
549
|
/**
|
|
500
550
|
* Answer one bridged stream with 404 without dialing anything: the refusal is
|
|
501
551
|
* complete here, so a non-whitelisted path costs the upstream nothing.
|
|
@@ -536,6 +586,9 @@ export class RelayBridgeConnector {
|
|
|
536
586
|
headers: bridgeUpstreamHeaders(frame.headers, host),
|
|
537
587
|
}, (response: http.IncomingMessage) => {
|
|
538
588
|
this.requests.delete(id)
|
|
589
|
+
// The body is what the object's window pauses and a cancel destroys, so
|
|
590
|
+
// the handle outlives this callback.
|
|
591
|
+
this.responses.set(id, response)
|
|
539
592
|
this.sendText(JSON.stringify({
|
|
540
593
|
t: 'res',
|
|
541
594
|
id,
|
|
@@ -544,8 +597,15 @@ export class RelayBridgeConnector {
|
|
|
544
597
|
headers: rawHeaderPairs(response.rawHeaders),
|
|
545
598
|
}))
|
|
546
599
|
response.on('data', (chunk: Buffer) => { this.sendChunk(encodeChunk(HTTP_BODY, id, chunk)) })
|
|
547
|
-
response.on('
|
|
548
|
-
response.on('
|
|
600
|
+
response.on('close', () => { this.responses.delete(id) })
|
|
601
|
+
response.on('end', () => {
|
|
602
|
+
this.responses.delete(id)
|
|
603
|
+
this.sendText(JSON.stringify({ t: 'fin', id }))
|
|
604
|
+
})
|
|
605
|
+
response.on('error', (error: Error) => {
|
|
606
|
+
this.responses.delete(id)
|
|
607
|
+
this.sendText(JSON.stringify({ t: 'fail', id, message: error.message }))
|
|
608
|
+
})
|
|
549
609
|
})
|
|
550
610
|
request.on('error', (error: Error) => {
|
|
551
611
|
this.requests.delete(id)
|
|
@@ -613,6 +673,8 @@ export class RelayBridgeConnector {
|
|
|
613
673
|
binary: (body: Buffer) => {
|
|
614
674
|
if (!peer.closed) dialed.socket.write(encodeBridgeFrame(0x2, body))
|
|
615
675
|
},
|
|
676
|
+
pause: () => { dialed.socket.pause() },
|
|
677
|
+
resume: () => { dialed.socket.resume() },
|
|
616
678
|
}
|
|
617
679
|
const parse = createBridgeFrameParser((incoming) => {
|
|
618
680
|
if (incoming.opcode === 0x1) {
|
|
@@ -682,6 +744,10 @@ export class RelayBridgeConnector {
|
|
|
682
744
|
|
|
683
745
|
/** Drop every stream this socket carried: the object re-opens them. */
|
|
684
746
|
private teardown(): void {
|
|
747
|
+
for (const [id, response] of this.responses) {
|
|
748
|
+
this.responses.delete(id)
|
|
749
|
+
response.destroy()
|
|
750
|
+
}
|
|
685
751
|
for (const [id, request] of this.requests) {
|
|
686
752
|
this.requests.delete(id)
|
|
687
753
|
request.destroy()
|