@witbitz/sdk 4.4.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 (79) hide show
  1. package/README.md +2 -2
  2. package/a2aCore.js +15 -0
  3. package/accountErase.js +9 -3
  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/awsKey.js +3 -1
  11. package/backupRecord.js +3 -0
  12. package/codeAttachments.js +1 -0
  13. package/codeCache.js +27 -3
  14. package/codeCloud.js +2 -0
  15. package/codeComputers.js +8 -0
  16. package/codeSent.js +43 -2
  17. package/codeTransport.js +24 -5
  18. package/connections.js +21 -3
  19. package/decrypt.html +69 -9
  20. package/eraseFile.js +15 -0
  21. package/idbSeal.js +5 -2
  22. package/inviteReceive.js +44 -0
  23. package/inviteSend.js +8 -2
  24. package/l1-worker-src.js +1 -1
  25. package/l1-worker.js +30 -14
  26. package/laneAssociation.js +11 -1
  27. package/laneLinkCore.js +9 -0
  28. package/ledgerView.js +30 -4
  29. package/manifest.json +78 -72
  30. package/offlineBundle.js +21 -0
  31. package/package.json +8 -2
  32. package/protectedLocal.js +34 -11
  33. package/reactionHolders.js +86 -0
  34. package/roomIntake.js +324 -0
  35. package/roomRoster.js +9 -2
  36. package/scheduleNext.js +60 -0
  37. package/sdkA2A.js +46 -8
  38. package/sdkAccount.js +71 -14
  39. package/sdkAccountDoc.js +3 -3
  40. package/sdkAccountSections.js +58 -18
  41. package/sdkAgui.js +33 -6
  42. package/sdkBackup.js +21 -6
  43. package/sdkBackupV2.js +15 -3
  44. package/sdkCloudDevice.js +12 -3
  45. package/sdkComputers.js +118 -17
  46. package/sdkDictation.js +1 -1
  47. package/sdkErase.js +3 -1
  48. package/sdkExports.js +15 -6
  49. package/sdkInvitations.js +4 -2
  50. package/sdkKeptAgent.js +19 -3
  51. package/sdkKeptIntake.js +100 -0
  52. package/sdkLaneLink.js +5 -6
  53. package/sdkRekey.js +72 -5
  54. package/sdkSchedules.js +8 -1
  55. package/sdkSpeech.js +14 -1
  56. package/sdkTemporaryRooms.js +2 -1
  57. package/sdkTurn.js +12 -4
  58. package/sharedViews.js +17 -1
  59. package/siri.js +29 -5
  60. package/spaceClient.js +96 -12
  61. package/spaceExport.js +50 -5
  62. package/spaceFork.js +15 -7
  63. package/spaceTemplates.js +2 -2
  64. package/speechOut.js +17 -3
  65. package/store.js +51 -13
  66. package/sw-notif-core.js +2 -1
  67. package/tapTrail.js +58 -0
  68. package/usageReceipts.js +12 -5
  69. package/vault-core.js +90 -16
  70. package/vault-kit.mjs +2 -2
  71. package/vault-screens.js +25 -11
  72. package/vaultAtRest.js +3 -2
  73. package/vaultCoreLock.js +3 -1
  74. package/vaultCorePush.js +58 -7
  75. package/vaultWorkerHost.js +9 -3
  76. package/witbitz-admin.d.ts +3 -0
  77. package/witbitz-admin.mjs +10 -10
  78. package/witbitz-sdk.d.ts +59 -23
  79. package/witbitz-sdk.js +271 -64
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.4.0 of this package is the release folder https://witbitz.chat/sdk/4.4.0/ unchanged (from commit
20
- `ab2472bedd442be2662fdf540a3175fd54ed1ad0`), 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
@@ -144,6 +144,14 @@ export const peersOf = (s, room) => (s.lanes[room] ? s.lanes[room].peers.map(({
144
144
  // ── the Sentinel ──
145
145
  /** What the Sentinel takes (a2a.mjs grant): PUBLIC halves and token hashes only. */
146
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
+ }
147
155
  /** sealed(mode, obj): attest the standing Sentinel, seal `obj` to it. plain(mode, extra): the unsealed ops. `err(kind, message, r)`
148
156
  * — kind 'refused' | 'unreachable' — lets each side keep its own codes. */
149
157
  export function sentinelCalls ({ post, auth = {}, attest, seal, err }) {
@@ -202,6 +210,13 @@ export const A2A_COLLECT_WINDOW_MS = 45_000
202
210
 
203
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). */
204
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
+ }
205
220
 
206
221
  export function applyRemovals(record, removals) {
207
222
  let changed = false
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 }
@@ -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.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 } : {}) })
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.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 } : {}), 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
  },
package/acctV2UiCore.js CHANGED
@@ -54,6 +54,7 @@ const MESSAGES = {
54
54
  keys_mismatch: 'The service answered with keys this device didn’t register. Nothing was changed.',
55
55
  session_ended: 'That took too long or something changed meanwhile. Nothing changed — start again.',
56
56
  pending_not_kept: 'This device couldn’t save the new recovery code, so it wasn’t activated. Your current code still works — free some space or try again.',
57
+ attested_prev_not_saved: 'The new recovery code wasn’t made: the service didn’t answer while your Spaces that need the Witbitz app were being linked to it. Your current code still works — try again in a moment.', // side sweep round 5: the record of the earlier keys comes before the new code
57
58
  address_taken: 'That email address already has an account on the new service. Restore it on this device instead (“Restore my account from the new service”).',
58
59
  bad_address: 'That doesn’t look like an email address.',
59
60
  state_changed: 'Something changed on your account meanwhile. Nothing changed — start again.',
@@ -259,7 +260,7 @@ export const emailCode = (address, kind = 'account') => withChoice(address, asyn
259
260
  })
260
261
 
261
262
  /** Append the section to the devices box; `rerender` redraws the panel after a change. */
262
- export function renderAcctV2Section(box, rerender) {
263
+ export function renderAcctV2Section(box, rerender, { devicesBox = null } = {}) { // devicesBox: the devices and "Sign out all" go there (the vault's Your devices view)
263
264
  const a = acctV2()
264
265
  if (!a.enabled()) { renderMoveOnly(box, rerender); return } // an account on the OLD service: only the move, where it is open
265
266
  const s = a.state()
@@ -301,7 +302,10 @@ export function renderAcctV2Section(box, rerender) {
301
302
  b.onclick = () => startFresh(a, address, rerender)
302
303
  sec.append(t, d, b); box.append(sec); return
303
304
  }
304
- sec.append(t, d, serviceDevicesBlock(a, address, rerender), b, nc)
305
+ // ON THEIR OWN CARD, WHERE ASKED (the owner, 2026-11-27, of the vault's Back up & recovery: "too many logouts … It should be on a
306
+ // different card"): the devices and "Sign out all other devices now" go to the caller's box; the recovery code stays here
307
+ if (devicesBox) { b.style.marginTop = '10px'; devicesBox.replaceChildren(serviceDevicesBlock(a, address, rerender), b); sec.append(t, d, nc) }
308
+ else sec.append(t, d, serviceDevicesBlock(a, address, rerender), b, nc)
305
309
  const mw = moveWarningBlock(rerender) // § 11.5, 3a: a move of this account's address under way — above everything else
306
310
  if (mw) sec.prepend(mw)
307
311
  box.append(sec)
@@ -487,6 +491,7 @@ export function moveOpen(svc, fetchImpl = (...x) => fetch(...x)) {
487
491
  try {
488
492
  const r = await fetchImpl(String(svc).replace(/\/+$/, '') + '/v2/account/legacy/intent', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' })
489
493
  const on = r.status !== 501 && r.status !== 404 && r.status < 500
494
+ if (r.status >= 500 && r.status !== 501) return false // an outage is not an answer: asked again next time (side sweep 2026-11-28: a 503 hid the move until reload)
490
495
  _moveKnown.set(svc, on)
491
496
  return on
492
497
  } catch { return false } finally { _moveProbe.delete(svc) }
@@ -526,12 +531,12 @@ export async function offerAutoMove(rerender = () => {}) {
526
531
  if (!oldAccountHere()) return false
527
532
  return moveAccount(rerender, { auto: true })
528
533
  }
529
- const AUTO_MOVE_TEXT = (address) => `Your account needs a one-time move to Witbitz’s new account service.\n\nWe’ll send a code to ${address} — type it in the next step. Your Spaces and your recovery code stay as they are.\n\nWhen the move is done, your OTHER devices are signed out: each clears itself the next time it’s online and says why. To use one again, restore your Spaces on it with your recovery code, or add it from this device (Add a device).\n\nYou can also do it later: Settings → Back up & recovery.`
534
+ const AUTO_MOVE_TEXT = (address) => `Your account needs a one-time move to Witbitz’s new account service.\n\nWe’ll send a code to ${address} — type it in the next step. Your Spaces and your recovery code stay as they are.\n\nWhen the move is done, your OTHER devices are signed out: each clears itself the next time it’s online and says why. To use one again, restore your Spaces on it with your recovery code, or add it from this device (Add a device).\n\nIts old backup has no account key, so it moves with your email only: Advanced Backup isn’t available for it afterwards, and the original backup is kept as it was for a year.\n\nYou can also do it later: Settings → Back up & recovery.`
530
535
  /** The move itself. The device is switched onto the service for it, and back if the account did not move. → whether it moved. */
531
536
  async function moveAccount(rerender, { auto = false } = {}) {
532
537
  const address = accountAddress()
533
538
  if (!address) { if (!auto) await notice('Sign in with your email on this device first.'); return false }
534
- if (!(await confirmSheet(auto ? { message: AUTO_MOVE_TEXT(address), confirmLabel: 'Move now', cancelLabel: 'Not now', destructive: false } : { message: `Move this account to the new account service?\n\nWe’ll send a code to ${address}. Your Spaces and your recovery code stay as they are.\n\nWhen the move is done, your OTHER devices are signed out: each clears itself the next time it’s online and says why. To use one again, restore your Spaces on it with your recovery code, or add it from this device (Add a device).`, confirmLabel: 'Move', destructive: false }))) return false
539
+ if (!(await confirmSheet(auto ? { message: AUTO_MOVE_TEXT(address), confirmLabel: 'Move now', cancelLabel: 'Not now', destructive: false } : { message: `Move this account to the new account service?\n\nWe’ll send a code to ${address}. Your Spaces and your recovery code stay as they are.\n\nWhen the move is done, your OTHER devices are signed out: each clears itself the next time it’s online and says why. To use one again, restore your Spaces on it with your recovery code, or add it from this device (Add a device).\n\nIf its old backup has no account key, it moves with your email only: Advanced Backup isn’t available for it afterwards, and the original backup is kept as it was for a year.`, confirmLabel: 'Move', destructive: false }))) return false
535
540
  let a = acctV2(), undo = () => {}
536
541
  if (!a.enabled()) {
537
542
  const svc = moveSvc()
@@ -558,12 +563,16 @@ async function moveAccount(rerender, { auto = false } = {}) {
558
563
  }
559
564
  }
560
565
  // MOVED. Only now are the other devices signed out (a move that failed signed out nobody).
566
+ // a SILENT move resumed here (its answer was lost): the other devices join it by themselves — never signed out (side sweep 2026-11-28)
561
567
  let others = null
562
- try { others = dep().afterMove ? await dep().afterMove({ trust: r.legacy_trust }) : null } catch { others = null }
568
+ if (r.silent) others = []
569
+ else { try { others = dep().afterMove ? await dep().afterMove({ trust: r.legacy_trust }) : null } catch { others = null } }
563
570
  const emailOnly = r.legacy_trust === 'email_only'
564
571
  await notice('Done. This account now uses the new account service, with the same recovery code.'
565
572
  + (emailOnly ? '\n\nIt was moved with your email only (its old backup had no account key), so it stays in a lower-trust state: Advanced Backup isn’t available for it, and the original backup is kept as it was for a year.' : '')
566
- + (Array.isArray(others) && !others.length ? '' : '\n\nYour other devices are being signed out: each clears itself the next time it’s online and says why. To use one again, restore your Spaces on it with your recovery code, or add it from this device (Add a device).'))
573
+ + (others && others.unconfirmed ? '\n\nThis device could not confirm that your other devices were told to sign out. If one still shows your Spaces, sign it out from Settings → Your devices on this device.'
574
+ : r.silent ? '\n\nYour other devices join it by themselves the next time they open.'
575
+ : Array.isArray(others) && !others.length ? '' : '\n\nYour other devices are being signed out: each clears itself the next time it’s online and says why. To use one again, restore your Spaces on it with your recovery code, or add it from this device (Add a device).'))
567
576
  rerender()
568
577
  return true
569
578
  }
@@ -605,6 +614,17 @@ export async function approveNewDevice({ newSpk, label }) {
605
614
  }
606
615
  }
607
616
 
617
+ /** § 8.6's undo, on the APPROVING device (both apps' givers): the new device declined the account, or never collected it, after
618
+ * approveNewDevice registered it — take the registration back, so it is not left among the account's devices. Best effort and
619
+ * silent: an older service (404/501), a refusal (the device already used the account, the window passed) or no network leaves
620
+ * it as before — Your devices → Sign out. → true when the service removed it. */
621
+ export async function cancelNewDevice(newSpk) {
622
+ try { const a = acctV2(); const r = await a.cancelEnrolment(newSpk); return !!(r && r.cancelled) } catch (e) {
623
+ console.warn('[link] the new device’s registration stays: ' + ((e && (e.code || e.message)) || e))
624
+ return false
625
+ }
626
+ }
627
+
608
628
  /** § 8.6 on the NEW device: the approving device registered it and sent { acct, base, address } with the account's keys.
609
629
  * This device is switched on for that service (only the service this app may use — acctV2Switch.baseOf) and reads the
610
630
  * backup through it with its own key. → { ok: true, rooms } | { ok: false, reason }; nothing kept on failure. */
@@ -797,7 +817,7 @@ export function renderAdvanced(sec, a, address, rerender, { confirm = confirmShe
797
817
  * restore goes on), { done, rooms, address } = restored, { message } = stop and show it. */
798
818
  export async function restoreFromCode(code, { service = null, signIn = null } = {}) {
799
819
  let a = acctV2()
800
- if (a.enabled() && a.state()) return null // this device already has an account on the new service
820
+ if (a.enabled() && a.state() && !(a.halfMade && a.halfMade())) return null // this device already has an account on the new service (not an older app's half-made restore — side sweep: interrupted-restore-retry)
801
821
  // A DEVICE NOT YET ON THE NEW SERVICE (a new phone, a fresh browser): once new accounts start there (the release switch,
802
822
  // acctV2Switch.newAccountService — the same rule, so every account it makes can be restored), the normal Restore asks it
803
823
  // too, switching this device on for the try and back if the code is not an account there. Without this, an account made