@linxin666/dsh-remote-bridge 0.4.7 → 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.
Files changed (78) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +93 -26
  3. package/README.zh.md +91 -26
  4. package/icon.svg +3 -0
  5. package/lib/client.js +274 -253
  6. package/lib/client.js.map +1 -1
  7. package/lib/index.js +8891 -2433
  8. package/lib/types/client/PairEntry.d.ts +2 -2
  9. package/lib/types/client/PairPanel.d.ts +10 -2
  10. package/lib/types/client/icons.d.ts +5 -13
  11. package/lib/types/client/locales.d.ts +10 -14
  12. package/lib/types/client/semantic.d.ts +9 -5
  13. package/lib/types/core/approvals.d.ts +24 -0
  14. package/lib/types/core/commands.d.ts +59 -0
  15. package/lib/types/core/connection.d.ts +124 -5
  16. package/lib/types/core/delta.d.ts +101 -0
  17. package/lib/types/core/devices.d.ts +98 -2
  18. package/lib/types/core/dsh-frames.d.ts +155 -4
  19. package/lib/types/core/envelope.d.ts +34 -0
  20. package/lib/types/core/extension.d.ts +144 -0
  21. package/lib/types/core/hub.d.ts +96 -20
  22. package/lib/types/core/jobs.d.ts +204 -0
  23. package/lib/types/core/liveactivity.d.ts +324 -0
  24. package/lib/types/core/protocol.d.ts +491 -2
  25. package/lib/types/core/push.d.ts +178 -0
  26. package/lib/types/core/questions.d.ts +109 -9
  27. package/lib/types/core/session-meta.d.ts +55 -1
  28. package/lib/types/core/squads.d.ts +130 -0
  29. package/lib/types/core/usage-stats.d.ts +160 -0
  30. package/lib/types/core/usage.d.ts +294 -0
  31. package/lib/types/core/wire.d.ts +1 -1
  32. package/lib/types/core/ws-frames.d.ts +11 -0
  33. package/lib/types/host/apns.d.ts +151 -0
  34. package/lib/types/host/squads-ledger.d.ts +39 -0
  35. package/lib/types/host/squads.d.ts +77 -0
  36. package/lib/types/host/usage-stats.d.ts +75 -0
  37. package/lib/types/host/watchers.d.ts +88 -0
  38. package/lib/types/host/websocket.d.ts +8 -1
  39. package/lib/types/index.d.ts +34 -3
  40. package/lib/types/mount-once.d.ts +55 -0
  41. package/locale/en.json +6 -0
  42. package/locale/ru.json +6 -0
  43. package/locale/zh.json +6 -0
  44. package/package.json +20 -14
  45. package/src/client/PairEntry.tsx +58 -31
  46. package/src/client/PairPanel.tsx +181 -97
  47. package/src/client/icons.tsx +17 -60
  48. package/src/client/locales.ts +15 -23
  49. package/src/client/panel.module.css +239 -186
  50. package/src/client/semantic.ts +10 -6
  51. package/src/core/approvals.ts +32 -1
  52. package/src/core/commands.ts +95 -0
  53. package/src/core/connection.ts +1483 -31
  54. package/src/core/delta.ts +204 -0
  55. package/src/core/devices.ts +221 -3
  56. package/src/core/dsh-frames.ts +365 -8
  57. package/src/core/envelope.ts +46 -0
  58. package/src/core/extension.ts +197 -0
  59. package/src/core/hub.ts +441 -49
  60. package/src/core/jobs.ts +372 -0
  61. package/src/core/liveactivity.ts +833 -0
  62. package/src/core/protocol.ts +556 -2
  63. package/src/core/push.ts +354 -0
  64. package/src/core/questions.ts +264 -17
  65. package/src/core/session-meta.ts +73 -1
  66. package/src/core/squads.ts +345 -0
  67. package/src/core/usage-stats.ts +424 -0
  68. package/src/core/usage.ts +937 -0
  69. package/src/core/wire.ts +13 -1
  70. package/src/core/ws-frames.ts +14 -0
  71. package/src/host/apns.ts +320 -0
  72. package/src/host/squads-ledger.ts +105 -0
  73. package/src/host/squads.ts +206 -0
  74. package/src/host/usage-stats.ts +155 -0
  75. package/src/host/watchers.ts +272 -0
  76. package/src/host/websocket.ts +37 -3
  77. package/src/index.ts +310 -9
  78. package/src/mount-once.ts +142 -0
@@ -0,0 +1,204 @@
1
+ /**
2
+ * Per-connection delta windows: what a client that already holds a copy of a
3
+ * whole set is sent instead of the whole set again.
4
+ *
5
+ * The difference is computed here, in the bridge, because the bridge is the
6
+ * only place that holds what the host said last — the host itself is asked for
7
+ * its complete answer every time and never learns that a client is caching one.
8
+ * That is the whole point of this module: the saving is bytes on the wire
9
+ * between the bridge and the phone, not a change to any host API.
10
+ *
11
+ * Three rules live in this file and nowhere else, so the roster and the board
12
+ * cannot disagree about them:
13
+ *
14
+ * - a delta is only diffed against the exact set this window last sent, and
15
+ * only for a token this window itself issued; anything else answers a reset,
16
+ * because a wrong base is a wrong answer;
17
+ * - a change is a change of the serialised row, not of a timestamp — the host's
18
+ * `updatedAt` is not a change signal for every field, and a row whose body is
19
+ * byte-identical has not changed;
20
+ * - a delta that is not clearly smaller than the reset body is not worth
21
+ * sending: past {@link DELTA_CHANGED_RATIO} of the rows, the answer is a reset.
22
+ * @module dsh-remote-bridge/core/delta
23
+ */
24
+
25
+ import { randomBytes } from 'node:crypto'
26
+
27
+ /** Largest roster one connection's delta window retains. */
28
+ export const ROSTER_DELTA_MAX_ROWS = 5000
29
+ /** Largest board one connection's delta window retains. */
30
+ export const BOARD_DELTA_MAX_ROWS = 2000
31
+
32
+ /**
33
+ * Share of the current set that may change before a reset is the cheaper
34
+ * answer. Bytes, not cleverness: past this point the delta carries most of the
35
+ * body already and the extra keys only make it bigger.
36
+ */
37
+ export const DELTA_CHANGED_RATIO = 0.6
38
+
39
+ /**
40
+ * Identity of this bridge process, minted once at load.
41
+ *
42
+ * Part of every token, so a token minted by an earlier boot can never be
43
+ * replayed into a delta against a set that boot never sent. It is not a secret
44
+ * on its own — the per-window secret beside it is what makes a token
45
+ * unguessable, and the exact comparison below is what actually decides.
46
+ */
47
+ const BOOT_ID = randomBytes(8).toString('hex')
48
+
49
+ /** The one row field every set this module diffs is keyed by. */
50
+ export interface DeltaRow {
51
+ readonly id: string
52
+ }
53
+
54
+ /** One window's answer, before a method wraps it in its own wire shape. */
55
+ export type DeltaAnswer<T> =
56
+ | {
57
+ readonly mode: 'reset'
58
+ /** Opaque token to send back as `since`; `""` when nothing was retained. */
59
+ readonly token: string
60
+ /** The whole set, exactly as the method always published it. */
61
+ readonly rows: readonly T[]
62
+ }
63
+ | {
64
+ readonly mode: 'delta'
65
+ readonly token: string
66
+ /** Every row that is new or whose body differs from the last one sent. */
67
+ readonly changed: readonly T[]
68
+ /** Every id this window sent before and the host no longer names. */
69
+ readonly removed: readonly string[]
70
+ }
71
+
72
+ /** Cap on the set one window may retain. */
73
+ export interface DeltaLimits {
74
+ readonly maxRows: number
75
+ }
76
+
77
+ /**
78
+ * One connection's view of one set: the rows it last sent, and the token that
79
+ * set was announced under.
80
+ *
81
+ * A window is created lazily by whoever needs it and lives exactly as long as
82
+ * the connection that owns it (see {@link RemoteBridgeDeltas}), so two
83
+ * connections never share a base and a dropped connection leaks nothing.
84
+ */
85
+ export class DeltaWindow<T extends DeltaRow> {
86
+ readonly #maxRows: number
87
+ /**
88
+ * This window's own secret: what makes one connection's token useless to
89
+ * another, and what a client cannot derive from a token it was given.
90
+ */
91
+ readonly #secret = randomBytes(8).toString('hex')
92
+ readonly #sent = new Map<string, string>()
93
+ #revision = 0
94
+ #token: string | undefined
95
+
96
+ constructor(limits: DeltaLimits) {
97
+ this.#maxRows = limits.maxRows
98
+ }
99
+
100
+ /**
101
+ * Answer one call over the current full set.
102
+ * @param rows - the complete set, exactly as the host answered it this time.
103
+ * @param since - the opaque token the client sent, if it sent one.
104
+ * @returns a reset carrying every row, or a delta against the last set sent.
105
+ */
106
+ answer(rows: readonly T[], since: string | undefined): DeltaAnswer<T> {
107
+ const current = new Map<string, string>()
108
+ for (const row of rows) current.set(row.id, JSON.stringify(row))
109
+ // A set past the cap is not retained at all: one connection must never pin
110
+ // an unbounded copy of the host's state, and a reset is answered instead of
111
+ // pretending a base exists.
112
+ if (current.size > this.#maxRows) return this.#forget(rows)
113
+ // The only base a delta may be diffed against is the set this window sent
114
+ // last, named by the token it handed out with it. A token from another
115
+ // connection, another boot, an older answer of this one, or garbage is not
116
+ // that base.
117
+ if (since === undefined || this.#token === undefined || since !== this.#token) {
118
+ return this.#reset(rows, current)
119
+ }
120
+ const changed: T[] = []
121
+ for (const row of rows) if (this.#sent.get(row.id) !== current.get(row.id)) changed.push(row)
122
+ const removed: string[] = []
123
+ for (const id of this.#sent.keys()) if (!current.has(id)) removed.push(id)
124
+ // Removals are not counted against the ratio: a removal costs one id on the
125
+ // wire, not a row, so a wave of deletions is exactly what a delta is for.
126
+ if (changed.length > DELTA_CHANGED_RATIO * rows.length) return this.#reset(rows, current)
127
+ this.#sent.clear()
128
+ for (const [id, body] of current) this.#sent.set(id, body)
129
+ return { mode: 'delta', token: this.#nextToken(), changed, removed }
130
+ }
131
+
132
+ /**
133
+ * Answer the whole set and keep it as the next base.
134
+ * @param rows - the complete set.
135
+ * @param current - the set, serialised, to retain.
136
+ */
137
+ #reset(rows: readonly T[], current: Map<string, string>): DeltaAnswer<T> {
138
+ this.#sent.clear()
139
+ for (const [id, body] of current) this.#sent.set(id, body)
140
+ return { mode: 'reset', token: this.#nextToken(), rows }
141
+ }
142
+
143
+ /**
144
+ * Answer the whole set and retain nothing.
145
+ *
146
+ * The empty token says so: this answer cannot be continued from, because
147
+ * there is no copy of it here to diff against. A client that sends it back is
148
+ * answered a reset, which is the truth rather than a wrong delta.
149
+ * @param rows - the complete set.
150
+ */
151
+ #forget(rows: readonly T[]): DeltaAnswer<T> {
152
+ this.#sent.clear()
153
+ this.#token = undefined
154
+ this.#revision += 1
155
+ return { mode: 'reset', token: '', rows }
156
+ }
157
+
158
+ /** @returns the token for the set just retained, bumping the window's revision. */
159
+ #nextToken(): string {
160
+ this.#revision += 1
161
+ this.#token = `d1.${BOOT_ID}.${this.#secret}.${this.#revision}`
162
+ return this.#token
163
+ }
164
+ }
165
+
166
+ /**
167
+ * The delta windows one connection owns, by the name its owner keys them with.
168
+ *
169
+ * Held on the connection, so the state is released exactly when the connection
170
+ * is: there is no second registry to expire, and no connection's window can be
171
+ * read by another.
172
+ */
173
+ export class RemoteBridgeDeltas {
174
+ readonly #windows = new Map<string, DeltaWindow<DeltaRow>>()
175
+
176
+ /**
177
+ * @param key - the window's name within this connection; one set, one key.
178
+ * @param limits - the cap this window retains.
179
+ * @returns the window, created on first use.
180
+ */
181
+ window<T extends DeltaRow>(key: string, limits: DeltaLimits): DeltaWindow<T> {
182
+ const known = this.#windows.get(key)
183
+ if (known !== undefined) return known as DeltaWindow<T>
184
+ const created = new DeltaWindow<T>(limits)
185
+ this.#windows.set(key, created as unknown as DeltaWindow<DeltaRow>)
186
+ return created
187
+ }
188
+
189
+ /**
190
+ * @param key - one window's name.
191
+ *
192
+ * Drops that window and the set it retained, so its token names nothing and
193
+ * the next call answers a reset. Used when a connection stops being served
194
+ * increments at all, which must cost it no memory either.
195
+ */
196
+ drop(key: string): void {
197
+ this.#windows.delete(key)
198
+ }
199
+
200
+ /** Drop every window: called when the owning connection is torn down. */
201
+ clear(): void {
202
+ this.#windows.clear()
203
+ }
204
+ }
@@ -20,8 +20,61 @@ import { base64UrlEncode, constantTimeEqualText, fingerprintOfSpki, isP256Spki,
20
20
  export const DEVICE_TOKEN_BYTES = 32
21
21
  /** Entropy of one device id. */
22
22
  export const DEVICE_ID_BYTES = 12
23
- /** On-disk schema version of the roster file. */
24
- export const ROSTER_VERSION = 1
23
+ /**
24
+ * On-disk schema version of the roster file.
25
+ *
26
+ * 1 carried the six identity fields only; 2 adds the optional `push` block per
27
+ * row (§28). The difference is additive, so a version-1 file reads as-is: no row
28
+ * loses a field, every paired phone stays paired, and the file is rewritten as
29
+ * version 2 the next time anything is written. The reader therefore accepts any
30
+ * version whose row table validates rather than quarantining a file it merely
31
+ * does not recognise — a downgrade must never un-pair every phone.
32
+ */
33
+ export const ROSTER_VERSION = 2
34
+
35
+ /** The APNs environments a device may register for. */
36
+ export type PushEnvironment = 'sandbox' | 'production'
37
+
38
+ /** One Live Activity push token, with the session the card belongs to. */
39
+ export interface PushLiveActivityToken {
40
+ readonly activityId: string
41
+ readonly token: string
42
+ /**
43
+ * The session this card belongs to (§29.9).
44
+ *
45
+ * A card is about one session, and a token without this field cannot be
46
+ * addressed at all: this bridge has nothing to put on it. Absent is therefore
47
+ * "never pushed to", not "pushed to with whatever is at hand" — the other
48
+ * reading would put one session's state on another session's lock screen.
49
+ */
50
+ readonly sessionId?: string
51
+ }
52
+
53
+ /**
54
+ * What one device registered so this bridge can notify it.
55
+ *
56
+ * Stored beside the device's identity in the same row: it is a fact about that
57
+ * device, so it disappears with the row when the device is revoked and it never
58
+ * becomes a second identity. Nothing here is a secret of the bridge's — an APNs
59
+ * token is the phone's, and holding it grants nothing without the signing key,
60
+ * which never touches this file.
61
+ */
62
+ export interface PushRegistration {
63
+ /** APNs device token, as the hex string the system handed the app. */
64
+ readonly deviceToken: string
65
+ readonly environment: PushEnvironment
66
+ /** The app's bundle id, used verbatim as `apns-topic`. */
67
+ readonly bundle: string
68
+ readonly locale?: string
69
+ readonly liveActivityTokens?: readonly PushLiveActivityToken[]
70
+ readonly registeredAt: number
71
+ }
72
+
73
+ /** One device a notification can be addressed to. */
74
+ export interface PushTargetView {
75
+ readonly deviceId: string
76
+ readonly push: PushRegistration
77
+ }
25
78
 
26
79
  /** One paired device as the bridge keeps it. */
27
80
  export interface DeviceRecord {
@@ -32,6 +85,12 @@ export interface DeviceRecord {
32
85
  readonly fingerprint: string
33
86
  readonly createdAt: number
34
87
  readonly lastSeenAt: number
88
+ /**
89
+ * The device's APNs registration, absent until it calls `push.register`.
90
+ * A row without it is a paired phone that asks for no notification, which is
91
+ * every phone that predates the channel.
92
+ */
93
+ readonly push?: PushRegistration
35
94
  }
36
95
 
37
96
  /** A roster row plus the one field that never leaves the file. */
@@ -53,6 +112,59 @@ export interface DeviceRosterOptions {
53
112
  readonly log?: (message: string) => void
54
113
  }
55
114
 
115
+ /**
116
+ * Read one row's `push` block.
117
+ *
118
+ * A malformed block is dropped rather than quarantining the file: the roster is
119
+ * every paired phone, and one unreadable push token is not a reason to un-pair
120
+ * them all. The row keeps its identity and simply asks for no notification.
121
+ * @param value - the raw `push` field of a row.
122
+ * @param log - where a dropped block is reported.
123
+ * @returns the registration, or undefined when there is none to read.
124
+ */
125
+ function pushOf(value: unknown, log: (message: string) => void): PushRegistration | undefined {
126
+ if (value === undefined) return undefined
127
+ if (typeof value !== 'object' || value === null) {
128
+ log('a device row carries an unreadable push block; ignoring it and keeping the row')
129
+ return undefined
130
+ }
131
+ const row = value as Record<string, unknown>
132
+ const environment = row.environment
133
+ if (typeof row.deviceToken !== 'string' || row.deviceToken === ''
134
+ || typeof row.bundle !== 'string' || row.bundle === ''
135
+ || (environment !== 'sandbox' && environment !== 'production')) {
136
+ log('a device row carries an unreadable push block; ignoring it and keeping the row')
137
+ return undefined
138
+ }
139
+ const liveActivityTokens = Array.isArray(row.liveActivityTokens)
140
+ ? row.liveActivityTokens.filter((entry): entry is PushLiveActivityToken => {
141
+ if (typeof entry !== 'object' || entry === null) return false
142
+ const token = entry as Record<string, unknown>
143
+ return typeof token.activityId === 'string' && token.activityId !== ''
144
+ && typeof token.token === 'string' && token.token !== ''
145
+ }).map((entry): PushLiveActivityToken => {
146
+ // A session id this reader cannot trust is dropped rather than repaired: the
147
+ // entry keeps its token and simply names no session, which is the state this
148
+ // bridge never pushes to. One unreadable card is not a reason to un-pair a
149
+ // phone, the same way one unreadable push block is not.
150
+ const raw = (entry as unknown as Record<string, unknown>).sessionId
151
+ return {
152
+ activityId: entry.activityId,
153
+ token: entry.token,
154
+ ...(typeof raw === 'string' && raw !== '' ? { sessionId: raw } : {}),
155
+ }
156
+ })
157
+ : undefined
158
+ return {
159
+ deviceToken: row.deviceToken,
160
+ environment,
161
+ bundle: row.bundle,
162
+ ...(typeof row.locale === 'string' && row.locale !== '' ? { locale: row.locale } : {}),
163
+ ...(liveActivityTokens === undefined ? {} : { liveActivityTokens }),
164
+ registeredAt: typeof row.registeredAt === 'number' ? row.registeredAt : 0,
165
+ }
166
+ }
167
+
56
168
  function isStoredDevice(value: unknown): value is StoredDevice {
57
169
  if (typeof value !== 'object' || value === null) return false
58
170
  const row = value as Record<string, unknown>
@@ -77,6 +189,7 @@ export class DeviceRoster {
77
189
  readonly #log: (message: string) => void
78
190
  readonly #devices = new Map<string, StoredDevice>()
79
191
  #loaded: Promise<void> | undefined
192
+ #writeQueue: Promise<void> = Promise.resolve()
80
193
 
81
194
  constructor(options: DeviceRosterOptions) {
82
195
  this.#file = options.file
@@ -149,6 +262,89 @@ export class DeviceRoster {
149
262
  if (touched !== undefined) await this.#persist()
150
263
  }
151
264
 
265
+ /**
266
+ * Record this device's APNs registration, replacing any it had.
267
+ *
268
+ * Registering twice is what a token rotation looks like from here, so this is
269
+ * a plain overwrite rather than a merge: the newest complete registration is
270
+ * the only one worth sending to, and a half-merged pair of rows would send to
271
+ * a token the phone already retired.
272
+ * @param deviceId - the device that just registered.
273
+ * @param registration - what it registered.
274
+ * @returns false when no such device is paired.
275
+ */
276
+ async registerPush(deviceId: string, registration: PushRegistration): Promise<boolean> {
277
+ for (const [hash, row] of this.#devices) {
278
+ if (row.deviceId !== deviceId) continue
279
+ this.#devices.set(hash, { ...row, push: registration })
280
+ await this.#persist()
281
+ return true
282
+ }
283
+ return false
284
+ }
285
+
286
+ /**
287
+ * Forget one Live Activity token the phone no longer holds.
288
+ *
289
+ * APNs answers 410 (or 400 `BadDeviceToken`) for the token of a card the app
290
+ * already ended, and such a token never works again: the next card arrives as a
291
+ * new activity with a new token through `push.register`, which is a complete
292
+ * replacement of this set. Dropping it here is therefore the whole recovery —
293
+ * retrying would only repeat the same refusal (§29 token lifecycle).
294
+ * @param activityId - the card the token belonged to.
295
+ * @param token - the token APNs refused.
296
+ * @returns whether any row changed.
297
+ */
298
+ async removeLiveActivityToken(activityId: string, token: string): Promise<boolean> {
299
+ for (const [hash, row] of this.#devices) {
300
+ const registration = row.push
301
+ if (registration === undefined) continue
302
+ const held = registration.liveActivityTokens
303
+ if (held === undefined) continue
304
+ const kept = held.filter(entry => !(entry.activityId === activityId && entry.token === token))
305
+ if (kept.length === held.length) continue
306
+ this.#devices.set(hash, { ...row, push: { ...registration, liveActivityTokens: kept } })
307
+ await this.#persist()
308
+ return true
309
+ }
310
+ return false
311
+ }
312
+
313
+ /**
314
+ * Forget one device's notification registration for a token APNs will never
315
+ * accept again.
316
+ *
317
+ * A dead alert token is the whole app install's refusal: the phone was restored,
318
+ * reinstalled, or the token belongs to another environment or bundle, so the
319
+ * Live Activity tokens that same install registered are dead by the same fact
320
+ * and go with it. The next `push.register` — which a live app performs on launch
321
+ * — writes a complete new block. The device itself stays paired: revoking a
322
+ * phone is a roster edit, never something a push refusal may do.
323
+ * @param deviceToken - the token APNs refused.
324
+ * @returns whether any row changed.
325
+ */
326
+ async removePush(deviceToken: string): Promise<boolean> {
327
+ for (const [hash, row] of this.#devices) {
328
+ const registration = row.push
329
+ if (registration === undefined || registration.deviceToken !== deviceToken) continue
330
+ const { tokenHash, deviceId, pubKey, fingerprint, createdAt, lastSeenAt } = row
331
+ this.#devices.set(hash, { tokenHash, deviceId, pubKey, fingerprint, createdAt, lastSeenAt })
332
+ await this.#persist()
333
+ return true
334
+ }
335
+ return false
336
+ }
337
+
338
+ /** @returns every paired device that registered for notifications. */
339
+ pushTargets(): readonly PushTargetView[] {
340
+ const targets: PushTargetView[] = []
341
+ for (const row of this.#devices.values()) {
342
+ if (row.push === undefined) continue
343
+ targets.push({ deviceId: row.deviceId, push: row.push })
344
+ }
345
+ return targets
346
+ }
347
+
152
348
  async #read(): Promise<void> {
153
349
  let text: string
154
350
  try {
@@ -170,7 +366,21 @@ export class DeviceRoster {
170
366
  await this.#quarantine('has no valid device table')
171
367
  return
172
368
  }
173
- for (const row of rows) this.#devices.set(row.tokenHash, row)
369
+ const declared = (parsed as { version?: unknown }).version
370
+ if (typeof declared === 'number' && declared !== ROSTER_VERSION) {
371
+ // Not an error and not a quarantine: the row table above already validated,
372
+ // so an older file is read as the roster it is and written back as the
373
+ // current schema on the next write.
374
+ this.#log(`device roster ${this.#file} is schema ${declared}; reading it as ${ROSTER_VERSION}`)
375
+ }
376
+ for (const row of rows) {
377
+ // The raw block is re-read per row instead of trusted from the guard, so a
378
+ // row that carries an unreadable token keeps its identity and loses only
379
+ // its notification.
380
+ const { push: raw, ...rest } = row as StoredDevice & { readonly push?: unknown }
381
+ const push = pushOf(raw, this.#log)
382
+ this.#devices.set(row.tokenHash, push === undefined ? rest : { ...rest, push })
383
+ }
174
384
  this.#log(`device roster ${this.#file}: ${rows.length} paired device(s)`)
175
385
  }
176
386
 
@@ -188,8 +398,16 @@ export class DeviceRoster {
188
398
  /**
189
399
  * Write the roster atomically: same directory, 0600 from creation, flushed
190
400
  * before the rename so a crash cannot leave a truncated file in place.
401
+ * Writes are serialized per roster so concurrent token retirement cannot race
402
+ * the replacement (Windows rejects overlapping renames).
191
403
  */
192
404
  async #persist(): Promise<void> {
405
+ const pending = this.#writeQueue.then(() => this.#write())
406
+ this.#writeQueue = pending.catch(() => undefined)
407
+ return pending
408
+ }
409
+
410
+ async #write(): Promise<void> {
193
411
  const directory = dirname(this.#file)
194
412
  await mkdir(directory, { recursive: true, mode: 0o700 })
195
413
  const payload = JSON.stringify({ version: ROSTER_VERSION, devices: [...this.#devices.values()] }, null, 2)