@witbitz/sdk 4.3.0 → 4.5.0

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 (112) hide show
  1. package/README.md +2 -2
  2. package/a2aCore.js +41 -5
  3. package/accountErase.js +15 -4
  4. package/accountIndexDoc.js +24 -7
  5. package/accountRecord.js +6 -2
  6. package/accountStores.js +21 -5
  7. package/acctV2App.js +111 -12
  8. package/acctV2Client.js +11 -1
  9. package/acctV2UiCore.js +27 -7
  10. package/agentDoorTools.js +28 -0
  11. package/awsKey.js +3 -1
  12. package/backupRecord.js +3 -0
  13. package/chatLock.js +16 -0
  14. package/cloudDevicePins.js +2 -2
  15. package/codeAttachments.js +101 -0
  16. package/codeCache.js +173 -0
  17. package/codeCloud.js +2 -2
  18. package/codeComputers.js +9 -0
  19. package/codeFolders.js +116 -0
  20. package/codeHistory.js +76 -0
  21. package/codeLanguage.js +54 -0
  22. package/codeModes.js +2 -0
  23. package/codeProgress.js +54 -0
  24. package/codeSent.js +109 -0
  25. package/codeSubagents.js +107 -0
  26. package/codeTransport.js +46 -5
  27. package/connections.js +37 -20
  28. package/decrypt.html +69 -9
  29. package/deviceAttest.js +9 -3
  30. package/eraseFile.js +15 -0
  31. package/idb.js +19 -3
  32. package/idbSeal.js +5 -2
  33. package/inviteReceive.js +44 -0
  34. package/inviteSend.js +8 -2
  35. package/jobAgents.js +2 -2
  36. package/keptMerge.js +9 -2
  37. package/l1-worker-src.js +1 -1
  38. package/l1-worker.js +122 -43
  39. package/laneAssociation.js +78 -0
  40. package/laneConfig.js +4 -3
  41. package/laneLinkCore.js +9 -0
  42. package/ledgerView.js +30 -4
  43. package/manifest.json +112 -87
  44. package/memberChange.js +4 -2
  45. package/mirrorBatch.js +47 -0
  46. package/offlineBundle.js +21 -0
  47. package/opRouting.js +10 -0
  48. package/package.json +27 -2
  49. package/pdfOptions.js +13 -0
  50. package/pdfText.js +107 -0
  51. package/pdfjs.mjs +28 -0
  52. package/pdfjs.worker.mjs +28 -0
  53. package/protectedLocal.js +52 -13
  54. package/reactionHolders.js +86 -0
  55. package/removedMessage.js +1 -1
  56. package/roomEmbed.js +111 -0
  57. package/roomIntake.js +324 -0
  58. package/roomName.js +1 -1
  59. package/roomRoster.js +30 -7
  60. package/rosterCount.js +6 -3
  61. package/scheduleNext.js +60 -0
  62. package/sdkA2A.js +200 -42
  63. package/sdkAccount.js +88 -18
  64. package/sdkAccountDoc.js +13 -5
  65. package/sdkAccountSections.js +172 -23
  66. package/sdkAgui.js +33 -6
  67. package/sdkBackup.js +53 -11
  68. package/sdkBackupV2.js +15 -3
  69. package/sdkCloudDevice.js +20 -5
  70. package/sdkComputers.js +695 -65
  71. package/sdkDictation.js +115 -25
  72. package/sdkErase.js +12 -5
  73. package/sdkExports.js +19 -8
  74. package/sdkInvitations.js +4 -2
  75. package/sdkKeptAgent.js +19 -3
  76. package/sdkKeptIntake.js +100 -0
  77. package/sdkLaneLink.js +8 -9
  78. package/sdkPlan.js +4 -2
  79. package/sdkRekey.js +122 -22
  80. package/sdkReport.js +1 -1
  81. package/sdkSafeMedia.js +1 -1
  82. package/sdkSchedules.js +8 -1
  83. package/sdkSpeech.js +32 -2
  84. package/sdkTemporaryRooms.js +124 -0
  85. package/sdkTurn.js +12 -4
  86. package/sdkVault.js +66 -10
  87. package/sentinelRelease.js +1 -0
  88. package/sharedViews.js +34 -4
  89. package/siri.js +140 -9
  90. package/spaceClient.js +112 -17
  91. package/spaceEmailGate.js +2 -2
  92. package/spaceExport.js +50 -5
  93. package/spaceFork.js +15 -7
  94. package/spaceTemplates.js +99 -0
  95. package/speechOut.js +21 -5
  96. package/store.js +134 -27
  97. package/sw-notif-core.js +11 -8
  98. package/tapTrail.js +58 -0
  99. package/turnVerdict.js +1 -0
  100. package/usageReceipts.js +12 -5
  101. package/vault-core.js +568 -126
  102. package/vault-kit.mjs +3 -3
  103. package/vault-screens.js +30 -18
  104. package/vaultAtRest.js +38 -6
  105. package/vaultCoreLock.js +3 -1
  106. package/vaultCorePush.js +58 -7
  107. package/vaultKeep.js +9 -3
  108. package/vaultWorkerHost.js +32 -7
  109. package/witbitz-admin.d.ts +3 -0
  110. package/witbitz-admin.mjs +12 -11
  111. package/witbitz-sdk.d.ts +170 -43
  112. package/witbitz-sdk.js +833 -203
package/README.md CHANGED
@@ -16,6 +16,6 @@ The guide: https://witbitz.chat/docs/sdk
16
16
 
17
17
  ## The same bytes as the hosted release
18
18
 
19
- Version 4.3.0 of this package is the release folder https://witbitz.chat/sdk/4.3.0/ unchanged (from commit
20
- `05216351dc94d8e6b5bd650b863faedd2eed8ecc`), plus this README, `package.json` and `LICENSE`. Its `manifest.json` lists the sha384 of every file; each file in the
19
+ Version 4.5.0 of this package is the release folder https://witbitz.chat/sdk/4.5.0/ unchanged (from commit
20
+ `fa43bad6c54e944c094d3b0ede5972dd9187ee84`), plus this README, `package.json` and `LICENSE`. Its `manifest.json` lists the sha384 of every file; each file in the
21
21
  package matches it.
package/a2aCore.js CHANGED
@@ -11,6 +11,7 @@ export const MAX_LANES = 32, MAX_PEERS = 32
11
11
  // THE SENTINEL TAKES 16 (infra/cloud-computer/sentinel/a2a.mjs LANES_MAX): a 17th lane made here could never be pushed — the whole
12
12
  // record was refused, every lane with it. MAX_LANES stays what a stored copy may hold; a NEW lane stops at this one (2026-11-23).
13
13
  export const SENTINEL_LANES_MAX = 16
14
+ const validConnectionId = value => typeof value === 'string' && /^[A-Za-z0-9_-]{1,64}$/.test(value)
14
15
  const laneErr = (code, m) => Object.assign(new Error(m), { code })
15
16
  const ROOM = /^[A-Za-z0-9_:.-]{4,120}$/, HANDLE = /^[A-Za-z0-9_-]{16,43}$/, COORD = /^[A-Za-z0-9_-]{43}$/
16
17
  const b64u = (u8) => { let s = ''; for (let i = 0; i < u8.length; i++) s += String.fromCharCode(u8[i]); return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') }
@@ -54,7 +55,7 @@ export function normA2A (o) {
54
55
  if (!pub || !COORD.test(String(pub.x)) || !COORD.test(String(pub.y)) || (!held && (!priv || !COORD.test(String(priv.d))))) continue
55
56
  const removed = marks(l.removed, (id) => PEER_ID.test(id))
56
57
  const peers = (Array.isArray(l.peers) ? l.peers : []).filter((p) => p && PEER_ID.test(String(p.id)) && !removed[String(p.id)] && /^[A-Za-z0-9+/]{43}=$/.test(String(p.tokenHash))).slice(0, MAX_PEERS)
57
- .map((p) => ({ id: String(p.id), name: String(p.name || '').slice(0, 80), tokenHash: String(p.tokenHash), reply: p.reply === 'auto' ? 'auto' : 'ask', created: Number(p.created) || 0, ...(p.job === true ? { job: true } : {}), ...(p.own === true ? { own: true } : {}) }))
58
+ .map((p) => ({ id: String(p.id), name: String(p.name || '').slice(0, 80), tokenHash: String(p.tokenHash), reply: p.reply === 'auto' ? 'auto' : 'ask', ...(Number(p.replyAt) > 0 ? { replyAt: Number(p.replyAt) } : {}), created: Number(p.created) || 0, ...(p.job === true ? { job: true, ...(validConnectionId(p.connectionId) ? { connectionId: p.connectionId } : {}) } : {}), ...(p.own === true ? { own: true } : {}) }))
58
59
  lanes[room] = { handle: String(l.handle), name: String(l.name || '').slice(0, 80), description: String(l.description || '').slice(0, 280), pub: { x: pub.x, y: pub.y }, ...(held ? { held: 1 } : { priv: { kty: 'EC', crv: 'P-256', x: pub.x, y: pub.y, d: priv.d } }), peers, ...(Object.keys(removed).length ? { removed } : {}), ...(Number(l.at) > 0 ? { at: Number(l.at) } : {}) }
59
60
  }
60
61
  return { lanes, ...(Object.keys(gone).length ? { gone } : {}) }
@@ -103,20 +104,23 @@ export const newPeerToken = () => 'a2a_' + rnd(32)
103
104
  const TOKEN_HASH = /^[A-Za-z0-9+/]{43}=$/
104
105
  /** Let one outside agent in → { id, token } — the token exists only here; only its hash is kept. With `tokenHash` (a token minted
105
106
  * ELSEWHERE — the hosted app's vault, which shows it on its own screen) no token is made here: → { id, token: '' }. */
106
- export async function addPeerIn (s, room, name, { reply = 'ask', job = false, own = false, tokenHash = '' } = {}, err) {
107
+ export async function addPeerIn (s, room, name, { reply = 'ask', job = false, own = false, connectionId, tokenHash = '' } = {}, err) {
107
108
  const l = s.lanes[room]
108
109
  if (!l) throw err('not_enabled', 'let outside agents reach this lane first')
109
110
  const n = String(name || '').trim(); if (!n) throw err('name_required', 'name the agent you are letting in')
110
111
  if (l.peers.length >= MAX_PEERS) throw err('too_many', `at most ${MAX_PEERS} agents per lane`)
111
112
  if (tokenHash && !TOKEN_HASH.test(String(tokenHash))) throw err('bad_token', 'the agent\'s key could not be made')
113
+ if (connectionId !== undefined && (!job || !validConnectionId(connectionId))) throw err('invalid_argument', 'Choose a valid connection ID for a job peer.')
112
114
  const token = tokenHash ? '' : newPeerToken(), id = 'p_' + rnd(9)
113
- l.peers.push({ id, name: n.slice(0, 80), ...(tokenHash ? { tokenHash } : { tokenHash: await a2aTokenHash(token) }), reply: reply === 'auto' ? 'auto' : 'ask', created: Date.now(), ...(job === true ? { job: true } : {}), ...(own === true ? { own: true } : {}) })
115
+ l.peers.push({ id, name: n.slice(0, 80), ...(tokenHash ? { tokenHash } : { tokenHash: await a2aTokenHash(token) }), reply: reply === 'auto' ? 'auto' : 'ask', created: Date.now(), ...(job === true ? { job: true, ...(connectionId ? { connectionId } : {}) } : {}), ...(own === true ? { own: true } : {}) })
114
116
  return { id, token }
115
117
  }
116
118
  export function setPeerReplyIn (s, room, id, reply, err) {
117
119
  const p = s.lanes[room] && s.lanes[room].peers.find((x) => x.id === id)
118
120
  if (!p) throw err('unknown_peer', 'no such agent on this lane')
119
- p.reply = reply === 'auto' ? 'auto' : 'ask'; return p.reply
121
+ const next = reply === 'auto' ? 'auto' : 'ask'
122
+ if (p.reply !== next) { p.reply = next; p.replyAt = Math.max(Date.now(), (p.replyAt || 0) + 1) }
123
+ return p.reply
120
124
  }
121
125
  export function removePeerIn (s, room, id) {
122
126
  if (!s.lanes[room]) return false
@@ -139,7 +143,15 @@ export const peersOf = (s, room) => (s.lanes[room] ? s.lanes[room].peers.map(({
139
143
 
140
144
  // ── the Sentinel ──
141
145
  /** What the Sentinel takes (a2a.mjs grant): PUBLIC halves and token hashes only. */
142
- export const recordFor = (s, account) => ({ account, lanes: Object.entries(s.lanes).map(([room, l]) => ({ handle: l.handle, room, name: l.name, description: l.description, inboxPub: { x: l.pub.x, y: l.pub.y }, peers: l.peers.map(({ own, ...p }) => p) })) }) // `own` stays the account's: the Sentinel needs none of it
146
+ export const recordFor = (s, account) => ({ account, lanes: Object.entries(s.lanes).map(([room, l]) => ({ handle: l.handle, room, name: l.name, description: l.description, inboxPub: { x: l.pub.x, y: l.pub.y }, peers: l.peers.map(({ own, connectionId, replyAt, ...p }) => p) })) }) // `own` stays the account's: the Sentinel needs none of it
147
+ /** THE INTAKE (docs/message-intake.md): `intake` = { room, pub, drops: { '<lane>|<peerId>': token } } (intakeProducers.js) →
148
+ * the record names the account's message intake and each peer its own drop address; the Sentinel then drops a peer's
149
+ * messages into the message room instead of keeping them. A peer with no address here keeps the old path. */
150
+ export function withIntake(rec, intake) {
151
+ if (!intake || !intake.room || !intake.pub) return rec
152
+ const drops = intake.drops || {}
153
+ return { ...rec, intake: { room: intake.room, pub: { x: intake.pub.x, y: intake.pub.y } }, lanes: rec.lanes.map((l) => ({ ...l, peers: l.peers.map((p) => (drops[l.room + '|' + p.id] ? { ...p, drop: drops[l.room + '|' + p.id] } : p)) })) }
154
+ }
143
155
  /** sealed(mode, obj): attest the standing Sentinel, seal `obj` to it. plain(mode, extra): the unsealed ops. `err(kind, message, r)`
144
156
  * — kind 'refused' | 'unreachable' — lets each side keep its own codes. */
145
157
  export function sentinelCalls ({ post, auth = {}, attest, seal, err }) {
@@ -198,3 +210,27 @@ export const A2A_COLLECT_WINDOW_MS = 45_000
198
210
 
199
211
  /** A reply to a task the peer already finished: "done", not a failure — ONE test for the app (a2aLane.js) and the SDK (sdkA2A.js). */
200
212
  export const finishedTask = (e) => /already finished|task is finished/i.test(String((e && (e.message || e.error)) || e))
213
+ /** …but one the requester ENDED (canceled, or declined from another device when this one replies) never got this reply: not "sent"
214
+ * (side sweep 2026-11-28: the review card cleared the member's edit and said Sent). The Sentinel names the end (`taskState`); an
215
+ * older one does not, and the reply reads as done, as before. */
216
+ export const replyNotDelivered = (e, { reject = false } = {}) => {
217
+ const st = String((e && e.taskState) || '').toUpperCase()
218
+ return !!st && !(st === 'COMPLETED' && !reject) && !(st === 'REJECTED' && reject)
219
+ }
220
+
221
+ export function applyRemovals(record, removals) {
222
+ let changed = false
223
+ for (const [room, handle, id] of removals) {
224
+ if (record.lanes[room]?.handle !== handle) continue
225
+ changed = (id ? removePeerIn(record, room, id) : disableLaneIn(record, room)) || changed
226
+ }
227
+ return changed
228
+ }
229
+ export function removalIntents(base, candidate) {
230
+ const intents = []
231
+ for (const [room, lane] of Object.entries(base.lanes)) {
232
+ if (candidate.gone?.[lane.handle]) intents.push([room, lane.handle, ''])
233
+ else for (const peer of lane.peers) if (candidate.lanes[room]?.removed?.[peer.id]) intents.push([room, lane.handle, peer.id])
234
+ }
235
+ return intents
236
+ }
package/accountErase.js CHANGED
@@ -16,11 +16,14 @@ const lc = (s) => String(s || '').trim().toLowerCase()
16
16
  * was judged from its oldest messages and someone who wrote only later was never seen). `page(sinceCount)` → a poll answer
17
17
  * { status?, entries, more?, version }. → the entries, or null when a page failed or the room did not end within `max` pages —
18
18
  * the caller treats null as "could not check", i.e. shared: never deleted. */
19
- export async function readAllEntries (page, { max = 200 } = {}) {
19
+ // `onGone`: called when the room answers 410 — it is deleted (an earlier run's delete, or its creator's): nothing to check
20
+ // (side sweep: account-erase-retry-treats-deleted-room-as-shared). Still null, as every failed read.
21
+ export async function readAllEntries (page, { max = 200, onGone } = {}) {
20
22
  const out = []
21
23
  let since = 0
22
24
  for (let i = 0; i < max; i++) {
23
25
  const v = await page(since).catch(() => null)
26
+ if (v && v.status === 410 && typeof onGone === 'function') { onGone(); return null }
24
27
  if (!v || (v.status != null && v.status !== 200) || !Array.isArray(v.entries)) return null
25
28
  out.push(...v.entries)
26
29
  if (!v.more) return out
@@ -154,22 +157,25 @@ export async function eraseAccount (d) {
154
157
  // Sentinel, Siri, outside agents, mail addresses, room-funding grants, the cloud device. After the backup (the point of no
155
158
  // return), BEFORE any room goes: a mail address and Siri are ended through the message room, a grant through the billing
156
159
  // record. A failure is a failure like any other: the rest runs, the index and the device stay, a re-run finishes it.
157
- const holdBilling = []
160
+ const holdBilling = [], holdMsgs = []
158
161
  for (const c of Array.isArray(d.cleanups) ? d.cleanups : []) {
159
162
  if (!c || typeof c.run !== 'function') continue
160
163
  say('Removing ' + c.what + '…')
161
164
  const r = await Promise.resolve().then(() => c.run(t)).catch((e) => ({ ok: false, why: String((e && e.message) || e) }))
162
165
  if (r && r.ok) (rep.account.cleaned = rep.account.cleaned || []).push(c.what)
163
- else { rep.failed.push({ what: c.what, why: (r && (r.why || r.error)) || 'failed' }); if (c.needsBilling) holdBilling.push(c.what) }
166
+ else { rep.failed.push({ what: c.what, why: (r && (r.why || r.error)) || 'failed' }); if (c.needsBilling) holdBilling.push(c.what); if (c.needsMsgs) holdMsgs.push(c.what) }
164
167
  }
165
168
  const account = new Set(d.rooms.account || [])
166
169
  const list = [...new Set([...(d.rooms.all || []), ...account])].filter((r) => r && r !== d.indexRoom)
167
170
  const queued = []
168
171
  for (const room of list) {
169
172
  say('Checking your Spaces…')
173
+ // the message room holds the mail-address and Siri registries a re-run needs to end them (side sweep): kept while either failed
174
+ if (d.msgsRoom && room === d.msgsRoom && holdMsgs.length) { rep.failed.push({ room, why: 'kept until ' + holdMsgs.join(', ') + ' is removed — run Delete my account again' }); continue }
170
175
  let shared = false
171
176
  if (!account.has(room)) {
172
177
  const r = await d.read(room).catch(() => null)
178
+ if (r && r.gone === true) { rep.deleted.push(room); continue } // already deleted (410): nothing to delete or leave — a re-run after an earlier delete
173
179
  shared = !r || roomIsShared({ entries: r.entries, config: r.config, me: d.me }) // unreadable ⇒ treat as shared: never delete what we could not check
174
180
  }
175
181
  if (shared) { await leaveInto(d, room, rep, rep.left); continue }
@@ -218,6 +224,11 @@ export async function eraseAccount (d) {
218
224
  if (queuedOnly(r)) await confirmQueued(d, [d.indexRoom], rep, say) // the index holds the account key: confirmed before the wipe (9·S#1)
219
225
  else if (deletionConfirmed(r)) rep.deleted.push(d.indexRoom); else if (r.status === 404) rep.lapsing.push(d.indexRoom); else rep.failed.push({ room: d.indexRoom, why: 'delete ' + (r.status || 'unreachable') })
220
226
  }
221
- if (!rep.failed.length) { say('Done.'); try { await d.wipe() } catch { /* */ } }
227
+ if (!rep.failed.length) {
228
+ try {
229
+ if (await d.wipe() === false) throw new Error('Device cleanup is pending. Close other Spaces windows to finish.')
230
+ say('Done.')
231
+ } catch (error) { rep.failed.push({ what: 'device cleanup', why: String(error.message || error) }) }
232
+ }
222
233
  return rep
223
234
  }
@@ -10,8 +10,13 @@ const isTemp = (room) => String(room || '').startsWith('tmp-') // temp rooms nev
10
10
  * `key` = the key part ({ mk } / { split, userShare, commit? } / {} when the key worker injects it), `marks` = what this device
11
11
  * knows of the room ({ help, gate, enclave }). Per-field last writer: a newer rename / archive / pin another device pushed is
12
12
  * kept; the latest activity anywhere orders the list; a Help / verified / confidential mark is never taken off. */
13
- export function indexRoomEntry (row, prev, key, { help = false, gate = '', enclave = false } = {}) {
14
- const myTitle = (row.title && row.title !== 'Space' && row.title !== row.room) ? row.title : ''
13
+ // A ROOM'S TIME MOVES AT MOST ONCE AN HOUR (side sweep: sdk-account-room-list-omits-recency; the owner's decision): every open
14
+ // stamps a row's `at`, and each newer `at` rewrote the account index — one write per room opened. While the index's time for a room
15
+ // is less than an hour old it stays (the doc then differs from what was read only if something else changed, and sameDoc skips the
16
+ // write); after that the newer time goes in. The account's room list (sdk `lastOpenedAt`) is at most an hour behind.
17
+ export const INDEX_AT_EVERY_MS = 3600_000
18
+ export function indexRoomEntry (row, prev, key, { help = false, gate = '', enclave = false, now = Date.now() } = {}) {
19
+ const myTitle = (row.title && (row.title !== 'Space' || row.renamed) && row.title !== row.room) ? row.title : '' // "Space" is the default name — unless set by hand: then it travels as that name, `manual` (side sweep room-rename-to-space-omitted-from-account-index)
15
20
  const myAt = row.titleAt || 0
16
21
  const keepRemote = prev && prev.title && (prev.titleAt || 0) > myAt // per-field LWW: don't clobber a newer rename another device pushed
17
22
  const archNewer = !prev || (row.archivedAt || 0) >= (prev.archivedAt || 0) // newest archive/unarchive wins
@@ -21,10 +26,12 @@ export function indexRoomEntry (row, prev, key, { help = false, gate = '', encla
21
26
  // only once it was ever set, so the doc of an account that never used it is byte-for-byte what it was (accountFormatGolden).
22
27
  const aoAt = Math.max(row.alwaysOnAt || 0, (prev && prev.alwaysOnAt) || 0)
23
28
  const aoOn = !prev || (row.alwaysOnAt || 0) >= (prev.alwaysOnAt || 0) ? !!row.alwaysOn : !!prev.alwaysOn
29
+ const prevAt = (prev && prev.at) || 0, rowAt = row.at || 0
30
+ const atHeld = prevAt > 0 && rowAt > prevAt && now - prevAt < INDEX_AT_EVERY_MS // the index moved this room's time within the hour
24
31
  return {
25
32
  ...key,
26
33
  title: keepRemote ? prev.title : myTitle, titleAt: keepRemote ? prev.titleAt : myAt, ...((keepRemote ? prev.manual : (myTitle && row.renamed)) ? { manual: true } : {}), // a name set by hand travels as such (roomTitle.js: never an impostor)
27
- at: Math.max(row.at || 0, (prev && prev.at) || 0), // ordering: keep the LATEST activity across devices so the list order converges
34
+ at: atHeld ? prevAt : Math.max(rowAt, prevAt), // the LATEST open across devices, moved at most once an hour (above)
28
35
  archived: archNewer ? !!row.archived : !!prev.archived, archivedAt: Math.max(row.archivedAt || 0, (prev && prev.archivedAt) || 0),
29
36
  pinned: pinNewer ? !!row.pinned : !!(prev && prev.pinned), pinnedAt: Math.max(row.pinnedAt || 0, (prev && prev.pinnedAt) || 0),
30
37
  ...(aoAt ? { alwaysOn: aoOn, alwaysOnAt: aoAt } : {}),
@@ -34,10 +41,11 @@ export function indexRoomEntry (row, prev, key, { help = false, gate = '', encla
34
41
  }
35
42
  }
36
43
 
37
- /** Every delete this device knows, as index entries — they win over any live entry. */
44
+ /** Every delete this device knows, as index entries — they win over any live entry. Never a temp room's: it was never in the
45
+ * synced index, and its delete written there came back after the push's temp filter (side sweep temporary-delete-keeps-drawer-key). */
38
46
  export function indexDeletes (tomb) {
39
47
  const out = {}
40
- for (const rm of Object.keys(tomb || {})) out[rm] = { deleted: true, at: tomb[rm] }
48
+ for (const rm of Object.keys(tomb || {})) if (!isTemp(rm)) out[rm] = { deleted: true, at: tomb[rm] }
41
49
  return out
42
50
  }
43
51
 
@@ -113,8 +121,17 @@ export const adoptsRemote = (localId, remoteId) => (!localId || (remoteId !== lo
113
121
  /** THE `xindex` DOC (the sealed 'index'): the rooms map, the device registry and its sign-outs, the person's name, the read
114
122
  * positions, and — only when this device has one — the invite inbox, the usage key (with the retired ones) and the pipes /
115
123
  * message room pointers. Key order is the doc's: accountFormatGolden.test.mjs hashes it as written (phase 3: the SDK writes it too). */
116
- export const indexDoc = ({ rooms, devices, signouts, name, seen, vseen, inviteKey, usageKey, usageKeysOld, pipesRoom, msgsRoom }) =>
117
- ({ v: 2, rooms, devices, signouts, name, seen, vseen, ...(inviteKey ? { inviteKey } : {}), ...(usageKey ? { usageKey, usageKeysOld } : {}), ...(pipesRoom ? { pipesRoom } : {}), ...(msgsRoom ? { msgsRoom } : {}) })
124
+ export const indexDoc = ({ rooms, devices, signouts, name, seen, vseen, inviteKey, usageKey, usageKeysOld, pipesRoom, msgsRoom, nameAt }) =>
125
+ ({ v: 2, rooms, devices, signouts, name, seen, vseen, ...(inviteKey ? { inviteKey } : {}), ...(usageKey ? { usageKey, usageKeysOld } : {}), ...(pipesRoom ? { pipesRoom } : {}), ...(msgsRoom ? { msgsRoom } : {}), ...(nameAt > 0 ? { nameAt } : {}) })
126
+
127
+ /** WHICH NAME THE INDEX CARRIES (side sweep app-index-push-reverts-account-display-name): the newer of this device's and the
128
+ * index's, by `nameAt` (additive; 0 = not known). With no time on the index's side, the old rule: this device's name, else the
129
+ * index's. → { name, nameAt, adopt } — `adopt`: the index's name is newer than this device's, take it here. */
130
+ export function pickName ({ localName = '', localAt = 0, remoteName = '', remoteAt = 0 } = {}) {
131
+ const rAt = Number(remoteAt) > 0 ? Number(remoteAt) : 0, lAt = Number(localAt) > 0 ? Number(localAt) : 0
132
+ if (remoteName && rAt > lAt) return { name: remoteName, nameAt: rAt, adopt: remoteName !== localName }
133
+ return { name: localName || remoteName || '', nameAt: Math.max(lAt, localName ? 0 : rAt), adopt: false }
134
+ }
118
135
 
119
136
  /** THE `xindex2` DOC (the sealed 'index2'): contacts, the personal calendar and to-dos, the Code settings, the connections'
120
137
  * call keys with their removal marks (`connGone` only once someone detached), Siri and the A2A lanes. */
package/accountRecord.js CHANGED
@@ -49,12 +49,16 @@ export function roomPin(r) {
49
49
  const at = Number.isFinite(r.pinnedAt) && r.pinnedAt > 0 ? r.pinnedAt : 0
50
50
  return r.pinned || at ? { pinned: !!r.pinned, pinnedAt: at } : {}
51
51
  }
52
+ // A room's LABEL and ARCHIVE clocks (the SDK's, sdkAccount.js mergeIndex): optional — a record without them reads as before (the room's
53
+ // `at` stands in). Dropped from the record, a restored rename took the room's later `at` as both clocks and cleared an archive another
54
+ // device made (side sweep: sdk-room-rename-archive-overwrite).
55
+ const fieldClocks = (r) => ({ ...(Number.isFinite(r.labelAt) && r.labelAt > 0 ? { labelAt: r.labelAt } : {}), ...(Number.isFinite(r.archivedAt) && r.archivedAt > 0 ? { archivedAt: r.archivedAt } : {}) })
52
56
  export function recordFromRooms ({ rooms = [], tomb, email, inviteKey, indexRoom, app = SDK_APP, at = Date.now() } = {}) {
53
57
  const recents = []; const keys = {}
54
58
  for (const r of rooms) {
55
59
  if (!r || !r.room || !r.link) continue
56
60
  recents.push({ room: r.room, title: r.label || '', ...(typeof r.renamed === 'boolean' ? { renamed: r.renamed } : {}), at: r.at || 0, ...roomPin(r), link: r.link, kind: r.kind === 'lane' ? 'lane' : 'space',
57
- ...(r.shared ? { shared: r.shared } : {}), ...(r.archived ? { archived: true } : {}) })
61
+ ...(r.shared ? { shared: r.shared } : {}), ...(r.mintedFor ? { mintedFor: r.mintedFor } : {}), ...(r.laneOrigin === 'minted' && !r.detachedLane ? { laneOrigin: 'minted' } : {}), ...(Number(r.associationAt) > 0 ? { associationAt: Number(r.associationAt) } : {}), ...(r.detachedLane ? { detachedLane: true } : {}), ...(r.archived ? { archived: true } : {}), ...fieldClocks(r) })
58
62
  const mk = keyInLink(r.link) || r.mk // the link's own key first: a separate copy of a plain room's key may be stale
59
63
  if (mk) keys[r.room] = { mk }
60
64
  }
@@ -72,7 +76,7 @@ export function roomsOfRecord (doc) {
72
76
  if (!Array.isArray(doc.recents)) return []
73
77
  const keys = doc.keys && typeof doc.keys === 'object' ? doc.keys : {}
74
78
  return doc.recents.filter((r) => r && r.room && r.link).map((r) => ({
75
- room: r.room, ...roomPin(r), ...(r.at ? { at: r.at } : {}), ...(r.archived ? { archived: true } : {}), link: r.link,
79
+ room: r.room, ...roomPin(r), ...(r.mintedFor ? { mintedFor: r.mintedFor } : {}), ...(r.laneOrigin === 'minted' && !r.detachedLane ? { laneOrigin: 'minted' } : {}), ...(Number(r.associationAt) > 0 ? { associationAt: Number(r.associationAt) } : {}), ...(r.detachedLane ? { detachedLane: true } : {}), ...(r.at ? { at: r.at } : {}), ...(r.archived ? { archived: true } : {}), ...fieldClocks(r), link: r.link,
76
80
  kind: r.kind === 'lane' ? 'lane' : 'space', ...(r.title ? { label: r.title } : {}), ...(typeof r.renamed === 'boolean' ? { renamed: r.renamed } : {}), ...(r.shared ? { shared: r.shared } : {}),
77
81
  ...(keys[r.room] && keys[r.room].mk && !keyInLink(r.link) ? { mk: keys[r.room].mk } : {}),
78
82
  }))
package/accountStores.js CHANGED
@@ -86,6 +86,7 @@ export function makeAccountStore ({ call, key, oldKeys = async () => [] }) {
86
86
  return null
87
87
  }
88
88
  const cleared = new Set() // room|name whose plain doc this page already emptied (or found emptied)
89
+ const plainSeen = new Map() // room|name → the OLDEST plain doc's version this page read since its last cleanup (the emptying is written over it)
89
90
  const read = async (room, mk, name) => { try { return await call(room, mk, name) } catch { return { status: 0 } } }
90
91
  // A computer removed here leaves the plain doc too, so its relay secret is not kept there — only TOMBSTONES are written
91
92
  // (nothing this device holds that the plain doc lacks), over the version just read; a miss waits for the next write.
@@ -106,18 +107,28 @@ export function makeAccountStore ({ call, key, oldKeys = async () => [] }) {
106
107
  async get (room, mk, name, { plainOpen = (s) => s } = {}) {
107
108
  const k = await key()
108
109
  const plainR = await read(room, mk, name)
110
+ // THE OLDEST plain version read since the last cleanup is kept, not the newest (side sweep: legacy-index-cleanup-overwrites-late-room):
111
+ // a read made after the caller built its list — the key worker's INSIDE the write, or an account pull between a push's read and
112
+ // its write — moved it to a doc holding a room that list lacks, and the cleanup emptied that room. Kept the oldest, no read can move
113
+ // it (`notePlain` is still taken from older callers; it no longer changes anything). null: the store names no versions (unconditional).
114
+ const pk = room + '|' + name
115
+ if (plainR && plainR.status === 200 && !plainSeen.has(pk)) plainSeen.set(pk, Number.isInteger(plainR.v) ? plainR.v : null)
109
116
  const plain = plainR && plainR.status === 200 && plainR.state && typeof plainR.state === 'object' ? await plainOpen(plainR.state) : null
110
117
  if (plain && plain.moved === MOVED) cleared.add(room + '|' + name)
111
118
  if (!k) return { status: plainR ? plainR.status : 0, state: plain && plain.moved !== MOVED ? plain : null, sealed: false }
112
119
  const sr = await read(room, mk, SEALED(name))
113
120
  if (!(sr && sr.status === 200)) return { status: (sr && sr.status) || 0, state: null, sealed: false }
114
- if (!isSealedDoc(sr.state)) return { status: plainR ? plainR.status : 0, state: plain && plain.moved !== MOVED ? plain : null, sealed: false } // not moved yet → the plain doc
121
+ // …with the sealed doc's version (none yet: its version too): the first sealing write is pinned to it, so a doc another device
122
+ // sealed meanwhile is merged first, never replaced by this stale read (side sweep 2026-11-28: a contact was lost)
123
+ if (!isSealedDoc(sr.state)) return { status: plainR ? plainR.status : 0, state: plain && plain.moved !== MOVED ? plain : null, sealed: false, ...(Number.isInteger(sr.v) ? { v: sr.v } : {}) } // not moved yet → the plain doc
115
124
  const opened = await openAny(k, sr.state)
116
125
  if (!opened) return { status: 0, state: null, sealed: true, unopenable: true }
117
126
  let st = opened.st
118
127
  let v = Number.isInteger(sr.v) ? { v: sr.v } : {}
119
128
  if (opened.old) { // under a previous key: write it back under this one (over the version just read; a race → the next read)
120
- try { const w = await call(room, mk, SEALED(name), await sealDoc(k, st), 'sealed under the new account key', '', Number.isInteger(sr.v) ? sr.v : 0); if (w && w.status === 200) v = {} } catch { /* the next read heals it */ }
129
+ // the version read is kept: a write pinned to it meets the rewrite (409) and the caller reads again — dropping it let that write
130
+ // replace a contact another device added (side sweep 2026-11-28)
131
+ try { const w = await call(room, mk, SEALED(name), await sealDoc(k, st), 'sealed under the new account key', '', Number.isInteger(sr.v) ? sr.v : 0); if (w && w.status === 200 && Number.isInteger(w.v)) v = { v: w.v } } catch { /* the next read heals it */ } // the rewrite's own version when the store names it
121
132
  }
122
133
  const reg = REGISTRIES[name]
123
134
  if (reg) return { status: 200, state: plain && plain.moved !== MOVED ? { ...st, [reg]: mergeRegistryMap(st[reg], plain[reg]) } : st, sealed: true, ...v } // the computer's own writes
@@ -149,7 +160,7 @@ export function makeAccountStore ({ call, key, oldKeys = async () => [] }) {
149
160
  for (let i = 0; i < 5; i++) {
150
161
  const sr = await read(room, mk, SEALED(name))
151
162
  if (!(sr && sr.status === 200)) return { status: (sr && sr.status) || 0, error: 'unread' } // unknown is not empty
152
- if (pinned && isSealedDoc(sr.state) && sr.v !== ifV) return { status: 409, error: 'moved' } // written since the caller's read
163
+ if (pinned && (isSealedDoc(sr.state) || Number.isInteger(sr.v)) && sr.v !== ifV) return { status: 409, error: 'moved' } // written since the caller's read (the first sealing too: side sweep 2026-11-28)
153
164
  let body = obj
154
165
  if (isSealedDoc(sr.state)) {
155
166
  const opened = await openAny(k, sr.state) // a previous key's document is merged and written under this one
@@ -162,8 +173,13 @@ export function makeAccountStore ({ call, key, oldKeys = async () => [] }) {
162
173
  if (status === 409) { await new Promise((res) => setTimeout(res, 20 + Math.floor(Math.random() * 80) * (i + 1))); continue } // another device wrote first: re-read, re-merge
163
174
  if (status === 200 && REGISTRIES[name]) await removalsToPlain(room, mk, name, REGISTRIES[name], body)
164
175
  if (status === 200 && !REGISTRIES[name] && !cleared.has(room + '|' + name)) { // the computers list's plain doc is the computer's channel: never emptied
165
- let w = null; try { w = await call(room, mk, name, { v: 2, moved: MOVED }, summary, by) } catch { /* emptied on a later write */ }
166
- if (w && w.status === 200) cleared.add(room + '|' + name)
176
+ // ONLY OVER THE PLAIN DOC THAT WAS READ (side sweep 2026-11-28): an older device's room added to it after this page's read was
177
+ // emptied with it. Emptied over the version the read saw; another write since → 409, kept, and the next read folds it in.
178
+ // No read since the last attempt → no cleanup now (a later write's, after a read). Every attempt starts the record again.
179
+ const pk = room + '|' + name, read0 = plainSeen.has(pk), pv = plainSeen.get(pk)
180
+ plainSeen.delete(pk)
181
+ let w = null; if (read0) { try { w = await call(room, mk, name, { v: 2, moved: MOVED }, summary, by, ...(Number.isInteger(pv) ? [pv] : [])) } catch { /* emptied on a later write */ } }
182
+ if (w && w.status === 200) cleared.add(pk)
167
183
  }
168
184
  return { status }
169
185
  }
package/acctV2App.js CHANGED
@@ -15,6 +15,7 @@ export const STATE_KEY = 'space:acctv2' // { acct, base, at, address? } — an a
15
15
  export const RESET_KEY = 'space:acctv2:reset' // § 11.5: the email move THIS device started — { reset, address, ready_at, expires, base }
16
16
  export const ERASE_KEY = 'space:acctv2:erase' // 10·Q#3: "Delete my account"'s request while its answer is unknown — { acct, body, at }; sent again, never remade
17
17
  export const MOVE_KEY = 'space:acctv2:move' // § 11.5, 3a: a move of THIS account's address under way, as the status answer said — { reset, ready_at, expires, objected, base }
18
+ export const RESTORING_KEY = 'space:acctv2:restoring' // a restore's finish sent with this device key, its answer not yet heard — { spk, acct, at }
18
19
 
19
20
  /** deps: { base, fetch?, storage (getItem/setItem/removeItem), deviceKey() → { priv, pub } (WebCrypto pair), vault() →
20
21
  * { master (base64), code? }, codeBytesOf(code) → Uint8Array, backupIdOf(master) → hex, wrapperIdOf(codeBytes) → hex,
@@ -53,10 +54,23 @@ export function makeAcctV2(deps) {
53
54
  * no account on the new service → a new device key (deps.newDeviceKey), then on. Offline / no answer: as before. */
54
55
  const freshKeyIfTaken = async () => {
55
56
  if (state() || !deps.newDeviceKey) return
56
- let r = null
57
- try { r = await client.deviceStatus(await signer()) } catch { return }
57
+ let r = null, dev = null
58
+ try { dev = await signer(); r = await client.deviceStatus(dev) } catch { return }
59
+ // a restore whose finish reply was lost registered THIS key already: keep it, or a retry registers a second device (side sweep
60
+ // 2026-11-28: the retry made a new key and the account showed two active entries for one device)
61
+ // — only while the service still holds the key ACTIVE: a revoked key makes a new key as before. NO AGE LIMIT any more (side sweep:
62
+ // restore-finish-duplicate-device — a retry after 7 days made a second device): a mark of ANOTHER account's landed finish costs one
63
+ // refused try (`key_registered`, and the mark is dropped there), not a second device entry
64
+ if (restoringWith(dev.spk) && r && r.state === 'active') return
65
+ try { deps.storage.removeItem(RESTORING_KEY) } catch { /* */ }
58
66
  if (r && r.state && r.state !== 'unknown') await deps.newDeviceKey()
59
67
  }
68
+ const restoringWith = (spk, acct) => {
69
+ try {
70
+ const m = JSON.parse(deps.storage.getItem(RESTORING_KEY) || 'null')
71
+ return !!(m && m.spk === spk && (!acct || m.acct === acct))
72
+ } catch { return false }
73
+ }
60
74
  // this device's name on the service ("Chrome on Windows") — the app's own label (devices.js), else a neutral one
61
75
  const myLabel = () => { try { return String((deps.label && deps.label()) || 'This device').slice(0, 64) } catch { return 'This device' } }
62
76
  /** R2-03: show the new code, then keep it as pending with its session id, and refuse to go on (no activation is sent)
@@ -126,7 +140,12 @@ export function makeAcctV2(deps) {
126
140
  const device = await signer()
127
141
  const it = await client.req('POST', '/v2/account/legacy/intent', { body: { gid, resume: true }, signer: device })
128
142
  // 10·Q#5: this device moved it already (the answer was lost): it is an active device of that account — take it, no second move
129
- if (it && it.moved) { setState({ acct: it.acct, base: deps.base, at: Date.now(), trust: it.legacy_trust }); return { acct: it.acct, legacy_trust: it.legacy_trust, resumed: true } }
143
+ // a move that was SILENT (the service says, `silent`): resumed as one, so the other devices still join (side sweep 2026-11-28)
144
+ if (it && it.moved) {
145
+ const silent = it.silent === true
146
+ setState({ acct: it.acct, base: deps.base, at: Date.now(), trust: it.legacy_trust, ...(silent ? { silent: 'moved' } : {}) })
147
+ return { acct: it.acct, legacy_trust: it.legacy_trust, resumed: true, ...(silent ? { silent: true } : {}) }
148
+ }
130
149
  const { ticket } = await client.req('POST', '/v2/account/email/start', { body: { purpose: 'legacy', attempt: it.attempt, address, gk: hexOf(gk) } })
131
150
  const v2 = await client.req('POST', '/v2/account/email/verify', { body: { ticket, code: await getCode() } })
132
151
  if (!v2.verified) throw Object.assign(new Error('email_code_wrong'), { code: 'email_code_wrong' })
@@ -168,7 +187,13 @@ export function makeAcctV2(deps) {
168
187
  if (e && e.code === 'already_migrated') { const acctSig = await accountSigner(); if (!acctSig) fail('no_account_key'); return joinMoved({ gid, codeBytes, device, acctSig, label }) }
169
188
  throw e
170
189
  }
171
- if (it && it.moved) { setState({ acct: it.acct, base: deps.base, at: Date.now(), trust: it.legacy_trust, silent: 'moved' }); return { acct: it.acct, legacy_trust: it.legacy_trust, moved: true } } // 10·Q#5
190
+ // 10·Q#5. An EMAIL move whose answer was lost (the service says `silent: false`; an older service says nothing — kept silent):
191
+ // the state carries no silent mark, so the caller signs the other devices out as that move promised (side sweep 2026-11-28)
192
+ if (it && it.moved) {
193
+ const manual = it.silent === false
194
+ setState({ acct: it.acct, base: deps.base, at: Date.now(), trust: it.legacy_trust, ...(manual ? {} : { silent: 'moved' }) })
195
+ return { acct: it.acct, legacy_trust: it.legacy_trust, moved: true, ...(manual ? { manual: true } : {}) }
196
+ }
172
197
  if (!it.account_key) fail('email_needed') // an old backup without an account key moves only with the email code
173
198
  const acctSig = await accountSigner()
174
199
  if (!acctSig) fail('no_account_key')
@@ -222,8 +247,31 @@ export function makeAcctV2(deps) {
222
247
  async resetBegin({ address, getCode }) {
223
248
  need()
224
249
  if (state()) throw Object.assign(new Error('already_migrated'), { code: 'already_migrated' })
250
+ // THE MOVE IS KEPT BEFORE ITS START (side sweep: email-move-start-reply-loses-pending-request): its id was saved only after the
251
+ // start answered — a page closed after the service took the start lost the move's controls here, and starting again got a fresh
252
+ // id the address's lock refused. A move kept without its dates (the start's answer lost) is asked of the service first.
253
+ const kept = this.pendingReset()
254
+ if (kept && !kept.expires && kept.address === address) { const live = await this.refreshReset(); if (live) return live }
225
255
  await freshKeyIfTaken()
226
- const r = await client.resetBegin({ device: await signer(), address, getCode })
256
+ let intent = ''
257
+ // …and ON DISK before the start is sent (round 5): with storage protection a write only queues its encryption, and a page closed
258
+ // after the service took the start, with it still queued, had no id to recover. Not kept → no start (the address is not locked).
259
+ const onIntent = async (reset) => {
260
+ intent = reset
261
+ const text = JSON.stringify({ reset, address, base: deps.base })
262
+ deps.storage.setItem(RESET_KEY, text)
263
+ if (typeof deps.storage.flushed === 'function') await deps.storage.flushed()
264
+ if (typeof deps.flushed === 'function') await deps.flushed()
265
+ if (typeof deps.durableRead === 'function' && await deps.durableRead(RESET_KEY) !== text) throw Object.assign(new Error('the email move could not be kept on this device'), { code: 'move_not_kept' })
266
+ }
267
+ let r
268
+ try { r = await client.resetBegin({ device: await signer(), address, getCode, onIntent }) } catch (e) {
269
+ // refused for certain (a wrong or cancelled code, the service's no): the start never happened — the kept id goes; a network
270
+ // failure keeps it (the start may have landed: the card asks the service)
271
+ const definite = !!(e && ((e.status >= 400 && e.status < 500) || ['cancelled', 'no_screen', 'email_code_wrong', 'move_not_kept'].includes(e.code)))
272
+ if (intent && definite && (this.pendingReset() || {}).reset === intent) deps.storage.removeItem(RESET_KEY)
273
+ throw e
274
+ }
227
275
  const rec = { reset: r.reset, address, ready_at: r.ready_at, expires: r.expires, base: deps.base }
228
276
  deps.storage.setItem(RESET_KEY, JSON.stringify(rec))
229
277
  return rec
@@ -256,12 +304,25 @@ export function makeAcctV2(deps) {
256
304
  /** A move that can no longer finish (cancelled, superseded, expired): forget it here. */
257
305
  forgetReset() { deps.storage.removeItem(RESET_KEY) },
258
306
 
307
+ /** A HALF-MADE ACCOUNT STATE an older app left (side sweep: interrupted-restore-retry): written by a restore or an adopt BEFORE
308
+ * the `adopting` mark existed, its backup never applied — so this device holds neither a master nor a first code pending (a new
309
+ * account's own state carries `setup`). Such a state is not an account here: Restore may run over it. Unknown (no vault to ask)
310
+ * → false. */
311
+ halfMade() {
312
+ const s = state()
313
+ if (!s || s.setup || s.adopting || typeof deps.vault !== 'function') return false
314
+ let v = null
315
+ try { v = (deps.vaultRecord && deps.vaultRecord()) || deps.vault() } catch { return false }
316
+ return !(v && (v.master || (v.pending && v.pending.master)))
317
+ },
318
+
259
319
  /** § 8.1 — bring an account on the new service to THIS device: the recovery code, an email code, and a security key when
260
320
  * the account is Advanced. Both objects are opened here BEFORE the device is registered (a wrong code or a damaged copy
261
321
  * registers nothing); then the restore finishes, and only then is the backup applied and the account kept. */
262
322
  async restoreHere({ address, getCode, typedCode, label = myLabel() }) {
263
323
  need()
264
- if (state()) throw Object.assign(new Error('already_migrated'), { code: 'already_migrated' })
324
+ const prior = state(), half = !!prior && this.halfMade()
325
+ if (prior && !half) throw Object.assign(new Error('already_migrated'), { code: 'already_migrated' })
265
326
  let codeBytes
266
327
  try { codeBytes = deps.codeBytesOf(typedCode) } catch { throw Object.assign(new Error('bad_code'), { code: 'bad_code' }) }
267
328
  await freshKeyIfTaken()
@@ -275,11 +336,32 @@ export function makeAcctV2(deps) {
275
336
  const payload = backup ? await deps.openBackup(master, dec.decode(backup)) : null
276
337
  if (!payload) throw Object.assign(new Error('backup_unopened'), { code: 'backup_unopened' })
277
338
  if (deps.checkIncomingBackup) await deps.checkIncomingBackup(payload, backupId)
278
- await r.finish()
279
- setState({ acct: r.acct, base: deps.base, at: Date.now(), trust: null, address: r.address }) // the address asked (it may be a function)
280
- const legacy = Array.isArray(r.versions) && r.versions.some((v) => v.id === backupId && v.ver === 'legacy')
281
- const rooms = await deps.applyRestored({ master, payload, code: typedCode, legacy, ...(deps.checkIncomingBackup ? { appChecked: true } : {}) })
282
- return { acct: r.acct, rooms, address: r.address }
339
+ // the finish may land while its reply is lost: remember the key it registered, so a retry keeps it (freshKeyIfTaken), and a
340
+ // retry the service refuses as `key_registered` with this key active on the service is that earlier finish (side sweep 2026-11-28)
341
+ const sentBefore = restoringWith(device.spk, r.acct)
342
+ try { deps.storage.setItem(RESTORING_KEY, JSON.stringify({ spk: device.spk, acct: r.acct, at: Date.now() })) } catch { /* private mode */ }
343
+ try { await r.finish() } catch (e) {
344
+ let landed = false
345
+ // …or the half-made restore of THIS account an older app left (its finish landed before the page died): the same key
346
+ if ((sentBefore || (half && prior.acct === r.acct)) && e && e.code === 'key_registered') { try { landed = (await client.deviceStatus(device)).state === 'active' } catch { /* unknown: the error stands */ } }
347
+ // not this account's earlier finish (another account's, or a revoked key): forget the mark, so the next try makes a new key
348
+ if (!landed) { if (e && e.code === 'key_registered') { try { deps.storage.removeItem(RESTORING_KEY) } catch { /* */ } } throw e }
349
+ }
350
+ // ⛔ THE SAME GAP adoptLinked closed in 10·Q#6 (side sweep 11-28, verified): the state was written before the backup was applied,
351
+ // so a page killed in between — or applyRestored throwing (its own "Retry the restore") — left an account state with no master,
352
+ // and every retry answered already_migrated: Reset this device was the only way out. Now `adopting` until applied, and a
353
+ // failure drops the state, so the restore can be run again.
354
+ const st = { acct: r.acct, base: deps.base, at: Date.now(), trust: null, address: r.address } // the address asked (it may be a function)
355
+ adoptingNow = true
356
+ setState({ ...st, adopting: true })
357
+ try {
358
+ const legacy = Array.isArray(r.versions) && r.versions.some((v) => v.id === backupId && v.ver === 'legacy')
359
+ const rooms = await deps.applyRestored({ master, payload, code: typedCode, legacy, ...(deps.checkIncomingBackup ? { appChecked: true } : {}) })
360
+ const now = state()
361
+ setState({ ...(now && now.acct === r.acct ? now : st), adopting: undefined }) // applied: the account is this device's for good
362
+ try { deps.storage.removeItem(RESTORING_KEY) } catch { /* */ }
363
+ return { acct: r.acct, rooms, address: r.address }
364
+ } catch (e) { deps.storage.removeItem(STATE_KEY); throw e } finally { adoptingNow = false }
283
365
  },
284
366
 
285
367
  /** § 8.6 Add a device, on the APPROVING device: register the new device's key with the service (this device + an email
@@ -292,6 +374,13 @@ export function makeAcctV2(deps) {
292
374
  await client.enrolDevice({ acct: s.acct, device: await signer(), newSpk, label, address, getCode, keys: deps.keys || null, onStep })
293
375
  return { acct: s.acct, base: deps.base, address: s.address || (typeof address === 'string' ? address : null) }
294
376
  },
377
+ /** …and its undo, when the new device declined the account or never collected it: the service removes the registration
378
+ * (only this device's own, minutes old, of a device that used nothing yet). → { cancelled: true }; throws on a refusal. */
379
+ async cancelEnrolment(newSpk) {
380
+ need()
381
+ if (!state()) throw Object.assign(new Error('not_migrated'), { code: 'not_migrated' })
382
+ return client.cancelEnrolment({ device: await signer(), newSpk })
383
+ },
295
384
 
296
385
  /** § 8.6 on the NEW device, once the approving device registered it and sent the account's keys over the link: this
297
386
  * device is the account's now — its backup is read through the service with this device's own key (a device-signed
@@ -444,6 +533,11 @@ export function makeAcctV2(deps) {
444
533
  const s = state()
445
534
  if (!s) throw Object.assign(new Error('not_migrated'), { code: 'not_migrated' })
446
535
  const prep = await deps.prepareRotation((id) => this.readBackup(id))
536
+ // ⛔ THE RECORD OF THE EARLIER KEYS FIRST (side sweep round 5, attested-backup-stranded-after-code-rotation): written only after
537
+ // the activation, a phone restoring with the new code meanwhile found neither a new attested backup nor the record — success
538
+ // with no rooms. Written here, under the NEW master (harmless if this code is never activated), before the code is shown;
539
+ // a failed write throws (attested_prev_not_saved) and nothing is activated — the old code keeps working.
540
+ if (deps.beforeActivate) await deps.beforeActivate(prep)
447
541
  const r = await client.rotate({
448
542
  acct: s.acct, device: await signer(), address, getCode,
449
543
  newCode: deps.codeBytesOf(prep.newCode), newMaster: prep.newMaster, backupId: prep.backupId, wrapperId: prep.wrapperId,
@@ -560,11 +654,16 @@ export function makeAcctV2(deps) {
560
654
  const dev = await signer()
561
655
  const { devices = [] } = await client.signedOutPush(dev)
562
656
  let n = 0, left = devices.length
657
+ // ONE ADDRESS, TWO RECORDS (side sweep: device-signout-removes-shared-current-endpoint): a device back under a new key keeps its
658
+ // push address, so the record signed out may name THIS device's own — taking it off every Space silenced this device. Marked
659
+ // done, left where it is — as one ANOTHER active device registered too (the service's `shared`; an older service sends none).
660
+ let mine = null // asked once, and only when there is an address to compare (the push module is loaded only then)
661
+ const mineNow = async () => { if (mine === null) { try { mine = deps.pushEndpoint ? await deps.pushEndpoint() : undefined } catch { mine = undefined } } return mine }
563
662
  for (const d of devices) {
564
663
  let endpoint = null
565
664
  try { endpoint = await deps.openPush(d.sealed) } catch { /* sealed under another master (before a new code): nothing to do here */ }
566
665
  if (!endpoint) continue
567
- if (!(await deps.withdrawPush([endpoint]))) continue
666
+ if (d.shared !== true && endpoint !== (await mineNow()) && !(await deps.withdrawPush([endpoint]))) continue
568
667
  await client.markPushPruned(dev, d.device, await sha256Hex(endpoint))
569
668
  n++; left--
570
669
  }
package/acctV2Client.js CHANGED
@@ -189,6 +189,10 @@ export function accountClient({ base, fetch: f = globalThis.fetch, now = () => M
189
189
  const proofs = { device: { spk: device.spk, sig: await sigOf(device, Tb) }, ...(ticket ? { email_authz: ticket } : {}), ...(await keyProof(c, Tb, keys)) }
190
190
  return req('POST', '/v2/account/enrol_device', { body: { challenge: c.challenge, params, proofs, idem: b64u(rand(16)) }, signer: device })
191
191
  },
192
+ /** § 8.6's undo: THIS device takes back the enrolment it just made of `newSpk` (the link was declined there, or never
193
+ * collected) — its own key alone; the service allows it only for its own fresh enrolment of a device that has used nothing.
194
+ * → { cancelled: true }; a service without the route answers 404 (thrown, as every refusal). */
195
+ cancelEnrolment: ({ device, newSpk }) => req('POST', '/v2/account/enrol_device/cancel', { body: { device_spk: String(newSpk || '') }, signer: device }),
192
196
  /** Release checklist 1.11 — delete this account on the service (as a sign-out is proved: this device + an email code). */
193
197
  async eraseAccount({ acct, device, address, getCode, keys = null, keep = null }) {
194
198
  // ⛔ 10·Q#3 (pass 10): a request whose answer was lost past these retries (offline, the page killed) is KEPT (`keep`) and a
@@ -252,14 +256,20 @@ export function accountClient({ base, fetch: f = globalThis.fetch, now = () => M
252
256
  return ticket
253
257
  },
254
258
  /** Start: the intent, a claim code, the start — the week begins. → { reset, ready_at, expires } */
255
- async resetBegin({ device, address, getCode }) {
259
+ async resetBegin({ device, address, getCode, onIntent }) {
256
260
  const { reset } = await req('POST', '/v2/account/reset/intent', { body: { address, dest: 'new' }, signer: device })
261
+ if (onIntent) await onIntent(reset) // kept BEFORE the start: an answer lost after the service took it still names the move (side sweep: email-move-start-reply-loses-pending-request)
257
262
  const ticket = await this.claimTicket({ reset, address, getCode })
258
263
  const r = await again(() => req('POST', `/v2/account/reset/${reset}/start`, { body: { ticket }, signer: device }))
259
264
  return { reset, ready_at: r.ready_at, expires: r.expires }
260
265
  },
261
266
  /** Finish, once the week is over: a NEW claim code, the claimant's signature → { acct } (a fresh account, this device in it). */
262
267
  async resetFinish({ device, reset, address, getCode, label = 'This device' }) {
268
+ // FINISHED ALREADY, ITS ANSWER LOST (the page closed): the service sends claim codes only for a move starting or waiting, and
269
+ // hands a finished move's account back to its claimant with no code (reset.mjs, 10·A#2) — asked so (side sweep:
270
+ // email-move-finish-retry-waits-for-unavailable-code)
271
+ const st = await this.resetState({ device, reset }).catch(() => null)
272
+ if (st && st.state === 'done') return again(() => req('POST', `/v2/account/reset/${reset}/finish`, { body: { label }, signer: device }))
263
273
  const ticket = await this.claimTicket({ reset, address, getCode })
264
274
  return again(() => req('POST', `/v2/account/reset/${reset}/finish`, { body: { ticket, label }, signer: device }))
265
275
  },