sodabase 0.1.11 → 0.1.12

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
@@ -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)
@@ -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 fetch(`${this.api}${path}`, { headers: this.authHeaders() }));
335
+ return this.parse(await this.send(path, () => ({ headers: this.authHeaders() })));
330
336
  }
331
337
  async post(path, json) {
332
- const init = { method: "POST", headers: { ...this.authHeaders() } };
333
- if (json !== undefined) {
334
- init.headers["content-type"] = "application/json";
335
- init.body = JSON.stringify(json);
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 this.parse(await fetch(`${this.api}${path}`, init));
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();
@@ -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
@@ -9,13 +9,18 @@ import { SodabaseClient } from "./api/client.js";
9
9
  import { FakeClient } from "./api/fakeClient.js";
10
10
  import { pickAgents } from "./agentPicker.js";
11
11
  import { App } from "./app.js";
12
- import { clearCreds, isSignedIn, loadCreds } from "./config/tokenStore.js";
13
- import { runLint } from "./functionsLint.js";
12
+ import { refreshSession, resolveGoTrueConfig } from "./api/gotrueAuth.js";
13
+ import { parseHelpOnly } from "./args.js";
14
+ import { clearCreds, freshCreds } from "./config/tokenStore.js";
15
+ import { FUNCTIONS_LINT_HELP, runLint } from "./functionsLint.js";
14
16
  import { INSTALL_MCP_HELP, detectAgents, installedAgents, parseInstallMcpArgs, resolveAgents, runInstallMcp, } from "./installMcp.js";
17
+ import { LOGIN_HELP, LOGIN_NEEDS_TERMINAL, NOT_SIGNED_IN, loginOutcome } from "./login.js";
15
18
  import { RULES_PULL_HELP, parseRulesPullArgs, runRulesPull } from "./rulesPull.js";
16
19
  import { ApiError } from "./api/types.js";
17
20
  const argv = process.argv.slice(2);
18
21
  const args = new Set(argv);
22
+ /** The saved session's refresh token → a new GoTrue session (the access token only lives about an hour). */
23
+ const refresh = (token) => refreshSession(resolveGoTrueConfig(), token);
19
24
  /** process.exit() drops output still queued on a pipe (async on macOS, e.g. `| tee log`): await this first. */
20
25
  async function drained() {
21
26
  await Promise.all([process.stdout, process.stderr].map((s) => new Promise((done) => s.write("", done))));
@@ -61,6 +66,17 @@ if (argv[0] === "install-mcp") {
61
66
  }
62
67
  // `functions lint`: static and offline — flags writes in supabase/functions/** with no check() line before them.
63
68
  if (argv[0] === "functions" && argv[1] === "lint") {
69
+ const opts = parseHelpOnly(argv.slice(2));
70
+ if ("error" in opts) {
71
+ process.stderr.write(`sodabase functions lint: ${opts.error}\n\n${FUNCTIONS_LINT_HELP}`);
72
+ await drained();
73
+ process.exit(2);
74
+ }
75
+ if (opts.help) {
76
+ process.stdout.write(FUNCTIONS_LINT_HELP);
77
+ await drained();
78
+ process.exit(0);
79
+ }
64
80
  const code = runLint(process.cwd(), (line) => process.stdout.write(`${line}\n`));
65
81
  await drained();
66
82
  process.exit(code);
@@ -81,13 +97,15 @@ if (argv[0] === "rules" && argv[1] === "pull") {
81
97
  await drained();
82
98
  process.exit(0);
83
99
  }
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
100
  const client = new SodabaseClient();
89
- client.setBearer(creds.accessToken);
90
101
  try {
102
+ // An expired access token is renewed from the saved refresh token (and re-saved) before the call, and again
103
+ // if the server still says 401; only a missing or revoked session ends up at NOT_SIGNED_IN.
104
+ const creds = await freshCreds(refresh);
105
+ if (!creds)
106
+ await fail(NOT_SIGNED_IN);
107
+ client.setBearer(creds.accessToken);
108
+ client.setRefresher(async () => (await freshCreds(refresh, { force: true }))?.accessToken);
91
109
  const code = await runRulesPull(project, (r) => client.rulesFile(r), process.cwd(), (line) => process.stdout.write(`${line}\n`));
92
110
  await drained();
93
111
  process.exit(code);
@@ -96,7 +114,7 @@ if (argv[0] === "rules" && argv[1] === "pull") {
96
114
  if (!(err instanceof ApiError))
97
115
  throw err;
98
116
  if (err.status === 401)
99
- await fail(login);
117
+ await fail(NOT_SIGNED_IN);
100
118
  if (err.status === 403)
101
119
  await fail("only a workspace owner or admin can pull the rules file");
102
120
  if (err.status === 404)
@@ -104,16 +122,68 @@ if (argv[0] === "rules" && argv[1] === "pull") {
104
122
  await fail(err.message);
105
123
  }
106
124
  }
107
- if (args.has("--help") || args.has("-h")) {
125
+ // A command group without (or with an unknown) subcommand: say what exists rather than launching the wizard.
126
+ const GROUPS = {
127
+ rules: { usage: "npx sodabase rules pull --project <ref>" },
128
+ functions: { usage: "npx sodabase functions lint" },
129
+ };
130
+ const group = GROUPS[argv[0] ?? ""];
131
+ if (group) {
132
+ const sub = argv[1];
133
+ const help = sub === undefined || sub === "--help" || sub === "-h";
134
+ const out = help ? process.stdout : process.stderr;
135
+ out.write(`${help ? "" : `sodabase ${argv[0]}: unknown command: ${sub}\n\n`}Usage: ${group.usage}\n\nAdd --help for details.\n`);
136
+ await drained();
137
+ process.exit(help && sub !== undefined ? 0 : 2);
138
+ }
139
+ // `login`: sign in, save the session, exit. Interactive by nature, so refuse up front when there's no terminal.
140
+ if (argv[0] === "login") {
141
+ const opts = parseHelpOnly(argv.slice(1));
142
+ if ("error" in opts) {
143
+ process.stderr.write(`sodabase login: ${opts.error}\n\n${LOGIN_HELP}`);
144
+ await drained();
145
+ process.exit(2);
146
+ }
147
+ if (opts.help) {
148
+ process.stdout.write(LOGIN_HELP);
149
+ await drained();
150
+ process.exit(0);
151
+ }
152
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
153
+ process.stderr.write(LOGIN_NEEDS_TERMINAL);
154
+ await drained();
155
+ process.exit(1);
156
+ }
157
+ // The saved session is left alone until the new one replaces it, so backing out keeps you signed in. Success is
158
+ // what THIS run's sign-in screen reports (not whatever is on disk): Ctrl+C ends Ink without it → 130.
159
+ let saved;
160
+ const app = render(_jsx(App, { services: new SodabaseClient(), fast: false, interactive: true, signedIn: false, demo: false, fullscreen: false, loginOnly: true, onSignedIn: (ok) => (saved = ok) }));
161
+ await app.waitUntilExit();
162
+ const outcome = loginOutcome(saved);
163
+ if (outcome.stdout)
164
+ process.stdout.write(outcome.stdout);
165
+ if (outcome.stderr)
166
+ process.stderr.write(outcome.stderr);
167
+ await drained();
168
+ process.exit(outcome.code);
169
+ }
170
+ if (argv[0] !== undefined && argv[0] !== "help" && !argv[0].startsWith("-")) {
171
+ process.stderr.write(`sodabase: unknown command: ${argv[0]}\n\nRun \`npx sodabase --help\` to see the commands.\n`);
172
+ await drained();
173
+ process.exit(2);
174
+ }
175
+ if (argv[0] === "help" || args.has("--help") || args.has("-h")) {
108
176
  process.stdout.write([
109
177
  "sodabase — data-quality onboarding wizard",
110
178
  "",
111
179
  "Usage: npx sodabase [options]",
180
+ " npx sodabase login",
112
181
  " npx sodabase install-mcp [-a, --agent <id>] [--all] [--no-skill] [--no-input]",
113
182
  " npx sodabase rules pull --project <ref>",
114
183
  " npx sodabase functions lint",
115
184
  "",
116
185
  "Commands:",
186
+ " login sign in, save the session, and exit (no setup wizard)",
117
187
  " install-mcp install the MCP + trust-advisor skill for your coding agent, then exit",
118
188
  " rules pull save the project's pipeline rules file and list it in each function's static_files",
119
189
  " functions lint flag writes in supabase/functions without a check() line before them",
@@ -121,7 +191,7 @@ if (args.has("--help") || args.has("-h")) {
121
191
  "Options:",
122
192
  " --demo run the whole flow offline against a fake backend",
123
193
  " --fast shorter delays (implied by --demo)",
124
- " --login sign in again (clears the saved session first)",
194
+ " --login sign in again (clears the saved session first), then run the setup",
125
195
  " --logout clear the saved session and exit",
126
196
  " --help, -h show this help",
127
197
  " --version print the version",
@@ -170,15 +240,18 @@ const interactive = !!process.stdin.isTTY && !args.has("--no-input");
170
240
  let signedIn = false;
171
241
  const services = demo
172
242
  ? new FakeClient({ fast })
173
- : (() => {
243
+ : await (async () => {
174
244
  const c = new SodabaseClient();
175
- const creds = loadCreds();
176
- // Require a real GoTrue JWT (starts "eyJ") — guards against a stale/fake token
177
- // (e.g. a leftover --demo session) skipping sign-in and then 401-ing on /api/v1.
178
- if (creds?.accessToken && creds.accessToken.startsWith("eyJ")) {
245
+ // An expired saved session is renewed from its refresh token; freshCreds only returns a real GoTrue JWT
246
+ // (never a leftover --demo token, which would skip sign-in and then 401 on /api/v1). Offline at boot →
247
+ // just show the sign-in screen rather than crash.
248
+ const creds = await freshCreds(refresh).catch(() => null);
249
+ if (creds) {
179
250
  c.setBearer(creds.accessToken);
180
- signedIn = isSignedIn(creds);
251
+ signedIn = true;
181
252
  }
253
+ // Mid-run, a 401 renews the session the sign-in screen (or a previous run) saved, then retries once.
254
+ c.setRefresher(async () => (await freshCreds(refresh, { force: true }))?.accessToken);
182
255
  return c;
183
256
  })();
184
257
  // Fullscreen: take over the terminal (alternate screen) and theme it dark by setting the terminal's OWN
@@ -2,9 +2,10 @@
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, writeFileSync } from "node:fs";
5
+ import { chmodSync, closeSync, fsyncSync, mkdirSync, openSync, 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);
@@ -21,11 +22,67 @@ export function loadCreds() {
21
22
  return null; // missing / unreadable / malformed → treat as signed-out
22
23
  }
23
24
  }
25
+ /** Atomically replace the creds file: write a 0600 temp file beside it, fsync, rename over. A concurrent run never
26
+ * reads a half-written file, and a kill mid-write never leaves a truncated one (losing a just-rotated token). */
24
27
  export function saveCreds(creds) {
25
28
  const path = credsPath();
26
29
  mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
27
- writeFileSync(path, JSON.stringify(creds, null, 2), { mode: 0o600 });
28
- chmodSync(path, 0o600); // enforce even if the file pre-existed with looser perms
30
+ const tmp = `${path}.${process.pid}.tmp`;
31
+ try {
32
+ const fd = openSync(tmp, "w", 0o600);
33
+ try {
34
+ writeSync(fd, JSON.stringify(creds, null, 2));
35
+ fsyncSync(fd);
36
+ }
37
+ finally {
38
+ closeSync(fd);
39
+ }
40
+ chmodSync(tmp, 0o600); // enforce even if a stale temp file pre-existed with looser perms
41
+ renameSync(tmp, path);
42
+ }
43
+ catch (e) {
44
+ rmSync(tmp, { force: true });
45
+ throw e;
46
+ }
47
+ }
48
+ const REJECTED = new Set([400, 401, 403]);
49
+ /** The saved session, refreshed (and re-saved) when the access token has expired or `force` is set. Null when
50
+ * there's no usable session: never signed in, a --demo token, no refresh token, or GoTrue rejected it.
51
+ * Any other refresh failure (offline, GoTrue down) is thrown, so it isn't reported as "not signed in". */
52
+ export async function freshCreds(refresh, opts = {}) {
53
+ const creds = loadCreds();
54
+ if (!creds?.accessToken?.startsWith("eyJ"))
55
+ return null;
56
+ if (!opts.force && isSignedIn(creds))
57
+ return creds;
58
+ if (!creds.refreshToken)
59
+ return null;
60
+ let next;
61
+ try {
62
+ next = await refresh(creds.refreshToken);
63
+ }
64
+ catch (e) {
65
+ const status = e?.status;
66
+ if (typeof status === "number" && REJECTED.has(status))
67
+ return null;
68
+ throw e;
69
+ }
70
+ const saved = {
71
+ accessToken: next.accessToken,
72
+ // GoTrue rotates it; keep the old one only if a response somehow came back without one
73
+ refreshToken: next.refreshToken ?? creds.refreshToken,
74
+ ...(next.expiresAt ? { expiresAt: next.expiresAt } : {}),
75
+ };
76
+ try {
77
+ saveCreds(saved);
78
+ }
79
+ catch (e) {
80
+ // the rotated token now exists only in memory, so this run must not carry on as if it were saved
81
+ const why = e?.code ?? (e instanceof Error ? e.message : String(e));
82
+ throw new ApiError(`couldn't save your refreshed session to ${credsPath()} (${String(why)}). ` +
83
+ "Check that the folder is writable, then run `npx sodabase login`.", 500, "save");
84
+ }
85
+ return saved;
29
86
  }
30
87
  export function clearCreds() {
31
88
  try {
@@ -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,42 @@
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
+ export const LOGIN_HELP = [
5
+ "sodabase login — sign in to Sodabase, save the session, and exit (no setup wizard)",
6
+ "",
7
+ "Usage: npx sodabase login",
8
+ "",
9
+ "Options:",
10
+ " --help, -h show this help",
11
+ "",
12
+ "Sign-in opens your browser (or emails you a code), so run it in a terminal window of your own: a coding",
13
+ "agent's shell can't answer the prompts. The session is saved under ~/.config/sodabase and renews itself,",
14
+ "so other commands (e.g. `npx sodabase rules pull --project <ref>`) keep working without signing in again.",
15
+ "",
16
+ ].join("\n");
17
+ export const LOGIN_NEEDS_TERMINAL = [
18
+ "sodabase login: sign-in is interactive (it opens your browser and asks you to pick an account), and this",
19
+ "shell isn't a terminal it can prompt in. Open a separate terminal window and run:",
20
+ "",
21
+ " npx sodabase login",
22
+ "",
23
+ "then come back here and run your command again.",
24
+ "",
25
+ ].join("\n");
26
+ export const LOGIN_DONE = "Signed in to Sodabase. Your session is saved; you can close this window and run your command.\n";
27
+ /** How `login` ends, from what its sign-in screen reported: undefined = it never finished (esc, Ctrl+C). */
28
+ export function loginOutcome(saved) {
29
+ if (saved === true)
30
+ return { code: 0, stdout: LOGIN_DONE };
31
+ if (saved === false) {
32
+ return {
33
+ code: 1,
34
+ stderr: "sodabase login: you signed in, but your session couldn't be saved to ~/.config/sodabase/credentials.json. " +
35
+ "Check that the folder is writable, then run `npx sodabase login` again.\n",
36
+ };
37
+ }
38
+ return { code: 130, stderr: "sodabase login: sign-in cancelled.\n" };
39
+ }
40
+ /** What to run when a command finds no usable session (never signed in, signed out, or the session was revoked). */
41
+ 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 " +
42
+ "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 --login`) as a workspace owner or admin.",
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) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sodabase",
3
- "version": "0.1.11",
3
+ "version": "0.1.12",
4
4
  "description": "Sodabase onboarding wizard — interactive CLI (npx sodabase).",
5
5
  "license": "UNLICENSED",
6
6
  "homepage": "https://sodabase.io",