@parity/product-sdk-terminal 0.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.
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,261 @@
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
+ **Register the WASM loader** — the host-papp SDK depends on `verifiablejs` which uses inline WASM (browser-only). The register hook redirects it to the Node.js WASM build. Pass it via `--import`:
20
+
21
+ ```bash
22
+ node --import @parity/product-sdk-terminal/register app.js
23
+ tsx --import @parity/product-sdk-terminal/register app.ts
24
+ ```
25
+
26
+ Or in your `package.json` scripts:
27
+
28
+ ```json
29
+ {
30
+ "scripts": {
31
+ "start": "tsx --import @parity/product-sdk-terminal/register index.ts"
32
+ }
33
+ }
34
+ ```
35
+
36
+ ## Quick Start
37
+
38
+ ```ts
39
+ import { createTerminalAdapter, renderQrCode, waitForSessions } from "@parity/product-sdk-terminal";
40
+
41
+ // 1. Create the adapter
42
+ const adapter = createTerminalAdapter({
43
+ appId: "my-terminal-app",
44
+ metadataUrl: "https://example.com/metadata.json",
45
+ });
46
+
47
+ // 2. Subscribe to pairing status to show the QR code
48
+ adapter.sso.pairingStatus.subscribe(async (status) => {
49
+ if (status.step === "pairing") {
50
+ console.log(await renderQrCode(status.payload));
51
+ console.log("Scan with the Polkadot mobile app...");
52
+ }
53
+ });
54
+
55
+ // 3. Authenticate (QR pairing + on-chain attestation)
56
+ const result = await adapter.sso.authenticate();
57
+
58
+ result.match(
59
+ (session) => console.log("Logged in!", session?.id),
60
+ (error) => console.error("Failed:", error.message),
61
+ );
62
+
63
+ // 4. Wait for sessions to load (they load asynchronously from disk)
64
+ const sessions = await waitForSessions(adapter, 2000);
65
+
66
+ // 5. Sign messages via the paired wallet
67
+ if (sessions.length > 0) {
68
+ const session = sessions[0];
69
+ const signer = createSessionSigner(session, adapter);
70
+ // use signer with polkadot-api transactions
71
+ }
72
+ ```
73
+
74
+ ## API
75
+
76
+ ### `createTerminalAdapter(options): TerminalAdapter`
77
+
78
+ Creates a terminal adapter backed by the host-papp SDK.
79
+
80
+ **Options:**
81
+ - `appId` -- unique app identifier (used as storage namespace)
82
+ - `metadataUrl` -- URL to metadata JSON shown during pairing
83
+ - `endpoints?` -- statement store WebSocket endpoints (defaults to Paseo)
84
+ - `hostMetadata?` -- optional host environment info
85
+ - `storageDir?` -- override the on-disk session directory (defaults to `~/.polkadot-apps/`). Useful in tests and containerised environments.
86
+
87
+ **Returns** a `TerminalAdapter` with:
88
+ - `appId` -- the value you passed in (re-exposed so `createSessionSigner` can pull the productId from the adapter)
89
+ - `sso` -- auth component (`.authenticate()`, `.abortAuthentication()`, status subscriptions)
90
+ - `sessions` -- session manager (signing, disconnect)
91
+ - `destroy()` -- disconnect the WebSocket and release resources. Idempotent. Suppresses `@novasamatech/statement-store`'s noisy `Statement subscription error` log for ~50 ms after the call.
92
+
93
+ ### `createSessionSigner(session, adapter): PolkadotSigner`
94
+
95
+ 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.
96
+
97
+ ```ts
98
+ const [session] = adapter.sessions.sessions.read();
99
+ const signer = createSessionSigner(session, adapter);
100
+ await contract.publish.tx(domain, cid, { signer, origin });
101
+ ```
102
+
103
+ ### `createSessionSignerForAccount(session, ref): PolkadotSigner`
104
+
105
+ 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.
106
+
107
+ `ref` is `{ productId: string; derivationIndex: number }`:
108
+ - `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.
109
+ - `derivationIndex` -- BIP32-style child-key index. `0` is the default account; non-zero indices reach additional sub-accounts derived from the same root.
110
+
111
+ ```ts
112
+ const subSigner = createSessionSignerForAccount(session, {
113
+ productId: "my-product",
114
+ derivationIndex: 3,
115
+ });
116
+ ```
117
+
118
+ > **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.
119
+
120
+ ### `renderQrCode(data, options?): Promise<string>`
121
+
122
+ Render a string as a QR code using Unicode half-block characters for terminal display.
123
+
124
+ ### `createNodeStorageAdapter(appId, storageDir?): StorageAdapter`
125
+
126
+ File-based storage adapter for Node.js. Data persists in `storageDir` (defaults to `~/.polkadot-apps/`).
127
+
128
+ ### `waitForSessions(adapter, timeoutMs?): Promise<UserSession[]>`
129
+
130
+ Waits for the session list to emit at least one entry, or resolves with `[]` after `timeoutMs`.
131
+
132
+ ## Migration from `@polkadot-apps/terminal`
133
+
134
+ 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.
135
+
136
+ | Concern | `@polkadot-apps/terminal` | `@parity/product-sdk-terminal` |
137
+ | --- | --- | --- |
138
+ | Package name | `@polkadot-apps/terminal` | `@parity/product-sdk-terminal` |
139
+ | Register import path | `--import @polkadot-apps/terminal/register` | `--import @parity/product-sdk-terminal/register` |
140
+ | `createTerminalAdapter` | `async` — returned `Promise<TerminalAdapter>` | **sync** — returns `TerminalAdapter` directly. Drop the `await`. |
141
+ | Default account signer | `createSessionSigner(session)` | `createSessionSigner(session, adapter)` — pass the adapter as second arg |
142
+ | Non-default sub-account signer | not exposed | `createSessionSignerForAccount(session, { productId, derivationIndex })` |
143
+ | Override session storage dir | not supported (hard-coded `~/.polkadot-apps/`) | `createTerminalAdapter({ ..., storageDir })` option |
144
+ | E2E test helper for sessions | none | `createTestSession` from `@parity/product-sdk-terminal/testing` |
145
+ | Node version | any (bundled `ws`) | **≥21** (uses global `WebSocket`) |
146
+ | `destroy()` shutdown noise | emitted `Statement subscription error` to stderr | suppressed; `console.error` muted for ~50 ms |
147
+
148
+ ### Why the signer API changed
149
+
150
+ `@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:
151
+
152
+ - `createSessionSigner(session, adapter)` for the default account (uses `[adapter.appId, 0]`)
153
+ - `createSessionSignerForAccount(session, { productId, derivationIndex })` for everything else
154
+
155
+ The single-argument `createSessionSigner(session)` from `@polkadot-apps/terminal` no longer works against host-papp 0.7 regardless of which package you use.
156
+
157
+ ### Migration steps
158
+
159
+ 1. **Replace the dep**: `pnpm remove @polkadot-apps/terminal && pnpm add @parity/product-sdk-terminal`
160
+ 2. **Update the `--import` flag** in your `node` / `tsx` invocations or `package.json` scripts.
161
+ 3. **Drop `await`** in front of `createTerminalAdapter(...)` calls.
162
+ 4. **Update each `createSessionSigner` call site**: change `createSessionSigner(session)` → `createSessionSigner(session, adapter)`.
163
+ 5. **Verify Node version** is ≥21 (`node --version`).
164
+
165
+ 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.
166
+
167
+ ## Testing
168
+
169
+ 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:
170
+
171
+ ```ts
172
+ import { mkdtempSync } from "node:fs";
173
+ import { tmpdir } from "node:os";
174
+ import { join } from "node:path";
175
+ import { createTerminalAdapter, waitForSessions } from "@parity/product-sdk-terminal";
176
+ import { createTestSession } from "@parity/product-sdk-terminal/testing";
177
+
178
+ const storageDir = mkdtempSync(join(tmpdir(), "e2e-"));
179
+ const { sessionId } = await createTestSession({
180
+ appId: "my-terminal-app",
181
+ storageDir,
182
+ });
183
+
184
+ const adapter = createTerminalAdapter({
185
+ appId: "my-terminal-app",
186
+ metadataUrl: "https://example.com/metadata.json",
187
+ storageDir,
188
+ });
189
+ const sessions = await waitForSessions(adapter);
190
+ // sessions[0].id === sessionId
191
+ ```
192
+
193
+ **Limits and usage notes.**
194
+
195
+ - **Signing does not round-trip.** `session.signRaw` goes out over the statement store and expects a real phone to respond. Use this helper for flows that test session discovery, persistence, and logout — not happy-path signing.
196
+ - **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.
197
+ - **No `expiresAt` option.** The on-disk codec has no expiry field; validity lives on chain.
198
+ - **Corrupted-session cases** don't need a helper — `fs.writeFile("<storageDir>/<appId>_SsoSessions.json", "not-hex")` from the test is enough.
199
+
200
+ ## Signing
201
+
202
+ After login and attestation, the paired wallet can sign messages via the statement store.
203
+
204
+ **`signRaw`** works end-to-end: the wallet receives the request, shows a prompt, and returns the signature.
205
+
206
+ **`signPayload`** (for signing transaction payloads) is not yet functional — the request is submitted but the wallet does not respond. This is a known limitation of the current wallet/protocol version.
207
+
208
+ ## Notes
209
+
210
+ ### WebSocket transport
211
+
212
+ 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.
213
+
214
+ 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.
215
+
216
+ ### `ExperimentalWarning: Importing WebAssembly module instances`
217
+
218
+ You'll see this warning at startup:
219
+
220
+ ```
221
+ (node:NNNNN) ExperimentalWarning: Importing WebAssembly module instances is an experimental feature and might change at any time
222
+ ```
223
+
224
+ It's emitted by Node when the loader hook imports the `verifiablejs` WASM. Harmless. To silence it, run with `--no-warnings=ExperimentalWarning`.
225
+
226
+ ## How It Works
227
+
228
+ 1. **QR Pairing** -- generates Sr25519 + P256 keypairs, encodes a `polkadotapp://pair?handshake=0x...` deep link, subscribes to the statement store
229
+ 2. **Attestation** -- registers the local account on the People chain so it can publish statements
230
+ 3. **Signing** -- sends encrypted signing requests to the wallet via the statement store, receives signed responses
231
+
232
+ 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.
233
+
234
+ ## Dependencies
235
+
236
+ - `@novasamatech/host-papp` -- Polkadot host-product SDK (auth, attestation, signing)
237
+ - `@novasamatech/statement-store` -- statement store client and session management
238
+ - `@novasamatech/storage-adapter` -- storage interface
239
+ - `@polkadot-api/ws-provider` -- WebSocket JSON-RPC provider
240
+ - `neverthrow` -- Result type for error handling
241
+ - `qrcode` -- QR code generation
242
+
243
+ ## Future Work
244
+
245
+ - **`KvStore`↔`StorageAdapter` bridge.** This package implements its own file-backed `StorageAdapter` for Node.js (`createNodeStorageAdapter`). Once `@parity/product-sdk-storage` grows a file backend with the same `read/write/clear/subscribe` `ResultAsync` shape, replace `node-storage.ts` with a thin adapter over it.
246
+ - **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.
247
+ - **Embedded host runner for allowance / attestation refresh.** Today this package consumes a paired session and signs against it, but cannot renew the on-chain attestation that gates allowance writes — once it expires the user has to re-do the full QR pairing. The proposed fix is a new `./host` sub-export (in addition to `.`, `./register`, `./testing`) exposing roughly:
248
+ ```ts
249
+ // proposed shape — not yet implemented
250
+ export interface AllowanceManager {
251
+ isExpired(): boolean;
252
+ refresh(): ResultAsync<void, Error>;
253
+ currentAttestation(): ResultAsync<Attestation, Error>;
254
+ }
255
+ export function createAllowanceManager(
256
+ adapter: TerminalAdapter,
257
+ options?: { hostEndpoint?: string },
258
+ ): AllowanceManager;
259
+ ```
260
+ Implementation should sit on top of `@parity/product-sdk-host`'s container/storage primitives so the host runner is shared with browser/desktop hosts rather than being CLI-specific. This is the gap Tarik flagged as "the CLI might also need to run some kind of host to get allowances".
261
+ - **`@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.).
@@ -0,0 +1,210 @@
1
+ // src/node-storage.ts
2
+ import { createLogger } from "@parity/product-sdk-logger";
3
+ import { fromPromise } from "neverthrow";
4
+ import { join } from "path";
5
+ import { readFile, writeFile, mkdir, unlink } from "fs/promises";
6
+ import { homedir } from "os";
7
+ var log = createLogger("terminal");
8
+ var DEFAULT_STORAGE_DIR = join(homedir(), ".polkadot-apps");
9
+ function sanitizeKey(appId, key) {
10
+ return `${appId}_${key}`.replace(/[^a-zA-Z0-9_.-]/g, "_");
11
+ }
12
+ function toError(e) {
13
+ return e instanceof Error ? e : new Error(String(e));
14
+ }
15
+ function createNodeStorageAdapter(appId, storageDir) {
16
+ const dir = storageDir ?? DEFAULT_STORAGE_DIR;
17
+ let dirCreated = false;
18
+ const subscribers = /* @__PURE__ */ new Map();
19
+ function fp(key) {
20
+ return join(dir, `${sanitizeKey(appId, key)}.json`);
21
+ }
22
+ async function ensureDir() {
23
+ if (dirCreated) return;
24
+ await mkdir(dir, { recursive: true });
25
+ dirCreated = true;
26
+ }
27
+ function notifySubscribers(key, value) {
28
+ const subs = subscribers.get(key);
29
+ if (subs) {
30
+ for (const cb of subs) {
31
+ try {
32
+ cb(value);
33
+ } catch (e) {
34
+ log.warn("storage subscriber callback threw", { key, error: e });
35
+ }
36
+ }
37
+ }
38
+ }
39
+ return {
40
+ read(key) {
41
+ return fromPromise(
42
+ readFile(fp(key), "utf-8").catch((e) => {
43
+ if (e.code !== "ENOENT") {
44
+ log.warn("storage read failed", { key, error: e });
45
+ } else {
46
+ log.debug("storage read miss", { key });
47
+ }
48
+ return null;
49
+ }),
50
+ toError
51
+ );
52
+ },
53
+ write(key, value) {
54
+ return fromPromise(
55
+ ensureDir().then(() => writeFile(fp(key), value, "utf-8")).then(() => {
56
+ notifySubscribers(key, value);
57
+ }),
58
+ toError
59
+ ).map(() => void 0);
60
+ },
61
+ clear(key) {
62
+ return fromPromise(
63
+ unlink(fp(key)).catch(() => {
64
+ }).then(() => {
65
+ notifySubscribers(key, null);
66
+ }),
67
+ toError
68
+ ).map(() => void 0);
69
+ },
70
+ subscribe(key, callback) {
71
+ if (!subscribers.has(key)) {
72
+ subscribers.set(key, /* @__PURE__ */ new Set());
73
+ }
74
+ subscribers.get(key).add(callback);
75
+ return () => {
76
+ subscribers.get(key)?.delete(callback);
77
+ };
78
+ }
79
+ };
80
+ }
81
+ if (void 0) {
82
+ const { describe, test, expect, beforeEach, afterAll } = void 0;
83
+ const { mkdtemp, rm } = await null;
84
+ const { tmpdir } = await null;
85
+ const { configure } = await null;
86
+ let testDir;
87
+ beforeEach(async () => {
88
+ configure({ handler: () => {
89
+ } });
90
+ testDir = await mkdtemp(join(tmpdir(), "terminal-storage-test-"));
91
+ });
92
+ afterAll(async () => {
93
+ try {
94
+ await rm(testDir, { recursive: true });
95
+ } catch {
96
+ }
97
+ });
98
+ describe("createNodeStorageAdapter", () => {
99
+ test("read returns null for missing key", async () => {
100
+ const store = createNodeStorageAdapter("test", testDir);
101
+ const result = await store.read("nonexistent");
102
+ expect(result.isOk()).toBe(true);
103
+ expect(result._unsafeUnwrap()).toBeNull();
104
+ });
105
+ test("write and read round-trip", async () => {
106
+ const store = createNodeStorageAdapter("test", testDir);
107
+ await store.write("key1", "hello");
108
+ const result = await store.read("key1");
109
+ expect(result._unsafeUnwrap()).toBe("hello");
110
+ });
111
+ test("write overwrites existing value", async () => {
112
+ const store = createNodeStorageAdapter("test", testDir);
113
+ await store.write("key1", "first");
114
+ await store.write("key1", "second");
115
+ const result = await store.read("key1");
116
+ expect(result._unsafeUnwrap()).toBe("second");
117
+ });
118
+ test("clear removes key", async () => {
119
+ const store = createNodeStorageAdapter("test", testDir);
120
+ await store.write("key1", "value");
121
+ await store.clear("key1");
122
+ const result = await store.read("key1");
123
+ expect(result._unsafeUnwrap()).toBeNull();
124
+ });
125
+ test("clear is safe for missing key", async () => {
126
+ const store = createNodeStorageAdapter("test", testDir);
127
+ const result = await store.clear("nonexistent");
128
+ expect(result.isOk()).toBe(true);
129
+ });
130
+ test("different appIds are isolated", async () => {
131
+ const storeA = createNodeStorageAdapter("app-a", testDir);
132
+ const storeB = createNodeStorageAdapter("app-b", testDir);
133
+ await storeA.write("key", "from-a");
134
+ await storeB.write("key", "from-b");
135
+ expect((await storeA.read("key"))._unsafeUnwrap()).toBe("from-a");
136
+ expect((await storeB.read("key"))._unsafeUnwrap()).toBe("from-b");
137
+ });
138
+ test("subscribe notifies on write", async () => {
139
+ const store = createNodeStorageAdapter("test", testDir);
140
+ const values = [];
141
+ store.subscribe("key1", (v) => values.push(v));
142
+ await store.write("key1", "hello");
143
+ expect(values).toEqual(["hello"]);
144
+ });
145
+ test("subscribe notifies on clear", async () => {
146
+ const store = createNodeStorageAdapter("test", testDir);
147
+ const values = [];
148
+ await store.write("key1", "hello");
149
+ store.subscribe("key1", (v) => values.push(v));
150
+ await store.clear("key1");
151
+ expect(values).toEqual([null]);
152
+ });
153
+ test("unsubscribe stops notifications", async () => {
154
+ const store = createNodeStorageAdapter("test", testDir);
155
+ const values = [];
156
+ const unsub = store.subscribe("key1", (v) => values.push(v));
157
+ await store.write("key1", "first");
158
+ unsub();
159
+ await store.write("key1", "second");
160
+ expect(values).toEqual(["first"]);
161
+ });
162
+ test("subscriber errors do not break other subscribers", async () => {
163
+ const store = createNodeStorageAdapter("test", testDir);
164
+ const values = [];
165
+ store.subscribe("key1", () => {
166
+ throw new Error("boom");
167
+ });
168
+ store.subscribe("key1", (v) => {
169
+ if (v) values.push(v);
170
+ });
171
+ await store.write("key1", "hello");
172
+ expect(values).toEqual(["hello"]);
173
+ });
174
+ test("sanitizes special characters in keys", async () => {
175
+ const store = createNodeStorageAdapter("test", testDir);
176
+ await store.write("key/with:special chars!", "value");
177
+ const result = await store.read("key/with:special chars!");
178
+ expect(result._unsafeUnwrap()).toBe("value");
179
+ });
180
+ test("handles JSON values", async () => {
181
+ const store = createNodeStorageAdapter("test", testDir);
182
+ const obj = { name: "test", count: 42, nested: { ok: true } };
183
+ await store.write("json", JSON.stringify(obj));
184
+ const raw = (await store.read("json"))._unsafeUnwrap();
185
+ expect(JSON.parse(raw)).toEqual(obj);
186
+ });
187
+ });
188
+ describe("toError", () => {
189
+ test("returns Error instances unchanged", () => {
190
+ const original = new TypeError("boom");
191
+ expect(toError(original)).toBe(original);
192
+ });
193
+ test("wraps non-Error string values", () => {
194
+ const result = toError("primitive failure");
195
+ expect(result).toBeInstanceOf(Error);
196
+ expect(result.message).toBe("primitive failure");
197
+ });
198
+ test("wraps non-Error nullish values", () => {
199
+ const result = toError(null);
200
+ expect(result).toBeInstanceOf(Error);
201
+ expect(result.message).toBe("null");
202
+ });
203
+ });
204
+ }
205
+
206
+ export {
207
+ sanitizeKey,
208
+ createNodeStorageAdapter
209
+ };
210
+ //# sourceMappingURL=chunk-5MCLSFKQ.js.map