@join-pantheon/cli 0.36.0-rc.1 → 0.37.0-rc.1

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,6 +1,6 @@
1
1
  const ESC = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
2
2
  const esc = (s) => s.replace(/[&<>"']/g, (c) => ESC[c]);
3
- export function codeEmailHtml(code, purpose) {
3
+ export function codeEmailHtml(code, purpose, link) {
4
4
  const eyebrow = purpose === "signup" ? "Confirm your email" : "New device sign-in";
5
5
  const action = purpose === "signup" ? "confirm your email and finish signing up" : "add this device to your account";
6
6
  const why = purpose === "signup" ? "sign up for Pantheon" : "sign in to Pantheon";
@@ -39,6 +39,10 @@ export function codeEmailHtml(code, purpose) {
39
39
  <p style="margin:22px 0 0;font-family:'Space Mono',Menlo,Consolas,'Liberation Mono',monospace;font-size:15px;line-height:1.65;color:#26221f">Enter it where the terminal is waiting, to ${action}. Or run:</p>
40
40
  </td></tr>
41
41
  <tr><td class="px" style="padding:12px 40px 6px"><table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%"><tr><td style="background:#1b1917;border-radius:8px;padding:13px 16px;font-family:'Space Mono',Menlo,Consolas,'Liberation Mono',monospace;font-size:14px;line-height:1.75;color:#f1e7d3;word-break:break-all"><span style="color:#e36f55">$</span> pantheon verify ${code}</td></tr></table></td></tr>
42
+ ${link ? ` <tr><td class="px" style="padding:18px 40px 6px">
43
+ <p style="margin:0 0 12px;font-family:'Space Mono',Menlo,Consolas,'Liberation Mono',monospace;font-size:15px;line-height:1.65;color:#26221f">Or confirm in your browser. You will type the two words your screen shows.</p>
44
+ <a href="${esc(link)}" style="display:inline-block;background:#e36f55;color:#1b1917;border-radius:8px;padding:12px 20px;font-family:'Space Mono',Menlo,Consolas,monospace;font-size:15px;font-weight:700;text-decoration:none">Confirm it's you</a>
45
+ </td></tr>` : ""}
42
46
  <tr><td class="px" style="padding:22px 40px 32px">
43
47
  <p style="margin:0;padding-top:18px;border-top:1px solid #ddd0b6;font-family:'Space Mono',Menlo,Consolas,'Liberation Mono',monospace;font-size:13px;line-height:1.65;color:#6b6257">
44
48
  Expires in 10 minutes. Works once.<br>
@@ -64,7 +68,7 @@ export function codeEmailHtml(code, purpose) {
64
68
  }
65
69
  export const WELCOME_SUBJECT = "Welcome to Pantheon";
66
70
  export const WELCOME_REPLY_TO = ["praneet@joinpantheon.network", "sid@joinpantheon.network"];
67
- export function welcomeEmailHtml(to) {
71
+ export function welcomeEmailHtml(to, joining) {
68
72
  const email = esc(to);
69
73
  return `<!doctype html>
70
74
  <html lang="en">
@@ -83,7 +87,7 @@ export function welcomeEmailHtml(to) {
83
87
  </style>
84
88
  </head>
85
89
  <body style="margin:0;padding:0;background:#ebe2d0">
86
- <div style="display:none;max-height:0;overflow:hidden;opacity:0">One teammate and one ask get you to your first hand-off.&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;</div>
90
+ <div style="display:none;max-height:0;overflow:hidden;opacity:0">${joining !== undefined ? `You're joining ${joining ? esc(joining) : "your teammate's team"}. One ask gets you to your first hand-off.` : "One teammate and one ask get you to your first hand-off."}&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;</div>
87
91
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#ebe2d0">
88
92
  <tr><td align="center" style="padding:32px 12px 40px">
89
93
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="max-width:600px;width:100%">
@@ -157,9 +161,12 @@ export function welcomeEmailHtml(to) {
157
161
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="font-family:'Space Mono',Menlo,Consolas,monospace;font-size:14px;line-height:1.6;color:#26221f">
158
162
  <tr>
159
163
  <td width="34" valign="top" style="padding:2px 0 16px"><span style="display:inline-block;width:24px;height:24px;line-height:24px;border-radius:12px;background:#e0aa3e;color:#1b1917;font-weight:700;text-align:center;font-size:13px">1</span></td>
160
- <td valign="top" style="padding:2px 0 16px"><b>Bring one teammate.</b> Run:
164
+ <td valign="top" style="padding:2px 0 16px">${joining !== undefined
165
+ ? `<b>You're joining ${joining ? esc(joining) : "your teammate's team"}.</b> Once it finishes, your agent can reach your teammates' agents.
166
+ <span style="color:#6b6257">If your coding agent was open while you joined, quit and reopen it once.</span>`
167
+ : `<b>Bring one teammate.</b> Run:
161
168
  <table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="margin-top:8px"><tr><td style="background:#1b1917;border-radius:8px;padding:12px 16px;font-family:'Space Mono',Menlo,Consolas,monospace;font-size:14px;color:#f1e7d3"><span style="color:#e36f55">$</span> pantheon invite</td></tr></table>
162
- <span style="color:#6b6257">It prints a link that works once, for 24 hours. Send it to them.</span></td>
169
+ <span style="color:#6b6257">It prints a link that works once, for 24 hours. Send it to them.</span>`}</td>
163
170
  </tr>
164
171
  <tr>
165
172
  <td width="34" valign="top" style="padding:2px 0 8px"><span style="display:inline-block;width:24px;height:24px;line-height:24px;border-radius:12px;background:#e0aa3e;color:#1b1917;font-weight:700;text-align:center;font-size:13px">2</span></td>
@@ -196,7 +203,7 @@ export function welcomeEmailHtml(to) {
196
203
  </html>
197
204
  `;
198
205
  }
199
- export function welcomeEmailText(to) {
206
+ export function welcomeEmailText(to, joining) {
200
207
  return [
201
208
  "Welcome to Pantheon.",
202
209
  "",
@@ -205,8 +212,11 @@ export function welcomeEmailText(to) {
205
212
  "Watch how it works (1:34): https://www.joinpantheon.network/#film",
206
213
  "",
207
214
  "Your first hand-off:",
208
- "1. Bring one teammate. Run: pantheon invite",
209
- " It prints a link that works once, for 24 hours. Send it to them.",
215
+ ...(joining !== undefined
216
+ ? [`1. You're joining ${joining || "your teammate's team"}. Once it finishes, your agent can reach your teammates' agents.`,
217
+ " If your coding agent was open while you joined, quit and reopen it once."]
218
+ : ["1. Bring one teammate. Run: pantheon invite",
219
+ " It prints a link that works once, for 24 hours. Send it to them."]),
210
220
  "2. Hand something off. Tell your agent, in your own words:",
211
221
  " \"Ask my teammate's agent to take the failing checkout test, due Friday.\"",
212
222
  "",
package/dist/email.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { codeEmailHtml, viewerCodeEmailHtml, viewerCodeEmailText, viewerCodeSubject, viewerInviteEmailHtml, viewerInviteEmailText, viewerInviteSubject, WELCOME_REPLY_TO, WELCOME_SUBJECT, welcomeEmailHtml, welcomeEmailText } from "./email-templates.js";
2
- function subjectAndBody(code, purpose) {
2
+ function subjectAndBody(code, purpose, link) {
3
3
  const action = purpose === "signup" ? "confirm your email and finish signing up" : "add this device to your account";
4
4
  const eyebrow = purpose === "signup" ? "Confirm your email" : "New device sign-in";
5
5
  const subject = `Your Pantheon code: ${code}`;
@@ -11,12 +11,13 @@ function subjectAndBody(code, purpose) {
11
11
  `Enter it where the terminal is waiting, to ${action}. Or run:`,
12
12
  ` pantheon verify ${code}`,
13
13
  ``,
14
+ ...(link ? [`Or confirm in your browser — you will type the two words your screen shows:`, ` ${link}`, ``] : []),
14
15
  `The code expires in 10 minutes and works once. If you did not ask for it,`,
15
16
  `ignore this email: nothing happens without the code.`,
16
17
  ``,
17
18
  `joinpantheon.network — your AI can talk to theirs`,
18
19
  ].join("\n");
19
- return { subject, text, html: codeEmailHtml(code, purpose) };
20
+ return { subject, text, html: codeEmailHtml(code, purpose, link) };
20
21
  }
21
22
  class ResendSender {
22
23
  apiKey;
@@ -28,8 +29,8 @@ class ResendSender {
28
29
  this.from = from;
29
30
  this.log = log;
30
31
  }
31
- async sendCode(to, code, purpose) {
32
- const { subject, text, html } = subjectAndBody(code, purpose);
32
+ async sendCode(to, code, purpose, link) {
33
+ const { subject, text, html } = subjectAndBody(code, purpose, link);
33
34
  try {
34
35
  const res = await fetch("https://api.resend.com/emails", {
35
36
  method: "POST",
@@ -47,12 +48,12 @@ class ResendSender {
47
48
  return false;
48
49
  }
49
50
  }
50
- async sendWelcome(to) {
51
+ async sendWelcome(to, joining) {
51
52
  try {
52
53
  const res = await fetch("https://api.resend.com/emails", {
53
54
  method: "POST",
54
55
  headers: { "content-type": "application/json", authorization: `Bearer ${this.apiKey}` },
55
- body: JSON.stringify({ from: this.from, to, subject: WELCOME_SUBJECT, text: welcomeEmailText(to), html: welcomeEmailHtml(to), reply_to: WELCOME_REPLY_TO }),
56
+ body: JSON.stringify({ from: this.from, to, subject: WELCOME_SUBJECT, text: welcomeEmailText(to, joining), html: welcomeEmailHtml(to, joining), reply_to: WELCOME_REPLY_TO }),
56
57
  signal: AbortSignal.timeout(10_000),
57
58
  });
58
59
  if (!res.ok)
@@ -111,12 +112,12 @@ class LogSender {
111
112
  constructor(log) {
112
113
  this.log = log;
113
114
  }
114
- async sendCode(to, code, purpose) {
115
- this.log(` [no email provider] ${purpose} code for ${to}: ${code} (set RESEND_API_KEY + PANTHEON_EMAIL_FROM to send real email)`);
115
+ async sendCode(to, code, purpose, link) {
116
+ this.log(` [no email provider] ${purpose} code for ${to}: ${code}${link ? ` link: ${link}` : ""} (set RESEND_API_KEY + PANTHEON_EMAIL_FROM to send real email)`);
116
117
  return true;
117
118
  }
118
- async sendWelcome(to) {
119
- this.log(` [no email provider] welcome email to ${maskEmail(to)}`);
119
+ async sendWelcome(to, joining) {
120
+ this.log(` [no email provider] welcome email to ${maskEmail(to)}${joining !== undefined ? ` (joining ${joining || "a team"})` : ""}`);
120
121
  return true;
121
122
  }
122
123
  async sendNotice(to, subject, _text) {
@@ -34,7 +34,7 @@ export function finishItems(f) {
34
34
  else
35
35
  out.push({ says: r.says, fix: r.fix });
36
36
  }
37
- const rowSaid = out.some((i) => /^The worker is installed but not running/.test(i.says));
37
+ const rowSaid = out.some((i) => /^The worker is installed but not running|^worker was not set up/.test(i.says));
38
38
  if (f.workerWanted && (f.served ?? 0) > 0 && f.worker && !(f.worker.installed && f.worker.loaded) && !rowSaid) {
39
39
  out.push(f.worker.installed
40
40
  ? { says: "Your worker is installed but not running, so teammates' requests wait for you while you're away.", fix: "pantheon service restart worker" }
@@ -0,0 +1,305 @@
1
+ import { isGithubNoreply, usernameSuggestion } from "./onboard-defaults.js";
2
+ import { validEmail, validUsername, normalizeEmail } from "./accounts.js";
3
+ export const RESUME_MS = 30 * 60_000;
4
+ export const CODE_REUSE_MS = 9 * 60_000;
5
+ const SPAM = "Not there in a minute? Check your spam folder.";
6
+ export const SIGNIN_FLAGS = ["email", "username", "code"];
7
+ export const SIGNIN_SWITCHES = ["resend"];
8
+ export function resumeArgs(argv) {
9
+ const out = [];
10
+ for (let i = 1; i < argv.length; i++) {
11
+ const a = argv[i];
12
+ if (a === "--email" || a === "--username" || a === "--code") {
13
+ i++;
14
+ continue;
15
+ }
16
+ if (a === "--resend" || a === "--continue" || a === "--json")
17
+ continue;
18
+ out.push(a);
19
+ }
20
+ return out;
21
+ }
22
+ export function resumedArgv(argv, pending, now) {
23
+ const cmd = argv[0];
24
+ if (cmd !== "join" && cmd !== "start")
25
+ return null;
26
+ const r = pending?.resume;
27
+ if (!r || r.cmd !== cmd || !(now - r.at < RESUME_MS) || now < r.at - 60_000)
28
+ return null;
29
+ const has = (f) => argv.includes(f);
30
+ const followUp = has("--code") || has("--continue") || has("--resend") || has("--username");
31
+ if (cmd === "join") {
32
+ if (argv[1] && !argv[1].startsWith("--"))
33
+ return null;
34
+ if (!followUp && !has("--email"))
35
+ return null;
36
+ const pos = positionals(argv.slice(1));
37
+ if (pos.length) {
38
+ const savedFlags = r.args[0] && !r.args[0].startsWith("--") ? r.args.slice(1) : r.args;
39
+ const rest = argv.slice(1).filter((_, i) => !pos.includes(i));
40
+ return [cmd, argv[1 + pos[0]], ...mergeArgs(savedFlags, rest)];
41
+ }
42
+ }
43
+ else if (!followUp)
44
+ return null;
45
+ return [cmd, ...mergeArgs(r.args, argv.slice(1))];
46
+ }
47
+ export const INVITE_SHAPE = /^(?:https?:\/\/(?:www\.)?joinpantheon\.network\/join\/[^\s#]+|pantheons?:\/\/[^\s#]+)#\S+$/i;
48
+ const VALUELESS = /^--(json|yes|resend|continue|reset|new-team|may-wake|unattended|allow-bash|portable|local|here|approve-all|ask-before-sending|questions|no-[a-z-]+)$/;
49
+ export function inviteIndexes(args) {
50
+ const out = [];
51
+ for (let i = 0; i < args.length; i++) {
52
+ const a = args[i];
53
+ if (a.startsWith("--")) {
54
+ const v = args[i + 1];
55
+ if (!VALUELESS.test(a) && v !== undefined && !v.startsWith("--") && !INVITE_SHAPE.test(v))
56
+ i++;
57
+ }
58
+ else
59
+ out.push(i);
60
+ }
61
+ return out;
62
+ }
63
+ const positionals = inviteIndexes;
64
+ export function mergeArgs(saved, now) {
65
+ const groups = (args) => {
66
+ const out = [];
67
+ for (let i = 0; i < args.length; i++) {
68
+ const a = args[i];
69
+ if (a.startsWith("--")) {
70
+ const v = args[i + 1];
71
+ if (v !== undefined && !v.startsWith("--")) {
72
+ out.push({ name: a, tokens: [a, v] });
73
+ i++;
74
+ }
75
+ else
76
+ out.push({ name: a, tokens: [a] });
77
+ }
78
+ else
79
+ out.push({ name: null, tokens: [a] });
80
+ }
81
+ return out;
82
+ };
83
+ const mine = groups(now);
84
+ const given = new Set(mine.map((g) => g.name).filter((n) => n !== null));
85
+ const kept = groups(saved).filter((g) => g.name === null || !given.has(g.name));
86
+ return [...kept.flatMap((g) => g.tokens), ...mine.flatMap((g) => g.tokens)];
87
+ }
88
+ function next(cmd, deps, what, email) {
89
+ return what === "code"
90
+ ? deps.command(`${cmd} --code <the 6-digit code>`)
91
+ : deps.command(`${cmd} --email ${email} --username <a username>`);
92
+ }
93
+ export async function requestCode(o) {
94
+ const { deps, cmd } = o;
95
+ const email = o.email.trim();
96
+ if (!validEmail(email))
97
+ return { kind: "error", exit: "usage", message: `"${email}" does not look like an email address — use the one you read mail at` };
98
+ if (isGithubNoreply(email))
99
+ return { kind: "error", exit: "usage", message: "that is GitHub's no-reply address: mail sent there goes nowhere, so the code would never arrive — use the email you read" };
100
+ if (o.username !== undefined && !validUsername(o.username.trim().toLowerCase())) {
101
+ return { kind: "error", exit: "usage", message: "username must be 2–32 characters: letters, digits, . _ - (not at the ends)" };
102
+ }
103
+ const prior = deps.identity();
104
+ if (prior?.account) {
105
+ if (normalizeEmail(prior.account.email) === normalizeEmail(email))
106
+ return { kind: "signed_in", account: prior.account, resume: o.resume, already: true };
107
+ return { kind: "error", exit: "failed", message: `this machine is signed in as ${prior.account.username} <${prior.account.email}>, not ${email}. To use another account here, sign this machine out first: ${deps.command("logout")}` };
108
+ }
109
+ const withKey = deps.saveLocked((cur) => cur?.publicKey && cur.privateKey ? cur
110
+ : { ...(cur ?? { relay: "", member: "me", space: "", token: "" }), ...deps.newKeypair() });
111
+ const pubkey = withKey.publicKey;
112
+ const pend = withKey.pendingAuth;
113
+ const live = pend && normalizeEmail(pend.email) === normalizeEmail(email) && typeof pend.at === "number" && deps.now() - pend.at < CODE_REUSE_MS
114
+ && (o.username === undefined || pend.purpose !== "signup" || o.username.trim() === pend.username);
115
+ if (live && !o.resend) {
116
+ deps.saveLocked((cur) => ({ ...(cur ?? withKey), pendingAuth: { ...pend, resume: o.resume } }));
117
+ const mins = Math.max(1, Math.round((deps.now() - pend.at) / 60_000));
118
+ return codeSent(cmd, deps, { email, username: pend.username, account: pend.purpose === "signup" ? "new" : "existing", reused: mins, ...(pend.words ? { words: pend.words } : {}) });
119
+ }
120
+ const login = await deps.post("/auth/login", { email, pubkey, label: deps.label, link: true });
121
+ if (!login)
122
+ return { kind: "error", exit: "network", message: `could not reach the relay: ${deps.unreachable()}` };
123
+ let purpose = "login";
124
+ let res = login;
125
+ let username;
126
+ const noAccount = login.status === 404 && (login.j.reason === "no_such_account" || /no active account/i.test(String(login.j.error ?? "")));
127
+ if (login.status === 404 && !noAccount) {
128
+ return { kind: "error", exit: "failed", message: "this relay has no email accounts — no sign-in is needed: run the same command without --email" };
129
+ }
130
+ if (noAccount) {
131
+ if (o.username === undefined) {
132
+ const suggested = usernameSuggestion(email, deps.gitEmail) || null;
133
+ saveResumeOnly(deps, withKey, email, o.resume);
134
+ return needsUsername(cmd, deps, email, suggested, `there is no Pantheon account for ${email} yet.`);
135
+ }
136
+ username = o.username.trim();
137
+ purpose = "signup";
138
+ const up = await deps.post("/auth/signup", { email, username, pubkey, label: deps.label, link: true, ...(o.joining ? { joining: o.joining } : {}) });
139
+ if (!up)
140
+ return { kind: "error", exit: "network", message: `could not reach the relay: ${deps.unreachable()}` };
141
+ res = up;
142
+ if (up.j.reason === "username_taken" || up.j.reason === "bad_username") {
143
+ saveResumeOnly(deps, withKey, email, o.resume);
144
+ const suggested = usernameSuggestion(email, deps.gitEmail, 10 + Math.floor(Math.random() * 90)) || null;
145
+ return needsUsername(cmd, deps, email, suggested, `the username "${username}" ${up.j.reason === "username_taken" ? "is taken" : "cannot be used"}.`);
146
+ }
147
+ if (up.j.reason === "email_taken") {
148
+ const again = await deps.post("/auth/login", { email, pubkey, label: deps.label, link: true });
149
+ if (!again)
150
+ return { kind: "error", exit: "network", message: `could not reach the relay: ${deps.unreachable()}` };
151
+ res = again;
152
+ purpose = "login";
153
+ username = undefined;
154
+ }
155
+ }
156
+ const tooSoon = res.j.reason === "too_soon";
157
+ const pendNow = tooSoon ? deps.identity()?.pendingAuth ?? pend : pend;
158
+ if (res.status !== 200 && !tooSoon) {
159
+ return { kind: "error", exit: "failed", message: String(res.j.error ?? `sign-in failed (${res.status})`) };
160
+ }
161
+ if (tooSoon && !(pendNow && typeof pendNow.at === "number" && normalizeEmail(pendNow.email) === normalizeEmail(email))) {
162
+ return { kind: "error", exit: "failed", message: `a code for ${email} was asked for a moment ago from another device, and it would not work on this one. Wait a minute, then run this again.` };
163
+ }
164
+ if (res.status === 200 && res.j.sent === false && res.j.via === "resend") {
165
+ return { kind: "error", exit: "failed", message: "the relay could not send the email just now — run the same command again in a minute" };
166
+ }
167
+ const at = tooSoon && pendNow?.at ? pendNow.at : deps.now();
168
+ const words = typeof res.j.words === "string" && /^[a-z]+ [a-z]+$/.test(res.j.words) ? res.j.words : tooSoon ? pendNow?.words : undefined;
169
+ const aud = typeof res.j.status_aud === "string" && /^[A-Za-z0-9.:\[\]-]{1,255}$/.test(res.j.status_aud) ? res.j.status_aud : tooSoon ? pendNow?.aud : undefined;
170
+ deps.saveLocked((cur) => ({
171
+ ...(cur ?? withKey),
172
+ ...(username ? { member: username } : {}),
173
+ pendingAuth: { email, ...(username ? { username } : {}), purpose, at, ...(words ? { words } : {}), ...(aud ? { aud } : {}), resume: o.resume },
174
+ }));
175
+ return codeSent(cmd, deps, {
176
+ email, username, account: purpose === "signup" ? "new" : "existing", ...(words ? { words } : {}),
177
+ ...(tooSoon ? { reused: Math.max(1, Math.round((deps.now() - at) / 60_000)) } : {}),
178
+ dev: res.j.via !== undefined && res.j.via !== "resend",
179
+ });
180
+ }
181
+ function saveResumeOnly(deps, withKey, email, resume) {
182
+ deps.saveLocked((cur) => ({ ...(cur ?? withKey), pendingAuth: { email, purpose: "signup", resume } }));
183
+ }
184
+ function codeSent(cmd, deps, s) {
185
+ const nxt = next(cmd, deps, "code");
186
+ const cont = deps.command(`${cmd} --continue`);
187
+ const head = s.reused
188
+ ? `A code was sent to ${s.email} ${s.reused} min ago — use that one. ${SPAM}`
189
+ : `Sent a 6-digit code to ${s.email}. ${SPAM}${s.dev ? " (A dev relay: the code is in its log.)" : ""}`;
190
+ const who = s.account === "new" ? `This makes a new account, ${s.username}.` : `This signs this computer in to your account.`;
191
+ return {
192
+ kind: "needs_person", needs: "code",
193
+ lines: [head, who, `When the person has the code, run: ${nxt}`,
194
+ ...(s.words ? [`Or they open the link in that email and type these two words there: ${s.words.toUpperCase()} — then run: ${cont}`] : []),
195
+ `Wrong address? Run the first command again with the right --email.`],
196
+ json: {
197
+ needs: "code", sent_to: s.email, account: s.account,
198
+ ...(s.username ? { username: s.username } : {}),
199
+ ...(s.reused ? { reused: true } : {}),
200
+ next: nxt,
201
+ ...(s.words ? { link: true, words: s.words, next_link: cont } : {}),
202
+ },
203
+ };
204
+ }
205
+ function needsUsername(cmd, deps, email, suggested, why) {
206
+ const nxt = next(cmd, deps, "username", email);
207
+ return {
208
+ kind: "needs_person", needs: "username",
209
+ lines: [
210
+ `${why} Ask the person for the username teammates will see — it cannot be changed later.${suggested ? ` Suggested: ${suggested}` : ""}`,
211
+ `Then run: ${nxt}`,
212
+ ],
213
+ json: { needs: "username", email, suggested, next: nxt },
214
+ };
215
+ }
216
+ export async function enterCode(o) {
217
+ const { deps, cmd } = o;
218
+ const prior = deps.identity();
219
+ if (prior?.account)
220
+ return { kind: "signed_in", account: prior.account, resume: prior.pendingAuth?.resume, already: true };
221
+ const pend = prior?.pendingAuth;
222
+ if (!prior?.publicKey || !pend) {
223
+ return { kind: "error", exit: "usage", message: `nothing is waiting for a code on this machine — start with: ${deps.command(`${cmd}${cmd === "join" ? " '<your invite link>'" : ""} --email you@work.com`)}` };
224
+ }
225
+ if (typeof pend.at !== "number") {
226
+ return { kind: "error", exit: "usage", message: `no code has been sent yet — a username is needed first: ${deps.command(`${cmd} --email ${pend.email} --username <a username>`)}` };
227
+ }
228
+ const code = o.code.trim();
229
+ if (!/^\d{6}$/.test(code))
230
+ return { kind: "error", exit: "usage", message: "the code is the 6 digits from the email" };
231
+ const v = await deps.post("/auth/verify", { email: pend.email, code, pubkey: prior.publicKey });
232
+ if (!v)
233
+ return { kind: "error", exit: "network", message: `could not reach the relay: ${deps.unreachable()} — the same code still works; run this again` };
234
+ if (v.status === 200) {
235
+ const acct = v.j.account;
236
+ deps.saveLocked((cur) => {
237
+ const c = { ...(cur ?? prior), member: acct.username, account: { username: acct.username, email: acct.email, verified_at: deps.now() } };
238
+ if (pend.resume)
239
+ c.pendingAuth = { email: pend.email, purpose: pend.purpose, resume: pend.resume };
240
+ else
241
+ delete c.pendingAuth;
242
+ return c;
243
+ });
244
+ return { kind: "signed_in", account: acct, resume: pend.resume };
245
+ }
246
+ const spent = v.j.reason === "expired" || v.j.reason === "too_many_attempts" || v.j.reason === "no_pending" || v.j.tries_left === 0;
247
+ const again = spent ? deps.command(`${cmd} --email ${pend.email} --resend`) : next(cmd, deps, "code");
248
+ return {
249
+ kind: "needs_person", needs: "code",
250
+ lines: [`${String(v.j.error ?? "that code is not right")}.`, spent ? `Get a new code: ${again}` : `Try again: ${again}`],
251
+ json: { needs: "code", sent_to: pend.email, retry: !spent, ...(typeof v.j.tries_left === "number" ? { tries_left: v.j.tries_left } : {}), next: again },
252
+ };
253
+ }
254
+ export const CONTINUE_WAIT_MS = 90_000;
255
+ export const CONTINUE_EVERY_MS = 5_000;
256
+ export async function awaitLink(o) {
257
+ const { deps, cmd } = o;
258
+ const prior = deps.identity();
259
+ if (prior?.account)
260
+ return { kind: "signed_in", account: prior.account, resume: prior.pendingAuth?.resume, already: true };
261
+ const pend = prior?.pendingAuth;
262
+ if (!prior?.publicKey || !pend || typeof pend.at !== "number" || !deps.status) {
263
+ return { kind: "error", exit: "usage", message: `nothing is waiting to be confirmed on this machine — start with: ${deps.command(`${cmd}${cmd === "join" ? " '<your invite link>'" : ""} --email you@work.com`)}` };
264
+ }
265
+ const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
266
+ const until = deps.now() + (o.waitMs ?? CONTINUE_WAIT_MS);
267
+ let reached = false;
268
+ for (;;) {
269
+ const r = await deps.status();
270
+ if (r) {
271
+ reached = true;
272
+ if (r.status === 200 && r.j.state === "confirmed") {
273
+ const acct = r.j.account;
274
+ if (normalizeEmail(acct.email) !== normalizeEmail(pend.email)) {
275
+ return { kind: "error", exit: "failed", message: `this machine was signed in to a different account (${acct.email}) than the one asked for (${pend.email}) — run pantheon whoami, and sign out with pantheon logout if it is not yours` };
276
+ }
277
+ deps.saveLocked((cur) => {
278
+ const c = { ...(cur ?? prior), member: acct.username, account: { username: acct.username, email: acct.email, verified_at: deps.now() } };
279
+ if (pend.resume)
280
+ c.pendingAuth = { email: pend.email, purpose: pend.purpose, resume: pend.resume };
281
+ else
282
+ delete c.pendingAuth;
283
+ return c;
284
+ });
285
+ return { kind: "signed_in", account: acct, resume: pend.resume };
286
+ }
287
+ if (r.status === 200 && r.j.state === "none") {
288
+ const again = deps.command(`${cmd} --email ${pend.email} --resend`);
289
+ return { kind: "needs_person", needs: "code", lines: ["That sign-in has expired or was used up.", `Get a new code and link: ${again}`], json: { needs: "code", sent_to: pend.email, retry: false, next: again } };
290
+ }
291
+ }
292
+ if (deps.now() >= until)
293
+ break;
294
+ await sleep(o.everyMs ?? CONTINUE_EVERY_MS);
295
+ }
296
+ if (!reached)
297
+ return { kind: "error", exit: "network", message: `could not reach the relay: ${deps.unreachable()} — run the same command again` };
298
+ const nxt = next(cmd, deps, "code"), cont = deps.command(`${cmd} --continue`);
299
+ return {
300
+ kind: "needs_person", needs: "code",
301
+ lines: [`Not confirmed yet.${pend.words ? ` In the email's link, type ${pend.words.toUpperCase()}, then run: ${cont}` : ""}`, `Or give the 6-digit code: ${nxt}`],
302
+ json: { needs: "code", sent_to: pend.email, next: nxt, ...(pend.words ? { link: true, words: pend.words, next_link: cont } : {}) },
303
+ };
304
+ }
305
+ //# sourceMappingURL=flag-signin.js.map
@@ -37,6 +37,8 @@ export const PANTHEON_HOME_ENTRIES = [
37
37
  { name: "worker.pid", what: "the worker's pid file" },
38
38
  { name: "notifier.pid", what: "the alerts' pid file" },
39
39
  { name: /^notifier-state(-.+)?\.json$/, sample: "notifier-state-team%2Fone.json", what: "the alerts' state" },
40
+ { name: /^invites-sent\.json$/, sample: "invites-sent.json", what: "the invites this machine made, hashed (for the joined alert)" },
41
+ { name: /^known-members\.json$/, sample: "known-members.json", what: "the teammates this machine has already said joined" },
40
42
  { name: "update-check.json", what: "the update check's cache" },
41
43
  { name: "uri-key", what: "the key pantheon:// links are signed with" },
42
44
  { name: "board.json", what: "the board's state" },
package/dist/identity.js CHANGED
@@ -25,6 +25,22 @@ export function verifyChallenge(publicKeyB64, space, member, nonce, signatureB64
25
25
  return false;
26
26
  }
27
27
  }
28
+ export function statusPayload(pubkey, ts, nonce, aud) {
29
+ return Buffer.from(`pantheon-auth-status/1\n/auth/status\n${ts}\n${nonce}\n${pubkey}\n${aud.toLowerCase()}`, "utf8");
30
+ }
31
+ export function signStatus(privateKeyB64, pubkey, ts, nonce, aud) {
32
+ const key = { key: Buffer.from(privateKeyB64, "base64"), format: "der", type: "pkcs8" };
33
+ return sign(null, statusPayload(pubkey, ts, nonce, aud), key).toString("base64");
34
+ }
35
+ export function verifyStatus(pubkey, ts, nonce, signatureB64, aud) {
36
+ try {
37
+ const key = createPublicKey({ key: Buffer.from(pubkey, "base64"), format: "der", type: "spki" });
38
+ return verify(null, statusPayload(pubkey, ts, nonce, aud), key, Buffer.from(signatureB64, "base64"));
39
+ }
40
+ catch {
41
+ return false;
42
+ }
43
+ }
28
44
  function activityPayload(space, member, session, state, seen, ts) {
29
45
  return Buffer.from(`pantheon-activity/1\n${space}\n${member}\n${session}\n${state}\n${seen}\n${ts}`, "utf8");
30
46
  }
@@ -153,6 +169,9 @@ export function verifyBytes(publicKeyB64, payload, signatureB64) {
153
169
  return false;
154
170
  }
155
171
  }
172
+ export function teamSetupPayload(member, s) {
173
+ return Buffer.from(`pantheon-team-setup/1\n${s.team}\n${member}\n${s.mode}\n${s.wake}\n${s.commands ? 1 : 0}\n${s.alerts}\n${s.at}`, "utf8");
174
+ }
156
175
  export function signDelegate(memberPrivateKeyB64, team, member, subPub, run, expires) {
157
176
  return { pub: subPub, run, expires, sig: signBytes(memberPrivateKeyB64, delegatePayload(team, member, fingerprint(subPub), run, expires)) };
158
177
  }
@@ -0,0 +1,65 @@
1
+ import { createHash } from "node:crypto";
2
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { CONFIG_DIR } from "./config.js";
5
+ function writeFileAtomic(file, text, mode) {
6
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
7
+ const tmp = `${file}.${process.pid}.tmp`;
8
+ writeFileSync(tmp, text, { mode });
9
+ renameSync(tmp, file);
10
+ }
11
+ export const inviteFp = (token) => createHash("sha256").update(token).digest("hex").slice(0, 16);
12
+ export const SENT_KEEP_MS = 8 * 86_400_000;
13
+ const sentPath = (home = CONFIG_DIR) => join(home, "invites-sent.json");
14
+ function read(home) {
15
+ try {
16
+ const j = JSON.parse(readFileSync(sentPath(home), "utf8"));
17
+ return j && typeof j === "object" ? j : {};
18
+ }
19
+ catch {
20
+ return {};
21
+ }
22
+ }
23
+ export function recordInviteSent(team, token, home = CONFIG_DIR, now = Date.now()) {
24
+ try {
25
+ const all = read(home);
26
+ const list = (all[team] ?? []).filter((e) => now - e.at < SENT_KEEP_MS);
27
+ list.push({ fp: inviteFp(token), at: now });
28
+ all[team] = list.slice(-200);
29
+ writeFileAtomic(sentPath(home), JSON.stringify(all), 0o600);
30
+ }
31
+ catch { }
32
+ }
33
+ export function invitesSent(team, home = CONFIG_DIR, now = Date.now()) {
34
+ return new Set((read(home)[team] ?? []).filter((e) => now - e.at < SENT_KEEP_MS).map((e) => e.fp));
35
+ }
36
+ const knownPath = (home = CONFIG_DIR) => join(home, "known-members.json");
37
+ export function newMembers(team, admitted, me, home = CONFIG_DIR) {
38
+ const all = readKnown(home);
39
+ const known = all[team];
40
+ if (!known) {
41
+ markKnown(team, admitted, home);
42
+ return [];
43
+ }
44
+ return admitted.filter((m) => m !== me && !known.includes(m));
45
+ }
46
+ export function markKnown(team, members, home = CONFIG_DIR) {
47
+ if (!members.length)
48
+ return;
49
+ const all = readKnown(home);
50
+ all[team] = [...new Set([...(all[team] ?? []), ...members])];
51
+ try {
52
+ writeFileAtomic(knownPath(home), JSON.stringify(all), 0o600);
53
+ }
54
+ catch { }
55
+ }
56
+ function readKnown(home) {
57
+ try {
58
+ const j = JSON.parse(readFileSync(knownPath(home), "utf8"));
59
+ return j && typeof j === "object" ? j : {};
60
+ }
61
+ catch {
62
+ return {};
63
+ }
64
+ }
65
+ //# sourceMappingURL=invites-sent.js.map
package/dist/managed.js CHANGED
@@ -238,32 +238,17 @@ export function runtimeNodeFit(layout, node, newest, relay, os = platform()) {
238
238
  share: "runtime Node too old for the newest release",
239
239
  };
240
240
  }
241
- export function joinInstructions(invite, relay, installers = true) {
242
- const link = quotableInvite(invite);
243
- const steps = [];
244
- const sh = link && installers ? installerLine(relay, "sh", ["join", link]) : null;
245
- const win = link && installers ? installerLine(relay, "windows", ["join", link]) : null;
246
- if (sh)
247
- steps.push({ label: "Mac or Linux (Terminal):", lines: [sh] });
248
- if (win)
249
- steps.push({ label: "Windows (Command Prompt or PowerShell):", lines: [win] });
250
- steps.push({
251
- label: steps.length ? "Already have Node.js 22.13 or newer? This works too:" : "With Node.js 22.13 or newer (nodejs.org):",
252
- lines: ["npm i -g @join-pantheon/cli", link ? `pantheon join '${link}'` : `pantheon join ${invite}`],
253
- });
254
- const joinLine = link ? `pantheon join '${link}'` : `pantheon join ${invite}`;
255
- return {
256
- intro: "You're invited to my Pantheon team. Paste the line for your computer into a terminal:",
257
- steps,
258
- agent: {
259
- label: "Or ask your coding agent (Claude Code, Codex, Cursor) to run:",
260
- lines: ["npm i -g @join-pantheon/cli", `${joinLine} --json`],
261
- note: "This needs Node.js 22.13 or newer. If join exits with code 10, you need to sign in once, and it says how.",
262
- },
263
- outro: sh || win
264
- ? "It installs Pantheon (with its own Node, no admin rights), asks for your email, sends you a 6-digit code (check spam if it does not arrive), and sets up the coding agents on your computer."
265
- : "`pantheon join` asks for your email, sends you a 6-digit code (check spam if it does not arrive), and sets up the coding agents on your computer.",
266
- };
241
+ export async function relayInstallerVersion(relay, timeoutMs = 4000) {
242
+ const base = installerBase(relay);
243
+ if (!base)
244
+ return null;
245
+ try {
246
+ const r = await fetch(`${base}/install.sh`, { method: "HEAD", signal: AbortSignal.timeout(timeoutMs) });
247
+ return r.status === 200 ? r.headers.get("x-pantheon-installs") : null;
248
+ }
249
+ catch {
250
+ return null;
251
+ }
267
252
  }
268
253
  export async function relayServesInstaller(relay, timeoutMs = 4000) {
269
254
  const base = installerBase(relay);