@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
|
@@ -1,8 +1,13 @@
|
|
|
1
|
+
import { Like, Not, sql } from '@cossackframework/database';
|
|
1
2
|
import { ClientVisibleError, getRequestContext } from '@cossackframework/core';
|
|
2
|
-
import {
|
|
3
|
-
import
|
|
4
|
-
import {
|
|
5
|
-
import
|
|
3
|
+
import { uuidv7 } from '../lib/uuid';
|
|
4
|
+
import { holdsAll, validPermission } from '../lib/permissions';
|
|
5
|
+
import { authOptions } from '../auth-options';
|
|
6
|
+
import { permissionsOf } from './rbac';
|
|
7
|
+
import { Role } from '@/models/Role';
|
|
8
|
+
import { UserRole } from '@/models/UserRole';
|
|
9
|
+
|
|
10
|
+
const ADMIN_ROLE = 'admin';
|
|
6
11
|
|
|
7
12
|
export interface RoleDetail {
|
|
8
13
|
id: string;
|
|
@@ -27,63 +32,148 @@ export interface ListRolesResult {
|
|
|
27
32
|
|
|
28
33
|
export interface CreateRoleInput {
|
|
29
34
|
name: string;
|
|
30
|
-
|
|
35
|
+
/** Permissions of the list, `*`, or patterns over the list such as `user:*`. */
|
|
36
|
+
permissions?: string[];
|
|
31
37
|
}
|
|
32
38
|
|
|
33
39
|
export interface UpdateRoleInput {
|
|
34
40
|
name?: string;
|
|
35
|
-
permissions?:
|
|
41
|
+
permissions?: string[];
|
|
36
42
|
}
|
|
37
43
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
44
|
+
/** Who changes a role: with one, the role gets only permissions the actor holds. */
|
|
45
|
+
export interface RoleActor { roles: readonly { name: string; permissions: readonly string[] }[] }
|
|
46
|
+
|
|
47
|
+
/** The signed-in user of this request changes the role, unless the caller names another actor. A seeder or a command has none. */
|
|
48
|
+
function requestActor(): RoleActor | undefined {
|
|
49
|
+
return getRequestContext()?.get('user' as never) as RoleActor | undefined;
|
|
41
50
|
}
|
|
42
51
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
52
|
+
function validatePermissions(permissions: string[], actor?: RoleActor): string[] {
|
|
53
|
+
const invalid = permissions.filter((permission) => !validPermission(permission));
|
|
54
|
+
if (invalid.length) {
|
|
55
|
+
throw new ClientVisibleError(`Unknown permission(s): ${invalid.join(', ')}`);
|
|
56
|
+
}
|
|
57
|
+
// A role manager gives only permissions they hold.
|
|
58
|
+
const missing = actor ? permissions.filter((permission) => !holdsAll(permissionsOf(actor), [permission])) : [];
|
|
59
|
+
if (missing.length) throw new ClientVisibleError(`You cannot give a role permissions you do not have: ${missing.join(', ')}.`);
|
|
60
|
+
return [...new Set(permissions)].sort();
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function toDetail(role: Role): RoleDetail {
|
|
64
|
+
return {
|
|
65
|
+
id: role.id,
|
|
66
|
+
name: role.name,
|
|
67
|
+
permissions: role.permissions ?? [],
|
|
68
|
+
createdAt: role.createdAt.toISOString(),
|
|
69
|
+
};
|
|
46
70
|
}
|
|
47
71
|
|
|
48
72
|
export async function listRoles(): Promise<RoleDetail[]>;
|
|
49
73
|
export async function listRoles(options: ListRolesOptions): Promise<ListRolesResult>;
|
|
50
74
|
export async function listRoles(options: ListRolesOptions = {}): Promise<RoleDetail[] | ListRolesResult> {
|
|
51
|
-
const
|
|
52
|
-
if (
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
75
|
+
const { search, page, pageSize } = options;
|
|
76
|
+
if (page === undefined && pageSize === undefined && search === undefined) {
|
|
77
|
+
return (await Role.find({ order: { createdAt: 'asc' } })).map(toDetail);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const safePage = Math.max(1, page ?? 1);
|
|
81
|
+
const safeSize = Math.max(1, pageSize ?? 20);
|
|
82
|
+
const where = search ? { name: Like(`%${search}%`) } : undefined;
|
|
83
|
+
const [roles, total] = await Promise.all([
|
|
84
|
+
Role.find({
|
|
85
|
+
...(where ? { where } : {}),
|
|
86
|
+
order: { createdAt: 'asc' },
|
|
87
|
+
take: safeSize,
|
|
88
|
+
skip: (safePage - 1) * safeSize,
|
|
89
|
+
}),
|
|
90
|
+
Role.count(where),
|
|
91
|
+
]);
|
|
92
|
+
const items = roles.map(toDetail);
|
|
93
|
+
if (items.length) {
|
|
94
|
+
const ids = items.map((role) => role.id);
|
|
95
|
+
const counts = (await sql<{ roleId: string; count: number }>`
|
|
96
|
+
SELECT role_id AS roleId, COUNT(user_id) AS count
|
|
97
|
+
FROM user_roles
|
|
98
|
+
WHERE role_id IN (${ids})
|
|
99
|
+
GROUP BY role_id
|
|
100
|
+
`).rows;
|
|
101
|
+
const byRole = new Map(counts.map((row) => [row.roleId, Number(row.count)]));
|
|
102
|
+
for (const item of items) item.userCount = byRole.get(item.id) ?? 0;
|
|
103
|
+
}
|
|
104
|
+
return { items, total, page: safePage, pageSize: safeSize };
|
|
57
105
|
}
|
|
58
106
|
|
|
59
|
-
/** The role new accounts get
|
|
107
|
+
/** The role new accounts get (`registration.defaultRole`: a role's ID or name), or null when none is set. */
|
|
60
108
|
export async function defaultRole(): Promise<RoleDetail | null> {
|
|
61
|
-
const
|
|
62
|
-
|
|
63
|
-
const role = id
|
|
64
|
-
return role ?
|
|
109
|
+
const wanted = authOptions.registration.defaultRole;
|
|
110
|
+
if (!wanted) return null;
|
|
111
|
+
const role = await Role.findOne({ where: { id: wanted } }) ?? await Role.findOne({ where: { name: wanted } });
|
|
112
|
+
return role ? toDetail(role) : null;
|
|
65
113
|
}
|
|
66
114
|
|
|
67
115
|
export async function getRole(id: string): Promise<RoleDetail | null> {
|
|
68
|
-
const role = await
|
|
69
|
-
return role ?
|
|
116
|
+
const role = await Role.findOne({ where: { id } });
|
|
117
|
+
return role ? toDetail(role) : null;
|
|
70
118
|
}
|
|
71
119
|
|
|
72
|
-
/**
|
|
73
|
-
|
|
74
|
-
|
|
120
|
+
/**
|
|
121
|
+
* A role's ID, from its name: "User manager" is `user-manager`. Rules and settings name roles by
|
|
122
|
+
* it, so it reads as the role does and stays when the role is renamed.
|
|
123
|
+
*/
|
|
124
|
+
async function roleId(name: string): Promise<string> {
|
|
125
|
+
const base = name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60);
|
|
126
|
+
// `admin` is the administrators' role.
|
|
127
|
+
if (!base || base === ADMIN_ROLE) return uuidv7();
|
|
128
|
+
if (!await Role.exists({ id: base })) return base;
|
|
129
|
+
for (let n = 2; n < 100; n++) if (!await Role.exists({ id: `${base}-${n}` })) return `${base}-${n}`;
|
|
130
|
+
return uuidv7();
|
|
75
131
|
}
|
|
76
132
|
|
|
77
|
-
export async function createRole(input: CreateRoleInput): Promise<RoleDetail> {
|
|
78
|
-
|
|
133
|
+
export async function createRole(input: CreateRoleInput, actor: RoleActor | undefined = requestActor()): Promise<RoleDetail> {
|
|
134
|
+
if (typeof input?.name !== 'string' || !input.name.trim() || input.name.length > 120) throw new ClientVisibleError('Enter a role name of at most 120 characters.');
|
|
135
|
+
if (await Role.exists({ name: input.name })) {
|
|
136
|
+
throw new ClientVisibleError('A role with this name already exists.');
|
|
137
|
+
}
|
|
138
|
+
const now = new Date();
|
|
139
|
+
const permissions = validatePermissions([...(input.permissions ?? [])], actor);
|
|
140
|
+
await Role.insert({
|
|
141
|
+
id: await roleId(input.name),
|
|
142
|
+
name: input.name,
|
|
143
|
+
permissions,
|
|
144
|
+
createdAt: now,
|
|
145
|
+
});
|
|
146
|
+
const role = await Role.findOne({ where: { name: input.name } });
|
|
147
|
+
if (!role) throw new Error('Role insert did not return a readable row.');
|
|
148
|
+
return toDetail(role);
|
|
79
149
|
}
|
|
80
150
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
151
|
+
export async function updateRole(id: string, patch: UpdateRoleInput, actor: RoleActor | undefined = requestActor()): Promise<void> {
|
|
152
|
+
const values: Partial<Role> = {};
|
|
153
|
+
const current = await Role.findOne({ where: { id } });
|
|
154
|
+
if (!current) throw new ClientVisibleError('Role not found.');
|
|
155
|
+
// The admin role holds everything and stays as it is: changing it could lock everyone out.
|
|
156
|
+
if (current.id === ADMIN_ROLE) throw new ClientVisibleError('The admin role cannot be changed.');
|
|
157
|
+
// Nobody weakens or renames a role that holds permissions they lack.
|
|
158
|
+
if (actor && !holdsAll(permissionsOf(actor), current.permissions ?? [])) throw new ClientVisibleError('This role has permissions you do not have, so you cannot change it.');
|
|
159
|
+
if (patch.name !== undefined) {
|
|
160
|
+
if (typeof patch.name !== 'string' || !patch.name.trim() || patch.name.length > 120) throw new ClientVisibleError('Enter a role name of at most 120 characters.');
|
|
161
|
+
if (await Role.exists({ id: Not(id), name: patch.name })) {
|
|
162
|
+
throw new ClientVisibleError('A role with this name already exists.');
|
|
163
|
+
}
|
|
164
|
+
values.name = patch.name;
|
|
165
|
+
}
|
|
166
|
+
if (patch.permissions !== undefined) {
|
|
167
|
+
values.permissions = validatePermissions([...patch.permissions], actor);
|
|
168
|
+
}
|
|
169
|
+
if (Object.keys(values).length) await Role.update({ id }, values);
|
|
84
170
|
}
|
|
85
171
|
|
|
86
|
-
/** The
|
|
172
|
+
/** The admin role, found by its stored name: deleting it would lock everyone out of these screens. */
|
|
87
173
|
export async function deleteRole(id: string): Promise<void> {
|
|
88
|
-
await
|
|
174
|
+
const role = await Role.findOne({ where: { id } });
|
|
175
|
+
if (!role) throw new ClientVisibleError('Role not found.');
|
|
176
|
+
if (role.id === ADMIN_ROLE) throw new ClientVisibleError('The admin role cannot be deleted.');
|
|
177
|
+
await UserRole.delete({ roleId: id });
|
|
178
|
+
await Role.delete({ id });
|
|
89
179
|
}
|
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
// Second factors and sign-in limits on the ORM: an authenticator app's secret, recovery
|
|
2
|
+
// codes, passkeys, the short-lived steps of pending sign-ins and passkey ceremonies, and the
|
|
3
|
+
// counters that limit guesses. Every check that guards a limit is one conditional write, so
|
|
4
|
+
// requests sent at once are each counted once.
|
|
5
|
+
import { generateRecoveryCodes, generateTotpSecret, hashRecoveryCode, verifyTotp } from '@cossackframework/auth';
|
|
6
|
+
import { ClientVisibleError } from '@cossackframework/core';
|
|
7
|
+
import { atomic, currentDialect, isWriteConflict, LessThanOrEqual, MoreThan, sql } from '@cossackframework/database';
|
|
8
|
+
import { AuthAttempt } from '@/models/AuthAttempt';
|
|
9
|
+
import { AuthChallenge } from '@/models/AuthChallenge';
|
|
10
|
+
import { Passkey } from '@/models/Passkey';
|
|
11
|
+
import { UserSecurity } from '@/models/UserSecurity';
|
|
12
|
+
|
|
13
|
+
export interface PasskeyInfo {
|
|
14
|
+
id: string;
|
|
15
|
+
name: string;
|
|
16
|
+
deviceType: string | null;
|
|
17
|
+
backedUp: boolean;
|
|
18
|
+
createdAt: number;
|
|
19
|
+
lastUsedAt: number | null;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface StoredPasskey extends PasskeyInfo {
|
|
23
|
+
userId: string;
|
|
24
|
+
publicKey: string;
|
|
25
|
+
counter: number;
|
|
26
|
+
transports: string[] | null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface AccountSecurity {
|
|
30
|
+
/** An authenticator app is set up and confirmed. */
|
|
31
|
+
totp: boolean;
|
|
32
|
+
/** Unused recovery codes. */
|
|
33
|
+
recoveryCodes: number;
|
|
34
|
+
passkeys: PasskeyInfo[];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export type ChallengeKind = 'signin' | 'passkey-register' | 'passkey-signin';
|
|
38
|
+
|
|
39
|
+
/** Wrong codes a pending sign-in allows. */
|
|
40
|
+
export const SIGN_IN_ATTEMPTS = 5;
|
|
41
|
+
/**
|
|
42
|
+
* Second-factor codes counted per account for a window, across every pending sign-in: a right
|
|
43
|
+
* password does not give them back, so knowing the password does not buy more guesses.
|
|
44
|
+
*/
|
|
45
|
+
export const SECOND_FACTOR_LOCK = Object.freeze({ windowMs: 15 * 60_000, perAccount: 10 });
|
|
46
|
+
/**
|
|
47
|
+
* Password sign-ins are counted per email and per client address for a window. A right
|
|
48
|
+
* password gives its attempt back. Past the limit the sign-in is refused until the window
|
|
49
|
+
* ends, whether or not the account exists.
|
|
50
|
+
*/
|
|
51
|
+
export const SIGN_IN_LOCK = Object.freeze({ windowMs: 15 * 60_000, perEmail: 5, perAddress: 20 });
|
|
52
|
+
/** Password reset requests per email and per address in an hour; beyond them nothing is sent. */
|
|
53
|
+
export const RESET_REQUESTS = Object.freeze({ windowMs: 60 * 60_000, perEmail: 3, perAddress: 10 });
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* The time this store reads. An application whose host has its own clock (the CMS, and tests
|
|
57
|
+
* that move time) sets `clock.now`.
|
|
58
|
+
*/
|
|
59
|
+
export const clock = { now: (): number => Date.now() };
|
|
60
|
+
|
|
61
|
+
/** A secret for a link or a cookie: 256 random bits, URL-safe. */
|
|
62
|
+
export function randomToken(bytes = 32): string {
|
|
63
|
+
const random = crypto.getRandomValues(new Uint8Array(bytes));
|
|
64
|
+
return btoa(String.fromCharCode(...random)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export async function sha256Hex(text: string): Promise<string> {
|
|
68
|
+
const bytes = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)));
|
|
69
|
+
return Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('');
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The sign-in counter of an email: hashed, lower-cased. */
|
|
73
|
+
async function emailKey(email: string): Promise<string> {
|
|
74
|
+
return `signin:e:${await sha256Hex(email.trim().toLowerCase())}`;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The sign-in counter of a client address. */
|
|
78
|
+
function addressKey(address: string): string {
|
|
79
|
+
return `signin:a:${(address || 'unknown').replace(/[^\x21-\x7e]/g, '-').slice(0, 100)}`;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The second-factor counter of an account. */
|
|
83
|
+
function secondFactorKey(userId: string): string {
|
|
84
|
+
return `signin:2fa:${userId.replace(/[^\x21-\x7e]/g, '-').slice(0, 100)}`;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function attemptKey(kind: string, key: string): string {
|
|
88
|
+
return `attempt:${kind}:${key.replace(/[^\x21-\x7e]/g, '-').slice(0, 120)}`;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* One more attempt for the key, unless it already has `max` in its window: true when this one
|
|
93
|
+
* was counted. An ended window starts again, then one conditional increment counts the
|
|
94
|
+
* attempt, so attempts sent at once are each counted once and no more than `max` pass.
|
|
95
|
+
*/
|
|
96
|
+
async function count(key: string, windowMs: number, max: number): Promise<boolean> {
|
|
97
|
+
const now = clock.now();
|
|
98
|
+
const until = new Date(now + windowMs);
|
|
99
|
+
// The row may exist already: then the insert does nothing and the increment decides.
|
|
100
|
+
const insert = currentDialect() === 'mysql'
|
|
101
|
+
? sql.fragment`INSERT IGNORE INTO auth_attempts (id, attempts, expires_at) VALUES (${key}, 0, ${until})`
|
|
102
|
+
: sql.fragment`INSERT INTO auth_attempts (id, attempts, expires_at) VALUES (${key}, 0, ${until}) ON CONFLICT (id) DO NOTHING`;
|
|
103
|
+
try {
|
|
104
|
+
const results = await atomic([
|
|
105
|
+
sql.fragment`DELETE FROM auth_attempts WHERE id = ${key} AND expires_at <= ${new Date(now)}`,
|
|
106
|
+
insert,
|
|
107
|
+
sql.fragment`UPDATE auth_attempts SET attempts = attempts + 1 WHERE id = ${key} AND attempts < ${max}`,
|
|
108
|
+
]);
|
|
109
|
+
return results[2]!.meta.rowsAffected === 1;
|
|
110
|
+
} catch (error) {
|
|
111
|
+
// A key under a burst of attempts can keep conflicting: refuse this attempt, as the limit
|
|
112
|
+
// would, rather than fail the request.
|
|
113
|
+
if (isWriteConflict(error)) return false;
|
|
114
|
+
throw error;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* A write that gives attempts back. Under a burst on the same key it can keep conflicting:
|
|
120
|
+
* the attempt then stays counted (the limit errs shut), and the request goes on.
|
|
121
|
+
*/
|
|
122
|
+
async function bestEffort(write: () => Promise<unknown>): Promise<void> {
|
|
123
|
+
try { await write(); }
|
|
124
|
+
catch (error) {
|
|
125
|
+
if (!isWriteConflict(error)) throw error;
|
|
126
|
+
console.warn('[Cossack Auth] a sign-in attempt could not be given back: the key is busy');
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async function giveBack(key: string): Promise<void> {
|
|
131
|
+
await bestEffort(async () => { await sql`UPDATE auth_attempts SET attempts = attempts - 1 WHERE id = ${key} AND attempts > 0`; });
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Start a password sign-in: one attempt is counted for the email and for the address before
|
|
136
|
+
* the password is checked. Refused while either is at its limit for the window. A right
|
|
137
|
+
* password gives the attempt back (`signInSucceeded`); a wrong one leaves it counted.
|
|
138
|
+
*/
|
|
139
|
+
export async function signInBegin(email: string, address: string): Promise<{ ok: true } | { ok: false; retryAfterMs: number }> {
|
|
140
|
+
const [emailId, addressId] = [await emailKey(email), addressKey(address)];
|
|
141
|
+
const byEmail = await count(emailId, SIGN_IN_LOCK.windowMs, SIGN_IN_LOCK.perEmail);
|
|
142
|
+
const byAddress = byEmail && await count(addressId, SIGN_IN_LOCK.windowMs, SIGN_IN_LOCK.perAddress);
|
|
143
|
+
if (byEmail && byAddress) return { ok: true };
|
|
144
|
+
// The email's attempt does not stand when the address refused it.
|
|
145
|
+
if (byEmail) await giveBack(emailId);
|
|
146
|
+
const row = await AuthAttempt.findOne({ where: { id: byEmail ? addressId : emailId } });
|
|
147
|
+
return { ok: false, retryAfterMs: Math.max(1, (row?.expiresAt.getTime() ?? 0) - clock.now()) };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** A right password: the email's failures are forgotten, and the address gets this attempt back. */
|
|
151
|
+
export async function signInSucceeded(email: string, address: string): Promise<void> {
|
|
152
|
+
const key = await emailKey(email);
|
|
153
|
+
await bestEffort(() => AuthAttempt.delete({ id: key }));
|
|
154
|
+
await giveBack(addressKey(address));
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Count an attempt of `kind` (such as `reset`) for a key within a window; false past `max`.
|
|
159
|
+
* A refused attempt keeps the gate shut until the window ends.
|
|
160
|
+
*/
|
|
161
|
+
export function attempt(kind: string, key: string, max: number, windowMs: number): Promise<boolean> {
|
|
162
|
+
return count(attemptKey(kind, key), windowMs, max);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Give back an attempt `attempt()` counted, for one that did not go ahead after all. */
|
|
166
|
+
export function release(kind: string, key: string): Promise<void> {
|
|
167
|
+
return giveBack(attemptKey(kind, key));
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function passkeyOf(row: Passkey): StoredPasskey {
|
|
171
|
+
return {
|
|
172
|
+
id: row.id, userId: row.userId, name: row.name, publicKey: row.publicKey, counter: row.signCount,
|
|
173
|
+
transports: row.transports, deviceType: row.deviceType, backedUp: row.backedUp,
|
|
174
|
+
createdAt: row.createdAt.getTime(), lastUsedAt: row.lastUsedAt?.getTime() ?? null,
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export async function passkeys(userId: string): Promise<StoredPasskey[]> {
|
|
179
|
+
return (await Passkey.find({ where: { userId }, order: { createdAt: 'asc' }, take: 50 })).map(passkeyOf);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export async function passkey(id: string): Promise<StoredPasskey | null> {
|
|
183
|
+
if (typeof id !== 'string' || !/^[A-Za-z0-9_-]{1,191}$/.test(id)) return null;
|
|
184
|
+
const row = await Passkey.findOne({ where: { id } });
|
|
185
|
+
return row ? passkeyOf(row) : null;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export async function status(userId: string): Promise<AccountSecurity> {
|
|
189
|
+
const [row, keys] = await Promise.all([UserSecurity.findOne({ where: { userId } }), passkeys(userId)]);
|
|
190
|
+
const confirmed = Boolean(row?.totpConfirmedAt);
|
|
191
|
+
return {
|
|
192
|
+
totp: confirmed,
|
|
193
|
+
recoveryCodes: confirmed ? (row?.recovery ?? []).length : 0,
|
|
194
|
+
passkeys: keys.map(({ userId: _user, publicKey: _key, counter: _counter, transports: _transports, ...info }) => info),
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** Whether the user has an authenticator app or a passkey. */
|
|
199
|
+
export async function hasSecondFactor(userId: string): Promise<boolean> {
|
|
200
|
+
const current = await status(userId);
|
|
201
|
+
return current.totp || current.passkeys.length > 0;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** Whether a code from the authenticator app is required at sign-in (passkeys sign in on their own). */
|
|
205
|
+
export async function requiresCode(userId: string): Promise<boolean> {
|
|
206
|
+
return Boolean((await UserSecurity.findOne({ where: { userId } }))?.totpConfirmedAt);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* A new, unconfirmed authenticator secret. It takes effect once confirmed with a code. A
|
|
211
|
+
* confirmed authenticator stays as it is: replacing it means turning it off first, which asks
|
|
212
|
+
* for one of its codes, so starting a setup never removes the factor in use.
|
|
213
|
+
*/
|
|
214
|
+
export async function startTotp(userId: string): Promise<string> {
|
|
215
|
+
const secret = generateTotpSecret();
|
|
216
|
+
const now = new Date(clock.now());
|
|
217
|
+
const insert = currentDialect() === 'mysql'
|
|
218
|
+
? sql.fragment`INSERT IGNORE INTO user_security (user_id, totp_secret, updated_at) VALUES (${userId}, ${secret}, ${now})`
|
|
219
|
+
: sql.fragment`INSERT INTO user_security (user_id, totp_secret, updated_at) VALUES (${userId}, ${secret}, ${now}) ON CONFLICT (user_id) DO NOTHING`;
|
|
220
|
+
const results = await atomic([
|
|
221
|
+
insert,
|
|
222
|
+
sql.fragment`UPDATE user_security SET totp_secret = ${secret}, totp_last_step = NULL, updated_at = ${now}
|
|
223
|
+
WHERE user_id = ${userId} AND totp_confirmed_at IS NULL`,
|
|
224
|
+
]);
|
|
225
|
+
if (results[1]!.meta.rowsAffected !== 1) {
|
|
226
|
+
throw new ClientVisibleError('An authenticator app is already on. Turn it off with one of its codes before setting up another.');
|
|
227
|
+
}
|
|
228
|
+
return secret;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** The secret of a setup that is not confirmed yet, for showing the QR code again. */
|
|
232
|
+
export async function pendingSecret(userId: string): Promise<string | null> {
|
|
233
|
+
const row = await UserSecurity.findOne({ where: { userId } });
|
|
234
|
+
return row?.totpSecret && !row.totpConfirmedAt ? row.totpSecret : null;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** Confirm the authenticator with a current code. Returns new recovery codes, shown once. */
|
|
238
|
+
export async function confirmTotp(userId: string, code: string): Promise<string[]> {
|
|
239
|
+
const secret = await pendingSecret(userId);
|
|
240
|
+
if (!secret) throw new ClientVisibleError('Start the authenticator setup again.');
|
|
241
|
+
const step = await verifyTotp(secret, code, { now: clock.now() });
|
|
242
|
+
if (step === null) throw new ClientVisibleError('That code is not right. Check the time on your device and try again.');
|
|
243
|
+
const codes = generateRecoveryCodes();
|
|
244
|
+
const now = new Date(clock.now());
|
|
245
|
+
await UserSecurity.update({ userId, totpSecret: secret },
|
|
246
|
+
{ totpConfirmedAt: now, totpLastStep: step, recovery: await Promise.all(codes.map(hashRecoveryCode)), updatedAt: now });
|
|
247
|
+
return codes;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** New recovery codes, replacing the old ones. Needs a confirmed authenticator. */
|
|
251
|
+
export async function regenerateRecoveryCodes(userId: string): Promise<string[]> {
|
|
252
|
+
if (!(await requiresCode(userId))) throw new ClientVisibleError('Set up an authenticator app first.');
|
|
253
|
+
const codes = generateRecoveryCodes();
|
|
254
|
+
await UserSecurity.update({ userId }, { recovery: await Promise.all(codes.map(hashRecoveryCode)), updatedAt: new Date(clock.now()) });
|
|
255
|
+
return codes;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
export async function disableTotp(userId: string): Promise<void> {
|
|
259
|
+
await UserSecurity.delete({ userId });
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Check a second-factor code: the authenticator's current code (each step once) or an unused
|
|
264
|
+
* recovery code, which is used up.
|
|
265
|
+
*/
|
|
266
|
+
export async function verifyCode(userId: string, code: string): Promise<'totp' | 'recovery' | null> {
|
|
267
|
+
const row = await UserSecurity.findOne({ where: { userId } });
|
|
268
|
+
if (!row?.totpSecret || !row.totpConfirmedAt) return null;
|
|
269
|
+
const step = await verifyTotp(row.totpSecret, code, { now: clock.now(), afterStep: row.totpLastStep });
|
|
270
|
+
if (step !== null) {
|
|
271
|
+
// The step is recorded only if no other sign-in used it first.
|
|
272
|
+
const update = await sql`UPDATE user_security SET totp_last_step = ${step}
|
|
273
|
+
WHERE user_id = ${userId} AND (totp_last_step IS NULL OR totp_last_step < ${step})`;
|
|
274
|
+
return update.meta.rowsAffected === 1 ? 'totp' : null;
|
|
275
|
+
}
|
|
276
|
+
const hashes = row.recovery ?? [];
|
|
277
|
+
const hash = await hashRecoveryCode(code);
|
|
278
|
+
if (!hashes.includes(hash)) return null;
|
|
279
|
+
// The code is used up only if the list is still the one that was read.
|
|
280
|
+
const update = await sql`UPDATE user_security SET recovery = ${sql.json(hashes.filter(entry => entry !== hash))}, updated_at = ${new Date(clock.now())}
|
|
281
|
+
WHERE user_id = ${userId} AND recovery = ${sql.json(hashes)}`;
|
|
282
|
+
return update.meta.rowsAffected === 1 ? 'recovery' : null;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
export async function addPasskey(
|
|
286
|
+
userId: string,
|
|
287
|
+
credential: { id: string; publicKey: string; counter: number; transports?: readonly string[]; deviceType?: string; backedUp?: boolean },
|
|
288
|
+
name: string,
|
|
289
|
+
): Promise<void> {
|
|
290
|
+
if ((await Passkey.count({ userId })) >= 20) throw new ClientVisibleError('A user can have at most 20 passkeys.');
|
|
291
|
+
if (await Passkey.exists({ id: credential.id })) throw new ClientVisibleError('This passkey is already registered.');
|
|
292
|
+
await Passkey.insert({
|
|
293
|
+
id: credential.id, userId, name: name.trim().slice(0, 80) || 'Passkey', publicKey: credential.publicKey, signCount: credential.counter,
|
|
294
|
+
transports: credential.transports ? [...credential.transports] : null, deviceType: credential.deviceType ?? null,
|
|
295
|
+
backedUp: credential.backedUp === true, createdAt: new Date(clock.now()), lastUsedAt: null,
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
export async function renamePasskey(userId: string, id: string, name: string): Promise<void> {
|
|
300
|
+
await Passkey.update({ id, userId }, { name: name.trim().slice(0, 80) || 'Passkey' });
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
export async function removePasskey(userId: string, id: string): Promise<void> {
|
|
304
|
+
// A missing ID must not widen the delete to every passkey of the user.
|
|
305
|
+
if (typeof id !== 'string' || !id) return;
|
|
306
|
+
await Passkey.delete({ id, userId });
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** Record a passkey sign-in. */
|
|
310
|
+
export async function usePasskey(id: string, counter: number): Promise<void> {
|
|
311
|
+
await Passkey.update({ id }, { signCount: counter, lastUsedAt: new Date(clock.now()) });
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** Remove every second factor, for a user who lost their device. */
|
|
315
|
+
export async function reset(userId: string): Promise<void> {
|
|
316
|
+
await UserSecurity.delete({ userId });
|
|
317
|
+
await Passkey.delete({ userId });
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** A step kept for `ttlMs`; its random ID goes into a cookie or form. */
|
|
321
|
+
export async function createChallenge(kind: ChallengeKind, userId: string | null, challenge: string, ttlMs = 5 * 60_000): Promise<string> {
|
|
322
|
+
const id = randomToken(24);
|
|
323
|
+
await AuthChallenge.insert({ id, kind, userId, challenge, attempts: 0, expiresAt: new Date(clock.now() + ttlMs) });
|
|
324
|
+
return id;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** A live step of the kind, without using it up. */
|
|
328
|
+
export async function challenge(id: string, kind: ChallengeKind): Promise<{ userId: string | null; challenge: string; attempts: number } | null> {
|
|
329
|
+
if (typeof id !== 'string' || !/^[A-Za-z0-9_-]{20,64}$/.test(id)) return null;
|
|
330
|
+
const row = await AuthChallenge.findOne({ where: { id, kind, expiresAt: MoreThan(new Date(clock.now())) } });
|
|
331
|
+
return row ? { userId: row.userId, challenge: row.challenge, attempts: row.attempts } : null;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** Use up a step: true only for the first caller while it is live. */
|
|
335
|
+
export async function takeChallenge(id: string, kind: ChallengeKind): Promise<boolean> {
|
|
336
|
+
return (await AuthChallenge.delete({ id, kind, expiresAt: MoreThan(new Date(clock.now())) })).meta.rowsAffected === 1;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* Spend one try of a pending sign-in before its code is checked: counted on the step (a
|
|
341
|
+
* conditional write, so codes sent at once each take a try and no more than `SIGN_IN_ATTEMPTS`
|
|
342
|
+
* are checked) and on the account (`SECOND_FACTOR_LOCK`). `expired` when the step has no tries
|
|
343
|
+
* left or ended, `locked` when the account has used its codes.
|
|
344
|
+
*/
|
|
345
|
+
export async function secondFactorAttempt(id: string, userId: string): Promise<{ left: number } | 'expired' | 'locked'> {
|
|
346
|
+
const counted = await sql`UPDATE auth_challenges SET attempts = attempts + 1
|
|
347
|
+
WHERE id = ${id} AND kind = ${'signin'} AND user_id = ${userId} AND attempts < ${SIGN_IN_ATTEMPTS} AND expires_at > ${new Date(clock.now())}`;
|
|
348
|
+
if (counted.meta.rowsAffected !== 1) return 'expired';
|
|
349
|
+
if (!(await count(secondFactorKey(userId), SECOND_FACTOR_LOCK.windowMs, SECOND_FACTOR_LOCK.perAccount))) {
|
|
350
|
+
await AuthChallenge.delete({ id });
|
|
351
|
+
return 'locked';
|
|
352
|
+
}
|
|
353
|
+
const live = await AuthChallenge.findOne({ where: { id } });
|
|
354
|
+
return { left: live ? SIGN_IN_ATTEMPTS - live.attempts : 0 };
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* Spend one of the account's code tries outside a sign-in (turning the authenticator off, new
|
|
359
|
+
* recovery codes): the same per-account count as at sign-in, so codes cannot be guessed
|
|
360
|
+
* faster on the security page. False when the account is locked.
|
|
361
|
+
*/
|
|
362
|
+
export function codeAttempt(userId: string): Promise<boolean> {
|
|
363
|
+
return count(secondFactorKey(userId), SECOND_FACTOR_LOCK.windowMs, SECOND_FACTOR_LOCK.perAccount);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/** A wrong code: the step ends once it has no tries left. */
|
|
367
|
+
export async function failChallenge(id: string): Promise<void> {
|
|
368
|
+
await sql`DELETE FROM auth_challenges WHERE id = ${id} AND attempts >= ${SIGN_IN_ATTEMPTS}`;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/** A right code: the account's second-factor count starts again. */
|
|
372
|
+
export async function secondFactorSucceeded(userId: string): Promise<void> {
|
|
373
|
+
await AuthAttempt.delete({ id: secondFactorKey(userId) });
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/** Remove pending steps whose time ended, which nothing else would. Call it from a schedule. */
|
|
377
|
+
export async function purgeExpired(): Promise<void> {
|
|
378
|
+
await AuthChallenge.delete({ expiresAt: LessThanOrEqual(new Date(clock.now())) });
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** Remove attempt counts whose window ended. Call it from a schedule. */
|
|
382
|
+
export async function purgeAttempts(): Promise<void> {
|
|
383
|
+
await AuthAttempt.delete({ expiresAt: LessThanOrEqual(new Date(clock.now())) });
|
|
384
|
+
}
|