@bsv/expo-wallet-toolbox 0.22.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/CHANGELOG.md +108 -0
  2. package/README.md +9 -5
  3. package/core/bridge/BrowserBridgeProvider.tsx +273 -0
  4. package/core/bridge/bindings.ts +459 -0
  5. package/core/bridge/conformance.ts +222 -0
  6. package/core/bridge/consent.ts +494 -0
  7. package/core/bridge/consentSheetSource.ts +98 -0
  8. package/core/bridge/dispatcher.ts +621 -0
  9. package/core/bridge/inbox.ts +464 -0
  10. package/core/bridge/index.ts +48 -0
  11. package/core/bridge/loopback/cors.ts +57 -0
  12. package/core/bridge/loopback/endpoints.ts +11 -0
  13. package/core/bridge/loopback/hostCheck.ts +25 -0
  14. package/core/bridge/loopback/index.ts +7 -0
  15. package/core/bridge/loopback/launchProof.ts +166 -0
  16. package/core/bridge/loopback/router.ts +770 -0
  17. package/core/bridge/loopback/routerTypes.ts +115 -0
  18. package/core/bridge/loopback/status.ts +52 -0
  19. package/core/bridge/memoryInboxStore.ts +222 -0
  20. package/core/bridge/permissionPolicy.ts +247 -0
  21. package/core/bridge/policy.ts +72 -0
  22. package/core/bridge/protocol/base64url.ts +64 -0
  23. package/core/bridge/protocol/connectionError.ts +79 -0
  24. package/core/bridge/protocol/constants.ts +21 -0
  25. package/core/bridge/protocol/continuity.ts +21 -0
  26. package/core/bridge/protocol/descriptor.ts +395 -0
  27. package/core/bridge/protocol/envelopes.ts +188 -0
  28. package/core/bridge/protocol/errorCodec.ts +164 -0
  29. package/core/bridge/protocol/json.ts +237 -0
  30. package/core/bridge/protocol/limits.ts +43 -0
  31. package/core/bridge/protocol/methods.ts +55 -0
  32. package/core/bridge/protocol/origin.ts +130 -0
  33. package/core/bridge/runtime.ts +642 -0
  34. package/core/bridge/runtimeFlags.ts +34 -0
  35. package/core/bridge/testing/conformanceCases.ts +149 -0
  36. package/core/bridge/testing/pageClient.ts +44 -0
  37. package/core/bridge/unverifiedManager.ts +97 -0
  38. package/core/bridge/unverifiedOriginator.ts +79 -0
  39. package/core/config.tsx +1 -16
  40. package/core/context/WalletConnectionContext.tsx +7 -1
  41. package/core/context/WalletContext.tsx +258 -133
  42. package/core/context/sessionTeardown.ts +46 -0
  43. package/core/hooks/usePermissionQueue.ts +89 -34
  44. package/core/i18n/translations.tsx +911 -12
  45. package/core/index.ts +15 -0
  46. package/core/services/autoApprovePolicy.ts +7 -1
  47. package/core/services/capWalletArgs.ts +2 -1
  48. package/core/services/permissionPrompts.ts +132 -0
  49. package/core/services/signingPermissionPolicy.ts +230 -2
  50. package/core/services/vault/guard.ts +10 -0
  51. package/core/services/walletArgLimits.ts +17 -2
  52. package/core/storage/encryptedDbImage.ts +325 -0
  53. package/core/toolboxConfig.ts +18 -1
  54. package/package.json +6 -6
  55. package/ui/bridgeSheet/ContextRelay.tsx +86 -0
  56. package/ui/bridgeSheet/relayedContexts.ts +21 -0
  57. package/ui/components/ui/PermissionSheet.tsx +534 -158
  58. package/ui/components/ui/Sheet.tsx +59 -7
  59. package/ui/components/ui/sheetResumeSignal.ts +19 -0
  60. package/ui/exportDatabases.ts +94 -5
  61. package/ui/hooks/useExportWalletData.ts +37 -24
  62. package/ui/importDatabases.ts +123 -28
  63. package/ui/index.ts +4 -0
  64. package/ui/screens/WalletConfigScreen.tsx +13 -1
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Pure checks the dispatcher applies to a request or an answer (spec 6.5, 6.6). No wallet,
3
+ * runtime or React imports, so they are unit-testable on their own.
4
+ */
5
+
6
+ /**
7
+ * The names an unverified origin must never reach: anything the wallet underneath would treat as a
8
+ * token-module name. `trim().toLowerCase()` is what the wallet applies, and whitespace runs are
9
+ * collapsed as well, which the wallet does not do: refusing them here costs nothing and keeps the
10
+ * rule independent of that detail.
11
+ *
12
+ * Exact-case `p btms ...` / `p color ...` names are refused here too. The permissions manager
13
+ * sends them to the refusing stub module only for the methods that call `delegateToPModuleIfNeeded`;
14
+ * `revealSpecificKeyLinkage` does not, and with the linkage-revelation flag off it would answer
15
+ * without a prompt. So the pre-scan, not the stub, is what keeps the namespace closed.
16
+ */
17
+ function isTokenModuleVariant(name: string): boolean {
18
+ const folded = name.trim().toLowerCase().replace(/\s+/g, ' ')
19
+ return folded.startsWith('p btms') || folded.startsWith('p color')
20
+ }
21
+
22
+ const MAX_DEPTH = 8
23
+
24
+ /**
25
+ * Walks the argument tree for the three kinds of name the manager inspects: baskets (any `basket`
26
+ * key, which covers `listOutputs`, `relinquishOutput`, `outputs[].basket` and
27
+ * `insertionRemittance.basket`), labels (any `labels` array) and protocol names
28
+ * (`protocolID[1]`). Returns the first offending name, or undefined.
29
+ *
30
+ * Applied to unattested bindings only; an attested binding's calls are not pre-scanned.
31
+ */
32
+ export function findTokenModuleVariant(args: unknown): string | undefined {
33
+ const visit = (v: unknown, depth: number): string | undefined => {
34
+ if (depth > MAX_DEPTH || v === null || typeof v !== 'object') return undefined
35
+ if (Array.isArray(v)) {
36
+ for (const item of v) {
37
+ const hit = visit(item, depth + 1)
38
+ if (hit !== undefined) return hit
39
+ }
40
+ return undefined
41
+ }
42
+ for (const [key, value] of Object.entries(v as Record<string, unknown>)) {
43
+ if (key === 'basket' && typeof value === 'string' && isTokenModuleVariant(value)) return value
44
+ if (key === 'labels' && Array.isArray(value)) {
45
+ for (const label of value) if (typeof label === 'string' && isTokenModuleVariant(label)) return label
46
+ }
47
+ if (key === 'protocolID' && Array.isArray(value) && typeof value[1] === 'string') {
48
+ if (isTokenModuleVariant(value[1])) return value[1]
49
+ }
50
+ const hit = visit(value, depth + 1)
51
+ if (hit !== undefined) return hit
52
+ }
53
+ return undefined
54
+ }
55
+ return visit(args, 0)
56
+ }
57
+
58
+ const BASE_MIN = 7
59
+ const BASE_MAX = 30
60
+ const VERSION_MAX_BYTES = 2048
61
+
62
+ /**
63
+ * `getVersion` result check (BRC-205): a base of 7 to 30 bytes, optionally followed by extension
64
+ * attributes, at most 2048 ASCII bytes in all. The SDK's own check caps the whole string at 30,
65
+ * which would refuse every extended string, so the dispatcher uses this one. The base is the text
66
+ * before the first space or semicolon.
67
+ */
68
+ export function isValidVersionString(v: unknown): v is string {
69
+ if (typeof v !== 'string' || v.length > VERSION_MAX_BYTES || !/^[\x20-\x7e]+$/.test(v)) return false
70
+ const base = v.split(/[ ;]/, 1)[0]
71
+ return base.length >= BASE_MIN && base.length <= BASE_MAX
72
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Canonical unpadded base64url (RFC 4648 section 5). The decoder is strict: any input
3
+ * that would not be produced by `b64uEncode` for the same bytes is rejected, so a value
4
+ * has exactly one spelling (BRC-185 section 3). No Buffer/atob: bundle-safe everywhere.
5
+ */
6
+
7
+ const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'
8
+ const LOOKUP: Record<string, number> = {}
9
+ for (let i = 0; i < ALPHABET.length; i++) LOOKUP[ALPHABET[i]] = i
10
+
11
+ export class Base64urlError extends Error {
12
+ constructor(message: string) {
13
+ super(message)
14
+ this.name = 'Base64urlError'
15
+ }
16
+ }
17
+
18
+ export function b64uEncode(bytes: Uint8Array): string {
19
+ let out = ''
20
+ let i = 0
21
+ for (; i + 2 < bytes.length; i += 3) {
22
+ const n = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]
23
+ out += ALPHABET[(n >> 18) & 63] + ALPHABET[(n >> 12) & 63] + ALPHABET[(n >> 6) & 63] + ALPHABET[n & 63]
24
+ }
25
+ const rest = bytes.length - i
26
+ if (rest === 1) {
27
+ const n = bytes[i] << 16
28
+ out += ALPHABET[(n >> 18) & 63] + ALPHABET[(n >> 12) & 63]
29
+ } else if (rest === 2) {
30
+ const n = (bytes[i] << 16) | (bytes[i + 1] << 8)
31
+ out += ALPHABET[(n >> 18) & 63] + ALPHABET[(n >> 12) & 63] + ALPHABET[(n >> 6) & 63]
32
+ }
33
+ return out
34
+ }
35
+
36
+ export function b64uDecode(s: string): Uint8Array {
37
+ if (typeof s !== 'string') throw new Base64urlError('base64url input must be a string')
38
+ for (let i = 0; i < s.length; i++) {
39
+ if (!(s[i] in LOOKUP)) throw new Base64urlError('base64url contains a character outside the alphabet')
40
+ }
41
+ const rem = s.length % 4
42
+ if (rem === 1) throw new Base64urlError('base64url has an impossible length')
43
+ const out = new Uint8Array(Math.floor((s.length * 3) / 4))
44
+ let o = 0
45
+ let i = 0
46
+ for (; i + 3 < s.length; i += 4) {
47
+ const n = (LOOKUP[s[i]] << 18) | (LOOKUP[s[i + 1]] << 12) | (LOOKUP[s[i + 2]] << 6) | LOOKUP[s[i + 3]]
48
+ out[o++] = (n >> 16) & 255
49
+ out[o++] = (n >> 8) & 255
50
+ out[o++] = n & 255
51
+ }
52
+ if (rem === 2) {
53
+ const n = (LOOKUP[s[i]] << 18) | (LOOKUP[s[i + 1]] << 12)
54
+ // The last character carries 4 payload bits and 4 trailing bits that must be zero.
55
+ if ((n & 0xffff) !== 0) throw new Base64urlError('base64url has non-zero trailing bits')
56
+ out[o++] = (n >> 16) & 255
57
+ } else if (rem === 3) {
58
+ const n = (LOOKUP[s[i]] << 18) | (LOOKUP[s[i + 1]] << 12) | (LOOKUP[s[i + 2]] << 6)
59
+ if ((n & 0xff) !== 0) throw new Base64urlError('base64url has non-zero trailing bits')
60
+ out[o++] = (n >> 16) & 255
61
+ out[o++] = (n >> 8) & 255
62
+ }
63
+ return out
64
+ }
@@ -0,0 +1,79 @@
1
+ /** BRC-185 section 6 connection errors and the outcome table that assigns them (spec 6.11). */
2
+ /** Cut to at most `maxBytes` of UTF-8 without splitting a code point. */
3
+ export function truncateUtf8(s: string, maxBytes: number): string {
4
+ let bytes = 0
5
+ let out = ''
6
+ for (const ch of s) {
7
+ const c = ch.codePointAt(0) as number
8
+ const n = c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4
9
+ if (bytes + n > maxBytes) break
10
+ bytes += n
11
+ out += ch
12
+ }
13
+ return out
14
+ }
15
+
16
+ export type ConnectionErrorCode =
17
+ | 'CONFIGURATION_ERROR'
18
+ | 'SELECTION_REQUIRED'
19
+ | 'USER_CANCELLED'
20
+ | 'DISCOVERY_BLOCKED'
21
+ | 'PROVIDER_CHANGED'
22
+ | 'PAIRING_EXPIRED'
23
+ | 'PAIRING_REJECTED'
24
+ | 'PROTOCOL_ERROR'
25
+ | 'RESOURCE_LIMIT'
26
+ | 'DISCONNECTED'
27
+ | 'CONNECTION_CLOSED'
28
+
29
+ /** `not-sent`: the wallet never saw the call. `unknown`: it may have run. */
30
+ export type Delivery = 'not-sent' | 'unknown'
31
+
32
+ export interface ConnectionError {
33
+ domain: 'brc185'
34
+ code: ConnectionErrorCode
35
+ message: string
36
+ delivery: Delivery
37
+ epoch?: string
38
+ cause?: string
39
+ /** A mutating call whose result failed validation: the transaction it names, when it reported one. */
40
+ txid?: string
41
+ }
42
+
43
+ export const CONNECTION_ERROR_CODES: readonly ConnectionErrorCode[] = Object.freeze([
44
+ 'CONFIGURATION_ERROR',
45
+ 'SELECTION_REQUIRED',
46
+ 'USER_CANCELLED',
47
+ 'DISCOVERY_BLOCKED',
48
+ 'PROVIDER_CHANGED',
49
+ 'PAIRING_EXPIRED',
50
+ 'PAIRING_REJECTED',
51
+ 'PROTOCOL_ERROR',
52
+ 'RESOURCE_LIMIT',
53
+ 'DISCONNECTED',
54
+ 'CONNECTION_CLOSED'
55
+ ])
56
+
57
+ export function connectionError(
58
+ code: ConnectionErrorCode,
59
+ message: string,
60
+ delivery: Delivery,
61
+ extra: { epoch?: string; cause?: string; txid?: string } = {}
62
+ ): ConnectionError {
63
+ const e: ConnectionError = { domain: 'brc185', code, message: truncateUtf8(String(message), 4096), delivery }
64
+ if (extra.epoch !== undefined) e.epoch = extra.epoch
65
+ if (extra.cause !== undefined) e.cause = extra.cause
66
+ if (extra.txid !== undefined) e.txid = extra.txid
67
+ return e
68
+ }
69
+
70
+ export function isConnectionError(v: unknown): v is ConnectionError {
71
+ if (typeof v !== 'object' || v === null) return false
72
+ const o = v as Record<string, unknown>
73
+ return (
74
+ o.domain === 'brc185' &&
75
+ typeof o.message === 'string' &&
76
+ (o.delivery === 'not-sent' || o.delivery === 'unknown') &&
77
+ CONNECTION_ERROR_CODES.includes(o.code as ConnectionErrorCode)
78
+ )
79
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Admin originator constants, in a module with no imports so the Safari extension bundle (and
3
+ * anything else that must stay free of app code) can reach them. `core/config` re-exports both.
4
+ */
5
+
6
+ /**
7
+ * Internal authority label passed only by the wallet shell.
8
+ *
9
+ * The permissions manager grants this originator administrative access, so it
10
+ * must be a name no external caller can present. It used to sit outside the
11
+ * hostname namespace altogether (`urn:bsv-wallet:internal-admin`), but
12
+ * @bsv/sdk 2.8 accepts only canonical hostnames as originators. It now lives
13
+ * in the RFC 6761 `.invalid` TLD, which never resolves, so no host can be
14
+ * served from it, and `parseExternalOrigin` refuses that whole TLD at the
15
+ * external trust boundary. An ordinary DNS name would let whoever controls
16
+ * that host acquire the same authority through a paired connection.
17
+ */
18
+ export const ADMIN_ORIGINATOR = 'internal-admin.bsv-wallet.invalid'
19
+
20
+ /** The label before @bsv/sdk 2.8, still found in data persisted by older builds. */
21
+ export const LEGACY_ADMIN_ORIGINATOR = 'urn:bsv-wallet:internal-admin'
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Per-application-context provider continuity (BRC-185 section 3).
3
+ *
4
+ * The continuity key is an Ed25519 key generated independently of wallet spending and identity keys.
5
+ * Its private half never leaves the store: callers only get `sign`. `getOrCreate` has to work while
6
+ * the wallet is locked because describe is non-interactive and answers inside one second.
7
+ */
8
+ export interface ContinuityHandle {
9
+ /** Lowercase UUIDv4, stable for this provider and application context. */
10
+ instanceId: string
11
+ /** Base64url of the 32-byte Ed25519 public key. */
12
+ continuityKey: string
13
+ /** Pure Ed25519 (RFC 8032) over the given preimage. */
14
+ sign(preimage: Uint8Array): Promise<Uint8Array>
15
+ }
16
+
17
+ export interface ContinuityStore {
18
+ getOrCreate(ctx: string): Promise<ContinuityHandle>
19
+ /** Rotate one context, or every context. A reset makes this a new provider for remembered-choice purposes. */
20
+ reset(ctx: string | 'all'): Promise<void>
21
+ }
@@ -0,0 +1,395 @@
1
+ /**
2
+ * BRC-185 provider descriptor and its signed describe/connect proofs (spec 6.10).
3
+ *
4
+ * Pure: depends only on `@bsv/sdk` utils and `@noble/curves`, so it can be bundled into the
5
+ * Safari extension unchanged.
6
+ */
7
+ import { Utils } from '@bsv/sdk'
8
+ import { ed25519 } from '@noble/curves/ed25519.js'
9
+ import { b64uDecode, b64uEncode } from './base64url'
10
+ import { canonicalize, hasLoneSurrogate, parseStrictJson } from './json'
11
+ import { CHALLENGE_BYTES, MAX_PROOF_RESPONSE_BYTES } from './limits'
12
+
13
+ export class DescriptorError extends Error {
14
+ constructor(message: string) {
15
+ super(message)
16
+ this.name = 'DescriptorError'
17
+ }
18
+ }
19
+
20
+ export class ProofError extends Error {
21
+ constructor(message: string) {
22
+ super(message)
23
+ this.name = 'ProofError'
24
+ }
25
+ }
26
+
27
+ export interface DescriptorEndpoint {
28
+ id: string
29
+ type: string
30
+ address: string
31
+ }
32
+
33
+ export interface Descriptor {
34
+ version: 1
35
+ instanceId: string
36
+ name: string
37
+ instanceLabel: string
38
+ icon?: string
39
+ vendor: string
40
+ continuityKey: string
41
+ endpoints: DescriptorEndpoint[]
42
+ }
43
+
44
+ export interface DescribeResponse {
45
+ descriptor: Descriptor
46
+ challenge: string
47
+ signature: string
48
+ }
49
+
50
+ export interface ConnectResponse extends DescribeResponse {
51
+ epoch: string
52
+ }
53
+
54
+ export interface ProofSigner {
55
+ sign(preimage: Uint8Array): Promise<Uint8Array>
56
+ }
57
+
58
+ export const DESCRIBE_PREFIX = 'BRC-185 descriptor v1\n'
59
+ export const CONNECT_PREFIX = 'BRC-185 connect v1\n'
60
+
61
+ const encoder = new TextEncoder()
62
+ const utf8 = (s: string): Uint8Array => encoder.encode(s)
63
+ const utf8Length = (s: string): number => encoder.encode(s).length
64
+
65
+ const UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
66
+ const VENDOR = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/
67
+ const ENDPOINT_ID = /^[A-Za-z0-9._-]{1,64}$/
68
+ const KNOWN_TYPES = new Set(['http-wire', 'http-json', 'https-json', 'window', 'xdm', 'react-native'])
69
+ const HTTP_TYPES = new Set(['http-wire', 'http-json'])
70
+ const PORT = '(?::(?:[1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5]))?'
71
+ const LOOPBACK_HTTP_ORIGIN = new RegExp(`^http://(?:localhost|127\\.0\\.0\\.1|\\[::1\\])${PORT}$`)
72
+ const HTTPS_ORIGIN = new RegExp(
73
+ `^https://(?:[a-z0-9]+(?:[a-z0-9-]*[a-z0-9])?)(?:\\.[a-z0-9]+(?:[a-z0-9-]*[a-z0-9])?)*${PORT}$`
74
+ )
75
+ const ICON_HTTPS = /^https:\/\/(?:[a-z0-9-]+(?:\.[a-z0-9-]+)*|\[[0-9a-f:]+\])(?::[0-9]{1,5})?\/[\x21-\x7e]*$/
76
+ // Text a user will see must stay inert: no control characters, no bidi overrides or isolates, no
77
+ // line/paragraph separators, no BOM or zero-width marks that could disguise one site as another.
78
+ // eslint-disable-next-line no-control-regex
79
+ const FORBIDDEN_TEXT = /[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u2028-\u202e\u2060-\u2069\ufeff]/
80
+
81
+ const DESCRIPTOR_KEYS = new Set([
82
+ 'version',
83
+ 'instanceId',
84
+ 'name',
85
+ 'instanceLabel',
86
+ 'icon',
87
+ 'vendor',
88
+ 'continuityKey',
89
+ 'endpoints'
90
+ ])
91
+
92
+ function isRecord(v: unknown): v is Record<string, unknown> {
93
+ return typeof v === 'object' && v !== null && !Array.isArray(v)
94
+ }
95
+
96
+ function plainText(v: unknown, field: string, min: number, max: number): string {
97
+ if (typeof v !== 'string') throw new DescriptorError(`${field} must be a string`)
98
+ if (hasLoneSurrogate(v) || FORBIDDEN_TEXT.test(v)) throw new DescriptorError(`${field} must be plain text`)
99
+ const n = utf8Length(v)
100
+ if (n < min || n > max) throw new DescriptorError(`${field} must be ${min}-${max} bytes`)
101
+ if (min > 0 && v.trim().length === 0) throw new DescriptorError(`${field} must not be blank`)
102
+ return v
103
+ }
104
+
105
+ function canonicalB64u(v: unknown, bytes: number, field: string): string {
106
+ if (typeof v !== 'string') throw new DescriptorError(`${field} must be a string`)
107
+ let decoded: Uint8Array
108
+ try {
109
+ decoded = b64uDecode(v)
110
+ } catch {
111
+ throw new DescriptorError(`${field} must be canonical base64url`)
112
+ }
113
+ if (decoded.length !== bytes) throw new DescriptorError(`${field} must decode to ${bytes} bytes`)
114
+ return v
115
+ }
116
+
117
+ function originParts(
118
+ address: string,
119
+ what: string,
120
+ bare: boolean
121
+ ): { protocol: string; hostname: string; port: string } {
122
+ let u: URL
123
+ try {
124
+ u = new URL(address)
125
+ } catch {
126
+ throw new ProofError(`${what} is not a URL`)
127
+ }
128
+ if (bare && ((u.pathname !== '/' && u.pathname !== '') || u.search !== '' || u.hash !== '')) {
129
+ throw new ProofError(`${what} must not carry a path, query or fragment`)
130
+ }
131
+ return { protocol: u.protocol, hostname: u.hostname, port: u.port }
132
+ }
133
+
134
+ /**
135
+ * Throws `ProofError` unless the descriptor advertises the responder the page actually reached: some
136
+ * endpoint has `type === responder.type` and an `address` with the same scheme, host and port as
137
+ * `responder.address` (parsed `URL` parts; no path allowed on the responder). A responder that
138
+ * answers `describe` on a loopback port must be reachable at an address the descriptor names, so a
139
+ * different process on another port cannot present a descriptor that points elsewhere. `127.0.0.1`
140
+ * does not satisfy `localhost`: the host is compared as written.
141
+ */
142
+ export function assertAdvertisesResponder(
143
+ descriptor: Descriptor,
144
+ responder: { type: 'http-json'; address: string }
145
+ ): void {
146
+ const want = originParts(responder.address, 'responder address', true)
147
+ for (const ep of descriptor.endpoints) {
148
+ if (ep.type !== responder.type) continue
149
+ let got: ReturnType<typeof originParts>
150
+ try {
151
+ got = originParts(ep.address, 'endpoint address', false)
152
+ } catch {
153
+ continue
154
+ }
155
+ if (got.protocol === want.protocol && got.hostname === want.hostname && got.port === want.port) return
156
+ }
157
+ throw new ProofError('descriptor does not advertise the responder that answered')
158
+ }
159
+
160
+ /** BRC-185 section 3.1. Returns false for anything that is not one of the three allowed forms. */
161
+ export function isValidIconReference(ref: string): boolean {
162
+ if (utf8Length(ref) < 1 || utf8Length(ref) > 256) return false
163
+ if (ref.startsWith('https://')) return ICON_HTTPS.test(ref) && !ref.includes('#')
164
+ if (ref.startsWith('uhrp://')) {
165
+ const id = ref.slice('uhrp://'.length)
166
+ if (!/^[1-9A-HJ-NP-Za-km-z]+$/.test(id)) return false
167
+ try {
168
+ const { prefix, data } = Utils.fromBase58Check(id, undefined, 2) as { prefix: number[]; data: number[] }
169
+ return prefix.length === 2 && prefix[0] === 0xce && prefix[1] === 0x00 && data.length === 32
170
+ } catch {
171
+ return false
172
+ }
173
+ }
174
+ if (ref.startsWith('chirp://')) {
175
+ // BRC-167 root identifiers are opaque, case-sensitive tokens. Only the token alphabet is checked here;
176
+ // content verification belongs to the resolver (section 3.1 keeps that outside the core).
177
+ return /^[A-Za-z0-9_-]{1,200}$/.test(ref.slice('chirp://'.length))
178
+ }
179
+ return false
180
+ }
181
+
182
+ function validateEndpoint(e: unknown): DescriptorEndpoint {
183
+ if (!isRecord(e)) throw new DescriptorError('endpoint must be an object')
184
+ for (const k of Object.keys(e)) {
185
+ if (k !== 'id' && k !== 'type' && k !== 'address') throw new DescriptorError(`unknown endpoint field "${k}"`)
186
+ }
187
+ const { id, type, address } = e
188
+ if (typeof id !== 'string' || !ENDPOINT_ID.test(id)) throw new DescriptorError('endpoint id is invalid')
189
+ if (typeof type !== 'string') throw new DescriptorError('endpoint type must be a string')
190
+ if (typeof address !== 'string' || address.length === 0 || hasLoneSurrogate(address) || utf8Length(address) > 2048) {
191
+ throw new DescriptorError('endpoint address is invalid')
192
+ }
193
+ if (FORBIDDEN_TEXT.test(address)) throw new DescriptorError('endpoint address has control characters')
194
+ if (HTTP_TYPES.has(type)) {
195
+ if (!LOOPBACK_HTTP_ORIGIN.test(address)) throw new DescriptorError('HTTP endpoint must be a loopback origin')
196
+ } else if (type === 'https-json') {
197
+ if (!HTTPS_ORIGIN.test(address)) throw new DescriptorError('https-json endpoint must be an https origin')
198
+ } else if (!KNOWN_TYPES.has(type)) {
199
+ // An extension's specification URI: absolute https, no whitespace.
200
+ if (!/^https:\/\/[\x21-\x7e]+$/.test(type)) throw new DescriptorError('endpoint type is unknown')
201
+ }
202
+ return { id, type, address }
203
+ }
204
+
205
+ /**
206
+ * Validate a descriptor (BRC-185 section 3). Unknown fields, null optionals and bad shapes throw.
207
+ * An invalid icon is the one soft failure: it is dropped from the returned value. Callers must verify
208
+ * signatures over the original object, never over this normalised copy.
209
+ */
210
+ export function validateDescriptor(d: unknown): Descriptor {
211
+ if (!isRecord(d)) throw new DescriptorError('descriptor must be an object')
212
+ for (const k of Object.keys(d)) {
213
+ if (!DESCRIPTOR_KEYS.has(k)) throw new DescriptorError(`unknown descriptor field "${k}"`)
214
+ }
215
+ if (d.version !== 1) throw new DescriptorError('descriptor version must be 1')
216
+ if (typeof d.instanceId !== 'string' || !UUID_V4.test(d.instanceId)) {
217
+ throw new DescriptorError('instanceId must be a lowercase UUIDv4')
218
+ }
219
+ const name = plainText(d.name, 'name', 1, 80)
220
+ const instanceLabel = plainText(d.instanceLabel, 'instanceLabel', 0, 80)
221
+ if (typeof d.vendor !== 'string' || d.vendor.length < 1 || d.vendor.length > 253 || !VENDOR.test(d.vendor)) {
222
+ throw new DescriptorError('vendor must be a lowercase reverse-domain string')
223
+ }
224
+ const continuityKey = canonicalB64u(d.continuityKey, 32, 'continuityKey')
225
+ if (!Array.isArray(d.endpoints) || d.endpoints.length < 1 || d.endpoints.length > 32) {
226
+ throw new DescriptorError('endpoints must hold 1-32 records')
227
+ }
228
+ const endpoints = d.endpoints.map(validateEndpoint)
229
+ if (new Set(endpoints.map(e => e.id)).size !== endpoints.length)
230
+ throw new DescriptorError('endpoint ids must be unique')
231
+
232
+ const out: Descriptor = {
233
+ version: 1,
234
+ instanceId: d.instanceId,
235
+ name,
236
+ instanceLabel,
237
+ vendor: d.vendor,
238
+ continuityKey,
239
+ endpoints
240
+ }
241
+ if ('icon' in d) {
242
+ if (typeof d.icon !== 'string') throw new DescriptorError('icon must be a string when present')
243
+ if (isValidIconReference(d.icon)) out.icon = d.icon
244
+ }
245
+ return out
246
+ }
247
+
248
+ /** Ed25519 public key usable as a continuity key: canonical encoding, on the curve, not small order. */
249
+ export function isStrongEd25519Key(pub: Uint8Array): boolean {
250
+ if (pub.length !== 32) return false
251
+ try {
252
+ const point = ed25519.Point.fromBytes(pub, false)
253
+ return !point.isSmallOrder()
254
+ } catch {
255
+ return false
256
+ }
257
+ }
258
+
259
+ function verifyEd25519(signature: Uint8Array, preimage: Uint8Array, pub: Uint8Array): boolean {
260
+ if (signature.length !== 64 || !isStrongEd25519Key(pub)) return false
261
+ try {
262
+ return ed25519.verify(signature, preimage, pub, { zip215: false })
263
+ } catch {
264
+ return false
265
+ }
266
+ }
267
+
268
+ export function describePreimage(input: { origin: string; challenge: string; descriptor: unknown }): Uint8Array {
269
+ const { origin, challenge, descriptor } = input
270
+ return utf8(DESCRIBE_PREFIX + canonicalize({ origin, challenge, descriptor }))
271
+ }
272
+
273
+ export function connectPreimage(input: {
274
+ origin: string
275
+ epoch: string
276
+ challenge: string
277
+ descriptor: unknown
278
+ }): Uint8Array {
279
+ const { origin, epoch, challenge, descriptor } = input
280
+ return utf8(CONNECT_PREFIX + canonicalize({ origin, epoch, challenge, descriptor }))
281
+ }
282
+
283
+ export async function signDescribe(
284
+ signer: ProofSigner,
285
+ input: { origin: string; challenge: string; descriptor: Descriptor }
286
+ ): Promise<DescribeResponse> {
287
+ const signature = await signer.sign(describePreimage(input))
288
+ return { descriptor: input.descriptor, challenge: input.challenge, signature: b64uEncode(signature) }
289
+ }
290
+
291
+ export async function signConnect(
292
+ signer: ProofSigner,
293
+ input: { origin: string; epoch: string; challenge: string; descriptor: Descriptor }
294
+ ): Promise<ConnectResponse> {
295
+ const signature = await signer.sign(connectPreimage(input))
296
+ return {
297
+ epoch: input.epoch,
298
+ descriptor: input.descriptor,
299
+ challenge: input.challenge,
300
+ signature: b64uEncode(signature)
301
+ }
302
+ }
303
+
304
+ function requireChallenge(challenge: string, what: string): void {
305
+ try {
306
+ if (b64uDecode(challenge).length === CHALLENGE_BYTES) return
307
+ } catch {
308
+ /* fall through */
309
+ }
310
+ throw new ProofError(`${what} must be 32 bytes of canonical base64url`)
311
+ }
312
+
313
+ /** Accept the raw text of a response (strictly parsed) or an already-parsed object; bound its size. */
314
+ function readResponse(resp: unknown, keys: string[]): Record<string, unknown> {
315
+ let obj: unknown = resp
316
+ if (typeof resp === 'string') {
317
+ if (utf8Length(resp) > MAX_PROOF_RESPONSE_BYTES) throw new ProofError('response is too large')
318
+ try {
319
+ obj = parseStrictJson(resp)
320
+ } catch (e) {
321
+ throw new ProofError(`response is not strict JSON: ${(e as Error).message}`)
322
+ }
323
+ } else {
324
+ let size: number
325
+ try {
326
+ size = utf8Length(canonicalize(resp))
327
+ } catch {
328
+ throw new ProofError('response is not plain JSON')
329
+ }
330
+ if (size > MAX_PROOF_RESPONSE_BYTES) throw new ProofError('response is too large')
331
+ }
332
+ if (!isRecord(obj)) throw new ProofError('response must be an object')
333
+ for (const k of Object.keys(obj)) if (!keys.includes(k)) throw new ProofError(`unknown response field "${k}"`)
334
+ for (const k of keys) if (!(k in obj)) throw new ProofError(`response is missing "${k}"`)
335
+ return obj
336
+ }
337
+
338
+ function checkSignature(raw: Record<string, unknown>, preimage: (descriptor: unknown) => Uint8Array): Descriptor {
339
+ let descriptor: Descriptor
340
+ try {
341
+ descriptor = validateDescriptor(raw.descriptor)
342
+ } catch (e) {
343
+ throw new ProofError((e as Error).message)
344
+ }
345
+ let sig: Uint8Array
346
+ try {
347
+ if (typeof raw.signature !== 'string') throw new Error('not a string')
348
+ sig = b64uDecode(raw.signature)
349
+ } catch {
350
+ throw new ProofError('signature must be canonical base64url')
351
+ }
352
+ // The signature covers the exact descriptor the provider sent (including an icon we may have
353
+ // dropped), so the preimage is built from the raw object.
354
+ if (!verifyEd25519(sig, preimage(raw.descriptor), b64uDecode(descriptor.continuityKey))) {
355
+ throw new ProofError('signature does not verify')
356
+ }
357
+ return descriptor
358
+ }
359
+
360
+ /** Verify a describe response for `origin` and the controller's own `challenge`. */
361
+ export function verifyDescribeProof(resp: unknown, ctx: { origin: string; challenge: string }): Descriptor {
362
+ requireChallenge(ctx.challenge, 'challenge')
363
+ const raw = readResponse(resp, ['descriptor', 'challenge', 'signature'])
364
+ if (raw.challenge !== ctx.challenge) throw new ProofError('challenge was not echoed exactly')
365
+ return checkSignature(raw, descriptor =>
366
+ describePreimage({ origin: ctx.origin, challenge: ctx.challenge, descriptor })
367
+ )
368
+ }
369
+
370
+ /** Verify a connect response, including that it proves the identity the controller selected. */
371
+ export function verifyConnectProof(
372
+ resp: unknown,
373
+ ctx: {
374
+ origin: string
375
+ epoch: string
376
+ challenge: string
377
+ expectedIdentity: { instanceId: string; continuityKey: string }
378
+ }
379
+ ): Descriptor {
380
+ requireChallenge(ctx.challenge, 'challenge')
381
+ if (!UUID_V4.test(ctx.epoch)) throw new ProofError('epoch must be a lowercase UUIDv4')
382
+ const raw = readResponse(resp, ['epoch', 'descriptor', 'challenge', 'signature'])
383
+ if (raw.challenge !== ctx.challenge) throw new ProofError('challenge was not echoed exactly')
384
+ if (raw.epoch !== ctx.epoch) throw new ProofError('epoch was not echoed exactly')
385
+ const descriptor = checkSignature(raw, d =>
386
+ connectPreimage({ origin: ctx.origin, epoch: ctx.epoch, challenge: ctx.challenge, descriptor: d })
387
+ )
388
+ if (
389
+ descriptor.instanceId !== ctx.expectedIdentity.instanceId ||
390
+ descriptor.continuityKey !== ctx.expectedIdentity.continuityKey
391
+ ) {
392
+ throw new ProofError('connect proof is for a different provider identity')
393
+ }
394
+ return descriptor
395
+ }