@vatio-ai/cli 0.101.0 → 0.103.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -93,7 +93,6 @@ kb write|cat|rm-entry Entries, from a file or stdin
93
93
  secrets list|set|rm Credentials your tools read
94
94
  keys list|create|origins|revoke API keys: publishable (page, app) and secret (backend)
95
95
  auth --new-key Keypair that signs the visitor's JWT
96
- auth --supabase [URL] Your users sign in with Supabase: no keys, no code
97
96
 
98
97
  whatsapp | instagram Set up in the inbox; prints the link
99
98
 
package/bin/vatio.mjs CHANGED
@@ -16,7 +16,7 @@ import { diff, publish, pull, push, rollback, status } from "../lib/commands/dep
16
16
  import { env } from "../lib/commands/env.mjs";
17
17
  import { keys, secrets } from "../lib/commands/workspace-admin.mjs";
18
18
  import { templates, webhooks } from "../lib/commands/webhooks.mjs";
19
- import { routines } from "../lib/commands/routines.mjs";
19
+ import { contacts } from "../lib/commands/contacts.mjs";
20
20
  import { auth } from "../lib/commands/identity-key.mjs";
21
21
  import { chat, chatHelp } from "../lib/commands/chat.mjs";
22
22
  import { kb } from "../lib/commands/knowledge.mjs";
@@ -102,8 +102,8 @@ async function run(command, args) {
102
102
  return await templates(config, args);
103
103
  case "webhooks":
104
104
  return await webhooks(config, args);
105
- case "routines":
106
- return await routines(config, args);
105
+ case "contacts":
106
+ return await contacts(config, args);
107
107
  case "auth":
108
108
  return await auth(config, args);
109
109
  case "chat":
@@ -267,30 +267,14 @@ export class ApiClient extends HttpClient {
267
267
  return this.get(`/webhook_endpoints/${encode(id)}/deliveries`);
268
268
  }
269
269
 
270
- // --- routines -------------------------------------------------------
270
+ // --- contacts -------------------------------------------------------
271
271
 
272
- listRoutines() {
273
- return this.get("/routines");
272
+ exportContact({ id }) {
273
+ return this.get(`/contacts/${encode(id)}/export`);
274
274
  }
275
275
 
276
- createRoutine(body) {
277
- return this.post("/routines", body);
278
- }
279
-
280
- updateRoutine({ id, ...attrs }) {
281
- return this.patch(`/routines/${encode(id)}`, attrs);
282
- }
283
-
284
- deleteRoutine({ id }) {
285
- return this.delete(`/routines/${encode(id)}`);
286
- }
287
-
288
- testRoutine({ id }) {
289
- return this.post(`/routines/${encode(id)}/test`);
290
- }
291
-
292
- listRoutineRuns({ id }) {
293
- return this.get(`/routines/${encode(id)}/runs`);
276
+ deleteContact({ id }) {
277
+ return this.delete(`/contacts/${encode(id)}`);
294
278
  }
295
279
 
296
280
  // --- chats ----------------------------------------------------------
@@ -97,6 +97,6 @@ function printAnswers(number) {
97
97
  return;
98
98
  }
99
99
  console.log(` The agent answers only: ${list.join(", ")}`);
100
- console.log(" Everyone else's messages reach the inbox unanswered; your routines' numbers always count.");
100
+ console.log(" Everyone else's messages reach the inbox unanswered.");
101
101
  console.log(" Back to everyone: vatio whatsapp everyone");
102
102
  }
@@ -0,0 +1,51 @@
1
+ // contacts — privacy requests on one person: what Vatio keeps about a contact,
2
+ // and forgetting them. The ID is the contact's number in the inbox.
3
+
4
+ import { writeFileSync } from "node:fs";
5
+ import { deployClient } from "./deploy.mjs";
6
+ import { ask, fail, paint, takeFlag, takeValue } from "../support.mjs";
7
+
8
+ const USAGE = "Usage: vatio contacts export ID [--out FILE]\n" +
9
+ " vatio contacts delete ID [--yes] [--json]";
10
+
11
+ export async function contacts(config, args) {
12
+ const sub = args.shift();
13
+ if (sub === "export") return await exportContact(config, args);
14
+ if (sub === "delete") return await deleteContact(config, args);
15
+ fail(USAGE);
16
+ }
17
+
18
+ async function exportContact(config, args) {
19
+ const out = takeValue(args, "--out");
20
+ const id = args.shift();
21
+ if (!id || args.length > 0) fail(USAGE);
22
+
23
+ const workspace = config.resolveWorkspaceRequired();
24
+ const data = await deployClient(config, workspace).exportContact({ id });
25
+ const text = `${JSON.stringify(data, null, 2)}\n`;
26
+ if (!out) return process.stdout.write(text);
27
+ writeFileSync(out, text);
28
+ console.log(`${paint("green", "✓")} Wrote everything Vatio keeps about contact #${id} to ${out}`);
29
+ }
30
+
31
+ async function deleteContact(config, args) {
32
+ const yes = takeFlag(args, "--yes");
33
+ const json = takeFlag(args, "--json");
34
+ const id = args.shift();
35
+ if (!id || args.length > 0) fail(USAGE);
36
+
37
+ const workspace = config.resolveWorkspaceRequired();
38
+ if (!yes) {
39
+ if (!process.stdin.isTTY) fail(`Deleting a contact cannot be undone, so without a terminal it needs --yes.\n\n${USAGE}`);
40
+ console.log(`This deletes contact #${id} on workspace ${workspace} for good: the contact, its channels,`);
41
+ console.log("memories and every conversation and message with them. Export first if you need a copy:");
42
+ console.log(` vatio contacts export ${id} --out contact-${id}.json`);
43
+ const typed = await ask(`${paint("green", "?")} Type ${id} to delete them: `);
44
+ if (typed !== String(id)) fail("Not deleted: what you typed is not the contact's ID.");
45
+ }
46
+
47
+ const answer = await deployClient(config, workspace).deleteContact({ id });
48
+ if (json) return console.log(JSON.stringify(answer, null, 2));
49
+ console.log(`${paint("green", "✓")} Deleted contact #${answer.contact_id ?? id}: ` +
50
+ `${answer.chats ?? 0} conversation${answer.chats === 1 ? "" : "s"}, ${answer.messages ?? 0} message${answer.messages === 1 ? "" : "s"}.`);
51
+ }
@@ -11,17 +11,14 @@ import { execFileSync } from "node:child_process";
11
11
  import { existsSync, writeFileSync, readFileSync, unlinkSync } from "node:fs";
12
12
  import { join } from "node:path";
13
13
  import { fail } from "../support.mjs";
14
- import { supabaseAuth } from "./supabase-auth.mjs";
15
14
 
16
15
  const PUBLIC_FILE = "identity.pub";
17
16
  const PRIVATE_FILE = "identity.pem";
18
17
 
19
18
  export async function auth(config, args) {
20
- if (args.includes("--supabase")) return supabaseAuth(config, args);
21
19
  if (!args.includes("--new-key")) {
22
20
  fail(
23
- "Usage: vatio auth --new-key (generates the keypair that signs your JWT)\n" +
24
- " vatio auth --supabase (your users sign in with Supabase: no keys, no code)"
21
+ "Usage: vatio auth --new-key (generates the keypair that signs your JWT)"
25
22
  );
26
23
  }
27
24
 
package/lib/help.mjs CHANGED
@@ -170,9 +170,6 @@ the two you are in. Commands default as listed.
170
170
  (replaces the list)
171
171
  keys revoke PREFIX
172
172
  auth --new-key Keypair that signs the JWT saying who a visitor is
173
- auth --supabase [URL] [--sign-in-url URL]
174
- Your users sign in with Supabase: verify their
175
- session, no keys or signing code
176
173
 
177
174
  Recover outbound WhatsApp messages (with your developer login):
178
175
  Vatio retries confirmed failures automatically. Inspect terminal failures:
@@ -193,11 +190,12 @@ the two you are in. Commands default as listed.
193
190
  webhooks list|create URL [--event NAME]...|test ID|deliveries ID|enable ID|rm ID
194
191
  Where Vatio tells your backend what happened
195
192
 
196
- Claude Code routines (WhatsApp):
197
- routines list|create NAME --url URL --phone NUMBER...|update ID|test ID|runs ID|enable ID|rm ID
198
- A routine on claude.ai the agent hands work to, as a
199
- tool (tools/NAME.yml with routine: NAME), in
200
- conversations with these numbers
193
+ Contacts (privacy requests on one person; the ID is the contact's number in the inbox):
194
+ contacts export ID [--out FILE]
195
+ Everything Vatio keeps about them, as JSON: the contact,
196
+ channels, memories and conversations
197
+ contacts delete ID [--yes] Delete them and everything about them, for good. Asks you
198
+ to type the ID; without a terminal, needs --yes
201
199
 
202
200
  Channels:
203
201
  whatsapp Set up in the inbox; prints the link (Try the agent
package/lib/suggest.mjs CHANGED
@@ -30,6 +30,7 @@ export const COMMANDS = [
30
30
  "changelog",
31
31
  "chat",
32
32
  "config",
33
+ "contacts",
33
34
  "diff",
34
35
  "docs",
35
36
  "doctor",
@@ -49,7 +50,6 @@ export const COMMANDS = [
49
50
  "push",
50
51
  "quiet-hours",
51
52
  "rollback",
52
- "routines",
53
53
  "secrets",
54
54
  "share-session",
55
55
  "status",
@@ -74,30 +74,29 @@ export const COMMANDS = [
74
74
  const SUBCOMMAND_OF = {
75
75
  add: ["flags", "test"],
76
76
  cat: ["kb"],
77
- create: ["kb", "keys", "templates", "webhooks", "routines"],
77
+ create: ["kb", "keys", "templates", "webhooks"],
78
+ delete: ["contacts"],
78
79
  deliveries: ["webhooks"],
79
- enable: ["webhooks", "routines"],
80
- export: ["chat"],
80
+ enable: ["webhooks"],
81
+ export: ["chat", "contacts"],
81
82
  failed: ["messages"],
82
83
  follow: ["kb"],
83
84
  get: ["config"],
84
85
  history: ["kb"],
85
86
  invite: ["team"],
86
- list: ["env", "kb", "secrets", "keys", "team", "templates", "webhooks", "routines", "test"],
87
+ list: ["env", "kb", "secrets", "keys", "team", "templates", "webhooks", "test"],
87
88
  off: ["quiet-hours"],
88
89
  origins: ["keys"],
89
90
  refresh: ["kb"],
90
- remove: ["secrets", "webhooks", "routines", "flags", "test"],
91
+ remove: ["secrets", "webhooks", "flags", "test"],
91
92
  revoke: ["keys"],
92
- rm: ["env", "kb", "secrets", "webhooks", "routines", "flags", "test"],
93
+ rm: ["env", "kb", "secrets", "webhooks", "flags", "test"],
93
94
  "rm-entry": ["kb"],
94
- runs: ["routines"],
95
95
  set: ["business", "quiet-hours", "secrets", "config"],
96
96
  show: ["chat", "kb", "business", "quiet-hours", "config"],
97
97
  "test-phones": ["whatsapp"],
98
98
  unfollow: ["kb"],
99
99
  unset: ["config"],
100
- update: ["routines"],
101
100
  write: ["kb"]
102
101
  };
103
102
 
package/lib/telemetry.mjs CHANGED
@@ -35,7 +35,7 @@ const SUBCOMMANDS = {
35
35
  keys: ["list", "create", "origins", "revoke"],
36
36
  templates: ["list", "create"],
37
37
  webhooks: ["list", "create", "test", "deliveries", "enable", "rm"],
38
- routines: ["list", "create", "update", "test", "runs", "enable", "rm"],
38
+ contacts: ["export", "delete"],
39
39
  whatsapp: ["only", "everyone"],
40
40
  config: ["show", "get", "set", "unset"],
41
41
  "share-session": ["--should-ask", "--never"]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vatio-ai/cli",
3
- "version": "0.101.0",
3
+ "version": "0.103.0",
4
4
  "description": "Vatio CLI — deploy and manage Vatio agent workspaces",
5
5
  "keywords": [
6
6
  "vatio",
@@ -1,165 +0,0 @@
1
- // `vatio routines` — Claude Code routines the agent can hand work to. A routine
2
- // is the trigger and token of one on claude.ai, and the WhatsApp numbers whose
3
- // conversations may use it; the agent gets it as a tool in the manifest
4
- // (tools/<key>.yml with `routine: <name>`). Calling it starts the routine with
5
- // where the conversation is, and Claude reads it with a server key
6
- // (GET /api/server/v1/:ws/chats/:id/messages).
7
-
8
- import { deployClient } from "./deploy.mjs";
9
- import { askSecret, fail, paint, sleep, takeEnv, takeFlag, takeValue } from "../support.mjs";
10
-
11
- const WAIT_INTERVAL_MS = 2_000;
12
-
13
- const CREATE_USAGE = "vatio routines create NAME --url URL --phone NUMBER [--phone NUMBER]... [--env NAME]";
14
- const UPDATE_USAGE = "vatio routines update ID [--name NAME] [--url URL] [--phone NUMBER]... [--new-token]";
15
- const USAGE = `Usage: vatio routines list|create NAME …|update ID …|test ID|runs ID|enable ID|rm ID\n` +
16
- ` ${CREATE_USAGE}\n ${UPDATE_USAGE}`;
17
-
18
- // Repeatable: `--phone +56911111111 --phone +56922222222`.
19
- function takeAll(args, name) {
20
- const values = [];
21
- for (let value = takeValue(args, name); value !== null; value = takeValue(args, name)) values.push(value);
22
- return values;
23
- }
24
-
25
- export async function routines(config, args) {
26
- const json = takeFlag(args, "--json");
27
- const workspace = config.resolveWorkspaceRequired();
28
- const client = deployClient(config, workspace);
29
- const sub = args.shift() ?? "list";
30
-
31
- if (sub === "list") {
32
- const { routines: list = [] } = await client.listRoutines();
33
- if (json) return console.log(JSON.stringify(list, null, 2));
34
- if (list.length === 0) {
35
- console.log(`No routines on workspace ${workspace}`);
36
- console.log(" Add one: vatio routines create encargos --url https://api.anthropic.com/v1/claude_code/routines/trig_…/fire " +
37
- "--phone +56912345678");
38
- return;
39
- }
40
- console.log(`Routines on workspace ${workspace} (${list.length}):`);
41
- for (const routine of list) printRoutine(routine);
42
- return;
43
- }
44
-
45
- if (sub === "create") {
46
- const environment = takeEnv(args, { fallback: "live" });
47
- const url = takeValue(args, "--url");
48
- const phoneNumbers = takeAll(args, "--phone");
49
- const name = args.shift();
50
- if (!name || !url || phoneNumbers.length === 0 || args.length > 0) fail(`Usage: ${CREATE_USAGE}`);
51
-
52
- // Asked for rather than typed on the command line, where it would stay in
53
- // shell history; piped in works too: `op read … | vatio routines create …`.
54
- const token = await askSecret(`${paint("green", "?")} Paste the routine's API token (sk-ant-oat01-…): `);
55
- if (token === "") fail("No token given. claude.ai shows it once, when you generate it on the routine's API trigger.");
56
-
57
- const body = { environment, name, url, token, phone_numbers: phoneNumbers };
58
- const routine = await client.createRoutine(body);
59
- if (json) return console.log(JSON.stringify(routine, null, 2));
60
- console.log(`${paint("green", "✓")} Created routine #${routine.id} (${routine.name}) on ${routine.environment}`);
61
- printRoutine(routine);
62
- console.log("");
63
- console.log("Give the routine a secret key so it can read the conversation: vatio keys create secret --env " +
64
- `${routine.environment} --label ${routine.name}`);
65
- console.log(`Check it starts: vatio routines test ${routine.id}`);
66
- console.log(`Then give it to the agent: tools/${routine.name}.yml with \`routine: ${routine.name}\`, ` +
67
- `${routine.name} in agent.tools, and vatio push`);
68
- return;
69
- }
70
-
71
- if (sub === "update") {
72
- const name = takeValue(args, "--name");
73
- const url = takeValue(args, "--url");
74
- const phoneNumbers = takeAll(args, "--phone");
75
- const newToken = takeFlag(args, "--new-token");
76
- const id = args.shift();
77
- if (!id || args.length > 0) fail(`Usage: ${UPDATE_USAGE}`);
78
-
79
- const body = {};
80
- if (name !== null) body.name = name;
81
- if (url !== null) body.url = url;
82
- if (phoneNumbers.length > 0) body.phone_numbers = phoneNumbers;
83
- if (newToken) {
84
- body.token = await askSecret(`${paint("green", "?")} Paste the new API token: `);
85
- if (body.token === "") fail("No token given");
86
- }
87
- if (Object.keys(body).length === 0) fail(`Nothing to change. ${UPDATE_USAGE}`);
88
-
89
- const routine = await client.updateRoutine({ id, ...body });
90
- if (json) return console.log(JSON.stringify(routine, null, 2));
91
- console.log(`${paint("green", "✓")} Updated routine #${routine.id}`);
92
- printRoutine(routine);
93
- return;
94
- }
95
-
96
- if (sub === "test") {
97
- const id = args.shift();
98
- if (!id) fail("Usage: vatio routines test ID");
99
- const run = await client.testRoutine({ id });
100
- console.log(`Fired a ping (run #${run.id}). It starts a real Claude session; the routine's prompt decides what a ping does.`);
101
- const deadline = Date.now() + 30_000;
102
- for (;;) {
103
- await sleep(WAIT_INTERVAL_MS);
104
- const { runs: list = [] } = await client.listRoutineRuns({ id });
105
- const current = list.find((entry) => entry.id === run.id);
106
- if (current && current.status !== "pending") {
107
- printRun(current);
108
- return;
109
- }
110
- if (Date.now() > deadline) {
111
- console.log(`No answer yet. Check later with: vatio routines runs ${id}`);
112
- return;
113
- }
114
- }
115
- }
116
-
117
- if (sub === "runs") {
118
- const id = args.shift();
119
- if (!id) fail("Usage: vatio routines runs ID");
120
- const { runs: list = [] } = await client.listRoutineRuns({ id });
121
- if (json) return console.log(JSON.stringify(list, null, 2));
122
- if (list.length === 0) {
123
- console.log("No runs yet.");
124
- return;
125
- }
126
- for (const run of list) printRun(run);
127
- return;
128
- }
129
-
130
- if (sub === "enable") {
131
- const id = args.shift();
132
- if (!id) fail("Usage: vatio routines enable ID");
133
- await client.updateRoutine({ id, enabled: true });
134
- console.log(`Enabled routine #${id}`);
135
- return;
136
- }
137
-
138
- if (sub === "rm" || sub === "remove" || sub === "delete") {
139
- const id = args.shift();
140
- if (!id) fail("Usage: vatio routines rm ID");
141
- await client.deleteRoutine({ id });
142
- console.log(`Removed routine #${id}`);
143
- return;
144
- }
145
-
146
- fail(USAGE);
147
- }
148
-
149
- function printRoutine(routine) {
150
- const state = routine.enabled ? paint("green", "enabled") : paint("red", "disabled");
151
- console.log(` #${routine.id} ${routine.name} ${routine.environment} ${state}`);
152
- console.log(` the agent can use it with: ${routine.phone_numbers.join(", ")}` +
153
- (routine.consecutive_failures > 0 ? ` failing: ${routine.consecutive_failures} in a row` : ""));
154
- }
155
-
156
- function printRun(run) {
157
- const status = run.status === "fired"
158
- ? paint("green", "fired")
159
- : run.status === "failed" ? paint("red", "failed") : paint("cyan", "pending");
160
- const http = run.response_status ? ` HTTP ${run.response_status}` : "";
161
- const chat = run.chat_id ? ` chat ${run.chat_id}` : "";
162
- console.log(` #${run.id} ${run.event} ${status}${http}${chat} attempts ${run.attempts} ${run.created_at}`);
163
- if (run.session_url) console.log(` ${run.session_url}`);
164
- if (run.last_error) console.log(` ${paint("red", run.last_error)}`);
165
- }
@@ -1,211 +0,0 @@
1
- // `vatio auth --supabase` — signed-in users for an app whose users already sign
2
- // in with Supabase Auth, with no keypair and no signing code.
3
- //
4
- // The project is found where the app already keeps it (a .env, or the client
5
- // Lovable generates), checked for the asymmetric signing keys Vatio verifies
6
- // with, and written into vatio.yml. Its URL and public anon key go into the
7
- // workspace secrets so a tool can call the project's REST API as the visitor,
8
- // with their own Row Level Security, in two headers.
9
-
10
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
11
- import { dirname, join, resolve } from "node:path";
12
- import { parseDocument } from "yaml";
13
- import { deployClient } from "./deploy.mjs";
14
- import { fail, paint, takeValue } from "../support.mjs";
15
-
16
- const PROJECT_URL = /^https:\/\/[a-z0-9]+\.supabase\.co$/;
17
- const URL_IN_SOURCE = /https:\/\/[a-z0-9]+\.supabase\.co/;
18
- const URL_VARIABLE = /^\s*(?:export\s+)?[A-Z_]*SUPABASE_URL\s*=\s*["']?(https:\/\/[a-z0-9]+\.supabase\.co)/m;
19
- // Anon or publishable only: a service-role or secret key would let whoever
20
- // holds it read past every policy, and it never belongs to a widget's tools.
21
- const KEY_VARIABLE = /^\s*(?:export\s+|const\s+)?[A-Z_]*SUPABASE_(?:ANON|PUBLISHABLE)[A-Z_]*KEY\s*[=:]\s*["']?([A-Za-z0-9._-]{20,})/m;
22
- const PLACES = [
23
- ".env",
24
- ".env.local",
25
- ".env.development",
26
- ".env.development.local",
27
- ".env.production",
28
- "src/integrations/supabase/client.ts",
29
- "src/integrations/supabase/client.js"
30
- ];
31
-
32
- export async function supabaseAuth(config, args) {
33
- const root = config.workspaceRootRequired();
34
- const workspace = config.resolveWorkspaceRequired();
35
- const signInUrl = takeValue(args, "--sign-in-url");
36
- const force = args.includes("--force");
37
- const skipSecrets = args.includes("--no-secrets");
38
- const index = args.indexOf("--supabase");
39
- const given = args[index + 1]?.startsWith("https://") ? args[index + 1] : null;
40
-
41
- if (signInUrl && !/^https:\/\/[^/\s?#]+/.test(signInUrl)) fail("--sign-in-url must be an https url on your own site");
42
-
43
- const found = given ? {} : detect([process.cwd(), root]);
44
- const url = normalize(given ?? found.url);
45
- if (!url) {
46
- fail(
47
- "Could not find your Supabase project URL in a .env or src/integrations/supabase/client.ts.\n" +
48
- "Pass it: vatio auth --supabase https://<project-ref>.supabase.co"
49
- );
50
- }
51
- if (!PROJECT_URL.test(url)) {
52
- fail(`${url} is not a Supabase project URL (https://<project-ref>.supabase.co). Custom domains are not supported yet.`);
53
- }
54
-
55
- await checkSigningKeys(url);
56
- writeManifest(config.manifestPath(), url, signInUrl, force);
57
-
58
- console.log(`${paint("green", "✓")} vatio.yml now verifies visitors with ${url}`);
59
- if (found.from && !given) console.log(` (found in ${found.from})`);
60
-
61
- if (!skipSecrets) await storeSecrets(config, workspace, url, found.key);
62
-
63
- console.log("");
64
- console.log("What happens after `vatio push` and `vatio publish`:");
65
- console.log(" • Web: the widget reads the Supabase session already on your page. Nothing to add —");
66
- console.log(" signed in, the visitor is known; signed out, they are anonymous.");
67
- if (signInUrl || existingSignInUrl(config.manifestPath())) {
68
- console.log(" • WhatsApp and Instagram: the Sign in button opens your sign_in_url. Keep the widget");
69
- console.log(" script on that page: it waits for the person to sign in and hands the session over.");
70
- } else {
71
- console.log(" • WhatsApp and Instagram: add your login page, with the widget script on it —");
72
- console.log(" vatio auth --supabase --sign-in-url https://your-app.com/login");
73
- }
74
- console.log("");
75
- console.log("A private tool reads the visitor's own rows, under your Row Level Security:");
76
- console.log("");
77
- console.log(" # tools/my_orders.yml");
78
- console.log(" access: private");
79
- console.log(" request:");
80
- console.log(" method: GET");
81
- console.log(" base_url: $env.SUPABASE_URL");
82
- console.log(" path: /rest/v1/orders");
83
- console.log(" query: { select: \"*\" }");
84
- console.log(" headers:");
85
- console.log(" apikey: $env.SUPABASE_ANON_KEY");
86
- console.log(" Authorization: Bearer $auth.token");
87
- console.log(" respond:");
88
- console.log(" data: { orders: \"$\" }");
89
- console.log(" message: { when_empty: No orders yet., default: \"Found {{count}} orders.\" }");
90
- console.log("");
91
- console.log("Docs: https://vatio.ai/docs/integrations/supabase");
92
- }
93
-
94
- // Where the app already says which project it uses: the nearest directory, from
95
- // here and from the workspace root upwards, that names one.
96
- function detect(starts) {
97
- const seen = new Set();
98
- for (const start of starts) {
99
- let dir = resolve(start);
100
- for (let depth = 0; depth < 4; depth += 1) {
101
- if (!seen.has(dir)) {
102
- seen.add(dir);
103
- const found = detectIn(dir);
104
- if (found.url) return found;
105
- }
106
- const parent = dirname(dir);
107
- if (parent === dir) break;
108
- dir = parent;
109
- }
110
- }
111
- return {};
112
- }
113
-
114
- function detectIn(dir) {
115
- let url = null;
116
- let key = null;
117
- let from = null;
118
- for (const place of PLACES) {
119
- const path = join(dir, place);
120
- if (!existsSync(path)) continue;
121
- const text = readFileSync(path, "utf8");
122
- const foundUrl = text.match(URL_VARIABLE)?.[1] ?? (place.startsWith("src/") ? text.match(URL_IN_SOURCE)?.[0] : null);
123
- if (!url && foundUrl) {
124
- url = foundUrl;
125
- from = path;
126
- }
127
- const foundKey = text.match(KEY_VARIABLE)?.[1];
128
- if (!key && foundKey && publicKey(foundKey)) key = foundKey;
129
- }
130
- return { url, key, from };
131
- }
132
-
133
- // The anon JWT (role "anon") or a publishable key; never a secret or
134
- // service-role one, whatever the variable was called.
135
- function publicKey(value) {
136
- if (value.startsWith("sb_publishable_")) return true;
137
- if (value.startsWith("sb_secret_")) return false;
138
- try {
139
- const payload = JSON.parse(Buffer.from(value.split(".")[1], "base64url").toString("utf8"));
140
- return payload.role === "anon";
141
- } catch {
142
- return false;
143
- }
144
- }
145
-
146
- function normalize(value) {
147
- return value ? value.trim().toLowerCase().replace(/\/+$/, "") : null;
148
- }
149
-
150
- async function checkSigningKeys(url) {
151
- let keys;
152
- try {
153
- const response = await fetch(`${url}/auth/v1/.well-known/jwks.json`, { signal: AbortSignal.timeout(8000) });
154
- if (!response.ok) throw new Error(`HTTP ${response.status}`);
155
- keys = (await response.json()).keys ?? [];
156
- } catch (error) {
157
- console.warn(`${paint("yellow", "!")} Could not reach ${url} to check its signing keys (${error.message}); the deploy checks again.`);
158
- return;
159
- }
160
- if (keys.length > 0) return;
161
-
162
- fail(
163
- `${url} still signs with the legacy JWT secret (HS256), which Vatio cannot verify without being able\n` +
164
- "to mint tokens too. In the Supabase dashboard: Project Settings → JWT Keys → migrate, then rotate\n" +
165
- "to an ES256 key, then run this again. Before rotating, check for code that verifies tokens with the\n" +
166
- "legacy secret and for Edge Functions with Verify JWT on: https://vatio.ai/docs/integrations/supabase"
167
- );
168
- }
169
-
170
- function writeManifest(path, url, signInUrl, force) {
171
- const doc = parseDocument(readFileSync(path, "utf8"));
172
- if (doc.hasIn(["auth", "public_key"]) && !force) {
173
- fail(
174
- "vatio.yml already verifies a JWT your backend signs (auth.public_key). Switching to Supabase signs out\n" +
175
- "every visitor holding one of those — re-run with --force if that is what you want."
176
- );
177
- }
178
- for (const key of [ "public_key", "algorithm" ]) {
179
- if (doc.hasIn(["auth", key])) doc.deleteIn(["auth", key]);
180
- }
181
- doc.setIn(["auth", "supabase"], url);
182
- if (signInUrl) doc.setIn(["auth", "sign_in_url"], signInUrl);
183
- writeFileSync(path, String(doc));
184
- }
185
-
186
- function existingSignInUrl(path) {
187
- return parseDocument(readFileSync(path, "utf8")).hasIn(["auth", "sign_in_url"]);
188
- }
189
-
190
- async function storeSecrets(config, workspace, url, key) {
191
- const commands = [ `vatio secrets set SUPABASE_URL ${url}` ];
192
- if (key) commands.push(`vatio secrets set SUPABASE_ANON_KEY ${key}`);
193
- else commands.push("vatio secrets set SUPABASE_ANON_KEY <your anon or publishable key>");
194
-
195
- if (!config.resolveBaseUrl() || !config.resolveToken()) {
196
- console.log("Not logged in, so the secrets your tools use are not set yet. After `vatio login`:");
197
- for (const command of commands) console.log(` ${command}`);
198
- return;
199
- }
200
-
201
- try {
202
- const client = deployClient(config, workspace);
203
- await client.upsertSecret({ key: "SUPABASE_URL", value: url, environment: null });
204
- if (key) await client.upsertSecret({ key: "SUPABASE_ANON_KEY", value: key, environment: null });
205
- console.log(`${paint("green", "✓")} Set secret SUPABASE_URL${key ? " and SUPABASE_ANON_KEY" : ""} on workspace ${workspace}`);
206
- if (!key) console.log(` Add the anon key yourself: ${commands[1]}`);
207
- } catch (error) {
208
- console.warn(`${paint("yellow", "!")} Could not set the secrets (${error.message}). Run:`);
209
- for (const command of commands) console.warn(` ${command}`);
210
- }
211
- }