@linxin666/dsh-remote-bridge 0.0.0-stage → 0.4.7

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 (69) hide show
  1. package/LICENSE +202 -0
  2. package/README.i18n.yaml +6 -0
  3. package/README.md +243 -2
  4. package/README.zh.md +244 -0
  5. package/cordis.patch.yml +17 -0
  6. package/lib/client.js +1830 -0
  7. package/lib/client.js.map +1 -0
  8. package/lib/index.js +3744 -0
  9. package/lib/types/client/PairEntry.d.ts +16 -0
  10. package/lib/types/client/PairPanel.d.ts +55 -0
  11. package/lib/types/client/icons.d.ts +18 -0
  12. package/lib/types/client/index.d.ts +35 -0
  13. package/lib/types/client/locales.d.ts +42 -0
  14. package/lib/types/client/pair-token.d.ts +73 -0
  15. package/lib/types/client/semantic.d.ts +28 -0
  16. package/lib/types/core/approvals.d.ts +75 -0
  17. package/lib/types/core/connection.d.ts +119 -0
  18. package/lib/types/core/crypto.d.ts +48 -0
  19. package/lib/types/core/devices.d.ts +72 -0
  20. package/lib/types/core/dsh-frames.d.ts +181 -0
  21. package/lib/types/core/envelope.d.ts +98 -0
  22. package/lib/types/core/gateway-errors.d.ts +49 -0
  23. package/lib/types/core/hub.d.ts +101 -0
  24. package/lib/types/core/loopback.d.ts +35 -0
  25. package/lib/types/core/owner-peer.d.ts +49 -0
  26. package/lib/types/core/pairing.d.ts +61 -0
  27. package/lib/types/core/protocol.d.ts +89 -0
  28. package/lib/types/core/questions.d.ts +246 -0
  29. package/lib/types/core/session-meta.d.ts +105 -0
  30. package/lib/types/core/session-permissions.d.ts +134 -0
  31. package/lib/types/core/wire.d.ts +115 -0
  32. package/lib/types/core/ws-frames.d.ts +61 -0
  33. package/lib/types/host/dsh-home.d.ts +16 -0
  34. package/lib/types/host/pair-origin.d.ts +44 -0
  35. package/lib/types/host/routes.d.ts +27 -0
  36. package/lib/types/host/websocket.d.ts +104 -0
  37. package/lib/types/index.d.ts +40 -0
  38. package/package.json +87 -3
  39. package/src/client/PairEntry.tsx +151 -0
  40. package/src/client/PairPanel.tsx +183 -0
  41. package/src/client/icons.tsx +72 -0
  42. package/src/client/index.ts +81 -0
  43. package/src/client/locales.ts +72 -0
  44. package/src/client/pair-token.ts +104 -0
  45. package/src/client/panel.module.css +344 -0
  46. package/src/client/semantic.ts +37 -0
  47. package/src/core/approvals.ts +142 -0
  48. package/src/core/connection.ts +1090 -0
  49. package/src/core/crypto.ts +113 -0
  50. package/src/core/devices.ts +209 -0
  51. package/src/core/dsh-frames.ts +486 -0
  52. package/src/core/envelope.ts +173 -0
  53. package/src/core/gateway-errors.ts +92 -0
  54. package/src/core/hub.ts +238 -0
  55. package/src/core/loopback.ts +60 -0
  56. package/src/core/owner-peer.ts +70 -0
  57. package/src/core/pairing.ts +113 -0
  58. package/src/core/protocol.ts +120 -0
  59. package/src/core/questions.ts +454 -0
  60. package/src/core/session-meta.ts +176 -0
  61. package/src/core/session-permissions.ts +266 -0
  62. package/src/core/wire.ts +155 -0
  63. package/src/core/ws-frames.ts +125 -0
  64. package/src/css-modules.d.ts +6 -0
  65. package/src/host/dsh-home.ts +42 -0
  66. package/src/host/pair-origin.ts +77 -0
  67. package/src/host/routes.ts +85 -0
  68. package/src/host/websocket.ts +325 -0
  69. package/src/index.ts +205 -0
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Bounded retry for the DSH service-activation window.
3
+ *
4
+ * The gateway raises its activation failures as `error.code`, never as an
5
+ * `instanceof` identity, and two generations of code strings coexist: the
6
+ * namespace-qualified `gateway/service-unavailable` and the bare
7
+ * `service-unavailable`. Both are recognized, verbatim from the family's
8
+ * task-board runner, so a provider that is merely slow to activate is retried
9
+ * rather than reported to the phone as a broken deployment.
10
+ * @module dsh-remote-bridge/core/gateway-errors
11
+ */
12
+
13
+ /** Tries one unary call may consume while the target service is activating. */
14
+ export const SERVICE_UNAVAILABLE_ATTEMPTS = 5
15
+ /** Wait between those tries. */
16
+ export const SERVICE_UNAVAILABLE_BACKOFF_MS = 2_000
17
+
18
+ /** Namespace-qualified and bare spellings of the same failure. */
19
+ function codeIsOneOf(error: unknown, bare: string): boolean {
20
+ const code = (error as { code?: unknown } | null | undefined)?.code
21
+ return code === bare || code === `gateway/${bare}`
22
+ }
23
+
24
+ /**
25
+ * Whether a failure means the target service has not finished activating.
26
+ * This is the one failure worth retrying: the same call succeeds moments later.
27
+ */
28
+ export function isServiceUnavailable(error: unknown): boolean {
29
+ return codeIsOneOf(error, 'service-unavailable')
30
+ }
31
+
32
+ /**
33
+ * Whether the running gateway does not serve this endpoint at all (the cohort
34
+ * changed under this plugin). Retrying cannot help; the caller reports it.
35
+ */
36
+ export function isInvocationUnavailable(error: unknown): boolean {
37
+ return codeIsOneOf(error, 'invocation-unavailable')
38
+ }
39
+
40
+ /** Whether the endpoint exists but its strict definition was withdrawn by the running gateway. */
41
+ export function isDefinitionWithdrawn(error: unknown): boolean {
42
+ return codeIsOneOf(error, 'definition-unavailable')
43
+ }
44
+
45
+ /** Whether the call's named arguments did not match the descriptor. */
46
+ export function isArgumentsInvalid(error: unknown): boolean {
47
+ return codeIsOneOf(error, 'arguments-invalid')
48
+ }
49
+
50
+ function delay(ms: number): Promise<void> {
51
+ return new Promise(resolve => { setTimeout(resolve, ms) })
52
+ }
53
+
54
+ /** One-line text of a failure, for a decideable reason the phone can show. */
55
+ export function failureText(error: unknown): string {
56
+ const message = error instanceof Error ? error.message : String(error)
57
+ return message.length > 300 ? `${message.slice(0, 297)}...` : message
58
+ }
59
+
60
+ /**
61
+ * The failure's own code, for the response envelope. The gateway's codes cross
62
+ * to the phone unchanged (`gateway/arguments-invalid` and friends) so the client
63
+ * can tell "this deployment cannot" from "this build is wrong"; anything
64
+ * without a string code is `internal`.
65
+ */
66
+ export function errorCodeOf(error: unknown, fallback: string): string {
67
+ const code = (error as { code?: unknown } | null | undefined)?.code
68
+ return typeof code === 'string' && code !== '' ? code : fallback
69
+ }
70
+
71
+ /**
72
+ * Run one unary call, retrying only the service-activation window.
73
+ * @param run - the call to attempt.
74
+ * @param options.attempts - total tries (default {@link SERVICE_UNAVAILABLE_ATTEMPTS}).
75
+ * @param options.backoffMs - wait between tries (default {@link SERVICE_UNAVAILABLE_BACKOFF_MS}).
76
+ * @returns the call's own result or failure; the failure is never swallowed.
77
+ */
78
+ export async function withServiceUnavailableRetry<T>(
79
+ run: () => Promise<T>,
80
+ options: { attempts?: number; backoffMs?: number } = {},
81
+ ): Promise<T> {
82
+ const attempts = options.attempts ?? SERVICE_UNAVAILABLE_ATTEMPTS
83
+ const backoffMs = options.backoffMs ?? SERVICE_UNAVAILABLE_BACKOFF_MS
84
+ for (let attempt = 1; ; attempt += 1) {
85
+ try {
86
+ return await run()
87
+ } catch (error) {
88
+ if (!isServiceUnavailable(error) || attempt >= attempts) throw error
89
+ await delay(backoffMs)
90
+ }
91
+ }
92
+ }
@@ -0,0 +1,238 @@
1
+ /**
2
+ * The bridge's process-wide connection registry and its claims on
3
+ * `approval/request` and `user-questions/request`.
4
+ *
5
+ * The hub is what makes "phone not answering equals refusal" true: a question
6
+ * is claimed only while at least one paired device is connected, the publish
7
+ * has to actually reach someone, and every other path (timeout, agent
8
+ * cancellation, the last phone leaving) delegates to the next answerer, which
9
+ * the Host normalizes to `'unavailable'`.
10
+ *
11
+ * The claim on `user-questions/request` follows the same two rules, with two
12
+ * differences that belong to the host's own semantics: delegating is not a
13
+ * refusal, because only a phone that declares `questions.v1` is ever shown the
14
+ * question; and a question is named on the wire even when the host named none,
15
+ * because a blocking ask carries no call id and the phone still needs a handle
16
+ * to answer with.
17
+ * @module dsh-remote-bridge/core/hub
18
+ */
19
+
20
+ import type { ApprovalOutcome } from '@deepseek-ai/dsh-user-approval'
21
+ import type { BridgeConnectionOptions, BridgeTransport, ConnectionAuth } from './connection.ts'
22
+ import { BridgeConnection } from './connection.ts'
23
+ import { CAP_QUESTIONS, TOPIC_APPROVAL_REQUEST, TOPIC_QUESTION_REQUEST } from './protocol.ts'
24
+ import type { ClaimedQuestionView, QuestionAnswer, QuestionRequestPayload, QuestionState, UserQuestionRequestLike } from './questions.ts'
25
+
26
+ /**
27
+ * The fields of an approval question this bridge reads. Structural on purpose:
28
+ * the event's own type is not exported from the package root, and only these
29
+ * fields are ever touched.
30
+ */
31
+ export interface ApprovalRequestLike {
32
+ /** The agent asking; its id IS the session id (the event carries no session field). */
33
+ readonly agent: { readonly id: string }
34
+ readonly toolName: string
35
+ readonly displayReason?: { readonly en: string; readonly [locale: string]: string }
36
+ readonly signal?: AbortSignal
37
+ }
38
+
39
+ /** The summary line a phone shows for one question. */
40
+ export function approvalSummary(request: ApprovalRequestLike): string {
41
+ return request.displayReason?.zh ?? request.displayReason?.en ?? request.toolName
42
+ }
43
+
44
+ /**
45
+ * The `question.request` payload for one claim.
46
+ *
47
+ * No `expiresAt`: the host's foreground deadline is not part of the request the
48
+ * waterfall carries, and a bridge-invented deadline would be a timeout of the
49
+ * bridge's own — the exact thing this channel must not have.
50
+ * @param state - whether the foreground ask still holds the question.
51
+ * @param question - the claim being published.
52
+ */
53
+ function questionPayload(state: QuestionState, question: ClaimedQuestionView): QuestionRequestPayload {
54
+ return { sessionId: question.sessionId, callId: question.callId, state, questions: question.questions }
55
+ }
56
+
57
+ /** The bridge's live connections plus the answerer it composes onto the approval chain. */
58
+ export class BridgeHub {
59
+ readonly #options: BridgeConnectionOptions
60
+ readonly #connections = new Set<BridgeConnection>()
61
+
62
+ constructor(options: BridgeConnectionOptions) {
63
+ this.#options = options
64
+ }
65
+
66
+ /** @returns how many paired devices could answer a question right now. */
67
+ get pairedClients(): number {
68
+ let count = 0
69
+ for (const connection of this.#connections) if (connection.paired) count += 1
70
+ return count
71
+ }
72
+
73
+ /**
74
+ * Register one accepted socket.
75
+ * @param transport - the carrier the connection writes through.
76
+ * @param auth - the device the upgrade proved, when it carried a valid token.
77
+ */
78
+ attach(transport: BridgeTransport, auth?: ConnectionAuth): BridgeConnection {
79
+ // The replay hook is wired here rather than by the caller: a phone that
80
+ // reconnects mid-question was not there for the broadcast, and every
81
+ // construction path has to hand it the live claims.
82
+ const connection = new BridgeConnection(
83
+ { ...this.#options, onDeclare: (fresh) => { this.replayQuestions(fresh) } },
84
+ transport,
85
+ auth,
86
+ )
87
+ this.#connections.add(connection)
88
+ connection.startHeartbeat()
89
+ if (auth !== undefined) void this.#options.roster.touch(auth.deviceId).catch(() => undefined)
90
+ this.#options.log(`connection open (${auth === undefined ? 'unpaired' : `device ${auth.deviceId}`})`)
91
+ return connection
92
+ }
93
+
94
+ /**
95
+ * Forget one connection and abort everything it owns. When it was the last
96
+ * paired device, every pending question is withdrawn: nobody left can answer.
97
+ */
98
+ detach(connection: BridgeConnection): void {
99
+ this.#connections.delete(connection)
100
+ connection.dispose()
101
+ if (this.pairedClients > 0) return
102
+ const withdrawn = this.#options.approvals.abandonAll()
103
+ if (withdrawn > 0) this.#options.log(`${withdrawn} approval question(s) withdrew: no paired device is connected`)
104
+ // A user question is delegated rather than refused: the next answerer in the
105
+ // host's chain decides, and the question's own deadline still holds.
106
+ const released = this.#options.questions.withdrawAll()
107
+ if (released > 0) this.#options.log(`${released} user question(s) released: no paired device is connected`)
108
+ }
109
+
110
+ /**
111
+ * Publish one event to every paired device.
112
+ * @returns how many connections actually took the frame.
113
+ */
114
+ broadcast(topic: string, payload: unknown): number {
115
+ let delivered = 0
116
+ for (const connection of this.#connections) {
117
+ if (!connection.paired) continue
118
+ if (connection.emit(topic, payload)) delivered += 1
119
+ }
120
+ return delivered
121
+ }
122
+
123
+ /**
124
+ * Publish one event to every paired device that announced a capability.
125
+ * @returns how many connections actually took the frame.
126
+ */
127
+ /**
128
+ * Hand one freshly declared connection the questions it can now answer.
129
+ *
130
+ * Without this, a question raised while the phone was reconnecting stays on the
131
+ * host with no card anywhere on the phone: the original broadcast was addressed
132
+ * to clients that had already announced the channel.
133
+ */
134
+ replayQuestions(connection: BridgeConnection): void {
135
+ if (!connection.paired || !connection.declares(CAP_QUESTIONS)) return
136
+ for (const claim of this.#options.questions.openClaims()) {
137
+ connection.emit(TOPIC_QUESTION_REQUEST, questionPayload('open', claim))
138
+ }
139
+ }
140
+
141
+ broadcastTo(capability: string, topic: string, payload: unknown): number {
142
+ let delivered = 0
143
+ for (const connection of this.#connections) {
144
+ if (!connection.paired || !connection.declares(capability)) continue
145
+ if (connection.emit(topic, payload)) delivered += 1
146
+ }
147
+ return delivered
148
+ }
149
+
150
+ /**
151
+ * The body of this plugin's `approval/request` listener.
152
+ * @param request - the pending question.
153
+ * @param next - the rest of the answerer chain.
154
+ * @returns a claimed decision, or whatever the next answerer says.
155
+ */
156
+ async approve(request: ApprovalRequestLike, next: () => Promise<ApprovalOutcome>): Promise<ApprovalOutcome> {
157
+ if (this.pairedClients === 0) return await next()
158
+ const sessionId = request.agent.id
159
+ const prompt = this.#options.approvals.open({
160
+ sessionId,
161
+ toolName: request.toolName,
162
+ summary: approvalSummary(request),
163
+ ...(request.signal === undefined ? {} : { signal: request.signal }),
164
+ })
165
+ const delivered = this.broadcast(TOPIC_APPROVAL_REQUEST, {
166
+ sessionId,
167
+ id: prompt.id,
168
+ summary: prompt.summary,
169
+ toolName: request.toolName,
170
+ })
171
+ // A question nobody could receive is withdrawn immediately instead of
172
+ // waiting out the phone's timeout with the agent blocked on it.
173
+ if (delivered === 0) this.#options.approvals.abandon([prompt.id])
174
+ const answer = await prompt.answer
175
+ return answer === undefined ? await next() : answer
176
+ }
177
+
178
+ /**
179
+ * The body of this plugin's `user-questions/request` listener.
180
+ *
181
+ * Claimed only while a paired device is connected and the ask names an agent:
182
+ * the payload has no session field of its own, and a question nobody can be
183
+ * told about is not one this bridge may hold. The wire id is the host's own
184
+ * when the ask is timed, and minted here when it is blocking and the host
185
+ * assigned none — either way the phone answers the id it was shown. A claim
186
+ * nobody received is withdrawn at once instead of holding the agent until the
187
+ * host's deadline.
188
+ * @param request - the pending question batch.
189
+ * @param next - the rest of the answerer chain.
190
+ * @returns the phone's answer, the host's own deadline outcome, or whatever the next answerer says.
191
+ */
192
+ async question(request: UserQuestionRequestLike, next: () => Promise<QuestionAnswer>): Promise<QuestionAnswer> {
193
+ const sessionId = request.agent?.id
194
+ if (sessionId === undefined) return await next()
195
+ if (this.pairedClients === 0) return await next()
196
+ // A blocking ask carries no `wait`: the host has no call id for it, but the
197
+ // phone needs a handle to answer with, so one is minted in this bridge's own
198
+ // namespace. Resolving the promise held here needs no host identity.
199
+ const hosted = request.wait?.callId
200
+ const callId = hosted ?? this.#options.questions.mintCallId()
201
+ const claim = this.#options.questions.open({
202
+ sessionId,
203
+ callId,
204
+ hosted: hosted !== undefined,
205
+ questions: request.questions,
206
+ next,
207
+ ...(request.signal === undefined ? {} : { signal: request.signal }),
208
+ onSettled: (question): void => {
209
+ // The phone's card has to go when the desktop answered it, or the phone
210
+ // keeps offering a question that no longer exists.
211
+ this.broadcastTo(CAP_QUESTIONS, TOPIC_QUESTION_REQUEST, questionPayload('settled', question))
212
+ },
213
+ onContinued: (question): void => {
214
+ // The foreground wait ended, but the question is still answerable: the
215
+ // phone is told which state it is in instead of losing the question.
216
+ this.broadcastTo(CAP_QUESTIONS, TOPIC_QUESTION_REQUEST, questionPayload('continued', question))
217
+ },
218
+ })
219
+ if (claim === undefined) return await next()
220
+ const delivered = this.broadcastTo(CAP_QUESTIONS, TOPIC_QUESTION_REQUEST, questionPayload('open', claim))
221
+ // A client that cannot receive this is not going to receive it later: the claim
222
+ // must not be left holding the host's ask with no card anywhere. A client that
223
+ // *can* receive it but was reconnecting is a different case — it is handed the
224
+ // live claims by `onDeclare` when it comes back.
225
+ if (delivered === 0) this.#options.questions.withdraw([callId])
226
+ return await claim.answer
227
+ }
228
+
229
+ /** Close every connection and withdraw every question. Idempotent. */
230
+ dispose(): void {
231
+ for (const connection of [...this.#connections]) {
232
+ this.#connections.delete(connection)
233
+ connection.dispose()
234
+ }
235
+ this.#options.approvals.abandonAll()
236
+ this.#options.questions.withdrawAll()
237
+ }
238
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * The gate in front of the bootstrap token endpoint.
3
+ *
4
+ * The socket address alone is NOT a loopback proof on this deployment: a
5
+ * request that arrives over a public tunnel is terminated by the tunnel client
6
+ * on the same machine, so cloudflared connects to the origin from loopback and
7
+ * `req.socket.remoteAddress` reads `127.0.0.1` for a request the whole internet
8
+ * can reach. The reliable discriminator is the `Host` header, which both the
9
+ * market relay and a plain tunnel rewrite to the public hostname before the
10
+ * origin sees the request (`market/worker/src/relay.js:263` sets it to the
11
+ * registered tunnel host). Both conditions must hold, so a forged
12
+ * `remoteAddress` in a test — or a proxy that forgets to rewrite `Host` — still
13
+ * cannot mint a pairing token.
14
+ * @module dsh-remote-bridge/core/loopback
15
+ */
16
+
17
+ import type { IncomingMessage } from 'node:http'
18
+
19
+ /** Socket addresses that count as "this machine". */
20
+ export const LOOPBACK_ADDRESSES: ReadonlySet<string> = new Set(['127.0.0.1', '::1', '::ffff:127.0.0.1'])
21
+
22
+ /** Host header values that count as "this machine". */
23
+ export const LOOPBACK_HOSTS: ReadonlySet<string> = new Set(['127.0.0.1', 'localhost', '[::1]'])
24
+
25
+ /** @returns whether a socket's remote address is this machine. */
26
+ export function isLoopbackAddress(remoteAddress: string | undefined): boolean {
27
+ return remoteAddress !== undefined && LOOPBACK_ADDRESSES.has(remoteAddress)
28
+ }
29
+
30
+ /**
31
+ * @returns whether a `Host` header names this machine. The port is ignored;
32
+ * anything that is not a loopback literal — including a public tunnel
33
+ * hostname — is refused.
34
+ */
35
+ export function isLoopbackHost(host: string | undefined): boolean {
36
+ if (host === undefined) return false
37
+ const name = host.trim().toLowerCase()
38
+ if (name === '') return false
39
+ const bare = name.startsWith('[')
40
+ // IPv6 literals carry their port after the closing bracket.
41
+ ? name.slice(0, name.indexOf(']') + 1)
42
+ : name.split(':')[0] ?? ''
43
+ return LOOPBACK_HOSTS.has(bare)
44
+ }
45
+
46
+ /**
47
+ * Why this request may not reach the bootstrap token endpoint, or undefined
48
+ * when it may.
49
+ * @param req - the incoming request.
50
+ * @returns a one-line reason, or undefined.
51
+ */
52
+ export function loopbackDenialOf(req: IncomingMessage): string | undefined {
53
+ if (!isLoopbackAddress(req.socket.remoteAddress)) {
54
+ return 'the request did not arrive from this machine'
55
+ }
56
+ if (!isLoopbackHost(req.headers.host)) {
57
+ return 'the request names a Host that is not this machine'
58
+ }
59
+ return undefined
60
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * The in-process owner peer every gateway call of this bridge speaks for.
3
+ *
4
+ * The 0.2.1 gateway made `peer` mandatory on every request, and the
5
+ * authorization layer reads only `peer.principal`: `{ kind: 'owner' }` is how
6
+ * host-local code states that the call IS the local user driving their own
7
+ * Host, so the gateway answers it directly instead of running a remote-access
8
+ * decision (only non-owner principals are judged).
9
+ * @module dsh-remote-bridge/core/owner-peer
10
+ */
11
+
12
+ import type { Context } from '@deepseek-ai/cordis'
13
+ import type { GatewayPeer } from './wire.ts'
14
+
15
+ /**
16
+ * Mint the in-process owner peer this bridge's Host calls speak for.
17
+ *
18
+ * The bridge's security model states that pairing is a full-control
19
+ * credential: a paired device reaches the harness in-process — sessions,
20
+ * prompts, approvals. Protocol v1 is therefore deliberately paired with the
21
+ * one principal that preserves the pre-0.2.1 capability of the bridge's own
22
+ * in-process calls: the owner. That claim is safe only because of WHERE this
23
+ * peer is attached:
24
+ *
25
+ * - Every gateway call a connection can trigger sits behind the bridge's own
26
+ * pairing gate: dispatch answers `unpaired` before any session, approval or
27
+ * roster work, and the three unpaired methods (`hello`, `pair.begin`,
28
+ * `pair.finish`) never invoke the gateway at all. The owner peer crosses to
29
+ * the harness only after a connection proved a device token (or just
30
+ * enrolled one), never for an unpaired one.
31
+ * - No wire field can set a principal: the connection never reads a `peer`
32
+ * or `principal` (or any identity) out of a client frame. The peer is minted
33
+ * here, in-process, fixed at `{ kind: 'owner' }`, and a client that names
34
+ * one in its payload is ignored — the call still speaks for this peer.
35
+ *
36
+ * `interactions` stays `'none'`: the bridge only invokes unary methods and
37
+ * opens the `session/follow` business stream. The gateway's interactions
38
+ * check gates exactly the forwarded-event endpoints (opening an event stream,
39
+ * answering a waterfall), which this caller never touches; an `'answer'`
40
+ * peer would additionally receive forwarded Host events, a capability the
41
+ * bridge neither needs nor wants — approvals reach devices through this
42
+ * plugin's own `approval/request` listener and the protocol's own events, not
43
+ * through a Typert forwarded-event subscription.
44
+ *
45
+ * The peer's signal aborts once `ctx` disposes, so calls and streams opened
46
+ * for it end with the plugin fiber, and `dispose()` is idempotent with racing
47
+ * calls sharing one completion. The id carries no credential — the protocol
48
+ * fixes `principal` as the only identity persisted in a session log — so a
49
+ * fresh unique id per mount is sufficient.
50
+ */
51
+ export function createOwnerPeer(ctx: Context): GatewayPeer {
52
+ const controller = new AbortController()
53
+ let completion: Promise<void> | undefined
54
+ const peer: GatewayPeer = {
55
+ id: `remote-bridge-owner:${crypto.randomUUID()}` as GatewayPeer['id'],
56
+ ctx,
57
+ principal: { kind: 'owner' },
58
+ signal: controller.signal,
59
+ interactions: 'none',
60
+ dispose() {
61
+ if (completion === undefined) {
62
+ controller.abort()
63
+ completion = Promise.resolve()
64
+ }
65
+ return completion
66
+ },
67
+ }
68
+ ctx.effect(() => () => { void peer.dispose() }, 'remote-bridge owner peer')
69
+ return peer
70
+ }
@@ -0,0 +1,113 @@
1
+ /**
2
+ * In-memory bootstrap tokens and pairing nonces.
3
+ *
4
+ * Both are one-shot and short-lived, and neither is ever persisted: a token an
5
+ * operator reads off the Host log is only useful while its 30 s window is open,
6
+ * and a restart invalidating every pending pairing is the desired behavior.
7
+ * @module dsh-remote-bridge/core/pairing
8
+ */
9
+
10
+ import { randomBase64Url } from './crypto.ts'
11
+
12
+ /** Lifetime of one bootstrap token handed to the operator's phone. */
13
+ export const BOOTSTRAP_TOKEN_TTL_MS = 30_000
14
+ /** Lifetime of one pairing nonce, from `pair.begin` to `pair.finish`. */
15
+ export const PAIR_NONCE_TTL_MS = 60_000
16
+ /** Entropy of one bootstrap token. */
17
+ export const BOOTSTRAP_TOKEN_BYTES = 32
18
+ /** Entropy of one pairing nonce. */
19
+ export const PAIR_NONCE_BYTES = 16
20
+
21
+ /** A minted one-shot secret and the instant it stops being accepted. */
22
+ export interface PairingTicket {
23
+ readonly value: string
24
+ readonly expiresAt: number
25
+ }
26
+
27
+ export interface PairingServiceOptions {
28
+ /** Clock, injectable so expiry is tested without sleeping. */
29
+ readonly now?: () => number
30
+ readonly tokenTtlMs?: number
31
+ readonly nonceTtlMs?: number
32
+ /** Secret source, injectable so a test can pin the value it will present. */
33
+ readonly random?: (byteLength: number) => string
34
+ }
35
+
36
+ /**
37
+ * The two one-shot secrets of the pairing handshake.
38
+ *
39
+ * `issueToken` is called by the loopback-only route an operator reaches from
40
+ * the Host itself; `beginPairing` consumes that token and mints the nonce the
41
+ * phone signs; `consumeNonce` closes the handshake. Consumption happens BEFORE
42
+ * any signature check in the caller, so a wrong signature still burns the
43
+ * nonce: a brute-force loop cannot reuse one challenge.
44
+ */
45
+ export class PairingService {
46
+ readonly #now: () => number
47
+ readonly #tokenTtlMs: number
48
+ readonly #nonceTtlMs: number
49
+ readonly #random: (byteLength: number) => string
50
+ readonly #tokens = new Map<string, number>()
51
+ readonly #nonces = new Map<string, number>()
52
+
53
+ constructor(options: PairingServiceOptions = {}) {
54
+ this.#now = options.now ?? (() => Date.now())
55
+ this.#tokenTtlMs = options.tokenTtlMs ?? BOOTSTRAP_TOKEN_TTL_MS
56
+ this.#nonceTtlMs = options.nonceTtlMs ?? PAIR_NONCE_TTL_MS
57
+ this.#random = options.random ?? randomBase64Url
58
+ }
59
+
60
+ /** Mint one bootstrap token, valid until its own expiry. */
61
+ issueToken(): PairingTicket {
62
+ this.#prune()
63
+ const value = this.#random(BOOTSTRAP_TOKEN_BYTES)
64
+ const expiresAt = this.#now() + this.#tokenTtlMs
65
+ this.#tokens.set(value, expiresAt)
66
+ return { value, expiresAt }
67
+ }
68
+
69
+ /**
70
+ * Consume one bootstrap token.
71
+ * @returns whether the token was live; a consumed or expired token is gone.
72
+ */
73
+ consumeToken(token: string): boolean {
74
+ this.#prune()
75
+ const expiresAt = this.#tokens.get(token)
76
+ if (expiresAt === undefined) return false
77
+ this.#tokens.delete(token)
78
+ return true
79
+ }
80
+
81
+ /** Mint one pairing nonce for a connection that just consumed a valid token. */
82
+ issueNonce(): PairingTicket {
83
+ this.#prune()
84
+ const value = this.#random(PAIR_NONCE_BYTES)
85
+ const expiresAt = this.#now() + this.#nonceTtlMs
86
+ this.#nonces.set(value, expiresAt)
87
+ return { value, expiresAt }
88
+ }
89
+
90
+ /**
91
+ * Consume one pairing nonce.
92
+ * @returns whether the nonce was live; a consumed or expired nonce is gone.
93
+ */
94
+ consumeNonce(nonce: string): boolean {
95
+ this.#prune()
96
+ const expiresAt = this.#nonces.get(nonce)
97
+ if (expiresAt === undefined) return false
98
+ this.#nonces.delete(nonce)
99
+ return true
100
+ }
101
+
102
+ /** @returns how many tokens and nonces are currently acceptable, for tests and diagnostics. */
103
+ get pending(): { tokens: number; nonces: number } {
104
+ this.#prune()
105
+ return { tokens: this.#tokens.size, nonces: this.#nonces.size }
106
+ }
107
+
108
+ #prune(): void {
109
+ const now = this.#now()
110
+ for (const [value, expiresAt] of this.#tokens) if (expiresAt <= now) this.#tokens.delete(value)
111
+ for (const [value, expiresAt] of this.#nonces) if (expiresAt <= now) this.#nonces.delete(value)
112
+ }
113
+ }