@rodit/hola-client 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/README.md ADDED
@@ -0,0 +1,104 @@
1
+ # @rodit/hola-client
2
+
3
+ Node helpers for IdentyClaw **HOLA line** construction — uppercase canonicalization, RFC 4648 base32 signatures, and mod-23 checksum.
4
+
5
+ This package handles **HOLA protocol signing only**. It does **not** perform API login. You need a separate **API bearer token** (`jwt_token` from `POST /api/login`) before calling `getNonce` or `createHola`.
6
+
7
+ | Concern | This package | IdentyClaw server docs |
8
+ | --- | --- | --- |
9
+ | API session (JWT) | Caller supplies `jwt` | [login-authentication.md](https://github.com/discernible-io/idclawserver-idc/blob/main/references/login-authentication.md) |
10
+ | HOLA nonce | `getNonce` → `GET /api/holanonce16ts` | [holanonce-api.md](https://github.com/discernible-io/idclawserver-idc/blob/main/references/holanonce-api.md) |
11
+ | HOLA line format | `buildAndSign`, `createHola` | [hola-agent-authentication.md](https://github.com/discernible-io/idclawserver-idc/blob/main/references/hola-agent-authentication.md) |
12
+ | Peer verify | Not included — use `@rodit/verify-hola` or API | `npx @rodit/verify-hola` / `POST /api/identity/verify` |
13
+
14
+ **Do not confuse timestamps:** login uses `timestamp_iso` from `GET /api/login/timestamp`. HOLA uses `timestamp` + `noncetsHex` from `GET /api/holanonce16ts`.
15
+
16
+ ---
17
+
18
+ ## Install
19
+
20
+ ```bash
21
+ npm install @rodit/hola-client
22
+ ```
23
+
24
+ From this monorepo (no npm publish required):
25
+
26
+ ```bash
27
+ cd hola-client && npm install
28
+ ```
29
+
30
+ Peer verification: use [`@rodit/verify-hola`](../verify-hola/) (`npx @rodit/verify-hola report "HOLA/..."`) or `POST /api/identity/verify`.
31
+
32
+ ---
33
+
34
+ ## API
35
+
36
+ | Export | Purpose |
37
+ | --- | --- |
38
+ | `createHola({ nearPrivateKey, jwt, tokenId, ... })` | API session + nonce fetch + local HOLA sign (recommended) |
39
+ | `getNonce({ baseUrl, jwt })` | `GET /api/holanonce16ts` (requires API bearer token) |
40
+ | `buildAndSign({ recipient, tokenId, timestamp, noncetsHex, privateKey })` | Build standard HOLA line when you already have nonce fields |
41
+ | `nearPrivateKeyToSigningSecretKey(nearPrivateKey)` | NEAR `ed25519:` key → tweetnacl secret (stays on host) |
42
+ | `buildCanonicalPrefix(...)` | Unsigned uppercase prefix (testing) |
43
+ | `parseHola(holaString)` | Format + checksum parse (not full trust / on-chain verify) |
44
+ | `computeHolaChecksum(prefix)` | Mod-23 checksum letter |
45
+ | `buildCollaborationEnvelope(...)` | `identyclaw.collaboration.v1` task wrapper |
46
+ | `parseCollaborationEnvelope(input)` | Parse JSON or ` ```identyclaw ` fenced message |
47
+ | `formatSessionsSendMessage(envelope)` | OpenClaw `sessions_send` body with fence |
48
+ | `assertCollaborationTrust(envelope, verifyResult)` | Trust decision after API verify |
49
+
50
+ `privateKey` is a 64-byte tweetnacl Ed25519 secret key. HOLA line signatures use **base32**; API login uses **base64url** over a different message — see server login docs.
51
+
52
+ ---
53
+
54
+ ## Example — full create path
55
+
56
+ ```javascript
57
+ const { createHola } = require("@rodit/hola-client");
58
+
59
+ // jwt_token from POST /api/login — NOT a HOLA line
60
+ const { hola } = await createHola({
61
+ baseUrl: "https://api.identyclaw.com",
62
+ jwt: process.env.IDENTYCLAW_JWT,
63
+ nearPrivateKey: process.env.IDENTYCLAW_NEAR_PRIVATE_KEY,
64
+ tokenId: "yourpassportid",
65
+ recipient: "MUNDO"
66
+ });
67
+ // hola is the wire string to send to a peer or POST /api/testhola
68
+ ```
69
+
70
+ ## Example — manual nonce + sign
71
+
72
+ ```javascript
73
+ const { getNonce, buildAndSign, nearPrivateKeyToSigningSecretKey } = require("@rodit/hola-client");
74
+
75
+ const { noncetsHex, timestamp } = await getNonce({
76
+ baseUrl: "https://api.identyclaw.com",
77
+ jwt: process.env.IDENTYCLAW_JWT
78
+ });
79
+ const privateKey = nearPrivateKeyToSigningSecretKey(process.env.IDENTYCLAW_NEAR_PRIVATE_KEY);
80
+
81
+ const { hola } = buildAndSign({
82
+ recipient: "MUNDO",
83
+ tokenId: "yourpassportid",
84
+ timestamp,
85
+ noncetsHex,
86
+ privateKey
87
+ });
88
+ ```
89
+
90
+ Peer verification: `npx @rodit/verify-hola report "HOLA/..."` or `POST /api/identity/verify`.
91
+
92
+ ---
93
+
94
+ ## Tests
95
+
96
+ ```bash
97
+ npm test
98
+ ```
99
+
100
+ ---
101
+
102
+ ## License
103
+
104
+ MIT-0
package/index.js ADDED
@@ -0,0 +1,60 @@
1
+ const { computeHolaChecksum, HOLA_CHECKSUM_ALPHABET } = require("./lib/checksum");
2
+ const {
3
+ buildAndSign,
4
+ buildCanonicalPrefix,
5
+ encodeSignatureBase32,
6
+ normalizeRecipient,
7
+ normalizeTokenId,
8
+ PROTOCOL_SUFFIX
9
+ } = require("./lib/sign");
10
+ const { getNonce } = require("./lib/nonce-api");
11
+ const { nearPrivateKeyToSigningSecretKey } = require("./lib/near-key");
12
+ const {
13
+ generateNearImplicitAccount,
14
+ validateNearCredentialsOutputDir,
15
+ writeNearCredentialsFile,
16
+ hasNearCredentialsDirSuffix
17
+ } = require("./lib/generate-near-account");
18
+ const { createHola } = require("./lib/create-hola");
19
+ const { parseHola } = require("./lib/parse");
20
+ const {
21
+ COLLABORATION_SCHEMA,
22
+ DEFAULT_MAX_AGE_MS,
23
+ IDENTYCLAW_FENCE,
24
+ buildCollaborationEnvelope,
25
+ parseCollaborationEnvelope,
26
+ extractIdentyclawFence,
27
+ validateCollaborationEnvelope,
28
+ assertCollaborationTrust,
29
+ formatSessionsSendMessage
30
+ } = require("./lib/collaboration-envelope");
31
+
32
+ module.exports = {
33
+ computeHolaChecksum,
34
+ HOLA_CHECKSUM_ALPHABET,
35
+ buildAndSign,
36
+ buildCanonicalPrefix,
37
+ encodeSignatureBase32,
38
+ normalizeRecipient,
39
+ normalizeTokenId,
40
+ PROTOCOL_SUFFIX,
41
+ getNonce,
42
+ nearPrivateKeyToSigningSecretKey,
43
+ generateNearImplicitAccount,
44
+ validateNearCredentialsOutputDir,
45
+ writeNearCredentialsFile,
46
+ hasNearCredentialsDirSuffix,
47
+ createHola,
48
+ parseHola,
49
+ COLLABORATION_SCHEMA,
50
+ DEFAULT_MAX_AGE_MS,
51
+ IDENTYCLAW_FENCE,
52
+ buildCollaborationEnvelope,
53
+ parseCollaborationEnvelope,
54
+ extractIdentyclawFence,
55
+ validateCollaborationEnvelope,
56
+ assertCollaborationTrust,
57
+ formatSessionsSendMessage,
58
+ /** @deprecated use parseHola */
59
+ verify: parseHola
60
+ };
@@ -0,0 +1,15 @@
1
+ /** HOLA line checksum: sum(char codes of UTF-16 units) mod 23 → one letter (omits I, L, O). */
2
+ const HOLA_CHECKSUM_ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ";
3
+
4
+ function computeHolaChecksum(prefix) {
5
+ let sum = 0;
6
+ for (let i = 0; i < prefix.length; i += 1) {
7
+ sum += prefix.charCodeAt(i);
8
+ }
9
+ return HOLA_CHECKSUM_ALPHABET[sum % HOLA_CHECKSUM_ALPHABET.length];
10
+ }
11
+
12
+ module.exports = {
13
+ HOLA_CHECKSUM_ALPHABET,
14
+ computeHolaChecksum
15
+ };
@@ -0,0 +1,201 @@
1
+ const { randomUUID } = require("crypto");
2
+ const { parseHola } = require("./parse");
3
+ const { normalizeTokenId } = require("./sign");
4
+
5
+ const COLLABORATION_SCHEMA = "identyclaw.collaboration.v1";
6
+ const DEFAULT_MAX_AGE_MS = 5 * 60 * 1000;
7
+ const IDENTYCLAW_FENCE = "```identyclaw";
8
+
9
+ /**
10
+ * @param {object} params
11
+ * @param {string} params.fromTokenId
12
+ * @param {string} params.hola
13
+ * @param {string} params.taskType
14
+ * @param {object} params.taskPayload
15
+ * @param {string} [params.toTokenId]
16
+ * @param {string} [params.toContactUri]
17
+ * @param {string} [params.messageId]
18
+ * @param {string} [params.timestamp]
19
+ * @param {object} [params.channelHints]
20
+ */
21
+ function buildCollaborationEnvelope({
22
+ fromTokenId,
23
+ hola,
24
+ taskType,
25
+ taskPayload,
26
+ toTokenId,
27
+ toContactUri,
28
+ messageId,
29
+ timestamp,
30
+ channelHints
31
+ }) {
32
+ if (!fromTokenId || !hola || !taskType || taskPayload == null) {
33
+ throw new Error("fromTokenId, hola, taskType, and taskPayload are required");
34
+ }
35
+
36
+ const envelope = {
37
+ schema: COLLABORATION_SCHEMA,
38
+ messageId: messageId || randomUUID(),
39
+ timestamp: timestamp || new Date().toISOString(),
40
+ from: { tokenId: normalizeTokenId(fromTokenId) },
41
+ hola: String(hola).trim(),
42
+ task: {
43
+ type: String(taskType),
44
+ payload: taskPayload
45
+ }
46
+ };
47
+
48
+ if (toTokenId) {
49
+ envelope.to = { tokenId: normalizeTokenId(toTokenId) };
50
+ if (toContactUri) {
51
+ envelope.to.contactUri = String(toContactUri);
52
+ }
53
+ } else if (toContactUri) {
54
+ envelope.to = { contactUri: String(toContactUri) };
55
+ }
56
+
57
+ if (channelHints && typeof channelHints === "object") {
58
+ envelope.channelHints = channelHints;
59
+ }
60
+
61
+ return envelope;
62
+ }
63
+
64
+ /**
65
+ * @param {string|object} input
66
+ * @returns {object}
67
+ */
68
+ function parseCollaborationEnvelope(input) {
69
+ let parsed = input;
70
+
71
+ if (typeof parsed === "string") {
72
+ const trimmed = parsed.trim();
73
+ const fenced = extractIdentyclawFence(trimmed);
74
+ parsed = JSON.parse(fenced || trimmed);
75
+ }
76
+
77
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
78
+ throw new Error("envelope must be a JSON object");
79
+ }
80
+
81
+ return parsed;
82
+ }
83
+
84
+ /**
85
+ * @param {string} message
86
+ * @returns {string|null}
87
+ */
88
+ function extractIdentyclawFence(message) {
89
+ if (typeof message !== "string" || message.length === 0) {
90
+ return null;
91
+ }
92
+
93
+ const start = message.indexOf(IDENTYCLAW_FENCE);
94
+ if (start === -1) {
95
+ return null;
96
+ }
97
+
98
+ const bodyStart = start + IDENTYCLAW_FENCE.length;
99
+ const end = message.indexOf("```", bodyStart);
100
+ if (end === -1) {
101
+ return null;
102
+ }
103
+
104
+ return message.slice(bodyStart, end).trim();
105
+ }
106
+
107
+ /**
108
+ * @param {object} envelope
109
+ * @param {number} [maxAgeMs]
110
+ * @returns {{ ok: true, envelope: object } | { ok: false, reason: string, step: string }}
111
+ */
112
+ function validateCollaborationEnvelope(envelope, maxAgeMs = DEFAULT_MAX_AGE_MS) {
113
+ if (envelope.schema !== COLLABORATION_SCHEMA) {
114
+ return { ok: false, step: "parse", reason: `expected schema ${COLLABORATION_SCHEMA}` };
115
+ }
116
+
117
+ if (!envelope.messageId || !envelope.timestamp || !envelope.from?.tokenId || !envelope.hola || !envelope.task?.type) {
118
+ return { ok: false, step: "parse", reason: "missing required envelope fields" };
119
+ }
120
+
121
+ const ageMs = Date.now() - Date.parse(envelope.timestamp);
122
+ if (!Number.isFinite(ageMs)) {
123
+ return { ok: false, step: "freshness", reason: "invalid envelope timestamp" };
124
+ }
125
+ if (ageMs < 0) {
126
+ return { ok: false, step: "freshness", reason: "envelope timestamp is in the future" };
127
+ }
128
+ if (ageMs > maxAgeMs) {
129
+ return { ok: false, step: "freshness", reason: `envelope older than ${maxAgeMs}ms` };
130
+ }
131
+
132
+ const holaShape = parseHola(envelope.hola);
133
+ if (!holaShape.valid) {
134
+ return { ok: false, step: "hola-shape", reason: holaShape.reason || "invalid HOLA format" };
135
+ }
136
+
137
+ return { ok: true, envelope, holaShape };
138
+ }
139
+
140
+ /**
141
+ * Pure trust decision after POST /api/identity/verify (and optional isauthorizedsigner).
142
+ *
143
+ * @param {object} envelope
144
+ * @param {object} verifyResult - API verify response with verified + peerTokenId
145
+ * @param {{ authorized?: boolean }|null} [signerResult]
146
+ * @returns {{ ok: true, peerTokenId: string } | { ok: false, reason: string, step: string }}
147
+ */
148
+ function assertCollaborationTrust(envelope, verifyResult, signerResult = null) {
149
+ const shape = validateCollaborationEnvelope(envelope);
150
+ if (!shape.ok) {
151
+ return shape;
152
+ }
153
+
154
+ if (!verifyResult?.verified) {
155
+ return { ok: false, step: "verify", reason: verifyResult?.reason || "HOLA not verified" };
156
+ }
157
+
158
+ const peerTokenId = normalizeTokenId(verifyResult.peerTokenId);
159
+ const declaredTokenId = normalizeTokenId(envelope.from.tokenId);
160
+
161
+ if (peerTokenId !== declaredTokenId) {
162
+ return {
163
+ ok: false,
164
+ step: "identity-match",
165
+ reason: `peerTokenId ${peerTokenId} does not match envelope.from.tokenId ${declaredTokenId}`
166
+ };
167
+ }
168
+
169
+ const holaShape = parseHola(envelope.hola);
170
+ if (holaShape.isSubagentFormat) {
171
+ if (!signerResult?.authorized) {
172
+ return { ok: false, step: "delegation", reason: "subagent HOLA requires authorized signer" };
173
+ }
174
+ }
175
+
176
+ return { ok: true, peerTokenId };
177
+ }
178
+
179
+ /**
180
+ * @param {object} envelope
181
+ * @param {string} [summaryLine]
182
+ * @returns {string}
183
+ */
184
+ function formatSessionsSendMessage(envelope, summaryLine) {
185
+ const intro =
186
+ summaryLine ||
187
+ `Trusted A2A message (${envelope.task.type}). Verify the identyclaw block before acting.`;
188
+ return `${intro}\n\n${IDENTYCLAW_FENCE}\n${JSON.stringify(envelope, null, 2)}\n\`\`\``;
189
+ }
190
+
191
+ module.exports = {
192
+ COLLABORATION_SCHEMA,
193
+ DEFAULT_MAX_AGE_MS,
194
+ IDENTYCLAW_FENCE,
195
+ buildCollaborationEnvelope,
196
+ parseCollaborationEnvelope,
197
+ extractIdentyclawFence,
198
+ validateCollaborationEnvelope,
199
+ assertCollaborationTrust,
200
+ formatSessionsSendMessage
201
+ };
@@ -0,0 +1,52 @@
1
+ const { getNonce } = require("./nonce-api");
2
+ const { buildAndSign, normalizeRecipient, normalizeTokenId } = require("./sign");
3
+ const { nearPrivateKeyToSigningSecretKey } = require("./near-key");
4
+
5
+ /**
6
+ * Fetch a fresh nonce and build a signed standard-format HOLA line locally.
7
+ * Private key stays on the caller machine — only JWT is sent to the API for nonce fetch.
8
+ *
9
+ * @param {object} params
10
+ * @param {string} params.nearPrivateKey - NEAR ed25519 private key (ed25519:...)
11
+ * @param {string} params.jwt - Bearer JWT from POST /api/login
12
+ * @param {string} params.tokenId - 12-letter Passport ID of the signer
13
+ * @param {string} [params.baseUrl] - API base URL
14
+ * @param {string} [params.recipient] - HOLA recipient (default MUNDO)
15
+ * @returns {Promise<object>}
16
+ */
17
+ async function createHola({
18
+ nearPrivateKey,
19
+ jwt,
20
+ tokenId,
21
+ baseUrl = "https://api.identyclaw.com",
22
+ recipient = "MUNDO"
23
+ }) {
24
+ if (!tokenId || typeof tokenId !== "string") {
25
+ throw new Error("tokenId is required");
26
+ }
27
+
28
+ const nonce = await getNonce({ baseUrl, jwt });
29
+ const privateKey = nearPrivateKeyToSigningSecretKey(nearPrivateKey);
30
+ const signed = buildAndSign({
31
+ recipient,
32
+ tokenId,
33
+ timestamp: nonce.timestamp,
34
+ noncetsHex: nonce.noncetsHex,
35
+ privateKey
36
+ });
37
+
38
+ return {
39
+ hola: signed.hola,
40
+ noncetsHex: nonce.noncetsHex,
41
+ timestamp: nonce.timestamp,
42
+ tokenId: normalizeTokenId(tokenId),
43
+ recipient: normalizeRecipient(recipient),
44
+ signatureB32: signed.signatureB32,
45
+ checksum: signed.checksum,
46
+ requestId: nonce.requestId
47
+ };
48
+ }
49
+
50
+ module.exports = {
51
+ createHola
52
+ };
@@ -0,0 +1,158 @@
1
+ const crypto = require("node:crypto");
2
+ const fs = require("node:fs");
3
+ const os = require("node:os");
4
+ const path = require("node:path");
5
+ const bs58 = require("bs58");
6
+ const nacl = require("tweetnacl");
7
+
8
+ const NEAR_CREDENTIALS_SUFFIX = "/secrets/near-credentials";
9
+
10
+ /**
11
+ * @typedef {Object} NearImplicitAccountCredentials
12
+ * @property {string} implicit_account_id 64-char hex (Ed25519 public key bytes)
13
+ * @property {string} account_id Same as implicit_account_id (NEAR / rodit-auth-be loader alias)
14
+ * @property {string} public_key ed25519: + base58(public)
15
+ * @property {string} private_key ed25519: + base58(seed||public) — never return from agent tools
16
+ */
17
+
18
+ /**
19
+ * Encode a tweetnacl key pair as gennearaccount credential fields.
20
+ *
21
+ * @param {nacl.SignKeyPair} keyPair
22
+ * @returns {NearImplicitAccountCredentials}
23
+ */
24
+ function encodeNearKeyPair(keyPair) {
25
+ const implicit_account_id = Buffer.from(keyPair.publicKey).toString("hex");
26
+ const public_key = `ed25519:${bs58.encode(Buffer.from(keyPair.publicKey))}`;
27
+ const private_key = `ed25519:${bs58.encode(Buffer.from(keyPair.secretKey))}`;
28
+ return {
29
+ implicit_account_id,
30
+ account_id: implicit_account_id,
31
+ public_key,
32
+ private_key
33
+ };
34
+ }
35
+
36
+ /**
37
+ * Generate NEAR implicit-account credentials (local host use — not an exportable wallet).
38
+ *
39
+ * Uses 32 bytes of CSPRNG entropy as the Ed25519 seed. Optional `seed` is for tests only.
40
+ *
41
+ * @param {Uint8Array} [seed] Optional 32-byte seed (for tests only)
42
+ * @returns {NearImplicitAccountCredentials}
43
+ */
44
+ function generateNearImplicitAccount(seed) {
45
+ const seedBytes = seed ?? crypto.randomBytes(32);
46
+ if (!(seedBytes instanceof Uint8Array) || seedBytes.length !== 32) {
47
+ throw new Error("seed must be a 32-byte Uint8Array");
48
+ }
49
+
50
+ return encodeNearKeyPair(nacl.sign.keyPair.fromSeed(seedBytes));
51
+ }
52
+
53
+ /**
54
+ * @param {string} resolved Absolute output directory path
55
+ * @returns {boolean}
56
+ */
57
+ function hasNearCredentialsDirSuffix(resolved) {
58
+ const normalized = resolved.split(path.sep).join("/").replace(/\/+$/, "");
59
+ return (
60
+ normalized.endsWith(NEAR_CREDENTIALS_SUFFIX) ||
61
+ normalized.endsWith("/near-credentials")
62
+ );
63
+ }
64
+
65
+ /**
66
+ * Resolve and validate an output directory for NEAR credential JSON files.
67
+ *
68
+ * Allowed when the path ends with `secrets/near-credentials` (recommended) or matches
69
+ * an explicit operator allowlist prefix from plugin config.
70
+ *
71
+ * @param {string} outputDir
72
+ * @param {{ allowedOutputDirs?: string[] }} [options]
73
+ * @returns {string} Absolute resolved directory
74
+ */
75
+ function validateNearCredentialsOutputDir(outputDir, options = {}) {
76
+ const { allowedOutputDirs = [] } = options;
77
+
78
+ if (typeof outputDir !== "string" || outputDir.trim().length === 0) {
79
+ throw new Error("outputDir must be a non-empty string");
80
+ }
81
+
82
+ const resolved = path.resolve(outputDir.trim());
83
+ const tmpRoot = path.resolve(os.tmpdir());
84
+ if (resolved === tmpRoot) {
85
+ throw new Error("Refusing to write NEAR credentials to the system temp directory root");
86
+ }
87
+
88
+ const allowedPrefixes = allowedOutputDirs
89
+ .filter((entry) => typeof entry === "string" && entry.trim().length > 0)
90
+ .map((entry) => path.resolve(entry.trim()));
91
+
92
+ const underAllowlist = allowedPrefixes.some(
93
+ (prefix) => resolved === prefix || resolved.startsWith(`${prefix}${path.sep}`)
94
+ );
95
+
96
+ if (!hasNearCredentialsDirSuffix(resolved) && !underAllowlist) {
97
+ throw new Error(
98
+ "Output directory must end with secrets/near-credentials or appear in nearCredentialsOutputDirs"
99
+ );
100
+ }
101
+
102
+ return resolved;
103
+ }
104
+
105
+ /**
106
+ * Write gennearaccount-compatible JSON to `<dir>/<implicit_account_id>.json`.
107
+ * Sets directory mode 0700 and file mode 0600 when supported.
108
+ *
109
+ * @param {string} outputDir
110
+ * @param {{ force?: boolean, allowedOutputDirs?: string[], seed?: Uint8Array }} [options]
111
+ * @returns {{ implicit_account_id: string, public_key: string, filePath: string }}
112
+ */
113
+ function writeNearCredentialsFile(outputDir, options = {}) {
114
+ const { force = false, allowedOutputDirs, seed } = options;
115
+ const dir = validateNearCredentialsOutputDir(outputDir, { allowedOutputDirs });
116
+ const credentials = generateNearImplicitAccount(seed);
117
+ const filePath = path.join(dir, `${credentials.implicit_account_id}.json`);
118
+
119
+ if (!force && fs.existsSync(filePath)) {
120
+ throw new Error(`Refusing to overwrite existing credentials file: ${filePath}`);
121
+ }
122
+
123
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
124
+ try {
125
+ fs.chmodSync(dir, 0o700);
126
+ } catch {
127
+ // Best effort — some filesystems ignore mode on mkdir/chmod.
128
+ }
129
+
130
+ // Compact single-line JSON so operators can `base64 -w0` into NEAR_CREDENTIALS_JSON_B64
131
+ // (cicd-deployment-standard: env-file values must be one logical line).
132
+ const payload = {
133
+ implicit_account_id: credentials.implicit_account_id,
134
+ account_id: credentials.account_id,
135
+ public_key: credentials.public_key,
136
+ private_key: credentials.private_key
137
+ };
138
+
139
+ fs.writeFileSync(filePath, `${JSON.stringify(payload)}\n`, { encoding: "utf8", mode: 0o600 });
140
+ try {
141
+ fs.chmodSync(filePath, 0o600);
142
+ } catch {
143
+ // Best effort
144
+ }
145
+
146
+ return {
147
+ implicit_account_id: credentials.implicit_account_id,
148
+ public_key: credentials.public_key,
149
+ filePath
150
+ };
151
+ }
152
+
153
+ module.exports = {
154
+ generateNearImplicitAccount,
155
+ validateNearCredentialsOutputDir,
156
+ writeNearCredentialsFile,
157
+ hasNearCredentialsDirSuffix
158
+ };
@@ -0,0 +1,31 @@
1
+ const bs58 = require("bs58");
2
+ const nacl = require("tweetnacl");
3
+
4
+ /**
5
+ * NEAR `ed25519:...` private key → 64-byte tweetnacl Ed25519 secret key for signing.
6
+ * Never send this value to the IdentyClaw API — use only on the agent host.
7
+ *
8
+ * @param {string} nearPrivateKey
9
+ * @returns {Uint8Array}
10
+ */
11
+ function nearPrivateKeyToSigningSecretKey(nearPrivateKey) {
12
+ if (typeof nearPrivateKey !== "string" || nearPrivateKey.trim().length === 0) {
13
+ throw new Error("nearPrivateKey must be a non-empty string");
14
+ }
15
+
16
+ const keyBody = nearPrivateKey.replace(/^ed25519:/, "").trim();
17
+ const decoded = bs58.decode(keyBody);
18
+
19
+ if (decoded.length >= 64) {
20
+ return decoded.slice(0, 64);
21
+ }
22
+ if (decoded.length >= 32) {
23
+ return nacl.sign.keyPair.fromSeed(decoded.slice(0, 32)).secretKey;
24
+ }
25
+
26
+ throw new Error("Invalid NEAR private key: decoded length is less than 32 bytes");
27
+ }
28
+
29
+ module.exports = {
30
+ nearPrivateKeyToSigningSecretKey
31
+ };
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Fetch a fresh HOLA nonce from GET /api/holanonce16ts (requires JWT).
3
+ *
4
+ * @param {object} params
5
+ * @param {string} params.baseUrl - API base URL (default https://api.identyclaw.com)
6
+ * @param {string} params.jwt - Bearer JWT from POST /api/login
7
+ * @returns {Promise<{ noncetsHex: string, timestamp: string, length: number, algorithm: string, requestId?: string }>}
8
+ */
9
+ async function getNonce({ baseUrl = "https://api.identyclaw.com", jwt }) {
10
+ if (!jwt || typeof jwt !== "string") {
11
+ throw new Error("jwt is required");
12
+ }
13
+
14
+ const resp = await fetch(`${baseUrl.replace(/\/+$/, "")}/api/holanonce16ts`, {
15
+ headers: {
16
+ authorization: `Bearer ${jwt}`
17
+ }
18
+ });
19
+
20
+ if (!resp.ok) {
21
+ const text = await resp.text().catch(() => "");
22
+ throw new Error(`GET /api/holanonce16ts failed: HTTP ${resp.status}${text ? ` — ${text.trim()}` : ""}`);
23
+ }
24
+
25
+ const data = await resp.json();
26
+ if (!data.noncetsHex || !data.timestamp) {
27
+ throw new Error("Nonce response missing noncetsHex or timestamp");
28
+ }
29
+
30
+ return data;
31
+ }
32
+
33
+ module.exports = {
34
+ getNonce
35
+ };
package/lib/parse.js ADDED
@@ -0,0 +1,71 @@
1
+ const { computeHolaChecksum } = require("./checksum");
2
+
3
+ /**
4
+ * Parse and validate HOLA format + checksum (no signature or on-chain checks).
5
+ *
6
+ * @param {string} hola
7
+ * @returns {{ valid: boolean, reason?: string, recipient?: string, tokenId?: string, isSubagentFormat?: boolean }}
8
+ */
9
+ function parseHola(hola) {
10
+ if (typeof hola !== "string" || hola.trim().length === 0) {
11
+ return { valid: false, reason: "hola must be a non-empty string" };
12
+ }
13
+
14
+ const trimmed = hola.trim();
15
+ if (!/^HOLA\//i.test(trimmed)) {
16
+ return { valid: false, reason: "expected HOLA/ prefix" };
17
+ }
18
+
19
+ const parts = trimmed.split("/");
20
+ if (parts.length !== 8 && parts.length !== 10) {
21
+ return { valid: false, reason: "invalid HOLA segment count" };
22
+ }
23
+
24
+ const checksumChar = parts[parts.length - 1];
25
+ const signatureB32 = parts[parts.length - 2];
26
+ const protocolPart = parts[parts.length - 3];
27
+ const canonicalPrefix = `${parts.slice(0, parts.length - 2).join("/")}/`.toUpperCase();
28
+ const checksumPrefix = `${canonicalPrefix}${signatureB32.toUpperCase()}/`;
29
+ const expectedChecksum = computeHolaChecksum(checksumPrefix);
30
+
31
+ if (checksumChar.toUpperCase() !== expectedChecksum) {
32
+ return { valid: false, reason: "checksum mismatch" };
33
+ }
34
+
35
+ if (protocolPart.toUpperCase() !== "API.IDENTYCLAW.COM") {
36
+ return { valid: false, reason: "unsupported protocol host" };
37
+ }
38
+
39
+ const isSubagentFormat = parts.length === 10;
40
+ const recipient = parts[1];
41
+
42
+ if (isSubagentFormat) {
43
+ return {
44
+ valid: true,
45
+ recipient,
46
+ delegateId: parts[2],
47
+ issuerTokenId: parts[3],
48
+ subagentPublicKey: parts[4],
49
+ timestamp: parts[5],
50
+ noncetsHex: parts[6],
51
+ signatureB32,
52
+ checksum: checksumChar,
53
+ isSubagentFormat: true
54
+ };
55
+ }
56
+
57
+ return {
58
+ valid: true,
59
+ recipient,
60
+ tokenId: parts[2],
61
+ timestamp: parts[3],
62
+ noncetsHex: parts[4],
63
+ signatureB32,
64
+ checksum: checksumChar,
65
+ isSubagentFormat: false
66
+ };
67
+ }
68
+
69
+ module.exports = {
70
+ parseHola
71
+ };
package/lib/sign.js ADDED
@@ -0,0 +1,103 @@
1
+ const base32 = require("hi-base32");
2
+ const nacl = require("tweetnacl");
3
+ const { computeHolaChecksum } = require("./checksum");
4
+
5
+ const PROTOCOL_SUFFIX = "API.IDENTYCLAW.COM/";
6
+
7
+ function encodeSignatureBase32(signatureBytes) {
8
+ return base32.encode(Buffer.from(signatureBytes)).replace(/=+$/g, "").toUpperCase();
9
+ }
10
+
11
+ function normalizeRecipient(recipient) {
12
+ const value = recipient && String(recipient).trim().length > 0 ? recipient : "MUNDO";
13
+ return String(value).toUpperCase();
14
+ }
15
+
16
+ function normalizeTokenId(tokenId) {
17
+ return String(tokenId || "").toLowerCase();
18
+ }
19
+
20
+ /**
21
+ * Build the unsigned canonical HOLA prefix (uppercase, trailing slash before signature).
22
+ *
23
+ * @param {object} params
24
+ * @param {string} params.recipient
25
+ * @param {string} params.tokenId - 12-letter passport ID (standard format)
26
+ * @param {string} params.timestamp - ISO-8601 from GET /api/holanonce16ts
27
+ * @param {string} params.noncetsHex - 32 hex chars from GET /api/holanonce16ts
28
+ * @param {string} [params.delegateId] - subagent format
29
+ * @param {string} [params.issuerTokenId] - subagent format
30
+ * @param {string} [params.subagentPublicKey] - base32 public key (subagent format)
31
+ * @returns {string}
32
+ */
33
+ function buildCanonicalPrefix({
34
+ recipient,
35
+ tokenId,
36
+ timestamp,
37
+ noncetsHex,
38
+ delegateId,
39
+ issuerTokenId,
40
+ subagentPublicKey
41
+ }) {
42
+ const normalizedRecipient = normalizeRecipient(recipient);
43
+ const normalizedNonce = String(noncetsHex || "").toUpperCase();
44
+ const normalizedTimestamp = String(timestamp || "");
45
+
46
+ if (delegateId && issuerTokenId && subagentPublicKey) {
47
+ const message =
48
+ `HOLA/${normalizedRecipient}/${String(delegateId).toUpperCase()}/` +
49
+ `${normalizeTokenId(issuerTokenId)}/${String(subagentPublicKey).toUpperCase()}/` +
50
+ `${normalizedTimestamp}/${normalizedNonce}/${PROTOCOL_SUFFIX}`;
51
+ return message.toUpperCase();
52
+ }
53
+
54
+ const message =
55
+ `HOLA/${normalizedRecipient}/${normalizeTokenId(tokenId)}/` +
56
+ `${normalizedTimestamp}/${normalizedNonce}/${PROTOCOL_SUFFIX}`;
57
+ return message.toUpperCase();
58
+ }
59
+
60
+ /**
61
+ * Sign a HOLA line. privateKey must be a 64-byte Ed25519 secret key (tweetnacl format).
62
+ *
63
+ * @param {object} params
64
+ * @param {string} params.recipient
65
+ * @param {string} params.tokenId
66
+ * @param {string} params.timestamp
67
+ * @param {string} params.noncetsHex
68
+ * @param {Uint8Array} params.privateKey
69
+ * @param {string} [params.delegateId]
70
+ * @param {string} [params.issuerTokenId]
71
+ * @param {string} [params.subagentPublicKey]
72
+ * @returns {{ hola: string, canonicalPrefix: string, signatureB32: string, checksum: string }}
73
+ */
74
+ function buildAndSign(params) {
75
+ const { privateKey } = params;
76
+ if (!(privateKey instanceof Uint8Array) || privateKey.length !== 64) {
77
+ throw new Error("privateKey must be a 64-byte Ed25519 secret key (tweetnacl format)");
78
+ }
79
+
80
+ const canonicalPrefix = buildCanonicalPrefix(params);
81
+ const messageBytes = new TextEncoder().encode(canonicalPrefix);
82
+ const signature = nacl.sign.detached(messageBytes, privateKey);
83
+ const signatureB32 = encodeSignatureBase32(signature);
84
+ const checksumPrefix = `${canonicalPrefix}${signatureB32}/`;
85
+ const checksum = computeHolaChecksum(checksumPrefix);
86
+ const hola = `${canonicalPrefix}${signatureB32}/${checksum}`;
87
+
88
+ return {
89
+ hola,
90
+ canonicalPrefix,
91
+ signatureB32,
92
+ checksum
93
+ };
94
+ }
95
+
96
+ module.exports = {
97
+ PROTOCOL_SUFFIX,
98
+ encodeSignatureBase32,
99
+ buildCanonicalPrefix,
100
+ buildAndSign,
101
+ normalizeRecipient,
102
+ normalizeTokenId
103
+ };
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@rodit/hola-client",
3
+ "version": "0.1.0",
4
+ "description": "Create and parse IdentyClaw HOLA handshake lines (uppercase canonicalization, base32, mod-23 checksum)",
5
+ "license": "MIT-0",
6
+ "type": "commonjs",
7
+ "main": "./index.js",
8
+ "dependencies": {
9
+ "bs58": "^5.0.0",
10
+ "hi-base32": "^0.5.1",
11
+ "tweetnacl": "^1.0.3"
12
+ },
13
+ "engines": {
14
+ "node": ">=18"
15
+ },
16
+ "files": [
17
+ "index.js",
18
+ "lib",
19
+ "README.md"
20
+ ],
21
+ "keywords": [
22
+ "identyclaw",
23
+ "hola",
24
+ "agent-identity",
25
+ "signing",
26
+ "near",
27
+ "rodit"
28
+ ],
29
+ "author": "Discernible IO",
30
+ "private": false,
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "git+https://github.com/discernible-io/rodit-sdk.git",
34
+ "directory": "hola-client"
35
+ },
36
+ "bugs": {
37
+ "url": "https://github.com/discernible-io/rodit-sdk/issues"
38
+ },
39
+ "homepage": "https://github.com/discernible-io/rodit-sdk/tree/main/hola-client#readme",
40
+ "publishConfig": {
41
+ "access": "public"
42
+ },
43
+ "scripts": {
44
+ "test": "node --test test/*.test.js"
45
+ }
46
+ }