sodabase 0.1.11 → 0.1.13
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 +13 -1
- package/dist/api/client.js +34 -7
- package/dist/api/fakeClient.js +1 -1
- package/dist/api/gotrueAuth.js +25 -0
- package/dist/app.js +7 -3
- package/dist/args.js +8 -0
- package/dist/cli.js +90 -19
- package/dist/config/tokenStore.js +102 -8
- package/dist/functionsLint.js +12 -0
- package/dist/login.js +44 -0
- package/dist/rulesPull.js +1 -1
- package/dist/ui.js +7 -4
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -38,6 +38,16 @@ install fails; a skill failure warns with a manual fallback.
|
|
|
38
38
|
|
|
39
39
|
Point at a local backend with `SODABASE_API_URL=http://localhost:8080`.
|
|
40
40
|
|
|
41
|
+
## Sign in only
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
npx sodabase login # sign in (browser or email code), save the session, exit — no setup wizard
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Interactive, so it refuses to run without a terminal (a coding agent's shell) and says to
|
|
48
|
+
run it in a separate window. The access token lasts about an hour; every command renews it
|
|
49
|
+
from the saved refresh token, so a session only ends on `--logout` or if it's revoked.
|
|
50
|
+
|
|
41
51
|
## Pipeline checks (Edge Functions)
|
|
42
52
|
|
|
43
53
|
```bash
|
|
@@ -53,6 +63,8 @@ src/
|
|
|
53
63
|
installMcp.ts `install-mcp`: arg parsing, agent detection, plain-output install
|
|
54
64
|
rulesPull.ts `rules pull`: the rules file + a line-based config.toml static_files edit
|
|
55
65
|
functionsLint.ts `functions lint`: unchecked-write heuristic over supabase/functions/**
|
|
66
|
+
login.ts `login`: help + the no-terminal / not-signed-in messages
|
|
67
|
+
args.ts shared --help-only arg parsing
|
|
56
68
|
agentPicker.tsx `install-mcp`'s inline agent checkbox list
|
|
57
69
|
app.tsx the Ink app (flow orchestrator + screens)
|
|
58
70
|
api/
|
|
@@ -60,7 +72,7 @@ src/
|
|
|
60
72
|
job poll, connections, relevance, scan report)
|
|
61
73
|
types.ts wire types
|
|
62
74
|
config/
|
|
63
|
-
tokenStore.ts 0600 credential file
|
|
75
|
+
tokenStore.ts 0600 credential file + refresh of an expired session
|
|
64
76
|
```
|
|
65
77
|
|
|
66
78
|
## What backs each step (all real endpoints)
|
package/dist/api/client.js
CHANGED
|
@@ -10,7 +10,7 @@ import { ApiError, } from "./types.js";
|
|
|
10
10
|
/** The MCP endpoint on the same origin the client talks to, so a dev install (SODABASE_API_URL) points at the dev MCP. */
|
|
11
11
|
export const MCP_URL = `${(process.env.SODABASE_API_URL ?? "https://sodabase.io").replace(/\/$/, "")}/mcp`;
|
|
12
12
|
/** The trust-advisor skill repo, resolved by the `skills` CLI (owner/repo on its default branch). */
|
|
13
|
-
export const SKILL_REF = "
|
|
13
|
+
export const SKILL_REF = "labs-soda/agent-skills";
|
|
14
14
|
/** An error thrown when `connect()`'s poll is aborted (the user left the connect screen). */
|
|
15
15
|
const abortedError = () => new ApiError("connect aborted", 499, "aborted");
|
|
16
16
|
/** Pull the `email` claim out of a GoTrue JWT without verifying it (display only — the server already
|
|
@@ -60,6 +60,8 @@ export class SodabaseClient {
|
|
|
60
60
|
site;
|
|
61
61
|
api;
|
|
62
62
|
bearer;
|
|
63
|
+
refresher;
|
|
64
|
+
refreshing;
|
|
63
65
|
constructor(opts = {}) {
|
|
64
66
|
this.site = (opts.baseUrl ?? process.env.SODABASE_API_URL ?? "https://sodabase.io").replace(/\/$/, "");
|
|
65
67
|
this.api = `${this.site}/api/v1`;
|
|
@@ -68,6 +70,10 @@ export class SodabaseClient {
|
|
|
68
70
|
setBearer(token) {
|
|
69
71
|
this.bearer = token;
|
|
70
72
|
}
|
|
73
|
+
/** On a 401, call `refresh` once for a new access token and retry the request with it (undefined = give up). */
|
|
74
|
+
setRefresher(refresh) {
|
|
75
|
+
this.refresher = refresh;
|
|
76
|
+
}
|
|
71
77
|
// ── Leg 1: GoTrue sign-in (loopback PKCE → aud="authenticated" session) ──────
|
|
72
78
|
async signIn(provider, onUrl) {
|
|
73
79
|
// Matches the web app's @supabase/ssr PKCE flow, driven from a loopback redirect.
|
|
@@ -326,15 +332,36 @@ export class SodabaseClient {
|
|
|
326
332
|
return this.bearer ? { authorization: `Bearer ${this.bearer}` } : {};
|
|
327
333
|
}
|
|
328
334
|
async get(path) {
|
|
329
|
-
return this.parse(await
|
|
335
|
+
return this.parse(await this.send(path, () => ({ headers: this.authHeaders() })));
|
|
330
336
|
}
|
|
331
337
|
async post(path, json) {
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
338
|
+
return this.parse(await this.send(path, () => {
|
|
339
|
+
const init = { method: "POST", headers: { ...this.authHeaders() } };
|
|
340
|
+
if (json !== undefined) {
|
|
341
|
+
init.headers["content-type"] = "application/json";
|
|
342
|
+
init.body = JSON.stringify(json);
|
|
343
|
+
}
|
|
344
|
+
return init;
|
|
345
|
+
}));
|
|
346
|
+
}
|
|
347
|
+
/** fetch, and on a 401 with a refresher set: refresh the session once and retry with the new bearer.
|
|
348
|
+
* Concurrent 401s share one refresh (the refresh token rotates, so each one may be used only once). */
|
|
349
|
+
async send(path, init) {
|
|
350
|
+
const sent = this.bearer;
|
|
351
|
+
const res = await fetch(`${this.api}${path}`, init());
|
|
352
|
+
if (res.status !== 401 || !this.refresher || !sent)
|
|
353
|
+
return res;
|
|
354
|
+
if (this.bearer === sent) {
|
|
355
|
+
this.refreshing ??= this.refresher().finally(() => (this.refreshing = undefined));
|
|
356
|
+
let token;
|
|
357
|
+
// a refresh that couldn't run (offline, or the session couldn't be saved) throws its own error: surface that,
|
|
358
|
+
// not the 401, which would read as "not signed in"
|
|
359
|
+
token = await this.refreshing;
|
|
360
|
+
if (!token || token === sent)
|
|
361
|
+
return res;
|
|
362
|
+
this.bearer = token;
|
|
336
363
|
}
|
|
337
|
-
return
|
|
364
|
+
return fetch(`${this.api}${path}`, init()); // with the bearer another request's refresh may already have set
|
|
338
365
|
}
|
|
339
366
|
async parse(res) {
|
|
340
367
|
const text = await res.text();
|
package/dist/api/fakeClient.js
CHANGED
|
@@ -162,6 +162,6 @@ export class FakeClient {
|
|
|
162
162
|
}
|
|
163
163
|
async installSkill(agents) {
|
|
164
164
|
await this.tick(500);
|
|
165
|
-
return { command: `npx skills add
|
|
165
|
+
return { command: `npx skills add labs-soda/agent-skills -g ${agents.map((a) => "-a " + a).join(" ")}` };
|
|
166
166
|
}
|
|
167
167
|
}
|
package/dist/api/gotrueAuth.js
CHANGED
|
@@ -146,6 +146,31 @@ export async function loopbackSignIn(cfg = resolveGoTrueConfig(), opts = {}) {
|
|
|
146
146
|
}
|
|
147
147
|
return sessionFromTokenBody(body);
|
|
148
148
|
}
|
|
149
|
+
// ── Session refresh ───────────────────────────────────────────────────────────────
|
|
150
|
+
// A GoTrue access token lives about an hour; the refresh token it came with trades for a new pair (and is
|
|
151
|
+
// rotated: the old one stops working, so the caller must save the new one).
|
|
152
|
+
/** Trade a refresh token for a fresh session. A rejected token is an ApiError with GoTrue's status (400/401);
|
|
153
|
+
* an unreachable GoTrue is a 503 "network" ApiError, so callers can tell "signed out" from "offline". */
|
|
154
|
+
export async function refreshSession(cfg, refreshToken) {
|
|
155
|
+
requireAnonKey(cfg);
|
|
156
|
+
let res;
|
|
157
|
+
try {
|
|
158
|
+
res = await fetch(`${cfg.supabaseUrl}/auth/v1/token?grant_type=refresh_token`, {
|
|
159
|
+
method: "POST",
|
|
160
|
+
headers: anonHeaders(cfg.anonKey),
|
|
161
|
+
body: JSON.stringify({ refresh_token: refreshToken }),
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
catch (e) {
|
|
165
|
+
const why = e instanceof Error ? e.message : String(e);
|
|
166
|
+
throw new ApiError(`could not reach the sign-in service to refresh your session (${why})`, 503, "network");
|
|
167
|
+
}
|
|
168
|
+
const body = (await res.json().catch(() => ({})));
|
|
169
|
+
if (!res.ok || typeof body.access_token !== "string") {
|
|
170
|
+
throw new ApiError(String(body.error_description ?? body.msg ?? "session refresh failed"), res.ok ? 401 : res.status, String(body.error ?? ""));
|
|
171
|
+
}
|
|
172
|
+
return sessionFromTokenBody(body);
|
|
173
|
+
}
|
|
149
174
|
// ── Email one-time-code sign-in (browserless; no loopback, no PKCE) ───────────────
|
|
150
175
|
// GoTrue's email OTP grant: POST /otp emails a code, POST /verify trades the typed code
|
|
151
176
|
// for a session. Two plain fetches, same anon-key headers — nothing to spin up locally.
|
package/dist/app.js
CHANGED
|
@@ -70,7 +70,7 @@ function backTarget(name) {
|
|
|
70
70
|
return null; // signin / home → quit
|
|
71
71
|
}
|
|
72
72
|
}
|
|
73
|
-
export function App({ services, fast, interactive, signedIn, demo, fullscreen }) {
|
|
73
|
+
export function App({ services, fast, interactive, signedIn, demo, fullscreen, loginOnly, onSignedIn }) {
|
|
74
74
|
const [screen, setScreen] = useState("signin");
|
|
75
75
|
const [ctx, setCtx] = useState({});
|
|
76
76
|
// onDone reads the current screen + ctx to compute the default next screen; refs keep those reads
|
|
@@ -106,11 +106,15 @@ export function App({ services, fast, interactive, signedIn, demo, fullscreen })
|
|
|
106
106
|
// Compute from refs, then fire the two state updates as siblings. (Calling setScreen from
|
|
107
107
|
// inside the setCtx updater makes that updater impure, which React may re-run — here it
|
|
108
108
|
// wedged the event loop so sub-screen timers never fired.)
|
|
109
|
+
if (loginOnly && screenRef.current === "signin") {
|
|
110
|
+
exit(); // cli.tsx waits for this, then says so and exits
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
109
113
|
const next = { ...ctxRef.current, ...patch };
|
|
110
114
|
const target = opts?.to ?? nextScreen(screenRef.current, next, interactive);
|
|
111
115
|
setCtx(next);
|
|
112
116
|
setScreen(target ?? "home");
|
|
113
|
-
}, [interactive]);
|
|
117
|
+
}, [interactive, loginOnly, exit]);
|
|
114
118
|
const Current = SCREENS[screen];
|
|
115
119
|
// Full-height frame only when cli.tsx put us in fullscreen (interactive TTY); otherwise inline (size null).
|
|
116
120
|
const termSize = useTerminalSize();
|
|
@@ -126,5 +130,5 @@ export function App({ services, fast, interactive, signedIn, demo, fullscreen })
|
|
|
126
130
|
// mounted, its input handlers also stay registered — so `tooSmall` is passed down and useGatedInput freezes
|
|
127
131
|
// every screen's useInput while hidden (otherwise a blind keypress could toggle a table or commit scope). The
|
|
128
132
|
// global escape handler above stays live, so the user can still quit from the resize prompt.
|
|
129
|
-
return (_jsxs(WizardProvider, { value: { services, fast, interactive, signedIn, demo, tooSmall }, children: [tooSmall && size && _jsx(TooSmall, { size: size }), _jsx(Box, { display: tooSmall ? "none" : "flex", flexDirection: "column", children: _jsx(Chrome, { size: size, children: Current ? _jsx(Current, { ctx: ctx, onDone: onDone }) : null }) })] }));
|
|
133
|
+
return (_jsxs(WizardProvider, { value: { services, fast, interactive, signedIn, demo, tooSmall, onSignedIn }, children: [tooSmall && size && _jsx(TooSmall, { size: size }), _jsx(Box, { display: tooSmall ? "none" : "flex", flexDirection: "column", children: _jsx(Chrome, { size: size, children: Current ? _jsx(Current, { ctx: ctx, onDone: onDone }) : null }) })] }));
|
|
130
134
|
}
|
package/dist/args.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// Shared argument parsing for the subcommands that take no options of their own.
|
|
2
|
+
/** Parse a subcommand's args when the only option it takes is --help/-h. */
|
|
3
|
+
export function parseHelpOnly(argv) {
|
|
4
|
+
if (argv.some((a) => a === "--help" || a === "-h"))
|
|
5
|
+
return { help: true };
|
|
6
|
+
const bad = argv[0];
|
|
7
|
+
return bad === undefined ? { help: false } : { error: `unknown option: ${bad}` };
|
|
8
|
+
}
|
package/dist/cli.js
CHANGED
|
@@ -3,19 +3,23 @@ import { jsx as _jsx } from "react/jsx-runtime";
|
|
|
3
3
|
import { render } from "ink";
|
|
4
4
|
import { rmSync } from "node:fs";
|
|
5
5
|
import { createRequire } from "node:module";
|
|
6
|
-
import { homedir } from "node:os";
|
|
7
6
|
import { join } from "node:path";
|
|
8
7
|
import { SodabaseClient } from "./api/client.js";
|
|
9
8
|
import { FakeClient } from "./api/fakeClient.js";
|
|
10
9
|
import { pickAgents } from "./agentPicker.js";
|
|
11
10
|
import { App } from "./app.js";
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
11
|
+
import { refreshSession, resolveGoTrueConfig } from "./api/gotrueAuth.js";
|
|
12
|
+
import { parseHelpOnly } from "./args.js";
|
|
13
|
+
import { clearCreds, configDir, freshCreds } from "./config/tokenStore.js";
|
|
14
|
+
import { FUNCTIONS_LINT_HELP, runLint } from "./functionsLint.js";
|
|
14
15
|
import { INSTALL_MCP_HELP, detectAgents, installedAgents, parseInstallMcpArgs, resolveAgents, runInstallMcp, } from "./installMcp.js";
|
|
16
|
+
import { LOGIN_HELP, LOGIN_NEEDS_TERMINAL, NOT_SIGNED_IN, loginOutcome } from "./login.js";
|
|
15
17
|
import { RULES_PULL_HELP, parseRulesPullArgs, runRulesPull } from "./rulesPull.js";
|
|
16
18
|
import { ApiError } from "./api/types.js";
|
|
17
19
|
const argv = process.argv.slice(2);
|
|
18
20
|
const args = new Set(argv);
|
|
21
|
+
/** The saved session's refresh token → a new GoTrue session (the access token only lives about an hour). */
|
|
22
|
+
const refresh = (token) => refreshSession(resolveGoTrueConfig(), token);
|
|
19
23
|
/** process.exit() drops output still queued on a pipe (async on macOS, e.g. `| tee log`): await this first. */
|
|
20
24
|
async function drained() {
|
|
21
25
|
await Promise.all([process.stdout, process.stderr].map((s) => new Promise((done) => s.write("", done))));
|
|
@@ -61,6 +65,17 @@ if (argv[0] === "install-mcp") {
|
|
|
61
65
|
}
|
|
62
66
|
// `functions lint`: static and offline — flags writes in supabase/functions/** with no check() line before them.
|
|
63
67
|
if (argv[0] === "functions" && argv[1] === "lint") {
|
|
68
|
+
const opts = parseHelpOnly(argv.slice(2));
|
|
69
|
+
if ("error" in opts) {
|
|
70
|
+
process.stderr.write(`sodabase functions lint: ${opts.error}\n\n${FUNCTIONS_LINT_HELP}`);
|
|
71
|
+
await drained();
|
|
72
|
+
process.exit(2);
|
|
73
|
+
}
|
|
74
|
+
if (opts.help) {
|
|
75
|
+
process.stdout.write(FUNCTIONS_LINT_HELP);
|
|
76
|
+
await drained();
|
|
77
|
+
process.exit(0);
|
|
78
|
+
}
|
|
64
79
|
const code = runLint(process.cwd(), (line) => process.stdout.write(`${line}\n`));
|
|
65
80
|
await drained();
|
|
66
81
|
process.exit(code);
|
|
@@ -81,13 +96,15 @@ if (argv[0] === "rules" && argv[1] === "pull") {
|
|
|
81
96
|
await drained();
|
|
82
97
|
process.exit(0);
|
|
83
98
|
}
|
|
84
|
-
const creds = loadCreds();
|
|
85
|
-
const login = "not signed in (or the session expired) — run `npx sodabase --login` first";
|
|
86
|
-
if (!isSignedIn(creds))
|
|
87
|
-
await fail(login);
|
|
88
99
|
const client = new SodabaseClient();
|
|
89
|
-
client.setBearer(creds.accessToken);
|
|
90
100
|
try {
|
|
101
|
+
// An expired access token is renewed from the saved refresh token (and re-saved) before the call, and again
|
|
102
|
+
// if the server still says 401; only a missing or revoked session ends up at NOT_SIGNED_IN.
|
|
103
|
+
const creds = await freshCreds(refresh);
|
|
104
|
+
if (!creds)
|
|
105
|
+
await fail(NOT_SIGNED_IN);
|
|
106
|
+
client.setBearer(creds.accessToken);
|
|
107
|
+
client.setRefresher(async () => (await freshCreds(refresh, { force: true }))?.accessToken);
|
|
91
108
|
const code = await runRulesPull(project, (r) => client.rulesFile(r), process.cwd(), (line) => process.stdout.write(`${line}\n`));
|
|
92
109
|
await drained();
|
|
93
110
|
process.exit(code);
|
|
@@ -96,7 +113,7 @@ if (argv[0] === "rules" && argv[1] === "pull") {
|
|
|
96
113
|
if (!(err instanceof ApiError))
|
|
97
114
|
throw err;
|
|
98
115
|
if (err.status === 401)
|
|
99
|
-
await fail(
|
|
116
|
+
await fail(NOT_SIGNED_IN);
|
|
100
117
|
if (err.status === 403)
|
|
101
118
|
await fail("only a workspace owner or admin can pull the rules file");
|
|
102
119
|
if (err.status === 404)
|
|
@@ -104,16 +121,68 @@ if (argv[0] === "rules" && argv[1] === "pull") {
|
|
|
104
121
|
await fail(err.message);
|
|
105
122
|
}
|
|
106
123
|
}
|
|
107
|
-
|
|
124
|
+
// A command group without (or with an unknown) subcommand: say what exists rather than launching the wizard.
|
|
125
|
+
const GROUPS = {
|
|
126
|
+
rules: { usage: "npx sodabase rules pull --project <ref>" },
|
|
127
|
+
functions: { usage: "npx sodabase functions lint" },
|
|
128
|
+
};
|
|
129
|
+
const group = GROUPS[argv[0] ?? ""];
|
|
130
|
+
if (group) {
|
|
131
|
+
const sub = argv[1];
|
|
132
|
+
const help = sub === undefined || sub === "--help" || sub === "-h";
|
|
133
|
+
const out = help ? process.stdout : process.stderr;
|
|
134
|
+
out.write(`${help ? "" : `sodabase ${argv[0]}: unknown command: ${sub}\n\n`}Usage: ${group.usage}\n\nAdd --help for details.\n`);
|
|
135
|
+
await drained();
|
|
136
|
+
process.exit(help && sub !== undefined ? 0 : 2);
|
|
137
|
+
}
|
|
138
|
+
// `login`: sign in, save the session, exit. Interactive by nature, so refuse up front when there's no terminal.
|
|
139
|
+
if (argv[0] === "login") {
|
|
140
|
+
const opts = parseHelpOnly(argv.slice(1));
|
|
141
|
+
if ("error" in opts) {
|
|
142
|
+
process.stderr.write(`sodabase login: ${opts.error}\n\n${LOGIN_HELP}`);
|
|
143
|
+
await drained();
|
|
144
|
+
process.exit(2);
|
|
145
|
+
}
|
|
146
|
+
if (opts.help) {
|
|
147
|
+
process.stdout.write(LOGIN_HELP);
|
|
148
|
+
await drained();
|
|
149
|
+
process.exit(0);
|
|
150
|
+
}
|
|
151
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
|
152
|
+
process.stderr.write(LOGIN_NEEDS_TERMINAL);
|
|
153
|
+
await drained();
|
|
154
|
+
process.exit(1);
|
|
155
|
+
}
|
|
156
|
+
// The saved session is left alone until the new one replaces it, so backing out keeps you signed in. Success is
|
|
157
|
+
// what THIS run's sign-in screen reports (not whatever is on disk): Ctrl+C ends Ink without it → 130.
|
|
158
|
+
let saved;
|
|
159
|
+
const app = render(_jsx(App, { services: new SodabaseClient(), fast: false, interactive: true, signedIn: false, demo: false, fullscreen: false, loginOnly: true, onSignedIn: (ok) => (saved = ok) }));
|
|
160
|
+
await app.waitUntilExit();
|
|
161
|
+
const outcome = loginOutcome(saved);
|
|
162
|
+
if (outcome.stdout)
|
|
163
|
+
process.stdout.write(outcome.stdout);
|
|
164
|
+
if (outcome.stderr)
|
|
165
|
+
process.stderr.write(outcome.stderr);
|
|
166
|
+
await drained();
|
|
167
|
+
process.exit(outcome.code);
|
|
168
|
+
}
|
|
169
|
+
if (argv[0] !== undefined && argv[0] !== "help" && !argv[0].startsWith("-")) {
|
|
170
|
+
process.stderr.write(`sodabase: unknown command: ${argv[0]}\n\nRun \`npx sodabase --help\` to see the commands.\n`);
|
|
171
|
+
await drained();
|
|
172
|
+
process.exit(2);
|
|
173
|
+
}
|
|
174
|
+
if (argv[0] === "help" || args.has("--help") || args.has("-h")) {
|
|
108
175
|
process.stdout.write([
|
|
109
176
|
"sodabase — data-quality onboarding wizard",
|
|
110
177
|
"",
|
|
111
178
|
"Usage: npx sodabase [options]",
|
|
179
|
+
" npx sodabase login",
|
|
112
180
|
" npx sodabase install-mcp [-a, --agent <id>] [--all] [--no-skill] [--no-input]",
|
|
113
181
|
" npx sodabase rules pull --project <ref>",
|
|
114
182
|
" npx sodabase functions lint",
|
|
115
183
|
"",
|
|
116
184
|
"Commands:",
|
|
185
|
+
" login sign in, save the session, and exit (no setup wizard)",
|
|
117
186
|
" install-mcp install the MCP + trust-advisor skill for your coding agent, then exit",
|
|
118
187
|
" rules pull save the project's pipeline rules file and list it in each function's static_files",
|
|
119
188
|
" functions lint flag writes in supabase/functions without a check() line before them",
|
|
@@ -121,7 +190,7 @@ if (args.has("--help") || args.has("-h")) {
|
|
|
121
190
|
"Options:",
|
|
122
191
|
" --demo run the whole flow offline against a fake backend",
|
|
123
192
|
" --fast shorter delays (implied by --demo)",
|
|
124
|
-
" --login sign in again (clears the saved session first)",
|
|
193
|
+
" --login sign in again (clears the saved session first), then run the setup",
|
|
125
194
|
" --logout clear the saved session and exit",
|
|
126
195
|
" --help, -h show this help",
|
|
127
196
|
" --version print the version",
|
|
@@ -148,8 +217,7 @@ if (args.has("--logout")) {
|
|
|
148
217
|
// (tokens live in credentials.json, cleared above), but a clean sign-out shouldn't leave a file
|
|
149
218
|
// naming your last project on disk. Nothing writes it anymore, so this only ever cleans up.
|
|
150
219
|
try {
|
|
151
|
-
|
|
152
|
-
rmSync(join(base, "sodabase", "progress.json"));
|
|
220
|
+
rmSync(join(configDir(), "progress.json"));
|
|
153
221
|
}
|
|
154
222
|
catch {
|
|
155
223
|
/* already gone */
|
|
@@ -170,15 +238,18 @@ const interactive = !!process.stdin.isTTY && !args.has("--no-input");
|
|
|
170
238
|
let signedIn = false;
|
|
171
239
|
const services = demo
|
|
172
240
|
? new FakeClient({ fast })
|
|
173
|
-
: (() => {
|
|
241
|
+
: await (async () => {
|
|
174
242
|
const c = new SodabaseClient();
|
|
175
|
-
|
|
176
|
-
//
|
|
177
|
-
//
|
|
178
|
-
|
|
243
|
+
// An expired saved session is renewed from its refresh token; freshCreds only returns a real GoTrue JWT
|
|
244
|
+
// (never a leftover --demo token, which would skip sign-in and then 401 on /api/v1). Offline at boot →
|
|
245
|
+
// just show the sign-in screen rather than crash.
|
|
246
|
+
const creds = await freshCreds(refresh).catch(() => null);
|
|
247
|
+
if (creds) {
|
|
179
248
|
c.setBearer(creds.accessToken);
|
|
180
|
-
signedIn =
|
|
249
|
+
signedIn = true;
|
|
181
250
|
}
|
|
251
|
+
// Mid-run, a 401 renews the session the sign-in screen (or a previous run) saved, then retries once.
|
|
252
|
+
c.setRefresher(async () => (await freshCreds(refresh, { force: true }))?.accessToken);
|
|
182
253
|
return c;
|
|
183
254
|
})();
|
|
184
255
|
// Fullscreen: take over the terminal (alternate screen) and theme it dark by setting the terminal's OWN
|
|
@@ -2,16 +2,37 @@
|
|
|
2
2
|
// dep-free (no native keychain module). Documented tradeoff: less hardened than an OS
|
|
3
3
|
// keychain, but no node-gyp/platform build and no new dependency. Can move to a keychain
|
|
4
4
|
// later if warranted.
|
|
5
|
-
import { chmodSync, mkdirSync, readFileSync, rmSync,
|
|
5
|
+
import { chmodSync, closeSync, fsyncSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, writeSync } from "node:fs";
|
|
6
6
|
import { homedir } from "node:os";
|
|
7
7
|
import { dirname, join } from "node:path";
|
|
8
|
+
import { ApiError } from "../api/types.js";
|
|
8
9
|
/** A real GoTrue JWT (starts "eyJ"; a leftover --demo token doesn't) with over a minute left on it. */
|
|
9
10
|
export function isSignedIn(creds) {
|
|
10
11
|
return !!creds?.accessToken?.startsWith("eyJ") && (!creds.expiresAt || creds.expiresAt > Date.now() + 60_000);
|
|
11
12
|
}
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
return join(
|
|
13
|
+
/** Where the CLI keeps its files: `$XDG_CONFIG_HOME/sodabase`, else `~/.config/sodabase`. */
|
|
14
|
+
export function configDir() {
|
|
15
|
+
return join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "sodabase");
|
|
16
|
+
}
|
|
17
|
+
export function credsPath() {
|
|
18
|
+
return join(configDir(), "credentials.json");
|
|
19
|
+
}
|
|
20
|
+
// Windows refuses to replace a file another process has open (an antivirus scan, a second run reading it) with one of
|
|
21
|
+
// these; it clears within moments, so the rename is retried a few times before giving up.
|
|
22
|
+
const RENAME_BUSY = new Set(["EPERM", "EACCES", "EBUSY"]);
|
|
23
|
+
function renameRetrying(from, to) {
|
|
24
|
+
for (let attempt = 1;; attempt++) {
|
|
25
|
+
try {
|
|
26
|
+
renameSync(from, to);
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
catch (e) {
|
|
30
|
+
const code = e?.code;
|
|
31
|
+
if (process.platform !== "win32" || attempt === 5 || typeof code !== "string" || !RENAME_BUSY.has(code))
|
|
32
|
+
throw e;
|
|
33
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 25 * attempt);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
15
36
|
}
|
|
16
37
|
export function loadCreds() {
|
|
17
38
|
try {
|
|
@@ -21,17 +42,90 @@ export function loadCreds() {
|
|
|
21
42
|
return null; // missing / unreadable / malformed → treat as signed-out
|
|
22
43
|
}
|
|
23
44
|
}
|
|
45
|
+
/** Atomically replace the creds file: write a 0600 temp file beside it, fsync, rename over. A concurrent run never
|
|
46
|
+
* reads a half-written file, and a kill mid-write never leaves a truncated one (losing a just-rotated token). */
|
|
24
47
|
export function saveCreds(creds) {
|
|
25
48
|
const path = credsPath();
|
|
26
49
|
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
27
|
-
|
|
28
|
-
|
|
50
|
+
const tmp = `${path}.${process.pid}.tmp`;
|
|
51
|
+
try {
|
|
52
|
+
const fd = openSync(tmp, "w", 0o600);
|
|
53
|
+
try {
|
|
54
|
+
writeSync(fd, JSON.stringify(creds, null, 2));
|
|
55
|
+
fsyncSync(fd);
|
|
56
|
+
}
|
|
57
|
+
finally {
|
|
58
|
+
closeSync(fd);
|
|
59
|
+
}
|
|
60
|
+
chmodSync(tmp, 0o600); // enforce even if a stale temp file pre-existed with looser perms
|
|
61
|
+
renameRetrying(tmp, path);
|
|
62
|
+
}
|
|
63
|
+
catch (e) {
|
|
64
|
+
rmSync(tmp, { force: true });
|
|
65
|
+
throw e;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
const REJECTED = new Set([400, 401, 403]);
|
|
69
|
+
/** The saved session, refreshed (and re-saved) when the access token has expired or `force` is set. Null when
|
|
70
|
+
* there's no usable session: never signed in, a --demo token, no refresh token, or GoTrue rejected it.
|
|
71
|
+
* Any other refresh failure (offline, GoTrue down) is thrown, so it isn't reported as "not signed in". */
|
|
72
|
+
export async function freshCreds(refresh, opts = {}) {
|
|
73
|
+
const creds = loadCreds();
|
|
74
|
+
if (!creds?.accessToken?.startsWith("eyJ"))
|
|
75
|
+
return null;
|
|
76
|
+
if (!opts.force && isSignedIn(creds))
|
|
77
|
+
return creds;
|
|
78
|
+
if (!creds.refreshToken)
|
|
79
|
+
return null;
|
|
80
|
+
let next;
|
|
81
|
+
try {
|
|
82
|
+
next = await refresh(creds.refreshToken);
|
|
83
|
+
}
|
|
84
|
+
catch (e) {
|
|
85
|
+
const status = e?.status;
|
|
86
|
+
if (typeof status === "number" && REJECTED.has(status))
|
|
87
|
+
return null;
|
|
88
|
+
throw e;
|
|
89
|
+
}
|
|
90
|
+
const saved = {
|
|
91
|
+
accessToken: next.accessToken,
|
|
92
|
+
// GoTrue rotates it; keep the old one only if a response somehow came back without one
|
|
93
|
+
refreshToken: next.refreshToken ?? creds.refreshToken,
|
|
94
|
+
...(next.expiresAt ? { expiresAt: next.expiresAt } : {}),
|
|
95
|
+
};
|
|
96
|
+
try {
|
|
97
|
+
saveCreds(saved);
|
|
98
|
+
}
|
|
99
|
+
catch (e) {
|
|
100
|
+
// the rotated token now exists only in memory, so this run must not carry on as if it were saved
|
|
101
|
+
const why = e?.code ?? (e instanceof Error ? e.message : String(e));
|
|
102
|
+
throw new ApiError(`couldn't save your refreshed session to ${credsPath()} (${String(why)}). ` +
|
|
103
|
+
"Check that the folder is writable, then run `npx sodabase login`.", 500, "save");
|
|
104
|
+
}
|
|
105
|
+
return saved;
|
|
29
106
|
}
|
|
107
|
+
/** Sign out: the creds file, and any temp copy a run killed mid-save left beside it (it holds the same tokens).
|
|
108
|
+
* Best-effort, as before: a file another process holds open (Windows) stays rather than crashing the sign-out. */
|
|
30
109
|
export function clearCreds() {
|
|
110
|
+
const path = credsPath();
|
|
111
|
+
const rm = (p) => {
|
|
112
|
+
try {
|
|
113
|
+
rmSync(p, { force: true });
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
/* held open: leave it */
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
rm(path);
|
|
120
|
+
let names = [];
|
|
31
121
|
try {
|
|
32
|
-
|
|
122
|
+
names = readdirSync(dirname(path));
|
|
33
123
|
}
|
|
34
124
|
catch {
|
|
35
|
-
|
|
125
|
+
return; // no config folder: nothing saved
|
|
36
126
|
}
|
|
127
|
+
const tmp = /^credentials\.json\.\d+\.tmp$/;
|
|
128
|
+
for (const n of names)
|
|
129
|
+
if (tmp.test(n))
|
|
130
|
+
rm(join(dirname(path), n));
|
|
37
131
|
}
|
package/dist/functionsLint.js
CHANGED
|
@@ -8,6 +8,18 @@
|
|
|
8
8
|
// write, `${}` inside templates and regex literals aren't parsed — upgrade to the TS compiler API if it misleads.
|
|
9
9
|
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
10
10
|
import { join, relative } from "node:path";
|
|
11
|
+
export const FUNCTIONS_LINT_HELP = [
|
|
12
|
+
"sodabase functions lint — flag database writes in supabase/functions without a check() line before them",
|
|
13
|
+
"",
|
|
14
|
+
"Usage: npx sodabase functions lint",
|
|
15
|
+
"",
|
|
16
|
+
"Options:",
|
|
17
|
+
" --help, -h show this help",
|
|
18
|
+
"",
|
|
19
|
+
"Run it from your Supabase project's root. Offline and read-only: no sign-in, nothing is sent anywhere.",
|
|
20
|
+
"Exit code: 0 all writes checked, 1 unchecked writes found, 2 no supabase/functions folder (or bad options).",
|
|
21
|
+
"",
|
|
22
|
+
].join("\n");
|
|
11
23
|
const EDGE_IMPORT = /\bfrom\s*["'](?:jsr:|npm:)?@sodabase\/edge(?:@[^"']*)?(?:\/[^"']*)?["']/;
|
|
12
24
|
const CALL_WRITE = /\.(insert|upsert|update)\s*\(/g;
|
|
13
25
|
const SQL_TAG = /\bsql\s*$/;
|
package/dist/login.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// `npx sodabase login` — sign in (browser or email code), save the session, and exit: no setup wizard. For an agent
|
|
2
|
+
// or a script that only needs a session before `rules pull`. Sign-in is interactive, so it refuses to start without
|
|
3
|
+
// a terminal on stdin (an agent's shell) and says where to run it instead.
|
|
4
|
+
import { credsPath } from "./config/tokenStore.js";
|
|
5
|
+
export const LOGIN_HELP = [
|
|
6
|
+
"sodabase login — sign in to Sodabase, save the session, and exit (no setup wizard)",
|
|
7
|
+
"",
|
|
8
|
+
"Usage: npx sodabase login",
|
|
9
|
+
"",
|
|
10
|
+
"Options:",
|
|
11
|
+
" --help, -h show this help",
|
|
12
|
+
"",
|
|
13
|
+
"Sign-in opens your browser (or emails you a code), so run it in a terminal window of your own: a coding",
|
|
14
|
+
"agent's shell can't answer the prompts. The session is saved in your config folder (~/.config/sodabase, or",
|
|
15
|
+
"$XDG_CONFIG_HOME/sodabase) and renews itself, so other commands (e.g. `npx sodabase rules pull --project",
|
|
16
|
+
"<ref>`) keep working without signing in again.",
|
|
17
|
+
"",
|
|
18
|
+
].join("\n");
|
|
19
|
+
export const LOGIN_NEEDS_TERMINAL = [
|
|
20
|
+
"sodabase login: sign-in is interactive (it opens your browser and asks you to pick an account), and this",
|
|
21
|
+
"shell isn't a terminal it can prompt in. Open a separate terminal window and run:",
|
|
22
|
+
"",
|
|
23
|
+
" npx sodabase login",
|
|
24
|
+
"",
|
|
25
|
+
"then come back here and run your command again.",
|
|
26
|
+
"",
|
|
27
|
+
].join("\n");
|
|
28
|
+
export const LOGIN_DONE = "Signed in to Sodabase. Your session is saved; you can close this window and run your command.\n";
|
|
29
|
+
/** How `login` ends, from what its sign-in screen reported: undefined = it never finished (esc, Ctrl+C). */
|
|
30
|
+
export function loginOutcome(saved) {
|
|
31
|
+
if (saved === true)
|
|
32
|
+
return { code: 0, stdout: LOGIN_DONE };
|
|
33
|
+
if (saved === false) {
|
|
34
|
+
return {
|
|
35
|
+
code: 1,
|
|
36
|
+
stderr: `sodabase login: you signed in, but your session couldn't be saved to ${credsPath()}. ` +
|
|
37
|
+
"Check that the folder is writable, then run `npx sodabase login` again.\n",
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
return { code: 130, stderr: "sodabase login: sign-in cancelled.\n" };
|
|
41
|
+
}
|
|
42
|
+
/** What to run when a command finds no usable session (never signed in, signed out, or the session was revoked). */
|
|
43
|
+
export const NOT_SIGNED_IN = "you're not signed in to Sodabase (or your session was revoked). Run `npx sodabase login` in a terminal window " +
|
|
44
|
+
"of your own (it opens your browser), then run this command again";
|
package/dist/rulesPull.js
CHANGED
|
@@ -16,7 +16,7 @@ export const RULES_PULL_HELP = [
|
|
|
16
16
|
" --project <ref> your 20-character Supabase project ref",
|
|
17
17
|
" --help, -h show this help",
|
|
18
18
|
"",
|
|
19
|
-
"Run it from your Supabase project's root, signed in (`npx sodabase
|
|
19
|
+
"Run it from your Supabase project's root, signed in (`npx sodabase login`) as a workspace owner or admin.",
|
|
20
20
|
"",
|
|
21
21
|
].join("\n");
|
|
22
22
|
/** Parse the args AFTER `rules pull`. Returns the project ref (or help), or an error message for bad input. */
|
package/dist/ui.js
CHANGED
|
@@ -169,7 +169,7 @@ function friendlySignInError(raw) {
|
|
|
169
169
|
return { text: raw };
|
|
170
170
|
}
|
|
171
171
|
export function SignIn({ onDone }) {
|
|
172
|
-
const { services, signedIn, demo, interactive } = useWizard();
|
|
172
|
+
const { services, signedIn, demo, interactive, onSignedIn } = useWizard();
|
|
173
173
|
const { exit } = useApp();
|
|
174
174
|
const spin = useSpinner();
|
|
175
175
|
const [stage, setStage] = useState(interactive ? "pick" : "signing");
|
|
@@ -188,6 +188,7 @@ export function SignIn({ onDone }) {
|
|
|
188
188
|
if (!mounted.current)
|
|
189
189
|
return;
|
|
190
190
|
services.setBearer(session.accessToken);
|
|
191
|
+
let saved = false;
|
|
191
192
|
if (!demo) {
|
|
192
193
|
// Never persist the fake --demo session to the real creds file.
|
|
193
194
|
try {
|
|
@@ -196,11 +197,13 @@ export function SignIn({ onDone }) {
|
|
|
196
197
|
...(session.refreshToken ? { refreshToken: session.refreshToken } : {}),
|
|
197
198
|
...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
|
|
198
199
|
});
|
|
200
|
+
saved = true;
|
|
199
201
|
}
|
|
200
202
|
catch {
|
|
201
|
-
/* non-fatal */
|
|
203
|
+
/* non-fatal for the wizard (the session is still held in memory); `login` reports it */
|
|
202
204
|
}
|
|
203
205
|
}
|
|
206
|
+
onSignedIn?.(saved);
|
|
204
207
|
onDone({});
|
|
205
208
|
}
|
|
206
209
|
function fail(e) {
|
|
@@ -479,7 +482,7 @@ export function Connect({ onDone }) {
|
|
|
479
482
|
return;
|
|
480
483
|
// A Sodabase-auth failure (expired session) won't be fixed by the Supabase browser flow — surface it.
|
|
481
484
|
if (e instanceof ApiError && e.status === 401) {
|
|
482
|
-
setError("Your Sodabase session has expired. Run `sodabase
|
|
485
|
+
setError("Your Sodabase session has expired. Run `npx sodabase login`, then try again.");
|
|
483
486
|
return;
|
|
484
487
|
}
|
|
485
488
|
// Anything else (offline / 5xx): fall through to authorize, which surfaces its own errors.
|
|
@@ -814,7 +817,7 @@ export function McpInstall({ onDone }) {
|
|
|
814
817
|
else if (key.return)
|
|
815
818
|
void run(list.picked());
|
|
816
819
|
}, { isActive: interactive && !busy && (!result || skillError !== null || ready) });
|
|
817
|
-
return (_jsxs(Box, { flexDirection: "column", paddingX: 2, marginTop: 1, alignItems: "center", children: [_jsx(Eyebrow, { children: "Set up your coding agent (optional)" }), error ? (_jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsxs(Text, { color: "yellow", children: ["Couldn't auto-install the MCP: ", error] }), _jsx(Text, { dimColor: true, children: "Add it yourself (Claude Code):" }), _jsxs(Text, { color: "cyan", children: [" ", "claude mcp add --transport http sodabase ", MCP_URL] }), interactive && (_jsx(Box, { marginTop: 1, children: _jsx(Text, { dimColor: true, children: "enter to continue" }) }))] })) : result ? (_jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsxs(Text, { dimColor: true, children: ["Ran: ", result.command] }), result.wrote.map((w) => (_jsxs(Text, { children: [" ", _jsx(Text, { color: "green", children: "\u2714" }), " ", w.agent, " ", _jsxs(Text, { dimColor: true, children: ["\u2192 ", w.path] })] }, w.agent))), skillResult && (_jsxs(Text, { children: [" ", _jsx(Text, { color: "green", children: "\u2714" }), " trust-advisor skill ", _jsx(Text, { dimColor: true, children: "\u2192
|
|
820
|
+
return (_jsxs(Box, { flexDirection: "column", paddingX: 2, marginTop: 1, alignItems: "center", children: [_jsx(Eyebrow, { children: "Set up your coding agent (optional)" }), error ? (_jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsxs(Text, { color: "yellow", children: ["Couldn't auto-install the MCP: ", error] }), _jsx(Text, { dimColor: true, children: "Add it yourself (Claude Code):" }), _jsxs(Text, { color: "cyan", children: [" ", "claude mcp add --transport http sodabase ", MCP_URL] }), interactive && (_jsx(Box, { marginTop: 1, children: _jsx(Text, { dimColor: true, children: "enter to continue" }) }))] })) : result ? (_jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsxs(Text, { dimColor: true, children: ["Ran: ", result.command] }), result.wrote.map((w) => (_jsxs(Text, { children: [" ", _jsx(Text, { color: "green", children: "\u2714" }), " ", w.agent, " ", _jsxs(Text, { dimColor: true, children: ["\u2192 ", w.path] })] }, w.agent))), skillResult && (_jsxs(Text, { children: [" ", _jsx(Text, { color: "green", children: "\u2714" }), " trust-advisor skill ", _jsx(Text, { dimColor: true, children: "\u2192 labs-soda/agent-skills" })] })), skillError && (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Text, { color: "yellow", children: ["Couldn't install the trust-advisor skill: ", skillError] }), _jsx(Text, { dimColor: true, children: "Add it yourself:" }), _jsxs(Text, { color: "cyan", children: [" ", "npx skills add labs-soda/agent-skills"] })] })), _jsx(Text, { color: "green", children: "Ready next time you restart your agent." }), (ready || skillError) && interactive && (_jsx(Box, { marginTop: 1, children: _jsx(Text, { dimColor: true, children: "enter to continue" }) }))] })) : (_jsxs(_Fragment, { children: [_jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsx(Text, { dimColor: true, children: "Install the Sodabase MCP + trust-advisor skill so your agent can ask \"is this data safe to trust?\"" }), _jsx(Text, { dimColor: true, children: "Explicit \u2014 we show the exact change and only write on your confirm." })] }), _jsx(Box, { marginTop: 1, children: _jsx(AgentChecklist, { sel: list.sel, cursor: interactive ? list.cursor : null, found: local.found, installed: local.installed }) })] }))] }));
|
|
818
821
|
}
|
|
819
822
|
// ── Phase: manage projects (the hub's "Manage projects" entry) ───────────────────
|
|
820
823
|
// A picker over the projects already being watched; selecting one drills into its watched tables.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sodabase",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.13",
|
|
4
4
|
"description": "Sodabase onboarding wizard — interactive CLI (npx sodabase).",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"homepage": "https://sodabase.io",
|
|
@@ -46,11 +46,11 @@
|
|
|
46
46
|
},
|
|
47
47
|
"dependencies": {
|
|
48
48
|
"ink": "7.1.1",
|
|
49
|
-
"react": "19.
|
|
49
|
+
"react": "19.3.1"
|
|
50
50
|
},
|
|
51
51
|
"devDependencies": {
|
|
52
52
|
"@types/node": "22.20.5",
|
|
53
|
-
"@types/react": "19.
|
|
53
|
+
"@types/react": "19.3.0",
|
|
54
54
|
"typescript": "5.9.3"
|
|
55
55
|
}
|
|
56
56
|
}
|