@cossackframework/cms 0.9.2 → 0.9.4

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 (120) hide show
  1. package/agent-docs.json +8 -8
  2. package/app/cossack-recipe.json +12 -8
  3. package/app/src/auth-events.ts +33 -0
  4. package/app/src/auth-input.ts +3 -0
  5. package/app/src/auth-options.ts +39 -7
  6. package/app/src/auth.ts +1309 -641
  7. package/app/src/avatars.ts +13 -0
  8. package/app/src/brand.ts +24 -2
  9. package/app/src/cms/actor.ts +13 -0
  10. package/app/src/cms/collab/room.ts +1 -1
  11. package/app/src/cms/content-api.ts +2 -1
  12. package/app/src/cms/content.ts +3 -2
  13. package/app/src/cms/dev-mail.ts +77 -0
  14. package/app/src/cms/index.ts +37 -10
  15. package/app/src/cms/maintenance.ts +1 -6
  16. package/app/src/cms/manage.ts +17 -14
  17. package/app/src/cms/middleware.ts +58 -18
  18. package/app/src/cms/network-accounts.ts +110 -0
  19. package/app/src/cms/notes-announce.ts +1 -1
  20. package/app/src/cms/people.ts +177 -0
  21. package/app/src/cms/recovery.ts +9 -14
  22. package/app/src/cms/request-calls.ts +56 -0
  23. package/app/src/cms/settings-form.ts +23 -6
  24. package/app/src/cms/settings-network.ts +8 -4
  25. package/app/src/cms/settings-search.ts +1 -0
  26. package/app/src/cms/site-editing.ts +3 -2
  27. package/app/src/cms/site-registration.ts +64 -0
  28. package/app/src/cms/site.ts +30 -19
  29. package/app/src/cms/sites.ts +182 -0
  30. package/app/src/dashboard/access.ts +3 -2
  31. package/app/src/dashboard/modules/users.ts +1 -0
  32. package/app/src/lib/permissions.ts +24 -0
  33. package/app/src/lib/uuid.ts +6 -0
  34. package/app/src/mail.ts +15 -0
  35. package/app/src/middlewares/auth.ts +6 -2
  36. package/app/src/middlewares/tenant.ts +108 -0
  37. package/app/src/pages/(site)/[...path]/index.ts +1 -1
  38. package/app/src/pages/(site)/preview/[collection]/[id]/index.ts +1 -1
  39. package/app/src/pages/api/cms/dev/mail.ts +19 -0
  40. package/app/src/pages/api/cms/forms/[slug]/index.ts +1 -1
  41. package/app/src/pages/api/cms/users/[id]/meta.ts +2 -1
  42. package/app/src/pages/auth/login/index.ts +1 -1
  43. package/app/src/pages/auth/magic/index.ts +1 -1
  44. package/app/src/pages/auth/recovery.ts +20 -0
  45. package/app/src/pages/auth/register-site/index.ts +146 -0
  46. package/app/src/pages/auth/setup/index.ts +8 -3
  47. package/app/src/pages/auth/tenant/callback.ts +23 -0
  48. package/app/src/pages/auth/tenant/redirect.ts +91 -0
  49. package/app/src/pages/auth/verify/index.ts +3 -7
  50. package/app/src/pages/dashboard/(cms)/appearance/menus/[id]/index.ts +1 -1
  51. package/app/src/pages/dashboard/(cms)/content/[collection]/[id]/index.ts +5 -5
  52. package/app/src/pages/dashboard/(cms)/content/[collection]/[id]/revisions/index.ts +1 -1
  53. package/app/src/pages/dashboard/(cms)/content/[collection]/index.ts +1 -1
  54. package/app/src/pages/dashboard/(cms)/network/index.ts +4 -2
  55. package/app/src/pages/dashboard/(cms)/network/sites/[id]/index.ts +16 -13
  56. package/app/src/pages/dashboard/(cms)/network/sites/index.ts +4 -2
  57. package/app/src/pages/dashboard/(cms)/network/sites/new/index.ts +1 -1
  58. package/app/src/pages/dashboard/(cms)/network/users/[id]/index.ts +29 -10
  59. package/app/src/pages/dashboard/(cms)/network/users/index.ts +8 -7
  60. package/app/src/pages/dashboard/(cms)/network/users/new/index.ts +2 -1
  61. package/app/src/pages/dashboard/(cms)/registrations/index.ts +5 -4
  62. package/app/src/pages/dashboard/(cms)/tools/health/index.ts +4 -1
  63. package/app/src/pages/dashboard/(cms)/tools/replace/index.ts +2 -1
  64. package/app/src/pages/dashboard/(cms)/tools/seo/index.ts +1 -1
  65. package/app/src/pages/dashboard/index.ts +3 -2
  66. package/app/src/pages/dashboard/roles/index.ts +2 -2
  67. package/app/src/pages/dashboard/users/registrations/index.ts +66 -0
  68. package/app/src/services/api-tokens.ts +86 -0
  69. package/app/src/services/rbac.ts +26 -15
  70. package/app/src/services/roles.ts +125 -35
  71. package/app/src/services/security.ts +384 -0
  72. package/app/src/services/tenants.ts +447 -0
  73. package/app/src/services/users.ts +241 -97
  74. package/app/src/tenants.ts +219 -0
  75. package/package.json +48 -12
  76. package/src/block-references.ts +3 -3
  77. package/src/collections.ts +3 -1
  78. package/src/forms.ts +4 -2
  79. package/src/hooks.ts +19 -1
  80. package/src/index.ts +4 -4
  81. package/src/isolate-core.ts +1 -1
  82. package/src/isolation.ts +1 -0
  83. package/src/manifest.ts +43 -2
  84. package/src/permissions.ts +13 -7
  85. package/src/resource.ts +85 -2
  86. package/src/server/attempts.ts +64 -0
  87. package/src/server/automations.ts +2 -2
  88. package/src/server/batch.ts +106 -0
  89. package/src/server/budget.ts +17 -0
  90. package/src/server/field-values.ts +207 -0
  91. package/src/server/forms.ts +3 -3
  92. package/src/server/host-schema.ts +55 -7
  93. package/src/server/host.ts +213 -85
  94. package/src/server/index.ts +9 -14
  95. package/src/server/isolation.ts +10 -0
  96. package/src/server/network.ts +129 -44
  97. package/src/server/outbox.ts +2 -2
  98. package/src/server/people.ts +191 -0
  99. package/src/server/reconcile.ts +5 -5
  100. package/src/server/repository.ts +243 -84
  101. package/src/server/shared-read.ts +34 -0
  102. package/src/server/site-export.ts +23 -13
  103. package/src/server/site-import.ts +12 -33
  104. package/src/server/site-settings.ts +9 -3
  105. package/src/server/sites.ts +117 -187
  106. package/src/server/stores.ts +3 -300
  107. package/src/server/taxonomies.ts +64 -13
  108. package/src/server/users.ts +151 -498
  109. package/src/settings-controls.ts +8 -4
  110. package/src/settings.ts +26 -3
  111. package/src/storage/cloudflare.ts +2 -0
  112. package/src/storage/index.ts +6 -0
  113. package/src/theme.ts +2 -2
  114. package/src/version.ts +1 -1
  115. package/app/src/cms/handoff.ts +0 -202
  116. package/src/server/accounts.ts +0 -418
  117. package/src/server/api-tokens.ts +0 -91
  118. package/src/server/auth.ts +0 -89
  119. package/src/server/handoffs.ts +0 -107
  120. package/src/server/security.ts +0 -391
@@ -5,7 +5,7 @@
5
5
  */
6
6
  import {
7
7
  ENTRY_VIEW_REFUSED_BLOCKS, siteEntryView, validateBlocks, type EntryViewParts,
8
- ANONYMOUS, ARTICLE_TYPES, withContentFields, authorUrl, entryAuthors, blockDocuments, SHARE_BRAND_URLS, blockIsData, blocksPlain, editedSize, fieldGroupDeclarations, hasBlockReference, parseBlockText, PATTERN_REFERENCE, resolveBindings, resolveBlockBindings, siteBindingScope, textBlocks, usesUserBinding, type BindingScopes, type ParsedText, flattenBlocks, escapeHtml, formatSiteDate, formInputs, formSettings, imageSrcset, imageUrl, imageWidths, IMAGE_WIDTHS, isCmsError, languageFlag, languageName, mediaUrl, notificationRules, recordTitle, resolvePresets, richTextBlocks, richTextParts, richTextPlain, systemPrincipal, templateCandidates, transformable, urlList,
8
+ ANONYMOUS, ARTICLE_TYPES, slugify, withContentFields, authorUrl, entryAuthors, blockDocuments, SHARE_BRAND_URLS, blockIsData, blocksPlain, editedSize, fieldGroupDeclarations, hasBlockReference, parseBlockText, PATTERN_REFERENCE, resolveBindings, resolveBlockBindings, siteBindingScope, textBlocks, usesUserBinding, type BindingScopes, type ParsedText, flattenBlocks, escapeHtml, formatSiteDate, formInputs, formSettings, imageSrcset, imageUrl, imageWidths, IMAGE_WIDTHS, isCmsError, languageFlag, languageName, mediaUrl, notificationRules, recordTitle, resolvePresets, richTextBlocks, richTextParts, richTextPlain, systemPrincipal, templateCandidates, transformable, urlList,
9
9
  type AuthorView, type Block,
10
10
  type Principal, type TemplatePage, type ThemeData, type ThemePresets,
11
11
  type ArchiveView, type BodyPart, type BrandIcon, type CollectionDefinition, type CommentShape, type CommentView, type CommentsView, type EntryReference, type EntryView, type FieldDeclaration, type FieldFilter,
@@ -547,23 +547,34 @@ function docMediaIds(cms: CmsHost, doc: RichTextDoc, into: Set<string>): void {
547
547
  }
548
548
  }
549
549
 
550
- /** Synced patterns the blocks and documents use, by ID: their blocks. Patterns inside patterns are not expanded. */
550
+ /**
551
+ * Synced patterns the blocks and documents use: their blocks, by ID, and by the name a
552
+ * `{{ pattern … /}}` gave. Patterns have no slug field, so that name is a pattern's ID or the
553
+ * slug of its title. Patterns inside patterns are not expanded.
554
+ */
551
555
  async function usedPatterns(cms: CmsHost, docs: readonly RichTextDoc[], blocks: readonly Block[] = []): Promise<Map<string, Block[]>> {
552
556
  const all = [...docs.flatMap(doc => richTextBlocks(doc)), ...flattenBlocks(blocks)];
553
557
  const ids = [...new Set(all.filter(block => block.type === 'core/pattern').map(block => String(block.data.pattern ?? '')))].filter(Boolean);
554
- // `{{ pattern hero /}}` in text names a pattern by its slug.
555
- const slugs = [...new Set(all.flatMap(block => referencedBlocks(cms, block as { type: string; data: Record<string, unknown> })).filter(block => block.type === PATTERN_REFERENCE).map(block => String(block.data.pattern ?? '')))].filter(Boolean).slice(0, 50);
556
- if (!ids.length && !slugs.length) return new Map();
557
- try {
558
- const repository = cms.resource('cms/patterns');
559
- const patterns = ids.length ? await repository.getMany(ids, renderer) : new Map<string, RecordShape>();
560
- const named = slugs.length ? (await repository.list({ where: { slug: { in: slugs } }, limit: 50 }, renderer)).records : [];
561
- return new Map([...[...patterns].flatMap(([id, record]) => Array.isArray(record.content) ? [[id, record.content as Block[]] as const] : []),
562
- ...named.flatMap(record => Array.isArray(record.content) && typeof record.slug === 'string' ? [[record.slug, record.content as Block[]] as const] : [])]);
563
- } catch (error) {
564
- if (isCmsError(error)) return new Map();
565
- throw error;
566
- }
558
+ const names = [...new Set(all.flatMap(block => referencedBlocks(cms, block as { type: string; data: Record<string, unknown> })).filter(block => block.type === PATTERN_REFERENCE).map(block => String(block.data.pattern ?? '')))].filter(Boolean).slice(0, 50);
559
+ if (!ids.length && !names.length) return new Map();
560
+ const repository = cms.resource('cms/patterns');
561
+ const found = new Map<string, Block[]>();
562
+ const keep = (key: string, record: RecordShape) => { if (Array.isArray(record.content)) found.set(key, record.content as Block[]); };
563
+ const guarded = async (read: () => Promise<void>) => {
564
+ try { await read(); } catch (error) { if (!isCmsError(error)) throw error; }
565
+ };
566
+ await guarded(async () => {
567
+ for (const [id, record] of await repository.getMany([...new Set([...ids, ...names])], renderer)) keep(id, record);
568
+ });
569
+ const unnamed = names.filter(name => !found.has(name));
570
+ if (unnamed.length) await guarded(async () => {
571
+ const { records } = await repository.list({ limit: 100 }, renderer);
572
+ for (const record of records) {
573
+ const name = typeof record.title === 'string' ? slugify(record.title) : '';
574
+ if (unnamed.includes(name) && !found.has(name)) keep(name, record);
575
+ }
576
+ });
577
+ return found;
567
578
  }
568
579
 
569
580
  /**
@@ -702,10 +713,10 @@ export function entryLock(record: RecordShape, reader: EntryReader): 'password'
702
713
  * Search results a signed-in dashboard user may see: a locked entry (`entryLock`) that matched
703
714
  * would tell what its content says, so only entries open to them stay, as the content API's search.
704
715
  */
705
- export function openMatches(cms: CmsHost, resourceId: string, records: readonly RecordShape[], principal: Principal): RecordShape[] {
706
- const repository = cms.resource(resourceId);
716
+ export async function openMatches(cms: CmsHost, resourceId: string, records: readonly RecordShape[], principal: Principal): Promise<RecordShape[]> {
707
717
  const signedIn = principal.kind === 'user';
708
- return records.filter(record => !entryLock(record, { editor: signedIn && repository.canUpdate(record, principal), signedIn, roles: signedIn ? principal.roles : [] }));
718
+ const editable = signedIn ? await cms.resource(resourceId).editable(records, { principal }) : new Set<string>();
719
+ return records.filter(record => !entryLock(record, { editor: editable.has(record.id), signedIn, roles: signedIn ? principal.roles : [] }));
709
720
  }
710
721
 
711
722
  /**
@@ -713,7 +724,7 @@ export function openMatches(cms: CmsHost, resourceId: string, records: readonly
713
724
  * entry's unlock cookie, as the entry's page decides: for the comments API and form.
714
725
  */
715
726
  export async function requestLock(cms: CmsHost, record: RecordShape, resourceId: string, principal: Principal, cookie: string | undefined): Promise<'password' | 'members' | null> {
716
- const editor = principal.kind === 'user' && cms.resource(resourceId).canUpdate(record, principal);
727
+ const editor = principal.kind === 'user' && await cms.resource(resourceId).canUpdate(record, { principal });
717
728
  const unlocked = isProtected(record) && cookie !== undefined && cookie === await unlockToken(record);
718
729
  return entryLock(record, { signedIn: principal.kind === 'user', roles: principal.kind === 'user' ? principal.roles : [], editor, unlocked: unlocked ? new Set([record.id]) : undefined });
719
730
  }
@@ -0,0 +1,182 @@
1
+ // The network's registry of sites on the dashboard package's tenants: a site is a tenant
2
+ // whose ID and slug are the site's ID, with its domains in `tenant_domains` and its members
3
+ // in `tenant_members`. The CMS library's `CmsNetwork` reads and writes sites through this
4
+ // (`SitesStore`); the creation step of a site that is still being made is a network setting.
5
+ //
6
+ // Every call runs against the main database, whichever site the request is for.
7
+ import { In } from '@cossackframework/database';
8
+ import { CmsError, MAIN_SITE, siteHost, type SiteDomain, type SiteRecord, type SitesStore, type SiteStatus } from '@cossackframework/cms/server';
9
+ import { accounts, asMainAccount, forgetTenantHosts } from '#app/tenants';
10
+ import { Tenant } from '@/models/Tenant';
11
+ import { TenantDomain } from '@/models/TenantDomain';
12
+ import { TenantMember } from '@/models/TenantMember';
13
+ import { TenantNetwork } from '@/models/TenantNetwork';
14
+ import { TenantSession } from '@/models/TenantSession';
15
+
16
+ const ID = /^[a-z0-9][a-z0-9-]{0,62}$/;
17
+ const DATABASE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
18
+ const RESERVED = new Set([MAIN_SITE, 'new']);
19
+ const STATUSES: readonly SiteStatus[] = ['creating', 'active', 'archived', 'deleted'];
20
+ const stepKey = (id: string) => `site.step:${id}`;
21
+
22
+ const main = <T>(work: () => Promise<T>): Promise<T> => asMainAccount(() => accounts(work));
23
+
24
+ function checkName(name: string): void {
25
+ if (typeof name !== 'string' || !name.trim() || name.length > 120) throw new CmsError('CMS_VALIDATION', 'Enter a site name of at most 120 characters.', { fields: { name: 'is required.' } });
26
+ }
27
+
28
+ async function records(tenants: readonly Tenant[]): Promise<SiteRecord[]> {
29
+ if (!tenants.length) return [];
30
+ const ids = tenants.map(tenant => tenant.id);
31
+ const [domains, steps] = await Promise.all([
32
+ TenantDomain.find({ where: { tenantId: In(ids) }, take: 5000 }),
33
+ TenantNetwork.find({ where: { key: In(ids.map(stepKey)) }, take: 5000 }),
34
+ ]);
35
+ const step = new Map(steps.map(row => [row.key, row.value]));
36
+ return tenants.map(tenant => Object.freeze({
37
+ id: tenant.id, name: tenant.name, database: tenant.database, status: tenant.status as SiteStatus,
38
+ step: tenant.status === 'creating' ? step.get(stepKey(tenant.id)) ?? null : null,
39
+ domains: Object.freeze(domains.filter(domain => domain.tenantId === tenant.id)
40
+ .map((domain): SiteDomain => Object.freeze({ host: domain.host, primary: domain.isPrimary, verifiedAt: domain.verifiedAt ? domain.verifiedAt.getTime() : null }))
41
+ .sort((a, b) => Number(b.primary) - Number(a.primary) || (a.host < b.host ? -1 : 1))),
42
+ createdAt: tenant.createdAt.getTime(), updatedAt: tenant.createdAt.getTime(),
43
+ deletedAt: tenant.deletedAt ? tenant.deletedAt.getTime() : null,
44
+ }));
45
+ }
46
+
47
+ export const tenantSites: SitesStore = {
48
+ count: () => main(() => Tenant.count()),
49
+
50
+ async get(id) {
51
+ if (!ID.test(id) || id === MAIN_SITE) return null;
52
+ return main(async () => (await records(await Tenant.find({ where: { id } })))[0] ?? null);
53
+ },
54
+
55
+ async getMany(ids) {
56
+ const wanted = [...new Set(ids.filter(id => ID.test(id) && id !== MAIN_SITE))];
57
+ if (!wanted.length) return [];
58
+ return main(async () => {
59
+ const found = new Map((await records(await Tenant.find({ where: { id: In(wanted) } }))).map(record => [record.id, record]));
60
+ return wanted.map(id => found.get(id)).filter((record): record is SiteRecord => record !== undefined);
61
+ });
62
+ },
63
+
64
+ async list(options = {}) {
65
+ return main(async () => {
66
+ const search = options.search?.trim().toLowerCase().slice(0, 100);
67
+ const all = await records(await Tenant.find({ ...(options.status ? { where: { status: options.status } } : {}), order: { createdAt: 'desc' }, take: 2000 }));
68
+ const matching = search ? all.filter(record => record.name.toLowerCase().includes(search) || record.domains.some(domain => domain.host.includes(search))) : all;
69
+ const offset = Math.max(options.offset ?? 0, 0);
70
+ return { items: matching.slice(offset, offset + Math.min(Math.max(options.limit ?? 20, 1), 100)), total: matching.length };
71
+ });
72
+ },
73
+
74
+ async inTurn(after, limit = 50) {
75
+ return main(async () => {
76
+ const live = (await Tenant.find({ where: { status: In(['active', 'archived']) }, order: { id: 'asc' }, take: 5000 }));
77
+ const turn = [...live.filter(tenant => tenant.id > after), ...live.filter(tenant => tenant.id <= after)];
78
+ return records(turn.slice(0, Math.min(Math.max(limit, 1), 200)));
79
+ });
80
+ },
81
+
82
+ async siteOf(host) {
83
+ const name = siteHost(host);
84
+ if (!name) return null;
85
+ return main(async () => {
86
+ const domain = await TenantDomain.findOne({ where: { host: name } });
87
+ return domain ? { site: domain.tenantId, domain: Object.freeze({ host: domain.host, primary: domain.isPrimary, verifiedAt: domain.verifiedAt ? domain.verifiedAt.getTime() : null }) } : null;
88
+ });
89
+ },
90
+
91
+ async create(input) {
92
+ if (!ID.test(input.id) || RESERVED.has(input.id)) throw new CmsError('CMS_VALIDATION', 'Site IDs are lowercase letters, digits and hyphens, other than main and new.', { fields: { id: 'is invalid.' } });
93
+ if (!DATABASE.test(input.database)) throw new CmsError('CMS_VALIDATION', 'Invalid database ID.');
94
+ checkName(input.name);
95
+ const status = input.status ?? 'active';
96
+ if (!STATUSES.includes(status)) throw new CmsError('CMS_VALIDATION', 'Unknown site status.');
97
+ const hosts = input.domains.map(domain => siteHost(domain.host));
98
+ if (!hosts.length || hosts.length > 20 || hosts.some(host => !host) || new Set(hosts).size !== hosts.length) throw new CmsError('CMS_VALIDATION', 'Enter each domain once, as a host name such as blog.example.com.', { fields: { domains: 'are invalid.' } });
99
+ const primary = Math.max(input.domains.findIndex(domain => domain.primary), 0);
100
+ return main(async () => {
101
+ if (await Tenant.exists({ id: input.id })) throw new CmsError('CMS_CONFLICT', 'A site with this ID exists.', { fields: { id: 'is taken.' } });
102
+ if (await Tenant.exists({ database: input.database })) throw new CmsError('CMS_CONFLICT', 'Another site uses this database.');
103
+ if (await TenantDomain.exists({ host: In(hosts) })) throw new CmsError('CMS_CONFLICT', 'Another site answers on this domain.', { fields: { host: 'is taken.' } });
104
+ const now = new Date();
105
+ await Tenant.insert({ id: input.id, slug: input.id, name: input.name.trim(), database: input.database, status, deletedAt: null, createdAt: now });
106
+ await TenantDomain.insert(input.domains.map((domain, index) => ({ host: hosts[index]!, tenantId: input.id, isPrimary: index === primary, verifiedAt: domain.verifiedAt ? new Date(domain.verifiedAt) : null, createdAt: now })));
107
+ if (input.step) await TenantNetwork.upsert({ key: stepKey(input.id), value: input.step, updatedAt: now }, ['key']);
108
+ forgetTenantHosts();
109
+ return (await records(await Tenant.find({ where: { id: input.id } })))[0]!;
110
+ });
111
+ },
112
+
113
+ async update(id, patch) {
114
+ return main(async () => {
115
+ const current = await Tenant.findOne({ where: { id } });
116
+ if (!current) return null;
117
+ if (patch.name !== undefined) checkName(patch.name);
118
+ if (patch.database !== undefined && !DATABASE.test(patch.database)) throw new CmsError('CMS_VALIDATION', 'Invalid database ID.');
119
+ const status = patch.status ?? (current.status as SiteStatus);
120
+ if (!STATUSES.includes(status)) throw new CmsError('CMS_VALIDATION', 'Unknown site status.');
121
+ await Tenant.update({ id }, { name: (patch.name ?? current.name).trim(), database: patch.database ?? current.database, status,
122
+ deletedAt: status === 'deleted' ? current.deletedAt ?? new Date() : null });
123
+ if (patch.step !== undefined) {
124
+ if (patch.step === null) await TenantNetwork.delete({ key: stepKey(id) });
125
+ else await TenantNetwork.upsert({ key: stepKey(id), value: patch.step, updatedAt: new Date() }, ['key']);
126
+ }
127
+ forgetTenantHosts();
128
+ return (await records(await Tenant.find({ where: { id } })))[0] ?? null;
129
+ });
130
+ },
131
+
132
+ async addDomain(id, host) {
133
+ const name = siteHost(host);
134
+ if (!name) throw new CmsError('CMS_VALIDATION', 'Enter a host name, such as blog.example.com.', { fields: { host: 'is invalid.' } });
135
+ return main(async () => {
136
+ if (id !== MAIN_SITE && !await Tenant.exists({ id })) return null;
137
+ if (await TenantDomain.exists({ host: name })) throw new CmsError('CMS_CONFLICT', 'Another site answers on this domain.', { fields: { host: 'is taken.' } });
138
+ await TenantDomain.insert({ host: name, tenantId: id, isPrimary: false, verifiedAt: null, createdAt: new Date() });
139
+ forgetTenantHosts();
140
+ return id === MAIN_SITE ? null : (await records(await Tenant.find({ where: { id } })))[0] ?? null;
141
+ });
142
+ },
143
+
144
+ async verifyDomain(id, host, options = {}) {
145
+ const name = siteHost(host);
146
+ return main(async () => {
147
+ const result = await TenantDomain.update({ host: name, tenantId: id }, { verifiedAt: new Date() });
148
+ if (result.meta.rowsAffected !== 1) return false;
149
+ if (options.primary) {
150
+ await TenantDomain.update({ tenantId: id }, { isPrimary: false });
151
+ await TenantDomain.update({ host: name, tenantId: id }, { isPrimary: true });
152
+ }
153
+ forgetTenantHosts();
154
+ return true;
155
+ });
156
+ },
157
+
158
+ async removeDomain(id, host) {
159
+ return main(async () => {
160
+ const result = await TenantDomain.delete({ host: siteHost(host), tenantId: id, isPrimary: false });
161
+ forgetTenantHosts();
162
+ return result.meta.rowsAffected === 1;
163
+ });
164
+ },
165
+
166
+ async deletedBefore(at, limit = 20) {
167
+ return main(async () => records((await Tenant.find({ where: { status: 'deleted' }, take: 2000 }))
168
+ .filter(tenant => tenant.deletedAt && tenant.deletedAt.getTime() < at)
169
+ .sort((a, b) => a.deletedAt!.getTime() - b.deletedAt!.getTime()).slice(0, limit)));
170
+ },
171
+
172
+ async remove(id) {
173
+ await main(async () => {
174
+ await TenantDomain.delete({ tenantId: id });
175
+ await TenantMember.delete({ tenantId: id });
176
+ await TenantSession.delete({ tenantId: id });
177
+ await TenantNetwork.delete({ key: stepKey(id) });
178
+ await Tenant.delete({ id });
179
+ forgetTenantHosts();
180
+ });
181
+ },
182
+ };
@@ -1,3 +1,4 @@
1
+ import { registrations } from '#app/auth';
1
2
  import type { Context } from 'hono';
2
3
  import { ANONYMOUS, applyDashboardMenu, dashboardLinkModuleId, dashboardMenuOf, dashboardNotices as noticesPoint, dashboardNoticesOf, dashboardTaskbar, EMPTY_DASHBOARD_MENU, evaluateRule, hasPermission, isCmsError, isNetworkAdmin, PERMISSIONS, recordTitle, taskbarItemsOf, type DashboardNotice, type Principal, type WriteActor } from '@cossackframework/cms';
3
4
  import { MAIN_SITE, type CmsHost } from '@cossackframework/cms/server';
@@ -51,7 +52,7 @@ export function waitingRegistrations(c: Context): Promise<number> {
51
52
  return remember(c, 'counts.registrations', async () => {
52
53
  const cms = c.get('cms') as CmsHost;
53
54
  const principal: Principal = c.get('principal') ?? ANONYMOUS;
54
- return hasPermission(principal, PERMISSIONS.manageUsers) ? cms.users.registrationCount().catch(() => 0) : 0;
55
+ return hasPermission(principal, PERMISSIONS.manageUsers) ? registrations().then(waiting => waiting.length, () => 0) : 0;
55
56
  });
56
57
  }
57
58
 
@@ -329,7 +330,7 @@ export async function dashboardFind(c: Context, text: string): Promise<{ id: str
329
330
  const found = await Promise.all(searched.map(async collection => {
330
331
  const resource = cms.resourceById(`cms/${collection.name}`);
331
332
  try {
332
- const records = openMatches(cms, resource.id, await cms.resource(resource.id).search(text, { limit: 5 }, { principal }), principal);
333
+ const records = await openMatches(cms, resource.id, await cms.resource(resource.id).search(text, { limit: 5 }, { principal }), principal);
333
334
  return records.map(record => {
334
335
  const href = `/dashboard/content/${collection.name}/${record.id}`;
335
336
  return { id: href, label: recordTitle(record, resource.titleField), group: collection.label, href };
@@ -12,6 +12,7 @@ const descriptor: DashboardModule = {
12
12
  children: [
13
13
  { label: 'All users', href: '/dashboard/users' },
14
14
  { label: 'Add user', href: '/dashboard/users/new' },
15
+ { label: 'Registrations', href: '/dashboard/users/registrations' },
15
16
  ],
16
17
  };
17
18
 
@@ -82,3 +82,27 @@ const LABELS: Record<string, string> = {
82
82
  export function permissionLabel(permission: string): string {
83
83
  return LABELS[permission] ?? permission;
84
84
  }
85
+
86
+ /**
87
+ * Permission patterns: `*` matches everything, `cms/*` every permission starting with `cms/`,
88
+ * and `cms/posts:*` every action on one resource. The same rule as the CMS's own `permissionMatches`.
89
+ */
90
+ export function permissionMatches(pattern: string, permission: string): boolean {
91
+ if (pattern === '*' || pattern === permission) return true;
92
+ return pattern.endsWith('*') && permission.startsWith(pattern.slice(0, -1));
93
+ }
94
+
95
+ /** Whether one of the held patterns gives the permission. */
96
+ export function holds(held: readonly string[], permission: string): boolean {
97
+ return held.some(pattern => permissionMatches(pattern, permission));
98
+ }
99
+
100
+ /** Whether the held patterns give every one of the permissions, each as written. */
101
+ export function holdsAll(held: readonly string[], permissions: readonly string[]): boolean {
102
+ return permissions.every(permission => holds(held, permission));
103
+ }
104
+
105
+ /** A permission a role may hold: any pattern of lowercase names, as plugins add their own. */
106
+ export function validPermission(permission: string): boolean {
107
+ return /^(?:\*|[a-z][a-z0-9:/._*-]{0,127})$/.test(permission);
108
+ }
@@ -0,0 +1,6 @@
1
+ // src/lib/uuid.ts
2
+ //
3
+ // UUIDv7 for every row id: time-sortable, which keeps indexes compact. It comes from the
4
+ // framework core, the same generator the CMS uses. Never use one as a secret; its time is
5
+ // readable. Tokens take crypto.getRandomValues().
6
+ export { uuidv7 } from '@cossackframework/core';
@@ -0,0 +1,15 @@
1
+ // The sender of the account emails, for the shared sign-in code (auth.ts): the site's mailer,
2
+ // so they go through `cms.mail.before-send`, the site's sender and, in development, the mail kept
3
+ // for `GET /api/cms/dev/mail`.
4
+ import { currentCms } from './cms/index';
5
+
6
+ export interface Mail { to: string; subject: string; text: string; kind?: 'verification' | 'reset' | 'magic-link' | 'invitation' | 'other' }
7
+
8
+ /** The site's mailer, or null when the site has no email sender. */
9
+ export function mailer(): { send(mail: Mail): Promise<void> } | null {
10
+ let cms;
11
+ try { cms = currentCms(); } catch { return null; }
12
+ const mail = cms.mail;
13
+ if (!mail) return null;
14
+ return { async send(message) { await mail.send({ ...(message.kind ? { kind: message.kind } : {}), to: message.to, from: cms.mailFrom, subject: message.subject, text: message.text }); } };
15
+ }
@@ -64,7 +64,9 @@ export const requireDashboardUser = defineServerMiddleware(async (c, next) => {
64
64
  * static assets) is reachable without a session.
65
65
  *
66
66
  * The OAuth routes (/auth/<provider>/redirect and /callback) are exempt from the
67
- * guest check: a signed-in user would otherwise be bounced away mid-flow.
67
+ * guest check: a signed-in user would otherwise be bounced away mid-flow. So is the
68
+ * CMS network's /auth/register-site, where a signed-in person registers a site for
69
+ * their own account.
68
70
  *
69
71
  * A page of something the project turned off (src/dashboard.config.ts) answers 404:
70
72
  * the password pages without `credentials`, a dashboard module that is not chosen,
@@ -72,6 +74,8 @@ export const requireDashboardUser = defineServerMiddleware(async (c, next) => {
72
74
  */
73
75
  const PASSWORD_PAGES = /^\/auth\/(?:register|forgot-password|reset-password|two-factor)(?:\/|$)/;
74
76
  const OAUTH_ROUTE = /^\/auth\/[^/]+\/(?:redirect|callback)$/;
77
+ /** Sign-in pages that also serve people who are signed in. */
78
+ const SIGNED_IN_PAGES = /^\/auth\/register-site\/?$/;
75
79
  /** The dashboard pages of each module. */
76
80
  const MODULE_PAGES: Record<string, RegExp> = {
77
81
  users: /^\/dashboard\/users(?:\/|$)/,
@@ -92,7 +96,7 @@ export const authGuard = defineServerMiddleware(async (c, next) => {
92
96
  const user = c.get('user');
93
97
 
94
98
  if (turnedOff(path)) return c.notFound();
95
- if (path.startsWith('/auth/') && user && !OAUTH_ROUTE.test(path)) {
99
+ if (path.startsWith('/auth/') && user && !OAUTH_ROUTE.test(path) && !SIGNED_IN_PAGES.test(path)) {
96
100
  return c.redirect(config('auth.redirectAfterLogin'));
97
101
  }
98
102
  // A fresh site creates its first administrator on the setup page.
@@ -0,0 +1,108 @@
1
+ import type { Context } from 'hono';
2
+ import { tenantORM } from '@/orm/factory';
3
+ import { defineServerMiddleware } from '@cossackframework/core';
4
+ import type { ORM } from '@cossackframework/database';
5
+ import { getCookie, deleteCookie, setCookie } from 'hono/cookie';
6
+ import { hostName, mainHost, markTenantRequest, sharedSignIn, tenantClaimingHost, tenantOfHost, tenantsEnabled, tenantsRunning, type TenantInfo } from '../tenants';
7
+ import { returnPath } from '../auth-input';
8
+ import { SESSION_COOKIE_NAME } from '../auth';
9
+
10
+ /**
11
+ * With tenants on: find the tenant of the request's host and run the request in that tenant's
12
+ * database. It goes after the ORM middleware (which opened the main database's scope) and
13
+ * before the session, so sign-in sees which tenant the request is for.
14
+ *
15
+ * The main host, and every host while APP_URL is not set, is the main tenant: nothing changes.
16
+ * An unknown host answers 404, an archived tenant 503.
17
+ */
18
+ // The cookies of shared sign-in; the endpoints under src/pages/auth/tenant read them.
19
+ const TENANT_STATE = 'tenant_state';
20
+ const TENANT_RETURN = 'tenant_return';
21
+ const TENANT_AUTO = 'tenant_auto';
22
+ const WELL_KNOWN = '/.well-known/cossack-tenant';
23
+ const TENANTS_SCREEN = /^\/dashboard\/tenants(?:\/|$)/;
24
+
25
+ export const tenantMiddleware = defineServerMiddleware(async (c, next) => {
26
+ // The Tenants screen exists on the main host, while tenants are on.
27
+ const screen = TENANTS_SCREEN.test(c.req.path);
28
+ if (!tenantsEnabled) return screen ? c.notFound() : next();
29
+ const main = mainHost();
30
+ const host = hostName(c.req.url);
31
+ if (!main || !host || host === main) {
32
+ return sharedSignInOnMainHost(c) ?? next();
33
+ }
34
+ if (screen) return c.notFound();
35
+ // A domain proves it points here by answering with the ID of the tenant that asked for it.
36
+ if (c.req.path === WELL_KNOWN) {
37
+ const claimed = await tenantClaimingHost(host);
38
+ return claimed ? c.text(claimed) : c.notFound();
39
+ }
40
+ // While the network is off, only the main host answers.
41
+ if (!await tenantsRunning()) return c.notFound();
42
+ const tenant = await tenantOfHost(host, main);
43
+ if (!tenant || tenant.status === 'creating' || tenant.status === 'deleted') return c.notFound();
44
+ // The tenant's other hosts lead to its primary domain.
45
+ if (tenant.primaryHost && host !== tenant.primaryHost && (c.req.method === 'GET' || c.req.method === 'HEAD')) {
46
+ const url = new URL(c.req.url);
47
+ url.hostname = tenant.primaryHost;
48
+ return c.redirect(url.toString(), 301);
49
+ }
50
+ if (tenant.status === 'archived') return c.text('This site is archived.', 503);
51
+ // Shared sign-in. The tenant's sign-in page is for its own accounts; people with a main
52
+ // account sign in on the main host, which sends them back with a one-time code. A visitor
53
+ // goes there once on their own: signed in already, they arrive signed in; if not, they come
54
+ // back to this page, whose link ("/auth/tenant/start") takes them to the main host's sign-in.
55
+ const routed = sharedSignInOnTenantHost(c, host, main);
56
+ if (routed) return routed;
57
+ return inTenantDatabase(c, tenant, () => next());
58
+ });
59
+
60
+ /**
61
+ * Shared sign-in, on the main host: a visitor a tenant's host sent here has signed in, and now
62
+ * goes back with a code. Null when the request is not that.
63
+ */
64
+ export function sharedSignInOnMainHost(c: Context): Response | null {
65
+ const waiting = sharedSignIn && c.req.method === 'GET' && !c.req.path.startsWith('/auth/') ? getCookie(c, TENANT_RETURN) : undefined;
66
+ if (!waiting || !getCookie(c, SESSION_COOKIE_NAME) || c.req.header('sec-fetch-dest') === 'empty') return null;
67
+ deleteCookie(c, TENANT_RETURN, { path: '/' });
68
+ return c.redirect(`/auth/tenant/redirect?${waiting}`);
69
+ }
70
+
71
+ /**
72
+ * Shared sign-in, on a tenant's host. Its sign-in page is for its own accounts; people with a
73
+ * main account sign in on the main host, which sends them back with a one-time code. A visitor
74
+ * who opens the dashboard without a session here goes to the main host once on their own:
75
+ * signed in there already, they arrive signed in; if not, they come back to the tenant's
76
+ * sign-in page, whose link ("/auth/tenant/start") takes them to the main host's sign-in.
77
+ * Null when the request is neither.
78
+ */
79
+ export function sharedSignInOnTenantHost(c: Context, host: string, main: string): Response | null {
80
+ const start = c.req.path === '/auth/tenant/start';
81
+ const first = /^\/dashboard(?:\/|$)/.test(c.req.path) && !getCookie(c, TENANT_AUTO) && !getCookie(c, SESSION_COOKIE_NAME) && c.req.header('sec-fetch-dest') !== 'empty';
82
+ if (!sharedSignIn || c.req.method !== 'GET' || !(start || first)) return null;
83
+ const url = new URL(c.req.url);
84
+ const secure = url.protocol === 'https:';
85
+ const state = crypto.randomUUID().replaceAll('-', '');
86
+ setCookie(c, TENANT_STATE, state, { path: '/', httpOnly: true, sameSite: 'Lax', maxAge: 600, secure });
87
+ // Once in five minutes, so a visitor without a main session is not sent in circles.
88
+ setCookie(c, TENANT_AUTO, '1', { path: '/', httpOnly: true, sameSite: 'Lax', maxAge: 300, secure });
89
+ const back = returnPath(start ? c.req.query('next') : `${url.pathname}${url.search}`);
90
+ const query = new URLSearchParams({ host, state, ...(back ? { next: back } : {}), ...(start ? {} : { auto: '1' }) });
91
+ url.hostname = main;
92
+ url.pathname = '/auth/tenant/redirect';
93
+ url.search = query.toString();
94
+ return c.redirect(url.toString());
95
+ }
96
+
97
+ /** Run the rest of the request in a tenant's database: models and services reach it, and the request knows its tenant. */
98
+ export async function inTenantDatabase<T>(c: Context, tenant: TenantInfo, work: () => Promise<T>): Promise<T> {
99
+ const opened = await tenantORM(c.env, tenant);
100
+ try {
101
+ markTenantRequest(c, tenant, c.get('orm' as never) as ORM, opened.orm);
102
+ return await opened.orm.run(work);
103
+ } finally {
104
+ // A response that streams keeps the database until its body ends.
105
+ const lifetime = c.get('cossack:response-lifetime' as never) as { deferCleanup?(cleanup: () => Promise<void>): boolean } | undefined;
106
+ if (!lifetime?.deferCleanup?.(() => opened.release())) await opened.release();
107
+ }
108
+ }
@@ -205,7 +205,7 @@ export default class SitePath extends Cossack {
205
205
  shown = { collection: resolved.collection.name, record: resolved.record };
206
206
  // Editors read their protected and members-only entries; visitors unlock protected ones with the password, which a cookie remembers.
207
207
  const reader = this.c.get('principal');
208
- const editor = reader.kind === 'user' && cms.resource(`cms/${resolved.collection.name}`).canUpdate(resolved.record, reader);
208
+ const editor = reader.kind === 'user' && await cms.resource(`cms/${resolved.collection.name}`).canUpdate(resolved.record, { principal: reader });
209
209
  const unlocked = isProtected(resolved.record) && getCookie(this.c, unlockCookie(resolved.record)) === await unlockToken(resolved.record);
210
210
  const only = new Set([resolved.record.id]);
211
211
  this.locked = entryLock(resolved.record, { unlocked: unlocked ? only : undefined, signedIn: reader.kind === 'user', roles: viewOptions.roles, editor });
@@ -53,7 +53,7 @@ export default class PreviewPage extends Cossack {
53
53
  } else {
54
54
  const repository = cms.resource(resourceId);
55
55
  const saved = await repository.get(id, { principal });
56
- if (saved && repository.canUpdate(saved, principal)) {
56
+ if (saved && await repository.canUpdate(saved, { principal })) {
57
57
  record = stored = saved;
58
58
  this.editUrl = `/dashboard/content/${collection.name}/${id}`;
59
59
  // Unsaved changes from the editor show in place of the saved ones.
@@ -0,0 +1,19 @@
1
+ import type { Context } from 'hono';
2
+ import { clearDevMail, devMail, devMailOpen } from '#app/cms/dev-mail';
3
+
4
+ /**
5
+ * Development only, while APP_URL and the request's address name this machine:
6
+ * `GET /api/cms/dev/mail` lists the mail the sites sent, oldest first (`?to=` keeps one
7
+ * recipient's), so a script can follow an invitation's link. `DELETE` forgets it. Elsewhere
8
+ * both answer 404.
9
+ */
10
+ export const GET = (c: Context) => {
11
+ if (!devMailOpen(c, (c.env as { APP_URL?: string }).APP_URL)) return c.json({ error: 'Not found.', code: 'CMS_NOT_FOUND' }, 404);
12
+ return c.json({ mail: devMail(c.req.query('to')) }, 200, { 'cache-control': 'no-store' });
13
+ };
14
+
15
+ export const DELETE = (c: Context) => {
16
+ if (!devMailOpen(c, (c.env as { APP_URL?: string }).APP_URL)) return c.json({ error: 'Not found.', code: 'CMS_NOT_FOUND' }, 404);
17
+ clearDevMail();
18
+ return c.body(null, 204);
19
+ };
@@ -106,7 +106,7 @@ export const POST = async (c: Context) => {
106
106
  */
107
107
  const saveBack = async (page: string, result: FormResult) => {
108
108
  const bucket = result.kind === 'success' ? null : result.kind === 'error' ? 'form-error' : 'form-result';
109
- const allowed = bucket === null || await cms.security.attempt(bucket, ip ?? 'anonymous', RESULTS_PER_ADDRESS, RESULTS_WINDOW_MS).catch(() => false);
109
+ const allowed = bucket === null || await cms.attempts.attempt(bucket, ip ?? 'anonymous', RESULTS_PER_ADDRESS, RESULTS_WINDOW_MS).catch(() => false);
110
110
  const query = allowed ? `?form=${encodeURIComponent(loaded.ref.slug)}&result=${await cms.forms.saveResult(loaded.ref.id, result)}` : '';
111
111
  return c.redirect(`${page}${query}#form-${loaded.ref.slug}`, 303);
112
112
  };
@@ -1,3 +1,4 @@
1
+ import { userOfPrincipal } from '#app/cms/actor';
1
2
  import type { Context } from 'hono';
2
3
  import { hasPermission, PERMISSIONS } from '@cossackframework/cms';
3
4
  import { apiError, writeAllowed, writeBody } from '#app/cms/content-api';
@@ -12,7 +13,7 @@ function actorOf(c: Context): PublicUser | undefined {
12
13
  const user = c.get('user') as PublicUser | undefined;
13
14
  if (user) return user;
14
15
  const principal = c.get('principal') as Principal | undefined;
15
- return principal?.kind === 'user' ? { id: principal.id, email: '', name: '', avatar: null, meta: null, roles: [], principal } : undefined;
16
+ return principal?.kind === 'user' ? userOfPrincipal(principal) : undefined;
16
17
  }
17
18
 
18
19
  /**
@@ -19,7 +19,7 @@ const OAUTH_REFUSALS: Record<string, string> = {
19
19
  };
20
20
 
21
21
  /** Sign-in failures the visitor is told about, after the password matched or before it is checked; see auth.ts. */
22
- const TOLD = new Set(['SignInLockedError', 'SignInPendingError', 'SignInPasskeyError']);
22
+ const TOLD = new Set(['SignInLockedError', 'SignInPendingError', 'SignInPasskeyError', 'SignInMemberError']);
23
23
  import { usePasskey } from '#app/passkeys.client';
24
24
 
25
25
  interface LoginForm {
@@ -51,7 +51,7 @@ export default class MagicLinkPage extends Cossack {
51
51
  }
52
52
  const { headers } = await authSessions.create(userId, this.c);
53
53
  headers.forEach((value, key) => this.c.header(key, value));
54
- this.redirect('/dashboard');
54
+ this.redirect(config('auth.redirectAfterLogin'));
55
55
  }
56
56
 
57
57
  render() {
@@ -0,0 +1,20 @@
1
+ import type { Context } from 'hono';
2
+ import { recoverAccount } from '#app/auth';
3
+
4
+ /**
5
+ * Recovery mode: `POST /auth/recovery` with `Authorization: Bearer <RECOVERY_CODE>` and
6
+ * `{ "email": "…", "secondFactors"?: true }` answers `{ email, resetUrl, expiresAt,
7
+ * secondFactorsCleared }`. Off (403) while the environment has no RECOVERY_CODE.
8
+ */
9
+ export const POST = async (c: Context) => {
10
+ const code = /^Bearer\s+(.+)$/i.exec(c.req.header('authorization') ?? '')?.[1]?.trim();
11
+ const length = Number(c.req.header('content-length') ?? '0');
12
+ if (length > 4096) return c.json({ error: 'The request body is too large.' }, 413);
13
+ let body: { email?: unknown; secondFactors?: unknown };
14
+ try { body = await c.req.json(); } catch { return c.json({ error: 'Send a JSON body: { "email": "…" }.' }, 400); }
15
+ if (!body || typeof body !== 'object' || Array.isArray(body)) return c.json({ error: 'Send a JSON body: { "email": "…" }.' }, 400);
16
+ const result = await recoverAccount(code, body.email, body.secondFactors === true);
17
+ return 'error' in result
18
+ ? c.json({ error: result.error }, result.status, { 'cache-control': 'no-store' })
19
+ : c.json(result, 200, { 'cache-control': 'no-store' });
20
+ };