@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
package/app/src/auth.ts CHANGED
@@ -1,36 +1,81 @@
1
1
  // src/auth.ts
2
2
  //
3
- // Authentication on the CMS. Users, roles, sessions and reset tokens live in RomeDB host
4
- // tables; the auth library owns password hashing, credential verification, session expiry,
5
- // rotation and cookies. This module exports the same functions as the database variant, so
6
- // the auth and dashboard pages are shared between both.
3
+ // Application account/storage composition. The auth library owns password
4
+ // hashing, credential verification, session expiry, rotation and cookies.
5
+ // Password reset delivery, user models and role lookup remain application-owned.
6
+ //
7
+ // All data access uses Active Record models scoped by the ORM middleware.
8
+ // Runtime bindings (the send_email
9
+ // binding, env vars) are read via the global `binding()` / `env()` helpers,
10
+ // so credential and reset helpers need no Hono `Context`. Session operations
11
+ // receive the context for request metadata and cookie handling.
7
12
 
8
- import { getCookie } from 'hono/cookie';
13
+ import { getCookie, setCookie } from 'hono/cookie';
9
14
  import type { Context } from 'hono';
10
- import { createAuth, createOAuth, createSessionManager, OAuthError, totpUri, type AuthSessionRecord, type OAuthKit, type OAuthUser, type TokenSet } from '@cossackframework/auth';
15
+ import { createAuth, createCredentialVerifier, createOAuth, createSessionManager, hashPassword, OAuthError, totpUri, type AuthSessionRecord, type OAuthKit, type OAuthStateStore, type OAuthUser, type TokenSet } from '@cossackframework/auth';
11
16
  import {
12
- passkeyAuthenticationOptions, passkeyRegistrationOptions, verifyPasskeyAuthentication, verifyPasskeyRegistration,
13
- type AuthenticationResponseJSON, type PasskeyConfig, type PublicKeyCredentialCreationOptionsJSON, type PublicKeyCredentialRequestOptionsJSON, type RegistrationResponseJSON,
17
+ passkeyAuthenticationOptions, passkeyRegistrationOptions, verifyPasskeyAuthentication, verifyPasskeyRegistration,
18
+ type AuthenticationResponseJSON, type PasskeyConfig, type PublicKeyCredentialCreationOptionsJSON, type PublicKeyCredentialRequestOptionsJSON, type RegistrationResponseJSON,
14
19
  } from '@cossackframework/auth/passkeys';
20
+ export { hashPassword, verifyPassword } from '@cossackframework/auth';
21
+ import { In, LessThan, MoreThan, sql } from '@cossackframework/database';
15
22
  import { ClientVisibleError, getClientIp, getRequestContext } from '@cossackframework/core';
16
- import { ANONYMOUS, hasPermission, holdsAll, isCmsError, isNetworkAdmin, PERMISSIONS, type Principal } from '@cossackframework/cms';
17
- import { MAIN_SITE, networkSite, randomToken, RESET_REQUESTS, sha256Hex, type ApiToken, type CmsHost, type CmsMember, type SecurityStatus as AccountSecurity } from '@cossackframework/cms/server';
18
23
  import { renderSVG } from 'uqr';
19
- import { currentCms, networkFor, type CmsBindings } from './cms/index';
20
- import { handoffSite, pendingSite } from './cms/handoff';
21
- import { mailOrigin } from './cms/seo';
24
+ import { uuidv7 } from './lib/uuid';
25
+ import { authOptions } from './auth-options';
26
+ import { mailer } from './mail';
27
+ import { avatarUploads as storedAvatars, storeAvatar } from './avatars';
28
+ import { authEvents } from './auth-events';
29
+ import { accounts, currentTenant, hostName, inTenant, mainHost, sharedSignIn, tenantOfHost, tenantOrigin } from './tenants';
30
+ import { TenantHandoff } from '@/models/TenantHandoff';
31
+ import { TenantSession } from '@/models/TenantSession';
32
+ import { Tenant } from '@/models/Tenant';
33
+ import { asMainAccount, asTenantAccount, markTenantAccountRequest, tenantAccountHome, withTenant } from './tenants';
34
+ import { ALL_PERMISSIONS } from './lib/permissions';
35
+ import { mainSiteName, siteName } from './brand';
36
+ import * as security from './services/security';
37
+ import * as apiTokens from './services/api-tokens';
38
+ import type { ApiToken } from './services/api-tokens';
39
+ // The models are the project's: its schema, its migrations.
40
+ import { User, type RoleAssignment } from '@/models/User';
41
+ import { Role } from '@/models/Role';
42
+ import { UserRole } from '@/models/UserRole';
43
+ import { Session, type SessionKind } from '@/models/Session';
44
+ import { OAuthAccount } from '@/models/OAuthAccount';
45
+ import { TenantMember } from '@/models/TenantMember';
22
46
 
23
47
  const SESSION_COOKIE = 'session_id';
24
48
  const SESSION_TTL_SECONDS = 60 * 60 * 24 * 7; // 7 days
25
49
 
26
- // --- Types -----------------------------------------------------------------
27
- export interface RoleAssignment {
28
- id: string;
29
- name: string;
30
- permissions: string[];
50
+ // `sessions.kind` separates sign-in sessions from the single-use tokens kept in the same table.
51
+ // Session listings show only sign-in rows. `meta` is the project's own.
52
+ const AUTH: SessionKind = 'auth';
53
+
54
+ const warnedSessionErrors = new Set<string>();
55
+
56
+ /**
57
+ * Session lookup must never make a public request fail just because the
58
+ * database binding or auth migrations are not ready yet. The auth middleware
59
+ * treats the request as a guest and warns once per isolate for each distinct
60
+ * kind of error, naming its type and code, so a query bug is not mistaken for
61
+ * a missing database.
62
+ */
63
+ function warnAboutSessionDatabase(error: unknown): void {
64
+ // The message can hold connection details or secrets, so only the error's
65
+ // type and code are printed.
66
+ const name = error instanceof Error ? error.name : typeof error;
67
+ const code = (error as { code?: unknown } | null)?.code;
68
+ const kind = typeof code === 'string' || typeof code === 'number' ? `${name} ${code}` : name;
69
+ if (warnedSessionErrors.has(kind)) return;
70
+ warnedSessionErrors.add(kind);
71
+ console.warn(
72
+ `[Cossack Auth] Session lookup failed with ${kind}; continuing as guest.\n` +
73
+ 'If the database is not set up, configure the DB binding and run `pnpm migrate` before using auth.',
74
+ );
31
75
  }
32
76
 
33
- /** The safe user shape exposed to pages (`this.user`). */
77
+ // --- Types -----------------------------------------------------------------
78
+ /** The safe user shape exposed to pages (`this.user`) — no password_hash. */
34
79
  export interface PublicUser {
35
80
  id: string;
36
81
  email: string;
@@ -38,157 +83,356 @@ export interface PublicUser {
38
83
  avatar: string | null;
39
84
  meta: Record<string, unknown> | null;
40
85
  roles: RoleAssignment[];
41
- /** What this user may do in the CMS, for repositories and permission checks. */
42
- principal: Principal;
86
+ /** A network administrator: every permission in every tenant, and the list of tenants. */
87
+ networkAdmin?: boolean;
43
88
  /** Set by `registerUser` when the account waits for the email's confirmation link instead of signing in. */
44
89
  verification?: 'sent';
45
90
  /** The account waits for an administrator's approval before it can sign in. */
46
91
  approval?: 'pending';
47
92
  }
48
93
 
49
- declare module '@cossackframework/core' {
50
- interface User {
51
- id: string;
52
- email: string;
53
- name: string;
54
- avatar: string | null;
55
- meta: Record<string, unknown> | null;
56
- roles: RoleAssignment[];
57
- principal: Principal;
94
+ /** The role a network administrator holds everywhere. It is not stored: the account's flag gives it. */
95
+ export const NETWORK_ADMIN_ROLE: RoleAssignment = Object.freeze({ id: 'network_admin', name: 'network_admin', permissions: ['*'] }) as RoleAssignment;
96
+
97
+ /** `u` is the account's row, from the main database. */
98
+ function publicUser(u: User, roles: RoleAssignment[] = []): PublicUser {
99
+ const admin = u.networkAdmin === true;
100
+ return { id: u.id, email: u.email, name: u.name ?? '', avatar: u.avatar, meta: u.meta,
101
+ roles: admin ? [...roles.filter((role) => role.id !== NETWORK_ADMIN_ROLE.id), NETWORK_ADMIN_ROLE] : roles, ...(admin ? { networkAdmin: true } : {}) };
102
+ }
103
+
104
+ // --- Roles -----------------------------------------------------------------
105
+ // Reads a user's assigned roles (with parsed permissions) by joining
106
+ // user_roles -> roles. Used by resolveUserById so c.get('user').roles is
107
+ // available to the authorizer (src/services/rbac.ts) and the dashboard nav.
108
+ async function rolesHere(userId: string): Promise<RoleAssignment[]> {
109
+ const rows = (await sql<{ id: string; name: string; permissions: string | string[] | null }>`
110
+ SELECT roles.id, roles.name, roles.permissions
111
+ FROM user_roles
112
+ INNER JOIN roles ON roles.id = user_roles.role_id
113
+ WHERE user_roles.user_id = ${userId}
114
+ `).rows;
115
+ return rows.map((r) => ({
116
+ id: r.id,
117
+ name: r.name,
118
+ permissions: parsePermissions(r.permissions),
119
+ }));
120
+ }
121
+
122
+ // A JSON column arrives as text from SQLite and already parsed from PostgreSQL and MySQL.
123
+ function parsePermissions(raw: string | string[] | null): string[] {
124
+ if (!raw) return [];
125
+ try {
126
+ const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw;
127
+ return Array.isArray(parsed) ? parsed.filter((p) => typeof p === 'string') : [];
128
+ } catch {
129
+ return [];
58
130
  }
59
131
  }
60
132
 
61
- /** The host on the given context, or the current request's. */
62
- function cms(c?: Context): CmsHost {
63
- return (c?.get('cms') as CmsHost | undefined) ?? currentCms();
133
+ /**
134
+ * A user's stored roles where the request is. With tenants, a tenant's member has the roles
135
+ * the tenant gave them, and anyone else has none there. A network administrator's role comes
136
+ * from the account (`publicUser`).
137
+ */
138
+ async function loadUserRoles(userId: string): Promise<RoleAssignment[]> {
139
+ if (!currentTenant()) return rolesHere(userId);
140
+ return await memberOfTenant(userId) ? inTenant(() => rolesHere(userId)) : [];
141
+ }
142
+
143
+ /** In a tenant's request: whether the ID is an account of this tenant only. */
144
+ async function tenantAccount(userId: string): Promise<boolean> {
145
+ if (!currentTenant()) return false;
146
+ return inTenant(async () => (await User.findOne({ where: { id: userId } }))?.tenantAccount === true);
147
+ }
148
+
149
+ /** Run account code where the account lives: this tenant's database for its own accounts, the main one otherwise. */
150
+ async function accountOf<T>(userId: string, work: () => Promise<T>): Promise<T> {
151
+ return await tenantAccount(userId) ? asTenantAccount(() => accounts(work)) : asMainAccount(() => accounts(work));
152
+ }
153
+
154
+ /**
155
+ * Run code about the account with this email, as someone on this host would mean it: on a
156
+ * tenant's host its own account with the email, else the main account (`elsewhere` is the
157
+ * answer where this host does not serve main accounts).
158
+ */
159
+ async function accountByEmail<T>(email: string, work: () => Promise<T>, elsewhere: T): Promise<T> {
160
+ const own = currentTenant() ? await inTenant(async () => (await User.findOne({ where: { email } }))?.tenantAccount === true) : false;
161
+ if (own) return asTenantAccount(work);
162
+ // With shared sign-in a tenant's host serves its own accounts only: a main account signs in,
163
+ // and resets its password, on the main host.
164
+ if (currentTenant() && sharedSignIn) return elsewhere;
165
+ return asMainAccount(work);
166
+ }
167
+
168
+ /**
169
+ * Run code that starts from a token (a link, a challenge): in the tenant's database first on
170
+ * a tenant's host, and in the main one when that found nothing.
171
+ */
172
+ async function accountByToken<T>(work: () => Promise<T>, nothing: (value: T) => boolean): Promise<T> {
173
+ if (!currentTenant()) return work();
174
+ const own = await asTenantAccount(work);
175
+ return nothing(own) ? asMainAccount(work) : own;
176
+ }
177
+
178
+ /**
179
+ * On a tenant's host a member's shared account is its owner's: only they change its profile,
180
+ * sign-in methods and application passwords there. The tenant's own accounts are the tenant's.
181
+ */
182
+ async function requireOwnerOfShared(userId: string): Promise<void> {
183
+ if (!currentTenant() || await tenantAccount(userId)) return;
184
+ const caller = (getRequestContext()?.get('user') as PublicUser | undefined)?.id;
185
+ if (caller !== userId) throw new ClientVisibleError(authOptions.accountLabels.sharedNotice);
186
+ }
187
+
188
+ /** Whether the account is a network administrator: its own flag, in the main database. */
189
+ async function isNetworkAdmin(userId: string): Promise<boolean> {
190
+ return asMainAccount(() => accounts(async () => (await User.findOne({ where: { id: userId } }))?.networkAdmin === true));
191
+ }
192
+
193
+ /** Whether the tenant of this request has the account as an active member. Always true without a tenant. */
194
+ async function memberOfTenant(userId: string): Promise<boolean> {
195
+ if (!currentTenant()) return true;
196
+ return inTenant(async () => (await User.findOne({ where: { id: userId } }))?.status === 'active');
197
+ }
198
+
199
+ /** Whether the account may act where the request is: a member of the tenant, or a network administrator. */
200
+ async function allowedHere(userId: string): Promise<boolean> {
201
+ if (!currentTenant() || await memberOfTenant(userId)) return true;
202
+ return isNetworkAdmin(userId);
203
+ }
204
+
205
+ // --- Session create / validate / resolve ----------------------------------
206
+ // Captures the request's origin metadata (IP, User-Agent, geo) for session
207
+ // tracking. location uses Cloudflare request.cf (country/city); off-CF it's null.
208
+ function captureRequestInfo(c: Context): { ip: string | null; userAgent: string | null; location: string | null } {
209
+ const ip = c.req.header('cf-connecting-ip') || c.req.header('x-forwarded-for')?.split(',')[0].trim() || null;
210
+ const userAgent = c.req.header('user-agent') || null;
211
+ const cf = (c.req.raw as Request & { cf?: { country?: string; city?: string } }).cf;
212
+ const location = cf?.country ? [cf.city, cf.country].filter(Boolean).join(', ') : null;
213
+ return { ip, userAgent, location };
214
+ }
215
+
216
+ function authSession(row: Session | null): AuthSessionRecord | null {
217
+ if (!row || !row.userId || row.kind !== 'auth') return null;
218
+ return { id: row.id, userId: row.userId, kind: 'auth',
219
+ createdAt: row.createdAt.getTime(), expiresAt: row.expiresAt.getTime() };
220
+ }
221
+
222
+ /**
223
+ * Run session code where this request's sessions are: a tenant keeps its sessions in its own
224
+ * database, and the main host in the main one. `auth.sessionHome` set to `main` reads the main
225
+ * host's sessions from a tenant's request (the shared sign-in's code names one).
226
+ */
227
+ function sessions<T>(work: () => Promise<T>): Promise<T> {
228
+ return getRequestContext()?.get('auth.sessionHome' as never) === 'main' ? accounts(work) : inTenant(work);
229
+ }
230
+
231
+
232
+ /** End the sessions that tenants' hosts made from a main session, named by its public ID. Called in any scope. */
233
+ async function endReached(publicId: string): Promise<void> {
234
+ await accounts(async () => {
235
+ const reached = await TenantSession.find({ where: { sessionPublicId: publicId }, take: 500 });
236
+ for (const entry of reached) {
237
+ const tenant = await Tenant.findOne({ where: { id: entry.tenantId } });
238
+ if (tenant) await withTenant(tenant, async () => { await sql`DELETE FROM sessions WHERE parent_id = ${publicId} AND kind = ${AUTH}`; }).catch((error) => console.warn(`[tenants] could not end the sessions of ${tenant.slug}`, error));
239
+ }
240
+ if (reached.length) await TenantSession.delete({ sessionPublicId: publicId });
241
+ });
64
242
  }
65
243
 
66
- function publicUser(user: CmsMember): PublicUser {
67
- return {
68
- id: user.id, email: user.email, name: user.name, avatar: user.avatar, meta: null,
69
- roles: user.assignments.map(role => ({ id: role.id, name: role.name, permissions: [...role.permissions] })),
70
- principal: user.principal,
71
- };
244
+ /**
245
+ * On the main host, after sessions of a user were ended there: end what tenants' hosts made
246
+ * from them. The session `keptId` (the caller's own) and what was made from it stay.
247
+ */
248
+ async function endReachedOfUser(userId: string, keptId: string): Promise<void> {
249
+ if (currentTenant() || !authOptions.tenants.enabled) return;
250
+ await accounts(async () => {
251
+ const kept = keptId ? (await Session.findOne({ where: { id: keptId } }))?.publicId ?? null : null;
252
+ const reached = new Set((await TenantSession.find({ where: { userId }, take: 2000 })).map(entry => entry.sessionPublicId));
253
+ for (const publicId of reached) if (publicId !== kept) await endReached(publicId);
254
+ });
72
255
  }
73
256
 
74
257
  /**
75
- * The member a signed-in account acts as on this site, or null when it is not one or is
76
- * disabled. On a site other than the main one, the child session's network role stands in for
77
- * the account, so the request reads only the site's database.
258
+ * End an account's sessions on every host: the main one and each tenant it is a member of.
259
+ * For a changed password and a removed account. Called in the main database's scope.
78
260
  */
79
- async function member(id: string, c?: Context): Promise<PublicUser | null> {
80
- const context = c ?? getRequestContext();
81
- const child = context?.get('site')?.id !== MAIN_SITE ? context?.get('cms.networkRole') : undefined;
82
- const user = await cms(c).users.resolve(id, child === undefined ? undefined : { networkRole: child });
83
- return user ? publicUser(user) : null;
261
+ async function endSessionsEverywhere(userId: string): Promise<void> {
262
+ await sql`DELETE FROM sessions WHERE user_id = ${userId} AND kind = ${AUTH}`;
263
+ if (!authOptions.tenants.enabled) return;
264
+ const memberships = await TenantMember.find({ where: { userId }, take: 500 });
265
+ for (const membership of memberships) {
266
+ const tenant = await Tenant.findOne({ where: { id: membership.tenantId } });
267
+ if (tenant) await withTenant(tenant, async () => { await sql`DELETE FROM sessions WHERE user_id = ${userId} AND kind = ${AUTH}`; }).catch((error) => console.warn(`[tenants] could not end the sessions of ${tenant.slug}`, error));
268
+ }
269
+ await TenantSession.delete({ userId });
84
270
  }
85
271
 
86
- // --- Sessions --------------------------------------------------------------
87
272
  export const authSessions = createSessionManager({
88
273
  ttlSeconds: SESSION_TTL_SECONDS,
89
274
  cookie: { name: SESSION_COOKIE },
90
275
  store: {
91
- create: (record, c) => {
92
- // A handoff in progress makes the session a child of the network session.
93
- const child = (c as Context).get('cms.child');
94
- // createSession() says whether this sign-in used a second factor; a child session copies its network session's.
95
- const secondFactor = (c as Context).get('cms.signInSecondFactor') === true;
96
- // Every sign-in ends here, whatever its method: plugins hear of it through cms.user.signed-in,
97
- // queued in the session's own write.
98
- return (async () => {
99
- const host = cms(c);
100
- const user = await host.users.get(record.userId).catch(() => null);
101
- const also = user ? [await host.userSignedInStatement(user, record.id)] : [];
102
- const result = child ? await host.authSessions.createChild(record, child, c, { also }) : await host.authSessions.create(record, c, { secondFactor, also });
103
- if (also.length) host.outboxWritten();
104
- return result;
105
- })();
276
+ async create(record, c) {
277
+ // A tenant's host signs in its members only.
278
+ if (!await allowedHere(record.userId)) throw new SignInMemberError(currentTenant()!.name);
279
+ const { ip, userAgent, location } = captureRequestInfo(c);
280
+ // Set by completeTenantHandoff(): the public ID of the main host's session this one is made from.
281
+ const parent = (c.get('auth.sessionParent') as string | undefined) ?? null;
282
+ await sessions(() => Session.insert({ id: record.id, publicId: crypto.randomUUID(), userId: record.userId, data: null,
283
+ createdAt: new Date(record.createdAt), expiresAt: new Date(record.expiresAt),
284
+ kind: AUTH, meta: null, ipAddress: ip, userAgent, location,
285
+ // Set by createSession() for the session it is about to store.
286
+ secondFactor: c.get('auth.signInSecondFactor') === true, parentId: parent }));
287
+ // The main database remembers which tenants the main session reached, to end them with it.
288
+ const tenant = currentTenant();
289
+ if (parent && tenant) await accounts(() => TenantSession.upsert({ sessionPublicId: parent, tenantId: tenant.id, userId: record.userId, createdAt: new Date() }, ['sessionPublicId', 'tenantId']));
290
+ await authEvents.signedIn({ id: record.userId });
106
291
  },
107
- read: async (id, c) => {
108
- const session = await cms(c).authSessions.read(id, c);
109
- if (session?.parentId) (c as Context).set('cms.networkRole', session.networkRole);
110
- if (session) (c as Context).set('cms.sessionSecondFactor', session.secondFactor);
111
- return session;
292
+ async read(id) { return authSession(await sessions(() => Session.findOne({ where: { id } }))); },
293
+ async replace(expected, replacement, now) {
294
+ // One SQL statement owns rotation. Match the complete prior record and
295
+ // auth purpose so concurrent rotation or revocation can have only one winner.
296
+ // Pass Date values: the sql tag encodes them in the column's stored format.
297
+ const result = await sessions(async () => sql`
298
+ UPDATE sessions SET id = ${replacement.id},
299
+ created_at = ${new Date(replacement.createdAt)},
300
+ expires_at = ${new Date(replacement.expiresAt)}
301
+ WHERE id = ${expected.id} AND user_id = ${expected.userId}
302
+ AND created_at = ${new Date(expected.createdAt)}
303
+ AND expires_at = ${new Date(expected.expiresAt)}
304
+ AND expires_at > ${new Date(Math.max(now, Date.now()))}
305
+ AND kind = ${AUTH}
306
+ `);
307
+ // Sessions made from this one name its public ID, which stays.
308
+ return result.meta.rowsAffected === 1;
309
+ },
310
+ async revoke(id) {
311
+ const row = authOptions.tenants.enabled ? await sessions(() => Session.findOne({ where: { id } })) : null;
312
+ await sessions(async () => sql`DELETE FROM sessions WHERE id = ${id} AND kind = ${AUTH}`);
313
+ if (!row || row.kind !== 'auth') return;
314
+ // Signing out anywhere ends the main host's session and every session made from it.
315
+ const made = currentTenant() ? row.parentId : null;
316
+ if (made) await accounts(async () => sql`DELETE FROM sessions WHERE public_id = ${made} AND kind = ${AUTH}`);
317
+ const family = made ?? (currentTenant() ? null : row.publicId);
318
+ if (family) await endReached(family);
112
319
  },
113
- replace: (expected: AuthSessionRecord, replacement: AuthSessionRecord, now: number, c) => cms(c).authSessions.replace(expected, replacement, now, c),
114
- revoke: (id, c) => cms(c).authSessions.revoke(id, c),
115
320
  },
116
321
  });
117
322
 
118
- async function sessionFingerprint(token: string): Promise<string> {
119
- const bytes = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(token)));
120
- return Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('');
121
- }
122
-
123
323
  export const auth = createAuth<PublicUser>({
124
324
  realtime: {
125
325
  key: 'cossack.session',
126
- async capture(sessionId, _userId, c) {
127
- // The public reference survives rotation; the fingerprint does not.
128
- const reference = await cms(c).authSessions.publicReference(sessionId);
129
- if (!reference) throw new Error('Session ended before subscription.');
130
- return { reference, fingerprint: await sessionFingerprint(sessionId) };
131
- },
326
+ capture: (sessionId, userId) => sessions(async () => {
327
+ const stored = await Session.findOne({ where: { id: sessionId } });
328
+ const row = stored ? await sessionWithReference(stored, userId) : null;
329
+ if (!row) throw new Error('Session ended before subscription.');
330
+ return { reference: row.publicId, fingerprint: await sessionFingerprint(sessionId) };
331
+ }),
132
332
  async validate(data, c) {
133
- const { reference, fingerprint } = (data ?? {}) as { reference?: unknown; fingerprint?: unknown };
134
- if (typeof reference !== 'string' || typeof fingerprint !== 'string' || !/^[0-9a-f]{64}$/.test(fingerprint)) return null;
135
- const row = await cms(c).authSessions.findByReference(reference);
136
- if (!row || row.expiresAt <= Date.now() || await sessionFingerprint(row.id) !== fingerprint) return null;
137
- c.set('cms.sessionSecondFactor', row.secondFactor);
138
- return row.userId;
333
+ if (!data || typeof data !== 'object' || Array.isArray(data)) return null;
334
+ const { reference, fingerprint } = data as { reference?: unknown; fingerprint?: unknown };
335
+ if (typeof reference !== 'string' || !PUBLIC_SESSION_REFERENCE.test(reference) ||
336
+ typeof fingerprint !== 'string' || !/^[0-9a-f]{64}$/.test(fingerprint)) return null;
337
+ const row = await sessions(() => Session.findOne({ where: { publicId: reference } }));
338
+ const active = row ? await authSessions.validate(row.id, c) : null;
339
+ if (!active || await sessionFingerprint(active.id) !== fingerprint) return null;
340
+ return active.userId;
139
341
  },
140
342
  },
141
- extractSessionId: c => getCookie(c, SESSION_COOKIE),
142
- // Before setup the session table does not exist; the auth kit then treats the visitor as a guest.
143
- validateSessionId: async (sessionId, c) => (await authSessions.validate(sessionId, c))?.userId ?? null,
144
- resolveUserById: (userId, c) => member(userId, c),
145
- createSession: async (user, c) => authSessions.create(user.id, c),
343
+ extractSessionId: (c) => getCookie(c, SESSION_COOKIE),
344
+ validateSessionId: async (sessionId, c) => {
345
+ try {
346
+ const session = await authSessions.validate(sessionId, c);
347
+ // Read only while two-step sign-in is required: whether this session used a second factor.
348
+ if (session && authOptions.security.requireTwoFactor) {
349
+ c.set('auth.sessionSecondFactor', (await sessions(() => Session.findOne({ where: { id: session.id } })))?.secondFactor === true);
350
+ }
351
+ return session?.userId ?? null;
352
+ } catch (error) {
353
+ warnAboutSessionDatabase(error);
354
+ return null;
355
+ }
356
+ },
357
+ resolveUserById: async (userId) => {
358
+ try {
359
+ // An account of this tenant only: everything of it is in the tenant's database.
360
+ if (await tenantAccount(userId)) {
361
+ const c = getRequestContext();
362
+ if (c) markTenantAccountRequest(c);
363
+ const own = await inTenant(() => User.findOne({ where: { id: userId } }));
364
+ return own?.status === 'active' ? publicUser(own, await inTenant(() => rolesHere(userId))) : null;
365
+ }
366
+ const row = await asMainAccount(() => accounts(() => User.findOne({ where: { id: userId } })));
367
+ // An account that was turned off, or waits again, is a guest even with a live session.
368
+ if (!row || row.status !== 'active') return null;
369
+ // So is an account on the host of a tenant it does not belong to.
370
+ if (!await allowedHere(userId)) return null;
371
+ const roles = await loadUserRoles(userId);
372
+ return publicUser(row, roles);
373
+ } catch (error) {
374
+ warnAboutSessionDatabase(error);
375
+ return null;
376
+ }
377
+ },
378
+ createSession: async (user, c) => {
379
+ const full = await accountOf(user.id, () => User.findOne({ where: { id: user.id } }));
380
+ if (!full) throw new Error('User not found');
381
+ return authSessions.create(full.id, c);
382
+ },
146
383
  });
147
384
 
148
- /**
149
- * Start a session for a sign-in, recording whether it used a second factor (an authenticator or
150
- * recovery code, or a passkey). Required two-step sign-in asks that of the session: a session
151
- * signed in with a password alone stays limited even after its account gains a factor.
152
- */
153
- export async function createSession(userId: string, c: Context, options: { secondFactor?: boolean } = {}) {
154
- c.set('cms.signInSecondFactor', options.secondFactor === true);
155
- try { return await authSessions.create(userId, c); }
156
- finally { c.set('cms.signInSecondFactor', false); }
385
+ async function sessionFingerprint(token: string): Promise<string> {
386
+ const bytes = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(token)));
387
+ return Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('');
157
388
  }
158
389
 
159
- declare module 'hono' {
160
- interface ContextVariableMap {
161
- /** Set by createSession() for the session it is about to store. */
162
- 'cms.signInSecondFactor': boolean;
163
- /** Whether the request's session was signed in with a second factor. */
164
- 'cms.sessionSecondFactor': boolean;
165
- }
166
- }
390
+ // --- Credential helpers (used by the page @Server methods) -----------------
391
+ const credentials = createCredentialVerifier<User, PublicUser>({
392
+ find: email => User.findOne({ where: { email } }),
393
+ passwordHash: user => user.passwordHash,
394
+ user: async user => publicUser(user, await loadUserRoles(user.id)),
395
+ async replacePasswordHash(user, expected, replacement) {
396
+ const result = await User.update({ id: user.id, passwordHash: expected }, { passwordHash: replacement });
397
+ return result.meta.rowsAffected === 1;
398
+ },
399
+ });
167
400
 
168
- // --- Credentials -----------------------------------------------------------
169
401
  /**
170
- * Email and password sign in this host's accounts: network accounts on the main site, the
171
- * site's own accounts on an added site. Network accounts reach an added site through the
172
- * network's sign-in (`/auth/handoff`).
402
+ * Sign in with email and password. The attempt is counted for the email and for the client's
403
+ * address before the password is checked, so guesses sent at once meet the limit too.
173
404
  */
174
405
  export async function loginUser(email: string, password: string, address = clientAddress()): Promise<PublicUser | null> {
175
- const host = cms();
176
- // The attempt is counted before the password is checked, so guesses sent at once meet the limit too.
177
- const allowed = await host.security.signInBegin(email, address);
406
+ return accountByEmail(email, () => accounts(async () => {
407
+ const allowed = await security.signInBegin(email, address);
178
408
  if (!allowed.ok) throw new SignInLockedError(allowed.retryAfterMs);
179
- const account = await host.signIn.accounts.verifier.verify(email, password);
180
- if (!account) {
181
- // The verifier signs in active accounts only. One that waits for approval hears so, once its password is right.
182
- const waiting = await host.signIn.accounts.disabledWithPassword(email, password).catch(() => null);
183
- if (waiting && await host.users.awaitingApproval(waiting.id).catch(() => false)) {
184
- await host.security.signInSucceeded(email, address);
185
- throw new SignInPendingError();
186
- }
187
- return null;
409
+ const user = await credentials.verify(email, password);
410
+ if (!user) return null;
411
+ await security.signInSucceeded(email, address);
412
+ // Only an active account signs in. One that waits for approval hears so, once its password is right.
413
+ const status = (await User.findOne({ where: { id: user.id } }))?.status;
414
+ if (status === 'pending') throw new SignInPendingError();
415
+ if (status !== 'active') return null;
416
+ // The password matched: on a tenant's host, the visitor is told when the account is not its member.
417
+ if (!await allowedHere(user.id)) throw new SignInMemberError(currentTenant()!.name);
418
+ return user;
419
+ }), null);
420
+ }
421
+
422
+ /** The account is right, but it is not a member of the tenant whose host this is. Thrown after the password matched. */
423
+ export class SignInMemberError extends ClientVisibleError {
424
+ constructor(tenant: string) {
425
+ super(`This account is not a member of ${tenant}.`);
426
+ this.name = 'SignInMemberError';
427
+ }
428
+ }
429
+
430
+ /** The password matched an account that waits for an administrator's approval. */
431
+ export class SignInPendingError extends ClientVisibleError {
432
+ constructor() {
433
+ super('Your account waits for an administrator to approve it. We will email you when it is ready.');
434
+ this.name = 'SignInPendingError';
188
435
  }
189
- await host.security.signInSucceeded(email, address);
190
- if (account.status !== 'active') return null;
191
- return member(account.id);
192
436
  }
193
437
 
194
438
  /** Too many wrong passwords for the email or from the address: the sign-in is refused for a while. */
@@ -201,17 +445,9 @@ export class SignInLockedError extends ClientVisibleError {
201
445
  }
202
446
  }
203
447
 
204
- /** The password matched an account that waits for an administrator's approval. */
205
- export class SignInPendingError extends ClientVisibleError {
206
- constructor() {
207
- super('Your account waits for an administrator to approve it. We will email you when it is ready.');
208
- this.name = 'SignInPendingError';
209
- }
210
- }
211
-
212
448
  /**
213
- * Two-step sign-in is required (Settings → General) and the account's only second factor is a
214
- * passkey: a password or an email link alone is one step, so the account signs in with its passkey.
449
+ * Two-step sign-in is required and the account's only second factor is a passkey: a password
450
+ * alone is one step, so the account signs in with its passkey.
215
451
  */
216
452
  export class SignInPasskeyError extends ClientVisibleError {
217
453
  constructor() {
@@ -230,166 +466,283 @@ function clientAddress(): string {
230
466
  const PASSWORD_CHECKS = { max: 10, windowMs: 15 * 60_000 };
231
467
 
232
468
  /**
233
- * Whether this is the user's current password, before they change it: their site account's, or
234
- * their network account's. Wrong answers are counted per account, so an open session cannot
235
- * guess its way to the password (and from there the email or the account).
469
+ * Whether this is the user's current password, before they change it. Wrong answers are
470
+ * counted per account, so an open session cannot guess its way to the password.
236
471
  */
237
472
  export async function passwordMatches(userId: string, password: string): Promise<boolean> {
238
- const host = cms();
239
- if (!(await host.security.attempt('password-check', userId, PASSWORD_CHECKS.max, PASSWORD_CHECKS.windowMs))) {
473
+ return accountOf(userId, async () => {
474
+ if (!(await security.attempt('password-check', userId, PASSWORD_CHECKS.max, PASSWORD_CHECKS.windowMs))) {
240
475
  throw new ClientVisibleError('Too many wrong passwords. Wait a few minutes, then try again.');
241
476
  }
242
- const { accounts } = await host.storesOf(userId);
243
- const account = await accounts.get(userId);
244
- const matches = !!account && (await accounts.verifier.verify(account.email, password))?.id === userId;
477
+ const row = await User.findOne({ where: { id: userId } });
478
+ const matches = !!row && (await credentials.verify(row.email, password))?.id === userId;
245
479
  // Only wrong passwords count against the account.
246
- if (matches) await host.security.release('password-check', userId).catch(() => undefined);
480
+ if (matches) await security.release('password-check', userId);
247
481
  return matches;
482
+ });
248
483
  }
249
484
 
250
- /** What others see on an added site instead of a network account's profile, password and sign-in methods. */
251
- export const NETWORK_ACCOUNT_LOCKED = 'A network account: its name, email, password and sign-in methods change on the network, by the person or a network admin. This site manages its roles.';
485
+ /** Whether visitors may create accounts on /auth/register (src/dashboard.config.ts: `registration.open`). */
486
+ export async function registrationOpen(): Promise<boolean> {
487
+ return accounts(async () => {
488
+ return authOptions.registration.open;
489
+ });
490
+ }
252
491
 
253
492
  /**
254
- * Whether the request's user may change this account's profile, password, second factors,
255
- * application passwords, status and membership here. On an added site a network account is the
256
- * person's or a network admin's to change; on the main site, theirs, a network admin's, or one who
257
- * holds every permission the account has on each of its sites. The dashboard's user permissions
258
- * govern the rest.
493
+ * Whether setup on /auth/setup is still to do: SETUP_CODE is set and no account administers
494
+ * the application. That is so before the first account, and after an import that brought
495
+ * accounts without one (the CMS's setup page then offers its takeover). /auth/login sends
496
+ * visitors there then. Without SETUP_CODE the first account comes from the seeder.
259
497
  */
260
- export async function manageableHere(userId: string): Promise<boolean> {
261
- const host = cms();
262
- const request = getRequestContext();
263
- // The signed-in person's own account, read from the session: until they add a second factor
264
- // that General settings require, their request principal is anonymous, yet adding one is theirs to do.
265
- if ((request?.get('user') as PublicUser | undefined)?.id === userId) return true;
266
- const principal = (request?.get('principal') as Principal | undefined) ?? ANONYMOUS;
267
- if (principal.kind === 'user' && (principal.id === userId || isNetworkAdmin(principal))) return true;
268
- if (host.siteAccounts) return (await host.users.get(userId))?.account !== 'network';
269
- // On the main site the account signs in everywhere: whoever changes it must hold every
270
- // permission it holds on each site it belongs to, or setting its password takes those sites too.
271
- return request ? heldOnEverySite(networkFor(request.env as CmsBindings), principal, userId) : true;
498
+ export async function setupRequired(): Promise<boolean> {
499
+ return accounts(async () => {
500
+ if (!env(authOptions.setupCodeVariable, '') || currentTenant()) return false;
501
+ try { return !(await User.exists({ networkAdmin: true })); }
502
+ catch { return false; }
503
+ });
504
+ }
505
+
506
+ /** Compare digests, so the time taken does not depend on how much of the code matches. */
507
+ async function sameSecret(candidate: string, expected: string): Promise<boolean> {
508
+ const digest = async (value: string) => new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value)));
509
+ const [a, b] = await Promise.all([digest(candidate), digest(expected)]);
510
+ let difference = 0;
511
+ for (let index = 0; index < a.length; index++) difference |= a[index]! ^ b[index]!;
512
+ return difference === 0;
272
513
  }
273
514
 
274
515
  /**
275
- * Every site the account belongs to counts, whatever its status and whether the network is on:
276
- * a site switched off, archived or deleted (until purged) can come back with the account still
277
- * its member. A site that cannot be read makes the account unmanageable here.
516
+ * First run: create the `admin` role with every permission and the first account, which holds
517
+ * it. Needs SETUP_CODE, so a visitor cannot claim a fresh deployment, and works only while no
518
+ * account exists.
278
519
  */
279
- async function heldOnEverySite(network: ReturnType<typeof networkFor>, principal: Principal, userId: string): Promise<boolean> {
280
- try {
281
- const ids = ((await network.main.accounts.memberships([userId])).get(userId) ?? []).filter(id => id !== MAIN_SITE);
282
- if (!ids.length) return true;
283
- const records = new Map((await network.sites.getMany(ids)).map(record => [record.id, record]));
284
- for (const id of ids) {
285
- const record = records.get(id);
286
- // A purged site has no record and no database left.
287
- if (!record) continue;
288
- const member = await network.hostOf(networkSite(record)).users.get(userId);
289
- if (member && !holdsAll(principal, member.permissions)) return false;
290
- }
291
- return true;
292
- } catch { return false; }
520
+ export async function completeSetup(code: string, account: { email: string; password: string; name?: string }): Promise<PublicUser> {
521
+ return accounts(async () => {
522
+ // Wrong codes are counted per address: the code is the only thing between a visitor and the site.
523
+ if (!(await security.attempt('setup', clientAddress(), 5, 60_000))) throw new ClientVisibleError('Too many attempts. Wait a minute, then try again.');
524
+ const expected = env(authOptions.setupCodeVariable, '');
525
+ if (!expected || !(await sameSecret(code, expected))) throw new ClientVisibleError('The setup code is not right.');
526
+ if (!(await setupRequired())) throw new ClientVisibleError('This site is already set up.');
527
+ const now = new Date();
528
+ // The admin role is the one with the ID `admin`, whatever it is called.
529
+ let role = await Role.findOne({ where: { id: 'admin' } });
530
+ if (!role) {
531
+ await Role.insert({ id: 'admin', name: 'admin', permissions: [...ALL_PERMISSIONS], createdAt: now });
532
+ role = await Role.findOne({ where: { id: 'admin' } });
533
+ }
534
+ if (!role) throw new Error('Unable to create the admin role.');
535
+ const id = uuidv7();
536
+ const email = account.email.trim().toLowerCase();
537
+ // The first account administers the application and, with tenants, the network.
538
+ await User.insert({ id, email, name: account.name?.trim() || null, passwordHash: await hashPassword(account.password), avatar: null, meta: null, status: 'active', networkAdmin: true, createdAt: now });
539
+ await UserRole.insert({ userId: id, roleId: role.id, createdAt: now });
540
+ return (await userById(id))!;
541
+ });
293
542
  }
294
543
 
295
- async function requireManageable(userId: string): Promise<void> {
296
- if (!(await manageableHere(userId))) throw new ClientVisibleError(NETWORK_ACCOUNT_LOCKED);
544
+ /**
545
+ * Where links in emails point: the site's own address (APP_URL), or the tenant's host under it
546
+ * for an account of that tenant only; never the request's Host header, which a client chooses. Without APP_URL, a request to this machine (development)
547
+ * uses its own origin; otherwise null, and no link is sent.
548
+ */
549
+ export function linkOrigin(): string | null {
550
+ // A tenant's own account exists on that tenant's host only: its links open there.
551
+ const own = tenantAccountHome() ? tenantOrigin(currentTenant()) : null;
552
+ if (own) return own;
553
+ const configured = env('APP_URL', '').replace(/\/+$/, '');
554
+ if (configured) return configured;
555
+ const c = getRequestContext();
556
+ if (!c) return null;
557
+ const url = new URL(c.req.url);
558
+ return ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname) ? url.origin : null;
297
559
  }
298
560
 
299
- /** Whether visitors may create accounts: the "Anyone can register" setting. */
300
- export async function registrationOpen(): Promise<boolean> {
301
- const c = getRequestContext();
302
- const host = (c ? await handoffSite(c, networkFor(c.env as CmsBindings)) : null) ?? cms();
303
- return (await host.installed()) && await host.settings.get('general.usersCanRegister');
561
+
562
+ // A link's token is kept as its hash, in the sessions table like reset tokens, with its own purpose.
563
+ type LinkKind = Extract<SessionKind, 'verify' | 'magic'>;
564
+ const LINK_TOKEN = /^[A-Za-z0-9_-]{20,128}$/;
565
+ /** How long a confirmation link lives. */
566
+ const VERIFICATION_TTL_MS = 48 * 60 * 60_000;
567
+ /** How long a sign-in link lives. */
568
+ const MAGIC_LINK_TTL_MS = 15 * 60_000;
569
+
570
+ async function linkId(kind: LinkKind, token: string): Promise<string> {
571
+ return `${kind}:${await security.sha256Hex(token)}`;
572
+ }
573
+
574
+ async function createLink(kind: LinkKind, userId: string, ttlMs: number): Promise<string> {
575
+ const token = security.randomToken(32);
576
+ const now = new Date();
577
+ await Session.insert({ id: await linkId(kind, token), userId, data: null, createdAt: now, expiresAt: new Date(now.getTime() + ttlMs),
578
+ kind, meta: null, location: null, userAgent: null, ipAddress: null });
579
+ return token;
580
+ }
581
+
582
+ async function liveLink(kind: LinkKind, token: string): Promise<Session | null> {
583
+ if (!LINK_TOKEN.test(token)) return null;
584
+ const row = await Session.findOne({ where: { id: await linkId(kind, token), expiresAt: MoreThan(new Date()) } });
585
+ return row && row.kind === kind ? row : null;
586
+ }
587
+
588
+ /** Spend a link: the account's ID for the first request while it is live, null otherwise. */
589
+ async function takeLink(kind: LinkKind, token: string): Promise<string | null> {
590
+ const row = await liveLink(kind, token);
591
+ if (!row?.userId) return null;
592
+ // One conditional delete, so two requests with the same link cannot both use it.
593
+ const deleted = await Session.delete({ id: row.id, expiresAt: MoreThan(new Date()) });
594
+ return deleted.meta.rowsAffected === 1 ? row.userId : null;
304
595
  }
305
596
 
306
597
  /**
307
- * True until an active network admin exists: a fresh install, or a site's database taking over
308
- * as its own install. /auth/login sends visitors to /auth/setup then.
598
+ * The email of the account a sign-in or confirmation link is for, read without spending the
599
+ * link: its page shows it, so someone opening a link another person sent sees whose account
600
+ * it would sign them into. Null for a link that is not valid.
309
601
  */
310
- export async function setupRequired(): Promise<boolean> {
311
- const host = cms();
312
- try { return !(await host.installed()) || !(await host.accounts.hasNetworkAdmin()); }
313
- catch { return true; }
602
+ export async function linkAccountEmail(kind: LinkKind, token: string): Promise<string | null> {
603
+ return accountByToken(() => accounts(async () => {
604
+ const row = await liveLink(kind, token);
605
+ if (!row?.userId) return null;
606
+ return (await User.findOne({ where: { id: row.userId } }))?.email ?? null;
607
+ }), value => value === null);
608
+ }
609
+
610
+ async function sendVerification(user: { id: string; email: string; name: string | null }): Promise<void> {
611
+ const [mail, origin] = [mailer(), linkOrigin()];
612
+ if (!mail || !origin) return;
613
+ const token = await createLink('verify', user.id, VERIFICATION_TTL_MS);
614
+ const title = await siteName().catch(() => '');
615
+ await mail.send({ kind: 'verification', to: user.email, subject: `Confirm your email for ${title || 'the site'}`,
616
+ text: `Hello ${user.name || user.email},\n\nConfirm your email address to finish creating your account on ${title || origin}:\n${origin}/auth/verify?token=${token}\n\nThe link works for two days. If you did not register, ignore this email.` });
314
617
  }
315
618
 
316
619
  /**
317
- * A new account, with the site's default role. On an added site it is a site account. On the
318
- * network host for another site (the visitor came from its network sign-in) it is a network
319
- * account, a member of that site only. `cms.user.before-register` filters may refuse it, change
320
- * its roles or hold it for approval; Settings → General may ask for both the email's
321
- * confirmation and an administrator's approval, in that order.
620
+ * A new account, with the project's default role (src/dashboard.config.ts: `registration`).
621
+ * The project may ask for the email's confirmation and for an administrator's approval, in
622
+ * that order: the account then waits, and the result says which.
322
623
  */
323
624
  export async function registerUser(email: string, password: string, name?: string): Promise<PublicUser> {
324
- const c = getRequestContext();
325
- const network = c ? networkFor(c.env as CmsBindings) : null;
326
- // Registering on the network host for another site: that site's settings apply, whoever hosts the form.
327
- const site = c && network ? await handoffSite(c, network) : null;
328
- const siteRecord = site && c && network ? await pendingSite(c, network) : null;
329
- const host = site ?? cms();
330
- if (!(await registrationOpen())) throw new ClientVisibleError('Registration is closed on this site.');
331
- const role = await host.settings.get('general.defaultRole');
332
- const origin = linkOrigin() ?? '';
333
- let draft;
334
- try {
335
- draft = await host.registrationDraft({ email, name: name?.trim() || email.split('@')[0]!, roles: role && (await host.users.role(role)) ? [role] : [], approval: await host.settings.get('general.approveRegistrations').catch(() => false) }, { origin });
336
- } catch (error) {
337
- if (isCmsError(error, 'CMS_VALIDATION')) throw new ClientVisibleError(error.message);
338
- throw error;
339
- }
340
- // With a sender (the one that sends the link: this request's host) and the site asking for it, the account waits for the email's link.
341
- const verify = Boolean(cms().mail) && await host.settings.get('general.verifyEmail').catch(() => true);
625
+ return (currentTenant() ? asTenantAccount : asMainAccount)(() => accounts(async () => {
626
+ const options = authOptions.registration;
627
+ if (!options.open) throw new ClientVisibleError('Registration is closed on this site.');
628
+ // With a sender and the project asking for it, the account waits for the email's link.
629
+ const verify = options.verifyEmail && mailer() !== null;
342
630
  // Without the site's address no link can be sent: the account is not created active instead.
343
- if (verify && !origin) {
344
- console.warn('[cms] registration refused: email confirmation is on, but APP_URL is not set, so no confirmation link can be sent');
631
+ if (verify && !linkOrigin()) {
632
+ console.warn('[Cossack Auth] registration refused: email confirmation is on, but APP_URL is not set, so no confirmation link can be sent');
345
633
  throw new ClientVisibleError('Registration is not available right now. Ask the site\'s administrator.');
346
634
  }
347
- await replaceUnconfirmed(host, email, site !== null);
348
- try {
349
- // Held for approval, the account is created disabled with its place in the queue, in one write.
350
- const user = await host.users.create({ email, password, name: draft.name, roles: draft.roles, ...(site ? { network: true } : {}),
351
- ...(draft.approval ? { approval: { verified: !verify } } : verify ? { status: 'disabled' as const } : {}) });
352
- const bare = { id: user.id, email: user.email, name: user.name, avatar: user.avatar, meta: null, roles: [], principal: ANONYMOUS };
353
- await host.userRegistered(user, verify ? 'verification' : draft.approval ? 'approval' : 'active').catch(() => undefined);
354
- if (verify) {
355
- await sendVerification(cms(), user.id, user.email, user.name, siteRecord?.id ?? null);
356
- return { ...bare, verification: 'sent' };
357
- }
358
- if (draft.approval) return { ...bare, approval: 'pending' };
359
- // The network host signs the account in; the handoff then takes it to its site.
360
- return site ? bare : (await member(user.id))!;
361
- } catch (error) {
362
- if (isCmsError(error, 'CMS_CONFLICT')) throw new ClientVisibleError('An account with this email already exists.');
363
- throw error;
635
+ // An account that never confirmed this email gives way to a new registration, so a missed
636
+ // link, or someone registering another person's address, never locks the address.
637
+ const existing = await User.findOne({ where: { email } });
638
+ if (existing?.status === 'unconfirmed') await removeAccount(existing.id);
639
+ else if (existing) throw new ClientVisibleError('An account with this email already exists.');
640
+ const id = uuidv7();
641
+ // What else has a say in a registration (src/auth-events.ts) may change the name, or refuse it.
642
+ name = (await authEvents.beforeRegister({ email, name: name ?? '' })).name || undefined;
643
+ const status = verify ? 'unconfirmed' : options.approve ? 'pending' : 'active';
644
+ // On a tenant's host the new account is that tenant's own.
645
+ await User.insert({ id, email, name: name ?? null, passwordHash: await hashPassword(password), avatar: null, meta: null, status, tenantAccount: tenantAccountHome(), createdAt: new Date() });
646
+ const role = options.defaultRole ? await Role.findOne({ where: { id: options.defaultRole } }) ?? await Role.findOne({ where: { name: options.defaultRole } }) : null;
647
+ if (role) await UserRole.insert({ userId: id, roleId: role.id, createdAt: new Date() });
648
+ const user: PublicUser = { id, email, name: name ?? '', avatar: null, meta: null, roles: role ? [{ id: role.id, name: role.name, permissions: role.permissions ?? [] }] : [] };
649
+ await authEvents.registered({ id, email, name: name ?? '' }, verify ? 'verification' : options.approve ? 'approval' : 'active');
650
+ if (verify) {
651
+ await sendVerification({ id, email, name: name ?? null });
652
+ return { ...user, verification: 'sent' };
364
653
  }
654
+ return options.approve ? { ...user, approval: 'pending' } : user;
655
+ }));
656
+ }
657
+
658
+ /** Remove an account with what belongs to it: sessions and links, roles, second factors. */
659
+ async function removeAccount(userId: string): Promise<void> {
660
+ await endSessionsEverywhere(userId);
661
+ await Session.delete({ userId });
662
+ await apiTokens.revokeAll(userId);
663
+ await sql`DELETE FROM user_roles WHERE user_id = ${userId}`;
664
+ await security.reset(userId);
665
+ await TenantMember.delete({ userId });
666
+ await User.delete({ id: userId });
365
667
  }
366
668
 
367
669
  /**
368
- * An account registered with this email that never confirmed it (created waiting, untouched since,
369
- * never signed in) gives way to a new registration, so a missed or expired link, or someone
370
- * registering another person's address, never locks the address. One waiting for approval stays.
670
+ * Open a confirmation link: the token is spent, and the account becomes active, or waits for
671
+ * an administrator's approval (`pending`). Null for an unknown, spent or expired link.
371
672
  */
372
- async function replaceUnconfirmed(host: CmsHost, email: string, network: boolean): Promise<void> {
373
- const accounts = network ? host.accounts : host.signIn.accounts;
374
- const account = await accounts.findByEmail(email).catch(() => null);
375
- if (!account?.unconfirmed || await host.users.awaitingApproval(account.id).catch(() => false)) return;
376
- await host.users.delete(account.id).catch(() => undefined);
377
- await accounts.delete(account.id).catch(() => undefined);
673
+ export async function verifyEmail(token: string): Promise<{ user: string; pending: boolean } | null> {
674
+ return accountByToken(() => accounts(async () => {
675
+ const userId = await takeLink('verify', token);
676
+ if (!userId) return null;
677
+ const pending = authOptions.registration.approve;
678
+ // Only an account still waiting for this link changes: one an administrator disabled since stays as it is.
679
+ const updated = await User.update({ id: userId, status: 'unconfirmed' }, { status: pending ? 'pending' : 'active' });
680
+ return updated.meta.rowsAffected === 1 ? { user: userId, pending } : null;
681
+ }), value => value === null);
682
+ }
683
+
684
+ /** Whether new accounts wait for an administrator's approval. */
685
+ export async function registrationApproval(): Promise<boolean> {
686
+ return accounts(async () => {
687
+ return authOptions.registration.approve;
688
+ });
689
+ }
690
+
691
+ export interface Registration { id: string; name: string; email: string; verified: boolean; createdAt: number }
692
+
693
+ /** The accounts that wait: for approval (`verified`), or still for their email's confirmation. */
694
+ export async function registrations(): Promise<Registration[]> {
695
+ return (currentTenant() ? asTenantAccount : asMainAccount)(() => accounts(async () => {
696
+ const rows = await User.find({ where: { status: In(['pending', 'unconfirmed']) }, order: { createdAt: 'asc' }, take: 200 });
697
+ return rows.map(row => ({ id: row.id, name: row.name ?? '', email: row.email, verified: row.status === 'pending', createdAt: row.createdAt.getTime() }));
698
+ }));
378
699
  }
379
700
 
380
701
  /**
381
- * Where links in this request's emails point: the site's own address (APP_URL for the main site,
382
- * its domain for an added one), never the request's Host header, which a client chooses. Without
383
- * a configured address, a request to this machine (development) uses its own origin; otherwise
384
- * null, and no link is sent.
702
+ * Approve an account that waits for it: it becomes active and gets an email saying so. False
703
+ * when it was not waiting for approval.
385
704
  */
386
- export function linkOrigin(): string | null {
387
- const c = getRequestContext();
388
- if (!c) return env('APP_URL', '').replace(/\/+$/, '') || null;
389
- return mailOrigin(c);
705
+ export async function approveRegistration(userId: string): Promise<boolean> {
706
+ return accountOf(userId, async () => {
707
+ const updated = await User.update({ id: userId, status: 'pending' }, { status: 'active' });
708
+ if (updated.meta.rowsAffected !== 1) return false;
709
+ const [user, mail, origin] = [await User.findOne({ where: { id: userId } }), mailer(), linkOrigin()];
710
+ if (user && mail) {
711
+ const title = await siteName().catch(() => '');
712
+ const where = origin ? ` Sign in at:\n${origin}/auth/login\n` : '\n';
713
+ await mail.send({ to: user.email, subject: `Your account on ${title || 'the site'} is ready`,
714
+ text: `Hello ${user.name || user.email},\n\nAn administrator approved your account.${where}` }).catch(() => undefined);
715
+ }
716
+ return true;
717
+ });
718
+ }
719
+
720
+ /** Delete an account that waits for approval or confirmation. False when it does not wait. */
721
+ export async function deleteRegistration(userId: string): Promise<boolean> {
722
+ return accountOf(userId, async () => {
723
+ const user = await User.findOne({ where: { id: userId } });
724
+ if (!user || (user.status !== 'pending' && user.status !== 'unconfirmed')) return false;
725
+ await removeAccount(userId);
726
+ return true;
727
+ });
390
728
  }
391
729
 
392
730
  // --- Profile updates -------------------------------------------------------
731
+ /**
732
+ * Whether profile pictures can be uploaded. Without file storage, users enter an image URL;
733
+ * configure a storage provider and implement uploadAvatar to accept uploads.
734
+ */
735
+ export const avatarUploads = storedAvatars;
736
+
737
+ /** Store an uploaded picture (src/avatars.ts) and make it the user's avatar. Answers its URL. */
738
+ export async function uploadAvatar(userId: string, file: File): Promise<string> {
739
+ await requireOwnerOfShared(userId);
740
+ if (!storedAvatars) throw new ClientVisibleError('Picture uploads need file storage. Enter an image URL instead.');
741
+ const url = await storeAvatar(userId, file);
742
+ await updateUserProfile(userId, { avatar: url });
743
+ return url;
744
+ }
745
+
393
746
  export interface ProfileUpdate {
394
747
  name?: string;
395
748
  avatar?: string | null;
@@ -398,49 +751,117 @@ export interface ProfileUpdate {
398
751
 
399
752
  /** Update editable profile fields. */
400
753
  export async function updateUserProfile(userId: string, patch: ProfileUpdate): Promise<void> {
401
- await cms().users.update(userId, { ...(patch.name !== undefined ? { name: patch.name } : {}), ...(patch.avatar !== undefined ? { avatar: patch.avatar } : {}) });
754
+ await requireOwnerOfShared(userId);
755
+ return accountOf(userId, async () => {
756
+ const values: Partial<User> = {};
757
+ if (patch.name !== undefined) values.name = patch.name;
758
+ if (patch.avatar !== undefined) values.avatar = patch.avatar;
759
+ if (patch.meta !== undefined) values.meta = patch.meta;
760
+ if (Object.keys(values).length === 0) return;
761
+ await User.update({ id: userId }, values);
762
+ });
402
763
  }
403
764
 
404
- /** Profile pictures are uploaded to the media library. */
405
- export const avatarUploads = true;
406
-
407
- /**
408
- * Store a profile picture and set it on the user; returns its URL. The signed-in user may
409
- * change their own picture, and user managers anyone's.
410
- */
411
- export async function uploadAvatar(userId: string, file: File): Promise<string> {
412
- await requireManageable(userId);
413
- const principal = (getRequestContext()?.get('principal') as Principal | undefined) ?? ANONYMOUS;
414
- try { return await cms().uploadAvatar(userId, { name: file.name, contentType: file.type, size: file.size, body: file.stream() }, { principal }); }
415
- catch (error) { throw isCmsError(error) ? new ClientVisibleError(error.message) : error; }
765
+ // --- Password reset (uses the sessions table for tokens) -------------------
766
+ function randomToken(): string {
767
+ const bytes = crypto.getRandomValues(new Uint8Array(32));
768
+ return btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
769
+ }
770
+
771
+ async function createPasswordResetToken(email: string, ttlMs = 60 * 60 * 1000): Promise<string | null> {
772
+ const user = await User.findOne({ where: { email } });
773
+ if (!user) return null; // do NOT leak whether the email exists
774
+ // A secret: 256 random bits, never a UUIDv7, whose time part is readable and leaves 74 random bits.
775
+ const token = randomToken();
776
+ const now = new Date();
777
+ const expiresAt = new Date(now.getTime() + ttlMs); // one hour, or an invitation's seven days
778
+ await Session.insert({
779
+ id: token,
780
+ userId: user.id,
781
+ data: null,
782
+ expiresAt,
783
+ createdAt: now,
784
+ kind: 'password_reset',
785
+ meta: null,
786
+ location: null,
787
+ userAgent: null,
788
+ ipAddress: null,
789
+ });
790
+ return token;
416
791
  }
417
792
 
793
+ async function consumePasswordResetToken(token: string): Promise<string | null> {
794
+ const row = await Session.findOne({
795
+ where: { id: token, expiresAt: MoreThan(new Date()) },
796
+ });
797
+ if (!row || row.kind !== 'password_reset') return null;
798
+ const deleted = await Session.delete({ id: token, expiresAt: MoreThan(new Date()) });
799
+ return deleted.meta.rowsAffected === 1 ? row.userId : null;
800
+ }
418
801
  // --- Second factors ----------------------------------------------------------
419
- /** This store keeps authenticator apps, recovery codes, passkeys and application passwords. */
802
+ /** This store keeps authenticator apps, recovery codes and passkeys (src/services/security.ts). */
420
803
  export const twoFactorAvailable = true;
421
-
422
804
  /** Cookie holding a pending sign-in between the password and the second factor. */
423
805
  export const TWO_FACTOR_COOKIE = 'two_factor';
424
806
 
807
+ export type SecurityStatus = security.AccountSecurity & {
808
+ /** Set when another host keeps the account's passkeys: the page lists them and links there instead of adding or removing them. */
809
+ passkeysManagedAt?: { name: string; href: string | null } | null;
810
+ };
811
+
425
812
  export type { ApiToken };
426
813
 
427
- /** An account's second factors and passkeys; on an added site, a network account's passkeys are the network host's. */
428
- export type SecurityStatus = AccountSecurity & { passkeysManagedAt?: { name: string; href: string | null } | null };
814
+ declare module 'hono' {
815
+ interface ContextVariableMap {
816
+ /** Set by createSession() for the session it is about to store. */
817
+ 'auth.signInSecondFactor': boolean;
818
+ /** Whether the request's session was signed in with a second factor. */
819
+ 'auth.sessionSecondFactor': boolean;
820
+ }
821
+ }
822
+
823
+ /**
824
+ * Start a session for a sign-in. `secondFactor` says whether it used one (an authenticator
825
+ * or recovery code, or a passkey). Required two-step sign-in asks that of the session: one
826
+ * signed in with a password alone stays limited even after its account gains a factor.
827
+ */
828
+ export async function createSession(userId: string, c: Context, options: { secondFactor?: boolean } = {}) {
829
+ return accountOf(userId, async () => {
830
+ c.set('auth.signInSecondFactor', options.secondFactor === true);
831
+ try { return await authSessions.create(userId, c); }
832
+ finally { c.set('auth.signInSecondFactor', false); }
833
+ });
834
+ }
835
+
836
+ async function userById(userId: string): Promise<PublicUser | null> {
837
+ const row = await User.findOne({ where: { id: userId } });
838
+ return row?.status === 'active' ? publicUser(row, await loadUserRoles(userId)) : null;
839
+ }
429
840
 
430
841
  /**
431
- * After a correct password or email link: null when the user signs in at once, or the ID of a
432
- * pending sign-in (5 minutes, 5 tries) that /auth/two-factor completes with a code. When
433
- * two-step sign-in is required for the dashboard and the account's second factor is a passkey,
434
- * having enrolled one is not having used it: throws SignInPasskeyError.
842
+ * Whether the project asks this user for two-step sign-in (src/dashboard.config.ts:
843
+ * `security.requireTwoFactor`), for everyone or for the roles `security.twoFactorRoles` names.
844
+ */
845
+ function twoFactorAsked(user: Pick<PublicUser, 'roles'>): boolean {
846
+ const { requireTwoFactor, twoFactorRoles } = authOptions.security;
847
+ if (!requireTwoFactor) return false;
848
+ // A role is named by its name, or by its ID where a package keeps the two apart.
849
+ return twoFactorRoles.length === 0 || user.roles.some(role => twoFactorRoles.includes(role.name) || twoFactorRoles.includes(role.id));
850
+ }
851
+
852
+ /**
853
+ * After a correct password: null when the user signs in at once, or the ID of a pending
854
+ * sign-in (5 minutes, 5 tries) that /auth/two-factor completes with a code. When two-step
855
+ * sign-in is required and the account's second factor is a passkey, having enrolled one is
856
+ * not having used it: throws SignInPasskeyError.
435
857
  */
436
858
  export async function beginTwoFactor(userId: string): Promise<string | null> {
437
- const host = cms();
438
- const { security } = host.signIn;
859
+ return accountOf(userId, async () => {
439
860
  if (await security.requiresCode(userId)) return security.createChallenge('signin', userId, 'password');
440
- if (!(await host.settings.get('general.requireTwoFactor').catch(() => false))) return null;
441
- const user = await member(userId);
442
- if (user && hasPermission(user.principal, PERMISSIONS.dashboard) && await security.hasSecondFactor(userId)) throw new SignInPasskeyError();
861
+ const user = await userById(userId);
862
+ if (user && twoFactorAsked(user) && await security.hasSecondFactor(userId)) throw new SignInPasskeyError();
443
863
  return null;
864
+ });
444
865
  }
445
866
 
446
867
  /**
@@ -448,7 +869,9 @@ export async function beginTwoFactor(userId: string): Promise<string | null> {
448
869
  * code is checked, on the pending sign-in and on the account, so codes sent at once count too.
449
870
  */
450
871
  export async function completeTwoFactor(challengeId: string, code: string): Promise<{ user: PublicUser; recovery: boolean } | { error: string; expired: boolean }> {
451
- const { security } = cms().signIn;
872
+ // The challenge is where the account that started it is.
873
+ const own = currentTenant() ? await asTenantAccount(() => accounts(async () => (await security.challenge(challengeId, 'signin')) !== null)) : false;
874
+ return (own ? asTenantAccount : asMainAccount)(() => accounts(async () => {
452
875
  const expired = { error: 'The sign-in expired. Enter your password again.', expired: true };
453
876
  const pending = await security.challenge(challengeId, 'signin');
454
877
  if (!pending?.userId) return expired;
@@ -459,65 +882,45 @@ export async function completeTwoFactor(challengeId: string, code: string): Prom
459
882
  if (!used) {
460
883
  await security.failChallenge(challengeId);
461
884
  const { left } = attempt;
462
- return left > 0 ? { error: `That code is not right. ${left} ${left === 1 ? 'try' : 'tries'} left.`, expired: false } : { error: 'Too many wrong codes. Enter your password again.', expired: true };
885
+ return left > 0
886
+ ? { error: `That code is not right. ${left} ${left === 1 ? 'try' : 'tries'} left.`, expired: false }
887
+ : { error: 'Too many wrong codes. Enter your password again.', expired: true };
463
888
  }
464
889
  if (!(await security.takeChallenge(challengeId, 'signin'))) return expired;
465
890
  await security.secondFactorSucceeded(pending.userId);
466
- const user = await member(pending.userId);
891
+ const user = await userById(pending.userId);
467
892
  if (!user) return { error: 'This account cannot sign in.', expired: true };
468
893
  return { user, recovery: used === 'recovery' };
469
- }
470
-
471
- /** The second factors, passkeys and application passwords of a user's account: its site's for a site account, the network's otherwise. */
472
- async function storesOf(userId: string) {
473
- return cms().storesOf(userId);
894
+ }));
474
895
  }
475
896
 
476
897
  export async function securityStatus(userId: string): Promise<SecurityStatus> {
477
- const [status, elsewhere] = await Promise.all([(await storesOf(userId)).security.status(userId), networkPasskeys(userId)]);
478
- return { ...status, passkeysManagedAt: elsewhere };
898
+ return accountOf(userId, async () => {
899
+ return { ...await security.status(userId), passkeysManagedAt: await passkeysElsewhere(userId) };
900
+ });
479
901
  }
480
902
 
481
903
  /**
482
- * Where a network account's passkeys are kept when this is an added site: the network host.
483
- * They are bound to its address and sign in there, so this site lists them and links there
484
- * rather than adding or removing them. Null for site accounts and on the main site.
904
+ * On a tenant's host, for an account every tenant shares: its passkeys sign it in on the main
905
+ * host and are added and removed there. Null for an account of this host.
485
906
  */
486
- async function networkPasskeys(userId: string): Promise<{ name: string; href: string | null } | null> {
487
- const host = cms();
488
- if (!host.siteAccounts || (await host.storesOf(userId)).kind !== 'network') return null;
489
- const c = getRequestContext();
490
- const network = networkFor(c?.env as CmsBindings);
491
- const name = (await network.settings()).name || await network.main.settings.get('general.siteTitle').catch(() => 'the network');
492
- let href: string | null = null;
493
- try { href = new URL('/dashboard/profile/security', env('APP_URL', '')).href; } catch { /* no network address */ }
494
- return { name, href };
495
- }
496
-
497
- async function requireLocalPasskeys(userId: string): Promise<void> {
498
- const elsewhere = await networkPasskeys(userId);
499
- if (elsewhere) throw new ClientVisibleError(`Add or remove this account's passkeys on ${elsewhere.name}.`);
500
- }
501
-
502
- async function twoFactorAsked(user: Pick<PublicUser, 'principal'>): Promise<boolean> {
503
- return hasPermission(user.principal, PERMISSIONS.dashboard) && await cms().settings.get('general.requireTwoFactor').catch(() => false) === true;
907
+ async function passkeysElsewhere(userId: string): Promise<{ name: string; href: string | null } | null> {
908
+ if (!currentTenant() || await tenantAccount(userId)) return null;
909
+ const origin = tenantOrigin(null);
910
+ return { name: await mainSiteName(), href: origin ? `${origin}/dashboard/profile/security` : null };
504
911
  }
505
912
 
506
913
  /**
507
- * Whether the request's session may not act as the user yet: General settings require two-step
508
- * sign-in of staff, and the session was signed in without a second factor. That covers staff
509
- * with no factor (they set one up) and a session signed in with a password alone (it signs in
510
- * again with the factor), so a factor added later does not trust a session that never used it.
914
+ * Whether the request's session may not act as the user yet: two-step sign-in is required of
915
+ * them, and the session was signed in without a second factor. That covers a user with no
916
+ * factor (they set one up) and a session signed in with a password alone (it signs in again
917
+ * with the factor), so a factor added later does not trust a session that never used it.
511
918
  */
512
919
  export async function secondFactorRequired(user: PublicUser, c: Context | undefined = getRequestContext()): Promise<boolean> {
513
- if (!(await twoFactorAsked(user))) return false;
514
- return c?.get('cms.sessionSecondFactor') !== true;
515
- }
516
-
517
- /** Whether an account itself still lacks the second factor General settings require: for application passwords, which have no sign-in of their own. */
518
- export async function accountNeedsSecondFactor(user: Pick<PublicUser, 'id' | 'principal'>): Promise<boolean> {
519
- if (!(await twoFactorAsked(user))) return false;
520
- return !(await (await storesOf(user.id)).security.hasSecondFactor(user.id));
920
+ return accountOf(user.id, async () => {
921
+ if (!twoFactorAsked(user)) return false;
922
+ return c?.get('auth.sessionSecondFactor') !== true;
923
+ });
521
924
  }
522
925
 
523
926
  /**
@@ -528,135 +931,135 @@ export async function accountNeedsSecondFactor(user: Pick<PublicUser, 'id' | 'pr
528
931
  async function requireFactorSetupAllowed(userId: string): Promise<void> {
529
932
  const c = getRequestContext();
530
933
  const user = c?.get('user') as PublicUser | undefined;
531
- if (!user || user.id !== userId || c?.get('cms.sessionSecondFactor') === true) return;
532
- if (!(await twoFactorAsked(user))) return;
533
- if (await (await storesOf(userId)).security.hasSecondFactor(userId)) {
934
+ if (!user || user.id !== userId || c?.get('auth.sessionSecondFactor') === true) return;
935
+ if (!twoFactorAsked(user)) return;
936
+ if (await security.hasSecondFactor(userId)) {
534
937
  throw new ClientVisibleError('This account already has two-step sign-in. Sign out, then sign in again with it.');
535
938
  }
536
939
  }
537
940
 
538
941
  /**
539
- * After the user added a factor in this session: the session counts as using it when it was the
540
- * account's first. Other sessions
541
- * keep what their own sign-in used, so a password-only one stays limited; they are not ended,
542
- * since whoever added the first factor (the owner, or someone with the password) would otherwise
543
- * sign the other out.
942
+ * After the user added a factor in this session: the session counts as using it when it was
943
+ * the account's first. Other sessions keep what their own sign-in used.
544
944
  */
545
945
  async function factorAdded(userId: string, hadFactor: boolean): Promise<void> {
546
946
  const c = getRequestContext();
547
947
  const id = c ? getCookie(c, SESSION_COOKIE) : undefined;
548
948
  const user = c?.get('user') as PublicUser | undefined;
549
949
  if (!c || !id || user?.id !== userId) return;
550
- // Only the account's first factor counts for the session that set it up: one added beside a
551
- // factor the session never used (setup raced another session's) does not.
552
- if (hadFactor && c.get('cms.sessionSecondFactor') !== true) return;
553
- await cms(c).authSessions.markSecondFactor(id);
554
- c.set('cms.sessionSecondFactor', true);
555
- }
556
-
557
- /** A new authenticator secret, its `otpauth://` URI and a QR code of it as SVG. */
558
- export async function startAuthenticator(user: PublicUser): Promise<{ secret: string; uri: string; qr: string }> {
559
- await requireFactorSetupAllowed(user.id);
560
- const host = cms();
561
- const secret = await (await storesOf(user.id)).security.startTotp(user.id);
562
- const issuer = await host.settings.get('general.siteTitle').catch(() => 'Cossack');
563
- const uri = totpUri({ secret, issuer, account: user.email });
564
- return { secret, uri, qr: renderSVG(uri, { border: 1 }) };
565
- }
566
-
567
- /** Confirm the authenticator with a code from it; returns the recovery codes, shown once. */
568
- export async function confirmAuthenticator(userId: string, code: string): Promise<string[]> {
569
- await requireFactorSetupAllowed(userId);
570
- const { security } = await storesOf(userId);
571
- const hadFactor = await security.hasSecondFactor(userId);
572
- let codes: string[];
573
- try { codes = await security.confirmTotp(userId, code); }
574
- catch (error) { throw isCmsError(error) ? new ClientVisibleError(error.message) : error; }
575
- await factorAdded(userId, hadFactor);
576
- return codes;
950
+ // Only the account's first factor counts for the session that set it up.
951
+ if (hadFactor && c.get('auth.sessionSecondFactor') !== true) return;
952
+ await sessions(() => Session.update({ id, userId }, { secondFactor: true }));
953
+ c.set('auth.sessionSecondFactor', true);
577
954
  }
578
955
 
579
956
  /**
580
957
  * Before a factor is removed or replaced: a session limited by required two-step sign-in never
581
- * used the account's factors, so it may not take them away (it could then set up its own and
582
- * count as two-step). It signs in again with a factor first.
958
+ * used the account's factors, so it may not take them away. It signs in again with a factor first.
583
959
  */
584
- async function requireFactorUsed(userId: string): Promise<void> {
960
+ function requireFactorUsed(userId: string): void {
585
961
  const c = getRequestContext();
586
962
  const user = c?.get('user') as PublicUser | undefined;
587
- if (!user || user.id !== userId || c?.get('cms.sessionSecondFactor') === true) return;
588
- if (!(await twoFactorAsked(user))) return;
963
+ if (!user || user.id !== userId || c?.get('auth.sessionSecondFactor') === true) return;
964
+ if (!twoFactorAsked(user)) return;
589
965
  throw new ClientVisibleError('Sign out, then sign in again with two-step sign-in to change it.');
590
966
  }
591
967
 
592
968
  /** Check an authenticator or recovery code, counted against the account's tries as at sign-in. */
593
969
  async function checkAccountCode(userId: string, code: string): Promise<void> {
594
- const { security } = await storesOf(userId);
595
970
  if (!(await security.codeAttempt(userId))) throw new ClientVisibleError('Too many wrong codes for this account. Try again in 15 minutes.');
596
971
  if (!(await security.verifyCode(userId, code))) throw new ClientVisibleError('That code is not right.');
597
972
  await security.secondFactorSucceeded(userId);
598
973
  }
599
974
 
975
+ /** A new authenticator secret, its `otpauth://` URI and a QR code of it as SVG. */
976
+ export async function startAuthenticator(user: PublicUser): Promise<{ secret: string; uri: string; qr: string }> {
977
+ return accountOf(user.id, async () => {
978
+ await requireFactorSetupAllowed(user.id);
979
+ const secret = await security.startTotp(user.id);
980
+ const uri = totpUri({ secret, issuer: await siteName().catch(() => 'Cossack'), account: user.email });
981
+ return { secret, uri, qr: renderSVG(uri, { border: 1 }) };
982
+ });
983
+ }
984
+
985
+ /** Confirm the authenticator with a code from it; returns the recovery codes, shown once. */
986
+ export async function confirmAuthenticator(userId: string, code: string): Promise<string[]> {
987
+ return accountOf(userId, async () => {
988
+ await requireFactorSetupAllowed(userId);
989
+ const hadFactor = await security.hasSecondFactor(userId);
990
+ const codes = await security.confirmTotp(userId, code);
991
+ await factorAdded(userId, hadFactor);
992
+ return codes;
993
+ });
994
+ }
995
+
600
996
  /** Turning the authenticator off needs one of its codes, or a recovery code. */
601
997
  export async function disableAuthenticator(userId: string, code: string): Promise<void> {
602
- await requireFactorUsed(userId);
998
+ return accountOf(userId, async () => {
999
+ requireFactorUsed(userId);
603
1000
  await checkAccountCode(userId, code);
604
- await (await storesOf(userId)).security.disableTotp(userId);
1001
+ await security.disableTotp(userId);
1002
+ });
605
1003
  }
606
1004
 
607
1005
  export async function newRecoveryCodes(userId: string, code: string): Promise<string[]> {
608
- await requireFactorUsed(userId);
1006
+ return accountOf(userId, async () => {
1007
+ requireFactorUsed(userId);
609
1008
  await checkAccountCode(userId, code);
610
- return (await storesOf(userId)).security.regenerateRecoveryCodes(userId);
1009
+ return security.regenerateRecoveryCodes(userId);
1010
+ });
611
1011
  }
612
1012
 
613
- /** Remove a user's second factors, for a user manager helping someone who lost their device. */
1013
+ /** Remove a user's second factors, for a user manager helping someone who lost their device. The page checks who may. */
614
1014
  export async function resetSecondFactors(userId: string): Promise<void> {
615
- await requireManageable(userId);
616
- await (await storesOf(userId)).security.reset(userId);
1015
+ await requireOwnerOfShared(userId);
1016
+ return accountOf(userId, async () => {
1017
+ await security.reset(userId);
1018
+ });
617
1019
  }
618
1020
 
619
1021
  /** The site's relying party for passkeys: this host, and the origins the browser may report. */
620
- function passkeySite(c: Context, siteName: string): PasskeyConfig {
1022
+ async function passkeySite(c: Context): Promise<PasskeyConfig> {
621
1023
  const url = new URL(c.req.url);
622
1024
  const origins = new Set([url.origin]);
623
1025
  if (c.req.header('x-forwarded-proto') === 'https') origins.add(`https://${url.host}`);
624
1026
  const configured = env('APP_URL', '');
625
1027
  if (configured) { try { origins.add(new URL(configured).origin); } catch { /* not a URL */ } }
626
- return { rpName: siteName, rpID: url.hostname, origin: [...origins] };
1028
+ return { rpName: await siteName().catch(() => 'Cossack'), rpID: url.hostname, origin: [...origins] };
627
1029
  }
628
1030
 
629
1031
  export async function passkeyRegistration(c: Context, user: PublicUser): Promise<{ challenge: string; options: PublicKeyCredentialCreationOptionsJSON }> {
630
- await requireLocalPasskeys(user.id);
1032
+ return accountOf(user.id, async () => {
1033
+ const elsewhere = await passkeysElsewhere(user.id);
1034
+ if (elsewhere) throw new ClientVisibleError(`Add or remove this account's passkeys on ${elsewhere.name}.`);
631
1035
  await requireFactorSetupAllowed(user.id);
632
- const host = cms(c);
633
- const site = passkeySite(c, await host.settings.get('general.siteTitle').catch(() => 'Cossack'));
634
- const { security } = await host.storesOf(user.id);
635
1036
  const existing = await security.passkeys(user.id);
636
- const options = await passkeyRegistrationOptions(site, { id: user.id, name: user.email, displayName: user.name }, existing.map(passkey => ({ ...passkey, transports: passkey.transports ?? undefined })));
1037
+ const options = await passkeyRegistrationOptions(await passkeySite(c), { id: user.id, name: user.email, displayName: user.name },
1038
+ existing.map(passkey => ({ ...passkey, transports: passkey.transports ?? undefined })));
637
1039
  return { challenge: await security.createChallenge('passkey-register', user.id, options.challenge), options };
1040
+ });
638
1041
  }
639
1042
 
640
1043
  export async function addPasskey(c: Context, user: PublicUser, challengeId: string, response: RegistrationResponseJSON, name: string): Promise<void> {
641
- await requireLocalPasskeys(user.id);
642
- const host = cms(c);
643
- const { security } = await host.storesOf(user.id);
1044
+ return accountOf(user.id, async () => {
644
1045
  const pending = await security.challenge(challengeId, 'passkey-register');
645
- if (!pending || pending.userId !== user.id || !(await security.takeChallenge(challengeId, 'passkey-register'))) throw new ClientVisibleError('The passkey request expired. Try again.');
646
- const site = passkeySite(c, await host.settings.get('general.siteTitle').catch(() => 'Cossack'));
647
- const passkey = await verifyPasskeyRegistration(site, response, pending.challenge);
1046
+ if (!pending || pending.userId !== user.id || !(await security.takeChallenge(challengeId, 'passkey-register'))) {
1047
+ throw new ClientVisibleError('The passkey request expired. Try again.');
1048
+ }
1049
+ const passkey = await verifyPasskeyRegistration(await passkeySite(c), response, pending.challenge);
648
1050
  if (!passkey) throw new ClientVisibleError('The passkey could not be verified.');
649
1051
  await requireFactorSetupAllowed(user.id);
650
1052
  const hadFactor = await security.hasSecondFactor(user.id);
651
- try { await security.addPasskey(user.id, passkey, name); }
652
- catch (error) { throw isCmsError(error) ? new ClientVisibleError(error.message) : error; }
1053
+ await security.addPasskey(user.id, passkey, name);
653
1054
  await factorAdded(user.id, hadFactor);
1055
+ });
654
1056
  }
655
1057
 
656
1058
  export async function removePasskey(userId: string, id: string): Promise<void> {
657
- await requireLocalPasskeys(userId);
658
- await requireFactorUsed(userId);
659
- await (await storesOf(userId)).security.removePasskey(userId, id);
1059
+ return accountOf(userId, async () => {
1060
+ requireFactorUsed(userId);
1061
+ await security.removePasskey(userId, id);
1062
+ });
660
1063
  }
661
1064
 
662
1065
  /**
@@ -665,109 +1068,126 @@ export async function removePasskey(userId: string, id: string): Promise<void> {
665
1068
  */
666
1069
  export const PASSKEY_CHALLENGES = Object.freeze({ windowMs: 10 * 60_000, perAddress: 30, perHost: 2000 });
667
1070
 
668
- /** A passkey signs in this host's accounts, bound to this host: the network's on the main site, the site's own on an added site. */
669
1071
  export async function passkeySignIn(c: Context): Promise<{ challenge: string; options: PublicKeyCredentialRequestOptionsJSON }> {
670
- const host = cms(c);
671
- const counters = host.signIn.security;
672
- if (!(await counters.attempt('passkey-options', `a:${clientAddress()}`, PASSKEY_CHALLENGES.perAddress, PASSKEY_CHALLENGES.windowMs))
673
- || !(await counters.attempt('passkey-options', 'host', PASSKEY_CHALLENGES.perHost, PASSKEY_CHALLENGES.windowMs))) {
1072
+ return accounts(async () => {
1073
+ if (!(await security.attempt('passkey-options', `a:${clientAddress()}`, PASSKEY_CHALLENGES.perAddress, PASSKEY_CHALLENGES.windowMs))
1074
+ || !(await security.attempt('passkey-options', 'host', PASSKEY_CHALLENGES.perHost, PASSKEY_CHALLENGES.windowMs))) {
674
1075
  throw new ClientVisibleError('Too many passkey sign-ins were started. Try again in a few minutes, or sign in with your password.');
675
1076
  }
676
- const site = passkeySite(c, await host.settings.get('general.siteTitle').catch(() => 'Cossack'));
677
- const options = await passkeyAuthenticationOptions(site);
678
- return { challenge: await host.signIn.security.createChallenge('passkey-signin', null, options.challenge), options };
1077
+ const options = await passkeyAuthenticationOptions(await passkeySite(c));
1078
+ return { challenge: await security.createChallenge('passkey-signin', null, options.challenge), options };
1079
+ });
679
1080
  }
680
1081
 
681
1082
  /** The user a passkey signs in, after checking its signature against the challenge. */
682
1083
  export async function completePasskeySignIn(c: Context, challengeId: string, response: AuthenticationResponseJSON): Promise<PublicUser | null> {
683
- const host = cms(c);
684
- const { security } = host.signIn;
1084
+ return accountByToken(() => accounts(async () => {
685
1085
  const pending = await security.challenge(challengeId, 'passkey-signin');
686
1086
  if (!pending || !(await security.takeChallenge(challengeId, 'passkey-signin'))) return null;
687
1087
  const passkey = await security.passkey(response?.id);
688
1088
  if (!passkey) return null;
689
- const site = passkeySite(c, await host.settings.get('general.siteTitle').catch(() => 'Cossack'));
690
- const verified = await verifyPasskeyAuthentication(site, response, pending.challenge, { ...passkey, transports: passkey.transports ?? undefined });
1089
+ const verified = await verifyPasskeyAuthentication(await passkeySite(c), response, pending.challenge, { ...passkey, transports: passkey.transports ?? undefined });
691
1090
  if (!verified) return null;
692
1091
  await security.usePasskey(passkey.id, verified.counter);
693
- return member(passkey.userId, c);
1092
+ if (!await allowedHere(passkey.userId)) throw new SignInMemberError(currentTenant()!.name);
1093
+ return userById(passkey.userId);
1094
+ }), value => value === null);
694
1095
  }
695
1096
 
696
1097
  // --- Application passwords -------------------------------------------------
697
- /** Application passwords sign apps and scripts in to the content API. */
1098
+ /** Application passwords sign apps and scripts in to the project's API routes (`apiTokenUser`). */
698
1099
  export const apiTokensAvailable = true;
699
1100
 
700
1101
  export async function listApiTokens(userId: string): Promise<ApiToken[]> {
701
- return await manageableHere(userId) ? (await storesOf(userId)).apiTokens.list(userId) : [];
1102
+ await requireOwnerOfShared(userId);
1103
+ return accountOf(userId, async () => {
1104
+ return apiTokens.list(userId);
1105
+ });
702
1106
  }
703
1107
 
704
- /** A new application password; the token is shown once. A network account's work on every site it belongs to. */
1108
+ /** A new application password; the token is shown once. */
705
1109
  export async function createApiToken(userId: string, name: string, scope: 'read' | 'write', expiresInDays: number | null = null): Promise<string> {
706
- await requireManageable(userId);
707
- // An application password signs in without a second factor: an account that General settings
708
- // require to have one gets passwords only once it does.
709
- const owner = await member(userId);
710
- if (owner && (await accountNeedsSecondFactor(owner) || (owner.id === (getRequestContext()?.get('user') as PublicUser | undefined)?.id && await secondFactorRequired(owner)))) throw new ClientVisibleError('This site requires two-step sign-in: set it up under Profile → Security before creating application passwords.');
1110
+ await requireOwnerOfShared(userId);
1111
+ return accountOf(userId, async () => {
1112
+ // An application password signs in without a second factor: an account that must have one
1113
+ // gets passwords only once it does, and only from a session that used it.
1114
+ const owner = await userById(userId);
1115
+ const own = owner?.id === (getRequestContext()?.get('user') as PublicUser | undefined)?.id;
1116
+ if (owner && twoFactorAsked(owner) && (!(await security.hasSecondFactor(userId)) || (own && await secondFactorRequired(owner)))) {
1117
+ throw new ClientVisibleError('This site requires two-step sign-in. Set it up before creating application passwords.');
1118
+ }
711
1119
  const expiresAt = expiresInDays && expiresInDays > 0 ? Date.now() + Math.trunc(expiresInDays) * 86_400_000 : null;
712
- try { return (await (await storesOf(userId)).apiTokens.create(userId, { name, scope, expiresAt })).token; }
713
- catch (error) { throw isCmsError(error) ? new ClientVisibleError(error.message) : error; }
1120
+ return (await apiTokens.create(userId, { name, scope, expiresAt })).token;
1121
+ });
714
1122
  }
715
1123
 
716
1124
  export async function revokeApiToken(userId: string, id: string): Promise<void> {
717
- await requireManageable(userId);
1125
+ await requireOwnerOfShared(userId);
1126
+ return accountOf(userId, async () => {
718
1127
  // A session that never used the account's second factor may not take its tokens away either.
719
- await requireFactorUsed(userId);
720
- await (await storesOf(userId)).apiTokens.revoke(userId, id).catch(() => undefined);
1128
+ requireFactorUsed(userId);
1129
+ await apiTokens.revoke(userId, id);
1130
+ });
721
1131
  }
722
1132
 
723
- // --- Password reset ----------------------------------------------------------
724
1133
  /**
725
- * Creates a reset token and emails it. Reads the `EMAIL` binding and `MAIL_FROM` via the
726
- * global helpers. Unknown emails and a missing send_email binding are silent no-ops. On an
727
- * added site, a member with a network account gets the network's reset link.
1134
+ * The user an application password signs in, for the project's API routes: pass the request's
1135
+ * `Authorization: Bearer app_...` token. Null for an unknown, wrong or expired token, and for
1136
+ * an account that is not active. `scope` is `read` for a token that may only read.
728
1137
  */
729
- export async function requestPasswordReset(email: string, _requestOrigin?: string): Promise<void> {
730
- const host = cms();
731
- // The link goes to the site's own address, never the Host the request named.
732
- let resetBaseUrl = linkOrigin();
733
- if (!resetBaseUrl) {
734
- console.warn('[cms] A password reset was requested, but the site has no address (APP_URL): the link was not sent.');
735
- return;
736
- }
737
- // A flood of requests for one email or from one address sends nothing after the first few.
738
- const address = clientAddress();
739
- const byEmail = await host.security.attempt('reset', `e:${email.trim().toLowerCase()}`, RESET_REQUESTS.perEmail, RESET_REQUESTS.windowMs);
740
- const byAddress = await host.security.attempt('reset', `a:${address}`, RESET_REQUESTS.perAddress, RESET_REQUESTS.windowMs);
741
- if (!byEmail || !byAddress) return;
742
- let reset = await host.signIn.accounts.createPasswordReset(email);
743
- if (!reset && host.siteAccounts && (await host.users.findByEmail(email).catch(() => null))?.account === 'network') {
744
- const network = env('APP_URL', '');
745
- reset = network ? await host.accounts.createPasswordReset(email) : null;
746
- resetBaseUrl = network;
747
- }
748
- if (!reset) return; // do NOT leak whether the email exists
749
- if (!host.mail) {
750
- console.warn('[cms] A password reset was requested, but no email sender is configured (an EMAIL binding, or SMTP_HOST on Node): the link was not sent.');
751
- return;
752
- }
753
- const resetUrl = `${resetBaseUrl.replace(/\/$/, '')}/auth/reset-password?token=${reset.token}`;
754
- await host.mail.send({ kind: 'reset', to: reset.account.email, subject: 'Reset your password',
1138
+ export async function apiTokenUser(token: string): Promise<{ user: PublicUser; scope: 'read' | 'write' } | null> {
1139
+ return accountByToken(() => accounts(async () => {
1140
+ const verified = await apiTokens.verify(token);
1141
+ if (!verified) return null;
1142
+ const user = await userById(verified.userId);
1143
+ return user ? { user, scope: verified.scope } : null;
1144
+ }), value => value === null);
1145
+ }
1146
+
1147
+ /**
1148
+ * Creates a reset token and emails it. Reads the `EMAIL` binding and
1149
+ * `MAIL_FROM` via the global helpers — no `Context` parameter needed. If the
1150
+ * send_email binding is not configured, this is a graceful no-op.
1151
+ */
1152
+ export async function requestPasswordReset(email: string, resetBaseUrl: string): Promise<void> {
1153
+ return accountByEmail(email, () => accounts(async () => {
1154
+ // Beyond the limits per email and per address nothing is sent, and the answer is the same.
1155
+ const key = await security.sha256Hex(email.trim().toLowerCase());
1156
+ if (!(await security.attempt('reset', `e:${key}`, security.RESET_REQUESTS.perEmail, security.RESET_REQUESTS.windowMs))
1157
+ || !(await security.attempt('reset', `a:${clientAddress()}`, security.RESET_REQUESTS.perAddress, security.RESET_REQUESTS.windowMs))) return;
1158
+ const token = await createPasswordResetToken(email);
1159
+ if (!token) return; // silently no-op for unknown emails
1160
+ const mail = mailer();
1161
+ if (!mail) return; // send_email not configured: graceful no-op
1162
+ const resetUrl = `${resetBaseUrl.replace(/\/$/, '')}/auth/reset-password?token=${token}`;
1163
+ await mail.send({ kind: 'reset', to: email, subject: 'Reset your password',
755
1164
  text: `We received a request to reset your password. Choose a new one here; the link works for one hour:\n${resetUrl}\n\nIf you did not ask for it, ignore this email.` });
1165
+ }), undefined);
756
1166
  }
757
1167
 
758
- /** One request can use a token; the account's sessions end with the change. */
759
1168
  export async function resetPassword(token: string, newPassword: string): Promise<boolean> {
760
- return cms().signIn.accounts.resetPassword(token, newPassword);
1169
+ return accountByToken(() => accounts(async () => {
1170
+ const userId = await consumePasswordResetToken(token);
1171
+ if (!userId) return false;
1172
+ const passwordHash = await hashPassword(newPassword);
1173
+ await User.update({ id: userId }, { passwordHash });
1174
+ // A new password ends every session of the account, on every host.
1175
+ await endSessionsEverywhere(userId);
1176
+ await Session.delete({ userId });
1177
+ return true;
1178
+ }), value => value === false);
761
1179
  }
762
1180
 
763
1181
  // --- Logout ----------------------------------------------------------------
764
- /** Signing out of a site signs out of the network too, and so of every site the session reached. */
1182
+ /**
1183
+ * Deletes the calling session's row and returns headers that expire the
1184
+ * session cookie. Needs `c` to read the cookie and is applied to the response
1185
+ * by the caller (mirrors `auth.createSession`'s `{ headers }` contract).
1186
+ */
765
1187
  export async function logout(c: Context): Promise<{ headers: Headers }> {
766
- const id = getCookie(c, SESSION_COOKIE) ?? '';
767
- const session = id ? await cms(c).authSessions.read(id, c).catch(() => null) : null;
768
- const headers = await authSessions.revoke(id, c);
769
- if (session?.parentId) await networkFor(c.env as CmsBindings).main.authSessions.revokeByReference(session.userId, session.parentId).catch(() => false);
770
- return { headers };
1188
+ return accounts(async () => {
1189
+ return { headers: await authSessions.revoke(getCookie(c, SESSION_COOKIE) ?? '', c) };
1190
+ });
771
1191
  }
772
1192
 
773
1193
  /** Clear the same cookie policy used for creation and rotation. */
@@ -778,221 +1198,224 @@ export interface SessionInfo {
778
1198
  /** Public management reference. Never the bearer token used in the cookie. */
779
1199
  reference: string;
780
1200
  expiresAt: string;
1201
+ /** When the session was created (the "Logged in" time). */
781
1202
  createdAt: string;
1203
+ /** True when this row is the calling session (never revokable from its own page). */
782
1204
  current: boolean;
1205
+ /** Origin metadata captured at login (null if unavailable). */
783
1206
  location: string | null;
784
1207
  userAgent: string | null;
785
1208
  ipAddress: string | null;
786
1209
  }
787
1210
 
1211
+
1212
+ const PUBLIC_SESSION_REFERENCE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
1213
+
788
1214
  function sessionOwner(c: Context): { userId: string; currentId: string } {
789
1215
  const user = c.get('user') as PublicUser | undefined;
790
1216
  const currentId = getCookie(c, SESSION_COOKIE);
791
- if (!user?.id || !currentId) throw new ClientVisibleError('Sign in to manage sessions.');
1217
+ if (!user || typeof user.id !== 'string' || !user.id || !currentId) {
1218
+ throw new ClientVisibleError('Sign in to manage sessions.');
1219
+ }
792
1220
  return { userId: user.id, currentId };
793
1221
  }
794
1222
 
795
- /** Lists only the authenticated caller's active sessions as safe DTOs. */
1223
+ function validSessionReference(row: Session): boolean {
1224
+ return typeof row.publicId === 'string' && PUBLIC_SESSION_REFERENCE.test(row.publicId) && row.publicId !== row.id;
1225
+ }
1226
+
1227
+ async function sessionWithReference(row: Session, userId: string): Promise<Session | null> {
1228
+ if (row.userId !== userId || row.kind !== 'auth' || row.expiresAt.getTime() <= Date.now()) return null;
1229
+ if (row.publicId == null) {
1230
+ // Conditional assignment and re-read retain one winner across tabs.
1231
+ await sql`UPDATE sessions SET public_id = ${crypto.randomUUID()}
1232
+ WHERE id = ${row.id} AND user_id = ${userId} AND public_id IS NULL
1233
+ AND kind = ${AUTH}
1234
+ AND expires_at > ${new Date()}`;
1235
+ const stored = await Session.findOne({ where: { id: row.id, userId } });
1236
+ if (!stored || stored.kind !== 'auth' || stored.expiresAt.getTime() <= Date.now()) return null;
1237
+ row = stored;
1238
+ }
1239
+ if (!validSessionReference(row)) throw new Error('Invalid session management reference.');
1240
+ return row;
1241
+ }
1242
+
1243
+ async function currentSessionReference(userId: string, currentId: string): Promise<string> {
1244
+ const row = await Session.findOne({ where: { id: currentId, userId } });
1245
+ const current = row ? await sessionWithReference(row, userId) : null;
1246
+ if (!current) throw new ClientVisibleError('Sign in to manage sessions.');
1247
+ return current.publicId!;
1248
+ }
1249
+
1250
+ /** Lists only the authenticated caller's active auth sessions as safe DTOs. */
796
1251
  export async function listUserSessions(c: Context): Promise<SessionInfo[]> {
1252
+ return sessions(async () => {
797
1253
  return sessionsOf(c, sessionOwner(c).userId);
1254
+ });
798
1255
  }
799
1256
 
800
1257
  /**
801
- * Any user's active sessions, for the user screen. The page decides who may see them;
802
- * the caller's own session is marked current.
1258
+ * Any user's active auth sessions, for the user screen. The page decides who may see
1259
+ * them; the caller's own session is marked current.
803
1260
  */
804
1261
  export async function sessionsOf(c: Context, userId: string): Promise<SessionInfo[]> {
805
- await requireManageable(userId);
806
- const host = cms(c);
1262
+ return sessions(async () => {
807
1263
  const currentId = getCookie(c, SESSION_COOKIE);
808
- const current = currentId ? await host.authSessions.publicReference(currentId) : null;
809
- return (await host.authSessions.listForUser(userId, Date.now())).map(row => ({
810
- reference: row.reference, createdAt: new Date(row.createdAt).toISOString(), expiresAt: new Date(row.expiresAt).toISOString(),
811
- current: row.reference === current, location: null, userAgent: row.userAgent, ipAddress: row.ip,
812
- }));
1264
+ const rows = await Session.find({
1265
+ where: { userId, expiresAt: MoreThan(new Date()) },
1266
+ });
1267
+ const sessions: SessionInfo[] = [];
1268
+ for (const candidate of rows) {
1269
+ // Existing auth rows get an independent reference on first listing.
1270
+ const row = await sessionWithReference(candidate, userId);
1271
+ if (!row) continue;
1272
+ sessions.push({
1273
+ reference: row.publicId!,
1274
+ expiresAt: row.expiresAt.toISOString(),
1275
+ createdAt: (row.createdAt || row.expiresAt).toISOString(),
1276
+ current: row.id === currentId,
1277
+ location: row.location,
1278
+ userAgent: row.userAgent,
1279
+ ipAddress: row.ipAddress,
1280
+ });
1281
+ }
1282
+ return sessions;
1283
+ });
813
1284
  }
814
1285
 
815
- /** End one of a user's sessions, never the caller's own. */
816
- export async function revokeSessionOf(c: Context, userId: string, reference: string): Promise<boolean> {
817
- await requireManageable(userId);
818
- return cms(c).authSessions.revokeByReference(userId, reference, getCookie(c, SESSION_COOKIE));
1286
+ /** Revoke one other auth session owned by the authenticated caller. */
1287
+ export async function revokeSession(c: Context, reference: string): Promise<boolean> {
1288
+ return sessions(async () => {
1289
+ const { userId, currentId } = sessionOwner(c);
1290
+ if (typeof reference !== 'string' || !PUBLIC_SESSION_REFERENCE.test(reference)) return false;
1291
+ const currentReference = await currentSessionReference(userId, currentId);
1292
+ const result = await sql`DELETE FROM sessions
1293
+ WHERE public_id = ${reference} AND user_id = ${userId} AND id <> ${currentId}
1294
+ AND public_id <> ${currentReference}
1295
+ AND kind = ${AUTH}
1296
+ AND expires_at > ${new Date()}`;
1297
+ // A session of the main host takes the sessions tenants' hosts made from it.
1298
+ if (result.meta.rowsAffected === 1 && !currentTenant()) await endReached(reference);
1299
+ return result.meta.rowsAffected === 1;
1300
+ });
819
1301
  }
820
1302
 
821
- /** End all of a user's sessions except the caller's own. */
822
- export async function revokeSessionsOf(c: Context, userId: string): Promise<void> {
823
- await requireManageable(userId);
824
- await cms(c).authSessions.revokeAllForUser(userId, getCookie(c, SESSION_COOKIE));
1303
+ /** End one of a user's auth sessions, never the caller's own. */
1304
+ export async function revokeSessionOf(c: Context, userId: string, reference: string): Promise<boolean> {
1305
+ return sessions(async () => {
1306
+ if (typeof reference !== 'string' || !PUBLIC_SESSION_REFERENCE.test(reference)) return false;
1307
+ const result = await sql`DELETE FROM sessions
1308
+ WHERE public_id = ${reference} AND user_id = ${userId} AND id <> ${getCookie(c, SESSION_COOKIE) ?? ''}
1309
+ AND kind = ${AUTH}
1310
+ AND expires_at > ${new Date()}`;
1311
+ if (result.meta.rowsAffected === 1 && !currentTenant()) await endReached(reference);
1312
+ return result.meta.rowsAffected === 1;
1313
+ });
825
1314
  }
826
1315
 
827
- /** Revoke one other session owned by the authenticated caller. */
828
- export async function revokeSession(c: Context, reference: string): Promise<boolean> {
829
- const { userId, currentId } = sessionOwner(c);
830
- return cms(c).authSessions.revokeByReference(userId, reference, currentId);
1316
+ /** End all of a user's auth sessions except the caller's own. */
1317
+ export async function revokeSessionsOf(c: Context, userId: string): Promise<void> {
1318
+ return sessions(async () => {
1319
+ await sql`DELETE FROM sessions WHERE user_id = ${userId} AND id <> ${getCookie(c, SESSION_COOKIE) ?? ''}
1320
+ AND kind = ${AUTH}`;
1321
+ await endReachedOfUser(userId, getCookie(c, SESSION_COOKIE) ?? '');
1322
+ });
831
1323
  }
832
1324
 
833
- /** Revoke the caller's sessions, optionally keeping the current one. */
1325
+ /** Revoke the caller's auth rows. Reset and OAuth-state rows remain separate. */
834
1326
  export async function revokeAllUserSessions(c: Context, keepCurrent = false): Promise<void> {
1327
+ return sessions(async () => {
835
1328
  const { userId, currentId } = sessionOwner(c);
836
- await cms(c).authSessions.revokeAllForUser(userId, keepCurrent ? currentId : undefined);
1329
+ if (keepCurrent) {
1330
+ const currentReference = await currentSessionReference(userId, currentId);
1331
+ await sql`DELETE FROM sessions WHERE user_id = ${userId}
1332
+ AND id <> ${currentId} AND (public_id IS NULL OR public_id <> ${currentReference})
1333
+ AND kind = ${AUTH}`;
1334
+ } else {
1335
+ await sql`DELETE FROM sessions WHERE user_id = ${userId} AND kind = ${AUTH}`;
1336
+ }
1337
+ await endReachedOfUser(userId, keepCurrent ? currentId : '');
1338
+ });
837
1339
  }
838
1340
 
839
1341
  /** The session cookie name, exported so pages/middleware can read it. */
840
1342
  export const SESSION_COOKIE_NAME = SESSION_COOKIE;
841
1343
 
842
- /**
843
- * A person deletes their own account: the password confirms it, the site's only administrator
844
- * may not, every session ends, and the account goes with its memberships. Returns the headers
845
- * that clear the browser's session.
846
- */
1344
+ /** A person deletes their own account: the password confirms it, every session ends, and the row goes. Returns the headers that clear the browser's session. */
847
1345
  export async function deleteOwnAccount(c: Context, userId: string, password: string): Promise<{ headers: Headers }> {
1346
+ return accounts(async () => {
848
1347
  if (!(await passwordMatches(userId, password))) throw new ClientVisibleError('The password is not right.');
849
- const host = cms();
850
- const me = await host.users.get(userId);
851
- if (!me) throw new ClientVisibleError('The account was not found.');
852
- if (me.permissions.includes('*')) {
853
- const admins = await host.users.list({ role: 'admin', limit: 2 });
854
- if (admins.total <= 1) throw new ClientVisibleError('You are the only administrator. Make someone else an administrator first.');
1348
+ if ((await User.findOne({ where: { id: userId } }))?.networkAdmin && (await User.find({ where: { networkAdmin: true, status: 'active' }, take: 2 })).every((other) => other.id === userId)) {
1349
+ throw new ClientVisibleError('The last network administrator cannot delete their account. Make someone else one first.');
855
1350
  }
1351
+ // The application keeps an administrator.
1352
+ const lastAdmin = (await sql<{ total: number }>`
1353
+ SELECT COUNT(*) AS total FROM user_roles ur INNER JOIN roles r ON r.id = ur.role_id INNER JOIN users u ON u.id = ur.user_id
1354
+ WHERE r.id = 'admin' AND u.status = 'active' AND ur.user_id <> ${userId}
1355
+ `).rows[0];
1356
+ if ((await rolesHere(userId)).some((role) => role.id === 'admin') && !Number(lastAdmin?.total ?? 0)) throw new ClientVisibleError('The last administrator cannot delete their account. Give someone else the admin role first.');
856
1357
  await revokeSessionsOf(c, userId);
857
1358
  const { headers } = await logout(c);
858
- await host.users.delete(userId);
1359
+ await removeAccount(userId);
859
1360
  return { headers };
1361
+ });
860
1362
  }
861
1363
 
862
- /** How long a confirmation link lives. */
863
- const VERIFICATION_TTL_MS = 48 * 60 * 60_000;
864
-
865
- /**
866
- * Send the confirmation link, from and to the host that registered the account (this request's);
867
- * the token's hash in its cache names the account, and the site it registered for when that is
868
- * another (a network registration), until it is opened or two days pass.
869
- */
870
- async function sendVerification(host: CmsHost, userId: string, email: string, name: string, site: string | null): Promise<void> {
871
- const origin = linkOrigin();
872
- if (!host.mail || !origin) return;
873
- const token = randomToken(32);
874
- await host.cache.set(`verify:${await sha256Hex(token)}`, { user: userId, ...(site ? { site } : {}) }, VERIFICATION_TTL_MS);
875
- const title = await host.settings.get('general.siteTitle').catch(() => '');
876
- await host.mail.send({ kind: 'verification', to: email, from: host.mailFrom, subject: `Confirm your email for ${title || 'the site'}`,
877
- text: `Hello ${name || email},\n\nConfirm your email address to finish creating your account on ${title || origin}:\n${origin.replace(/\/$/, '')}/auth/verify?token=${token}\n\nThe link works for two days. If you did not register, ignore this email.` });
878
- }
879
-
880
- /**
881
- * Open a confirmation link: the token is spent, and the account becomes active, or keeps
882
- * waiting for an administrator's approval (`pending`). Null for an unknown or expired link.
883
- */
884
- /**
885
- * The email of the account a sign-in or confirmation link is for, read without spending the
886
- * link: its page shows it, so someone opening a link another person sent sees whose account
887
- * it would sign them into. Null for a link that is not valid.
888
- */
889
- export async function linkAccountEmail(kind: 'magic' | 'verify', token: string): Promise<string | null> {
890
- if (!/^[A-Za-z0-9_-]{20,128}$/.test(token)) return null;
891
- const host = cms();
892
- const found = await host.cache.get<{ user: string }>(`${kind}:${await sha256Hex(token)}`).catch(() => undefined);
893
- if (!found?.user) return null;
894
- const user = await host.users.get(found.user).catch(() => null);
895
- if (user?.email) return user.email;
896
- const account = await host.accounts.get(found.user).catch(() => null);
897
- return account?.email ?? null;
898
- }
899
-
900
- export async function verifyEmail(token: string): Promise<{ user: string; pending: boolean; site?: string } | null> {
901
- if (!/^[A-Za-z0-9_-]{20,128}$/.test(token)) return null;
902
- const key = `verify:${await sha256Hex(token)}`;
903
- const found = await cms().cache.take<{ user: string; site?: string }>(key);
904
- if (!found?.user) return null;
905
- // A network registration for another site waits on that site: its approval, its member.
906
- const c = getRequestContext();
907
- const record = found.site && c ? await networkFor(c.env as CmsBindings).sites.get(found.site).catch(() => null) : null;
908
- const host = record ? networkFor(c!.env as CmsBindings).hostOf(networkSite(record)) : cms();
909
- if (await host.users.confirmRegistration(found.user)) return { user: found.user, pending: true };
910
- // Only an account still waiting for this link becomes active: one an administrator disabled (or changed) since stays as it is.
911
- const account = await (await host.storesOf(found.user)).accounts.get(found.user).catch(() => null);
912
- if (!account?.unconfirmed) return null;
913
- await host.users.setStatus(found.user, 'active');
914
- return { user: found.user, pending: false, ...(record ? { site: record.id } : {}) };
915
- }
916
-
917
- /**
918
- * Approve a member who waits for it: their account becomes active and they get an email saying
919
- * so. False when they were not waiting; `CMS_VALIDATION` before their email is confirmed.
920
- */
921
- export async function approveRegistration(userId: string): Promise<boolean> {
922
- const host = cms();
923
- if (!(await host.users.approve(userId))) return false;
924
- const user = await host.users.get(userId);
925
- // The site's configured address, never the request's Host, which a caller could set.
926
- const origin = linkOrigin();
927
- if (user && host.mail) {
928
- const title = await host.settings.get('general.siteTitle').catch(() => '');
929
- const where = origin ? ` Sign in at:\n${origin.replace(/\/$/, '')}/auth/login\n` : '\n';
930
- await host.mail.send({ to: user.email, from: host.mailFrom, subject: `Your account on ${title || 'the site'} is ready`,
931
- text: `Hello ${user.name || user.email},\n\nAn administrator approved your account.${where}` }).catch(() => undefined);
932
- }
933
- return true;
934
- }
935
-
936
- /** How long a sign-in link lives. */
937
- const MAGIC_LINK_TTL_MS = 15 * 60_000;
938
-
939
1364
  /**
940
1365
  * Email a one-time sign-in link to an active account. Nothing says whether the email exists; a
941
1366
  * flood for one address or from one client stops after a few. Without a mail sender, nothing is sent.
942
1367
  */
943
1368
  export async function requestMagicLink(email: string, _requestOrigin?: string): Promise<void> {
944
- const host = cms();
945
- const origin = linkOrigin();
1369
+ return accountByEmail(email, () => accounts(async () => {
1370
+ const [mail, origin] = [mailer(), linkOrigin()];
946
1371
  if (!origin) return;
947
- const address = clientAddress();
948
- const allowedEmail = await host.security.attempt('magic', `e:${email.trim().toLowerCase()}`, RESET_REQUESTS.perEmail, RESET_REQUESTS.windowMs);
949
- const allowedAddress = await host.security.attempt('magic', `a:${address}`, RESET_REQUESTS.perAddress, RESET_REQUESTS.windowMs);
950
- if (!allowedEmail || !allowedAddress || !host.mail) return;
951
- const account = await host.signIn.accounts.findByEmail(email).catch(() => null);
1372
+ const key = await security.sha256Hex(email.trim().toLowerCase());
1373
+ const allowedEmail = await security.attempt('magic', `e:${key}`, security.RESET_REQUESTS.perEmail, security.RESET_REQUESTS.windowMs);
1374
+ const allowedAddress = await security.attempt('magic', `a:${clientAddress()}`, security.RESET_REQUESTS.perAddress, security.RESET_REQUESTS.windowMs);
1375
+ if (!allowedEmail || !allowedAddress || !mail) return;
1376
+ const account = await User.findOne({ where: { email } });
952
1377
  if (!account || account.status !== 'active') return;
953
- const token = randomToken(32);
954
- await host.cache.set(`magic:${await sha256Hex(token)}`, { user: account.id }, MAGIC_LINK_TTL_MS);
955
- const title = await host.settings.get('general.siteTitle').catch(() => '');
956
- await host.mail.send({ kind: 'magic-link', to: account.email, from: host.mailFrom, subject: `Sign in to ${title || 'the site'}`,
1378
+ const token = await createLink('magic', account.id, MAGIC_LINK_TTL_MS);
1379
+ const title = await siteName().catch(() => '');
1380
+ await mail.send({ kind: 'magic-link', to: account.email, subject: `Sign in to ${title || 'the site'}`,
957
1381
  text: `Open this link to sign in; it works once, for fifteen minutes:\n${origin}/auth/magic?token=${token}\n\nIf you did not ask for it, ignore this email.` });
1382
+ }), undefined);
958
1383
  }
959
1384
 
960
1385
  /** Spend a sign-in link: the account's ID, or null for a link that is unknown, spent or expired. */
961
1386
  export async function consumeMagicLink(token: string): Promise<string | null> {
962
- if (!/^[A-Za-z0-9_-]{20,128}$/.test(token)) return null;
963
- const host = cms();
964
- const key = `magic:${await sha256Hex(token)}`;
965
- // Taken in one conditional delete, so two requests with the same link cannot both sign in.
966
- const found = await host.cache.take<{ user: string }>(key);
967
- if (!found?.user) return null;
968
- const account = await host.signIn.accounts.get(found.user).catch(() => null);
969
- return account && account.status === 'active' ? account.id : null;
1387
+ return accountByToken(() => accounts(async () => {
1388
+ const userId = await takeLink('magic', token);
1389
+ if (!userId) return null;
1390
+ return (await User.findOne({ where: { id: userId } }))?.status === 'active' ? userId : null;
1391
+ }), value => value === null);
970
1392
  }
971
1393
 
972
1394
  // --- OAuth -------------------------------------------------------------------
973
- // The site's providers are its `oauth` option (src/cms.config.ts). Each reads
974
- // <PROVIDER>_CLIENT_ID and <PROVIDER>_CLIENT_SECRET; OAUTH_SECRET signs the state, which the
975
- // host's store spends once. /auth/<provider>/redirect and /callback are the routes.
976
- //
977
- // A provider proves an email address, as a sign-in link does: the account with that verified
978
- // address signs in, and still takes its second step. No provider identity is stored.
1395
+ // The providers are the project's choice (src/dashboard.config.ts: `oauth`). Each reads
1396
+ // <PROVIDER>_CLIENT_ID and <PROVIDER>_CLIENT_SECRET; OAUTH_SECRET signs the state.
1397
+ // /auth/<provider>/redirect and /auth/<provider>/callback are the pages beside the sign-in page.
979
1398
  const oauthVariables = (provider: string) => ({
980
1399
  clientId: `${provider.toUpperCase()}_CLIENT_ID`,
981
1400
  clientSecret: `${provider.toUpperCase()}_CLIENT_SECRET`,
982
1401
  });
983
1402
 
984
- /** Whether this site offers the provider. */
1403
+ /** Whether the project offers this provider. */
985
1404
  export function oauthProvider(provider: string): boolean {
986
- try { return cms().oauth.includes(provider); }
987
- catch { return false; }
1405
+ return authOptions.authMethods.includes('oauth') && (authOptions.oauth as readonly string[]).includes(provider);
988
1406
  }
989
1407
 
990
1408
  function oauthConfigurationError(c: Context, provider: string): OAuthError | null {
991
1409
  if (!oauthProvider(provider)) return new OAuthError('COSSACK_OAUTH_PROVIDER_UNKNOWN');
992
1410
  const variables = oauthVariables(provider);
993
- const env = c.env as Record<string, unknown>;
994
- if ([variables.clientId, variables.clientSecret].some(name => !String(env[name] ?? '').trim())) return new OAuthError('COSSACK_OAUTH_CREDENTIALS_MISSING');
995
- if (String(env.OAUTH_SECRET ?? '').length < 16) return new OAuthError('COSSACK_OAUTH_SECRET_INVALID');
1411
+ const missing = [variables.clientId, variables.clientSecret].filter((name) => !String(c.env[name] ?? '').trim());
1412
+ if (missing.length) {
1413
+ return new OAuthError('COSSACK_OAUTH_CREDENTIALS_MISSING');
1414
+ }
1415
+
1416
+ if (String(c.env.OAUTH_SECRET ?? '').length < 16) {
1417
+ return new OAuthError('COSSACK_OAUTH_SECRET_INVALID');
1418
+ }
996
1419
  return null;
997
1420
  }
998
1421
 
@@ -1002,15 +1425,33 @@ function oauthUnavailable(c: Context, error: OAuthError): Response {
1002
1425
  return c.json({ error: message, ...diagnostic }, error.status);
1003
1426
  }
1004
1427
 
1428
+ export const oauthStateStore: OAuthStateStore = {
1429
+ async create(record) {
1430
+ await accounts(() => Session.insert({ id: record.key, userId: null, kind: 'oauth_state',
1431
+ data: { provider: record.provider }, meta: null,
1432
+ createdAt: new Date(record.createdAt), expiresAt: new Date(record.expiresAt),
1433
+ location: null, userAgent: null, ipAddress: null }));
1434
+ },
1435
+ async consume(key, provider, now) {
1436
+ // One conditional write owns callback replay. Never read then delete.
1437
+ const result = await accounts(async () => sql`DELETE FROM sessions WHERE id = ${key}
1438
+ AND user_id IS NULL AND kind = ${'oauth_state' satisfies SessionKind} AND data = ${sql.json({ provider })}
1439
+ AND expires_at > ${new Date(Math.max(now, Date.now()))}`);
1440
+ return result.meta.rowsAffected === 1;
1441
+ },
1442
+ };
1443
+
1005
1444
  function createOAuthForRequest(c: Context): OAuthKit {
1006
- const host = cms(c);
1007
- const env = c.env as Record<string, unknown>;
1008
1445
  return createOAuth({
1009
- secret: String(env.OAUTH_SECRET ?? ''),
1010
- stateStore: host.oauthStates,
1011
- providers: Object.fromEntries(host.oauth.map(provider => {
1446
+ secret: String(c.env.OAUTH_SECRET ?? ''),
1447
+ stateStore: oauthStateStore,
1448
+ providers: Object.fromEntries(authOptions.oauth.map((provider) => {
1012
1449
  const variables = oauthVariables(provider);
1013
- return [provider, { clientId: String(env[variables.clientId] ?? ''), clientSecret: String(env[variables.clientSecret] ?? ''), redirectUrl: `/auth/${provider}/callback` }];
1450
+ return [provider, {
1451
+ clientId: String(c.env[variables.clientId] ?? ''),
1452
+ clientSecret: String(c.env[variables.clientSecret] ?? ''),
1453
+ redirectUrl: `/auth/${provider}/callback`,
1454
+ }];
1014
1455
  })),
1015
1456
  });
1016
1457
  }
@@ -1029,54 +1470,281 @@ export const oauth: OAuthKit = {
1029
1470
  };
1030
1471
 
1031
1472
  /**
1032
- * The provider sent the visitor back. Its verified email names the account: an active one signs
1033
- * in (through its second step, when it has one), and an unknown one becomes an account when
1034
- * registration is open, with the site's default role and its approval rule. The sign-in page
1035
- * says why a sign-in did not happen (`?oauth=<reason>`).
1473
+ * The provider sent the visitor back. A linked account signs in, through its second step when
1474
+ * it has one; an unknown one becomes an account only while registration is open, with the
1475
+ * default role and the approval rule. The sign-in page says why a sign-in did not happen
1476
+ * (`?oauth=<reason>`).
1036
1477
  */
1037
- export async function handleOAuthUser(_provider: string, oauthUser: OAuthUser, _tokens: TokenSet, c: Context) {
1038
- const refused = (reason: 'unverified' | 'closed' | 'pending' | 'inactive' | 'passkey') => c.redirect(`/auth/login?oauth=${reason}`);
1039
- const email = oauthUser.emailVerified === true && typeof oauthUser.email === 'string' ? oauthUser.email.trim().toLowerCase() : '';
1040
- // Only an address the provider verified may name or create an account.
1041
- if (!email) return refused('unverified');
1042
- const host = cms(c);
1043
- // The provider confirmed the address: a registration that never confirmed it gives way.
1044
- await replaceUnconfirmed(host, email, false);
1045
- let account = await host.signIn.accounts.findByEmail(email).catch(() => null);
1046
- if (!account) {
1047
- if (!(await registrationOpen())) return refused('closed');
1048
- const role = await host.settings.get('general.defaultRole');
1049
- let draft;
1050
- try {
1051
- draft = await host.registrationDraft({ email, name: (oauthUser.name ?? oauthUser.nickname ?? '').trim() || email.split('@')[0]!,
1052
- roles: role && (await host.users.role(role)) ? [role] : [], approval: await host.settings.get('general.approveRegistrations').catch(() => false) }, { origin: linkOrigin() ?? '' });
1053
- } catch (error) {
1054
- if (isCmsError(error, 'CMS_VALIDATION')) return refused('closed');
1478
+ export async function handleOAuthUser(
1479
+ provider: string,
1480
+ oauthUser: OAuthUser,
1481
+ _tokens: TokenSet,
1482
+ c: Context,
1483
+ ) {
1484
+ return accounts(async () => {
1485
+ const refused = (reason: 'closed' | 'pending' | 'inactive' | 'passkey') => c.redirect(`/auth/login?oauth=${reason}`);
1486
+ const account = await OAuthAccount.findOne({
1487
+ where: { provider, providerUserId: oauthUser.id },
1488
+ });
1489
+ let user = account
1490
+ ? await User.findOne({ where: { id: account.userId } })
1491
+ : null;
1492
+ // Only an address the provider verified may identify or claim an account.
1493
+ const verifiedEmail = oauthUser.emailVerified === true ? oauthUser.email : null;
1494
+ if (!user && verifiedEmail) {
1495
+ const existing = await User.findOne({ where: { email: verifiedEmail } });
1496
+ if (existing) throw new ClientVisibleError('Sign in to your existing account before linking an OAuth provider.');
1497
+ }
1498
+ if (!user) {
1499
+ // A new account is a registration: closed registration, the approval rule and the default role apply.
1500
+ const options = authOptions.registration;
1501
+ if (!options.open) return refused('closed');
1502
+ const email = verifiedEmail ?? `${provider}-${oauthUser.id}@oauth.invalid`;
1503
+ let name: string;
1504
+ try { name = (await authEvents.beforeRegister({ email, name: oauthUser.name ?? oauthUser.nickname ?? '' })).name; }
1505
+ catch (error) {
1506
+ if (error instanceof ClientVisibleError) return refused('closed');
1055
1507
  throw error;
1056
1508
  }
1057
- // The account has no password anyone knows: it signs in with the provider, or sets one through "Forgot password".
1058
- const user = await host.users.create({ email, password: randomToken(48), name: draft.name, roles: draft.roles,
1059
- ...(draft.approval ? { approval: { verified: true } } : {}) });
1060
- await host.userRegistered(user, draft.approval ? 'approval' : 'active').catch(() => undefined);
1061
- if (draft.approval) return refused('pending');
1062
- account = await host.signIn.accounts.get(user.id).catch(() => null);
1509
+ const id = uuidv7();
1510
+ await User.insert({
1511
+ id,
1512
+ email,
1513
+ name: name || null,
1514
+ passwordHash: null,
1515
+ avatar: oauthUser.avatar ?? null,
1516
+ meta: null,
1517
+ status: options.approve ? 'pending' : 'active',
1518
+ createdAt: new Date(),
1519
+ });
1520
+ const role = options.defaultRole ? await Role.findOne({ where: { id: options.defaultRole } }) ?? await Role.findOne({ where: { name: options.defaultRole } }) : null;
1521
+ if (role) await UserRole.insert({ userId: id, roleId: role.id, createdAt: new Date() });
1522
+ await authEvents.registered({ id, email, name }, options.approve ? 'approval' : 'active');
1523
+ user = await User.findOne({ where: { id } });
1063
1524
  }
1064
- if (!account || account.status !== 'active') {
1065
- return refused(account && await host.users.awaitingApproval(account.id).catch(() => false) ? 'pending' : 'inactive');
1525
+ if (!user) throw new Error('Unable to provision OAuth user.');
1526
+ if (!account) {
1527
+ await OAuthAccount.insert({
1528
+ id: uuidv7(),
1529
+ userId: user.id,
1530
+ provider,
1531
+ providerUserId: oauthUser.id,
1532
+ createdAt: new Date(),
1533
+ });
1066
1534
  }
1067
- // The provider stands in for the password only: an enrolled authenticator is still asked for.
1535
+ if (user.status !== 'active') return refused(user.status === 'pending' ? 'pending' : 'inactive');
1536
+ // The provider stands in for the password only: an authenticator app is still asked for.
1068
1537
  let pending: string | null;
1069
- try { pending = await beginTwoFactor(account.id); }
1538
+ try { pending = await beginTwoFactor(user.id); }
1070
1539
  catch (error) {
1071
1540
  if (!(error instanceof SignInPasskeyError)) throw error;
1072
1541
  return refused('passkey');
1073
1542
  }
1074
1543
  if (pending) {
1075
- const secure = new URL(c.req.url).protocol === 'https:';
1076
- c.header('set-cookie', `${TWO_FACTOR_COOKIE}=${pending}; Path=/; HttpOnly; SameSite=Lax; Max-Age=300${secure ? '; Secure' : ''}`, { append: true });
1544
+ setCookie(c, TWO_FACTOR_COOKIE, pending, { path: '/', httpOnly: true, sameSite: 'Lax', maxAge: 300, secure: new URL(c.req.url).protocol === 'https:' });
1077
1545
  return c.redirect('/auth/two-factor');
1078
1546
  }
1079
- const { headers } = await authSessions.create(account.id, c);
1080
- headers.forEach((value, key) => c.header(key, value, { append: key.toLowerCase() === 'set-cookie' }));
1547
+ if (auth.createSession) {
1548
+ const { headers } = await auth.createSession(publicUser(user), c);
1549
+ headers.forEach((value, key) => c.header(key, value));
1550
+ }
1081
1551
  return c.redirect(config('auth.redirectAfterLogin'));
1552
+ });
1553
+ }
1554
+
1555
+
1556
+ // --- Tenants ---------------------------------------------------------------
1557
+ /** Whether the project runs tenants (src/dashboard.config.ts: `tenants`). The CMS has sites instead. */
1558
+ export const tenantsAvailable = authOptions.tenants.enabled;
1559
+ export {
1560
+ addTenantDomain, addTenantMember, createTenant, listNetworkAdmins, listTenantMembers, listTenants, networkRunning, removeTenantDomain, removeTenantMember,
1561
+ registerTenant, setNetworkAdmin, setNetworkRunning, setPrimaryTenantDomain, setTenantRegistration, setTenantStatus, tenantRegistrationOpen, tenantsOf, verifyTenantDomain,
1562
+ type NetworkAdminSummary, type TenantDomainSummary, type TenantMemberSummary, type TenantSummary,
1563
+ } from './services/tenants';
1564
+ export { tenantOrigin } from './tenants';
1565
+
1566
+ /** Whether this request is on the main host, where tenants are managed. */
1567
+ export function onMainHost(): boolean {
1568
+ return !currentTenant();
1569
+ }
1570
+
1571
+ // Shared sign-in (`tenants.signIn: 'shared'`): people sign in on the main host, and a tenant's
1572
+ // host gets a session of its own from a one-time code. src/middlewares/tenant.ts sends
1573
+ // visitors here; the two endpoints are /auth/tenant/redirect and /auth/tenant/callback.
1574
+ export const sharedSignInAvailable = sharedSignIn;
1575
+ const HANDOFF_MS = 60_000;
1576
+
1577
+ async function handoffId(code: string): Promise<string> {
1578
+ return sessionFingerprint(`tenant-handoff:${code}`);
1579
+ }
1580
+
1581
+ /**
1582
+ * On the main host, for a signed-in account: a one-time code for the tenant at `host`, and the
1583
+ * address on that host which trades it for a session. `error` says why there is none.
1584
+ */
1585
+ export async function issueTenantHandoff(c: Context, host: string, state: string, next: string | null): Promise<{ url: string } | { error: string; status: 400 | 403 | 404 }> {
1586
+ return accounts(async () => {
1587
+ if (!sharedSignIn || currentTenant()) return { error: 'Not found.', status: 404 as const };
1588
+ const user = c.get('user') as PublicUser | undefined;
1589
+ const sessionId = getCookie(c, SESSION_COOKIE);
1590
+ const name = hostName(`http://${host}`);
1591
+ if (!user || !sessionId || !name || !/^[A-Za-z0-9_-]{16,128}$/.test(state)) return { error: 'The request is not complete.', status: 400 as const };
1592
+ const tenant = name === mainHost() ? null : await tenantOfHost(name);
1593
+ if (!tenant || tenant.status !== 'active') return { error: 'There is no such site.', status: 404 as const };
1594
+ const member = await TenantMember.exists({ tenantId: tenant.id, userId: user.id });
1595
+ if (!member && !user.networkAdmin) return { error: `This account is not a member of ${tenant.name}.`, status: 403 as const };
1596
+ const code = randomToken();
1597
+ await TenantHandoff.delete({ expiresAt: LessThan(new Date()) });
1598
+ await TenantHandoff.insert({ id: await handoffId(code), sessionId, userId: user.id, tenantId: tenant.id, expiresAt: new Date(Date.now() + HANDOFF_MS) });
1599
+ // The tenant's host, with the scheme and port of this request.
1600
+ const url = new URL(c.req.url);
1601
+ url.hostname = name;
1602
+ url.pathname = '/auth/tenant/callback';
1603
+ url.search = new URLSearchParams({ code, state, ...(next ? { next } : {}) }).toString();
1604
+ return { url: url.toString() };
1605
+ });
1606
+ }
1607
+
1608
+ /**
1609
+ * On a tenant's host: trade the code for a session there, linked to the main host's session.
1610
+ * The code works once, for this tenant, for a minute, and only while that session is alive.
1611
+ * Returns the response headers that set the cookie, or null.
1612
+ */
1613
+ export async function completeTenantHandoff(c: Context, code: string): Promise<Headers | null> {
1614
+ return accounts(async () => {
1615
+ const tenant = currentTenant();
1616
+ if (!sharedSignIn || !tenant || !/^[A-Za-z0-9_-]{16,128}$/.test(code)) return null;
1617
+ const id = await handoffId(code);
1618
+ const row = await TenantHandoff.findOne({ where: { id } });
1619
+ // One conditional delete owns the code: a second request with it finds nothing.
1620
+ const taken = await TenantHandoff.delete({ id, tenantId: tenant.id });
1621
+ if (!row || row.tenantId !== tenant.id || taken.meta.rowsAffected !== 1 || row.expiresAt.getTime() <= Date.now()) return null;
1622
+ // The code names a session of the main host, which must still be alive.
1623
+ c.set('auth.sessionHome' as never, 'main' as never);
1624
+ let reference: string | null;
1625
+ let secondFactor = false;
1626
+ try {
1627
+ const parent = await authSessions.validate(row.sessionId, c);
1628
+ if (!parent || parent.userId !== row.userId) return null;
1629
+ const stored = await Session.findOne({ where: { id: parent.id } });
1630
+ reference = stored ? (await sessionWithReference(stored, row.userId))?.publicId ?? null : null;
1631
+ // The sign-in on the main host is the tenant session's sign-in: a second factor used there counts here.
1632
+ secondFactor = stored?.secondFactor === true;
1633
+ } finally { c.set('auth.sessionHome' as never, undefined as never); }
1634
+ if (!reference) return null;
1635
+ // The tenant's own session, in its database, made from that one.
1636
+ c.set('auth.sessionParent' as never, reference as never);
1637
+ c.set('auth.signInSecondFactor', secondFactor);
1638
+ try { return (await authSessions.create(row.userId, c)).headers; }
1639
+ finally { c.set('auth.signInSecondFactor', false); }
1640
+ });
1641
+ }
1642
+
1643
+ /**
1644
+ * On the main host: the tenant a one-time code for `host` would sign in to. `custom` is true for
1645
+ * a domain of the tenant's own: whoever runs that domain reads the code, so the main host asks
1646
+ * the person before it sends one there. A host under the main host is the application's own,
1647
+ * and a `localhost` name is this machine's.
1648
+ */
1649
+ export async function tenantHandoffTarget(host: string): Promise<{ name: string; host: string; custom: boolean } | null> {
1650
+ return asMainAccount(() => accounts(async () => {
1651
+ const name = hostName(`http://${host}`);
1652
+ const main = mainHost();
1653
+ if (!sharedSignIn || currentTenant() || !name || name === main) return null;
1654
+ const tenant = await tenantOfHost(name);
1655
+ if (!tenant || tenant.status !== 'active') return null;
1656
+ // Names under the main host are the application's, and `localhost` names reach this machine only.
1657
+ const own = (!!main && name.endsWith(`.${main}`)) || name === 'localhost' || name.endsWith('.localhost');
1658
+ return { name: tenant.name, host: name, custom: !own };
1659
+ }));
1660
+ }
1661
+
1662
+ /** On the main host: the sign-in page of the tenant at `host`, or null when the host is no active tenant's. */
1663
+ export async function tenantSignInUrl(c: Context, host: string): Promise<string | null> {
1664
+ return asMainAccount(() => accounts(async () => {
1665
+ const name = hostName(`http://${host}`);
1666
+ if (!sharedSignIn || currentTenant() || !name || name === mainHost()) return null;
1667
+ const tenant = await tenantOfHost(name);
1668
+ if (!tenant || tenant.status !== 'active') return null;
1669
+ const url = new URL(c.req.url);
1670
+ url.hostname = name;
1671
+ url.pathname = '/auth/login';
1672
+ url.search = '';
1673
+ return url.toString();
1674
+ }));
1675
+ }
1676
+
1677
+ // --- Invitations -------------------------------------------------------------
1678
+ /** Whether an invitation can be sent: it needs an email sender and the site's address (APP_URL). */
1679
+ export function canInvite(): boolean {
1680
+ return mailer() !== null && linkOrigin() !== null;
1681
+ }
1682
+
1683
+ /**
1684
+ * Email an account a link to set its password, good for seven days: an administrator made the
1685
+ * account without choosing a password. False when no email could be sent.
1686
+ */
1687
+ export async function sendInvitation(userId: string): Promise<boolean> {
1688
+ return accountOf(userId, async () => {
1689
+ const [user, mail, origin] = [await User.findOne({ where: { id: userId } }), mailer(), linkOrigin()];
1690
+ if (!user || !mail || !origin) return false;
1691
+ const token = await createPasswordResetToken(user.email, 7 * 24 * 60 * 60 * 1000);
1692
+ if (!token) return false;
1693
+ const title = currentTenant()?.name ?? await siteName().catch(() => '');
1694
+ await mail.send({ kind: 'invitation', to: user.email, subject: `You are invited to ${title || 'the site'}`,
1695
+ text: `Hello ${user.name || user.email},\n\nAn account was made for you on ${title || origin}. Set your password here within seven days:\n${origin}/auth/reset-password?token=${token}\n\nIf you were not expecting this, ignore this email.` });
1696
+ return true;
1697
+ });
1698
+ }
1699
+
1700
+ // --- Recovery mode -----------------------------------------------------------
1701
+ /** The shortest recovery code that turns recovery mode on. */
1702
+ export const RECOVERY_CODE_MIN_LENGTH = 24;
1703
+ const RECOVERY_ATTEMPTS = Object.freeze({ max: 5, windowMs: 15 * 60_000 });
1704
+
1705
+ export interface RecoveryResult {
1706
+ email: string;
1707
+ /** Open it within the hour to choose a new password. */
1708
+ resetUrl: string;
1709
+ expiresAt: number;
1710
+ /** The authenticator app, recovery codes and passkeys were removed too. */
1711
+ secondFactorsCleared: boolean;
1712
+ }
1713
+
1714
+ /**
1715
+ * Recovery mode, for someone who can change the environment and is locked out of the
1716
+ * dashboard: with RECOVERY_CODE set (24 characters or more), `POST /auth/recovery` with that
1717
+ * code makes a one-hour reset link for an active account, and can remove its second factors.
1718
+ * The account is told by email when the site can send one. `status` says why there is no link.
1719
+ */
1720
+ export async function recoverAccount(code: unknown, email: unknown, clearSecondFactors = false): Promise<RecoveryResult | { error: string; status: 400 | 401 | 403 | 404 | 429 }> {
1721
+ const address = typeof email === 'string' ? email.trim().toLowerCase() : '';
1722
+ return accountByEmail(address, () => accounts(async () => {
1723
+ const expected = env(authOptions.recoveryCodeVariable, '').trim();
1724
+ if (!expected) return { error: `Recovery mode is off: set ${authOptions.recoveryCodeVariable} in the environment to turn it on.`, status: 403 as const };
1725
+ if (expected.length < RECOVERY_CODE_MIN_LENGTH) return { error: `${authOptions.recoveryCodeVariable} must be at least ${RECOVERY_CODE_MIN_LENGTH} characters.`, status: 403 as const };
1726
+ if (!(await security.attempt('recovery', `a:${clientAddress()}`, RECOVERY_ATTEMPTS.max, RECOVERY_ATTEMPTS.windowMs))) return { error: 'Too many recovery attempts. Wait fifteen minutes.', status: 429 as const };
1727
+ if (typeof code !== 'string' || !(await sameSecret(code, expected))) return { error: 'The recovery code is not correct.', status: 401 as const };
1728
+ if (!address || address.length > 254 || !address.includes('@')) return { error: 'Give the email address of the account.', status: 400 as const };
1729
+ const origin = linkOrigin();
1730
+ const user = await User.findOne({ where: { email: address } });
1731
+ if (!user || user.status !== 'active') return { error: 'No active account has this email.', status: 404 as const };
1732
+ if (!origin) return { error: 'Set APP_URL: without the site\'s address no reset link can be made.', status: 400 as const };
1733
+ const token = await createPasswordResetToken(address);
1734
+ if (!token) return { error: 'No active account has this email.', status: 404 as const };
1735
+ if (clearSecondFactors) await security.reset(user.id);
1736
+ console.warn(`[Cossack Auth] recovery mode made a reset link for ${user.id}${clearSecondFactors ? ' and removed its second factors' : ''}`);
1737
+ await mailer()?.send({ to: user.email, subject: 'A password reset link was made for your account',
1738
+ text: `Someone with access to the site's settings used recovery mode to make a password reset link for your account${clearSecondFactors ? ', and removed its second factors' : ''}. If this was not you or your administrator, tell the site's owner.` }).catch(() => undefined);
1739
+ return { email: user.email, resetUrl: `${origin}/auth/reset-password?token=${token}`, expiresAt: Date.now() + 60 * 60 * 1000, secondFactorsCleared: clearSecondFactors };
1740
+ }), { error: 'Recover a main account on the main host.', status: 400 as const });
1741
+ }
1742
+
1743
+ /** The newest sign-ins on this host that are still signed in (a session ends at sign-out), for an overview. */
1744
+ export async function recentSignIns(limit = 8): Promise<{ userId: string; createdAt: number; userAgent: string | null; ip: string | null }[]> {
1745
+ return sessions(async () => {
1746
+ const rows = (await Session.find({ where: { expiresAt: MoreThan(new Date()) }, order: { createdAt: 'desc' }, take: Math.min(Math.max(limit, 1), 50) * 3 }))
1747
+ .filter((row) => row.userId && row.kind === 'auth').slice(0, limit);
1748
+ return rows.map((row) => ({ userId: row.userId!, createdAt: row.createdAt.getTime(), userAgent: row.userAgent, ip: row.ipAddress }));
1749
+ });
1082
1750
  }