@linxin666/dsh-remote-bridge 0.4.8 → 0.4.9
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 +50 -17
- package/README.zh.md +50 -17
- package/lib/client.js +274 -253
- package/lib/client.js.map +1 -1
- package/lib/index.js +6690 -2277
- package/lib/types/client/PairEntry.d.ts +2 -2
- package/lib/types/client/PairPanel.d.ts +10 -2
- package/lib/types/client/icons.d.ts +5 -13
- package/lib/types/client/locales.d.ts +10 -14
- package/lib/types/client/semantic.d.ts +9 -5
- package/lib/types/core/commands.d.ts +59 -0
- package/lib/types/core/connection.d.ts +68 -0
- package/lib/types/core/devices.d.ts +98 -2
- package/lib/types/core/hub.d.ts +65 -15
- package/lib/types/core/liveactivity.d.ts +324 -0
- package/lib/types/core/protocol.d.ts +260 -1
- package/lib/types/core/push.d.ts +178 -0
- package/lib/types/core/questions.d.ts +61 -9
- package/lib/types/core/session-meta.d.ts +55 -1
- package/lib/types/core/squads.d.ts +130 -0
- package/lib/types/core/usage-stats.d.ts +160 -0
- package/lib/types/core/usage.d.ts +294 -0
- package/lib/types/host/apns.d.ts +151 -0
- package/lib/types/host/squads-ledger.d.ts +39 -0
- package/lib/types/host/squads.d.ts +77 -0
- package/lib/types/host/usage-stats.d.ts +75 -0
- package/lib/types/host/watchers.d.ts +88 -0
- package/lib/types/index.d.ts +18 -2
- package/package.json +13 -13
- package/src/client/PairEntry.tsx +58 -31
- package/src/client/PairPanel.tsx +181 -97
- package/src/client/icons.tsx +17 -60
- package/src/client/locales.ts +15 -23
- package/src/client/panel.module.css +239 -186
- package/src/client/semantic.ts +10 -6
- package/src/core/commands.ts +95 -0
- package/src/core/connection.ts +646 -10
- package/src/core/devices.ts +221 -3
- package/src/core/hub.ts +362 -42
- package/src/core/liveactivity.ts +833 -0
- package/src/core/protocol.ts +294 -1
- package/src/core/push.ts +354 -0
- package/src/core/questions.ts +81 -10
- package/src/core/session-meta.ts +73 -1
- package/src/core/squads.ts +345 -0
- package/src/core/usage-stats.ts +424 -0
- package/src/core/usage.ts +937 -0
- package/src/core/wire.ts +8 -0
- package/src/host/apns.ts +320 -0
- package/src/host/squads-ledger.ts +105 -0
- package/src/host/squads.ts +206 -0
- package/src/host/usage-stats.ts +155 -0
- package/src/host/watchers.ts +272 -0
- package/src/index.ts +257 -8
package/src/core/wire.ts
CHANGED
|
@@ -121,7 +121,15 @@ export const WIRE_TABLE: readonly WireRow[] = [
|
|
|
121
121
|
{ namespace: 'session', method: 'projections', wire: 'request' },
|
|
122
122
|
{ namespace: 'session', method: 'modelCatalog', wire: 'none' },
|
|
123
123
|
{ namespace: 'session', method: 'selectModel', wire: 'request' },
|
|
124
|
+
{ namespace: 'session', method: 'rename', wire: 'request' },
|
|
125
|
+
{ namespace: 'workspace', method: 'pinSession', wire: 'request' },
|
|
126
|
+
{ namespace: 'workspace', method: 'unpinSession', wire: 'request' },
|
|
127
|
+
{ namespace: 'workspace', method: 'archiveSession', wire: 'request' },
|
|
128
|
+
{ namespace: 'workspace', method: 'unarchiveSession', wire: 'request' },
|
|
124
129
|
{ namespace: 'agentPresets', method: 'list', wire: 'none' },
|
|
130
|
+
{ namespace: 'commands', method: 'list', wire: { names: ['agentId'] } },
|
|
131
|
+
{ namespace: 'commands', method: 'execute', wire: { names: ['agentId', 'line', 'submittedAttachments'] } },
|
|
132
|
+
{ namespace: 'skills', method: 'list', wire: 'request' },
|
|
125
133
|
{ namespace: 'userQuestions', method: 'answer', wire: { names: ['agentId', 'callId', 'answer'] } },
|
|
126
134
|
{ namespace: 'userQuestions', method: 'attachWait', wire: { names: ['agentId', 'callId'] } },
|
|
127
135
|
{ namespace: 'pluginInventory', method: 'list', wire: 'none' },
|
package/src/host/apns.ts
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The APNs client this bridge sends notifications through.
|
|
3
|
+
*
|
|
4
|
+
* Written against `node:http2` and `node:crypto` and nothing else: the provider
|
|
5
|
+
* API is one POST per notification behind an ES256 JWT, which is small enough
|
|
6
|
+
* that a dependency would cost more than it saves, and this package's whole
|
|
7
|
+
* install surface is one browser library.
|
|
8
|
+
*
|
|
9
|
+
* Two facts about the credential shape everything here:
|
|
10
|
+
*
|
|
11
|
+
* - the signing key is an Apple `.p8` on this machine, named by an environment
|
|
12
|
+
* variable. It never enters this repository, the roster file, a log line or a
|
|
13
|
+
* wire frame; only the JWT derived from it leaves the process.
|
|
14
|
+
* - a bridge with no key is a bridge with the channel OFF. {@link apnsConfigFromEnv}
|
|
15
|
+
* answers undefined, no sender is constructed, and every notification path is
|
|
16
|
+
* a no-op — the existing protocol runs byte for byte as it did before (§28).
|
|
17
|
+
* @module dsh-remote-bridge/host/apns
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { createPrivateKey, sign, type KeyObject } from 'node:crypto'
|
|
21
|
+
import { readFile } from 'node:fs/promises'
|
|
22
|
+
import { connect, type ClientHttp2Session } from 'node:http2'
|
|
23
|
+
import type { LiveActivityAddress, LiveActivityNotification, LiveActivitySender } from '../core/liveactivity.ts'
|
|
24
|
+
import type { PushAddress, PushNotification, PushSendResult, PushSender } from '../core/push.ts'
|
|
25
|
+
|
|
26
|
+
/** Production APNs authority. */
|
|
27
|
+
export const APNS_PRODUCTION_AUTHORITY = 'api.push.apple.com'
|
|
28
|
+
/** Development APNs authority; a build signed for development must use it. */
|
|
29
|
+
export const APNS_SANDBOX_AUTHORITY = 'api.sandbox.push.apple.com'
|
|
30
|
+
/** Path prefix of one device delivery. */
|
|
31
|
+
export const APNS_DEVICE_PATH = '/3/device/'
|
|
32
|
+
/**
|
|
33
|
+
* The topic suffix a Live Activity push needs.
|
|
34
|
+
*
|
|
35
|
+
* A Live Activity is addressed under the app bundle's own topic with this
|
|
36
|
+
* suffix appended (§29); the bare bundle is the alert channel's topic, and
|
|
37
|
+
* sending a card there is delivered as an alert the App cannot decode.
|
|
38
|
+
*/
|
|
39
|
+
export const APNS_LIVE_ACTIVITY_TOPIC_SUFFIX = '.push-type.liveactivity'
|
|
40
|
+
/**
|
|
41
|
+
* How long one signed provider token is reused.
|
|
42
|
+
*
|
|
43
|
+
* Apple rejects a token older than an hour and throttles a provider that mints
|
|
44
|
+
* one per request, so the token is refreshed well inside that window.
|
|
45
|
+
*/
|
|
46
|
+
export const APNS_TOKEN_TTL_MS = 45 * 60 * 1000
|
|
47
|
+
/** How long one delivery may take before it is abandoned. */
|
|
48
|
+
export const APNS_TIMEOUT_MS = 10_000
|
|
49
|
+
/** Environment variables this bridge reads its credential from. */
|
|
50
|
+
export const APNS_ENV = {
|
|
51
|
+
keyFile: 'DSH_REMOTE_BRIDGE_APNS_KEY_FILE',
|
|
52
|
+
keyId: 'DSH_REMOTE_BRIDGE_APNS_KEY_ID',
|
|
53
|
+
teamId: 'DSH_REMOTE_BRIDGE_APNS_TEAM_ID',
|
|
54
|
+
} as const
|
|
55
|
+
|
|
56
|
+
/** The credential this bridge signs with. */
|
|
57
|
+
export interface ApnsConfig {
|
|
58
|
+
/** Absolute path of the `.p8` private key. */
|
|
59
|
+
readonly keyFile: string
|
|
60
|
+
/** The key id Apple issued for that file. */
|
|
61
|
+
readonly keyId: string
|
|
62
|
+
/** The Apple Developer team id, which is the token's `iss`. */
|
|
63
|
+
readonly teamId: string
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Read the APNs credential from the environment.
|
|
68
|
+
* @param env - the environment to read; defaults to this process's.
|
|
69
|
+
* @returns the credential, or undefined when any part of it is missing — which
|
|
70
|
+
* is how the channel stays off by default.
|
|
71
|
+
*/
|
|
72
|
+
export function apnsConfigFromEnv(env: NodeJS.ProcessEnv = process.env): ApnsConfig | undefined {
|
|
73
|
+
const keyFile = env[APNS_ENV.keyFile]?.trim()
|
|
74
|
+
const keyId = env[APNS_ENV.keyId]?.trim()
|
|
75
|
+
const teamId = env[APNS_ENV.teamId]?.trim()
|
|
76
|
+
if (keyFile === undefined || keyFile === '' || keyId === undefined || keyId === '' || teamId === undefined || teamId === '') return undefined
|
|
77
|
+
return { keyFile, keyId, teamId }
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** @returns the base64url text of one buffer, without padding. */
|
|
81
|
+
export function base64Url(value: Buffer | string): string {
|
|
82
|
+
return Buffer.from(value).toString('base64url')
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Sign one APNs provider token.
|
|
87
|
+
*
|
|
88
|
+
* Header and claims are exactly what Apple accepts and nothing more: `alg`,
|
|
89
|
+
* `kid` and `iss`, `iat`. APNs rejects a token carrying any other claim, so
|
|
90
|
+
* this is not a place to add a convenient `exp` beside it.
|
|
91
|
+
* @param input - the key, its id, the team id, and the issue time.
|
|
92
|
+
* @returns the compact JWT.
|
|
93
|
+
*/
|
|
94
|
+
export function es256Jwt(input: {
|
|
95
|
+
readonly key: KeyObject
|
|
96
|
+
readonly keyId: string
|
|
97
|
+
readonly teamId: string
|
|
98
|
+
readonly issuedAt?: number
|
|
99
|
+
}): string {
|
|
100
|
+
const header = base64Url(JSON.stringify({ alg: 'ES256', kid: input.keyId }))
|
|
101
|
+
const claims = base64Url(JSON.stringify({ iss: input.teamId, iat: Math.floor((input.issuedAt ?? Date.now()) / 1000) }))
|
|
102
|
+
const signingInput = `${header}.${claims}`
|
|
103
|
+
// ES256 is ECDSA over P-256 with SHA-256, and APNs wants the raw r||s pair
|
|
104
|
+
// rather than a DER sequence: 'ieee-p1363' is that encoding.
|
|
105
|
+
const signature = sign('sha256', Buffer.from(signingInput, 'utf8'), { key: input.key, dsaEncoding: 'ieee-p1363' })
|
|
106
|
+
return `${signingInput}.${base64Url(signature)}`
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** What one delivery's HTTP/2 request looks like. */
|
|
110
|
+
export interface ApnsRequestSpec {
|
|
111
|
+
readonly authority: string
|
|
112
|
+
readonly path: string
|
|
113
|
+
readonly headers: Readonly<Record<string, string>>
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* The request one notification becomes.
|
|
118
|
+
*
|
|
119
|
+
* `apns-topic` is the registration's own bundle id and `apns-push-type` is
|
|
120
|
+
* always `alert`: this channel only ever sends a user-visible notification, and
|
|
121
|
+
* a body typed as anything else would be dropped by the system for having an
|
|
122
|
+
* alert payload.
|
|
123
|
+
* @param target - the device being notified.
|
|
124
|
+
* @param jwt - the provider token.
|
|
125
|
+
* @returns the authority, path and headers of the POST.
|
|
126
|
+
*/
|
|
127
|
+
export function apnsRequestSpec(target: PushAddress, jwt: string): ApnsRequestSpec {
|
|
128
|
+
return {
|
|
129
|
+
authority: target.environment === 'production' ? APNS_PRODUCTION_AUTHORITY : APNS_SANDBOX_AUTHORITY,
|
|
130
|
+
path: `${APNS_DEVICE_PATH}${target.deviceToken}`,
|
|
131
|
+
headers: {
|
|
132
|
+
authorization: `bearer ${jwt}`,
|
|
133
|
+
'apns-topic': target.bundle,
|
|
134
|
+
'apns-push-type': 'alert',
|
|
135
|
+
'apns-priority': '10',
|
|
136
|
+
'content-type': 'application/json',
|
|
137
|
+
},
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* The topic one Live Activity push is addressed under.
|
|
143
|
+
* @param bundle - the app bundle the device registered with.
|
|
144
|
+
* @returns the bundle plus the Live Activity suffix, appended once.
|
|
145
|
+
*/
|
|
146
|
+
export function liveActivityTopicOf(bundle: string): string {
|
|
147
|
+
return bundle.endsWith(APNS_LIVE_ACTIVITY_TOPIC_SUFFIX) ? bundle : `${bundle}${APNS_LIVE_ACTIVITY_TOPIC_SUFFIX}`
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* The request one Live Activity push becomes.
|
|
152
|
+
*
|
|
153
|
+
* Three headers differ from the alert request beside it, and each of them is a
|
|
154
|
+
* rule rather than a preference: the push type is `liveactivity`, the topic is
|
|
155
|
+
* the app bundle's Live Activity topic, and the expiration is `0` — a card
|
|
156
|
+
* update that could not be delivered now must never be delivered later, because
|
|
157
|
+
* it would overwrite the present with the past (§29).
|
|
158
|
+
* @param target - the card being pushed to.
|
|
159
|
+
* @param jwt - the provider token.
|
|
160
|
+
* @returns the authority, path and headers of the POST.
|
|
161
|
+
*/
|
|
162
|
+
export function liveActivityRequestSpec(target: LiveActivityAddress, jwt: string): ApnsRequestSpec {
|
|
163
|
+
return {
|
|
164
|
+
authority: target.environment === 'production' ? APNS_PRODUCTION_AUTHORITY : APNS_SANDBOX_AUTHORITY,
|
|
165
|
+
path: `${APNS_DEVICE_PATH}${target.token}`,
|
|
166
|
+
headers: {
|
|
167
|
+
authorization: `bearer ${jwt}`,
|
|
168
|
+
'apns-topic': liveActivityTopicOf(target.bundle),
|
|
169
|
+
'apns-push-type': 'liveactivity',
|
|
170
|
+
'apns-priority': '10',
|
|
171
|
+
'apns-expiration': '0',
|
|
172
|
+
'content-type': 'application/json',
|
|
173
|
+
},
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** The reason APNs named, or its raw answer when it named none. */
|
|
178
|
+
function apnsReason(text: string): string {
|
|
179
|
+
try {
|
|
180
|
+
const parsed: unknown = JSON.parse(text)
|
|
181
|
+
if (typeof parsed === 'object' && parsed !== null) {
|
|
182
|
+
const reason = (parsed as { reason?: unknown }).reason
|
|
183
|
+
if (typeof reason === 'string' && reason !== '') return reason
|
|
184
|
+
}
|
|
185
|
+
} catch {
|
|
186
|
+
// Not JSON: the body itself is the answer, and it is all there is.
|
|
187
|
+
}
|
|
188
|
+
return text.slice(0, 200)
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export interface ApnsSenderOptions {
|
|
192
|
+
readonly config: ApnsConfig
|
|
193
|
+
readonly log?: (message: string) => void
|
|
194
|
+
/** Clock the token lifetime is measured against; the wall clock by default. */
|
|
195
|
+
readonly now?: () => number
|
|
196
|
+
readonly timeoutMs?: number
|
|
197
|
+
/** The HTTP/2 dial, injectable so the failure paths need no network. */
|
|
198
|
+
readonly connect?: (authority: string) => ClientHttp2Session
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* The APNs delivery half of the push channel.
|
|
203
|
+
*
|
|
204
|
+
* Every method resolves: a delivery that failed is a {@link PushSendResult} with
|
|
205
|
+
* `ok: false`, never a rejection, because both callers sit on frame paths that
|
|
206
|
+
* must not learn about APNs at all.
|
|
207
|
+
*/
|
|
208
|
+
export class ApnsSender implements PushSender, LiveActivitySender {
|
|
209
|
+
readonly #config: ApnsConfig
|
|
210
|
+
readonly #log: (message: string) => void
|
|
211
|
+
readonly #now: () => number
|
|
212
|
+
readonly #timeoutMs: number
|
|
213
|
+
readonly #dial: (authority: string) => ClientHttp2Session
|
|
214
|
+
#key: Promise<KeyObject> | undefined
|
|
215
|
+
#token: { readonly value: string; readonly mintedAt: number } | undefined
|
|
216
|
+
|
|
217
|
+
constructor(options: ApnsSenderOptions) {
|
|
218
|
+
this.#config = options.config
|
|
219
|
+
this.#log = options.log ?? (() => undefined)
|
|
220
|
+
this.#now = options.now ?? (() => Date.now())
|
|
221
|
+
this.#timeoutMs = options.timeoutMs ?? APNS_TIMEOUT_MS
|
|
222
|
+
this.#dial = options.connect ?? (authority => connect(`https://${authority}`))
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Deliver one notification, or report why it did not arrive. */
|
|
226
|
+
async send(target: PushAddress, notification: PushNotification): Promise<PushSendResult> {
|
|
227
|
+
let jwt: string
|
|
228
|
+
try {
|
|
229
|
+
jwt = await this.#providerToken()
|
|
230
|
+
} catch (error) {
|
|
231
|
+
return { ok: false, reason: `signing key unusable: ${String(error)}` }
|
|
232
|
+
}
|
|
233
|
+
return await this.#post(apnsRequestSpec(target, jwt), JSON.stringify(notification))
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Deliver one Live Activity push, or report why it did not arrive.
|
|
238
|
+
*
|
|
239
|
+
* The same provider token, the same transport and the same "resolve, never
|
|
240
|
+
* reject" rule as {@link send}; only the request's headers and the body differ,
|
|
241
|
+
* and both are built outside this class so the contract stays assertable.
|
|
242
|
+
*/
|
|
243
|
+
async sendLiveActivity(target: LiveActivityAddress, notification: LiveActivityNotification): Promise<PushSendResult> {
|
|
244
|
+
let jwt: string
|
|
245
|
+
try {
|
|
246
|
+
jwt = await this.#providerToken()
|
|
247
|
+
} catch (error) {
|
|
248
|
+
return { ok: false, reason: `signing key unusable: ${String(error)}` }
|
|
249
|
+
}
|
|
250
|
+
return await this.#post(liveActivityRequestSpec(target, jwt), JSON.stringify(notification))
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* POST one already-built body to APNs.
|
|
255
|
+
*
|
|
256
|
+
* One HTTP/2 session per delivery, closed as soon as the answer is in: the
|
|
257
|
+
* provider API has no session to keep warm, and one left open would outlive the
|
|
258
|
+
* caller that wanted it. Every failure resolves, because both callers sit on
|
|
259
|
+
* frame paths that must not learn about APNs at all.
|
|
260
|
+
* @param spec - the authority, path and headers of the delivery.
|
|
261
|
+
* @param body - the JSON body to send.
|
|
262
|
+
* @returns whether APNs accepted it, and why not when it did not.
|
|
263
|
+
*/
|
|
264
|
+
async #post(spec: ApnsRequestSpec, body: string): Promise<PushSendResult> {
|
|
265
|
+
const authority = spec.authority
|
|
266
|
+
return await new Promise<PushSendResult>((resolve) => {
|
|
267
|
+
let settled = false
|
|
268
|
+
let timer: NodeJS.Timeout | undefined
|
|
269
|
+
const finish = (result: PushSendResult): void => {
|
|
270
|
+
if (settled) return
|
|
271
|
+
settled = true
|
|
272
|
+
if (timer !== undefined) clearTimeout(timer)
|
|
273
|
+
try {
|
|
274
|
+
session.close()
|
|
275
|
+
} catch {
|
|
276
|
+
// A session already gone is the outcome we wanted anyway.
|
|
277
|
+
}
|
|
278
|
+
resolve(result)
|
|
279
|
+
}
|
|
280
|
+
let session: ClientHttp2Session
|
|
281
|
+
try {
|
|
282
|
+
session = this.#dial(authority)
|
|
283
|
+
} catch (error) {
|
|
284
|
+
resolve({ ok: false, reason: `connect failed: ${String(error)}` })
|
|
285
|
+
return
|
|
286
|
+
}
|
|
287
|
+
timer = setTimeout(() => { finish({ ok: false, reason: `no answer within ${this.#timeoutMs} ms` }) }, this.#timeoutMs)
|
|
288
|
+
timer.unref?.()
|
|
289
|
+
session.on('error', (error: Error) => { finish({ ok: false, reason: String(error) }) })
|
|
290
|
+
session.on('close', () => { finish({ ok: false, reason: 'the connection closed before APNs answered' }) })
|
|
291
|
+
let status = 0
|
|
292
|
+
let text = ''
|
|
293
|
+
try {
|
|
294
|
+
const stream = session.request({ ':method': 'POST', ':path': spec.path, ...spec.headers })
|
|
295
|
+
stream.setEncoding('utf8')
|
|
296
|
+
stream.on('response', (headers) => { status = Number(headers[':status'] ?? 0) })
|
|
297
|
+
stream.on('data', (chunk: string) => { text += chunk })
|
|
298
|
+
stream.on('error', (error: Error) => { finish({ ok: false, reason: String(error) }) })
|
|
299
|
+
stream.on('end', () => {
|
|
300
|
+
finish(status === 200 ? { ok: true, status } : { ok: false, status, reason: apnsReason(text) })
|
|
301
|
+
})
|
|
302
|
+
stream.end(body)
|
|
303
|
+
} catch (error) {
|
|
304
|
+
finish({ ok: false, reason: `request failed: ${String(error)}` })
|
|
305
|
+
}
|
|
306
|
+
})
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** @returns the cached provider token, minting one when it has aged out. */
|
|
310
|
+
async #providerToken(): Promise<string> {
|
|
311
|
+
const now = this.#now()
|
|
312
|
+
if (this.#token !== undefined && now - this.#token.mintedAt < APNS_TOKEN_TTL_MS) return this.#token.value
|
|
313
|
+
this.#key ??= readFile(this.#config.keyFile, 'utf8').then(pem => createPrivateKey({ key: pem, format: 'pem' }))
|
|
314
|
+
const key = await this.#key
|
|
315
|
+
const value = es256Jwt({ key, keyId: this.#config.keyId, teamId: this.#config.teamId, issuedAt: now })
|
|
316
|
+
this.#token = { value, mintedAt: now }
|
|
317
|
+
this.#log(`minted an APNs provider token for key ${this.#config.keyId}`)
|
|
318
|
+
return value
|
|
319
|
+
}
|
|
320
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The read-only ledger fallback of the squads channel.
|
|
3
|
+
*
|
|
4
|
+
* `dsh-agents` is the only writer of this document, and this bridge reads the
|
|
5
|
+
* same bytes under the same rules: a document of an unknown generation, a
|
|
6
|
+
* revision that is not a whole number, or a team/run set this build cannot read
|
|
7
|
+
* is refused rather than repaired. Nothing here writes, locks, creates or
|
|
8
|
+
* quarantines anything — a Host whose loopback route cannot answer still shows
|
|
9
|
+
* the user's own definitions, and never edits them from behind the plugin's back.
|
|
10
|
+
*
|
|
11
|
+
* The rows themselves are mapped by `core/squads.ts`, exactly as a loopback
|
|
12
|
+
* answer is: the two paths meet in one mapping, so a fallback body cannot drift
|
|
13
|
+
* from a served one.
|
|
14
|
+
* @module dsh-remote-bridge/host/squads-ledger
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { readFile } from 'node:fs/promises'
|
|
18
|
+
import { join } from 'node:path'
|
|
19
|
+
import { CODE_SQUADS_UNAVAILABLE } from '../core/protocol.ts'
|
|
20
|
+
import { SquadRefusal } from '../core/squads.ts'
|
|
21
|
+
|
|
22
|
+
/** Ledger file name inside the plugin's own directory. */
|
|
23
|
+
export const SQUAD_LEDGER_FILE = 'ledger.json'
|
|
24
|
+
|
|
25
|
+
/** Owner lock beside it; it is what carries the owning pid. */
|
|
26
|
+
export const SQUAD_LEDGER_LOCK_FILE = 'ledger.json.lock'
|
|
27
|
+
|
|
28
|
+
/** The one ledger generation this build reads. */
|
|
29
|
+
export const SQUAD_LEDGER_SCHEMA_VERSION = 1
|
|
30
|
+
|
|
31
|
+
/** One state document read off the ledger, in the plugin's own key names. */
|
|
32
|
+
export interface SquadLedgerDocument {
|
|
33
|
+
teams: readonly unknown[]
|
|
34
|
+
runs: readonly unknown[]
|
|
35
|
+
host: { ownerPid?: number }
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The plugin's own code for a ledger this build cannot read. */
|
|
39
|
+
const CODE_LEDGER_CORRUPT = 'ledger-corrupt'
|
|
40
|
+
|
|
41
|
+
function record(value: unknown): Record<string, unknown> | undefined {
|
|
42
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value) ? value as Record<string, unknown> : undefined
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function messageOf(error: unknown): string {
|
|
46
|
+
return error instanceof Error ? error.message : String(error)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function corrupt(reason: string): SquadRefusal {
|
|
50
|
+
return new SquadRefusal(CODE_LEDGER_CORRUPT, 'the dsh-agents ledger ' + reason)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Read the owning pid from the ledger lock.
|
|
55
|
+
*
|
|
56
|
+
* The lock is the plugin's own record of who is writing; a missing or unreadable
|
|
57
|
+
* one leaves the pid absent, because a channel with no owner to name is not a
|
|
58
|
+
* failure of the read.
|
|
59
|
+
* @param directory - the plugin-owned directory.
|
|
60
|
+
* @returns `{ownerPid}` when the lock names one, or an empty object.
|
|
61
|
+
*/
|
|
62
|
+
async function ownerOf(directory: string): Promise<{ ownerPid?: number }> {
|
|
63
|
+
try {
|
|
64
|
+
const parsed = record(JSON.parse(await readFile(join(directory, SQUAD_LEDGER_LOCK_FILE), 'utf8')))
|
|
65
|
+
const pid = parsed?.pid
|
|
66
|
+
return typeof pid === 'number' && Number.isInteger(pid) && pid > 0 ? { ownerPid: pid } : {}
|
|
67
|
+
} catch {
|
|
68
|
+
return {}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Read the ledger document without touching it.
|
|
74
|
+
* @param directory - the plugin-owned directory (`$DSH_HOME/dsh-agents`).
|
|
75
|
+
* @returns the definitions and runs as stored, plus the owning pid when the lock
|
|
76
|
+
* names one.
|
|
77
|
+
* @throws {SquadRefusal} `squads-unavailable` when there is no readable ledger, or
|
|
78
|
+
* the plugin's own `ledger-corrupt` when the bytes are not the document this
|
|
79
|
+
* build reads.
|
|
80
|
+
*/
|
|
81
|
+
export async function readSquadLedger(directory: string): Promise<SquadLedgerDocument> {
|
|
82
|
+
const file = join(directory, SQUAD_LEDGER_FILE)
|
|
83
|
+
let text: string
|
|
84
|
+
try {
|
|
85
|
+
text = await readFile(file, 'utf8')
|
|
86
|
+
} catch (error) {
|
|
87
|
+
throw new SquadRefusal(CODE_SQUADS_UNAVAILABLE, 'this host serves no dsh-agents squad domain over loopback and holds no ledger at ' + file + ': ' + messageOf(error))
|
|
88
|
+
}
|
|
89
|
+
let parsed: unknown
|
|
90
|
+
try {
|
|
91
|
+
parsed = JSON.parse(text)
|
|
92
|
+
} catch (error) {
|
|
93
|
+
throw corrupt('at ' + file + ' is not valid JSON: ' + messageOf(error))
|
|
94
|
+
}
|
|
95
|
+
const document = record(parsed)
|
|
96
|
+
if (document === undefined) throw corrupt('is not a JSON object')
|
|
97
|
+
if (document.schemaVersion !== SQUAD_LEDGER_SCHEMA_VERSION) {
|
|
98
|
+
throw corrupt('declares generation ' + String(document.schemaVersion) + ', and this build reads ' + String(SQUAD_LEDGER_SCHEMA_VERSION))
|
|
99
|
+
}
|
|
100
|
+
if (typeof document.revision !== 'number' || !Number.isInteger(document.revision) || document.revision < 0) {
|
|
101
|
+
throw corrupt('carries no usable revision')
|
|
102
|
+
}
|
|
103
|
+
if (!Array.isArray(document.teams) || !Array.isArray(document.runs)) throw corrupt('holds no team/run arrays')
|
|
104
|
+
return { teams: document.teams, runs: document.runs, host: await ownerOf(directory) }
|
|
105
|
+
}
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The squad domain as this Host reaches it: the `dsh-agents` HTTP routes over
|
|
3
|
+
* this machine's own loopback origin, with its ledger as a read-only fallback.
|
|
4
|
+
*
|
|
5
|
+
* The plugin's routes are the preferred source because they are the live one: a
|
|
6
|
+
* definition the user just saved and a run that is still settling are both in the
|
|
7
|
+
* plugin's own process state, while the ledger is the last committed write. So the
|
|
8
|
+
* read is `GET /dsh-agents/api/state` and the two launches are POSTs, all
|
|
9
|
+
* addressed at the origin `webServer` already serves and all carrying the `origin`
|
|
10
|
+
* header the plugin's browser fence reads as its same-origin signal.
|
|
11
|
+
*
|
|
12
|
+
* A loopback call that cannot connect at all — nothing bound, a refused
|
|
13
|
+
* connection, or a deadline — is what makes the fallback necessary: the
|
|
14
|
+
* definitions are then read from the plugin's ledger, read-only, and the two run
|
|
15
|
+
* commands fail closed with `squads-run-unavailable` instead of answering a run
|
|
16
|
+
* that never started. An answer of any status is NOT a fallback: it is the plugin
|
|
17
|
+
* speaking, and its refusal crosses with its own code.
|
|
18
|
+
* @module dsh-remote-bridge/host/squads
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { CODE_SQUADS_RUN_UNAVAILABLE, CODE_SQUADS_UNAVAILABLE } from '../core/protocol.ts'
|
|
22
|
+
import { SquadRefusal, type SquadMemberRunRequest, type SquadRunRequest, type SquadTransport } from '../core/squads.ts'
|
|
23
|
+
import { readSquadLedger } from './squads-ledger.ts'
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The three routes this channel drives, restated from the plugin's own
|
|
27
|
+
* `DSH_AGENTS_ROUTE_PATHS`. They are spelled here rather than imported: this
|
|
28
|
+
* package depends on no other plugin, so a frozen path is the only thing that can
|
|
29
|
+
* cross between them.
|
|
30
|
+
*/
|
|
31
|
+
export const SQUADS_STATE_PATH = '/dsh-agents/api/state'
|
|
32
|
+
export const SQUADS_RUN_MEMBER_PATH = '/dsh-agents/api/run'
|
|
33
|
+
export const SQUADS_RUN_SQUAD_PATH = '/dsh-agents/api/squad/run'
|
|
34
|
+
|
|
35
|
+
/** Deadline behind one loopback read: the plugin answers a state read from memory. */
|
|
36
|
+
export const SQUADS_LOOPBACK_TIMEOUT_MS = 5_000
|
|
37
|
+
/**
|
|
38
|
+
* Deadline behind one launch. A launch composes a session, restores it when it is
|
|
39
|
+
* cold and may queue a first message, so it is allowed far longer than a read; the
|
|
40
|
+
* bound exists to keep one stuck call from holding a connection open, not to time
|
|
41
|
+
* the plugin's work.
|
|
42
|
+
*/
|
|
43
|
+
export const SQUADS_RUN_TIMEOUT_MS = 60_000
|
|
44
|
+
|
|
45
|
+
/** What one loopback call produced: the host's answer, or no connection at all. */
|
|
46
|
+
type LoopbackOutcome =
|
|
47
|
+
| { readonly kind: 'answer'; readonly status: number; readonly body: unknown }
|
|
48
|
+
| { readonly kind: 'unreachable'; readonly reason: string }
|
|
49
|
+
|
|
50
|
+
/** The answer half of {@link LoopbackOutcome}. */
|
|
51
|
+
type LoopbackAnswer = Extract<LoopbackOutcome, { kind: 'answer' }>
|
|
52
|
+
|
|
53
|
+
/** Construction options; the origin and the ledger directory are resolved per call. */
|
|
54
|
+
export interface LoopbackSquadsOptions {
|
|
55
|
+
/** The origin this host's own web server listens on, or undefined before it binds. */
|
|
56
|
+
readonly origin: () => string | undefined
|
|
57
|
+
/** The plugin-owned directory `dsh-agents` keeps its ledger in. */
|
|
58
|
+
readonly ledgerDirectory: () => string
|
|
59
|
+
/** Outbound call seam; the production default is the process's own fetch. */
|
|
60
|
+
readonly fetch?: typeof fetch
|
|
61
|
+
/** Deadline behind one read; the default is {@link SQUADS_LOOPBACK_TIMEOUT_MS}. */
|
|
62
|
+
readonly timeoutMs?: number
|
|
63
|
+
/** Deadline behind one launch; the default is {@link SQUADS_RUN_TIMEOUT_MS}. */
|
|
64
|
+
readonly runTimeoutMs?: number
|
|
65
|
+
readonly log: (message: string) => void
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function record(value: unknown): Record<string, unknown> | undefined {
|
|
69
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value) ? value as Record<string, unknown> : undefined
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function messageOf(error: unknown): string {
|
|
73
|
+
return error instanceof Error ? error.message : String(error)
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function parseJson(text: string): unknown {
|
|
77
|
+
try {
|
|
78
|
+
return JSON.parse(text)
|
|
79
|
+
} catch {
|
|
80
|
+
return undefined
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The squad domain over loopback, with the ledger as its read-only fallback. */
|
|
85
|
+
export class LoopbackSquads implements SquadTransport {
|
|
86
|
+
readonly #options: LoopbackSquadsOptions
|
|
87
|
+
|
|
88
|
+
constructor(options: LoopbackSquadsOptions) {
|
|
89
|
+
this.#options = options
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Read the definitions and runs.
|
|
94
|
+
*
|
|
95
|
+
* A loopback call that connects answers for the domain, its refusals included.
|
|
96
|
+
* A call that cannot connect at all falls back to the ledger, and a ledger that
|
|
97
|
+
* is missing or unreadable refuses the read rather than answering an empty
|
|
98
|
+
* board.
|
|
99
|
+
*/
|
|
100
|
+
async state(): Promise<unknown> {
|
|
101
|
+
const call = await this.#request('GET', SQUADS_STATE_PATH)
|
|
102
|
+
if (call.kind === 'unreachable') {
|
|
103
|
+
this.#options.log('squad state read fell back to the ledger: ' + call.reason)
|
|
104
|
+
return await readSquadLedger(this.#options.ledgerDirectory())
|
|
105
|
+
}
|
|
106
|
+
return this.#bodyOf(call, SQUADS_STATE_PATH)
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Launch one member session through the plugin's own run route.
|
|
111
|
+
* @param request - the squad, the member and the optional first message.
|
|
112
|
+
*/
|
|
113
|
+
async runMember(request: SquadMemberRunRequest): Promise<unknown> {
|
|
114
|
+
const call = await this.#request('POST', SQUADS_RUN_MEMBER_PATH, {
|
|
115
|
+
teamId: request.squadId,
|
|
116
|
+
memberId: request.memberId,
|
|
117
|
+
...(request.firstMessage === undefined ? {} : { firstMessage: request.firstMessage }),
|
|
118
|
+
}, this.#options.runTimeoutMs ?? SQUADS_RUN_TIMEOUT_MS)
|
|
119
|
+
if (call.kind === 'unreachable') throw this.#runUnavailable(call.reason)
|
|
120
|
+
return this.#bodyOf(call, SQUADS_RUN_MEMBER_PATH)
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Launch the Lead session of one whole squad through the plugin's own squad run
|
|
125
|
+
* route.
|
|
126
|
+
* @param request - the squad and the optional goal its Lead is given.
|
|
127
|
+
*/
|
|
128
|
+
async runSquad(request: SquadRunRequest): Promise<unknown> {
|
|
129
|
+
const call = await this.#request('POST', SQUADS_RUN_SQUAD_PATH, {
|
|
130
|
+
teamId: request.squadId,
|
|
131
|
+
...(request.goal === undefined ? {} : { goal: request.goal }),
|
|
132
|
+
}, this.#options.runTimeoutMs ?? SQUADS_RUN_TIMEOUT_MS)
|
|
133
|
+
if (call.kind === 'unreachable') throw this.#runUnavailable(call.reason)
|
|
134
|
+
return this.#bodyOf(call, SQUADS_RUN_SQUAD_PATH)
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* The refusal behind a launch this host cannot perform.
|
|
139
|
+
* @param reason - why the loopback call produced no connection.
|
|
140
|
+
*/
|
|
141
|
+
#runUnavailable(reason: string): SquadRefusal {
|
|
142
|
+
return new SquadRefusal(CODE_SQUADS_RUN_UNAVAILABLE, 'this host reached no dsh-agents run route over loopback (' + reason + '), and the read-only ledger cannot launch a session')
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Read the body of an answer, or refuse with the code the plugin wrote.
|
|
147
|
+
*
|
|
148
|
+
* A non-2xx body carrying the plugin's `{ok:false, code, error}` crosses with
|
|
149
|
+
* that code and that sentence; any other status means this host does not serve
|
|
150
|
+
* the route at all, which is the one refusal this bridge names itself.
|
|
151
|
+
* @param answer - the connected answer.
|
|
152
|
+
* @param path - the route the answer came from, named in the refusal.
|
|
153
|
+
*/
|
|
154
|
+
#bodyOf(answer: LoopbackAnswer, path: string): Record<string, unknown> {
|
|
155
|
+
const body = record(answer.body)
|
|
156
|
+
if (answer.status >= 200 && answer.status < 300) {
|
|
157
|
+
if (body === undefined) {
|
|
158
|
+
throw new SquadRefusal(CODE_SQUADS_UNAVAILABLE, 'the dsh-agents route ' + path + ' answered a body this bridge cannot read')
|
|
159
|
+
}
|
|
160
|
+
return body
|
|
161
|
+
}
|
|
162
|
+
if (body?.ok === false && typeof body.code === 'string') {
|
|
163
|
+
const text = typeof body.error === 'string' && body.error !== '' ? body.error : 'the dsh-agents host refused ' + path
|
|
164
|
+
throw new SquadRefusal(body.code, text)
|
|
165
|
+
}
|
|
166
|
+
throw new SquadRefusal(CODE_SQUADS_UNAVAILABLE, 'this host does not serve ' + path + ': it answered ' + String(answer.status))
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* One loopback call against this host's own origin.
|
|
171
|
+
* @param method - the route's own method.
|
|
172
|
+
* @param path - the route's exact path.
|
|
173
|
+
* @param body - the JSON body, for the two POST routes.
|
|
174
|
+
* @param timeoutMs - the deadline behind this one call.
|
|
175
|
+
* @returns the answer, or the reason no connection was made.
|
|
176
|
+
*/
|
|
177
|
+
async #request(
|
|
178
|
+
method: 'GET' | 'POST',
|
|
179
|
+
path: string,
|
|
180
|
+
body?: Readonly<Record<string, unknown>>,
|
|
181
|
+
timeoutMs: number = this.#options.timeoutMs ?? SQUADS_LOOPBACK_TIMEOUT_MS,
|
|
182
|
+
): Promise<LoopbackOutcome> {
|
|
183
|
+
const origin = this.#options.origin()
|
|
184
|
+
if (origin === undefined) return { kind: 'unreachable', reason: 'this host has bound no web server port' }
|
|
185
|
+
const call = this.#options.fetch ?? fetch
|
|
186
|
+
try {
|
|
187
|
+
const response = await call(origin + path, {
|
|
188
|
+
method,
|
|
189
|
+
// The plugin's fence admits this machine's own browser only: the socket has
|
|
190
|
+
// to be loopback and a same-origin signal has to be present, and an origin
|
|
191
|
+
// header naming this host is that signal.
|
|
192
|
+
headers: {
|
|
193
|
+
origin,
|
|
194
|
+
accept: 'application/json',
|
|
195
|
+
...(body === undefined ? {} : { 'content-type': 'application/json' }),
|
|
196
|
+
},
|
|
197
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
198
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
199
|
+
})
|
|
200
|
+
const text = await response.text()
|
|
201
|
+
return { kind: 'answer', status: response.status, body: parseJson(text) }
|
|
202
|
+
} catch (error) {
|
|
203
|
+
return { kind: 'unreachable', reason: messageOf(error) }
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|