@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
@@ -0,0 +1,146 @@
1
+ import { Client, ClientStore, Cossack, isClientVisibleError, Page, Server, State } from '@cossackframework/core';
2
+ import { input, type InputOf } from '@cossackframework/core/input';
3
+ import { Alert, Button, Field, Input, PasswordInput, Turnstile } from '@cossackframework/ui';
4
+ import { html, component, bind } from '@cossackframework/renderer';
5
+ import { networkSite } from '@cossackframework/cms/server';
6
+ import { authSessions, logout, type PublicUser } from '#app/auth';
7
+ import { registerSite, siteRegistrationOpen } from '#app/cms/site-registration';
8
+ import { botCheckKey, passesBotCheck } from '#app/auth-bot-check';
9
+ import { BOT_CHECK_FAILED, botCheckToken } from '#app/auth-bot-token';
10
+ import { networkFor, siteUrl, type CmsBindings } from '#app/cms/index';
11
+
12
+ const registerSiteInput = input.object({
13
+ siteName: input.string({ required: true, maxLength: 120 }),
14
+ subdomain: input.string({ required: true, maxLength: 40 }),
15
+ name: input.string({ maxLength: 191 }),
16
+ email: input.string({ maxLength: 191 }),
17
+ password: input.string({ maxLength: 1024 }),
18
+ turnstile: input.string({ maxLength: 4096 }).optional(),
19
+ });
20
+ type RegisterSiteInput = InputOf<typeof registerSiteInput>;
21
+
22
+ interface RegisterSiteForm {
23
+ siteName: string;
24
+ subdomain: string;
25
+ name: string;
26
+ email: string;
27
+ password: string;
28
+ }
29
+
30
+ /**
31
+ * Register a site on the network host, while Settings → Network → People can register a site is
32
+ * on: the site's name and address, and the account that runs it. A new account confirms its
33
+ * email first, and the site is made when the link is opened; an existing account gives its
34
+ * password. A person who is signed in gives the site alone, for their own account. The person
35
+ * becomes the site's administrator and is taken there.
36
+ */
37
+ @Page({ transport: 'http' })
38
+ export default class RegisterSitePage extends Cossack {
39
+ @ClientStore() form: RegisterSiteForm = { siteName: '', subdomain: '', name: '', email: '', password: '' };
40
+ @State() closed = false;
41
+ /** The domain the address ends with, such as `example.com`. */
42
+ @State() suffix = '';
43
+ @State() sent = false;
44
+ @State() error = '';
45
+ /** The Turnstile site key while the bot check is on. */
46
+ @State() botKey: string | null = null;
47
+ /** The signed-in person's email: the site is theirs, and the form asks for no account. */
48
+ @State() signedInAs: string | null = null;
49
+
50
+ async init() {
51
+ this.closed = !(await siteRegistrationOpen());
52
+ this.botKey = botCheckKey();
53
+ this.signedInAs = (this.c.get('user') as PublicUser | undefined)?.email ?? null;
54
+ const network = networkFor(this.c.env as CmsBindings);
55
+ if (!this.closed) this.suffix = (await network.settings()).subdomainSuffix || network.subdomainSuffix || 'localhost';
56
+ }
57
+
58
+ @Client()
59
+ async submit(event: Event) {
60
+ event.preventDefault();
61
+ this.error = '';
62
+ await this.register({ ...this.form, turnstile: botCheckToken(event.target) });
63
+ }
64
+
65
+ @Server({ input: registerSiteInput })
66
+ async register(submitted: RegisterSiteInput) {
67
+ const values = await registerSiteInput.parse(submitted);
68
+ this.error = '';
69
+ if (!(await passesBotCheck(values.turnstile, 'register'))) { this.error = BOT_CHECK_FAILED; return; }
70
+ // The session names the account, never the form.
71
+ const user = (this.c.get('user') as PublicUser | undefined) ?? null;
72
+ if (!user && (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values.email.trim()) || values.password.length < 8)) {
73
+ this.error = 'Enter your email and a password of at least 8 characters.';
74
+ return;
75
+ }
76
+ try {
77
+ // The domain is the network's, whatever the browser sent.
78
+ const network = networkFor(this.c.env as CmsBindings);
79
+ const suffix = (await network.settings()).subdomainSuffix || network.subdomainSuffix || 'localhost';
80
+ const site = { name: values.siteName, host: `${values.subdomain.trim().toLowerCase()}.${suffix}` };
81
+ const result = await registerSite(user ? { site } : { site, name: values.name, email: values.email.trim(), password: values.password }, user?.id ?? null);
82
+ if (result.signIn) {
83
+ const { headers } = await authSessions.create(result.user, this.c);
84
+ headers.forEach((value, key) => this.c.header(key, value));
85
+ }
86
+ // Signed in here, the new site's link to the network signs its administrator in there.
87
+ const record = await network.sites.get(result.site);
88
+ const target = record ? siteUrl(this.c.env as CmsBindings, networkSite(record)) : undefined;
89
+ this.redirect(target ? `${target.replace(/\/+$/, '')}/auth/tenant/start?next=${encodeURIComponent('/dashboard')}` : '/dashboard');
90
+ } catch (error) {
91
+ this.error = isClientVisibleError(error) ? error.message : 'Could not register the site. Try again.';
92
+ }
93
+ }
94
+
95
+ /** Sign out, to register the site with another account. */
96
+ @Server()
97
+ async signOut() {
98
+ this.error = '';
99
+ try {
100
+ const { headers } = await logout(this.c);
101
+ headers.forEach((value, key) => this.c.header(key, value));
102
+ this.redirect('/auth/register-site');
103
+ } catch {
104
+ this.error = 'Could not sign out. Try again.';
105
+ }
106
+ }
107
+
108
+ render() {
109
+ if (this.closed) return html`
110
+ <h3 class="mb-3 text-xl font-semibold text-foreground">${__('Register a site')}</h3>
111
+ ${component(Alert, {}, __('Site registration is closed on this network.'))}
112
+ <p class="mt-6 text-center text-sm text-muted-foreground"><a href="/auth/login" class="text-primary font-medium hover:underline">${__('Sign in')}</a></p>`;
113
+ if (this.sent) return html`
114
+ <h3 class="mb-3 text-xl font-semibold text-foreground">${__('Check your email')}</h3>
115
+ ${component(Alert, {}, __('We sent you a link to confirm your email address. Open it to create your site; it works for two days.'))}
116
+ <p class="mt-6 text-center text-sm text-muted-foreground"><a href="/auth/login" class="text-primary font-medium hover:underline">${__('Back to sign in')}</a></p>`;
117
+ return html`
118
+ <h3 class="mb-6 text-xl font-semibold text-foreground">${__('Register a site')}</h3>
119
+ <form @submit=${(event: Event) => this.submit(event)} class="space-y-4" data-register-site>
120
+ ${component(Field, { label: __('Site name'), for: 'site-name',
121
+ control: attributes => component(Input, { ...attributes, type: 'text', required: true, maxlength: 120, '.value': bind(this.form, 'siteName') }) })}
122
+ ${component(Field, { label: __('Site address'), for: 'site-subdomain', hint: `${__('Lowercase letters, digits and hyphens.')} ${__('Your site will be at')} ${this.form.subdomain || 'name'}.${this.suffix}`,
123
+ control: attributes => html`<div class="flex items-center gap-2">
124
+ ${component(Input, { ...attributes, type: 'text', required: true, maxlength: 40, pattern: '[a-z0-9](?:[a-z0-9-]*[a-z0-9])?', autocapitalize: 'off', spellcheck: 'false', '.value': bind(this.form, 'subdomain') })}
125
+ <span class="shrink-0 text-sm text-muted-foreground">.${this.suffix}</span>
126
+ </div>` })}
127
+ ${this.signedInAs ? html`<p class="text-sm text-muted-foreground" data-signed-in-as>${__('Signed in as')} <span class="font-medium text-foreground">${this.signedInAs}</span>. ${__('The site will be yours.')}</p>` : html`
128
+ ${component(Field, { label: __('Your name'), for: 'name',
129
+ control: attributes => component(Input, { ...attributes, type: 'text', autocomplete: 'name', '.value': bind(this.form, 'name') }) })}
130
+ ${component(Field, { label: __('Email'), for: 'email',
131
+ control: attributes => component(Input, { ...attributes, type: 'email', autocomplete: 'username', spellcheck: 'false', required: true, '.value': bind(this.form, 'email') }) })}
132
+ ${component(Field, { label: __('Password'), for: 'password', hint: __('At least 8 characters. Have an account? Enter its email and password.'),
133
+ control: attributes => component(PasswordInput, { ...attributes, autocomplete: 'new-password', required: true, minlength: 8, value: this.form.password, onValueChange: (value: string) => { this.form.password = value; } }) })}`}
134
+ ${this.botKey ? component(Turnstile, { id: 'register-site-verify', siteKey: this.botKey, action: 'register', label: __('Bot protection') }) : null}
135
+ ${this.error ? component(Alert, { variant: 'destructive' }, this.error) : null}
136
+ ${component(Button, { type: 'submit', block: true }, __('Create site'))}
137
+ </form>
138
+ ${this.signedInAs ? html`<p class="mt-6 text-center text-sm text-muted-foreground">
139
+ ${__('Another account?')}
140
+ <button type="button" class="text-primary font-medium hover:underline" @click=${() => this.signOut()} data-sign-out>${__('Sign out')}</button>
141
+ </p>` : html`<p class="mt-6 text-center text-sm text-muted-foreground">
142
+ ${__('Already have a site?')}
143
+ <a href="/auth/login" class="text-primary font-medium hover:underline">${__('Sign in')}</a>
144
+ </p>`}`;
145
+ }
146
+ }
@@ -1,3 +1,5 @@
1
+ import { hashPassword } from '@cossackframework/auth';
2
+ import { User } from '@/models/User';
1
3
  import { Client, Cossack, Page, RateLimit, State, flash, flashed, type HeadValue } from '@cossackframework/core';
2
4
  import { Alert } from '@cossackframework/ui';
3
5
  import { html, component } from '@cossackframework/renderer';
@@ -73,12 +75,14 @@ export default class SetupPage extends Cossack {
73
75
  return this.redirect('/auth/setup');
74
76
  }
75
77
  await cms.ready({ force: true });
76
- if (await cms.accounts.hasNetworkAdmin()) return this.redirect('/auth/login');
78
+ // Set up once: the first account is the network's administrator.
79
+ if (await User.exists({ networkAdmin: true })) return this.redirect('/auth/login');
77
80
  if ((await cms.users.count()) > 0) return this.takeOver(value('email'), value('password'));
78
81
  try {
79
82
  for (const role of DEFAULT_ROLES) await cms.users.defineRole({ ...role, permissions: [...role.permissions] });
80
83
  // The first account runs the network as well as this site.
81
- const user = await cms.users.create({ email: value('email'), name: value('name'), password: value('password'), roles: ['admin'], networkRole: NETWORK_ADMIN });
84
+ const user = await cms.users.create({ email: value('email'), name: value('name'), password: value('password'), roles: ['admin'] });
85
+ await User.update({ id: user.id }, { networkAdmin: true });
82
86
  await cms.settings.update('general', { siteTitle: value('siteTitle').trim() || 'My Site', adminEmail: user.email }, { principal: systemPrincipal('setup') });
83
87
  // A first post, a category, a contact form and its page, as the administrator, when asked for; a restored database keeps its own content.
84
88
  if (value('starter')) {
@@ -128,7 +132,8 @@ export default class SetupPage extends Cossack {
128
132
  const address = normalizeEmail(email);
129
133
  const member = (await cms.users.list({ search: address, limit: 100 })).items.find(user => user.email === address);
130
134
  if (!member?.assignments.some(role => role.id === 'admin')) throw new Error('Enter the email of one of this site\'s administrators.');
131
- await cms.accounts.adoptMembers(MAIN_SITE, member.id, password);
135
+ // The members came with the export, without passwords: this one gets a password and runs the network.
136
+ await User.update({ id: member.id }, { passwordHash: await hashPassword(password), networkAdmin: true, status: 'active' });
132
137
  const { headers } = await authSessions.create(member.id, this.c);
133
138
  headers.forEach((header, name) => this.c.header(name, header, { append: true }));
134
139
  } catch (error) {
@@ -0,0 +1,23 @@
1
+ import type { Context } from 'hono';
2
+ import { deleteCookie, getCookie } from 'hono/cookie';
3
+ import { completeTenantHandoff, sharedSignInAvailable } from '#app/auth';
4
+ import { returnPath } from '#app/auth-input';
5
+
6
+ /** The value a tenant's host gave the visitor before sending them to the main host. */
7
+ const TENANT_STATE_COOKIE = 'tenant_state';
8
+
9
+ /**
10
+ * Shared sign-in, on a tenant's host: the main host sent the visitor back with a one-time
11
+ * code. The code counts only in the browser that started here (the state cookie), so nobody
12
+ * can be signed in to someone else's account by a link.
13
+ */
14
+ export const GET = async (c: Context) => {
15
+ if (!sharedSignInAvailable) return c.notFound();
16
+ const state = c.req.query('state') ?? '';
17
+ const expected = getCookie(c, TENANT_STATE_COOKIE) ?? '';
18
+ deleteCookie(c, TENANT_STATE_COOKIE, { path: '/' });
19
+ const headers = state && state === expected ? await completeTenantHandoff(c, c.req.query('code') ?? '') : null;
20
+ if (!headers) return c.text('This sign-in did not complete. Open the site again to retry.', 400);
21
+ headers.forEach((value, key) => c.header(key, value, { append: true }));
22
+ return c.redirect(returnPath(c.req.query('next')) ?? config('auth.redirectAfterLogin'));
23
+ };
@@ -0,0 +1,91 @@
1
+ import type { Context } from 'hono';
2
+ import { setCookie } from 'hono/cookie';
3
+ import { issueTenantHandoff, sharedSignInAvailable, tenantHandoffTarget, tenantSignInUrl, type PublicUser } from '#app/auth';
4
+ import { returnPath } from '#app/auth-input';
5
+
6
+ /** Where a visitor who still has to sign in was going: kept on the main host for ten minutes. */
7
+ const TENANT_RETURN_COOKIE = 'tenant_return';
8
+
9
+ const escape = (text: string) => text.replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`);
10
+
11
+ /** A form of this host's own page sent the request: another site cannot press Continue for the visitor. */
12
+ function ownForm(c: Context): boolean {
13
+ const site = c.req.header('sec-fetch-site')?.toLowerCase();
14
+ if (site === 'same-origin') return true;
15
+ if (site !== undefined) return false;
16
+ const origin = c.req.header('origin');
17
+ const url = new URL(c.req.url);
18
+ return origin === url.origin || (c.req.header('x-forwarded-proto')?.toLowerCase() === 'https' && origin === `https://${url.host}`);
19
+ }
20
+
21
+ /**
22
+ * A tenant's own domain is run by the tenant: a code sent there can be read there. So the
23
+ * visitor says yes on the main host first, and sees which account and which site it is for.
24
+ */
25
+ function confirmation(c: Context, target: { name: string; host: string }, user: PublicUser, fields: Record<string, string>): Response {
26
+ const inputs = Object.entries(fields).map(([name, value]) => `<input type="hidden" name="${escape(name)}" value="${escape(value)}">`).join('');
27
+ return c.html(`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noindex"><title>Sign in to ${escape(target.name)}</title>
28
+ <style>body{font:16px/1.5 system-ui,sans-serif;margin:0;display:grid;place-items:center;min-height:100vh;background:#f6f6f7;color:#18181b}main{max-width:26rem;margin:1rem;padding:1.5rem;background:#fff;border:1px solid #e4e4e7;border-radius:.5rem}h1{font-size:1.25rem;margin:0 0 .75rem}p{margin:0 0 1rem}button{font:inherit;padding:.5rem 1rem;border-radius:.375rem;border:1px solid #18181b;background:#18181b;color:#fff;cursor:pointer}a{margin-left:.75rem;color:inherit}@media (prefers-color-scheme:dark){body{background:#09090b;color:#fafafa}main{background:#18181b;border-color:#27272a}button{background:#fafafa;color:#18181b;border-color:#fafafa}}</style></head>
29
+ <body><main><h1>Sign in to ${escape(target.name)}?</h1>
30
+ <p>You are about to sign in to <strong>${escape(target.name)}</strong> at <strong>${escape(target.host)}</strong> as <strong>${escape(user.email)}</strong>.</p>
31
+ <p>Continue only if you opened this site yourself.</p>
32
+ <form method="post" action="/auth/tenant/redirect">${inputs}<button type="submit">Continue</button><a href="/dashboard">Cancel</a></form></main></body></html>`);
33
+ }
34
+
35
+ async function handoff(c: Context, host: string, state: string, next: string | null, auto: boolean): Promise<Response> {
36
+ const issued = await issueTenantHandoff(c, host, state, next);
37
+ if ('error' in issued) {
38
+ const back = auto ? await tenantSignInUrl(c, host) : null;
39
+ return back ? c.redirect(back) : c.text(issued.error, issued.status);
40
+ }
41
+ return c.redirect(issued.url);
42
+ }
43
+
44
+ /**
45
+ * Shared sign-in, on the main host: a tenant's host sent the visitor here. A signed-in member
46
+ * goes back with a one-time code; anyone else signs in first and is brought back here. With
47
+ * `auto=1` the tenant's host sent the visitor on its own, and nobody is asked to sign in.
48
+ * For a tenant's own domain the visitor confirms first (`POST`), and is never sent on their own.
49
+ */
50
+ export const GET = async (c: Context) => {
51
+ if (!sharedSignInAvailable) return c.notFound();
52
+ const host = c.req.query('host') ?? '';
53
+ const state = c.req.query('state') ?? '';
54
+ const next = returnPath(c.req.query('next'));
55
+ // The visitor did not ask to come: without a session here, or without a place in the tenant,
56
+ // they go back to the tenant's own sign-in page.
57
+ const auto = c.req.query('auto') === '1';
58
+ const user = c.get('user') as PublicUser | undefined;
59
+ if (auto && !user) {
60
+ const back = await tenantSignInUrl(c, host);
61
+ return back ? c.redirect(back) : c.notFound();
62
+ }
63
+ if (!user) {
64
+ const secure = new URL(c.req.url).protocol === 'https:';
65
+ setCookie(c, TENANT_RETURN_COOKIE, new URLSearchParams({ host, state, ...(next ? { next } : {}) }).toString(), { path: '/', httpOnly: true, sameSite: 'Lax', maxAge: 600, secure });
66
+ return c.redirect('/auth/login');
67
+ }
68
+ const target = await tenantHandoffTarget(host);
69
+ if (target?.custom) {
70
+ // Nobody is signed in to a tenant's own domain without asking for it.
71
+ if (auto) {
72
+ const back = await tenantSignInUrl(c, host);
73
+ return back ? c.redirect(back) : c.notFound();
74
+ }
75
+ return confirmation(c, target, user, { host, state, ...(next ? { next } : {}) });
76
+ }
77
+ return handoff(c, host, state, next, auto);
78
+ };
79
+
80
+ /** The visitor pressed Continue on this host's confirmation page. */
81
+ export const POST = async (c: Context) => {
82
+ if (!sharedSignInAvailable) return c.notFound();
83
+ if (!ownForm(c)) return c.text('Forbidden', 403);
84
+ // Only a signed-in visitor saw the page whose form this is.
85
+ if (!c.get('user')) return c.text('Sign in first.', 401);
86
+ let form: FormData;
87
+ try { form = await c.req.formData(); }
88
+ catch { return c.text('The request is not complete.', 400); }
89
+ const value = (name: string) => String(form.get(name) ?? '');
90
+ return handoff(c, value('host'), value('state'), returnPath(value('next') || undefined), false);
91
+ };
@@ -2,8 +2,6 @@ import { Client, Cossack, Page, Server, State } from '@cossackframework/core';
2
2
  import { Alert, Button } from '@cossackframework/ui';
3
3
  import { html, component } from '@cossackframework/renderer';
4
4
  import { authSessions, linkAccountEmail, verifyEmail } from '#app/auth';
5
- import { networkFor, siteUrl, type CmsBindings } from '#app/cms/index';
6
- import { networkSite } from '@cossackframework/cms/server';
7
5
 
8
6
  /**
9
7
  * The confirmation link of a new account. Opening it changes nothing: a button confirms, so a
@@ -42,16 +40,14 @@ export default class VerifyPage extends Cossack {
42
40
  if (verified.pending) { this.pending = true; return; }
43
41
  const { headers } = await authSessions.create(verified.user, this.c);
44
42
  headers.forEach((value, key) => this.c.header(key, value));
45
- // Registered on the network for one of its sites: signed in here, the site's handoff takes them there.
46
- const record = verified.site ? await networkFor(this.c.env as CmsBindings).sites.get(verified.site).catch(() => null) : null;
47
- const target = record ? siteUrl(this.c.env as CmsBindings, networkSite(record)) : undefined;
48
- this.redirect(target ? `${target.replace(/\/+$/, '')}/auth/handoff?next=${encodeURIComponent('/dashboard?verified=1')}` : '/dashboard?verified=1');
43
+ this.redirect(config('auth.redirectAfterLogin'));
49
44
  }
50
45
 
51
46
  render() {
52
47
  return html`
53
48
  <h3 class="mb-3 text-xl font-semibold text-foreground">${__('Confirm your email')}</h3>
54
- ${this.pending ? component(Alert, {}, __('Your email address is confirmed. An administrator approves new accounts on this site; we will email you when yours is ready.')) : this.failed ? component(Alert, { variant: 'destructive' }, __('This link is not valid any more. Register again with the same email to get a new one, or sign in if your account is already confirmed.')) : html`
49
+ ${this.pending ? component(Alert, {}, __('Your email address is confirmed. An administrator approves new accounts on this site; we will email you when yours is ready.'))
50
+ : this.failed ? component(Alert, { variant: 'destructive' }, __('This confirmation link is not valid any more. Register again to get a new one.')) : html`
55
51
  <form class="space-y-4" @submit=${(event: Event) => this.submit(event)}>
56
52
  <p class="text-sm text-muted-foreground">${__('Confirm')} <strong class="text-foreground">${this.email}</strong> ${__('to finish creating your account. If this is not your address, close this page.')}</p>
57
53
  ${component(Button, { type: 'submit', block: true }, __('Confirm email'))}
@@ -239,7 +239,7 @@ export default class MenuEditor extends Cossack {
239
239
  } else {
240
240
  const collection = cms.collection(source);
241
241
  const where = collection.publishable === false ? {} : { where: { status: 'published' } };
242
- const records = query.trim() ? openMatches(cms, `cms/${source}`, await cms.resource(`cms/${source}`).search(query.slice(0, 100), { limit: 30, ...where }, { principal }).catch(() => []), principal)
242
+ const records = query.trim() ? await openMatches(cms, `cms/${source}`, await cms.resource(`cms/${source}`).search(query.slice(0, 100), { limit: 30, ...where }, { principal }).catch(() => []), principal)
243
243
  : (await cms.resource(`cms/${source}`).list({ ...where, limit: 30 }, { principal })).records;
244
244
  entries = records.map(record => ({ id: record.id, title: recordTitle(record, 'title'), depth: 0 }));
245
245
  }
@@ -193,7 +193,7 @@ export default class EntryEditor extends Cossack {
193
193
  const view = await editorView(cms, this.route, principal);
194
194
  const { resource } = routeResource(cms, this.route);
195
195
  const record = this.id === 'new' ? null : await cms.resource(resource.id).get(this.id, { principal });
196
- if (this.id !== 'new' && (!record || !cms.resource(resource.id).canUpdate(record, principal))) { this.error = __('This entry does not exist or you cannot edit it.'); this.c.status(404); return; }
196
+ if (this.id !== 'new' && (!record || !await cms.resource(resource.id).canUpdate(record, { principal }))) { this.error = __('This entry does not exist or you cannot edit it.'); this.c.status(404); return; }
197
197
  if (!record && evaluateRule(resource.access.create, principal) === 'deny') { this.error = __('You cannot create entries here.'); this.c.status(403); return; }
198
198
  this.view = view;
199
199
  this.schema = recordSchema(resource);
@@ -236,7 +236,7 @@ export default class EntryEditor extends Cossack {
236
236
  if (view.path !== null || view.route === 'forms') this.previewLinks = await cms.previews.count(resource.id, record.id).catch(() => 0);
237
237
  }
238
238
  // The entry's notes, with who wrote them; opening the entry marks the viewer's mentions seen.
239
- if (record && principal.kind === 'user' && cms.resource(resource.id).canUpdate(record, principal)) {
239
+ if (record && principal.kind === 'user' && await cms.resource(resource.id).canUpdate(record, { principal })) {
240
240
  this.meId = principal.id;
241
241
  this.canRemoveNotes = hasPermission(principal, PERMISSIONS.manageUsers);
242
242
  this.notes = await cms.notes.forEntry(resource.id, record.id).catch(() => []);
@@ -976,7 +976,7 @@ export default class EntryEditor extends Cossack {
976
976
  if (!Object.values(resource.fields).some(field => field.search)) continue;
977
977
  try {
978
978
  const principal = this.c.get('principal');
979
- const records = openMatches(cms, resource.id, await cms.resource(resource.id).search(query, { limit: 6, ...(collection.publishable === false ? {} : { where: { status: 'published' } }) }, { principal }), principal).filter(record => record.id !== exclude);
979
+ const records = (await openMatches(cms, resource.id, await cms.resource(resource.id).search(query, { limit: 6, ...(collection.publishable === false ? {} : { where: { status: 'published' } }) }, { principal }), principal)).filter(record => record.id !== exclude);
980
980
  const urls = await cms.entryUrls(collection, records);
981
981
  for (const record of records) if (urls.get(record.id)) found.push({ title: recordTitle(record, 'title'), url: urls.get(record.id)!, collection: collection.singular });
982
982
  } catch (error) { if (!isCmsError(error)) throw error; }
@@ -1051,7 +1051,7 @@ export default class EntryEditor extends Cossack {
1051
1051
  return;
1052
1052
  }
1053
1053
  const record = await cms.resource(resource.id).get(this.id, { principal });
1054
- if (!record || !cms.resource(resource.id).canUpdate(record, principal)) throw new ClientVisibleError(__('This entry does not exist or you cannot edit it.'));
1054
+ if (!record || !await cms.resource(resource.id).canUpdate(record, { principal })) throw new ClientVisibleError(__('This entry does not exist or you cannot edit it.'));
1055
1055
  }
1056
1056
 
1057
1057
  /** The resource this editor's route names, read on the server. */
@@ -1916,7 +1916,7 @@ export default class EntryEditor extends Cossack {
1916
1916
  if (!['title', 'excerpt', 'summary'].includes(kind)) throw new ClientVisibleError(__('Unknown suggestion.'));
1917
1917
  await this.assertEditor();
1918
1918
  const principal = this.c.get('principal');
1919
- if (!(await cms.security.attempt('suggest', principalId(principal), SUGGESTIONS.max, SUGGESTIONS.windowMs))) throw new ClientVisibleError(__('Too many suggestions in a short time. Wait a minute and try again.'));
1919
+ if (!(await cms.attempts.attempt('suggest', principalId(principal), SUGGESTIONS.max, SUGGESTIONS.windowMs))) throw new ClientVisibleError(__('Too many suggestions in a short time. Wait a minute and try again.'));
1920
1920
  const parts: string[] = [];
1921
1921
  for (const [name, value] of Object.entries(values)) {
1922
1922
  if (name === kind || parts.join(' ').length > 12_000) continue;
@@ -46,7 +46,7 @@ export default class RevisionsPage extends Cossack {
46
46
  this.title = recordTitle(record, resource.titleField);
47
47
  this.singular = collection?.singular ?? __('Entry');
48
48
  this.current = record.rev;
49
- this.canRestore = repository.canUpdate(record, principal);
49
+ this.canRestore = await repository.canUpdate(record, { principal });
50
50
  const revisions = await repository.revisions(this.id, { principal }, { limit: 50 });
51
51
  const actors = await cms.users.getMany(revisions.map(entry => entry.actor ?? '').filter(Boolean));
52
52
  this.revisions = revisions.map(entry => ({ revision: entry.revision, at: entry.at, actor: actors.get(entry.actor ?? '')?.name ?? entry.actor ?? '' }));
@@ -195,7 +195,7 @@ export default class EntriesPage extends Cossack {
195
195
  const offset = Math.min((this.page - 1) * this.perPage, 10_000 - this.perPage - 1);
196
196
  const found = await repository.search(this.search, { ...filter, limit: this.perPage + 1, offset }, context);
197
197
  this.more = found.length > this.perPage;
198
- records = openMatches(cms, resource.id, found.slice(0, this.perPage), context.principal);
198
+ records = await openMatches(cms, resource.id, found.slice(0, this.perPage), context.principal);
199
199
  this.total = offset + records.length;
200
200
  } else {
201
201
  // The Date column sorts by the publication time on the Published and Scheduled tabs, by the last change elsewhere.
@@ -1,3 +1,4 @@
1
+ import { networkAdminIds } from '#app/cms/network-accounts';
1
2
  import { Cossack, Page, State, type HeadValue } from '@cossackframework/core';
2
3
  import { Card, CardBody } from '@cossackframework/ui';
3
4
  import { html, component } from '@cossackframework/renderer';
@@ -24,8 +25,9 @@ export default class NetworkHome extends Cossack {
24
25
  const [active, archived, deleted] = await Promise.all((['active', 'archived', 'deleted'] as const).map(async status => (await net.sites.list({ status, limit: 1 })).total));
25
26
  // The main site counts as an active site.
26
27
  this.sites = { active: active + 1, archived, deleted };
27
- this.accounts = await net.main.accounts.count();
28
- this.admins = (await net.main.accounts.list({ networkAdmins: true, limit: 1 })).total;
28
+ // Accounts of the network are the main site's users.
29
+ this.accounts = await net.main.users.count();
30
+ this.admins = (await networkAdminIds()).size;
29
31
  this.canAdd = net.canAddSites;
30
32
  }
31
33
 
@@ -1,3 +1,5 @@
1
+ import { moveAccount } from '#app/services/tenants';
2
+ import { networkAdminIds, siteMemberships } from '#app/cms/network-accounts';
1
3
  import { Client, Cossack, Page, State, flash, flashed, type HeadValue } from '@cossackframework/core';
2
4
  import { Badge, Card, CardBody, CardHeader, NativeSelect, Button } from '@cossackframework/ui';
3
5
  import { html, component, type TemplateResult } from '@cossackframework/renderer';
@@ -49,20 +51,20 @@ export default class NetworkSite extends Cossack {
49
51
  Object.assign(this, { id: record.id, name: record.name, status: record.status, createdAt: record.createdAt, domains: [...record.domains] }, siteLinks(this.c, networkSite(record)));
50
52
  if (record.status !== 'creating') {
51
53
  const host = net.hostOf(networkSite(record));
52
- const users = (await host.users.list({ limit: 100 })).items;
54
+ // The site's users and roles are in its own database.
55
+ const [users, roles] = await net.inSite(networkSite(record), async () => [(await host.users.list({ limit: 100 })).items, await host.users.roles()] as const);
53
56
  const network = users.filter(user => user.account === 'network').map(user => user.id);
54
- const [sites, admins] = await Promise.all([net.main.accounts.memberships(network), net.main.accounts.list({ networkAdmins: true, limit: 100 })]);
55
- const runsNetwork = new Set(admins.items.map(account => account.id));
57
+ const [sites, runsNetwork] = await Promise.all([siteMemberships(network), networkAdminIds()]);
56
58
  this.members = users.map(user => ({
57
59
  id: user.id, name: user.name, email: user.email, roles: user.assignments.map(role => role.name).join(', ') || __('No role'), account: user.account,
58
60
  movable: user.account === 'site' || (!runsNetwork.has(user.id) && (sites.get(user.id) ?? []).every(site => site === record.id)),
59
61
  }));
60
- this.roles = (await host.users.roles()).map(role => ({ id: role.id, name: role.name }));
61
- this.importState = await siteImportState(host);
62
+ this.roles = roles.map(role => ({ id: role.id, name: role.name }));
63
+ this.importState = await net.inSite(networkSite(record), () => siteImportState(host));
62
64
  }
63
65
  const request = (await net.exportRequests()).get(record.id);
64
66
  if (request) {
65
- const account = await net.main.accounts.get(request.requestedBy);
67
+ const account = await net.main.users.get(request.requestedBy);
66
68
  this.exportRequest = { by: account ? `${account.name} (${account.email})` : request.requestedBy, at: request.requestedAt, approvedAt: request.approvedAt, expiresAt: request.expiresAt };
67
69
  }
68
70
  this.message = flashed<string>('network.message') ?? '';
@@ -96,20 +98,20 @@ export default class NetworkSite extends Cossack {
96
98
  await net.removeDomain(id, value('host'), { principal });
97
99
  flash('network.message', __('Removed.'));
98
100
  } else if (action === 'add-member') {
99
- const account = await net.main.accounts.findByEmail(value('email'));
101
+ const account = await net.main.users.findByEmail(value('email'));
100
102
  if (!account) throw new Error(__('No network account has that email.'));
101
103
  const host = net.hostOf(networkSite(record));
102
- await host.users.addMember(account.id);
103
- await host.users.setRoles(account.id, value('role') ? [value('role')] : []);
104
+ await net.inSite(networkSite(record), async () => { await host.users.addMember(account.id, { roles: value('role') ? [value('role')] : [] }); });
104
105
  flash('network.message', `${account.name} ${__('is a member now.')}`);
105
106
  } else if (action === 'convert-member') {
106
107
  const to = value('to') === 'site' ? 'site' : 'network';
107
- const user = await net.hostOf(networkSite(record)).users.convert(value('account'), to);
108
- flash('network.message', `${user.name} ${to === 'site' ? __('has a site account now.') : __('has a network account now.')}`);
108
+ const before = await net.inSite(networkSite(record), () => net.hostOf(networkSite(record)).users.get(value('account')));
109
+ await moveAccount({ id: record.id, slug: record.id, name: record.name, database: record.database, status: 'active' }, value('account'), to === 'site' ? 'tenant' : 'main');
110
+ flash('network.message', `${before?.name ?? __('The account')} ${to === 'site' ? __('has a site account now.') : __('has a network account now.')}`);
109
111
  } else if (action === 'import') {
110
112
  return this.importSite(id, false);
111
113
  } else if (action === 'remove-member') {
112
- await net.hostOf(networkSite(record)).users.delete(value('account'));
114
+ await net.inSite(networkSite(record), async () => { await net.hostOf(networkSite(record)).users.delete(value('account')); });
113
115
  flash('network.message', __('Removed from the site.'));
114
116
  } else if (action === 'approve-export' || action === 'decline-export') {
115
117
  await net.answerExport(id, action === 'approve-export', { principal });
@@ -130,7 +132,8 @@ export default class NetworkSite extends Cossack {
130
132
  try {
131
133
  const record = await net.sites.get(id);
132
134
  if (!record || record.status === 'creating') throw new Error(__('There is no such site.'));
133
- flash('network.message', importSummary(await importRequest(this.c, net.hostOf(networkSite(record)))));
135
+ // The import writes the site's users, which are in its own database.
136
+ flash('network.message', importSummary(await net.inSite(networkSite(record), () => importRequest(this.c, net.hostOf(networkSite(record))))));
134
137
  return raw ? this.c.json({ next: `/dashboard/network/sites/${id}` }) : this.redirect(`/dashboard/network/sites/${id}`);
135
138
  } catch (error) {
136
139
  const message = isCmsError(error) || error instanceof Error ? (error as Error).message : __('The export could not be imported.');
@@ -1,3 +1,4 @@
1
+ import { siteMemberCounts } from '#app/cms/network-accounts';
1
2
  import { Client, Cossack, Page, Server, State, flashed, type HeadValue } from '@cossackframework/core';
2
3
  import { AlertDialog } from '@cossackframework/ui';
3
4
  import { html, component } from '@cossackframework/renderer';
@@ -54,7 +55,7 @@ export default class NetworkSites extends Cossack {
54
55
  const [totals, memberships, mainName, networkIcon, requests] = await Promise.all([
55
56
  Promise.all(STATUSES.map(status => net.sites.list({ ...search, status, limit: 1 }).then(found => found.total))),
56
57
  // Network accounts by site, for sites whose database is not open: being created or deleted.
57
- net.main.accounts.memberCounts(),
58
+ siteMemberCounts(),
58
59
  net.main.settings.get('general.siteTitle').then(title => title || __('Main site'), () => __('Main site')),
59
60
  // The main site's icon is the network's, for sites without one.
60
61
  siteIconUrl(this.c, net.main, { host: null }),
@@ -74,7 +75,8 @@ export default class NetworkSites extends Cossack {
74
75
  // Sites being created or deleted have no settings to read; open ones count site accounts too.
75
76
  const open = site.status === 'active' || site.status === 'archived' ? net.hostOf(networkSite(site)) : null;
76
77
  const own = open ? await siteIconUrl(this.c, open, { host }) : '';
77
- const members = open ? await open.users.count().catch(() => memberships.get(site.id) ?? 0) : memberships.get(site.id) ?? 0;
78
+ // A site's users are in its own database.
79
+ const members = open ? await net.inSite(networkSite(site), () => open.users.count()).catch(() => memberships.get(site.id) ?? 0) : memberships.get(site.id) ?? 0;
78
80
  return { id: site.id, name: site.name, host, status: site.status, members, createdAt: site.createdAt, icon: own || networkIcon,
79
81
  exportRequested: requests.get(site.id)?.approvedAt === null, ...siteLinks(this.c, { host }) };
80
82
  }))];
@@ -39,7 +39,7 @@ export default class NewNetworkSite extends Cossack {
39
39
  const net = network(this.c);
40
40
  const principal = this.c.get('principal');
41
41
  try {
42
- const admin = form.admin ? await net.main.accounts.findByEmail(form.admin) : await net.main.accounts.get(principal.kind === 'user' ? principal.id : '');
42
+ const admin = form.admin ? await net.main.users.findByEmail(form.admin) : await net.main.users.get(principal.kind === 'user' ? principal.id : '');
43
43
  if (!admin) throw new Error(__('No account has that email. Add the person under Network → Users first.'));
44
44
  const site = await net.createSite({ name: form.name, host: form.host, admin: admin.id, ...(value('id') ? { id: value('id') } : {}), ...(form.language ? { language: form.language } : {}), starter: form.starter }, { principal });
45
45
  flash('network.message', `${site.name} ${__('is ready.')}`);