sodabase 0.1.10 → 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 +22 -1
- package/dist/api/client.js +37 -6
- package/dist/api/gotrueAuth.js +25 -0
- package/dist/app.js +7 -3
- package/dist/args.js +8 -0
- package/dist/cli.js +135 -10
- package/dist/config/tokenStore.js +64 -3
- package/dist/functionsLint.js +174 -0
- package/dist/installMcp.js +1 -1
- package/dist/login.js +42 -0
- package/dist/rulesPull.js +181 -0
- package/dist/ui.js +5 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -38,12 +38,33 @@ 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
|
+
|
|
51
|
+
## Pipeline checks (Edge Functions)
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
npx sodabase rules pull --project <ref> # save supabase/functions/_shared/sodabase.rules.yml + its static_files entries (signed-in owner/admin)
|
|
55
|
+
npx sodabase functions lint # flag writes in supabase/functions/** without a check() line before them (offline; exits 1 if any)
|
|
56
|
+
```
|
|
57
|
+
|
|
41
58
|
## Layout
|
|
42
59
|
|
|
43
60
|
```
|
|
44
61
|
src/
|
|
45
62
|
cli.tsx entry — renders <App/> (or runs the install-mcp subcommand)
|
|
46
63
|
installMcp.ts `install-mcp`: arg parsing, agent detection, plain-output install
|
|
64
|
+
rulesPull.ts `rules pull`: the rules file + a line-based config.toml static_files edit
|
|
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
|
|
47
68
|
agentPicker.tsx `install-mcp`'s inline agent checkbox list
|
|
48
69
|
app.tsx the Ink app (flow orchestrator + screens)
|
|
49
70
|
api/
|
|
@@ -51,7 +72,7 @@ src/
|
|
|
51
72
|
job poll, connections, relevance, scan report)
|
|
52
73
|
types.ts wire types
|
|
53
74
|
config/
|
|
54
|
-
tokenStore.ts 0600 credential file
|
|
75
|
+
tokenStore.ts 0600 credential file + refresh of an expired session
|
|
55
76
|
```
|
|
56
77
|
|
|
57
78
|
## What backs each step (all real endpoints)
|
package/dist/api/client.js
CHANGED
|
@@ -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.
|
|
@@ -317,20 +323,45 @@ export class SodabaseClient {
|
|
|
317
323
|
});
|
|
318
324
|
return { command };
|
|
319
325
|
}
|
|
326
|
+
// ── `rules pull`: the project's pipeline rules file (writers only; GET /projects/{ref}/edge/rules-file) ──
|
|
327
|
+
async rulesFile(projectRef) {
|
|
328
|
+
return this.get(`/projects/${encodeURIComponent(projectRef)}/edge/rules-file`);
|
|
329
|
+
}
|
|
320
330
|
// ── low-level helpers ───────────────────────────────────────────────────────
|
|
321
331
|
authHeaders() {
|
|
322
332
|
return this.bearer ? { authorization: `Bearer ${this.bearer}` } : {};
|
|
323
333
|
}
|
|
324
334
|
async get(path) {
|
|
325
|
-
return this.parse(await
|
|
335
|
+
return this.parse(await this.send(path, () => ({ headers: this.authHeaders() })));
|
|
326
336
|
}
|
|
327
337
|
async post(path, json) {
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
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;
|
|
332
363
|
}
|
|
333
|
-
return
|
|
364
|
+
return fetch(`${this.api}${path}`, init()); // with the bearer another request's refresh may already have set
|
|
334
365
|
}
|
|
335
366
|
async parse(res) {
|
|
336
367
|
const text = await res.text();
|
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
|
@@ -9,10 +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 {
|
|
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";
|
|
13
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";
|
|
18
|
+
import { RULES_PULL_HELP, parseRulesPullArgs, runRulesPull } from "./rulesPull.js";
|
|
19
|
+
import { ApiError } from "./api/types.js";
|
|
14
20
|
const argv = process.argv.slice(2);
|
|
15
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);
|
|
16
24
|
/** process.exit() drops output still queued on a pipe (async on macOS, e.g. `| tee log`): await this first. */
|
|
17
25
|
async function drained() {
|
|
18
26
|
await Promise.all([process.stdout, process.stderr].map((s) => new Promise((done) => s.write("", done))));
|
|
@@ -56,20 +64,134 @@ if (argv[0] === "install-mcp") {
|
|
|
56
64
|
await drained();
|
|
57
65
|
process.exit(code);
|
|
58
66
|
}
|
|
59
|
-
|
|
67
|
+
// `functions lint`: static and offline — flags writes in supabase/functions/** with no check() line before them.
|
|
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
|
+
}
|
|
80
|
+
const code = runLint(process.cwd(), (line) => process.stdout.write(`${line}\n`));
|
|
81
|
+
await drained();
|
|
82
|
+
process.exit(code);
|
|
83
|
+
}
|
|
84
|
+
// `rules pull --project <ref>`: the project's pipeline rules file + its static_files entries (signed-in writer).
|
|
85
|
+
if (argv[0] === "rules" && argv[1] === "pull") {
|
|
86
|
+
const opts = parseRulesPullArgs(argv.slice(2));
|
|
87
|
+
const fail = async (msg, code = 1) => {
|
|
88
|
+
process.stderr.write(`sodabase rules pull: ${msg}\n${code === 2 ? `\n${RULES_PULL_HELP}` : ""}`);
|
|
89
|
+
await drained();
|
|
90
|
+
process.exit(code);
|
|
91
|
+
};
|
|
92
|
+
if ("error" in opts)
|
|
93
|
+
await fail(opts.error, 2);
|
|
94
|
+
const { project, help } = opts;
|
|
95
|
+
if (help) {
|
|
96
|
+
process.stdout.write(RULES_PULL_HELP);
|
|
97
|
+
await drained();
|
|
98
|
+
process.exit(0);
|
|
99
|
+
}
|
|
100
|
+
const client = new SodabaseClient();
|
|
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);
|
|
109
|
+
const code = await runRulesPull(project, (r) => client.rulesFile(r), process.cwd(), (line) => process.stdout.write(`${line}\n`));
|
|
110
|
+
await drained();
|
|
111
|
+
process.exit(code);
|
|
112
|
+
}
|
|
113
|
+
catch (err) {
|
|
114
|
+
if (!(err instanceof ApiError))
|
|
115
|
+
throw err;
|
|
116
|
+
if (err.status === 401)
|
|
117
|
+
await fail(NOT_SIGNED_IN);
|
|
118
|
+
if (err.status === 403)
|
|
119
|
+
await fail("only a workspace owner or admin can pull the rules file");
|
|
120
|
+
if (err.status === 404)
|
|
121
|
+
await fail("no such project in your workspace, or pipeline checks aren't on for it yet");
|
|
122
|
+
await fail(err.message);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
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")) {
|
|
60
176
|
process.stdout.write([
|
|
61
177
|
"sodabase — data-quality onboarding wizard",
|
|
62
178
|
"",
|
|
63
179
|
"Usage: npx sodabase [options]",
|
|
180
|
+
" npx sodabase login",
|
|
64
181
|
" npx sodabase install-mcp [-a, --agent <id>] [--all] [--no-skill] [--no-input]",
|
|
182
|
+
" npx sodabase rules pull --project <ref>",
|
|
183
|
+
" npx sodabase functions lint",
|
|
65
184
|
"",
|
|
66
185
|
"Commands:",
|
|
67
|
-
"
|
|
186
|
+
" login sign in, save the session, and exit (no setup wizard)",
|
|
187
|
+
" install-mcp install the MCP + trust-advisor skill for your coding agent, then exit",
|
|
188
|
+
" rules pull save the project's pipeline rules file and list it in each function's static_files",
|
|
189
|
+
" functions lint flag writes in supabase/functions without a check() line before them",
|
|
68
190
|
"",
|
|
69
191
|
"Options:",
|
|
70
192
|
" --demo run the whole flow offline against a fake backend",
|
|
71
193
|
" --fast shorter delays (implied by --demo)",
|
|
72
|
-
" --login sign in again (clears the saved session first)",
|
|
194
|
+
" --login sign in again (clears the saved session first), then run the setup",
|
|
73
195
|
" --logout clear the saved session and exit",
|
|
74
196
|
" --help, -h show this help",
|
|
75
197
|
" --version print the version",
|
|
@@ -118,15 +240,18 @@ const interactive = !!process.stdin.isTTY && !args.has("--no-input");
|
|
|
118
240
|
let signedIn = false;
|
|
119
241
|
const services = demo
|
|
120
242
|
? new FakeClient({ fast })
|
|
121
|
-
: (() => {
|
|
243
|
+
: await (async () => {
|
|
122
244
|
const c = new SodabaseClient();
|
|
123
|
-
|
|
124
|
-
//
|
|
125
|
-
//
|
|
126
|
-
|
|
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) {
|
|
127
250
|
c.setBearer(creds.accessToken);
|
|
128
|
-
signedIn =
|
|
251
|
+
signedIn = true;
|
|
129
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);
|
|
130
255
|
return c;
|
|
131
256
|
})();
|
|
132
257
|
// Fullscreen: take over the terminal (alternate screen) and theme it dark by setting the terminal's OWN
|
|
@@ -2,9 +2,14 @@
|
|
|
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, 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";
|
|
9
|
+
/** A real GoTrue JWT (starts "eyJ"; a leftover --demo token doesn't) with over a minute left on it. */
|
|
10
|
+
export function isSignedIn(creds) {
|
|
11
|
+
return !!creds?.accessToken?.startsWith("eyJ") && (!creds.expiresAt || creds.expiresAt > Date.now() + 60_000);
|
|
12
|
+
}
|
|
8
13
|
function credsPath() {
|
|
9
14
|
const base = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
|
|
10
15
|
return join(base, "sodabase", "credentials.json");
|
|
@@ -17,11 +22,67 @@ export function loadCreds() {
|
|
|
17
22
|
return null; // missing / unreadable / malformed → treat as signed-out
|
|
18
23
|
}
|
|
19
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). */
|
|
20
27
|
export function saveCreds(creds) {
|
|
21
28
|
const path = credsPath();
|
|
22
29
|
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
23
|
-
|
|
24
|
-
|
|
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;
|
|
25
86
|
}
|
|
26
87
|
export function clearCreds() {
|
|
27
88
|
try {
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
// `npx sodabase functions lint` — flags database writes in supabase/functions/** that no `check()` line from
|
|
2
|
+
// @sodabase/edge covers (planning repo edge-function-writes-mvp-spec §4.1, §11 P5). Static and offline: no sign-in.
|
|
3
|
+
//
|
|
4
|
+
// What counts as a write: supabase-js / Drizzle `.insert(` `.upsert(` `.update(`, and a postgres.js
|
|
5
|
+
// sql`insert …` / sql`update …` template. A write is covered when the file imports @sodabase/edge and a `check(`
|
|
6
|
+
// call comes earlier in the same block or an enclosing one (a check inside a sibling, already-closed block doesn't).
|
|
7
|
+
// shortcut: brace-depth heuristic, not an AST (typescript is dev-only); an outer function's earlier check() can mask a
|
|
8
|
+
// write, `${}` inside templates and regex literals aren't parsed — upgrade to the TS compiler API if it misleads.
|
|
9
|
+
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
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");
|
|
23
|
+
const EDGE_IMPORT = /\bfrom\s*["'](?:jsr:|npm:)?@sodabase\/edge(?:@[^"']*)?(?:\/[^"']*)?["']/;
|
|
24
|
+
const CALL_WRITE = /\.(insert|upsert|update)\s*\(/g;
|
|
25
|
+
const SQL_TAG = /\bsql\s*$/;
|
|
26
|
+
const SQL_WRITE = /^\s*(insert|update)\b/i;
|
|
27
|
+
const CHECK = /\bcheck\s*\(/g;
|
|
28
|
+
// node:crypto's hash.update(data) is not a database write: neither the same-line chain nor a name bound to one
|
|
29
|
+
const HASH_CHAIN = /create(?:Hash|Hmac)\s*\(/;
|
|
30
|
+
const HASH_BINDING = /\b(?:const|let|var)\s+(\w+)\s*=\s*(?:[\w.]+\.)?create(?:Hash|Hmac)\s*\(/g;
|
|
31
|
+
/** Blank comments, strings and template bodies (keeping newlines and the quote characters), so braces and calls
|
|
32
|
+
* inside them don't count. Returns the blanked code and each template's start offset + raw body. */
|
|
33
|
+
function blank(src) {
|
|
34
|
+
const out = src.split("");
|
|
35
|
+
const templates = [];
|
|
36
|
+
const wipe = (from, to) => {
|
|
37
|
+
for (let k = from; k < to; k++)
|
|
38
|
+
if (out[k] !== "\n")
|
|
39
|
+
out[k] = " ";
|
|
40
|
+
};
|
|
41
|
+
let i = 0;
|
|
42
|
+
while (i < src.length) {
|
|
43
|
+
const c = src[i];
|
|
44
|
+
if (c === "/" && src[i + 1] === "/") {
|
|
45
|
+
const end = src.indexOf("\n", i);
|
|
46
|
+
const stop = end === -1 ? src.length : end;
|
|
47
|
+
wipe(i, stop);
|
|
48
|
+
i = stop;
|
|
49
|
+
}
|
|
50
|
+
else if (c === "/" && src[i + 1] === "*") {
|
|
51
|
+
const end = src.indexOf("*/", i + 2);
|
|
52
|
+
const stop = end === -1 ? src.length : end + 2;
|
|
53
|
+
wipe(i, stop);
|
|
54
|
+
i = stop;
|
|
55
|
+
}
|
|
56
|
+
else if (c === "'" || c === '"' || c === "`") {
|
|
57
|
+
let j = i + 1;
|
|
58
|
+
while (j < src.length && src[j] !== c && !(c !== "`" && src[j] === "\n"))
|
|
59
|
+
j += src[j] === "\\" ? 2 : 1;
|
|
60
|
+
if (c === "`")
|
|
61
|
+
templates.push({ at: i, body: src.slice(i + 1, j) });
|
|
62
|
+
wipe(i + 1, Math.min(j, src.length));
|
|
63
|
+
i = j + 1;
|
|
64
|
+
}
|
|
65
|
+
else
|
|
66
|
+
i++;
|
|
67
|
+
}
|
|
68
|
+
return { code: out.join(""), templates };
|
|
69
|
+
}
|
|
70
|
+
/** The unchecked writes in one source file. */
|
|
71
|
+
export function lintSource(src) {
|
|
72
|
+
const { code, templates } = blank(src);
|
|
73
|
+
const imported = EDGE_IMPORT.test(src);
|
|
74
|
+
const checks = new Set();
|
|
75
|
+
for (const m of code.matchAll(CHECK))
|
|
76
|
+
checks.add(m.index);
|
|
77
|
+
const hashes = new Set([...code.matchAll(HASH_BINDING)].map((m) => m[1]));
|
|
78
|
+
const writes = [];
|
|
79
|
+
for (const m of code.matchAll(CALL_WRITE)) {
|
|
80
|
+
// at most 256 chars back (a hostile long line stays linear); `\b` stops the name regex retrying inside a word
|
|
81
|
+
const before = code.slice(Math.max(code.lastIndexOf("\n", m.index) + 1, m.index - 256), m.index);
|
|
82
|
+
if (m[1] === "update" && (HASH_CHAIN.test(before) || hashes.has(/\b(\w+)\s*$/.exec(before)?.[1] ?? "")))
|
|
83
|
+
continue;
|
|
84
|
+
writes.push({ at: m.index, kind: m[1] });
|
|
85
|
+
}
|
|
86
|
+
for (const t of templates) {
|
|
87
|
+
const w = SQL_WRITE.exec(t.body);
|
|
88
|
+
if (w && SQL_TAG.test(code.slice(Math.max(0, t.at - 64), t.at)))
|
|
89
|
+
writes.push({ at: t.at, kind: `sql ${w[1].toLowerCase()}` });
|
|
90
|
+
}
|
|
91
|
+
// One forward pass: a stack of "a check() ran earlier in this block", one entry per open block (plus the file). A
|
|
92
|
+
// write is covered when its block or an enclosing one has one; a check inside a closed sibling block doesn't count.
|
|
93
|
+
const covered = new Set();
|
|
94
|
+
if (imported) {
|
|
95
|
+
const at = new Set(writes.map((w) => w.at));
|
|
96
|
+
const stack = [false];
|
|
97
|
+
for (let i = 0; i < code.length; i++) {
|
|
98
|
+
const c = code[i];
|
|
99
|
+
if (c === "{")
|
|
100
|
+
stack.push(false);
|
|
101
|
+
else if (c === "}") {
|
|
102
|
+
if (stack.length > 1)
|
|
103
|
+
stack.pop();
|
|
104
|
+
}
|
|
105
|
+
if (checks.has(i))
|
|
106
|
+
stack[stack.length - 1] = true;
|
|
107
|
+
if (at.has(i) && stack.includes(true))
|
|
108
|
+
covered.add(i);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
const starts = [0];
|
|
112
|
+
for (let i = 0; i < src.length; i++)
|
|
113
|
+
if (src[i] === "\n")
|
|
114
|
+
starts.push(i + 1);
|
|
115
|
+
const lineOf = (pos) => {
|
|
116
|
+
let lo = 0;
|
|
117
|
+
let hi = starts.length - 1;
|
|
118
|
+
while (lo < hi) {
|
|
119
|
+
const mid = (lo + hi + 1) >> 1;
|
|
120
|
+
if (starts[mid] <= pos)
|
|
121
|
+
lo = mid;
|
|
122
|
+
else
|
|
123
|
+
hi = mid - 1;
|
|
124
|
+
}
|
|
125
|
+
return lo + 1;
|
|
126
|
+
};
|
|
127
|
+
return writes
|
|
128
|
+
.filter((w) => !covered.has(w.at))
|
|
129
|
+
.map((w) => ({ line: lineOf(w.at), kind: w.kind }))
|
|
130
|
+
.sort((a, b) => a.line - b.line);
|
|
131
|
+
}
|
|
132
|
+
const SOURCE = /\.(ts|tsx|js|mjs)$/;
|
|
133
|
+
const MAX_BYTES = 1_000_000; // a bigger "source" file is generated or hostile: skipped, and said so
|
|
134
|
+
/** The source files under `dir`, relative to it. Symlinks are never followed (a link out of the tree, or a loop). */
|
|
135
|
+
function sources(dir, rel = "") {
|
|
136
|
+
const out = [];
|
|
137
|
+
for (const d of readdirSync(join(dir, rel), { withFileTypes: true })) {
|
|
138
|
+
if (d.isSymbolicLink() || d.name === "node_modules")
|
|
139
|
+
continue;
|
|
140
|
+
const path = rel ? join(rel, d.name) : d.name;
|
|
141
|
+
if (d.isDirectory())
|
|
142
|
+
out.push(...sources(dir, path));
|
|
143
|
+
else if (d.isFile() && SOURCE.test(d.name))
|
|
144
|
+
out.push(path);
|
|
145
|
+
}
|
|
146
|
+
return out;
|
|
147
|
+
}
|
|
148
|
+
/** Lint supabase/functions/** under `cwd`; prints file:line per finding. 1 = findings, 2 = no functions folder. */
|
|
149
|
+
export function runLint(cwd, log) {
|
|
150
|
+
const root = join(cwd, "supabase", "functions");
|
|
151
|
+
if (!existsSync(root)) {
|
|
152
|
+
log("No supabase/functions folder here — run this from your Supabase project's root.");
|
|
153
|
+
return 2;
|
|
154
|
+
}
|
|
155
|
+
const files = sources(root).sort();
|
|
156
|
+
let found = 0;
|
|
157
|
+
for (const f of files) {
|
|
158
|
+
const full = join(root, f);
|
|
159
|
+
if (statSync(full).size > MAX_BYTES) {
|
|
160
|
+
log(`${relative(cwd, full)}: skipped (over 1 MB)`);
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
for (const x of lintSource(readFileSync(full, "utf8"))) {
|
|
164
|
+
found++;
|
|
165
|
+
log(`${relative(cwd, full)}:${x.line} ${x.kind} without a check() before it`);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
if (found) {
|
|
169
|
+
log(`\n${found} write(s) without a check() line. Add sb.check("<schema>.<table>", rows) before each one.`);
|
|
170
|
+
return 1;
|
|
171
|
+
}
|
|
172
|
+
log(`No unchecked writes in ${files.length} file(s).`);
|
|
173
|
+
return 0;
|
|
174
|
+
}
|
package/dist/installMcp.js
CHANGED
|
@@ -30,7 +30,7 @@ const hasJsonEntry = (text) => text.includes(MCP_URL) &&
|
|
|
30
30
|
JSON.parse(text).mcpServers?.sodabase?.url === MCP_URL;
|
|
31
31
|
// Line by line, not one regex: our table's keys run from `[mcp_servers.sodabase]` to the next table header, a
|
|
32
32
|
// value may itself contain `[` (`args = ["x"]`), and a `url` under a subtable (`[mcp_servers.sodabase.env]`) isn't ours.
|
|
33
|
-
const TOML_HEADER = /^\s*\[\[?\s*([^\]]+?)\s*\]\]?\s*(#.*)?$/;
|
|
33
|
+
export const TOML_HEADER = /^\s*\[\[?\s*([^\]]+?)\s*\]\]?\s*(#.*)?$/;
|
|
34
34
|
const TOML_URL = /^\s*url\s*=\s*(["'])(.*?)\1\s*(#.*)?$/;
|
|
35
35
|
function hasTomlEntry(text) {
|
|
36
36
|
let ours = false;
|
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";
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
// `npx sodabase rules pull --project <ref>` — fetch the project's pipeline rules file (the backend's generator, the
|
|
2
|
+
// same one the MCP `pipeline_rules` tool uses), save it as supabase/functions/_shared/sodabase.rules.yml, and make sure
|
|
3
|
+
// every function lists it in `static_files` in supabase/config.toml (planning repo edge-function-writes-mvp-spec §5.3).
|
|
4
|
+
// shortcut: line-based TOML edit, not a parser (no deps); upgrade if config.toml shapes defeat it.
|
|
5
|
+
import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { dirname, join, relative } from "node:path";
|
|
7
|
+
import { TOML_HEADER } from "./installMcp.js";
|
|
8
|
+
export const RULES_FILE = join("supabase", "functions", "_shared", "sodabase.rules.yml");
|
|
9
|
+
export const STATIC_PATH = "./functions/_shared/sodabase.rules.yml"; // relative to supabase/, as config.toml has it
|
|
10
|
+
export const RULES_PULL_HELP = [
|
|
11
|
+
"sodabase rules pull — save the project's pipeline rules file and list it in each function's static_files",
|
|
12
|
+
"",
|
|
13
|
+
"Usage: npx sodabase rules pull --project <ref>",
|
|
14
|
+
"",
|
|
15
|
+
"Options:",
|
|
16
|
+
" --project <ref> your 20-character Supabase project ref",
|
|
17
|
+
" --help, -h show this help",
|
|
18
|
+
"",
|
|
19
|
+
"Run it from your Supabase project's root, signed in (`npx sodabase login`) as a workspace owner or admin.",
|
|
20
|
+
"",
|
|
21
|
+
].join("\n");
|
|
22
|
+
/** Parse the args AFTER `rules pull`. Returns the project ref (or help), or an error message for bad input. */
|
|
23
|
+
export function parseRulesPullArgs(argv) {
|
|
24
|
+
if (argv.some((a) => a === "--help" || a === "-h"))
|
|
25
|
+
return { project: "", help: true };
|
|
26
|
+
let project;
|
|
27
|
+
for (let i = 0; i < argv.length; i++) {
|
|
28
|
+
const arg = argv[i];
|
|
29
|
+
if (arg === "--project")
|
|
30
|
+
project = argv[++i];
|
|
31
|
+
else if (arg.startsWith("--project="))
|
|
32
|
+
project = arg.slice("--project=".length);
|
|
33
|
+
else
|
|
34
|
+
return { error: `unknown option: ${arg}` };
|
|
35
|
+
}
|
|
36
|
+
if (!project || !/^[a-z0-9]{20}$/.test(project))
|
|
37
|
+
return { error: "--project <ref> is required (your 20-character project ref)" };
|
|
38
|
+
return { project, help: false };
|
|
39
|
+
}
|
|
40
|
+
/** The index just past the `]` that closes the first `[` at or after `from` (quotes respected), or -1. */
|
|
41
|
+
function closeOf(line, from) {
|
|
42
|
+
let depth = 0;
|
|
43
|
+
let quote = "";
|
|
44
|
+
for (let i = from; i < line.length; i++) {
|
|
45
|
+
const c = line[i];
|
|
46
|
+
if (quote) {
|
|
47
|
+
if (c === "\\" && quote === '"')
|
|
48
|
+
i++;
|
|
49
|
+
else if (c === quote)
|
|
50
|
+
quote = "";
|
|
51
|
+
}
|
|
52
|
+
else if (c === '"' || c === "'")
|
|
53
|
+
quote = c;
|
|
54
|
+
else if (c === "#")
|
|
55
|
+
return -1;
|
|
56
|
+
else if (c === "[")
|
|
57
|
+
depth++;
|
|
58
|
+
else if (c === "]" && --depth === 0)
|
|
59
|
+
return i;
|
|
60
|
+
}
|
|
61
|
+
return -1;
|
|
62
|
+
}
|
|
63
|
+
function sectionOf(key, fn) {
|
|
64
|
+
return key === `functions.${fn}` || key === `functions."${fn}"` || key === `functions.'${fn}'`;
|
|
65
|
+
}
|
|
66
|
+
/** Add `path` to each function's `static_files` (adding the key or the `[functions.<fn>]` section when missing).
|
|
67
|
+
* Every other line is left byte-identical. `changed` names the functions whose config moved. */
|
|
68
|
+
export function ensureStaticFiles(toml, functions, path = STATIC_PATH) {
|
|
69
|
+
const eol = toml.includes("\r\n") ? "\r\n" : "\n";
|
|
70
|
+
const lines = toml.split(eol);
|
|
71
|
+
const entry = JSON.stringify(path);
|
|
72
|
+
const listed = (s) => s.includes(entry) || s.includes(`'${path}'`);
|
|
73
|
+
const changed = [];
|
|
74
|
+
for (const fn of functions) {
|
|
75
|
+
const start = lines.findIndex((l) => {
|
|
76
|
+
const h = TOML_HEADER.exec(l);
|
|
77
|
+
return !!h && !l.trim().startsWith("[[") && sectionOf(h[1], fn);
|
|
78
|
+
});
|
|
79
|
+
if (start === -1) {
|
|
80
|
+
const at = lines.length && lines[lines.length - 1] === "" ? lines.length - 1 : lines.length;
|
|
81
|
+
const add = [`[functions.${fn}]`, `static_files = [${entry}]`];
|
|
82
|
+
if (at > 0 && lines[at - 1].trim() !== "")
|
|
83
|
+
add.unshift("");
|
|
84
|
+
lines.splice(at, 0, ...add);
|
|
85
|
+
changed.push(fn);
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
let end = lines.findIndex((l, i) => i > start && TOML_HEADER.test(l));
|
|
89
|
+
if (end === -1)
|
|
90
|
+
end = lines.length;
|
|
91
|
+
const key = lines.findIndex((l, i) => i > start && i < end && /^\s*static_files\s*=/.test(l));
|
|
92
|
+
if (key === -1) {
|
|
93
|
+
lines.splice(start + 1, 0, `static_files = [${entry}]`);
|
|
94
|
+
changed.push(fn);
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
// the array runs from `key` to the line holding its closing `]`
|
|
98
|
+
let close = key;
|
|
99
|
+
let at = closeOf(lines[key], lines[key].indexOf("="));
|
|
100
|
+
if (at === -1) {
|
|
101
|
+
close = lines.findIndex((l, i) => i > key && i < end && /^[^#]*\]/.test(l) && !/^\s*#/.test(l));
|
|
102
|
+
if (close === -1)
|
|
103
|
+
continue; // shapes we don't understand stay untouched
|
|
104
|
+
at = lines[close].indexOf("]");
|
|
105
|
+
}
|
|
106
|
+
if (listed(lines.slice(key, close + 1).join(eol)))
|
|
107
|
+
continue;
|
|
108
|
+
const line = lines[close];
|
|
109
|
+
const before = line.slice(0, at);
|
|
110
|
+
if (close === key || before.trim() !== "") {
|
|
111
|
+
// `static_files = ["a"]` / `= []` / ` "b" ]`: insert before the `]`
|
|
112
|
+
const head = before.replace(/\s*$/, "");
|
|
113
|
+
const sep = head.endsWith("[") ? "" : head.endsWith(",") ? " " : ", ";
|
|
114
|
+
lines[close] = `${head}${sep}${entry}${line.slice(at)}`;
|
|
115
|
+
}
|
|
116
|
+
else {
|
|
117
|
+
// multi-line with `]` on its own line: a new element line before it (and a comma after the previous one)
|
|
118
|
+
let prev = close - 1;
|
|
119
|
+
while (prev > key && (lines[prev].trim() === "" || lines[prev].trim().startsWith("#")))
|
|
120
|
+
prev--;
|
|
121
|
+
const indent = prev > key ? /^\s*/.exec(lines[prev])[0] : " ";
|
|
122
|
+
if (prev > key && !/,\s*(#.*)?$/.test(lines[prev]))
|
|
123
|
+
lines[prev] = lines[prev].replace(/\s*(#.*)?$/, (m) => `,${m}`);
|
|
124
|
+
lines.splice(close, 0, `${indent}${entry},`);
|
|
125
|
+
}
|
|
126
|
+
changed.push(fn);
|
|
127
|
+
}
|
|
128
|
+
return { text: lines.join(eol), changed };
|
|
129
|
+
}
|
|
130
|
+
/** True when `path` exists and is a symlink (a cloned repo can plant one to redirect our writes). */
|
|
131
|
+
function isLink(path) {
|
|
132
|
+
try {
|
|
133
|
+
return lstatSync(path).isSymbolicLink();
|
|
134
|
+
}
|
|
135
|
+
catch {
|
|
136
|
+
return false;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
/** The deployable functions: the folders under supabase/functions not starting with `_` or `.`. */
|
|
140
|
+
export function functionDirs(cwd) {
|
|
141
|
+
const root = join(cwd, "supabase", "functions");
|
|
142
|
+
if (!existsSync(root))
|
|
143
|
+
return [];
|
|
144
|
+
return readdirSync(root, { withFileTypes: true })
|
|
145
|
+
// the backend's function-name rule: anything else (`a.b`, `x]`, a newline) would break or inject into config.toml
|
|
146
|
+
.filter((d) => d.isDirectory() && !/^[_.]/.test(d.name) && /^[A-Za-z0-9_-]{1,64}$/.test(d.name))
|
|
147
|
+
.map((d) => d.name)
|
|
148
|
+
.sort();
|
|
149
|
+
}
|
|
150
|
+
/** Write the rules file + the static_files entries; prints what changed. 0 ok, 1 no supabase/config.toml here. */
|
|
151
|
+
export async function runRulesPull(ref, fetchRules, cwd, log) {
|
|
152
|
+
const config = join(cwd, "supabase", "config.toml");
|
|
153
|
+
if (!existsSync(config)) {
|
|
154
|
+
log("No supabase/config.toml here — run this from your Supabase project's root.");
|
|
155
|
+
return 1;
|
|
156
|
+
}
|
|
157
|
+
const rules = join(cwd, RULES_FILE); // never a path from the server
|
|
158
|
+
const linked = [join(cwd, "supabase"), dirname(dirname(rules)), dirname(rules), rules, config].find(isLink);
|
|
159
|
+
if (linked) {
|
|
160
|
+
log(`${relative(cwd, linked) || linked} is a symlink — refusing to write through it. Replace it with a real file or folder.`);
|
|
161
|
+
return 1;
|
|
162
|
+
}
|
|
163
|
+
const { content } = await fetchRules(ref);
|
|
164
|
+
const old = existsSync(rules) ? readFileSync(rules, "utf8") : null;
|
|
165
|
+
mkdirSync(dirname(rules), { recursive: true });
|
|
166
|
+
writeFileSync(rules, content);
|
|
167
|
+
log(`${old === null ? "Created" : old === content ? "Unchanged" : "Updated"} ${RULES_FILE}`);
|
|
168
|
+
const fns = functionDirs(cwd);
|
|
169
|
+
const { text, changed } = ensureStaticFiles(readFileSync(config, "utf8"), fns);
|
|
170
|
+
if (changed.length) {
|
|
171
|
+
writeFileSync(config, text);
|
|
172
|
+
for (const fn of changed)
|
|
173
|
+
log(`Added ${STATIC_PATH} to static_files for [functions.${fn}] in supabase/config.toml`);
|
|
174
|
+
}
|
|
175
|
+
else if (fns.length)
|
|
176
|
+
log(`supabase/config.toml already ships it for ${fns.length} function(s).`);
|
|
177
|
+
else
|
|
178
|
+
log("No functions under supabase/functions yet — run this again once you add one.");
|
|
179
|
+
log("Review the diff and commit both files; deploy your functions to use the new rules.");
|
|
180
|
+
return 0;
|
|
181
|
+
}
|
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) {
|