@bsv/expo-wallet-toolbox 0.13.0 → 0.14.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,52 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.14.0
4
+
5
+ ### Fixed
6
+
7
+ - **External apps can sign under BRC-29 again.** The vault guard refused every
8
+ external `createSignature`, `encrypt`, `decrypt`, `createHmac`,
9
+ `verifyHmac`, `verifySignature` and key-linkage call under
10
+ `[2, '3241645161d8']` (XR-020), so payment apps that sign BRC-29 outputs
11
+ did not work. The namespace is no longer reserved. Because it also derives
12
+ this wallet's own address-rail keys, `seekProtocolPermissionsForSigning` is
13
+ now `true`: a connected app is asked before it first signs under a
14
+ security level 1 or 2 protocol (level 2 per counterparty), BRC-29
15
+ included. This differs from Metanet Desktop, which does not ask.
16
+ `[2, 'mandala token']` stays reserved, and privileged calls are still
17
+ refused. So are the address rail's own key IDs: a BRC-29 call from a
18
+ connected origin whose key ID is `base64(YYYY-MM-DD) + ' ' +
19
+ base64('legacy')` is refused for every key-using method and counterparty
20
+ (`isAddressRailKeyID`, exported from the vault guard).
21
+ - **BRC-29 signing asks every time.** An approval under `3241645161d8` is
22
+ never reused: each signature gets its own prompt, and one app's concurrent
23
+ calls are asked one at a time so a single tap cannot approve a batch. Each
24
+ approval is still recorded as a permission token, tagged
25
+ `keyid <hex of the key ID>` (or `keyidhash <sha256>` when too long), as a
26
+ history of what was approved; BRC-29 tokens, cache entries and the
27
+ recent-grant cover are never read back. BRC-29 entries in a site's
28
+ manifest `groupPermissions`/`counterpartyPermissions` are ignored, so the
29
+ grouped sheet never offers them and is not raised again before each
30
+ signature. A grant is keyed by origin, protocol and counterparty, never key
31
+ ID, so a reused one would cover the wallet's BSV address receipts and
32
+ change too. Each recorded approval is a 1-satoshi token output plus its
33
+ transaction fee.
34
+ - Signing under `[2, 'auth message signature']` (BRC-103 mutual auth and its
35
+ BRC-104 HTTP transport) is exempt from the prompt, so authenticated
36
+ requests never ask. Both rules live in `SigningPolicyPermissionsManager`
37
+ (`core/services/signingPermissionPolicy.ts`).
38
+ - A non-privileged `verifySignature` is never prompted: it reveals nothing
39
+ and spends nothing.
40
+ - The permission sheet no longer shows BRC-29 as `3241645161d8`. Its prompt
41
+ is titled "Payment Key Signature", says coins paid to the key (or the
42
+ wallet's change, for counterparty self) could be spent with the signature,
43
+ and its details name the protocol "Payments (BRC-29)" and show the key ID,
44
+ decoded from base64 when it is readable text. Other protocols are
45
+ unchanged.
46
+ - `getPublicKey`, `encrypt`, `decrypt`, HMAC and key-linkage calls under
47
+ BRC-29 with an app's key ID are not prompted (their `seek*` flags stay
48
+ off).
49
+
3
50
  ## 0.13.0
4
51
 
5
52
  ### 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)
@@ -0,0 +1,258 @@
1
+ import { Hash, Utils } from '@bsv/sdk'
2
+ import { WalletPermissionsManager } from '@bsv/wallet-toolbox-mobile'
3
+
4
+ /**
5
+ * Protocols a connected app may sign under without a protocol prompt, even
6
+ * though seekProtocolPermissionsForSigning is on.
7
+ *
8
+ * `auth message signature` is the one protocol @bsv/auth signs under: BRC-103
9
+ * mutual authentication and its BRC-104 HTTP transport (AuthFetch) both sign
10
+ * every handshake and message with it. Any site that talks to an
11
+ * authenticated server does this on its first request, so prompting for it
12
+ * would ask on nearly every connection. Names are compared the way
13
+ * KeyDeriver.computeInvoiceNumber normalizes them, since that is the key the
14
+ * signature is made with.
15
+ */
16
+ export const PROMPT_FREE_SIGNING_PROTOCOLS = new Set(['auth message signature'])
17
+
18
+ /**
19
+ * Protocols whose approval is never reused: every signature under them is
20
+ * asked for again, one call at a time. Each approval is still recorded as a
21
+ * permission token, tagged with the key ID it was given for, as a history of
22
+ * what the user approved; the manager just never looks those tokens up.
23
+ *
24
+ * BRC-29 (`3241645161d8`) is where this wallet keeps money: BSV address
25
+ * receipts (counterparty 'anyone', date key IDs), change (counterparty self)
26
+ * and payments from other parties. A grant is keyed by origin, protocol and
27
+ * counterparty, never key ID, so a reused approval for one app key would also
28
+ * cover every one of those. Asking per call keeps each signature the user's
29
+ * decision.
30
+ */
31
+ export const ASK_EVERY_TIME_PROTOCOLS = new Set(['3241645161d8'])
32
+
33
+ type EnsureProtocolPermissionArgs = Parameters<WalletPermissionsManager['ensureProtocolPermission']>[0]
34
+ type CreateSignatureArgs = Parameters<WalletPermissionsManager['createSignature']>
35
+ type VerifySignatureArgs = Parameters<WalletPermissionsManager['verifySignature']>
36
+
37
+ function protocolName(protocolID: unknown): string | undefined {
38
+ return Array.isArray(protocolID) && typeof protocolID[1] === 'string' ? protocolID[1].toLowerCase().trim() : undefined
39
+ }
40
+
41
+ export function isPromptFreeSigning({ usageType, privileged, protocolID }: EnsureProtocolPermissionArgs): boolean {
42
+ const name = protocolName(protocolID)
43
+ return usageType === 'signing' && !privileged && name !== undefined && PROMPT_FREE_SIGNING_PROTOCOLS.has(name)
44
+ }
45
+
46
+ export function isAskEveryTimeProtocol(protocolID: unknown): boolean {
47
+ const name = protocolName(protocolID)
48
+ return name !== undefined && ASK_EVERY_TIME_PROTOCOLS.has(name)
49
+ }
50
+
51
+ /** Matches the manager's protocol cache key,
52
+ * `proto:<origin>:<privileged>:<level>,<name>:<counterparty>`, capturing the
53
+ * name. Origins may carry a port, so the match anchors on the privileged flag. */
54
+ const PROTOCOL_CACHE_KEY = /^proto:.*:(?:true|false):\d+,([^:]*):/
55
+
56
+ function isAskEveryTimeCacheKey(key: unknown): boolean {
57
+ const match = typeof key === 'string' ? PROTOCOL_CACHE_KEY.exec(key) : null
58
+ return match !== null && isAskEveryTimeProtocol([2, match[1]])
59
+ }
60
+
61
+ /** Largest tag the wallet stores (validateTag: 1..300 bytes). */
62
+ const MAX_TAG_BYTES = 300
63
+
64
+ /** The token tag recording which key ID an approval was given for. Tags are
65
+ * lowercased by the wallet and key IDs are case-sensitive (often base64), so
66
+ * the key ID is stored as hex of its UTF-8 bytes, or as its SHA-256 when that
67
+ * would not fit in a tag. */
68
+ export function keyIDTag(keyID: string): string {
69
+ const bytes = Utils.toArray(keyID, 'utf8')
70
+ const tag = `keyid ${Utils.toHex(bytes)}`
71
+ return tag.length <= MAX_TAG_BYTES ? tag : `keyidhash ${Utils.toHex(Hash.sha256(bytes))}`
72
+ }
73
+
74
+ /** A protocol permission request with the key ID this class attaches to it. */
75
+ interface ProtocolRequest {
76
+ type?: string
77
+ originator?: string
78
+ protocolID?: unknown
79
+ keyID?: string
80
+ }
81
+
82
+ /** The manager's internals this class reaches. They are private in the
83
+ * typings only; __tests__/services/signingPermissionPolicy.test.ts runs
84
+ * against the real manager, so an upgrade that renames one fails there. */
85
+ interface ManagerInternals {
86
+ prepareOriginator(originator: string): { normalized: string }
87
+ activeRequests: Map<string, { request: ProtocolRequest }>
88
+ findProtocolToken(originator: string, privileged: boolean, protocolID: unknown, ...rest: unknown[]): Promise<unknown>
89
+ markRecentGrant(request: ProtocolRequest): void
90
+ cachePermission(key: string, expiry: number): void
91
+ buildTagsForRequest(request: ProtocolRequest): string[]
92
+ firePermissionRequestEvent(request: ProtocolRequest, key: string): Promise<void>
93
+ underlying: { verifySignature: WalletPermissionsManager['verifySignature'] }
94
+ fetchManifestPermissions(originator: string): Promise<ManifestPermissions>
95
+ }
96
+
97
+ /** The parts of a site's manifest.json permissions the manager reads. */
98
+ interface ManifestPermissions {
99
+ groupPermissions: { protocolPermissions?: Array<{ protocolID?: unknown }> } | null
100
+ counterpartyPermissions: { protocols?: Array<{ protocolName?: unknown }> } | null
101
+ }
102
+
103
+ /** The manifest's permissions without ASK_EVERY_TIME_PROTOCOLS. A site's
104
+ * manifest may list them in its grouped (bulk) request, but such a grant is
105
+ * never kept, so the manager would find it missing on every call and raise
106
+ * the bulk sheet again before each signature prompt. */
107
+ function withoutAskEveryTime(manifest: ManifestPermissions): ManifestPermissions {
108
+ const { groupPermissions, counterpartyPermissions } = manifest
109
+ return {
110
+ groupPermissions:
111
+ groupPermissions?.protocolPermissions == null
112
+ ? groupPermissions
113
+ : {
114
+ ...groupPermissions,
115
+ protocolPermissions: groupPermissions.protocolPermissions.filter(
116
+ p => !isAskEveryTimeProtocol(p?.protocolID)
117
+ )
118
+ },
119
+ counterpartyPermissions:
120
+ counterpartyPermissions?.protocols == null
121
+ ? counterpartyPermissions
122
+ : {
123
+ ...counterpartyPermissions,
124
+ protocols: counterpartyPermissions.protocols.filter(p => !isAskEveryTimeProtocol([2, p?.protocolName]))
125
+ }
126
+ }
127
+ }
128
+
129
+ /**
130
+ * WalletPermissionsManager with this wallet's signing policy:
131
+ * - PROMPT_FREE_SIGNING_PROTOCOLS sign with no prompt;
132
+ * - ASK_EVERY_TIME_PROTOCOLS never reuse an approval. Each one is minted as
133
+ * a token tagged with its key ID, but no token, cache entry or recent-grant
134
+ * cover is ever read back for them; a site's manifest never puts them in a
135
+ * grouped request; and one origin's createSignature calls under them run
136
+ * one at a time, so a burst of calls cannot ride on one approval;
137
+ * - a non-privileged verifySignature is never prompted.
138
+ * Every other check runs unchanged.
139
+ */
140
+ export class SigningPolicyPermissionsManager extends WalletPermissionsManager {
141
+ private readonly askEveryTimeQueues = new Map<string, Promise<unknown>>()
142
+ /** Key ID of the ask-every-time createSignature call each (normalized)
143
+ * origin has in flight. The per-origin queue keeps it to one at a time. */
144
+ private readonly keyIDInFlight = new Map<string, string>()
145
+
146
+ constructor(...args: ConstructorParameters<typeof WalletPermissionsManager>) {
147
+ super(...args)
148
+ const internals = this as unknown as ManagerInternals
149
+ const findProtocolToken = internals.findProtocolToken.bind(this)
150
+ internals.findProtocolToken = async (originator, privileged, protocolID, ...rest) =>
151
+ isAskEveryTimeProtocol(protocolID)
152
+ ? undefined
153
+ : await findProtocolToken(originator, privileged, protocolID, ...rest)
154
+ const markRecentGrant = internals.markRecentGrant.bind(this)
155
+ internals.markRecentGrant = request => {
156
+ if (request?.type === 'protocol' && isAskEveryTimeProtocol(request.protocolID)) return
157
+ markRecentGrant(request)
158
+ }
159
+ const cachePermission = internals.cachePermission.bind(this)
160
+ internals.cachePermission = (key, expiry) => {
161
+ if (isAskEveryTimeCacheKey(key)) return
162
+ cachePermission(key, expiry)
163
+ }
164
+ const buildTagsForRequest = internals.buildTagsForRequest.bind(this)
165
+ internals.buildTagsForRequest = request => {
166
+ const tags = buildTagsForRequest(request)
167
+ return typeof request?.keyID === 'string' ? [...tags, keyIDTag(request.keyID)] : tags
168
+ }
169
+ // The request object is the one the manager keeps until it is answered,
170
+ // so the key ID set here reaches both the prompt (the event's arguments
171
+ // spread it) and the token a grant mints (buildTagsForRequest above).
172
+ const firePermissionRequestEvent = internals.firePermissionRequestEvent.bind(this)
173
+ internals.firePermissionRequestEvent = async (request, key) => {
174
+ if (request?.type === 'protocol' && isAskEveryTimeProtocol(request.protocolID) && request.originator) {
175
+ const keyID = this.keyIDInFlight.get(request.originator)
176
+ if (keyID !== undefined) request.keyID = keyID
177
+ }
178
+ return await firePermissionRequestEvent(request, key)
179
+ }
180
+ const fetchManifestPermissions = internals.fetchManifestPermissions.bind(this)
181
+ internals.fetchManifestPermissions = async originator =>
182
+ withoutAskEveryTime(await fetchManifestPermissions(originator))
183
+ }
184
+
185
+ private get internals(): ManagerInternals {
186
+ return this as unknown as ManagerInternals
187
+ }
188
+
189
+ override async ensureProtocolPermission(args: EnsureProtocolPermissionArgs): Promise<boolean> {
190
+ if (isPromptFreeSigning(args)) {
191
+ // Still refuse a missing or malformed originator, as the full check
192
+ // does first.
193
+ this.internals.prepareOriginator(args.originator)
194
+ return true
195
+ }
196
+ return await super.ensureProtocolPermission(args)
197
+ }
198
+
199
+ override async createSignature(
200
+ ...args: CreateSignatureArgs
201
+ ): ReturnType<WalletPermissionsManager['createSignature']> {
202
+ return await this.oneAtATime(args[0], args[1], async () => await super.createSignature(...args))
203
+ }
204
+
205
+ /** Verifying a signature reveals nothing and spends nothing, so a
206
+ * non-privileged verification is answered without a protocol prompt. The
207
+ * originator is still validated, and admin-reserved (`admin…`) and
208
+ * module-routed (`p …`) protocols still take the manager's full path. */
209
+ override async verifySignature(
210
+ ...args: VerifySignatureArgs
211
+ ): ReturnType<WalletPermissionsManager['verifySignature']> {
212
+ const [request, originator] = args
213
+ const name = protocolName(request?.protocolID)
214
+ if (request?.privileged || name === undefined || name.startsWith('admin') || name.startsWith('p ')) {
215
+ return await super.verifySignature(...args)
216
+ }
217
+ this.internals.prepareOriginator(String(originator))
218
+ return await this.internals.underlying.verifySignature(request, originator)
219
+ }
220
+
221
+ /**
222
+ * Runs an ask-every-time createSignature call after the same origin's
223
+ * previous one. The manager hands every call already waiting on a request
224
+ * the same answer, so concurrent calls would otherwise share a single
225
+ * approval. While it runs, its key ID is what its prompt shows and what a
226
+ * grant of its request records.
227
+ */
228
+ private async oneAtATime<T>(
229
+ args: { protocolID?: unknown; keyID?: string },
230
+ originator: string | undefined,
231
+ call: () => Promise<T>
232
+ ): Promise<T> {
233
+ if (!isAskEveryTimeProtocol(args?.protocolID)) return await call()
234
+ let origin: string
235
+ try {
236
+ origin = this.internals.prepareOriginator(String(originator)).normalized
237
+ } catch {
238
+ return await call() // the manager refuses it with its own error
239
+ }
240
+ const previous = this.askEveryTimeQueues.get(origin) ?? Promise.resolve()
241
+ const current = previous
242
+ .catch(() => {})
243
+ .then(async () => {
244
+ this.keyIDInFlight.set(origin, String(args.keyID))
245
+ try {
246
+ return await call()
247
+ } finally {
248
+ this.keyIDInFlight.delete(origin)
249
+ }
250
+ })
251
+ this.askEveryTimeQueues.set(origin, current)
252
+ try {
253
+ return await current
254
+ } finally {
255
+ if (this.askEveryTimeQueues.get(origin) === current) this.askEveryTimeQueues.delete(origin)
256
+ }
257
+ }
258
+ }
@@ -32,6 +32,7 @@ import {
32
32
  PrivateKey,
33
33
  PublicKey,
34
34
  Transaction,
35
+ Utils,
35
36
  Validation,
36
37
  type ListActionsArgs,
37
38
  type ListActionsResult,
@@ -121,17 +122,56 @@ const PRIVILEGED_CAPABLE = new Set<keyof WalletInterface>([
121
122
  * own vault code ever reaches it. */
122
123
  const VAULT_PROTOCOL_NAMES = new Set(['vault', 'vault salt', 'vault marker', 'vault descriptor', 'vault meta'])
123
124
 
124
- /** Protocol namespaces this package's OWN internal, fund-controlling payment
125
- * rails derive under: the BRC-29 address rail / PeerPay (address.ts's
126
- * BRC29_PROTOCOL_ID and localpay/pending.ts's identical PEERPAY_PROTOCOL_ID,
127
- * both `[2, '3241645161d8']`) and the FT/mandala-token rail (localpay/verify.ts's
128
- * FT_PROTOCOL_ID, `[2, 'mandala token']`). These are not Vault state, but
129
- * core/localpay/build.ts proves createSignature+getPublicKey over them is
130
- * sufficient to construct a valid spend -- so a connected origin must not be
131
- * able to mint either primitive under these namespaces itself, exactly as
132
- * for Vault's own namespaces. The one exception is getPublicKey toward
133
- * another party's identity key (see derivesTowardAnotherParty). */
134
- const RESERVED_RAIL_PROTOCOL_NAMES = new Set(['3241645161d8', 'mandala token'])
125
+ /** Protocol namespace this package's OWN internal, fund-controlling FT/
126
+ * mandala-token rail derives under (localpay/verify.ts's FT_PROTOCOL_ID,
127
+ * `[2, 'mandala token']`). It is not Vault state, but core/localpay/build.ts
128
+ * proves createSignature+getPublicKey over it is sufficient to construct a
129
+ * valid spend -- so a connected origin must not be able to mint either
130
+ * primitive under it itself, exactly as for Vault's own namespaces. The one
131
+ * exception is getPublicKey toward another party's identity key (see
132
+ * derivesTowardAnotherParty).
133
+ *
134
+ * BRC-29 (`[2, '3241645161d8']`) was reserved here too (XR-020) and is not any
135
+ * more: it is the standard BRC-100 payment protocol, and refusing it broke
136
+ * every external payment app that signs under it. External signing under it
137
+ * goes through the permissions manager's protocol prompt instead
138
+ * (seekProtocolPermissionsForSigning in WalletContext.tsx), except for the
139
+ * address rail's own key IDs, which stay refused (isAddressRailKeyID). */
140
+ const RESERVED_RAIL_PROTOCOL_NAMES = new Set(['mandala token'])
141
+
142
+ /** base64('legacy'), the suffix every address-rail key ID ends in
143
+ * (pay/rails/address.ts's LEGACY_DERIVATION_SUFFIX). */
144
+ const ADDRESS_RAIL_KEY_SUFFIX = Utils.toBase64(Utils.toArray('legacy', 'utf8'))
145
+
146
+ /** True for a key ID shaped like the BRC-29 address rail's own:
147
+ * `base64(YYYY-MM-DD) + ' ' + base64('legacy')` (pay/rails/address.ts's
148
+ * legacyKeyId). Those keys hold this wallet's BSV-address receipts, and anyone
149
+ * who knows a date can name one, so no connected origin has a reason to ask
150
+ * for them: refused outright, for every method and counterparty, whatever
151
+ * permission the user has given. KeyDeriver uses the key ID verbatim, so the
152
+ * comparison is exact. */
153
+ export function isAddressRailKeyID(keyID: unknown): boolean {
154
+ if (typeof keyID !== 'string') return false
155
+ const parts = keyID.split(' ')
156
+ if (parts.length !== 2 || parts[1] !== ADDRESS_RAIL_KEY_SUFFIX) return false
157
+ try {
158
+ const bytes = Utils.toArray(parts[0], 'base64')
159
+ if (Utils.toBase64(bytes) !== parts[0]) return false
160
+ return /^\d{4}-\d{2}-\d{2}$/.test(Utils.toUTF8(bytes))
161
+ } catch {
162
+ return false
163
+ }
164
+ }
165
+
166
+ /** BRC-29's protocol name, under which the address rail derives. */
167
+ const BRC29_PROTOCOL_NAME = '3241645161d8'
168
+
169
+ function requestsAddressRailKey(args: unknown): boolean {
170
+ return (
171
+ matchesProtocolNamespace(args, new Set([BRC29_PROTOCOL_NAME])) &&
172
+ isAddressRailKeyID((args as { keyID?: unknown }).keyID)
173
+ )
174
+ }
135
175
 
136
176
  /** The BRC-42 'anyone' counterparty (1·G), in canonical form. */
137
177
  const ANYONE_PUBLIC_KEY = new PrivateKey(1).toPublicKey().toString()
@@ -150,13 +190,13 @@ function counterpartyPublicKey(counterparty: unknown): string | undefined {
150
190
  }
151
191
 
152
192
  /** getPublicKey under a reserved rail namespace toward another party's
153
- * identity key is the ordinary BRC-29 / FT payer (forSelf false) and payee
193
+ * identity key is the ordinary FT payer (forSelf false) and payee
154
194
  * (forSelf true) step every payment dApp takes. ECDH is symmetric, so that
155
195
  * party can compute the same public key itself: revealing it neither signs
156
196
  * nor tells anyone anything new. createSignature and the other private-key
157
197
  * methods stay reserved, as do the two counterparties this wallet's own funds
158
- * are locked to where a site could guess the keyID: 'anyone' (the address
159
- * rail's date keyIDs) and the wallet's own identity key (FT change). Any
198
+ * are locked to where a site could guess the keyID: 'anyone' and the
199
+ * wallet's own identity key (FT change). Any
160
200
  * failure to read the identity key counts as a match, so the call is refused. */
161
201
  async function derivesTowardAnotherParty(
162
202
  getPublicKey: (args: any, originator?: string) => Promise<{ publicKey: string }>,
@@ -725,6 +765,7 @@ export function guardVaultAccess<T extends WalletInterface>(
725
765
  requestsVaultProtocol(args) ||
726
766
  requestsConnectionAuthorityProtocol(args) ||
727
767
  requestsPendingAbortAuthorityProtocol(args) ||
768
+ requestsAddressRailKey(args) ||
728
769
  (requestsReservedRailProtocol(args) &&
729
770
  !(method === 'getPublicKey' && (await derivesTowardAnotherParty(bound, args, adminOriginator)))))
730
771
  ) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bsv/expo-wallet-toolbox",
3
- "version": "0.13.0",
3
+ "version": "0.14.0",
4
4
  "private": false,
5
5
  "description": "Wallet screens and P2P local-payment backend for Expo/React Native apps, extracted from BSV Wallet.",
6
6
  "license": "SEE LICENSE IN LICENSE.txt",
@@ -5,6 +5,7 @@ import Sheet from './Sheet'
5
5
  import PressableScale from './PressableScale'
6
6
  import { useTranslation } from 'react-i18next'
7
7
  import AmountDisplay from '../wallet/AmountDisplay'
8
+ import { describeProtocolPrompt } from './protocolPrompt'
8
9
  import {
9
10
  spacing,
10
11
  radii,
@@ -250,17 +251,22 @@ export function deriveActive(
250
251
 
251
252
  if (ctx.protocolAccessModalOpen && ctx.protocolRequests.length > 0) {
252
253
  const r = ctx.protocolRequests[0]
254
+ const prompt = describeProtocolPrompt(r.protocolID ?? '', r.counterparty, r.keyID)
255
+ const details: { label: string; value: string }[] = [
256
+ { label: 'Protocol', value: truncate(prompt.protocolLabel, 40) },
257
+ { label: 'Security level', value: String(r.protocolSecurityLevel) }
258
+ ]
259
+ if (prompt.counterpartyLabel) details.push({ label: 'Shared with', value: prompt.counterpartyLabel })
260
+ if (prompt.keyIDLabel) details.push({ label: 'Key ID', value: truncate(prompt.keyIDLabel, 40) })
261
+ if (prompt.askEveryTime) details.push({ label: 'Approval', value: 'This signature only' })
253
262
  return {
254
263
  kind: 'protocol',
255
264
  requestID: r.requestID,
256
265
  originator: r.originator || 'Unknown app',
257
- title: r.renewal ? 'Protocol Access Renewal' : 'Protocol Access',
258
- description: r.description || 'wants to use a cryptographic protocol',
266
+ title: r.renewal ? `${prompt.title} Renewal` : prompt.title,
267
+ description: prompt.description ?? (r.description || 'wants to use a cryptographic protocol'),
259
268
  renewal: r.renewal,
260
- details: [
261
- { label: 'Protocol ID', value: truncate(r.protocolID, 28) },
262
- { label: 'Security level', value: String(r.protocolSecurityLevel) }
263
- ]
269
+ details
264
270
  }
265
271
  }
266
272
 
@@ -807,7 +813,9 @@ const PermissionSheet: React.FC = () => {
807
813
  </Text>
808
814
  {active.groupPermissions.protocolPermissions.map((p, i) => (
809
815
  <View key={i} style={styles.groupRow}>
810
- <Text style={[styles.groupRowLabel, { color: colors.textPrimary }]}>{p.protocolID[1]}</Text>
816
+ <Text style={[styles.groupRowLabel, { color: colors.textPrimary }]}>
817
+ {describeProtocolPrompt(p.protocolID[1], p.counterparty).protocolLabel}
818
+ </Text>
811
819
  {p.description && (
812
820
  <Text style={[styles.groupRowDesc, { color: colors.textSecondary }]}>{p.description}</Text>
813
821
  )}
@@ -0,0 +1,118 @@
1
+ import { PrivateKey, PublicKey, Utils } from '@bsv/sdk'
2
+
3
+ /** BRC-29's protocol name. Apps sign under it to receive and move payments,
4
+ * and this wallet's own payment keys (BSV address receipts, change) live
5
+ * under it too, so a grant here is a grant over money. */
6
+ const BRC29_PROTOCOL_NAME = '3241645161d8'
7
+
8
+ /** The BRC-42 'anyone' counterparty (1·G), in canonical form. */
9
+ const ANYONE_PUBLIC_KEY = new PrivateKey(1).toPublicKey().toString()
10
+
11
+ type Counterparty = { kind: 'anyone' } | { kind: 'self' } | { kind: 'party'; key: string }
12
+
13
+ /** The protocol grant's counterparty as the permissions manager reports it:
14
+ * 'self' when the app named none, 'anyone' as the literal or as 1·G in any
15
+ * encoding, otherwise another party's key. */
16
+ function classifyCounterparty(counterparty: unknown): Counterparty {
17
+ if (counterparty === undefined || counterparty === null || counterparty === '' || counterparty === 'self') {
18
+ return { kind: 'self' }
19
+ }
20
+ if (counterparty === 'anyone') return { kind: 'anyone' }
21
+ const raw = String(counterparty)
22
+ try {
23
+ const key = PublicKey.fromString(raw).toString()
24
+ return key === ANYONE_PUBLIC_KEY ? { kind: 'anyone' } : { kind: 'party', key }
25
+ } catch {
26
+ return { kind: 'party', key: raw }
27
+ }
28
+ }
29
+
30
+ function abbreviate(key: string): string {
31
+ return key.length <= 13 ? key : key.slice(0, 8) + '…' + key.slice(-4)
32
+ }
33
+
34
+ /** One space-separated part of a key ID as text: the decoded value when the
35
+ * part is canonical base64 of printable ASCII (BRC-29 key IDs are usually
36
+ * base64 prefix + ' ' + base64 suffix), otherwise the part as given. */
37
+ function readablePart(part: string): string {
38
+ try {
39
+ const bytes = Utils.toArray(part, 'base64')
40
+ if (bytes.length === 0 || Utils.toBase64(bytes) !== part) return part
41
+ if (!bytes.every(b => b >= 0x20 && b <= 0x7e)) return part
42
+ return Utils.toUTF8(bytes)
43
+ } catch {
44
+ return part
45
+ }
46
+ }
47
+
48
+ /** A key ID as a person can read it, so an app's fixed key ID ("xana-earnings
49
+ * 1") is visibly not one of the wallet's own. */
50
+ export function readableKeyID(keyID: string): string {
51
+ return keyID.split(' ').map(readablePart).join(' ')
52
+ }
53
+
54
+ export interface ProtocolPrompt {
55
+ /** Sheet title, before any "Renewal" suffix. */
56
+ title: string
57
+ /** What approving lets the app do, completing "<app> …". Undefined means
58
+ * the caller's own text (or its generic fallback) is used. */
59
+ description?: string
60
+ /** Name to show for the protocol in place of its raw ID. */
61
+ protocolLabel: string
62
+ /** Who the keys are shared with, when that is worth naming. */
63
+ counterpartyLabel?: string
64
+ /** The key ID asked for, readable, when the request carries it. */
65
+ keyIDLabel?: string
66
+ /** The approval covers this one call and is never reused
67
+ * (core/services/signingPermissionPolicy.ts's ASK_EVERY_TIME_PROTOCOLS). */
68
+ askEveryTime?: boolean
69
+ }
70
+
71
+ /**
72
+ * Plain-language copy for a protocol permission request. Most protocol names
73
+ * are an app's own words and are shown as they are. BRC-29's is an opaque
74
+ * hex ID, and approving it lets the app sign with a key that can hold money,
75
+ * so it gets its own title and a description that says which money. The
76
+ * address rail's own key IDs never reach a prompt (vault guard's
77
+ * isAddressRailKeyID refuses them), so the copy describes the app's key.
78
+ */
79
+ export function describeProtocolPrompt(protocolName: string, counterparty?: unknown, keyID?: unknown): ProtocolPrompt {
80
+ if (protocolName.toLowerCase().trim() !== BRC29_PROTOCOL_NAME) {
81
+ return { title: 'Protocol Access', protocolLabel: protocolName }
82
+ }
83
+ const party = classifyCounterparty(counterparty)
84
+ const protocolLabel = 'Payments (BRC-29)'
85
+ const keyIDLabel = typeof keyID === 'string' ? readableKeyID(keyID) : undefined
86
+ switch (party.kind) {
87
+ case 'anyone':
88
+ return {
89
+ title: 'Payment Key Signature',
90
+ description:
91
+ 'wants a signature from one of your payment keys. Coins paid to this key could be spent with this signature.',
92
+ protocolLabel,
93
+ askEveryTime: true,
94
+ counterpartyLabel: 'Anyone',
95
+ keyIDLabel
96
+ }
97
+ case 'self':
98
+ return {
99
+ title: 'Payment Key Signature',
100
+ description:
101
+ "wants a signature from one of your wallet's own payment keys. Your change could be spent with this signature.",
102
+ protocolLabel,
103
+ askEveryTime: true,
104
+ counterpartyLabel: 'Only you',
105
+ keyIDLabel
106
+ }
107
+ case 'party':
108
+ return {
109
+ title: 'Payment Key Signature',
110
+ description:
111
+ 'wants a signature from a payment key you share with another party. Coins paid to this key could be spent with this signature.',
112
+ protocolLabel,
113
+ askEveryTime: true,
114
+ counterpartyLabel: abbreviate(party.key),
115
+ keyIDLabel
116
+ }
117
+ }
118
+ }