@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
@@ -21,15 +21,27 @@
21
21
  // 503, never a sign out. A Client asking for a prototype that is not
22
22
  // client-facing, its page or any file built from it under
23
23
  // /<project>/_p/<slug>/, gets 404. Without a session a page gets the sign-in
24
- // page (401), which says what to do and has no form, and anything else a
25
- // plain-text 401. Without GATE_SECRET or the store the gate fails closed (503).
26
- import { base64, sha256 } from '../core/bytes.js';
24
+ // page (401), which says what to do, and anything else a plain-text 401.
25
+ // Without GATE_SECRET or the store the gate fails closed (503).
26
+ //
27
+ // With a mailer (server/mailer.ts: the studio set a mail key and a sender),
28
+ // there is a second way in, on both kinds of host (email.md): the sign-in
29
+ // page has an email field, `POST /_gate/code` asks for a code and always
30
+ // answers the code page, whatever the address (the mail goes after the
31
+ // response), and `POST /_gate/code/use` signs in with it. Without one there
32
+ // is no form, and both paths are what any other path is. A link's page and
33
+ // the code page set a `try` cookie, so a second press of Continue or of a
34
+ // right code signs the same browser in again (the service's claim), and
35
+ // every sign-in POST and link view counts against a cap per network address,
36
+ // when the host's adapter gives one.
37
+ import { base64, base64url, sha256 } from '../core/bytes.js';
27
38
  import { escapeHtml } from '../core/html.js';
28
- import { GATE_FONT, handoffPath, hostName, isPrototypeSlug, PROOF_PATH, routeOf, STUDIO_PAGE, studioRouteOf, } from '../core/prototype.js';
29
- import { STUDIO_SITE, } from '../core/review/model.js';
39
+ import { CODE_ASK, CODE_USE, GATE_FONT, handoffPath, hostName, isPrototypeSlug, PROOF_PATH, routeOf, STUDIO_PAGE, studioRouteOf, } from '../core/prototype.js';
40
+ import { CODE, STUDIO_SITE, } from '../core/review/model.js';
30
41
  import { ReviewError } from '../core/review/service.js';
31
42
  import { studioReview } from './api.js';
32
43
  import { hostCache, hostOf } from './hosts.js';
44
+ import { chooseMailer, codeMail, sendAndRecord } from './mailer.js';
33
45
  import { clearedCookie, isFresh, issuePersonToken, PERSON_COOKIE, readCookie, readPersonToken, sameOrigin, sessionCookie, sessionSeconds, studioGate, } from './session.js';
34
46
  export const DEFAULT_SITE_NAME = 'Prototypes';
35
47
  // What the gate pages load before sign-in: the hub's face (the Vite plugin
@@ -39,29 +51,50 @@ export { GATE_FONT };
39
51
  // the pages carry no 'unsafe-inline', and they run no script at all. The gate
40
52
  // is hub chrome, so it wears the hub's neutral system look (shell/system.css)
41
53
  // inlined, never the project's brand. Geist (latin, variable) is the one
42
- // font, preloaded so the first paint is already in it.
54
+ // font, preloaded so the first paint is already in it. The pages are one set
55
+ // (email.md, section 3): no card, the words on the page, the studio's name
56
+ // as the masthead, the task as the title, one filled button.
43
57
  const CSS = `
44
58
  @font-face{font-family:Geist;src:url(${GATE_FONT}) format("woff2");font-weight:100 900;font-style:normal;font-display:swap}
45
- :root{color-scheme:light;--bg:oklch(.985 0 0);--surface:oklch(1 0 0);--ink:oklch(.205 0 0);--ink-3:oklch(.46 0 0);--brand:oklch(.205 0 0);--brand-hover:oklch(.3 0 0);--on-brand:oklch(.985 0 0);--ring:0 0 0 2px oklch(1 0 0),0 0 0 4px oklch(.556 0 0);--shadow:0 1px 2px 0 oklch(0 0 0/.05);--raised:0 0 0 1px oklch(0 0 0/.06),0 1px 2px oklch(0 0 0/.05),0 12px 24px -8px oklch(0 0 0/.1);--ease-out:cubic-bezier(.23,1,.32,1);--ease-press:cubic-bezier(.33,1,.68,1);--ease-hover:cubic-bezier(.25,.46,.45,.94)}
46
- @media(prefers-color-scheme:dark){:root{color-scheme:dark;--bg:oklch(.145 0 0);--surface:oklch(.175 0 0);--ink:oklch(.985 0 0);--ink-3:oklch(.72 0 0);--brand:oklch(.985 0 0);--brand-hover:oklch(.87 0 0);--on-brand:oklch(.205 0 0);--ring:0 0 0 2px oklch(.175 0 0),0 0 0 4px oklch(.708 0 0);--shadow:0 0 #0000;--raised:0 0 0 1px oklch(1 0 0/.09)}}
59
+ :root{color-scheme:light;--bg:oklch(.985 0 0);--surface:oklch(1 0 0);--ink:oklch(.205 0 0);--ink-3:oklch(.46 0 0);--brand:oklch(.205 0 0);--brand-hover:oklch(.3 0 0);--on-brand:oklch(.985 0 0);--ring:0 0 0 2px oklch(.985 0 0),0 0 0 4px oklch(.556 0 0);--shadow:0 1px 2px 0 oklch(0 0 0/.05);--line:oklch(.87 0 0);--line-strong:oklch(.556 0 0);--danger:oklch(.505 .213 27.518);--ease-out:cubic-bezier(.23,1,.32,1);--ease-press:cubic-bezier(.33,1,.68,1);--ease-hover:cubic-bezier(.25,.46,.45,.94)}
60
+ @media(prefers-color-scheme:dark){:root{color-scheme:dark;--bg:oklch(.145 0 0);--surface:oklch(.175 0 0);--ink:oklch(.985 0 0);--ink-3:oklch(.72 0 0);--brand:oklch(.985 0 0);--brand-hover:oklch(.87 0 0);--on-brand:oklch(.205 0 0);--ring:0 0 0 2px oklch(.145 0 0),0 0 0 4px oklch(.708 0 0);--shadow:0 0 #0000;--line:oklch(.32 0 0);--line-strong:oklch(.708 0 0);--danger:oklch(.704 .191 22.216)}}
47
61
  *{box-sizing:border-box}
48
62
  html{height:100%;-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:transparent}
49
- body{margin:0;min-height:100%;display:grid;place-items:center;padding:max(24px,env(safe-area-inset-top)) max(16px,env(safe-area-inset-right)) max(24px,env(safe-area-inset-bottom)) max(16px,env(safe-area-inset-left));background:var(--bg);color:var(--ink);font:14px/20px Geist,ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;font-optical-sizing:auto;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;text-rendering:optimizeLegibility}
50
- .gate{width:100%;max-width:360px;padding:32px;background:var(--surface);border-radius:12px;box-shadow:var(--raised);transition:opacity 240ms var(--ease-out),transform 240ms var(--ease-out)}
63
+ body{margin:0;min-height:100%;display:grid;place-items:start center;padding:max(24px,env(safe-area-inset-top),min(20vh,160px)) max(16px,env(safe-area-inset-right)) max(24px,env(safe-area-inset-bottom)) max(16px,env(safe-area-inset-left));background:var(--bg);color:var(--ink);font:14px/1.5 Geist,ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;font-optical-sizing:auto;font-synthesis:none;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;text-rendering:optimizeLegibility}
64
+ .gate{width:100%;max-width:360px;transition:opacity 240ms var(--ease-out),transform 240ms var(--ease-out)}
51
65
  @starting-style{.gate{opacity:0;transform:translateY(6px)}}
52
- h1{margin:0 0 4px;font-size:20px;line-height:28px;font-weight:600;letter-spacing:-.02em;text-wrap:balance}
53
- p{margin:0;color:var(--ink-3);text-wrap:pretty}
54
- p+p{margin-top:8px}
55
- strong{font-weight:500;color:var(--ink)}
66
+ .brand{margin-bottom:48px;font-weight:500;overflow-wrap:anywhere}
67
+ h1{margin:0;font-size:28px;line-height:1.15;font-weight:600;letter-spacing:-.02em;text-wrap:balance;overflow-wrap:anywhere}
68
+ p{margin:0;text-wrap:pretty}
69
+ .lead{margin-top:12px;font-size:16px;overflow-wrap:anywhere}
70
+ .note{margin-top:8px;color:var(--ink-3)}
71
+ strong{font-weight:500;overflow-wrap:anywhere}
56
72
  form{margin:0}
57
- .go{display:block;width:100%;height:44px;margin-top:24px;padding:0;border:0;border-radius:6px;background:var(--brand);color:var(--on-brand);font:inherit;font-weight:500;line-height:44px;text-align:center;text-decoration:none;cursor:pointer;touch-action:manipulation;-webkit-user-select:none;user-select:none;box-shadow:var(--shadow);transition:background-color 120ms var(--ease-hover),transform 160ms var(--ease-press)}
73
+ .field{margin-top:32px}
74
+ label{display:block;font-weight:500}
75
+ input{display:block;width:100%;height:44px;margin:8px 0 0;padding:0 12px;border:1px solid var(--line);border-radius:6px;background:var(--surface);color:var(--ink);font:inherit;outline:2px solid transparent;outline-offset:2px;touch-action:manipulation;transition:border-color 120ms var(--ease-hover)}
76
+ input:focus-visible{border-color:var(--line-strong)}
77
+ input[aria-invalid=true]{border-color:var(--danger)}
78
+ input[inputmode=numeric]{font-variant-numeric:tabular-nums}
79
+ .hint{margin-top:8px;color:var(--ink-3)}
80
+ .hint[data-error]{color:var(--danger)}
81
+ .go{display:block;width:100%;height:44px;margin-top:24px;padding:0;border:0;border-radius:6px;background:var(--brand);color:var(--on-brand);font:inherit;font-weight:500;line-height:44px;text-align:center;text-decoration:none;cursor:pointer;touch-action:manipulation;-webkit-user-select:none;user-select:none;box-shadow:var(--shadow);transition:background-color 120ms var(--ease-hover),color 120ms var(--ease-hover),transform 160ms var(--ease-press)}
58
82
  .go:focus-visible{outline:2px solid transparent;outline-offset:2px;box-shadow:var(--ring)}
59
83
  .go:active{transform:scale(.97)}
60
- @media(hover:hover) and (pointer:fine){.go:hover{background:var(--brand-hover)}}
61
- @media(max-width:400px){.gate{padding:24px}}
84
+ .alt{width:auto;margin-top:4px;background:transparent;color:var(--ink);box-shadow:none;text-align:left}
85
+ .help{margin-top:32px;color:var(--ink-3)}
86
+ .alt+.help,form+form+.help{margin-top:12px}
87
+ @media(hover:hover) and (pointer:fine){.go:hover{background:var(--brand-hover)}.alt:hover{background:transparent;color:var(--ink-3)}}
88
+ @media(pointer:coarse){input{font-size:16px}}
89
+ @media(prefers-contrast:more){input:focus-visible{box-shadow:var(--ring)}}
90
+ @media(max-width:400px){.brand{margin-bottom:32px}}
62
91
  @media(prefers-reduced-motion:reduce){.gate{transition:opacity 240ms var(--ease-out)}@starting-style{.gate{transform:none}}.go:active{transform:none}}
92
+ @media(forced-colors:active){input:focus-visible{outline-color:Highlight}}
63
93
  `;
64
- function shell(siteName, page, body) {
94
+ /** The line over every title: the studio's name when its mailer gives one, else the site's. Never a client's (S10). */
95
+ const brandOf = ({ siteName, mailer }) => mailer && !mailer.name.includes('@') ? mailer.name : siteName;
96
+ const line = (name, html) => (html ? `<p class="${name}">${html}</p>\n` : '');
97
+ function shell(face, page, { title, lead, note, body, help }) {
65
98
  return `<!doctype html>
66
99
  <html lang="en">
67
100
  <head>
@@ -69,52 +102,130 @@ function shell(siteName, page, body) {
69
102
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
70
103
  <meta name="robots" content="noindex, nofollow">
71
104
  <meta name="color-scheme" content="light dark">
72
- <title>${escapeHtml(siteName)}</title>
105
+ <title>${escapeHtml(face.siteName)}</title>
73
106
  <link rel="icon" type="image/svg+xml" href="/favicon.svg">
74
107
  <link rel="preload" href="${GATE_FONT}" as="font" type="font/woff2" crossorigin>
75
108
  <style>${CSS}</style>
76
109
  </head>
77
110
  <body>
78
111
  <main class="gate" data-gate="${page}">
79
- <h1>${escapeHtml(siteName)}</h1>
80
- ${body}
81
- </main>
112
+ <p class="brand">${escapeHtml(brandOf(face))}</p>
113
+ <h1>${title}</h1>
114
+ ${line('lead', lead)}${line('note', note)}${body ? `${body}\n` : ''}${line('help', help)}</main>
82
115
  </body>
83
116
  </html>
84
117
  `;
85
118
  }
86
- const signInPage = (siteName) => shell(siteName, 'sign-in', `<p>To sign in, open the link the studio sent you. Each link signs in one device, then stops working.</p>
87
- <p>For another device, or if your link has stopped working, ask the studio for a new one.</p>`);
119
+ const hidden = (fields) => Object.entries(fields)
120
+ .map(([name, value]) => `<input type="hidden" name="${name}" value="${escapeHtml(String(value))}">`)
121
+ .join('');
122
+ /** With a mailer, the sign-in page asks for an address: `next` is the path the person asked for. */
123
+ const emailForm = (next) => `<form method="post" action="${CODE_ASK}">${hidden({ next })}
124
+ <div class="field"><label for="email">Email</label>
125
+ <input id="email" name="email" type="email" autocomplete="email" spellcheck="false" maxlength="254" required></div>
126
+ <button class="go" type="submit">Send code</button></form>`;
127
+ /** The sign-in page; `next` (a path on this host) makes it the email form, given only when the studio has a mailer. */
128
+ const signInPage = (face, next = null) => shell(face, 'sign-in', next === null
129
+ ? {
130
+ title: 'Sign in',
131
+ lead: 'Open the link the studio sent you.',
132
+ note: 'Each link works once, on one device.',
133
+ help: 'Need a new link? Ask the studio.',
134
+ }
135
+ : {
136
+ title: 'Sign in',
137
+ lead: 'Get a sign-in code by email.',
138
+ body: emailForm(next),
139
+ help: 'Have a link from the studio? Open it instead.',
140
+ });
141
+ const CODE_HINTS = {
142
+ wrong: 'That code did not work. Try again.',
143
+ expired: 'That code expired. Send another.',
144
+ tries: 'Too many tries. Send another.',
145
+ };
146
+ const CODE_HINT = `The ${CODE.digits} digits from the email.`;
147
+ const CODE_SENT = 'If that address has access, a code is on its way.';
148
+ // A dead code (expired, or out of tries) cannot sign anyone in, so its page
149
+ // shows one button, Send another, and no Sign in.
150
+ const codePage = (face, { email, next, sent, tries, problem }) => {
151
+ const who = email ? `<strong>${escapeHtml(email)}</strong>` : 'that address';
152
+ const invalid = problem ? ' aria-invalid="true"' : '';
153
+ const dead = problem === 'expired' || problem === 'tries';
154
+ const hint = problem
155
+ ? `<p class="hint" id="code-hint" data-error>${CODE_HINTS[problem]}</p>`
156
+ : `<p class="hint" id="code-hint">${CODE_HINT}</p>`;
157
+ return shell(face, 'code', {
158
+ title: 'Check your email',
159
+ lead: `If ${who} has access, a code is on its way.`,
160
+ body: `<form method="post" action="${CODE_USE}">${hidden({ email, next, sent, tries })}
161
+ <div class="field"><label for="code">Code</label>
162
+ <input id="code" name="code" type="text" inputmode="numeric" autocomplete="one-time-code" spellcheck="false" maxlength="12" required aria-describedby="code-hint"${invalid}>
163
+ ${hint}</div>${dead ? '' : '\n<button class="go" type="submit">Sign in</button>'}</form>
164
+ <form method="post" action="${CODE_ASK}">${hidden({ email, next })}<button class="go${dead ? '' : ' alt'}" type="submit">Send another</button></form>`,
165
+ help: 'No code? Check spam or ask the studio.',
166
+ });
167
+ };
168
+ const SLOW = 'Too many tries. Wait a minute, then try again.';
169
+ /** The cap's answer, the same whatever was typed. */
170
+ const slowPage = (face) => shell(face, 'slow', { title: 'Too many tries', lead: 'Wait a minute, then try again.' });
88
171
  // A GET shows who the link is for and a POST signs them in, so a mail
89
- // scanner that opens every link never uses it up.
90
- const linkPage = (siteName, person) => shell(siteName, 'link', `<p>This link signs in <strong>${escapeHtml(person.name)}</strong>, ${escapeHtml(person.team)}, on this device.</p>
91
- <p>It works once. For another device, ask the studio for a new link.</p>
92
- <form method="post"><button class="go" type="submit" autofocus>Continue</button></form>`);
172
+ // scanner that opens every link never uses it up. `byEmail`: their address
173
+ // gets a code on this host (E4, E5), so "next time" is true for them.
174
+ const linkPage = (face, person, byEmail) => shell(face, 'link', {
175
+ title: `Sign in as ${escapeHtml(person.name)}`,
176
+ lead: `You were invited for ${escapeHtml(person.team)}. This link works once, on this device.`,
177
+ body: '<form method="post"><button class="go" type="submit" autofocus>Continue</button></form>',
178
+ help: face.mailer && byEmail
179
+ ? 'Next time, sign in with your email.'
180
+ : 'For another device, ask the studio for a new link.',
181
+ });
93
182
  // Someone who opens their link again on a device it already signed in gets
94
183
  // here too, so the page offers the way in as well: the prototypes on a
95
184
  // client's host, the list of clients on the studio's own.
96
- const usedPage = (siteName, home = 'prototypes') => shell(siteName, 'used', `<p>This link has been used, has expired or was removed. Each link signs in one device, then stops working.</p>
97
- <p>Ask the studio for a new one. If this device is already signed in, open the ${home}.</p>
98
- <a class="go" href="/">Open the ${home}</a>`);
185
+ const usedPage = (face, home = 'prototypes') => shell(face, 'used', {
186
+ title: 'This link no longer works',
187
+ lead: 'It has been used, has expired or was removed. Each link signs in one device.',
188
+ note: `Ask the studio for a new one. If this device is already signed in, open the ${home}.`,
189
+ body: `<a class="go" href="/">Open the ${home}</a>`,
190
+ });
99
191
  /**
100
192
  * On the studio's own host, after Open: why the client did not open, and the
101
193
  * way back to the clients. Only a Studio person signed in there meets it.
102
194
  */
103
- const stoppedPage = (siteName, why) => shell(siteName, 'stopped', `<p>${escapeHtml(why)}</p>\n<a class="go" href="/">Back to the clients</a>`);
195
+ const stoppedPage = (face, why) => shell(face, 'stopped', {
196
+ title: 'This did not open',
197
+ lead: escapeHtml(why),
198
+ body: '<a class="go" href="/">Back to the clients</a>',
199
+ });
104
200
  const SIGNED_OUT = 'Sign in with the link the studio sent you.';
105
201
  const USED = 'This link has been used, has expired or was removed.';
106
202
  const OPEN_IN_BROWSER = 'Open this link in a browser to sign in.';
203
+ const SAMPLE = { email: 'rae@acme.example', next: '/', sent: 0, tries: 0 };
204
+ const LONG_EMAIL = 'rae.chen-montgomery.design-review@product-studio.acme-international.example';
205
+ const sampleCode = (face, problem, email = SAMPLE.email) => codePage(face, { ...SAMPLE, email, problem });
107
206
  const PREVIEWS = {
108
- 'sign-in': signInPage,
109
- link: (siteName) => linkPage(siteName, { name: 'Rae Chen', team: 'Acme' }),
110
- used: (siteName) => usedPage(siteName),
111
- stopped: (siteName) => stoppedPage(siteName, NOT_OPENED),
207
+ 'sign-in': (face) => signInPage(face),
208
+ email: (face) => signInPage(face, '/'),
209
+ // As with email on, the link's page says how to sign in next time; link-no-email
210
+ // is someone whose address gets no code there (none, or Studio on a client's host).
211
+ link: (face) => linkPage({ ...face, mailer: { name: face.siteName } }, { name: 'Rae Chen', team: 'Acme' }, true),
212
+ 'link-no-email': (face) => linkPage({ ...face, mailer: { name: face.siteName } }, { name: 'Rae Chen', team: 'Acme' }, false),
213
+ used: (face) => usedPage(face),
214
+ stopped: (face) => stoppedPage(face, NOT_OPENED),
215
+ code: (face) => sampleCode(face, null),
216
+ 'code-wrong': (face) => sampleCode(face, 'wrong'),
217
+ 'code-expired': (face) => sampleCode(face, 'expired'),
218
+ 'code-tries': (face) => sampleCode(face, 'tries'),
219
+ 'code-long': (face) => sampleCode(face, 'wrong', LONG_EMAIL),
220
+ slow: slowPage,
112
221
  };
113
- // `design-hub dev` has no gate; the Vite plugin serves this at /_gate/ (?page=link or ?page=used) so the pages can be reviewed.
222
+ // `design-hub dev` has no gate; the Vite plugin serves this at /_gate/ so the pages can be reviewed:
223
+ // ?page=link, link-no-email, used, stopped, email (sign-in with the email form), code, code-wrong, code-expired,
224
+ // code-tries, code-long (a long address) and slow (the cap's 429).
114
225
  export async function gatePreview(page, siteName = DEFAULT_SITE_NAME) {
115
226
  // hasOwn, so ?page=__proto__ or toString never reaches Object.prototype.
116
- const render = page !== null && Object.hasOwn(PREVIEWS, page) ? PREVIEWS[page] : signInPage;
117
- return { html: render(siteName), csp: await csp() };
227
+ const render = page !== null && Object.hasOwn(PREVIEWS, page) ? PREVIEWS[page] : PREVIEWS['sign-in'];
228
+ return { html: render({ siteName }), csp: await csp() };
118
229
  }
119
230
  let cspPromise;
120
231
  function csp() {
@@ -170,6 +281,67 @@ const NOT_FOUND = 'Not found.';
170
281
  /** The store did not answer: a 503 that passes, so it says when to try again. */
171
282
  export const storeDown = (request) => plain(request, 503, STORE_DOWN, { retryAfter: 30 });
172
283
  const STORE_DOWN = 'The review store did not answer. Try again in a minute.';
284
+ /** The page a person who is signed out sees: with a mailer, the email form, sending them back to `request`'s path. */
285
+ const signInFor = (ctx) => {
286
+ const url = new URL(ctx.request.url);
287
+ return signInPage(ctx, ctx.mailer ? safeNext(`${url.pathname}${url.search}`) : null);
288
+ };
289
+ /**
290
+ * A page holding a form that POSTs here sends a same-origin referrer, as the
291
+ * link page does, so the POST carries a real Origin (Safari 14 to 16.3 sends
292
+ * no Sec-Fetch-Site, and `Origin: null` under no-referrer). Without a mailer
293
+ * the sign-in page holds no form and keeps no-referrer.
294
+ */
295
+ const FORM_PAGE = { referrer: 'same-origin' };
296
+ const signInExtra = (ctx) => (ctx.mailer ? FORM_PAGE : {});
297
+ /**
298
+ * Where a sign-in goes on to (E9): `value` when it is a path on this host,
299
+ * otherwise `/`. Resolved against a host nothing can name, so a `//host`,
300
+ * a backslash or a tab that a URL parser would turn into another host is `/`.
301
+ * The gate's own routes (`/_gate/…`) are `/` too: they answer a POST, so a
302
+ * sign-in sent back to one with a GET (Open pressed with the session ended)
303
+ * would meet "Method not allowed".
304
+ */
305
+ function safeNext(value) {
306
+ if (!value || value.length > 2048 || !value.startsWith('/'))
307
+ return '/';
308
+ try {
309
+ const url = new URL(value, 'https://next.invalid');
310
+ // A path the parser left starting `//` (`/.//host`, `/..//host`, `/./\\host`) is another host to a browser.
311
+ if (url.origin !== 'https://next.invalid' || /^[/\\]{2}/.test(url.pathname))
312
+ return '/';
313
+ if (url.pathname === '/_gate' || url.pathname.startsWith('/_gate/'))
314
+ return '/';
315
+ return `${url.pathname}${url.search}`;
316
+ }
317
+ catch {
318
+ return '/';
319
+ }
320
+ }
321
+ // The second press (email.md, section 3): a page that holds a form which uses
322
+ // a link or a code sets this, and the claim keeps its hash.
323
+ const TRY_COOKIE = '__Host-hub_try';
324
+ const TRY_SECONDS = 10 * 60;
325
+ const tryCookie = () => `${TRY_COOKIE}=${base64url(crypto.getRandomValues(new Uint8Array(32)))}; Path=/; Max-Age=${TRY_SECONDS}; HttpOnly; Secure; SameSite=Strict`;
326
+ const browserOf = (request) => readCookie(request, TRY_COOKIE) ?? null;
327
+ /**
328
+ * Counts one request against the cap per network address, before any person
329
+ * is looked up: null when it may go on (or the adapter gave no address), the
330
+ * 429 when it is over, the same whatever was typed, or a 503 when the store
331
+ * did not answer.
332
+ */
333
+ async function capped(ctx, review, kind) {
334
+ const { address, request } = ctx;
335
+ if (!address)
336
+ return null;
337
+ const within = await ask(() => review.hit(kind, address));
338
+ if (within === undefined)
339
+ return storeDown(request);
340
+ if (within)
341
+ return null;
342
+ const retryAfter = 60 - ctx.at.getUTCSeconds();
343
+ return page(request, 429, slowPage(ctx), SLOW, { retryAfter });
344
+ }
173
345
  /**
174
346
  * A store call that can fail without signing anyone out: `undefined` when the
175
347
  * store did not answer, so the caller answers 503 and leaves the cookie alone.
@@ -188,14 +360,19 @@ async function ask(run) {
188
360
  * 404, its way in the host's own `/`. On the studio's own host only Studio
189
361
  * links are looked up, so a Client's link there reads as an unknown one.
190
362
  */
191
- const noLink = ({ siteName, request }, at) => page(request, 404, usedPage(siteName, at === STUDIO_SITE ? 'clients' : 'prototypes'), USED);
363
+ const noLink = (ctx, at) => page(ctx.request, 404, usedPage(ctx, at === STUDIO_SITE ? 'clients' : 'prototypes'), USED);
192
364
  async function showLink(ctx, review, at, token) {
193
- const { siteName, request } = ctx;
365
+ const { request } = ctx;
194
366
  const person = await ask(() => review.peekLink(at, token));
195
367
  if (person === undefined)
196
368
  return storeDown(request);
369
+ // A code reaches a Client on their client's host and Studio on the studio's own only (E4).
370
+ const byEmail = (p) => p.email !== null && (p.kind === 'studio') === (at === STUDIO_SITE);
197
371
  return person
198
- ? page(request, 200, linkPage(siteName, person), OPEN_IN_BROWSER, { referrer: 'same-origin' })
372
+ ? page(request, 200, linkPage(ctx, person, byEmail(person)), OPEN_IN_BROWSER, {
373
+ referrer: 'same-origin',
374
+ cookie: tryCookie(),
375
+ })
199
376
  : noLink(ctx, at);
200
377
  }
201
378
  /** The cookie for someone the store just said yes to, lasting to their access end. */
@@ -212,7 +389,7 @@ function signedIn(cookie, location) {
212
389
  }
213
390
  async function signInWithLink(ctx, { review, gate }, at, token) {
214
391
  const { request } = ctx;
215
- const person = await ask(() => review.useLink(at, token));
392
+ const person = await ask(() => review.useLink(at, token, browserOf(request)));
216
393
  if (person === undefined)
217
394
  return storeDown(request);
218
395
  if (!person)
@@ -226,20 +403,105 @@ async function link(ctx, setup, at, token) {
226
403
  return plain(request, 403, 'Forbidden');
227
404
  if (request.method !== 'POST' && !isRead(request))
228
405
  return plain(request, 405, 'Method not allowed', { allow: 'GET, HEAD, POST' });
406
+ const over = await capped(ctx, setup.review, request.method === 'POST' ? 'post' : 'view');
407
+ if (over)
408
+ return over;
229
409
  return request.method === 'POST'
230
410
  ? signInWithLink(ctx, setup, at, token)
231
411
  : showLink(ctx, setup.review, at, token);
232
412
  }
413
+ /** Form bodies the code pages send: an address, a code, a path and two numbers, never more than this. */
414
+ const MAX_CODE_FORM_BYTES = 4096;
415
+ /** A same-origin form's fields; empty for any other body, so it is answered as a form with nothing typed. */
416
+ async function formOf(request) {
417
+ const type = request.headers.get('content-type') ?? '';
418
+ if (!type.startsWith('application/x-www-form-urlencoded'))
419
+ return new URLSearchParams();
420
+ const text = await request.text();
421
+ return text.length > MAX_CODE_FORM_BYTES ? new URLSearchParams() : new URLSearchParams(text);
422
+ }
423
+ /** The code page, with a fresh `try` cookie for its Sign in: for a fetch, its one sentence. */
424
+ const codeAnswer = (ctx, status, state) => page(ctx.request, status, codePage(ctx, state), state.problem ? CODE_HINTS[state.problem] : CODE_SENT, {
425
+ ...FORM_PAGE,
426
+ cookie: tryCookie(),
427
+ });
428
+ /**
429
+ * Mails a code, after the response, and records the answer for Studio
430
+ * (email.md, "When mail breaks"). Never rejects: a mailer that fails or
431
+ * hangs changes nothing a person sees. The idempotency key is the person and
432
+ * the code's hash, so a second send of one code is one mail.
433
+ */
434
+ async function mailCode(mailer, review, asked) {
435
+ const { person, code, hash } = asked;
436
+ await sendAndRecord(mailer, review, codeMail(mailer.name, person.email ?? '', code, `${person.id}-${hash}`));
437
+ }
438
+ /**
439
+ * POST /_gate/code: a code for whoever holds the address where `at` is. The
440
+ * answer is the code page, whatever the address: unknown, another client's,
441
+ * Studio's on a client's host, revoked, over a limit, or known. The mail, if
442
+ * any, is work after the response.
443
+ */
444
+ async function askForCode(ctx, mailer, { review }, at, form) {
445
+ const email = (form.get('email') ?? '').trim();
446
+ const next = safeNext(form.get('next'));
447
+ const asked = await ask(() => review.askCode(at, email));
448
+ if (asked === undefined)
449
+ return storeDown(ctx.request);
450
+ const answer = await codeAnswer(ctx, 200, { email, next, sent: ctx.at.getTime(), tries: 0, problem: null });
451
+ return asked ? { answer, after: mailCode(mailer, review, asked) } : answer;
452
+ }
453
+ /** The words a refused code gets, from what the page carried: past the code's time, past its tries, or wrong. */
454
+ function problemOf(sent, tries, at) {
455
+ if (at.getTime() - sent >= CODE.minutes * 60_000)
456
+ return 'expired';
457
+ return tries >= CODE.tries ? 'tries' : 'wrong';
458
+ }
459
+ /** A whole count the page carried, or 0. */
460
+ const countOf = (value) => {
461
+ const n = Number(value ?? '');
462
+ return Number.isSafeInteger(n) && n >= 0 ? n : 0;
463
+ };
464
+ /** POST /_gate/code/use: a 303 to `next` with the cookie, or the code page again with what went wrong. */
465
+ async function signInWithCode(ctx, { review, gate }, at, form) {
466
+ const { request } = ctx;
467
+ const email = (form.get('email') ?? '').trim();
468
+ const next = safeNext(form.get('next'));
469
+ const person = await ask(() => review.useCode(at, email, form.get('code') ?? '', browserOf(request)));
470
+ if (person === undefined)
471
+ return storeDown(request);
472
+ if (person)
473
+ return signedIn(await sessionFor(gate, person, ctx.at), next);
474
+ const sent = countOf(form.get('sent')) || ctx.at.getTime();
475
+ const tries = Math.min(countOf(form.get('tries')) + 1, CODE.tries);
476
+ return codeAnswer(ctx, 401, { email, next, sent, tries, problem: problemOf(sent, tries, ctx.at) });
477
+ }
478
+ /**
479
+ * Email sign-in where `at` is, only with a mailer: a same-origin POST,
480
+ * counted against the cap before anyone is looked up.
481
+ */
482
+ async function code(ctx, mailer, setup, at, step) {
483
+ const { request } = ctx;
484
+ if (request.method !== 'POST')
485
+ return plain(request, 405, 'Method not allowed', { allow: 'POST' });
486
+ if (!sameOrigin(request))
487
+ return plain(request, 403, 'Forbidden');
488
+ const over = await capped(ctx, setup.review, 'post');
489
+ if (over)
490
+ return over;
491
+ const form = await formOf(request);
492
+ return step === 'ask' ? askForCode(ctx, mailer, setup, at, form) : signInWithCode(ctx, setup, at, form);
493
+ }
233
494
  /**
234
495
  * No session. A page gets the sign-in page, and anything else (an asset, a
235
496
  * fetch, a POST to any path but a link) a plain 401: there is nothing to
236
497
  * sign in with here. A cookie that was sent but does not hold is cleared.
237
498
  */
238
- function signedOut({ siteName, request }, staleCookie) {
499
+ function signedOut(ctx, staleCookie) {
500
+ const { request } = ctx;
239
501
  const extra = staleCookie ? { cookie: clearedCookie(PERSON_COOKIE) } : {};
240
502
  if (!isRead(request))
241
503
  return plain(request, 401, SIGNED_OUT, extra);
242
- return page(request, 401, signInPage(siteName), SIGNED_OUT, extra);
504
+ return page(request, 401, signInFor(ctx), SIGNED_OUT, { ...extra, ...signInExtra(ctx) });
243
505
  }
244
506
  const passHeaders = (cookie) => ({
245
507
  'cache-control': 'private, no-store',
@@ -398,21 +660,21 @@ async function proven({ review, place, route }, request, pathname) {
398
660
  * a used link's answer; nothing is used up by a HEAD or a POST.
399
661
  */
400
662
  async function openHandoff(ctx, { review, place }, token) {
401
- const { request, siteName } = ctx;
663
+ const { request } = ctx;
402
664
  if (request.method !== 'GET')
403
665
  return plain(request, 405, 'Method not allowed', { allow: 'GET' });
404
666
  const claimed = await ask(() => review.claimHandoff(place.scope, token));
405
667
  if (claimed === undefined)
406
668
  return storeDown(request);
407
669
  if (!claimed)
408
- return page(request, 404, usedPage(siteName), USED);
670
+ return page(request, 404, usedPage(ctx), USED);
409
671
  const to = claimed.project ? `/${claimed.project}/` : '/';
410
672
  return signedIn(await sessionFor(place.gate, claimed.person, ctx.at), to);
411
673
  }
412
674
  const NOT_OPENED = 'This client or project cannot be opened now. It may still be waiting for its address, or it was archived or is not shared yet.';
413
675
  const PICK_A_CLIENT = 'Open a client from the list of clients.';
414
676
  /** A handoff that did not start, for a browser the stopped page, for anything else its text. */
415
- const stopped = (ctx, status, why, extra = {}) => page(ctx.request, status, stoppedPage(ctx.siteName, why), why, extra);
677
+ const stopped = (ctx, status, why, extra = {}) => page(ctx.request, status, stoppedPage(ctx, why), why, extra);
416
678
  /** Form bodies the studio hub sends: two slugs, never more than this. */
417
679
  const MAX_FORM_BYTES = 1024;
418
680
  /** The client and project a handoff is asked for, from a same-origin form POST; null for anything else. */
@@ -448,7 +710,10 @@ async function startHandoff(ctx, review, { claim }) {
448
710
  if (person === undefined)
449
711
  return stopped(ctx, 503, STORE_DOWN, { retryAfter: 30 });
450
712
  if (!person)
451
- return page(request, 401, signInPage(ctx.siteName), SIGNED_OUT, { cookie: clearedCookie(PERSON_COOKIE) });
713
+ return page(request, 401, signInFor(ctx), SIGNED_OUT, {
714
+ cookie: clearedCookie(PERSON_COOKIE),
715
+ ...signInExtra(ctx),
716
+ });
452
717
  let made;
453
718
  try {
454
719
  made = await review.startHandoff(person, asked);
@@ -490,6 +755,8 @@ async function studioHost(ctx, { review, keys }, url) {
490
755
  const gate = studioGate(keys);
491
756
  if (where.kind === 'none')
492
757
  return notFound(request);
758
+ if (where.kind === 'code')
759
+ return ctx.mailer ? code(ctx, ctx.mailer, { review, gate }, STUDIO_SITE, where.step) : notFound(request);
493
760
  if (where.kind === 'link')
494
761
  return link(ctx, { review, gate }, STUDIO_SITE, where.token);
495
762
  if (where.kind === 'proof')
@@ -507,10 +774,12 @@ async function studioHost(ctx, { review, keys }, url) {
507
774
  : { pass: 'next', headers };
508
775
  }
509
776
  /** The gate a host's adapter runs on every request (vercel/proxy.ts on Vercel). Its sign-in page names no client (S10). */
510
- export function createGate({ siteName = DEFAULT_SITE_NAME, now = () => new Date() } = {}) {
777
+ export function createGate(options = {}) {
778
+ const { siteName = DEFAULT_SITE_NAME, now = () => new Date() } = options;
511
779
  const hosts = hostCache(now);
512
- return async function gate(request) {
513
- const ctx = { siteName, request, at: now() };
780
+ const mailerNow = () => ('mailer' in options ? (options.mailer ?? null) : chooseMailer(process.env));
781
+ return async function gate(request, { address = null } = {}) {
782
+ const ctx = { siteName, request, at: now(), mailer: mailerNow(), address };
514
783
  const url = new URL(request.url);
515
784
  const looked = await lookUp(request, hosts, ctx.at);
516
785
  if ('refused' in looked)
@@ -526,6 +795,8 @@ export function createGate({ siteName = DEFAULT_SITE_NAME, now = () => new Date(
526
795
  return link(ctx, { review: found.review, gate: place.gate }, place.scope, route.token);
527
796
  if (route.kind === 'handoff')
528
797
  return openHandoff(ctx, found, route.token);
798
+ if (route.kind === 'code' && ctx.mailer)
799
+ return code(ctx, ctx.mailer, { review: found.review, gate: place.gate }, place.scope, route.step);
529
800
  if (route.kind === 'asset' && isRead(request))
530
801
  return { pass: 'next' };
531
802
  const admitted = await admit(found, request, ctx.at);
@@ -0,0 +1,60 @@
1
+ import { type Person } from '../core/review/model.ts';
2
+ import type { Review, Sent } from '../core/review/service.ts';
3
+ export type { Sent };
4
+ /** One mail. `key` is its idempotency key: the same key twice is one mail. */
5
+ export type Mail = {
6
+ to: string;
7
+ subject: string;
8
+ text: string;
9
+ html: string;
10
+ key: string;
11
+ };
12
+ export interface Mailer {
13
+ /** Who the mail is from, as the studio names itself: the name in MAIL_FROM. */
14
+ readonly name: string;
15
+ /** Never throws: an answer the adapter does not know is refused; none in 5 seconds, or a network error, is down. */
16
+ send(mail: Mail): Promise<Sent>;
17
+ }
18
+ /** The name in a sender (`Suits & Sandals <signin@mail.example.com>`), or its address when it has none. */
19
+ export declare function senderName(from: string): string;
20
+ /** The studio's mailer: null unless both RESEND_API_KEY and MAIL_FROM are set, so a studio that wants only links sets up nothing. */
21
+ export declare function chooseMailer(env: Record<string, string | undefined>, fetcher?: typeof fetch): Mailer | null;
22
+ /**
23
+ * The code mail (email.md, section 3): the studio's name, the code in two
24
+ * groups of four, how long it lasts, and one line to ignore it. No link, no
25
+ * tracking, no image. The subject starts with the code, so it reads from a
26
+ * notification. `key` is the person and the code's hash, so each new code is
27
+ * a new mail and a second send of one code is not.
28
+ */
29
+ export declare function codeMail(studio: string, to: string, code: string, key: string): Mail;
30
+ /**
31
+ * The invite (email.md, E10): who gave them access, their one-time link as
32
+ * one button and as plain text, that it works once on one device, and the
33
+ * address to sign in at with this email from then on: their client's own
34
+ * host, or the studio's for a Studio person, never another's. Its words are
35
+ * the link page's ("Sign in as", "Next time, sign in with your email"). No
36
+ * tracking, no image. `key` is the person's id: one add, one mail.
37
+ */
38
+ export declare function inviteMail(studio: string, person: {
39
+ id: string;
40
+ name: string;
41
+ email: string;
42
+ }, link: string, address: string): Mail;
43
+ /** What an add says of the invite: what the mailer answered, or off when none was sent. */
44
+ export type Mailed = Sent | 'off';
45
+ /**
46
+ * Sends one mail and records the answer for Studio (recordMail, email.md,
47
+ * "When mail breaks"): the one way the studio's mail goes out, a code's or an
48
+ * invite's. Never rejects: a mailer that throws is down, and a record that
49
+ * fails is logged, so the answer stands whatever the store does.
50
+ */
51
+ export declare function sendAndRecord(mailer: Mailer, review: Pick<Review, 'recordMail'>, mail: Mail): Promise<Sent>;
52
+ /**
53
+ * Mails a new person their invite, with their link on `home`, the host they
54
+ * sign in on, and records the answer as a code's is (sendAndRecord). Waits
55
+ * for the send, since whoever adds is Studio (E7 is about the person signing
56
+ * in). Never throws: the person and their link stand whatever happens.
57
+ */
58
+ export declare const sendInvite: (mailer: Mailer, review: Pick<Review, 'recordMail'>, person: Person & {
59
+ email: string;
60
+ }, token: string, home: string) => Promise<Sent>;