run402 4.160.0 → 4.162.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,259 @@
1
+ /**
2
+ * run402 dev --login <email> — a real project user's sign-in for the local
3
+ * dev server.
4
+ *
5
+ * The user signs in through the project's own emailed code; nothing is
6
+ * minted with the service key. What the token endpoint answers is stored
7
+ * under the CLI's base config directory (never the project directory), one
8
+ * file per project and email, mode 0600. The @run402/astro dev-session
9
+ * middleware is handed that file's path and keeps it fresh itself, so a
10
+ * later `run402 dev --login` reuses it with no new ceremony.
11
+ *
12
+ * A branch is its own project with its own copied users, so a sign-in for
13
+ * `--branch` is a separate file from the parent's.
14
+ */
15
+
16
+ import { createHash } from "node:crypto";
17
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
18
+ import { join } from "node:path";
19
+ import { getConfigBaseDir } from "../core-dist/config.js";
20
+
21
+ /** The variable the @run402/astro adapter reads under `astro dev`: a path, never a token. */
22
+ export const DEV_SESSION_FILE_ENV = "RUN402_DEV_SESSION_FILE";
23
+
24
+ /** The one reusable branch `run402 dev --branch` finds, renews or creates. */
25
+ export const DEV_BRANCH_NAME = "dev";
26
+
27
+ /** A stored session is reused while its access token has at least this left; otherwise it is refreshed first. */
28
+ const REUSE_AHEAD_MS = 120_000;
29
+ /** Renew the dev branch when it would expire within this. */
30
+ const BRANCH_RENEW_AHEAD_MS = 24 * 3_600_000;
31
+
32
+ const emailKey = (email) => createHash("sha256").update(String(email).trim().toLowerCase()).digest("hex").slice(0, 16);
33
+
34
+ export function devSessionsDir(projectId) {
35
+ return join(getConfigBaseDir(), "dev-sessions", projectId);
36
+ }
37
+ export function devSessionPath(projectId, email) {
38
+ return join(devSessionsDir(projectId), `${emailKey(email)}.json`);
39
+ }
40
+ function pendingPath(projectId, email) {
41
+ return join(devSessionsDir(projectId), `${emailKey(email)}.pending.json`);
42
+ }
43
+
44
+ function readJson(path) {
45
+ try {
46
+ return JSON.parse(readFileSync(path, "utf-8"));
47
+ } catch {
48
+ return null;
49
+ }
50
+ }
51
+
52
+ function writePrivate(path, value) {
53
+ const dir = join(path, "..");
54
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
55
+ const tmp = `${path}.${process.pid}.tmp`;
56
+ writeFileSync(tmp, JSON.stringify(value, null, 2) + "\n", { mode: 0o600 });
57
+ renameSync(tmp, path);
58
+ }
59
+
60
+ /** A local failure with the CLI's error shape; `dev.mjs` hands it to `fail()`. */
61
+ export class DevSignInError extends Error {
62
+ constructor(fields) {
63
+ super(fields.message);
64
+ this.fields = fields;
65
+ }
66
+ }
67
+
68
+ function stored(path, projectId) {
69
+ const v = readJson(path);
70
+ const ok =
71
+ v && v.version === 1 && v.project_id === projectId &&
72
+ typeof v.access_token === "string" && typeof v.refresh_token === "string" &&
73
+ typeof v.user?.id === "string" && typeof v.user?.email === "string" &&
74
+ !Number.isNaN(Date.parse(v.access_expires_at));
75
+ return ok ? v : null;
76
+ }
77
+
78
+ function fromTokens({ projectId, parentProjectId, apiBase, target, tokens, now, signedInAt }) {
79
+ return {
80
+ version: 1,
81
+ project_id: projectId,
82
+ // A branch's sign-in names the project it is a branch of, so `--logout` on the parent finds it.
83
+ ...(parentProjectId ? { parent_project_id: parentProjectId } : {}),
84
+ api_base: apiBase,
85
+ target,
86
+ user: {
87
+ id: tokens.user.id,
88
+ email: tokens.user.email,
89
+ email_verified: tokens.user.email_verified_at != null,
90
+ },
91
+ access_token: tokens.access_token,
92
+ refresh_token: tokens.refresh_token,
93
+ access_expires_at: new Date(now + (tokens.expires_in ?? 3600) * 1000).toISOString(),
94
+ signed_in_at: signedInAt ?? new Date(now).toISOString(),
95
+ };
96
+ }
97
+
98
+ const sameEmail = (a, b) => String(a).trim().toLowerCase() === String(b).trim().toLowerCase();
99
+
100
+ /** The command that completes or repeats this sign-in, for hints and next actions. */
101
+ export function loginCommand({ email, target, branchProjectId, code }) {
102
+ const where = target === "branch" ? (branchProjectId ? `--branch ${branchProjectId}` : "--branch") : "--live";
103
+ return `run402 dev --login ${email} ${where}${code ? ` --code ${code}` : ""}`;
104
+ }
105
+
106
+ /**
107
+ * Sign in, or reuse a stored sign-in. Returns
108
+ * { status: "signed_in", path, session, reused } the dev server can start
109
+ * { status: "code_sent", email, command, challenge_id } no terminal: run `command` with the code
110
+ *
111
+ * `prompt` is the terminal's question (absent when there is no terminal);
112
+ * `code` is `--code`. The SDK client must carry the keys of `projectId`.
113
+ */
114
+ export async function devSignIn({ sdk, projectId, parentProjectId, apiBase, email, target, branchProjectId, code, prompt, now = Date.now() }) {
115
+ const path = devSessionPath(projectId, email);
116
+ const pending = pendingPath(projectId, email);
117
+
118
+ if (!code) {
119
+ const kept = stored(path, projectId);
120
+ if (kept && sameEmail(kept.user.email, email)) {
121
+ if (Date.parse(kept.access_expires_at) - now > REUSE_AHEAD_MS) {
122
+ const session = { ...kept, target };
123
+ writePrivate(path, session);
124
+ return { status: "signed_in", path, session, reused: true };
125
+ }
126
+ try {
127
+ const tokens = await sdk.auth.refreshSession(projectId, kept.refresh_token);
128
+ const session = fromTokens({ projectId, parentProjectId, apiBase, target, tokens, now, signedInAt: kept.signed_in_at });
129
+ writePrivate(path, session);
130
+ return { status: "signed_in", path, session, reused: true };
131
+ } catch (err) {
132
+ // The stored session is over (expired, revoked, or spent): a new ceremony replaces it.
133
+ if (err?.status !== 400 && err?.status !== 401) throw err;
134
+ rmSync(path, { force: true });
135
+ }
136
+ }
137
+ }
138
+
139
+ let challengeId;
140
+ let theCode = code;
141
+ if (theCode) {
142
+ const waiting = readJson(pending);
143
+ if (!waiting?.challenge_id) {
144
+ throw new DevSignInError({
145
+ code: "DEV_LOGIN_NO_PENDING_CODE",
146
+ message: `No code is waiting for ${email} on ${projectId}.`,
147
+ hint: `Send one first: ${loginCommand({ email, target, branchProjectId })}`,
148
+ next_actions: [{ type: "authenticate", command: loginCommand({ email, target, branchProjectId }), why: "Sends the sign-in code to the address." }],
149
+ });
150
+ }
151
+ challengeId = waiting.challenge_id;
152
+ } else {
153
+ const sent = await sdk.auth.requestMagicLink(projectId, { email, delivery: "code" });
154
+ challengeId = sent.challengeId;
155
+ if (!challengeId) {
156
+ throw new DevSignInError({
157
+ code: "DEV_LOGIN_CODE_UNAVAILABLE",
158
+ message: `The project did not send a sign-in code to ${email}.`,
159
+ hint: "The project's auth answers email sign-in with a link only. Emailed codes are what `run402 dev --login` signs in with.",
160
+ });
161
+ }
162
+ writePrivate(pending, { challenge_id: challengeId, email, requested_at: new Date(now).toISOString() });
163
+ if (!prompt) {
164
+ const command = loginCommand({ email, target, branchProjectId, code: "<code>" });
165
+ return { status: "code_sent", email, challenge_id: challengeId, command };
166
+ }
167
+ theCode = String(await prompt(`Code sent to ${email}: `)).trim();
168
+ }
169
+
170
+ const tokens = await sdk.auth.verifyEmailCode(projectId, { challengeId, code: theCode });
171
+ rmSync(pending, { force: true });
172
+ const session = fromTokens({ projectId, parentProjectId, apiBase, target, tokens, now });
173
+ writePrivate(path, session);
174
+ return { status: "signed_in", path, session, reused: false };
175
+ }
176
+
177
+ /**
178
+ * End the stored sign-ins of a project and of its branches (one email, or
179
+ * all): the refresh token stops working at the gateway and the file is
180
+ * deleted. `sdkFor(projectId)` gives a client holding that project's keys. A
181
+ * gateway failure still deletes the local file and is reported per entry.
182
+ */
183
+ export async function devSignOut({ sdkFor, projectId, email }) {
184
+ const root = join(getConfigBaseDir(), "dev-sessions");
185
+ const dirs = existsSync(root) ? readdirSync(root) : [];
186
+ const ended = [];
187
+ for (const dir of dirs) {
188
+ const names = readdirSync(join(root, dir)).filter((n) => n.endsWith(".json") && !n.endsWith(".pending.json"));
189
+ for (const name of names) {
190
+ const path = join(root, dir, name);
191
+ const session = stored(path, dir);
192
+ if (!session) continue;
193
+ if (session.project_id !== projectId && session.parent_project_id !== projectId) continue;
194
+ if (email && !sameEmail(session.user.email, email)) continue;
195
+ let revoked = true;
196
+ try {
197
+ await sdkFor(session.project_id).auth.endSession(session.project_id, session.refresh_token);
198
+ } catch {
199
+ revoked = false;
200
+ }
201
+ rmSync(path, { force: true });
202
+ rmSync(`${path}.lock`, { force: true });
203
+ ended.push({ project_id: session.project_id, email: session.user.email, target: session.target, revoked });
204
+ }
205
+ }
206
+ if (email) rmSync(pendingPath(projectId, email), { force: true });
207
+ return ended;
208
+ }
209
+
210
+ /**
211
+ * The branch `run402 dev --branch` runs against: the one named, else the
212
+ * active branch called `dev` (renewed when it expires within a day), else a
213
+ * new one from a fresh live capture. Returns its id, keys and expiry.
214
+ *
215
+ * `sdk` signs as the wallet (branches are an owner or developer action);
216
+ * the branch's keys come from the create answer or the local keystore.
217
+ */
218
+ export async function resolveDevBranch({ sdk, parentProjectId, branchProjectId, now = Date.now(), say = () => {} }) {
219
+ const { branches } = await sdk.branches.list(parentProjectId);
220
+ const active = branches.filter((b) => b.status === "active");
221
+ let branch = branchProjectId
222
+ ? active.find((b) => b.branch_project_id === branchProjectId)
223
+ : active.find((b) => b.name === DEV_BRANCH_NAME);
224
+ if (branchProjectId && !branch) {
225
+ throw new DevSignInError({
226
+ code: "DEV_BRANCH_NOT_FOUND",
227
+ message: `${branchProjectId} is not an active branch of ${parentProjectId}.`,
228
+ hint: `List them with 'run402 branches list --project ${parentProjectId}', or run 'run402 dev --branch' to use the '${DEV_BRANCH_NAME}' branch.`,
229
+ });
230
+ }
231
+ let created = false;
232
+ let keys = null;
233
+ if (!branch) {
234
+ say(` branch: creating '${DEV_BRANCH_NAME}' from a fresh capture of ${parentProjectId} …`);
235
+ const made = await sdk.branches.create(parentProjectId, { name: DEV_BRANCH_NAME });
236
+ branch = made;
237
+ keys = { anon_key: made.anon_key, service_key: made.service_key };
238
+ created = true;
239
+ } else if (Date.parse(branch.expires_at) - now < BRANCH_RENEW_AHEAD_MS) {
240
+ branch = { ...branch, ...(await sdk.branches.renew(parentProjectId, branch.branch_project_id)) };
241
+ }
242
+ if (!keys) keys = await sdk.credentials?.getProjectCredentials?.(branch.branch_project_id) ?? null;
243
+ if (!keys?.anon_key || !keys?.service_key) {
244
+ throw new DevSignInError({
245
+ code: "DEV_BRANCH_KEYS_MISSING",
246
+ message: `This machine does not hold the keys of branch ${branch.branch_project_id}.`,
247
+ hint: `Export them with 'run402 credentials project-keys export --project ${branch.branch_project_id} --reveal', or delete the branch ('run402 branches delete ${branch.branch_project_id} --project ${parentProjectId}') and run 'run402 dev --branch' again to create one here.`,
248
+ });
249
+ }
250
+ return {
251
+ branch_project_id: branch.branch_project_id,
252
+ parent_project_id: parentProjectId,
253
+ name: branch.name,
254
+ expires_at: branch.expires_at,
255
+ email_mode: branch.email_mode,
256
+ created,
257
+ keys: { anon_key: keys.anon_key, service_key: keys.service_key },
258
+ };
259
+ }
package/lib/dev.mjs CHANGED
@@ -11,7 +11,12 @@
11
11
  * SDK's `auth.createTestSession`) and hand it to the child in
12
12
  * RUN402_DEV_TEST_SESSION; the @run402/astro adapter then runs
13
13
  * every request signed in as that test user, under `astro dev` only.
14
- * 4. Spawn `astro dev` as a child process inheriting the env.
14
+ * 4. With `--login <email>`, sign in as a real project user through the
15
+ * project's own emailed code (never the service key), keep the session
16
+ * under the CLI's config directory, and hand the child its path in
17
+ * RUN402_DEV_SESSION_FILE; the adapter refreshes it itself. `--login`
18
+ * names where local code writes: `--live` or `--branch`.
19
+ * 5. Spawn `astro dev` as a child process inheriting the env.
15
20
  *
16
21
  * Beyond that, `run402 dev` is a thin wrapper that ensures the env shape
17
22
  * is right and the Astro dev server starts with Run402 credentials in
@@ -25,6 +30,14 @@ import { resolve } from "node:path";
25
30
  import { fail, reportLocalOrSdkError } from "./sdk-errors.mjs";
26
31
  import { apiBase } from "./config.mjs";
27
32
  import { getSdk } from "./sdk.mjs";
33
+ import {
34
+ DEV_SESSION_FILE_ENV,
35
+ DevSignInError,
36
+ devSignIn,
37
+ devSignOut,
38
+ loginCommand,
39
+ resolveDevBranch,
40
+ } from "./dev-sign-in.mjs";
28
41
 
29
42
  /** The variable the @run402/astro adapter reads under `astro dev`. */
30
43
  export const DEV_TEST_SESSION_ENV = "RUN402_DEV_TEST_SESSION";
@@ -33,6 +46,9 @@ const HELP = `run402 dev — Run Astro dev with Run402 context
33
46
 
34
47
  Usage:
35
48
  run402 dev [--port <n>] [--host <h>] [--project <project_id>] [--as <label>]
49
+ run402 dev --login <email> (--live | --branch [<branch_project_id>]) [--code <code>]
50
+ run402 dev --branch [<branch_project_id>] [--as <label>]
51
+ run402 dev --logout [<email>]
36
52
 
37
53
  Options:
38
54
  --port <n> Astro dev port (default 4321)
@@ -41,6 +57,20 @@ Options:
41
57
  --as <label> Preview signed in as the test user <label>@<project_id>.test.invalid
42
58
  (a watermarked test user, never a real member; needs RUN402_ANON_KEY
43
59
  and the project's test mode, on by default for prototype)
60
+ --login <email> Preview signed in as that real project user. You sign in yourself:
61
+ a code is emailed to the address and you enter it (nothing is minted
62
+ with the service key). The session is kept under the run402 config
63
+ directory, refreshed by the dev server, and reused on the next run.
64
+ Needs a target: --live or --branch.
65
+ --code <code> The emailed code, when no terminal is attached: the first
66
+ 'run402 dev --login' sends the code and exits; run it again with --code.
67
+ --live With --login: local code reads and writes the LIVE project.
68
+ --branch [<id>] Run against a branch of the project instead of the live one: the
69
+ branch named 'dev' (created from a fresh capture when absent, renewed
70
+ near expiry), or the branch you name. A branch has its own copy of the
71
+ users, and reroutes email, sign-in codes included, to the organization
72
+ owner's address.
73
+ --logout [<email>] End the stored sign-ins of this project (one address, or all) and exit.
44
74
 
45
75
  The command:
46
76
  1. Loads .env.local from the current directory (if present)
@@ -49,7 +79,10 @@ The command:
49
79
  (server-side only: the browser never holds the token or the service key),
50
80
  and prints the test user's id for your role table (any user's id:
51
81
  run402 auth users get --email <addr>)
52
- 4. Stops an Astro dev server already running for this project (it keeps
82
+ 4. With --login, signs in (or reuses the stored sign-in) and passes the dev server
83
+ the path of the session file, never a token; prints who is signed in and whether
84
+ local code writes to LIVE or to a branch
85
+ 5. Stops an Astro dev server already running for this project (it keeps
53
86
  the environment it started with), then spawns 'astro dev' with the env
54
87
  inherited. Under an AI agent Astro runs it in the background: stop it
55
88
  with 'npx astro dev stop'
@@ -111,9 +144,91 @@ export async function run(sub, args = []) {
111
144
 
112
145
  process.env.RUN402_PROJECT_ID = projectId;
113
146
 
114
- // Only `--as` may hand the dev server a session; never one inherited from the shell.
147
+ // Only `--as` / `--login` may hand the dev server a session; never one inherited from the shell.
115
148
  delete process.env[DEV_TEST_SESSION_ENV];
149
+ delete process.env[DEV_SESSION_FILE_ENV];
116
150
  const asIndex = all.indexOf("--as");
151
+ const flags = devFlags(all);
152
+
153
+ if (flags.logout) {
154
+ // The project in .env.local signs out with its own keys; a branch of it with the keys this machine's keystore holds.
155
+ const ended = await devSignOut({
156
+ sdkFor: (id) => (id === projectId ? keyedSdk(projectId) : getSdk()),
157
+ projectId,
158
+ email: flags.logout === true ? undefined : flags.logout,
159
+ });
160
+ console.log(JSON.stringify({ project_id: projectId, signed_out: ended }, null, 2));
161
+ return;
162
+ }
163
+
164
+ let target = null;
165
+ let liveProjectId = projectId;
166
+ let branch = null;
167
+ if (flags.branch) {
168
+ try {
169
+ branch = await resolveDevBranch({
170
+ sdk: getSdk(),
171
+ parentProjectId: projectId,
172
+ branchProjectId: flags.branch === true ? undefined : flags.branch,
173
+ say: (line) => console.log(line),
174
+ });
175
+ } catch (err) {
176
+ if (err instanceof DevSignInError) fail(err.fields);
177
+ reportLocalOrSdkError(err);
178
+ }
179
+ // The dev server and every SDK call in it now talk to the branch.
180
+ liveProjectId = branch.branch_project_id;
181
+ process.env.RUN402_PROJECT_ID = branch.branch_project_id;
182
+ process.env.RUN402_ANON_KEY = branch.keys.anon_key;
183
+ process.env.RUN402_SERVICE_KEY = branch.keys.service_key;
184
+ target = "branch";
185
+ } else if (flags.live) {
186
+ target = "live";
187
+ }
188
+
189
+ let signIn = null;
190
+ if (flags.login) {
191
+ if (!process.env.RUN402_ANON_KEY) {
192
+ fail({
193
+ code: "BAD_USAGE",
194
+ message: "Missing RUN402_ANON_KEY.",
195
+ hint: "run402 dev --login signs in with the project's anon key. Add it to .env.local; print the project's keys with 'run402 credentials project-keys export --project <project_id> --reveal'.",
196
+ });
197
+ }
198
+ try {
199
+ const result = await devSignIn({
200
+ sdk: keyedSdk(liveProjectId),
201
+ projectId: liveProjectId,
202
+ parentProjectId: branch ? projectId : undefined,
203
+ apiBase: apiBase(),
204
+ email: flags.login,
205
+ target,
206
+ branchProjectId: flags.branch === true ? undefined : flags.branch || undefined,
207
+ code: flags.code,
208
+ prompt: !flags.code && process.stdin.isTTY && process.stdout.isTTY ? askLine : undefined,
209
+ });
210
+ if (result.status === "code_sent") {
211
+ console.log(JSON.stringify({
212
+ project_id: liveProjectId,
213
+ email: result.email,
214
+ target,
215
+ code_sent: true,
216
+ signed_in: false,
217
+ message: branch && branch.email_mode !== "off"
218
+ ? `A sign-in code for ${result.email} was sent. This is a branch: its email is rerouted to the organization owner's address.`
219
+ : `A sign-in code was sent to ${result.email}.`,
220
+ next_actions: [{ type: "authenticate", command: result.command, why: "Completes the sign-in with the emailed code and starts the dev server." }],
221
+ }, null, 2));
222
+ return;
223
+ }
224
+ signIn = result;
225
+ } catch (err) {
226
+ if (err instanceof DevSignInError) fail(err.fields);
227
+ reportLocalOrSdkError(err);
228
+ }
229
+ process.env[DEV_SESSION_FILE_ENV] = signIn.path;
230
+ }
231
+
117
232
  let signedInAs = null;
118
233
  if (asIndex !== -1) {
119
234
  const label = all[asIndex + 1];
@@ -132,7 +247,8 @@ export async function run(sub, args = []) {
132
247
  }
133
248
  try {
134
249
  signedInAs = await mintDevTestSession({
135
- projectId,
250
+ // With --branch the keys in the environment are the branch's, and so is the test user.
251
+ projectId: liveProjectId,
136
252
  label,
137
253
  keys: { anon_key: process.env.RUN402_ANON_KEY, service_key: process.env.RUN402_SERVICE_KEY },
138
254
  });
@@ -151,7 +267,7 @@ export async function run(sub, args = []) {
151
267
  process.env[DEV_TEST_SESSION_ENV] = JSON.stringify(signedInAs);
152
268
  }
153
269
 
154
- for (const line of devBanner({ host, port, projectId, apiBase: apiBase(), envLoaded: existsSync(envFile), signedInAs })) {
270
+ for (const line of devBanner({ host, port, projectId: liveProjectId, apiBase: apiBase(), envLoaded: existsSync(envFile), signedInAs, signIn, branch })) {
155
271
  console.log(line);
156
272
  }
157
273
  // A dev server Astro already runs for this project keeps the environment it
@@ -193,7 +309,7 @@ export async function run(sub, args = []) {
193
309
  * user's id rides beside its email with a role-row hint, because an app's
194
310
  * role table is keyed by user id and nothing else shows it.
195
311
  */
196
- export function devBanner({ host, port, projectId, apiBase, envLoaded, signedInAs }) {
312
+ export function devBanner({ host, port, projectId, apiBase, envLoaded, signedInAs, signIn, branch }) {
197
313
  const lines = [
198
314
  `run402 dev — Astro on http://${host}:${port}`,
199
315
  ` project: ${projectId}`,
@@ -208,6 +324,21 @@ export function devBanner({ host, port, projectId, apiBase, envLoaded, signedInA
208
324
  ` give it a role: run402 projects sql "INSERT INTO <role_table> (user_id, role) VALUES ('${id}', '<role>')"`,
209
325
  );
210
326
  }
327
+ if (signIn) {
328
+ const { id, email } = signIn.session.user;
329
+ lines.push(
330
+ ` signed in as: ${email} (real user${signIn.reused ? ", stored sign-in" : ""})`,
331
+ ` user id: ${id}`,
332
+ );
333
+ }
334
+ if (branch) {
335
+ lines.push(` writes to: branch of ${branch.parent_project_id} (${branch.branch_project_id}, expires ${branch.expires_at})`);
336
+ if (signIn && branch.email_mode !== "off") {
337
+ lines.push(" branch email: rerouted to the organization owner's address, sign-in codes included");
338
+ }
339
+ } else if (signIn) {
340
+ lines.push(` writes to: LIVE ${projectId}`);
341
+ }
211
342
  return lines;
212
343
  }
213
344
 
@@ -282,6 +413,69 @@ export function restartRunningDevServer(cwd, { run = (cmd, args) => spawnSync(cm
282
413
  return running;
283
414
  }
284
415
 
416
+ /** An SDK client that holds only the keys the dev server runs on, for the project's own auth routes. */
417
+ function keyedSdk(projectId) {
418
+ const keys = { anon_key: process.env.RUN402_ANON_KEY, service_key: process.env.RUN402_SERVICE_KEY };
419
+ return getSdk({
420
+ credentials: {
421
+ getAuth: async () => null,
422
+ getProjectCredentials: async (id) => (id === projectId ? keys : null),
423
+ },
424
+ });
425
+ }
426
+
427
+ async function askLine(question) {
428
+ const { createInterface } = await import("node:readline/promises");
429
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
430
+ try {
431
+ return await rl.question(question);
432
+ } finally {
433
+ rl.close();
434
+ }
435
+ }
436
+
437
+ /**
438
+ * The identity and target flags, checked together before anything is sent:
439
+ * `--login` needs exactly one of `--live` / `--branch`, and never rides with `--as`.
440
+ */
441
+ export function devFlags(all) {
442
+ const optional = (flag, looksLikeValue) => {
443
+ const i = all.indexOf(flag);
444
+ if (i === -1) return null;
445
+ const next = all[i + 1];
446
+ return next && !next.startsWith("--") && looksLikeValue(next) ? next : true;
447
+ };
448
+ const login = pickFlagValue(all, "--login");
449
+ const code = pickFlagValue(all, "--code");
450
+ const live = all.includes("--live");
451
+ const branch = optional("--branch", (v) => v.startsWith("prj_"));
452
+ const logout = optional("--logout", (v) => v.includes("@"));
453
+ const usage = (message, next) => fail({
454
+ code: "BAD_USAGE",
455
+ message,
456
+ ...(next ? { next_actions: next.map((command) => ({ type: "edit_request", command, why: "A complete form of this command." })) } : {}),
457
+ });
458
+ if (all.includes("--login")) {
459
+ if (!login || login.startsWith("--") || !login.includes("@")) {
460
+ usage("--login needs the email of a project user, e.g. `run402 dev --login you@example.com --live`.");
461
+ }
462
+ if (all.includes("--as")) usage("--login and --as are two identities: a real user and a test user. Pass one.");
463
+ if (live === Boolean(branch)) {
464
+ usage(
465
+ live
466
+ ? "--live and --branch are two targets. Pass one."
467
+ : "--login needs a target: --live writes to the live project, --branch to a branch of it.",
468
+ [loginCommand({ email: login, target: "live" }), loginCommand({ email: login, target: "branch" })],
469
+ );
470
+ }
471
+ } else {
472
+ if (code) usage("--code completes a sign-in: pass it with --login <email>.");
473
+ if (live && branch) usage("--live and --branch are two targets. Pass one.");
474
+ }
475
+ if (all.includes("--code") && (!code || !/^\d{6}$/.test(code))) usage("--code is the six-digit code from the email.");
476
+ return { login: all.includes("--login") ? login : null, code: code ?? null, live, branch, logout };
477
+ }
478
+
285
479
  function pickFlagValue(args, flag) {
286
480
  const idx = args.indexOf(flag);
287
481
  if (idx === -1) return undefined;