@witbitz/sdk 0.0.0-stage → 4.3.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/LICENSE +21 -0
- package/README.md +20 -2
- package/a2aCore.js +200 -0
- package/a2aShared.js +27 -0
- package/accountErase.js +223 -0
- package/accountIndexDoc.js +122 -0
- package/accountOwner.js +59 -0
- package/accountRecord.js +90 -0
- package/accountScope.js +114 -0
- package/accountSeal.js +42 -0
- package/accountStores.js +173 -0
- package/acctV2App.js +619 -0
- package/acctV2Check.js +29 -0
- package/acctV2Client.js +382 -0
- package/acctV2Keys.js +43 -0
- package/acctV2Legacy.js +14 -0
- package/acctV2Switch.js +80 -0
- package/acctV2UiCore.js +857 -0
- package/acctV2WebAuthn.js +61 -0
- package/acctV2Wire.js +59 -0
- package/address.js +42 -0
- package/attestedBox.js +30 -0
- package/attestedRooms.js +78 -0
- package/awsKey.js +98 -0
- package/backupRecord.js +106 -0
- package/backupVault.js +97 -0
- package/blocks.js +115 -0
- package/blocksPush.js +64 -0
- package/browseSeal.js +103 -0
- package/cbor.js +225 -0
- package/changePush.js +75 -0
- package/chatLock.js +149 -0
- package/chatLockSw.js +13 -0
- package/cloudDeviceBuilds.js +11 -0
- package/cloudDevicePins.js +33 -0
- package/cloudDeviceSeal.js +53 -0
- package/codeBrowse.js +224 -0
- package/codeCloud.js +652 -0
- package/codeCloudKeys.js +112 -0
- package/codeCommands.js +167 -0
- package/codeComputers.js +388 -0
- package/codeEgress.js +123 -0
- package/codeFilesRoutes.js +17 -0
- package/codeMkdir.js +8 -0
- package/codeModes.js +57 -0
- package/codeOrphanKeys.js +42 -0
- package/codeOutputs.js +141 -0
- package/codeRelay.js +505 -0
- package/codeSentinel.js +86 -0
- package/codeTransport.js +295 -0
- package/codeUndo.js +48 -0
- package/compress.js +24 -0
- package/config.js +11 -0
- package/connCatalog.js +164 -0
- package/connDisp.js +76 -0
- package/connOtherWays.js +74 -0
- package/connPending.js +16 -0
- package/connWrap.js +53 -0
- package/connectionEntry.js +89 -0
- package/connections.js +562 -0
- package/credits.js +30 -0
- package/csAttest.js +112 -0
- package/decrypt.html +384 -0
- package/deviceAttest.js +521 -0
- package/deviceCall.js +54 -0
- package/deviceKeyCore.js +41 -0
- package/deviceSeal.js +59 -0
- package/e2ee.js +323 -0
- package/eat.js +103 -0
- package/emailFork.js +275 -0
- package/emailSignIn.js +81 -0
- package/emptySpaces.js +111 -0
- package/encSource.js +55 -0
- package/enclaveAccept.js +214 -0
- package/enclaveClaim.js +241 -0
- package/enclaveRoute.js +102 -0
- package/enclaveSnapshotMerge.js +44 -0
- package/entrySig.js +165 -0
- package/env.js +73 -0
- package/eraseFile.js +58 -0
- package/followImage.js +86 -0
- package/healNames.js +45 -0
- package/idb.js +97 -0
- package/idbSeal.js +119 -0
- package/indexGone.js +12 -0
- package/invite.js +51 -0
- package/inviteEnroll.js +67 -0
- package/inviteSend.js +68 -0
- package/jobAgents.js +87 -0
- package/keptMerge.js +84 -0
- package/l1-worker-src.js +2 -0
- package/l1-worker.js +831 -0
- package/laneConfig.js +57 -0
- package/laneLinkCore.js +177 -0
- package/ledgerView.js +64 -0
- package/manifest.json +220 -0
- package/mcpRecommended.js +25 -0
- package/memberChange.js +123 -0
- package/mkseal.js +101 -0
- package/nativePush.js +153 -0
- package/nitroVerify.js +220 -0
- package/noble-p256.js +27 -0
- package/notice.js +116 -0
- package/notifKey.js +58 -0
- package/offlineBundle.js +62 -0
- package/ohttp.js +177 -0
- package/opencodeWire.js +282 -0
- package/oprf.js +70 -0
- package/ownAgentLink.js +96 -0
- package/ownerPolicy.js +117 -0
- package/package.json +254 -4
- package/pollVerdict.js +33 -0
- package/prefetchPoll.js +60 -0
- package/protectedLocal.js +410 -0
- package/pushCore.js +42 -0
- package/recovery.js +107 -0
- package/regions.js +42 -0
- package/removedMessage.js +11 -0
- package/renameRefusal.js +9 -0
- package/replyQuote.js +34 -0
- package/reqEnvelope.js +126 -0
- package/roomDefaultPrefs.js +76 -0
- package/roomDelete.js +109 -0
- package/roomName.js +177 -0
- package/roomPass.js +256 -0
- package/roomRoster.js +289 -0
- package/roomSettings.js +61 -0
- package/roomState.js +58 -0
- package/roomStreamClient.js +115 -0
- package/rosterCount.js +49 -0
- package/rosterHash.js +13 -0
- package/rowSchema.js +113 -0
- package/safeMedia.js +116 -0
- package/safeMediaPins.js +17 -0
- package/schedulesDoc.js +78 -0
- package/sdkA2A.js +404 -0
- package/sdkAccount.js +470 -0
- package/sdkAccountDoc.js +81 -0
- package/sdkAccountSections.js +223 -0
- package/sdkAgui.js +141 -0
- package/sdkAttest.js +34 -0
- package/sdkBackup.js +480 -0
- package/sdkBackupV2.js +630 -0
- package/sdkBrowserPrivate.js +28 -0
- package/sdkBuilds.js +208 -0
- package/sdkCloudDevice.js +215 -0
- package/sdkComputers.js +480 -0
- package/sdkDictation.js +142 -0
- package/sdkErase.js +283 -0
- package/sdkExports.js +69 -0
- package/sdkInvitations.js +34 -0
- package/sdkKeptAgent.js +188 -0
- package/sdkLaneLink.js +205 -0
- package/sdkPlan.js +94 -0
- package/sdkProtect.js +228 -0
- package/sdkRedact.js +36 -0
- package/sdkRekey.js +307 -0
- package/sdkReport.js +68 -0
- package/sdkSafeMedia.js +255 -0
- package/sdkSchedules.js +39 -0
- package/sdkSpeech.js +54 -0
- package/sdkTurn.js +117 -0
- package/sdkVault.js +124 -0
- package/sealShare.js +18 -0
- package/sealedNames.js +64 -0
- package/sealedReceipt.js +17 -0
- package/sentinelRelease.js +154 -0
- package/shamir.js +85 -0
- package/sharedViews.js +38 -0
- package/sheetChrome.js +450 -0
- package/siri.js +171 -0
- package/spaceClient.js +1418 -0
- package/spaceConfig.js +81 -0
- package/spaceEmailGate.js +813 -0
- package/spaceExport.js +125 -0
- package/spaceFork.js +216 -0
- package/spaceLock.js +358 -0
- package/spacePasskey.js +180 -0
- package/speechOut.js +100 -0
- package/splitKeyClient.js +90 -0
- package/store.js +587 -0
- package/streamHint.js +36 -0
- package/sttCloud.js +220 -0
- package/sttWorklet.js +38 -0
- package/sw-notif-core.js +538 -0
- package/tempList.js +48 -0
- package/tinfoilVerifier.js +78 -0
- package/toolBooks.js +31 -0
- package/toolRules.js +52 -0
- package/turnCerts.js +254 -0
- package/turnFeed.js +58 -0
- package/turnVerdict.js +36 -0
- package/usageReceipts.js +176 -0
- package/usageSummary.js +90 -0
- package/util.js +181 -0
- package/vault-core.js +1958 -0
- package/vault-kit.mjs +354 -0
- package/vault-screens.js +263 -0
- package/vaultAtRest.js +177 -0
- package/vaultCoreLock.js +111 -0
- package/vaultCorePush.js +140 -0
- package/vaultDeviceKey.js +95 -0
- package/vaultEnclaveHandoff.js +114 -0
- package/vaultKeep.js +281 -0
- package/vaultSealedStore.js +77 -0
- package/vaultWorkerHost.js +98 -0
- package/vcWorker.js +34 -0
- package/voiceAttest.js +50 -0
- package/voiceCert.js +51 -0
- package/witbitz-admin.d.ts +135 -0
- package/witbitz-admin.js +529 -0
- package/witbitz-admin.mjs +1459 -0
- package/witbitz-sdk.d.ts +1106 -0
- package/witbitz-sdk.js +3835 -0
- package/workerClient.js +16 -0
- package/workerLiveness.js +21 -0
- package/x509.js +218 -0
package/spaceLock.js
ADDED
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
// spaceLock.js — SHARED tier-2 biometric lock (Face ID / Touch ID). Used by BOTH the tenant vault (vault-loader.js,
|
|
2
|
+
// covering the app IFRAME) and the regular single-origin app (space.js, covering its OWN DOM). Extracted so the two
|
|
3
|
+
// don't drift (convergence: one core, the surface difference parameterised — cf. sw-notif-core.js).
|
|
4
|
+
//
|
|
5
|
+
// ★ TIER 2 = the OS biometric prompt gates the PIXELS: an opaque overlay covers the app until a user-verified WebAuthn
|
|
6
|
+
// assertion passes. It does NOT encrypt keys by itself — a storage extraction bypasses it. TIER 3 is the `protect` option
|
|
7
|
+
// below (docs/device-storage-protection.md): "Also protect this device's storage" enrolls a PRF/largeBlob passkey
|
|
8
|
+
// (spacePasskey.js) and hands the derived device secret to the shell at enroll / unlock / lock, which seals the key store.
|
|
9
|
+
//
|
|
10
|
+
// The DIFFERENCES between the two surfaces are the only config:
|
|
11
|
+
// storeKey localStorage key for the {on,auto,credId} config ('vault:lock' vs 'space:lock')
|
|
12
|
+
// ids DOM id map (the regular app overrides `err` — space.html already owns a #lockErr for an unrelated msg)
|
|
13
|
+
// cover { onEngage, onRelease } — the vault hides/shows the app iframe; the regular app is a no-op (the overlay,
|
|
14
|
+
// at max z-index, covers its own DOM)
|
|
15
|
+
// onState called after any config change (vault → postMessage the app its Settings row state; app → refresh the row)
|
|
16
|
+
|
|
17
|
+
const B64 = (u8) => { let t = ''; for (let i = 0; i < u8.length; i++) t += String.fromCharCode(u8[i]); return btoa(t).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') }
|
|
18
|
+
const U8 = (b) => { const t = atob(String(b).replace(/-/g, '+').replace(/_/g, '/')); const u = new Uint8Array(t.length); for (let i = 0; i < t.length; i++) u[i] = t.charCodeAt(i); return u }
|
|
19
|
+
|
|
20
|
+
// What this device calls its passkey check — the lock screen said "Face ID or Touch ID" on a Windows computer too.
|
|
21
|
+
export function unlockWithName (nav = globalThis.navigator) {
|
|
22
|
+
const ua = String((nav && nav.userAgent) || ''), plat = String((nav && nav.userAgentData && nav.userAgentData.platform) || '')
|
|
23
|
+
if (/Windows/i.test(plat) || /Windows/i.test(ua)) return 'Windows Hello'
|
|
24
|
+
if (/iPhone|iPad|Mac/i.test(ua) || /macOS|iOS/i.test(plat)) return 'Face ID or Touch ID'
|
|
25
|
+
return 'your fingerprint or screen lock'
|
|
26
|
+
}
|
|
27
|
+
// The lock card's own words for it (sync sweep 10-24 #27: "Face ID lock", "Waiting for Face ID…" on a Windows computer):
|
|
28
|
+
// `check` is what asks, `title` the switch, `require` the line under the card's title. A Mac without touch has Touch ID.
|
|
29
|
+
export function lockNames (nav = globalThis.navigator) {
|
|
30
|
+
const n = unlockWithName(nav), ua = String((nav && nav.userAgent) || '')
|
|
31
|
+
if (n === 'Windows Hello') return { check: 'Windows Hello', title: 'Windows Hello lock', require: 'Windows Hello' }
|
|
32
|
+
if (n === 'Face ID or Touch ID' && /Macintosh/i.test(ua) && !(Number(nav && nav.maxTouchPoints) > 1)) return { check: 'Touch ID', title: 'Touch ID lock', require: 'Touch ID' }
|
|
33
|
+
if (n === 'Face ID or Touch ID') return { check: 'Face ID', title: 'Face ID lock', require: 'Face ID / Touch ID' }
|
|
34
|
+
return { check: 'your screen lock', title: 'Screen lock', require: 'your fingerprint or screen lock' }
|
|
35
|
+
}
|
|
36
|
+
// What a failed check says — this device's own name for it, never "Face ID" on a computer (sync sweep 10-20 #9).
|
|
37
|
+
// the browser's own reason in brackets (the owner's iPhone app, 2026-11-22: "Why I get didn't complete yet?" — it said nothing more)
|
|
38
|
+
const whyOf = (e) => { const n = (e && e.name) || '', m = String((e && e.message) || '').slice(0, 90); return n || m ? ` (${[n, m].filter(Boolean).join(': ')})` : '' }
|
|
39
|
+
const didntComplete = (e) => `${unlockWithName().replace(/^your /, 'The ')} didn’t complete — try again.${whyOf(e)}`
|
|
40
|
+
// A second request while the system's prompt is still up is refused as already pending — not a failed check.
|
|
41
|
+
export const isPendingRefusal = (e) => !!e && (e.name === 'InvalidStateError' || /already pending|pending request|in progress/i.test(String(e.message || '')))
|
|
42
|
+
|
|
43
|
+
const DEFAULT_IDS = { screen: 'lockscreen', set: 'lockset', unlockBtn: 'unlockBtn', err: 'lockErr', on: 'lockOn', off: 'lockOff', msg: 'lockMsg', auto: 'lockAuto', close: 'lockClose', protect: 'lockProtect', protectMsg: 'lockProtectMsg', previews: 'lockPreviews', toggle: 'lockToggle', toggleLbl: 'lockToggleLbl', desc: 'lockDesc', reset: 'lockReset' }
|
|
44
|
+
|
|
45
|
+
// `appName` (default 'Spaces'): the name the sheet and the lock's own passkey say — a builder's vault (vaultCoreLock.js) passes its brand.
|
|
46
|
+
// `owner` (the desktop app, Linux and the Mac — desktop/ownerCheck.mjs; the owner, 2026-11-22): { check(reason) → Promise<{ ok }>, names }
|
|
47
|
+
// — the OPERATING SYSTEM confirms the person (the Mac's Touch ID or password, Linux's polkit dialog) in place of a passkey, which
|
|
48
|
+
// Electron cannot show there. No credential is made; the config's credId is the marker OWNER_ID. Tier 3 (`protect`) is not offered
|
|
49
|
+
// with it: the desktop app's storage is sealed by the OS key store already.
|
|
50
|
+
export const OWNER_ID = 'desktop-owner'
|
|
51
|
+
export function makeLock({ storeKey, ids = {}, cover = {}, onState, protect = null, appName = 'Spaces', owner = null } = {}) {
|
|
52
|
+
const id = { ...DEFAULT_IDS, ...ids }
|
|
53
|
+
const O = owner && typeof owner.check === 'function' ? owner : null
|
|
54
|
+
const names = () => (O && O.names && O.names.check ? O.names : lockNames())
|
|
55
|
+
const checkName = () => (O && O.names && O.names.check ? O.names.check : unlockWithName())
|
|
56
|
+
const ownerConfirms = async () => { const r = await O.check('unlock ' + appName); if (r && r.ok) return true; if (r && !r.cancelled && r.error) throw Object.assign(new Error(r.error), { name: 'OwnerCheck' }); return false }
|
|
57
|
+
// §PROTECT hooks (all optional; absent ⇒ tier 2 exactly as before): enroll(label) → { credId, secret }; unlock(credId) →
|
|
58
|
+
// { secret } (a user-verified assertion, so it also serves as the tier-2 gate); onProtect(secret) seals the device's
|
|
59
|
+
// stores; onUnlock(secret) opens them; onLock() drops them from memory; onUnprotect(secret) writes them back in the clear.
|
|
60
|
+
const P = protect && typeof protect === 'object' ? protect : null
|
|
61
|
+
const protectOn = () => { const c = cfg(); return !!(P && c.protect && c.protect.on && c.protect.credId) }
|
|
62
|
+
// §PREVIEWS (opt-in under protection): leave only the push-preview keys in the clear, so a tickle shows the sender + first
|
|
63
|
+
// line while the device is locked; the room keys, the identity and the cached messages stay sealed. onPreviews(on) applies it.
|
|
64
|
+
const previewsOn = () => { const c = cfg(); return !!(c.protect && c.protect.on && c.protect.previews) }
|
|
65
|
+
const el = (k) => { try { return document.getElementById(id[k]) } catch (e) { return null } }
|
|
66
|
+
const onEngage = cover.onEngage || (() => {}) // vault: hide the app iframe · regular: no-op (overlay covers)
|
|
67
|
+
const onRelease = cover.onRelease || (() => {})
|
|
68
|
+
const notify = typeof onState === 'function' ? onState : (() => {})
|
|
69
|
+
|
|
70
|
+
function cfg() { try { const c = JSON.parse(localStorage.getItem(storeKey) || 'null'); return (c && typeof c === 'object') ? c : { on: false, auto: 5 } } catch (e) { return { on: false, auto: 5 } } }
|
|
71
|
+
function save(c) { try { localStorage.setItem(storeKey, JSON.stringify(c)) } catch (e) {} notify(cfg()) }
|
|
72
|
+
|
|
73
|
+
async function enroll() { // a dedicated PLATFORM credential for the lock (wraps nothing in tier 2)
|
|
74
|
+
if (O) return (await ownerConfirms()) ? OWNER_ID : null // the desktop app: the system confirms; nothing to make
|
|
75
|
+
const cred = await navigator.credentials.create({ publicKey: {
|
|
76
|
+
challenge: crypto.getRandomValues(new Uint8Array(32)),
|
|
77
|
+
rp: { name: appName }, user: { id: crypto.getRandomValues(new Uint8Array(16)), name: appName + ' lock', displayName: appName + ' lock' },
|
|
78
|
+
pubKeyCredParams: [{ type: 'public-key', alg: -7 }, { type: 'public-key', alg: -257 }],
|
|
79
|
+
authenticatorSelection: { authenticatorAttachment: 'platform', userVerification: 'required', residentKey: 'preferred' },
|
|
80
|
+
timeout: 60000 } })
|
|
81
|
+
return (cred && cred.rawId) ? B64(new Uint8Array(cred.rawId)) : null
|
|
82
|
+
}
|
|
83
|
+
async function assert() { // ANY user-verified assertion unlocks — pinned to the enrolled credential when we have one
|
|
84
|
+
if (O) return ownerConfirms()
|
|
85
|
+
const c = cfg()
|
|
86
|
+
const pk = { challenge: crypto.getRandomValues(new Uint8Array(32)), userVerification: 'required', timeout: 60000 }
|
|
87
|
+
if (c.credId) pk.allowCredentials = [{ type: 'public-key', id: U8(c.credId) }]
|
|
88
|
+
const a = await navigator.credentials.get({ publicKey: pk })
|
|
89
|
+
return !!a
|
|
90
|
+
}
|
|
91
|
+
// THE OWNER, PROVEN, WITH A PASSKEY THAT EXISTS (2026-10-16; the owner: "It did not read my face … it doesn't find a
|
|
92
|
+
// passkey"). The lock keeps its credId when it goes off, and the credential can be gone from the device since (deleted,
|
|
93
|
+
// replaced). Asking only for it then fails for ever: the switch never goes off and a launch never unlocks. When the
|
|
94
|
+
// remembered one does not answer, a NEW platform passkey with userVerification 'required' is the same Face ID / passcode
|
|
95
|
+
// proof — make it, keep it. ⇒ the credId that verified, or null.
|
|
96
|
+
async function verifyOwner() {
|
|
97
|
+
if (O) return (await ownerConfirms()) ? OWNER_ID : null // the system's own check, every time — never a passkey
|
|
98
|
+
const c = cfg()
|
|
99
|
+
if (c.credId) { try { if (await assert()) return c.credId } catch (e) { if (isPendingRefusal(e)) throw e /* the first prompt is still up — never a new passkey for it */ } } // else gone, or cancelled: a new passkey asks again
|
|
100
|
+
const id = await enroll()
|
|
101
|
+
if (id) save({ ...cfg(), credId: id })
|
|
102
|
+
return id
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
let _locked = false, _hiddenAt = 0, _visWired = false
|
|
106
|
+
// §HAND-OFF: the standalone app LOADS A NEW PAGE whenever it opens a room (location.href) — and "lock when the app opens"
|
|
107
|
+
// used to fire on every one of those (the owner's phone, 2026-10-06: a Face ID for each room). An unlocked page stamps
|
|
108
|
+
// the moment it leaves (pagehide); a page that loads within HANDOFF_MS of that stamp is the same session continuing, not a
|
|
109
|
+
// launch. Tier 3 also needs the KEY to cross: P.handoff() asks the service worker for it (space.js); no key → the prompt.
|
|
110
|
+
const HANDOFF_MS = 20000
|
|
111
|
+
const leftKey = storeKey + ':left'
|
|
112
|
+
const stampLeft = () => { try { if (cfg().on && !_locked) sessionStorage.setItem(leftKey, String(Date.now())) } catch (e) {} }
|
|
113
|
+
const takeLeft = () => { try { const v = +sessionStorage.getItem(leftKey) || 0; sessionStorage.removeItem(leftKey); return v } catch (e) { return 0 } }
|
|
114
|
+
// WHY rides along (2026-10-21, the owner's vault: "app frame hidden (Face ID lock)" while turning the lock OFF, and the app
|
|
115
|
+
// stayed hidden): the cover says which path engaged it, and a lock that is off never engages.
|
|
116
|
+
function engage(why = '') {
|
|
117
|
+
if (_locked) return
|
|
118
|
+
if (!cfg().on) return
|
|
119
|
+
_locked = true
|
|
120
|
+
if (protectOn() && P.onLock) { try { Promise.resolve(P.onLock()).catch(() => {}) } catch (e) {} } // §PROTECT: nothing usable stays in memory while locked
|
|
121
|
+
try {
|
|
122
|
+
const scr = el('screen'); if (!scr) { _locked = false; return }
|
|
123
|
+
const btn = el('unlockBtn'); if (btn) btn.onclick = tryUnlock
|
|
124
|
+
const em = el('err'); if (em) em.textContent = ''
|
|
125
|
+
const how = scr.querySelector && scr.querySelector('p'); if (how) how.textContent = `Unlock with ${checkName()} to continue.`
|
|
126
|
+
onEngage(why); holdScroll(true); scr.style.display = 'flex'
|
|
127
|
+
} catch (e) { _locked = false }
|
|
128
|
+
}
|
|
129
|
+
// NO SCROLLBAR UNDER THE LOCK (the owner, 2026-10-21, desktop: "when I unlock it wiggles left and right before settling").
|
|
130
|
+
// While the card is up the room is laid out beneath it; for a frame the page was taller than the window, a classic
|
|
131
|
+
// scrollbar appeared, the window's width dropped by its ~24 px and the centred card jumped 12 px left and back (measured
|
|
132
|
+
// frame by frame in the recording). The page's own overflow is held hidden for exactly as long as the card is shown.
|
|
133
|
+
let _ovf = null
|
|
134
|
+
const holdScroll = (on) => { try { const h = document.documentElement; if (on) { if (_ovf === null) { _ovf = h.style.overflow || ''; h.style.overflow = 'hidden' } } else if (_ovf !== null) { h.style.overflow = _ovf; _ovf = null } } catch (e) {} }
|
|
135
|
+
function release() { _locked = false; try { const scr = el('screen'); if (scr) scr.style.display = 'none'; holdScroll(false); onRelease() } catch (e) {} }
|
|
136
|
+
async function tryUnlock() {
|
|
137
|
+
const em = el('err'), btn = el('unlockBtn')
|
|
138
|
+
// ★ FEEDBACK AT ONCE (the owner, 2026-10-19: "when i press unlock there is no feedback that it was being pressed"): the
|
|
139
|
+
// system's passkey prompt can take a moment to come up — the button says so, and a second press does nothing meanwhile
|
|
140
|
+
if (btn && btn.disabled) return
|
|
141
|
+
const label = btn ? btn.textContent : ''
|
|
142
|
+
if (btn) { btn.disabled = true; btn.setAttribute?.('aria-busy', 'true'); if (btn.style) btn.style.opacity = '0.6'; btn.textContent = 'Unlocking…' }
|
|
143
|
+
try { return await unlockOnce(em) } finally {
|
|
144
|
+
if (btn) { btn.disabled = false; btn.removeAttribute?.('aria-busy'); if (btn.style) btn.style.opacity = ''; btn.textContent = label }
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
async function unlockOnce(em) {
|
|
148
|
+
try {
|
|
149
|
+
if (em) em.textContent = ''
|
|
150
|
+
if (protectOn()) { // §PROTECT: the passkey assertion IS the gate, and its secret reopens the sealed stores
|
|
151
|
+
const r = await P.unlock(cfg().protect.credId)
|
|
152
|
+
if (!r || !r.secret) { if (em) em.textContent = 'Not verified — try again.'; offerStartOver(); return }
|
|
153
|
+
if (P.onUnlock) await P.onUnlock(r.secret, { previews: previewsOn() })
|
|
154
|
+
// a switch-on that was cut short: finish it now, with the same key — but a failure there (a full disk) must not keep the
|
|
155
|
+
// person behind the lock the passkey just opened (A#14): `pending` stays, the next unlock tries again
|
|
156
|
+
try { await finishPending(r.secret) } catch (e) { try { console.warn('lock: finishing protection failed — tried again at the next unlock', e && e.message) } catch (_) {} }
|
|
157
|
+
release(); return
|
|
158
|
+
}
|
|
159
|
+
const ok = await verifyOwner(); if (ok) release(); else if (em) em.textContent = 'Not verified — try again.'
|
|
160
|
+
}
|
|
161
|
+
catch (e) {
|
|
162
|
+
if (isPendingRefusal(e)) return // the prompt from the first press is still up: nothing failed, nothing to start over
|
|
163
|
+
if (em) em.textContent = `${checkName().replace(/^your /, 'The ')} didn’t complete — press Unlock to try again.${whyOf(e)}`; offerStartOver()
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
// A PROTECTED device whose passkey is gone (replaced on the authenticator, deleted, another computer) can never open its
|
|
167
|
+
// sealed stores again. After a failed unlock, offer to start this browser over — the Spaces themselves live in the
|
|
168
|
+
// account (the backup, the other devices); only this browser's sealed copy goes. The shell supplies P.startOver.
|
|
169
|
+
function offerStartOver() {
|
|
170
|
+
try {
|
|
171
|
+
if (!protectOn() || !P || typeof P.startOver !== 'function') return
|
|
172
|
+
const b = el('reset'); if (!b) return
|
|
173
|
+
b.style.display = ''
|
|
174
|
+
b.onclick = () => { try { P.startOver() } catch (e) { /* */ } }
|
|
175
|
+
} catch (e) { /* */ }
|
|
176
|
+
}
|
|
177
|
+
function wireVisibility() {
|
|
178
|
+
if (_visWired) return; _visWired = true
|
|
179
|
+
try { addEventListener('pagehide', stampLeft) } catch (e) {}
|
|
180
|
+
document.addEventListener('visibilitychange', () => {
|
|
181
|
+
try {
|
|
182
|
+
const c = cfg(); if (!c.on) return
|
|
183
|
+
if (document.hidden) { _hiddenAt = Date.now(); return }
|
|
184
|
+
const away = _hiddenAt ? Date.now() - _hiddenAt : 0
|
|
185
|
+
_hiddenAt = 0 // ONE absence, judged once — a stale stamp must not lock a later return (a Face ID prompt, 2026-10-21)
|
|
186
|
+
if (_locked) return
|
|
187
|
+
const auto = +c.auto || 0
|
|
188
|
+
if (auto > 0 && away > auto * 60000) engage('away ' + Math.round(away / 60000) + ' min')
|
|
189
|
+
} catch (e) {}
|
|
190
|
+
})
|
|
191
|
+
}
|
|
192
|
+
function onLaunch() {
|
|
193
|
+
try {
|
|
194
|
+
if (!cfg().on) return
|
|
195
|
+
const left = takeLeft(), gap = Date.now() - left
|
|
196
|
+
if (!(left && gap >= 0 && gap < HANDOFF_MS)) { engage('launch'); return } // a launch (or a long gap): the lock, as before
|
|
197
|
+
if (!protectOn()) return // tier 2: the same session, continuing — stay unlocked
|
|
198
|
+
Promise.resolve().then(() => (P && P.handoff ? P.handoff() : false)).then((ok) => { if (!ok) engage('handoff: no key') }, () => engage('handoff failed')) // tier 3: the key must have crossed too
|
|
199
|
+
} catch (e) {}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
async function showSheet() { // enable/disable ceremony — needs REAL top-level user activation (WebAuthn)
|
|
203
|
+
const scr = el('set'); if (!scr) return
|
|
204
|
+
const onB = el('on'), offB = el('off'), msg = el('msg'), sel = el('auto')
|
|
205
|
+
const c = cfg()
|
|
206
|
+
if (msg) msg.textContent = ''
|
|
207
|
+
if (sel) sel.value = String(+c.auto || 0)
|
|
208
|
+
const nm = names() // this device's own words (Windows Hello, Touch ID…, the desktop app's system check), never "Face ID" on a computer
|
|
209
|
+
const lbl = el('toggleLbl'), desc = el('desc')
|
|
210
|
+
if (lbl) lbl.textContent = nm.title
|
|
211
|
+
if (desc) desc.textContent = `Require ${nm.require} to open ${appName} on this device.`
|
|
212
|
+
if (onB) onB.textContent = `Turn on ${nm.title}`
|
|
213
|
+
if (offB) offB.textContent = `Turn off (${nm.check.replace(/^your /, '')})`
|
|
214
|
+
if (onB) onB.style.display = c.on ? 'none' : ''
|
|
215
|
+
if (offB) offB.style.display = c.on ? '' : 'none'
|
|
216
|
+
const pBox = el('protect'), pMsg = el('protectMsg')
|
|
217
|
+
// §PROTECT FOLLOWS THE LOCK (the owner, 2026-10-16: "always off and grayed out without the lock on. With the lock on it
|
|
218
|
+
// is turned on and off only after checking the passkey"). Off + greyed out while the lock is off; while it is on, each
|
|
219
|
+
// change is one passkey ceremony — on: a protection passkey, its secret seals the stores; off: that passkey's secret
|
|
220
|
+
// writes them back — and the lock stays on. A failed or cancelled ceremony puts the switch back.
|
|
221
|
+
const showProtect = () => {
|
|
222
|
+
if (!pBox) return
|
|
223
|
+
const cur = cfg()
|
|
224
|
+
if (O && !protectOn()) { pBox.disabled = true; pBox.checked = false; if (pMsg) pMsg.textContent = 'This computer’s storage is already encrypted by its own key store.'; return }
|
|
225
|
+
pBox.disabled = !P || !cur.on; pBox.checked = protectOn()
|
|
226
|
+
if (pMsg) pMsg.textContent = !P ? 'Storage protection needs a browser with passkeys (Chrome, Edge, Safari).' : !cur.on ? `Turn on ${nm.title} first.` : (protectOn() ? 'On — your keys and messages on this device are encrypted until you unlock.' : '')
|
|
227
|
+
}
|
|
228
|
+
showProtect()
|
|
229
|
+
if (pBox) pBox.onchange = async () => {
|
|
230
|
+
const want = !!pBox.checked, cur = cfg()
|
|
231
|
+
if (!P || !cur.on || want === protectOn()) { showProtect(); return }
|
|
232
|
+
pBox.disabled = true; if (pMsg) pMsg.textContent = `Waiting for ${nm.check}…`
|
|
233
|
+
try {
|
|
234
|
+
if (want) {
|
|
235
|
+
const r = await P.enroll(appName + ' device protection')
|
|
236
|
+
if (!r || !r.credId || !r.secret) { showProtect(); if (pMsg) pMsg.textContent = 'This passkey can’t protect storage on this device.'; return }
|
|
237
|
+
const previews = !!(P.previewsPref ? P.previewsPref() : (vBox && vBox.checked))
|
|
238
|
+
// WRITE-AHEAD (2026-11-08, docs/state-machines.md I4): the config says "protected, not finished" BEFORE anything is sealed
|
|
239
|
+
await switchOnProtection(r.secret, { credId: r.credId, mode: r.mode || 'prf', previews }) // the same passkey gates the lock from now on
|
|
240
|
+
} else {
|
|
241
|
+
const r = await P.unlock(cur.protect.credId)
|
|
242
|
+
if (!r || !r.secret) { showProtect(); if (pMsg) pMsg.textContent = 'Not verified — protection stays on.'; return }
|
|
243
|
+
if (P.onUnprotect) await P.onUnprotect(r.secret)
|
|
244
|
+
const next = { ...cfg() }; delete next.protect; save(next) // the lock stays on, gated by the same passkey
|
|
245
|
+
}
|
|
246
|
+
showProtect()
|
|
247
|
+
} catch (e) { showProtect(); if (pMsg) pMsg.textContent = didntComplete(e) }
|
|
248
|
+
}
|
|
249
|
+
const vBox = el('previews')
|
|
250
|
+
if (vBox) { // §PREVIEWS: a sub-option of protection — while the lock is OFF it rides into the switch-on; while protection is ON it applies at once
|
|
251
|
+
vBox.checked = !!(c.protect && c.protect.previews)
|
|
252
|
+
vBox.disabled = !P || !protectOn()
|
|
253
|
+
vBox.onchange = async () => {
|
|
254
|
+
const cur = cfg(); if (!protectOn()) return // not on yet: the choice rides the switch-on
|
|
255
|
+
vBox.disabled = true
|
|
256
|
+
try { if (P.onPreviews) await P.onPreviews(vBox.checked); save({ ...cur, protect: { ...cur.protect, previews: vBox.checked } }) } catch (e) { vBox.checked = !vBox.checked }
|
|
257
|
+
vBox.disabled = false
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
onEngage(); scr.style.display = 'flex'
|
|
261
|
+
if (onB) onB.onclick = async () => {
|
|
262
|
+
onB.disabled = true; if (msg) msg.textContent = `Waiting for ${nm.check}…`
|
|
263
|
+
try {
|
|
264
|
+
// §PREVIEWS: the shell's "Show message preview" setting decides (beside Notifications, notifPreview.js); the sheet's
|
|
265
|
+
// own box only on a shell that still has one.
|
|
266
|
+
const protectCfg = null // storage protection is its own switch once the lock is on (§PROTECT FOLLOWS THE LOCK)
|
|
267
|
+
const credId = await verifyOwner() // ALWAYS a Face ID — a remembered passkey may be gone (verifyOwner)
|
|
268
|
+
if (!credId) { if (msg) msg.textContent = `Couldn’t set up ${nm.check} on this device.`; onB.disabled = false; return }
|
|
269
|
+
save({ on: true, auto: +(sel && sel.value) || 0, credId, ...(protectCfg ? { protect: protectCfg } : {}) })
|
|
270
|
+
if (msg) msg.textContent = protectCfg ? 'On ✓ — your keys and messages on this device are now encrypted until you unlock.' : `On ✓ — ${appName} will ask for ${nm.check} when it opens.`
|
|
271
|
+
showProtect()
|
|
272
|
+
onB.style.display = 'none'; onB.disabled = false; if (offB) offB.style.display = ''
|
|
273
|
+
} catch (e) { if (msg) msg.textContent = O ? `${nm.check.replace(/^your /, 'The ')} didn’t complete — try again.${whyOf(e)}` : didntComplete(e); onB.disabled = false }
|
|
274
|
+
}
|
|
275
|
+
if (offB) offB.onclick = async () => {
|
|
276
|
+
offB.disabled = true; if (msg) msg.textContent = `Confirm with ${nm.check} to turn off…`
|
|
277
|
+
try {
|
|
278
|
+
const cur0 = cfg()
|
|
279
|
+
if (protectOn()) { // §PROTECT: the passkey's secret writes the stores back in the clear before the lock goes
|
|
280
|
+
const r = await P.unlock(cur0.protect.credId)
|
|
281
|
+
if (!r || !r.secret) { if (msg) msg.textContent = 'Not verified.'; offB.disabled = false; return }
|
|
282
|
+
if (P.onUnprotect) await P.onUnprotect(r.secret)
|
|
283
|
+
} else {
|
|
284
|
+
const ok = await verifyOwner()
|
|
285
|
+
if (!ok) { if (msg) msg.textContent = 'Not verified.'; offB.disabled = false; return }
|
|
286
|
+
}
|
|
287
|
+
const cur = cfg(); save({ on: false, auto: cur.auto, credId: cur.credId })
|
|
288
|
+
if (_locked) release() // a cover that engaged meanwhile goes with the lock — never a lock screen for a lock that is off // keep the credential — re-enabling skips enrollment; protection is forgotten (re-enable re-enrolls)
|
|
289
|
+
showProtect()
|
|
290
|
+
if (vBox) { vBox.checked = false; vBox.disabled = true }
|
|
291
|
+
if (msg) msg.textContent = `Off. ${appName} opens without a lock.`
|
|
292
|
+
offB.style.display = 'none'; offB.disabled = false; if (onB) onB.style.display = ''
|
|
293
|
+
} catch (e) { if (msg) msg.textContent = didntComplete(e); offB.disabled = false }
|
|
294
|
+
}
|
|
295
|
+
if (sel) sel.onchange = () => { const cur = cfg(); if (cur.on) save({ ...cur, auto: +sel.value || 0 }) }
|
|
296
|
+
// THE SWITCH (a shell that has #lockToggle; 2026-10-10): one switch in place of the Turn on / Turn off buttons — it runs
|
|
297
|
+
// the same ceremony as they do (Face ID, the protection passkey) and shows the lock's REAL state after, so a cancelled
|
|
298
|
+
// Face ID leaves it where it was. The buttons stay as the ceremony's handles; a shell without the switch keeps them.
|
|
299
|
+
const sw = el('toggle')
|
|
300
|
+
if (sw) {
|
|
301
|
+
const show = () => sw.setAttribute('aria-checked', String(!!cfg().on))
|
|
302
|
+
if (onB) onB.style.display = 'none'
|
|
303
|
+
if (offB) offB.style.display = 'none'
|
|
304
|
+
show()
|
|
305
|
+
sw.onclick = async () => {
|
|
306
|
+
sw.disabled = true
|
|
307
|
+
try { await (cfg().on ? (offB && offB.onclick && offB.onclick()) : (onB && onB.onclick && onB.onclick())) } finally {
|
|
308
|
+
if (onB) onB.style.display = 'none'
|
|
309
|
+
if (offB) offB.style.display = 'none'
|
|
310
|
+
show(); sw.disabled = false
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
const cl = el('close'); if (cl) cl.onclick = () => { scr.style.display = 'none'; onRelease() }
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** §PREVIEWS changed OUTSIDE the sheet ("Show message preview", beside Notifications): under protection, apply it now —
|
|
318
|
+
* the push-preview keys go clear (on) or sealed (off) — and remember it. Nothing to do without protection. */
|
|
319
|
+
async function applyPreviews (on) {
|
|
320
|
+
if (!protectOn() || !P || !P.onPreviews) return false
|
|
321
|
+
await P.onPreviews(!!on)
|
|
322
|
+
const cur = cfg(); save({ ...cur, protect: { ...cur.protect, previews: !!on } })
|
|
323
|
+
return true
|
|
324
|
+
}
|
|
325
|
+
// DESKTOP PROTECTION (secureComputer.js, docs/desktop-protection.md): the switch-on below without the sheet — setup made the
|
|
326
|
+
// passkey already, so this seals the stores with its key and turns the lock on, the same credential gating both.
|
|
327
|
+
async function enableProtection({ credId, mode = 'prf', raw, previews = false }) {
|
|
328
|
+
if (!P || !P.onProtect) throw new Error('protection_unavailable')
|
|
329
|
+
if (!credId || !raw) throw new Error('no_key')
|
|
330
|
+
const cur = cfg()
|
|
331
|
+
// sealed under ANOTHER passkey already (another tab secured this computer — pass 9, V#1): a switch-on with this one would
|
|
332
|
+
// remove what that one sealed. Only the passkey the configuration names may finish (its own pending switch-on).
|
|
333
|
+
if (cur.protect && cur.protect.on && cur.protect.credId && cur.protect.credId !== credId) throw new Error('already_protected')
|
|
334
|
+
save({ ...cur, on: true, auto: Number.isFinite(+cur.auto) && +cur.auto > 0 ? +cur.auto : 5 })
|
|
335
|
+
await switchOnProtection(raw, { credId, mode, previews })
|
|
336
|
+
return true
|
|
337
|
+
}
|
|
338
|
+
// ⛔ PROTECTION IS SWITCHED ON WRITE-AHEAD (2026-11-08, docs/state-machines.md I4 / A#1): the stores were sealed FIRST and the
|
|
339
|
+
// config said so only after — a page killed (iOS), a tab closed or a throw (quota) in between left a disk sealed under a
|
|
340
|
+
// key the config did not name: the next launch read it as unprotected, the device looked signed out, and switching
|
|
341
|
+
// protection on again deleted the sealed entries for good. Now the config names the key and `pending` first; the seal
|
|
342
|
+
// follows; `pending` goes when it is done. A launch that finds `pending` unlocks with that passkey and finishes the switch-on
|
|
343
|
+
// (unlockOnce) — the same secret, so whatever was sealed opens and the rest is sealed.
|
|
344
|
+
async function switchOnProtection (secret, { credId, mode, previews }) {
|
|
345
|
+
save({ ...cfg(), credId, protect: { on: true, credId, mode, at: Date.now(), previews, pending: true } })
|
|
346
|
+
if (P.onProtect) await P.onProtect(secret, { previews })
|
|
347
|
+
const c = cfg(); const { pending: _p, ...done } = c.protect || {}
|
|
348
|
+
save({ ...c, protect: done })
|
|
349
|
+
}
|
|
350
|
+
async function finishPending (secret) {
|
|
351
|
+
const c = cfg()
|
|
352
|
+
if (!(c.protect && c.protect.pending) || !P.onProtect) return
|
|
353
|
+
await P.onProtect(secret, { previews: !!c.protect.previews, resume: true }) // resume: what is sealed already is this key's, not an earlier setup's leftover
|
|
354
|
+
const n = cfg(); const { pending: _p, ...done } = n.protect || {}
|
|
355
|
+
save({ ...n, protect: done })
|
|
356
|
+
}
|
|
357
|
+
return { enableProtection, cfg, save, enroll, assert, engage, release, tryUnlock, wireVisibility, onLaunch, showSheet, isLocked: () => _locked, protectOn, previewsOn, applyPreviews }
|
|
358
|
+
}
|
package/spacePasskey.js
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
// spaces/public/spacePasskey.js — a PHRASELESS recovery secret from a passkey, so you can restore your Spaces with a
|
|
2
|
+
// fingerprint/PIN instead of a typed code. Two mechanisms, tried in order:
|
|
3
|
+
// • PRF (WebAuthn `prf`) — the authenticator DERIVES a stable secret from the credential (best: re-derives on any
|
|
4
|
+
// synced device). Works on iOS/Android, Safari on recent macOS, some desktop setups.
|
|
5
|
+
// • largeBlob (`largeBlob`) — the authenticator STORES a random secret we write into the credential. Covers many
|
|
6
|
+
// desktop passkeys that support log-in but not PRF (common on Windows Hello, Chrome/Mac).
|
|
7
|
+
// Either way the 32-byte secret feeds recovery.js deriveKeysFromSecret → the exact same content-blind backup. We never
|
|
8
|
+
// verify the assertion server-side; the passkey is a LOCAL secret oracle bound to user verification. Zero deps.
|
|
9
|
+
|
|
10
|
+
const SALT = new TextEncoder().encode('witbitz-spaces-backup-prf-v1') // fixed → same credential + salt ⇒ same PRF secret
|
|
11
|
+
const rpId = () => location.hostname
|
|
12
|
+
const rnd = (n) => crypto.getRandomValues(new Uint8Array(n))
|
|
13
|
+
// What an authenticator said about the two ways it can hold a key — for the diagnostics list, never the secret itself.
|
|
14
|
+
const extSummary = (ext) => { try { const p = ext && ext.prf, l = ext && ext.largeBlob; return `prf:${p ? (p.results && p.results.first ? 'result' : (p.enabled === true ? 'enabled' : p.enabled === false ? 'disabled' : 'silent')) : 'absent'} largeBlob:${l ? (l.blob ? 'blob' : l.written === true ? 'written' : l.supported === true ? 'supported' : l.supported === false ? 'unsupported' : 'silent') : 'absent'}` } catch { return '?' } }
|
|
15
|
+
const b64url = (u8) => b64(u8).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
|
16
|
+
const b64 = (u8) => { let s = ''; for (let i = 0; i < u8.length; i++) s += String.fromCharCode(u8[i]); return btoa(s) }
|
|
17
|
+
const fromB64 = (s) => { const b = atob(s); const u = new Uint8Array(b.length); for (let i = 0; i < b.length; i++) u[i] = b.charCodeAt(i); return u }
|
|
18
|
+
// A STABLE per-device user.id so re-enrolling doesn't spawn a NEW passkey every time — the authenticator/manager treats
|
|
19
|
+
// the same (rpId, user.id) as one account and updates it in place, instead of piling up duplicates (as happened before).
|
|
20
|
+
// ⚑ ONE HANDLE PER PURPOSE (2026-10-06): "updates it in place" is also how a SECOND purpose's enrollment replaced the
|
|
21
|
+
// first — device protection enrolled under the recovery passkey's handle and the authenticator overwrote it. `key` names
|
|
22
|
+
// the purpose's own handle (sdkProtect.js uses 'space:pkuser:protect'); the default is the recovery handle, as before.
|
|
23
|
+
function stableUserId(key = 'space:pkuser') {
|
|
24
|
+
try { const s = localStorage.getItem(key); if (s) return fromB64(s); const u = rnd(16); localStorage.setItem(key, b64(u)); return u } catch { return rnd(16) }
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// ⛔ THE REPAIR MUST NOT BREAK THE DEVICE (2026-10-17). A device that turned storage protection on before 755e9c48 enrolled
|
|
28
|
+
// its PROTECTION passkey under the recovery handle (that is how its recovery passkey was replaced). Adding a backup
|
|
29
|
+
// passkey there now would replace the protection passkey in turn — and the device could no longer open its own sealed
|
|
30
|
+
// storage. Recognised by: protection on (either lock's config) while this device never made a protection handle.
|
|
31
|
+
// Turning protection off and on again re-enrols it under its own handle; then a backup passkey is safe to add.
|
|
32
|
+
export const SHARED_HANDLE_TEXT = 'This device’s storage protection uses the same passkey slot as a backup passkey, so adding one here would replace it. Turn “Also protect this device’s storage” off and on again (Face ID lock), then add the passkey.'
|
|
33
|
+
export function protectionSharesRecoveryHandle () {
|
|
34
|
+
try {
|
|
35
|
+
if (localStorage.getItem('space:pkuser:protect')) return false
|
|
36
|
+
return ['space:lock', 'vault:lock'].some((k) => { const c = JSON.parse(localStorage.getItem(k) || 'null'); return !!(c && c.protect && c.protect.on) })
|
|
37
|
+
} catch { return false }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** This device as a person would recognise it ("Chrome on Windows") — the same words as Your devices (devices.js). */
|
|
41
|
+
export function passkeyDevice() {
|
|
42
|
+
const ua = (typeof navigator !== 'undefined' && navigator.userAgent) || ''
|
|
43
|
+
const os = /iPhone/.test(ua) ? 'iPhone' : /iPad/.test(ua) ? 'iPad' : /Android/.test(ua) ? 'Android' : /(Mac OS X|Macintosh)/.test(ua) ? 'Mac' : /Windows/.test(ua) ? 'Windows' : /Linux/.test(ua) ? 'Linux' : 'a device'
|
|
44
|
+
const br = /Edg\//.test(ua) ? 'Edge' : /(OPR\/|Opera)/.test(ua) ? 'Opera' : /Firefox\//.test(ua) ? 'Firefox' : /Chrome\//.test(ua) ? 'Chrome' : /Safari\//.test(ua) ? 'Safari' : 'a browser'
|
|
45
|
+
return br + ' on ' + os
|
|
46
|
+
}
|
|
47
|
+
/** The name a passkey carries in the keychain (the owner, 2026-10-11: "many passkeys for the same origin. Can I distinguish
|
|
48
|
+
* between them? For what device? What purpose?") — purpose · device · date, e.g. "Spaces backup · Chrome on Windows · 11 Oct 2026". */
|
|
49
|
+
export function describePasskey(purpose, at = Date.now()) {
|
|
50
|
+
let day = ''; try { day = new Date(at).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' }) } catch { /* */ }
|
|
51
|
+
return [purpose, passkeyDevice(), day].filter(Boolean).join(' · ')
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** A backup passkey's name says WHOSE it is (the owner, 2026-10-12: two accounts' passkeys were both "Spaces backup · iPhone
|
|
55
|
+
* · date", and nothing told them apart in Passwords). The app is the website it is filed under. */
|
|
56
|
+
export const passkeyPurpose = (email) => (email && /@/.test(String(email)) ? String(email).trim().toLowerCase() + ' · ' : '') + 'Spaces backup'
|
|
57
|
+
|
|
58
|
+
/** Is the platform capable of a passkey at all? (Coarse — real PRF/largeBlob support is only known once we try to enroll.) */
|
|
59
|
+
export function passkeyPossible() {
|
|
60
|
+
if (window.WitbitzDesktop && window.WitbitzDesktop.passkeyAvailable === false) return false
|
|
61
|
+
return !!(window.PublicKeyCredential && navigator.credentials && navigator.credentials.create && location.protocol === 'https:')
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Read the secret from an assertion, requesting BOTH mechanisms — PRF (derive) and largeBlob (stored) — and returning
|
|
65
|
+
// whichever the credential answers with. `credId` scopes to a known credential; null → discoverable (a new device picks a
|
|
66
|
+
// synced passkey). Throws 'cancelled' on dismiss, 'no_secret' if neither mechanism produced one.
|
|
67
|
+
async function readSecret(credId, rpIdOverride, hints) {
|
|
68
|
+
let a
|
|
69
|
+
try {
|
|
70
|
+
a = await navigator.credentials.get({ publicKey: {
|
|
71
|
+
challenge: rnd(32),
|
|
72
|
+
rpId: rpIdOverride || rpId(),
|
|
73
|
+
allowCredentials: credId ? [{ type: 'public-key', id: credId }] : [],
|
|
74
|
+
userVerification: 'required',
|
|
75
|
+
...(hints ? { hints } : {}), // the same phone again, for a passkey just saved there
|
|
76
|
+
// evalByCredential too, for the credential we name (the owner's 1Password through Windows, 2026-10-11: create said
|
|
77
|
+
// prf:enabled, the read returned no prf at all with `eval` alone). The spec allows both; for a named credential it
|
|
78
|
+
// takes evalByCredential, which some platform paths map where they ignore `eval`.
|
|
79
|
+
extensions: { prf: { eval: { first: SALT }, ...(credId ? { evalByCredential: { [b64url(credId)]: { first: SALT } } } : {}) }, largeBlob: { read: true } },
|
|
80
|
+
} })
|
|
81
|
+
} catch (e) { const err = new Error(e && e.name === 'NotAllowedError' ? 'cancelled' : 'get_failed'); err.detail = (e && (e.name + ': ' + e.message)) || ''; throw err }
|
|
82
|
+
const r = a.getClientExtensionResults() || {}
|
|
83
|
+
const credOut = b64(new Uint8Array(a.rawId))
|
|
84
|
+
// A credential can answer with BOTH a PRF secret and a largeBlob secret, and the backup may have been made with either
|
|
85
|
+
// (e.g. a device without PRF used largeBlob, another device sees PRF). Return ALL of them so restore can try each.
|
|
86
|
+
const secrets = []
|
|
87
|
+
if (r.prf && r.prf.results && r.prf.results.first) secrets.push({ secret: new Uint8Array(r.prf.results.first), mode: 'prf' })
|
|
88
|
+
if (r.largeBlob && r.largeBlob.blob) secrets.push({ secret: new Uint8Array(r.largeBlob.blob), mode: 'largeblob' })
|
|
89
|
+
if (!secrets.length) { const err = new Error('no_secret'); err.detail = 'get ' + extSummary(r); throw err }
|
|
90
|
+
return { credId: credOut, secret: secrets[0].secret, mode: secrets[0].mode, secrets }
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Store `secret` into a credential's largeBlob (a follow-up get with `write`). Returns true iff written.
|
|
94
|
+
const sameBytes = (a, b) => { if (!a || !b || a.length !== b.length) return false; let d = 0; for (let i = 0; i < a.length; i++) d |= a[i] ^ b[i]; return d === 0 }
|
|
95
|
+
async function writeLargeBlob(credId, secret, rpIdOverride) {
|
|
96
|
+
try {
|
|
97
|
+
const a = await navigator.credentials.get({ publicKey: {
|
|
98
|
+
challenge: rnd(32),
|
|
99
|
+
rpId: rpIdOverride || rpId(),
|
|
100
|
+
allowCredentials: [{ type: 'public-key', id: credId }],
|
|
101
|
+
userVerification: 'required',
|
|
102
|
+
extensions: { largeBlob: { write: secret } },
|
|
103
|
+
} })
|
|
104
|
+
const r = a.getClientExtensionResults() || {}
|
|
105
|
+
return !!(r.largeBlob && r.largeBlob.written)
|
|
106
|
+
} catch { return false }
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Enroll a new discoverable passkey and obtain its secret — PRF if available, else largeBlob. Returns
|
|
110
|
+
* { credId (b64), secret (Uint8Array), mode }. Throws 'prf_unsupported' if the passkey can hold NEITHER a PRF nor a
|
|
111
|
+
* largeBlob key (→ fall back to a typed code), 'cancelled' on dismiss. */
|
|
112
|
+
export async function enrollPasskey(label, rpIdOverride, { rpName = 'Witbitz Spaces', userName = 'Spaces backup', userKey, onSecondStep, hints } = {}) { // rpIdOverride: enrol under the app's registrable domain so a subdomain vault's passkey is usable by the app; the names + userKey: an SDK app's own, or a second purpose's own handle
|
|
113
|
+
if (!userKey && protectionSharesRecoveryHandle()) { const err = new Error('protect_shared_handle'); err.detail = SHARED_HANDLE_TEXT; throw err } // ⛔ above
|
|
114
|
+
let cred
|
|
115
|
+
try {
|
|
116
|
+
cred = await navigator.credentials.create({ publicKey: {
|
|
117
|
+
rp: { id: rpIdOverride || rpId(), name: rpName },
|
|
118
|
+
user: { id: stableUserId(userKey), name: userName, displayName: label || userName }, // stable id → one passkey per purpose, not many
|
|
119
|
+
challenge: rnd(32),
|
|
120
|
+
pubKeyCredParams: [{ type: 'public-key', alg: -7 }, { type: 'public-key', alg: -257 }],
|
|
121
|
+
authenticatorSelection: { residentKey: 'required', requireResidentKey: true, userVerification: 'required' },
|
|
122
|
+
extensions: { prf: { eval: { first: SALT } }, largeBlob: { support: 'preferred' } },
|
|
123
|
+
...(hints ? { hints } : {}), // ['hybrid'] = save it on a phone: the browser shows a code the phone scans (WebAuthn L3 hints)
|
|
124
|
+
} })
|
|
125
|
+
} catch (e) { const err = new Error(e && e.name === 'NotAllowedError' ? 'cancelled' : 'create_failed'); err.detail = (e && (e.name + ': ' + e.message)) || ''; throw err }
|
|
126
|
+
const ext = cred.getClientExtensionResults() || {}
|
|
127
|
+
const credId = new Uint8Array(cred.rawId)
|
|
128
|
+
|
|
129
|
+
// ⛔ A SECRET FROM create() IS NOT TRUSTED UNTIL AN ASSERTION GIVES IT BACK (the owner's Windows Hello in Edge, 2026-10-12:
|
|
130
|
+
// create() returned a PRF value, every later get() — eval, evalByCredential, both — returned NONE; the computer was sealed
|
|
131
|
+
// under a secret no unlock could ever produce). The secret that counts is the one an UNLOCK will see, so it is read from
|
|
132
|
+
// an assertion — and when create() also answered, the two must match. One extra prompt, at setup only.
|
|
133
|
+
const createdPrf = (ext.prf && ext.prf.results && ext.prf.results.first) ? new Uint8Array(ext.prf.results.first) : null
|
|
134
|
+
// ASK THE CREDENTIAL, don't trust create()'s silence. The PRF value only ever arrives on an ASSERTION for many
|
|
135
|
+
// authenticators (iOS), and the spec does not require a provider to echo extension results from create() at all —
|
|
136
|
+
// plenty simply don't. Gating this follow-up get() on `ext.prf` therefore misclassified perfectly capable
|
|
137
|
+
// credentials as "can't hold a key": a Bitwarden-stored passkey on iOS enrolled fine at one point and failed later
|
|
138
|
+
// with prf_unsupported, purely because create() said nothing about prf. The assertion is the authoritative test,
|
|
139
|
+
// so always run it before giving up. Cost is one extra prompt, and ONLY on the path that would otherwise fail.
|
|
140
|
+
try { if (onSecondStep) onSecondStep() } catch { /* the note is a courtesy */ } // say why a second prompt is coming (the owner, 2026-10-11)
|
|
141
|
+
const trail = ['create ' + extSummary(ext)] // what each step answered — rides the failure to the diagnostics list
|
|
142
|
+
try {
|
|
143
|
+
const s = await readSecret(credId, rpIdOverride, hints)
|
|
144
|
+
const prf = s && (s.secrets || []).find((x) => x.mode === 'prf' && x.secret && x.secret.length >= 16)
|
|
145
|
+
if (prf && (!createdPrf || sameBytes(createdPrf, prf.secret))) return { credId: s.credId, secret: prf.secret, mode: 'prf', secrets: [prf] }
|
|
146
|
+
trail.push(prf ? 'get prf: differs from create' : ('get ' + (createdPrf ? 'prf: none (create gave one)' : 'prf: none')))
|
|
147
|
+
} catch (e) { trail.push((e && e.detail) || ('get ' + ((e && e.message) || 'failed'))) } // fall through to largeBlob
|
|
148
|
+
// FALLBACK: largeBlob — STORE a random secret in the credential (for passkeys that log in but can't do PRF). Same
|
|
149
|
+
// reasoning: attempt the write unless create() explicitly said largeBlob is unsupported.
|
|
150
|
+
if (!ext.largeBlob || ext.largeBlob.supported !== false) {
|
|
151
|
+
const secret = rnd(32)
|
|
152
|
+
if (await writeLargeBlob(credId, secret, rpIdOverride)) {
|
|
153
|
+
// …and READ IT BACK, as an unlock will: a "written" the next read cannot see is the same trap as a create-only PRF
|
|
154
|
+
try { const s = await readSecret(credId, rpIdOverride, hints); const lb = s && (s.secrets || []).find((x) => x.mode === 'largeblob'); if (lb && sameBytes(lb.secret, secret)) return { credId: b64(credId), secret, mode: 'largeblob' }; trail.push('largeBlob: written, not read back') } catch (e) { trail.push('largeBlob read-back: ' + ((e && e.detail) || (e && e.message) || 'failed')) }
|
|
155
|
+
} else trail.push('largeBlob write: refused')
|
|
156
|
+
}
|
|
157
|
+
// Nothing will ever use this passkey — ask the provider to drop it, so it does not sit in the user's list (and in every
|
|
158
|
+
// later passkey prompt) doing nothing. Best-effort: the Signal API is newer than WebAuthn, and providers may ignore it.
|
|
159
|
+
try { if (window.PublicKeyCredential && PublicKeyCredential.signalUnknownCredential) await PublicKeyCredential.signalUnknownCredential({ rpId: rpIdOverride || rpId(), credentialId: b64url(credId) }) } catch { /* */ }
|
|
160
|
+
{ const err = new Error('prf_unsupported'); err.detail = trail.join(' · ') + ' · ' + ((typeof navigator !== 'undefined' && navigator.userAgent) || '').slice(0, 120); throw err } // neither PRF nor largeBlob → this passkey can't hold a backup key
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** What to tell a person whose new passkey could not hold a key (prf_unsupported). Windows Hello is the common case on a
|
|
164
|
+
* desktop (the owner, 2026-10-11): it signs in, but gives the app no key — a phone's passkey (over the Windows prompt's
|
|
165
|
+
* phone option) does. */
|
|
166
|
+
export function noKeyPasskeyText() {
|
|
167
|
+
const ua = (typeof navigator !== 'undefined' && navigator.userAgent) || ''
|
|
168
|
+
// Measured on the owner's Windows 11 (2026-10-11): a passkey SAVED TO THIS WINDOWS DEVICE holds the key; 1Password reached through the
|
|
169
|
+
// Windows box said prf:enabled and then answered nothing. So name the manager as the cause and the device as the cure.
|
|
170
|
+
if (/Windows/.test(ua)) return 'That passkey couldn’t hold the key your backup needs, so it wasn’t added — some passkey managers reached through the Windows box (1Password, for one) can’t. Your recovery code still works. Save it to this Windows device instead: in the Windows box choose this device, or turn on Windows Settings → Accounts → Passkeys → Advanced options → “Save passkeys to this Windows device”. Or use your phone.'
|
|
171
|
+
return 'That passkey couldn’t hold a key. Try saving it to a different provider (iCloud Keychain is reliable on iOS) — your backup is unaffected.'
|
|
172
|
+
}
|
|
173
|
+
export const PASSKEY_SECOND_STEP = 'One more step: confirm the passkey you just made so it can hold your key.'
|
|
174
|
+
|
|
175
|
+
/** Read the secret from an existing/synced passkey (a follow-up unlock, or a new device's restore) — PRF or largeBlob.
|
|
176
|
+
* Returns { credId, secret, mode }; throws 'prf_no_result' if the passkey yielded no secret, 'cancelled' on dismiss. */
|
|
177
|
+
export async function unlockPasskey(credIdB64, rpIdOverride) { // rpIdOverride: assert under the app's registrable domain (a subdomain vault uses the parent rpId)
|
|
178
|
+
try { return await readSecret(credIdB64 ? fromB64(credIdB64) : null, rpIdOverride) }
|
|
179
|
+
catch (e) { const err = new Error(e && e.message === 'no_secret' ? 'prf_no_result' : (e && e.message) || 'get_failed'); if (e && e.detail) err.detail = e.detail; throw err }
|
|
180
|
+
}
|