@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.
- package/agent-docs.json +8 -8
- package/app/cossack-recipe.json +12 -8
- package/app/src/auth-events.ts +33 -0
- package/app/src/auth-input.ts +3 -0
- package/app/src/auth-options.ts +39 -7
- package/app/src/auth.ts +1309 -641
- package/app/src/avatars.ts +13 -0
- package/app/src/brand.ts +24 -2
- package/app/src/cms/actor.ts +13 -0
- package/app/src/cms/collab/room.ts +1 -1
- package/app/src/cms/content-api.ts +2 -1
- package/app/src/cms/content.ts +3 -2
- package/app/src/cms/dev-mail.ts +77 -0
- package/app/src/cms/index.ts +37 -10
- package/app/src/cms/maintenance.ts +1 -6
- package/app/src/cms/manage.ts +17 -14
- package/app/src/cms/middleware.ts +58 -18
- package/app/src/cms/network-accounts.ts +110 -0
- package/app/src/cms/notes-announce.ts +1 -1
- package/app/src/cms/people.ts +177 -0
- package/app/src/cms/recovery.ts +9 -14
- package/app/src/cms/request-calls.ts +56 -0
- package/app/src/cms/settings-form.ts +23 -6
- package/app/src/cms/settings-network.ts +8 -4
- package/app/src/cms/settings-search.ts +1 -0
- package/app/src/cms/site-editing.ts +3 -2
- package/app/src/cms/site-registration.ts +64 -0
- package/app/src/cms/site.ts +30 -19
- package/app/src/cms/sites.ts +182 -0
- package/app/src/dashboard/access.ts +3 -2
- package/app/src/dashboard/modules/users.ts +1 -0
- package/app/src/lib/permissions.ts +24 -0
- package/app/src/lib/uuid.ts +6 -0
- package/app/src/mail.ts +15 -0
- package/app/src/middlewares/auth.ts +6 -2
- package/app/src/middlewares/tenant.ts +108 -0
- package/app/src/pages/(site)/[...path]/index.ts +1 -1
- package/app/src/pages/(site)/preview/[collection]/[id]/index.ts +1 -1
- package/app/src/pages/api/cms/dev/mail.ts +19 -0
- package/app/src/pages/api/cms/forms/[slug]/index.ts +1 -1
- package/app/src/pages/api/cms/users/[id]/meta.ts +2 -1
- package/app/src/pages/auth/login/index.ts +1 -1
- package/app/src/pages/auth/magic/index.ts +1 -1
- package/app/src/pages/auth/recovery.ts +20 -0
- package/app/src/pages/auth/register-site/index.ts +146 -0
- package/app/src/pages/auth/setup/index.ts +8 -3
- package/app/src/pages/auth/tenant/callback.ts +23 -0
- package/app/src/pages/auth/tenant/redirect.ts +91 -0
- package/app/src/pages/auth/verify/index.ts +3 -7
- package/app/src/pages/dashboard/(cms)/appearance/menus/[id]/index.ts +1 -1
- package/app/src/pages/dashboard/(cms)/content/[collection]/[id]/index.ts +5 -5
- package/app/src/pages/dashboard/(cms)/content/[collection]/[id]/revisions/index.ts +1 -1
- package/app/src/pages/dashboard/(cms)/content/[collection]/index.ts +1 -1
- package/app/src/pages/dashboard/(cms)/network/index.ts +4 -2
- package/app/src/pages/dashboard/(cms)/network/sites/[id]/index.ts +16 -13
- package/app/src/pages/dashboard/(cms)/network/sites/index.ts +4 -2
- package/app/src/pages/dashboard/(cms)/network/sites/new/index.ts +1 -1
- package/app/src/pages/dashboard/(cms)/network/users/[id]/index.ts +29 -10
- package/app/src/pages/dashboard/(cms)/network/users/index.ts +8 -7
- package/app/src/pages/dashboard/(cms)/network/users/new/index.ts +2 -1
- package/app/src/pages/dashboard/(cms)/registrations/index.ts +5 -4
- package/app/src/pages/dashboard/(cms)/tools/health/index.ts +4 -1
- package/app/src/pages/dashboard/(cms)/tools/replace/index.ts +2 -1
- package/app/src/pages/dashboard/(cms)/tools/seo/index.ts +1 -1
- package/app/src/pages/dashboard/index.ts +3 -2
- package/app/src/pages/dashboard/roles/index.ts +2 -2
- package/app/src/pages/dashboard/users/registrations/index.ts +66 -0
- package/app/src/services/api-tokens.ts +86 -0
- package/app/src/services/rbac.ts +26 -15
- package/app/src/services/roles.ts +125 -35
- package/app/src/services/security.ts +384 -0
- package/app/src/services/tenants.ts +447 -0
- package/app/src/services/users.ts +241 -97
- package/app/src/tenants.ts +219 -0
- package/package.json +48 -12
- package/src/block-references.ts +3 -3
- package/src/collections.ts +3 -1
- package/src/forms.ts +4 -2
- package/src/hooks.ts +19 -1
- package/src/index.ts +4 -4
- package/src/isolate-core.ts +1 -1
- package/src/isolation.ts +1 -0
- package/src/manifest.ts +43 -2
- package/src/permissions.ts +13 -7
- package/src/resource.ts +85 -2
- package/src/server/attempts.ts +64 -0
- package/src/server/automations.ts +2 -2
- package/src/server/batch.ts +106 -0
- package/src/server/budget.ts +17 -0
- package/src/server/field-values.ts +207 -0
- package/src/server/forms.ts +3 -3
- package/src/server/host-schema.ts +55 -7
- package/src/server/host.ts +213 -85
- package/src/server/index.ts +9 -14
- package/src/server/isolation.ts +10 -0
- package/src/server/network.ts +129 -44
- package/src/server/outbox.ts +2 -2
- package/src/server/people.ts +191 -0
- package/src/server/reconcile.ts +5 -5
- package/src/server/repository.ts +243 -84
- package/src/server/shared-read.ts +34 -0
- package/src/server/site-export.ts +23 -13
- package/src/server/site-import.ts +12 -33
- package/src/server/site-settings.ts +9 -3
- package/src/server/sites.ts +117 -187
- package/src/server/stores.ts +3 -300
- package/src/server/taxonomies.ts +64 -13
- package/src/server/users.ts +151 -498
- package/src/settings-controls.ts +8 -4
- package/src/settings.ts +26 -3
- package/src/storage/cloudflare.ts +2 -0
- package/src/storage/index.ts +6 -0
- package/src/theme.ts +2 -2
- package/src/version.ts +1 -1
- package/app/src/cms/handoff.ts +0 -202
- package/src/server/accounts.ts +0 -418
- package/src/server/api-tokens.ts +0 -91
- package/src/server/auth.ts +0 -89
- package/src/server/handoffs.ts +0 -107
- package/src/server/security.ts +0 -391
package/src/settings-controls.ts
CHANGED
|
@@ -3,12 +3,14 @@ import { FIELD_MEDIA_KINDS, validateValue } from './fields';
|
|
|
3
3
|
import type { SettingControl, SettingDeclaration } from './settings';
|
|
4
4
|
|
|
5
5
|
const COLOR_PATTERN = '#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})';
|
|
6
|
+
/** Values of a source joined by commas, such as role IDs. */
|
|
7
|
+
const CHECKLIST_PATTERN = '[A-Za-z0-9_-]{1,80}(?:,[A-Za-z0-9_-]{1,80})*';
|
|
6
8
|
const FILE_PATTERN = '(?:https?://[^\\s\\\\\\u0000-\\u001f\\u007f]+|/(?![/\\\\])[^\\s\\\\\\u0000-\\u001f\\u007f]*)';
|
|
7
9
|
|
|
8
10
|
/** JSON Schema checks syntax; the server also parses absolute file URLs. */
|
|
9
11
|
export function settingControlPattern(control: SettingControl): string {
|
|
10
12
|
// Unlike $, the final assertion does not permit a trailing line break.
|
|
11
|
-
return `^(?:${control === 'color' ? COLOR_PATTERN : FILE_PATTERN})?(?![\\s\\S])`;
|
|
13
|
+
return `^(?:${control === 'color' ? COLOR_PATTERN : control === 'checklist' ? CHECKLIST_PATTERN : FILE_PATTERN})?(?![\\s\\S])`;
|
|
12
14
|
}
|
|
13
15
|
|
|
14
16
|
function controlValueProblem(declaration: SettingDeclaration, value: unknown): string | undefined {
|
|
@@ -37,9 +39,11 @@ export function settingControlProblems(name: string, declaration: SettingDeclara
|
|
|
37
39
|
const problems: string[] = [];
|
|
38
40
|
const at = `field ${name}`;
|
|
39
41
|
const preview = declaration.control === 'icon-style' || declaration.control === 'palette';
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
42
|
+
// A checklist offers its source's choices; the other controls have none.
|
|
43
|
+
const sourced = declaration.control === 'checklist' ? declaration.source !== undefined && declaration.source !== 'media' : declaration.source === undefined;
|
|
44
|
+
if (declaration.control !== undefined && (!['color', 'file', 'icon-style', 'palette', 'checklist'].includes(declaration.control)
|
|
45
|
+
|| declaration.kind !== (preview ? 'enum' : 'string') || declaration.multiple || declaration.media || !sourced)) {
|
|
46
|
+
problems.push(`${at}: control is color or file on a single string without a source, checklist on a single string with a source, or icon-style or palette on an enum without a source.`);
|
|
43
47
|
}
|
|
44
48
|
if (declaration.fileKinds !== undefined && (declaration.control !== 'file' || !Array.isArray(declaration.fileKinds)
|
|
45
49
|
|| !declaration.fileKinds.length || declaration.fileKinds.some(kind => !(FIELD_MEDIA_KINDS as readonly string[]).includes(kind))
|
package/src/settings.ts
CHANGED
|
@@ -6,16 +6,17 @@ import { CACHE_HOLDS, type CacheHold } from './cache';
|
|
|
6
6
|
import { field, type FieldDeclaration, type FieldMediaKind } from './fields';
|
|
7
7
|
import { DEFAULT_ICON_STYLE, ICON_STYLE_LABELS, ICON_STYLES, type IconStyleName } from './icons';
|
|
8
8
|
import { SEO_TEMPLATE_DEFAULTS } from './seo';
|
|
9
|
+
import { hasPermission, PERMISSIONS, type Principal } from './permissions';
|
|
9
10
|
|
|
10
11
|
/** Choices filled in by the host when a form renders, such as the list of roles. */
|
|
11
12
|
/** Where a setting's choices come from; `media` lists the library's images by their URL. */
|
|
12
13
|
export type SettingSource = 'roles' | 'pages' | 'categories' | 'timezones' | 'media';
|
|
13
14
|
/** String settings keep their scalar value while offering a richer editor. */
|
|
14
|
-
export type SettingControl = 'color' | 'file' | 'icon-style' | 'palette';
|
|
15
|
+
export type SettingControl = 'color' | 'file' | 'icon-style' | 'palette' | 'checklist';
|
|
15
16
|
|
|
16
17
|
export interface SettingDeclaration extends FieldDeclaration {
|
|
17
18
|
readonly source?: SettingSource;
|
|
18
|
-
/** color: a hex color; file: an HTTP(S) or root-relative file URL; icon-style and palette: an enum shown with a preview. */
|
|
19
|
+
/** color: a hex color; file: an HTTP(S) or root-relative file URL; icon-style and palette: an enum shown with a preview; checklist: the source's choices as checkboxes, stored as their values joined by commas. */
|
|
19
20
|
readonly control?: SettingControl;
|
|
20
21
|
/** file control: the kinds the media chooser lists first; other kinds remain available. */
|
|
21
22
|
readonly fileKinds?: readonly FieldMediaKind[];
|
|
@@ -50,6 +51,25 @@ export interface SettingsGroup {
|
|
|
50
51
|
readonly sections?: readonly SettingsSection[];
|
|
51
52
|
}
|
|
52
53
|
|
|
54
|
+
/** Role IDs separated by commas, such as `admin,editor`, or nothing. */
|
|
55
|
+
const ROLE_LIST = '(?:[A-Za-z0-9_-]{1,80}(?:,[A-Za-z0-9_-]{1,80}){0,19})?';
|
|
56
|
+
|
|
57
|
+
/** The roles a comma-separated setting names, such as `general.twoFactorRoles`. */
|
|
58
|
+
export function settingRoles(value: unknown): string[] {
|
|
59
|
+
return typeof value === 'string' ? [...new Set(value.split(',').map(role => role.trim()).filter(Boolean))] : [];
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Whether General settings ask this principal for two-step sign-in: someone who can use the
|
|
64
|
+
* dashboard, while `general.requireTwoFactor` is on, holding one of the roles
|
|
65
|
+
* `general.twoFactorRoles` names when it names any.
|
|
66
|
+
*/
|
|
67
|
+
export function twoFactorRequired(principal: Principal, settings: { readonly required: unknown; readonly roles: unknown }): boolean {
|
|
68
|
+
if (settings.required !== true || principal.kind !== 'user' || !hasPermission(principal, PERMISSIONS.dashboard)) return false;
|
|
69
|
+
const roles = settingRoles(settings.roles);
|
|
70
|
+
return !roles.length || principal.roles.some(role => roles.includes(role));
|
|
71
|
+
}
|
|
72
|
+
|
|
53
73
|
export const DATE_FORMATS = Object.freeze({ long: 'October 16, 2026', medium: 'Oct 16, 2026', iso: '2026-10-16', us: '10/16/2026', eu: '16/10/2026' });
|
|
54
74
|
export const TIME_FORMATS = Object.freeze({ '12h': '3:45 pm', '24h': '15:45' });
|
|
55
75
|
|
|
@@ -74,7 +94,8 @@ export const general: SettingsGroup = {
|
|
|
74
94
|
maintenance: { ...field.enum(['off', 'maintenance', 'soon'], { default: 'off', label: 'Maintenance mode', description: 'Visitors see a holding page with status 503 while people who can use the dashboard see the site. Search engines keep the pages indexed.' }),
|
|
75
95
|
choices: { off: 'Off: the site is public', maintenance: 'Maintenance: back soon', soon: 'Coming soon: not launched yet' } },
|
|
76
96
|
maintenanceMessage: field.text({ max: 2000, default: '', label: 'Holding page message', description: 'Shown under the site title; empty uses a sentence for the mode.' }),
|
|
77
|
-
requireTwoFactor: field.boolean({ default: false, label: 'Require two-step sign-in
|
|
97
|
+
requireTwoFactor: field.boolean({ default: false, label: 'Require two-step sign-in', description: 'Of everyone who can use the dashboard, or only of the roles chosen below. They add an authenticator app or a passkey before they can continue.' }),
|
|
98
|
+
twoFactorRoles: { ...field.string({ max: 800, default: '', pattern: ROLE_LIST, label: 'Only for these roles', description: 'Leave all unchecked to require it of everyone who can use the dashboard.' }), source: 'roles', control: 'checklist' },
|
|
78
99
|
favicon: { ...field.string({ max: 2000, default: '', pattern: '(?:https?://[^\\s]+|/[^\\s]*)?', label: 'Site icon', description: 'Shown in browser tabs and bookmarks: an SVG or a square PNG from the library.' }), source: 'media' },
|
|
79
100
|
appIcon: { ...field.string({ max: 2000, default: '', pattern: '(?:https?://[^\\s]+|/[^\\s]*)?', label: 'App icon', description: 'For home screens and the web app manifest: a square PNG of at least 512 pixels from the library; it is resized as needed.' }), source: 'media' },
|
|
80
101
|
logo: { ...field.string({ max: 2000, default: '', pattern: '(?:https?://[^\\s]+|/[^\\s]*)?', label: 'Logo', description: 'The site\'s logo in any shape, shown in the site header, on sign-in pages and in the dashboard. Search results use the square SEO logo.' }), source: 'media' },
|
|
@@ -327,6 +348,8 @@ export interface SiteSettings {
|
|
|
327
348
|
'general.timeFormat': keyof typeof TIME_FORMATS;
|
|
328
349
|
'general.weekStartsOn': 'sunday' | 'monday' | 'saturday';
|
|
329
350
|
'general.requireTwoFactor': boolean;
|
|
351
|
+
/** Role IDs separated by commas; empty for everyone who can use the dashboard. */
|
|
352
|
+
'general.twoFactorRoles': string;
|
|
330
353
|
'general.maintenance': 'off' | 'maintenance' | 'soon';
|
|
331
354
|
'general.maintenanceMessage': string;
|
|
332
355
|
'general.favicon': string;
|
|
@@ -91,4 +91,6 @@ export const cloudflareStorage: CmsStorage<CloudflareStorageBindings> = {
|
|
|
91
91
|
};
|
|
92
92
|
},
|
|
93
93
|
// Webhook deliveries use the Worker's own fetch, which cannot reach private networks.
|
|
94
|
+
// A request's subrequests are cancelled with it, so the CMS ends its database calls itself.
|
|
95
|
+
cancelsRequestIo: true,
|
|
94
96
|
};
|
package/src/storage/index.ts
CHANGED
|
@@ -27,4 +27,10 @@ export interface CmsStorage<Env = never> {
|
|
|
27
27
|
imageTransformer(env: Env): ImageTransformer | undefined;
|
|
28
28
|
/** The `fetch` of webhook deliveries; unset uses the runtime's own. */
|
|
29
29
|
readonly webhookFetch?: typeof fetch;
|
|
30
|
+
/**
|
|
31
|
+
* The runtime cancels a request's I/O when the request ends (Workers): a database call of a
|
|
32
|
+
* request that ended first never settles and keeps one of the client's 32 places for good.
|
|
33
|
+
* The CMS then ends a request's database calls when its visitor leaves or it fails.
|
|
34
|
+
*/
|
|
35
|
+
readonly cancelsRequestIo?: boolean;
|
|
30
36
|
}
|
package/src/theme.ts
CHANGED
|
@@ -991,7 +991,7 @@ export interface SiteTheme {
|
|
|
991
991
|
}
|
|
992
992
|
|
|
993
993
|
/** Template files that fill the theme's named slots; every other file is a specific template. */
|
|
994
|
-
const TEMPLATE_FILES: { readonly [stem: string]: keyof SiteTheme } = { layout: 'layout', entry: 'entry', archive: 'archive', home: 'home', search: 'search', 'not-found': 'notFound', head: 'head', password: 'password' };
|
|
994
|
+
const TEMPLATE_FILES: { readonly [stem: string]: keyof SiteTheme } = { layout: 'layout', entry: 'entry', archive: 'archive', home: 'home', search: 'search', 'not-found': 'notFound', head: 'head', password: 'password', members: 'members' };
|
|
995
995
|
/** Names a specific template can have. */
|
|
996
996
|
export const SPECIFIC_TEMPLATE = /^(?:entry-[a-z][a-z0-9_-]*|archive-[a-z][a-z0-9_-]*|term(?:-[a-z][a-z0-9_-]*)?|author)$/;
|
|
997
997
|
|
|
@@ -1056,7 +1056,7 @@ export function siteThemeProblems(theme: unknown): string[] {
|
|
|
1056
1056
|
const value = theme as { [name: string]: unknown };
|
|
1057
1057
|
const problems: string[] = [];
|
|
1058
1058
|
for (const name of ['layout', 'entry', 'archive']) if (typeof value[name] !== 'function') problems.push(`theme.${name} must be a function.`);
|
|
1059
|
-
for (const name of ['home', 'search', 'notFound', 'head']) if (value[name] !== undefined && typeof value[name] !== 'function') problems.push(`theme.${name} must be a function.`);
|
|
1059
|
+
for (const name of ['home', 'search', 'notFound', 'head', 'password', 'members']) if (value[name] !== undefined && typeof value[name] !== 'function') problems.push(`theme.${name} must be a function.`);
|
|
1060
1060
|
if (value.templates !== undefined) {
|
|
1061
1061
|
if (typeof value.templates !== 'object' || value.templates === null) problems.push('theme.templates must map template names to functions.');
|
|
1062
1062
|
else for (const [name, template] of Object.entries(value.templates)) {
|
package/src/version.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/** The version of this package. A test keeps it equal to `package.json`. */
|
|
2
|
-
export const CMS_VERSION = '0.9.
|
|
2
|
+
export const CMS_VERSION = '0.9.4';
|
package/app/src/cms/handoff.ts
DELETED
|
@@ -1,202 +0,0 @@
|
|
|
1
|
-
import type { Context } from 'hono';
|
|
2
|
-
import { deleteCookie, getCookie, setCookie } from 'hono/cookie';
|
|
3
|
-
import { NETWORK_ADMIN } from '@cossackframework/cms';
|
|
4
|
-
import { MAIN_SITE, networkSite, type ChildSession, type CmsHost, type CmsNetwork, type NetworkSite } from '@cossackframework/cms/server';
|
|
5
|
-
import { authSessions, SESSION_COOKIE_NAME } from '../auth';
|
|
6
|
-
import { siteUrl, type CmsBindings } from './index';
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* Sign-in for a network of sites. An added site's own sign-in pages sign in its site accounts.
|
|
10
|
-
* Network accounts sign in only on the network host (the main site), and the site gets its own
|
|
11
|
-
* child session back through a one-use code:
|
|
12
|
-
*
|
|
13
|
-
* 1. `<site>/auth/handoff?next=<path>` (the sign-in pages' network link) →
|
|
14
|
-
* `<network>/auth/handoff?site=<id>&next=<path>`.
|
|
15
|
-
* 2. Without a network session, the network keeps the request in a cookie and shows its sign-in;
|
|
16
|
-
* after any sign-in, the next page continues the handoff.
|
|
17
|
-
* 3. With one, the network issues a code bound to the site and the session, valid for a minute,
|
|
18
|
-
* and sends the visitor to `<site>/auth/handoff?code=…&state=…`, which trades it for a child
|
|
19
|
-
* session when `state` is the one the site set in this browser at step 1.
|
|
20
|
-
*
|
|
21
|
-
* A visitor who opens a site's dashboard without a session there goes through the same steps on
|
|
22
|
-
* their own, with `auto=1`: a network admin, or a member signed in on the network, arrives signed
|
|
23
|
-
* in without a click; anyone else comes back to the site's own sign-in, and the attempt is not
|
|
24
|
-
* repeated for a while (`cms_handoff_auto`), so a site account signs in there as before.
|
|
25
|
-
*/
|
|
26
|
-
const HANDOFF_COOKIE = 'cms_handoff';
|
|
27
|
-
/** Set by a site that started a handoff on its own: no second attempt until it expires. */
|
|
28
|
-
const AUTO_COOKIE = 'cms_handoff_auto';
|
|
29
|
-
/**
|
|
30
|
-
* Set by a site as it sends the visitor to the network, and sent back with the code: a code
|
|
31
|
-
* opened in a browser that did not start the handoff (a link someone else made with their own
|
|
32
|
-
* account) is refused, so nobody is signed in to another person's account.
|
|
33
|
-
*/
|
|
34
|
-
const STATE_COOKIE = 'cms_handoff_state';
|
|
35
|
-
const STATE = /^[0-9a-f]{32}$/;
|
|
36
|
-
/** The site paths a missing session starts a handoff for: the dashboard, which needs one. */
|
|
37
|
-
const AUTO_PATHS = /^\/dashboard(?:\/|$)/;
|
|
38
|
-
|
|
39
|
-
/** A path on the same site to go to afterwards; anything else is the dashboard. */
|
|
40
|
-
function nextPath(value: string | null | undefined): string {
|
|
41
|
-
return value && /^\/(?!\/)[^\s\\]*$/.test(value) ? value : '/dashboard';
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
function secure(c: Context): boolean {
|
|
45
|
-
return new URL(c.req.url).protocol === 'https:';
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
/**
|
|
49
|
-
* Handoff routes and redirects, before auth runs. Null lets the request through. Without
|
|
50
|
-
* APP_URL there is no network host to send sign-ins to, and each site signs in on its own host.
|
|
51
|
-
*/
|
|
52
|
-
export async function handoff(c: Context, network: CmsNetwork, site: NetworkSite): Promise<Response | null> {
|
|
53
|
-
const env = c.env as CmsBindings;
|
|
54
|
-
const url = new URL(c.req.url);
|
|
55
|
-
if (site.id !== MAIN_SITE) {
|
|
56
|
-
if (url.pathname === '/auth/handoff') {
|
|
57
|
-
if (url.searchParams.has('code')) return toSite(c, network, site);
|
|
58
|
-
// Sign in with a network account: on the network host, which hands the session back.
|
|
59
|
-
if (!env.APP_URL) return c.text('This network has no sign-in host: set APP_URL.', 404);
|
|
60
|
-
return c.redirect(toNetwork(env.APP_URL, site, nextPath(url.searchParams.get('next')), url.searchParams.get('auto') === '1', startState(c)));
|
|
61
|
-
}
|
|
62
|
-
// The dashboard without a live session here: the network may have one, so ask it once before the site's sign-in shows.
|
|
63
|
-
if (env.APP_URL && c.req.method === 'GET' && AUTO_PATHS.test(url.pathname) && !getCookie(c, AUTO_COOKIE) && !(await siteSession(c))) {
|
|
64
|
-
setCookie(c, AUTO_COOKIE, '1', { path: '/', httpOnly: true, sameSite: 'Lax', maxAge: 300, secure: secure(c) });
|
|
65
|
-
return c.redirect(toNetwork(env.APP_URL, site, nextPath(url.pathname + url.search), true, startState(c)));
|
|
66
|
-
}
|
|
67
|
-
return null;
|
|
68
|
-
}
|
|
69
|
-
if (url.pathname === '/auth/handoff') return fromNetwork(c, network);
|
|
70
|
-
// After signing in on the network host, continue the handoff the visitor came for.
|
|
71
|
-
const pending = getCookie(c, HANDOFF_COOKIE);
|
|
72
|
-
if (pending && !url.pathname.startsWith('/auth/') && !url.pathname.startsWith('/api/') && await networkSession(c, network)) {
|
|
73
|
-
deleteCookie(c, HANDOFF_COOKIE, { path: '/' });
|
|
74
|
-
const { site: id, next, state } = parsePending(pending);
|
|
75
|
-
if (id) return c.redirect(`/auth/handoff?site=${encodeURIComponent(id)}&next=${encodeURIComponent(next)}&state=${encodeURIComponent(state)}`);
|
|
76
|
-
}
|
|
77
|
-
return null;
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
/** The network's handoff address for a site: where the site sends a visitor to sign in, or to try their network session (`auto`). */
|
|
81
|
-
function toNetwork(appUrl: string, site: Pick<NetworkSite, 'id'>, next: string, auto: boolean, state: string): string {
|
|
82
|
-
const target = new URL('/auth/handoff', appUrl);
|
|
83
|
-
target.searchParams.set('site', site.id);
|
|
84
|
-
target.searchParams.set('next', next);
|
|
85
|
-
target.searchParams.set('state', state);
|
|
86
|
-
if (auto) target.searchParams.set('auto', '1');
|
|
87
|
-
return target.toString();
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
/** A new handoff state for this browser, kept in a cookie on the site for ten minutes. */
|
|
91
|
-
function startState(c: Context): string {
|
|
92
|
-
const state = [...crypto.getRandomValues(new Uint8Array(16))].map(byte => byte.toString(16).padStart(2, '0')).join('');
|
|
93
|
-
setCookie(c, STATE_COOKIE, state, { path: '/auth/handoff', httpOnly: true, sameSite: 'Lax', maxAge: 600, secure: secure(c) });
|
|
94
|
-
return state;
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
/** Whether the request carries a live session of this site. */
|
|
98
|
-
async function siteSession(c: Context): Promise<boolean> {
|
|
99
|
-
const id = getCookie(c, SESSION_COOKIE_NAME);
|
|
100
|
-
return !!id && !!(await authSessions.validate(id, c).catch(() => null));
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
/**
|
|
104
|
-
* On the network host: issue a code for the site, or sign in first. An attempt the site started
|
|
105
|
-
* on its own (`auto`) never shows the network's sign-in: without a session, or for an account
|
|
106
|
-
* that is not a member, the visitor goes back to the site's own sign-in.
|
|
107
|
-
*/
|
|
108
|
-
async function fromNetwork(c: Context, network: CmsNetwork): Promise<Response> {
|
|
109
|
-
const env = c.env as CmsBindings;
|
|
110
|
-
const url = new URL(c.req.url);
|
|
111
|
-
const id = url.searchParams.get('site') ?? '';
|
|
112
|
-
const next = nextPath(url.searchParams.get('next'));
|
|
113
|
-
const auto = url.searchParams.get('auto') === '1';
|
|
114
|
-
const state = url.searchParams.get('state') ?? '';
|
|
115
|
-
if (!STATE.test(state)) return c.text('Start signing in from the site.', 400);
|
|
116
|
-
const record = await network.sites.get(id);
|
|
117
|
-
if (!record || (record.status !== 'active' && record.status !== 'archived')) return c.text('No site at this address.', 404);
|
|
118
|
-
const site = networkSite(record);
|
|
119
|
-
const siteLogin = () => c.redirect(new URL('/auth/login', siteUrl(env, site)).toString());
|
|
120
|
-
const session = await networkSession(c, network);
|
|
121
|
-
if (!session) {
|
|
122
|
-
if (auto) return siteLogin();
|
|
123
|
-
setCookie(c, HANDOFF_COOKIE, JSON.stringify({ site: id, next, state }), { path: '/', httpOnly: true, sameSite: 'Lax', maxAge: 600, secure: secure(c) });
|
|
124
|
-
return c.redirect(url.searchParams.get('register') === '1' ? '/auth/register' : '/auth/login');
|
|
125
|
-
}
|
|
126
|
-
deleteCookie(c, HANDOFF_COOKIE, { path: '/' });
|
|
127
|
-
const account = await network.main.accounts.get(session.userId);
|
|
128
|
-
if (!account || account.status !== 'active') return auto ? siteLogin() : c.redirect('/auth/login');
|
|
129
|
-
if (account.networkRole !== NETWORK_ADMIN && !(await network.hostOf(site).users.get(account.id))) {
|
|
130
|
-
if (auto) return siteLogin();
|
|
131
|
-
return c.text(`Your account is not a member of ${record.name}. Ask its administrator to add you.`, 403);
|
|
132
|
-
}
|
|
133
|
-
const code = await network.handoffs.issue({ session: session.reference, user: account.id, site: site.id });
|
|
134
|
-
const target = new URL('/auth/handoff', siteUrl(c.env as CmsBindings, site));
|
|
135
|
-
target.searchParams.set('code', code);
|
|
136
|
-
target.searchParams.set('next', next);
|
|
137
|
-
target.searchParams.set('state', state);
|
|
138
|
-
return c.redirect(target.toString());
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
/** On a site: trade the code for a child session in the site's own database. */
|
|
142
|
-
async function toSite(c: Context, network: CmsNetwork, site: NetworkSite): Promise<Response> {
|
|
143
|
-
const url = new URL(c.req.url);
|
|
144
|
-
// Only the browser that started this handoff may finish it; the code is left unused otherwise.
|
|
145
|
-
const state = getCookie(c, STATE_COOKIE) ?? '';
|
|
146
|
-
if (!STATE.test(state) || url.searchParams.get('state') !== state) return c.html('<p>This sign-in did not start in this browser. <a href="/auth/login">Sign in again</a>.</p>', 400);
|
|
147
|
-
deleteCookie(c, STATE_COOKIE, { path: '/auth/handoff' });
|
|
148
|
-
const handoff = await network.handoffs.consume(url.searchParams.get('code') ?? '', site.id);
|
|
149
|
-
if (!handoff) return c.html('<p>This sign-in link expired or was used. <a href="/auth/login">Sign in again</a>.</p>', 400);
|
|
150
|
-
const cms = network.hostOf(site);
|
|
151
|
-
// A network admin may open any site; the first visit copies them in without a role, so their writes have an author.
|
|
152
|
-
if (handoff.networkRole === NETWORK_ADMIN) await cms.users.addMember(handoff.user);
|
|
153
|
-
if (!(await cms.users.get(handoff.user))) return c.text('Your account is not a member of this site.', 403);
|
|
154
|
-
// The child session used a second factor only if the network session did: the site's own two-step requirement then asks it of the child.
|
|
155
|
-
c.set('cms.child', { parentId: handoff.session, networkRole: handoff.networkRole, expiresAt: handoff.expiresAt, secondFactor: handoff.secondFactor });
|
|
156
|
-
const { headers } = await authSessions.create(handoff.user, c);
|
|
157
|
-
headers.forEach((value, name) => c.header(name, value, { append: true }));
|
|
158
|
-
deleteCookie(c, AUTO_COOKIE, { path: '/' });
|
|
159
|
-
return c.redirect(nextPath(url.searchParams.get('next')));
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
/** On the network host, the site a visitor is signing in to (active or archived), or null. */
|
|
163
|
-
export async function pendingSite(c: Context, network: CmsNetwork): Promise<NetworkSite | null> {
|
|
164
|
-
const id = parsePending(getCookie(c, HANDOFF_COOKIE) ?? '').site;
|
|
165
|
-
if (!id || c.get('site')?.id !== MAIN_SITE) return null;
|
|
166
|
-
const record = await network.sites.get(id);
|
|
167
|
-
return record && (record.status === 'active' || record.status === 'archived') ? networkSite(record) : null;
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
/** On the network host, the site a visitor is registering for, or null. */
|
|
171
|
-
export async function handoffSite(c: Context, network: CmsNetwork): Promise<CmsHost | null> {
|
|
172
|
-
const id = parsePending(getCookie(c, HANDOFF_COOKIE) ?? '').site;
|
|
173
|
-
if (!id || c.get('site')?.id !== MAIN_SITE) return null;
|
|
174
|
-
const record = await network.sites.get(id);
|
|
175
|
-
return record && record.status === 'active' ? network.hostOf(networkSite(record)) : null;
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
/** The visitor's live session on the network host, with its public reference. */
|
|
179
|
-
async function networkSession(c: Context, network: CmsNetwork): Promise<{ userId: string; reference: string } | null> {
|
|
180
|
-
const id = getCookie(c, SESSION_COOKIE_NAME);
|
|
181
|
-
if (!id) return null;
|
|
182
|
-
const record = await authSessions.validate(id, c).catch(() => null);
|
|
183
|
-
const reference = record ? await network.main.authSessions.publicReference(id) : null;
|
|
184
|
-
return record && reference ? { userId: record.userId, reference } : null;
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
function parsePending(value: string): { site: string | null; next: string; state: string } {
|
|
188
|
-
try {
|
|
189
|
-
const parsed = JSON.parse(value) as { site?: unknown; next?: unknown; state?: unknown };
|
|
190
|
-
return { site: typeof parsed.site === 'string' && /^[a-z0-9-]{1,63}$/.test(parsed.site) ? parsed.site : null, next: nextPath(typeof parsed.next === 'string' ? parsed.next : null),
|
|
191
|
-
state: typeof parsed.state === 'string' && STATE.test(parsed.state) ? parsed.state : '' };
|
|
192
|
-
} catch { return { site: null, next: '/dashboard', state: '' }; }
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
declare module 'hono' {
|
|
196
|
-
interface ContextVariableMap {
|
|
197
|
-
/** A handoff in progress: the next session created on this request is a child session. */
|
|
198
|
-
'cms.child': ChildSession;
|
|
199
|
-
/** The network role a child session copied at its handoff. */
|
|
200
|
-
'cms.networkRole': string | null;
|
|
201
|
-
}
|
|
202
|
-
}
|