@milesroxas/design-hub 0.12.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.
- package/README.md +5 -5
- package/core/prototype.test.ts +12 -1
- package/core/prototype.ts +21 -2
- package/core/review/model.ts +71 -6
- package/core/review/service.test.ts +575 -39
- package/core/review/service.ts +452 -25
- package/core/review/store.ts +47 -6
- package/core/review/suite-kv.ts +17 -0
- package/dist/core/prototype.d.ts +20 -2
- package/dist/core/prototype.js +17 -2
- package/dist/core/review/model.d.ts +42 -3
- package/dist/core/review/model.js +52 -3
- package/dist/core/review/service.d.ts +81 -7
- package/dist/core/review/service.js +407 -23
- package/dist/core/review/store.d.ts +29 -2
- package/dist/core/review/store.js +6 -2
- package/dist/core/review/suite-kv.d.ts +7 -0
- package/dist/core/review/suite-kv.js +12 -0
- package/dist/scripts/client.d.ts +1 -1
- package/dist/scripts/client.js +4 -4
- package/dist/scripts/lib/cli.js +5 -0
- package/dist/scripts/lib/dns.d.ts +16 -2
- package/dist/scripts/lib/dns.js +66 -3
- package/dist/scripts/lib/fake-host.d.ts +17 -3
- package/dist/scripts/lib/fake-host.js +56 -10
- package/dist/scripts/lib/host.d.ts +15 -25
- package/dist/scripts/lib/host.js +15 -324
- package/dist/scripts/lib/resend.d.ts +36 -0
- package/dist/scripts/lib/resend.js +66 -0
- package/dist/scripts/lib/studio-deps.d.ts +23 -0
- package/dist/scripts/lib/studio-deps.js +46 -16
- package/dist/scripts/lib/studios.d.ts +16 -6
- package/dist/scripts/lib/studios.js +28 -10
- package/dist/scripts/lib/vercel-host.d.ts +17 -0
- package/dist/scripts/lib/vercel-host.js +416 -0
- package/dist/scripts/people.d.ts +16 -4
- package/dist/scripts/people.js +67 -17
- package/dist/scripts/share.js +3 -2
- package/dist/scripts/studio.d.ts +26 -4
- package/dist/scripts/studio.js +364 -19
- package/dist/server/api.d.ts +20 -7
- package/dist/server/api.js +83 -27
- package/dist/server/dev.js +21 -1
- package/dist/server/gate.d.ts +120 -0
- package/dist/server/gate.js +808 -0
- package/dist/server/mailer.d.ts +60 -0
- package/dist/server/mailer.js +104 -0
- package/dist/server/mailers/fake.d.ts +8 -0
- package/dist/server/mailers/fake.js +16 -0
- package/dist/server/mailers/resend.d.ts +21 -0
- package/dist/server/mailers/resend.js +49 -0
- package/dist/server/mark.d.ts +17 -0
- package/dist/server/mark.js +46 -1
- package/dist/server/session.d.ts +2 -1
- package/dist/server/session.js +6 -3
- package/dist/server/stores/backends.d.ts +22 -0
- package/dist/server/stores/backends.js +96 -0
- package/dist/server/{fake-upstash.js → stores/fake-upstash.js} +1 -1
- package/dist/server/stores/index.d.ts +41 -0
- package/dist/server/stores/index.js +63 -0
- package/dist/server/stores/pglite.d.ts +16 -0
- package/dist/server/stores/pglite.js +98 -0
- package/dist/server/stores/postgres.d.ts +63 -0
- package/dist/server/stores/postgres.js +153 -0
- package/dist/server/{upstash.d.ts → stores/upstash.d.ts} +1 -1
- package/dist/vercel/files.js +1 -1
- package/dist/vercel/proxy.d.ts +6 -82
- package/dist/vercel/proxy.js +24 -524
- package/dist/vite/plugin.js +4 -2
- package/kit/ui/Menu.tsx +29 -18
- package/kit/ui/layer.ts +41 -0
- package/package.json +3 -1
- package/shell/review/Bar.tsx +1 -0
- package/shell/review/Card.tsx +17 -7
- package/shell/review/People.tsx +908 -134
- package/shell/review/Review.tsx +2 -2
- package/shell/review/anchor.ts +6 -1
- package/shell/review/client.ts +41 -7
- package/shell/review/menu-place.test.ts +41 -0
- package/shell/review/place.test.ts +26 -1
- package/shell/review/place.ts +17 -0
- package/shell/review/review.css +97 -11
- package/shell/review/view.test.ts +115 -1
- package/shell/review/view.ts +92 -2
- package/shell/studio/StudioHub.tsx +1 -0
- package/shell/studio/hub.css +99 -13
- package/skills/miles-deploy/SKILL.md +26 -4
- package/templates/studio/.env.example +9 -0
- package/templates/studio/README.md +13 -0
- package/templates/studio/package.json +1 -1
- /package/dist/server/{fake-upstash.d.ts → stores/fake-upstash.d.ts} +0 -0
- /package/dist/server/{upstash.js → stores/upstash.js} +0 -0
|
@@ -0,0 +1,808 @@
|
|
|
1
|
+
// The gate in front of every path of every client's host, the review API
|
|
2
|
+
// included, free of any host: it answers each request with a Decision (pass
|
|
3
|
+
// on, pass on with headers, go on to another URL, or a Response it makes
|
|
4
|
+
// itself), and a host's adapter carries that out. On Vercel that is Routing
|
|
5
|
+
// Middleware (vercel/proxy.ts, a studio site's proxy.ts). There is one way in, a one-time link that
|
|
6
|
+
// Studio makes for one named person, on that person's client's host:
|
|
7
|
+
//
|
|
8
|
+
// GET /invite/<token> shows who the link is for, and uses nothing up, so
|
|
9
|
+
// a mail or chat preview that opens it costs nothing
|
|
10
|
+
// POST /invite/<token> uses the link up, sets the person's signed cookie
|
|
11
|
+
// (server/session.ts) and goes to the client's hub
|
|
12
|
+
//
|
|
13
|
+
// A used, expired or unknown link is 404. Studio has its own host as well,
|
|
14
|
+
// `studio.<apex>`, where only a Studio person's link and cookie hold, and
|
|
15
|
+
// from which a Studio person opens any client with a one-time handoff that
|
|
16
|
+
// the client's host claims (`/_gate/handoff/<token>`). Every other path needs
|
|
17
|
+
// the cookie, signed to the host's client. It carries when the store last said yes;
|
|
18
|
+
// after CHECK_SECONDS (5 minutes) the gate asks the store again on the next
|
|
19
|
+
// request of any kind, so a revoke, a sign out everywhere or a changed access
|
|
20
|
+
// end reaches every request within minutes. A store that does not answer is
|
|
21
|
+
// 503, never a sign out. A Client asking for a prototype that is not
|
|
22
|
+
// client-facing, its page or any file built from it under
|
|
23
|
+
// /<project>/_p/<slug>/, gets 404. Without a session a page gets the sign-in
|
|
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';
|
|
38
|
+
import { escapeHtml } from '../core/html.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';
|
|
41
|
+
import { ReviewError } from '../core/review/service.js';
|
|
42
|
+
import { studioReview } from './api.js';
|
|
43
|
+
import { hostCache, hostOf } from './hosts.js';
|
|
44
|
+
import { chooseMailer, codeMail, sendAndRecord } from './mailer.js';
|
|
45
|
+
import { clearedCookie, isFresh, issuePersonToken, PERSON_COOKIE, readCookie, readPersonToken, sameOrigin, sessionCookie, sessionSeconds, studioGate, } from './session.js';
|
|
46
|
+
export const DEFAULT_SITE_NAME = 'Prototypes';
|
|
47
|
+
// What the gate pages load before sign-in: the hub's face (the Vite plugin
|
|
48
|
+
// emits it at this fixed path, at the host root) and the favicon. Nothing else.
|
|
49
|
+
export { GATE_FONT };
|
|
50
|
+
// The gate pages. The CSS is a constant so its CSP hash is computed once and
|
|
51
|
+
// the pages carry no 'unsafe-inline', and they run no script at all. The gate
|
|
52
|
+
// is hub chrome, so it wears the hub's neutral system look (shell/system.css)
|
|
53
|
+
// inlined, never the project's brand. Geist (latin, variable) is the one
|
|
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.
|
|
57
|
+
const CSS = `
|
|
58
|
+
@font-face{font-family:Geist;src:url(${GATE_FONT}) format("woff2");font-weight:100 900;font-style:normal;font-display:swap}
|
|
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)}}
|
|
61
|
+
*{box-sizing:border-box}
|
|
62
|
+
html{height:100%;-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:transparent}
|
|
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)}
|
|
65
|
+
@starting-style{.gate{opacity:0;transform:translateY(6px)}}
|
|
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}
|
|
72
|
+
form{margin:0}
|
|
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)}
|
|
82
|
+
.go:focus-visible{outline:2px solid transparent;outline-offset:2px;box-shadow:var(--ring)}
|
|
83
|
+
.go:active{transform:scale(.97)}
|
|
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}}
|
|
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}}
|
|
93
|
+
`;
|
|
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 }) {
|
|
98
|
+
return `<!doctype html>
|
|
99
|
+
<html lang="en">
|
|
100
|
+
<head>
|
|
101
|
+
<meta charset="utf-8">
|
|
102
|
+
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
|
103
|
+
<meta name="robots" content="noindex, nofollow">
|
|
104
|
+
<meta name="color-scheme" content="light dark">
|
|
105
|
+
<title>${escapeHtml(face.siteName)}</title>
|
|
106
|
+
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
|
|
107
|
+
<link rel="preload" href="${GATE_FONT}" as="font" type="font/woff2" crossorigin>
|
|
108
|
+
<style>${CSS}</style>
|
|
109
|
+
</head>
|
|
110
|
+
<body>
|
|
111
|
+
<main class="gate" data-gate="${page}">
|
|
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>
|
|
115
|
+
</body>
|
|
116
|
+
</html>
|
|
117
|
+
`;
|
|
118
|
+
}
|
|
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.' });
|
|
171
|
+
// A GET shows who the link is for and a POST signs them in, so a mail
|
|
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
|
+
});
|
|
182
|
+
// Someone who opens their link again on a device it already signed in gets
|
|
183
|
+
// here too, so the page offers the way in as well: the prototypes on a
|
|
184
|
+
// client's host, the list of clients on the studio's own.
|
|
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
|
+
});
|
|
191
|
+
/**
|
|
192
|
+
* On the studio's own host, after Open: why the client did not open, and the
|
|
193
|
+
* way back to the clients. Only a Studio person signed in there meets it.
|
|
194
|
+
*/
|
|
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
|
+
});
|
|
200
|
+
const SIGNED_OUT = 'Sign in with the link the studio sent you.';
|
|
201
|
+
const USED = 'This link has been used, has expired or was removed.';
|
|
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 });
|
|
206
|
+
const PREVIEWS = {
|
|
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,
|
|
221
|
+
};
|
|
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).
|
|
225
|
+
export async function gatePreview(page, siteName = DEFAULT_SITE_NAME) {
|
|
226
|
+
// hasOwn, so ?page=__proto__ or toString never reaches Object.prototype.
|
|
227
|
+
const render = page !== null && Object.hasOwn(PREVIEWS, page) ? PREVIEWS[page] : PREVIEWS['sign-in'];
|
|
228
|
+
return { html: render({ siteName }), csp: await csp() };
|
|
229
|
+
}
|
|
230
|
+
let cspPromise;
|
|
231
|
+
function csp() {
|
|
232
|
+
cspPromise ??= sha256(CSS).then((css) => `default-src 'none'; style-src 'sha256-${base64(css)}'; script-src 'none'; font-src 'self'; img-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'`);
|
|
233
|
+
return cspPromise;
|
|
234
|
+
}
|
|
235
|
+
const NO_STORE = 'no-store, max-age=0';
|
|
236
|
+
function wantsHtml(request) {
|
|
237
|
+
const dest = request.headers.get('sec-fetch-dest');
|
|
238
|
+
if (dest)
|
|
239
|
+
return dest === 'document' || dest === 'iframe';
|
|
240
|
+
return (request.headers.get('accept') ?? '').includes('text/html');
|
|
241
|
+
}
|
|
242
|
+
export const isRead = (request) => request.method === 'GET' || request.method === 'HEAD';
|
|
243
|
+
/**
|
|
244
|
+
* Every answer the gate makes itself carries these: never cached, never
|
|
245
|
+
* indexed, no referrer. The link page alone sends a same-origin referrer, so
|
|
246
|
+
* its Continue POST carries a real Origin: with no-referrer a browser sends
|
|
247
|
+
* `Origin: null`, which sameOrigin trusts only beside Sec-Fetch-Site, and
|
|
248
|
+
* older Safari sends no Sec-Fetch-Site.
|
|
249
|
+
*/
|
|
250
|
+
function gateHeaders(type, { cookie, allow, referrer = 'no-referrer', retryAfter }) {
|
|
251
|
+
const headers = new Headers({
|
|
252
|
+
'cache-control': NO_STORE,
|
|
253
|
+
'content-type': type,
|
|
254
|
+
'x-robots-tag': 'noindex, nofollow',
|
|
255
|
+
'referrer-policy': referrer,
|
|
256
|
+
});
|
|
257
|
+
if (cookie)
|
|
258
|
+
headers.append('set-cookie', cookie);
|
|
259
|
+
if (allow)
|
|
260
|
+
headers.set('allow', allow);
|
|
261
|
+
if (retryAfter)
|
|
262
|
+
headers.set('retry-after', String(retryAfter));
|
|
263
|
+
return headers;
|
|
264
|
+
}
|
|
265
|
+
export const plain = (request, status, text, extra = {}) => new Response(request.method === 'HEAD' ? null : text, {
|
|
266
|
+
status,
|
|
267
|
+
headers: gateHeaders('text/plain; charset=utf-8', extra),
|
|
268
|
+
});
|
|
269
|
+
/** A gate page for a browser, or `text` for anything else (a fetch, an asset, a preview bot). */
|
|
270
|
+
async function page(request, status, html, text, extra = {}) {
|
|
271
|
+
if (!wantsHtml(request))
|
|
272
|
+
return plain(request, status, text, extra);
|
|
273
|
+
const headers = gateHeaders('text/html; charset=utf-8', extra);
|
|
274
|
+
headers.set('content-security-policy', await csp());
|
|
275
|
+
return new Response(request.method === 'HEAD' ? null : html, { status, headers });
|
|
276
|
+
}
|
|
277
|
+
const unavailable = (request, error) => plain(request, 503, error);
|
|
278
|
+
/** One answer for a prototype a Client may not have, whether it is internal or not there at all. */
|
|
279
|
+
export const notFound = (request) => plain(request, 404, NOT_FOUND);
|
|
280
|
+
const NOT_FOUND = 'Not found.';
|
|
281
|
+
/** The store did not answer: a 503 that passes, so it says when to try again. */
|
|
282
|
+
export const storeDown = (request) => plain(request, 503, STORE_DOWN, { retryAfter: 30 });
|
|
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
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* A store call that can fail without signing anyone out: `undefined` when the
|
|
347
|
+
* store did not answer, so the caller answers 503 and leaves the cookie alone.
|
|
348
|
+
*/
|
|
349
|
+
async function ask(run) {
|
|
350
|
+
try {
|
|
351
|
+
return await run();
|
|
352
|
+
}
|
|
353
|
+
catch (error) {
|
|
354
|
+
console.error('[gate]', error);
|
|
355
|
+
return undefined;
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
/**
|
|
359
|
+
* What a link that signs nobody in here answers, on any host: the used page,
|
|
360
|
+
* 404, its way in the host's own `/`. On the studio's own host only Studio
|
|
361
|
+
* links are looked up, so a Client's link there reads as an unknown one.
|
|
362
|
+
*/
|
|
363
|
+
const noLink = (ctx, at) => page(ctx.request, 404, usedPage(ctx, at === STUDIO_SITE ? 'clients' : 'prototypes'), USED);
|
|
364
|
+
async function showLink(ctx, review, at, token) {
|
|
365
|
+
const { request } = ctx;
|
|
366
|
+
const person = await ask(() => review.peekLink(at, token));
|
|
367
|
+
if (person === undefined)
|
|
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);
|
|
371
|
+
return person
|
|
372
|
+
? page(request, 200, linkPage(ctx, person, byEmail(person)), OPEN_IN_BROWSER, {
|
|
373
|
+
referrer: 'same-origin',
|
|
374
|
+
cookie: tryCookie(),
|
|
375
|
+
})
|
|
376
|
+
: noLink(ctx, at);
|
|
377
|
+
}
|
|
378
|
+
/** The cookie for someone the store just said yes to, lasting to their access end. */
|
|
379
|
+
async function sessionFor(gate, person, at) {
|
|
380
|
+
const claim = { id: person.id, epoch: person.epoch, kind: person.kind };
|
|
381
|
+
const token = await issuePersonToken(gate, claim, person.accessEndsAt, at);
|
|
382
|
+
return sessionCookie(PERSON_COOKIE, token, sessionSeconds(person.accessEndsAt, at));
|
|
383
|
+
}
|
|
384
|
+
/** A 303 to `location` on this host, setting `cookie`: where a link or a handoff sends the person it signed in. */
|
|
385
|
+
function signedIn(cookie, location) {
|
|
386
|
+
const headers = gateHeaders('text/plain; charset=utf-8', { cookie });
|
|
387
|
+
headers.set('location', location);
|
|
388
|
+
return new Response(null, { status: 303, headers });
|
|
389
|
+
}
|
|
390
|
+
async function signInWithLink(ctx, { review, gate }, at, token) {
|
|
391
|
+
const { request } = ctx;
|
|
392
|
+
const person = await ask(() => review.useLink(at, token, browserOf(request)));
|
|
393
|
+
if (person === undefined)
|
|
394
|
+
return storeDown(request);
|
|
395
|
+
if (!person)
|
|
396
|
+
return noLink(ctx, at);
|
|
397
|
+
return signedIn(await sessionFor(gate, person, ctx.at), '/');
|
|
398
|
+
}
|
|
399
|
+
/** A one-time link where `at` reaches: shown on a read, used on a same-origin POST. */
|
|
400
|
+
async function link(ctx, setup, at, token) {
|
|
401
|
+
const { request } = ctx;
|
|
402
|
+
if (request.method === 'POST' && !sameOrigin(request))
|
|
403
|
+
return plain(request, 403, 'Forbidden');
|
|
404
|
+
if (request.method !== 'POST' && !isRead(request))
|
|
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;
|
|
409
|
+
return request.method === 'POST'
|
|
410
|
+
? signInWithLink(ctx, setup, at, token)
|
|
411
|
+
: showLink(ctx, setup.review, at, token);
|
|
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
|
+
}
|
|
494
|
+
/**
|
|
495
|
+
* No session. A page gets the sign-in page, and anything else (an asset, a
|
|
496
|
+
* fetch, a POST to any path but a link) a plain 401: there is nothing to
|
|
497
|
+
* sign in with here. A cookie that was sent but does not hold is cleared.
|
|
498
|
+
*/
|
|
499
|
+
function signedOut(ctx, staleCookie) {
|
|
500
|
+
const { request } = ctx;
|
|
501
|
+
const extra = staleCookie ? { cookie: clearedCookie(PERSON_COOKIE) } : {};
|
|
502
|
+
if (!isRead(request))
|
|
503
|
+
return plain(request, 401, SIGNED_OUT, extra);
|
|
504
|
+
return page(request, 401, signInFor(ctx), SIGNED_OUT, { ...extra, ...signInExtra(ctx) });
|
|
505
|
+
}
|
|
506
|
+
const passHeaders = (cookie) => ({
|
|
507
|
+
'cache-control': 'private, no-store',
|
|
508
|
+
...(cookie ? { 'set-cookie': cookie } : {}),
|
|
509
|
+
});
|
|
510
|
+
/**
|
|
511
|
+
* Whether a prototype is open to a Client in `scope`: client-facing, asked of
|
|
512
|
+
* the store on every request, no cache. A name that is no prototype slug
|
|
513
|
+
* (`all.js`, or '' for a path that could mean more than one file) is never
|
|
514
|
+
* open, without asking. `undefined` when the store did not answer.
|
|
515
|
+
*/
|
|
516
|
+
async function prototypeOpen(review, scope, slug) {
|
|
517
|
+
if (!isPrototypeSlug(slug))
|
|
518
|
+
return false;
|
|
519
|
+
const audience = await ask(() => review.audienceOf(scope, slug));
|
|
520
|
+
return audience === undefined ? undefined : audience === 'client';
|
|
521
|
+
}
|
|
522
|
+
const NOT_THERE = { refused: 'not-found' };
|
|
523
|
+
const DOWN = { refused: 'store-down' };
|
|
524
|
+
/** What the request's host serves, or why nothing: a site not set up, a store that did not answer, or the plain 404. */
|
|
525
|
+
async function lookUp(request, hosts, at) {
|
|
526
|
+
const setup = studioReview(process.env, null, () => at);
|
|
527
|
+
if ('error' in setup)
|
|
528
|
+
return { refused: 'unavailable', error: setup.error };
|
|
529
|
+
const host = hostName(hostOf(request));
|
|
530
|
+
const site = host ? await ask(() => hosts(host, (h) => setup.review.siteOfHost(h))) : null;
|
|
531
|
+
if (site === undefined)
|
|
532
|
+
return DOWN;
|
|
533
|
+
return site ? { review: setup.review, keys: setup.keys, site } : NOT_THERE;
|
|
534
|
+
}
|
|
535
|
+
/** A client's host: its gate and scope, and where `pathname` goes on it. */
|
|
536
|
+
function placeOf({ review, keys }, client, request, pathname) {
|
|
537
|
+
const gate = { ...keys, client: client.slug, since: client.createdAt };
|
|
538
|
+
const place = { client, gate, scope: { client: client.slug } };
|
|
539
|
+
return { review, place, route: routeOf(hostOf(request), pathname) };
|
|
540
|
+
}
|
|
541
|
+
/**
|
|
542
|
+
* The client `pathname` is asked of on the request's host, or why there is
|
|
543
|
+
* none: an unknown host is the plain 404, and so is the studio's own host,
|
|
544
|
+
* which serves no client's anything.
|
|
545
|
+
*/
|
|
546
|
+
export async function findPlace(request, pathname, hosts, at) {
|
|
547
|
+
const looked = await lookUp(request, hosts, at);
|
|
548
|
+
if ('refused' in looked)
|
|
549
|
+
return looked;
|
|
550
|
+
if (looked.site === STUDIO_SITE)
|
|
551
|
+
return NOT_THERE;
|
|
552
|
+
return placeOf(looked, looked.site, request, pathname);
|
|
553
|
+
}
|
|
554
|
+
/**
|
|
555
|
+
* The project a route names, when it is the client's, and for a Client, only
|
|
556
|
+
* a client-facing prototype's files. Every other answer is the plain 404, so
|
|
557
|
+
* another client's project, a project with no build (its files and its
|
|
558
|
+
* review API alike) and an internal prototype read the same as a path that
|
|
559
|
+
* is not there.
|
|
560
|
+
*/
|
|
561
|
+
async function boundary({ review, place, route }, kind) {
|
|
562
|
+
if (route.kind === 'none' || route.kind === 'link' || route.kind === 'handoff')
|
|
563
|
+
return NOT_THERE;
|
|
564
|
+
const named = route.kind === 'file' || route.kind === 'api' ? route.project : null;
|
|
565
|
+
if (named === null)
|
|
566
|
+
return null;
|
|
567
|
+
const scope = { client: place.client.slug, project: named };
|
|
568
|
+
const project = await ask(() => review.projectOf(scope));
|
|
569
|
+
if (project === undefined)
|
|
570
|
+
return DOWN;
|
|
571
|
+
if (!project || project.build === null)
|
|
572
|
+
return NOT_THERE;
|
|
573
|
+
if (route.kind !== 'file' || route.prototype === null || kind === 'studio')
|
|
574
|
+
return project;
|
|
575
|
+
const open = await prototypeOpen(review, scope, route.prototype);
|
|
576
|
+
return open === undefined ? DOWN : open ? project : NOT_THERE;
|
|
577
|
+
}
|
|
578
|
+
/**
|
|
579
|
+
* The session a request's cookie carries where `at` is, signed to `gate`'s
|
|
580
|
+
* client, and asked of the store again once its stamp is stale. On the
|
|
581
|
+
* studio's own host only a Studio person's holds.
|
|
582
|
+
*/
|
|
583
|
+
async function session(review, gate, at, request, time) {
|
|
584
|
+
const cookie = readCookie(request, PERSON_COOKIE);
|
|
585
|
+
const claim = await readPersonToken(gate, cookie, time);
|
|
586
|
+
if (!claim || (at === STUDIO_SITE && claim.kind !== 'studio'))
|
|
587
|
+
return { refused: 'signed-out', stale: cookie !== undefined };
|
|
588
|
+
if (isFresh(claim, time))
|
|
589
|
+
return { claim, current: null };
|
|
590
|
+
const asked = await ask(() => review.sessionPerson(at, claim.id, claim.epoch));
|
|
591
|
+
if (asked === undefined)
|
|
592
|
+
return DOWN;
|
|
593
|
+
return asked ? { claim, current: asked } : { refused: 'signed-out', stale: true };
|
|
594
|
+
}
|
|
595
|
+
/**
|
|
596
|
+
* The checks every studio request passes, in the gate and again in the files
|
|
597
|
+
* function: a session signed to this host's client (asked of the store again
|
|
598
|
+
* once its stamp is stale), then the boundary.
|
|
599
|
+
*/
|
|
600
|
+
export async function admit(found, request, at) {
|
|
601
|
+
const held = await session(found.review, found.place.gate, found.place.scope, request, at);
|
|
602
|
+
if ('refused' in held)
|
|
603
|
+
return held;
|
|
604
|
+
const { claim, current } = held;
|
|
605
|
+
const kind = current ? current.kind : claim.kind;
|
|
606
|
+
const project = await boundary(found, kind);
|
|
607
|
+
return project && 'refused' in project ? project : { ...found, kind, current, project };
|
|
608
|
+
}
|
|
609
|
+
/** The answer for a refusal: the same from the gate and from the files function. */
|
|
610
|
+
export function refuse(ctx, refusal) {
|
|
611
|
+
switch (refusal.refused) {
|
|
612
|
+
case 'not-found':
|
|
613
|
+
return notFound(ctx.request);
|
|
614
|
+
case 'store-down':
|
|
615
|
+
return storeDown(ctx.request);
|
|
616
|
+
case 'unavailable':
|
|
617
|
+
return unavailable(ctx.request, refusal.error);
|
|
618
|
+
case 'signed-out':
|
|
619
|
+
return signedOut(ctx, refusal.stale);
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
/**
|
|
623
|
+
* Where an admitted request goes on to: a project's file to the files
|
|
624
|
+
* function and its review API to the review function, each with the project
|
|
625
|
+
* the path named, and anything else on to the site's own files.
|
|
626
|
+
*/
|
|
627
|
+
function onward(url, route, cookie) {
|
|
628
|
+
const headers = passHeaders(cookie);
|
|
629
|
+
if (route.kind === 'file')
|
|
630
|
+
return {
|
|
631
|
+
pass: 'rewrite',
|
|
632
|
+
to: new URL(`/api/files?path=${encodeURIComponent(url.pathname)}`, url),
|
|
633
|
+
headers,
|
|
634
|
+
};
|
|
635
|
+
if (route.kind !== 'api' || route.project === null)
|
|
636
|
+
return { pass: 'next', headers };
|
|
637
|
+
const to = new URL(`/api/review${url.search}`, url);
|
|
638
|
+
to.searchParams.set('project', route.project);
|
|
639
|
+
return { pass: 'rewrite', to, headers };
|
|
640
|
+
}
|
|
641
|
+
/**
|
|
642
|
+
* The host proof `client add` asks a new client's host for (PROOF_PATH): its
|
|
643
|
+
* answer, on a GET whose ask the store holds for this host's client. Any
|
|
644
|
+
* other ask, method or store failure goes on as the hub path it is, so the
|
|
645
|
+
* path tells a caller without the ask nothing, and a host no client has
|
|
646
|
+
* never gets here (findPlace's plain 404).
|
|
647
|
+
*/
|
|
648
|
+
async function proven({ review, place, route }, request, pathname) {
|
|
649
|
+
const given = route.kind === 'hub' && request.method === 'GET' ? pathname.match(PROOF_PATH)?.[1] : undefined;
|
|
650
|
+
const answer = given ? await ask(() => review.proofAnswer(place.scope, given)) : null;
|
|
651
|
+
return answer ? plain(request, 200, answer) : null;
|
|
652
|
+
}
|
|
653
|
+
/**
|
|
654
|
+
* A handoff's claim on a client's host (`/_gate/handoff/<token>`), a GET the
|
|
655
|
+
* studio's host redirected here: the store gives up the handoff once, only
|
|
656
|
+
* when it was made for this host's client and is not past its minute, and
|
|
657
|
+
* the gate sets this host's own cookie for the Studio person it names. It
|
|
658
|
+
* goes on to the client's hub, or to the project the handoff named, a path
|
|
659
|
+
* built here from the stored slug, never from the request. Anything else is
|
|
660
|
+
* a used link's answer; nothing is used up by a HEAD or a POST.
|
|
661
|
+
*/
|
|
662
|
+
async function openHandoff(ctx, { review, place }, token) {
|
|
663
|
+
const { request } = ctx;
|
|
664
|
+
if (request.method !== 'GET')
|
|
665
|
+
return plain(request, 405, 'Method not allowed', { allow: 'GET' });
|
|
666
|
+
const claimed = await ask(() => review.claimHandoff(place.scope, token));
|
|
667
|
+
if (claimed === undefined)
|
|
668
|
+
return storeDown(request);
|
|
669
|
+
if (!claimed)
|
|
670
|
+
return page(request, 404, usedPage(ctx), USED);
|
|
671
|
+
const to = claimed.project ? `/${claimed.project}/` : '/';
|
|
672
|
+
return signedIn(await sessionFor(place.gate, claimed.person, ctx.at), to);
|
|
673
|
+
}
|
|
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.';
|
|
675
|
+
const PICK_A_CLIENT = 'Open a client from the list of clients.';
|
|
676
|
+
/** A handoff that did not start, for a browser the stopped page, for anything else its text. */
|
|
677
|
+
const stopped = (ctx, status, why, extra = {}) => page(ctx.request, status, stoppedPage(ctx, why), why, extra);
|
|
678
|
+
/** Form bodies the studio hub sends: two slugs, never more than this. */
|
|
679
|
+
const MAX_FORM_BYTES = 1024;
|
|
680
|
+
/** The client and project a handoff is asked for, from a same-origin form POST; null for anything else. */
|
|
681
|
+
async function handoffAsked(request) {
|
|
682
|
+
const type = request.headers.get('content-type') ?? '';
|
|
683
|
+
if (!type.startsWith('application/x-www-form-urlencoded'))
|
|
684
|
+
return null;
|
|
685
|
+
const text = await request.text();
|
|
686
|
+
if (text.length > MAX_FORM_BYTES)
|
|
687
|
+
return null;
|
|
688
|
+
const form = new URLSearchParams(text);
|
|
689
|
+
return { client: form.get('client') ?? '', project: form.get('project') || null };
|
|
690
|
+
}
|
|
691
|
+
/**
|
|
692
|
+
* A handoff asked for on the studio's own host (POST /_gate/handoff): the
|
|
693
|
+
* Studio person is read from the store, whatever the cookie's stamp says,
|
|
694
|
+
* the service writes a one-time handoff for that one client, and the answer
|
|
695
|
+
* sends the browser to the client's host to claim it. The address is the
|
|
696
|
+
* client's stored host and the token, never text the request sent; a client
|
|
697
|
+
* still being added, archived or unknown, or a project it has not built, is
|
|
698
|
+
* the plain 404.
|
|
699
|
+
*/
|
|
700
|
+
async function startHandoff(ctx, review, { claim }) {
|
|
701
|
+
const { request } = ctx;
|
|
702
|
+
if (request.method !== 'POST')
|
|
703
|
+
return plain(request, 405, 'Method not allowed', { allow: 'POST' });
|
|
704
|
+
if (!sameOrigin(request))
|
|
705
|
+
return plain(request, 403, 'Forbidden');
|
|
706
|
+
const asked = await handoffAsked(request);
|
|
707
|
+
if (!asked)
|
|
708
|
+
return stopped(ctx, 400, PICK_A_CLIENT);
|
|
709
|
+
const person = await ask(() => review.sessionPerson(STUDIO_SITE, claim.id, claim.epoch));
|
|
710
|
+
if (person === undefined)
|
|
711
|
+
return stopped(ctx, 503, STORE_DOWN, { retryAfter: 30 });
|
|
712
|
+
if (!person)
|
|
713
|
+
return page(request, 401, signInFor(ctx), SIGNED_OUT, {
|
|
714
|
+
cookie: clearedCookie(PERSON_COOKIE),
|
|
715
|
+
...signInExtra(ctx),
|
|
716
|
+
});
|
|
717
|
+
let made;
|
|
718
|
+
try {
|
|
719
|
+
made = await review.startHandoff(person, asked);
|
|
720
|
+
}
|
|
721
|
+
catch (error) {
|
|
722
|
+
if (error instanceof ReviewError)
|
|
723
|
+
return stopped(ctx, 404, NOT_OPENED);
|
|
724
|
+
console.error('[gate]', error);
|
|
725
|
+
return stopped(ctx, 503, STORE_DOWN, { retryAfter: 30 });
|
|
726
|
+
}
|
|
727
|
+
const headers = gateHeaders('text/plain; charset=utf-8', {});
|
|
728
|
+
headers.set('location', `https://${made.host}${handoffPath(made.token)}`);
|
|
729
|
+
return new Response(null, { status: 303, headers });
|
|
730
|
+
}
|
|
731
|
+
/**
|
|
732
|
+
* The host proof `studio create` and `studio deploy` ask the studio's own
|
|
733
|
+
* host for: its answer, on a GET whose ask the store holds. Any other ask,
|
|
734
|
+
* method or store failure is the plain 404 every unknown path there gets.
|
|
735
|
+
*/
|
|
736
|
+
async function studioProof(ctx, review, given) {
|
|
737
|
+
const { request } = ctx;
|
|
738
|
+
const answer = request.method === 'GET' ? await ask(() => review.studioProofAnswer(given)) : null;
|
|
739
|
+
return answer ? plain(request, 200, answer) : notFound(request);
|
|
740
|
+
}
|
|
741
|
+
/**
|
|
742
|
+
* The studio's own host (`studio.<apex>`): Studio signs in here with a
|
|
743
|
+
* Studio person's link, and nobody else gets in. Its session is signed to
|
|
744
|
+
* `studio`, so a client host's cookie never holds here, and a Client's
|
|
745
|
+
* cookie answers the sign-in page a client host shows, word for word; a
|
|
746
|
+
* Client's link reads as an unknown one (the used page). Its host proof
|
|
747
|
+
* is answered before any session. Signed in, `/` is the studio hub and `/api/review` its data (the
|
|
748
|
+
* review function checks the session again), and a POST to /_gate/handoff
|
|
749
|
+
* opens a client. Everything else is the plain 404, every path a client's
|
|
750
|
+
* host answers included.
|
|
751
|
+
*/
|
|
752
|
+
async function studioHost(ctx, { review, keys }, url) {
|
|
753
|
+
const { request } = ctx;
|
|
754
|
+
const where = studioRouteOf(url.pathname);
|
|
755
|
+
const gate = studioGate(keys);
|
|
756
|
+
if (where.kind === 'none')
|
|
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);
|
|
760
|
+
if (where.kind === 'link')
|
|
761
|
+
return link(ctx, { review, gate }, STUDIO_SITE, where.token);
|
|
762
|
+
if (where.kind === 'proof')
|
|
763
|
+
return studioProof(ctx, review, where.ask);
|
|
764
|
+
if (where.kind === 'asset' && isRead(request))
|
|
765
|
+
return { pass: 'next' };
|
|
766
|
+
const held = await session(review, gate, STUDIO_SITE, request, ctx.at);
|
|
767
|
+
if ('refused' in held)
|
|
768
|
+
return refuse(ctx, held);
|
|
769
|
+
if (where.kind === 'handoff')
|
|
770
|
+
return startHandoff(ctx, review, held);
|
|
771
|
+
const headers = passHeaders(held.current ? await sessionFor(gate, held.current, ctx.at) : undefined);
|
|
772
|
+
return where.kind === 'page'
|
|
773
|
+
? { pass: 'rewrite', to: new URL(STUDIO_PAGE, url), headers }
|
|
774
|
+
: { pass: 'next', headers };
|
|
775
|
+
}
|
|
776
|
+
/** The gate a host's adapter runs on every request (vercel/proxy.ts on Vercel). Its sign-in page names no client (S10). */
|
|
777
|
+
export function createGate(options = {}) {
|
|
778
|
+
const { siteName = DEFAULT_SITE_NAME, now = () => new Date() } = options;
|
|
779
|
+
const hosts = hostCache(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 };
|
|
783
|
+
const url = new URL(request.url);
|
|
784
|
+
const looked = await lookUp(request, hosts, ctx.at);
|
|
785
|
+
if ('refused' in looked)
|
|
786
|
+
return refuse(ctx, looked);
|
|
787
|
+
if (looked.site === STUDIO_SITE)
|
|
788
|
+
return studioHost(ctx, looked, url);
|
|
789
|
+
const found = placeOf(looked, looked.site, request, url.pathname);
|
|
790
|
+
const proof = await proven(found, request, url.pathname);
|
|
791
|
+
if (proof)
|
|
792
|
+
return proof;
|
|
793
|
+
const { route, place } = found;
|
|
794
|
+
if (route.kind === 'link')
|
|
795
|
+
return link(ctx, { review: found.review, gate: place.gate }, place.scope, route.token);
|
|
796
|
+
if (route.kind === 'handoff')
|
|
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);
|
|
800
|
+
if (route.kind === 'asset' && isRead(request))
|
|
801
|
+
return { pass: 'next' };
|
|
802
|
+
const admitted = await admit(found, request, ctx.at);
|
|
803
|
+
if ('refused' in admitted)
|
|
804
|
+
return refuse(ctx, admitted);
|
|
805
|
+
const cookie = admitted.current ? await sessionFor(place.gate, admitted.current, ctx.at) : undefined;
|
|
806
|
+
return onward(url, route, cookie);
|
|
807
|
+
};
|
|
808
|
+
}
|