@bsv/expo-wallet-toolbox 0.13.0 → 0.15.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/CHANGELOG.md CHANGED
@@ -1,5 +1,76 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.15.0
4
+
5
+ ### Changed
6
+
7
+ - **Breaking: Mandala token keys derive under `[2, 'p mandala token']`.**
8
+ Requires `@bsv/mandala` 0.4.0, which renamed `FT_PROTOCOL` from
9
+ `[2, 'mandala token']`. Every token key derivation changes; tokens held
10
+ under the old protocol are not migrated.
11
+ - **Mandala token keys are gated by the `mandala` permission module, not the
12
+ vault guard.** The `'p '` prefix makes `WalletPermissionsManager` route
13
+ every call under the token protocol to `MandalaTokenModule`, the way
14
+ `[0, 'p btms']` reaches the BTMS module. The vault guard no longer reserves
15
+ the namespace, so a connected app (such as the Mandala console) can issue
16
+ tokens and send to itself. For a connected app:
17
+ - `getPublicKey` and `verifySignature` pass through, for any counterparty.
18
+ - `createSignature` passes without a prompt when it signs the BIP-143
19
+ sighash of an input of a transaction the user approved through the
20
+ module's `createAction` prompt within the last 60 seconds. Any other
21
+ signature gets its own `mandala_signature` prompt, and approving it does
22
+ not cover later signatures.
23
+ - `encrypt`, `decrypt`, `createHmac` and `verifyHmac` are refused.
24
+ - `revealSpecificKeyLinkage` is no longer refused and is not prompted.
25
+ - Privileged calls are still refused.
26
+
27
+ ## 0.14.0
28
+
29
+ ### Fixed
30
+
31
+ - **External apps can sign under BRC-29 again.** The vault guard refused every
32
+ external `createSignature`, `encrypt`, `decrypt`, `createHmac`,
33
+ `verifyHmac`, `verifySignature` and key-linkage call under
34
+ `[2, '3241645161d8']` (XR-020), so payment apps that sign BRC-29 outputs
35
+ did not work. The namespace is no longer reserved. Because it also derives
36
+ this wallet's own address-rail keys, `seekProtocolPermissionsForSigning` is
37
+ now `true`: a connected app is asked before it first signs under a
38
+ security level 1 or 2 protocol (level 2 per counterparty), BRC-29
39
+ included. This differs from Metanet Desktop, which does not ask.
40
+ `[2, 'mandala token']` stays reserved, and privileged calls are still
41
+ refused. So are the address rail's own key IDs: a BRC-29 call from a
42
+ connected origin whose key ID is `base64(YYYY-MM-DD) + ' ' +
43
+ base64('legacy')` is refused for every key-using method and counterparty
44
+ (`isAddressRailKeyID`, exported from the vault guard).
45
+ - **BRC-29 signing asks every time.** An approval under `3241645161d8` is
46
+ never reused: each signature gets its own prompt, and one app's concurrent
47
+ calls are asked one at a time so a single tap cannot approve a batch. Each
48
+ approval is still recorded as a permission token, tagged
49
+ `keyid <hex of the key ID>` (or `keyidhash <sha256>` when too long), as a
50
+ history of what was approved; BRC-29 tokens, cache entries and the
51
+ recent-grant cover are never read back. BRC-29 entries in a site's
52
+ manifest `groupPermissions`/`counterpartyPermissions` are ignored, so the
53
+ grouped sheet never offers them and is not raised again before each
54
+ signature. A grant is keyed by origin, protocol and counterparty, never key
55
+ ID, so a reused one would cover the wallet's BSV address receipts and
56
+ change too. Each recorded approval is a 1-satoshi token output plus its
57
+ transaction fee.
58
+ - Signing under `[2, 'auth message signature']` (BRC-103 mutual auth and its
59
+ BRC-104 HTTP transport) is exempt from the prompt, so authenticated
60
+ requests never ask. Both rules live in `SigningPolicyPermissionsManager`
61
+ (`core/services/signingPermissionPolicy.ts`).
62
+ - A non-privileged `verifySignature` is never prompted: it reveals nothing
63
+ and spends nothing.
64
+ - The permission sheet no longer shows BRC-29 as `3241645161d8`. Its prompt
65
+ is titled "Payment Key Signature", says coins paid to the key (or the
66
+ wallet's change, for counterparty self) could be spent with the signature,
67
+ and its details name the protocol "Payments (BRC-29)" and show the key ID,
68
+ decoded from base64 when it is readable text. Other protocols are
69
+ unchanged.
70
+ - `getPublicKey`, `encrypt`, `decrypt`, HMAC and key-linkage calls under
71
+ BRC-29 with an app's key ID are not prompted (their `seek*` flags stay
72
+ off).
73
+
3
74
  ## 0.13.0
4
75
 
5
76
  ### Breaking
@@ -16,6 +16,7 @@ import {
16
16
  import { KeyDeriver, PrivateKey, MerklePath, Transaction, Utils } from '@bsv/sdk'
17
17
  import { DEFAULT_SETTINGS } from './defaultWalletSettings'
18
18
  import { conformWalletResults } from '../services/conformWalletResults'
19
+ import { SigningPolicyPermissionsManager } from '../services/signingPermissionPolicy'
19
20
  import { VAULT_RETENTION_MS, ceremony as vaultCeremony } from '../services/vault/ceremonyHost'
20
21
  import { getVaultDriver } from '../services/vault/driver'
21
22
  import { backupAttestation } from '../services/vault/backupAttestation'
@@ -693,6 +694,9 @@ type ProtocolAccessRequest = {
693
694
  protocolSecurityLevel: number
694
695
  protocolID: string
695
696
  counterparty?: string
697
+ /** The key ID a BRC-29 signature asks for (SigningPolicyPermissionsManager
698
+ * attaches it; the stock manager's requests carry none). */
699
+ keyID?: string
696
700
  originator?: string
697
701
  description?: string
698
702
  renewal?: boolean
@@ -1184,6 +1188,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1184
1188
  const protocolPermissionCallback = useCallback(
1185
1189
  (args: PermissionRequest & { requestID: string }): Promise<void> => {
1186
1190
  const { requestID, counterparty, originator, reason, renewal, protocolID } = args
1191
+ const keyID = (args as { keyID?: unknown }).keyID
1187
1192
  if (!requestID || !protocolID) return Promise.resolve()
1188
1193
 
1189
1194
  const [protocolSecurityLevel, protocolNameString] = protocolID
@@ -1198,6 +1203,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1198
1203
  protocolSecurityLevel,
1199
1204
  protocolID: protocolNameString,
1200
1205
  counterparty,
1206
+ keyID: typeof keyID === 'string' ? keyID : undefined,
1201
1207
  originator,
1202
1208
  description: reason,
1203
1209
  renewal,
@@ -1925,7 +1931,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1925
1931
  })
1926
1932
 
1927
1933
  // Setup permissions with provided callbacks and BTMS module.
1928
- const permissionsManager = new WalletPermissionsManager(wallet, adminOriginator, {
1934
+ const permissionsManager = new SigningPolicyPermissionsManager(wallet, adminOriginator, {
1929
1935
  differentiatePrivilegedOperations: true,
1930
1936
  seekBasketInsertionPermissions: false,
1931
1937
  seekBasketListingPermissions: false,
@@ -1947,7 +1953,13 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1947
1953
  seekPermissionWhenListingActionsByLabel: false,
1948
1954
  seekProtocolPermissionsForEncrypting: false,
1949
1955
  seekProtocolPermissionsForHMAC: false,
1950
- seekProtocolPermissionsForSigning: false,
1956
+ // On, unlike Metanet Desktop: the vault guard no longer refuses
1957
+ // external BRC-29 ([2,'3241645161d8']) signing outright, and that
1958
+ // namespace also derives this wallet's own address-rail keys
1959
+ // (counterparty 'anyone'), so a site signing under it must be
1960
+ // asked first -- for BRC-29, on every signature. BRC-103/104 auth
1961
+ // signing is exempt (SigningPolicyPermissionsManager).
1962
+ seekProtocolPermissionsForSigning: true,
1951
1963
  seekSpendingPermissions: true,
1952
1964
  permissionModules: { btms: btmsModule, mandala: mandalaModule }
1953
1965
  } as any)
@@ -17,7 +17,7 @@ const DEMO_OVERLAY_KEY = '02' + 'de'.repeat(32)
17
17
  const DEMO_OVERLAY_URL = 'https://overlay.demo.invalid'
18
18
 
19
19
  export const DEMO_USD: TokenAssetInfo = {
20
- assetId: 'd0'.repeat(32) + '.0',
20
+ assetId: 'd0'.repeat(32) + '_0',
21
21
  label: 'Acme Dollar',
22
22
  ticker: 'USDX',
23
23
  decimals: 2,
@@ -27,7 +27,7 @@ export const DEMO_USD: TokenAssetInfo = {
27
27
  }
28
28
 
29
29
  export const DEMO_CHF: TokenAssetInfo = {
30
- assetId: 'cf'.repeat(32) + '.0',
30
+ assetId: 'cf'.repeat(32) + '_0',
31
31
  label: 'Helvetia Franc',
32
32
  ticker: 'CHFX',
33
33
  decimals: 2,
@@ -9,7 +9,7 @@ import {
9
9
  UnlockingScript,
10
10
  Utils
11
11
  } from '@bsv/sdk'
12
- import { MandalaToken } from '@bsv/templates'
12
+ import { MandalaToken } from '../mandala/token'
13
13
  import { FRAME_VERSION, type PaymentFrame } from './codec'
14
14
  import { isRequestableAmount, type Session } from './session'
15
15
  import { PEERPAY_LABEL, PEERPAY_PROTOCOL_ID } from './pending'
@@ -503,7 +503,7 @@ const SETTLEMENT_PREWRITE_FAILURE = 'could not record the settlement row before
503
503
  * derivation field to undefined, and this is the only slot that survives to
504
504
  * the day the coin is spent.
505
505
  */
506
- const FT_PROTOCOL_ID: [number, string] = [2, 'mandala token']
506
+ const FT_PROTOCOL_ID: [number, string] = [2, 'p mandala token']
507
507
 
508
508
  /** What `internalizeAction` is told about one frame's output. */
509
509
  function internalizeOutput(frame: PaymentFrame): Record<string, unknown> {
@@ -252,7 +252,7 @@ export function decodeSession(text: string): Session {
252
252
  if (t !== undefined) {
253
253
  if (typeof t !== 'object' || t === null) throw new CodecError('bad asset block')
254
254
  const { i: ai, n, s: tick, d, u, k: ok } = t as Record<string, unknown>
255
- if (typeof ai !== 'string' || !/^[0-9a-f]{64}\.\d+$/.test(ai)) throw new CodecError('bad assetId')
255
+ if (typeof ai !== 'string' || !/^[0-9a-f]{64}_0$/.test(ai)) throw new CodecError('bad assetId')
256
256
  if (typeof u !== 'string' || u.length === 0) throw new CodecError('bad overlayUrl')
257
257
  if (typeof ok !== 'string' || ok.length !== 66) throw new CodecError('bad overlayIdentityKey')
258
258
  if (n !== undefined && typeof n !== 'string') throw new CodecError('bad asset label')
@@ -37,7 +37,7 @@ export interface SettlementAck {
37
37
  txid: string
38
38
  /** Sorted ascending, exactly as the overlay signed them. */
39
39
  outputsToAdmit: number[]
40
- /** σ_I over `admissionDigestV2(txid, outputsToAdmit)`, DER hex. */
40
+ /** σ_I over `admissionDigestV3(topic, txid, outputsToAdmit)`, DER hex. */
41
41
  admissionSignature: string
42
42
  }
43
43
 
@@ -1,6 +1,6 @@
1
1
  import { Hash, P2PKH, PublicKey, Transaction, Utils } from '@bsv/sdk'
2
2
  import type { ChainTracker } from '@bsv/sdk'
3
- import { MandalaToken } from '@bsv/templates'
3
+ import { MandalaToken } from '../mandala/token'
4
4
  import type { PaymentFrame } from './codec'
5
5
  import { coverFromFrame, type CoverVerifier } from '../mandala/bundle'
6
6
  import { PEERPAY_PROTOCOL_ID } from './pending'
@@ -9,7 +9,7 @@ import type { DeclineReason } from './types'
9
9
 
10
10
  // mandala's FT derivation protocol — the payer locks token outputs under it
11
11
  // with OUR payee-minted nonces as keyID, preserving the frame-to-session binding
12
- export const FT_PROTOCOL_ID: [2, string] = [2, 'mandala token']
12
+ export const FT_PROTOCOL_ID: [2, string] = [2, 'p mandala token']
13
13
 
14
14
  export type VerifiedPayment =
15
15
  | { kind: 'bsv'; satoshis: number }
@@ -29,7 +29,7 @@
29
29
  * becomes a one-line import and nothing else here changes.
30
30
  */
31
31
  import { Beef, Transaction } from '@bsv/sdk'
32
- import { MandalaToken } from '@bsv/templates'
32
+ import { MandalaToken } from './token'
33
33
  import type { PaymentFrame } from '../localpay/codec'
34
34
  import type { AdmissionEntryWire, CoverResult, SettlementStore } from './types'
35
35
 
@@ -22,13 +22,15 @@
22
22
  * with the bytes and the evidence the local tables hold.
23
23
  */
24
24
  import { Beef, Transaction, Utils, type WalletInterface } from '@bsv/sdk'
25
- import { MandalaToken } from '@bsv/templates'
25
+ import { MandalaToken } from './token'
26
26
  import {
27
27
  blindingCommit,
28
28
  blindingGet,
29
29
  blindingPruneReserved,
30
30
  blindingReserve,
31
31
  cover as coverWalk,
32
+ decodeToken,
33
+ decodeValue,
32
34
  createOverlayFacilitator,
33
35
  fetchAdmission as libFetchAdmission,
34
36
  fetchRegistry,
@@ -45,6 +47,7 @@ import {
45
47
  registryIsLive,
46
48
  resolveAssetMetadata,
47
49
  submitToOverlay,
50
+ tokenTopic,
48
51
  transferTokens,
49
52
  verifyAdmission as libVerifyAdmission,
50
53
  verifyFetchedAdmission,
@@ -718,19 +721,18 @@ export function createMandalaRuntime(args: CreateMandalaRuntimeArgs): MandalaRun
718
721
  const vout = Number(voutText)
719
722
  const script = beef.findTxid(txid)?.tx?.outputs[vout]?.lockingScript
720
723
  if (!script) continue
721
- try {
722
- const decoded = MandalaToken.decode(script)
723
- out.push({
724
- outpoint: output.outpoint,
725
- txid,
726
- vout,
727
- assetId: decoded.assetId,
728
- amount: decoded.amount,
729
- spendable: output.spendable !== false
730
- })
731
- } catch {
732
- // A stray non-token output in the basket is not this asset's coin.
733
- }
724
+ // BRC-162: only value-role outputs are coins; a stray non-token (or
725
+ // deploy/authority) output in the basket is not this asset's coin.
726
+ const decoded = decodeValue(script)
727
+ if (decoded == null) continue
728
+ out.push({
729
+ outpoint: output.outpoint,
730
+ txid,
731
+ vout,
732
+ assetId: decoded.tokenId,
733
+ amount: decoded.amount,
734
+ spendable: output.spendable !== false
735
+ })
734
736
  }
735
737
  return out
736
738
  }
@@ -847,12 +849,48 @@ export function createMandalaRuntime(args: CreateMandalaRuntimeArgs): MandalaRun
847
849
  )
848
850
  )
849
851
 
852
+ /**
853
+ * BRC-162: the σI topic of a token transaction is `tokenTopic(tokenId)` of its
854
+ * token outputs (value or authority). Undefined when no token output decodes.
855
+ */
856
+ const topicOfTx = (tx: Transaction | undefined): string | undefined => {
857
+ for (const o of tx?.outputs ?? []) {
858
+ const d = o.lockingScript != null ? decodeToken(o.lockingScript) : null
859
+ if (d?.tokenId != null) {
860
+ try {
861
+ return tokenTopic(d.tokenId)
862
+ } catch {
863
+ continue
864
+ }
865
+ }
866
+ }
867
+ return undefined
868
+ }
869
+ const topicCache = new Map<string, string>()
870
+ const topicOfTxid = async (txid: string): Promise<string | undefined> => {
871
+ const hit = topicCache.get(txid)
872
+ if (hit !== undefined) return hit
873
+ let topic: string | undefined
874
+ try {
875
+ topic = topicOfTx((await loadBeefContaining(txid))?.findTxid(txid)?.tx)
876
+ } catch (e) {
877
+ devLog(`[mandala] could not derive the token topic of ${txid}:`, e)
878
+ }
879
+ if (topic !== undefined) topicCache.set(txid, topic)
880
+ return topic
881
+ }
882
+
850
883
  /** FIX H, in one function: an entry proves nothing unless THIS overlay signed it. */
851
- const verifyAdmissionEntry: VerifyAdmissionFn = (entry, key) => {
884
+ const verifyAdmissionEntry: VerifyAdmissionFn = async (entry, key) => {
852
885
  if (entry.signerKey.toLowerCase() !== key.toLowerCase()) return false
886
+ // σI v3 binds the token topic. An entry that does not name it (a cached
887
+ // row, an older frame) gets it from the transaction's own token outputs.
888
+ const topic = entry.topic ?? (await topicOfTxid(entry.txid))
889
+ if (topic === undefined) return false
853
890
  try {
854
891
  return libVerifyAdmission({
855
892
  txid: entry.txid,
893
+ topic,
856
894
  outputsToAdmit: entry.outputsToAdmit,
857
895
  signature: Array.from(entry.signature),
858
896
  signerKey: entry.signerKey
@@ -1030,11 +1068,18 @@ export function createMandalaRuntime(args: CreateMandalaRuntimeArgs): MandalaRun
1030
1068
  } catch (e) {
1031
1069
  devLog(`[mandala] could not read the linkage payload of ${txid}:`, e)
1032
1070
  }
1071
+ const topic = topicOfTx(own)
1072
+ if (topic === undefined) {
1073
+ devLog(`[mandala] ${txid} carries no BRC-162 token output; nothing to submit`)
1074
+ return { kind: 'unavailable', code: 'ERR_LOCAL_BYTES', retryable: true }
1075
+ }
1076
+ topicCache.set(txid, topic)
1033
1077
  try {
1034
1078
  const admitted = await submitToOverlay(
1035
1079
  bytes,
1036
1080
  linkage && linkage.payloadBytes.length > 0 ? Array.from(linkage.payloadBytes) : undefined,
1037
- facilitator()
1081
+ facilitator(),
1082
+ [topic]
1038
1083
  )
1039
1084
  // The lib already refuses an unsigned or unverifiable answer
1040
1085
  // (ERR_NO_ADMISSION / ERR_BAD_ADMISSION); this is the wallet's own
@@ -1050,6 +1095,7 @@ export function createMandalaRuntime(args: CreateMandalaRuntimeArgs): MandalaRun
1050
1095
  }
1051
1096
  const trusted = await verifyAdmission({
1052
1097
  txid,
1098
+ topic: admitted.topic ?? topic,
1053
1099
  outputsToAdmit: admitted.outputsToAdmit,
1054
1100
  signature: hexToBytes(signatureHex),
1055
1101
  signerKey
@@ -26,8 +26,8 @@
26
26
  * dependency and is unit-testable against an in-memory SQLite.
27
27
  */
28
28
  import { Beef, Utils } from '@bsv/sdk'
29
- import { MandalaToken } from '@bsv/templates'
30
- import { payloadHash } from '@bsv/mandala'
29
+ import { MandalaToken } from './token'
30
+ import { payloadHash, tokenTopicOrEmpty } from '@bsv/mandala'
31
31
  import type { PostOutcome } from '../offline/plan'
32
32
  import { devLog } from '../logging'
33
33
  import {
@@ -196,7 +196,8 @@ export async function populateEvidenceFromFrame(
196
196
  const at = (opts.now?.() ?? new Date()).toISOString()
197
197
 
198
198
  for (const entry of token.admissions ?? []) {
199
- if (!(await entryIsTrustworthy(entry, opts))) {
199
+ // BRC-162: σI v3 binds the token topic; the frame's asset names it.
200
+ if (!(await entryIsTrustworthy({ ...entry, topic: entry.topic ?? tokenTopicOrEmpty(token.assetId) }, opts))) {
200
201
  result.admissionsDropped++
201
202
  continue
202
203
  }
@@ -390,7 +391,8 @@ export interface TokenStepDeps extends EvidenceTrustAnchor {
390
391
  async function admissionStandsIn(
391
392
  row: TokenAdmissionRow | undefined,
392
393
  anchor: EvidenceTrustAnchor,
393
- requiredVouts: readonly number[]
394
+ requiredVouts: readonly number[],
395
+ assetId?: string
394
396
  ): Promise<boolean> {
395
397
  if (row === undefined) return false
396
398
  if (row.signatureHex.length === 0 || row.outputsToAdmit.length === 0) return false
@@ -398,6 +400,7 @@ async function admissionStandsIn(
398
400
  return await entryIsTrustworthy(
399
401
  {
400
402
  txid: row.txid,
403
+ ...(assetId !== undefined ? { topic: tokenTopicOrEmpty(assetId) } : {}),
401
404
  outputsToAdmit: row.outputsToAdmit,
402
405
  signature: hexToBytes(row.signatureHex),
403
406
  signerKey: row.signerKey
@@ -496,7 +499,7 @@ export async function postTokenStep(
496
499
  // bytes this device does not hold) left an already-admitted tip at
497
500
  // `admitted` on every tick, never broadcast (2026-09-16).
498
501
  const tipAdmission = await store.getAdmission(tip)
499
- if (await admissionStandsIn(tipAdmission, deps, tipRequiredVouts)) {
502
+ if (await admissionStandsIn(tipAdmission, deps, tipRequiredVouts, settlement.assetId)) {
500
503
  await store.advanceSettlement(tip, PRE_ADMIT_STATES, 'admitted', {
501
504
  admissionOutputs: tipAdmission?.outputsToAdmit,
502
505
  admissionSignatureHex: tipAdmission?.signatureHex
@@ -544,7 +547,7 @@ export async function postTokenStep(
544
547
  // vout(s) of it something still in this walk actually spends.
545
548
  const requiredVouts =
546
549
  ancestorTxid === tip ? tipRequiredVouts : await requiredVoutsOfAncestor(store, ancestorTxid, cover.mustSubmit)
547
- if (await admissionStandsIn(cached, deps, requiredVouts)) {
550
+ if (await admissionStandsIn(cached, deps, requiredVouts, settlement.assetId)) {
548
551
  await store.advanceSettlement(ancestorTxid, PRE_ADMIT_STATES, 'admitted', {
549
552
  admissionOutputs: cached?.outputsToAdmit,
550
553
  admissionSignatureHex: cached?.signatureHex
@@ -74,6 +74,7 @@ interface RawInboxMessage {
74
74
  /** What one decoded hand-over needs from `settle` — the exact shape `SettleArgs` wants. */
75
75
  interface DecodedHandover {
76
76
  tip: Transaction
77
+ assetId: string
77
78
  mustSubmit: string[]
78
79
  bytesFor: (txid: string) => { beef: number[]; offChainValues: number[] } | undefined
79
80
  }
@@ -128,6 +129,7 @@ function decodeHandover(body: RawHandoverBody, cover: PreHoldCoverFn): DecodedHa
128
129
 
129
130
  return {
130
131
  tip,
132
+ assetId: body.assetId,
131
133
  mustSubmit: result.mustSubmit,
132
134
  bytesFor: (id: string) => {
133
135
  const found = beef.findAtomicTransaction(id)
@@ -172,7 +174,12 @@ export async function preHoldInboxSettlements(deps: PreHoldInboxDeps): Promise<S
172
174
  if (!decoded) continue // COVER refused it — acceptOne will reach the same refusal before internalizing
173
175
 
174
176
  try {
175
- await deps.settle({ txid: decoded.tip.id('hex'), mustSubmit: decoded.mustSubmit, bytesFor: decoded.bytesFor })
177
+ await deps.settle({
178
+ txid: decoded.tip.id('hex'),
179
+ mustSubmit: decoded.mustSubmit,
180
+ assetId: decoded.assetId,
181
+ bytesFor: decoded.bytesFor
182
+ })
176
183
  } catch (e) {
177
184
  devLog(
178
185
  `[mandala] inbox pre-hold could not write the settlement row for message ${raw.messageId}; holding it back this pass:`,
@@ -10,11 +10,19 @@
10
10
  * via `MandalaToken.decode` from `@bsv/templates`, NOT BTMS's `PushDrop.decode`:
11
11
  * the two token formats are unrelated.
12
12
  *
13
- * There is no Mandala equivalent of BTMS's `createSignature`/preimage-binding
14
- * layer: Mandala's FT protocol (`[2, 'mandala token']`) is not `'p '`-prefixed
15
- * (renaming it would touch every derivation in the blinding scheme — far too
16
- * invasive, see offline-settlement-final.md §8.2), so `createSignature` is
17
- * never routed through this module. Basket-gating alone is the whole gate.
13
+ * Mandala's FT protocol is `[2, 'p mandala token']` (@bsv/mandala 0.4.0), so
14
+ * `WalletPermissionsManager` also routes every wallet call keyed on that
15
+ * protocol here, the same way BTMS's `[0, 'p btms']` reaches
16
+ * `BasicTokenModule`. For a connected app:
17
+ * - `getPublicKey`/`verifySignature` pass through. A public key cannot
18
+ * spend, and issuing or sending to yourself needs keys toward `self`/
19
+ * your own identity key.
20
+ * - `createSignature` passes only when the digest it signs is the BIP-143
21
+ * sighash of an input of a transaction this module saw the user approve
22
+ * (the `createAction` response, captured in `onResponse`). Any other
23
+ * signature gets its own prompt and never grants a session.
24
+ * - `encrypt`/`decrypt`/`createHmac`/`verifyHmac` are refused: nothing in
25
+ * the Mandala lib uses them under the token protocol.
18
26
  *
19
27
  * Source of truth: offline-settlement-final.md §8.3, plus a set of
20
28
  * adversarial-review findings closed here (see the inline notes tagged
@@ -28,13 +36,62 @@
28
36
  * 4. [medium] Prompt amounts are grouped by assetId and decimal-formatted.
29
37
  * 5. [low] relinquishOutput is its own authorization class.
30
38
  */
31
- import { LockingScript, Transaction } from '@bsv/sdk'
39
+ import { Hash, LockingScript, Transaction, Utils } from '@bsv/sdk'
32
40
  import type { PermissionsModule } from '@bsv/wallet-toolbox-mobile'
33
- import { MandalaToken } from '@bsv/templates'
41
+ import { MandalaToken } from './token'
34
42
  import { MANDALA_BASKET } from './types'
35
43
 
36
44
  const SESSION_TIMEOUT_MS = 60_000
37
45
  const SESSION_CLEANUP_INTERVAL_MS = 30_000
46
+ /** Approved transactions remembered per originator. A token send signs right
47
+ * after its createAction, so a handful covers any honest app; the cap keeps
48
+ * a looping one from growing the map without bound. */
49
+ const MAX_AUTHORIZED_TRANSACTIONS_PER_ORIGINATOR = 8
50
+
51
+ /** Token-protocol methods the Mandala lib never calls: refused outright. */
52
+ const REFUSED_KEY_METHODS = new Set(['encrypt', 'decrypt', 'createHmac', 'verifyHmac'])
53
+
54
+ /**
55
+ * The digest a `createSignature` call will actually sign: `hashToDirectlySign`
56
+ * as given, otherwise SHA-256 of `data` (what ProtoWallet does). Undefined
57
+ * for anything malformed, which the caller then refuses.
58
+ */
59
+ export function signedDigestHex(args: unknown): string | undefined {
60
+ if (args === null || typeof args !== 'object') return undefined
61
+ const { hashToDirectlySign, data } = args as { hashToDirectlySign?: unknown; data?: unknown }
62
+ const bytes = (value: unknown): number[] | undefined => {
63
+ if (!Array.isArray(value) && !(value instanceof Uint8Array)) return undefined
64
+ const out = Array.from(value as ArrayLike<unknown>)
65
+ return out.every(b => Number.isInteger(b) && (b as number) >= 0 && (b as number) <= 255)
66
+ ? (out as number[])
67
+ : undefined
68
+ }
69
+ if (hashToDirectlySign !== undefined) {
70
+ const hash = bytes(hashToDirectlySign)
71
+ return hash !== undefined && hash.length === 32 ? Utils.toHex(hash) : undefined
72
+ }
73
+ const payload = bytes(data)
74
+ return payload !== undefined ? Utils.toHex(Hash.sha256(payload)) : undefined
75
+ }
76
+
77
+ /**
78
+ * The BIP-143 sighash (SIGHASH_ALL|FORKID, what `walletMandalaUnlock` signs
79
+ * by default) of every input of a signable transaction. An input whose
80
+ * source is not in the BEEF cannot be hashed and is skipped: it is not one
81
+ * the wallet can be asked to sign for anyway.
82
+ */
83
+ export function authorizedSighashes(atomicBEEF: number[] | Uint8Array): Set<string> {
84
+ const tx = Transaction.fromAtomicBEEF(Array.from(atomicBEEF))
85
+ const digests = new Set<string>()
86
+ for (let i = 0; i < tx.inputs.length; i++) {
87
+ try {
88
+ digests.add(Utils.toHex(Hash.hash256(tx.preimage(i))))
89
+ } catch {
90
+ // No source transaction for this input.
91
+ }
92
+ }
93
+ return digests
94
+ }
38
95
 
39
96
  /**
40
97
  * Normalises an outpoint the same way the SDK's own `Number(...)` coercion
@@ -345,6 +402,9 @@ export class MandalaTokenModule implements PermissionsModule {
345
402
  * adversarial-review finding (5): it is its own authorization class.
346
403
  */
347
404
  private readonly sessionAuthorizations: Map<string, number> = new Map()
405
+ /** Per originator: the input sighashes of each transaction the user
406
+ * approved through `promptForSpend`/`promptGeneric`, newest last. */
407
+ private readonly authorizedTransactions: Map<string, { digests: Set<string>; timestamp: number }[]> = new Map()
348
408
  private readonly cleanupTimer: ReturnType<typeof setInterval>
349
409
 
350
410
  constructor(deps: MandalaTokenModuleDeps) {
@@ -367,6 +427,16 @@ export class MandalaTokenModule implements PermissionsModule {
367
427
  this.sessionAuthorizations.delete(originator)
368
428
  }
369
429
  }
430
+ for (const originator of this.authorizedTransactions.keys()) this.liveAuthorizedTransactions(originator)
431
+ }
432
+
433
+ /** This originator's unexpired approved transactions; prunes the rest. */
434
+ private liveAuthorizedTransactions(originator: string): { digests: Set<string>; timestamp: number }[] {
435
+ const now = Date.now()
436
+ const live = (this.authorizedTransactions.get(originator) ?? []).filter(t => now - t.timestamp <= SESSION_TIMEOUT_MS)
437
+ if (live.length === 0) this.authorizedTransactions.delete(originator)
438
+ else this.authorizedTransactions.set(originator, live)
439
+ return live
370
440
  }
371
441
 
372
442
  private hasSessionAuthorization(originator: string): boolean {
@@ -429,10 +499,15 @@ export class MandalaTokenModule implements PermissionsModule {
429
499
  case 'internalizeAction':
430
500
  await this.promptForCredit(args as MandalaInternalizeActionArgsLike, originator)
431
501
  break
502
+ case 'createSignature':
503
+ await this.authorizeSignature(args, originator)
504
+ break
432
505
  default:
433
- // No other method is ever routed here (basket-gating only covers
434
- // these five) — pass through defensively rather than throw on a
435
- // future manager version that adds one.
506
+ if (REFUSED_KEY_METHODS.has(method)) {
507
+ throw new Error(`Mandala token keys cannot be used for ${method}`)
508
+ }
509
+ // getPublicKey/verifySignature, and any method a future manager
510
+ // version routes here, pass through.
436
511
  break
437
512
  }
438
513
 
@@ -440,14 +515,45 @@ export class MandalaTokenModule implements PermissionsModule {
440
515
  }
441
516
 
442
517
  /**
443
- * Mandala tokens carry no post-hoc metadata to redact and there is no
444
- * preimage-binding layer here (createSignature is not P-routed for this
445
- * protocol, see the class doc) — the response passes through unchanged.
518
+ * After an approved `createAction` (`onRequest` threw otherwise), remembers
519
+ * the input sighashes of the transaction the wallet built, so the app's
520
+ * `createSignature` calls for exactly that transaction need no second
521
+ * prompt. A response that cannot be hashed is passed on unchanged and
522
+ * simply leaves those signatures to `authorizeSignature`'s own prompt.
446
523
  */
447
- async onResponse(res: unknown, _context: { method: string; originator: string }): Promise<unknown> {
524
+ async onResponse(res: unknown, context: { method: string; originator: string }): Promise<unknown> {
525
+ if (context.method !== 'createAction' || context.originator === this.deps.adminOriginator) return res
526
+ const tx = (res as { signableTransaction?: { tx?: number[] | Uint8Array } } | null)?.signableTransaction?.tx
527
+ if (tx === undefined) return res
528
+ let digests: Set<string>
529
+ try {
530
+ digests = authorizedSighashes(tx)
531
+ } catch {
532
+ return res
533
+ }
534
+ const live = this.liveAuthorizedTransactions(context.originator)
535
+ live.push({ digests, timestamp: Date.now() })
536
+ this.authorizedTransactions.set(context.originator, live.slice(-MAX_AUTHORIZED_TRANSACTIONS_PER_ORIGINATOR))
448
537
  return res
449
538
  }
450
539
 
540
+ /**
541
+ * `createSignature` under the token protocol from a connected app. Signing
542
+ * an input of a transaction the user just approved goes ahead; anything
543
+ * else (an unrouted createAction, an expired approval, a digest that is not
544
+ * one of that transaction's) is asked about on its own. The prompt never
545
+ * grants a session: one approval is one signature.
546
+ */
547
+ private async authorizeSignature(args: object, originator: string): Promise<void> {
548
+ const digest = signedDigestHex(args)
549
+ if (digest === undefined) throw new Error('Invalid createSignature args')
550
+ if (this.liveAuthorizedTransactions(originator).some(t => t.digests.has(digest))) return
551
+ const approved = await this.deps.requestTokenAccess(originator, JSON.stringify({ type: 'mandala_signature' }))
552
+ if (!approved) {
553
+ throw new Error('User denied permission to sign with a Mandala token key')
554
+ }
555
+ }
556
+
451
557
  /** listOutputs / listActions — once per 60s session, like BTMS's promptForBTMSAccess. */
452
558
  private async promptOnceForAccess(originator: string, action: 'listOutputs' | 'listActions'): Promise<void> {
453
559
  if (this.hasSessionAuthorization(originator)) return
@@ -27,14 +27,14 @@
27
27
  * transaction's own status: a resend is a delivery, not a payment.
28
28
  */
29
29
  import { Transaction } from '@bsv/sdk'
30
- import { MandalaToken } from '@bsv/templates'
30
+ import { MandalaToken } from './token'
31
31
  import { isDuplicateMessageError } from '../peerpay/control'
32
32
 
33
33
  /** The recipient-side inbox `receiveTokens` drains (`@bsv/mandala` `MESSAGEBOX`). */
34
34
  export const MANDALA_MESSAGE_BOX = 'mandala-payments'
35
35
 
36
36
  /** The FT derivation protocol, as the lib's `FT_PROTOCOL`. */
37
- const FT_PROTOCOL: [number, string] = [2, 'mandala token']
37
+ const FT_PROTOCOL: [number, string] = [2, 'p mandala token']
38
38
 
39
39
  export type TokenResendFailure = 'no_record' | 'no_transaction'
40
40
  export type TokenResendOutcome = { ok: true } | { ok: false; reason: TokenResendFailure }