@cossackframework/cms 0.9.2 → 0.9.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/agent-docs.json +8 -8
- package/app/cossack-recipe.json +12 -8
- package/app/src/auth-events.ts +33 -0
- package/app/src/auth-input.ts +3 -0
- package/app/src/auth-options.ts +39 -7
- package/app/src/auth.ts +1309 -641
- package/app/src/avatars.ts +13 -0
- package/app/src/brand.ts +24 -2
- package/app/src/cms/actor.ts +13 -0
- package/app/src/cms/collab/room.ts +1 -1
- package/app/src/cms/content-api.ts +2 -1
- package/app/src/cms/content.ts +3 -2
- package/app/src/cms/dev-mail.ts +77 -0
- package/app/src/cms/index.ts +37 -10
- package/app/src/cms/maintenance.ts +1 -6
- package/app/src/cms/manage.ts +17 -14
- package/app/src/cms/middleware.ts +58 -18
- package/app/src/cms/network-accounts.ts +110 -0
- package/app/src/cms/notes-announce.ts +1 -1
- package/app/src/cms/people.ts +177 -0
- package/app/src/cms/recovery.ts +9 -14
- package/app/src/cms/request-calls.ts +56 -0
- package/app/src/cms/settings-form.ts +23 -6
- package/app/src/cms/settings-network.ts +8 -4
- package/app/src/cms/settings-search.ts +1 -0
- package/app/src/cms/site-editing.ts +3 -2
- package/app/src/cms/site-registration.ts +64 -0
- package/app/src/cms/site.ts +30 -19
- package/app/src/cms/sites.ts +182 -0
- package/app/src/dashboard/access.ts +3 -2
- package/app/src/dashboard/modules/users.ts +1 -0
- package/app/src/lib/permissions.ts +24 -0
- package/app/src/lib/uuid.ts +6 -0
- package/app/src/mail.ts +15 -0
- package/app/src/middlewares/auth.ts +6 -2
- package/app/src/middlewares/tenant.ts +108 -0
- package/app/src/pages/(site)/[...path]/index.ts +1 -1
- package/app/src/pages/(site)/preview/[collection]/[id]/index.ts +1 -1
- package/app/src/pages/api/cms/dev/mail.ts +19 -0
- package/app/src/pages/api/cms/forms/[slug]/index.ts +1 -1
- package/app/src/pages/api/cms/users/[id]/meta.ts +2 -1
- package/app/src/pages/auth/login/index.ts +1 -1
- package/app/src/pages/auth/magic/index.ts +1 -1
- package/app/src/pages/auth/recovery.ts +20 -0
- package/app/src/pages/auth/register-site/index.ts +146 -0
- package/app/src/pages/auth/setup/index.ts +8 -3
- package/app/src/pages/auth/tenant/callback.ts +23 -0
- package/app/src/pages/auth/tenant/redirect.ts +91 -0
- package/app/src/pages/auth/verify/index.ts +3 -7
- package/app/src/pages/dashboard/(cms)/appearance/menus/[id]/index.ts +1 -1
- package/app/src/pages/dashboard/(cms)/content/[collection]/[id]/index.ts +5 -5
- package/app/src/pages/dashboard/(cms)/content/[collection]/[id]/revisions/index.ts +1 -1
- package/app/src/pages/dashboard/(cms)/content/[collection]/index.ts +1 -1
- package/app/src/pages/dashboard/(cms)/network/index.ts +4 -2
- package/app/src/pages/dashboard/(cms)/network/sites/[id]/index.ts +16 -13
- package/app/src/pages/dashboard/(cms)/network/sites/index.ts +4 -2
- package/app/src/pages/dashboard/(cms)/network/sites/new/index.ts +1 -1
- package/app/src/pages/dashboard/(cms)/network/users/[id]/index.ts +29 -10
- package/app/src/pages/dashboard/(cms)/network/users/index.ts +8 -7
- package/app/src/pages/dashboard/(cms)/network/users/new/index.ts +2 -1
- package/app/src/pages/dashboard/(cms)/registrations/index.ts +5 -4
- package/app/src/pages/dashboard/(cms)/tools/health/index.ts +4 -1
- package/app/src/pages/dashboard/(cms)/tools/replace/index.ts +2 -1
- package/app/src/pages/dashboard/(cms)/tools/seo/index.ts +1 -1
- package/app/src/pages/dashboard/index.ts +3 -2
- package/app/src/pages/dashboard/roles/index.ts +2 -2
- package/app/src/pages/dashboard/users/registrations/index.ts +66 -0
- package/app/src/services/api-tokens.ts +86 -0
- package/app/src/services/rbac.ts +26 -15
- package/app/src/services/roles.ts +125 -35
- package/app/src/services/security.ts +384 -0
- package/app/src/services/tenants.ts +447 -0
- package/app/src/services/users.ts +241 -97
- package/app/src/tenants.ts +219 -0
- package/package.json +48 -12
- package/src/block-references.ts +3 -3
- package/src/collections.ts +3 -1
- package/src/forms.ts +4 -2
- package/src/hooks.ts +19 -1
- package/src/index.ts +4 -4
- package/src/isolate-core.ts +1 -1
- package/src/isolation.ts +1 -0
- package/src/manifest.ts +43 -2
- package/src/permissions.ts +13 -7
- package/src/resource.ts +85 -2
- package/src/server/attempts.ts +64 -0
- package/src/server/automations.ts +2 -2
- package/src/server/batch.ts +106 -0
- package/src/server/budget.ts +17 -0
- package/src/server/field-values.ts +207 -0
- package/src/server/forms.ts +3 -3
- package/src/server/host-schema.ts +55 -7
- package/src/server/host.ts +213 -85
- package/src/server/index.ts +9 -14
- package/src/server/isolation.ts +10 -0
- package/src/server/network.ts +129 -44
- package/src/server/outbox.ts +2 -2
- package/src/server/people.ts +191 -0
- package/src/server/reconcile.ts +5 -5
- package/src/server/repository.ts +243 -84
- package/src/server/shared-read.ts +34 -0
- package/src/server/site-export.ts +23 -13
- package/src/server/site-import.ts +12 -33
- package/src/server/site-settings.ts +9 -3
- package/src/server/sites.ts +117 -187
- package/src/server/stores.ts +3 -300
- package/src/server/taxonomies.ts +64 -13
- package/src/server/users.ts +151 -498
- package/src/settings-controls.ts +8 -4
- package/src/settings.ts +26 -3
- package/src/storage/cloudflare.ts +2 -0
- package/src/storage/index.ts +6 -0
- package/src/theme.ts +2 -2
- package/src/version.ts +1 -1
- package/app/src/cms/handoff.ts +0 -202
- package/src/server/accounts.ts +0 -418
- package/src/server/api-tokens.ts +0 -91
- package/src/server/auth.ts +0 -89
- package/src/server/handoffs.ts +0 -107
- package/src/server/security.ts +0 -391
package/app/src/auth.ts
CHANGED
|
@@ -1,36 +1,81 @@
|
|
|
1
1
|
// src/auth.ts
|
|
2
2
|
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
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
|
-
|
|
13
|
-
|
|
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 {
|
|
20
|
-
import {
|
|
21
|
-
import {
|
|
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
|
-
//
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
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
|
-
|
|
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
|
-
/**
|
|
42
|
-
|
|
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
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
roles:
|
|
57
|
-
|
|
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
|
-
/**
|
|
62
|
-
|
|
63
|
-
|
|
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
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
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
|
-
*
|
|
76
|
-
*
|
|
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
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
const
|
|
83
|
-
|
|
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
|
|
92
|
-
// A
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
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
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
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
|
-
|
|
127
|
-
|
|
128
|
-
const
|
|
129
|
-
if (!
|
|
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
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
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
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
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
|
-
|
|
150
|
-
|
|
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
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
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
|
-
*
|
|
171
|
-
*
|
|
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
|
-
|
|
176
|
-
|
|
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
|
|
180
|
-
if (!
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
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
|
|
214
|
-
*
|
|
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
|
|
234
|
-
*
|
|
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
|
-
|
|
239
|
-
if (!(await
|
|
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
|
|
243
|
-
const
|
|
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
|
|
480
|
+
if (matches) await security.release('password-check', userId);
|
|
247
481
|
return matches;
|
|
482
|
+
});
|
|
248
483
|
}
|
|
249
484
|
|
|
250
|
-
/**
|
|
251
|
-
export
|
|
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
|
|
255
|
-
* application
|
|
256
|
-
*
|
|
257
|
-
*
|
|
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
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
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
|
-
*
|
|
276
|
-
*
|
|
277
|
-
*
|
|
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
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
}
|
|
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
|
-
|
|
296
|
-
|
|
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
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
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
|
-
*
|
|
308
|
-
*
|
|
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
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
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
|
|
318
|
-
*
|
|
319
|
-
*
|
|
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
|
-
|
|
325
|
-
const
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
const
|
|
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 && !
|
|
344
|
-
console.warn('[
|
|
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
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
}
|
|
362
|
-
|
|
363
|
-
|
|
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
|
-
*
|
|
369
|
-
*
|
|
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
|
|
373
|
-
|
|
374
|
-
const
|
|
375
|
-
if (!
|
|
376
|
-
|
|
377
|
-
|
|
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
|
-
*
|
|
382
|
-
*
|
|
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
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
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
|
|
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
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
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
|
|
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
|
-
|
|
428
|
-
|
|
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
|
-
*
|
|
432
|
-
*
|
|
433
|
-
|
|
434
|
-
|
|
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
|
-
|
|
438
|
-
const { security } = host.signIn;
|
|
859
|
+
return accountOf(userId, async () => {
|
|
439
860
|
if (await security.requiresCode(userId)) return security.createChallenge('signin', userId, 'password');
|
|
440
|
-
|
|
441
|
-
|
|
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
|
-
|
|
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
|
|
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
|
|
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
|
-
|
|
478
|
-
return { ...status, passkeysManagedAt:
|
|
898
|
+
return accountOf(userId, async () => {
|
|
899
|
+
return { ...await security.status(userId), passkeysManagedAt: await passkeysElsewhere(userId) };
|
|
900
|
+
});
|
|
479
901
|
}
|
|
480
902
|
|
|
481
903
|
/**
|
|
482
|
-
*
|
|
483
|
-
*
|
|
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
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
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:
|
|
508
|
-
*
|
|
509
|
-
*
|
|
510
|
-
*
|
|
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
|
-
|
|
514
|
-
|
|
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('
|
|
532
|
-
if (!
|
|
533
|
-
if (await
|
|
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
|
|
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
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
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
|
|
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
|
-
|
|
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('
|
|
588
|
-
if (!
|
|
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
|
-
|
|
998
|
+
return accountOf(userId, async () => {
|
|
999
|
+
requireFactorUsed(userId);
|
|
603
1000
|
await checkAccountCode(userId, code);
|
|
604
|
-
await
|
|
1001
|
+
await security.disableTotp(userId);
|
|
1002
|
+
});
|
|
605
1003
|
}
|
|
606
1004
|
|
|
607
1005
|
export async function newRecoveryCodes(userId: string, code: string): Promise<string[]> {
|
|
608
|
-
|
|
1006
|
+
return accountOf(userId, async () => {
|
|
1007
|
+
requireFactorUsed(userId);
|
|
609
1008
|
await checkAccountCode(userId, code);
|
|
610
|
-
return
|
|
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
|
|
616
|
-
|
|
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
|
|
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
|
-
|
|
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(
|
|
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
|
-
|
|
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')))
|
|
646
|
-
|
|
647
|
-
|
|
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
|
-
|
|
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
|
-
|
|
658
|
-
|
|
659
|
-
await
|
|
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
|
-
|
|
671
|
-
|
|
672
|
-
|
|
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
|
|
677
|
-
|
|
678
|
-
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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.
|
|
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
|
|
707
|
-
|
|
708
|
-
//
|
|
709
|
-
|
|
710
|
-
|
|
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
|
-
|
|
713
|
-
|
|
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
|
|
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
|
-
|
|
720
|
-
await
|
|
1128
|
+
requireFactorUsed(userId);
|
|
1129
|
+
await apiTokens.revoke(userId, id);
|
|
1130
|
+
});
|
|
721
1131
|
}
|
|
722
1132
|
|
|
723
|
-
// --- Password reset ----------------------------------------------------------
|
|
724
1133
|
/**
|
|
725
|
-
*
|
|
726
|
-
*
|
|
727
|
-
*
|
|
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
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
}
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
const resetUrl = `${resetBaseUrl.replace(/\/$/, '')}/auth/reset-password?token=${
|
|
754
|
-
await
|
|
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
|
|
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
|
-
/**
|
|
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
|
-
|
|
767
|
-
|
|
768
|
-
|
|
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
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
806
|
-
const host = cms(c);
|
|
1262
|
+
return sessions(async () => {
|
|
807
1263
|
const currentId = getCookie(c, SESSION_COOKIE);
|
|
808
|
-
const
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
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
|
-
/**
|
|
816
|
-
export async function
|
|
817
|
-
|
|
818
|
-
|
|
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
|
|
822
|
-
export async function
|
|
823
|
-
|
|
824
|
-
|
|
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
|
-
/**
|
|
828
|
-
export async function
|
|
829
|
-
|
|
830
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
850
|
-
|
|
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
|
|
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
|
-
|
|
945
|
-
const origin = linkOrigin();
|
|
1369
|
+
return accountByEmail(email, () => accounts(async () => {
|
|
1370
|
+
const [mail, origin] = [mailer(), linkOrigin()];
|
|
946
1371
|
if (!origin) return;
|
|
947
|
-
const
|
|
948
|
-
const allowedEmail = await
|
|
949
|
-
const allowedAddress = await
|
|
950
|
-
if (!allowedEmail || !allowedAddress || !
|
|
951
|
-
const account = await
|
|
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 =
|
|
954
|
-
await
|
|
955
|
-
|
|
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
|
-
|
|
963
|
-
const
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
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
|
|
974
|
-
// <PROVIDER>_CLIENT_ID and <PROVIDER>_CLIENT_SECRET; OAUTH_SECRET signs the state
|
|
975
|
-
//
|
|
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
|
|
1403
|
+
/** Whether the project offers this provider. */
|
|
985
1404
|
export function oauthProvider(provider: string): boolean {
|
|
986
|
-
|
|
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
|
|
994
|
-
if (
|
|
995
|
-
|
|
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:
|
|
1011
|
-
providers: Object.fromEntries(
|
|
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, {
|
|
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.
|
|
1033
|
-
*
|
|
1034
|
-
*
|
|
1035
|
-
*
|
|
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(
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
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
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
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 (!
|
|
1065
|
-
|
|
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
|
-
|
|
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(
|
|
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
|
-
|
|
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
|
-
|
|
1080
|
-
|
|
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
|
}
|