@bsv/expo-wallet-toolbox 0.26.0 → 0.27.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
@@ -2,6 +2,33 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.27.0
6
+
7
+ Paymail send. No native change: hosts do not rebuild.
8
+
9
+ ### Breaking / host action
10
+
11
+ - **A host that supplies its own `RegistryResolver` must add `discoverCapabilities`.** `createRegistryResolver` already has it.
12
+ - **A host that reads outbox rows must handle the `OutboxEntry` union.** Use `isPaymailEntry` to tell a `paymail` row from a PeerPay row.
13
+
14
+ ### Added
15
+
16
+ - **`classifyPaymailDomain` and `classifyPaymailDomainDetailed`.** They read a domain's capability map and return `peerpay`, `legacy`, `unsupported` or `failed`.
17
+ - **`sendViaPaymail`.** It pays a `legacy` paymail (for example HandCash) with BSV. It mints with `noSend`, writes an outbox row, posts the plain BEEF, then broadcasts. It throws `PaymailSendError`.
18
+ - **The `paymail` outbox kind**, with retry, cancel and drain.
19
+ - **`RegistryResolver.discoverCapabilities`.** It returns the raw capability map from the same cached and DNSSEC-checked discovery.
20
+ - **`createLegacyPaymailClient`, `statusFnFromStorage` and `abortNosendByTxid`.**
21
+
22
+ ### Changed
23
+
24
+ - **`abortPeerPayNosend` now calls the new `abortNosendByTxid`.**
25
+ - **`isAbortSafe` also guards `paymail` actions.**
26
+ - **An outgoing `paymail` action reads as sent, not spent.**
27
+
28
+ ### Not added
29
+
30
+ - **No `@bsv/paymail` dependency.** The toolbox has its own small client on the bounded fetch.
31
+
5
32
  ## 0.26.0
6
33
 
7
34
  The BSV Wallet app's launch changes, upstreamed from its patch of 0.25.1: one key tap for a Vault spend, a key removal that can finish, a monthly limit for group spending grants, and a new icon set. No native change: hosts do not rebuild.
@@ -284,7 +284,11 @@ import {
284
284
  readMessageBoxUrl,
285
285
  retryDelivery
286
286
  } from '../pay/rails/handle'
287
- import { getOutboxEntries, pruneExpiredSent, unsentEntries } from '../peerpay/outbox'
287
+ import { getOutboxEntries, isPaymailEntry, isPeerPayEntry, pruneExpiredSent, unsentEntries } from '../peerpay/outbox'
288
+ import { retryPaymailDelivery } from '../pay/rails/paymail'
289
+ import { createLegacyPaymailClient } from '../pay/paymail/client'
290
+ import { statusFnFromStorage } from '../pay/paymail/networkCheck'
291
+ import { createRegistryResolver } from '../identity/handleRegistry/resolver'
288
292
  import { MAX_HEX_RESPONSE_CHARS, wocConfigFor } from '../pay/rails/address'
289
293
  import { PeerPayClient } from '@bsv/message-box-client'
290
294
  import {
@@ -2422,6 +2426,8 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2422
2426
  )
2423
2427
  TaskCreditInbox.noteEnqueued()
2424
2428
 
2429
+ // One resolver per wallet build, for the paymail rail's discovery.
2430
+ const paymailResolver = createRegistryResolver({ pinned: getHandleRegistryConfig(chain) })
2425
2431
  monitor.addTask(
2426
2432
  new TaskDrainOutbox(
2427
2433
  monitor,
@@ -2429,7 +2435,20 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2429
2435
  const entries = unsentEntries(await getOutboxEntries(phoneStorage!))
2430
2436
  return drainUnsentEntries({
2431
2437
  entries,
2438
+ isolate: isPaymailEntry,
2432
2439
  retry: async entry => {
2440
+ if (isPaymailEntry(entry)) {
2441
+ await retryPaymailDelivery({
2442
+ wallet: permissionsManager as never,
2443
+ adminOriginator,
2444
+ storage: phoneStorage!,
2445
+ client: createLegacyPaymailClient({ resolver: paymailResolver }),
2446
+ getStatusForTxids: statusFnFromStorage(phoneStorage!),
2447
+ entry
2448
+ })
2449
+ return
2450
+ }
2451
+ if (!isPeerPayEntry(entry)) return
2433
2452
  const client = bindMessageBoxNetwork(
2434
2453
  new PeerPayClient({
2435
2454
  messageBoxHost: entry.messageBoxUrl,
@@ -708,6 +708,8 @@ const resources = {
708
708
  review_imported_payment: 'Review imported payment',
709
709
  review_imported_payment_detail:
710
710
  'This payment came from a backup and may have been canceled. Send {{amount}} satoshis to {{recipient}} now?',
711
+ review_imported_paymail_detail:
712
+ 'This payment came from a backup and may have been canceled. It is listed as {{amount}} satoshis to {{recipient}}, but the app cannot check that the signed transaction pays that recipient or that amount. Send it anyway?',
711
713
  payment_not_delivered: 'Not delivered',
712
714
  payment_delivered: 'Delivered',
713
715
  retry: 'Retry',
@@ -1914,6 +1916,8 @@ const resources = {
1914
1916
  outgoing_payments: '已发出',
1915
1917
  review_imported_payment: '审核导入的付款',
1916
1918
  review_imported_payment_detail: '此付款来自备份,可能已被取消。现在向 {{recipient}} 发送 {{amount}} 聪吗?',
1919
+ review_imported_paymail_detail:
1920
+ '此付款来自备份,可能已被取消。它显示为向 {{recipient}} 发送 {{amount}} 聪,但应用无法核实已签名的交易是否支付给该收款人或该金额。仍要发送吗?',
1917
1921
  payment_not_delivered: '未送达',
1918
1922
  payment_delivered: '已送达',
1919
1923
  retry: '重试',
@@ -3132,6 +3136,8 @@ const resources = {
3132
3136
  review_imported_payment: 'आयातित भुगतान की समीक्षा करें',
3133
3137
  review_imported_payment_detail:
3134
3138
  'यह भुगतान बैकअप से आया है और संभव है कि इसे रद्द कर दिया गया हो। क्या अभी {{recipient}} को {{amount}} सातोशी भेजें?',
3139
+ review_imported_paymail_detail:
3140
+ 'यह भुगतान बैकअप से आया है और संभव है कि इसे रद्द कर दिया गया हो। इसमें {{recipient}} को {{amount}} सातोशी दिखाए गए हैं, लेकिन ऐप जाँच नहीं सकता कि हस्ताक्षरित लेन-देन उसी प्राप्तकर्ता को या उसी राशि का भुगतान करता है। फिर भी भेजें?',
3135
3141
  payment_not_delivered: 'डिलीवर नहीं हुआ',
3136
3142
  payment_delivered: 'डिलीवर हो गया',
3137
3143
  retry: 'पुनः प्रयास',
@@ -4394,6 +4400,8 @@ const resources = {
4394
4400
  review_imported_payment: 'Revisar pago importado',
4395
4401
  review_imported_payment_detail:
4396
4402
  'Este pago procede de una copia de seguridad y puede haberse cancelado. ¿Enviar ahora {{amount}} satoshis a {{recipient}}?',
4403
+ review_imported_paymail_detail:
4404
+ 'Este pago procede de una copia de seguridad y puede haberse cancelado. Figura como {{amount}} satoshis para {{recipient}}, pero la app no puede comprobar que la transacción firmada pague a ese destinatario ni esa cantidad. ¿Enviar de todos modos?',
4397
4405
  payment_not_delivered: 'No entregado',
4398
4406
  payment_delivered: 'Entregado',
4399
4407
  retry: 'Reintentar',
@@ -5675,6 +5683,8 @@ const resources = {
5675
5683
  review_imported_payment: 'Vérifier le paiement importé',
5676
5684
  review_imported_payment_detail:
5677
5685
  'Ce paiement provient d’une sauvegarde et a peut-être été annulé. Envoyer maintenant {{amount}} satoshis à {{recipient}} ?',
5686
+ review_imported_paymail_detail:
5687
+ 'Ce paiement provient d’une sauvegarde et a peut-être été annulé. Il est indiqué comme {{amount}} satoshis pour {{recipient}}, mais l’application ne peut pas vérifier que la transaction signée paie ce destinataire ni ce montant. Envoyer quand même ?',
5678
5688
  payment_not_delivered: 'Non livré',
5679
5689
  payment_delivered: 'Livré',
5680
5690
  retry: 'Réessayer',
@@ -6918,6 +6928,8 @@ const resources = {
6918
6928
  review_imported_payment: 'مراجعة الدفعة المستوردة',
6919
6929
  review_imported_payment_detail:
6920
6930
  'جاءت هذه الدفعة من نسخة احتياطية وربما أُلغيت. هل تريد إرسال {{amount}} ساتوشي إلى {{recipient}} الآن؟',
6931
+ review_imported_paymail_detail:
6932
+ 'جاءت هذه الدفعة من نسخة احتياطية وربما أُلغيت. هي مدرجة بمبلغ {{amount}} ساتوشي إلى {{recipient}}، لكن التطبيق لا يستطيع التحقق من أن المعاملة الموقعة تدفع لهذا المستلم أو بهذا المبلغ. هل تريد الإرسال على أي حال؟',
6921
6933
  payment_not_delivered: 'لم يتم التسليم',
6922
6934
  payment_delivered: 'تم التسليم',
6923
6935
  retry: 'إعادة المحاولة',
@@ -8160,6 +8172,8 @@ const resources = {
8160
8172
  review_imported_payment: 'Rever pagamento importado',
8161
8173
  review_imported_payment_detail:
8162
8174
  'Este pagamento veio de uma cópia de segurança e pode ter sido cancelado. Enviar agora {{amount}} satoshis para {{recipient}}?',
8175
+ review_imported_paymail_detail:
8176
+ 'Este pagamento veio de uma cópia de segurança e pode ter sido cancelado. Consta como {{amount}} satoshis para {{recipient}}, mas a app não consegue confirmar que a transação assinada paga a esse destinatário nem esse valor. Enviar mesmo assim?',
8163
8177
  payment_not_delivered: 'Não entregue',
8164
8178
  payment_delivered: 'Entregue',
8165
8179
  retry: 'Tentar novamente',
@@ -9415,6 +9429,8 @@ const resources = {
9415
9429
  review_imported_payment: 'আমদানি করা পেমেন্ট যাচাই করুন',
9416
9430
  review_imported_payment_detail:
9417
9431
  'এই পেমেন্টটি ব্যাকআপ থেকে এসেছে এবং হয়তো বাতিল করা হয়েছে। এখন {{recipient}}-কে {{amount}} সাতোশি পাঠাবেন?',
9432
+ review_imported_paymail_detail:
9433
+ 'এই পেমেন্টটি ব্যাকআপ থেকে এসেছে এবং হয়তো বাতিল করা হয়েছে। এটি {{recipient}}-কে {{amount}} সাতোশি হিসেবে দেখানো আছে, কিন্তু স্বাক্ষরিত লেনদেন সেই প্রাপককে বা সেই পরিমাণ দেয় কি না, অ্যাপ তা যাচাই করতে পারে না। তবুও পাঠাবেন?',
9418
9434
  payment_not_delivered: 'ডেলিভারি হয়নি',
9419
9435
  payment_delivered: 'ডেলিভারি হয়েছে',
9420
9436
  retry: 'পুনরায় চেষ্টা',
@@ -10672,6 +10688,8 @@ const resources = {
10672
10688
  review_imported_payment: 'Проверить импортированный платёж',
10673
10689
  review_imported_payment_detail:
10674
10690
  'Этот платёж восстановлен из резервной копии и мог быть отменён. Отправить сейчас {{amount}} сатоши получателю {{recipient}}?',
10691
+ review_imported_paymail_detail:
10692
+ 'Этот платёж восстановлен из резервной копии и мог быть отменён. Он указан как {{amount}} сатоши получателю {{recipient}}, но приложение не может проверить, что подписанная транзакция платит этому получателю или эту сумму. Всё равно отправить?',
10675
10693
  payment_not_delivered: 'Не доставлено',
10676
10694
  payment_delivered: 'Доставлено',
10677
10695
  retry: 'Повторить',
@@ -11935,6 +11953,8 @@ const resources = {
11935
11953
  review_imported_payment: 'Tinjau pembayaran yang diimpor',
11936
11954
  review_imported_payment_detail:
11937
11955
  'Pembayaran ini berasal dari cadangan dan mungkin telah dibatalkan. Kirim {{amount}} satoshi ke {{recipient}} sekarang?',
11956
+ review_imported_paymail_detail:
11957
+ 'Pembayaran ini berasal dari cadangan dan mungkin telah dibatalkan. Tercatat {{amount}} satoshi untuk {{recipient}}, tetapi aplikasi tidak dapat memeriksa bahwa transaksi yang ditandatangani membayar penerima atau jumlah itu. Tetap kirim?',
11938
11958
  payment_not_delivered: 'Belum terkirim',
11939
11959
  payment_delivered: 'Terkirim',
11940
11960
  retry: 'Coba lagi',
@@ -13201,6 +13221,8 @@ const resources = {
13201
13221
  review_imported_payment: 'インポートした支払いを確認',
13202
13222
  review_imported_payment_detail:
13203
13223
  'この支払いはバックアップから復元されたもので、キャンセル済みの可能性があります。今すぐ {{recipient}} に {{amount}} サトシを送信しますか?',
13224
+ review_imported_paymail_detail:
13225
+ 'この支払いはバックアップから復元されたもので、キャンセル済みの可能性があります。{{recipient}} 宛て {{amount}} サトシと表示されていますが、署名済みの取引がその受取人やその金額に支払うものかどうか、アプリでは確認できません。それでも送信しますか?',
13204
13226
  payment_not_delivered: '未配信',
13205
13227
  payment_delivered: '配信済み',
13206
13228
  retry: '再試行',
@@ -14473,6 +14495,8 @@ const resources = {
14473
14495
  review_imported_payment: 'Sprawdź zaimportowaną płatność',
14474
14496
  review_imported_payment_detail:
14475
14497
  'Ta płatność pochodzi z kopii zapasowej i mogła zostać anulowana. Wysłać teraz {{amount}} satoshi do {{recipient}}?',
14498
+ review_imported_paymail_detail:
14499
+ 'Ta płatność pochodzi z kopii zapasowej i mogła zostać anulowana. Jest wpisana jako {{amount}} satoshi dla {{recipient}}, ale aplikacja nie może sprawdzić, czy podpisana transakcja płaci temu odbiorcy ani tę kwotę. Wysłać mimo to?',
14476
14500
  payment_not_delivered: 'Nie dostarczono',
14477
14501
  payment_delivered: 'Dostarczono',
14478
14502
  retry: 'Ponów',
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Classify a paymail domain by its capability map.
3
+ *
4
+ * `peerpay`: the domain runs the profile lookup (`0ace65da5987`), so it is a
5
+ * MessageBox registry. `legacy`: it serves the paymail P2P pair that HandCash
6
+ * serves, so it can be paid by `sendViaPaymail`. `unsupported`: the document
7
+ * loaded and has neither, or the SRV answer was not authenticated. `failed`:
8
+ * DNS or HTTP gave no answer.
9
+ */
10
+ import { isPublicHttpsUrl } from '../../net/publicDestination'
11
+ import { BRFC_LOOKUP, BRFC_P2P_DESTINATION, BRFC_P2P_RECEIVE_BEEF, looksLikeDomain } from './rules'
12
+ import type { RegistryResolver } from './resolver'
13
+
14
+ export type PaymailClass = 'peerpay' | 'legacy' | 'unsupported' | 'failed'
15
+ export type UnsupportedReason = 'unsecured' | 'no_capabilities'
16
+ export interface PaymailClassification {
17
+ kind: PaymailClass
18
+ /** Only when `kind` is `unsupported`. */
19
+ reason?: UnsupportedReason
20
+ }
21
+ export interface ClassifyArgs {
22
+ resolver: Pick<RegistryResolver, 'discoverCapabilities'>
23
+ ownDomains: readonly string[]
24
+ }
25
+
26
+ const LEGACY_PLACEHOLDERS = ['{alias}', '{domain.tld}'] as const
27
+
28
+ /**
29
+ * A string that starts with `https://`, holds every placeholder, has none in
30
+ * the authority (a placeholder in the host would let user input choose the
31
+ * host), and passes `isPublicHttpsUrl`.
32
+ */
33
+ export function isLegacyCapabilityUrl(value: unknown, placeholders: readonly string[]): value is string {
34
+ if (typeof value !== 'string' || !value.startsWith('https://')) return false
35
+ if (!placeholders.every(p => value.includes(p))) return false
36
+ const rest = value.slice('https://'.length)
37
+ const end = rest.search(/[/?#]/)
38
+ const authority = end === -1 ? rest : rest.slice(0, end)
39
+ if (placeholders.some(p => authority.includes(p))) return false
40
+ return isPublicHttpsUrl(value)
41
+ }
42
+
43
+ export async function classifyPaymailDomainDetailed(
44
+ args: ClassifyArgs,
45
+ domain: string
46
+ ): Promise<PaymailClassification> {
47
+ const d = domain.trim().toLowerCase()
48
+ if (args.ownDomains.some(own => own.toLowerCase() === d)) return { kind: 'peerpay' }
49
+ if (!looksLikeDomain(d)) return { kind: 'unsupported', reason: 'no_capabilities' }
50
+ const found = await args.resolver.discoverCapabilities(d)
51
+ switch (found.kind) {
52
+ case 'failed':
53
+ return { kind: 'failed' }
54
+ case 'unsecured':
55
+ return { kind: 'unsupported', reason: 'unsecured' }
56
+ case 'none':
57
+ return { kind: 'unsupported', reason: 'no_capabilities' }
58
+ case 'ok': {
59
+ const caps = found.capabilities
60
+ if (typeof caps[BRFC_LOOKUP] === 'string') return { kind: 'peerpay' }
61
+ if (
62
+ isLegacyCapabilityUrl(caps[BRFC_P2P_DESTINATION], LEGACY_PLACEHOLDERS) &&
63
+ isLegacyCapabilityUrl(caps[BRFC_P2P_RECEIVE_BEEF], LEGACY_PLACEHOLDERS)
64
+ ) {
65
+ return { kind: 'legacy' }
66
+ }
67
+ return { kind: 'unsupported', reason: 'no_capabilities' }
68
+ }
69
+ }
70
+ }
71
+
72
+ export async function classifyPaymailDomain(args: ClassifyArgs, domain: string): Promise<PaymailClass> {
73
+ return (await classifyPaymailDomainDetailed(args, domain)).kind
74
+ }
@@ -31,10 +31,19 @@ export interface RegistryEndpoints {
31
31
  readonly pinned: boolean
32
32
  }
33
33
 
34
+ /** What discovery found for a domain, before anyone decides what it means. */
35
+ export type CapabilityDiscovery =
36
+ | { kind: 'ok'; domain: string; origin: string; capabilities: Readonly<Record<string, unknown>> }
37
+ | { kind: 'unsecured' } // SRV not authenticated, or SRV target not a public https origin
38
+ | { kind: 'none' } // answered, but not a usable capability document (HTTP 4xx, not an object)
39
+ | { kind: 'failed' } // DNS or HTTP gave no answer (throw, timeout, 5xx)
40
+
34
41
  export interface RegistryResolver {
35
42
  resolve(domain: string): Promise<RegistryEndpoints | null>
43
+ /** The raw capability map from the same cached, DNSSEC-checked discovery. */
44
+ discoverCapabilities(domain: string): Promise<CapabilityDiscovery>
36
45
  /** Test seam, and the way a "try again" control forgets a failed lookup. */
37
- clearCache(): void
46
+ clearCache(domain?: string): void
38
47
  }
39
48
 
40
49
  export const REGISTRY_TIMEOUT_MS = 8000
@@ -106,7 +115,12 @@ async function readBoundedJson(res: Response, fallback: () => Promise<unknown>,
106
115
  * single stalled body would wedge every later write for the life of the
107
116
  * process, with no toast and no timeout.
108
117
  */
109
- export async function fetchWithTimeout(fetchImpl: typeof fetch, url: string, init?: RequestInit): Promise<Response> {
118
+ export async function fetchWithTimeout(
119
+ fetchImpl: typeof fetch,
120
+ url: string,
121
+ init?: RequestInit,
122
+ timeoutMs: number = REGISTRY_TIMEOUT_MS
123
+ ): Promise<Response> {
110
124
  const controller = new AbortController()
111
125
  const caller = init?.signal ?? null
112
126
  const onAbort = () => controller.abort(caller?.reason)
@@ -114,7 +128,7 @@ export async function fetchWithTimeout(fetchImpl: typeof fetch, url: string, ini
114
128
  caller?.addEventListener('abort', onAbort)
115
129
  const release = () => caller?.removeEventListener('abort', onAbort)
116
130
  const startedAt = Date.now()
117
- const timer = setTimeout(() => controller.abort(), REGISTRY_TIMEOUT_MS)
131
+ const timer = setTimeout(() => controller.abort(), timeoutMs)
118
132
  let response: Response
119
133
  try {
120
134
  response = await fetchImpl(url, { ...init, signal: controller.signal })
@@ -141,9 +155,9 @@ export async function fetchWithTimeout(fetchImpl: typeof fetch, url: string, ini
141
155
  bodyTimer = setTimeout(
142
156
  () => {
143
157
  controller.abort()
144
- reject(new Error(`handleRegistry: no body from ${url} after ${REGISTRY_TIMEOUT_MS}ms`))
158
+ reject(new Error(`handleRegistry: no body from ${url} after ${timeoutMs}ms`))
145
159
  },
146
- Math.max(0, REGISTRY_TIMEOUT_MS - (Date.now() - startedAt))
160
+ Math.max(0, timeoutMs - (Date.now() - startedAt))
147
161
  )
148
162
  void readBoundedJson(response, fallback, url).then(resolve, reject)
149
163
  })
@@ -202,6 +216,10 @@ function templateOf(value: unknown, placeholder: string): string | null {
202
216
  return isPublicHttpsUrl(value) ? value : null
203
217
  }
204
218
 
219
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
220
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
221
+ }
222
+
205
223
  export function createRegistryResolver(args: {
206
224
  pinned?: RegistryPin
207
225
  /** Trusted test transport; production must retain the native byte ceiling. */
@@ -214,7 +232,7 @@ export function createRegistryResolver(args: {
214
232
  const dohEndpoints = args.dohEndpoints ?? DOH_ENDPOINTS
215
233
  const pinnedDomain = args.pinned?.domain.trim().toLowerCase() ?? ''
216
234
  const pinnedOrigin = trimTrailingSlashes(args.pinned?.url.trim() ?? '')
217
- const cache = new Map<string, { at: number; value: RegistryEndpoints | null }>()
235
+ const cache = new Map<string, { at: number; value: CapabilityDiscovery }>()
218
236
 
219
237
  const pinnedEndpoints: RegistryEndpoints | null =
220
238
  pinnedDomain !== '' && pinnedOrigin !== ''
@@ -235,7 +253,7 @@ export function createRegistryResolver(args: {
235
253
  * DNSSEC failure into `https://<domain>`. It is a failure of that resolver
236
254
  * instead, and the next one gets the question.
237
255
  */
238
- async function lookupSrv(domain: string): Promise<{ target: string; port: number } | null> {
256
+ async function lookupSrv(domain: string): Promise<{ target: string; port: number } | 'unsecured' | null> {
239
257
  const fallback = { target: domain, port: 443 }
240
258
  for (const endpoint of dohEndpoints) {
241
259
  let body: DohResponse
@@ -255,58 +273,83 @@ export function createRegistryResolver(args: {
255
273
  if (body.Status === NXDOMAIN || records.length === 0) return fallback
256
274
  records.sort((a, b) => a.priority - b.priority || b.weight - a.weight)
257
275
  const best = records[0]
258
- if (body.AD !== true && best.target !== domain) return null
276
+ if (body.AD !== true && best.target !== domain) return 'unsecured'
259
277
  return { target: best.target, port: best.port }
260
278
  }
261
279
  return null
262
280
  }
263
281
 
264
- async function discover(domain: string): Promise<RegistryEndpoints | null> {
282
+ async function discover(domain: string): Promise<CapabilityDiscovery> {
265
283
  const host = await lookupSrv(domain)
266
- if (!host) return null
284
+ if (host === null) return { kind: 'failed' }
285
+ if (host === 'unsecured') return { kind: 'unsecured' }
267
286
  const origin = `https://${host.target}${host.port === 443 ? '' : `:${host.port}`}`
268
287
  // An SRV target is ordinarily just a hostname, but nothing stops one from
269
288
  // being an IP literal, `localhost`, or a `.local` name — and DNSSEC only
270
289
  // authenticates that the domain's own zone said so, not that it is a
271
290
  // sensible destination (XR-073 / SEC2-057, SEC2-076).
272
- if (!isPublicHttpsUrl(`${origin}/`)) return null
273
- let capabilities: Record<string, unknown>
291
+ if (!isPublicHttpsUrl(`${origin}/`)) return { kind: 'unsecured' }
292
+ let body: unknown
274
293
  try {
275
294
  const res = await fetchWithTimeout(fetchImpl, `${origin}/.well-known/bsvalias`, {
276
295
  headers: { accept: 'application/json' }
277
296
  })
278
- if (!res.ok) return null
279
- const body = (await res.json()) as { capabilities?: Record<string, unknown> }
280
- capabilities = body?.capabilities ?? {}
297
+ if (!res.ok) return res.status >= 500 ? { kind: 'failed' } : { kind: 'none' }
298
+ body = await res.json()
281
299
  } catch {
282
- return null
300
+ return { kind: 'failed' }
283
301
  }
284
- const searchTemplate = templateOf(capabilities[BRFC_LOOKUP], '{query}')
285
- const reverseTemplate = templateOf(capabilities[BRFC_REVERSE_LOOKUP], '{pubkey}')
286
- if (!searchTemplate || !reverseTemplate) return null
287
- return {
288
- domain,
289
- search: query => searchTemplate.replace('{query}', encodeURIComponent(query)),
290
- reverse: pubkey => reverseTemplate.replace('{pubkey}', encodeURIComponent(pubkey)),
291
- pinned: false
302
+ if (!isPlainObject(body)) return { kind: 'none' }
303
+ const capabilities = body.capabilities ?? {}
304
+ if (!isPlainObject(capabilities)) return { kind: 'none' }
305
+ return { kind: 'ok', domain, origin, capabilities }
306
+ }
307
+
308
+ async function discoverCapabilities(rawDomain: string): Promise<CapabilityDiscovery> {
309
+ const domain = rawDomain.trim().toLowerCase()
310
+ if (pinnedEndpoints && domain === pinnedDomain) {
311
+ return {
312
+ kind: 'ok',
313
+ domain,
314
+ origin: pinnedOrigin,
315
+ capabilities: {
316
+ [BRFC_LOOKUP]: `${pinnedOrigin}/api/handle/{query}`,
317
+ [BRFC_REVERSE_LOOKUP]: `${pinnedOrigin}/api/identityKey/{pubkey}`
318
+ }
319
+ }
292
320
  }
321
+ // Ahead of the cache, not inside discovery: a half-typed domain is not an
322
+ // answer, and the cache has no eviction — search resolves as the user types.
323
+ if (!looksLikeDomain(domain)) return { kind: 'none' }
324
+ const hit = cache.get(domain)
325
+ if (hit && now() - hit.at < (hit.value.kind === 'ok' ? RESOLVER_SUCCESS_TTL_MS : RESOLVER_FAILURE_TTL_MS)) {
326
+ return hit.value
327
+ }
328
+ const value = await discover(domain)
329
+ cache.set(domain, { at: now(), value })
330
+ return value
293
331
  }
294
332
 
295
333
  return {
296
334
  async resolve(rawDomain) {
297
335
  const domain = rawDomain.trim().toLowerCase()
298
336
  if (pinnedEndpoints && domain === pinnedDomain) return pinnedEndpoints
299
- // Ahead of the cache, not inside discovery: a half-typed domain is not an
300
- // answer, and the cache has no eviction — search resolves as the user types.
301
- if (!looksLikeDomain(domain)) return null
302
- const hit = cache.get(domain)
303
- if (hit && now() - hit.at < (hit.value ? RESOLVER_SUCCESS_TTL_MS : RESOLVER_FAILURE_TTL_MS)) return hit.value
304
- const value = await discover(domain)
305
- cache.set(domain, { at: now(), value })
306
- return value
337
+ const found = await discoverCapabilities(domain)
338
+ if (found.kind !== 'ok') return null
339
+ const searchTemplate = templateOf(found.capabilities[BRFC_LOOKUP], '{query}')
340
+ const reverseTemplate = templateOf(found.capabilities[BRFC_REVERSE_LOOKUP], '{pubkey}')
341
+ if (!searchTemplate || !reverseTemplate) return null
342
+ return {
343
+ domain,
344
+ search: query => searchTemplate.replace('{query}', encodeURIComponent(query)),
345
+ reverse: pubkey => reverseTemplate.replace('{pubkey}', encodeURIComponent(pubkey)),
346
+ pinned: false
347
+ }
307
348
  },
308
- clearCache() {
309
- cache.clear()
349
+ discoverCapabilities,
350
+ clearCache(domain) {
351
+ if (domain === undefined) cache.clear()
352
+ else cache.delete(domain.trim().toLowerCase())
310
353
  }
311
354
  }
312
355
  }
@@ -20,6 +20,10 @@ export const PROFILE_CERT_TYPE = 'SbatVXXssDW3AO0J9bxIljkHGbPBGCVAXg94gXFf0cE='
20
20
  export const BRFC_LOOKUP = '0ace65da5987'
21
21
  /** BRFC id of the `public profile reverse lookup` capability — key → profile. */
22
22
  export const BRFC_REVERSE_LOOKUP = '43dcf83ddc5f'
23
+ /** BRFC id of the paymail P2P payment destination capability. */
24
+ export const BRFC_P2P_DESTINATION = '2a40af698840'
25
+ /** BRFC id of the paymail P2P receive-BEEF capability. */
26
+ export const BRFC_P2P_RECEIVE_BEEF = '5c55a7fdb7bb'
23
27
  /** There is no on-chain revocation: a profile is replaced or tombstoned. */
24
28
  export const ZERO_OUTPOINT = `${'0'.repeat(64)}.0`
25
29
 
package/core/index.ts CHANGED
@@ -317,6 +317,13 @@ export * from './pay/rails/address'
317
317
  export * from './pay/rails/sweep'
318
318
  export * from './pay/rails/handle'
319
319
  export * from './pay/rails/direct'
320
+ export * from './pay/rails/paymail'
321
+ export * from './pay/paymail/client'
322
+ export * from './pay/paymail/networkCheck'
323
+ export { classifyPaymailDomain, classifyPaymailDomainDetailed } from './identity/handleRegistry/classify'
324
+ export type { PaymailClass, PaymailClassification, UnsupportedReason } from './identity/handleRegistry/classify'
325
+ export { createRegistryResolver } from './identity/handleRegistry/resolver'
326
+ export type { RegistryResolver, CapabilityDiscovery } from './identity/handleRegistry/resolver'
320
327
  // nearby.ts is a pure re-export barrel over localpay/* (already exported above)
321
328
  // and @bsv/air-gap; only its genuinely new names are re-exported here by hand —
322
329
  // a blanket `export *` would collide (TS2308) with the localpay/offline exports
@@ -21,15 +21,25 @@ export interface DrainOutboxResult {
21
21
  stopped?: boolean
22
22
  }
23
23
 
24
- /** Retry unsent entries in order; the first throw aborts the rest. */
24
+ /**
25
+ * Retry unsent entries in order; the first throw aborts the rest. A throw from
26
+ * an entry that `isolate` accepts (a paymail row: its receiver is a third
27
+ * party that can fail for good) is skipped instead, so it cannot starve the
28
+ * rows behind it. Such a row stays counted as remaining, so the pass backs off.
29
+ */
25
30
  export async function drainUnsentEntries(args: {
26
31
  entries: OutboxEntry[]
27
32
  retry: (entry: OutboxEntry) => Promise<void>
33
+ isolate?: (entry: OutboxEntry) => boolean
28
34
  }): Promise<DrainOutboxResult> {
29
35
  let retried = 0
30
36
  for (const entry of args.entries) {
31
- await args.retry(entry)
32
- retried++
37
+ try {
38
+ await args.retry(entry)
39
+ retried++
40
+ } catch (e) {
41
+ if (!args.isolate?.(entry)) throw e
42
+ }
33
43
  }
34
44
  return { retried, remaining: args.entries.length - retried, stopped: false }
35
45
  }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Paymail address rules shared by the send path and the outbox import check.
3
+ *
4
+ * The alias follows the bsvalias grammar (letters, digits, `-`, `_`, `.`), so
5
+ * it may start with `_`, `.` or `-`. `+` is accepted after the first character
6
+ * for sub-addressing. `/`, `?`, `#`, whitespace and `@` are never allowed; the
7
+ * alias is also URL-encoded when a capability template is filled.
8
+ */
9
+ import { looksLikeDomain } from '../../identity/handleRegistry/rules'
10
+
11
+ export const ALIAS_FORMAT = /^[a-z0-9._-][a-z0-9._+-]{0,63}$/
12
+
13
+ /** The lowercased alias and domain, or null when this is not a paymail. */
14
+ export function parsePaymail(paymail: string): { alias: string; domain: string } | null {
15
+ if (typeof paymail !== 'string') return null
16
+ const parts = paymail.trim().toLowerCase().split('@')
17
+ if (parts.length !== 2 || !ALIAS_FORMAT.test(parts[0]) || !looksLikeDomain(parts[1])) return null
18
+ return { alias: parts[0], domain: parts[1] }
19
+ }