@hsuite/native-connect-types 1.0.0 → 2.1.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.
@@ -0,0 +1,48 @@
1
+ /**
2
+ * HSuite Native Connect
3
+ * Copyright 2024-2025 HSuite (https://hsuite.finance)
4
+ *
5
+ * SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
6
+ *
7
+ * This file is part of HSuite Native Connect. For commercial licensing,
8
+ * visit https://hsuite.finance/licensing
9
+ */
10
+ /**
11
+ * @file Canonical, ordered XRPL endpoint lists per network.
12
+ *
13
+ * @description
14
+ * Single source of truth for the rippled endpoints the wallet talks to. The
15
+ * first entry in each list is the primary node; the rest are failover targets
16
+ * tried in order when the primary cannot be reached. Mainnet carries multiple
17
+ * endpoints so a single unreachable node (network/VPN/proxy blocking the WSS
18
+ * handshake, or a public-cluster IP rate-limit) does not take down the whole
19
+ * XRPL read path. Testnet/devnet stay single-entry.
20
+ *
21
+ * Cross-package consumers — the `ledger-xrpl` adapter (WS clients,
22
+ * account-existence checks, the ledger manifest) and the `native-wallet-sdk`
23
+ * (token discovery, account import validation) — MUST import these from
24
+ * `@hsuite/native-connect-types` rather than re-declaring the URLs, so the list
25
+ * stays in lock-step everywhere. `ledger-xrpl` re-exports them through its own
26
+ * `endpoints` module for local ergonomics.
27
+ *
28
+ * Any endpoint added here for mainnet must ALSO be whitelisted in the wallet
29
+ * app's CSP surfaces (`index.html` meta + `_headers`) or the browser blocks the
30
+ * connection — `xrplcluster.com`, `s1.ripple.com`, and `s2.ripple.com` are
31
+ * already present in both.
32
+ */
33
+ /**
34
+ * Ordered XRPL endpoints per network; primary first, the rest are failover.
35
+ *
36
+ * @constant
37
+ */
38
+ export declare const XRPL_ENDPOINTS: Record<string, readonly string[]>;
39
+ /**
40
+ * Resolve the ordered endpoint list for a network id.
41
+ *
42
+ * @param networkId - Network identifier (e.g. `xrpl:mainnet`).
43
+ * @returns The ordered endpoint list (primary first), or an empty list when the
44
+ * network is unknown. Callers treat an empty list as "no endpoints
45
+ * configured" and surface a retryable error rather than connecting.
46
+ */
47
+ export declare function endpointsFor(networkId: string): readonly string[];
48
+ //# sourceMappingURL=xrpl-endpoints.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"xrpl-endpoints.d.ts","sourceRoot":"","sources":["../src/xrpl-endpoints.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH;;;;GAIG;AACH,eAAO,MAAM,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAI5D,CAAC;AAEF;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAAC,SAAS,EAAE,MAAM,GAAG,SAAS,MAAM,EAAE,CAEjE"}
@@ -0,0 +1,54 @@
1
+ /**
2
+ * HSuite Native Connect
3
+ * Copyright 2024-2025 HSuite (https://hsuite.finance)
4
+ *
5
+ * SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
6
+ *
7
+ * This file is part of HSuite Native Connect. For commercial licensing,
8
+ * visit https://hsuite.finance/licensing
9
+ */
10
+ /**
11
+ * @file Canonical, ordered XRPL endpoint lists per network.
12
+ *
13
+ * @description
14
+ * Single source of truth for the rippled endpoints the wallet talks to. The
15
+ * first entry in each list is the primary node; the rest are failover targets
16
+ * tried in order when the primary cannot be reached. Mainnet carries multiple
17
+ * endpoints so a single unreachable node (network/VPN/proxy blocking the WSS
18
+ * handshake, or a public-cluster IP rate-limit) does not take down the whole
19
+ * XRPL read path. Testnet/devnet stay single-entry.
20
+ *
21
+ * Cross-package consumers — the `ledger-xrpl` adapter (WS clients,
22
+ * account-existence checks, the ledger manifest) and the `native-wallet-sdk`
23
+ * (token discovery, account import validation) — MUST import these from
24
+ * `@hsuite/native-connect-types` rather than re-declaring the URLs, so the list
25
+ * stays in lock-step everywhere. `ledger-xrpl` re-exports them through its own
26
+ * `endpoints` module for local ergonomics.
27
+ *
28
+ * Any endpoint added here for mainnet must ALSO be whitelisted in the wallet
29
+ * app's CSP surfaces (`index.html` meta + `_headers`) or the browser blocks the
30
+ * connection — `xrplcluster.com`, `s1.ripple.com`, and `s2.ripple.com` are
31
+ * already present in both.
32
+ */
33
+ /**
34
+ * Ordered XRPL endpoints per network; primary first, the rest are failover.
35
+ *
36
+ * @constant
37
+ */
38
+ export const XRPL_ENDPOINTS = {
39
+ 'xrpl:mainnet': ['wss://xrplcluster.com', 'wss://s1.ripple.com', 'wss://s2.ripple.com'],
40
+ 'xrpl:testnet': ['wss://s.altnet.rippletest.net:51233'],
41
+ 'xrpl:devnet': ['wss://s.devnet.rippletest.net:51233'],
42
+ };
43
+ /**
44
+ * Resolve the ordered endpoint list for a network id.
45
+ *
46
+ * @param networkId - Network identifier (e.g. `xrpl:mainnet`).
47
+ * @returns The ordered endpoint list (primary first), or an empty list when the
48
+ * network is unknown. Callers treat an empty list as "no endpoints
49
+ * configured" and surface a retryable error rather than connecting.
50
+ */
51
+ export function endpointsFor(networkId) {
52
+ return XRPL_ENDPOINTS[networkId] ?? [];
53
+ }
54
+ //# sourceMappingURL=xrpl-endpoints.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"xrpl-endpoints.js","sourceRoot":"","sources":["../src/xrpl-endpoints.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH;;;;GAIG;AACH,MAAM,CAAC,MAAM,cAAc,GAAsC;IAC/D,cAAc,EAAE,CAAC,uBAAuB,EAAE,qBAAqB,EAAE,qBAAqB,CAAC;IACvF,cAAc,EAAE,CAAC,qCAAqC,CAAC;IACvD,aAAa,EAAE,CAAC,qCAAqC,CAAC;CACvD,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,UAAU,YAAY,CAAC,SAAiB;IAC5C,OAAO,cAAc,CAAC,SAAS,CAAC,IAAI,EAAE,CAAC;AACzC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hsuite/native-connect-types",
3
- "version": "1.0.0",
3
+ "version": "2.1.0",
4
4
  "license": "PolyForm-Noncommercial-1.0.0",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
package/src/index.ts CHANGED
@@ -195,3 +195,24 @@ export {
195
195
  HEDERA_FEE_COLLECTOR_ACCOUNTS,
196
196
  HEDERA_SYSTEM_ACCOUNTS,
197
197
  } from './hedera-system-accounts.js';
198
+
199
+ // === XRPL Endpoints ===
200
+ // Canonical, ordered rippled endpoint lists per network (primary first, rest
201
+ // are failover). Imported by the ledger-xrpl adapter (WS clients, account
202
+ // checks, manifest) and the native-wallet-sdk (token discovery, import
203
+ // validation) so every XRPL read path fails over across the same nodes and the
204
+ // endpoint set never drifts across packages.
205
+ export { XRPL_ENDPOINTS, endpointsFor } from './xrpl-endpoints.js';
206
+
207
+ // === IPFS CDN primitives ===
208
+ // Single source of truth for the HSuite Bunny CDN host/base URL and the
209
+ // per-surface image-optimizer helper. Imported by the SDK gateway layer
210
+ // (the `convertIpfsUrl` default), the wallet app's image getters, and the UI
211
+ // render surfaces so the CDN domain and the optimizer query format never
212
+ // drift across packages.
213
+ export {
214
+ HSUITE_IPFS_CDN_BASE,
215
+ HSUITE_IPFS_CDN_HOST,
216
+ NFT_IMAGE_WIDTH,
217
+ withImageOptimizer,
218
+ } from './ipfs-cdn.js';
@@ -0,0 +1,163 @@
1
+ /**
2
+ * HSuite Native Connect
3
+ * Copyright 2024-2025 HSuite (https://hsuite.finance)
4
+ *
5
+ * SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
6
+ *
7
+ * This file is part of HSuite Native Connect. For commercial licensing,
8
+ * visit https://hsuite.finance/licensing
9
+ */
10
+
11
+ /**
12
+ * @fileoverview Tests for the shared HSuite IPFS CDN primitives.
13
+ *
14
+ * `withImageOptimizer` is the single source of truth for appending the Bunny
15
+ * image-optimizer query (`?optimizer=image&width=N`) to NFT image URLs. It is
16
+ * imported by the SDK gateway layer, the wallet app getters, and the UI render
17
+ * surfaces, so its contract must be airtight: it MUST only rewrite raster
18
+ * images served from the HSuite CDN host, MUST never touch SVG/GIF/video or
19
+ * third-party hosts (Arweave, DaVinci, public gateways), and MUST be
20
+ * idempotent so re-wrapping an already-optimized URL is a no-op.
21
+ */
22
+
23
+ import { describe, it, expect } from 'vitest';
24
+ import {
25
+ HSUITE_IPFS_CDN_BASE,
26
+ HSUITE_IPFS_CDN_HOST,
27
+ NFT_IMAGE_WIDTH,
28
+ withImageOptimizer,
29
+ } from './ipfs-cdn.js';
30
+
31
+ const CID = 'bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi';
32
+
33
+ describe('CDN constants', () => {
34
+ it('exposes the HSuite Bunny CDN host', () => {
35
+ expect(HSUITE_IPFS_CDN_HOST).toBe('hsuite-wallet.b-cdn.net');
36
+ });
37
+
38
+ it('exposes the /ipfs/ base URL on that host', () => {
39
+ expect(HSUITE_IPFS_CDN_BASE).toBe('https://hsuite-wallet.b-cdn.net/ipfs/');
40
+ });
41
+
42
+ it('keeps base and host in sync (no drift)', () => {
43
+ expect(new URL(HSUITE_IPFS_CDN_BASE).hostname).toBe(HSUITE_IPFS_CDN_HOST);
44
+ });
45
+
46
+ it('defines the three surface width tiers', () => {
47
+ expect(NFT_IMAGE_WIDTH.THUMB).toBe(200);
48
+ expect(NFT_IMAGE_WIDTH.GRID).toBe(350);
49
+ expect(NFT_IMAGE_WIDTH.DETAIL).toBe(800);
50
+ });
51
+ });
52
+
53
+ describe('withImageOptimizer — CDN-host raster images', () => {
54
+ it('appends the optimizer query at the default (GRID) width', () => {
55
+ const input = `${HSUITE_IPFS_CDN_BASE}${CID}/art.png`;
56
+ expect(withImageOptimizer(input)).toBe(`${input}?optimizer=image&width=350`);
57
+ });
58
+
59
+ it('honors a caller-supplied width', () => {
60
+ const input = `${HSUITE_IPFS_CDN_BASE}${CID}/art.png`;
61
+ expect(withImageOptimizer(input, NFT_IMAGE_WIDTH.DETAIL)).toBe(
62
+ `${input}?optimizer=image&width=800`,
63
+ );
64
+ });
65
+
66
+ it('optimizes every supported raster extension', () => {
67
+ for (const ext of ['png', 'jpg', 'jpeg', 'webp', 'avif', 'bmp']) {
68
+ const input = `${HSUITE_IPFS_CDN_BASE}${CID}/art.${ext}`;
69
+ expect(withImageOptimizer(input, 200)).toBe(`${input}?optimizer=image&width=200`);
70
+ }
71
+ });
72
+
73
+ it('treats extensions case-insensitively', () => {
74
+ const input = `${HSUITE_IPFS_CDN_BASE}${CID}/ART.PNG`;
75
+ expect(withImageOptimizer(input, 200)).toBe(`${input}?optimizer=image&width=200`);
76
+ });
77
+
78
+ it('preserves a path-bearing CID and joins with & when a query already exists', () => {
79
+ const input = `${HSUITE_IPFS_CDN_BASE}${CID}/25.png?v=2`;
80
+ expect(withImageOptimizer(input, 350)).toBe(`${input}&optimizer=image&width=350`);
81
+ });
82
+ });
83
+
84
+ describe('withImageOptimizer — must NOT rewrite', () => {
85
+ it('leaves SVG untouched (optimizer would rasterize vectors)', () => {
86
+ const input = `${HSUITE_IPFS_CDN_BASE}${CID}/logo.svg`;
87
+ expect(withImageOptimizer(input)).toBe(input);
88
+ });
89
+
90
+ it('leaves GIF untouched (optimizer would flatten animation)', () => {
91
+ const input = `${HSUITE_IPFS_CDN_BASE}${CID}/loop.gif`;
92
+ expect(withImageOptimizer(input)).toBe(input);
93
+ });
94
+
95
+ it('leaves video/3D/audio extensions untouched', () => {
96
+ for (const ext of ['mp4', 'webm', 'glb', 'mp3']) {
97
+ const input = `${HSUITE_IPFS_CDN_BASE}${CID}/media.${ext}`;
98
+ expect(withImageOptimizer(input)).toBe(input);
99
+ }
100
+ });
101
+
102
+ it('leaves extensionless CDN URLs untouched (cannot prove raster)', () => {
103
+ const input = `${HSUITE_IPFS_CDN_BASE}${CID}`;
104
+ expect(withImageOptimizer(input)).toBe(input);
105
+ });
106
+
107
+ it('leaves Arweave images untouched (different host)', () => {
108
+ const input = 'https://arweave.net/abc123/art.png';
109
+ expect(withImageOptimizer(input)).toBe(input);
110
+ });
111
+
112
+ it('leaves DaVinciGraph token images untouched (different host)', () => {
113
+ const input = 'https://s1.pics.davincigraph.io/0.0.123/icon.png';
114
+ expect(withImageOptimizer(input)).toBe(input);
115
+ });
116
+
117
+ it('leaves public IPFS gateway URLs untouched (different host)', () => {
118
+ const input = 'https://ipfs.io/ipfs/QmHash/art.png';
119
+ expect(withImageOptimizer(input)).toBe(input);
120
+ });
121
+
122
+ it('does not match a look-alike host that merely contains the CDN host', () => {
123
+ const input = 'https://hsuite-wallet.b-cdn.net.evil.example/art.png';
124
+ expect(withImageOptimizer(input)).toBe(input);
125
+ });
126
+
127
+ it('does not match the CDN host on a non-standard port (host comparison includes port)', () => {
128
+ const input = `https://${HSUITE_IPFS_CDN_HOST}:9999/ipfs/${CID}/art.png`;
129
+ expect(withImageOptimizer(input)).toBe(input);
130
+ });
131
+ });
132
+
133
+ describe('withImageOptimizer — idempotency & invalid input', () => {
134
+ it('does not double-append when already optimized', () => {
135
+ const input = `${HSUITE_IPFS_CDN_BASE}${CID}/art.png?optimizer=image&width=350`;
136
+ expect(withImageOptimizer(input, 800)).toBe(input);
137
+ });
138
+
139
+ it('returns undefined unchanged', () => {
140
+ expect(withImageOptimizer(undefined)).toBeUndefined();
141
+ });
142
+
143
+ it('returns an empty string unchanged', () => {
144
+ expect(withImageOptimizer('')).toBe('');
145
+ });
146
+
147
+ it('returns malformed / relative URLs unchanged', () => {
148
+ expect(withImageOptimizer('not a url')).toBe('not a url');
149
+ expect(withImageOptimizer('/ipfs/Qm/art.png')).toBe('/ipfs/Qm/art.png');
150
+ });
151
+
152
+ it('falls back to the GRID width for non-positive / non-finite widths', () => {
153
+ const input = `${HSUITE_IPFS_CDN_BASE}${CID}/art.png`;
154
+ expect(withImageOptimizer(input, 0)).toBe(`${input}?optimizer=image&width=350`);
155
+ expect(withImageOptimizer(input, Number.NaN)).toBe(`${input}?optimizer=image&width=350`);
156
+ expect(withImageOptimizer(input, -100)).toBe(`${input}?optimizer=image&width=350`);
157
+ });
158
+
159
+ it('rounds fractional widths to an integer', () => {
160
+ const input = `${HSUITE_IPFS_CDN_BASE}${CID}/art.png`;
161
+ expect(withImageOptimizer(input, 199.6)).toBe(`${input}?optimizer=image&width=200`);
162
+ });
163
+ });
@@ -0,0 +1,152 @@
1
+ /**
2
+ * HSuite Native Connect
3
+ * Copyright 2024-2025 HSuite (https://hsuite.finance)
4
+ *
5
+ * SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
6
+ *
7
+ * This file is part of HSuite Native Connect. For commercial licensing,
8
+ * visit https://hsuite.finance/licensing
9
+ */
10
+
11
+ /**
12
+ * @file Shared HSuite IPFS CDN primitives.
13
+ *
14
+ * The wallet resolves all NFT media (`ipfs://…`) through HSuite's own Bunny
15
+ * CDN, which fronts an IPFS gateway and ships a built-in image optimizer.
16
+ * This module is the single source of truth for:
17
+ *
18
+ * - the CDN host / base URL (so the SDK gateway, the wallet app, and the UI
19
+ * never hardcode the domain independently and drift apart), and
20
+ * - {@link withImageOptimizer}, which appends the Bunny optimizer query
21
+ * (`?optimizer=image&width=N`) so each surface fetches a right-sized
22
+ * variant instead of downloading a full-resolution master for a thumbnail.
23
+ *
24
+ * It lives in `@hsuite/native-connect-types` because that is the only package
25
+ * the SDK, the UI library, and the app all already depend on — the UI does
26
+ * not (and should not) depend on the SDK's channel-protocol/crypto stack.
27
+ *
28
+ * @module ipfs-cdn
29
+ */
30
+
31
+ /**
32
+ * Host of HSuite's Bunny IPFS CDN. Used for an exact-match host check in
33
+ * {@link withImageOptimizer} so the optimizer is never appended to
34
+ * third-party hosts (Arweave, DaVinciGraph, public IPFS gateways).
35
+ */
36
+ export const HSUITE_IPFS_CDN_HOST = 'hsuite-wallet.b-cdn.net';
37
+
38
+ /**
39
+ * Base URL for IPFS content on the HSuite CDN. `convertIpfsUrl` rewrites
40
+ * `ipfs://CID/path` to `${HSUITE_IPFS_CDN_BASE}CID/path`. Derived from
41
+ * {@link HSUITE_IPFS_CDN_HOST} so the host and base can never drift apart.
42
+ */
43
+ export const HSUITE_IPFS_CDN_BASE = `https://${HSUITE_IPFS_CDN_HOST}/ipfs/` as const;
44
+
45
+ /**
46
+ * Logical request widths per render surface, in CSS pixels (already ~2× the
47
+ * display size to cover retina). Bunny returns a variant resized to this
48
+ * width. Tunable in one place; every surface imports from here.
49
+ *
50
+ * - `THUMB` (200): tiny previews — account-overview cover, send NFT picker,
51
+ * approval/transfer hero cards.
52
+ * - `GRID` (350): collection grids and collection cover images.
53
+ * - `DETAIL` (800): the NFT detail-page hero.
54
+ */
55
+ export const NFT_IMAGE_WIDTH = {
56
+ THUMB: 200,
57
+ GRID: 350,
58
+ DETAIL: 800,
59
+ } as const;
60
+
61
+ /**
62
+ * Raster formats the Bunny optimizer can safely resize. SVG (vector) and GIF
63
+ * (animation) are deliberately excluded — optimizing them would rasterize the
64
+ * vector or flatten the animation. Anything else (video/audio/3D, or no
65
+ * extension) is left untouched as well.
66
+ */
67
+ const OPTIMIZABLE_RASTER_EXTENSIONS: ReadonlySet<string> = new Set([
68
+ 'png',
69
+ 'jpg',
70
+ 'jpeg',
71
+ 'webp',
72
+ 'avif',
73
+ 'bmp',
74
+ ]);
75
+
76
+ /**
77
+ * Extract the lowercased file extension from a URL pathname, or `''` when the
78
+ * last path segment has none.
79
+ * @param pathname - The URL pathname (already decoded by the URL parser).
80
+ */
81
+ function fileExtension(pathname: string): string {
82
+ const lastSlash = pathname.lastIndexOf('/');
83
+ const filename = lastSlash >= 0 ? pathname.slice(lastSlash + 1) : pathname;
84
+ const lastDot = filename.lastIndexOf('.');
85
+ return lastDot >= 0 ? filename.slice(lastDot + 1).toLowerCase() : '';
86
+ }
87
+
88
+ /**
89
+ * Append the Bunny image-optimizer query to an HSuite-CDN raster image URL.
90
+ *
91
+ * The transform is intentionally conservative — it returns the input
92
+ * **unchanged** in every case where optimizing would be wrong or unsafe:
93
+ *
94
+ * - empty / `undefined` input,
95
+ * - malformed or relative URLs (cannot be parsed),
96
+ * - any host other than {@link HSUITE_IPFS_CDN_HOST} (Arweave, DaVinci,
97
+ * public IPFS gateways, base64/data URIs),
98
+ * - non-raster or extensionless paths (SVG, GIF, video, audio, 3D, …),
99
+ * - URLs that already carry an `optimizer` param (idempotent — no double
100
+ * append, so re-wrapping is a no-op).
101
+ *
102
+ * Only when the URL is a CDN-hosted raster image does it append
103
+ * `?optimizer=image&width=<width>` (joining with `&` if a query already
104
+ * exists). This makes the helper safe to call from every image getter: it is
105
+ * a guaranteed no-op for non-image media and third-party hosts.
106
+ *
107
+ * @param url - The (already gateway-resolved) image URL, or `undefined`.
108
+ * @param width - Target width in pixels; defaults to {@link NFT_IMAGE_WIDTH}.GRID.
109
+ * Non-finite or non-positive values fall back to GRID; fractional values are
110
+ * rounded.
111
+ * @returns The optimized URL, or the original input unchanged.
112
+ */
113
+ export function withImageOptimizer(
114
+ url: string | undefined,
115
+ width: number = NFT_IMAGE_WIDTH.GRID,
116
+ ): string | undefined {
117
+ // Empty string and undefined pass straight through.
118
+ if (!url) {
119
+ return url;
120
+ }
121
+
122
+ let parsed: URL;
123
+ try {
124
+ parsed = new URL(url);
125
+ } catch {
126
+ // Relative or malformed URLs are never CDN raster images.
127
+ return url;
128
+ }
129
+
130
+ // Exact host match only (host includes any port) — never rewrite
131
+ // third-party hosts, look-alike subdomains, or the CDN host reached
132
+ // on a non-standard port.
133
+ if (parsed.host !== HSUITE_IPFS_CDN_HOST) {
134
+ return url;
135
+ }
136
+
137
+ // Only resize raster formats; leave SVG/GIF/video/extensionless alone.
138
+ if (!OPTIMIZABLE_RASTER_EXTENSIONS.has(fileExtension(parsed.pathname))) {
139
+ return url;
140
+ }
141
+
142
+ // Idempotent: if it's already optimized, return the original untouched.
143
+ if (parsed.searchParams.has('optimizer')) {
144
+ return url;
145
+ }
146
+
147
+ const safeWidth = Number.isFinite(width) && width > 0 ? Math.round(width) : NFT_IMAGE_WIDTH.GRID;
148
+
149
+ parsed.searchParams.set('optimizer', 'image');
150
+ parsed.searchParams.set('width', String(safeWidth));
151
+ return parsed.toString();
152
+ }
package/src/messages.ts CHANGED
@@ -34,6 +34,7 @@ import {
34
34
  LedgerIdSchema,
35
35
  NetworkIdSchema,
36
36
  } from './ledger.js';
37
+ import { KeyAlgorithmSchema, type KeyAlgorithm } from './vault.js';
37
38
 
38
39
  /**
39
40
  * @description Schema for dApp session request payload
@@ -97,6 +98,24 @@ export const SignPayloadSchema = z.object({
97
98
  payload: z.union([z.string(), z.instanceof(Uint8Array)]),
98
99
  derivationPath: DerivationPathSchema.optional(),
99
100
  context: z.record(z.unknown()).optional(),
101
+ /**
102
+ * Optional cryptographic-algorithm hint for raw-scalar keys (e.g. an imported
103
+ * Hedera ECDSA key). This is the typed home for the algorithm on the sign
104
+ * surface; signing chokepoints populate it from the account's VaultKey and the
105
+ * Hedera adapter prefers it over the legacy `context.keyType` fallback.
106
+ */
107
+ keyType: KeyAlgorithmSchema.optional(),
108
+ /**
109
+ * Optional account public key (raw or DER hex) for the fail-safe pre-sign
110
+ * assertion. Populated by {@link WalletCore.signDirect} from the account's
111
+ * VaultKey; the Hedera adapter refuses to sign if the reconstructed key's
112
+ * public key does not match. Best-effort — absent on legacy baselines.
113
+ * Mirrors `SignMessagePayload.expectedPublicKey` so both signing surfaces
114
+ * carry the algorithm fail-safe input in a typed field rather than `context`.
115
+ *
116
+ * @security SOC2-CC6.1 — enables wrong-algorithm signature prevention.
117
+ */
118
+ expectedPublicKey: z.string().optional(),
100
119
  nonce: z.string().uuid().optional(),
101
120
  // Batch transaction support
102
121
  isBatch: z.boolean().optional(),
@@ -171,6 +190,22 @@ export interface SignMessagePayload {
171
190
  * Must match `/^[a-z0-9]+:[a-z0-9]+$/` (CAIP-2 lower-kebab-case shape).
172
191
  */
173
192
  caipChainId: string;
193
+ /**
194
+ * Optional cryptographic-algorithm hint for raw-scalar keys (e.g. an imported
195
+ * Hedera ECDSA key). Populated by {@link WalletCore.signMessageDirect} from the
196
+ * account's VaultKey so the adapter reconstructs the correct PrivateKey instead
197
+ * of defaulting a raw 32-byte key to Ed25519. Mirrors `SignPayload.keyType`.
198
+ */
199
+ keyType?: KeyAlgorithm;
200
+ /**
201
+ * Optional account public key (raw or DER hex) for the fail-safe pre-sign
202
+ * assertion. Populated by {@link WalletCore.signMessageDirect} from the
203
+ * account's VaultKey; the adapter refuses to sign if the reconstructed key's
204
+ * public key does not match. Best-effort — absent on legacy baselines.
205
+ *
206
+ * @security SOC2-CC6.1 — enables wrong-algorithm signature prevention.
207
+ */
208
+ expectedPublicKey?: string;
174
209
  }
175
210
 
176
211
  /**
@@ -909,6 +909,19 @@ export interface RiskFactor {
909
909
  | 'unusual_pattern'
910
910
  | 'high_fee'
911
911
  | 'unknown_token'
912
+ // Scam / suspicious-transaction factor types, populated by the local,
913
+ // chain-agnostic scam-detection engine. Map 1:1 from `ScamFactorType`
914
+ // (@hsuite/native-connect-sdk security/scam-detection) so the approval and
915
+ // history surfaces can render a type-specific icon/label instead of
916
+ // collapsing every scam signal into `'custom'`.
917
+ | 'credential_solicitation'
918
+ | 'phishing_url'
919
+ | 'reward_bait'
920
+ | 'impersonation'
921
+ | 'unicode_obfuscation'
922
+ | 'dust_delivery'
923
+ | 'address_poisoning'
924
+ | 'unknown_counterparty'
912
925
  | 'custom';
913
926
  /** Severity level */
914
927
  severity: 'info' | 'warning' | 'danger';
@@ -918,6 +931,15 @@ export interface RiskFactor {
918
931
  description?: string;
919
932
  /** Help URL for more information (optional) */
920
933
  helpUrl?: string;
934
+ /**
935
+ * When true, this factor is severe enough to force the explicit
936
+ * acknowledgment gate at approval time, and to drive the `critical` banner
937
+ * styling on read-only surfaces (e.g. transaction history, which ignores
938
+ * {@link RiskAssessment.requiresAcknowledgment}). Always paired with
939
+ * `severity: 'danger'`. Optional + additive: absent on factors produced
940
+ * before the scam-detection engine existed.
941
+ */
942
+ critical?: boolean;
921
943
  }
922
944
 
923
945
  /**
@@ -933,6 +955,14 @@ export interface RiskAssessment {
933
955
  confidence?: number;
934
956
  /** Recommendation for user */
935
957
  recommendation?: string;
958
+ /**
959
+ * When true, an approval surface MUST require an explicit user acknowledgment
960
+ * before enabling the action — the tiered scam-alert enforcement gate for
961
+ * high-risk transactions (never a hard block; the wallet is non-custodial).
962
+ * Read-only surfaces such as transaction history ignore this flag. Optional +
963
+ * additive: absent on assessments produced before the scam-detection engine.
964
+ */
965
+ requiresAcknowledgment?: boolean;
936
966
  }
937
967
 
938
968
  /**
package/src/vault.spec.ts CHANGED
@@ -8,6 +8,7 @@ import {
8
8
  VaultKeySchema,
9
9
  VaultConfigSchema,
10
10
  VaultRecoveryBundleSchema,
11
+ KeyAlgorithmSchema,
11
12
  } from './vault.js';
12
13
 
13
14
  describe('VaultSeedSchema', () => {
@@ -266,3 +267,38 @@ describe('Schema extensibility', () => {
266
267
  // Exact behavior depends on schema definition
267
268
  });
268
269
  });
270
+
271
+ describe('keyType typed field', () => {
272
+ it('accepts ed25519 and ecdsa on VaultKey', () => {
273
+ for (const keyType of ['ed25519', 'ecdsa'] as const) {
274
+ const parsed = VaultKeySchema.parse({
275
+ id: crypto.randomUUID(),
276
+ seedId: crypto.randomUUID(),
277
+ ledgerId: 'hedera',
278
+ networkId: 'hedera:testnet',
279
+ address: '0.0.1234',
280
+ publicKey: 'ab12',
281
+ derivationPath: { purpose: 44, coinType: 3030, account: 0, change: 0, addressIndex: 0 },
282
+ protection: 'none',
283
+ keyType,
284
+ });
285
+ expect(parsed.keyType).toBe(keyType);
286
+ }
287
+ });
288
+
289
+ it('rejects an unknown algorithm token', () => {
290
+ expect(() => KeyAlgorithmSchema.parse('secp256k1')).toThrow();
291
+ });
292
+
293
+ it('keyType is optional (back-compat with existing records)', () => {
294
+ const parsed = VaultSeedSchema.parse({
295
+ id: crypto.randomUUID(),
296
+ createdAt: 0,
297
+ encryptedSeed: 'x',
298
+ kdfSalt: 'y',
299
+ derivationScheme: 'imported',
300
+ protection: { mode: 'none' },
301
+ });
302
+ expect(parsed.keyType).toBeUndefined();
303
+ });
304
+ });
package/src/vault.ts CHANGED
@@ -96,6 +96,25 @@ export const VaultRecoverySchema = z.object({
96
96
  */
97
97
  export type VaultRecovery = z.infer<typeof VaultRecoverySchema>;
98
98
 
99
+ /**
100
+ * @description Canonical key algorithm token for Hedera (and any ledger using
101
+ * raw scalar keys). The same 32-byte scalar is valid under both Ed25519 and
102
+ * ECDSA secp256k1, producing different public keys and signatures, so the
103
+ * algorithm must be carried alongside the key.
104
+ *
105
+ * The codebase also uses 'secp256k1' (export service) and 'ecdsa_secp256k1'
106
+ * (message-sign result); those are mapped at their boundaries. The
107
+ * vault/sign/import surface standardizes on this pair.
108
+ *
109
+ * @security SOC2-CC6.1 - enables fail-safe pre-sign algorithm verification.
110
+ */
111
+ export const KeyAlgorithmSchema = z.enum(['ed25519', 'ecdsa']);
112
+
113
+ /**
114
+ * @description Type representing a key algorithm
115
+ */
116
+ export type KeyAlgorithm = z.infer<typeof KeyAlgorithmSchema>;
117
+
99
118
  /**
100
119
  * @description Schema for derived vault key
101
120
  * Moved before VaultRecoveryBundleSchema to avoid forward reference.
@@ -109,6 +128,13 @@ export const VaultKeySchema = z.object({
109
128
  publicKey: z.string(),
110
129
  derivationPath: DerivationPathSchema,
111
130
  protection: VaultProtectionModeSchema,
131
+ /**
132
+ * Cryptographic algorithm of the underlying key. Optional for back-compat:
133
+ * legacy records (written before this field existed) are all Ed25519, since
134
+ * ECDSA import never worked. Read by the signing chokepoints to reconstruct
135
+ * the correct PrivateKey and to assert against the stored public key.
136
+ */
137
+ keyType: KeyAlgorithmSchema.optional(),
112
138
  metadata: z.record(z.unknown()).optional(),
113
139
  });
114
140
 
@@ -180,6 +206,11 @@ export const VaultSeedSchema = z.object({
180
206
  kdfSalt: z.string(),
181
207
  derivationScheme: z.string(),
182
208
  protection: VaultProtectionSchema,
209
+ /**
210
+ * Cryptographic algorithm of the stored seed/key when it is a raw scalar
211
+ * (imported Hedera key). Optional for back-compat. See {@link KeyAlgorithm}.
212
+ */
213
+ keyType: KeyAlgorithmSchema.optional(),
183
214
  metadata: z.record(z.unknown()).optional(),
184
215
  recovery: VaultRecoverySchema.optional(),
185
216
  });