@velocity-astro/cms-astro 0.1.0-beta.3 → 0.1.0-beta.5

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 (58) hide show
  1. package/dist/admin-files.d.ts +2 -2
  2. package/dist/admin-files.d.ts.map +1 -1
  3. package/dist/admin-files.js +13 -7
  4. package/dist/admin-files.js.map +1 -1
  5. package/dist/challenge.d.ts +35 -0
  6. package/dist/challenge.d.ts.map +1 -0
  7. package/dist/challenge.js +84 -0
  8. package/dist/challenge.js.map +1 -0
  9. package/dist/connection.d.ts.map +1 -1
  10. package/dist/connection.js +22 -11
  11. package/dist/connection.js.map +1 -1
  12. package/dist/editor.d.ts +2 -0
  13. package/dist/editor.d.ts.map +1 -1
  14. package/dist/editor.js +9 -1
  15. package/dist/editor.js.map +1 -1
  16. package/dist/form-post.d.ts +9 -1
  17. package/dist/form-post.d.ts.map +1 -1
  18. package/dist/form-post.js +10 -3
  19. package/dist/form-post.js.map +1 -1
  20. package/dist/index.d.ts +8 -3
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +8 -3
  23. package/dist/index.js.map +1 -1
  24. package/dist/media-store.d.ts +9 -0
  25. package/dist/media-store.d.ts.map +1 -1
  26. package/dist/media-store.js +17 -1
  27. package/dist/media-store.js.map +1 -1
  28. package/dist/page-marks.d.ts +34 -0
  29. package/dist/page-marks.d.ts.map +1 -0
  30. package/dist/page-marks.js +68 -0
  31. package/dist/page-marks.js.map +1 -0
  32. package/dist/resend-mailer.d.ts +18 -1
  33. package/dist/resend-mailer.d.ts.map +1 -1
  34. package/dist/resend-mailer.js +24 -3
  35. package/dist/resend-mailer.js.map +1 -1
  36. package/dist/site-editor.d.ts +1 -1
  37. package/dist/site-editor.d.ts.map +1 -1
  38. package/dist/site-editor.js +28 -6
  39. package/dist/site-editor.js.map +1 -1
  40. package/dist/site-forms.d.ts +11 -0
  41. package/dist/site-forms.d.ts.map +1 -1
  42. package/dist/site-forms.js +29 -16
  43. package/dist/site-forms.js.map +1 -1
  44. package/dist/site-mail.d.ts +45 -0
  45. package/dist/site-mail.d.ts.map +1 -0
  46. package/dist/site-mail.js +84 -0
  47. package/dist/site-mail.js.map +1 -0
  48. package/dist/site-name.d.ts +9 -0
  49. package/dist/site-name.d.ts.map +1 -0
  50. package/dist/site-name.js +21 -0
  51. package/dist/site-name.js.map +1 -0
  52. package/dist/site-storage.d.ts +34 -0
  53. package/dist/site-storage.d.ts.map +1 -0
  54. package/dist/site-storage.js +118 -0
  55. package/dist/site-storage.js.map +1 -0
  56. package/package.json +7 -7
  57. package/routes/form-client.js.ts +68 -0
  58. package/routes/preview-client.js.ts +4 -56
@@ -1,14 +1,16 @@
1
1
  import { isLiveType } from '@velocity-astro/cms-core';
2
2
  import { sharedConnection, SITE } from './connection.js';
3
- import { FORM_ABOUT_FIELD, FORM_LOCALE_FIELD, FORM_PAGE_FIELD, FORM_TOKEN_FIELD, FORM_TRAP_FIELD, FormPosts, aboutMark, formToken } from './form-post.js';
3
+ import { FORM_ABOUT_FIELD, FORM_CHALLENGE_KEY_FIELD, FORM_LOCALE_FIELD, FORM_PAGE_FIELD, FORM_TOKEN_FIELD, FORM_TRAP_FIELD, FormPosts, MemoryRateLimiter, aboutMark, formToken } from './form-post.js';
4
4
  import { pageAt } from './page-head.js';
5
5
  import { currentSite, siteKey } from './hosted.js';
6
- import { mailerFromEnv } from './resend-mailer.js';
6
+ import { LogMailer } from './editor.js';
7
+ import { SiteMail } from './site-mail.js';
8
+ import { siteNameNow } from './site-name.js';
9
+ import { SiteChallenge, TURNSTILE_HOST, TURNSTILE_SCRIPT } from './challenge.js';
7
10
  import { siteSecret } from './secret.js';
8
11
  import { editorOrigin } from './site-editor.js';
9
12
  /** One taker of form posts for each site this server runs. */
10
13
  const takers = new Map();
11
- const takesNotices = (mailer) => typeof mailer === 'object' && mailer !== null && typeof mailer.sendSubmissionNotice === 'function';
12
14
  /** The site's address for forms. A site that has not said its address yet is taken at the request's word. */
13
15
  function originOf(request, settings) {
14
16
  try {
@@ -23,19 +25,27 @@ export function siteFormPosts(settings) {
23
25
  const key = siteKey();
24
26
  let posts = takers.get(key);
25
27
  if (!posts) {
26
- const made = sharedConnection({}).then(({ cms }) => new FormPosts({
27
- cms,
28
- origin: (request) => originOf(request, settings),
29
- siteName: currentSite()?.name ?? settings.siteName,
30
- secret: siteSecret(),
31
- entryAt: async (path) => {
32
- const { type, entry } = await pageAt(cms, await cms.schema.list(), path);
33
- return type && entry ? { typeId: type.id, entry: entry.translationGroup } : undefined;
34
- },
35
- // The site's own mailer when it sends notices, then Resend from its settings, then nobody.
36
- mailer: takesNotices(settings.mailer) ? settings.mailer : mailerFromEnv(),
37
- onFault: (error) => console.error('[velocity-cms]', error instanceof Error ? error.message : error),
38
- }));
28
+ const onFault = (error) => console.error('[velocity-cms]', error instanceof Error ? error.message : error);
29
+ const made = sharedConnection({}).then(({ cms }) => {
30
+ const challenge = new SiteChallenge({ account: () => cms.settings.challengeAccount(), onFault });
31
+ const counted = new MemoryRateLimiter();
32
+ return new FormPosts({
33
+ cms,
34
+ origin: (request) => originOf(request, settings),
35
+ siteName: currentSite()?.name ?? settings.siteName,
36
+ secret: siteSecret(),
37
+ entryAt: async (path) => {
38
+ const { type, entry } = await pageAt(cms, await cms.schema.list(), path);
39
+ return type && entry ? { typeId: type.id, entry: entry.translationGroup } : undefined;
40
+ },
41
+ // The site's own mailer when it sends notices, then Resend from the server's settings, then what an owner set up in the editor.
42
+ mailer: new SiteMail({ settings: cms.settings, own: settings.mailer, fallback: new LogMailer(), hosted: currentSite() !== undefined, ...(currentSite() === undefined && { siteName: () => siteNameNow(cms) }) }),
43
+ challenge,
44
+ // What an owner set under Settings, Forms and spam. Settings that cannot be read leave the limit the CMS comes with.
45
+ limiter: { take: async (address) => counted.take(address, await cms.settings.formPostsPerAddress().catch(() => undefined)) },
46
+ onFault,
47
+ });
48
+ });
39
49
  posts = made;
40
50
  takers.set(key, made);
41
51
  made.catch(() => {
@@ -59,6 +69,7 @@ export async function siteForm(page, choice, options = {}) {
59
69
  return null;
60
70
  const token = await formToken(siteSecret(), form.key);
61
71
  const locale = page.currentLocale;
72
+ const siteKey = await cms.settings.challengeSiteKey();
62
73
  let about;
63
74
  if (options.about) {
64
75
  // An entry that is not there, or not published, leaves the form as one about nothing.
@@ -75,8 +86,10 @@ export async function siteForm(page, choice, options = {}) {
75
86
  ...(locale !== undefined && { [FORM_LOCALE_FIELD]: locale }),
76
87
  ...(token !== undefined && { [FORM_TOKEN_FIELD]: token }),
77
88
  ...(about !== undefined && { [FORM_ABOUT_FIELD]: about }),
89
+ ...(siteKey !== null && { [FORM_CHALLENGE_KEY_FIELD]: siteKey }),
78
90
  },
79
91
  trap: FORM_TRAP_FIELD,
92
+ ...(siteKey !== null && { challenge: { provider: 'turnstile', siteKey, script: TURNSTILE_SCRIPT, host: TURNSTILE_HOST } }),
80
93
  };
81
94
  }
82
95
  catch (error) {
@@ -1 +1 @@
1
- {"version":3,"file":"site-forms.js","sourceRoot":"","sources":["../src/site-forms.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AACzD,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,eAAe,EAAE,gBAAgB,EAAE,eAAe,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS,EAAqB,MAAM,gBAAgB,CAAC;AAC7K,OAAO,EAAE,MAAM,EAAkB,MAAM,gBAAgB,CAAC;AACxD,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,YAAY,EAA2B,MAAM,kBAAkB,CAAC;AAEzE,8DAA8D;AAC9D,MAAM,MAAM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AAO,CAAC,KAAK,CAAC,0CAA0C,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;QAC1G,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC"}
@@ -0,0 +1,45 @@
1
+ import type { InvitationMail, Mailer, SignInMail } from '@velocity-astro/cms-auth';
2
+ import { type Cms, type MailFixedBy } from '@velocity-astro/cms-core';
3
+ import type { NoticeMailer, SubmissionNotice } from './form-post.js';
4
+ import { type TestMail } from './resend-mailer.js';
5
+ export interface SiteMailOptions {
6
+ /** The site's settings, where an owner may have said how email is sent. */
7
+ readonly settings: Cms['settings'];
8
+ /** The site's own mailer, from its code (`velocityCms({ mailer })`). It wins over everything. */
9
+ readonly own?: Mailer | undefined;
10
+ /** What sign-in links go to when nothing sends email: the server's log. */
11
+ readonly fallback: Mailer;
12
+ /** What an owner called the site in the editor, or `null`. It is what an email calls the site, when there is one. */
13
+ readonly siteName?: () => Promise<string | null>;
14
+ /** Whether a host runs this site among many, so what is fixed is fixed by the host. */
15
+ readonly hosted?: boolean;
16
+ /** Defaults to the server's own environment. */
17
+ readonly env?: Readonly<Record<string, string | undefined>>;
18
+ /** Defaults to the platform's own `fetch`. */
19
+ readonly fetch?: typeof globalThis.fetch;
20
+ }
21
+ /**
22
+ * How one site's email leaves, decided each time one is sent: the site's own mailer from its
23
+ * code, then Resend from the server's settings, then what an owner set up in the editor, and
24
+ * for sign-in links with none of the three, the server's log. The editor's settings are read
25
+ * from the database for every email, so every running copy follows a change at once, and the
26
+ * key is held only for as long as the email takes.
27
+ */
28
+ export declare class SiteMail implements Mailer, NoticeMailer {
29
+ #private;
30
+ constructor(options: SiteMailOptions);
31
+ /** Who decides how email is sent when the editor's settings do not. */
32
+ fixedBy(): MailFixedBy | null;
33
+ sendSignInLink(mail: SignInMail): Promise<void>;
34
+ sendInvitation(mail: InvitationMail): Promise<void>;
35
+ /** A notice goes through the site's own mailer when it sends notices, and otherwise as the settings say. */
36
+ sendSubmissionNotice(mail: SubmissionNotice): Promise<void>;
37
+ /** Whether email is sent in a way that can send a test. */
38
+ canTest(): Promise<boolean>;
39
+ /**
40
+ * Sends the test. What the provider said goes nowhere but into the words for the owner who
41
+ * asked: which of the two things they typed to look at again.
42
+ */
43
+ sendTest(mail: TestMail): Promise<void>;
44
+ }
45
+ //# sourceMappingURL=site-mail.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"site-mail.d.ts","sourceRoot":"","sources":["../src/site-mail.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AACnF,OAAO,EAAiB,KAAK,GAAG,EAAE,KAAK,WAAW,EAAE,MAAM,0BAA0B,CAAC;AACrF,OAAO,KAAK,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AACrE,OAAO,EAAiD,KAAK,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAElG,MAAM,WAAW,eAAe;IAC9B,2EAA2E;IAC3E,QAAQ,CAAC,QAAQ,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC;IACnC,iGAAiG;IACjG,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAClC,2EAA2E;IAC3E,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,qHAAqH;IACrH,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IACjD,uFAAuF;IACvF,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC;IAC1B,gDAAgD;IAChD,QAAQ,CAAC,GAAG,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC,CAAC;IAC5D,8CAA8C;IAC9C,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,UAAU,CAAC,KAAK,CAAC;CAC1C;AAQD;;;;;;GAMG;AACH,qBAAa,QAAS,YAAW,MAAM,EAAE,YAAY;;gBAGvC,OAAO,EAAE,eAAe;IAIpC,uEAAuE;IACvE,OAAO,IAAI,WAAW,GAAG,IAAI;IAKvB,cAAc,CAAC,IAAI,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC;IAI/C,cAAc,CAAC,IAAI,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;IAIzD,4GAA4G;IACtG,oBAAoB,CAAC,IAAI,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC;IAOjE,2DAA2D;IACrD,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC;IAIjC;;;OAGG;IACG,QAAQ,CAAC,IAAI,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;CAyC9C"}
@@ -0,0 +1,84 @@
1
+ import { ConflictError } from '@velocity-astro/cms-core';
2
+ import { MailRefusedError, ResendMailer, mailerFromEnv } from './resend-mailer.js';
3
+ const takesNotices = (mailer) => typeof mailer === 'object' && mailer !== null && typeof mailer.sendSubmissionNotice === 'function';
4
+ const sendsTests = (mailer) => typeof mailer === 'object' && mailer !== null && typeof mailer.sendTest === 'function';
5
+ /**
6
+ * How one site's email leaves, decided each time one is sent: the site's own mailer from its
7
+ * code, then Resend from the server's settings, then what an owner set up in the editor, and
8
+ * for sign-in links with none of the three, the server's log. The editor's settings are read
9
+ * from the database for every email, so every running copy follows a change at once, and the
10
+ * key is held only for as long as the email takes.
11
+ */
12
+ export class SiteMail {
13
+ #options;
14
+ constructor(options) {
15
+ this.#options = options;
16
+ }
17
+ /** Who decides how email is sent when the editor's settings do not. */
18
+ fixedBy() {
19
+ const fixed = this.#options.own ? 'code' : this.#fromServer() ? 'server' : null;
20
+ return fixed !== null && this.#options.hosted === true ? 'host' : fixed;
21
+ }
22
+ async sendSignInLink(mail) {
23
+ await ((await this.#mailer()) ?? this.#options.fallback).sendSignInLink(await this.#named(mail));
24
+ }
25
+ async sendInvitation(mail) {
26
+ await ((await this.#mailer()) ?? this.#options.fallback).sendInvitation(await this.#named(mail));
27
+ }
28
+ /** A notice goes through the site's own mailer when it sends notices, and otherwise as the settings say. */
29
+ async sendSubmissionNotice(mail) {
30
+ const { own } = this.#options;
31
+ const mailer = takesNotices(own) ? own : (this.#fromServer() ?? (await this.#fromEditor()));
32
+ if (!mailer)
33
+ throw new Error('No email provider is set up. Set one up under Settings, Email in the editor.');
34
+ await mailer.sendSubmissionNotice(await this.#named(mail));
35
+ }
36
+ /** Whether email is sent in a way that can send a test. */
37
+ async canTest() {
38
+ return sendsTests(await this.#mailer());
39
+ }
40
+ /**
41
+ * Sends the test. What the provider said goes nowhere but into the words for the owner who
42
+ * asked: which of the two things they typed to look at again.
43
+ */
44
+ async sendTest(mail) {
45
+ const mailer = await this.#mailer();
46
+ if (!sendsTests(mailer))
47
+ throw new ConflictError('No test email can be sent yet. Save an API key and a sender first.');
48
+ try {
49
+ await mailer.sendTest(await this.#named(mail));
50
+ }
51
+ catch (error) {
52
+ if (!(error instanceof MailRefusedError))
53
+ throw new ConflictError('The email service could not be reached, so no test was sent. Try again in a moment.');
54
+ const { status } = error;
55
+ throw new ConflictError(status === 401
56
+ ? 'Resend did not accept the API key (401). Check that it was pasted whole, and that it has not been deleted in Resend.'
57
+ : status === 403
58
+ ? 'Resend refused to send from this sender (403). Verify the sender\'s domain in Resend, and check that the API key may send email.'
59
+ : status === 422
60
+ ? 'Resend did not accept the sender (422). Use an address on a domain you have verified in Resend.'
61
+ : status === 429
62
+ ? 'Resend is turning email away for now (429): too many were sent, or the plan\'s limit is reached. Try again later.'
63
+ : `Resend could not send the test (${status}). Try again in a moment.`);
64
+ }
65
+ }
66
+ /** The email with the site called what an owner called it. A name that cannot be read leaves the email as it was. */
67
+ async #named(mail) {
68
+ const siteName = await this.#options.siteName?.().catch(() => null);
69
+ return siteName ? { ...mail, siteName } : mail;
70
+ }
71
+ async #mailer() {
72
+ return this.#options.own ?? this.#fromServer() ?? (await this.#fromEditor());
73
+ }
74
+ #fromServer() {
75
+ return mailerFromEnv(this.#options.env, this.#options.fetch);
76
+ }
77
+ async #fromEditor() {
78
+ const account = await this.#options.settings.mailAccount();
79
+ if (account === null)
80
+ return undefined;
81
+ return new ResendMailer({ apiKey: account.apiKey, from: account.from, ...(this.#options.fetch && { fetch: this.#options.fetch }) });
82
+ }
83
+ }
84
+ //# sourceMappingURL=site-mail.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"site-mail.js","sourceRoot":"","sources":["../src/site-mail.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAA8B,MAAM,0BAA0B,CAAC;AAErF,OAAO,EAAE,gBAAgB,EAAE,YAAY,EAAE,aAAa,EAAiB,MAAM,oBAAoB,CAAC;AAqBlG,MAAM,YAAY,GAAG,CAAC,MAAe,EAA0B,EAAE,CAC/D,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,KAAK,IAAI,IAAI,OAAQ,MAA6C,CAAC,oBAAoB,KAAK,UAAU,CAAC;AAC7I,MAAM,UAAU,GAAG,CAAC,MAAe,EAAoB,EAAE,CAAC,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,KAAK,IAAI,IAAI,OAAQ,MAAiC,CAAC,QAAQ,KAAK,UAAU,CAAC;AAE7K;;;;;;GAMG;AACH,MAAM,OAAO,QAAQ;IACV,QAAQ,CAAkB;IAEnC,YAAY,OAAwB;QAClC,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;IAC1B,CAAC;IAED,uEAAuE;IACvE,OAAO;QACL,MAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC;QAChF,OAAO,KAAK,KAAK,IAAI,IAAI,IAAI,CAAC,QAA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QACT,OAAO,aAAa,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,EAAE,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IAC/D,CAAC;IAED,KAAK,CAAC,WAAW;QACf,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC;QAC3D,IAAI,OAAO,KAAK,IAAI;YAAE,OAAO,SAAS,CAAC;QACvC,OAAO,IAAI,YAAY,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,IAAI,EAAE,KAAK,EAAE,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;IACtI,CAAC;CACF"}
@@ -0,0 +1,9 @@
1
+ import { type Cms } from '@velocity-astro/cms-core';
2
+ /**
3
+ * What the site is called, when nothing fixes it: the name published on the page of the settings
4
+ * that holds it (a template's "Business details"), then what an owner saved under Settings,
5
+ * General. `null` when neither says, so the name from the site's code stands. One field names
6
+ * the site for its visitors, its editor and its emails.
7
+ */
8
+ export declare function siteNameNow(cms: Cms): Promise<string | null>;
9
+ //# sourceMappingURL=site-name.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"site-name.d.ts","sourceRoot":"","sources":["../src/site-name.ts"],"names":[],"mappings":"AAAA,OAAO,EAA4B,KAAK,GAAG,EAAE,MAAM,0BAA0B,CAAC;AAG9E;;;;;GAKG;AACH,wBAAsB,WAAW,CAAC,GAAG,EAAE,GAAG,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAUlE"}
@@ -0,0 +1,21 @@
1
+ import { isLiveType, siteNameFrom } from '@velocity-astro/cms-core';
2
+ import { DEFAULT_LOCALE, entriesOf } from './link.js';
3
+ /**
4
+ * What the site is called, when nothing fixes it: the name published on the page of the settings
5
+ * that holds it (a template's "Business details"), then what an owner saved under Settings,
6
+ * General. `null` when neither says, so the name from the site's code stands. One field names
7
+ * the site for its visitors, its editor and its emails.
8
+ */
9
+ export async function siteNameNow(cms) {
10
+ const type = (await cms.schema.list()).find((candidate) => isLiveType(candidate) && candidate.siteNamePath !== undefined);
11
+ if (type) {
12
+ const published = (await entriesOf(cms, type)).filter((entry) => entry.published !== undefined);
13
+ // The first language's name is the site's: an email is not written in a visitor's language.
14
+ const entry = published.find((candidate) => candidate.locale === DEFAULT_LOCALE) ?? published[0];
15
+ const name = entry?.published ? siteNameFrom(type, entry.published.data) : null;
16
+ if (name !== null)
17
+ return name;
18
+ }
19
+ return cms.settings.siteName();
20
+ }
21
+ //# sourceMappingURL=site-name.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"site-name.js","sourceRoot":"","sources":["../src/site-name.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAY,MAAM,0BAA0B,CAAC;AAC9E,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAEtD;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,GAAQ;IACxC,MAAM,IAAI,GAAG,CAAC,MAAM,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,UAAU,CAAC,SAAS,CAAC,IAAI,SAAS,CAAC,YAAY,KAAK,SAAS,CAAC,CAAC;IAC1H,IAAI,IAAI,EAAE,CAAC;QACT,MAAM,SAAS,GAAG,CAAC,MAAM,SAAS,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,SAAS,KAAK,SAAS,CAAC,CAAC;QAChG,4FAA4F;QAC5F,MAAM,KAAK,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,MAAM,KAAK,cAAc,CAAC,IAAI,SAAS,CAAC,CAAC,CAAC,CAAC;QACjG,MAAM,IAAI,GAAG,KAAK,EAAE,SAAS,CAAC,CAAC,CAAC,YAAY,CAAC,IAAI,EAAE,KAAK,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;QAChF,IAAI,IAAI,KAAK,IAAI;YAAE,OAAO,IAAI,CAAC;IACjC,CAAC;IACD,OAAO,GAAG,CAAC,QAAQ,CAAC,QAAQ,EAAE,CAAC;AACjC,CAAC"}
@@ -0,0 +1,34 @@
1
+ import { type BucketAccount, type MediaStore, type NameLookup, type StorageRoom, type StoredFile } from '@velocity-astro/cms-core';
2
+ export interface SiteMediaStoreOptions {
3
+ /** The bucket an owner named in the editor's settings, read when it is needed. */
4
+ readonly account: () => Promise<BucketAccount | null>;
5
+ /** The store the server's own settings or the site's host name. It wins over the editor's. */
6
+ readonly fixed?: MediaStore | undefined;
7
+ /** Whether a host runs this site among many. Its uploads are then the host's to place, and the editor's settings are never used. */
8
+ readonly hosted?: boolean;
9
+ /** The folder on the server's disk, where there is one: where uploads go until a bucket is named, and where earlier ones are still read. */
10
+ readonly folder?: MediaStore | undefined;
11
+ /** Every address a host's name leads to, so a bucket's address that leads to a private machine is refused. */
12
+ readonly lookup: NameLookup;
13
+ /** Defaults to the platform's own `fetch`. */
14
+ readonly fetch?: typeof globalThis.fetch;
15
+ /** How long the editor's settings are believed before they are read again. Defaults to five seconds. */
16
+ readonly believeForMs?: number;
17
+ }
18
+ /**
19
+ * Where one site's uploads are kept, decided as each file is kept or read: the store the server
20
+ * or the host fixed, then the bucket an owner named in the editor, then the folder on the
21
+ * server's disk. The editor's settings are read again every few seconds, so every running copy
22
+ * follows a change. A file kept on the disk before a bucket was named is still read from there.
23
+ */
24
+ export declare class SiteMediaStore implements MediaStore {
25
+ #private;
26
+ constructor(options: SiteMediaStoreOptions);
27
+ ready(): Promise<boolean>;
28
+ put(key: string, file: StoredFile): Promise<void>;
29
+ get(key: string): Promise<StoredFile | null>;
30
+ remove(key: string): Promise<void>;
31
+ /** What the settings screen asks: who decides, where an upload would go, and whether the named bucket works. */
32
+ room(): StorageRoom;
33
+ }
34
+ //# sourceMappingURL=site-storage.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"site-storage.d.ts","sourceRoot":"","sources":["../src/site-storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAmC,KAAK,aAAa,EAAE,KAAK,UAAU,EAAE,KAAK,UAAU,EAA4C,KAAK,WAAW,EAAE,KAAK,UAAU,EAAE,MAAM,0BAA0B,CAAC;AAG9M,MAAM,WAAW,qBAAqB;IACpC,kFAAkF;IAClF,QAAQ,CAAC,OAAO,EAAE,MAAM,OAAO,CAAC,aAAa,GAAG,IAAI,CAAC,CAAC;IACtD,8FAA8F;IAC9F,QAAQ,CAAC,KAAK,CAAC,EAAE,UAAU,GAAG,SAAS,CAAC;IACxC,oIAAoI;IACpI,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC;IAC1B,4IAA4I;IAC5I,QAAQ,CAAC,MAAM,CAAC,EAAE,UAAU,GAAG,SAAS,CAAC;IACzC,8GAA8G;IAC9G,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAC;IAC5B,8CAA8C;IAC9C,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,UAAU,CAAC,KAAK,CAAC;IACzC,wGAAwG;IACxG,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;CAChC;AAKD;;;;;GAKG;AACH,qBAAa,cAAe,YAAW,UAAU;;gBAInC,OAAO,EAAE,qBAAqB;IAIpC,KAAK,IAAI,OAAO,CAAC,OAAO,CAAC;IAIzB,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC;IAMjD,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC;IAQ5C,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAOxC,gHAAgH;IAChH,IAAI,IAAI,WAAW;CA8EpB"}
@@ -0,0 +1,118 @@
1
+ import { ConflictError, isPrivateAddress } from '@velocity-astro/cms-core';
2
+ import { S3MediaStore, StorageRefusedError } from './media-store.js';
3
+ /** A small PNG: one see-through pixel. What a test keeps in the bucket, reads back and removes. */
4
+ const PIXEL = Uint8Array.from(atob('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII='), (letter) => letter.charCodeAt(0));
5
+ /**
6
+ * Where one site's uploads are kept, decided as each file is kept or read: the store the server
7
+ * or the host fixed, then the bucket an owner named in the editor, then the folder on the
8
+ * server's disk. The editor's settings are read again every few seconds, so every running copy
9
+ * follows a change. A file kept on the disk before a bucket was named is still read from there.
10
+ */
11
+ export class SiteMediaStore {
12
+ #options;
13
+ #named = null;
14
+ constructor(options) {
15
+ this.#options = options;
16
+ }
17
+ async ready() {
18
+ return (await this.#place()) !== undefined;
19
+ }
20
+ async put(key, file) {
21
+ const place = await this.#place();
22
+ if (!place)
23
+ throw new ConflictError('This site has nowhere to keep uploads yet. An owner can set storage up under Settings, Storage.');
24
+ await place.put(key, file);
25
+ }
26
+ async get(key) {
27
+ const place = await this.#place();
28
+ const { folder } = this.#options;
29
+ const found = (await place?.get(key)) ?? null;
30
+ // An image uploaded before the bucket was named is still on the disk.
31
+ return found === null && folder && place !== folder ? folder.get(key) : found;
32
+ }
33
+ async remove(key) {
34
+ const place = await this.#place();
35
+ const { folder } = this.#options;
36
+ await place?.remove(key);
37
+ if (folder && place !== folder)
38
+ await folder.remove(key);
39
+ }
40
+ /** What the settings screen asks: who decides, where an upload would go, and whether the named bucket works. */
41
+ room() {
42
+ return {
43
+ fixedBy: () => this.#fixedBy(),
44
+ keeping: () => this.#keeping(),
45
+ test: () => this.#test(),
46
+ };
47
+ }
48
+ #fixedBy() {
49
+ return this.#options.hosted === true ? 'host' : this.#options.fixed ? 'server' : null;
50
+ }
51
+ async #keeping() {
52
+ const place = await this.#place().catch(() => undefined);
53
+ return place === undefined ? 'none' : place === this.#options.folder ? 'folder' : 'bucket';
54
+ }
55
+ async #place() {
56
+ const { fixed, folder } = this.#options;
57
+ if (fixed || this.#options.hosted === true)
58
+ return fixed;
59
+ return (await this.#bucket()) ?? folder;
60
+ }
61
+ /** The bucket the editor's settings name, made anew when they are read again. */
62
+ #bucket() {
63
+ const now = Date.now();
64
+ if (this.#named === null || now - this.#named.at >= (this.#options.believeForMs ?? 5000)) {
65
+ const store = this.#options.account().then((account) => (account === null ? undefined : this.#storeFor(account)));
66
+ const named = { at: now, store };
67
+ this.#named = named;
68
+ // A failure is not believed for five seconds: the next file asks again.
69
+ store.catch(() => {
70
+ if (this.#named === named)
71
+ this.#named = null;
72
+ });
73
+ }
74
+ return this.#named.store;
75
+ }
76
+ async #storeFor(account) {
77
+ const host = new URL(account.endpoint).hostname;
78
+ const addresses = await this.#options.lookup(host).catch(() => []);
79
+ if (addresses.length === 0 || addresses.some(isPrivateAddress)) {
80
+ throw new ConflictError(`The storage service's address, ${host}, leads nowhere this site may send files. Check it under Settings, Storage.`);
81
+ }
82
+ const send = this.#options.fetch ?? globalThis.fetch;
83
+ // An answer that sends the request elsewhere is refused: only the address that was checked is used.
84
+ return new S3MediaStore({ ...account, fetch: (input, init) => send(input, { ...init, redirect: 'error' }) });
85
+ }
86
+ async #test() {
87
+ const account = await this.#options.account();
88
+ if (account === null)
89
+ throw new ConflictError('There is no bucket to try yet. Save its address, name and both keys first.');
90
+ const bucket = await this.#storeFor(account);
91
+ const key = `connection-test-${globalThis.crypto.randomUUID().replace(/-/g, '')}.png`;
92
+ try {
93
+ await bucket.put(key, { bytes: PIXEL, contentType: 'image/png' });
94
+ const back = await bucket.get(key);
95
+ await bucket.remove(key);
96
+ if (back === null || back.bytes.length !== PIXEL.length)
97
+ throw new ConflictError('The bucket took a file and did not give it back. Check that the keys may read from it as well as write.');
98
+ }
99
+ catch (error) {
100
+ if (error instanceof ConflictError)
101
+ throw error;
102
+ if (!(error instanceof StorageRefusedError)) {
103
+ throw new ConflictError('The storage service could not be reached. Check its address, and the region if the service has more than one.');
104
+ }
105
+ const { status } = error;
106
+ throw new ConflictError(status === 401 || status === 403
107
+ ? `The storage service refused the keys (${status}). Check that both were pasted whole, and that they may read, write and delete in this bucket.`
108
+ : status === 404
109
+ ? 'The storage service knows no bucket of this name (404). Check the name, and that the address is the one for your account.'
110
+ : status === 400
111
+ ? 'The storage service did not accept the request (400). Check the region: it must be the one the bucket is in.'
112
+ : `The storage service could not keep a file (${status}). Try again in a moment.`);
113
+ }
114
+ // What was just proved is used at once, not in five seconds.
115
+ this.#named = null;
116
+ }
117
+ }
118
+ //# sourceMappingURL=site-storage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"site-storage.js","sourceRoot":"","sources":["../src/site-storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAqI,MAAM,0BAA0B,CAAC;AAC9M,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAmBrE,mGAAmG;AACnG,MAAM,KAAK,GAAG,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,8FAA8F,CAAC,EAAE,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC;AAEtK;;;;;GAKG;AACH,MAAM,OAAO,cAAc;IAChB,QAAQ,CAAwB;IACzC,MAAM,GAAoF,IAAI,CAAC;IAE/F,YAAY,OAA8B;QACxC,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;IAC1B,CAAC;IAED,KAAK,CAAC,KAAK;QACT,OAAO,CAAC,MAAM,IAAI,CAAC,MAAM,EAAE,CAAC,KAAK,SAAS,CAAC;IAC7C,CAAC;IAED,KAAK,C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8CAA8C,MAAM,2BAA2B,CACxF,CAAC;QACJ,CAAC;QACD,6DAA6D;QAC7D,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;IACrB,CAAC;CACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@velocity-astro/cms-astro",
3
- "version": "0.1.0-beta.3",
3
+ "version": "0.1.0-beta.5",
4
4
  "description": "The Astro side of Velocity CMS: a live loader for pages rendered on demand, a Content Layer loader for static builds, and the integration.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -34,12 +34,12 @@
34
34
  "!dist/**/*.test.*"
35
35
  ],
36
36
  "dependencies": {
37
- "@velocity-astro/cms-admin": "0.1.0-beta.3",
38
- "@velocity-astro/cms-api": "0.1.0-beta.3",
39
- "@velocity-astro/cms-auth": "0.1.0-beta.3",
40
- "@velocity-astro/cms-db": "0.1.0-beta.3",
41
- "@velocity-astro/cms-plugins": "0.1.0-beta.3",
42
- "@velocity-astro/cms-core": "0.1.0-beta.3"
37
+ "@velocity-astro/cms-admin": "0.1.0-beta.5",
38
+ "@velocity-astro/cms-api": "0.1.0-beta.5",
39
+ "@velocity-astro/cms-auth": "0.1.0-beta.5",
40
+ "@velocity-astro/cms-core": "0.1.0-beta.5",
41
+ "@velocity-astro/cms-db": "0.1.0-beta.5",
42
+ "@velocity-astro/cms-plugins": "0.1.0-beta.5"
43
43
  },
44
44
  "optionalDependencies": {
45
45
  "sharp": "^0.35.4"
@@ -15,6 +15,11 @@ export const prerender = false;
15
15
  * - a submit button may carry `data-cms-form-sending`, its words while the form is on its way.
16
16
  * They replace the button's words, or those of the `[data-cms-form-label]` inside it.
17
17
  *
18
+ * - `[data-cms-form-challenge]`: where the check that the sender is a person is drawn, when an
19
+ * owner set one up (Cloudflare Turnstile). Without the mark it is drawn above the submit
20
+ * button. A site with a content security policy allows `https://challenges.cloudflare.com`
21
+ * for scripts and frames.
22
+ *
18
23
  * Every word is written as text. Nothing the visitor typed comes back from the site.
19
24
  */
20
25
  const SCRIPT = `
@@ -39,6 +44,66 @@ function say(form, state, message) {
39
44
  }
40
45
  }
41
46
 
47
+ const CHALLENGE = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit';
48
+ const challenges = new WeakMap();
49
+ const waiting = new WeakMap();
50
+ let challengeScript;
51
+
52
+ /** Loads the challenge's script once, however many forms a page has. */
53
+ function challengeReady() {
54
+ challengeScript ??= new Promise((resolve, reject) => {
55
+ if (window.turnstile) return resolve();
56
+ const script = document.createElement('script');
57
+ script.src = CHALLENGE;
58
+ script.async = true;
59
+ script.onload = () => resolve();
60
+ script.onerror = () => {
61
+ challengeScript = undefined;
62
+ reject(new Error('The challenge could not be loaded.'));
63
+ };
64
+ document.head.append(script);
65
+ });
66
+ return challengeScript;
67
+ }
68
+
69
+ /** Draws the check that the sender is a person, when the form carries a site key for one. */
70
+ function challenge(form) {
71
+ const siteKey = form.elements.namedItem('_challenge')?.value;
72
+ if (!siteKey || challenges.has(form)) return;
73
+ let place = form.querySelector('[data-cms-form-challenge]');
74
+ if (!place) {
75
+ place = document.createElement('div');
76
+ place.dataset.cmsFormChallenge = '';
77
+ const button = form.querySelector('[type="submit"]');
78
+ if (button) button.before(place);
79
+ else form.append(place);
80
+ }
81
+ challenges.set(
82
+ form,
83
+ challengeReady()
84
+ .then(() => window.turnstile.render(place, { sitekey: siteKey, theme: 'auto', size: 'flexible', language: document.documentElement.lang || 'auto', callback: () => waiting.get(form)?.() }))
85
+ // Without the challenge the form still posts. The site decides what to make of it.
86
+ .catch(() => undefined),
87
+ );
88
+ }
89
+
90
+ /** Waits, for a while, for the sender to pass a challenge that is still being worked out. */
91
+ async function challengePassed(form) {
92
+ const widget = await challenges.get(form);
93
+ if (widget == null || window.turnstile.getResponse(widget)) return;
94
+ await new Promise((resolve) => {
95
+ waiting.set(form, resolve);
96
+ setTimeout(resolve, 15000);
97
+ });
98
+ waiting.delete(form);
99
+ }
100
+
101
+ /** An answer to the challenge is used once: a new one is asked for after every post. */
102
+ async function challengeAgain(form) {
103
+ const widget = await challenges.get(form);
104
+ if (widget != null) window.turnstile?.reset(widget);
105
+ }
106
+
42
107
  async function send(form) {
43
108
  const button = form.querySelector('[type="submit"]');
44
109
  const words = button?.querySelector('[data-cms-form-label]') ?? button;
@@ -50,6 +115,7 @@ async function send(form) {
50
115
  if (button.dataset.cmsFormSending) words.textContent = button.dataset.cmsFormSending;
51
116
  }
52
117
  try {
118
+ await challengePassed(form);
53
119
  const response = await fetch(form.action, { method: 'POST', headers: { accept: 'application/json' }, body: new URLSearchParams(new FormData(form)) });
54
120
  const answer = await response.json().catch(() => null);
55
121
  if (response.ok && answer?.ok) {
@@ -75,6 +141,7 @@ async function send(form) {
75
141
  } catch {
76
142
  say(form, 'failed', form.dataset.cmsFormFailed ?? '');
77
143
  } finally {
144
+ void challengeAgain(form);
78
145
  if (button) {
79
146
  button.disabled = false;
80
147
  words.textContent = label;
@@ -86,6 +153,7 @@ function start() {
86
153
  for (const form of document.querySelectorAll('form[data-cms-form]')) {
87
154
  if (form.dataset.cmsFormReady) continue;
88
155
  form.dataset.cmsFormReady = 'true';
156
+ challenge(form);
89
157
  form.addEventListener('submit', (event) => {
90
158
  event.preventDefault();
91
159
  if (form.dataset.cmsFormState !== 'sending') void send(form);