@vatio-ai/cli 0.113.0 → 0.116.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 +28 -6
- package/lib/commands/chat.mjs +96 -22
- package/lib/commands/improve.mjs +11 -1
- package/lib/commands/workspace-admin.mjs +77 -15
- package/lib/help.mjs +17 -6
- 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
|
|
|
@@ -176,10 +183,14 @@ export class ApiClient extends HttpClient {
|
|
|
176
183
|
return this.get("/api_keys");
|
|
177
184
|
}
|
|
178
185
|
|
|
179
|
-
|
|
180
|
-
|
|
186
|
+
// `scopes` (a secret key's) left null takes the platform's default: every
|
|
187
|
+
// scope but `team`. `confirmation` is { code } or { recovery_code }, which a
|
|
188
|
+
// `team` key needs.
|
|
189
|
+
createApiKey({ kind, environment, label = null, allowedOrigins = [], scopes = null, confirmation = {} }) {
|
|
190
|
+
const body = { kind, environment, ...confirmation };
|
|
181
191
|
if (String(label ?? "").trim() !== "") body.label = String(label).trim();
|
|
182
192
|
if (allowedOrigins.length > 0) body.allowed_origins = allowedOrigins;
|
|
193
|
+
if (Array.isArray(scopes) && scopes.length > 0) body.scopes = scopes;
|
|
183
194
|
return this.post("/api_keys", body);
|
|
184
195
|
}
|
|
185
196
|
|
|
@@ -283,12 +294,23 @@ export class ApiClient extends HttpClient {
|
|
|
283
294
|
|
|
284
295
|
// --- chats ----------------------------------------------------------
|
|
285
296
|
|
|
286
|
-
|
|
287
|
-
|
|
297
|
+
// Who is writing: `asPhone` a verified phone (Vatio::Preview::Tester), or
|
|
298
|
+
// `visitorToken` a signed-in visitor, the JWT the workspace signed, which
|
|
299
|
+
// Vatio verifies against the public key in vatio.yml (see
|
|
300
|
+
// lib/visitor-identity.mjs). Left out, the chat is the token holder.
|
|
301
|
+
createChat({ environment, asPhone = null, visitorToken = null }) {
|
|
302
|
+
return this.post("/chats", chatFields({ environment, asPhone, visitorToken }));
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
resetChat({ chatId, environment, asPhone = null, visitorToken = null }) {
|
|
306
|
+
return this.post(`/chats/${encode(chatId)}/reset`, chatFields({ environment, asPhone, visitorToken }));
|
|
288
307
|
}
|
|
289
308
|
|
|
290
|
-
|
|
291
|
-
|
|
309
|
+
// A fresh token for a chat that already knows who it is talking to. Answers
|
|
310
|
+
// `identified: false` with a reason when it does not verify, or names someone
|
|
311
|
+
// else.
|
|
312
|
+
identifyChat({ chatId, visitorToken }) {
|
|
313
|
+
return this.post(`/chats/${encode(chatId)}/identify`, { visitor_token: visitorToken });
|
|
292
314
|
}
|
|
293
315
|
|
|
294
316
|
// No `view` parameter: the developer token is the developer view, so the
|
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`);
|
|
@@ -104,27 +104,39 @@ function secretScope({ environment, tests }) {
|
|
|
104
104
|
|
|
105
105
|
// Repeatable: `--origin https://a.com --origin https://b.com`.
|
|
106
106
|
function takeOrigins(args) {
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
107
|
+
return takeRepeated(args, "--origin");
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function takeRepeated(args, flag) {
|
|
111
|
+
const values = [];
|
|
112
|
+
for (let value = takeValue(args, flag); value !== null; value = takeValue(args, flag)) {
|
|
113
|
+
values.push(value);
|
|
110
114
|
}
|
|
111
|
-
return
|
|
115
|
+
return values;
|
|
112
116
|
}
|
|
113
117
|
|
|
114
118
|
const KINDS = ["publishable", "secret"];
|
|
119
|
+
// What a secret key may call on the server API. The platform validates them;
|
|
120
|
+
// this list is only for the help text. `team` is never given by default.
|
|
121
|
+
const SCOPES = ["messages", "instagram", "chats", "team"];
|
|
115
122
|
const KEYS_USAGE =
|
|
116
|
-
"Usage: vatio keys list [--json]|create publishable|secret [--env live|preview] [--label NAME] [--origin URL]...
|
|
117
|
-
"origins PREFIX URL...|revoke PREFIX";
|
|
123
|
+
"Usage: vatio keys list [--json]|create publishable|secret [--env live|preview] [--label NAME] [--origin URL]... " +
|
|
124
|
+
"[--scope NAME]... [--code CODE | --recovery-code CODE] [--json]|origins PREFIX URL...|revoke PREFIX";
|
|
118
125
|
|
|
119
126
|
// API keys, of two kinds. A publishable key is for a page or an app: public by
|
|
120
127
|
// design, accepted only from the origins it lists. A secret key is for the
|
|
121
|
-
// developer's own backend (
|
|
122
|
-
// it never goes in a page or an app, and unlike the
|
|
123
|
-
// to the workspace, so it outlives whoever created
|
|
128
|
+
// developer's own backend (to have the agent write to a contact first, read a
|
|
129
|
+
// chat, keep the team): it never goes in a page or an app, and unlike the
|
|
130
|
+
// CLI's own token it belongs to the workspace, so it outlives whoever created
|
|
131
|
+
// it. A secret key carries scopes; without --scope it gets every one but
|
|
132
|
+
// `team`.
|
|
124
133
|
export async function keys(config, args) {
|
|
125
134
|
const environment = environmentOption(args, "live");
|
|
126
135
|
const label = takeValue(args, "--label") ?? takeValue(args, "-l");
|
|
127
136
|
const origins = takeOrigins(args);
|
|
137
|
+
const scopes = takeRepeated(args, "--scope");
|
|
138
|
+
const code = takeValue(args, "--code");
|
|
139
|
+
const recoveryCode = takeValue(args, "--recovery-code");
|
|
128
140
|
const json = takeFlag(args, "--json");
|
|
129
141
|
const workspace = config.resolveWorkspaceRequired();
|
|
130
142
|
const client = deployClient(config, workspace);
|
|
@@ -151,20 +163,29 @@ export async function keys(config, args) {
|
|
|
151
163
|
parts.push(key.last_used_at ? `last used ${key.last_used_at}` : "never used");
|
|
152
164
|
console.log(` ${parts.filter(Boolean).join(" ")}`);
|
|
153
165
|
if (key.kind === "publishable") console.log(` origins: ${originsLine(key.allowed_origins)}`);
|
|
166
|
+
if (key.kind === "secret") console.log(` scopes: ${asArray(key.scopes).join(", ") || "none"}`);
|
|
154
167
|
}
|
|
155
168
|
return;
|
|
156
169
|
}
|
|
157
170
|
if (sub === "create") {
|
|
158
171
|
const kind = args.shift();
|
|
159
|
-
if (!KINDS.includes(kind))
|
|
172
|
+
if (!KINDS.includes(kind)) {
|
|
173
|
+
fail("Say which kind: vatio keys create publishable|secret [--env NAME] [--label NAME] [--origin URL]... [--scope NAME]...");
|
|
174
|
+
}
|
|
160
175
|
if (kind === "secret" && origins.length > 0) {
|
|
161
176
|
fail("--origin only applies to a publishable key. A secret key is for your backend and has no origins.");
|
|
162
177
|
}
|
|
163
|
-
|
|
178
|
+
if (kind === "publishable" && scopes.length > 0) {
|
|
179
|
+
fail(`--scope only applies to a secret key (${SCOPES.join(", ")}).`);
|
|
180
|
+
}
|
|
181
|
+
const payload = await createKey(client, {
|
|
164
182
|
kind,
|
|
165
183
|
environment,
|
|
166
184
|
label,
|
|
167
|
-
allowedOrigins: kind === "publishable" ? origins : []
|
|
185
|
+
allowedOrigins: kind === "publishable" ? origins : [],
|
|
186
|
+
scopes: kind === "secret" && scopes.length > 0 ? scopes : null,
|
|
187
|
+
code,
|
|
188
|
+
recoveryCode
|
|
168
189
|
});
|
|
169
190
|
// For a script that hands the key straight to something else: the key or a
|
|
170
191
|
// failed command, never a line of prose to grep it out of.
|
|
@@ -174,6 +195,7 @@ export async function keys(config, args) {
|
|
|
174
195
|
}
|
|
175
196
|
console.log(`Created a ${kind} key for ${environment} on workspace ${workspace}`);
|
|
176
197
|
if (kind === "publishable") console.log(` origins: ${originsLine(payload.api_key?.allowed_origins)}`);
|
|
198
|
+
if (kind === "secret") console.log(` scopes: ${asArray(payload.api_key?.scopes).join(", ")}`);
|
|
177
199
|
console.log("");
|
|
178
200
|
// Shown in full exactly once: the platform stores a digest, so this is the
|
|
179
201
|
// only moment the value exists anywhere the developer can copy it.
|
|
@@ -187,9 +209,16 @@ export async function keys(config, args) {
|
|
|
187
209
|
console.log("");
|
|
188
210
|
console.log(` VATIO_SERVER_KEY=${payload.key}`);
|
|
189
211
|
console.log("");
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
212
|
+
// A first call the key's scopes allow, that changes nothing.
|
|
213
|
+
const granted = asArray(payload.api_key?.scopes);
|
|
214
|
+
const [what, path] = granted.includes("messages")
|
|
215
|
+
? ["lists the templates your number can send", "templates"]
|
|
216
|
+
: granted.includes("team") ? ["lists the workspace's team", "team_members"] : [null, null];
|
|
217
|
+
if (path) {
|
|
218
|
+
console.log(`Try it (${what}):`);
|
|
219
|
+
console.log(` curl ${config.resolveBaseUrl()}/api/server/v1/${workspace}/${path} \\`);
|
|
220
|
+
console.log(' -H "Authorization: Bearer $VATIO_SERVER_KEY"');
|
|
221
|
+
}
|
|
193
222
|
return;
|
|
194
223
|
}
|
|
195
224
|
if (sub === "origins") {
|
|
@@ -210,6 +239,39 @@ export async function keys(config, args) {
|
|
|
210
239
|
fail(KEYS_USAGE);
|
|
211
240
|
}
|
|
212
241
|
|
|
242
|
+
// A `team` key needs the owner's second factor, as `vatio team invite` does:
|
|
243
|
+
// from a terminal the code is asked for; a coding agent has none, so it fails
|
|
244
|
+
// with what to ask the person for.
|
|
245
|
+
async function createKey(client, { code, recoveryCode, ...fields }) {
|
|
246
|
+
const confirmation = {};
|
|
247
|
+
if (code) confirmation.code = code;
|
|
248
|
+
if (recoveryCode) confirmation.recovery_code = recoveryCode;
|
|
249
|
+
try {
|
|
250
|
+
return await client.createApiKey({ ...fields, confirmation }).catch(explainKeyError);
|
|
251
|
+
} catch (error) {
|
|
252
|
+
const needsCode = error?.status === 403 && error?.body?.error?.code === "reauthentication_required";
|
|
253
|
+
// explainKeyError let it through only when the terminal can answer it.
|
|
254
|
+
if (!needsCode || code || recoveryCode) throw error;
|
|
255
|
+
const typed = await askSecret(`${paint("green", "?")} Code from your authenticator app: `);
|
|
256
|
+
return await client.createApiKey({ ...fields, confirmation: { code: typed } }).catch(explainKeyError);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// The answers whose own words say what to do, which the generic 403 and 422
|
|
261
|
+
// lines would hide. Left to throw: everything else, and a missing code the
|
|
262
|
+
// terminal can still ask for.
|
|
263
|
+
const KEY_ERRORS_THAT_SAY_WHY = new Set(["owner_only", "invalid_confirmation", "invalid_scopes"]);
|
|
264
|
+
|
|
265
|
+
function explainKeyError(error) {
|
|
266
|
+
const body = error?.body ?? {};
|
|
267
|
+
const code = body.error?.code ?? body.error_key;
|
|
268
|
+
if (code === "reauthentication_required" && !(process.stdin.isTTY && /--code/.test(error.message))) {
|
|
269
|
+
fail(error.message);
|
|
270
|
+
}
|
|
271
|
+
if (KEY_ERRORS_THAT_SAY_WHY.has(code)) fail(body.error_description ?? error.message);
|
|
272
|
+
throw error;
|
|
273
|
+
}
|
|
274
|
+
|
|
213
275
|
// A flag whose value is optional: `--flag`, `--flag VALUE` or `--flag=VALUE`.
|
|
214
276
|
// Returns null when it is absent and "" when it is there with no value, so
|
|
215
277
|
// the caller can tell those two apart. A following token that starts with `-`
|
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
|
|
@@ -162,9 +168,14 @@ the two you are in. Commands default as listed.
|
|
|
162
168
|
otherwise the value everywhere. With --tests, the
|
|
163
169
|
value preview and every test run use, like a staging URL
|
|
164
170
|
keys list [--json] API keys of both kinds: publishable (for a page or
|
|
165
|
-
app) and secret (for your backend)
|
|
171
|
+
app) and secret (for your backend, with its scopes)
|
|
166
172
|
keys create publishable|secret [--env NAME] [--label NAME] [--origin URL]... [--json]
|
|
167
173
|
--origin only for a publishable key
|
|
174
|
+
keys create secret --scope NAME... [--code CODE | --recovery-code CODE]
|
|
175
|
+
What the secret key may call: messages, instagram,
|
|
176
|
+
chats, team (repeatable). Without --scope, all but
|
|
177
|
+
team. team (add people to the team) is the owner's,
|
|
178
|
+
with a code from their authenticator app
|
|
168
179
|
keys origins PREFIX URL...
|
|
169
180
|
The origins a publishable key is accepted from
|
|
170
181
|
(replaces the list)
|
|
@@ -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
|
+
}
|