@milesroxas/design-hub 0.13.0 → 0.15.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.
Files changed (101) hide show
  1. package/README.md +38 -33
  2. package/core/catalog.test.ts +28 -1
  3. package/core/catalog.ts +21 -4
  4. package/core/prototype.test.ts +12 -1
  5. package/core/prototype.ts +21 -2
  6. package/core/review/model.ts +71 -6
  7. package/core/review/service.test.ts +536 -1
  8. package/core/review/service.ts +452 -25
  9. package/core/review/store.ts +45 -4
  10. package/dist/core/catalog.d.ts +8 -1
  11. package/dist/core/catalog.js +12 -3
  12. package/dist/core/prototype.d.ts +20 -2
  13. package/dist/core/prototype.js +17 -2
  14. package/dist/core/review/model.d.ts +42 -3
  15. package/dist/core/review/model.js +52 -3
  16. package/dist/core/review/service.d.ts +81 -7
  17. package/dist/core/review/service.js +407 -23
  18. package/dist/core/review/store.d.ts +29 -2
  19. package/dist/core/review/store.js +4 -0
  20. package/dist/scripts/client.d.ts +1 -1
  21. package/dist/scripts/client.js +1 -1
  22. package/dist/scripts/lib/catalog.d.ts +1 -1
  23. package/dist/scripts/lib/catalog.js +3 -3
  24. package/dist/scripts/lib/dns.d.ts +16 -2
  25. package/dist/scripts/lib/dns.js +66 -3
  26. package/dist/scripts/lib/fake-host.d.ts +16 -1
  27. package/dist/scripts/lib/fake-host.js +36 -1
  28. package/dist/scripts/lib/host.d.ts +2 -0
  29. package/dist/scripts/lib/resend.d.ts +36 -0
  30. package/dist/scripts/lib/resend.js +66 -0
  31. package/dist/scripts/lib/studio-deps.d.ts +7 -0
  32. package/dist/scripts/lib/studio-deps.js +6 -1
  33. package/dist/scripts/lib/studios.d.ts +2 -2
  34. package/dist/scripts/lib/studios.js +5 -5
  35. package/dist/scripts/lib/vercel-host.js +6 -0
  36. package/dist/scripts/new.d.ts +8 -3
  37. package/dist/scripts/new.js +15 -4
  38. package/dist/scripts/people.d.ts +16 -4
  39. package/dist/scripts/people.js +67 -17
  40. package/dist/scripts/preflight.js +1 -1
  41. package/dist/scripts/share.js +3 -3
  42. package/dist/scripts/studio.d.ts +19 -3
  43. package/dist/scripts/studio.js +327 -6
  44. package/dist/server/api.d.ts +25 -2
  45. package/dist/server/api.js +77 -17
  46. package/dist/server/dev-studio.d.ts +36 -0
  47. package/dist/server/dev-studio.js +181 -0
  48. package/dist/server/dev.d.ts +16 -1
  49. package/dist/server/dev.js +23 -3
  50. package/dist/server/gate.d.ts +26 -3
  51. package/dist/server/gate.js +323 -52
  52. package/dist/server/mailer.d.ts +60 -0
  53. package/dist/server/mailer.js +104 -0
  54. package/dist/server/mailers/fake.d.ts +8 -0
  55. package/dist/server/mailers/fake.js +16 -0
  56. package/dist/server/mailers/resend.d.ts +21 -0
  57. package/dist/server/mailers/resend.js +49 -0
  58. package/dist/server/session.js +4 -1
  59. package/dist/vercel/proxy.js +10 -3
  60. package/dist/vite/plugin.js +6 -1
  61. package/kit/ViewTools.tsx +9 -0
  62. package/kit/prefs.ts +3 -4
  63. package/kit/ui/Menu.tsx +29 -18
  64. package/kit/ui/layer.ts +41 -0
  65. package/package.json +1 -1
  66. package/shell/Command.tsx +142 -0
  67. package/shell/Index.tsx +902 -400
  68. package/shell/Milestone.tsx +302 -0
  69. package/shell/Sidebar.tsx +236 -0
  70. package/shell/index.css +224 -0
  71. package/shell/milestones.test.ts +157 -0
  72. package/shell/milestones.ts +144 -0
  73. package/shell/registry.ts +4 -3
  74. package/shell/review/Bar.tsx +1 -0
  75. package/shell/review/Card.tsx +17 -7
  76. package/shell/review/People.tsx +908 -134
  77. package/shell/review/Review.tsx +2 -2
  78. package/shell/review/anchor.ts +6 -1
  79. package/shell/review/client.ts +41 -7
  80. package/shell/review/menu-place.test.ts +41 -0
  81. package/shell/review/place.test.ts +26 -1
  82. package/shell/review/place.ts +17 -0
  83. package/shell/review/review.css +97 -11
  84. package/shell/review/view.test.ts +115 -1
  85. package/shell/review/view.ts +92 -2
  86. package/shell/shell.css +8 -175
  87. package/shell/sidebar.css +86 -0
  88. package/shell/studio/ClientHub.tsx +21 -10
  89. package/shell/studio/StudioHub.tsx +121 -45
  90. package/shell/studio/hub.css +118 -27
  91. package/shell/studio/page.tsx +28 -17
  92. package/shell/system.css +12 -0
  93. package/skills/miles-deploy/SKILL.md +25 -4
  94. package/skills/miles-new-feature/SKILL.md +2 -1
  95. package/skills/miles-prototype/SKILL.md +1 -1
  96. package/templates/app/README.md +1 -1
  97. package/templates/brand/README.md +1 -1
  98. package/templates/site/README.md +1 -1
  99. package/templates/space/README.md +1 -1
  100. package/templates/studio/.env.example +6 -0
  101. package/templates/studio/package.json +1 -1
@@ -13,6 +13,10 @@
13
13
  // own host if it is not yet
14
14
  // studio link lists a studio folder that already exists on this machine
15
15
  // and links it to the studio's project on its team
16
+ // studio email turns email sign-in on (email.md, "Turning it on"): the
17
+ // sender's domain at Resend, its DNS records, a send-only
18
+ // key, a test mail, and only then the site's two secrets and
19
+ // a deploy; `--off` takes the two secrets off and deploys
16
20
  //
17
21
  // Every step checks before it acts, so a command stopped part way is safe to
18
22
  // run again. Secrets go only to the folder's gitignored .env and the site's
@@ -20,14 +24,18 @@
20
24
  import { randomBytes } from 'node:crypto';
21
25
  import { copyFileSync, cpSync, existsSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync, } from 'node:fs';
22
26
  import { basename, join, resolve } from 'node:path';
27
+ import { escapeHtml } from '../core/html.js';
28
+ import { emailOf } from '../core/review/model.js';
23
29
  import { readEnv, removeEnv, writeEnv } from '../server/env.js';
24
30
  import { localStudio } from '../server/local.js';
31
+ import { resendMailer } from '../server/mailers/resend.js';
25
32
  import { claimDatabase, claimFiles, MarkError } from '../server/mark.js';
26
33
  import { PACKAGE, TEMPLATES } from '../server/paths.js';
27
34
  import { CliError } from './lib/cli.js';
28
35
  import { keepingGitignore } from './lib/deploy.js';
29
36
  import { pointHost, waitServed } from './lib/dns.js';
30
37
  import { deployAlone } from './lib/host.js';
38
+ import { resendAccount } from './lib/resend.js';
31
39
  import { openReview, realDeps } from './lib/studio-deps.js';
32
40
  import { addToList, BLOB_NAME, CLOUDFLARE_NAME, DNS_PROVIDERS, findStudio, hasStore, KV_PROVIDERS, MODE_OF, readStudio, STORE_NAMES, STUDIO_FILE, studioHost, studioProblems, writeStudio, } from './lib/studios.js';
33
41
  export const spec = {
@@ -37,7 +45,7 @@ export const spec = {
37
45
  {
38
46
  name: 'action',
39
47
  required: true,
40
- description: 'create: scaffold --dir, install and build it here, set it up on --team, deploy, set up studio.<apex> (its DNS record and domain) and list it. deploy: install and build the studio folder here, so the site installs the package its package.json names, deploy it again, remove every older deployment, and set up studio.<apex> if it is not yet. link: list an existing studio folder (--dir) on this machine and link it to the studio’s project.',
48
+ description: 'create: scaffold --dir, install and build it here, set it up on --team, deploy, set up studio.<apex> (its DNS record and domain) and list it. deploy: install and build the studio folder here, so the site installs the package its package.json names, deploy it again, remove every older deployment, and set up studio.<apex> if it is not yet. link: list an existing studio folder (--dir) on this machine and link it to the studio’s project. email: turn email sign-in on, in this order, each step safe to run again: the full Resend key into .env; the sender’s domain at Resend (one already verified, or a verified parent, is used as it is, with no DNS change); else the domain made and its records added (Cloudflare by its API; Vercel DNS and manual print them and stop) and verified; a new send-only key for that domain; a test mail to --test; only then RESEND_API_KEY and MAIL_FROM on the site, a deploy, and the earlier send-only key removed. With --off: take the two off the site and deploy; links work as before.',
41
49
  },
42
50
  ],
43
51
  flags: {
@@ -94,10 +102,23 @@ export const spec = {
94
102
  },
95
103
  studio: {
96
104
  type: 'string',
97
- description: 'For deploy: the studio’s slug. Absent, the studio folder this runs in.',
105
+ description: 'For deploy and email: the studio’s slug. Absent, the studio folder this runs in.',
106
+ },
107
+ from: {
108
+ type: 'string',
109
+ description: 'For email: who sign-in mail is from, "<Name> <address>", the address at the apex or below it, such as "North Studio <signin@mail.example.com>". The name is the studio’s in every mail.',
110
+ },
111
+ 'resend-key-file': {
112
+ type: 'string',
113
+ description: 'For email: a file holding a full-access Resend API key, copied into the studio’s .env as RESEND_FULL_KEY; never pass a key itself. Absent, the one already in .env.',
114
+ },
115
+ test: { type: 'string', description: 'For email: the address the test mail goes to.' },
116
+ off: {
117
+ type: 'boolean',
118
+ description: 'For email: turn email sign-in off. Takes RESEND_API_KEY and MAIL_FROM off the site and deploys it.',
98
119
  },
99
120
  },
100
- output: 'create: { ok, studio, dir, folder, list, package, vercel, env: { GATE_SECRET: set | kept, database: created | connected | kept, files: created | kept, pulled }, mark: claimed | kept (the database marked as this studio’s), filesMark: claimed | kept (the file store, the same), dns, owner, deployment, removed, studioHost: { host, state: ready | waiting, error?, fix?, record? }, link? (the owner’s, on the studio’s host, the run it first answers), next }. deploy: { ok, studio, package, deployment, removed, studioHost, link? }. The deploy is done whatever studioHost says; while it is waiting, its fix says what to do (a record to add, a certificate still coming) and the next deploy finishes it. package is what the folder’s package.json names for @milesroxas/design-hub. link: { ok, studio, dir, list, env, warnings }',
121
+ output: 'create: { ok, studio, dir, folder, list, package, vercel, env: { GATE_SECRET: set | kept, database: created | connected | kept, files: created | kept, pulled }, mark: claimed | kept (the database marked as this studio’s), filesMark: claimed | kept (the file store, the same), dns, owner, deployment, removed, studioHost: { host, state: ready | waiting, error?, fix?, record? }, link? (the owner’s, on the studio’s host, the run it first answers), next }. deploy: { ok, studio, package, deployment, removed, studioHost, link? }. The deploy is done whatever studioHost says; while it is waiting, its fix says what to do (a record to add, a certificate still coming) and the next deploy finishes it. package is what the folder’s package.json names for @milesroxas/design-hub. link: { ok, studio, dir, list, env, warnings }. email: { ok, studio, from, domain, dns: none (already verified) | added | exists | printed, key (the send-only key’s name at Resend), test: sent, secrets, package, deployment, removed, keysRemoved, next }; while a step waits on a person it stops with ok: false, what to do (records to add, a domain not verified yet) and “run this again”. email --off: { ok, studio, secrets, package, deployment, removed, next }',
101
122
  };
102
123
  const need = (value, flag, action) => {
103
124
  if (!value)
@@ -147,6 +168,46 @@ function sameStudio(kept, asked) {
147
168
  const HUB = '@milesroxas/design-hub';
148
169
  const LOCKFILE = 'pnpm-lock.yaml';
149
170
  const manifestOf = (dir) => JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));
171
+ /** The first Design Hub whose gate has the email form and the code routes (email.md, slice 3). */
172
+ const EMAIL_SINCE = [0, 14, 0];
173
+ const versionOf = (v) => typeof v === 'string'
174
+ ? (v
175
+ .match(/^\D*(\d+)\.(\d+)\.(\d+)/)
176
+ ?.slice(1)
177
+ .map(Number) ?? null)
178
+ : null;
179
+ const olderThan = (v, than) => {
180
+ const i = v.findIndex((n, k) => n !== than[k]);
181
+ return i >= 0 && v[i] < than[i];
182
+ };
183
+ /**
184
+ * Refuses a studio folder whose Design Hub has no email sign-in, before
185
+ * anything is written: a site on it would hold the mail secrets with no code
186
+ * form, and invites would promise one. It judges the version installed in the
187
+ * folder and the one its package.json names; a `file:` pack, by the installed
188
+ * one alone.
189
+ */
190
+ function emailReady(dir, slug) {
191
+ const spec = manifestOf(dir).dependencies[HUB] ?? '';
192
+ let installed;
193
+ try {
194
+ installed = JSON.parse(readFileSync(join(dir, 'node_modules', HUB, 'package.json'), 'utf8')).version;
195
+ }
196
+ catch { }
197
+ const seen = [installed, spec.startsWith('file:') ? undefined : spec]
198
+ .map(versionOf)
199
+ .filter((v) => v !== null);
200
+ const old = seen.find((v) => olderThan(v, EMAIL_SINCE));
201
+ if (!old && seen.length > 0)
202
+ return;
203
+ const since = EMAIL_SINCE.join('.');
204
+ throw new CliError(old
205
+ ? `The studio folder has ${HUB} ${old.join('.')}, which has no email sign-in; nothing was changed.`
206
+ : `The studio folder's ${HUB} version could not be read; nothing was changed.`, {
207
+ named: spec,
208
+ fix: `Move the studio folder to ${since} or newer first: pnpm add ${HUB}@<version> in ${dir}, or pnpm studio deploy --studio ${slug} --package <tgz>. Then run this again.`,
209
+ });
210
+ }
150
211
  /** The --package file, checked before anything is written. */
151
212
  function packFile(tgz) {
152
213
  if (tgz === undefined)
@@ -243,10 +304,12 @@ function tokenFrom(file) {
243
304
  token = readFileSync(resolve(file), 'utf8').trim();
244
305
  }
245
306
  catch {
246
- throw new CliError('--cloudflare-token-file could not be read.', { got: file });
307
+ throw new CliError('--cloudflare-token-file could not be read.', {
308
+ fix: 'Pass the path of a file that holds the token, never the token itself.',
309
+ });
247
310
  }
248
311
  if (!/^[\w-]{20,200}$/.test(token))
249
- throw new CliError('--cloudflare-token-file does not hold one API token on one line.', { got: file });
312
+ throw new CliError('--cloudflare-token-file does not hold one API token on one line.');
250
313
  return token;
251
314
  }
252
315
  /**
@@ -501,15 +564,273 @@ async function link(flags, deps) {
501
564
  : [];
502
565
  return { studio: config.slug, dir, list, env: { pulled }, warnings };
503
566
  }
567
+ /** The names the site reads its mail by (chooseMailer), and the full key's, which stays in the folder. */
568
+ const MAIL_NAMES = ['RESEND_API_KEY', 'MAIL_FROM'];
569
+ const FULL_KEY = 'RESEND_FULL_KEY';
570
+ /** A Resend API key as a file holds it: `re_`, then letters, digits, `_` and `-`. */
571
+ const RESEND_KEY = /^re_[\w-]{8,200}$/;
572
+ /** Resend verified a new domain in about a minute (email-findings.md, b): looked at for up to two. */
573
+ const VERIFY_TRIES = 12;
574
+ const VERIFY_GAP_MS = 10_000;
575
+ /** The sender `--from` names, its address at the apex or below it. */
576
+ function senderFrom(given, apex) {
577
+ const raw = need(given, 'from', 'email');
578
+ const parts = raw.match(/^\s*"?([^"<>\\\r\n]*?)"?\s*<([^<>]+)>\s*$/);
579
+ const name = parts?.[1].trim() ?? '';
580
+ const address = emailOf(parts?.[2]);
581
+ if (!name || !address)
582
+ throw new CliError('--from takes a name and an address, such as "North Studio <signin@mail.example.com>".', {
583
+ got: raw,
584
+ });
585
+ const domain = address.slice(address.indexOf('@') + 1);
586
+ if (domain !== apex && !domain.endsWith(`.${apex}`))
587
+ throw new CliError(`The sender’s address must be at ${apex} or below it.`, {
588
+ got: address,
589
+ fix: `Use an address such as signin@mail.${apex}.`,
590
+ });
591
+ // A name with a comma, a period or another special goes in quotes, or Resend reads it as more than one sender.
592
+ const shown = /[()<>[\]:;@,."]/.test(name) ? `"${name}"` : name;
593
+ return { name, address, domain, from: `${shown} <${address}>` };
594
+ }
595
+ /**
596
+ * Step 1: the full key, from the file into the folder's .env, or the one
597
+ * already there. Read from a file, so it never shows in a process list or a
598
+ * shell's history; no error repeats it.
599
+ */
600
+ function fullKey(dir, file) {
601
+ if (!file) {
602
+ const kept = readEnv(dir)[FULL_KEY];
603
+ if (kept)
604
+ return kept;
605
+ throw new CliError(`No ${FULL_KEY} in the studio's .env.`, {
606
+ fix: 'Run this again with --resend-key-file <a file holding a full-access Resend API key>.',
607
+ });
608
+ }
609
+ let key;
610
+ try {
611
+ key = readFileSync(resolve(file), 'utf8').trim();
612
+ }
613
+ catch {
614
+ throw new CliError('--resend-key-file could not be read.', {
615
+ fix: 'Pass the path of a file that holds the key, never the key itself.',
616
+ });
617
+ }
618
+ if (!RESEND_KEY.test(key))
619
+ throw new CliError('--resend-key-file does not hold one Resend API key on one line.');
620
+ writeEnv(dir, { [FULL_KEY]: key });
621
+ return key;
622
+ }
623
+ /**
624
+ * The sender's domain, and each of its parents under the apex, is no host
625
+ * the studio serves: not `studio.<apex>`, and no client's, even one named
626
+ * `mail` before that name was kept.
627
+ */
628
+ async function notServed(deps, studio, domain) {
629
+ const review = await openReview(deps, studio);
630
+ const { apex } = studio.config;
631
+ for (let name = domain; name.endsWith(`.${apex}`); name = name.slice(name.indexOf('.') + 1))
632
+ if (await review.siteOfHost(name))
633
+ throw new CliError(`${name} is a host this studio serves, so mail cannot be sent from it.`, {
634
+ fix: `Send from another domain under the apex, such as signin@mail.${apex}, if no client is there.`,
635
+ });
636
+ }
637
+ /** The account's domain for the sender: a verified one that is the sender's domain or a parent of it, the nearest; else the sender's own, as it stands. */
638
+ function domainFor(domains, domain) {
639
+ const covers = (d) => domain === d.name || domain.endsWith(`.${d.name}`);
640
+ const verified = domains
641
+ .filter((d) => d.status === 'verified' && covers(d))
642
+ .sort((a, b) => b.name.length - a.name.length);
643
+ return verified[0] ?? domains.find((d) => d.name === domain) ?? null;
644
+ }
645
+ /** Resend's records as the DNS port takes them, each name in full: Resend names them relative to the apex (email-findings.md, a). */
646
+ function wantedOf(records, apex) {
647
+ return records.map((r) => {
648
+ const type = r.type.toUpperCase();
649
+ if (type !== 'TXT' && type !== 'MX' && type !== 'CNAME')
650
+ throw new CliError(`Resend asks for a ${r.type} record, which this command cannot add.`, {
651
+ fix: 'Add the domain’s records at the DNS provider from its page at resend.com/domains, then run this again.',
652
+ });
653
+ const relative = r.name.toLowerCase().replace(/\.$/, '');
654
+ const name = relative === apex || relative.endsWith(`.${apex}`) ? relative : `${relative}.${apex}`;
655
+ return { type, name, value: r.value, ...(type === 'MX' ? { priority: Number(r.priority ?? 10) } : {}) };
656
+ });
657
+ }
658
+ /** Step 4: Resend asked to verify, then looked at until it says verified, for up to two minutes. */
659
+ async function verifiedDomain(deps, account, id) {
660
+ await account.verify(id);
661
+ let domain = await account.domain(id);
662
+ for (let i = 1; i < VERIFY_TRIES && domain.status !== 'verified'; i++) {
663
+ await deps.wait(VERIFY_GAP_MS);
664
+ domain = await account.domain(id);
665
+ }
666
+ return domain;
667
+ }
668
+ /**
669
+ * Steps 2 to 4: the domain the sender sends from. One the account has
670
+ * verified, or a verified parent, is used as it is: no DNS record is read or
671
+ * written. Else the sender's domain is made at Resend (once: a second make is
672
+ * refused, so the list is read first), its records go through the DNS port,
673
+ * and Resend verifies it, or the command stops to be run again.
674
+ */
675
+ async function mailDomain(deps, studio, account, wanted) {
676
+ const found = domainFor(await account.domains(), wanted);
677
+ if (found?.status === 'verified')
678
+ return { domain: found, dns: 'none' };
679
+ const made = found ?? (await account.createDomain(wanted));
680
+ const records = made.records ?? (await account.domain(made.id)).records ?? [];
681
+ const dns = deps.dns(studio, deps.host(studio.dir, studio.config));
682
+ const recorded = await dns.records(wantedOf(records, studio.config.apex));
683
+ // Records only printed, for a domain this run made, cannot be there yet: show them now, wait for nothing.
684
+ if (typeof recorded === 'object' && !found)
685
+ throw new CliError('Add the records listed at the DNS provider, then run this again; nothing was set on the site.', { records: recorded.records, fix: 'Add each record at the DNS provider, then run this again.' });
686
+ const domain = await verifiedDomain(deps, account, made.id);
687
+ if (domain.status !== 'verified')
688
+ throw new CliError(`Resend has not verified ${made.name} yet; nothing was set on the site.`, {
689
+ status: domain.status,
690
+ ...(typeof recorded === 'object'
691
+ ? { records: recorded.records, fix: 'Add each record at the DNS provider, then run this again.' }
692
+ : { fix: 'New records can take some minutes to be served: run this again.' }),
693
+ });
694
+ return { domain, dns: recorded };
695
+ }
696
+ /** The send-only key's name at Resend: the studio's slug and id, so an earlier run's is found by it and no other studio's is. */
697
+ const keyName = (config) => `design-hub-${config.slug}-${String(config.id).slice(0, 8)}`;
698
+ /** Step 6's mail: it names the studio and the sender, so the inbox shows what sign-in mail will look like. */
699
+ function testMail(sender, to, key) {
700
+ const subject = `Email sign-in is ready for ${sender.name}`;
701
+ const line = `Sign-in codes and invites for ${sender.name} will come from ${sender.address}.`;
702
+ const text = `${subject}.\n\n${line}\n\nNothing to do: this mail only proves that mail is sent.\n`;
703
+ const html = `<!doctype html><html lang="en"><body><p>${escapeHtml(line)}</p><p>Nothing to do: this mail only proves that mail is sent.</p></body></html>`;
704
+ return { to, subject, text, html, key: `test-${key}` };
705
+ }
706
+ /** A fetch that keeps the status and message of what it last heard back, and nothing else (no header, no key). */
707
+ function heard(fetcher, said) {
708
+ return async (input, init) => {
709
+ const res = await fetcher(input, init);
710
+ const body = (await res
711
+ .clone()
712
+ .json()
713
+ .catch(() => null));
714
+ said.status = res.status;
715
+ said.message = typeof body?.message === 'string' ? body.message.slice(0, 300) : undefined;
716
+ return res;
717
+ };
718
+ }
719
+ /** Puts a secret on the site in place of the one there, which setSecret alone keeps. */
720
+ async function replaceSecret(host, name, value) {
721
+ await host.removeSecret(name);
722
+ await host.setSecret(name, value);
723
+ }
724
+ async function emailOn(flags, deps, keys) {
725
+ const studio = findStudio(deps.home, flags.studio, deps.cwd);
726
+ const { dir, config } = studio;
727
+ emailReady(dir, config.slug);
728
+ const sender = senderFrom(flags.from, config.apex);
729
+ const to = emailOf(need(flags.test, 'test', 'email'));
730
+ if (!to)
731
+ throw new CliError('--test takes an email address.', { got: flags.test });
732
+ // 1. The full key, into .env.
733
+ const full = fullKey(dir, flags['resend-key-file']);
734
+ keys.push(full);
735
+ await notServed(deps, studio, sender.domain);
736
+ const account = resendAccount({ key: full, fetcher: deps.fetcher });
737
+ // 2 to 4. The domain, verified.
738
+ const { domain, dns } = await mailDomain(deps, studio, account, sender.domain);
739
+ // 5. A new send-only key for it. An earlier run's goes only once the site holds this one.
740
+ const name = keyName(config);
741
+ const key = await account.createKey(name, domain.id);
742
+ keys.push(key.token);
743
+ // 6. The test mail, by the site's own adapter, with the key the site will hold.
744
+ const said = {};
745
+ const test = await resendMailer({
746
+ key: key.token,
747
+ from: sender.from,
748
+ fetcher: heard(deps.fetcher, said),
749
+ }).send(testMail(sender, to, key.id));
750
+ if (test !== 'sent')
751
+ throw new CliError(test === 'down'
752
+ ? 'Resend did not answer the test mail; nothing was set on the site.'
753
+ : `Resend refused the test mail; nothing was set on the site. Resend said (${said.status ?? 'no status'}): ${said.message ?? 'no message'}`, {
754
+ to,
755
+ ...(said.status === undefined ? {} : { status: said.status }),
756
+ fix: 'Check the --test address and that Resend sends from the sender’s domain, then run this again.',
757
+ });
758
+ // 7. Only now: the folder's .env, the site's two secrets, a deploy, and then the earlier keys removed.
759
+ writeEnv(dir, { RESEND_API_KEY: key.token, MAIL_FROM: sender.from });
760
+ const pkg = installAndBuild(dir, deps);
761
+ const host = deps.host(dir, config);
762
+ await replaceSecret(host, 'RESEND_API_KEY', key.token);
763
+ await replaceSecret(host, 'MAIL_FROM', sender.from);
764
+ const deployed = await deployAlone(host);
765
+ const older = (await account.keys()).filter((k) => k.name === name && k.id !== key.id);
766
+ for (const k of older)
767
+ await account.deleteKey(k.id);
768
+ return {
769
+ studio: config.slug,
770
+ from: sender.from,
771
+ domain: domain.name,
772
+ dns: typeof dns === 'object' ? 'printed' : dns,
773
+ key: name,
774
+ test,
775
+ secrets: [...MAIL_NAMES],
776
+ package: pkg,
777
+ ...deployed,
778
+ keysRemoved: older.length,
779
+ next: `Email sign-in is on: a person with an email signs in alone with a code. A test mail went to ${to}.`,
780
+ };
781
+ }
782
+ async function emailOff(flags, deps) {
783
+ if (flags.from || flags.test || flags['resend-key-file'])
784
+ throw new CliError('--off takes no --from, --test or --resend-key-file.');
785
+ const { dir, config } = findStudio(deps.home, flags.studio, deps.cwd);
786
+ const pkg = installAndBuild(dir, deps);
787
+ const host = deps.host(dir, config);
788
+ const secrets = {};
789
+ for (const name of MAIL_NAMES)
790
+ secrets[name] = await host.removeSecret(name);
791
+ const deployed = await deployAlone(host);
792
+ // The folder too, so `people add` mails no more; the full key stays, for turning it on again.
793
+ removeEnv(dir, MAIL_NAMES);
794
+ return {
795
+ studio: config.slug,
796
+ secrets,
797
+ package: pkg,
798
+ ...deployed,
799
+ next: `Email sign-in is off; links work as before. ${FULL_KEY} stays in the studio's .env, so turning it on again needs only --from and --test.`,
800
+ };
801
+ }
802
+ /** An error with every key this run knows put out of it, whatever made it. */
803
+ function withoutKeys(error, keys) {
804
+ const scrub = (text) => keys.reduce((t, k) => t.split(k).join('<key>'), text);
805
+ const problems = error?.problems;
806
+ const detail = error instanceof CliError || error instanceof MarkError
807
+ ? error.detail
808
+ : Array.isArray(problems)
809
+ ? { problems }
810
+ : {};
811
+ const message = error instanceof Error ? error.message : String(error);
812
+ return new CliError(scrub(message), JSON.parse(scrub(JSON.stringify(detail))));
813
+ }
814
+ /** Email on or off. No key is ever in what it prints, an error's words and detail included. */
815
+ async function email(flags, deps) {
816
+ const keys = [];
817
+ try {
818
+ return await (flags.off ? emailOff(flags, deps) : emailOn(flags, deps, keys));
819
+ }
820
+ catch (error) {
821
+ throw withoutKeys(error, keys.filter(Boolean));
822
+ }
823
+ }
504
824
  const ACTIONS = {
505
825
  create,
506
826
  deploy,
507
827
  link,
828
+ email,
508
829
  };
509
830
  export async function run({ positionals: [action], flags }, deps) {
510
831
  const act = Object.hasOwn(ACTIONS, action) ? ACTIONS[action] : undefined;
511
832
  if (!act)
512
- throw new CliError(`Unknown action ${action}.`, { fix: 'create, deploy or link' });
833
+ throw new CliError(`Unknown action ${action}.`, { fix: 'create, deploy, link or email' });
513
834
  return act(flags, deps);
514
835
  }
515
836
  export const main = (args) => run(args, realDeps());
@@ -2,15 +2,36 @@ import type { Checks } from '../core/checks.ts';
2
2
  import { type Person, type Scope } from '../core/review/model.ts';
3
3
  import { type HostScope, type Review } from '../core/review/service.ts';
4
4
  import { type HostLookup } from './hosts.ts';
5
+ import { type Mailer } from './mailer.ts';
5
6
  import { type Gate, type GateKeys } from './session.ts';
6
7
  export declare const API_PATH = "/api/review";
7
- /** One request: the service, who is signed in, and the scope every op runs in. */
8
+ /**
9
+ * One request: the service, who is signed in, and the scope every op runs
10
+ * in. `mailer` is the studio's, or none (no invite is mailed); `host` is the
11
+ * host the scope's Client people sign in on, named in their invite: on a
12
+ * studio site the client's own, from its record.
13
+ */
8
14
  export type ApiContext = {
9
15
  review: Review;
10
16
  actor: Person | null;
11
17
  scope: Scope;
18
+ mailer?: Mailer | null;
19
+ host?: string | null;
20
+ /** pnpm dev with no DESIGN_HUB_DEV_MAIL: no studio is here to say how mail stands, so access answers mail: null and the People tab says nothing of it. */
21
+ mailUnknown?: boolean;
12
22
  };
13
23
  export declare const handleReview: (request: Request, ctx: ApiContext) => Promise<Response>;
24
+ /**
25
+ * The studio's own host's review API for one Studio person already known:
26
+ * `design-hub dev` serves the studio hub's page on it, over a local store,
27
+ * with no gate in front.
28
+ */
29
+ export declare const handleStudioReview: (request: Request, { review, actor, host, mailer }: {
30
+ review: Review;
31
+ actor: Person;
32
+ host: string;
33
+ mailer: Mailer | null;
34
+ }) => Promise<Response>;
14
35
  /** The person a request's signed cookie names, while they may still sign in, where `at` is: a client's scope, or the studio's host. */
15
36
  export declare function actorFrom(request: Request, review: Review, gate: Gate, at: HostScope): Promise<Person | null>;
16
37
  /** A studio site's review service and gate keys, or why it has none. */
@@ -32,5 +53,7 @@ export declare function studioReview(env: Record<string, string | undefined>, ch
32
53
  /**
33
54
  * A studio site's review function: the host's client is the scope, and the
34
55
  * gate's client, of every op; the studio's own host has the studio hub's.
56
+ * `mailer` is the studio's, chosen from the env as the gate chooses it
57
+ * (chooseMailer), unless a test gives one or null.
35
58
  */
36
- export declare function studioHandler(request: Request, checks: Checks | null, hosts: HostLookup): Promise<Response>;
59
+ export declare function studioHandler(request: Request, checks: Checks | null, hosts: HostLookup, mailer?: Mailer | null): Promise<Response>;
@@ -4,6 +4,7 @@ import { isAdded, STUDIO_SITE, } from '../core/review/model.js';
4
4
  import { createReview, NO_PROJECT, ReviewError, } from '../core/review/service.js';
5
5
  import { jevTriager } from '../core/review/triage.js';
6
6
  import { hostOf } from './hosts.js';
7
+ import { chooseMailer, sendInvite } from './mailer.js';
7
8
  import { clearedCookie, PERSON_COOKIE, readCookie, readGate, readPersonToken, sameOrigin, studioGate, } from './session.js';
8
9
  import { chooseStore } from './stores/index.js';
9
10
  export const API_PATH = '/api/review';
@@ -36,7 +37,8 @@ function projectScope(scope) {
36
37
  }
37
38
  /** What a client's hub shows of a project: its slug, for the link, and its name. */
38
39
  const listed = ({ slug, name }) => ({ slug, name });
39
- async function query(op, params, { review, actor, scope }) {
40
+ async function query(op, params, ctx) {
41
+ const { review, actor, scope } = ctx;
40
42
  switch (op) {
41
43
  case 'me':
42
44
  // The client is this request's: the page judges its controls in it, as the service does every op.
@@ -57,19 +59,49 @@ async function query(op, params, { review, actor, scope }) {
57
59
  return { projects: (await review.listProjects(scope, actor)).map(listed) };
58
60
  case 'people':
59
61
  return { people: (await review.listPeople(scope, actor)).map(visible) };
60
- case 'access':
61
- return { access: await review.defaultAccess(scope, actor) };
62
+ case 'access': {
63
+ // The default first: it refuses anyone but Studio, so a Client never learns how mail stands.
64
+ const access = await review.defaultAccess(scope, actor);
65
+ return { access, mail: ctx.mailUnknown ? null : await mailState(review, ctx.mailer ?? null) };
66
+ }
62
67
  default:
63
68
  return undefined;
64
69
  }
65
70
  }
71
+ /** How sign-in mail stands, for Studio: off with no mailer, failing while the last failed send is newer than the last that went (email.md, "When mail breaks"). */
72
+ async function mailState(review, mailer) {
73
+ if (!mailer)
74
+ return 'off';
75
+ const { okAt, failedAt } = await review.mailRecord();
76
+ return failedAt !== null && (okAt === null || failedAt > okAt) ? 'failing' : 'on';
77
+ }
66
78
  /** A link as a client's host answers it: at its own root, where its gate answers it. */
67
79
  const link = (r) => ({ person: visible(r.person), link: `/invite/${r.token}` });
80
+ /**
81
+ * Mails a new person their invite (email.md, E10), unless Studio said not to
82
+ * (`mail: false`), they have no address, the studio has no mailer, or there
83
+ * is no host to name (sendInvite).
84
+ */
85
+ async function invite(review, { mailer, homeOf }, issued, wanted) {
86
+ const { person, token } = issued;
87
+ const home = wanted === false ? null : homeOf(person);
88
+ if (!mailer || !home || !person.email)
89
+ return 'off';
90
+ return sendInvite(mailer, review, { ...person, email: person.email }, token, home);
91
+ }
68
92
  /** Studio's commands over people, their links and how long they keep access. */
69
- async function peopleCommand(op, b, { review, actor, at, link }) {
93
+ async function peopleCommand(op, b, { review, actor, at, link, invites }) {
70
94
  switch (op) {
71
- case 'people.add':
72
- return link(await review.addPerson(at, actor, { name: b.name, team: b.team, kind: b.kind, access: b.access }));
95
+ case 'people.add': {
96
+ const issued = await review.addPerson(at, actor, {
97
+ name: b.name,
98
+ team: b.team,
99
+ kind: b.kind,
100
+ access: b.access,
101
+ email: b.email,
102
+ });
103
+ return { ...link(issued), mailed: await invite(review, invites, issued, b.mail) };
104
+ }
73
105
  case 'people.link':
74
106
  return link(await review.newLink(at, actor, str(b.id)));
75
107
  case 'people.signOut':
@@ -78,6 +110,9 @@ async function peopleCommand(op, b, { review, actor, at, link }) {
78
110
  return { person: visible(await review.revoke(at, actor, str(b.id))) };
79
111
  case 'people.access':
80
112
  return { person: visible(await review.setAccess(at, actor, str(b.id), b.access)) };
113
+ case 'people.email':
114
+ // `email` must be sent: an address sets or changes it, null or empty clears it.
115
+ return { person: visible(await review.setEmail(at, actor, str(b.id), b.email)) };
81
116
  default:
82
117
  return undefined;
83
118
  }
@@ -93,12 +128,22 @@ const PROJECT_COMMANDS = [
93
128
  'prototype.audience',
94
129
  'control.audience',
95
130
  ];
131
+ /**
132
+ * Invites where a client's people are added: a Client's names the host the
133
+ * context gives, their client's own. A Studio person signs in by email on
134
+ * the studio's own host, which a client's host does not know, so none is
135
+ * mailed here; the studio hub mails them.
136
+ */
137
+ const clientInvites = ({ mailer = null, host = null }) => ({
138
+ mailer,
139
+ homeOf: (p) => (p.client === null ? null : host),
140
+ });
96
141
  async function command(op, b, ctx) {
97
142
  const { review, actor } = ctx;
98
143
  if (op === 'access.set')
99
144
  return { access: await review.setDefaultAccess(ctx.scope, actor, b.access) };
100
145
  if (!PROJECT_COMMANDS.includes(op))
101
- return peopleCommand(op, b, { review, actor, at: ctx.scope, link });
146
+ return peopleCommand(op, b, { review, actor, at: ctx.scope, link, invites: clientInvites(ctx) });
102
147
  const scope = projectScope(ctx.scope);
103
148
  const at = () => ({ prototype: prototypeOf(b.prototype), id: str(b.id) });
104
149
  switch (op) {
@@ -212,6 +257,7 @@ const PEOPLE_COMMANDS = [
212
257
  'people.signOut',
213
258
  'people.revoke',
214
259
  'people.access',
260
+ 'people.email',
215
261
  ];
216
262
  /**
217
263
  * The review API on the studio's own host, for a Studio person signed in
@@ -224,7 +270,7 @@ const PEOPLE_COMMANDS = [
224
270
  * No client's host has any of this: there `clients` is an unknown query, and
225
271
  * a `client` parameter is never read (S10).
226
272
  */
227
- const studioOps = (review, actor, host) => {
273
+ const studioOps = (review, actor, host, mailer) => {
228
274
  const where = async (client) => {
229
275
  if (client === undefined || client === null)
230
276
  return { at: STUDIO_SITE, host };
@@ -233,14 +279,14 @@ const studioOps = (review, actor, host) => {
233
279
  };
234
280
  const people = async (client) => {
235
281
  const w = await where(client);
282
+ // The host a person signs in on: a Client's from their client's record, never this request's; a Studio person's this one.
283
+ const homeOf = (p) => (p.client === null ? host : w.host);
236
284
  return {
237
285
  review,
238
286
  actor,
239
287
  at: w.at,
240
- link: (r) => ({
241
- person: visible(r.person),
242
- link: `https://${r.person.client === null ? host : w.host}/invite/${r.token}`,
243
- }),
288
+ link: (r) => ({ person: visible(r.person), link: `https://${homeOf(r.person)}/invite/${r.token}` }),
289
+ invites: { mailer, homeOf },
244
290
  };
245
291
  };
246
292
  return {
@@ -257,6 +303,7 @@ const studioOps = (review, actor, host) => {
257
303
  if (op === 'access')
258
304
  return {
259
305
  access: at === STUDIO_SITE ? await review.studioAccess(actor) : await review.defaultAccess(at, actor),
306
+ mail: await mailState(review, mailer),
260
307
  };
261
308
  // A client's section lists its own people; the Studio people have a section of their own.
262
309
  const listed = await review.listPeople(at, actor);
@@ -267,6 +314,12 @@ const studioOps = (review, actor, host) => {
267
314
  },
268
315
  };
269
316
  };
317
+ /**
318
+ * The studio's own host's review API for one Studio person already known:
319
+ * `design-hub dev` serves the studio hub's page on it, over a local store,
320
+ * with no gate in front.
321
+ */
322
+ export const handleStudioReview = (request, { review, actor, host, mailer }) => answer(request, studioOps(review, actor, host, mailer));
270
323
  /** The person a request's signed cookie names, while they may still sign in, where `at` is: a client's scope, or the studio's host. */
271
324
  export async function actorFrom(request, review, gate, at) {
272
325
  const claim = await readPersonToken(gate, readCookie(request, PERSON_COOKIE));
@@ -294,6 +347,8 @@ export function studioReview(env, checks = null, now) {
294
347
  keys,
295
348
  review: createReview(store.open(), {
296
349
  triage: jevTriager(env.TYPESAFE_API_KEY ?? '', checks),
350
+ // Sign-in codes are kept as an HMAC under the gate's secret (email.md, section 4).
351
+ codeKey: keys.secret,
297
352
  ...(now ? { now } : {}),
298
353
  }),
299
354
  };
@@ -330,30 +385,35 @@ const signedOut = (request) => json(401, { error: 'Sign in with the link the stu
330
385
  * signed out, or signed in for another client, gets one answer whatever
331
386
  * project the request names.
332
387
  */
333
- async function opsFor(request, { review, keys }, { host, site }) {
388
+ async function opsFor(request, { review, keys, mailer }, { host, site }) {
334
389
  if (site === STUDIO_SITE) {
335
390
  const actor = await actorFrom(request, review, studioGate(keys), STUDIO_SITE);
336
- return actor ? studioOps(review, actor, host) : signedOut(request);
391
+ return actor ? studioOps(review, actor, host, mailer) : signedOut(request);
337
392
  }
338
393
  const client = site.slug;
339
394
  const actor = await actorFrom(request, review, { ...keys, client, since: site.createdAt }, { client });
340
395
  if (!actor)
341
396
  return signedOut(request);
342
397
  const scope = await studioScope(request, review, client);
343
- return scope ? clientOps({ review, actor, scope }) : json(404, { error: 'Not found.' });
398
+ // An invite names the client's host from its record, as its links are on it (S9: a codename host too).
399
+ return scope
400
+ ? clientOps({ review, actor, scope, mailer, host: site.host })
401
+ : json(404, { error: 'Not found.' });
344
402
  }
345
403
  /**
346
404
  * A studio site's review function: the host's client is the scope, and the
347
405
  * gate's client, of every op; the studio's own host has the studio hub's.
406
+ * `mailer` is the studio's, chosen from the env as the gate chooses it
407
+ * (chooseMailer), unless a test gives one or null.
348
408
  */
349
- export async function studioHandler(request, checks, hosts) {
409
+ export async function studioHandler(request, checks, hosts, mailer = chooseMailer(process.env)) {
350
410
  const setup = studioReview(process.env, checks);
351
411
  if ('error' in setup)
352
412
  return json(503, { error: setup.error });
353
413
  let ops;
354
414
  try {
355
415
  const found = await hostSite(request, setup.review, hosts);
356
- ops = found ? await opsFor(request, setup, found) : json(404, { error: 'Not found.' });
416
+ ops = found ? await opsFor(request, { ...setup, mailer }, found) : json(404, { error: 'Not found.' });
357
417
  }
358
418
  catch (error) {
359
419
  console.error('[review]', error);