@ghostdagger/ghostlink-server 0.0.0-stage → 0.1.0-beta.2

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/dist/index.js ADDED
@@ -0,0 +1,108 @@
1
+ import {
2
+ createPostgresStorage,
3
+ migratePostgresStorage
4
+ } from "./chunk-44GVNLDI.js";
5
+ import {
6
+ createGhostlinkServer,
7
+ validateKaspaAddress,
8
+ verifyKaspaSignature
9
+ } from "./chunk-DAQY4RJN.js";
10
+ import {
11
+ createSqliteStorage
12
+ } from "./chunk-XMINHYKA.js";
13
+
14
+ // src/storage-conformance.ts
15
+ async function assertStorageConformance(store, peer = store) {
16
+ const assert = (condition, message) => {
17
+ if (!condition) throw new Error(`Storage conformance: ${message}`);
18
+ };
19
+ const now = Date.parse("2026-09-16T12:00:00.000Z");
20
+ await store.putBrowser({ hash: "browser-a", csrf: "csrf", expiresAt: now + 1e4 });
21
+ await store.putBrowser({ hash: "browser-b", csrf: "csrf", expiresAt: now + 1e4 });
22
+ const challenge = { id: "challenge-a", browserHash: "browser-a", profile: "ghostlink-kaspa-v1", address: "fixture-address", network: "testnet-11", message: "fixture", issuedAt: now, expiresAt: new Date(now + 1e3).toISOString() };
23
+ await store.putChallenge(challenge);
24
+ assert(await peer.getChallenge(challenge.id, "browser-b") === null, "challenge binding");
25
+ const session = { hash: "session-a", browserHash: "browser-a", lastSeen: now, session: { address: "fixture-address", accountId: "fixture-account", chainId: "kaspa:testnet-11", network: "testnet-11", issuedAt: new Date(now).toISOString(), expiresAt: new Date(now + 4e3).toISOString(), idleExpiresAt: new Date(now + 2e3).toISOString() }, receipt: { profile: "ghostlink-kaspa-v1", message: "fixture", signature: "fixture" } };
26
+ assert(!await peer.commitLogin(challenge.id, "browser-b", now, { ...session, browserHash: "browser-b" }), "commit browser binding");
27
+ const results = await Promise.all([store.commitLogin(challenge.id, "browser-a", now, session), peer.commitLogin(challenge.id, "browser-a", now, { ...session, hash: "session-other" })]);
28
+ assert(results.filter(Boolean).length === 1, "single atomic challenge consumption");
29
+ const winningHash = results[0] ? session.hash : "session-other";
30
+ assert(await peer.getSession(winningHash, "browser-b", now, 2e3) === null, "session binding");
31
+ assert(await peer.getSession(winningHash, "browser-a", now + 1999, 2e3) !== null, "session idle refresh");
32
+ assert(await store.getSession(winningHash, "browser-a", now + 3999, 2e3) === null, "idle expiry");
33
+ assert(await store.getSession(winningHash, "browser-a", now + 4e3, 5e3) === null, "absolute expiry");
34
+ await store.putChallenge(challenge);
35
+ await peer.revokeBrowser("browser-a");
36
+ assert(await store.getChallenge(challenge.id, "browser-a") === null, "revoke outstanding challenges");
37
+ assert(await store.getSession(winningHash, "browser-a", now, 2e3) === null, "revoke sessions");
38
+ await store.putChallenge(challenge);
39
+ assert(await store.commitLogin(challenge.id, "browser-a", now + 1e3, session) === false, "challenge expiry at commit");
40
+ assert(await store.consumeRateLimit("fixture-limit", now, 1e3, 1), "first rate-limit request");
41
+ assert(!await store.consumeRateLimit("fixture-limit", now, 1e3, 1), "rate-limit enforcement");
42
+ assert(await store.consumeRateLimit("fixture-limit", now + 1e3, 1e3, 1), "rate-limit reset");
43
+ const limited = await Promise.all(Array.from({ length: 12 }, (_, i) => (i % 2 ? peer : store).consumeRateLimit("concurrent-limit", now, 1e3, 3)));
44
+ assert(limited.filter(Boolean).length === 3, "atomic rate limits across instances");
45
+ await store.putChallenge(challenge);
46
+ await peer.putChallenge({ ...challenge, id: "replacement" });
47
+ assert(await store.getChallenge(challenge.id, "browser-a") === null, "challenge replacement");
48
+ assert(await store.commitLogin("replacement", "browser-a", now, session), "replacement login");
49
+ await peer.putChallenge({ ...challenge, id: "rotation" });
50
+ assert(await peer.commitLogin("rotation", "browser-a", now, { ...session, hash: "rotated" }), "session rotation");
51
+ assert(await store.getSession(session.hash, "browser-a", now, 2e3) === null, "old session invalidation");
52
+ assert((await store.getSession("rotated", "browser-a", now + 3999, 5e3))?.idleExpiresAt === session.session.expiresAt, "idle expiry capped by absolute expiry");
53
+ await store.putBrowser({ hash: "expired-browser", csrf: "csrf", expiresAt: now });
54
+ await store.putChallenge({ ...challenge, id: "expired-binding", browserHash: "expired-browser" });
55
+ assert(!await peer.commitLogin("expired-binding", "expired-browser", now, { ...session, browserHash: "expired-browser" }), "expired binding at commit");
56
+ await store.prune(now + 1e4);
57
+ assert(await store.getBrowser("browser-a", now) === null, "expired browser pruning");
58
+ }
59
+
60
+ // src/node.ts
61
+ function createNodeHandler(server) {
62
+ return async (req, res) => {
63
+ res.setHeader("Cache-Control", "no-store");
64
+ res.setHeader("X-Content-Type-Options", "nosniff");
65
+ try {
66
+ if (req.headers.host !== new URL(server.origin).host) {
67
+ res.writeHead(400);
68
+ res.end("Untrusted host");
69
+ return;
70
+ }
71
+ const chunks = [];
72
+ let size = 0;
73
+ for await (const chunk of req) {
74
+ size += chunk.length;
75
+ if (size > 16384) {
76
+ res.writeHead(413);
77
+ res.end("Request too large");
78
+ return;
79
+ }
80
+ chunks.push(chunk);
81
+ }
82
+ const headers = new Headers();
83
+ for (const [name, value] of Object.entries(req.headers)) if (value !== void 0) headers.set(name, Array.isArray(value) ? value.join(", ") : value);
84
+ const request = new Request(new URL(req.url ?? "/", server.origin), { method: req.method, headers, ...!["GET", "HEAD"].includes(req.method ?? "GET") ? { body: Buffer.concat(chunks) } : {} });
85
+ const response = await server.handle(request, { ip: req.socket.remoteAddress });
86
+ res.statusCode = response.status;
87
+ response.headers.forEach((value, key) => {
88
+ if (key !== "set-cookie") res.setHeader(key, value);
89
+ });
90
+ const setCookies = response.headers.getSetCookie();
91
+ if (setCookies.length) res.setHeader("Set-Cookie", setCookies);
92
+ res.end(Buffer.from(await response.arrayBuffer()));
93
+ } catch {
94
+ if (!res.headersSent) res.writeHead(500);
95
+ res.end("Authentication service unavailable");
96
+ }
97
+ };
98
+ }
99
+ export {
100
+ assertStorageConformance,
101
+ createGhostlinkServer,
102
+ createNodeHandler,
103
+ createPostgresStorage,
104
+ createSqliteStorage,
105
+ migratePostgresStorage,
106
+ validateKaspaAddress,
107
+ verifyKaspaSignature
108
+ };
@@ -0,0 +1,26 @@
1
+ import { GhostlinkStorage } from './index.js';
2
+ import '@ghostdagger/ghostlink-core';
3
+
4
+ /** Structural subset shared by pg and @neondatabase/serverless Pool clients. */
5
+ interface PostgresConnection {
6
+ query(text: string, values?: unknown[]): Promise<{
7
+ rows: Record<string, unknown>[];
8
+ }>;
9
+ release(destroy?: boolean): void;
10
+ }
11
+ /** Supply a writable primary pool. Read replicas and HTTP-only query functions are not supported. */
12
+ interface PostgresPool {
13
+ connect(): Promise<PostgresConnection>;
14
+ }
15
+ /** Isolate each application/environment in its own schema or database. */
16
+ interface PostgresStorageOptions {
17
+ /** Owned schema, default ghostlink. Lowercase SQL identifier, at most 63 characters. */
18
+ schema?: string;
19
+ }
20
+ /** Apply the versioned schema once during deployment, using a migration role. Safe to call concurrently. The caller owns the pool and must await pool.end() when finished. */
21
+ declare function migratePostgresStorage(pool: PostgresPool, options?: PostgresStorageOptions): Promise<void>;
22
+ /** Create a Postgres/Neon adapter after migratePostgresStorage. No I/O or pool ownership: share a bounded pool, and await pool.end() at shutdown. All security operations use the writable primary. */
23
+ declare function createPostgresStorage(pool: PostgresPool, options?: PostgresStorageOptions): GhostlinkStorage;
24
+
25
+ export { createPostgresStorage, migratePostgresStorage };
26
+ export type { PostgresConnection, PostgresPool, PostgresStorageOptions };
@@ -0,0 +1,8 @@
1
+ import {
2
+ createPostgresStorage,
3
+ migratePostgresStorage
4
+ } from "./chunk-44GVNLDI.js";
5
+ export {
6
+ createPostgresStorage,
7
+ migratePostgresStorage
8
+ };
@@ -0,0 +1,46 @@
1
+ import { Network, AuthSession } from '@ghostdagger/ghostlink-core';
2
+ import { GhostlinkStorage } from './index.js';
3
+
4
+ /** Trusted authentication policy. Origin/network configuration must agree with the browser client. */
5
+ interface GhostlinkServerConfig {
6
+ /** Exact public HTTP(S) origin, including port when present; no path or trailing slash. */
7
+ origin: string;
8
+ /** Absolute same-origin URI included in login messages; no credentials or fragment. */
9
+ loginUri: string;
10
+ /** Persistence adapter. Use createSqliteStorage or createPostgresStorage; its creator owns database/pool shutdown. */
11
+ storage: GhostlinkStorage;
12
+ /** Nonempty allowed network list. Defaults to mainnet, testnet-10, and testnet-11. */
13
+ networks?: readonly Network[];
14
+ /** Authentication route prefix without a trailing slash. Defaults to /auth/ghostlink. */
15
+ prefix?: string;
16
+ /** Permit HTTP only for localhost/loopback development. Defaults to false; public origins require HTTPS. */
17
+ allowInsecureLocalhost?: boolean;
18
+ /** Challenge lifetime in milliseconds. Defaults to 300_000 (5 minutes); must be positive and at most 300_000. */
19
+ challengeTtlMs?: number;
20
+ /** Absolute session lifetime in milliseconds. Defaults to 86_400_000 (24 hours); must be a positive safe integer. */
21
+ sessionTtlMs?: number;
22
+ /** Idle session lifetime in milliseconds. Defaults to 1_800_000 (30 minutes); successful getSession calls refresh it, capped by absolute expiry. */
23
+ idleTtlMs?: number;
24
+ /** Future-issued challenge tolerance in milliseconds. Defaults to 30_000; allowed range is 0–30_000. */
25
+ clockSkewMs?: number;
26
+ /** Clock returning Unix milliseconds. Defaults to Date.now; override for deterministic tests. */
27
+ now?: () => number;
28
+ }
29
+ /** Request metadata supplied by a trusted server adapter. */
30
+ interface RequestContext {
31
+ ip?: string;
32
+ }
33
+ /** Create Node authentication handlers with cookie sessions, CSRF checks, and signature verification. Validates policy immediately; does not start an HTTP listener or own storage shutdown. */
34
+ declare function createGhostlinkServer(config: GhostlinkServerConfig): {
35
+ /** Handle session/challenge/verify/logout Web requests under prefix. Pass trusted peer metadata for rate limits; returns HTTP failures as Responses. */
36
+ handle: (request: Request, context?: RequestContext) => Promise<Response>;
37
+ /** Read identity from request cookies, returning null if missing/expired. Refreshes idle expiry. Does not enforce application authorization, origin checks, or CSRF for your own routes. */
38
+ getSession: (request: Request) => Promise<AuthSession | null>;
39
+ /** Validated public origin used for audience and Host checks. */
40
+ origin: string;
41
+ /** Authentication route prefix; mount these routes on the same origin as the browser app. */
42
+ prefix: string;
43
+ };
44
+
45
+ export { createGhostlinkServer };
46
+ export type { GhostlinkServerConfig, RequestContext };
package/dist/server.js ADDED
@@ -0,0 +1,6 @@
1
+ import {
2
+ createGhostlinkServer
3
+ } from "./chunk-DAQY4RJN.js";
4
+ export {
5
+ createGhostlinkServer
6
+ };
@@ -0,0 +1,7 @@
1
+ import { GhostlinkStorage } from './index.js';
2
+ import '@ghostdagger/ghostlink-core';
3
+
4
+ /** Open a Node 24 SQLite store, creating parent directories and schema as needed. Use :memory: for isolated tests; otherwise persist this file. The caller must close the store on shutdown. */
5
+ declare function createSqliteStorage(filename: string): GhostlinkStorage;
6
+
7
+ export { createSqliteStorage };
package/dist/sqlite.js ADDED
@@ -0,0 +1,6 @@
1
+ import {
2
+ createSqliteStorage
3
+ } from "./chunk-XMINHYKA.js";
4
+ export {
5
+ createSqliteStorage
6
+ };
@@ -0,0 +1,48 @@
1
+ import { AuthChallenge, AuthSession } from '@ghostdagger/ghostlink-core';
2
+
3
+ interface BrowserRecord {
4
+ hash: string;
5
+ csrf: string;
6
+ expiresAt: number;
7
+ }
8
+ interface ChallengeRecord extends AuthChallenge {
9
+ browserHash: string;
10
+ issuedAt: number;
11
+ }
12
+ interface SessionRecord {
13
+ hash: string;
14
+ browserHash: string;
15
+ session: AuthSession;
16
+ lastSeen: number;
17
+ receipt: {
18
+ profile: string;
19
+ message: string;
20
+ signature: string;
21
+ publicKey?: string;
22
+ };
23
+ }
24
+ /** All times are Unix milliseconds. commitLogin MUST atomically consume the challenge and create the session. Operations must coordinate across independent server instances; subsequent reads must observe completed revocations. Fail closed on storage errors. */
25
+ interface GhostlinkStorage {
26
+ /** Look up an unexpired browser record by its hashed cookie token. */
27
+ getBrowser(hash: string, now: number): Promise<BrowserRecord | null>;
28
+ /** Persist the browser binding and CSRF token. */
29
+ putBrowser(browser: BrowserRecord): Promise<void>;
30
+ /** Store the new challenge, replacing outstanding challenges for the same browser. */
31
+ putChallenge(challenge: ChallengeRecord): Promise<void>;
32
+ /** Look up a challenge only within its bound browser. commitLogin must still enforce expiry. */
33
+ getChallenge(id: string, browserHash: string): Promise<ChallengeRecord | null>;
34
+ /** Atomically consume one unexpired challenge and replace the browser's session. Return false if already consumed, expired, or browser binding is invalid. */
35
+ commitLogin(challengeId: string, browserHash: string, now: number, session: SessionRecord): Promise<boolean>;
36
+ /** Return null for expired/wrong-browser sessions; otherwise refresh lastSeen and idleExpiresAt, capped by absolute expiry. All time arguments are milliseconds. */
37
+ getSession(hash: string, browserHash: string, now: number, idleMs: number): Promise<AuthSession | null>;
38
+ /** Revoke all sessions and outstanding challenges for this browser. */
39
+ revokeBrowser(browserHash: string): Promise<void>;
40
+ /** Atomically consume a request in the given millisecond window; false means the maximum was exceeded. */
41
+ consumeRateLimit(key: string, now: number, windowMs: number, maximum: number): Promise<boolean>;
42
+ /** Remove expired records. now is Unix milliseconds. */
43
+ prune(now: number): Promise<void>;
44
+ /** Optional synchronous shutdown. The storage creator owns calling this when no requests remain. */
45
+ close?(): void;
46
+ }
47
+
48
+ export type { BrowserRecord as B, ChallengeRecord as C, GhostlinkStorage as G, SessionRecord as S };
package/package.json CHANGED
@@ -1,6 +1,58 @@
1
1
  {
2
2
  "name": "@ghostdagger/ghostlink-server",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0-beta.2",
4
+ "type": "module",
5
+ "description": "Server verification and revocable sessions for Ghostlink",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ },
13
+ "./server": {
14
+ "types": "./dist/server.d.ts",
15
+ "import": "./dist/server.js"
16
+ },
17
+ "./postgres": {
18
+ "types": "./dist/postgres.d.ts",
19
+ "import": "./dist/postgres.js"
20
+ },
21
+ "./sqlite": {
22
+ "types": "./dist/sqlite.d.ts",
23
+ "import": "./dist/sqlite.js"
24
+ }
25
+ },
26
+ "files": [
27
+ "dist",
28
+ "vendor",
29
+ "README.md",
30
+ "LICENSE"
31
+ ],
32
+ "sideEffects": false,
33
+ "engines": {
34
+ "node": ">=24 <25"
35
+ },
36
+ "dependencies": {
37
+ "@ghostdagger/ghostlink-core": "0.1.0-beta.2"
38
+ },
39
+ "license": "MIT",
40
+ "repository": {
41
+ "type": "git",
42
+ "url": "git+https://github.com/ghostdagger-labs/ghostlink.git",
43
+ "directory": "packages/ghostlink-server"
44
+ },
45
+ "homepage": "https://github.com/ghostdagger-labs/ghostlink#readme",
46
+ "bugs": {
47
+ "url": "https://github.com/ghostdagger-labs/ghostlink/issues"
48
+ },
49
+ "publishConfig": {
50
+ "registry": "https://registry.npmjs.org/",
51
+ "access": "public",
52
+ "tag": "candidate"
53
+ },
54
+ "scripts": {
55
+ "build": "tsup src/index.ts src/server.ts src/postgres.ts src/sqlite.ts --format esm --dts --clean",
56
+ "typecheck": "tsc -p tsconfig.json"
57
+ }
6
58
  }
@@ -0,0 +1,15 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2022-2024 Kaspa developers
4
+
5
+ Permission to use, copy, modify, and distribute this software for any
6
+ purpose with or without fee is hereby granted, provided that the above
7
+ copyright notice and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
@@ -0,0 +1,206 @@
1
+
2
+ ## WASM32 bindings for Rusty Kaspa SDK
3
+
4
+ [<img alt="github" src="https://img.shields.io/badge/github-kaspanet/rusty--kaspa-8da0cb?style=for-the-badge&labelColor=555555&color=8da0cb&logo=github" height="20">](https://github.com/kaspanet/rusty-kaspa/tree/master/wasm)
5
+ [<img alt="crates.io" src="https://img.shields.io/crates/v/kaspa-wasm.svg?maxAge=2592000&style=for-the-badge&color=fc8d62&logo=rust" height="20">](https://crates.io/crates/kaspa-wasm)
6
+ [<img alt="docs.rs" src="https://img.shields.io/badge/docs.rs-kaspa--wasm-56c2a5?maxAge=2592000&style=for-the-badge&logo=docs.rs" height="20">](https://docs.rs/kaspa-wasm)
7
+ <img alt="license" src="https://img.shields.io/crates/l/kaspa-wasm.svg?maxAge=2592000&color=6ac&style=for-the-badge&logoColor=fff" height="20">
8
+
9
+ Rusty-Kaspa WASM32 bindings offer direct integration of Rust code and Rusty-Kaspa
10
+ codebase within JavaScript and TypeScript environments such as Node.js and Web Browsers.
11
+
12
+ ## Documentation
13
+
14
+ - [**integrating with Kaspa** guide](https://kaspa.aspectron.org/)
15
+ - [**Rust** documentation](https://docs.rs/kaspa-wasm/latest/kaspa_wasm/index.html)
16
+ - [**TypeScript** documentation](https://kaspa.aspectron.org/docs/)
17
+
18
+ Please note that while WASM directly binds JavaScript and Rust resources, their names on JavaScript side
19
+ are different from their name in Rust as they conform to the 'camelCase' convention in JavaScript and
20
+ to the 'snake_case' convention in Rust.
21
+
22
+ The WASM32 bindings can be used in both TypeScript and JavaScript environments, where in JavaScript
23
+ types will not be constrained by TypeScript type definitions.
24
+
25
+ ## Interfaces
26
+
27
+ The SDK is currently separated into the following top-level categories:
28
+
29
+ - **RPC API** — RPC API for the Kaspa node using WebSockets.
30
+ - **Wallet SDK** — Bindings for primitives related to key management and transactions.
31
+ - **Wallet API** — API for the Rusty Kaspa Wallet framework.
32
+
33
+ ## WASM32 SDK release packages
34
+
35
+ The SDK is built as 4 packages for Web Browsers as follows:
36
+ - KeyGen - Key & Address Generation only
37
+ - RPC - RPC only
38
+ - Core - RPC + Key & Address Generation + Wallet SDK
39
+ - Full - Full SDK + Integrated Wallet
40
+ For NodeJS, the SDK is built as a single package containing all features.
41
+
42
+ ## SDK folder structure
43
+
44
+ The following is a brief overview of the SDK folder structure (as available in the release):
45
+
46
+ - `web/kaspa` - **full** Rusty Kaspa WASM32 SDK bindings for use in web browsers.
47
+ - `web/kaspa-rpc` - only the RPC bindings for use in web browsers (reduced WASM binary size).
48
+ - `nodejs/kaspa` - **full** Rusty Kaspa WASM32 SDK bindings for use with NodeJS.
49
+ - `docs` - Rusty Kaspa WASM32 SDK documentation.
50
+ - `examples` folders contain examples for NodeJS and web browsers.
51
+ - `examples/data` - folder used by examples for configuration and wallet data storage.
52
+ - `examples/javascript` - JavaScript examples.
53
+ - `examples/javascript/general` - General SDK examples (keys & derivation, addresses, encryption, etc.).
54
+ - `examples/javascript/transactions` - Creating, sending and receiving transactions.
55
+ - `examples/javascript/wallet` - Interfacing with the Rusty Kaspa Wallet framework.
56
+ - `examples/typescript` - TypeScript examples.
57
+
58
+ If you are using JavaScript and Visual Studio Code, it is highly recommended you replicate
59
+ the `jsconfig.json` configuration file as is done in the SDK examples. This file allows
60
+ Visual Studio to provide TypeScript-like code completion, type checking and documentation.
61
+
62
+ Included documentation in the release can be accessed by loading the `docs/kaspa/index.html`
63
+ file in a web browser.
64
+
65
+ ## Building from Source
66
+
67
+ To build the WASM32 SDK from source, you need to have the Rust environment installed. To do that,
68
+ follow instructions in the [Rusty Kaspa README](https://github.com/kaspanet/rusty-kaspa).
69
+
70
+ Once you have Rust installed, you can build the WASM32 SDK as follows:
71
+
72
+ - `./build-release` - build the release version of the WASM32 SDK + Docs. The release version also contains `debug` builds of the libraries.
73
+ - `./build-web` - build the web package (ES6 module)
74
+ - `./build-node` - build the NodeJS package (CommonJS module)
75
+ - `./build-docs` - runs `build-web` and then generates TypeDoc documentation from the resulting build.
76
+
77
+ Please note that to build from source, you need to have TypeDoc installed globally via `npm install -g typedoc` (see below).
78
+
79
+ ## Running Web examples
80
+
81
+ **IMPORTANT:** To view web examples, you need to serve them from a local web server and
82
+ serve them from the root of the SDK folder (`kaspa-wasm32-sdk` if using a redistributable or
83
+ `rusty-kaspa/wasm` if building from source). This is because examples use relative paths.
84
+ WASM32 currently can not be loaded using the `file://` protocol.
85
+
86
+ You can use any web server of your choice. If you don't have one, you can run one as follows:
87
+ ```bash
88
+ cargo install http-server
89
+ http-server
90
+ ```
91
+ Access the examples at [http://localhost:7878/examples/web/index.html](http://localhost:7878/examples/web/index.html).
92
+ (Make sure to change the port if you are using a different server. Many servers will serve on
93
+ [http://localhost:8000/examples/web/index.html](http://localhost:8000/examples/web/index.html) by default)
94
+
95
+ If building from source, you must run `build-release` or `build-web` scripts before running the examples.
96
+
97
+ ## Running NodeJs examples
98
+
99
+ This applies to running examples while building the project from source as some dependencies are instantiated as a part of the build process. You just need to run `node init` to initialize a local config.
100
+
101
+ NOTES:
102
+ - `npm install` will install NodeJs types for TypeScript and W3C websocket modules
103
+ - `npm install -g typedoc` is needed for the release build to generate documentation
104
+ - `node init` creates a local `examples/data/config.json` that contains a private key (mnemonic) use across NodeJS examples. You can override address used in some examples by specifying the address as a command line argument.
105
+ - Majority of examples will accept following arguments: `node <script> [address] [mainnet|testnet-10|testnet-11] [--address <address>] [--network <mainnet|testnet-10|testnet-11>] [--encoding <borsh|json>]`.
106
+
107
+ By default all wRPC connections use Borsh binary encoding.
108
+
109
+ Example:
110
+ ```bash
111
+ cd wasm
112
+ ./build-release
113
+ cd examples
114
+ npm install
115
+ node init
116
+ node nodejs/javascript/general/rpc.js
117
+ ```
118
+
119
+ ## Using RPC
120
+
121
+ There are multiple ways to use RPC:
122
+ - Control over WebSocket-framed JSON-RPC protocol (you have to manually handle serialization)
123
+ - Use `RpcClient` class that handles the connectivity automatically and provides RPC interfaces in a form of async function calls.
124
+
125
+ **NODEJS:** To use WASM RPC client in the Node.js environment, you need to introduce a W3C WebSocket object
126
+ before loading the WASM32 library. The compatible WebSocket library is [WebSocket](https://www.npmjs.com/package/websocket) and is included in the `kaspa` NPM package. `kaspa` package is a wrapper around `kaspa-wasm` that imports and installs this WebSocket shim in the `globalThis` object and then re-exports `kaspa-wasm` exports.
127
+
128
+
129
+ ## Loading in a Web App
130
+
131
+ ```html
132
+ <html>
133
+ <head>
134
+ <script type="module">
135
+ import * as kaspa from './kaspa/kaspa-wasm.js';
136
+ (async () => {
137
+ await kaspa.default('./kaspa/kaspa-wasm_bg.wasm');
138
+ console.log(kaspa.version());
139
+ // ...
140
+ })();
141
+ </script>
142
+ </head>
143
+ <body></body>
144
+ </html>
145
+ ```
146
+
147
+ ## Loading in a Node.js App
148
+
149
+ ```javascript
150
+ //
151
+ // W3C WebSocket module shim
152
+ // this is provided by NPM `kaspa` module and is only needed
153
+ // if you are building WASM libraries for NodeJS from source
154
+ //
155
+ // @ts-ignore
156
+ // globalThis.WebSocket = require('websocket').w3cwebsocket;
157
+ //
158
+
159
+ let {
160
+ RpcClient,
161
+ Encoding,
162
+ initConsolePanicHook
163
+ } = require('./kaspa');
164
+
165
+ // enabling console panic hooks allows WASM to print panic details to console
166
+ // initConsolePanicHook();
167
+ // enabling browser panic hooks will create a full-page DIV with panic details
168
+ // this is useful for mobile devices where console is not available
169
+ // initBrowserPanicHook();
170
+ ```
171
+
172
+ ```javascript
173
+ // if port is not specified, it will use the default port for the specified network
174
+ const rpc = new RpcClient({
175
+ url: "127.0.0.1",
176
+ encoding: Encoding.Borsh,
177
+ network : "testnet-10"
178
+ });
179
+
180
+ (async () => {
181
+ try {
182
+ await rpc.connect();
183
+ let info = await rpc.getInfo();
184
+ console.log(info);
185
+ } finally {
186
+ await rpc.disconnect();
187
+ }
188
+ })();
189
+ ```
190
+
191
+ For more details, please follow the [**integrating with Kaspa**](https://kaspa.aspectron.org/) guide.
192
+
193
+ ## Creating Documentation
194
+
195
+ Please note that to build documentation from source you need to have the Rust environment installed.
196
+ The build script will first build the WASM32 SDK and then generate typedoc documentation from it.
197
+
198
+ You can build documentation from source as follows:
199
+
200
+ ```bash
201
+ npm install -g typedoc
202
+ ./build-docs
203
+ ```
204
+
205
+ The resulting documentation will be located in `docs/typedoc/`
206
+