@milesroxas/design-hub 0.13.0 → 0.14.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 (67) hide show
  1. package/README.md +1 -1
  2. package/core/prototype.test.ts +12 -1
  3. package/core/prototype.ts +21 -2
  4. package/core/review/model.ts +71 -6
  5. package/core/review/service.test.ts +536 -1
  6. package/core/review/service.ts +452 -25
  7. package/core/review/store.ts +45 -4
  8. package/dist/core/prototype.d.ts +20 -2
  9. package/dist/core/prototype.js +17 -2
  10. package/dist/core/review/model.d.ts +42 -3
  11. package/dist/core/review/model.js +52 -3
  12. package/dist/core/review/service.d.ts +81 -7
  13. package/dist/core/review/service.js +407 -23
  14. package/dist/core/review/store.d.ts +29 -2
  15. package/dist/core/review/store.js +4 -0
  16. package/dist/scripts/client.d.ts +1 -1
  17. package/dist/scripts/client.js +1 -1
  18. package/dist/scripts/lib/dns.d.ts +16 -2
  19. package/dist/scripts/lib/dns.js +66 -3
  20. package/dist/scripts/lib/fake-host.d.ts +16 -1
  21. package/dist/scripts/lib/fake-host.js +36 -1
  22. package/dist/scripts/lib/host.d.ts +2 -0
  23. package/dist/scripts/lib/resend.d.ts +36 -0
  24. package/dist/scripts/lib/resend.js +66 -0
  25. package/dist/scripts/lib/studio-deps.d.ts +7 -0
  26. package/dist/scripts/lib/studio-deps.js +6 -1
  27. package/dist/scripts/lib/studios.d.ts +2 -2
  28. package/dist/scripts/lib/studios.js +5 -5
  29. package/dist/scripts/lib/vercel-host.js +6 -0
  30. package/dist/scripts/people.d.ts +16 -4
  31. package/dist/scripts/people.js +67 -17
  32. package/dist/scripts/studio.d.ts +19 -3
  33. package/dist/scripts/studio.js +327 -6
  34. package/dist/server/api.d.ts +14 -2
  35. package/dist/server/api.js +71 -17
  36. package/dist/server/dev.js +21 -1
  37. package/dist/server/gate.d.ts +26 -3
  38. package/dist/server/gate.js +323 -52
  39. package/dist/server/mailer.d.ts +60 -0
  40. package/dist/server/mailer.js +104 -0
  41. package/dist/server/mailers/fake.d.ts +8 -0
  42. package/dist/server/mailers/fake.js +16 -0
  43. package/dist/server/mailers/resend.d.ts +21 -0
  44. package/dist/server/mailers/resend.js +49 -0
  45. package/dist/server/session.js +4 -1
  46. package/dist/vercel/proxy.js +10 -3
  47. package/dist/vite/plugin.js +3 -1
  48. package/kit/ui/Menu.tsx +29 -18
  49. package/kit/ui/layer.ts +41 -0
  50. package/package.json +1 -1
  51. package/shell/review/Bar.tsx +1 -0
  52. package/shell/review/Card.tsx +17 -7
  53. package/shell/review/People.tsx +908 -134
  54. package/shell/review/Review.tsx +2 -2
  55. package/shell/review/anchor.ts +6 -1
  56. package/shell/review/client.ts +41 -7
  57. package/shell/review/menu-place.test.ts +41 -0
  58. package/shell/review/place.test.ts +26 -1
  59. package/shell/review/place.ts +17 -0
  60. package/shell/review/review.css +97 -11
  61. package/shell/review/view.test.ts +115 -1
  62. package/shell/review/view.ts +92 -2
  63. package/shell/studio/StudioHub.tsx +1 -0
  64. package/shell/studio/hub.css +99 -13
  65. package/skills/miles-deploy/SKILL.md +24 -3
  66. package/templates/studio/.env.example +6 -0
  67. package/templates/studio/package.json +1 -1
@@ -10,9 +10,12 @@
10
10
  // person, the owner too, gets a new link without a session. Studio also adds
11
11
  // people from the People tab and the studio hub. Without a link to a studio,
12
12
  // and with --local, they are this machine's dev store's, whose links open
13
- // nothing anywhere.
13
+ // nothing anywhere. When the studio sends mail (its .env holds the site's
14
+ // RESEND_API_KEY and MAIL_FROM), add mails a person with an address their
15
+ // link, unless --no-mail: the flag is the yes the People tab asks for.
14
16
  import { ACCESS, PERSON_KINDS, STUDIO_SITE } from '../core/review/model.js';
15
17
  import { localStudio } from '../server/local.js';
18
+ import { sendInvite } from '../server/mailer.js';
16
19
  import { CliError } from './lib/cli.js';
17
20
  import { readLink, realProjectDeps } from './lib/linked.js';
18
21
  import { cliReview } from './lib/review.js';
@@ -20,13 +23,13 @@ import { openReview } from './lib/studio-deps.js';
20
23
  import { findStudio, isStudioFolder, studioHost } from './lib/studios.js';
21
24
  export const spec = {
22
25
  name: 'people',
23
- summary: 'List or add the people who comment on the deployed prototypes, give them sign-in links, sign them out, revoke them, and set how long they keep access.',
26
+ summary: 'List or add the people who comment on the deployed prototypes, give them sign-in links, sign them out, revoke them, set how long they keep access, and set the address they sign in with by email.',
24
27
  positionals: [
25
28
  {
26
29
  name: 'action',
27
- description: 'list (default): everyone. add: a new person and their link. link <id>: another one-time link, for another device. sign-out <id>: ends every session and unused link, and gives one new link. revoke <id>: ends their access everywhere. access [id]: with an id and --access, sets that person’s access from now; without an id, reads the default a new Client gets (in a project the client’s own, else the studio’s; in the studio folder or with --studio the studio’s), or sets it with --access.',
30
+ description: 'list (default): everyone. add: a new person and their link. link <id>: another one-time link, for another device. sign-out <id>: ends every session and unused link, and gives one new link. revoke <id>: ends their access everywhere. email <id>: sets or changes their address with --email, or clears it with --clear. access [id]: with an id and --access, sets that person’s access from now; without an id, reads the default a new Client gets (in a project the client’s own, else the studio’s; in the studio folder or with --studio the studio’s), or sets it with --access.',
28
31
  },
29
- { name: 'id', description: 'The person, for link, sign-out, revoke and access' },
32
+ { name: 'id', description: 'The person, for link, sign-out, revoke, email and access' },
30
33
  ],
31
34
  flags: {
32
35
  name: { type: 'string', description: 'For add: their name as it shows on comments.' },
@@ -44,6 +47,18 @@ export const spec = {
44
47
  choices: ACCESS,
45
48
  description: 'How long they keep access: 3m, 6m or open. For add, absent means the client’s default for a client (people access reads it) and open for studio.',
46
49
  },
50
+ email: {
51
+ type: 'string',
52
+ description: 'For add and email: the address they sign in with by email, kept lower case. Optional: without one they sign in by link only. Within one client, or the studio’s own people, one person holds an address.',
53
+ },
54
+ clear: {
55
+ type: 'boolean',
56
+ description: 'For email: removes their address, so they sign in by link only.',
57
+ },
58
+ 'no-mail': {
59
+ type: 'boolean',
60
+ description: 'For add: do not email them their link. Absent, a person with --email is mailed it when the studio sends mail (RESEND_API_KEY and MAIL_FROM in its .env), and mailed says how that went.',
61
+ },
47
62
  studio: {
48
63
  type: 'string',
49
64
  description: 'The studio whose own people these are, by slug, from anywhere on this machine; in the studio folder it is that studio. Their links are on studio.<apex>. Client people are a project’s: run people in the project linked to their client.',
@@ -53,7 +68,7 @@ export const spec = {
53
68
  description: 'Use this machine’s dev store, even in a project linked to a studio.',
54
69
  },
55
70
  },
56
- output: '{ ok, store, studio?, people } or { ok, store, studio?, person, link, next?, notice? } or { ok, store, studio?, person } or { ok, store, studio?, access }; store is studio in a linked project, with studio: { studio, client, host, project }, and notice when a Studio person is added there; store is studio with studio: { studio, host } for the studio’s own people (the studio folder or --studio); local otherwise. A Studio person’s link is on studio.<apex> once it answers.',
71
+ output: '{ ok, store, studio?, people } or { ok, store, studio?, person, link, mailed?, next?, notice? } or { ok, store, studio?, person } or { ok, store, studio?, access }; store is studio in a linked project, with studio: { studio, client, host, project }, and notice when a Studio person is added there; store is studio with studio: { studio, host } for the studio’s own people (the studio folder or --studio); local otherwise. A Studio person’s link is on studio.<apex> once it answers. mailed, on add: sent (Resend took the invite; have them check spam if it does not show), refused or down (it did not go: send the link yourself), or off (none was sent).',
57
72
  };
58
73
  /** A link on the host it signs in on; a local one is a path the dev server never asks for. */
59
74
  const linkFor = (token, host) => {
@@ -74,6 +89,18 @@ function needId(action, id) {
74
89
  async function withLink(r, c) {
75
90
  return { person: strip(r.person), ...linkFor(r.token, await c.hostFor(r.person)) };
76
91
  }
92
+ /**
93
+ * The invite to a new person with an address (email.md, E10), unless
94
+ * --no-mail or the studio has no mailer: their link, on the host they sign in
95
+ * on (homeFor), a Client's client's own, a Studio person's studio.<apex>.
96
+ */
97
+ async function invite(c, r) {
98
+ const { person, token } = r;
99
+ if (c.flags['no-mail'] || !c.mailer || !person.email)
100
+ return 'off';
101
+ const home = await c.homeFor(person);
102
+ return home ? sendInvite(c.mailer, c.review, { ...person, email: person.email }, token, home) : 'off';
103
+ }
77
104
  /** One person's access with an id, else the default for a new Client: read it, or set it with --access. */
78
105
  async function access({ review, at, actor, flags, id }) {
79
106
  if (id) {
@@ -93,23 +120,37 @@ async function access({ review, at, actor, flags, id }) {
93
120
  : await review.defaultAccess(at, actor),
94
121
  };
95
122
  }
123
+ /** Sets or changes one person's address with --email, or clears it with --clear; never both, never neither. */
124
+ async function email({ review, at, actor, flags, id }) {
125
+ const person = needId('email', id);
126
+ if ((flags.email === undefined) === !flags.clear)
127
+ throw new CliError('Give an address or clear it, one of the two.', {
128
+ fix: 'pnpm people email <id> --email name@example.com, or pnpm people email <id> --clear.',
129
+ });
130
+ return { person: strip(await review.setEmail(at, actor, person, flags.clear ? null : flags.email)) };
131
+ }
96
132
  /** What adding a Studio person from a linked project means, in plain words, with --kind studio or --studio alike. */
97
133
  const studioWide = ({ studio, client }, link) => `A Studio person sees every client of studio ${studio}, not only ${client}: every project, comment and person. This link signs them in on ${new URL(link).host}. For someone who should see ${client} alone, add them in this project with --kind client and no --studio.`;
98
134
  /** The actions that print a link: a run that cannot print one is refused before any of them writes. */
99
135
  const LINKING = new Set(['add', 'link', 'sign-out']);
100
136
  const ACTIONS = {
101
137
  list: async ({ review, at, actor }) => ({ people: (await review.listPeople(at, actor)).map(strip) }),
102
- add: async (c) => withLink(await c.review.addPerson(c.at, c.actor, {
103
- name: c.flags.name,
104
- team: c.flags.team,
105
- kind: c.flags.kind ?? (c.at === STUDIO_SITE ? 'studio' : 'client'),
106
- access: c.flags.access,
107
- }), c),
138
+ add: async (c) => {
139
+ const added = await c.review.addPerson(c.at, c.actor, {
140
+ name: c.flags.name,
141
+ team: c.flags.team,
142
+ kind: c.flags.kind ?? (c.at === STUDIO_SITE ? 'studio' : 'client'),
143
+ access: c.flags.access,
144
+ email: c.flags.email,
145
+ });
146
+ return { ...(await withLink(added, c)), mailed: await invite(c, added) };
147
+ },
108
148
  link: async (c) => withLink(await c.review.newLink(c.at, c.actor, needId('link', c.id)), c),
109
149
  'sign-out': async (c) => withLink(await c.review.signOutEverywhere(c.at, c.actor, needId('sign-out', c.id)), c),
110
150
  revoke: async ({ review, at, actor, id }) => ({
111
151
  person: strip(await review.revoke(at, actor, needId('revoke', id))),
112
152
  }),
153
+ email,
113
154
  access,
114
155
  };
115
156
  /**
@@ -148,6 +189,8 @@ async function studioPeople(flags, deps) {
148
189
  studio: { studio: slug, host: studioHost(apex) },
149
190
  // Checked before the action runs (canLink), so a person, a link or a sign out is never made for no link.
150
191
  hostFor: async () => studioHost(apex),
192
+ mailer: deps.mailer(studio),
193
+ homeFor: async () => studioHost(apex),
151
194
  async canLink() {
152
195
  if (await answeringStudioHost(review, actor, apex))
153
196
  return;
@@ -167,8 +210,11 @@ async function projectPeople(flags, deps) {
167
210
  const found = await cliReview(flags.local, deps);
168
211
  const { review, store, scope, actor } = found;
169
212
  const where = found.studio;
213
+ const none = async () => undefined;
170
214
  if (!where)
171
- return { review, store, at: scope, actor, hostFor: async () => undefined };
215
+ return { review, store, at: scope, actor, hostFor: none, mailer: null, homeFor: none };
216
+ const studio = findStudio(deps.home, where.studio, deps.cwd);
217
+ const studioHome = async () => answeringStudioHost(review, actor, studio.config.apex);
172
218
  return {
173
219
  review,
174
220
  store,
@@ -176,17 +222,21 @@ async function projectPeople(flags, deps) {
176
222
  actor,
177
223
  studio: where,
178
224
  async hostFor(person) {
179
- if (person.client !== null)
180
- return where.host;
181
- const { apex } = findStudio(deps.home, where.studio, deps.cwd).config;
182
- return (await answeringStudioHost(review, actor, apex)) ?? where.host;
225
+ return person.client !== null ? where.host : ((await studioHome()) ?? where.host);
226
+ },
227
+ mailer: deps.mailer(studio),
228
+ // A Studio person signs in by email on the studio's own host alone: until it answers, they are not mailed.
229
+ async homeFor(person) {
230
+ return person.client !== null ? where.host : ((await studioHome()) ?? undefined);
183
231
  },
184
232
  };
185
233
  }
186
234
  export async function run({ positionals: [action = 'list', id], flags }, deps) {
187
235
  const act = Object.hasOwn(ACTIONS, action) ? ACTIONS[action] : undefined;
188
236
  if (!act)
189
- throw new CliError(`Unknown action ${action}.`, { fix: 'list, add, link, sign-out, revoke or access' });
237
+ throw new CliError(`Unknown action ${action}.`, {
238
+ fix: 'list, add, link, sign-out, revoke, email or access',
239
+ });
190
240
  // The studio's own people: named by --studio, or the studio folder this runs in.
191
241
  const own = flags.studio !== undefined || (!flags.local && !readLink(deps.root) && isStudioFolder(deps.root));
192
242
  const found = own ? await studioPeople(flags, deps) : await projectPeople(flags, deps);
@@ -7,7 +7,7 @@ export declare const spec: {
7
7
  readonly positionals: [{
8
8
  readonly name: 'action';
9
9
  readonly required: true;
10
- readonly 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.';
10
+ readonly 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.';
11
11
  }];
12
12
  readonly flags: {
13
13
  readonly dir: {
@@ -72,10 +72,26 @@ export declare const spec: {
72
72
  };
73
73
  readonly studio: {
74
74
  readonly type: 'string';
75
- readonly description: 'For deploy: the studio’s slug. Absent, the studio folder this runs in.';
75
+ readonly description: 'For deploy and email: the studio’s slug. Absent, the studio folder this runs in.';
76
+ };
77
+ readonly from: {
78
+ readonly type: 'string';
79
+ readonly 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.';
80
+ };
81
+ readonly 'resend-key-file': {
82
+ readonly type: 'string';
83
+ readonly 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.';
84
+ };
85
+ readonly test: {
86
+ readonly type: 'string';
87
+ readonly description: 'For email: the address the test mail goes to.';
88
+ };
89
+ readonly off: {
90
+ readonly type: 'boolean';
91
+ readonly description: 'For email: turn email sign-in off. Takes RESEND_API_KEY and MAIL_FROM off the site and deploys it.';
76
92
  };
77
93
  };
78
- readonly 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 }';
94
+ readonly 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 }';
79
95
  };
80
96
  export declare function run({ positionals: [action], flags }: Args<typeof spec>, deps: StudioDeps): Promise<Record<string, unknown>>;
81
97
  export declare const main: (args: Args<typeof spec>) => Promise<Record<string, unknown>>;
@@ -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,13 +2,23 @@ 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>;
14
24
  /** 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. */
@@ -32,5 +42,7 @@ export declare function studioReview(env: Record<string, string | undefined>, ch
32
42
  /**
33
43
  * A studio site's review function: the host's client is the scope, and the
34
44
  * gate's client, of every op; the studio's own host has the studio hub's.
45
+ * `mailer` is the studio's, chosen from the env as the gate chooses it
46
+ * (chooseMailer), unless a test gives one or null.
35
47
  */
36
- export declare function studioHandler(request: Request, checks: Checks | null, hosts: HostLookup): Promise<Response>;
48
+ export declare function studioHandler(request: Request, checks: Checks | null, hosts: HostLookup, mailer?: Mailer | null): Promise<Response>;