@witbitz/sdk 4.6.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 +2 -2
- package/acctV2Switch.js +3 -2
- package/acctV2UiCore.js +4 -4
- package/codeBrowse.js +3 -3
- package/codeCache.js +5 -4
- package/codeCloud.js +4 -0
- package/deviceKeyCore.js +44 -6
- package/earlierHistory.js +32 -0
- package/emailFork.js +8 -5
- package/emptySpaces.js +12 -6
- package/idb.js +31 -4
- package/idbSeal.js +7 -0
- package/l1-worker-src.js +1 -1
- package/manifest.json +39 -37
- package/memberChange.js +18 -2
- package/nativePush.js +6 -0
- package/package.json +4 -2
- package/reqEnvelope.js +1 -1
- package/roomName.js +22 -6
- package/roomRoles.js +138 -0
- package/roomRoster.js +4 -1
- package/sdkA2A.js +2 -2
- package/sdkAccount.js +3 -1
- package/sdkBackup.js +1 -0
- package/sdkBackupV2.js +20 -9
- package/sdkCloudDevice.js +18 -9
- package/sdkComputers.js +1 -0
- package/sdkExports.js +11 -3
- package/sdkInvitations.js +2 -2
- package/sdkPlan.js +21 -9
- package/sdkRekey.js +64 -7
- package/sdkVault.js +1 -1
- package/spaceClient.js +8 -4
- package/util.js +11 -1
- package/vault-core.js +92 -39
- package/vault-kit.mjs +1 -1
- package/witbitz-admin.mjs +10 -10
- package/witbitz-sdk.d.ts +20 -6
- package/witbitz-sdk.js +145 -34
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.
|
|
20
|
-
`
|
|
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/acctV2Switch.js
CHANGED
|
@@ -50,9 +50,10 @@ export function prodSwitch(loc = globalThis.location, storage = globalThis.local
|
|
|
50
50
|
// made on the new service stay on it.
|
|
51
51
|
export const NEW_ACCOUNTS_ON_V2 = true
|
|
52
52
|
/** Where a NEW account made here starts: the new service's address, or '' (the old service, as before). The production
|
|
53
|
-
* regular app and the production vault (the hosted app's v2 client runs there — acctV2VaultWiring.js); the staging app
|
|
54
|
-
*
|
|
53
|
+
* regular app and the production vault (the hosted app's v2 client runs there — acctV2VaultWiring.js); the staging app uses
|
|
54
|
+
* the staging service by default. A device switched off (?acctv2=off) stays off. */
|
|
55
55
|
export function newAccountService({ host, stored, releaseOn = NEW_ACCOUNTS_ON_V2 }) {
|
|
56
|
+
if (host === STAGING_APP) return stored === 'off' ? '' : STAGING_SERVICE
|
|
56
57
|
if (host === PROD_VAULT && stored !== 'off') return releaseOn ? PROD_SERVICE : '' // the hosted app: its vault
|
|
57
58
|
if (host !== PROD_APP || stored === 'off') return ''
|
|
58
59
|
if (stored === PROD_SERVICE) return PROD_SERVICE
|
package/acctV2UiCore.js
CHANGED
|
@@ -48,7 +48,7 @@ const MESSAGES = {
|
|
|
48
48
|
attestation_refused: 'That key can’t be used for Advanced Backup. It must be a YubiKey with a PIN (or fingerprint) set up.',
|
|
49
49
|
advanced_not_enabled: 'Advanced Backup isn’t available yet.',
|
|
50
50
|
possession_pending: 'Set up your recovery code first.',
|
|
51
|
-
email_only: 'This
|
|
51
|
+
email_only: 'This action is unavailable because the old backup was moved using email alone.',
|
|
52
52
|
too_many_keys: 'This account already has the most security keys it can hold (5).',
|
|
53
53
|
no_other_key: 'Removing a key needs another of your keys to confirm it.',
|
|
54
54
|
keys_mismatch: 'The service answered with keys this device didn’t register. Nothing was 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
|
|
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
|
|
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()
|
|
@@ -569,7 +569,7 @@ async function moveAccount(rerender, { auto = false } = {}) {
|
|
|
569
569
|
else { try { others = dep().afterMove ? await dep().afterMove({ trust: r.legacy_trust }) : null } catch { others = null } }
|
|
570
570
|
const emailOnly = r.legacy_trust === 'email_only'
|
|
571
571
|
await notice('Done. This account now uses the new account service, with the same recovery code.'
|
|
572
|
-
+ (emailOnly ? '\n\nIt was moved with your email only (its old backup had no account key),
|
|
572
|
+
+ (emailOnly ? '\n\nIt was moved with your email only (its old backup had no account key), and the original backup is kept as it was for a year.' : '')
|
|
573
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
574
|
: r.silent ? '\n\nYour other devices join it by themselves the next time they open.'
|
|
575
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).'))
|
package/codeBrowse.js
CHANGED
|
@@ -39,9 +39,9 @@ export function browseRow (report, cloud, egress, { session = '' } = {}) {
|
|
|
39
39
|
if (!watch) return null // no key on this computer: there is nothing to open, so there is nothing to say
|
|
40
40
|
// ★ A BROWSER PER SESSION (the owner, 2026-11-29: "when you see the browser is open in one session it could show it is
|
|
41
41
|
// closed in another. The state is completely separate"). A computer that says `perSession` reports each session's browser
|
|
42
|
-
// in `sessions`; only THIS session's entry decides here. An older
|
|
43
|
-
const per = !!
|
|
44
|
-
const mine = per && /^[A-Za-z0-9_-]{1,128}$/.test(String(session || '')) ? report.sessions[session] : null
|
|
42
|
+
// in `sessions`; only THIS session's entry decides here. An older connector or image has one browser: `running`, as before.
|
|
43
|
+
const per = !!report.perSession
|
|
44
|
+
const mine = per && /^[A-Za-z0-9_-]{1,128}$/.test(String(session || '')) ? report.sessions?.[session] : null
|
|
45
45
|
const running = per ? !!(mine && mine.open) : !!report.running
|
|
46
46
|
// the controls are held PER SESSION (the owner, 2026-11-29): this session's entry says `held`
|
|
47
47
|
const taken = per ? !!((mine && mine.held) || (Array.isArray(report.held) && report.held.includes('*'))) : !!report.takeover
|
package/codeCache.js
CHANGED
|
@@ -98,10 +98,11 @@ export async function clearSession(cid, sid, store = idb, strict = false) {
|
|
|
98
98
|
export async function removeCachedSession(cid, sid, store = idb, local) {
|
|
99
99
|
if (cid && sid) removed.add(SESS(cid, sid))
|
|
100
100
|
await clearSession(cid, sid, store, true)
|
|
101
|
-
|
|
101
|
+
// read strictly: a failed read is not "no list" — the deleted session's title would stay listed offline (sync sweep 11-27 P3)
|
|
102
|
+
const saved = await loadList(cid, store, { strict: true })
|
|
102
103
|
if (saved?.list.some(row => row.id === sid)) {
|
|
103
104
|
await saveList(cid, saved.list.filter(row => row.id !== sid), store, { allowEmpty: true })
|
|
104
|
-
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')
|
|
105
106
|
}
|
|
106
107
|
const raw = local?.getItem('oc.list')
|
|
107
108
|
if (!raw) return
|
|
@@ -128,9 +129,9 @@ export async function saveList(cid, list, store = idb, { allowEmpty = false } =
|
|
|
128
129
|
await store.set(LIST(cid), { list: list.slice(0, 200), at: Date.now() })
|
|
129
130
|
}
|
|
130
131
|
|
|
131
|
-
export async function loadList(cid, store = idb) {
|
|
132
|
+
export async function loadList(cid, store = idb, { strict = false } = {}) {
|
|
132
133
|
if (!cid) return null
|
|
133
|
-
const c = await store.get(LIST(cid))
|
|
134
|
+
const c = await (strict && store.getStrict ? store.getStrict(LIST(cid)) : store.get(LIST(cid)))
|
|
134
135
|
return c && Array.isArray(c.list) ? c : null
|
|
135
136
|
}
|
|
136
137
|
|
package/codeCloud.js
CHANGED
|
@@ -49,6 +49,7 @@ export const CLOUD_API = 'https://api.witbitz.chat/v1/cloud-computer'
|
|
|
49
49
|
// now seen in the other direction. Per-image epochs remain the fix, and until they land NEITHER number is a usable
|
|
50
50
|
// stop condition on its own; the check that holds is the file-by-file tarball diff.
|
|
51
51
|
export const CLOUD_PCR0 = [
|
|
52
|
+
'2f92640e0cd5a84e96de0d0fa1857a7643eddd1bac5c6a2512e0a1879919c7720db7b403c9daa0cd088b946aa6ba31f0', // p3j, reproduced on both fleet hosts from 95eaefba
|
|
52
53
|
'66c77a098b36a21fa4a7612ecad202ef2c8e46e34f14e9ab56a3a2a9f3108190f6d2bac14c526f501b1e0109d9605a72', // p3i, reproduced twice from c6ca1e6b
|
|
53
54
|
]
|
|
54
55
|
// The published Credential Sentinel image.
|
|
@@ -88,6 +89,7 @@ export const CLOUD_PCR0 = [
|
|
|
88
89
|
// ⚑ So "SENTINEL_PCR0 must not move when the Sentinel did not change" is a usable stop condition again — the check
|
|
89
90
|
// that caught the esbuild-cwd leak, and which caught nothing for four cycles because the number always moved.
|
|
90
91
|
export const SENTINEL_PCR0 = [
|
|
92
|
+
'cad3d3e47d1a512fcac60c136b840e83ce28304c37da6e8d66bed205ef5d257cc62e1c118191f1c2561bc749a33cd161', // p3j, reproduced on both fleet hosts from 95eaefba
|
|
91
93
|
'aaeb3d3f64efa4f072372a7f257eaa89fd969614139ca08a8ce817ec46cd0d32cf2b4e6103b984a2b7f9d7ce3354c248', // p3i, reproduced twice from c6ca1e6b
|
|
92
94
|
]
|
|
93
95
|
export const GRANT_TTL_MS = 24 * 3600_000
|
|
@@ -308,6 +310,8 @@ export async function openCloud(computer, { token, aws = null, onStep = () => {}
|
|
|
308
310
|
if (r.status === 401 && out.code) throw new CloudError(`your AWS key was not accepted: ${out.error || out.code}`, { status: 401, code: out.code })
|
|
309
311
|
if (r.status === 401 && !askedAgain) { askedAgain = true; await tokenNow(true); continue } // once more, with a fresh one
|
|
310
312
|
if (r.status === 401) throw new CloudError(`your sign-in was not accepted${out.reason ? ` (${out.reason})` : ''} — sign in again with your email`, { status: 401, code: 'no_token' })
|
|
313
|
+
// heldUsd: what your OTHER open cloud computers hold — the month is not used, they hold the rest of it for now
|
|
314
|
+
if (r.status === 429 && out.code === 'aws_limit' && Number(out.heldUsd) > 0) throw new CloudError(`your other open cloud computer holds the rest of this month's allowance — close it, or wait a few minutes, and try again`, { status: 429, code: 'aws_limit' })
|
|
311
315
|
if (r.status === 429 && out.code === 'aws_limit') throw new CloudError(`this month's cloud computer allowance is used${out.resetsAt ? ` — it starts again on ${String(out.resetsAt).slice(0, 10)}` : ''}`, { status: 429, code: 'aws_limit' })
|
|
312
316
|
if (r.status !== 200 || out.error) throw new CloudError(out.error || `the cloud computer service said ${r.status}`, { status: r.status, code: out.code || out.error || '' })
|
|
313
317
|
return out
|
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
|
-
|
|
10
|
-
|
|
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
|
-
|
|
21
|
-
|
|
22
|
-
|
|
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++) {
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// earlierHistory.js — a linked continuation's EARLIER VERSIONS in an export (side sweep: room-export-omits-linked-earlier-history).
|
|
2
|
+
// The conversation draws the parent chain's messages when this device holds their keys (space.js loadEpochChainHistory), but both
|
|
3
|
+
// exports read the selected room's record alone and finished as if that were all of it. The portable file now carries the earlier
|
|
4
|
+
// versions' messages beside its own (`earlier`, additive — a recreate replays `entries` as before), and when they cannot be read, or
|
|
5
|
+
// the export cannot carry them (the sealed download: one Space's record), it SAYS so. Pure — the caller passes the reader.
|
|
6
|
+
|
|
7
|
+
/** This device's keys for a room's earlier versions ({ parentRoom: mk, … }), or null (not a linked continuation here). */
|
|
8
|
+
export function epochKeysOf(room, storage = globalThis.localStorage) {
|
|
9
|
+
try { const s = storage && storage.getItem('space:epoch:' + room); const o = s ? JSON.parse(s) : null; return o && typeof o === 'object' && Object.keys(o).length ? o : null } catch { return null }
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** → { earlier: { from, count, entries } | null, note: '' | a sentence for the toast }.
|
|
13
|
+
* `parent` is the room's config's parent; `readChain(parent, mk, epochKeys)` reads the chain (spaceFork readEpochChain).
|
|
14
|
+
* `configRead: false` = the room's settings (where the parent is named) could not be read: a room this device follows earlier
|
|
15
|
+
* versions of then says they are left out, not nothing (side sweep: room-export-omits-linked-earlier-history, reopened). */
|
|
16
|
+
const UNREAD = ' Its earlier versions’ messages couldn’t be read just now, so they are not in the file — export again to try once more.'
|
|
17
|
+
export async function earlierForExport({ parent, epochKeys, readChain, configRead = true }) {
|
|
18
|
+
if (!parent && epochKeys && configRead === false) return { earlier: null, note: UNREAD }
|
|
19
|
+
if (!parent || !epochKeys) return { earlier: null, note: '' } // not a continuation of an earlier version this device follows
|
|
20
|
+
if (!epochKeys[parent] || typeof readChain !== 'function') return { earlier: null, note: ' Its earlier versions’ messages aren’t on this device, so they are not in the file.' }
|
|
21
|
+
try {
|
|
22
|
+
const entries = await readChain(parent, epochKeys[parent], epochKeys)
|
|
23
|
+
if (!Array.isArray(entries)) throw new Error('no_history')
|
|
24
|
+
// the note counts MESSAGES as drawn: a photo's Safe media copy (`kind: 'safe'`) is its own entry, drawn in the photo's place — as
|
|
25
|
+
// spaceExport.js messageCount (side sweep: room-export-counts-hidden-records-as-messages); the file keeps both, `count` = entries
|
|
26
|
+
const shown = entries.filter((e) => !(e && e.kind === 'safe')).length
|
|
27
|
+
return { earlier: { from: parent, count: entries.length, entries }, note: shown ? ' Its earlier versions’ ' + shown + ' message' + (shown === 1 ? ' is' : 's are') + ' included too.' : '' }
|
|
28
|
+
} catch { return { earlier: null, note: UNREAD } }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** The sealed download holds ONE version's record: a continuation says its earlier versions are not in it. */
|
|
32
|
+
export const sealedEarlierNote = (epochKeys) => (epochKeys ? 'This file holds this version of the Space only — its earlier versions’ messages are not in it.' : '')
|
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'
|
|
@@ -81,20 +82,22 @@ export const govOf = (cfg) => ({ owners: lower(cfg && cfg.owners && cfg.owners.e
|
|
|
81
82
|
* (the server's rule — spaceService refuses a fork notice from a non-admin where there are admins). */
|
|
82
83
|
export function mayMove(cfg, email) {
|
|
83
84
|
const { owners, admins } = govOf(cfg), me = String(email || '').toLowerCase()
|
|
84
|
-
|
|
85
|
+
// a room whose roles name only @username tags (docs/spaces-usernames.md § 13.1) HAS owners: an email alone is not one of them
|
|
86
|
+
const tagged = !!cfg && ['owners', 'admins'].some((k) => cfg[k] && Array.isArray(cfg[k].tags) && cfg[k].tags.length)
|
|
87
|
+
return !(admins.length || owners.length || tagged) || admins.includes(me) || owners.includes(me)
|
|
85
88
|
}
|
|
86
89
|
|
|
87
90
|
/** The OWNERS step of a move, before anything is minted: fills the new gate's owners (and, unless stated, the admins it
|
|
88
91
|
* still admits) from the old room, and refuses a move the server would refuse. → { gate, gov } (gov null in a room
|
|
89
92
|
* without owners). `statedAdmins` = whether the caller stated the new admins itself. */
|
|
90
|
-
export function planGovernance(old, gate, email, statedAdmins) {
|
|
93
|
+
export function planGovernance(old, gate, email, statedAdmins, byOwner = false) {
|
|
91
94
|
const { owners: oldOwners, admins: oldAdmins } = govOf(old)
|
|
92
95
|
const me = String(email || '').toLowerCase()
|
|
93
|
-
if (!oldOwners.length) return { gate, gov: null }
|
|
96
|
+
if (!oldOwners.length && !old?.owners?.tags?.length) return { gate, gov: null }
|
|
94
97
|
gate.owners = gate.owners || { emails: oldOwners }
|
|
95
98
|
if (!statedAdmins && oldAdmins.length) gate.admins = { emails: oldAdmins.filter((e) => admittedBy(gate, e)) }
|
|
96
99
|
const gov = { owners: (gate.owners && gate.owners.emails) || [], admins: (gate.admins && gate.admins.emails) || [] }
|
|
97
|
-
const why = govRefusal(oldOwners, oldAdmins, gov, oldOwners.includes(me))
|
|
100
|
+
const why = govRefusal(oldOwners, oldAdmins, gov, byOwner || oldOwners.includes(me))
|
|
98
101
|
if (why) throw Object.assign(new Error('witbitz: ' + why), { code: 'not_owner' })
|
|
99
102
|
const out = [...gov.owners, ...gov.admins].find((x) => !admittedBy(gate, x))
|
|
100
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`)
|
|
@@ -119,7 +122,7 @@ export function carriedHandles(old) {
|
|
|
119
122
|
export function checkAdminCollections(data, cfg) {
|
|
120
123
|
const adminOnly = data && typeof data === 'object' ? Object.entries(data).find(([, v]) => v && typeof v === 'object' && v.write === 'admins') : null
|
|
121
124
|
const g = cfg || {}
|
|
122
|
-
if (adminOnly && !(g
|
|
125
|
+
if (adminOnly && !hasRoles(g)) {
|
|
123
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' })
|
|
124
127
|
}
|
|
125
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
|
-
|
|
35
|
-
|
|
36
|
-
|
|
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 {
|
|
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
|
|
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
|
|
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
|
|