@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.
Files changed (92) hide show
  1. package/README.md +5 -5
  2. package/core/prototype.test.ts +12 -1
  3. package/core/prototype.ts +21 -2
  4. package/core/review/model.ts +71 -6
  5. package/core/review/service.test.ts +575 -39
  6. package/core/review/service.ts +452 -25
  7. package/core/review/store.ts +47 -6
  8. package/core/review/suite-kv.ts +17 -0
  9. package/dist/core/prototype.d.ts +20 -2
  10. package/dist/core/prototype.js +17 -2
  11. package/dist/core/review/model.d.ts +42 -3
  12. package/dist/core/review/model.js +52 -3
  13. package/dist/core/review/service.d.ts +81 -7
  14. package/dist/core/review/service.js +407 -23
  15. package/dist/core/review/store.d.ts +29 -2
  16. package/dist/core/review/store.js +6 -2
  17. package/dist/core/review/suite-kv.d.ts +7 -0
  18. package/dist/core/review/suite-kv.js +12 -0
  19. package/dist/scripts/client.d.ts +1 -1
  20. package/dist/scripts/client.js +4 -4
  21. package/dist/scripts/lib/cli.js +5 -0
  22. package/dist/scripts/lib/dns.d.ts +16 -2
  23. package/dist/scripts/lib/dns.js +66 -3
  24. package/dist/scripts/lib/fake-host.d.ts +17 -3
  25. package/dist/scripts/lib/fake-host.js +56 -10
  26. package/dist/scripts/lib/host.d.ts +15 -25
  27. package/dist/scripts/lib/host.js +15 -324
  28. package/dist/scripts/lib/resend.d.ts +36 -0
  29. package/dist/scripts/lib/resend.js +66 -0
  30. package/dist/scripts/lib/studio-deps.d.ts +23 -0
  31. package/dist/scripts/lib/studio-deps.js +46 -16
  32. package/dist/scripts/lib/studios.d.ts +16 -6
  33. package/dist/scripts/lib/studios.js +28 -10
  34. package/dist/scripts/lib/vercel-host.d.ts +17 -0
  35. package/dist/scripts/lib/vercel-host.js +416 -0
  36. package/dist/scripts/people.d.ts +16 -4
  37. package/dist/scripts/people.js +67 -17
  38. package/dist/scripts/share.js +3 -2
  39. package/dist/scripts/studio.d.ts +26 -4
  40. package/dist/scripts/studio.js +364 -19
  41. package/dist/server/api.d.ts +20 -7
  42. package/dist/server/api.js +83 -27
  43. package/dist/server/dev.js +21 -1
  44. package/dist/server/gate.d.ts +120 -0
  45. package/dist/server/gate.js +808 -0
  46. package/dist/server/mailer.d.ts +60 -0
  47. package/dist/server/mailer.js +104 -0
  48. package/dist/server/mailers/fake.d.ts +8 -0
  49. package/dist/server/mailers/fake.js +16 -0
  50. package/dist/server/mailers/resend.d.ts +21 -0
  51. package/dist/server/mailers/resend.js +49 -0
  52. package/dist/server/mark.d.ts +17 -0
  53. package/dist/server/mark.js +46 -1
  54. package/dist/server/session.d.ts +2 -1
  55. package/dist/server/session.js +6 -3
  56. package/dist/server/stores/backends.d.ts +22 -0
  57. package/dist/server/stores/backends.js +96 -0
  58. package/dist/server/{fake-upstash.js → stores/fake-upstash.js} +1 -1
  59. package/dist/server/stores/index.d.ts +41 -0
  60. package/dist/server/stores/index.js +63 -0
  61. package/dist/server/stores/pglite.d.ts +16 -0
  62. package/dist/server/stores/pglite.js +98 -0
  63. package/dist/server/stores/postgres.d.ts +63 -0
  64. package/dist/server/stores/postgres.js +153 -0
  65. package/dist/server/{upstash.d.ts → stores/upstash.d.ts} +1 -1
  66. package/dist/vercel/files.js +1 -1
  67. package/dist/vercel/proxy.d.ts +6 -82
  68. package/dist/vercel/proxy.js +24 -524
  69. package/dist/vite/plugin.js +4 -2
  70. package/kit/ui/Menu.tsx +29 -18
  71. package/kit/ui/layer.ts +41 -0
  72. package/package.json +3 -1
  73. package/shell/review/Bar.tsx +1 -0
  74. package/shell/review/Card.tsx +17 -7
  75. package/shell/review/People.tsx +908 -134
  76. package/shell/review/Review.tsx +2 -2
  77. package/shell/review/anchor.ts +6 -1
  78. package/shell/review/client.ts +41 -7
  79. package/shell/review/menu-place.test.ts +41 -0
  80. package/shell/review/place.test.ts +26 -1
  81. package/shell/review/place.ts +17 -0
  82. package/shell/review/review.css +97 -11
  83. package/shell/review/view.test.ts +115 -1
  84. package/shell/review/view.ts +92 -2
  85. package/shell/studio/StudioHub.tsx +1 -0
  86. package/shell/studio/hub.css +99 -13
  87. package/skills/miles-deploy/SKILL.md +26 -4
  88. package/templates/studio/.env.example +9 -0
  89. package/templates/studio/README.md +13 -0
  90. package/templates/studio/package.json +1 -1
  91. /package/dist/server/{fake-upstash.d.ts → stores/fake-upstash.d.ts} +0 -0
  92. /package/dist/server/{upstash.js → stores/upstash.js} +0 -0
@@ -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>;
@@ -0,0 +1,104 @@
1
+ // The one port mail goes through (email.md, E12): a studio site sends when it
2
+ // has a mail key and a sender, and never otherwise. Resend is its first
3
+ // adapter (server/mailers/resend.ts). A send never throws and answers sent,
4
+ // refused or down; whoever sends records the answer for Studio (recordMail),
5
+ // and a person is never shown it (E7).
6
+ import { escapeHtml } from '../core/html.js';
7
+ import { CODE } from '../core/review/model.js';
8
+ import { resendMailer } from './mailers/resend.js';
9
+ /** The name in a sender (`Suits & Sandals <signin@mail.example.com>`), or its address when it has none. */
10
+ export function senderName(from) {
11
+ const named = from.match(/^\s*"?([^"<]*?)"?\s*<([^>]+)>\s*$/);
12
+ return (named?.[1] || named?.[2] || from).trim();
13
+ }
14
+ /** 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. */
15
+ export function chooseMailer(env, fetcher) {
16
+ const key = env.RESEND_API_KEY?.trim();
17
+ const from = env.MAIL_FROM?.trim();
18
+ if (!key || !from)
19
+ return null;
20
+ return { name: senderName(from), ...resendMailer({ key, from, ...(fetcher ? { fetcher } : {}) }) };
21
+ }
22
+ /** A code as it is read aloud: two groups of four. */
23
+ const spacedCode = (code) => `${code.slice(0, 4)} ${code.slice(4)}`;
24
+ /**
25
+ * The code mail (email.md, section 3): the studio's name, the code in two
26
+ * groups of four, how long it lasts, and one line to ignore it. No link, no
27
+ * tracking, no image. The subject starts with the code, so it reads from a
28
+ * notification. `key` is the person and the code's hash, so each new code is
29
+ * a new mail and a second send of one code is not.
30
+ */
31
+ export function codeMail(studio, to, code, key) {
32
+ const spaced = spacedCode(code);
33
+ const subject = `${spaced} is your sign-in code for ${studio}`;
34
+ const lasts = `It works once and lasts ${CODE.minutes} minutes.`;
35
+ const ignore = 'If you did not ask for it, ignore this email.';
36
+ const text = `Your sign-in code for ${studio}:\n\n${spaced}\n\n${lasts}\n\n${ignore}\n`;
37
+ const font = 'font-family:-apple-system,BlinkMacSystemFont,&quot;Segoe UI&quot;,Helvetica,Arial,sans-serif';
38
+ const html = `<!doctype html>
39
+ <html lang="en">
40
+ <head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${escapeHtml(subject)}</title></head>
41
+ <body style="margin:0;padding:32px 16px;background:#ffffff;color:#171717;${font};font-size:14px;line-height:20px">
42
+ <div style="max-width:360px;margin:0 auto">
43
+ <p style="margin:0 0 16px">Your sign-in code for ${escapeHtml(studio)}:</p>
44
+ <p style="margin:0 0 16px;font-size:28px;line-height:36px;font-weight:600;letter-spacing:.08em;font-variant-numeric:tabular-nums">${spaced}</p>
45
+ <p style="margin:0 0 8px;color:#585858">${lasts}</p>
46
+ <p style="margin:0;color:#585858">${ignore}</p>
47
+ </div>
48
+ </body>
49
+ </html>
50
+ `;
51
+ return { to, subject, text, html, key: `code-${key}` };
52
+ }
53
+ /**
54
+ * The invite (email.md, E10): who gave them access, their one-time link as
55
+ * one button and as plain text, that it works once on one device, and the
56
+ * address to sign in at with this email from then on: their client's own
57
+ * host, or the studio's for a Studio person, never another's. Its words are
58
+ * the link page's ("Sign in as", "Next time, sign in with your email"). No
59
+ * tracking, no image. `key` is the person's id: one add, one mail.
60
+ */
61
+ export function inviteMail(studio, person, link, address) {
62
+ const subject = `Your sign-in link for ${studio}`;
63
+ const title = `Sign in as ${person.name}`;
64
+ const lead = `${studio} gave you access. This link works once, on one device.`;
65
+ const home = `https://${address}`;
66
+ const text = `${title}\n\n${lead}\n\n${link}\n\nNext time, sign in with your email at ${home}\n`;
67
+ const font = 'font-family:-apple-system,BlinkMacSystemFont,&quot;Segoe UI&quot;,Helvetica,Arial,sans-serif';
68
+ const muted = 'color:#585858';
69
+ const html = `<!doctype html>
70
+ <html lang="en">
71
+ <head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${escapeHtml(subject)}</title></head>
72
+ <body style="margin:0;padding:32px 16px;background:#ffffff;color:#171717;${font};font-size:14px;line-height:20px">
73
+ <div style="max-width:360px;margin:0 auto">
74
+ <p style="margin:0 0 12px;${muted}">${escapeHtml(studio)}</p>
75
+ <p style="margin:0 0 8px;font-size:20px;line-height:28px;font-weight:600;overflow-wrap:anywhere">${escapeHtml(title)}</p>
76
+ <p style="margin:0 0 20px">${escapeHtml(lead)}</p>
77
+ <p style="margin:0 0 20px"><a href="${escapeHtml(link)}" style="display:inline-block;padding:12px 20px;line-height:20px;border-radius:8px;background:#171717;color:#ffffff;font-weight:600;text-decoration:none">Sign in</a></p>
78
+ <p style="margin:0 0 20px">Next time, sign in with your email at <a href="${escapeHtml(home)}" style="color:#171717">${escapeHtml(address)}</a>.</p>
79
+ <p style="margin:0 0 4px;font-size:12px;line-height:16px;${muted}">If the button does not open, paste this link into your browser:</p>
80
+ <p style="margin:0;font-size:12px;line-height:16px;${muted};word-break:break-all">${escapeHtml(link)}</p>
81
+ </div>
82
+ </body>
83
+ </html>
84
+ `;
85
+ return { to: person.email, subject, text, html, key: `invite-${person.id}` };
86
+ }
87
+ /**
88
+ * Sends one mail and records the answer for Studio (recordMail, email.md,
89
+ * "When mail breaks"): the one way the studio's mail goes out, a code's or an
90
+ * invite's. Never rejects: a mailer that throws is down, and a record that
91
+ * fails is logged, so the answer stands whatever the store does.
92
+ */
93
+ export async function sendAndRecord(mailer, review, mail) {
94
+ const answer = await mailer.send(mail).catch(() => 'down');
95
+ await review.recordMail(answer).catch((error) => console.error('[mail] not recorded:', error));
96
+ return answer;
97
+ }
98
+ /**
99
+ * Mails a new person their invite, with their link on `home`, the host they
100
+ * sign in on, and records the answer as a code's is (sendAndRecord). Waits
101
+ * for the send, since whoever adds is Studio (E7 is about the person signing
102
+ * in). Never throws: the person and their link stand whatever happens.
103
+ */
104
+ export const sendInvite = (mailer, review, person, token, home) => sendAndRecord(mailer, review, inviteMail(mailer.name, person, `https://${home}/invite/${token}`, home));
@@ -0,0 +1,8 @@
1
+ import type { Mail, Mailer, Sent } from '../mailer.ts';
2
+ export type FakeMailer = Mailer & {
3
+ /** Every mail sent, in order. */
4
+ sent: Mail[];
5
+ /** What the next sends answer; `hang` never answers. */
6
+ answer: Sent | 'hang' | 'throw';
7
+ };
8
+ export declare function fakeMailer(name?: string): FakeMailer;
@@ -0,0 +1,16 @@
1
+ export function fakeMailer(name = 'Test Studio') {
2
+ const mailer = {
3
+ name,
4
+ sent: [],
5
+ answer: 'sent',
6
+ send(mail) {
7
+ mailer.sent.push(mail);
8
+ if (mailer.answer === 'hang')
9
+ return new Promise(() => { });
10
+ if (mailer.answer === 'throw')
11
+ return Promise.reject(new Error('fake mailer failed'));
12
+ return Promise.resolve(mailer.answer);
13
+ },
14
+ };
15
+ return mailer;
16
+ }
@@ -0,0 +1,21 @@
1
+ import type { Sent } from '../../core/review/service.ts';
2
+ type Mail = {
3
+ to: string;
4
+ subject: string;
5
+ text: string;
6
+ html: string;
7
+ key: string;
8
+ };
9
+ export type ResendOptions = {
10
+ /** The send-only key (RESEND_API_KEY). */
11
+ key: string;
12
+ /** The sender, `Name <address>` (MAIL_FROM). */
13
+ from: string;
14
+ fetcher?: typeof fetch;
15
+ /** How long a send may take before it is down; tests shorten it. */
16
+ timeoutMs?: number;
17
+ };
18
+ export declare function resendMailer({ key, from, fetcher, timeoutMs }: ResendOptions): {
19
+ send(mail: Mail): Promise<Sent>;
20
+ };
21
+ export {};
@@ -0,0 +1,49 @@
1
+ const ENDPOINT = 'https://api.resend.com/emails';
2
+ const TIMEOUT_MS = 5_000;
3
+ /** A 200 whose body names the mail Resend made. */
4
+ async function made(response) {
5
+ const body = (await response.json().catch(() => null));
6
+ return typeof body?.id === 'string' && body.id !== '';
7
+ }
8
+ export function resendMailer({ key, from, fetcher = fetch, timeoutMs = TIMEOUT_MS }) {
9
+ async function post(mail, signal) {
10
+ const response = await fetcher(ENDPOINT, {
11
+ method: 'POST',
12
+ headers: {
13
+ authorization: `Bearer ${key}`,
14
+ 'content-type': 'application/json',
15
+ // Held 24 hours by Resend: the same mail sent twice is one mail.
16
+ 'idempotency-key': mail.key,
17
+ },
18
+ body: JSON.stringify({ from, to: [mail.to], subject: mail.subject, text: mail.text, html: mail.html }),
19
+ signal,
20
+ });
21
+ if (response.status === 200 && (await made(response)))
22
+ return 'sent';
23
+ console.error('[mail] Resend refused a send:', response.status);
24
+ return 'refused';
25
+ }
26
+ return {
27
+ async send(mail) {
28
+ const abort = new AbortController();
29
+ let timer;
30
+ // A fetch that ignores its signal still ends here: the timer answers down.
31
+ const late = new Promise((resolve) => {
32
+ timer = setTimeout(() => {
33
+ abort.abort();
34
+ resolve('down');
35
+ }, timeoutMs);
36
+ });
37
+ try {
38
+ return await Promise.race([post(mail, abort.signal), late]);
39
+ }
40
+ catch {
41
+ console.error('[mail] Resend did not answer.');
42
+ return 'down';
43
+ }
44
+ finally {
45
+ clearTimeout(timer);
46
+ }
47
+ },
48
+ };
49
+ }
@@ -1,3 +1,4 @@
1
+ import type { Files } from '../core/files.ts';
1
2
  import { type KV } from '../core/review/store.ts';
2
3
  /** What the mark is checked against: a studio folder and the settings its studio.json holds. */
3
4
  export type MarkedStudio = {
@@ -39,3 +40,19 @@ export declare function claimDatabase(kv: KV, studio: MarkedStudio): Promise<'cl
39
40
  * clients, people or links.
40
41
  */
41
42
  export declare function mustBeOwnDatabase(kv: KV, studio: MarkedStudio): Promise<void>;
43
+ /**
44
+ * The file store's mark: one file at a fixed path, outside every client's
45
+ * `c/` folder, holding the id of the studio the store serves. No request
46
+ * reaches it: the studio site serves only paths under a build.
47
+ */
48
+ export declare const FILES_MARK = "studio/id.txt";
49
+ /**
50
+ * Marks the file store as this studio's, or finds it is: 'claimed' when it
51
+ * held no mark, 'kept' when the mark is this studio's id. A store marked by
52
+ * another studio is refused with nothing written. `studio create` runs this,
53
+ * and so does every command that writes or removes files (openFiles in
54
+ * scripts/lib/studio-deps.ts), so a store from before the mark gets it on
55
+ * its first use. Two at once: the store never overwrites a file, so the
56
+ * second write fails and the mark is read again.
57
+ */
58
+ export declare function claimFiles(files: Files, studio: MarkedStudio): Promise<'claimed' | 'kept'>;
@@ -31,7 +31,7 @@ export class MarkError extends Error {
31
31
  }
32
32
  /** What every refusal says: whose database this must be, and how to give the studio one of its own. */
33
33
  function ownDatabase({ dir, config }) {
34
- return `A database serves one studio only; never connect one another studio uses. On team ${config.vercel.team}'s Storage page on Vercel, disconnect this one from project ${config.vercel.project}, remove KV_REST_API_URL and KV_REST_API_TOKEN from ${join(dir, '.env')}, then run design-hub studio create again in ${dir} with the same flags, without --database (a new free one) or with --database <a database no studio uses>.`;
34
+ return `A database serves one studio only; never connect one another studio uses. On team ${config.vercel.team}'s Storage page on Vercel, disconnect this one from project ${config.vercel.project}, take its names (KV_REST_API_URL and KV_REST_API_TOKEN, or DATABASE_URL and POSTGRES_URL) out of ${join(dir, '.env')}, then run design-hub studio create again in ${dir} with the same flags, without --database (a new free one) or with --database <a database no studio uses>.`;
35
35
  }
36
36
  /**
37
37
  * Whether a database marked as no studio's is free for this one: it holds no
@@ -109,3 +109,48 @@ export async function mustBeOwnDatabase(kv, studio) {
109
109
  fix: ownDatabase(studio),
110
110
  });
111
111
  }
112
+ /**
113
+ * The file store's mark: one file at a fixed path, outside every client's
114
+ * `c/` folder, holding the id of the studio the store serves. No request
115
+ * reaches it: the studio site serves only paths under a build.
116
+ */
117
+ export const FILES_MARK = 'studio/id.txt';
118
+ /**
119
+ * Marks the file store as this studio's, or finds it is: 'claimed' when it
120
+ * held no mark, 'kept' when the mark is this studio's id. A store marked by
121
+ * another studio is refused with nothing written. `studio create` runs this,
122
+ * and so does every command that writes or removes files (openFiles in
123
+ * scripts/lib/studio-deps.ts), so a store from before the mark gets it on
124
+ * its first use. Two at once: the store never overwrites a file, so the
125
+ * second write fails and the mark is read again.
126
+ */
127
+ export async function claimFiles(files, studio) {
128
+ const { id, slug } = studio.config;
129
+ if (!id)
130
+ throw new Error('A studio is given its id before its file store is claimed.');
131
+ const read = async () => {
132
+ const found = await files.get(FILES_MARK);
133
+ return found ? (await new Response(found.body).text()).trim() : null;
134
+ };
135
+ const mark = await read();
136
+ if (mark === id)
137
+ return 'kept';
138
+ if (mark === null) {
139
+ try {
140
+ await files.put(FILES_MARK, new TextEncoder().encode(id), 'text/plain; charset=utf-8');
141
+ return 'claimed';
142
+ }
143
+ catch (error) {
144
+ const now = await read();
145
+ if (now === id)
146
+ return 'kept';
147
+ if (now === null)
148
+ throw error;
149
+ }
150
+ }
151
+ throw new MarkError(`The file store in studio ${slug}'s .env is another studio's; nothing was changed.`, {
152
+ code: 'files_not_this_studios',
153
+ studio: slug,
154
+ fix: `A file store serves one studio only. Put this studio's own BLOB_READ_WRITE_TOKEN in ${join(studio.dir, '.env')} (design-hub studio link --dir ${studio.dir} reads it back from the site's Production env), then run this again.`,
155
+ });
156
+ }
@@ -3,7 +3,8 @@ export declare const PERSON_COOKIE = "__Host-hub_person";
3
3
  /** How long the store's last yes is trusted before the gate asks again. */
4
4
  export declare const CHECK_SECONDS: number;
5
5
  /**
6
- * `site` is the review store's URL. It is signed into every token, so two
6
+ * `site` is the review store's address: Upstash's URL, or Postgres's host,
7
+ * port and database with no credential (server/stores/). It is signed into every token, so two
7
8
  * studios that share one GATE_SECRET (a copied folder keeps its .env) never
8
9
  * accept each other's cookies.
9
10
  * `client` is the client of the host the gate answers, or `studio` for the
@@ -15,6 +15,7 @@
15
15
  import { base64url } from '../core/bytes.js';
16
16
  import { SLUG } from '../core/feature.js';
17
17
  import { PERSON_KINDS, STUDIO_SITE } from '../core/review/model.js';
18
+ import { storeSite } from './stores/index.js';
18
19
  export const PERSON_COOKIE = '__Host-hub_person';
19
20
  const MAX_SESSION_SECONDS = 60 * 60 * 24 * 400;
20
21
  /** How long the store's last yes is trusted before the gate asks again. */
@@ -29,8 +30,7 @@ export const studioGate = (keys) => ({ ...keys, client: STUDIO_SITE, since: '' }
29
30
  /** The gate's keys, or null when GATE_SECRET is missing or short (the gate then fails closed). */
30
31
  export function readGate(env) {
31
32
  const secret = env.GATE_SECRET ?? '';
32
- const site = (env.KV_REST_API_URL ?? env.UPSTASH_REDIS_REST_URL ?? '').replace(/\/$/, '');
33
- return secret.length >= 32 ? { secret, site } : null;
33
+ return secret.length >= 32 ? { secret, site: storeSite(env) } : null;
34
34
  }
35
35
  const encoder = new TextEncoder();
36
36
  async function hmac(secret, message) {
@@ -109,6 +109,9 @@ export const clearedCookie = (name) => `${name}=; Path=/; Max-Age=0; HttpOnly; S
109
109
  // A request with neither header is not from a browser that could be tricked
110
110
  // into it (every current browser sends Origin on a POST), so it passes: it
111
111
  // holds whatever it sends, and a forged request needs a victim's browser.
112
+ // http only on this machine: localhost and its subdomains (acme.localhost),
113
+ // which every current browser resolves to loopback.
114
+ const isLocalhost = (hostname) => hostname === 'localhost' || hostname.endsWith('.localhost');
112
115
  export function sameOrigin(request) {
113
116
  const site = request.headers.get('sec-fetch-site');
114
117
  if (site && site !== 'same-origin')
@@ -121,7 +124,7 @@ export function sameOrigin(request) {
121
124
  const host = request.headers.get('x-forwarded-host') ?? request.headers.get('host') ?? new URL(request.url).host;
122
125
  try {
123
126
  const o = new URL(origin);
124
- return (o.protocol === 'https:' || o.hostname === 'localhost') && o.host === host;
127
+ return (o.protocol === 'https:' || isLocalhost(o.hostname)) && o.host === host;
125
128
  }
126
129
  catch {
127
130
  return false;
@@ -0,0 +1,22 @@
1
+ export type TestStore = {
2
+ name: 'upstash' | 'postgres';
3
+ /** The env names that point a site at this store. */
4
+ env: Record<string, string>;
5
+ /** The names of another store of the same kind: another site, the same rows. */
6
+ other: Record<string, string>;
7
+ /** A store of the other kind, which beside this one names two databases. */
8
+ rival: Record<string, string>;
9
+ /** Before each test: an empty store, answering. */
10
+ start(): Promise<void>;
11
+ /** After each test. */
12
+ stop(): void;
13
+ /** Every store call fails until `up`. */
14
+ down(): void;
15
+ up(): void;
16
+ /** From now on, every store call by its Redis name and key (`HGET hub4:…`), in order. */
17
+ watch(): string[];
18
+ };
19
+ /** For a test file that runs a suite on Postgres: call before the suite loads. */
20
+ export declare function onPostgres(): void;
21
+ /** The store the suites of this test file run on. */
22
+ export declare const testStore: () => TestStore;
@@ -0,0 +1,96 @@
1
+ /// <reference types="node" />
2
+ // The review store a studio site's tests run on, picked once per test file:
3
+ // the fake Upstash (by default) or the embedded Postgres, each reached the
4
+ // way the site reaches it, from the env, through chooseStore. A suite is
5
+ // written once against this and run on each: vercel/gate.postgres.test.ts
6
+ // picks Postgres, then loads the gate suite.
7
+ import { fakeUpstash } from './fake-upstash.js';
8
+ import { postgresThrough } from './index.js';
9
+ import { pgliteQuery } from './pglite.js';
10
+ import { createTable, STATEMENTS, TABLE } from './postgres.js';
11
+ /** The fake Upstash behind the global fetch, as the site's adapter calls it. */
12
+ function upstash() {
13
+ const real = globalThis.fetch;
14
+ let failing = false;
15
+ let seen = null;
16
+ let store = fakeUpstash();
17
+ return {
18
+ name: 'upstash',
19
+ env: { KV_REST_API_URL: 'https://kv.test', KV_REST_API_TOKEN: 't' },
20
+ other: { KV_REST_API_URL: 'https://kv-other.test', KV_REST_API_TOKEN: 't' },
21
+ rival: { DATABASE_URL: 'postgres://studio:pw@db.test/hub' },
22
+ async start() {
23
+ store = fakeUpstash();
24
+ failing = false;
25
+ seen = null;
26
+ globalThis.fetch = ((url, init) => {
27
+ if (failing)
28
+ return Promise.resolve(new Response('{"error":"down"}', { status: 500 }));
29
+ const [cmd, key] = JSON.parse(String(init?.body));
30
+ seen?.push(`${cmd} ${key}`);
31
+ return store(url, init);
32
+ });
33
+ },
34
+ stop() {
35
+ globalThis.fetch = real;
36
+ },
37
+ down() {
38
+ failing = true;
39
+ },
40
+ up() {
41
+ failing = false;
42
+ },
43
+ watch() {
44
+ seen = [];
45
+ return seen;
46
+ },
47
+ };
48
+ }
49
+ /** Which op a statement is, by the adapter's own SQL. */
50
+ const OPS = Object.entries(STATEMENTS).map(([op, text]) => [text.replace('$t', TABLE), op.toUpperCase()]);
51
+ /** The embedded Postgres behind every connection string, as the site's adapter queries it. */
52
+ function postgres() {
53
+ let failing = false;
54
+ let seen = null;
55
+ let query;
56
+ return {
57
+ name: 'postgres',
58
+ env: { DATABASE_URL: 'postgres://studio:pw@db.test/hub?sslmode=require' },
59
+ other: { DATABASE_URL: 'postgres://studio:pw@db-other.test/hub?sslmode=require' },
60
+ rival: { KV_REST_API_URL: 'https://kv.test' },
61
+ async start() {
62
+ query ??= await pgliteQuery();
63
+ const db = query;
64
+ failing = false;
65
+ seen = null;
66
+ await createTable(db);
67
+ await db(`TRUNCATE ${TABLE}`, []);
68
+ postgresThrough(() => async (text, params) => {
69
+ if (failing)
70
+ throw new Error('the store is down');
71
+ const op = OPS.find(([sql]) => sql === text)?.[1];
72
+ if (op)
73
+ seen?.push(`${op} ${params[0]}`);
74
+ return db(text, params);
75
+ });
76
+ },
77
+ stop() { },
78
+ down() {
79
+ failing = true;
80
+ },
81
+ up() {
82
+ failing = false;
83
+ },
84
+ watch() {
85
+ seen = [];
86
+ return seen;
87
+ },
88
+ };
89
+ }
90
+ let picked = 'upstash';
91
+ /** For a test file that runs a suite on Postgres: call before the suite loads. */
92
+ export function onPostgres() {
93
+ picked = 'postgres';
94
+ }
95
+ /** The store the suites of this test file run on. */
96
+ export const testStore = () => (picked === 'postgres' ? postgres() : upstash());
@@ -1,7 +1,7 @@
1
1
  /// <reference types="node" />
2
2
  // A fetch that answers like Upstash's REST API from memory, for tests that
3
3
  // exercise a studio site's code path (its gate and functions) without an account.
4
- import { memoryKV } from '../core/review/store.js';
4
+ import { memoryKV } from '../../core/review/store.js';
5
5
  /** How many keys one SCAN call looks at: few, so a walk takes many calls, some of them finding nothing. */
6
6
  const SCAN_PAGE = 2;
7
7
  /** A Redis glob as a RegExp: `*`, `?`, `[…]`, and `\` before a character that stands for itself. */
@@ -0,0 +1,41 @@
1
+ import type { KV } from '../../core/review/store.ts';
2
+ import { type Query } from './postgres.ts';
3
+ export type StoreKind = 'upstash' | 'postgres';
4
+ /**
5
+ * The store an env names: its kind, the site its tokens are signed to, how
6
+ * to open it, and how to make what it needs before its first write (the
7
+ * Postgres table), which only `studio create` runs.
8
+ */
9
+ export type StoreChoice = {
10
+ kind: StoreKind;
11
+ site: string;
12
+ open(): KV;
13
+ prepare(): Promise<void>;
14
+ };
15
+ type Env = Record<string, string | undefined>;
16
+ /**
17
+ * How a connection string becomes a Query: the driver, one pool per string
18
+ * per instance, kept for the life of the instance so every request reuses
19
+ * its connections. Tests put an embedded Postgres here (postgresThrough).
20
+ */
21
+ type Pool = Query & {
22
+ end?(): Promise<void>;
23
+ };
24
+ /** For tests: every connection string opens `to` from here on, until another call. */
25
+ export declare function postgresThrough(to: (url: string) => Pool): void;
26
+ /**
27
+ * Closes every pool this process opened, for a command once it is done: an
28
+ * idle connection would otherwise keep the process alive until it times out.
29
+ */
30
+ export declare function closeStores(): Promise<void>;
31
+ /**
32
+ * The review store the env names, null when it names none, or why none can
33
+ * be opened: a store of each kind, or two Postgres databases. Nothing is
34
+ * connected until `open` is called.
35
+ */
36
+ export declare function chooseStore(env: Env): StoreChoice | {
37
+ error: string;
38
+ } | null;
39
+ /** The site the env's store gives the gate to sign tokens to; empty when it names none, or two. */
40
+ export declare function storeSite(env: Env): string;
41
+ export {};
@@ -0,0 +1,63 @@
1
+ import { createTable, driverQuery, isPostgresUrl, postgresKV, postgresSite } from './postgres.js';
2
+ import { storeConfig, upstashKV } from './upstash.js';
3
+ /** The env names each kind of store is read from. */
4
+ const STORE_ENV = {
5
+ upstash: ['KV_REST_API_URL', 'KV_REST_API_TOKEN', 'UPSTASH_REDIS_REST_URL', 'UPSTASH_REDIS_REST_TOKEN'],
6
+ postgres: ['DATABASE_URL', 'POSTGRES_URL'],
7
+ };
8
+ let connect = driverQuery;
9
+ const pools = new Map();
10
+ const pool = (url) => pools.get(url) ?? pools.set(url, connect(url)).get(url);
11
+ /** For tests: every connection string opens `to` from here on, until another call. */
12
+ export function postgresThrough(to) {
13
+ connect = to;
14
+ pools.clear();
15
+ }
16
+ /**
17
+ * Closes every pool this process opened, for a command once it is done: an
18
+ * idle connection would otherwise keep the process alive until it times out.
19
+ */
20
+ export async function closeStores() {
21
+ const open = [...pools.values()];
22
+ pools.clear();
23
+ await Promise.all(open.map((p) => p.end?.()));
24
+ }
25
+ /** The Postgres connection string an env names, the names it was read from, or why it is refused. */
26
+ function postgresUrl(env) {
27
+ const [a, b] = STORE_ENV.postgres.map((name) => (isPostgresUrl(env[name]) ? env[name] : undefined));
28
+ if (a && b && postgresSite(a) !== postgresSite(b))
29
+ return { error: 'DATABASE_URL and POSTGRES_URL name two different databases.' };
30
+ const url = a ?? b;
31
+ return url ? { url } : null;
32
+ }
33
+ /**
34
+ * The review store the env names, null when it names none, or why none can
35
+ * be opened: a store of each kind, or two Postgres databases. Nothing is
36
+ * connected until `open` is called.
37
+ */
38
+ export function chooseStore(env) {
39
+ const upstash = storeConfig(env);
40
+ const pg = postgresUrl(env);
41
+ if (pg && 'error' in pg)
42
+ return pg;
43
+ // An Upstash URL alone, with no token, still names a store: never a reason to take the Postgres one.
44
+ if ((upstash || env.KV_REST_API_URL || env.UPSTASH_REDIS_REST_URL) && pg)
45
+ return {
46
+ error: 'Both an Upstash store (KV_REST_API_URL) and a Postgres one (DATABASE_URL or POSTGRES_URL) are set, and a studio has one database.',
47
+ };
48
+ if (upstash)
49
+ return { kind: 'upstash', site: upstash.url, open: () => upstashKV(upstash), prepare: async () => { } };
50
+ if (pg)
51
+ return {
52
+ kind: 'postgres',
53
+ site: postgresSite(pg.url),
54
+ open: () => postgresKV(pool(pg.url)),
55
+ prepare: () => createTable(pool(pg.url)),
56
+ };
57
+ return null;
58
+ }
59
+ /** The site the env's store gives the gate to sign tokens to; empty when it names none, or two. */
60
+ export function storeSite(env) {
61
+ const chosen = chooseStore(env);
62
+ return chosen && 'site' in chosen ? chosen.site : '';
63
+ }
@@ -0,0 +1,16 @@
1
+ import type { KV, Snapshot } from '../../core/review/store.ts';
2
+ import { type Query } from './postgres.ts';
3
+ /** The process's one embedded Postgres, as a Query. */
4
+ export declare function pgliteQuery(): Promise<Query>;
5
+ /**
6
+ * A store made at once and ready on its first call, so a test builds it
7
+ * where it built a memory store. `after` runs after every op, with its name
8
+ * and arguments, before the op answers.
9
+ */
10
+ export declare function deferredKV(ready: Promise<KV>, after?: (op: keyof KV, args: string[]) => Promise<void>): KV;
11
+ /**
12
+ * The memory store's shape on the embedded Postgres: a store on a new table
13
+ * of its own, holding `initial`, that calls `onChange` with every key after
14
+ * each write, as memoryKV does.
15
+ */
16
+ export declare function pgliteKV(initial?: Snapshot, onChange?: (s: Snapshot) => void): KV;