@bsv/expo-wallet-toolbox 0.21.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/CHANGELOG.md +222 -0
  2. package/README.md +82 -13
  3. package/core/bridge/BrowserBridgeProvider.tsx +273 -0
  4. package/core/bridge/bindings.ts +459 -0
  5. package/core/bridge/conformance.ts +222 -0
  6. package/core/bridge/consent.ts +494 -0
  7. package/core/bridge/consentSheetSource.ts +98 -0
  8. package/core/bridge/dispatcher.ts +621 -0
  9. package/core/bridge/inbox.ts +464 -0
  10. package/core/bridge/index.ts +48 -0
  11. package/core/bridge/loopback/cors.ts +57 -0
  12. package/core/bridge/loopback/endpoints.ts +11 -0
  13. package/core/bridge/loopback/hostCheck.ts +25 -0
  14. package/core/bridge/loopback/index.ts +7 -0
  15. package/core/bridge/loopback/launchProof.ts +166 -0
  16. package/core/bridge/loopback/router.ts +770 -0
  17. package/core/bridge/loopback/routerTypes.ts +115 -0
  18. package/core/bridge/loopback/status.ts +52 -0
  19. package/core/bridge/memoryInboxStore.ts +222 -0
  20. package/core/bridge/permissionPolicy.ts +247 -0
  21. package/core/bridge/policy.ts +72 -0
  22. package/core/bridge/protocol/base64url.ts +64 -0
  23. package/core/bridge/protocol/connectionError.ts +79 -0
  24. package/core/bridge/protocol/constants.ts +21 -0
  25. package/core/bridge/protocol/continuity.ts +21 -0
  26. package/core/bridge/protocol/descriptor.ts +395 -0
  27. package/core/bridge/protocol/envelopes.ts +188 -0
  28. package/core/bridge/protocol/errorCodec.ts +164 -0
  29. package/core/bridge/protocol/json.ts +237 -0
  30. package/core/bridge/protocol/limits.ts +43 -0
  31. package/core/bridge/protocol/methods.ts +55 -0
  32. package/core/bridge/protocol/origin.ts +130 -0
  33. package/core/bridge/runtime.ts +642 -0
  34. package/core/bridge/runtimeFlags.ts +34 -0
  35. package/core/bridge/testing/conformanceCases.ts +149 -0
  36. package/core/bridge/testing/pageClient.ts +44 -0
  37. package/core/bridge/unverifiedManager.ts +97 -0
  38. package/core/bridge/unverifiedOriginator.ts +79 -0
  39. package/core/config.tsx +1 -16
  40. package/core/contacts/contactActivity.ts +48 -28
  41. package/core/contacts/contactsStore.ts +2 -2
  42. package/core/context/WalletConnectionContext.tsx +7 -1
  43. package/core/context/WalletContext.tsx +420 -348
  44. package/core/context/sessionTeardown.ts +46 -0
  45. package/core/demo/demoAssets.ts +8 -10
  46. package/core/demo/demoLedger.ts +32 -38
  47. package/core/demo/demoMandalaRuntime.ts +67 -49
  48. package/core/demo/index.ts +1 -1
  49. package/core/hooks/usePermissionQueue.ts +89 -34
  50. package/core/i18n/translations.tsx +983 -12
  51. package/core/index.ts +70 -37
  52. package/core/localpay/build.ts +110 -569
  53. package/core/localpay/codec.ts +190 -93
  54. package/core/localpay/pending.ts +217 -202
  55. package/core/localpay/session.ts +99 -25
  56. package/core/localpay/types.ts +6 -5
  57. package/core/localpay/verify.ts +118 -173
  58. package/core/mandala/abortGuard.ts +97 -120
  59. package/core/mandala/accessPolicy.ts +133 -0
  60. package/core/mandala/assets.ts +370 -0
  61. package/core/mandala/colorGuard.ts +178 -0
  62. package/core/mandala/colorModule.ts +82 -0
  63. package/core/mandala/createRuntime.ts +483 -2392
  64. package/core/mandala/handle.ts +694 -0
  65. package/core/mandala/kvStore.ts +105 -0
  66. package/core/mandala/nearby.ts +185 -0
  67. package/core/mandala/receipt.ts +121 -0
  68. package/core/mandala/runtime.ts +166 -312
  69. package/core/mandala/settle.ts +540 -0
  70. package/core/mandala/transferJournal.ts +395 -0
  71. package/core/mandala/types.ts +61 -311
  72. package/core/networks.ts +5 -5
  73. package/core/offline/cancelParked.ts +80 -63
  74. package/core/offline/payerHold.ts +52 -118
  75. package/core/parsePeerPayURI.ts +25 -12
  76. package/core/pay/rails/handle.ts +15 -14
  77. package/core/pay/rails/index.ts +5 -3
  78. package/core/pay/rails/nearby.ts +25 -87
  79. package/core/profiles/assertProfileEmpty.ts +19 -10
  80. package/core/services/autoApprovePolicy.ts +7 -1
  81. package/core/services/capWalletArgs.ts +2 -1
  82. package/core/services/permissionPrompts.ts +132 -0
  83. package/core/services/signingPermissionPolicy.ts +230 -2
  84. package/core/services/vault/guard.ts +15 -4
  85. package/core/services/walletArgLimits.ts +17 -2
  86. package/core/storage/StorageExpoSQLite.ts +93 -229
  87. package/core/storage/encryptedDbImage.ts +325 -0
  88. package/core/storage/methods/processOfflineActions.ts +86 -136
  89. package/core/storage/schema/createTables.ts +9 -184
  90. package/core/toolboxConfig.ts +18 -1
  91. package/package.json +9 -8
  92. package/ui/bridgeSheet/ContextRelay.tsx +86 -0
  93. package/ui/bridgeSheet/relayedContexts.ts +21 -0
  94. package/ui/components/pay/AssetPicker.tsx +2 -2
  95. package/ui/components/pay/HandleReceive.tsx +4 -4
  96. package/ui/components/pay/NearbyFlow.tsx +324 -239
  97. package/ui/components/pay/RequestHub.tsx +10 -0
  98. package/ui/components/pay/UniversalSend.tsx +31 -28
  99. package/ui/components/pay/useRecipientInput.ts +2 -2
  100. package/ui/components/ui/PermissionSheet.tsx +625 -315
  101. package/ui/components/ui/Sheet.tsx +59 -7
  102. package/ui/components/ui/colorPrompt.ts +236 -0
  103. package/ui/components/ui/sheetResumeSignal.ts +19 -0
  104. package/ui/components/wallet/AmountInput.tsx +9 -6
  105. package/ui/components/wallet/AssetAmount.tsx +6 -6
  106. package/ui/components/wallet/AssetSwitcherDropdown.tsx +26 -7
  107. package/ui/components/wallet/Balance.tsx +3 -1
  108. package/ui/components/wallet/ContactActivityList.tsx +10 -13
  109. package/ui/components/wallet/tokenEviction.ts +9 -9
  110. package/ui/exportDatabases.ts +94 -5
  111. package/ui/hooks/useExportWalletData.ts +37 -24
  112. package/ui/hooks/useMandala.ts +6 -6
  113. package/ui/hooks/useSpendableBalance.ts +3 -1
  114. package/ui/importDatabases.ts +124 -29
  115. package/ui/index.ts +4 -0
  116. package/ui/screens/PayScreen.tsx +14 -20
  117. package/ui/screens/SettingsScreen.tsx +3 -1
  118. package/ui/screens/WalletCheckScreen.tsx +7 -2
  119. package/ui/screens/WalletConfigScreen.tsx +13 -1
  120. package/ui/screens/WalletHomeScreen.tsx +40 -14
  121. package/ui/screens/tokenRowTitle.ts +28 -15
  122. package/ui/tokenFormat.ts +133 -69
  123. package/ui/tokenStatus.ts +5 -8
  124. package/core/localpay/settlementAck.ts +0 -155
  125. package/core/mandala/basketMigration.ts +0 -166
  126. package/core/mandala/bundle.ts +0 -244
  127. package/core/mandala/drain.ts +0 -754
  128. package/core/mandala/inboxPrehold.ts +0 -193
  129. package/core/mandala/permissionModule.ts +0 -931
  130. package/core/mandala/resendTransfer.ts +0 -178
  131. package/core/mandala/settlementStore.ts +0 -434
  132. package/core/mandala/token.ts +0 -45
  133. package/core/offline/tokenFrames.ts +0 -197
@@ -0,0 +1,188 @@
1
+ /**
2
+ * Wire shapes shared by every bridge layer (spec 6.8, 6.10): BRC-185 `brc185:*` XDM envelopes,
3
+ * and the durable inbox's records, results and close events. Types plus strict structural
4
+ * validators; no behaviour. Project 3's ts-stack side must reproduce the fixtures built from
5
+ * these shapes.
6
+ */
7
+ import type { ConnectionError } from './connectionError'
8
+ import type { WireError } from './errorCodec'
9
+
10
+ /** BRC-185 section 4: why an epoch closed, as seen by a page. */
11
+ export type CloseReason = 'account-changed' | 'revoked' | 'lost'
12
+ /** Internal close reasons add `disconnected`, which is never sent to the page that asked. */
13
+ export type InternalCloseReason = CloseReason | 'disconnected'
14
+
15
+ export const BRC185_VERSION = 1
16
+
17
+ export interface XdmConnect {
18
+ type: 'brc185:connect'
19
+ version: 1
20
+ instanceId: string
21
+ continuityKey: string
22
+ epoch: string
23
+ challenge: string
24
+ }
25
+ export interface XdmConnected {
26
+ type: 'brc185:connected'
27
+ version: 1
28
+ proof: unknown
29
+ }
30
+ export interface XdmConnectionError {
31
+ type: 'brc185:connection-error'
32
+ version: 1
33
+ epoch: string
34
+ error: ConnectionError
35
+ }
36
+ export interface XdmInvoke {
37
+ type: 'brc185:invoke'
38
+ version: 1
39
+ instanceId: string
40
+ epoch: string
41
+ id: string
42
+ method: string
43
+ params: unknown
44
+ }
45
+ export interface XdmResult {
46
+ type: 'brc185:result'
47
+ version: 1
48
+ instanceId: string
49
+ epoch: string
50
+ id: string
51
+ result: unknown
52
+ }
53
+ export interface XdmError {
54
+ type: 'brc185:error'
55
+ version: 1
56
+ instanceId: string
57
+ epoch: string
58
+ id: string
59
+ error: WireError | ConnectionError
60
+ }
61
+ export interface XdmClosed {
62
+ type: 'brc185:closed'
63
+ version: 1
64
+ instanceId: string
65
+ epoch: string
66
+ reason: CloseReason
67
+ }
68
+ export type XdmEnvelope = XdmConnect | XdmConnected | XdmConnectionError | XdmInvoke | XdmResult | XdmError | XdmClosed
69
+
70
+ /** Durable inbox (6.8). There is no `attestation` field: trust comes from the registered transport. */
71
+ export interface InboxRecord {
72
+ v: 1
73
+ id: string
74
+ kind: 'invoke' | 'disconnect'
75
+ epoch: string
76
+ instanceId: string
77
+ continuityKey: string
78
+ origin: string
79
+ accountContext: string
80
+ walletRevision: string
81
+ boundAt: number
82
+ method?: string
83
+ args?: unknown
84
+ createdAt: number
85
+ notAfter: number
86
+ }
87
+
88
+ export type InboxResult =
89
+ | { v: 1; id: string; ok: true; result: unknown }
90
+ | { v: 1; id: string; ok: false; error: WireError | ConnectionError }
91
+
92
+ /**
93
+ * Epoch-specific close event in the store's outbox; `closeSeq` is monotonic. A page-initiated
94
+ * `disconnect` is written too (reason `lost`) with `notifyPage: false`: it is a close, but the
95
+ * page that asked is not told, so the reader must not emit `brc185:closed` for it.
96
+ */
97
+ export interface InboxCloseEvent {
98
+ v: 1
99
+ closeSeq: number
100
+ instanceId: string
101
+ epoch: string
102
+ reason: CloseReason
103
+ notifyPage?: false
104
+ }
105
+
106
+ const UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
107
+ const CLOSE_REASONS: readonly string[] = ['account-changed', 'revoked', 'lost']
108
+
109
+ export function isUuidV4(v: unknown): v is string {
110
+ return typeof v === 'string' && UUID_V4.test(v)
111
+ }
112
+ export function isCloseReason(v: unknown): v is CloseReason {
113
+ return typeof v === 'string' && CLOSE_REASONS.includes(v)
114
+ }
115
+
116
+ function hasExactKeys(o: Record<string, unknown>, keys: string[]): boolean {
117
+ const have = Object.keys(o)
118
+ return have.length === keys.length && keys.every(k => Object.prototype.hasOwnProperty.call(o, k))
119
+ }
120
+
121
+ /**
122
+ * Structural check of an incoming XDM envelope. Returns the envelope or undefined: routing fields
123
+ * must be UUIDv4 strings, `version` must be 1, the key set must match exactly (so `result` and
124
+ * `error` stay mutually exclusive), and the type must be a known `brc185:*`. Unknown types are
125
+ * not envelopes of ours and are left to the legacy CWI path.
126
+ */
127
+ export function parseXdmEnvelope(v: unknown): XdmEnvelope | undefined {
128
+ if (typeof v !== 'object' || v === null || Array.isArray(v)) return undefined
129
+ const o = v as Record<string, unknown>
130
+ if (o.version !== BRC185_VERSION) return undefined
131
+ const routing = (...names: string[]) => names.every(n => isUuidV4(o[n]))
132
+ switch (o.type) {
133
+ case 'brc185:connect':
134
+ return hasExactKeys(o, ['type', 'version', 'instanceId', 'continuityKey', 'epoch', 'challenge']) &&
135
+ routing('epoch') &&
136
+ typeof o.instanceId === 'string' &&
137
+ typeof o.continuityKey === 'string' &&
138
+ typeof o.challenge === 'string'
139
+ ? (o as unknown as XdmConnect)
140
+ : undefined
141
+ case 'brc185:connected':
142
+ return hasExactKeys(o, ['type', 'version', 'proof']) ? (o as unknown as XdmConnected) : undefined
143
+ case 'brc185:connection-error':
144
+ return hasExactKeys(o, ['type', 'version', 'epoch', 'error']) && routing('epoch')
145
+ ? (o as unknown as XdmConnectionError)
146
+ : undefined
147
+ case 'brc185:invoke':
148
+ return hasExactKeys(o, ['type', 'version', 'instanceId', 'epoch', 'id', 'method', 'params']) &&
149
+ routing('epoch', 'id') &&
150
+ typeof o.instanceId === 'string' &&
151
+ typeof o.method === 'string'
152
+ ? (o as unknown as XdmInvoke)
153
+ : undefined
154
+ case 'brc185:result':
155
+ return hasExactKeys(o, ['type', 'version', 'instanceId', 'epoch', 'id', 'result']) &&
156
+ routing('epoch', 'id') &&
157
+ typeof o.instanceId === 'string'
158
+ ? (o as unknown as XdmResult)
159
+ : undefined
160
+ case 'brc185:error':
161
+ return hasExactKeys(o, ['type', 'version', 'instanceId', 'epoch', 'id', 'error']) &&
162
+ routing('epoch', 'id') &&
163
+ typeof o.instanceId === 'string' &&
164
+ typeof o.error === 'object' &&
165
+ o.error !== null
166
+ ? (o as unknown as XdmError)
167
+ : undefined
168
+ case 'brc185:closed':
169
+ return hasExactKeys(o, ['type', 'version', 'instanceId', 'epoch', 'reason']) &&
170
+ routing('epoch') &&
171
+ typeof o.instanceId === 'string' &&
172
+ isCloseReason(o.reason)
173
+ ? (o as unknown as XdmClosed)
174
+ : undefined
175
+ default:
176
+ return undefined
177
+ }
178
+ }
179
+
180
+ export function xdmResult(instanceId: string, epoch: string, id: string, result: unknown): XdmResult {
181
+ return { type: 'brc185:result', version: 1, instanceId, epoch, id, result }
182
+ }
183
+ export function xdmError(instanceId: string, epoch: string, id: string, error: WireError | ConnectionError): XdmError {
184
+ return { type: 'brc185:error', version: 1, instanceId, epoch, id, error }
185
+ }
186
+ export function xdmClosed(instanceId: string, epoch: string, reason: CloseReason): XdmClosed {
187
+ return { type: 'brc185:closed', version: 1, instanceId, epoch, reason }
188
+ }
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Wallet error <-> BRC-100 wire error (spec 6.11). Pure TS, usable page-side and wallet-side.
3
+ *
4
+ * Mapping is by `instanceof` for SDK classes, by numeric `code`, by toolbox `name`, and by string
5
+ * `code` for HMAC/signature failures. It never goes by the truthiness of `code`: toolbox errors
6
+ * expose `code` as a string getter that returns the `WERR_*` name.
7
+ */
8
+ import { WERR_INSUFFICIENT_FUNDS, WERR_INVALID_PARAMETER, WERR_REVIEW_ACTIONS } from '@bsv/sdk'
9
+ import { isConnectionError, truncateUtf8 } from './connectionError'
10
+
11
+ export const MAX_ERROR_MESSAGE_BYTES = 4096
12
+
13
+ export interface WireError {
14
+ isError: true
15
+ code: number
16
+ name: string
17
+ message: string
18
+ data: { originalName?: string; originalCode?: number | string }
19
+ [field: string]: unknown
20
+ }
21
+
22
+ type Loose = Record<string, unknown>
23
+
24
+ const PARAM_NAMES = new Set(['WERR_INVALID_PARAMETER', 'VaultAccessDenied', 'WalletArgTooLarge'])
25
+ const WIRE_NAME: Record<number, string> = {
26
+ 1: 'WERR_UNKNOWN',
27
+ 3: 'ERR_INVALID_HMAC',
28
+ 4: 'ERR_INVALID_SIGNATURE',
29
+ 5: 'WERR_REVIEW_ACTIONS',
30
+ 6: 'WERR_INVALID_PARAMETER',
31
+ 7: 'WERR_INSUFFICIENT_FUNDS'
32
+ }
33
+
34
+ function str(v: unknown): string | undefined {
35
+ return typeof v === 'string' ? v : undefined
36
+ }
37
+ function num(v: unknown): number {
38
+ return typeof v === 'number' && Number.isFinite(v) ? v : 0
39
+ }
40
+ function arr(v: unknown): unknown[] {
41
+ return Array.isArray(v) ? v : []
42
+ }
43
+
44
+ export function encodeWalletError(e: unknown): WireError {
45
+ const o: Loose = typeof e === 'object' && e !== null ? (e as Loose) : {}
46
+ const originalName = str(o.name)
47
+ const rawCode = o.code
48
+ const message = truncateUtf8(
49
+ str(o.message) ?? (typeof e === 'string' ? e : 'Wallet call failed'),
50
+ MAX_ERROR_MESSAGE_BYTES
51
+ )
52
+ const data: WireError['data'] = {}
53
+ if (originalName !== undefined) data.originalName = originalName
54
+ if (typeof rawCode === 'number' || typeof rawCode === 'string') data.originalCode = rawCode
55
+
56
+ const wire = (code: number, fields: Loose = {}): WireError => ({
57
+ ...fields,
58
+ isError: true,
59
+ code,
60
+ name: WIRE_NAME[code],
61
+ message,
62
+ data
63
+ })
64
+
65
+ if (e instanceof WERR_REVIEW_ACTIONS || originalName === 'WERR_REVIEW_ACTIONS' || rawCode === 5) {
66
+ const f: Loose = { reviewActionResults: arr(o.reviewActionResults), sendWithResults: arr(o.sendWithResults) }
67
+ if (str(o.txid) !== undefined) f.txid = o.txid
68
+ if (o.tx instanceof Uint8Array) f.tx = Array.from(o.tx)
69
+ else if (Array.isArray(o.tx)) f.tx = o.tx
70
+ if (Array.isArray(o.noSendChange)) f.noSendChange = o.noSendChange
71
+ return wire(5, f)
72
+ }
73
+ if (
74
+ e instanceof WERR_INVALID_PARAMETER ||
75
+ (originalName !== undefined && PARAM_NAMES.has(originalName)) ||
76
+ rawCode === 6
77
+ ) {
78
+ // SDK clients require `parameter`; errors that carry only `field` (or nothing) get one.
79
+ return wire(6, { parameter: str(o.parameter) || str(o.field) || 'request' })
80
+ }
81
+ if (e instanceof WERR_INSUFFICIENT_FUNDS || originalName === 'WERR_INSUFFICIENT_FUNDS' || rawCode === 7) {
82
+ return wire(7, { totalSatoshisNeeded: num(o.totalSatoshisNeeded), moreSatoshisNeeded: num(o.moreSatoshisNeeded) })
83
+ }
84
+ if (rawCode === 'ERR_INVALID_HMAC') return wire(3)
85
+ if (rawCode === 'ERR_INVALID_SIGNATURE') return wire(4)
86
+ // WERR_INVALID_MERKLE_ROOT, user denial and everything else: 1, message only, never a stack.
87
+ return wire(1)
88
+ }
89
+
90
+ function plain(w: Loose, message: string, code: number | string): Error {
91
+ const e = new Error(message) as Error & Loose
92
+ const name = str(w.name)
93
+ e.name = name !== undefined && name.length > 0 && name.length <= 100 ? name : 'Error'
94
+ e.isError = true
95
+ e.code = code
96
+ return e
97
+ }
98
+
99
+ /** Rebuild an `Error` from a wire error or a ConnectionError, with the SDK's bounds on fields. */
100
+ export function decodeWireError(w: unknown): Error {
101
+ if (typeof w !== 'object' || w === null)
102
+ return plain({}, typeof w === 'string' ? truncateUtf8(w, MAX_ERROR_MESSAGE_BYTES) : 'Wallet call failed', 1)
103
+ const o = w as Loose
104
+ if (isConnectionError(o)) {
105
+ const e = new Error(o.message) as Error & Loose
106
+ e.name = 'ConnectionError'
107
+ e.domain = o.domain
108
+ e.code = o.code
109
+ e.delivery = o.delivery
110
+ if (o.epoch !== undefined) e.epoch = o.epoch
111
+ if (o.cause !== undefined) e.cause = o.cause
112
+ return e
113
+ }
114
+ const message = truncateUtf8(str(o.message) ?? 'Wallet call failed', MAX_ERROR_MESSAGE_BYTES)
115
+ switch (o.code) {
116
+ case 5: {
117
+ const { reviewActionResults: r, sendWithResults: s, txid, tx, noSendChange: n } = o
118
+ const okTx = tx === undefined || (Array.isArray(tx) && tx.every(b => Number.isInteger(b) && b >= 0 && b <= 255))
119
+ const okN = n === undefined || (Array.isArray(n) && n.every(x => typeof x === 'string'))
120
+ if (Array.isArray(r) && Array.isArray(s) && (txid === undefined || typeof txid === 'string') && okTx && okN) {
121
+ const e = new WERR_REVIEW_ACTIONS(
122
+ r as never,
123
+ s as never,
124
+ txid as string | undefined,
125
+ tx as number[] | undefined,
126
+ n as string[] | undefined
127
+ )
128
+ e.message = message
129
+ return e
130
+ }
131
+ break
132
+ }
133
+ case 6: {
134
+ const p = o.parameter
135
+ if (typeof p === 'string' && p.length > 0 && p.length <= 250) {
136
+ const e = new WERR_INVALID_PARAMETER(p)
137
+ e.message = message
138
+ return e
139
+ }
140
+ break
141
+ }
142
+ case 7: {
143
+ const { totalSatoshisNeeded: t, moreSatoshisNeeded: m } = o
144
+ if (
145
+ typeof t === 'number' &&
146
+ typeof m === 'number' &&
147
+ Number.isFinite(t) &&
148
+ Number.isFinite(m) &&
149
+ t >= 0 &&
150
+ m >= 0
151
+ ) {
152
+ const e = new WERR_INSUFFICIENT_FUNDS(t, m)
153
+ e.message = message
154
+ return e
155
+ }
156
+ break
157
+ }
158
+ case 3:
159
+ return plain(o, message, 'ERR_INVALID_HMAC')
160
+ case 4:
161
+ return plain(o, message, 'ERR_INVALID_SIGNATURE')
162
+ }
163
+ return plain(o, message, typeof o.code === 'number' && Number.isInteger(o.code) ? o.code : 1)
164
+ }
@@ -0,0 +1,237 @@
1
+ /**
2
+ * Strict JSON parsing and RFC 8785 (JCS) canonicalisation for BRC-185.
3
+ *
4
+ * `JSON.parse` silently keeps the last of two equal keys and accepts lone surrogates, either of which
5
+ * lets two parties read the same bytes differently. The wire profile refuses both, plus non-finite
6
+ * numbers, so a signed preimage has one meaning.
7
+ */
8
+
9
+ export class StrictJsonError extends Error {
10
+ constructor(message: string) {
11
+ super(message)
12
+ this.name = 'StrictJsonError'
13
+ }
14
+ }
15
+
16
+ const MAX_DEPTH = 64
17
+
18
+ function isHigh(c: number): boolean {
19
+ return c >= 0xd800 && c <= 0xdbff
20
+ }
21
+ function isLow(c: number): boolean {
22
+ return c >= 0xdc00 && c <= 0xdfff
23
+ }
24
+
25
+ /** True when `s` contains an unpaired surrogate code unit. */
26
+ export function hasLoneSurrogate(s: string): boolean {
27
+ for (let i = 0; i < s.length; i++) {
28
+ const c = s.charCodeAt(i)
29
+ if (isHigh(c)) {
30
+ if (i + 1 < s.length && isLow(s.charCodeAt(i + 1))) i++
31
+ else return true
32
+ } else if (isLow(c)) {
33
+ return true
34
+ }
35
+ }
36
+ return false
37
+ }
38
+
39
+ function setOwn(obj: Record<string, unknown>, key: string, value: unknown): void {
40
+ // defineProperty so a "__proto__" key is data, never a prototype write.
41
+ Object.defineProperty(obj, key, { value, enumerable: true, writable: true, configurable: true })
42
+ }
43
+
44
+ class Parser {
45
+ private i = 0
46
+ constructor(private readonly s: string) {}
47
+
48
+ parse(): unknown {
49
+ this.ws()
50
+ const v = this.value(0)
51
+ this.ws()
52
+ if (this.i !== this.s.length) this.fail('unexpected trailing content')
53
+ return v
54
+ }
55
+
56
+ private fail(msg: string): never {
57
+ throw new StrictJsonError(`${msg} at offset ${this.i}`)
58
+ }
59
+
60
+ private ws(): void {
61
+ while (this.i < this.s.length) {
62
+ const c = this.s[this.i]
63
+ if (c === ' ' || c === '\t' || c === '\n' || c === '\r') this.i++
64
+ else break
65
+ }
66
+ }
67
+
68
+ private value(depth: number): unknown {
69
+ if (depth > MAX_DEPTH) this.fail('nesting too deep')
70
+ const c = this.s[this.i]
71
+ if (c === '{') return this.object(depth)
72
+ if (c === '[') return this.array(depth)
73
+ if (c === '"') return this.string()
74
+ if (c === 't') return this.literal('true', true)
75
+ if (c === 'f') return this.literal('false', false)
76
+ if (c === 'n') return this.literal('null', null)
77
+ if (c === '-' || (c >= '0' && c <= '9')) return this.number()
78
+ return this.fail('unexpected character')
79
+ }
80
+
81
+ private literal<T>(word: string, value: T): T {
82
+ if (this.s.startsWith(word, this.i)) {
83
+ this.i += word.length
84
+ return value
85
+ }
86
+ return this.fail('invalid literal')
87
+ }
88
+
89
+ private number(): number {
90
+ const m = /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/.exec(this.s.slice(this.i, this.i + 400))
91
+ if (!m) this.fail('invalid number')
92
+ const n = Number(m[0])
93
+ if (!Number.isFinite(n)) this.fail('non-finite number')
94
+ this.i += m[0].length
95
+ return n
96
+ }
97
+
98
+ private string(): string {
99
+ this.i++ // opening quote
100
+ let out = ''
101
+ for (;;) {
102
+ if (this.i >= this.s.length) this.fail('unterminated string')
103
+ const c = this.s[this.i]
104
+ const code = c.charCodeAt(0)
105
+ if (c === '"') {
106
+ this.i++
107
+ break
108
+ }
109
+ if (code < 0x20) this.fail('control character in string')
110
+ if (c === '\\') {
111
+ const e = this.s[this.i + 1]
112
+ this.i += 2
113
+ switch (e) {
114
+ case '"':
115
+ case '\\':
116
+ case '/':
117
+ out += e
118
+ break
119
+ case 'b':
120
+ out += '\b'
121
+ break
122
+ case 'f':
123
+ out += '\f'
124
+ break
125
+ case 'n':
126
+ out += '\n'
127
+ break
128
+ case 'r':
129
+ out += '\r'
130
+ break
131
+ case 't':
132
+ out += '\t'
133
+ break
134
+ case 'u': {
135
+ const hex = this.s.slice(this.i, this.i + 4)
136
+ if (!/^[0-9a-fA-F]{4}$/.test(hex)) this.fail('invalid unicode escape')
137
+ out += String.fromCharCode(parseInt(hex, 16))
138
+ this.i += 4
139
+ break
140
+ }
141
+ default:
142
+ this.fail('invalid escape')
143
+ }
144
+ } else {
145
+ out += c
146
+ this.i++
147
+ }
148
+ }
149
+ if (hasLoneSurrogate(out)) this.fail('lone surrogate in string')
150
+ return out
151
+ }
152
+
153
+ private array(depth: number): unknown[] {
154
+ this.i++
155
+ const out: unknown[] = []
156
+ this.ws()
157
+ if (this.s[this.i] === ']') {
158
+ this.i++
159
+ return out
160
+ }
161
+ for (;;) {
162
+ this.ws()
163
+ out.push(this.value(depth + 1))
164
+ this.ws()
165
+ const c = this.s[this.i++]
166
+ if (c === ',') continue
167
+ if (c === ']') return out
168
+ this.i--
169
+ this.fail('expected , or ]')
170
+ }
171
+ }
172
+
173
+ private object(depth: number): Record<string, unknown> {
174
+ this.i++
175
+ const out: Record<string, unknown> = {}
176
+ const seen = new Set<string>()
177
+ this.ws()
178
+ if (this.s[this.i] === '}') {
179
+ this.i++
180
+ return out
181
+ }
182
+ for (;;) {
183
+ this.ws()
184
+ if (this.s[this.i] !== '"') this.fail('expected string key')
185
+ const key = this.string()
186
+ if (seen.has(key)) this.fail(`duplicate key "${key}"`)
187
+ seen.add(key)
188
+ this.ws()
189
+ if (this.s[this.i++] !== ':') {
190
+ this.i--
191
+ this.fail('expected :')
192
+ }
193
+ this.ws()
194
+ setOwn(out, key, this.value(depth + 1))
195
+ this.ws()
196
+ const c = this.s[this.i++]
197
+ if (c === ',') continue
198
+ if (c === '}') return out
199
+ this.i--
200
+ this.fail('expected , or }')
201
+ }
202
+ }
203
+ }
204
+
205
+ /** Parse JSON text, throwing {@link StrictJsonError} on duplicate keys, lone surrogates or non-finite numbers. */
206
+ export function parseStrictJson(text: string): unknown {
207
+ if (typeof text !== 'string') throw new StrictJsonError('JSON input must be a string')
208
+ if (hasLoneSurrogate(text)) throw new StrictJsonError('lone surrogate in input')
209
+ return new Parser(text).parse()
210
+ }
211
+
212
+ /**
213
+ * RFC 8785 JSON Canonicalization Scheme. Keys sort by UTF-16 code units, numbers use the ECMAScript
214
+ * shortest form (which JCS adopts), strings use the minimal JSON escapes. Values JSON cannot carry
215
+ * (undefined, functions, bigint, NaN, lone surrogates) throw rather than being dropped.
216
+ */
217
+ export function canonicalize(value: unknown): string {
218
+ if (value === null) return 'null'
219
+ switch (typeof value) {
220
+ case 'boolean':
221
+ return value ? 'true' : 'false'
222
+ case 'number':
223
+ if (!Number.isFinite(value)) throw new StrictJsonError('cannot canonicalize a non-finite number')
224
+ return JSON.stringify(value)
225
+ case 'string':
226
+ if (hasLoneSurrogate(value)) throw new StrictJsonError('cannot canonicalize a lone surrogate')
227
+ return JSON.stringify(value)
228
+ case 'object': {
229
+ if (Array.isArray(value)) return `[${value.map(canonicalize).join(',')}]`
230
+ const rec = value as Record<string, unknown>
231
+ const keys = Object.keys(rec).sort()
232
+ return `{${keys.map(k => `${canonicalize(k)}:${canonicalize(rec[k])}`).join(',')}}`
233
+ }
234
+ default:
235
+ throw new StrictJsonError(`cannot canonicalize a ${typeof value}`)
236
+ }
237
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Bridge limits (spec 6.6, 6.7, 6.8, 6.4). Pure constants so every layer, and the
3
+ * Safari extension bundle, agrees on one set of numbers.
4
+ */
5
+
6
+ /** Largest single bridge request body. */
7
+ export const MAX_BRIDGE_REQUEST_BYTES = 5 * 1024 * 1024
8
+ /** Concurrent requests per binding. */
9
+ export const MAX_IN_FLIGHT_PER_BINDING = 4
10
+ /** Concurrent requests across all bindings. */
11
+ export const MAX_IN_FLIGHT_TOTAL = 16
12
+ /** Request bytes in flight across all bindings. */
13
+ export const MAX_IN_FLIGHT_BYTES = 5 * 1024 * 1024
14
+
15
+ /** Live bindings per origin. */
16
+ export const MAX_BINDINGS_PER_ORIGIN = 8
17
+ /** Live bindings overall. */
18
+ export const MAX_BINDINGS_TOTAL = 64
19
+ /** Tombstone ring capacity and age. */
20
+ export const TOMBSTONE_RING_SIZE = 1024
21
+ export const TOMBSTONE_TTL_MS = 24 * 60 * 60 * 1000
22
+
23
+ /** Durable inbox: longest `notAfter - createdAt`, accepted clock skew, result retention. */
24
+ export const INBOX_MAX_VALIDITY_MS = 15 * 60 * 1000
25
+ export const INBOX_CLOCK_SKEW_MS = 5 * 60 * 1000
26
+ export const INBOX_RESULT_TTL_MS = 15 * 60 * 1000
27
+
28
+ /** After a decline the same site is not asked again for this long. */
29
+ export const DECLINE_BACKOFF_MS = 30 * 1000
30
+ /** Taps on an approval control are ignored for this long after it appears. */
31
+ export const TAP_PROTECTION_MS = 700
32
+
33
+ /** Grant tag: `g` followed by this many lowercase base32 characters. */
34
+ export const GRANT_TAG_PREFIX = 'g'
35
+ export const GRANT_TAG_RANDOM_CHARS = 10
36
+
37
+ /** Reconnect token: random bytes, sent as base64url, stored as a SHA-256 hash. */
38
+ export const RECONNECT_TOKEN_BYTES = 32
39
+
40
+ /** BRC-185 section 3: describe and connect responses are bounded. */
41
+ export const MAX_PROOF_RESPONSE_BYTES = 16384
42
+ /** BRC-185 section 3: challenge is 32 random bytes. */
43
+ export const CHALLENGE_BYTES = 32
@@ -0,0 +1,55 @@
1
+ /**
2
+ * The 28 BRC-100 methods the bridge carries, with the two properties the dispatcher needs
3
+ * (spec 6.6): whether the call changes wallet state (so backup is nudged on every outcome) and
4
+ * whether it is a probe (answered without consent, a wallet call or a wait).
5
+ *
6
+ * Typed against the SDK's `WalletInterface`, so adding a method there fails type-checking until
7
+ * it is classified here.
8
+ */
9
+ import type { WalletInterface } from '@bsv/sdk'
10
+
11
+ export type WalletMethodName = keyof WalletInterface
12
+
13
+ export interface BridgeMethodInfo {
14
+ mutating: boolean
15
+ probe: boolean
16
+ }
17
+
18
+ const read: BridgeMethodInfo = Object.freeze({ mutating: false, probe: false })
19
+ const write: BridgeMethodInfo = Object.freeze({ mutating: true, probe: false })
20
+ const probe: BridgeMethodInfo = Object.freeze({ mutating: false, probe: true })
21
+
22
+ export const BRIDGE_METHODS: Readonly<Record<WalletMethodName, BridgeMethodInfo>> = Object.freeze({
23
+ getPublicKey: read,
24
+ revealCounterpartyKeyLinkage: read,
25
+ revealSpecificKeyLinkage: read,
26
+ encrypt: read,
27
+ decrypt: read,
28
+ createHmac: read,
29
+ verifyHmac: read,
30
+ createSignature: read,
31
+ verifySignature: read,
32
+ createAction: write,
33
+ signAction: write,
34
+ abortAction: write,
35
+ listActions: read,
36
+ internalizeAction: write,
37
+ listOutputs: read,
38
+ relinquishOutput: write,
39
+ acquireCertificate: write,
40
+ listCertificates: read,
41
+ proveCertificate: read,
42
+ relinquishCertificate: write,
43
+ discoverByIdentityKey: read,
44
+ discoverByAttributes: read,
45
+ isAuthenticated: probe,
46
+ waitForAuthentication: read,
47
+ getHeight: read,
48
+ getHeaderForHeight: read,
49
+ getNetwork: read,
50
+ getVersion: probe
51
+ })
52
+
53
+ export function isBridgeMethod(name: unknown): name is WalletMethodName {
54
+ return typeof name === 'string' && Object.prototype.hasOwnProperty.call(BRIDGE_METHODS, name)
55
+ }