@vatio-ai/cli 0.114.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 +22 -4
- package/lib/commands/chat.mjs +96 -22
- package/lib/commands/improve.mjs +11 -1
- package/lib/help.mjs +11 -5
- 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
|
|
|
@@ -287,12 +294,23 @@ export class ApiClient extends HttpClient {
|
|
|
287
294
|
|
|
288
295
|
// --- chats ----------------------------------------------------------
|
|
289
296
|
|
|
290
|
-
|
|
291
|
-
|
|
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 }));
|
|
292
307
|
}
|
|
293
308
|
|
|
294
|
-
|
|
295
|
-
|
|
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 });
|
|
296
314
|
}
|
|
297
315
|
|
|
298
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`);
|
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
|
|
@@ -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
|
+
}
|