@vatio-ai/cli 0.114.0 → 0.117.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/lib/api-client.mjs +63 -4
- package/lib/commands/channels.mjs +149 -46
- package/lib/commands/chat.mjs +96 -22
- package/lib/commands/improve.mjs +11 -1
- package/lib/commands/team.mjs +6 -3
- package/lib/commands/webhooks.mjs +25 -1
- package/lib/help.mjs +42 -26
- package/lib/visitor-identity.mjs +142 -0
- package/package.json +1 -1
package/lib/api-client.mjs
CHANGED
|
@@ -8,6 +8,13 @@ import { HttpClient } from "./http.mjs";
|
|
|
8
8
|
|
|
9
9
|
const encode = (value) => encodeURIComponent(String(value));
|
|
10
10
|
|
|
11
|
+
function chatFields({ environment, asPhone, visitorToken }) {
|
|
12
|
+
const body = { environment };
|
|
13
|
+
if (asPhone) body.as_phone = asPhone;
|
|
14
|
+
if (visitorToken) body.visitor_token = visitorToken;
|
|
15
|
+
return body;
|
|
16
|
+
}
|
|
17
|
+
|
|
11
18
|
export class ApiClient extends HttpClient {
|
|
12
19
|
// --- outbound WhatsApp messages ------------------------------------
|
|
13
20
|
|
|
@@ -29,11 +36,48 @@ export class ApiClient extends HttpClient {
|
|
|
29
36
|
return this.get("/whatsapp");
|
|
30
37
|
}
|
|
31
38
|
|
|
39
|
+
setWhatsappLive(active) {
|
|
40
|
+
return this.patch("/whatsapp/live", { active });
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
checkWhatsapp() {
|
|
44
|
+
return this.post("/whatsapp/health_check", {});
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
disconnectWhatsapp() {
|
|
48
|
+
return this.delete("/whatsapp");
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
inviteWhatsappConnector(body) {
|
|
52
|
+
return this.post("/whatsapp/invite", body);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
whatsappTeam() {
|
|
56
|
+
return this.get("/whatsapp/team");
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
moveTestPhone(phoneNumber) {
|
|
60
|
+
return this.post(`/test_phones/${encode(phoneNumber)}/move`, {});
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
syncTemplates() {
|
|
64
|
+
return this.post("/templates/sync", {});
|
|
65
|
+
}
|
|
66
|
+
|
|
32
67
|
// The phones verified in Try the agent.
|
|
33
68
|
testPhones() {
|
|
34
69
|
return this.get("/test_phones");
|
|
35
70
|
}
|
|
36
71
|
|
|
72
|
+
// The code a phone sends to Vatio's shared number to join; it adds nothing by itself.
|
|
73
|
+
testPhoneCode() {
|
|
74
|
+
return this.post("/test_phones", {});
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
removeTestPhone(phoneNumber) {
|
|
78
|
+
return this.delete(`/test_phones/${encode(phoneNumber)}`);
|
|
79
|
+
}
|
|
80
|
+
|
|
37
81
|
deployedManifest({ environment = "live" } = {}) {
|
|
38
82
|
return this.get("/manifest", { environment });
|
|
39
83
|
}
|
|
@@ -249,6 +293,10 @@ export class ApiClient extends HttpClient {
|
|
|
249
293
|
return this.post("/templates", payload);
|
|
250
294
|
}
|
|
251
295
|
|
|
296
|
+
deleteTemplate({ name, language = null }) {
|
|
297
|
+
return this.delete(`/templates/${encode(name)}${query({ language })}`);
|
|
298
|
+
}
|
|
299
|
+
|
|
252
300
|
listWebhookEndpoints() {
|
|
253
301
|
return this.get("/webhook_endpoints");
|
|
254
302
|
}
|
|
@@ -287,12 +335,23 @@ export class ApiClient extends HttpClient {
|
|
|
287
335
|
|
|
288
336
|
// --- chats ----------------------------------------------------------
|
|
289
337
|
|
|
290
|
-
|
|
291
|
-
|
|
338
|
+
// Who is writing: `asPhone` a verified phone (Vatio::Preview::Tester), or
|
|
339
|
+
// `visitorToken` a signed-in visitor, the JWT the workspace signed, which
|
|
340
|
+
// Vatio verifies against the public key in vatio.yml (see
|
|
341
|
+
// lib/visitor-identity.mjs). Left out, the chat is the token holder.
|
|
342
|
+
createChat({ environment, asPhone = null, visitorToken = null }) {
|
|
343
|
+
return this.post("/chats", chatFields({ environment, asPhone, visitorToken }));
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
resetChat({ chatId, environment, asPhone = null, visitorToken = null }) {
|
|
347
|
+
return this.post(`/chats/${encode(chatId)}/reset`, chatFields({ environment, asPhone, visitorToken }));
|
|
292
348
|
}
|
|
293
349
|
|
|
294
|
-
|
|
295
|
-
|
|
350
|
+
// A fresh token for a chat that already knows who it is talking to. Answers
|
|
351
|
+
// `identified: false` with a reason when it does not verify, or names someone
|
|
352
|
+
// else.
|
|
353
|
+
identifyChat({ chatId, visitorToken }) {
|
|
354
|
+
return this.post(`/chats/${encode(chatId)}/identify`, { visitor_token: visitorToken });
|
|
296
355
|
}
|
|
297
356
|
|
|
298
357
|
// No `view` parameter: the developer token is the developer view, so the
|
|
@@ -1,45 +1,76 @@
|
|
|
1
|
-
// whatsapp / instagram --
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
// accounts are verified; after, the channel's own page (WhatsApp, Instagram).
|
|
1
|
+
// whatsapp / instagram -- connecting your own number or account needs Meta's
|
|
2
|
+
// consent screen, so `connect` prints where in the inbox, and that depends on
|
|
3
|
+
// whether the workspace has published: before, "Try the agent"; after, the
|
|
4
|
+
// channel's own page. Everything else on the WhatsApp page is here too.
|
|
6
5
|
// vatio.ai/workspaces is only for a server too old to send the link, and
|
|
7
6
|
// redirects to the inbox.
|
|
8
7
|
|
|
9
8
|
import { deployClient } from "./deploy.mjs";
|
|
10
|
-
import {
|
|
9
|
+
import { messages } from "./messages.mjs";
|
|
10
|
+
import { withSecondFactor } from "./team.mjs";
|
|
11
|
+
import { templates } from "./webhooks.mjs";
|
|
12
|
+
import { ask, fail, paint, takeFlag, takeValue } from "../support.mjs";
|
|
11
13
|
|
|
12
|
-
const WHATSAPP_USAGE =
|
|
13
|
-
"Usage: vatio whatsapp [
|
|
14
|
+
const WHATSAPP_USAGE = [
|
|
15
|
+
"Usage: vatio whatsapp [status] [--json]",
|
|
16
|
+
" vatio whatsapp connect | live on|off | check | disconnect [--yes] | team",
|
|
17
|
+
" vatio whatsapp invite EMAIL [--code CODE | --recovery-code CODE]",
|
|
18
|
+
" vatio whatsapp phones [list] | add | rm PHONE | move PHONE [--json]",
|
|
19
|
+
" vatio whatsapp templates [list] | create NAME ... | rm NAME | sync",
|
|
20
|
+
" vatio whatsapp failed [--since DATE] [--until DATE] [--error-code CODE] ...",
|
|
21
|
+
].join("\n");
|
|
14
22
|
// The list of who the agent answered on your own number is gone: it answers
|
|
15
|
-
// everyone, and
|
|
23
|
+
// everyone, and `vatio whatsapp live off` is how it answers nobody.
|
|
16
24
|
const AGENT_NUMBERS_REMOVED =
|
|
17
25
|
"`vatio whatsapp only` and `everyone` were removed: the agent answers everyone who writes to your number. " +
|
|
18
|
-
"To have it answer nobody
|
|
26
|
+
"To have it answer nobody: vatio whatsapp live off.";
|
|
19
27
|
// "Your numbers" were a list typed by hand; the team's numbers took its place.
|
|
20
28
|
const MINE_REMOVED =
|
|
21
29
|
"`vatio whatsapp mine` was removed: the team's numbers are the ones each member verified on their account " +
|
|
22
|
-
"(Account in the inbox)
|
|
30
|
+
"(Account in the inbox): vatio whatsapp team. A tool declares which role may use it with " +
|
|
23
31
|
"`access: supervisor`, `developer` or `owner`.";
|
|
24
32
|
|
|
33
|
+
// One noun per thing on the inbox's WhatsApp page, each with the same verbs:
|
|
34
|
+
// the number itself, its test phones, its templates and its failed messages.
|
|
35
|
+
// `test-phones`, `vatio templates` and `vatio messages failed` still work.
|
|
25
36
|
export async function whatsapp(config, args = []) {
|
|
37
|
+
const json = takeFlag(args, "--json");
|
|
26
38
|
const sub = args.shift();
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
39
|
+
const client = () => deployClient(config, config.resolveWorkspaceRequired());
|
|
40
|
+
switch (sub) {
|
|
41
|
+
case undefined:
|
|
42
|
+
case "status":
|
|
43
|
+
return status(config, client(), { json });
|
|
44
|
+
case "connect":
|
|
45
|
+
return inInbox(config, { name: "WhatsApp", key: "whatsapp", own: "number", test: "phone" });
|
|
46
|
+
case "live": {
|
|
47
|
+
const value = args.shift();
|
|
48
|
+
if (!["on", "off"].includes(value) || args.length) fail(WHATSAPP_USAGE);
|
|
49
|
+
return printNumber(await client().setWhatsappLive(value === "on"), { json });
|
|
50
|
+
}
|
|
51
|
+
case "check":
|
|
52
|
+
return printNumber(await client().checkWhatsapp(), { json });
|
|
53
|
+
case "disconnect":
|
|
54
|
+
return disconnect(client(), args, { json });
|
|
55
|
+
case "invite":
|
|
56
|
+
return invite(client(), args, { json });
|
|
57
|
+
case "team":
|
|
58
|
+
return printTeam(await client().whatsappTeam(), { json });
|
|
59
|
+
case "phones":
|
|
60
|
+
case "test-phones":
|
|
61
|
+
return phones(config, client(), args, { json });
|
|
62
|
+
case "templates":
|
|
63
|
+
return templates(config, json ? [...args, "--json"] : args);
|
|
64
|
+
case "failed":
|
|
65
|
+
return messages(config, ["failed", ...args, ...(json ? ["--json"] : [])]);
|
|
66
|
+
case "only":
|
|
67
|
+
case "everyone":
|
|
68
|
+
return fail(AGENT_NUMBERS_REMOVED);
|
|
69
|
+
case "mine":
|
|
70
|
+
return fail(MINE_REMOVED);
|
|
71
|
+
default:
|
|
72
|
+
return fail(WHATSAPP_USAGE);
|
|
34
73
|
}
|
|
35
|
-
if (sub === "test-phones") {
|
|
36
|
-
const json = takeFlag(args, "--json");
|
|
37
|
-
if (args.length > 0) fail(WHATSAPP_USAGE);
|
|
38
|
-
return printTestPhones(config, { json });
|
|
39
|
-
}
|
|
40
|
-
if (sub === "only" || sub === "everyone") fail(AGENT_NUMBERS_REMOVED);
|
|
41
|
-
if (sub === "mine") fail(MINE_REMOVED);
|
|
42
|
-
fail(WHATSAPP_USAGE);
|
|
43
74
|
}
|
|
44
75
|
|
|
45
76
|
export const instagram = (config) =>
|
|
@@ -59,34 +90,106 @@ async function inInbox(config, channel) {
|
|
|
59
90
|
console.log(` ${published ? url : (status.try_url ?? url)}`);
|
|
60
91
|
}
|
|
61
92
|
|
|
93
|
+
async function status(config, client, { json }) {
|
|
94
|
+
let number = null;
|
|
95
|
+
try {
|
|
96
|
+
number = await client.getWhatsapp();
|
|
97
|
+
} catch (error) {
|
|
98
|
+
if (error?.body?.error?.code !== "whatsapp_not_connected") throw error;
|
|
99
|
+
}
|
|
100
|
+
if (json) return console.log(JSON.stringify(number ?? { connected: false }, null, 2));
|
|
101
|
+
await inInbox(config, { name: "WhatsApp", key: "whatsapp", own: "number", test: "phone" });
|
|
102
|
+
// A server that predates the route answers 404; the link above is enough.
|
|
103
|
+
await printPhones(await client.testPhones()).catch((error) => {
|
|
104
|
+
if (error?.status !== 404 && error?.body?.error?.code !== "not_found") throw error;
|
|
105
|
+
});
|
|
106
|
+
if (number) printNumber(number);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async function phones(config, client, args, { json }) {
|
|
110
|
+
const action = args.shift() ?? "list";
|
|
111
|
+
const phone = args.shift();
|
|
112
|
+
if (args.length) fail(WHATSAPP_USAGE);
|
|
113
|
+
if (action === "list" && !phone) {
|
|
114
|
+
const list = await client.testPhones();
|
|
115
|
+
return json ? console.log(JSON.stringify(list, null, 2)) : printPhones(list);
|
|
116
|
+
}
|
|
117
|
+
if (action === "add" && !phone) return printJoin(await client.testPhoneCode(), { json });
|
|
118
|
+
if (action === "rm" && phone) {
|
|
119
|
+
await client.removeTestPhone(phone);
|
|
120
|
+
return json ? console.log(JSON.stringify({ removed: phone })) : console.log(`Removed ${phone} from the test phones.`);
|
|
121
|
+
}
|
|
122
|
+
if (action === "move" && phone) {
|
|
123
|
+
const { data } = await client.moveTestPhone(phone);
|
|
124
|
+
return json ? console.log(JSON.stringify(data)) : console.log(`${data.phone_number} now tests this workspace.`);
|
|
125
|
+
}
|
|
126
|
+
fail(WHATSAPP_USAGE);
|
|
127
|
+
}
|
|
128
|
+
|
|
62
129
|
// The phones that joined by sending Try the agent's code: the ones a preview
|
|
63
|
-
// message can go to.
|
|
64
|
-
|
|
65
|
-
const { data = [], max } = await deployClient(config, config.resolveWorkspaceRequired()).testPhones();
|
|
66
|
-
if (json) return console.log(JSON.stringify({ data, max }, null, 2));
|
|
130
|
+
// message can go to.
|
|
131
|
+
function printPhones({ data = [], max, elsewhere = [] }) {
|
|
67
132
|
if (data.length === 0) {
|
|
68
|
-
console.log("\nNo test phones yet. Add yours
|
|
69
|
-
|
|
133
|
+
console.log("\nNo test phones yet. Add yours: vatio whatsapp phones add");
|
|
134
|
+
} else {
|
|
135
|
+
console.log(`\nTest phones (${data.length} of ${max}):`);
|
|
136
|
+
for (const phone of data) console.log(` ${phone.phone_number}`);
|
|
137
|
+
}
|
|
138
|
+
if (elsewhere.length) {
|
|
139
|
+
console.log("Verified on your other workspaces (vatio whatsapp phones move PHONE brings one here):");
|
|
140
|
+
for (const phone of elsewhere) console.log(` ${phone.phone_number} ${phone.workspace}`);
|
|
70
141
|
}
|
|
71
|
-
console.log(`\nTest phones (${data.length} of ${max}), verified in Try the agent:`);
|
|
72
|
-
for (const phone of data) console.log(` ${phone.phone_number}`);
|
|
73
142
|
}
|
|
74
143
|
|
|
75
|
-
//
|
|
76
|
-
//
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
144
|
+
// The same code Try the agent shows: the phone joins when it sends it, so the
|
|
145
|
+
// message is the proof that whoever added it holds the phone.
|
|
146
|
+
function printJoin(join, { json }) {
|
|
147
|
+
if (json) return console.log(JSON.stringify(join, null, 2));
|
|
148
|
+
console.log(`From the phone to add, send this to ${join.send_to ?? "Vatio's test number"} on WhatsApp:`);
|
|
149
|
+
console.log(` ${join.message}`);
|
|
150
|
+
if (join.link_url) console.log(`Or open this on the phone, it writes the message:\n ${join.link_url}`);
|
|
151
|
+
console.log(`The code works for ${Math.round((join.expires_in ?? 900) / 60)} minutes. Check with: vatio whatsapp phones`);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async function disconnect(client, args, { json }) {
|
|
155
|
+
const yes = takeFlag(args, "--yes");
|
|
156
|
+
if (args.length) fail(WHATSAPP_USAGE);
|
|
157
|
+
if (!yes) {
|
|
158
|
+
if (!process.stdin.isTTY) fail("Disconnecting stops the agent answering on your number, so without a terminal it needs --yes.");
|
|
159
|
+
const answer = await ask(`${paint("green", "?")} Disconnect your WhatsApp number? Type yes: `);
|
|
160
|
+
if (answer.trim().toLowerCase() !== "yes") fail("Nothing changed.");
|
|
84
161
|
}
|
|
162
|
+
const after = await client.disconnectWhatsapp();
|
|
163
|
+
if (json) return console.log(JSON.stringify(after, null, 2));
|
|
164
|
+
console.log("Disconnected. Connect a number again with: vatio whatsapp connect");
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// The owner's: whoever holds the number (often a client) gets the link that
|
|
168
|
+
// connects it, and joins as a supervisor. Confirmed with a second factor, as
|
|
169
|
+
// `vatio team invite` is.
|
|
170
|
+
async function invite(client, args, { json }) {
|
|
171
|
+
const code = takeValue(args, "--code");
|
|
172
|
+
const recoveryCode = takeValue(args, "--recovery-code");
|
|
173
|
+
const email = args.shift();
|
|
174
|
+
if (!email || args.length) fail(WHATSAPP_USAGE);
|
|
175
|
+
const answer = await withSecondFactor((body) => client.inviteWhatsappConnector(body),
|
|
176
|
+
{ email, code, recovery_code: recoveryCode });
|
|
177
|
+
if (json) return console.log(JSON.stringify(answer, null, 2));
|
|
178
|
+
console.log(`Emailed ${answer.invited} the link that connects your number (${answer.role} on the team).`);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function printTeam({ members = [] }, { json }) {
|
|
182
|
+
if (json) return console.log(JSON.stringify(members, null, 2));
|
|
183
|
+
if (members.length === 0) return console.log("No one on the team has verified their WhatsApp yet (Account, in the inbox).");
|
|
184
|
+
for (const member of members) console.log(` ${member.role.padEnd(11)} ${member.number} ${member.name}`);
|
|
85
185
|
}
|
|
86
186
|
|
|
87
|
-
function
|
|
187
|
+
function printNumber(number, { json = false } = {}) {
|
|
188
|
+
if (json) return console.log(JSON.stringify(number, null, 2));
|
|
88
189
|
const live = number.live
|
|
89
190
|
? paint("green", "live: the agent answers everyone who writes")
|
|
90
|
-
: paint("cyan", "paused:
|
|
91
|
-
console.log(`\n${number.display_phone_number ?? "Your number"}: ${live}`);
|
|
191
|
+
: paint("cyan", "paused: vatio whatsapp live on to answer");
|
|
192
|
+
console.log(`\n${number.number ?? number.display_phone_number ?? "Your number"}: ${live}`);
|
|
193
|
+
if (number.last_health_error) console.log(` ${paint("red", "problem:")} ${number.last_health_error} (vatio whatsapp check)`);
|
|
194
|
+
if (number.failed_deliveries) console.log(` ${number.failed_deliveries} failed deliveries: vatio whatsapp failed`);
|
|
92
195
|
}
|
package/lib/commands/chat.mjs
CHANGED
|
@@ -1,16 +1,24 @@
|
|
|
1
1
|
// `vatio chat …` — a conversation with one of your own deployments.
|
|
2
2
|
//
|
|
3
|
-
//
|
|
4
|
-
// on the `cli` channel. There is no flag that pretends to be a
|
|
5
|
-
// Instagram visitor; the shared WhatsApp preview number and the
|
|
6
|
-
// accounts do that for real, and a simulated channel was only
|
|
7
|
-
// answer to keep in step with the true one.
|
|
3
|
+
// By default you are yourself: the chat belongs to the token you are holding,
|
|
4
|
+
// on the `cli` channel, and anonymous. There is no flag that pretends to be a
|
|
5
|
+
// WhatsApp or Instagram visitor; the shared WhatsApp preview number and the
|
|
6
|
+
// Instagram test accounts do that for real, and a simulated channel was only
|
|
7
|
+
// ever a second answer to keep in step with the true one.
|
|
8
|
+
//
|
|
9
|
+
// What you can be is someone who already proved who they are: `--as-phone`
|
|
10
|
+
// speaks as a phone verified on WhatsApp (yours, or a test phone), and
|
|
11
|
+
// `--as-subject` signs the token your backend would, with your identity key,
|
|
12
|
+
// or `--visitor-token` brings one you have. Vatio only verifies them, as it
|
|
13
|
+
// does the widget's and WhatsApp's, so this gives you nothing you did not
|
|
14
|
+
// already hold (lib/visitor-identity.mjs, Vatio::Preview::Tester).
|
|
8
15
|
|
|
9
16
|
import { appendFileSync, existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
10
17
|
import { join } from "node:path";
|
|
11
18
|
|
|
12
19
|
import { ApiClient } from "../api-client.mjs";
|
|
13
20
|
import { fail, sleep, takeEnv, takeFlag, takeValue } from "../support.mjs";
|
|
21
|
+
import { IDENTITY_FLAGS_USAGE, takeIdentity, tokenFor } from "../visitor-identity.mjs";
|
|
14
22
|
|
|
15
23
|
export const STATE_FILE = ".vatio-chat.json";
|
|
16
24
|
|
|
@@ -36,8 +44,9 @@ export async function chat(config, args) {
|
|
|
36
44
|
for (const arg of args) {
|
|
37
45
|
if (REMOVED_FLAGS.some((flag) => arg === flag || arg.startsWith(`${flag}=`))) {
|
|
38
46
|
fail(
|
|
39
|
-
`\`${arg}\` was removed. A CLI chat is you, the developer holding the token
|
|
40
|
-
"
|
|
47
|
+
`\`${arg}\` was removed. A CLI chat is you, the developer holding the token, unless you say who: ` +
|
|
48
|
+
"--as-phone speaks as your verified WhatsApp (me) or a test phone, --as-subject ID signs a visitor in " +
|
|
49
|
+
"with your identity key, and --visitor-token brings a token you have; " +
|
|
41
50
|
"to pick a deployment use --env."
|
|
42
51
|
);
|
|
43
52
|
}
|
|
@@ -51,8 +60,11 @@ export async function chat(config, args) {
|
|
|
51
60
|
const fresh = takeFlag(args, "--new");
|
|
52
61
|
const apiUrl = takeValue(args, "--api-url");
|
|
53
62
|
const token = takeValue(args, "--token");
|
|
63
|
+
const asPhone = takeValue(args, "--as-phone");
|
|
64
|
+
|
|
65
|
+
const identity = takeIdentity(args, config);
|
|
54
66
|
|
|
55
|
-
const options = { environment, timeout, last, lastGiven: lastValue != null, json, apiUrl, token };
|
|
67
|
+
const options = { environment, timeout, last, lastGiven: lastValue != null, json, apiUrl, token, asPhone, identity };
|
|
56
68
|
if (args.length === 1 && RETIRED[args[0]]) fail(RETIRED[args[0]]);
|
|
57
69
|
if (args.length === 1 && NOT_SUBCOMMANDS.has(args[0].toLowerCase())) {
|
|
58
70
|
fail(
|
|
@@ -66,16 +78,19 @@ export async function chat(config, args) {
|
|
|
66
78
|
if (sub === "help") return console.log(chatHelp());
|
|
67
79
|
if (sub === "show") return await showChat(config, options, args);
|
|
68
80
|
|
|
69
|
-
|
|
81
|
+
// A phone is fixed when a chat opens, so naming one opens one. A signed-in
|
|
82
|
+
// visitor opens one only when it is someone else (ensureChat).
|
|
83
|
+
const opening = fresh || Boolean(asPhone);
|
|
84
|
+
if (opening) await startOver(config, options);
|
|
70
85
|
const message = args.join(" ").trim();
|
|
71
|
-
if (message === "") return
|
|
86
|
+
if (message === "") return opening ? undefined : console.log(chatHelp());
|
|
72
87
|
|
|
73
88
|
return await converse(config, options, message);
|
|
74
89
|
}
|
|
75
90
|
|
|
76
91
|
export function chatHelp() {
|
|
77
92
|
return `Usage:
|
|
78
|
-
vatio chat "message" [--env NAME] [--new] [--timeout N]
|
|
93
|
+
vatio chat "message" [--env NAME] [--new] [--timeout N] [--as-phone me|PHONE] ${IDENTITY_FLAGS_USAGE}
|
|
79
94
|
vatio chat show [CHAT_ID] [--env NAME] [--last N] [--json]
|
|
80
95
|
${EXPORT_USAGE}
|
|
81
96
|
|
|
@@ -92,10 +107,24 @@ A [safeguard] line says which of Vatio's checks discarded or rewrote a draft,
|
|
|
92
107
|
and a [vatio] line marks a reply Vatio wrote because the agent's turn produced
|
|
93
108
|
none: why, and whether anything in your workspace caused it.
|
|
94
109
|
|
|
110
|
+
--as-subject ID talks as that person, signed in: it signs the JWT your backend
|
|
111
|
+
would, with the private key from \`vatio auth --new-key\` (VATIO_IDENTITY_PRIVATE_KEY,
|
|
112
|
+
identity.pem next to vatio.yml, or --identity-key FILE), so tools marked
|
|
113
|
+
\`access: private\` run with their \`$auth.token\`. Vatio only verifies it, the
|
|
114
|
+
way it does the widget's. --visitor-token JWT (or VATIO_VISITOR_TOKEN) brings a
|
|
115
|
+
token you signed elsewhere.
|
|
116
|
+
A chat as someone else starts over; the same person continues it.
|
|
117
|
+
|
|
95
118
|
The open chat per deployment is remembered in ${STATE_FILE}, so a second
|
|
96
119
|
\`vatio chat\` continues the first. \`--new\` starts over as a visitor the
|
|
97
120
|
workspace has never met.
|
|
98
121
|
|
|
122
|
+
\`--as-phone\` opens a preview chat that speaks as a phone, for tools that
|
|
123
|
+
need $contact.phone_number or a team role (access: supervisor and up): \`me\`
|
|
124
|
+
is your own verified WhatsApp, with your role on the team; a number from
|
|
125
|
+
\`vatio whatsapp test-phones\` is a customer. It stays a CLI chat: nothing goes
|
|
126
|
+
to WhatsApp.
|
|
127
|
+
|
|
99
128
|
\`export\` prints what people said and what they were answered between two
|
|
100
129
|
dates (live unless --env says otherwise), one conversation per line as JSON,
|
|
101
130
|
for reading them in bulk -- with a coding agent, say. Vatio redacts it before
|
|
@@ -191,43 +220,88 @@ export function rememberedChatId(config, environment) {
|
|
|
191
220
|
return chatsFor(config, config.resolveApiUrl())[environment] ?? null;
|
|
192
221
|
}
|
|
193
222
|
|
|
194
|
-
|
|
223
|
+
// Who each remembered chat is with: the subject it was signed in as, or null
|
|
224
|
+
// for the anonymous one. A chat is continued only by the same answer.
|
|
225
|
+
function subjectsFor(config, apiUrl) {
|
|
226
|
+
const state = loadState(config);
|
|
227
|
+
if (state.api_url !== apiUrl) return {};
|
|
228
|
+
return state.subjects && typeof state.subjects === "object" ? state.subjects : {};
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function rememberChat(config, { apiUrl, environment, chatId, subject = null }) {
|
|
195
232
|
const chats = { ...chatsFor(config, apiUrl), [environment]: chatId };
|
|
196
|
-
|
|
233
|
+
const subjects = { ...subjectsFor(config, apiUrl), [environment]: subject };
|
|
234
|
+
writeFileSync(statePath(config), `${JSON.stringify({ api_url: apiUrl, chats, subjects }, null, 2)}\n`);
|
|
197
235
|
}
|
|
198
236
|
|
|
199
237
|
async function ensureChat(config, options) {
|
|
200
238
|
const apiUrl = config.resolveApiUrl({ explicit: options.apiUrl });
|
|
201
239
|
const existing = chatsFor(config, apiUrl)[options.environment];
|
|
202
|
-
|
|
240
|
+
const subject = options.identity?.subject ?? null;
|
|
241
|
+
const same = (subjectsFor(config, apiUrl)[options.environment] ?? null) === subject;
|
|
242
|
+
if (existing && same) {
|
|
243
|
+
if (options.identity) await refreshIdentity(config, options, Number(existing));
|
|
244
|
+
return Number(existing);
|
|
245
|
+
}
|
|
203
246
|
|
|
204
|
-
|
|
247
|
+
// A chat as someone else is another conversation, with another visitor.
|
|
248
|
+
const payload = await openChat(config, options, { apiUrl, chatId: existing ? Number(existing) : null });
|
|
205
249
|
return Number(payload.chat_id);
|
|
206
250
|
}
|
|
207
251
|
|
|
252
|
+
// The chat keeps the token it was opened with, and a signed one is short-lived:
|
|
253
|
+
// each command hands it a fresh one, so a conversation outlives the first.
|
|
254
|
+
async function refreshIdentity(config, options, chatId) {
|
|
255
|
+
const outcome = await client(config, options).identifyChat({
|
|
256
|
+
chatId,
|
|
257
|
+
visitorToken: tokenFor(options.identity)
|
|
258
|
+
});
|
|
259
|
+
if (outcome.identified === false) fail(identityRefusal(outcome.reason));
|
|
260
|
+
}
|
|
261
|
+
|
|
208
262
|
async function openChat(config, options, { apiUrl, chatId = null }) {
|
|
209
263
|
const api = client(config, options);
|
|
264
|
+
const visitorToken = options.identity ? tokenFor(options.identity) : null;
|
|
210
265
|
const payload = chatId
|
|
211
|
-
? await api.resetChat({ chatId, environment: options.environment })
|
|
212
|
-
: await api.createChat({ environment: options.environment });
|
|
266
|
+
? await api.resetChat({ chatId, environment: options.environment, asPhone: options.asPhone, visitorToken })
|
|
267
|
+
: await api.createChat({ environment: options.environment, asPhone: options.asPhone, visitorToken });
|
|
213
268
|
|
|
214
|
-
rememberChat(config, {
|
|
215
|
-
|
|
269
|
+
rememberChat(config, {
|
|
270
|
+
apiUrl,
|
|
271
|
+
environment: options.environment,
|
|
272
|
+
chatId: payload.chat_id,
|
|
273
|
+
subject: options.identity?.subject ?? null
|
|
274
|
+
});
|
|
275
|
+
announce(options.environment, payload, options.identity);
|
|
216
276
|
return payload;
|
|
217
277
|
}
|
|
218
278
|
|
|
279
|
+
function identityRefusal(reason) {
|
|
280
|
+
return reason === "identity_changed"
|
|
281
|
+
? "That chat belongs to someone else. Start over with `vatio chat --new`."
|
|
282
|
+
: "Vatio could not verify that token. It has to be signed with the key matching `auth.public_key` in vatio.yml " +
|
|
283
|
+
"(pushed to this environment), with `aud` set to the workspace slug and an `exp` that has not passed.";
|
|
284
|
+
}
|
|
285
|
+
|
|
219
286
|
// Live is not refused -- you asked for it -- but it is said out loud, once,
|
|
220
287
|
// when the chat opens. A conversation against live is a real one: it lands in
|
|
221
288
|
// the inbox next to the ones visitors started, and nothing downstream knows it
|
|
222
289
|
// came from a terminal.
|
|
223
|
-
function announce(environment) {
|
|
290
|
+
function announce(environment, payload = {}, identity = null) {
|
|
291
|
+
const as = `${speaker(payload)}${identity ? `, signed in as ${identity.subject}` : ""}`;
|
|
224
292
|
if (environment === "live") {
|
|
225
|
-
console.log(
|
|
293
|
+
console.log(`Talking to live${as} — this is a real conversation and appears in your inbox.`);
|
|
226
294
|
} else {
|
|
227
|
-
console.log(`Talking to ${environment}`);
|
|
295
|
+
console.log(`Talking to ${environment}${as}`);
|
|
228
296
|
}
|
|
229
297
|
}
|
|
230
298
|
|
|
299
|
+
function speaker(payload) {
|
|
300
|
+
const phone = payload.contact?.phone_number;
|
|
301
|
+
if (!phone) return "";
|
|
302
|
+
return ` as ${phone}${payload.team_role ? ` (${payload.team_role})` : ""}`;
|
|
303
|
+
}
|
|
304
|
+
|
|
231
305
|
async function converse(config, options, message) {
|
|
232
306
|
const api = client(config, options);
|
|
233
307
|
const chatId = await ensureChat(config, options);
|
package/lib/commands/improve.mjs
CHANGED
|
@@ -15,6 +15,7 @@ import { rememberedChatId } from "./chat.mjs";
|
|
|
15
15
|
import { clientHeaders } from "../telemetry.mjs";
|
|
16
16
|
import { fail, sleep, takeEnv, takeFlag, takeValue } from "../support.mjs";
|
|
17
17
|
import { printSkillsHint } from "../skills-hint.mjs";
|
|
18
|
+
import { takeIdentity, tokenFor } from "../visitor-identity.mjs";
|
|
18
19
|
|
|
19
20
|
const POLL_MS = 3_000;
|
|
20
21
|
const DEFAULT_TIMEOUT_S = 900;
|
|
@@ -281,11 +282,20 @@ async function runTests(config, args, { name, waitByDefault }) {
|
|
|
281
282
|
const wait = takeFlag(args, "--wait");
|
|
282
283
|
const noWait = takeFlag(args, "--no-wait");
|
|
283
284
|
const timeoutS = Number(takeValue(args, "--timeout") ?? DEFAULT_TIMEOUT_S);
|
|
285
|
+
const identity = takeIdentity(args, config);
|
|
284
286
|
const waiting = wait || (waitByDefault && !noWait);
|
|
285
287
|
|
|
286
288
|
const { url, token } = workspaceBase(config);
|
|
287
289
|
const client = new HttpClient({ baseUrl: url, token });
|
|
288
|
-
|
|
290
|
+
// Every case of the run replays as that visitor, signed in: what a tool
|
|
291
|
+
// marked `access: private` needs to run. Vatio keeps the token only until
|
|
292
|
+
// the run ends.
|
|
293
|
+
const started = await client.post("/evals/runs", {
|
|
294
|
+
environment,
|
|
295
|
+
agent: agent ?? undefined,
|
|
296
|
+
visitor_token: identity ? tokenFor(identity) : undefined
|
|
297
|
+
});
|
|
298
|
+
if (identity) console.error(`vatio: replaying every case signed in as ${identity.subject}`);
|
|
289
299
|
|
|
290
300
|
for (const slug of started.missing_agents ?? []) {
|
|
291
301
|
console.error(`vatio: no agent \`${slug}\` on ${environment}; its cases were skipped`);
|
package/lib/commands/team.mjs
CHANGED
|
@@ -67,16 +67,19 @@ function print(answer, workspace, json) {
|
|
|
67
67
|
// An owner with a second factor confirms it is them, as the inbox asks. From a
|
|
68
68
|
// terminal the code is asked for; a coding agent has none, so it fails with what
|
|
69
69
|
// to ask the person for.
|
|
70
|
-
|
|
70
|
+
// `vatio whatsapp invite` asks the same way.
|
|
71
|
+
const invite = (client, body) => withSecondFactor((confirmed) => client.inviteMember(confirmed), body);
|
|
72
|
+
|
|
73
|
+
export async function withSecondFactor(send, body) {
|
|
71
74
|
const confirmed = Object.fromEntries(Object.entries(body).filter(([, value]) => value));
|
|
72
75
|
try {
|
|
73
|
-
return await
|
|
76
|
+
return await send(confirmed);
|
|
74
77
|
} catch (error) {
|
|
75
78
|
const needsCode = error?.status === 403 && error?.body?.error?.code === "reauthentication_required";
|
|
76
79
|
if (!needsCode || confirmed.code || confirmed.recovery_code) throw error;
|
|
77
80
|
if (!process.stdin.isTTY || !/--code/.test(error.message)) throw error;
|
|
78
81
|
const code = await askSecret(`${paint("green", "?")} Code from your authenticator app: `);
|
|
79
|
-
return await
|
|
82
|
+
return await send({ ...confirmed, code });
|
|
80
83
|
}
|
|
81
84
|
}
|
|
82
85
|
|
|
@@ -19,6 +19,8 @@ function takeAll(args, name) {
|
|
|
19
19
|
const LIST_USAGE = "vatio templates list [--env live] [--json]";
|
|
20
20
|
const CREATE_USAGE = "vatio templates create NAME --language CODE --body TEXT [--example VALUE]... " +
|
|
21
21
|
"[--category utility|marketing] [--footer TEXT] [--json]";
|
|
22
|
+
const RM_USAGE = "vatio templates rm NAME [--language CODE] [--json]";
|
|
23
|
+
const SYNC_USAGE = "vatio templates sync [--json]";
|
|
22
24
|
|
|
23
25
|
export async function templates(config, args) {
|
|
24
26
|
const json = takeFlag(args, "--json");
|
|
@@ -26,11 +28,20 @@ export async function templates(config, args) {
|
|
|
26
28
|
args.shift();
|
|
27
29
|
return createTemplate(config, args, json);
|
|
28
30
|
}
|
|
31
|
+
if (args[0] === "sync") {
|
|
32
|
+
const payload = await deployClient(config, config.resolveWorkspaceRequired()).syncTemplates();
|
|
33
|
+
if (json) return console.log(JSON.stringify(payload.templates ?? [], null, 2));
|
|
34
|
+
return console.log(`Synced ${(payload.templates ?? []).length} templates from Meta. See them: vatio whatsapp templates`);
|
|
35
|
+
}
|
|
36
|
+
if (args[0] === "rm") {
|
|
37
|
+
args.shift();
|
|
38
|
+
return deleteTemplate(config, args, json);
|
|
39
|
+
}
|
|
29
40
|
const environment = takeEnv(args, { fallback: "live" });
|
|
30
41
|
const workspace = config.resolveWorkspaceRequired();
|
|
31
42
|
const client = deployClient(config, workspace);
|
|
32
43
|
const sub = args.shift() ?? "list";
|
|
33
|
-
if (sub !== "list") fail(`Usage: ${LIST_USAGE}\n ${CREATE_USAGE}`);
|
|
44
|
+
if (sub !== "list") fail(`Usage: ${LIST_USAGE}\n ${CREATE_USAGE}\n ${RM_USAGE}\n ${SYNC_USAGE}`);
|
|
34
45
|
|
|
35
46
|
const payload = await client.listTemplates({ environment });
|
|
36
47
|
const list = Array.isArray(payload.templates) ? payload.templates : [];
|
|
@@ -101,6 +112,19 @@ async function createTemplate(config, args, json) {
|
|
|
101
112
|
}
|
|
102
113
|
}
|
|
103
114
|
|
|
115
|
+
// Where create put it: the workspace's own number, or Vatio's test number
|
|
116
|
+
// before it has one. Every language under the name unless one is given.
|
|
117
|
+
async function deleteTemplate(config, args, json) {
|
|
118
|
+
const language = takeValue(args, "--language");
|
|
119
|
+
const name = args.shift();
|
|
120
|
+
if (!name || args.length > 0) fail(`Usage: ${RM_USAGE}`);
|
|
121
|
+
|
|
122
|
+
const client = deployClient(config, config.resolveWorkspaceRequired());
|
|
123
|
+
const { deleted = [] } = await client.deleteTemplate({ name, language });
|
|
124
|
+
if (json) return console.log(JSON.stringify(deleted, null, 2));
|
|
125
|
+
for (const template of deleted) console.log(`Deleted ${template.name} (${template.language}).`);
|
|
126
|
+
}
|
|
127
|
+
|
|
104
128
|
export async function webhooks(config, args) {
|
|
105
129
|
const environment = takeEnv(args, { fallback: "live" });
|
|
106
130
|
const label = takeValue(args, "--label");
|
package/lib/help.mjs
CHANGED
|
@@ -69,10 +69,14 @@ the two you are in. Commands default as listed.
|
|
|
69
69
|
--env live answers "what would publishing change?"
|
|
70
70
|
diff --stat|--name-only|--format json|--full
|
|
71
71
|
|
|
72
|
-
Talk to your agent (as yourself — the token is the identity):
|
|
73
|
-
chat "message" [--env NAME] [--new]
|
|
72
|
+
Talk to your agent (as yourself by default — the token is the identity):
|
|
73
|
+
chat "message" [--env NAME] [--new] [--as-phone me|PHONE]
|
|
74
|
+
[--as-subject ID | --visitor-token JWT]
|
|
74
75
|
preview by default; --env live is real; --new
|
|
75
|
-
starts over as a visitor the agent never met
|
|
76
|
+
starts over as a visitor the agent never met.
|
|
77
|
+
--as-phone speaks as your verified WhatsApp or a
|
|
78
|
+
test phone; --as-subject signs a visitor in with
|
|
79
|
+
your identity key, so \`access: private\` tools run
|
|
76
80
|
chat show [CHAT_ID] [--json] [--last N]
|
|
77
81
|
The chat you are in, or any chat in the workspace
|
|
78
82
|
(web, WhatsApp, ...): messages, tool calls, channel
|
|
@@ -99,11 +103,13 @@ the two you are in. Commands default as listed.
|
|
|
99
103
|
Each tool's calls, error rate, timeouts and
|
|
100
104
|
p50/p95, then the calls that failed with what
|
|
101
105
|
your backend answered. Default: live, 7d
|
|
102
|
-
test [--env NAME] [--agent SLUG]
|
|
106
|
+
test [--env NAME] [--agent SLUG] [--as-subject ID | --visitor-token JWT]
|
|
103
107
|
Test every report and test against preview
|
|
104
108
|
(default): starts the runs on Vatio's servers,
|
|
105
109
|
prints their ids and returns.
|
|
106
|
-
--env live also resolves the reports it passes
|
|
110
|
+
--env live also resolves the reports it passes.
|
|
111
|
+
--as-subject replays every case signed in as
|
|
112
|
+
that visitor (see \`vatio chat\`)
|
|
107
113
|
test --wait [--timeout N] Wait for the judge and print the report; exits 1
|
|
108
114
|
if a case fails. Joins this version's running run
|
|
109
115
|
test --show RUN_ID One run's report so far, with the replay chat of
|
|
@@ -176,22 +182,7 @@ the two you are in. Commands default as listed.
|
|
|
176
182
|
keys revoke PREFIX
|
|
177
183
|
auth --new-key Keypair that signs the JWT saying who a visitor is
|
|
178
184
|
|
|
179
|
-
|
|
180
|
-
Vatio retries confirmed failures automatically. Inspect terminal failures:
|
|
181
|
-
messages failed [--since DATE] [--until DATE] [--error-code CODE]
|
|
182
|
-
[--error-contains TEXT] [--before ID] [--json]
|
|
183
|
-
List failed outgoing messages, including Meta's
|
|
184
|
-
delivery failures (default: live)
|
|
185
|
-
|
|
186
|
-
Sending from your backend (WhatsApp, with a server key):
|
|
187
|
-
templates list [--env live] [--json]
|
|
188
|
-
The number's templates, parameter counts, and the
|
|
189
|
-
"template" object to send
|
|
190
|
-
templates create NAME --language CODE --body TEXT [--example VALUE]...
|
|
191
|
-
[--category utility|marketing] [--footer TEXT] [--json]
|
|
192
|
-
Submit a template for Meta's review: on your number,
|
|
193
|
-
or on Vatio's test number until you connect one;
|
|
194
|
-
one --example per {{n}} in the body
|
|
185
|
+
Sending from your backend (with a server key):
|
|
195
186
|
webhooks list|create URL [--event NAME]...|test ID|deliveries ID|enable ID|rm ID
|
|
196
187
|
Where Vatio tells your backend what happened
|
|
197
188
|
|
|
@@ -202,12 +193,37 @@ the two you are in. Commands default as listed.
|
|
|
202
193
|
contacts delete ID [--yes] Delete them and everything about them, for good. Asks you
|
|
203
194
|
to type the ID; without a terminal, needs --yes
|
|
204
195
|
|
|
196
|
+
WhatsApp (everything on the inbox's WhatsApp page; --json on each):
|
|
197
|
+
whatsapp [status] Your number, whether it is live, its problems,
|
|
198
|
+
and the test phones
|
|
199
|
+
whatsapp connect Where to connect your number (Meta's consent
|
|
200
|
+
screen only opens in the inbox)
|
|
201
|
+
whatsapp live on|off Answer everyone who writes, or nobody
|
|
202
|
+
whatsapp check Check the number with Meta and re-subscribe it
|
|
203
|
+
whatsapp disconnect [--yes]
|
|
204
|
+
whatsapp invite EMAIL [--code CODE]
|
|
205
|
+
Email whoever holds the number the link that
|
|
206
|
+
connects it (owner only)
|
|
207
|
+
whatsapp team Who on the team verified their own WhatsApp
|
|
208
|
+
whatsapp phones [list] Test phones on Vatio's shared preview number
|
|
209
|
+
whatsapp phones add The code a phone sends to join, and its link
|
|
210
|
+
whatsapp phones rm PHONE | move PHONE
|
|
211
|
+
Remove one, or bring one you verified elsewhere
|
|
212
|
+
whatsapp templates [list] [--env live]
|
|
213
|
+
The number's templates and the "template" to send
|
|
214
|
+
whatsapp templates create NAME --language CODE --body TEXT [--example VALUE]...
|
|
215
|
+
[--category utility|marketing] [--footer TEXT]
|
|
216
|
+
Submit one for Meta's review: on your number, or
|
|
217
|
+
on Vatio's test number until you connect one
|
|
218
|
+
whatsapp templates rm NAME [--language CODE] | sync
|
|
219
|
+
Delete one at Meta; pull back ones made elsewhere
|
|
220
|
+
whatsapp failed [--since DATE] [--until DATE] [--error-code CODE]
|
|
221
|
+
[--error-contains TEXT] [--before ID]
|
|
222
|
+
Messages Vatio gave up retrying (default: live)
|
|
223
|
+
templates ... Older spelling of whatsapp templates; still works
|
|
224
|
+
messages failed ... Older spelling of whatsapp failed; still works
|
|
225
|
+
|
|
205
226
|
Channels:
|
|
206
|
-
whatsapp Set up in the inbox; prints the link (Try the agent
|
|
207
|
-
until you publish, then Channels)
|
|
208
|
-
whatsapp test-phones [--json]
|
|
209
|
-
The phones verified in Try the agent, to send a
|
|
210
|
-
preview message to
|
|
211
227
|
instagram The same, for Instagram
|
|
212
228
|
|
|
213
229
|
Everything else:
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
// Who a developer's chat or test run talks as: a signed-in visitor, proved the
|
|
2
|
+
// way the widget proves one -- a JWT the workspace signed.
|
|
3
|
+
//
|
|
4
|
+
// Vatio holds only the public key, so it cannot mint this token and nothing
|
|
5
|
+
// here asks it to. The developer already holds the private half (`vatio auth
|
|
6
|
+
// --new-key` made it) and could sign a token for any `sub` by hand; signing it
|
|
7
|
+
// here only saves the openssl and base64 work, so the key never leaves the
|
|
8
|
+
// machine and Vatio's check on the other side is the one visitors face.
|
|
9
|
+
//
|
|
10
|
+
// --as-subject ID sign a token for this subject with your identity key
|
|
11
|
+
// --visitor-token JWT use a token you already have (VATIO_VISITOR_TOKEN too)
|
|
12
|
+
// --identity-key FILE the key to sign with (default: VATIO_IDENTITY_PRIVATE_KEY,
|
|
13
|
+
// then identity.pem next to vatio.yml)
|
|
14
|
+
|
|
15
|
+
import { constants, createPrivateKey, sign } from "node:crypto";
|
|
16
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
17
|
+
import { join } from "node:path";
|
|
18
|
+
|
|
19
|
+
import { parse as parseYaml } from "yaml";
|
|
20
|
+
|
|
21
|
+
import { fail, takeValue } from "./support.mjs";
|
|
22
|
+
import { MANIFEST_FILE } from "./workspace.mjs";
|
|
23
|
+
|
|
24
|
+
const KEY_ENV = "VATIO_IDENTITY_PRIVATE_KEY";
|
|
25
|
+
const KEY_FILE = "identity.pem";
|
|
26
|
+
const TOKEN_ENV = "VATIO_VISITOR_TOKEN";
|
|
27
|
+
// Long enough for a test run to finish on Vatio's servers, short enough that a
|
|
28
|
+
// token lost in a transcript is worthless by the afternoon.
|
|
29
|
+
const TTL_SECONDS = 60 * 60;
|
|
30
|
+
|
|
31
|
+
const ALGORITHMS = ["RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512"];
|
|
32
|
+
const ES_CURVES = { prime256v1: "ES256", secp384r1: "ES384", secp521r1: "ES512" };
|
|
33
|
+
|
|
34
|
+
export const IDENTITY_FLAGS_USAGE = "[--as-subject ID | --visitor-token JWT] [--identity-key FILE]";
|
|
35
|
+
|
|
36
|
+
// Takes the identity flags out of `args`. Null when none was asked for, so a
|
|
37
|
+
// command that does not need an identity behaves exactly as before.
|
|
38
|
+
export function takeIdentity(args, config) {
|
|
39
|
+
const subject = takeValue(args, "--as-subject");
|
|
40
|
+
const keyFile = takeValue(args, "--identity-key");
|
|
41
|
+
const flagged = takeValue(args, "--visitor-token");
|
|
42
|
+
|
|
43
|
+
if (subject !== null && flagged !== null) fail("Use --as-subject or --visitor-token, not both.");
|
|
44
|
+
const token = flagged ?? (subject === null ? process.env[TOKEN_ENV] || null : null);
|
|
45
|
+
|
|
46
|
+
if (subject === null && token === null) {
|
|
47
|
+
if (keyFile !== null) fail("--identity-key signs a token for --as-subject; pass that too.");
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
if (token !== null) return { token: token.trim(), subject: subjectOf(token), signed: false };
|
|
51
|
+
if (subject.trim() === "") fail("--as-subject needs the id your backend knows the person by.");
|
|
52
|
+
|
|
53
|
+
return { subject, signed: true, sign: () => signToken({ subject, config, keyFile }) };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// The token to send now. A signed one is made fresh each time, so a chat that
|
|
57
|
+
// outlives one token keeps going on the next.
|
|
58
|
+
export function tokenFor(identity) {
|
|
59
|
+
return identity.signed ? identity.sign() : identity.token;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function signToken({ subject, config, keyFile }) {
|
|
63
|
+
const key = loadKey(config, keyFile);
|
|
64
|
+
const algorithm = declaredAlgorithm(config) ?? algorithmFor(key);
|
|
65
|
+
const now = Math.floor(Date.now() / 1000);
|
|
66
|
+
const header = { alg: algorithm, typ: "JWT" };
|
|
67
|
+
const claims = { sub: subject, aud: config.resolveWorkspaceRequired(), iat: now, exp: now + TTL_SECONDS };
|
|
68
|
+
const signingInput = `${base64url(JSON.stringify(header))}.${base64url(JSON.stringify(claims))}`;
|
|
69
|
+
|
|
70
|
+
const options = { key };
|
|
71
|
+
if (algorithm.startsWith("PS")) {
|
|
72
|
+
options.padding = constants.RSA_PKCS1_PSS_PADDING;
|
|
73
|
+
options.saltLength = constants.RSA_PSS_SALTLEN_DIGEST;
|
|
74
|
+
}
|
|
75
|
+
// JWT writes an ECDSA signature as r || s, not the ASN.1 form OpenSSL gives.
|
|
76
|
+
if (algorithm.startsWith("ES")) options.dsaEncoding = "ieee-p1363";
|
|
77
|
+
|
|
78
|
+
const signature = sign(`sha${algorithm.slice(2)}`, Buffer.from(signingInput), options);
|
|
79
|
+
return `${signingInput}.${base64url(signature)}`;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function loadKey(config, keyFile) {
|
|
83
|
+
let pem = null;
|
|
84
|
+
if (keyFile !== null) {
|
|
85
|
+
if (!existsSync(keyFile)) fail(`--identity-key ${keyFile} does not exist.`);
|
|
86
|
+
pem = readFileSync(keyFile, "utf8");
|
|
87
|
+
} else if (process.env[KEY_ENV]) {
|
|
88
|
+
pem = process.env[KEY_ENV];
|
|
89
|
+
} else {
|
|
90
|
+
const path = join(config.workspaceRootRequired(), KEY_FILE);
|
|
91
|
+
if (existsSync(path)) pem = readFileSync(path, "utf8");
|
|
92
|
+
}
|
|
93
|
+
if (pem === null) {
|
|
94
|
+
fail(
|
|
95
|
+
`There is no key to sign with. Put the private key you made with \`vatio auth --new-key\` in ${KEY_ENV}, ` +
|
|
96
|
+
`or in ${KEY_FILE} next to vatio.yml, or pass --identity-key FILE. ` +
|
|
97
|
+
"If you sign tokens somewhere else, make one there and pass it as --visitor-token."
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
try {
|
|
101
|
+
return createPrivateKey(pem);
|
|
102
|
+
} catch {
|
|
103
|
+
fail(`The identity key is not a PEM private key. Check ${keyFile ?? `${KEY_ENV} or ${KEY_FILE}`}.`);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// Vatio verifies with the algorithm the manifest declares, never the token's
|
|
108
|
+
// own header, so a token signed with another one would simply not verify.
|
|
109
|
+
function declaredAlgorithm(config) {
|
|
110
|
+
try {
|
|
111
|
+
const manifest = parseYaml(readFileSync(join(config.workspaceRootRequired(), MANIFEST_FILE), "utf8"));
|
|
112
|
+
const algorithm = String(manifest?.auth?.algorithm ?? "").trim().toUpperCase();
|
|
113
|
+
return ALGORITHMS.includes(algorithm) ? algorithm : null;
|
|
114
|
+
} catch {
|
|
115
|
+
return null;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// What the workspace's `auth.algorithm` is when the manifest leaves it out:
|
|
120
|
+
// the one the key's type implies.
|
|
121
|
+
function algorithmFor(key) {
|
|
122
|
+
if (key.asymmetricKeyType === "rsa") return "RS256";
|
|
123
|
+
if (key.asymmetricKeyType === "ec") {
|
|
124
|
+
const algorithm = ES_CURVES[key.asymmetricKeyDetails?.namedCurve];
|
|
125
|
+
if (algorithm) return algorithm;
|
|
126
|
+
}
|
|
127
|
+
return fail("The identity key has to be an RSA or EC (P-256, P-384, P-521) private key.");
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function subjectOf(token) {
|
|
131
|
+
try {
|
|
132
|
+
const payload = JSON.parse(Buffer.from(token.split(".")[1], "base64url").toString("utf8"));
|
|
133
|
+
if (payload.sub !== undefined && payload.sub !== null && String(payload.sub) !== "") return String(payload.sub);
|
|
134
|
+
} catch {
|
|
135
|
+
// Falls through to the message below.
|
|
136
|
+
}
|
|
137
|
+
return fail("--visitor-token is not a JWT with a `sub`.");
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function base64url(value) {
|
|
141
|
+
return Buffer.from(value).toString("base64url");
|
|
142
|
+
}
|