run402 4.162.0 → 4.163.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.
@@ -1,259 +0,0 @@
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
- }