@witbitz/sdk 4.7.0 → 4.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.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.7.0 of this package is the release folder https://witbitz.chat/sdk/4.7.0/ unchanged (from commit
20
- `a98d5ae3b3fceb654ceed8264e49babac09f8d62`), plus this README, `package.json` and `LICENSE`. Its `manifest.json` lists the sha384 of every file; each file in the
19
+ Version 4.7.1 of this package is the release folder https://witbitz.chat/sdk/4.7.1/ unchanged (from commit
20
+ `00dd61d7a078a10492a7f464b2734f66d0a92287`), 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/acctV2UiCore.js CHANGED
@@ -531,12 +531,12 @@ export async function offerAutoMove(rerender = () => {}) {
531
531
  if (!oldAccountHere()) return false
532
532
  return moveAccount(rerender, { auto: true })
533
533
  }
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.`
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. The original backup is kept for a year. After the move, you can enroll security keys if Advanced Backup is available on this service.\n\nYou can also do it later: Settings → Back up & recovery.`
535
535
  /** The move itself. The device is switched onto the service for it, and back if the account did not move. → whether it moved. */
536
536
  async function moveAccount(rerender, { auto = false } = {}) {
537
537
  const address = accountAddress()
538
538
  if (!address) { if (!auto) await notice('Sign in with your email on this device first.'); 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
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. The original backup is kept for a year. After the move, you can enroll security keys if Advanced Backup is available on this service.`, confirmLabel: 'Move', destructive: false }))) return false
540
540
  let a = acctV2(), undo = () => {}
541
541
  if (!a.enabled()) {
542
542
  const svc = moveSvc()
package/codeCache.js CHANGED
@@ -102,7 +102,7 @@ export async function removeCachedSession(cid, sid, store = idb, local) {
102
102
  const saved = await loadList(cid, store, { strict: true })
103
103
  if (saved?.list.some(row => row.id === sid)) {
104
104
  await saveList(cid, saved.list.filter(row => row.id !== sid), store, { allowEmpty: true })
105
- if ((await loadList(cid, store))?.list.some(row => row.id === sid)) throw new Error('The cached session directory could not be updated')
105
+ if ((await loadList(cid, store, { strict: true }))?.list.some(row => row.id === sid)) throw new Error('The cached session directory could not be updated')
106
106
  }
107
107
  const raw = local?.getItem('oc.list')
108
108
  if (!raw) return
package/deviceKeyCore.js CHANGED
@@ -6,27 +6,65 @@
6
6
  export const DEVKEY_IDB = 'devkey:v1'
7
7
  const b64u = (u8) => btoa(String.fromCharCode(...u8)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
8
8
 
9
- /** A NEW key, kept → { priv, pub, spk, at } */
10
- export async function newKeyRecord(store) {
9
+ // Boot, pairing and another tab can all ask before the first key exists. Serialize the read and possible
10
+ // write together, including intentional replacements. Each caller reads its own store inside the lock.
11
+ let localWrites = Promise.resolve()
12
+ function withKeyLock(work) {
13
+ const runHere = () => {
14
+ const result = localWrites.then(work)
15
+ localWrites = result.catch(() => {})
16
+ return result
17
+ }
18
+ let locks
19
+ try { locks = globalThis.navigator?.locks } catch { /* embedded without Web Locks */ }
20
+ if (!locks) return runHere()
21
+ let entered = false
22
+ return locks.request('witbitz:device-key', () => { entered = true; return work() }).catch(e => {
23
+ if (!entered && e?.name === 'SecurityError') return runHere()
24
+ throw e
25
+ })
26
+ }
27
+
28
+ export const validKeyRecord = rec => !!(rec?.spk && (typeof CryptoKey === 'undefined' || rec.priv instanceof CryptoKey))
29
+
30
+ // Start inside a readwrite transaction. Its completion, after the optional put, commits the returned winner.
31
+ export function keepKeyRequest(objectStore, key, candidate) {
32
+ const kept = { result: candidate }
33
+ const read = objectStore.get(key)
34
+ read.onsuccess = () => {
35
+ if (validKeyRecord(read.result)) kept.result = read.result
36
+ else objectStore.put(candidate, key)
37
+ }
38
+ return kept
39
+ }
40
+
41
+ async function generateAndKeep(store, first = false) {
11
42
  const kp = await crypto.subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, false, ['sign', 'verify']) // false ⇒ the PRIVATE half can never be exported
12
43
  const rec = { priv: kp.privateKey, pub: kp.publicKey, spk: b64u(new Uint8Array(await crypto.subtle.exportKey('raw', kp.publicKey))), at: Date.now() }
44
+ if (first && store.keep) return store.keep(DEVKEY_IDB, rec)
13
45
  await store.set(DEVKEY_IDB, rec) // CryptoKey is structured-cloneable → the non-extractable key persists as a key, never as bytes
14
46
  return rec
15
47
  }
16
48
 
49
+ /** Explicit replacement, even if this device already has a key. */
50
+ export const newKeyRecord = (store) => withKeyLock(() => generateAndKeep(store))
51
+
17
52
  /** The kept key, or a new one when there is none — or when what is kept is no key (sealed as JSON by an older protected-storage
18
53
  * build → `{}`). → { priv, pub, spk, at } */
19
54
  export async function ensureKeyRecord(store) {
20
- const rec = await store.get(DEVKEY_IDB)
21
- if (rec && rec.spk && (typeof CryptoKey === 'undefined' || rec.priv instanceof CryptoKey)) return rec
22
- return newKeyRecord(store)
55
+ return withKeyLock(async () => {
56
+ const rec = await store.get(DEVKEY_IDB)
57
+ if (validKeyRecord(rec)) return rec
58
+ return generateAndKeep(store, true)
59
+ })
23
60
  }
24
61
 
25
62
  const KEY_RETRY_MS = [150, 400, 900]
26
63
  /** A key store whose `get` THROWS on a read that keeps failing (never null) and whose `set` throws when not kept — so
27
64
  * ensureKeyRecord never writes a new key over one it could not read (sync sweep 11-16 #2 in the vault; 10·Q#2 in the regular app). */
28
- export function retryingKeyStore({ get, set }, { wait = (ms) => new Promise((r) => setTimeout(r, ms)) } = {}) {
65
+ export function retryingKeyStore({ get, set, keep }, { wait = (ms) => new Promise((r) => setTimeout(r, ms)) } = {}) {
29
66
  return {
67
+ keep,
30
68
  get: async (k) => {
31
69
  let last = null
32
70
  for (let i = 0; i <= KEY_RETRY_MS.length; i++) {
package/emailFork.js CHANGED
@@ -6,6 +6,7 @@
6
6
  // member's device checks before it follows. Moved verbatim out of witbitz-sdk.js (Space#fork, _maybeMoved,
7
7
  // _newRoomKeepsGov, 2026-10-05); the MINT and the transport stay with the caller (the SDK's client, the app's split-,
8
8
  // tenant- and enclave-aware path).
9
+ import { hasRoles } from './roomRoles.js'
9
10
  import { memberHash } from './rosterHash.js'
10
11
  import { boxesHash, bareEC, jkey } from './spaceFork.js'
11
12
  import { sealTo, openBox } from './e2ee.js'
@@ -89,14 +90,14 @@ export function mayMove(cfg, email) {
89
90
  /** The OWNERS step of a move, before anything is minted: fills the new gate's owners (and, unless stated, the admins it
90
91
  * still admits) from the old room, and refuses a move the server would refuse. → { gate, gov } (gov null in a room
91
92
  * without owners). `statedAdmins` = whether the caller stated the new admins itself. */
92
- export function planGovernance(old, gate, email, statedAdmins) {
93
+ export function planGovernance(old, gate, email, statedAdmins, byOwner = false) {
93
94
  const { owners: oldOwners, admins: oldAdmins } = govOf(old)
94
95
  const me = String(email || '').toLowerCase()
95
- if (!oldOwners.length) return { gate, gov: null }
96
+ if (!oldOwners.length && !old?.owners?.tags?.length) return { gate, gov: null }
96
97
  gate.owners = gate.owners || { emails: oldOwners }
97
98
  if (!statedAdmins && oldAdmins.length) gate.admins = { emails: oldAdmins.filter((e) => admittedBy(gate, e)) }
98
99
  const gov = { owners: (gate.owners && gate.owners.emails) || [], admins: (gate.admins && gate.admins.emails) || [] }
99
- const why = govRefusal(oldOwners, oldAdmins, gov, oldOwners.includes(me))
100
+ const why = govRefusal(oldOwners, oldAdmins, gov, byOwner || oldOwners.includes(me))
100
101
  if (why) throw Object.assign(new Error('witbitz: ' + why), { code: 'not_owner' })
101
102
  const out = [...gov.owners, ...gov.admins].find((x) => !admittedBy(gate, x))
102
103
  if (out) throw new Error(`witbitz: "${out}" is an owner or admin of the new room but its gate does not admit them — add them to emails`)
@@ -121,7 +122,7 @@ export function carriedHandles(old) {
121
122
  export function checkAdminCollections(data, cfg) {
122
123
  const adminOnly = data && typeof data === 'object' ? Object.entries(data).find(([, v]) => v && typeof v === 'object' && v.write === 'admins') : null
123
124
  const g = cfg || {}
124
- if (adminOnly && !(g.admins && Array.isArray(g.admins.emails) && g.admins.emails.length) && !(g.owners && Array.isArray(g.owners.emails) && g.owners.emails.length)) {
125
+ if (adminOnly && !hasRoles(g)) {
125
126
  throw Object.assign(new Error(`witbitz: collection "${adminOnly[0]}" is write: 'admins', but the room has no admins or owners — give admission.admins (or owners), or drop write: 'admins'`), { code: 'admins_required' })
126
127
  }
127
128
  }
package/emptySpaces.js CHANGED
@@ -27,18 +27,24 @@ export const setEmptySpacesHooks = (h) => { _h = { ..._h, ...h } }
27
27
  /** A message is anything a person or the assistant put in the room — not its name (title entries) or a system line. */
28
28
  export const hasMessages = (entries) => (Array.isArray(entries) ? entries : []).some((e) => e && e.kind !== 'title' && !e.sys)
29
29
  /** Other people named in its sealed config (invited by email, admins, owners) — then it is not only yours. */
30
- export async function ownAdmissionEntries(config, email, readRoster) {
30
+ export async function ownAdmissionEntries(config, email, readRoster, readTags = async () => []) {
31
31
  const mine = String(email || '').trim().toLowerCase()
32
- if (!mine || ![config?.allow, config?.admins, config?.owners].some(p => p?.users?.length || p?.mh?.length)) return []
33
- const book = await Promise.resolve().then(readRoster).catch(() => null)
34
- if (book?.status !== 200) return []
35
- return Object.values(book.seen || {}).filter(row => String(row?.email || '').trim().toLowerCase() === mine)
36
- .flatMap(row => Array.isArray(row.entries) ? row.entries : [])
32
+ if (!mine || ![config?.allow, config?.admins, config?.owners].some(p => p?.users?.length || p?.mh?.length || p?.tags?.length)) return []
33
+ const [book, tags] = await Promise.all([Promise.resolve().then(readRoster).catch(() => null), Promise.resolve().then(readTags).catch(() => [])])
34
+ const own = new Set(tags.map(tag => 'mh:' + tag))
35
+ if (book?.status === 200) for (const row of Object.values(book.seen || {})) {
36
+ if (!row || row.left || row.swapped || !Array.isArray(row.entries)) continue
37
+ if (String(row.email || '').trim().toLowerCase() === mine || row.entries.some(entry => tags.some(tag => entry === 'mh:' + tag))) {
38
+ for (const entry of row.entries) own.add(entry)
39
+ }
40
+ }
41
+ return [...own]
37
42
  }
38
43
  export function othersIn(config, me, selfHash = '', selfEntries = []) {
39
44
  if (!config || typeof config !== 'object' || config.gated || config.error) return true
40
45
  for (const policy of [config.allow, config.admins, config.owners]) {
41
46
  if (policy?.mh && (!Array.isArray(policy.mh) || policy.mh.some(hash => hash !== selfHash && !selfEntries.includes('mh:' + hash)))) return true
47
+ if (policy?.tags && (!Array.isArray(policy.tags) || policy.tags.some(tag => !selfEntries.includes('mh:' + tag)))) return true
42
48
  if (policy?.domains?.length) return true
43
49
  if (policy?.users?.some(user => !user?.handle || !selfEntries.includes('u:' + String(user.handle).toLowerCase()))) return true
44
50
  }
package/idb.js CHANGED
@@ -6,7 +6,8 @@
6
6
  // through idbSeal.js — with device storage protection on they are sealed on write and opened on read; while the device is
7
7
  // locked a protected key reads as absent and a write is dropped. Every other key, and every call while protection is off,
8
8
  // is exactly what it was. `getRaw/setRaw/entriesRaw` bypass the layer for the migration itself.
9
- import { wrapForStore, unwrapFromStore, migrateIdbProtection, unprotectIdb, idbNamingState, IDB_SHARED_NAMES } from './idbSeal.js'
9
+ import { DEVKEY_IDB, keepKeyRequest, validKeyRecord } from './deviceKeyCore.js'
10
+ import { wrapForStore, unwrapFromStore, unwrapStrict, migrateIdbProtection, unprotectIdb, idbNamingState, IDB_SHARED_NAMES } from './idbSeal.js'
10
11
  import { seal, open as openSealed } from './deviceSeal.js'
11
12
  import { isOpaqueName } from './sealedNames.js'
12
13
 
@@ -37,7 +38,8 @@ export const idb = (() => {
37
38
  // under this app's address — and this frame keeps no database of its own. Set by the page's loader before the app runs.
38
39
  const vault = () => (typeof globalThis !== 'undefined' && typeof globalThis.__wbAppIdb === 'function' ? globalThis.__wbAppIdb : null)
39
40
  const getRaw = (k) => (vault() ? vault()('get', k).then((v) => (v === undefined ? null : v)) : tx('readonly', (s) => s.get(k), (m) => copy(m.get(k)))).catch(() => null)
40
- const setRaw = (k, v) => (vault() ? vault()('set', k, v) : tx('readwrite', (s) => s.put(v, k), (m) => { m.set(k, copy(v)) })).catch(() => {})
41
+ const setRawStrict = (k, v) => vault() ? vault()('set', k, v) : tx('readwrite', (s) => s.put(v, k), (m) => { m.set(k, copy(v)) })
42
+ const setRaw = (k, v) => setRawStrict(k, v).catch(() => {})
41
43
  // ★★ A PREFIX READ LOADS ONLY THAT PREFIX (2026-10-06). Every key here is a string, so the keys under `pfx` are exactly the
42
44
  // range [pfx, pfx + '\uffff'): IndexedDB answers it from the index without touching another prefix's VALUES. This used to be
43
45
  // getAllKeys() + getAll() over the WHOLE store and a filter in JS — so the worker's `mk:` map at boot, its unseal/relock
@@ -75,6 +77,23 @@ export const idb = (() => {
75
77
  // instead; no database at all still answers from memory, as before.
76
78
  const getRawStrict = (k) => (vault() ? vault()('get', k).then((v) => (v === undefined ? null : v)) : tx('readonly', (s) => s.get(k), (m) => copy(m.get(k))))
77
79
  const self = {
80
+ async keepDeviceKey(k, candidate, allowMemory = true) {
81
+ if (k !== DEVKEY_IDB) throw new Error('not the device key')
82
+ if (vault()) {
83
+ try { return await vault()('keepDeviceKey', k, candidate) } catch (e) {
84
+ if (e?.message !== 'unknown op keepDeviceKey') throw e
85
+ // An older vault has only get/set. The caller holds the origin lock where supported.
86
+ const existing = await getRawStrict(k)
87
+ if (validKeyRecord(existing)) return existing
88
+ await vault()('set', k, candidate)
89
+ return candidate
90
+ }
91
+ }
92
+ return tx('readwrite', s => keepKeyRequest(s, k, candidate), allowMemory && (m => {
93
+ if (!validKeyRecord(m.get(k))) m.set(k, candidate)
94
+ return copy(m.get(k))
95
+ }))
96
+ },
78
97
  get: (k) => (!isNamed(k) ? legacyGet(k) : !idbNamingState().namer ? Promise.resolve(null)
79
98
  : (async () => { const v = await getRaw(await idbNamingState().namer.opaque(k)); return v != null ? openSealed(idbNamingState().key, v) : legacyGet(k) })()).catch(() => null),
80
99
  set: (k, v) => (!isNamed(k) ? wrapForStore(k, v).then((stored) => (stored === undefined ? undefined : setRaw(k, stored)))
@@ -102,9 +121,17 @@ export const idb = (() => {
102
121
  })().catch(() => []),
103
122
  // §NAMES: the real names under a prefix, values never read (the protection migration and listings).
104
123
  names: (pfx) => (idbNamingState().on && idbNamingState().namer ? nameIndex().then(async (ix) => [...ix.map(([, n]) => n).filter((n) => n.startsWith(pfx)), ...await keysRaw(pfx)]) : keysRaw(pfx)).catch(() => []),
105
- getRaw, setRaw, delRaw, entriesRaw, keysRaw, nameIndex,
124
+ getRaw, setRaw, setRawStrict, delRaw, entriesRaw, keysRaw, nameIndex,
106
125
  /** A read that THROWS when it failed (never null for an error) — for a value that must not be replaced on a failed read. */
107
- getStrict: (k) => (!isNamed(k) ? getRawStrict(k).then((v) => (v == null ? v : unwrapFromStore(k, v))) : self.get(k)),
126
+ async getStrict(k) {
127
+ if (isNamed(k)) {
128
+ const { namer, key } = idbNamingState()
129
+ if (!namer) throw new Error('Unlock device storage to read this entry')
130
+ const v = await getRawStrict(await namer.opaque(k))
131
+ if (v != null) return openSealed(key, v)
132
+ }
133
+ return unwrapStrict(k, await getRawStrict(k))
134
+ },
108
135
  // §PROTECT: switch on / unlock (seal the clear content in place) and switch off (write it back) — the lock hooks call these.
109
136
  protect: (rawKey) => migrateIdbProtection(self, rawKey),
110
137
  unprotect: (rawKey) => unprotectIdb(self, rawKey),
package/idbSeal.js CHANGED
@@ -54,6 +54,13 @@ export async function unwrapFromStore (k, v) {
54
54
  try { return await openIf(st.key, v) } catch { return null }
55
55
  }
56
56
 
57
+ /** Destructive operations must distinguish a missing entry from one that could not be opened. */
58
+ export async function unwrapStrict(k, v) {
59
+ if (!isProtectedIdbKey(k) || !isSealed(v)) return v
60
+ if (!st.key) throw new Error('Unlock device storage to read this entry')
61
+ return openIf(st.key, v)
62
+ }
63
+
57
64
  /** The protected keys under every prefix, WITHOUT their values (keysRaw where the store has it; else the keys of entriesRaw). */
58
65
  const protectedKeys = async (idb) => { const out = []; for (const pfx of IDB_PROTECTED_PREFIXES) { if (typeof idb.keysRaw === 'function') out.push(...await idb.keysRaw(pfx)); else for (const [k] of await idb.entriesRaw(pfx)) out.push(k) } return out }
59
66