@bsv/expo-wallet-toolbox 0.15.2 → 0.16.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 +158 -0
- package/core/backup/appData.ts +5 -1
- package/core/backup/codec.ts +9 -3
- package/core/backup/contactsBackup.ts +145 -0
- package/core/backup/push.ts +14 -0
- package/core/backup/restoreOnImport.ts +15 -0
- package/core/contacts/contactsStore.ts +47 -3
- package/core/context/LocalStorageProvider.tsx +3 -1
- package/core/context/WalletContext.tsx +5 -2
- package/core/context/startupPrewarm.ts +54 -0
- package/core/hooks/useConfirmationSound.ts +7 -0
- package/core/identity/handleRegistry/client.ts +2 -1
- package/core/identity/handleRegistry/profileKeys.ts +16 -0
- package/core/identity/handleRegistry/resolver.ts +2 -1
- package/core/identity/handleRegistry/rules.ts +7 -3
- package/core/index.ts +2 -1
- package/core/localpay/build.ts +4 -3
- package/core/localpay/session.ts +6 -0
- package/core/localpay/transport/select.ts +64 -3
- package/core/localpay/verify.ts +2 -1
- package/core/net/trimTrailingSlashes.ts +13 -0
- package/core/parsePeerPayURI.ts +25 -2
- package/core/pay/creditInbox.ts +31 -1
- package/core/pay/rails/address.ts +3 -2
- package/core/pay/rails/handle.ts +8 -2
- package/core/pay/rails/index.ts +6 -4
- package/core/pos/protocol.ts +172 -0
- package/core/profiles/removalProblems.ts +41 -0
- package/core/push/registration.ts +2 -1
- package/core/services/revokeConnection.ts +98 -0
- package/core/storage/schema/createTables.ts +24 -0
- package/core/toolboxConfig.ts +22 -4
- package/package.json +1 -1
- package/ui/components/pay/MessageBoxConfig.tsx +2 -1
- package/ui/components/pay/NearbyFlow.tsx +410 -7
- package/ui/exportTransactions.ts +26 -13
- package/ui/index.ts +2 -2
- package/ui/screens/ConnectionsScreen.tsx +8 -63
- package/ui/screens/ProfileScreen.tsx +2 -40
- package/ui/screens/WalletConfigScreen.tsx +57 -51
|
@@ -23,6 +23,7 @@ import {
|
|
|
23
23
|
import { verifyProfileCertificate, type ProfileCertJson, type RegistryProfile } from './profileCert'
|
|
24
24
|
import { createRegistryResolver, fetchWithTimeout, type RegistryPin, type RegistryResolver } from './resolver'
|
|
25
25
|
import { createKeyPinStore, type KeyPinStore } from './keyPinStore'
|
|
26
|
+
import { trimTrailingSlashes } from '../../net/trimTrailingSlashes'
|
|
26
27
|
|
|
27
28
|
/** Why a handle is not free. The server's `stale` arrives as `cooldown`. */
|
|
28
29
|
export type AvailabilityReason = 'taken' | 'too_similar' | 'reserved' | 'invalid' | 'cooldown'
|
|
@@ -90,7 +91,7 @@ export function createHandleRegistryClient(args: {
|
|
|
90
91
|
const fetchImpl = args.fetchImpl ?? ((input: RequestInfo | URL, init?: RequestInit) => fetch(input, init))
|
|
91
92
|
const now = args.now ?? (() => Date.now())
|
|
92
93
|
const domain = args.pinned.domain.trim().toLowerCase()
|
|
93
|
-
const origin = args.pinned.url.trim()
|
|
94
|
+
const origin = trimTrailingSlashes(args.pinned.url.trim())
|
|
94
95
|
const resolver = args.resolver ?? createRegistryResolver({ pinned: args.pinned, fetchImpl, now })
|
|
95
96
|
const pinStore = args.pinStore ?? createKeyPinStore()
|
|
96
97
|
let skewMs = 0
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where a wallet keeps its own profile on this device (its storage key-value
|
|
3
|
+
* table). Shared so every host that registers a handle (Profile, a host's own
|
|
4
|
+
* onboarding) reads and writes the same entries.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/** The full `handle@domain`, cached for a cold start. The registry decides. */
|
|
8
|
+
export const HANDLE_KV_KEY = 'profile_registered_handle'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The display name lives here on this device, and — once a handle is
|
|
12
|
+
* registered — as a PUBLIC plaintext field of the profile certificate
|
|
13
|
+
* (2026-09-18 ruling). The identity overlay's `name` is only a fallback for a
|
|
14
|
+
* wallet that has never set one.
|
|
15
|
+
*/
|
|
16
|
+
export const DISPLAY_NAME_KV_KEY = 'profile_display_name'
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
*/
|
|
14
14
|
import { BRFC_LOOKUP, BRFC_REVERSE_LOOKUP, looksLikeDomain } from './rules'
|
|
15
15
|
import { isPublicHttpsUrl } from '../../net/publicDestination'
|
|
16
|
+
import { trimTrailingSlashes } from '../../net/trimTrailingSlashes'
|
|
16
17
|
|
|
17
18
|
/** The domain this build's own handles live under, and the host serving it. */
|
|
18
19
|
export interface RegistryPin {
|
|
@@ -216,7 +217,7 @@ export function createRegistryResolver(args: {
|
|
|
216
217
|
const now = args.now ?? (() => Date.now())
|
|
217
218
|
const dohEndpoints = args.dohEndpoints ?? DOH_ENDPOINTS
|
|
218
219
|
const pinnedDomain = args.pinned?.domain.trim().toLowerCase() ?? ''
|
|
219
|
-
const pinnedOrigin = args.pinned?.url.trim()
|
|
220
|
+
const pinnedOrigin = trimTrailingSlashes(args.pinned?.url.trim() ?? '')
|
|
220
221
|
const cache = new Map<string, { at: number; value: RegistryEndpoints | null }>()
|
|
221
222
|
|
|
222
223
|
const pinnedEndpoints: RegistryEndpoints | null =
|
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
* as a rail — a handle is the local part of a `handle@domain` paymail.
|
|
13
13
|
*/
|
|
14
14
|
import { Utils } from '@bsv/sdk'
|
|
15
|
+
import { getHandleMinLength } from '../../toolboxConfig'
|
|
15
16
|
|
|
16
17
|
/** base64(SHA-256("public profile lookup")) — the profile certificate's type. */
|
|
17
18
|
export const PROFILE_CERT_TYPE = 'SbatVXXssDW3AO0J9bxIljkHGbPBGCVAXg94gXFf0cE='
|
|
@@ -44,7 +45,7 @@ export const MAX_SEARCH_QUERY_LENGTH = 32
|
|
|
44
45
|
*/
|
|
45
46
|
export const MAX_SEARCH_RESULTS = 10
|
|
46
47
|
|
|
47
|
-
const HANDLE_FORMAT = /^[a-z0-9][a-z0-9._-]{
|
|
48
|
+
const HANDLE_FORMAT = /^[a-z0-9](?:[a-z0-9._-]{0,30}[a-z0-9])?$/
|
|
48
49
|
const DOMAIN_FORMAT = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)+$/
|
|
49
50
|
const SEARCH_QUERY_FORMAT = /^[a-z0-9._-]+$/
|
|
50
51
|
|
|
@@ -60,9 +61,12 @@ const SEARCH_QUERY_FORMAT = /^[a-z0-9._-]+$/
|
|
|
60
61
|
*/
|
|
61
62
|
const RESERVED_QUERY_PATHS = new Set(['available', '..'])
|
|
62
63
|
|
|
63
|
-
/**
|
|
64
|
+
/**
|
|
65
|
+
* a-z 0-9 . _ -, beginning and ending with a letter or digit, at most 32
|
|
66
|
+
* characters and at least the host's minimum (3 unless configured lower).
|
|
67
|
+
*/
|
|
64
68
|
export function isValidHandleFormat(handle: string): boolean {
|
|
65
|
-
return HANDLE_FORMAT.test(handle)
|
|
69
|
+
return handle.length >= getHandleMinLength() && HANDLE_FORMAT.test(handle)
|
|
66
70
|
}
|
|
67
71
|
|
|
68
72
|
/** A dotted, all-lowercase domain. Says nothing about whether it resolves. */
|
package/core/index.ts
CHANGED
|
@@ -114,7 +114,7 @@ export * from './localpay/nearbyPermissions'
|
|
|
114
114
|
// surface now that the screen holds LocalPaymentTransport[] (spec §6) and
|
|
115
115
|
// callers need to tell an AckError (radio failure → fountain) from a decline.
|
|
116
116
|
export { AckError, QrHandoffRequired, type Ack, type LocalPaymentTransport, type ReceivedFrame } from './localpay/types'
|
|
117
|
-
export { selectTransport } from './localpay/transport/select'
|
|
117
|
+
export { selectTransport, fallbackRadio, failedBeforeConnect } from './localpay/transport/select'
|
|
118
118
|
export * from './peerpay/outbox'
|
|
119
119
|
export * from './peerpay/control'
|
|
120
120
|
export * from './peerpay/handleResendRequests'
|
|
@@ -430,6 +430,7 @@ export * from './services/vault/chainRecovery'
|
|
|
430
430
|
// that never trigger a haptic. useConfirmationSound.ts already requires
|
|
431
431
|
// expo-audio the same way.
|
|
432
432
|
export { default as connectionStore } from './stores/ConnectionStore'
|
|
433
|
+
export { revokeConnection } from './services/revokeConnection'
|
|
433
434
|
export type { Connection } from './stores/ConnectionStore'
|
|
434
435
|
export * from './context/WalletConnectionContext'
|
|
435
436
|
export * from './context/VaultContext'
|
package/core/localpay/build.ts
CHANGED
|
@@ -313,8 +313,9 @@ export async function buildPaymentFrame(
|
|
|
313
313
|
// what happened. Not the payee's key: the row draws the counterparty as
|
|
314
314
|
// a sigil from the label below, and an abbreviated key as a title told
|
|
315
315
|
// the user nothing about a blinded transfer (2026-09-16). A payer's note
|
|
316
|
-
// overrides this fixed wording, same as the message-box rail
|
|
317
|
-
description
|
|
316
|
+
// overrides this fixed wording, same as the message-box rail, space-padded:
|
|
317
|
+
// a description must be at least 5 bytes and the validator doesn't trim.
|
|
318
|
+
description: (note?.trim() || 'Sent BSV').padEnd(5),
|
|
318
319
|
// The payee's identity key rides as a label, and the derivation data as
|
|
319
320
|
// the output's customInstructions — exactly what the handle rail writes.
|
|
320
321
|
// Both rails derive to BRC-29 (`counterparty: identityKey`, keyID
|
|
@@ -642,7 +643,7 @@ async function buildTokenPaymentFrame(
|
|
|
642
643
|
// and without it a nearby token payment rendered as a BSV row — the
|
|
643
644
|
// payee's key over "+0 sats" (2026-09-16). The payee key stays on as a
|
|
644
645
|
// label for the resend path.
|
|
645
|
-
description: note?.trim() || 'Sent token',
|
|
646
|
+
description: (note?.trim() || 'Sent token').padEnd(5),
|
|
646
647
|
labels: [PEERPAY_LABEL, session.identityKey, MANDALA_ACTION_LABEL, MANDALA_TOKEN_SPEND_LABEL],
|
|
647
648
|
inputBEEF: sourceBeef.toBinary(),
|
|
648
649
|
inputs: selected.map(coin => ({
|
package/core/localpay/session.ts
CHANGED
|
@@ -72,6 +72,12 @@ export interface SessionAsset {
|
|
|
72
72
|
}
|
|
73
73
|
|
|
74
74
|
export interface Session {
|
|
75
|
+
/** Verified host display metadata; never encoded into the base pairing QR. */
|
|
76
|
+
merchantName?: string
|
|
77
|
+
merchantChain?: string
|
|
78
|
+
merchantExpires?: number
|
|
79
|
+
merchantSubtotal?: number
|
|
80
|
+
merchantTip?: number
|
|
75
81
|
version: number
|
|
76
82
|
caps: number
|
|
77
83
|
sessionId: Uint8Array
|
|
@@ -1,6 +1,17 @@
|
|
|
1
1
|
import { Platform } from 'react-native'
|
|
2
2
|
import { getLocalPayBleTransport, getLocalPayTransport } from '@bsv/react-native-localpay-transport'
|
|
3
|
-
import {
|
|
3
|
+
import {
|
|
4
|
+
CAP_AWDL,
|
|
5
|
+
CAP_BLE,
|
|
6
|
+
CAP_BLE_SCAN,
|
|
7
|
+
CAP_NEARBY,
|
|
8
|
+
HINT_BT,
|
|
9
|
+
HINT_NET,
|
|
10
|
+
HINT_ONLINE_KNOWN,
|
|
11
|
+
HINT_WIFI,
|
|
12
|
+
RUNG_MASK,
|
|
13
|
+
type Session
|
|
14
|
+
} from '../session'
|
|
4
15
|
import type { BluetoothState } from '../deviceCaps'
|
|
5
16
|
|
|
6
17
|
export type TransportKind = 'awdl' | 'nearby' | 'ble' | 'qr'
|
|
@@ -57,15 +68,65 @@ export function localSupportsBle(): boolean {
|
|
|
57
68
|
* the peer's AWDL/Nearby bits can never match local ability. `session.os` is
|
|
58
69
|
* metadata and is deliberately not read here (see Session.os). QR is the
|
|
59
70
|
* floor every pair can reach — and the automatic fallback when a chosen radio
|
|
60
|
-
* fails at send time (see NearbyFlow's executeSend)
|
|
71
|
+
* fails at send time (see NearbyFlow's executeSend), after fallbackRadio()
|
|
72
|
+
* below when the first radio never connected.
|
|
61
73
|
*/
|
|
62
74
|
export function selectTransport(session: Session): TransportKind {
|
|
63
|
-
if ((session.caps & CAP_AWDL) !== 0 && localSupportsAwdl()) return 'awdl'
|
|
75
|
+
if ((session.caps & CAP_AWDL) !== 0 && !peerKnownOffWifi(session) && localSupportsAwdl()) return 'awdl'
|
|
64
76
|
if ((session.caps & CAP_NEARBY) !== 0 && localSupportsNearby()) return 'nearby'
|
|
65
77
|
if ((session.caps & CAP_BLE) !== 0 && localSupportsBle()) return 'ble'
|
|
66
78
|
return 'qr'
|
|
67
79
|
}
|
|
68
80
|
|
|
81
|
+
/**
|
|
82
|
+
* The text every native connect-phase failure carries: the code-14 connect
|
|
83
|
+
* timeout, and (AWDL) any `.failed`/`.cancelled` that landed before the link
|
|
84
|
+
* reached `.ready` — see HybridLocalPayTransport.swift `neverConnected`.
|
|
85
|
+
*/
|
|
86
|
+
export const NEVER_CONNECTED_MARKER = 'no route to peer'
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* True when a radio send failed before its link came up, so not one byte of
|
|
90
|
+
* the frame left this device. Only then may the payer try a second radio: a
|
|
91
|
+
* failure after the link was up (a lost ack, a timeout waiting for the payee's
|
|
92
|
+
* save) may already have delivered the frame, and delivering it again on
|
|
93
|
+
* another radio would land in a payee race that is already settled — which
|
|
94
|
+
* answers with a decline the payer would act on by releasing inputs the payee
|
|
95
|
+
* now holds a signed transaction for. Those failures go to the QR fountain.
|
|
96
|
+
*/
|
|
97
|
+
export function failedBeforeConnect(error: unknown): boolean {
|
|
98
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
99
|
+
return message.includes(NEVER_CONNECTED_MARKER)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* The radio to try after `failed` never connected, or null for "go to QR".
|
|
104
|
+
* Graceful degradation on iOS is AWDL (fastest, ~300 ms) → BLE → QR: AWDL can
|
|
105
|
+
* fail for reasons this device cannot see in advance (the peer's Wi-Fi radio,
|
|
106
|
+
* Local Network permission, the two phones on different Wi-Fi channels), and
|
|
107
|
+
* BLE is only offered when the payee minted CAP_BLE with its radio powered on.
|
|
108
|
+
* Only AWDL has a fallback rung — its native side is the one that proves a
|
|
109
|
+
* failure happened before `.ready` (see failedBeforeConnect).
|
|
110
|
+
*/
|
|
111
|
+
export function fallbackRadio(session: Session, failed: TransportKind): TransportKind | null {
|
|
112
|
+
if (failed === 'awdl' && (session.caps & CAP_BLE) !== 0 && localSupportsBle()) return 'ble'
|
|
113
|
+
return null
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* The payee's QR says, from a network probe that answered, that it was not on
|
|
118
|
+
* a Wi-Fi network when it made the code. Its AWDL bit can still be set then —
|
|
119
|
+
* Control Center's Wi-Fi toggle only disconnects, so the radio (and awdl0)
|
|
120
|
+
* stays up — but AWDL between phones off a network fails in practice and
|
|
121
|
+
* costs the payer the whole connect timeout before the next rung. So the
|
|
122
|
+
* payer does not try it. Unknown (no probe answer, or an older code with no
|
|
123
|
+
* hint bits) is not "off": the AWDL rung stays as it was.
|
|
124
|
+
*/
|
|
125
|
+
export function peerKnownOffWifi(session: Session): boolean {
|
|
126
|
+
const known = (session.caps & (HINT_ONLINE_KNOWN | HINT_NET)) !== 0
|
|
127
|
+
return known && (session.caps & HINT_WIFI) === 0
|
|
128
|
+
}
|
|
129
|
+
|
|
69
130
|
/** The GATT role THIS device takes as payer once the ladder chose 'ble'. */
|
|
70
131
|
export type BleRole = 'central' | 'peripheral'
|
|
71
132
|
|
package/core/localpay/verify.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { coverFromFrame, type CoverVerifier } from '../mandala/bundle'
|
|
|
6
6
|
import { PEERPAY_PROTOCOL_ID } from './pending'
|
|
7
7
|
import { isRequestableAmount } from './session'
|
|
8
8
|
import type { DeclineReason } from './types'
|
|
9
|
+
import { trimTrailingSlashes } from '../net/trimTrailingSlashes'
|
|
9
10
|
|
|
10
11
|
// mandala's FT derivation protocol — the payer locks token outputs under it
|
|
11
12
|
// with OUR payee-minted nonces as keyID, preserving the frame-to-session binding
|
|
@@ -323,7 +324,7 @@ function sameOverlay(
|
|
|
323
324
|
token: { overlayUrl: string; overlayIdentityKey: string },
|
|
324
325
|
asset: { overlayUrl: string; overlayIdentityKey: string }
|
|
325
326
|
): boolean {
|
|
326
|
-
const url = (u: string) => u.trim()
|
|
327
|
+
const url = (u: string) => trimTrailingSlashes(u.trim())
|
|
327
328
|
return (
|
|
328
329
|
token.overlayIdentityKey.toLowerCase() === asset.overlayIdentityKey.toLowerCase() &&
|
|
329
330
|
url(token.overlayUrl) === url(asset.overlayUrl)
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `s` without its trailing slashes ("https://host//" → "https://host").
|
|
3
|
+
*
|
|
4
|
+
* In place of `s.replace(/\/+$/, '')`: on a string with many slashes that
|
|
5
|
+
* aren't at its end, that regex backtracks from every one of them, quadratic
|
|
6
|
+
* in the input (CodeQL js/polynomial-redos). URLs reach these call sites
|
|
7
|
+
* from links, QR codes and other apps.
|
|
8
|
+
*/
|
|
9
|
+
export function trimTrailingSlashes(s: string): string {
|
|
10
|
+
let end = s.length
|
|
11
|
+
while (end > 0 && s.charCodeAt(end - 1) === 47 /* '/' */) end--
|
|
12
|
+
return end === s.length ? s : s.slice(0, end)
|
|
13
|
+
}
|
package/core/parsePeerPayURI.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { PublicKey } from '@bsv/sdk'
|
|
2
|
+
import { trimTrailingSlashes } from './net/trimTrailingSlashes'
|
|
2
3
|
|
|
3
4
|
/**
|
|
4
5
|
* BRC-125 PeerPay URI (https://bsv.brc.dev/payments/0125).
|
|
@@ -20,7 +21,21 @@ import { PublicKey } from '@bsv/sdk'
|
|
|
20
21
|
* is ignored, not fatal — a typo in the hint must not block a payment
|
|
21
22
|
* whose key is fine. Only https is accepted because the payer will
|
|
22
23
|
* authenticate against whatever host this names.
|
|
24
|
+
*
|
|
25
|
+
* And `note`: what the payment is for, as the payee wrote it, for the payer's
|
|
26
|
+
* wallet to start the payment's own note with. Shown as text only; trimmed,
|
|
27
|
+
* stripped of control characters and capped at PEERPAY_NOTE_MAX. A wallet
|
|
28
|
+
* that doesn't know it ignores it (BRC-125's extension rule).
|
|
23
29
|
*/
|
|
30
|
+
export const PEERPAY_NOTE_MAX = 120
|
|
31
|
+
|
|
32
|
+
/** A note as a link may carry it: plain, single-line text, or nothing. */
|
|
33
|
+
export function cleanPeerPayNote(raw: string | null | undefined): string | undefined {
|
|
34
|
+
// eslint-disable-next-line no-control-regex
|
|
35
|
+
const text = (raw ?? '').replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, ' ').replace(/\s+/g, ' ').trim()
|
|
36
|
+
return text ? Array.from(text).slice(0, PEERPAY_NOTE_MAX).join('') : undefined
|
|
37
|
+
}
|
|
38
|
+
|
|
24
39
|
export interface PeerPayParams {
|
|
25
40
|
identityKey: string
|
|
26
41
|
sats?: number
|
|
@@ -29,6 +44,8 @@ export interface PeerPayParams {
|
|
|
29
44
|
/** Base units of `asset`. Never present without it. */
|
|
30
45
|
amount?: number
|
|
31
46
|
messageBoxUrl?: string
|
|
47
|
+
/** What it's for, as the payee wrote it (the `note` extension). */
|
|
48
|
+
note?: string
|
|
32
49
|
}
|
|
33
50
|
|
|
34
51
|
export interface PeerPayValidationResult {
|
|
@@ -39,6 +56,8 @@ export interface PeerPayValidationResult {
|
|
|
39
56
|
amount?: number
|
|
40
57
|
/** Present only when the link carried a usable https `url` extension. */
|
|
41
58
|
messageBoxUrl?: string
|
|
59
|
+
/** Present only when the link carried a non-empty `note` extension. */
|
|
60
|
+
note?: string
|
|
42
61
|
errors: {
|
|
43
62
|
identityKey?: string
|
|
44
63
|
sats?: string
|
|
@@ -73,7 +92,8 @@ export function parsePeerPayURI(uri: string): PeerPayParams | null {
|
|
|
73
92
|
...(result.sats !== undefined ? { sats: result.sats } : {}),
|
|
74
93
|
...(result.asset !== undefined ? { asset: result.asset } : {}),
|
|
75
94
|
...(result.amount !== undefined ? { amount: result.amount } : {}),
|
|
76
|
-
...(result.messageBoxUrl ? { messageBoxUrl: result.messageBoxUrl } : {})
|
|
95
|
+
...(result.messageBoxUrl ? { messageBoxUrl: result.messageBoxUrl } : {}),
|
|
96
|
+
...(result.note ? { note: result.note } : {})
|
|
77
97
|
}
|
|
78
98
|
}
|
|
79
99
|
|
|
@@ -101,6 +121,7 @@ export function validatePeerPayURI(uri: string): PeerPayValidationResult {
|
|
|
101
121
|
let asset: string | undefined
|
|
102
122
|
let amount: number | undefined
|
|
103
123
|
let messageBoxUrl: string | undefined
|
|
124
|
+
let note: string | undefined
|
|
104
125
|
if (queryPart) {
|
|
105
126
|
const params = new URLSearchParams(queryPart)
|
|
106
127
|
if (params.has('sats')) {
|
|
@@ -123,8 +144,9 @@ export function validatePeerPayURI(uri: string): PeerPayValidationResult {
|
|
|
123
144
|
if (params.has('sats') && (params.has('asset') || params.has('amount'))) {
|
|
124
145
|
errors.sats = 'PeerPay link mixes sats with a token request'
|
|
125
146
|
}
|
|
126
|
-
const url = (params.get('url') ?? '').trim()
|
|
147
|
+
const url = trimTrailingSlashes((params.get('url') ?? '').trim())
|
|
127
148
|
if (url && MESSAGE_BOX_URL_REGEX.test(url)) messageBoxUrl = url
|
|
149
|
+
note = cleanPeerPayNote(params.get('note'))
|
|
128
150
|
}
|
|
129
151
|
|
|
130
152
|
return {
|
|
@@ -134,6 +156,7 @@ export function validatePeerPayURI(uri: string): PeerPayValidationResult {
|
|
|
134
156
|
...(asset !== undefined ? { asset } : {}),
|
|
135
157
|
...(amount !== undefined ? { amount } : {}),
|
|
136
158
|
...(messageBoxUrl ? { messageBoxUrl } : {}),
|
|
159
|
+
...(note ? { note } : {}),
|
|
137
160
|
errors
|
|
138
161
|
}
|
|
139
162
|
}
|
package/core/pay/creditInbox.ts
CHANGED
|
@@ -93,6 +93,36 @@ async function listRawInbox(
|
|
|
93
93
|
}
|
|
94
94
|
}
|
|
95
95
|
|
|
96
|
+
/**
|
|
97
|
+
* The sender's note, put back on each parsed payment. The MessageBox client
|
|
98
|
+
* rebuilds a token from the PaymentToken fields alone, so the `note` this
|
|
99
|
+
* app's sending side adds (see sendViaHandle) is dropped on the way in; the
|
|
100
|
+
* raw message still has it.
|
|
101
|
+
*/
|
|
102
|
+
export function withSenderNotes(
|
|
103
|
+
list: IncomingPayment[],
|
|
104
|
+
raw: { messageId: string; body: unknown }[]
|
|
105
|
+
): IncomingPayment[] {
|
|
106
|
+
const notes = new Map<string, string>()
|
|
107
|
+
for (const m of raw) {
|
|
108
|
+
let body = m.body
|
|
109
|
+
if (typeof body === 'string') {
|
|
110
|
+
try {
|
|
111
|
+
body = JSON.parse(body)
|
|
112
|
+
} catch {
|
|
113
|
+
continue
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
const note = body && typeof body === 'object' ? (body as { note?: unknown }).note : undefined
|
|
117
|
+
if (typeof note === 'string' && note.trim()) notes.set(String(m.messageId), note)
|
|
118
|
+
}
|
|
119
|
+
if (!notes.size) return list
|
|
120
|
+
return list.map(p => {
|
|
121
|
+
const note = notes.get(String(p.messageId))
|
|
122
|
+
return note && p.token && typeof p.token === 'object' ? { ...p, token: { ...p.token, note } as typeof p.token } : p
|
|
123
|
+
})
|
|
124
|
+
}
|
|
125
|
+
|
|
96
126
|
function attentionCountFor(
|
|
97
127
|
displayPayments: IncomingPayment[],
|
|
98
128
|
damaged: DamagedInboxMessage[],
|
|
@@ -117,8 +147,8 @@ async function runCreditInbox(args: {
|
|
|
117
147
|
accept: (payment: IncomingPayment) => Promise<void>
|
|
118
148
|
}): Promise<CreditInboxResult> {
|
|
119
149
|
const { client, messageBoxUrl, storage, force, classify, accept } = args
|
|
120
|
-
const list = await client.listIncomingPayments(messageBoxUrl)
|
|
121
150
|
const raw = await listRawInbox(client, messageBoxUrl)
|
|
151
|
+
const list = withSenderNotes(await client.listIncomingPayments(messageBoxUrl), raw)
|
|
122
152
|
const fromDiff = listDamagedInboxMessages({ raw, parsed: list })
|
|
123
153
|
const byId = new Map(fromDiff.map(d => [d.messageId, d]))
|
|
124
154
|
for (const p of list) {
|
|
@@ -535,8 +535,9 @@ export async function sendToAddress(args: {
|
|
|
535
535
|
{
|
|
536
536
|
// The recipient's address is the description so the activity list has a
|
|
537
537
|
// name for the row without a lookup; the to: label is what lets it draw
|
|
538
|
-
// a face. A sender's own note overrides it, same as the other rails
|
|
539
|
-
description
|
|
538
|
+
// a face. A sender's own note overrides it, same as the other rails,
|
|
539
|
+
// space-padded to the 5-byte minimum a description must have.
|
|
540
|
+
description: (note?.trim() || abbreviateKey(address)).padEnd(5),
|
|
540
541
|
outputs: [{ lockingScript, satoshis: sats, outputDescription: 'BSV for recipient address' }],
|
|
541
542
|
labels: ['legacy', 'outbound', addressLabel(TO_ADDRESS_LABEL_PREFIX, address)],
|
|
542
543
|
...(isSendMax ? { options: { randomizeOutputs: false } } : {})
|
package/core/pay/rails/handle.ts
CHANGED
|
@@ -21,9 +21,11 @@ import {
|
|
|
21
21
|
} from '../../peerpay/outbox'
|
|
22
22
|
import type { CreditFailureKind } from '../creditErrors'
|
|
23
23
|
import { abbreviateKey } from '../counterparty'
|
|
24
|
+
import { cleanPeerPayNote } from '../../parsePeerPayURI'
|
|
24
25
|
import { isDuplicateMessageError, sendControlMessage, type ResendReason } from '../../peerpay/control'
|
|
25
26
|
import { TaskDrainOutbox } from '../../monitor/TaskDrainOutbox'
|
|
26
27
|
import type { MandalaRuntime, TokenSendResult } from '../../mandala/runtime'
|
|
28
|
+
import { trimTrailingSlashes } from '../../net/trimTrailingSlashes'
|
|
27
29
|
|
|
28
30
|
export const MESSAGE_BOX_URL_KEY = 'message_box_url'
|
|
29
31
|
export const DEFAULT_MESSAGE_BOX_URL = 'https://messagebox.bsvblockchain.tech'
|
|
@@ -81,7 +83,9 @@ export function peerPayLinkFor(
|
|
|
81
83
|
identityKey: string,
|
|
82
84
|
sats?: number,
|
|
83
85
|
messageBoxUrl?: string,
|
|
84
|
-
token?: { assetId: string; baseUnits?: number }
|
|
86
|
+
token?: { assetId: string; baseUnits?: number },
|
|
87
|
+
/** what it's for: the link's `note` extension (see parsePeerPayURI.ts) */
|
|
88
|
+
note?: string
|
|
85
89
|
): string {
|
|
86
90
|
const params: string[] = []
|
|
87
91
|
if (token) {
|
|
@@ -92,8 +96,10 @@ export function peerPayLinkFor(
|
|
|
92
96
|
const amount = sats !== undefined ? Math.round(Number(sats)) : NaN
|
|
93
97
|
if (Number.isFinite(amount) && amount > 0) params.push(`sats=${amount}`)
|
|
94
98
|
}
|
|
95
|
-
const host = (messageBoxUrl ?? '').trim()
|
|
99
|
+
const host = trimTrailingSlashes((messageBoxUrl ?? '').trim())
|
|
96
100
|
if (host && host !== NO_MESSAGE_BOX) params.push(`url=${encodeURIComponent(host)}`)
|
|
101
|
+
const forWhat = cleanPeerPayNote(note)
|
|
102
|
+
if (forWhat) params.push(`note=${encodeURIComponent(forWhat)}`)
|
|
97
103
|
const base = `peerpay:${identityKey.toLowerCase()}`
|
|
98
104
|
return params.length ? `${base}?${params.join('&')}` : base
|
|
99
105
|
}
|
package/core/pay/rails/index.ts
CHANGED
|
@@ -30,7 +30,7 @@ export type RailId = 'nearby' | 'handle' | 'address'
|
|
|
30
30
|
*/
|
|
31
31
|
export type PayTarget =
|
|
32
32
|
| { kind: 'nearby'; session: Session }
|
|
33
|
-
| { kind: 'handle'; identityKey: string; sats?: number; asset?: string; amount?: number; messageBoxUrl?: string }
|
|
33
|
+
| { kind: 'handle'; identityKey: string; sats?: number; asset?: string; amount?: number; messageBoxUrl?: string; note?: string }
|
|
34
34
|
| { kind: 'address'; address: string; sats?: number; network?: 'main' | 'test' }
|
|
35
35
|
|
|
36
36
|
/** Six cell names. Since the universal input, `pay-*` are deep-link aliases that all open the send form; `get-*` open one receive method directly. */
|
|
@@ -131,7 +131,7 @@ export type RecipientInput =
|
|
|
131
131
|
| { kind: 'empty' }
|
|
132
132
|
| { kind: 'address'; address: string; network?: 'main' | 'test' }
|
|
133
133
|
| { kind: 'invalid_address' }
|
|
134
|
-
| { kind: 'handle'; identityKey: string; sats?: number; asset?: string; amount?: number; messageBoxUrl?: string }
|
|
134
|
+
| { kind: 'handle'; identityKey: string; sats?: number; asset?: string; amount?: number; messageBoxUrl?: string; note?: string }
|
|
135
135
|
| { kind: 'invalid_link'; message: string }
|
|
136
136
|
| { kind: 'search'; query: string }
|
|
137
137
|
|
|
@@ -153,7 +153,8 @@ function handleFromPeerPay(result: PeerPayValidationResult): RecipientInput {
|
|
|
153
153
|
...(result.sats !== undefined ? { sats: result.sats } : {}),
|
|
154
154
|
...(result.asset !== undefined ? { asset: result.asset } : {}),
|
|
155
155
|
...(result.amount !== undefined ? { amount: result.amount } : {}),
|
|
156
|
-
...(result.messageBoxUrl ? { messageBoxUrl: result.messageBoxUrl } : {})
|
|
156
|
+
...(result.messageBoxUrl ? { messageBoxUrl: result.messageBoxUrl } : {}),
|
|
157
|
+
...(result.note ? { note: result.note } : {})
|
|
157
158
|
}
|
|
158
159
|
}
|
|
159
160
|
|
|
@@ -203,7 +204,8 @@ export function classifyScan(raw: string): PayTarget | null {
|
|
|
203
204
|
...(result.sats !== undefined ? { sats: result.sats } : {}),
|
|
204
205
|
...(result.asset !== undefined ? { asset: result.asset } : {}),
|
|
205
206
|
...(result.amount !== undefined ? { amount: result.amount } : {}),
|
|
206
|
-
...(result.messageBoxUrl ? { messageBoxUrl: result.messageBoxUrl } : {})
|
|
207
|
+
...(result.messageBoxUrl ? { messageBoxUrl: result.messageBoxUrl } : {}),
|
|
208
|
+
...(result.note ? { note: result.note } : {})
|
|
207
209
|
}
|
|
208
210
|
}
|
|
209
211
|
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { ProtoWallet, PublicKey, Random, type WalletInterface } from '@bsv/sdk'
|
|
2
|
+
import { decodeSession, type Session } from '../localpay/session'
|
|
3
|
+
|
|
4
|
+
export const POS_PROTOCOL: [2, string] = [2, 'bsv pos authorization']
|
|
5
|
+
export const POS_PREFIX = 'bsvpos1:'
|
|
6
|
+
export type Signer = Pick<WalletInterface, 'getPublicKey' | 'createSignature'>
|
|
7
|
+
export interface Signed<T> {
|
|
8
|
+
payload: T
|
|
9
|
+
identityKey: string
|
|
10
|
+
signature: number[]
|
|
11
|
+
}
|
|
12
|
+
export interface Invite {
|
|
13
|
+
kind: 'invite'
|
|
14
|
+
merchant: string
|
|
15
|
+
name: string
|
|
16
|
+
service: string
|
|
17
|
+
chain: string
|
|
18
|
+
id: string
|
|
19
|
+
expires: number
|
|
20
|
+
}
|
|
21
|
+
export interface MerchantRequest {
|
|
22
|
+
kind: 'payment'
|
|
23
|
+
merchant: string
|
|
24
|
+
name: string
|
|
25
|
+
cashier: string
|
|
26
|
+
invoice: string
|
|
27
|
+
chain: string
|
|
28
|
+
expires: number
|
|
29
|
+
session: string
|
|
30
|
+
subtotal?: number
|
|
31
|
+
tip?: number
|
|
32
|
+
}
|
|
33
|
+
export interface Rpc {
|
|
34
|
+
version: 1
|
|
35
|
+
method: string
|
|
36
|
+
nonce: string
|
|
37
|
+
time: number
|
|
38
|
+
body: Record<string, unknown>
|
|
39
|
+
}
|
|
40
|
+
export interface Receipt {
|
|
41
|
+
invoice: string
|
|
42
|
+
txid: string
|
|
43
|
+
amount: number
|
|
44
|
+
status: 'accepted'
|
|
45
|
+
}
|
|
46
|
+
export function randomId(): string {
|
|
47
|
+
return Array.from(Random(16), b => b.toString(16).padStart(2, '0')).join('')
|
|
48
|
+
}
|
|
49
|
+
export function key(value: unknown): string {
|
|
50
|
+
if (typeof value !== 'string' || !/^(02|03)[0-9a-f]{64}$/i.test(value)) throw new Error('Invalid identity')
|
|
51
|
+
PublicKey.fromString(value)
|
|
52
|
+
return value.toLowerCase()
|
|
53
|
+
}
|
|
54
|
+
export function serviceUrl(value: unknown): string {
|
|
55
|
+
if (typeof value !== 'string') throw new Error('Invalid service address')
|
|
56
|
+
const url = new URL(value)
|
|
57
|
+
if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash)
|
|
58
|
+
throw new Error('Use an HTTPS merchant service address')
|
|
59
|
+
return url.toString().replace(/\/$/, '')
|
|
60
|
+
}
|
|
61
|
+
/** Sorted JSON fields and consistent Unicode separators across Go and JS. */
|
|
62
|
+
export function bytes(payload: unknown): number[] {
|
|
63
|
+
const ordered = (v: unknown): unknown =>
|
|
64
|
+
Array.isArray(v)
|
|
65
|
+
? v.map(ordered)
|
|
66
|
+
: v !== null && typeof v === 'object'
|
|
67
|
+
? Object.fromEntries(
|
|
68
|
+
Object.keys(v)
|
|
69
|
+
.sort()
|
|
70
|
+
.map(k => [k, ordered((v as Record<string, unknown>)[k])])
|
|
71
|
+
)
|
|
72
|
+
: v
|
|
73
|
+
const text = JSON.stringify(ordered(payload))
|
|
74
|
+
.replace(/\u2028/g, '\\u2028')
|
|
75
|
+
.replace(/\u2029/g, '\\u2029')
|
|
76
|
+
return Array.from(new TextEncoder().encode(text))
|
|
77
|
+
}
|
|
78
|
+
export async function sign<T>(wallet: Signer, payload: T, originator?: string): Promise<Signed<T>> {
|
|
79
|
+
const { publicKey } = await wallet.getPublicKey({ identityKey: true }, originator)
|
|
80
|
+
const { signature } = await wallet.createSignature(
|
|
81
|
+
{ protocolID: POS_PROTOCOL, keyID: 'v1', counterparty: 'anyone', data: bytes(payload) },
|
|
82
|
+
originator
|
|
83
|
+
)
|
|
84
|
+
return { payload, identityKey: key(publicKey), signature }
|
|
85
|
+
}
|
|
86
|
+
export async function verify<T>(value: Signed<T>, expected?: string): Promise<T> {
|
|
87
|
+
if (
|
|
88
|
+
!value ||
|
|
89
|
+
typeof value !== 'object' ||
|
|
90
|
+
!Array.isArray(value.signature) ||
|
|
91
|
+
value.signature.length > 80 ||
|
|
92
|
+
!value.signature.every(b => Number.isInteger(b) && b >= 0 && b <= 255)
|
|
93
|
+
)
|
|
94
|
+
throw new Error('Invalid merchant authorization')
|
|
95
|
+
const identity = key(value.identityKey)
|
|
96
|
+
if (expected && identity !== key(expected)) throw new Error('Merchant identity does not match')
|
|
97
|
+
const result = await new ProtoWallet('anyone').verifySignature({
|
|
98
|
+
protocolID: POS_PROTOCOL,
|
|
99
|
+
keyID: 'v1',
|
|
100
|
+
counterparty: identity,
|
|
101
|
+
data: bytes(value.payload),
|
|
102
|
+
signature: value.signature
|
|
103
|
+
})
|
|
104
|
+
if (!result.valid) throw new Error('Invalid merchant signature')
|
|
105
|
+
return value.payload
|
|
106
|
+
}
|
|
107
|
+
export function encodePos(value: Signed<Invite | MerchantRequest>): string {
|
|
108
|
+
return (
|
|
109
|
+
POS_PREFIX +
|
|
110
|
+
globalThis
|
|
111
|
+
.btoa(unescape(encodeURIComponent(JSON.stringify(value))))
|
|
112
|
+
.replace(/\+/g, '-')
|
|
113
|
+
.replace(/\//g, '_')
|
|
114
|
+
.replace(/=+$/, '')
|
|
115
|
+
)
|
|
116
|
+
}
|
|
117
|
+
export async function decodePos(text: string): Promise<Signed<Invite | MerchantRequest>> {
|
|
118
|
+
if (!text.startsWith(POS_PREFIX) || text.length > 12000) throw new Error('Invalid point-of-sale code')
|
|
119
|
+
const raw = text.slice(POS_PREFIX.length).replace(/-/g, '+').replace(/_/g, '/')
|
|
120
|
+
const value = JSON.parse(
|
|
121
|
+
decodeURIComponent(escape(globalThis.atob(raw + '='.repeat((4 - (raw.length % 4)) % 4))))
|
|
122
|
+
) as Signed<Invite | MerchantRequest>
|
|
123
|
+
const p = await verify(value)
|
|
124
|
+
if (
|
|
125
|
+
!p ||
|
|
126
|
+
!['invite', 'payment'].includes(p.kind) ||
|
|
127
|
+
key(p.merchant) !== key(value.identityKey) ||
|
|
128
|
+
typeof p.name !== 'string' ||
|
|
129
|
+
!p.name.trim() ||
|
|
130
|
+
p.name.length > 80 ||
|
|
131
|
+
!Number.isSafeInteger(p.expires) ||
|
|
132
|
+
p.expires <= Date.now() ||
|
|
133
|
+
!['main', 'test', 'teratest'].includes(p.chain)
|
|
134
|
+
)
|
|
135
|
+
throw new Error('Expired or invalid merchant code')
|
|
136
|
+
if (p.kind === 'invite') {
|
|
137
|
+
serviceUrl(p.service)
|
|
138
|
+
if (typeof p.id !== 'string' || !/^[a-f0-9]{32}$/.test(p.id)) throw new Error('Invalid enrollment code')
|
|
139
|
+
} else {
|
|
140
|
+
key(p.cashier)
|
|
141
|
+
if (typeof p.invoice !== 'string' || !/^[a-f0-9]{32}$/.test(p.invoice)) throw new Error('Invalid invoice')
|
|
142
|
+
const session = decodeSession(p.session)
|
|
143
|
+
if (key(session.identityKey) !== key(p.merchant) || !session.amount || session.asset)
|
|
144
|
+
throw new Error('Merchant request has an invalid destination')
|
|
145
|
+
if (p.subtotal !== undefined || p.tip !== undefined) {
|
|
146
|
+
const tip = p.tip ?? 0
|
|
147
|
+
if (
|
|
148
|
+
!Number.isSafeInteger(p.subtotal) ||
|
|
149
|
+
p.subtotal! < 1 ||
|
|
150
|
+
!Number.isSafeInteger(tip) ||
|
|
151
|
+
tip < 0 ||
|
|
152
|
+
tip > session.amount ||
|
|
153
|
+
p.subtotal !== session.amount - tip
|
|
154
|
+
)
|
|
155
|
+
throw new Error('Merchant request has an invalid tip breakdown')
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return value
|
|
159
|
+
}
|
|
160
|
+
export async function decodePaymentRequest(text: string): Promise<Session> {
|
|
161
|
+
if (!text.startsWith(POS_PREFIX)) return decodeSession(text)
|
|
162
|
+
const { payload } = await decodePos(text)
|
|
163
|
+
if (payload.kind !== 'payment') throw new Error('This code enrolls a cashier; it is not a payment request')
|
|
164
|
+
return {
|
|
165
|
+
...decodeSession(payload.session),
|
|
166
|
+
merchantName: payload.name,
|
|
167
|
+
merchantChain: payload.chain,
|
|
168
|
+
merchantExpires: payload.expires,
|
|
169
|
+
merchantSubtotal: payload.subtotal,
|
|
170
|
+
merchantTip: payload.tip
|
|
171
|
+
}
|
|
172
|
+
}
|