@witbitz/sdk 4.7.0 → 4.8.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.
- package/README.md +2 -2
- package/acctV2Client.js +3 -3
- package/acctV2UiCore.js +3 -2
- package/acctV2WebAuthn.js +4 -4
- package/codeCache.js +1 -1
- package/deviceKeyCore.js +44 -6
- package/emailFork.js +5 -4
- package/emptySpaces.js +12 -6
- package/idb.js +32 -4
- package/idbSeal.js +7 -0
- package/l1-worker-src.js +1 -1
- package/l1-worker.js +22 -1
- package/manifest.json +36 -36
- package/memberChange.js +9 -0
- package/nativePush.js +6 -0
- package/package.json +2 -2
- package/reqEnvelope.js +1 -1
- package/roomName.js +22 -6
- package/roomRoles.js +22 -0
- package/sdkAccount.js +3 -1
- package/sdkBackupV2.js +20 -9
- package/sdkCloudDevice.js +18 -9
- package/sdkExports.js +1 -1
- package/sdkInvitations.js +2 -2
- package/sdkPlan.js +21 -9
- package/sdkRekey.js +17 -7
- package/sdkVault.js +1 -1
- package/sentinelRelease.js +1 -0
- package/spaceClient.js +34 -14
- package/sw-notif-core.js +4 -2
- package/util.js +11 -1
- package/vault-core.js +41 -11
- package/vault-kit.mjs +1 -1
- package/vaultAtRest.js +3 -2
- package/witbitz-admin.mjs +11 -10
- package/witbitz-sdk.js +49 -23
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.8.0 of this package is the release folder https://witbitz.chat/sdk/4.8.0/ unchanged (from commit
|
|
20
|
+
`b47312c7930f4196ede9d28eb94ce9e6f56e30b3`), 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/acctV2Client.js
CHANGED
|
@@ -83,7 +83,7 @@ export function accountClient({ base, fetch: f = globalThis.fetch, now = () => M
|
|
|
83
83
|
if (!keys) throw Object.assign(new Error('need_security_key'), { code: 'need_security_key' })
|
|
84
84
|
const allow = (c.keys || []).filter((k) => k.id !== except)
|
|
85
85
|
if (!allow.length) throw Object.assign(new Error('no_other_key'), { code: 'no_other_key' })
|
|
86
|
-
return { hwkey: await keys.get({ challenge: await sha256(Tb), allow }) }
|
|
86
|
+
return { hwkey: await keys.get({ challenge: await sha256(Tb), allow, rpId: c.rpId }) }
|
|
87
87
|
}
|
|
88
88
|
const fail = (code) => { throw Object.assign(new Error(code), { code }) }
|
|
89
89
|
/** A new code's parameters (§ 8.2): every value derived HERE from the new code and master, before anything is sent. */
|
|
@@ -360,11 +360,11 @@ export function accountClient({ base, fetch: f = globalThis.fetch, now = () => M
|
|
|
360
360
|
const assertions = []
|
|
361
361
|
for (const [i, m] of made.entries()) {
|
|
362
362
|
onStep({ step: 'confirm', index: i, of: made.length })
|
|
363
|
-
assertions.push(await keys.get({ challenge: ch, allow: [m] }))
|
|
363
|
+
assertions.push(await keys.get({ challenge: ch, allow: [m], rpId: f.rpId }))
|
|
364
364
|
}
|
|
365
365
|
if (purpose === 'key_add') {
|
|
366
366
|
onStep({ step: 'existing' })
|
|
367
|
-
assertions.push(await keys.get({ challenge: ch, allow: (f.active || []).filter((k) => !creds.includes(k.id)) }))
|
|
367
|
+
assertions.push(await keys.get({ challenge: ch, rpId: f.rpId, allow: (f.active || []).filter((k) => !creds.includes(k.id)) }))
|
|
368
368
|
}
|
|
369
369
|
return req('POST', `/v2/account/enrol/${eid}/finish`, { body: { device_sig: await sigOf(device, Tf), assertions, idem: b64u(rand(16)) }, signer: device })
|
|
370
370
|
},
|
package/acctV2UiCore.js
CHANGED
|
@@ -42,6 +42,7 @@ const MESSAGES = {
|
|
|
42
42
|
already_migrated: 'This device already has an account on the new service.',
|
|
43
43
|
need_security_key: 'This needs one of your security keys, and this device can’t ask for one.',
|
|
44
44
|
key_cancelled: 'The security key didn’t answer — the prompt was closed, timed out, or a key that isn’t on this account was touched. Nothing changed.',
|
|
45
|
+
key_domain_mismatch: 'Open the vault on the website where you set up your security keys.',
|
|
45
46
|
key_wrong_site: 'Security keys can’t be used in this app yet.', // accounts are per app (sync sweep 11-16 #17): never sent to another app's address
|
|
46
47
|
webauthn_unavailable: 'This browser can’t use security keys.',
|
|
47
48
|
key_already_registered: 'That key is already on this account. Use a different key.',
|
|
@@ -531,12 +532,12 @@ export async function offerAutoMove(rerender = () => {}) {
|
|
|
531
532
|
if (!oldAccountHere()) return false
|
|
532
533
|
return moveAccount(rerender, { auto: true })
|
|
533
534
|
}
|
|
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
|
|
535
|
+
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
536
|
/** The move itself. The device is switched onto the service for it, and back if the account did not move. → whether it moved. */
|
|
536
537
|
async function moveAccount(rerender, { auto = false } = {}) {
|
|
537
538
|
const address = accountAddress()
|
|
538
539
|
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
|
|
540
|
+
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
541
|
let a = acctV2(), undo = () => {}
|
|
541
542
|
if (!a.enabled()) {
|
|
542
543
|
const svc = moveSvc()
|
package/acctV2WebAuthn.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// acctV2WebAuthn.js — the security-key ceremonies of account recovery v2 (docs/account-recovery-protocol.md § 10), as the
|
|
2
2
|
// small adapter the client takes (acctV2Client.js `keys`): create(options) → the registration, get({challenge, allow}) →
|
|
3
3
|
// an assertion, everything in base64url. This file is the BROWSER's adapter (navigator.credentials); the tests pass a
|
|
4
|
-
// simulated key with the same shape. The
|
|
4
|
+
// simulated key with the same shape. The service chooses the verified vault's RP (§ 10.2). Older responses use the shared Spaces RP.
|
|
5
5
|
import { b64u, unb64u } from './acctV2Wire.js'
|
|
6
6
|
|
|
7
7
|
export const RP_ID = 'witbitz.chat'
|
|
@@ -21,7 +21,7 @@ const rethrow = (e) => { throw (e && e.code === 'cancelled' ? e : why(e)) }
|
|
|
21
21
|
function why(e) {
|
|
22
22
|
if (e && e.name === 'NotAllowedError') return err('key_cancelled') // closed, timed out, or no matching key touched
|
|
23
23
|
if (e && e.name === 'InvalidStateError') return err('key_already_registered') // excludeCredentials matched
|
|
24
|
-
if (e && e.name === 'SecurityError') return err('key_wrong_site') // this origin may not use
|
|
24
|
+
if (e && e.name === 'SecurityError') return err('key_wrong_site') // this origin may not use the requested RP (§ 10.2)
|
|
25
25
|
return err('key_failed')
|
|
26
26
|
}
|
|
27
27
|
|
|
@@ -45,11 +45,11 @@ export function browserKeys({ rpId = RP_ID } = {}) {
|
|
|
45
45
|
return { attestationObject: ab(r.attestationObject), clientDataJSON: ab(r.clientDataJSON), transports: (r.getTransports && r.getTransports()) || [] }
|
|
46
46
|
},
|
|
47
47
|
/** An assertion over `challenge` (bytes) by one of `allow` ([{ id, transports }]). */
|
|
48
|
-
async get({ challenge, allow }) {
|
|
48
|
+
async get({ challenge, allow, rpId: requestRpId = rpId }) {
|
|
49
49
|
if (!available()) throw err('webauthn_unavailable')
|
|
50
50
|
let a
|
|
51
51
|
const publicKey = {
|
|
52
|
-
rpId, challenge, userVerification: 'required', timeout: 120000,
|
|
52
|
+
rpId: requestRpId, challenge, userVerification: 'required', timeout: 120000,
|
|
53
53
|
allowCredentials: (allow || []).map((c) => ({ type: 'public-key', id: unb64u(c.id), transports: c.transports || [] })),
|
|
54
54
|
}
|
|
55
55
|
try { a = await ceremony('get', () => navigator.credentials.get({ publicKey })) } catch (e) { rethrow(e) }
|
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
|
-
|
|
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++) {
|
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
|
|
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
|
-
|
|
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,18 @@ 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
|
-
|
|
124
|
+
setDeviceRaw: (k, v) => tx('readwrite', (s) => s.put(v, k)),
|
|
125
|
+
getRaw, setRaw, setRawStrict, delRaw, entriesRaw, keysRaw, nameIndex,
|
|
106
126
|
/** 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
|
|
127
|
+
async getStrict(k) {
|
|
128
|
+
if (isNamed(k)) {
|
|
129
|
+
const { namer, key } = idbNamingState()
|
|
130
|
+
if (!namer) throw new Error('Unlock device storage to read this entry')
|
|
131
|
+
const v = await getRawStrict(await namer.opaque(k))
|
|
132
|
+
if (v != null) return openSealed(key, v)
|
|
133
|
+
}
|
|
134
|
+
return unwrapStrict(k, await getRawStrict(k))
|
|
135
|
+
},
|
|
108
136
|
// §PROTECT: switch on / unlock (seal the clear content in place) and switch off (write it back) — the lock hooks call these.
|
|
109
137
|
protect: (rawKey) => migrateIdbProtection(self, rawKey),
|
|
110
138
|
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
|
|