@parity/product-sdk-terminal 0.0.0-dev.312.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,337 @@
1
+ # @parity/product-sdk-terminal
2
+
3
+ > Migrated from `@polkadot-apps/terminal` v0.3.0 (`paritytech/polkadot-apps`).
4
+
5
+ QR code login, attestation, and transaction signing for CLI/terminal apps via the Polkadot mobile wallet.
6
+
7
+ Wraps the [`@novasamatech/host-papp`](https://www.npmjs.com/package/@novasamatech/host-papp) SDK with Node.js-compatible adapters (file-based storage, WebSocket transport) so the full SSO protocol works outside the browser.
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ pnpm add @parity/product-sdk-terminal
13
+ ```
14
+
15
+ ## Setup
16
+
17
+ **Requires Node ≥21.** The package relies on the global `WebSocket` exposed by Node 21+ (via `@polkadot-api/ws-provider@0.9`). On older Node versions the WebSocket connection fails at runtime with `WebSocket is not defined`.
18
+
19
+ > **Note (≥0.3):** The `@parity/product-sdk-terminal/register` WASM loader hook has been removed. It existed only to patch `verifiablejs` (a browser-only inline-WASM dependency of `@novasamatech/host-papp`). host-papp ≥0.7.9 no longer uses `verifiablejs` — its sr25519 primitives are pure JS — so no loader hook is needed. Drop any `--import @parity/product-sdk-terminal/register` flags from your `node`/`tsx` invocations.
20
+
21
+ ## Quick Start
22
+
23
+ ```ts
24
+ import { createTerminalAdapter, renderQrCode, waitForSessions } from "@parity/product-sdk-terminal";
25
+
26
+ // 1. Create the adapter
27
+ const adapter = createTerminalAdapter({
28
+ appId: "my-terminal-app",
29
+ });
30
+
31
+ // 2. Subscribe to pairing status to show the QR code
32
+ adapter.sso.pairingStatus.subscribe(async (status) => {
33
+ if (status.step === "pairing") {
34
+ console.log(await renderQrCode(status.payload));
35
+ console.log("Scan with the Polkadot mobile app...");
36
+ }
37
+ });
38
+
39
+ // 3. Authenticate (QR pairing + on-chain attestation)
40
+ const result = await adapter.sso.authenticate();
41
+
42
+ result.match(
43
+ (session) => console.log("Logged in!", session?.id),
44
+ (error) => console.error("Failed:", error.message),
45
+ );
46
+
47
+ // 4. Wait for sessions to load (they load asynchronously from disk)
48
+ const sessions = await waitForSessions(adapter, 2000);
49
+
50
+ // 5. Sign messages via the paired wallet
51
+ if (sessions.length > 0) {
52
+ const session = sessions[0];
53
+ const signer = createSessionSigner(session, adapter);
54
+ // use signer with polkadot-api transactions
55
+ }
56
+ ```
57
+
58
+ ## API
59
+
60
+ ### `createTerminalAdapter(options): TerminalAdapter`
61
+
62
+ Creates a terminal adapter backed by the host-papp SDK.
63
+
64
+ **Options:**
65
+ - `appId` -- unique app identifier (used as storage namespace)
66
+ - `endpoints?` -- statement store WebSocket endpoints (defaults to Paseo)
67
+ - `hostMetadata?` -- optional host environment info
68
+ - `storageDir?` -- override the on-disk session directory (defaults to `~/.polkadot-apps/`). Useful in tests and containerised environments.
69
+
70
+ **Returns** a `TerminalAdapter` with:
71
+ - `appId` -- the value you passed in (re-exposed so `createSessionSigner` can pull the productId from the adapter)
72
+ - `sso` -- auth component (`.authenticate()`, `.abortAuthentication()`, status subscriptions)
73
+ - `sessions` -- session manager (signing, disconnect)
74
+ - `destroy()` -- disconnect the WebSocket and release resources. Idempotent. Suppresses `@novasamatech/statement-store`'s noisy `Statement subscription error` log for ~50 ms after the call.
75
+
76
+ ### `createSessionSigner(session, adapter): PolkadotSigner`
77
+
78
+ Creates a `PolkadotSigner` backed by a QR-paired mobile wallet session, using the session's **default account** (`derivationIndex: 0`) under the adapter's `appId`. This is the right entry point for ~all CLI flows.
79
+
80
+ ```ts
81
+ const [session] = adapter.sessions.sessions.read();
82
+ const signer = createSessionSigner(session, adapter);
83
+ await contract.publish.tx(domain, cid, { signer, origin });
84
+ ```
85
+
86
+ ### `createSessionSignerForAccount(session, ref): PolkadotSigner`
87
+
88
+ Escape hatch for signing as a non-default sub-account of a paired session, or as a `productId` that differs from the adapter's `appId`. Most callers don't need this.
89
+
90
+ `ref` is `{ productId: string; derivationIndex: number }`:
91
+ - `productId` -- dotNS-style identifier of the requesting product. In normal usage this equals the adapter's `appId`; pass a different value only if you have an explicit reason.
92
+ - `derivationIndex` -- BIP32-style child-key index. `0` is the default account; non-zero indices reach additional sub-accounts derived from the same root.
93
+
94
+ ```ts
95
+ const subSigner = createSessionSignerForAccount(session, {
96
+ productId: "my-product",
97
+ derivationIndex: 3,
98
+ });
99
+ ```
100
+
101
+ > **Wire format note:** `@novasamatech/host-papp` 0.7 expects `productAccountId: [productId, derivationIndex]` in `SigningRawRequest`. Both functions above hide that tuple — pass an adapter for the default case or a named-fields object for the escape hatch.
102
+
103
+ ### `renderQrCode(data, options?): Promise<string>`
104
+
105
+ Render a string as a QR code using Unicode half-block characters for terminal display.
106
+
107
+ ### `createNodeStorageAdapter(appId, storageDir?): StorageAdapter`
108
+
109
+ File-based storage adapter for Node.js. Data persists in `storageDir` (defaults to `~/.polkadot-apps/`).
110
+
111
+ ### `waitForSessions(adapter, timeoutMs?): Promise<UserSession[]>`
112
+
113
+ Waits for the session list to emit at least one entry, or resolves with `[]` after `timeoutMs`.
114
+
115
+ ## Allowance signers — the canonical path
116
+
117
+ For CLIs that need to write to Bulletin or publish to the Statement Store: ask the paired wallet for an allowance slot, get a `PolkadotSigner` back, sign extrinsics with it. This is what most consumers want.
118
+
119
+ ```ts
120
+ import {
121
+ createTerminalAdapter,
122
+ getBulletinSigner,
123
+ getStatementStoreProver,
124
+ waitForSessions,
125
+ } from "@parity/product-sdk-terminal";
126
+
127
+ const adapter = createTerminalAdapter({ appId: "my-cli" });
128
+
129
+ // ...QR pair the phone, wait for the session...
130
+ await waitForSessions(adapter);
131
+
132
+ // First call prompts the wallet for an allowance slot; subsequent calls
133
+ // return the cached slot key — no wire round-trip.
134
+ const bulletinSigner = await getBulletinSigner(adapter, "my-cli.dot");
135
+ await bulletinClient.tx.TransactionStorage.store({ data }).signAndSubmit(bulletinSigner);
136
+
137
+ // Same idea, returns a StatementProver for `@novasamatech/statement-store` writes.
138
+ const prover = await getStatementStoreProver(adapter, "my-cli.dot");
139
+ ```
140
+
141
+ ### `getBulletinSigner(adapter, productId, sessionId?): Promise<PolkadotSigner>`
142
+
143
+ ### `getStatementStoreProver(adapter, productId, sessionId?): Promise<StatementProver>`
144
+
145
+ Both default `sessionId` to the only paired session. With zero or more than one paired sessions and no explicit id, both throw `AllowanceError` with `reason: 'NoSession'`. Pass an explicit `sessionId` to disambiguate.
146
+
147
+ Failures from the host (`Rejected`, `NotAvailable`, codec drift) surface as `AllowanceError`:
148
+
149
+ ```ts
150
+ import { AllowanceError } from "@parity/product-sdk-terminal";
151
+
152
+ try {
153
+ const signer = await getBulletinSigner(adapter, "my-cli.dot");
154
+ } catch (err) {
155
+ if (err instanceof AllowanceError && err.reason === "Rejected") {
156
+ // user denied the allowance request on the phone
157
+ }
158
+ throw err;
159
+ }
160
+ ```
161
+
162
+ Behind the scenes both helpers wrap `adapter.allowance` (inherited from host-papp's `PappAdapter`) and unwrap its neverthrow `ResultAsync` into a throwing `Promise`. If you want to keep neverthrow's `.match()` / `.mapErr()` ergonomics or need explicit multi-session handling, call `adapter.allowance.getBulletinSigner(sessionId, productId)` / `getStatementStoreProver(...)` directly.
163
+
164
+ ### Cache-only probes — `hasBulletinAllowance` / `hasStatementStoreAllowance`
165
+
166
+ For paths that must run silently — login health checks, "would calling `getBulletinSigner` prompt the phone?" decisions, readiness probes — use the cache-only variants. They read host-papp's on-disk allowance file directly and **never** trigger a wallet prompt.
167
+
168
+ ```ts
169
+ import {
170
+ getBulletinSigner,
171
+ hasBulletinAllowance,
172
+ } from "@parity/product-sdk-terminal";
173
+
174
+ if (await hasBulletinAllowance(adapter, "my-cli.dot")) {
175
+ // happy path — fetch the signer without risking a wallet prompt
176
+ const signer = await getBulletinSigner(adapter, "my-cli.dot");
177
+ } else {
178
+ // tell the user a wallet prompt will fire, then call getBulletinSigner
179
+ console.log("Approve the allowance request on your phone…");
180
+ const signer = await getBulletinSigner(adapter, "my-cli.dot");
181
+ }
182
+ ```
183
+
184
+ #### `hasBulletinAllowance(adapter, productId, sessionId?): Promise<boolean>`
185
+
186
+ #### `hasStatementStoreAllowance(adapter, productId, sessionId?): Promise<boolean>`
187
+
188
+ Resolves `true` when a slot key for `(sessionId, productId, resource)` is already cached on disk; `false` when it is not (file absent, or present with no matching entry). Same `sessionId` defaulting as the fetching helpers: defaults to the only paired session, throws `AllowanceError('NoSession')` for zero or multiple paired sessions without an explicit id.
189
+
190
+ Rejects only on decrypt or decode failures — a corrupted cache file is a real failure, not a "no allowance" signal.
191
+
192
+ > The cache-only check uses an internal mirror of host-papp's `AllowanceRepository` codec because host-papp doesn't expose a public probe today. We'll switch to the upstream API when one ships; the public surface (`hasBulletinAllowance` / `hasStatementStoreAllowance`) won't change.
193
+
194
+ ## Allowance management — manual cache + AP control (`./host` subpath)
195
+
196
+ For CLIs that need finer control — pre-allocating multiple resources in one wallet prompt, inspecting the cache before round-tripping, or building a signer over a cached key without consulting the wallet — the `@parity/product-sdk-terminal/host` subpath exposes the lower-level Host-runner surface (the [RFC-10](https://github.com/paritytech/triangle-js-sdks/blob/valentunn-rfc-0010/docs/rfcs/0010-allowance.md) Accounts Protocol companion, an on-disk allowance-key cache, and a local sr25519 signer over the cached keys). Most CLIs don't need this — start with `getBulletinSigner` / `getStatementStoreProver` above.
197
+
198
+ ```ts
199
+ import {
200
+ ensureSlotAccountSigner,
201
+ requestResourceAllocation,
202
+ getCachedAllocation,
203
+ createSlotAccountSigner,
204
+ } from "@parity/product-sdk-terminal/host";
205
+
206
+ // First call prompts the wallet; subsequent calls are wire-free.
207
+ const signer = await ensureSlotAccountSigner(session, adapter, {
208
+ tag: "BulletInAllowance",
209
+ value: undefined,
210
+ });
211
+ await bulletinTx.submitAndWatch(signer);
212
+ ```
213
+
214
+ ### `ensureSlotAccountSigner(session, adapter, resource): Promise<PolkadotSigner>`
215
+
216
+ The one call most CLIs want. Cache hit → returns signer; cache miss → allocates via the wallet, then returns signer. Throws on `Rejected` / `NotAvailable`. Slot-table resources only (`BulletInAllowance`, `StatementStoreAllowance`).
217
+
218
+ ### `requestResourceAllocation(session, adapter, resources, options?): Promise<ApAllocationOutcome[]>`
219
+
220
+ Lower-level: pre-allocate any combination of resources. Granted keys cached at `{storageDir}/{appId}_AllowanceKeys.json` (`0o600`, atomic write). `onExisting` auto-picks `Ignore`/`Increase` based on cache state; override via `options.onExisting`.
221
+
222
+ ### `getCachedAllocation(adapter, resource): Promise<CachedAllocation | null>`
223
+
224
+ Read-only cache lookup; no wire round-trip.
225
+
226
+ ### `createSlotAccountSigner(adapter, resource): Promise<PolkadotSigner | null>`
227
+
228
+ Build a `PolkadotSigner` from the cached slot key without round-tripping. Returns `null` if nothing's cached (use `ensureSlotAccountSigner` for the round-trip-if-missing flow).
229
+
230
+ > **Caveats.** `AutoSigning` currently returns `NotAvailable` on both Android and iOS wallets. Slot renewal at expiry depends on [paritytech/individuality#931](https://github.com/paritytech/individuality/pull/931) (open) — first-time allocation works end-to-end today.
231
+
232
+ ## Migration from `@polkadot-apps/terminal`
233
+
234
+ For consumers moving from `@polkadot-apps/terminal` v0.2.0 / v0.3.0. Existing sessions on disk (`~/.polkadot-apps/`) carry over — same `appId`, same path. No re-pairing required for the migration itself.
235
+
236
+ | Concern | `@polkadot-apps/terminal` | `@parity/product-sdk-terminal` |
237
+ | --- | --- | --- |
238
+ | Package name | `@polkadot-apps/terminal` | `@parity/product-sdk-terminal` |
239
+ | WASM loader hook | `--import @polkadot-apps/terminal/register` (required) | **removed** — no `--import` needed (host-papp ≥0.7.9 dropped `verifiablejs`) |
240
+ | `createTerminalAdapter` | `async` — returned `Promise<TerminalAdapter>` | **sync** — returns `TerminalAdapter` directly. Drop the `await`. |
241
+ | Default account signer | `createSessionSigner(session)` | `createSessionSigner(session, adapter)` — pass the adapter as second arg |
242
+ | Non-default sub-account signer | not exposed | `createSessionSignerForAccount(session, { productId, derivationIndex })` |
243
+ | Override session storage dir | not supported (hard-coded `~/.polkadot-apps/`) | `createTerminalAdapter({ ..., storageDir })` option |
244
+ | E2E test helper for sessions | none | `createTestSession` from `@parity/product-sdk-terminal/testing` |
245
+ | Node version | any (bundled `ws`) | **≥21** (uses global `WebSocket`) |
246
+ | `destroy()` shutdown noise | emitted `Statement subscription error` to stderr | suppressed; `console.error` muted for ~50 ms |
247
+
248
+ ### Why the signer API changed
249
+
250
+ `@novasamatech/host-papp` 0.7 replaced `SigningRawRequest.address` with `productAccountId: [productId, derivationIndex]`. The wire format requires both fields, so a session-only argument is no longer enough — the signer needs to know *which sub-account of which product is asking*. We split that into two functions to keep the common case ergonomic:
251
+
252
+ - `createSessionSigner(session, adapter)` for the default account (uses `[adapter.appId, 0]`)
253
+ - `createSessionSignerForAccount(session, { productId, derivationIndex })` for everything else
254
+
255
+ The single-argument `createSessionSigner(session)` from `@polkadot-apps/terminal` no longer works against host-papp 0.7 regardless of which package you use.
256
+
257
+ ### Migration steps
258
+
259
+ 1. **Replace the dep**: `pnpm remove @polkadot-apps/terminal && pnpm add @parity/product-sdk-terminal`
260
+ 2. **Remove the `--import @.../register` flag** from your `node` / `tsx` invocations or `package.json` scripts — the WASM loader hook no longer exists (and is no longer needed).
261
+ 3. **Drop `await`** in front of `createTerminalAdapter(...)` calls.
262
+ 4. **Update each `createSessionSigner` call site**: change `createSessionSigner(session)` → `createSessionSigner(session, adapter)`.
263
+ 5. **Verify Node version** is ≥21 (`node --version`).
264
+
265
+ If your existing sessions don't appear after migrating, double-check that the `appId` is identical to what you used in `@polkadot-apps/terminal` — the on-disk file names depend on it.
266
+
267
+ ## Testing
268
+
269
+ The `@parity/product-sdk-terminal/testing` subpath exports `createTestSession`, a helper that synthesizes a valid persisted session on disk. E2E tests can inject a known-good session without going through QR pairing + attestation:
270
+
271
+ ```ts
272
+ import { mkdtempSync } from "node:fs";
273
+ import { tmpdir } from "node:os";
274
+ import { join } from "node:path";
275
+ import { createTerminalAdapter, waitForSessions } from "@parity/product-sdk-terminal";
276
+ import { createTestSession } from "@parity/product-sdk-terminal/testing";
277
+
278
+ const storageDir = mkdtempSync(join(tmpdir(), "e2e-"));
279
+ const { sessionId } = await createTestSession({
280
+ appId: "my-terminal-app",
281
+ storageDir,
282
+ });
283
+
284
+ const adapter = createTerminalAdapter({
285
+ appId: "my-terminal-app",
286
+ storageDir,
287
+ });
288
+ const sessions = await waitForSessions(adapter);
289
+ // sessions[0].id === sessionId
290
+ ```
291
+
292
+ **Limits and usage notes.**
293
+
294
+ - **Signing does not round-trip.** Both `session.signRaw` and `session.signPayload` go out over the statement store and expect a real phone to respond. Use this helper for flows that test session discovery, persistence, and logout — not happy-path signing.
295
+ - **Expiry tests still work.** The synthesized local account was never registered on the People chain, so any statement-store write from this session fails with `NoAllowanceError`. That's the same error the CLI sees when a previously valid session's on-chain attestation has expired.
296
+ - **No `expiresAt` option.** The on-disk codec has no expiry field; validity lives on chain.
297
+ - **Corrupted-session cases** don't need a helper — `fs.writeFile("<storageDir>/<appId>_SsoSessions.json", "not-hex")` from the test is enough.
298
+
299
+ ## Signing
300
+
301
+ After login and attestation, the paired wallet can sign both transactions and raw messages via the statement store. The `PolkadotSigner` returned by `createSessionSigner` routes each path to the right host-papp method:
302
+
303
+ - **Transactions** (`signTx` from polkadot-api's perspective — what `submitAndWatch`, `signSubmitAndWatch`, contract method calls, etc. invoke) go through `session.signRaw` with the `Payload` tag. polkadot-api assembles the full SCALE-encoded signing payload from runtime metadata — `callData ‖ extras ‖ additionalSigneds` for every signed extension the chain declares — and hands the bytes to the wallet as an opaque hex blob. The wallet signs the payload as-is, with no envelope wrapping. Any signed extension declared by the runtime (including extensions polkadot-api doesn't know about, e.g. `AsPgas` on Paseo Next v2) survives end-to-end because the wallet doesn't inspect the bytes — it just signs them.
304
+ - **Raw bytes** (`signBytes`) go through `session.signRaw` with the `Bytes` tag. Mobile applies the standard `<Bytes>...</Bytes>` anti-phishing wrap before signing — appropriate for arbitrary data, the same behavior `signRaw` has across all Polkadot wallets.
305
+
306
+ > **Note on previous bugs.** Versions prior to `0.1.1` routed *all* signing through `signRaw` with no tag distinction, producing `BadProof`-rejected signatures. Versions `0.1.1` through `0.2.x` then used `polkadot-api/pjs-signer`, which threw `PJS does not support this signed-extension: <name>` on any extension outside its eight built-in mappers (notably `AsPgas`). The current path bypasses both pitfalls.
307
+
308
+ ## Notes
309
+
310
+ ### WebSocket transport
311
+
312
+ The adapter uses `@polkadot-api/ws-provider@0.9`, which relies on the global `WebSocket` exposed by Node ≥21. Older Node versions (18, 20) will fail at connect time with `WebSocket is not defined` — upgrade Node, or pass an explicit `websocketClass` from the [`ws`](https://www.npmjs.com/package/ws) package.
313
+
314
+ The default WebSocket is constructed without `followRedirects: true`, so endpoints behind an HTTP redirect will fail to connect. If you must point at an endpoint that does, supply the resolved URL directly via the `endpoints` option.
315
+
316
+ ## How It Works
317
+
318
+ 1. **QR Pairing** -- generates Sr25519 + P256 keypairs, encodes a `polkadotapp://pair?handshake=0x...` deep link, subscribes to the statement store
319
+ 2. **Attestation** -- registers the local account on the People chain so it can publish statements
320
+ 3. **Signing** -- sends encrypted signing requests to the wallet via the statement store, receives signed responses
321
+
322
+ Sessions are persisted to `~/.polkadot-apps/` and survive across restarts. The SDK loads them asynchronously on startup — subscribe to `adapter.sessions.sessions` and wait for the first emission.
323
+
324
+ ## Dependencies
325
+
326
+ - `@novasamatech/host-papp` -- Polkadot host-product SDK (auth, attestation, signing)
327
+ - `@novasamatech/statement-store` -- statement store client and session management
328
+ - `@novasamatech/storage-adapter` -- storage interface
329
+ - `@polkadot-api/ws-provider` -- WebSocket JSON-RPC provider
330
+ - `neverthrow` -- Result type for error handling
331
+ - `qrcode` -- QR code generation
332
+
333
+ ## Future Work
334
+
335
+ - **`KvStore`↔`StorageAdapter` bridge.** This package implements its own file-backed `StorageAdapter` for Node.js (`createNodeStorageAdapter`). Once `@parity/product-sdk-local-storage` grows a file backend with the same `read/write/clear/subscribe` `ResultAsync` shape, replace `node-storage.ts` with a thin adapter over it.
336
+ - **Codec re-exports from `@parity/product-sdk-statement-store`.** `testing.ts` imports session-account codec helpers (`AccountIdCodec`, `LocalSessionAccountCodec`, etc.) directly from `@novasamatech/statement-store`. Re-exporting them through the in-monorepo wrapper would let this package depend only on workspace siblings.
337
+ - **`@noble/*` major version drift.** This package pins `@noble/{ciphers,curves,hashes}: ^2.x` because upstream `@polkadot-apps/terminal` did, and the `testing.ts` codec helpers use the v2 import paths (`@noble/hashes/blake2.js`, `@noble/curves/nist.js`). The rest of the monorepo is on `^1.x`. Both majors coexist in the lockfile; not a runtime problem today but worth a coordinated bump. Either move the whole monorepo to v2, or rewrite `testing.ts` against v1 paths (`@noble/hashes/blake2b.js` etc.).