vantyx-cli 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,200 @@
1
+ // Support chat for vantyxvault.com. A visitor talks to Claude first; Claude can look up a vault's plan and payments on
2
+ // chain. "Talk to a person" hands the conversation to the Vantyx team, who reply from the admin inbox.
3
+ // Refunds and payment fixes are decided by a person only; the assistant never promises them.
4
+ import Anthropic from "@anthropic-ai/sdk";
5
+ import { readFileSync, writeFileSync, existsSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { randomBytes, scryptSync, timingSafeEqual } from "node:crypto";
8
+ import { parseAbiItem, getAddress, isHash, decodeEventLog } from "viem";
9
+ import { CONFIG } from "./config.mjs";
10
+ import { pub } from "./chain.mjs";
11
+ import { PLANS, plan } from "./hosted.mjs";
12
+
13
+ const FILE = join(CONFIG.dataDir, "support.json");
14
+ const D = existsSync(FILE) ? JSON.parse(readFileSync(FILE, "utf8")) : { convs: {} };
15
+ const save = () => writeFileSync(FILE, JSON.stringify(D), { mode: 0o600 });
16
+ const MAX_TEXT = 2000, MAX_AI_TURNS = 40;
17
+ const SUBSCRIBED = parseAbiItem("event Subscribed(address indexed vault, address indexed payer, uint8 plan, bool yearly, uint256 periods, uint256 amount, uint64 until)");
18
+ const PLANS_FROM = BigInt(process.env.VANTYX_PLANS_FROM || "130747648");
19
+ const usd = (v) => `${Number(v) / 1e6} USDG`;
20
+
21
+ // ---------------------------------------------------------------- rate limits (per IP, in memory)
22
+ const hits = new Map();
23
+ function limit(ip, key, max, perMs) {
24
+ const k = `${ip}|${key}`, now = Date.now();
25
+ const arr = (hits.get(k) || []).filter((t) => now - t < perMs);
26
+ if (arr.length >= max) throw new Error("too many requests; wait a little and try again");
27
+ arr.push(now); hits.set(k, arr);
28
+ }
29
+
30
+ // ---------------------------------------------------------------- the assistant
31
+ const SYSTEM = `You are the support assistant on vantyxvault.com, the website of Vantyx Labs. Answer in the visitor's language, briefly and plainly.
32
+
33
+ What Vantyx is:
34
+ - Vantyx Vault: a desktop app (macOS, Windows, Linux) that makes a 24-word seed and post-quantum keys (ML-DSA-65, SLH-DSA, ML-KEM-768) on an offline computer. Approvals leave as animated QR codes.
35
+ - Each user deploys their own VantyxVault contract on Robinhood Chain (chain id 4663) holding USDG. The contract checks hash-based proofs on chain (fast mode: hash chain with commit and reveal; strict mode: Winternitz signatures). ML-DSA-65 is the vault's identity signature, checked off chain.
36
+ - vantyx-cli (npx vantyx-cli) is the online companion: relayer, agents, guardian, dashboard.
37
+ - Plans, per vault: Core is free (offline vault and post-quantum keys). Guardian Pro is 19 USDG a month or 190 USDG a year, and adds AI agents (scheduled payments, x402) and the 24/7 Guardian, hosted by Vantyx. Team is 79 USDG a month or 790 a year. Pay at vantyxvault.com/subscribe/ in USDG on Robinhood Chain; the plan starts as soon as the payment confirms, with no manual step. Visa, Mastercard and other methods are coming soon.
38
+ - Payment contract ${PLANS}, no admin, verified on Sourcify. Payments go straight to the Vantyx treasury.
39
+ - After paying for the hosted Guardian: set the vault's guardian to the hosted guardian address shown on the subscribe page (in the vault app), then save rules there with the wallet that paid.
40
+ - The contracts have not had an external audit yet; say so if asked about safety.
41
+
42
+ How to help with payments: use the lookup tools to check what the chain says before answering. Say exactly what you found.
43
+
44
+ Hard rules:
45
+ - Never ask for or accept a seed phrase, private key, password or backup share. If someone offers one, tell them not to share it with anyone, including Vantyx.
46
+ - You cannot move funds, refund, extend a plan or change anything. Refunds, missing or wrong payments and anything you cannot settle go to a person: tell the visitor to press "Talk to a person" and that the team will reply in this chat.
47
+ - Don't give investment advice. Don't invent features, prices, dates or numbers.`;
48
+
49
+ const TOOLS = [
50
+ {
51
+ name: "vault_plan",
52
+ description: "Look up a vault's current plan (none, Guardian Pro or Team), when it ends, and every payment made for it on chain, read from the VantyxPlans contract on Robinhood Chain.",
53
+ strict: true,
54
+ input_schema: { type: "object", properties: { vault: { type: "string", description: "The vault contract address, 0x followed by 40 hex characters" } }, required: ["vault"], additionalProperties: false },
55
+ },
56
+ {
57
+ name: "payment_tx",
58
+ description: "Look up a transaction hash on Robinhood Chain: whether it succeeded, and whether it paid for a Vantyx plan (which vault, how much, until when).",
59
+ strict: true,
60
+ input_schema: { type: "object", properties: { hash: { type: "string", description: "Transaction hash, 0x followed by 64 hex characters" } }, required: ["hash"], additionalProperties: false },
61
+ },
62
+ ];
63
+
64
+ async function runTool(name, input) {
65
+ if (name === "vault_plan") {
66
+ let vault;
67
+ try { vault = getAddress(String(input.vault).toLowerCase()); } catch { return "That is not a valid address."; }
68
+ const p = await plan(vault);
69
+ const head = await pub.getBlockNumber();
70
+ const pays = [];
71
+ for (let from = PLANS_FROM; from <= head; from += 2_000_000n) {
72
+ const to = from + 1_999_999n > head ? head : from + 1_999_999n;
73
+ for (const l of await pub.getLogs({ address: PLANS, event: SUBSCRIBED, args: { vault }, fromBlock: from, toBlock: to }))
74
+ pays.push({ tx: l.transactionHash, payer: l.args.payer, plan: l.args.plan === 2 ? "Team" : "Guardian Pro", yearly: l.args.yearly, periods: Number(l.args.periods), amount: usd(l.args.amount), until: new Date(Number(l.args.until) * 1000).toISOString() });
75
+ }
76
+ return JSON.stringify({ vault, plan: p.name, until: p.until ? new Date(p.until * 1000).toISOString() : null, payments: pays });
77
+ }
78
+ if (name === "payment_tx") {
79
+ if (!isHash(input.hash)) return "That is not a transaction hash.";
80
+ const r = await pub.getTransactionReceipt({ hash: input.hash }).catch(() => null);
81
+ if (!r) return "No such transaction on Robinhood Chain (yet). It may be pending, on another network, or mistyped.";
82
+ const pay = r.logs.filter((l) => l.address.toLowerCase() === PLANS.toLowerCase()).map((l) => {
83
+ try { return decodeEventLog({ abi: [SUBSCRIBED], data: l.data, topics: l.topics }).args; } catch { return null; }
84
+ }).filter(Boolean);
85
+ return JSON.stringify({ status: r.status, to: r.to, block: Number(r.blockNumber), planPayment: pay.length ? { vault: pay[0].vault, payer: pay[0].payer, amount: usd(pay[0].amount), until: new Date(Number(pay[0].until) * 1000).toISOString() } : null });
86
+ }
87
+ return "Unknown tool.";
88
+ }
89
+
90
+ let client = null;
91
+ const anthropic = () => (client ??= new Anthropic()); // reads ANTHROPIC_API_KEY from the environment
92
+
93
+ async function aiReply(conv) {
94
+ if (!process.env.ANTHROPIC_API_KEY && !process.env.ANTHROPIC_AUTH_TOKEN) return "The assistant isn't switched on yet. Press \"Talk to a person\" and the team will reply here.";
95
+ const messages = conv.ai;
96
+ for (let step = 0; step < 6; step++) {
97
+ let res;
98
+ try {
99
+ res = await anthropic().beta.messages.create({
100
+ model: "claude-opus-5-5",
101
+ max_tokens: 2000,
102
+ system: SYSTEM,
103
+ cache_control: { type: "ephemeral" },
104
+ output_config: { effort: "low" },
105
+ betas: ["server-side-fallback-2026-07-01"],
106
+ fallbacks: "default",
107
+ tools: TOOLS,
108
+ messages,
109
+ });
110
+ } catch (e) {
111
+ if (e instanceof Anthropic.RateLimitError) return "The assistant is busy right now. Try again in a minute, or press \"Talk to a person\".";
112
+ if (e instanceof Anthropic.AuthenticationError) return "The assistant isn't available right now. Press \"Talk to a person\" and the team will reply here.";
113
+ if (e instanceof Anthropic.APIError) return "The assistant had a problem answering. Press \"Talk to a person\" and the team will reply here.";
114
+ throw e;
115
+ }
116
+ messages.push({ role: "assistant", content: res.content });
117
+ if (res.stop_reason === "refusal") return "I can't help with that here. Press \"Talk to a person\" and the team will reply in this chat.";
118
+ if (res.stop_reason !== "tool_use") return res.content.filter((b) => b.type === "text").map((b) => b.text).join("\n").trim() || "…";
119
+ const results = [];
120
+ for (const b of res.content.filter((x) => x.type === "tool_use")) {
121
+ let out;
122
+ try { out = await runTool(b.name, b.input); } catch (e) { out = `Lookup failed: ${e.shortMessage || e.message}`; }
123
+ results.push({ type: "tool_result", tool_use_id: b.id, content: out });
124
+ }
125
+ messages.push({ role: "user", content: results });
126
+ }
127
+ return "I couldn't finish that. Press \"Talk to a person\" and the team will reply here.";
128
+ }
129
+
130
+ // ---------------------------------------------------------------- visitor API
131
+ const pubView = (c) => ({ id: c.id, status: c.status, messages: c.messages });
132
+ function get(id, token) {
133
+ const c = D.convs[id];
134
+ if (!c || typeof token !== "string" || token.length !== c.token.length || !timingSafeEqual(Buffer.from(token), Buffer.from(c.token))) throw new Error("conversation not found");
135
+ return c;
136
+ }
137
+
138
+ export function start(ip) {
139
+ limit(ip, "start", 8, 3600_000);
140
+ const id = randomBytes(6).toString("hex"), token = randomBytes(18).toString("hex");
141
+ D.convs[id] = { id, token, created: Date.now(), updated: Date.now(), status: "ai", email: null, aiTurns: 0, unread: false,
142
+ messages: [{ from: "ai", text: "Hi, I'm the Vantyx assistant. Ask me anything about the vault, plans or a payment. You can also talk to a person on the team.", at: Date.now() }], ai: [] };
143
+ save();
144
+ return { id, token, ...pubView(D.convs[id]) };
145
+ }
146
+
147
+ export async function send(ip, { id, token, text }) {
148
+ limit(ip, "send", 30, 600_000);
149
+ const c = get(id, token);
150
+ text = String(text || "").trim().slice(0, MAX_TEXT);
151
+ if (!text) throw new Error("empty message");
152
+ c.messages.push({ from: "user", text, at: Date.now() });
153
+ c.updated = Date.now();
154
+ if (c.status === "human") { c.unread = true; save(); return pubView(c); }
155
+ if (c.aiTurns >= MAX_AI_TURNS) { c.messages.push({ from: "ai", text: "This chat is long. Press \"Talk to a person\" to continue with the team.", at: Date.now() }); save(); return pubView(c); }
156
+ c.aiTurns += 1;
157
+ c.ai.push({ role: "user", content: text });
158
+ const reply = await aiReply(c);
159
+ c.messages.push({ from: "ai", text: reply, at: Date.now() });
160
+ c.updated = Date.now();
161
+ save();
162
+ return pubView(c);
163
+ }
164
+
165
+ export function human(ip, { id, token, email }) {
166
+ limit(ip, "human", 10, 3600_000);
167
+ const c = get(id, token);
168
+ if (email && /^[^\s@]{1,64}@[^\s@]{1,190}\.[a-z]{2,}$/i.test(email)) c.email = String(email).slice(0, 254);
169
+ if (c.status !== "human") {
170
+ c.status = "human"; c.unread = true;
171
+ c.messages.push({ from: "system", text: "You're now talking to the Vantyx team. A person will reply in this chat" + (c.email ? ` (we may also write to ${c.email})` : "") + ". Keep this page open or come back later: the chat is saved in this browser.", at: Date.now() });
172
+ }
173
+ c.updated = Date.now(); save();
174
+ return pubView(c);
175
+ }
176
+
177
+ export function poll({ id, token }) { return pubView(get(id, token)); }
178
+
179
+ // ---------------------------------------------------------------- admin (the Vantyx team)
180
+ export function checkAdmin(header) {
181
+ const hash = process.env.VANTYX_ADMIN_HASH; // "salt:hex" made by bin/admin-password.mjs
182
+ const pw = String(header || "").replace(/^Bearer /, "");
183
+ if (!hash || !pw) throw new Error("not allowed");
184
+ const [salt, want] = hash.split(":");
185
+ const got = scryptSync(pw, Buffer.from(salt, "hex"), 32);
186
+ if (!timingSafeEqual(got, Buffer.from(want, "hex"))) throw new Error("not allowed");
187
+ }
188
+ export function adminList() {
189
+ return Object.values(D.convs).sort((a, b) => b.updated - a.updated).slice(0, 200).map((c) => ({
190
+ id: c.id, status: c.status, email: c.email, unread: c.unread, updated: c.updated, last: c.messages.at(-1)?.text.slice(0, 120), count: c.messages.length,
191
+ }));
192
+ }
193
+ export function adminGet(id) { const c = D.convs[id]; if (!c) throw new Error("not found"); c.unread = false; save(); return { ...pubView(c), email: c.email }; }
194
+ export function adminReply(id, text) {
195
+ const c = D.convs[id]; if (!c) throw new Error("not found");
196
+ text = String(text || "").trim().slice(0, 4000); if (!text) throw new Error("empty");
197
+ c.messages.push({ from: "team", text, at: Date.now() }); c.status = "human"; c.updated = Date.now(); c.unread = false; save();
198
+ return pubView(c);
199
+ }
200
+ export function adminClose(id) { const c = D.convs[id]; if (!c) throw new Error("not found"); c.status = "closed"; c.messages.push({ from: "system", text: "The team closed this conversation. Start a new one any time.", at: Date.now() }); save(); return pubView(c); }
package/src/token.mjs ADDED
@@ -0,0 +1,15 @@
1
+ // The Vantyx token's address, for the holders gate and Guardian Pro: VANTYX_TOKEN in .env, or else the CA the owner saved in
2
+ // the studio (<data>/studio/token.json). Read on every call, so saving the CA in the studio switches both on without a restart.
3
+ import { readFileSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { getAddress } from "viem";
6
+ import { CONFIG } from "./config.mjs";
7
+
8
+ export function tokenAddress() {
9
+ const env = process.env.VANTYX_TOKEN;
10
+ if (env) return getAddress(String(env).toLowerCase());
11
+ try {
12
+ const ca = JSON.parse(readFileSync(join(CONFIG.dataDir, "studio", "token.json"), "utf8")).ca;
13
+ return ca ? getAddress(String(ca).toLowerCase()) : null;
14
+ } catch { return null; }
15
+ }
@@ -0,0 +1,42 @@
1
+ // The public keys of every vault this companion relays for, kept in <data>/identities.json as { dsa, slh, kem }
2
+ // (older files stored the ML-DSA key alone). Shared by the dashboard server and the command line, so both refuse the
3
+ // same things: no action is relayed without a valid ML-DSA-65 signature, no rotation without a valid SLH-DSA-128s one.
4
+ import { readFileSync, writeFileSync, existsSync } from "node:fs";
5
+ import { join } from "node:path";
6
+ import { CONFIG } from "./config.mjs";
7
+ import { vaultStatus, checkIdentity } from "./chain.mjs";
8
+ import { verifyGenesis, verifySlh } from "./pq.mjs";
9
+
10
+ const FILE = join(CONFIG.dataDir, "identities.json");
11
+ const ids = existsSync(FILE) ? JSON.parse(readFileSync(FILE, "utf8")) : {};
12
+ for (const [k, v] of Object.entries(ids)) if (typeof v === "string") ids[k] = { dsa: v };
13
+ const save = () => writeFileSync(FILE, JSON.stringify(ids), { mode: 0o600 });
14
+
15
+ export const keysOf = (vault) => ids[String(vault).toLowerCase()] || null;
16
+
17
+ /// After a deploy from a genesis this companion already checked.
18
+ export function remember(vault, g) {
19
+ ids[String(vault).toLowerCase()] = { dsa: g.ml_dsa_public, slh: g.slh_dsa_public, kem: g.ml_kem_public };
20
+ save();
21
+ }
22
+
23
+ /// A vault deployed elsewhere: check the genesis signatures and that its identity is the one the contract holds.
24
+ export async function register(vault, g) {
25
+ verifyGenesis(g, CONFIG.chainId);
26
+ const st = await vaultStatus(vault);
27
+ if (String(st.identity).toLowerCase() !== g.identity.toLowerCase()) throw new Error("this genesis belongs to another vault");
28
+ remember(vault, g);
29
+ }
30
+
31
+ /// Throws unless the bundle carries the vault's ML-DSA-65 signature (and, for a rotation, its SLH-DSA-128s one).
32
+ export async function verifyBundle(bundle) {
33
+ const k = keysOf(bundle.vault);
34
+ if (!k?.dsa) throw new Error("this companion doesn't know the vault's keys yet: scan its deploy QR once (dashboard: Deploy → I already have a vault; command line: vantyx register <vault> <genesis-frames.txt>)");
35
+ const identity = await checkIdentity(bundle, k.dsa);
36
+ if (!identity.ok) throw new Error(identity.reason);
37
+ if (bundle.kind === 7) {
38
+ if (!k.slh) throw new Error("scan the vault's deploy QR once so this companion knows its SLH-DSA key");
39
+ if (!bundle.slh_sig || !verifySlh(bundle.slh_sig, bundle.action_hash, k.slh)) throw new Error("the SLH-DSA-128s signature on this rotation is missing or wrong");
40
+ }
41
+ return identity;
42
+ }