@linxin666/dsh-remote-bridge 0.4.12 → 0.4.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +45 -8
  3. package/README.zh.md +45 -8
  4. package/lib/client.js +1 -1
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +18031 -373
  7. package/lib/types/core/connection.d.ts +9 -0
  8. package/lib/types/core/devices.d.ts +27 -6
  9. package/lib/types/core/liveactivity.d.ts +7 -0
  10. package/lib/types/core/model-efforts.d.ts +83 -0
  11. package/lib/types/core/protocol.d.ts +2 -0
  12. package/lib/types/core/push.d.ts +51 -2
  13. package/lib/types/host/firewall.d.ts +74 -0
  14. package/lib/types/host/host-bind-capability.d.ts +90 -0
  15. package/lib/types/host/ingress-gate.d.ts +59 -0
  16. package/lib/types/host/ingress-sync.d.ts +429 -0
  17. package/lib/types/host/lan-bind-plan.d.ts +96 -0
  18. package/lib/types/host/lan-bind.d.ts +106 -0
  19. package/lib/types/host/lan-forward.d.ts +112 -0
  20. package/lib/types/host/lan.d.ts +61 -0
  21. package/lib/types/host/pair-origin.d.ts +34 -19
  22. package/lib/types/host/relay-bridge-connector.d.ts +215 -0
  23. package/lib/types/host/relay-connector.d.ts +152 -0
  24. package/lib/types/host/relay-control.d.ts +124 -0
  25. package/lib/types/host/relay-registry.d.ts +114 -0
  26. package/lib/types/host/relay.d.ts +170 -0
  27. package/lib/types/host/routes.d.ts +24 -1
  28. package/lib/types/host/tunnel-orphan.d.ts +145 -0
  29. package/lib/types/host/tunnel-plan.d.ts +41 -0
  30. package/lib/types/host/tunnel.d.ts +289 -0
  31. package/lib/types/index.d.ts +426 -1
  32. package/package.json +4 -2
  33. package/src/client/panel.module.css +16 -1
  34. package/src/core/connection.ts +206 -11
  35. package/src/core/devices.ts +31 -6
  36. package/src/core/hub.ts +17 -5
  37. package/src/core/liveactivity.ts +16 -2
  38. package/src/core/model-efforts.ts +223 -0
  39. package/src/core/protocol.ts +3 -0
  40. package/src/core/push.ts +70 -4
  41. package/src/host/firewall.ts +230 -0
  42. package/src/host/host-bind-capability.ts +249 -0
  43. package/src/host/ingress-gate.ts +203 -0
  44. package/src/host/ingress-sync.ts +1074 -0
  45. package/src/host/lan-bind-plan.ts +134 -0
  46. package/src/host/lan-bind.ts +250 -0
  47. package/src/host/lan-forward.ts +321 -0
  48. package/src/host/lan.ts +142 -0
  49. package/src/host/pair-origin.ts +44 -38
  50. package/src/host/relay-bridge-connector.ts +783 -0
  51. package/src/host/relay-connector.ts +317 -0
  52. package/src/host/relay-control.ts +224 -0
  53. package/src/host/relay-registry.ts +263 -0
  54. package/src/host/relay.ts +294 -0
  55. package/src/host/routes.ts +47 -3
  56. package/src/host/tunnel-orphan.ts +325 -0
  57. package/src/host/tunnel-plan.ts +58 -0
  58. package/src/host/tunnel.ts +688 -0
  59. package/src/index.ts +1280 -22
@@ -0,0 +1,263 @@
1
+ /**
2
+ * Relay registry client: a stable `https://<id>.dsh-market.com` origin in
3
+ * front of the plugin-managed quick tunnel, so a paired phone keeps one
4
+ * bookmark and one cookie context across `dsh web` restarts.
5
+ *
6
+ * The plugin mints an id + secret on first run and persists them per profile
7
+ * under `$DSH_HOME/remote-web-ui-registry/`; every tunnel (re)start
8
+ * re-registers the current quick URL with the market worker. Registration is
9
+ * best-effort: a registry outage never blocks the tunnel — the QR just falls
10
+ * back to the raw quick URL for that session (the pre-relay behavior).
11
+ *
12
+ * Not to be confused with `./relay.ts`, the bridge's own APNs push sender: the
13
+ * relay in this file is the Cloudflare-side one that fronts the tunnel. The
14
+ * persisted directory and file names below keep their historical spelling on
15
+ * purpose, so an existing profile keeps the identity it already paired with.
16
+ */
17
+
18
+ import { randomBytes } from 'node:crypto'
19
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
20
+ import { dirname, join } from 'node:path'
21
+ import { dshHome } from './dsh-home.ts'
22
+
23
+ /** The market worker's registration endpoints (dsh-market.com edge API). */
24
+ export const RELAY_REGISTER_URL = 'https://dsh-market.com/api/relay/register'
25
+ export const RELAY_UNREGISTER_URL = 'https://dsh-market.com/api/relay/unregister'
26
+ /**
27
+ * The public origin template: one stable single-label subdomain per
28
+ * registration id. Single label on purpose — Universal SSL covers exactly
29
+ * one subdomain level, so a two-level hostname would get no certificate.
30
+ */
31
+ export const RELAY_BASE_SUFFIX = '.dsh-market.com'
32
+
33
+ export const RELAY_ID_RE = /^[a-z0-9]{16}$/
34
+ export const RELAY_SECRET_RE = /^[A-Za-z0-9_-]{43}$/
35
+
36
+ /** Persisted per-profile relay identity. */
37
+ export interface RelayIdentity {
38
+ id: string
39
+ secret: string
40
+ /**
41
+ * True only for an identity minted in this process that has never been
42
+ * accepted by the registry: the first register carries `new_secret` so
43
+ * the endpoint may create the row; refreshes authenticate with `secret`
44
+ * alone and must not re-claim an id that already exists.
45
+ */
46
+ fresh?: boolean
47
+ }
48
+
49
+ /** The observable relay lifecycle the settings card renders. */
50
+ export type RelayState =
51
+ | { state: 'off' }
52
+ | { state: 'registering' }
53
+ | { state: 'running'; url: string }
54
+ | { state: 'failed'; error: string }
55
+
56
+ /** Registry storage layout: one file per profile under the relay directory. */
57
+ export function relayIdentityFile(profile: string, home: string = dshHome()): string {
58
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(profile)) {
59
+ throw new Error(`relay registry: profile ${JSON.stringify(profile)} is not a safe path segment`)
60
+ }
61
+ return join(home, 'remote-web-ui-registry', `${profile}.json`)
62
+ }
63
+
64
+ /** Generate one identity pair (id: 8-byte hex slug; secret: 32-byte base64url). */
65
+ export function generateRelayIdentity(random: (size: number) => Buffer = randomBytes): RelayIdentity {
66
+ return {
67
+ id: random(8).toString('hex'),
68
+ secret: random(32).toString('base64url'),
69
+ fresh: true,
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Load (or lazily mint) the per-profile relay identity. The file is written
75
+ * owner-only on first mint; a corrupt file is reminted (the phone then
76
+ * re-pairs once — the same cost as losing the devices file).
77
+ */
78
+ export function loadRelayIdentity(profile: string, home: string = dshHome(), random: (size: number) => Buffer = randomBytes): RelayIdentity {
79
+ const file = relayIdentityFile(profile, home)
80
+ try {
81
+ if (existsSync(file)) {
82
+ const parsed = JSON.parse(readFileSync(file, 'utf8')) as Partial<RelayIdentity>
83
+ if (typeof parsed.id === 'string' && RELAY_ID_RE.test(parsed.id)
84
+ && typeof parsed.secret === 'string' && RELAY_SECRET_RE.test(parsed.secret)) {
85
+ // A persisted identity has certainly been registered before.
86
+ return { id: parsed.id, secret: parsed.secret }
87
+ }
88
+ console.warn(`relay registry: ${file} is malformed — reminting the identity (paired devices must scan the QR once more)`)
89
+ }
90
+ } catch (error) {
91
+ console.warn(`relay registry: could not read ${file} (${error instanceof Error ? error.message : String(error)}) — reminting`)
92
+ }
93
+ const identity = generateRelayIdentity(random)
94
+ mkdirSync(dirname(file), { recursive: true })
95
+ writeFileSync(file, JSON.stringify({ id: identity.id, secret: identity.secret }, null, 2) + '\n', { mode: 0o600 })
96
+ return identity
97
+ }
98
+
99
+ /**
100
+ * 读一份**已经存在**的身份,绝不生成。
101
+ *
102
+ * 与 {@link loadRelayIdentity} 的唯一区别就在这里:文件不在、或读不出合法的
103
+ * id/secret 时返回 undefined,既不 mint 也不写盘,目录也不会被创建。关掉 relay 的
104
+ * 挂载路径靠它收掉上一次挂载留下的注册行与租约——挂载本身不是「申请一份新身份」的
105
+ * 理由,一个从没配过 relay 的宿主不该因为挂载就在 $DSH_HOME 里落下一份密钥文件。
106
+ * 坏文件同样原样留在盘上:等 relay 真的打开时由 loadRelayIdentity 按既有语义重新生成。
107
+ * @param profile - 受管 profile。
108
+ * @param home - DSH home(测试注入)。
109
+ * @returns 已存在的身份,或 undefined(没有可用身份,且什么都没写)。
110
+ */
111
+ export function readExistingRelayIdentity(profile: string, home: string = dshHome()): RelayIdentity | undefined {
112
+ const file = relayIdentityFile(profile, home)
113
+ try {
114
+ if (!existsSync(file)) return undefined
115
+ const parsed = JSON.parse(readFileSync(file, 'utf8')) as Partial<RelayIdentity>
116
+ if (typeof parsed.id !== 'string' || !RELAY_ID_RE.test(parsed.id)) return undefined
117
+ if (typeof parsed.secret !== 'string' || !RELAY_SECRET_RE.test(parsed.secret)) return undefined
118
+ return { id: parsed.id, secret: parsed.secret }
119
+ } catch {
120
+ // 读不出来就是没有可用身份:这条路径什么都不做,也不写盘。
121
+ return undefined
122
+ }
123
+ }
124
+
125
+ /** Build the registration request body for one identity + tunnel target. */
126
+ function registrationBody(identity: RelayIdentity, target: string): string {
127
+ return JSON.stringify({
128
+ id: identity.id,
129
+ secret: identity.secret,
130
+ new_secret: identity.fresh === true ? identity.secret : undefined,
131
+ target,
132
+ })
133
+ }
134
+
135
+ /** Best-effort removal of the mapping (used on disable; errors are swallowed). */
136
+ export async function unregisterRelay(
137
+ identity: RelayIdentity,
138
+ endpoint: string = RELAY_UNREGISTER_URL,
139
+ fetchFn: typeof fetch = fetch,
140
+ ): Promise<void> {
141
+ await fetchFn(endpoint, {
142
+ method: 'POST',
143
+ headers: { 'content-type': 'application/json' },
144
+ body: JSON.stringify({ id: identity.id, secret: identity.secret }),
145
+ })
146
+ }
147
+
148
+ /**
149
+ * The stable relay base for one identity — the origin the QR and the phone
150
+ * bookmark use while (or after) the registration is accepted.
151
+ */
152
+ export function relayBaseOf(identity: RelayIdentity): string {
153
+ return `https://${identity.id}${RELAY_BASE_SUFFIX}`
154
+ }
155
+
156
+ /**
157
+ * Registration loop with capped exponential backoff. Re-registration happens
158
+ * on every tunnel start (the quick URL can change after a crash-restart);
159
+ * failures retry with backoff and surface the last error to the card.
160
+ */
161
+ export class RelayRegistrar {
162
+ private timer: NodeJS.Timeout | undefined
163
+ private attempts = 0
164
+ private lastError: string | undefined
165
+ private disposed = false
166
+
167
+ constructor(
168
+ private readonly identity: RelayIdentity,
169
+ private readonly setState: (state: RelayState) => void,
170
+ private readonly options: {
171
+ fetchFn?: typeof fetch
172
+ registerUrl?: string
173
+ unregisterUrl?: string
174
+ baseDelayMs?: number
175
+ maxDelayMs?: number
176
+ timerFn?: (fn: () => void, ms: number) => NodeJS.Timeout
177
+ } = {},
178
+ ) {}
179
+
180
+ /** The stable relay base for the QR while registered. */
181
+ get baseUrl(): string {
182
+ return relayBaseOf(this.identity)
183
+ }
184
+
185
+ /** The last registration failure detail (undefined while healthy). */
186
+ get error(): string | undefined {
187
+ return this.lastError
188
+ }
189
+
190
+ /** Push one tunnel target; resolves the stable base once accepted. */
191
+ async announce(target: string): Promise<string | undefined> {
192
+ // A disposed registrar stays disposed: a pending retry timer must not
193
+ // resurrect it (re-enabling creates a fresh registrar instead).
194
+ if (this.disposed) return undefined
195
+ if (this.timer !== undefined) {
196
+ clearTimeout(this.timer)
197
+ this.timer = undefined
198
+ }
199
+ this.setState({ state: 'registering' })
200
+ try {
201
+ const fetchFn = this.options.fetchFn ?? fetch
202
+ const response = await fetchFn(this.options.registerUrl ?? RELAY_REGISTER_URL, {
203
+ method: 'PUT',
204
+ headers: { 'content-type': 'application/json' },
205
+ body: registrationBody(this.identity, target),
206
+ })
207
+ if (!response.ok) {
208
+ const detail = await response.json().catch(() => undefined)
209
+ const error = detail && typeof detail.error === 'string' ? detail.error : `HTTP ${String(response.status)}`
210
+ throw new Error(error)
211
+ }
212
+ // The row exists now: never claim a fresh id twice.
213
+ this.identity.fresh = false
214
+ this.attempts = 0
215
+ this.lastError = undefined
216
+ this.setState({ state: 'running', url: this.baseUrl })
217
+ return this.baseUrl
218
+ } catch (error) {
219
+ this.lastError = error instanceof Error ? error.message : String(error)
220
+ if (this.lastError === 'invalid-params' && this.identity.fresh !== true) {
221
+ // The registry lost the row (a D1 restore or manual wipe): re-claim
222
+ // the id with a fresh claim on the next retry. A 403 auth-failed
223
+ // means the id is owned by another secret and stays failed.
224
+ this.identity.fresh = true
225
+ }
226
+ this.setState({ state: 'failed', error: this.lastError })
227
+ this.scheduleRetry(target)
228
+ return undefined
229
+ }
230
+ }
231
+
232
+ /** Best-effort removal of the registry row (the relay toggle turned off). */
233
+ async unregister(): Promise<void> {
234
+ await unregisterRelay(this.identity, this.options.unregisterUrl, this.options.fetchFn)
235
+ }
236
+
237
+ private scheduleRetry(target: string): void {
238
+ if (this.disposed) return
239
+ const base = this.options.baseDelayMs ?? 5_000
240
+ const max = this.options.maxDelayMs ?? 60_000
241
+ const delay = Math.min(base * 2 ** this.attempts, max)
242
+ this.attempts += 1
243
+ const timerFn = this.options.timerFn ?? ((fn: () => void, ms: number) => {
244
+ const timer = setTimeout(fn, ms)
245
+ timer.unref?.()
246
+ return timer
247
+ })
248
+ this.timer = timerFn(() => {
249
+ this.timer = undefined
250
+ void this.announce(target)
251
+ }, delay)
252
+ }
253
+
254
+ /** Stop retrying and clear the card state (tunnel stopped or disabled). */
255
+ dispose(): void {
256
+ this.disposed = true
257
+ if (this.timer !== undefined) {
258
+ clearTimeout(this.timer)
259
+ this.timer = undefined
260
+ }
261
+ this.setState({ state: 'off' })
262
+ }
263
+ }
@@ -0,0 +1,294 @@
1
+ /**
2
+ * The hosted relay this bridge hands a notification to when it holds no Apple key.
3
+ *
4
+ * §28's channel needs an Apple signing key, and a distributed App cannot get one
5
+ * onto every user's machine: the key would have to be shipped with the App's
6
+ * operator, which is the one thing a store release may not do. So the same event
7
+ * can be delivered two ways, and this file is the second one — one HTTPS POST to
8
+ * a service that signs with a key no deployment holds.
9
+ *
10
+ * Four rules, each of them borrowed from the direct path beside it:
11
+ *
12
+ * - the bridge sends the EVENT, not the state: `{event, sessionId, title, workspace}`
13
+ * for a notification and `{event: 'live-activity', sessionId, activityId,
14
+ * activityEvent, contentState, dismiss?}` for a card. It no longer decides the APNs
15
+ * headers, the bundle, the environment or the alert bodies — the service does,
16
+ * from the registration the App made directly with it;
17
+ * - a failure is a return value, never a rejection and never a retry: both callers
18
+ * sit on frame paths that must not learn about the network at all (§28.5);
19
+ * - the relay token is the phone's credential, scoped to this pairing's
20
+ * fingerprint. It is read off the roster row and put in one header; it is never
21
+ * logged, echoed in a frame, or written anywhere but that row;
22
+ * - the route is exclusive with the local key rather than a fallback chain. A
23
+ * machine that holds a key keeps signing for itself, so a developer's delivery
24
+ * never travels through the service and a hosted deployment never silently
25
+ * switches routes halfway through a session.
26
+ * @module dsh-remote-bridge/host/relay
27
+ */
28
+
29
+ import type { LiveActivityAddress, LiveActivityNotification, LiveActivitySender } from '../core/liveactivity.ts'
30
+ import type { PushAddress, PushNotification, PushRoute, PushSendResult, PushSender } from '../core/push.ts'
31
+
32
+ /**
33
+ * Where the hosted relay lives by default.
34
+ *
35
+ * The account service the App already signs into: one deployment, one hostname, so
36
+ * an operator with no relay of their own configures nothing at all.
37
+ */
38
+ export const RELAY_DEFAULT_URL = 'https://account.dsh-market.com'
39
+ /** The environment variable that moves the relay to another deployment. */
40
+ export const RELAY_ENV = { url: 'DSH_REMOTE_BRIDGE_RELAY_URL' } as const
41
+ /** The one path a delivery is posted to. */
42
+ export const RELAY_PATH = '/v1/push/relay'
43
+ /** How long one delivery may take before it is abandoned. */
44
+ export const RELAY_TIMEOUT_MS = 10_000
45
+
46
+ /**
47
+ * Read the relay's base address.
48
+ * @param env - the environment to read; defaults to this process's.
49
+ * @returns the trimmed base with no trailing slash, or {@link RELAY_DEFAULT_URL}.
50
+ */
51
+ export function relayUrlFromEnv(env: NodeJS.ProcessEnv = process.env): string {
52
+ const configured = env[RELAY_ENV.url]?.trim()
53
+ if (configured === undefined || configured === '') return RELAY_DEFAULT_URL
54
+ return configured.endsWith('/') ? configured.slice(0, -1) : configured
55
+ }
56
+
57
+ /** The notification body the relay accepts (contract v1, frozen). */
58
+ export interface RelayNotificationRequest {
59
+ readonly event: PushNotification['st']
60
+ readonly sessionId: string
61
+ /** The session's own name; the service substitutes its fixed line when absent. */
62
+ readonly title?: string
63
+ /** The workspace's short name, which is a directory's basename and not a path. */
64
+ readonly workspace?: string
65
+ }
66
+
67
+ /** The Live Activity body the relay accepts (contract v1, frozen). */
68
+ export interface RelayLiveActivityRequest {
69
+ readonly event: 'live-activity'
70
+ readonly sessionId: string
71
+ readonly activityId: string
72
+ readonly activityEvent: LiveActivityNotification['aps']['event']
73
+ readonly contentState: LiveActivityNotification['aps']['content-state']
74
+ /**
75
+ * Whether the card must go the moment this delivery lands, rather than at its
76
+ * `stale-date`. Only ever `true`: the key is absent when the card stays, because
77
+ * a `false` would be a second way to say the same thing and an older service
78
+ * would have to learn it. The dismissal date itself is the service's to write —
79
+ * it is the one that knows when the delivery landed (§29.3).
80
+ */
81
+ readonly dismiss?: boolean
82
+ }
83
+
84
+ /**
85
+ * The notification one delivery becomes.
86
+ *
87
+ * Pure, and exported so the body can be asserted without a network. What crosses is
88
+ * exactly what §28.4 already allows on a lock screen — the event, the session id,
89
+ * the session's name and the workspace's short name — and nothing else: no message,
90
+ * no tool output, no path, no question body.
91
+ * @param notification - the payload the notifier built for the direct path.
92
+ * @returns the body to POST.
93
+ */
94
+ export function buildRelayNotification(notification: PushNotification): RelayNotificationRequest {
95
+ return {
96
+ event: notification.st,
97
+ sessionId: notification.s,
98
+ // The notifier already decided what may name this event — the session's own
99
+ // title, or the fixed status line when it holds none — so passing it through
100
+ // keeps one answer to "what may a notification say" for both routes.
101
+ title: notification.aps.alert.title,
102
+ ...(notification.w === undefined || notification.w === '' ? {} : { workspace: notification.w }),
103
+ }
104
+ }
105
+
106
+ /**
107
+ * The Live Activity body one delivery becomes.
108
+ *
109
+ * The card's content state crosses verbatim: it is the App's own
110
+ * `SessionActivityState` (§29.3), already built by `core/liveactivity.ts` with its
111
+ * frozen key set and Apple-reference timestamps, and rebuilding it here would be a
112
+ * second answer to the same encoding question.
113
+ * @param target - the card being pushed to.
114
+ * @param notification - the payload the notifier built for the direct path.
115
+ * @returns the body to POST, or undefined when the card names no session.
116
+ */
117
+ export function buildRelayLiveActivity(
118
+ target: LiveActivityAddress,
119
+ notification: LiveActivityNotification,
120
+ ): RelayLiveActivityRequest | undefined {
121
+ if (target.sessionId === undefined) return undefined
122
+ return {
123
+ event: 'live-activity',
124
+ sessionId: target.sessionId,
125
+ activityId: target.activityId,
126
+ activityEvent: notification.aps.event,
127
+ contentState: notification.aps['content-state'],
128
+ // The direct payload already decided this: it writes `dismissal-date` only for an
129
+ // `end` whose session left the roster. Reading that decision back off the payload
130
+ // keeps one answer to "does this card go now" for both routes, and the date is
131
+ // left to the service, which stamps its own delivery moment.
132
+ ...(notification.aps['dismissal-date'] === undefined ? {} : { dismiss: true }),
133
+ }
134
+ }
135
+
136
+ /** The 200 body the relay answers with (contract v1, frozen). */
137
+ export interface RelayAnswer {
138
+ readonly ok?: boolean
139
+ /** How many devices took the delivery. */
140
+ readonly delivered?: number
141
+ /** How many registrations the relay judged dead and cleaned up. */
142
+ readonly dead?: number
143
+ }
144
+
145
+ /** The one request shape this file makes, with the answer narrowed to what it reads. */
146
+ export type RelayFetch = (
147
+ url: string,
148
+ init: {
149
+ readonly method: string
150
+ readonly headers: Readonly<Record<string, string>>
151
+ readonly body: string
152
+ readonly signal: AbortSignal
153
+ },
154
+ ) => Promise<{ readonly status: number; text(): Promise<string> }>
155
+
156
+ export interface RelaySenderOptions {
157
+ /** The relay's base address, from {@link relayUrlFromEnv}. */
158
+ readonly url: string
159
+ /** The HTTP client; the global `fetch` by default, injectable so failures need no network. */
160
+ readonly fetch?: RelayFetch
161
+ readonly timeoutMs?: number
162
+ }
163
+
164
+ /**
165
+ * The relay half of the push channel.
166
+ *
167
+ * Every method resolves: a delivery that failed is a {@link PushSendResult} with
168
+ * `ok: false`, never a rejection, because both callers sit on frame paths that must
169
+ * not learn about the network at all. Nothing is retried — an alert that could not
170
+ * be delivered is one line in the log, and the next event is the next attempt.
171
+ */
172
+ export class RelaySender implements PushSender, LiveActivitySender {
173
+ readonly #url: string
174
+ readonly #fetch: RelayFetch
175
+ readonly #timeoutMs: number
176
+
177
+ constructor(options: RelaySenderOptions) {
178
+ this.#url = options.url
179
+ this.#fetch = options.fetch ?? ((url, init) => globalThis.fetch(url, init))
180
+ this.#timeoutMs = options.timeoutMs ?? RELAY_TIMEOUT_MS
181
+ }
182
+
183
+ /** Deliver one notification, or report why it did not arrive. */
184
+ async send(target: PushAddress, notification: PushNotification): Promise<PushSendResult> {
185
+ if (target.relayToken === undefined || target.relayToken === '') {
186
+ return { ok: false, reason: 'this device row holds no relay token' }
187
+ }
188
+ return await this.#post(target.relayToken, buildRelayNotification(notification))
189
+ }
190
+
191
+ /** Deliver one Live Activity push, or report why it did not arrive. */
192
+ async sendLiveActivity(target: LiveActivityAddress, notification: LiveActivityNotification): Promise<PushSendResult> {
193
+ if (target.relayToken === undefined || target.relayToken === '') {
194
+ return { ok: false, reason: 'this device row holds no relay token' }
195
+ }
196
+ const body = buildRelayLiveActivity(target, notification)
197
+ if (body === undefined) return { ok: false, reason: 'this card names no session, so the relay has nothing to address' }
198
+ return await this.#post(target.relayToken, body)
199
+ }
200
+
201
+ /**
202
+ * POST one already-built body.
203
+ *
204
+ * The relay answers 200 for every outcome, including a delivery Apple refused:
205
+ * `delivered` counts what landed and `dead` counts the tokens it retired. A
206
+ * delivery that landed on nothing is therefore reported as the failure it is,
207
+ * with `dead` telling the roster to forget a registration that can never work
208
+ * again.
209
+ * @param token - the relay credential of the device this is addressed to.
210
+ * @param body - the JSON body to send.
211
+ * @returns whether anything took it, and what the relay said when nothing did.
212
+ */
213
+ async #post(token: string, body: RelayNotificationRequest | RelayLiveActivityRequest): Promise<PushSendResult> {
214
+ let status: number
215
+ let text: string
216
+ try {
217
+ const response = await this.#fetch(`${this.#url}${RELAY_PATH}`, {
218
+ method: 'POST',
219
+ headers: {
220
+ authorization: `Bearer ${token}`,
221
+ 'content-type': 'application/json',
222
+ accept: 'application/json',
223
+ },
224
+ body: JSON.stringify(body),
225
+ signal: AbortSignal.timeout(this.#timeoutMs),
226
+ })
227
+ status = response.status
228
+ text = await response.text()
229
+ } catch (error) {
230
+ // A connection that never answered, a timeout, a DNS failure and a body the
231
+ // proxy rewrote all end here, as the same one line.
232
+ return { ok: false, reason: `relay request failed: ${String(error)}` }
233
+ }
234
+ if (status === 401) return { ok: false, status, reason: 'unauthorized' }
235
+ if (status !== 200) return { ok: false, status, reason: `relay answered ${String(status)}` }
236
+ const answer = parseAnswer(text)
237
+ if (answer === undefined || answer.ok !== true) return { ok: false, status, reason: 'the relay answered no usable result' }
238
+ if ((answer.delivered ?? 0) > 0) return { ok: true, status }
239
+ if ((answer.dead ?? 0) > 0) return { ok: false, status, dead: true, reason: 'the relay retired this registration' }
240
+ return { ok: false, status, reason: 'the relay delivered to no device' }
241
+ }
242
+ }
243
+
244
+ /** @returns the parsed answer, or undefined when the body is not one. */
245
+ function parseAnswer(text: string): RelayAnswer | undefined {
246
+ try {
247
+ const parsed: unknown = JSON.parse(text)
248
+ if (typeof parsed !== 'object' || parsed === null) return undefined
249
+ return parsed as RelayAnswer
250
+ } catch {
251
+ return undefined
252
+ }
253
+ }
254
+
255
+ /**
256
+ * Which road this bridge stands on, given the two credentials it could hold.
257
+ *
258
+ * A local key wins over a relay token, deliberately: the machine that can sign for
259
+ * itself must not route a developer's events through the hosted service, and the
260
+ * two routes never run side by side for one event.
261
+ * @param localKey - whether this machine holds a complete APNs credential.
262
+ * @param relayArmed - whether some paired row holds a relay token.
263
+ * @returns the route the channel is on.
264
+ */
265
+ export function pushRouteOf(localKey: boolean, relayArmed: boolean): PushRoute {
266
+ if (localKey) return 'direct'
267
+ return relayArmed ? 'relay' : 'off'
268
+ }
269
+
270
+ /** What the mount log needs to know to say where this bridge stands. */
271
+ export interface PushChannelDescription {
272
+ readonly route: PushRoute
273
+ /** The key id of the local credential, when the route is `direct`. */
274
+ readonly keyId?: string
275
+ /** The team that key belongs to, when the route is `direct`. */
276
+ readonly teamId?: string
277
+ /** The relay's base address, when the route is `relay`. */
278
+ readonly relayUrl?: string
279
+ }
280
+
281
+ /**
282
+ * The one line the mount log says about the push channel.
283
+ *
284
+ * Three routes, three lines, and the line names the credential each one reads: an
285
+ * operator reading a log has to be able to tell a bridge signing for itself from
286
+ * one asking a service to, without opening any file.
287
+ * @param description - the route and the parts of it worth naming.
288
+ * @returns the line to log.
289
+ */
290
+ export function pushChannelLine(description: PushChannelDescription): string {
291
+ if (description.route === 'direct') return `push: direct (APNs key ${description.keyId ?? '?'} of team ${description.teamId ?? '?'})`
292
+ if (description.route === 'relay') return `push: relay (${description.relayUrl ?? RELAY_DEFAULT_URL})`
293
+ return `push: off (no APNs key on this machine and no paired device holds a relay token)`
294
+ }
@@ -19,7 +19,14 @@ import { discoverPairOrigin, type PairOriginFacts } from './pair-origin.ts'
19
19
  export interface PairTokenRouteDeps {
20
20
  readonly pairing: PairingService
21
21
  readonly log: (message: string) => void
22
- /** Origin discovery seam; defaults to {@link discoverPairOrigin}. */
22
+ /**
23
+ * 桥自己此刻的公网入口(relay 租约的 hostname 或隧道的 running URL),由接线方
24
+ * 注入:本模块不认识隧道与租约,只按顺序问地址。返回实时快照,不缓存。
25
+ */
26
+ readonly realtime?: () => string | undefined
27
+ /** 无公网时的局域网兜底:本机地址与 webServer 端口。 */
28
+ readonly lan?: () => { address: string; port: number } | undefined
29
+ /** Origin discovery seam; defaults to {@link discoverPairOrigin} over the two seams above. */
23
30
  readonly pairOrigin?: () => PairOriginFacts | undefined
24
31
  }
25
32
 
@@ -35,6 +42,33 @@ function writeJson(res: ServerResponse, status: number, body: unknown): void {
35
42
  res.end(text)
36
43
  }
37
44
 
45
+ /** The schemes one discovered origin can carry, and the socket scheme it dials. */
46
+ const DIAL_SCHEME: Readonly<Record<string, string>> = { 'https://': 'wss://', 'http://': 'ws://' }
47
+
48
+ /**
49
+ * The WebSocket URL a phone dials for one one-shot ticket.
50
+ *
51
+ * `origin` names where this host is reachable (`https://<id>.dsh-market.com`,
52
+ * `http://192.168.1.5:3080`), but the handshake this URL opens is a WebSocket
53
+ * one: the scheme follows the transport, so https becomes wss and http becomes
54
+ * ws. Keeping the origin's own scheme would hand the client an HTTP URL and ask
55
+ * it to dial a socket with it.
56
+ * @param origin - the discovered origin, with or without the scheme.
57
+ * @param token - the one-shot ticket to carry in the query.
58
+ * @returns the URL the pairing QR encodes.
59
+ */
60
+ export function pairingDialUrlOf(origin: string, token: string): string {
61
+ const base = origin.replace(/\/+$/, '')
62
+ let dial = base
63
+ for (const [scheme, socket] of Object.entries(DIAL_SCHEME)) {
64
+ if (base.startsWith(scheme)) {
65
+ dial = socket + base.slice(scheme.length)
66
+ break
67
+ }
68
+ }
69
+ return dial + WS_PATH + '?token=' + token
70
+ }
71
+
38
72
  /**
39
73
  * Build the handler for `GET /remote-bridge/pair/token`.
40
74
  * @param deps - the pairing service that mints the token, plus the Host log.
@@ -62,8 +96,18 @@ export function makePairTokenHandler(deps: PairTokenRouteDeps): WebRoute['handle
62
96
  // The link the PHONE should dial, when this machine knows its own public
63
97
  // origin. `pairingUrl` is what a QR should carry: the iOS client parses
64
98
  // `{token, url}` and adopts the origin from `url`, so one scan sets both.
65
- const discovered = (deps.pairOrigin ?? discoverPairOrigin)()
66
- const pairingUrl = discovered === undefined ? undefined : `${discovered.origin}${WS_PATH}?token=${ticket.value}`
99
+ //
100
+ // The origin comes from the live-first discovery order (pair-origin.ts): this
101
+ // bridge's own relay lease or running tunnel first, then the configured base,
102
+ // then the LAN forwarder while it is listening. The response shape and the
103
+ // field names are unchanged.
104
+ const discovered = (deps.pairOrigin ?? (() => discoverPairOrigin({
105
+ ...(deps.realtime === undefined ? {} : { realtime: deps.realtime }),
106
+ ...(deps.lan === undefined ? {} : { lan: deps.lan }),
107
+ })))()
108
+ const pairingUrl = discovered === undefined
109
+ ? undefined
110
+ : pairingDialUrlOf(discovered.origin, ticket.value)
67
111
  deps.log(
68
112
  pairingUrl === undefined
69
113
  ? `pair a device with ${url}`