@mielk/auth 0.0.0-stage → 2.0.1
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/CHANGELOG.md +84 -0
- package/LICENSE +21 -0
- package/README.md +673 -2
- package/dist/client/api-address.d.ts +17 -0
- package/dist/client/api-address.js +434 -0
- package/dist/client/auth-client.d.ts +226 -0
- package/dist/client/auth-client.js +676 -0
- package/dist/client/errors.d.ts +66 -0
- package/dist/client/errors.js +33 -0
- package/dist/client/guards.d.ts +26 -0
- package/dist/client/guards.js +27 -0
- package/dist/client/index.d.ts +4 -0
- package/dist/client/index.js +2 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +4 -0
- package/dist/locales/en-GB.json +50 -0
- package/dist/locales/pl.json +50 -0
- package/dist/messages.d.ts +65 -0
- package/dist/messages.js +57 -0
- package/dist/pg/index.d.ts +1 -0
- package/dist/pg/index.js +1 -0
- package/dist/pg/migrations/0001_mielk_auth.sql +65 -0
- package/dist/pg/pg-auth-repository.d.ts +91 -0
- package/dist/pg/pg-auth-repository.js +252 -0
- package/dist/react/auth-provider.d.ts +70 -0
- package/dist/react/auth-provider.js +72 -0
- package/dist/react/index.d.ts +2 -0
- package/dist/react/index.js +1 -0
- package/dist/schemas/index.d.ts +234 -0
- package/dist/schemas/index.js +145 -0
- package/dist/server/access-token.d.ts +48 -0
- package/dist/server/access-token.js +54 -0
- package/dist/server/auth-middleware.d.ts +40 -0
- package/dist/server/auth-middleware.js +61 -0
- package/dist/server/config.d.ts +231 -0
- package/dist/server/config.js +250 -0
- package/dist/server/cookies.d.ts +13 -0
- package/dist/server/cookies.js +35 -0
- package/dist/server/core.d.ts +20 -0
- package/dist/server/core.js +32 -0
- package/dist/server/create-auth.d.ts +38 -0
- package/dist/server/create-auth.js +33 -0
- package/dist/server/errors.d.ts +177 -0
- package/dist/server/errors.js +201 -0
- package/dist/server/http-errors.d.ts +9 -0
- package/dist/server/http-errors.js +34 -0
- package/dist/server/limits.d.ts +95 -0
- package/dist/server/limits.js +98 -0
- package/dist/server/one-time-token.d.ts +49 -0
- package/dist/server/one-time-token.js +60 -0
- package/dist/server/opaque-token.d.ts +6 -0
- package/dist/server/opaque-token.js +7 -0
- package/dist/server/password.d.ts +45 -0
- package/dist/server/password.js +72 -0
- package/dist/server/ports.d.ts +343 -0
- package/dist/server/ports.js +11 -0
- package/dist/server/proxy-check.d.ts +17 -0
- package/dist/server/proxy-check.js +80 -0
- package/dist/server/refresh-token.d.ts +60 -0
- package/dist/server/refresh-token.js +122 -0
- package/dist/server/router.d.ts +29 -0
- package/dist/server/router.js +329 -0
- package/dist/server/safe-log.d.ts +9 -0
- package/dist/server/safe-log.js +24 -0
- package/dist/server/service.d.ts +153 -0
- package/dist/server/service.js +244 -0
- package/package.json +136 -5
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Operations of the authentication endpoints without Express: they take plain values, return plain values and throw the
|
|
3
|
+
* errors of the library (`AuthError`), which the router maps to responses. The router and the tests build on it.
|
|
4
|
+
*/
|
|
5
|
+
import type { IssuedAccessToken } from './access-token.js';
|
|
6
|
+
import type { AuthLogger } from './config.js';
|
|
7
|
+
import type { AuthCore } from './core.js';
|
|
8
|
+
import type { AuthUser, ClientKind, UserId } from './ports.js';
|
|
9
|
+
import type { IssuedRefreshToken } from './refresh-token.js';
|
|
10
|
+
export { logError, logWarning } from './safe-log.js';
|
|
11
|
+
/** Context of one request that the operations need: the language of the e-mails and where failures are logged. */
|
|
12
|
+
export type RequestContext = {
|
|
13
|
+
/** Language of the e-mails, e.g. `pl` or `en-GB`. */
|
|
14
|
+
locale: string;
|
|
15
|
+
log: AuthLogger | undefined;
|
|
16
|
+
};
|
|
17
|
+
/** Category of a failure of the mailer: whether it rejected with an `Error` or with another value. */
|
|
18
|
+
export type LinkDeliveryReason = 'mailer_error' | 'mailer_non_error';
|
|
19
|
+
/**
|
|
20
|
+
* Failure of the mailer. It carries no cause, message, name or address of the original error: the errors of mail ports
|
|
21
|
+
* tend to quote the recipient or the link with the token, and their names are chosen by foreign code, so only a fixed
|
|
22
|
+
* category is kept; this error is logged and reaches the final error handler.
|
|
23
|
+
*/
|
|
24
|
+
export declare class LinkDeliveryError extends Error {
|
|
25
|
+
readonly name = "LinkDeliveryError";
|
|
26
|
+
/** Fixed category of the original failure, safe to log. */
|
|
27
|
+
readonly reason: LinkDeliveryReason;
|
|
28
|
+
constructor(original: unknown);
|
|
29
|
+
}
|
|
30
|
+
/** Fixed categories of an error for logs: they never come from the error object, whose name or fields may carry data. */
|
|
31
|
+
export type ErrorCategory = 'link_delivery' | 'library_error' | 'unexpected_error';
|
|
32
|
+
/**
|
|
33
|
+
* What of an error may be logged: a fixed category only. The message, name and fields of an error from a dependency
|
|
34
|
+
* (repository, mailer, Redis) may quote an address, a key or a token, and the name is chosen by foreign code too.
|
|
35
|
+
*/
|
|
36
|
+
export declare const safeErrorInfo: (err: unknown) => {
|
|
37
|
+
errorCategory: ErrorCategory;
|
|
38
|
+
};
|
|
39
|
+
/** Result of a login. */
|
|
40
|
+
export type LoginResult = {
|
|
41
|
+
user: AuthUser;
|
|
42
|
+
accessToken: IssuedAccessToken;
|
|
43
|
+
refreshToken: IssuedRefreshToken;
|
|
44
|
+
};
|
|
45
|
+
/** Result of a refresh. */
|
|
46
|
+
export type RefreshResult = {
|
|
47
|
+
accessToken: IssuedAccessToken;
|
|
48
|
+
refreshToken: IssuedRefreshToken;
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* Result of a registration: the sending of its e-mail, already started (r1:U1). Its failures are logged, and a logger that throws or
|
|
52
|
+
* rejects is ignored (r3:U1), so it does not reject because of the logger; the router still catches any other
|
|
53
|
+
* rejection (r2:U1).
|
|
54
|
+
*/
|
|
55
|
+
export type RegisterResult = {
|
|
56
|
+
delivery: Promise<void>;
|
|
57
|
+
};
|
|
58
|
+
/** Operations of the authentication endpoints (plan TASK-191, 2.2). */
|
|
59
|
+
export type AuthService = {
|
|
60
|
+
/**
|
|
61
|
+
* Creates the account and sends the verification link. For an e-mail that is registered already it creates nothing,
|
|
62
|
+
* changes nothing and sends the account the `account_exists` message with a password reset link instead (audit S3).
|
|
63
|
+
* Reserves hashing capacity synchronously so the router can answer before account storage (TASK-393). The promise
|
|
64
|
+
* resolves after hashing and attempting to create the account. Reading the existing account, applying its limit and
|
|
65
|
+
* sending mail run in `delivery`.
|
|
66
|
+
* A failure of `delivery` is logged and does not fail the registration (the link can be requested again); a
|
|
67
|
+
* logger that throws or rejects is ignored (r3:U1). A caller that does not await it should still catch any other
|
|
68
|
+
* rejection (r2:U1).
|
|
69
|
+
*
|
|
70
|
+
* @throws `PasswordHashingBusyError` synchronously when hashing capacity is full.
|
|
71
|
+
*/
|
|
72
|
+
register(email: string, password: string, client: ClientKind, ctx: RequestContext): Promise<RegisterResult>;
|
|
73
|
+
/**
|
|
74
|
+
* Logs in. The password is checked before the transaction (audit S8); `afterPasswordCheck` runs after the password
|
|
75
|
+
* matched and before the transaction starts (the router clears the login counters there): when it rejects, no
|
|
76
|
+
* session is issued. Neither bcrypt nor the call of `afterPasswordCheck` holds a connection or the lock of the user.
|
|
77
|
+
*
|
|
78
|
+
* @throws `InvalidCredentialsError` for an unknown e-mail and for a wrong password alike (`rest:AUT-8`), also when
|
|
79
|
+
* the password changed between the check and the lock.
|
|
80
|
+
*/
|
|
81
|
+
login(email: string, password: string, clientKind: ClientKind, afterPasswordCheck?: () => Promise<void>): Promise<LoginResult>;
|
|
82
|
+
/** @throws the refresh token errors of `RefreshTokenService.rotate`. */
|
|
83
|
+
refresh(refreshToken: string, clientKind: ClientKind): Promise<RefreshResult>;
|
|
84
|
+
/** Revokes the refresh token; idempotent. */
|
|
85
|
+
logout(refreshToken: string, clientKind: ClientKind): Promise<void>;
|
|
86
|
+
/** Revokes all refresh tokens of the user. */
|
|
87
|
+
revokeAllSessions(userId: UserId): Promise<void>;
|
|
88
|
+
/** @throws `InvalidAccessTokenError` when the account of a valid token no longer exists. */
|
|
89
|
+
getUser(userId: UserId): Promise<AuthUser>;
|
|
90
|
+
/**
|
|
91
|
+
* Sends a new verification link; does nothing for a verified e-mail.
|
|
92
|
+
*
|
|
93
|
+
* @throws `LinkDeliveryError` when the mailer fails.
|
|
94
|
+
*/
|
|
95
|
+
resendVerification(userId: UserId, client: ClientKind, ctx: RequestContext): Promise<void>;
|
|
96
|
+
/**
|
|
97
|
+
* Returns the account of a verification token that could be used now, without using it: the router keys the limit of
|
|
98
|
+
* password checks on it before `confirmEmail` (audit S4, DEC-281).
|
|
99
|
+
*
|
|
100
|
+
* @throws `InvalidAuthTokenError` for a token that is unknown, used, replaced or expired.
|
|
101
|
+
*/
|
|
102
|
+
emailVerificationOwner(token: string): Promise<UserId>;
|
|
103
|
+
/**
|
|
104
|
+
* Marks the e-mail as verified when the password of the account matches, and revokes all refresh tokens of the
|
|
105
|
+
* account, in one transaction with the use of the token (audit S4, DEC-281): who registered someone else's address
|
|
106
|
+
* has no link, the owner of the mailbox who did not register has no password, so only who has both confirms it. The
|
|
107
|
+
* sessions issued before stay revoked as well; the owner signs in again. The token and the password are checked
|
|
108
|
+
* before the transaction, so no connection and no lock of the user wait for bcrypt (audit S8); the transaction
|
|
109
|
+
* confirms only while the stored hash is still the checked one. A refused confirmation leaves the token usable.
|
|
110
|
+
*
|
|
111
|
+
* @throws `InvalidAuthTokenError` for a token that is unknown, used, replaced or expired.
|
|
112
|
+
* @throws `CurrentPasswordInvalidError` for a wrong password, also when the password changed after it was checked.
|
|
113
|
+
*/
|
|
114
|
+
confirmEmail(token: string, password: string): Promise<void>;
|
|
115
|
+
/**
|
|
116
|
+
* Sends the reset link when the account exists. Gives no sign of whether the account exists (`rest:AUT-8`):
|
|
117
|
+
* failures are logged, and a logger that throws or rejects is ignored (r3:U1). A caller that does not await it
|
|
118
|
+
* should still catch any other rejection (r2:U1).
|
|
119
|
+
*/
|
|
120
|
+
requestPasswordReset(email: string, client: ClientKind, ctx: RequestContext): Promise<void>;
|
|
121
|
+
/**
|
|
122
|
+
* Sets the new password and revokes all refresh tokens of the user (`rest:AUT-10`), in one transaction with the use
|
|
123
|
+
* of the token.
|
|
124
|
+
*
|
|
125
|
+
* @returns the account, as read under its lock (the router clears the lock of its e-mail, audit N4).
|
|
126
|
+
* @throws `InvalidAuthTokenError` for a token that is unknown, used, replaced or expired.
|
|
127
|
+
*/
|
|
128
|
+
confirmPasswordReset(token: string, password: string): Promise<AuthUser>;
|
|
129
|
+
/**
|
|
130
|
+
* Changes the password and revokes all refresh tokens of the user, also the current session (`rest:AUT-10`).
|
|
131
|
+
*
|
|
132
|
+
* @throws `CurrentPasswordInvalidError`, `InvalidAccessTokenError` when the account no longer exists.
|
|
133
|
+
*/
|
|
134
|
+
changePassword(userId: UserId, currentPassword: string, newPassword: string): Promise<void>;
|
|
135
|
+
/**
|
|
136
|
+
* Deletes the account after the password check (before the transaction, audit S8), running `onUserDeleted` in the
|
|
137
|
+
* transaction that deletes it.
|
|
138
|
+
*
|
|
139
|
+
* @throws `CurrentPasswordInvalidError`, `InvalidAccessTokenError` when the account no longer exists.
|
|
140
|
+
*/
|
|
141
|
+
deleteAccount(userId: UserId, password: string): Promise<void>;
|
|
142
|
+
};
|
|
143
|
+
/** Options of `createAuthService`. */
|
|
144
|
+
export type AuthServiceOptions = {
|
|
145
|
+
/**
|
|
146
|
+
* Tells whether a password reset link (or a notice of a registration) may be sent to the account now, and counts it
|
|
147
|
+
* (audit S5); default: always. A refusal or a failure sends nothing and issues no token, and the caller is answered
|
|
148
|
+
* the same.
|
|
149
|
+
*/
|
|
150
|
+
allowPasswordResetEmail?: (userId: UserId) => Promise<boolean>;
|
|
151
|
+
};
|
|
152
|
+
/** Creates the service on the core of the library. */
|
|
153
|
+
export declare const createAuthService: (core: AuthCore, options?: AuthServiceOptions) => AuthService;
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
import { AuthError, CurrentPasswordInvalidError, EmailTakenError, InvalidAccessTokenError, InvalidAuthTokenError, InvalidCredentialsError, } from './errors.js';
|
|
2
|
+
import { buildAuthLink } from './one-time-token.js';
|
|
3
|
+
import { logError } from './safe-log.js';
|
|
4
|
+
export { logError, logWarning } from './safe-log.js';
|
|
5
|
+
/**
|
|
6
|
+
* Failure of the mailer. It carries no cause, message, name or address of the original error: the errors of mail ports
|
|
7
|
+
* tend to quote the recipient or the link with the token, and their names are chosen by foreign code, so only a fixed
|
|
8
|
+
* category is kept; this error is logged and reaches the final error handler.
|
|
9
|
+
*/
|
|
10
|
+
export class LinkDeliveryError extends Error {
|
|
11
|
+
name = 'LinkDeliveryError';
|
|
12
|
+
/** Fixed category of the original failure, safe to log. */
|
|
13
|
+
reason;
|
|
14
|
+
constructor(original) {
|
|
15
|
+
super('The e-mail with the link could not be sent.');
|
|
16
|
+
this.reason = original instanceof Error ? 'mailer_error' : 'mailer_non_error';
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* What of an error may be logged: a fixed category only. The message, name and fields of an error from a dependency
|
|
21
|
+
* (repository, mailer, Redis) may quote an address, a key or a token, and the name is chosen by foreign code too.
|
|
22
|
+
*/
|
|
23
|
+
export const safeErrorInfo = (err) => ({
|
|
24
|
+
errorCategory: err instanceof LinkDeliveryError
|
|
25
|
+
? 'link_delivery'
|
|
26
|
+
: err instanceof AuthError
|
|
27
|
+
? 'library_error'
|
|
28
|
+
: 'unexpected_error',
|
|
29
|
+
});
|
|
30
|
+
/** Creates the service on the core of the library. */
|
|
31
|
+
export const createAuthService = (core, options = {}) => {
|
|
32
|
+
const { config, accessTokens, refreshTokens, oneTimeTokens, passwords } = core;
|
|
33
|
+
const { repository, mailer, clock } = config;
|
|
34
|
+
const allowResetEmail = options.allowPasswordResetEmail ?? (() => Promise.resolve(true));
|
|
35
|
+
const linkBase = (client) => client === 'mobile' && config.links.mobile !== undefined ? config.links.mobile : config.links.web;
|
|
36
|
+
const sendLink = async (user, purpose, client, ctx, kind = purpose) => {
|
|
37
|
+
const issued = await oneTimeTokens.issue(user.userId, purpose);
|
|
38
|
+
try {
|
|
39
|
+
await mailer.send({
|
|
40
|
+
kind,
|
|
41
|
+
to: user.email,
|
|
42
|
+
url: buildAuthLink(linkBase(client), purpose, issued.token),
|
|
43
|
+
locale: ctx.locale,
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
catch (err) {
|
|
47
|
+
throw new LinkDeliveryError(err);
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
/** Sends a link without failing the caller; the failure is logged (the logged error carries no token or link). */
|
|
51
|
+
const trySendLink = async (user, purpose, client, ctx, kind = purpose) => {
|
|
52
|
+
try {
|
|
53
|
+
await sendLink(user, purpose, client, ctx, kind);
|
|
54
|
+
}
|
|
55
|
+
catch (err) {
|
|
56
|
+
logError(ctx.log, {
|
|
57
|
+
...safeErrorInfo(err),
|
|
58
|
+
...(err instanceof LinkDeliveryError ? { reason: err.reason } : {}),
|
|
59
|
+
purpose,
|
|
60
|
+
kind,
|
|
61
|
+
}, 'The e-mail with the link could not be sent.');
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
/**
|
|
65
|
+
* Sends the owner of a registered address the `account_exists` notice within the limit per account; never rejects
|
|
66
|
+
* (failures are logged).
|
|
67
|
+
*/
|
|
68
|
+
const trySendAccountNotice = async (email, client, ctx) => {
|
|
69
|
+
let user;
|
|
70
|
+
try {
|
|
71
|
+
user = await repository.findUserByEmail(email);
|
|
72
|
+
}
|
|
73
|
+
catch (err) {
|
|
74
|
+
logError(ctx.log, safeErrorInfo(err), 'The registered account could not be read; nothing is sent.');
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
if (user === null) {
|
|
78
|
+
// Deleted between the registration and this reading: nobody to notify.
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
let allowed;
|
|
82
|
+
try {
|
|
83
|
+
allowed = await allowResetEmail(user.userId);
|
|
84
|
+
}
|
|
85
|
+
catch (err) {
|
|
86
|
+
logError(ctx.log, safeErrorInfo(err), 'The limit of reset links could not be checked; nothing is sent.');
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
if (allowed) {
|
|
90
|
+
await trySendLink(user, 'password_reset', client, ctx, 'account_exists');
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
const requireUser = async (userId, source = repository) => {
|
|
94
|
+
const user = await source.findUserById(userId);
|
|
95
|
+
if (user === null) {
|
|
96
|
+
throw new InvalidAccessTokenError();
|
|
97
|
+
}
|
|
98
|
+
return user;
|
|
99
|
+
};
|
|
100
|
+
const requirePassword = async (user, password) => {
|
|
101
|
+
if (!(await passwords.verify(password, user.passwordHash))) {
|
|
102
|
+
throw new CurrentPasswordInvalidError();
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
return {
|
|
106
|
+
register: (email, password, client, ctx) => passwords.enqueueHash(password).then(async (passwordHash) => {
|
|
107
|
+
let user = null;
|
|
108
|
+
try {
|
|
109
|
+
user = await repository.createUser({ email, passwordHash, createdAt: clock.now() });
|
|
110
|
+
}
|
|
111
|
+
catch (err) {
|
|
112
|
+
if (!(err instanceof EmailTakenError)) {
|
|
113
|
+
throw err;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
const delivery = user === null
|
|
117
|
+
? trySendAccountNotice(email, client, ctx)
|
|
118
|
+
: trySendLink(user, 'email_verification', client, ctx);
|
|
119
|
+
return { delivery };
|
|
120
|
+
}),
|
|
121
|
+
login: async (email, password, clientKind, afterPasswordCheck) => {
|
|
122
|
+
const found = await repository.findUserByEmail(email);
|
|
123
|
+
// The password is checked before the transaction, so no connection and no lock of the user wait for bcrypt
|
|
124
|
+
// (audit S8). An unknown account is compared with a dummy hash, so the time does not reveal it (rest:AUT-8).
|
|
125
|
+
if (!(await passwords.verify(password, found?.passwordHash ?? null)) || found === null) {
|
|
126
|
+
throw new InvalidCredentialsError();
|
|
127
|
+
}
|
|
128
|
+
await afterPasswordCheck?.();
|
|
129
|
+
// The session is issued under the lock of the user, only while the stored hash is still the checked one: a
|
|
130
|
+
// parallel change or reset of the password either comes first (this login is refused) or revokes the session
|
|
131
|
+
// this login has just issued (AuthRepository.lockUser).
|
|
132
|
+
const { user, refreshToken } = await repository.withTransaction(async (tx) => {
|
|
133
|
+
await tx.lockUser(found.userId);
|
|
134
|
+
const current = await tx.findUserById(found.userId);
|
|
135
|
+
if (current === null || current.passwordHash !== found.passwordHash) {
|
|
136
|
+
throw new InvalidCredentialsError();
|
|
137
|
+
}
|
|
138
|
+
return { user: current, refreshToken: await refreshTokens.issue(current.userId, clientKind, tx) };
|
|
139
|
+
});
|
|
140
|
+
// The state of the e-mail is the one read under the lock with the session (r1:U2).
|
|
141
|
+
return {
|
|
142
|
+
user,
|
|
143
|
+
accessToken: await accessTokens.issue(user.userId, user.emailVerifiedAt !== null),
|
|
144
|
+
refreshToken,
|
|
145
|
+
};
|
|
146
|
+
},
|
|
147
|
+
refresh: async (refreshToken, clientKind) => {
|
|
148
|
+
const { emailVerified, ...rotated } = await refreshTokens.rotate(refreshToken, clientKind);
|
|
149
|
+
return { accessToken: await accessTokens.issue(rotated.userId, emailVerified), refreshToken: rotated };
|
|
150
|
+
},
|
|
151
|
+
logout: (refreshToken, clientKind) => refreshTokens.revoke(refreshToken, clientKind),
|
|
152
|
+
revokeAllSessions: async (userId) => {
|
|
153
|
+
await refreshTokens.revokeAll(userId);
|
|
154
|
+
},
|
|
155
|
+
getUser: (userId) => requireUser(userId),
|
|
156
|
+
resendVerification: async (userId, client, ctx) => {
|
|
157
|
+
const user = await requireUser(userId);
|
|
158
|
+
if (user.emailVerifiedAt === null) {
|
|
159
|
+
await sendLink(user, 'email_verification', client, ctx);
|
|
160
|
+
}
|
|
161
|
+
},
|
|
162
|
+
emailVerificationOwner: (token) => oneTimeTokens.check(token, 'email_verification'),
|
|
163
|
+
confirmEmail: async (token, password) => {
|
|
164
|
+
const owner = await oneTimeTokens.check(token, 'email_verification');
|
|
165
|
+
const checked = await repository.findUserById(owner);
|
|
166
|
+
if (checked === null) {
|
|
167
|
+
throw new InvalidAuthTokenError('email_verification');
|
|
168
|
+
}
|
|
169
|
+
await requirePassword(checked, password);
|
|
170
|
+
await repository.withTransaction(async (tx) => {
|
|
171
|
+
// `consume` locks the user, so a parallel login issues its session either before (revoked here) or after
|
|
172
|
+
// the commit, and a parallel change of the password either comes first (refused here) or after.
|
|
173
|
+
const userId = await oneTimeTokens.consume(token, 'email_verification', tx);
|
|
174
|
+
const current = await tx.findUserById(userId);
|
|
175
|
+
if (current === null || current.passwordHash !== checked.passwordHash) {
|
|
176
|
+
throw new CurrentPasswordInvalidError();
|
|
177
|
+
}
|
|
178
|
+
await tx.markEmailVerified(userId, clock.now());
|
|
179
|
+
await refreshTokens.revokeAll(userId, tx);
|
|
180
|
+
});
|
|
181
|
+
},
|
|
182
|
+
requestPasswordReset: async (email, client, ctx) => {
|
|
183
|
+
try {
|
|
184
|
+
const user = await repository.findUserByEmail(email);
|
|
185
|
+
// Over the limit per account no token is issued, so the last link sent is not replaced (audit S5).
|
|
186
|
+
if (user !== null && (await allowResetEmail(user.userId))) {
|
|
187
|
+
await sendLink(user, 'password_reset', client, ctx);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
catch (err) {
|
|
191
|
+
logError(ctx.log, safeErrorInfo(err), 'The password reset request could not be handled.');
|
|
192
|
+
}
|
|
193
|
+
},
|
|
194
|
+
confirmPasswordReset: async (token, password) => {
|
|
195
|
+
// A token that cannot be used is refused before bcrypt, so an unknown token costs no hash; the new password is
|
|
196
|
+
// hashed before the transaction, so no connection and no lock of the user wait for bcrypt (audit S8). The
|
|
197
|
+
// token is checked again when it is used in the transaction.
|
|
198
|
+
await oneTimeTokens.check(token, 'password_reset');
|
|
199
|
+
const passwordHash = await passwords.hash(password);
|
|
200
|
+
return repository.withTransaction(async (tx) => {
|
|
201
|
+
// `consume` locks the user before it touches the token row (the same order as `issue`).
|
|
202
|
+
const userId = await oneTimeTokens.consume(token, 'password_reset', tx);
|
|
203
|
+
const user = await requireUser(userId, tx);
|
|
204
|
+
await tx.updatePasswordHash(userId, passwordHash, clock.now());
|
|
205
|
+
await refreshTokens.revokeAll(userId, tx);
|
|
206
|
+
return user;
|
|
207
|
+
});
|
|
208
|
+
},
|
|
209
|
+
changePassword: async (userId, currentPassword, newPassword) => {
|
|
210
|
+
// The current password is checked first and the new one is hashed only after it matched (audit W1), both
|
|
211
|
+
// outside the transaction, so no connection and no lock of the user wait for bcrypt.
|
|
212
|
+
const checked = await requireUser(userId);
|
|
213
|
+
await requirePassword(checked, currentPassword);
|
|
214
|
+
const passwordHash = await passwords.hash(newPassword);
|
|
215
|
+
await repository.withTransaction(async (tx) => {
|
|
216
|
+
// Under the lock of the user the stored hash must still be the checked one: a parallel change or reset
|
|
217
|
+
// that came first fails this one as a wrong current password, so two parallel changes with the same
|
|
218
|
+
// current password cannot both succeed, and a parallel login cannot slip a session in.
|
|
219
|
+
await tx.lockUser(userId);
|
|
220
|
+
const current = await requireUser(userId, tx);
|
|
221
|
+
if (current.passwordHash !== checked.passwordHash) {
|
|
222
|
+
throw new CurrentPasswordInvalidError();
|
|
223
|
+
}
|
|
224
|
+
await tx.updatePasswordHash(userId, passwordHash, clock.now());
|
|
225
|
+
await refreshTokens.revokeAll(userId, tx);
|
|
226
|
+
});
|
|
227
|
+
},
|
|
228
|
+
deleteAccount: async (userId, password) => {
|
|
229
|
+
// The password is checked before the transaction (audit S8); under the lock of the user the stored hash must
|
|
230
|
+
// still be the checked one, so a parallel change or reset of the password that came first fails this one.
|
|
231
|
+
const checked = await requireUser(userId);
|
|
232
|
+
await requirePassword(checked, password);
|
|
233
|
+
await repository.withTransaction(async (tx) => {
|
|
234
|
+
await tx.lockUser(userId);
|
|
235
|
+
const current = await requireUser(userId, tx);
|
|
236
|
+
if (current.passwordHash !== checked.passwordHash) {
|
|
237
|
+
throw new CurrentPasswordInvalidError();
|
|
238
|
+
}
|
|
239
|
+
await config.onUserDeleted?.(userId, tx);
|
|
240
|
+
await tx.deleteUser(userId);
|
|
241
|
+
});
|
|
242
|
+
},
|
|
243
|
+
};
|
|
244
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,137 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@mielk/auth",
|
|
3
|
+
"version": "2.0.1",
|
|
4
|
+
"description": "Authentication for mielk applications: server (Express), client, React layer and PostgreSQL adapter.",
|
|
5
|
+
"keywords": [],
|
|
6
|
+
"author": "mielk",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"engines": {
|
|
9
|
+
"node": ">=24"
|
|
10
|
+
},
|
|
11
|
+
"main": "./dist/index.js",
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"types": "./dist/index.d.ts",
|
|
16
|
+
"import": "./dist/index.js",
|
|
17
|
+
"default": "./dist/index.js"
|
|
18
|
+
},
|
|
19
|
+
"./schemas": {
|
|
20
|
+
"types": "./dist/schemas/index.d.ts",
|
|
21
|
+
"import": "./dist/schemas/index.js",
|
|
22
|
+
"default": "./dist/schemas/index.js"
|
|
23
|
+
},
|
|
24
|
+
"./client": {
|
|
25
|
+
"types": "./dist/client/index.d.ts",
|
|
26
|
+
"import": "./dist/client/index.js",
|
|
27
|
+
"default": "./dist/client/index.js"
|
|
28
|
+
},
|
|
29
|
+
"./react": {
|
|
30
|
+
"types": "./dist/react/index.d.ts",
|
|
31
|
+
"import": "./dist/react/index.js",
|
|
32
|
+
"default": "./dist/react/index.js"
|
|
33
|
+
},
|
|
34
|
+
"./pg": {
|
|
35
|
+
"types": "./dist/pg/index.d.ts",
|
|
36
|
+
"import": "./dist/pg/index.js",
|
|
37
|
+
"default": "./dist/pg/index.js"
|
|
38
|
+
},
|
|
39
|
+
"./pg/migrations/*": "./dist/pg/migrations/*",
|
|
40
|
+
"./locales/*": "./dist/locales/*.json"
|
|
41
|
+
},
|
|
42
|
+
"scripts": {
|
|
43
|
+
"check:import": "node scripts/check-import.ts",
|
|
44
|
+
"check:readme": "node scripts/check-readme.ts",
|
|
45
|
+
"test:pg": "node scripts/test-pg.ts",
|
|
46
|
+
"test": "vitest run --coverage",
|
|
47
|
+
"test:dist": "vitest run --config vitest.dist.config.ts",
|
|
48
|
+
"build": "npm run clean && tsc -p tsconfig.build.json && node scripts/copy-migrations.ts",
|
|
49
|
+
"clean": "node -e \"const fs = require('node:fs'); for (const e of fs.existsSync('dist') ? fs.readdirSync('dist') : []) fs.rmSync('dist/' + e, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 })\"",
|
|
50
|
+
"typecheck": "tsc --noEmit",
|
|
51
|
+
"lint": "eslint . --max-warnings 0",
|
|
52
|
+
"format": "prettier --write .",
|
|
53
|
+
"format:check": "prettier --check .",
|
|
54
|
+
"check:package": "mielk-check-package",
|
|
55
|
+
"check": "npm run build && npm run test:dist && npm run check:package && npm run check:import && npm run check:readme",
|
|
56
|
+
"prepublishOnly": "npm run typecheck && npm run lint && npm test && npm run build && npm run test:dist && npm run check:package && npm run check:readme",
|
|
57
|
+
"version": "mielk-release-changelog && git add CHANGELOG.md"
|
|
58
|
+
},
|
|
59
|
+
"license": "MIT",
|
|
60
|
+
"repository": {
|
|
61
|
+
"type": "git",
|
|
62
|
+
"url": "git+https://github.com/mielk/mielk-auth.git"
|
|
63
|
+
},
|
|
64
|
+
"homepage": "https://github.com/mielk/mielk-auth#readme",
|
|
65
|
+
"publishConfig": {
|
|
66
|
+
"access": "public"
|
|
67
|
+
},
|
|
68
|
+
"sideEffects": false,
|
|
69
|
+
"devDependencies": {
|
|
70
|
+
"@arethetypeswrong/cli": "0.18.5",
|
|
71
|
+
"@mielk/db": "3.0.0",
|
|
72
|
+
"@mielk/fn": "2.1.0",
|
|
73
|
+
"@mielk/http": "3.0.0",
|
|
74
|
+
"@mielk/lib-config": "2.0.0",
|
|
75
|
+
"@testing-library/dom": "10.4.2",
|
|
76
|
+
"@testing-library/react": "16.3.3",
|
|
77
|
+
"@types/express": "5.0.6",
|
|
78
|
+
"@types/node": "24.19.2",
|
|
79
|
+
"@types/pg": "8.23.1",
|
|
80
|
+
"@types/react": "19.3.0",
|
|
81
|
+
"@types/react-dom": "19.3.0",
|
|
82
|
+
"@vitest/coverage-v8": "5.1.1",
|
|
83
|
+
"bcryptjs": "3.0.3",
|
|
84
|
+
"eslint": "10.15.0",
|
|
85
|
+
"express": "5.3.0",
|
|
86
|
+
"helmet": "8.3.0",
|
|
87
|
+
"jose": "6.2.18",
|
|
88
|
+
"jsdom": "29.1.1",
|
|
89
|
+
"pg": "8.23.1",
|
|
90
|
+
"prettier": "3.10.1",
|
|
91
|
+
"publint": "0.3.25",
|
|
92
|
+
"react": "19.3.1",
|
|
93
|
+
"react-dom": "19.3.1",
|
|
94
|
+
"redis": "5.12.4",
|
|
95
|
+
"typescript": "5.9.3",
|
|
96
|
+
"vitest": "5.1.1",
|
|
97
|
+
"zod": "4.6.7"
|
|
98
|
+
},
|
|
99
|
+
"peerDependencies": {
|
|
100
|
+
"@mielk/db": "^3",
|
|
101
|
+
"@mielk/http": "^3",
|
|
102
|
+
"bcryptjs": "^3",
|
|
103
|
+
"express": "^5",
|
|
104
|
+
"jose": "^6",
|
|
105
|
+
"pg": "^8",
|
|
106
|
+
"react": "^19",
|
|
107
|
+
"zod": "^4"
|
|
108
|
+
},
|
|
109
|
+
"peerDependenciesMeta": {
|
|
110
|
+
"@mielk/db": {
|
|
111
|
+
"optional": true
|
|
112
|
+
},
|
|
113
|
+
"@mielk/http": {
|
|
114
|
+
"optional": true
|
|
115
|
+
},
|
|
116
|
+
"bcryptjs": {
|
|
117
|
+
"optional": true
|
|
118
|
+
},
|
|
119
|
+
"express": {
|
|
120
|
+
"optional": true
|
|
121
|
+
},
|
|
122
|
+
"jose": {
|
|
123
|
+
"optional": true
|
|
124
|
+
},
|
|
125
|
+
"pg": {
|
|
126
|
+
"optional": true
|
|
127
|
+
},
|
|
128
|
+
"react": {
|
|
129
|
+
"optional": true
|
|
130
|
+
}
|
|
131
|
+
},
|
|
132
|
+
"files": [
|
|
133
|
+
"dist",
|
|
134
|
+
"CHANGELOG.md"
|
|
135
|
+
],
|
|
136
|
+
"prettier": "@mielk/lib-config/prettier"
|
|
137
|
+
}
|