@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,72 @@
|
|
|
1
|
+
import bcrypt from 'bcryptjs';
|
|
2
|
+
import { PASSWORD_MAX_BYTES } from '../schemas/index.js';
|
|
3
|
+
import { PasswordHashingBusyError, PasswordTooLongError } from './errors.js';
|
|
4
|
+
/** bcrypt cost of new password hashes (`rest:AUT-7`: at least 12). */
|
|
5
|
+
export const PASSWORD_HASH_COST = 12;
|
|
6
|
+
export { PASSWORD_MAX_BYTES };
|
|
7
|
+
const isTooLong = (password) => Buffer.byteLength(password, 'utf8') > PASSWORD_MAX_BYTES;
|
|
8
|
+
/**
|
|
9
|
+
* bcrypt hash with cost `PASSWORD_HASH_COST` of a random password that was thrown away. Comparing with it takes as long
|
|
10
|
+
* as comparing with a real hash, so the time of a login does not reveal whether the account exists (`rest:AUT-8`). It is
|
|
11
|
+
* a constant and not computed at the first login: computing it would add a whole hashing to the first check of an
|
|
12
|
+
* unknown account. Even a match would log nobody in, because `verifyPassword` returns `false` for a missing hash.
|
|
13
|
+
*/
|
|
14
|
+
export const DUMMY_PASSWORD_HASH = '$2b$12$N/oSdCXhBWtCig3A.bM6veb9avwhgfmjU6WIASnHhh4EWpIhwhCmy';
|
|
15
|
+
/**
|
|
16
|
+
* Returns the bcrypt hash of the password with cost `PASSWORD_HASH_COST`.
|
|
17
|
+
*
|
|
18
|
+
* @throws `PasswordTooLongError` when the password has more than `PASSWORD_MAX_BYTES` bytes.
|
|
19
|
+
*/
|
|
20
|
+
export const hashPassword = async (password) => {
|
|
21
|
+
if (isTooLong(password)) {
|
|
22
|
+
throw new PasswordTooLongError();
|
|
23
|
+
}
|
|
24
|
+
return bcrypt.hash(password, PASSWORD_HASH_COST);
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Checks the password against the stored hash. With `hash === null` (unknown e-mail, or an account without a password)
|
|
28
|
+
* it compares with a dummy hash and returns `false`, so it takes the same time as with an account. A password longer
|
|
29
|
+
* than `PASSWORD_MAX_BYTES` never matches, because bcrypt would compare only its first 72 bytes.
|
|
30
|
+
*/
|
|
31
|
+
export const verifyPassword = async (password, hash) => {
|
|
32
|
+
const matches = await bcrypt.compare(password, hash ?? DUMMY_PASSWORD_HASH);
|
|
33
|
+
return matches && hash !== null && !isTooLong(password);
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* Creates the hasher of one instance of the library. bcryptjs runs on the main thread, so every operation that runs at
|
|
37
|
+
* once slows all requests of the process; the bound keeps that work limited and refuses the excess at once (503)
|
|
38
|
+
* instead of letting it pile up.
|
|
39
|
+
*/
|
|
40
|
+
export const createPasswordHasher = ({ maxConcurrent, maxQueued }) => {
|
|
41
|
+
let running = 0;
|
|
42
|
+
const waiting = [];
|
|
43
|
+
const acquire = () => {
|
|
44
|
+
if (running < maxConcurrent) {
|
|
45
|
+
running++;
|
|
46
|
+
return Promise.resolve();
|
|
47
|
+
}
|
|
48
|
+
if (waiting.length >= maxQueued) {
|
|
49
|
+
throw new PasswordHashingBusyError();
|
|
50
|
+
}
|
|
51
|
+
// The place is handed over by `release` without being given back first, so `running` stays the same.
|
|
52
|
+
return new Promise((resolve) => {
|
|
53
|
+
waiting.push(resolve);
|
|
54
|
+
});
|
|
55
|
+
};
|
|
56
|
+
const release = () => {
|
|
57
|
+
const next = waiting.shift();
|
|
58
|
+
if (next === undefined) {
|
|
59
|
+
running--;
|
|
60
|
+
}
|
|
61
|
+
else {
|
|
62
|
+
next();
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
const enqueue = (work) => acquire().then(work).finally(release);
|
|
66
|
+
const enqueueHash = (password) => enqueue(() => hashPassword(password));
|
|
67
|
+
return {
|
|
68
|
+
hash: async (password) => enqueueHash(password),
|
|
69
|
+
enqueueHash,
|
|
70
|
+
verify: async (password, hash) => enqueue(() => verifyPassword(password, hash)),
|
|
71
|
+
};
|
|
72
|
+
};
|
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ports of the application (plan TASK-191, chapter 2.4): the library does not connect to a database or a mail server
|
|
3
|
+
* itself; the application passes implementations of these interfaces in the configuration.
|
|
4
|
+
*
|
|
5
|
+
* Extension rule: later versions of the library (e.g. external login) add new optional ports or optional members,
|
|
6
|
+
* never new required members of an existing port, so an application implementation of a port stays valid.
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* Identifier of a user. A string, because PostgreSQL `bigint` arrives in Node.js as a string.
|
|
10
|
+
*
|
|
11
|
+
* @since 2.0.0
|
|
12
|
+
*/
|
|
13
|
+
export type UserId = string;
|
|
14
|
+
/**
|
|
15
|
+
* Kind of client a refresh token was issued to; a web token does not work on the mobile endpoints and back.
|
|
16
|
+
*
|
|
17
|
+
* @since 2.0.0
|
|
18
|
+
*/
|
|
19
|
+
export type ClientKind = 'web' | 'mobile';
|
|
20
|
+
/**
|
|
21
|
+
* Purpose of a one-time token.
|
|
22
|
+
*
|
|
23
|
+
* @since 2.0.0
|
|
24
|
+
*/
|
|
25
|
+
export type AuthTokenPurpose = 'email_verification' | 'password_reset';
|
|
26
|
+
/**
|
|
27
|
+
* Kind of a message of the library (`AuthMail.kind`): the purpose of its token, or `account_exists` for a registration
|
|
28
|
+
* of an address that has an account (its link is a password reset link).
|
|
29
|
+
*
|
|
30
|
+
* @since 2.0.0
|
|
31
|
+
*/
|
|
32
|
+
export type AuthMailKind = AuthTokenPurpose | 'account_exists';
|
|
33
|
+
/**
|
|
34
|
+
* Account data used by the library (table `users`; the application may have more columns).
|
|
35
|
+
*
|
|
36
|
+
* @since 2.0.0
|
|
37
|
+
*/
|
|
38
|
+
export type AuthUser = {
|
|
39
|
+
userId: UserId;
|
|
40
|
+
/** E-mail in lower case. */
|
|
41
|
+
email: string;
|
|
42
|
+
/** bcrypt hash; `null` for an account without a password (external login, later versions). */
|
|
43
|
+
passwordHash: string | null;
|
|
44
|
+
emailVerifiedAt: Date | null;
|
|
45
|
+
createdAt: Date;
|
|
46
|
+
updatedAt: Date;
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* Why a refresh token stopped being valid: `rotated` - replaced by a newer token of the same live session (only such a
|
|
50
|
+
* token counts as reused when presented again); `revoked` - its session ended (logout, revoke all sessions, change or
|
|
51
|
+
* reset of the password, a detected reuse).
|
|
52
|
+
*
|
|
53
|
+
* @since 2.0.0
|
|
54
|
+
*/
|
|
55
|
+
export type RefreshTokenRevocation = 'rotated' | 'revoked';
|
|
56
|
+
/**
|
|
57
|
+
* Stored refresh token (table `refresh_tokens`); the token itself is never stored, only its SHA-256 hash.
|
|
58
|
+
*
|
|
59
|
+
* @since 2.0.0
|
|
60
|
+
*/
|
|
61
|
+
export type RefreshTokenRecord = {
|
|
62
|
+
userId: UserId;
|
|
63
|
+
tokenHash: string;
|
|
64
|
+
/**
|
|
65
|
+
* Session (token family) the token belongs to: a login starts a new family, a rotation keeps it. A detected reuse
|
|
66
|
+
* ends only this family, not the other devices of the user (audit S1).
|
|
67
|
+
*/
|
|
68
|
+
familyId: string;
|
|
69
|
+
clientKind: ClientKind;
|
|
70
|
+
expiresAt: Date;
|
|
71
|
+
revokedAt: Date | null;
|
|
72
|
+
/** `null` while the token is valid. */
|
|
73
|
+
revokedReason: RefreshTokenRevocation | null;
|
|
74
|
+
createdAt: Date;
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* Stored one-time token (table `auth_tokens`); only its SHA-256 hash is stored.
|
|
78
|
+
*
|
|
79
|
+
* @since 2.0.0
|
|
80
|
+
*/
|
|
81
|
+
export type AuthTokenRecord = {
|
|
82
|
+
userId: UserId;
|
|
83
|
+
purpose: AuthTokenPurpose;
|
|
84
|
+
tokenHash: string;
|
|
85
|
+
expiresAt: Date;
|
|
86
|
+
usedAt: Date | null;
|
|
87
|
+
createdAt: Date;
|
|
88
|
+
};
|
|
89
|
+
/**
|
|
90
|
+
* Data of a new account.
|
|
91
|
+
*
|
|
92
|
+
* @since 2.0.0
|
|
93
|
+
*/
|
|
94
|
+
export type NewUser = {
|
|
95
|
+
/** E-mail in lower case. */
|
|
96
|
+
email: string;
|
|
97
|
+
passwordHash: string | null;
|
|
98
|
+
createdAt: Date;
|
|
99
|
+
};
|
|
100
|
+
/**
|
|
101
|
+
* Data of a new refresh token.
|
|
102
|
+
*
|
|
103
|
+
* @since 2.0.0
|
|
104
|
+
*/
|
|
105
|
+
export type NewRefreshToken = Omit<RefreshTokenRecord, 'revokedAt' | 'revokedReason'>;
|
|
106
|
+
/**
|
|
107
|
+
* Data of a new one-time token.
|
|
108
|
+
*
|
|
109
|
+
* @since 2.0.0
|
|
110
|
+
*/
|
|
111
|
+
export type NewAuthToken = Omit<AuthTokenRecord, 'usedAt'>;
|
|
112
|
+
/**
|
|
113
|
+
* Storage of accounts and tokens. Every method that changes rows takes the time from the caller (the library clock), so
|
|
114
|
+
* tests do not depend on the current time.
|
|
115
|
+
*
|
|
116
|
+
* Concurrency guarantees an adapter must give (checked by the contract tests `describeAuthRepositoryContract` in
|
|
117
|
+
* `src/testing`, which the PostgreSQL adapter runs too):
|
|
118
|
+
*
|
|
119
|
+
* - a transaction sees only committed rows of other transactions, and its rollback undoes only its own writes
|
|
120
|
+
* (PostgreSQL `READ COMMITTED` gives both);
|
|
121
|
+
* - `revokeRefreshToken` and `consumeAuthToken` are single atomic statements;
|
|
122
|
+
* - `lockUser` serializes the transactions that lock the same user. The library locks the user before every change that
|
|
123
|
+
* must see all tokens of the user written by other transactions: issuing a one-time token (a new token invalidates
|
|
124
|
+
* the earlier ones, so two parallel issues leave exactly one usable token), rotating a refresh token and revoking all
|
|
125
|
+
* refresh tokens (a token issued by a parallel rotation is either revoked by the revocation of all, or its rotation
|
|
126
|
+
* sees the presented token revoked and is treated as a reuse), and using a one-time token (`findAuthToken`, then
|
|
127
|
+
* `lockUser`, then `consumeAuthToken`).
|
|
128
|
+
*
|
|
129
|
+
* Lock order (no deadlock): every transaction of the library takes the lock of the user first and touches rows of that
|
|
130
|
+
* user's tokens only after it; no transaction takes a token row lock before `lockUser`.
|
|
131
|
+
*
|
|
132
|
+
* @since 2.0.0
|
|
133
|
+
*/
|
|
134
|
+
export interface AuthRepository {
|
|
135
|
+
/**
|
|
136
|
+
* Runs `work` in one database transaction (`rest:LAY-5`) with a repository bound to it; commits when `work`
|
|
137
|
+
* resolves and rolls back when it rejects.
|
|
138
|
+
*
|
|
139
|
+
* @param work - the operations of the transaction; receives the repository bound to it and must use that one.
|
|
140
|
+
* @returns what `work` returns.
|
|
141
|
+
*/
|
|
142
|
+
withTransaction<T>(work: (repository: AuthRepository) => Promise<T>): Promise<T>;
|
|
143
|
+
/**
|
|
144
|
+
* Locks the user until the end of the open transaction, so another transaction calling `lockUser` with the same user
|
|
145
|
+
* waits until this one commits or rolls back. Called only on the repository of `withTransaction`. A statement that
|
|
146
|
+
* runs after the lock is granted must see the rows the previous holder committed.
|
|
147
|
+
*
|
|
148
|
+
* PostgreSQL adapter: `SELECT 1 FROM users WHERE user_id = $1 FOR UPDATE` (a missing user locks nothing, and then
|
|
149
|
+
* it has no tokens either), or a transaction-level advisory lock `pg_advisory_xact_lock` keyed by the user. Under
|
|
150
|
+
* `READ COMMITTED` the following `UPDATE` statements take a new snapshot, so they see the committed rows.
|
|
151
|
+
*
|
|
152
|
+
* @param userId - the user to lock.
|
|
153
|
+
* @returns resolves when the lock is held (released at the end of the transaction), or at once when the user does not
|
|
154
|
+
* exist: nothing is locked then.
|
|
155
|
+
*/
|
|
156
|
+
lockUser(userId: UserId): Promise<void>;
|
|
157
|
+
/**
|
|
158
|
+
* Returns the account with the e-mail (compared case-insensitively), or `null`.
|
|
159
|
+
*
|
|
160
|
+
* @param email - the e-mail to look up.
|
|
161
|
+
* @returns the account, or `null` when there is none.
|
|
162
|
+
*/
|
|
163
|
+
findUserByEmail(email: string): Promise<AuthUser | null>;
|
|
164
|
+
/**
|
|
165
|
+
* Returns the account, or `null`.
|
|
166
|
+
*
|
|
167
|
+
* @param userId - the identifier of the account.
|
|
168
|
+
* @returns the account, or `null` when there is none.
|
|
169
|
+
*/
|
|
170
|
+
findUserById(userId: UserId): Promise<AuthUser | null>;
|
|
171
|
+
/**
|
|
172
|
+
* Creates an account and returns it.
|
|
173
|
+
*
|
|
174
|
+
* @param user - the data of the new account.
|
|
175
|
+
* @returns the created account with its generated identifier.
|
|
176
|
+
* @throws `EmailTakenError` when an account with the e-mail exists (unique violation, `rest:SQL-5`).
|
|
177
|
+
*/
|
|
178
|
+
createUser(user: NewUser): Promise<AuthUser>;
|
|
179
|
+
/**
|
|
180
|
+
* Sets the password hash of the account.
|
|
181
|
+
*
|
|
182
|
+
* @param userId - the account.
|
|
183
|
+
* @param passwordHash - the new bcrypt hash.
|
|
184
|
+
* @param updatedAt - the time of the change.
|
|
185
|
+
* @returns resolves when the hash is stored.
|
|
186
|
+
*/
|
|
187
|
+
updatePasswordHash(userId: UserId, passwordHash: string, updatedAt: Date): Promise<void>;
|
|
188
|
+
/**
|
|
189
|
+
* Marks the e-mail of the account as verified, unless it already is.
|
|
190
|
+
*
|
|
191
|
+
* @param userId - the account.
|
|
192
|
+
* @param verifiedAt - the time of the verification.
|
|
193
|
+
* @returns resolves when the account is marked as verified (also when it already was).
|
|
194
|
+
*/
|
|
195
|
+
markEmailVerified(userId: UserId, verifiedAt: Date): Promise<void>;
|
|
196
|
+
/**
|
|
197
|
+
* Deletes the account together with its tokens.
|
|
198
|
+
*
|
|
199
|
+
* @param userId - the account to delete.
|
|
200
|
+
* @returns resolves when the account and its tokens are deleted.
|
|
201
|
+
*/
|
|
202
|
+
deleteUser(userId: UserId): Promise<void>;
|
|
203
|
+
/**
|
|
204
|
+
* Stores a refresh token.
|
|
205
|
+
*
|
|
206
|
+
* @param token - the token record (hash only).
|
|
207
|
+
* @returns resolves when the token is stored.
|
|
208
|
+
*/
|
|
209
|
+
createRefreshToken(token: NewRefreshToken): Promise<void>;
|
|
210
|
+
/**
|
|
211
|
+
* Returns the refresh token with the hash, revoked and expired ones included, or `null`.
|
|
212
|
+
*
|
|
213
|
+
* @param tokenHash - the SHA-256 hash of the token.
|
|
214
|
+
* @returns the record, or `null` when it is unknown.
|
|
215
|
+
*/
|
|
216
|
+
findRefreshToken(tokenHash: string): Promise<RefreshTokenRecord | null>;
|
|
217
|
+
/**
|
|
218
|
+
* Revokes the refresh token only if it is not revoked yet, atomically (one `UPDATE` with the condition
|
|
219
|
+
* `revoked_at IS NULL` and `RETURNING`, `rest:AUT-4`), and returns it; returns `null` when it is unknown or was
|
|
220
|
+
* already revoked, so of two parallel calls exactly one gets the record.
|
|
221
|
+
*
|
|
222
|
+
* @param tokenHash - the SHA-256 hash of the token.
|
|
223
|
+
* @param revokedAt - the time of the revocation.
|
|
224
|
+
* @param reason - stored with the revocation (`revokedReason`).
|
|
225
|
+
* @returns the revoked record, or `null` when it is unknown or was already revoked.
|
|
226
|
+
*/
|
|
227
|
+
revokeRefreshToken(tokenHash: string, revokedAt: Date, reason: RefreshTokenRevocation): Promise<RefreshTokenRecord | null>;
|
|
228
|
+
/**
|
|
229
|
+
* Ends the session (token family) in one statement: revokes its tokens that are not revoked yet with the reason
|
|
230
|
+
* `revoked`, and sets the reason `revoked` on its rotated tokens too (keeping their `revokedAt`), so none of them
|
|
231
|
+
* can be rotated again.
|
|
232
|
+
*
|
|
233
|
+
* @param familyId - the session.
|
|
234
|
+
* @param revokedAt - the time of the revocation.
|
|
235
|
+
* @returns how many tokens were valid and are revoked now.
|
|
236
|
+
*/
|
|
237
|
+
revokeRefreshTokenFamily(familyId: string, revokedAt: Date): Promise<number>;
|
|
238
|
+
/**
|
|
239
|
+
* Ends all sessions of the user in one statement, as `revokeRefreshTokenFamily` does for every family of the user.
|
|
240
|
+
*
|
|
241
|
+
* @param userId - the user.
|
|
242
|
+
* @param revokedAt - the time of the revocation.
|
|
243
|
+
* @returns how many tokens were valid and are revoked now.
|
|
244
|
+
*/
|
|
245
|
+
revokeAllRefreshTokens(userId: UserId, revokedAt: Date): Promise<number>;
|
|
246
|
+
/**
|
|
247
|
+
* Stores a one-time token.
|
|
248
|
+
*
|
|
249
|
+
* @param token - the token record (hash only).
|
|
250
|
+
* @returns resolves when the token is stored.
|
|
251
|
+
*/
|
|
252
|
+
createAuthToken(token: NewAuthToken): Promise<void>;
|
|
253
|
+
/**
|
|
254
|
+
* Marks all unused one-time tokens of the user with the purpose as used, so they stop working.
|
|
255
|
+
*
|
|
256
|
+
* @param userId - the user.
|
|
257
|
+
* @param purpose - the purpose of the tokens to invalidate.
|
|
258
|
+
* @param usedAt - the time of the invalidation.
|
|
259
|
+
* @returns resolves when the tokens are marked as used.
|
|
260
|
+
*/
|
|
261
|
+
invalidateAuthTokens(userId: UserId, purpose: AuthTokenPurpose, usedAt: Date): Promise<void>;
|
|
262
|
+
/**
|
|
263
|
+
* Returns the one-time token with the hash in any state (used and expired ones included), or `null`. A plain read
|
|
264
|
+
* without a row lock: the library uses it to learn the owner, so it can lock the user before it updates the token
|
|
265
|
+
* row (`lockUser`, `consumeAuthToken`): the lock order is always the user first, then the token rows.
|
|
266
|
+
*
|
|
267
|
+
* @param tokenHash - the SHA-256 hash of the token.
|
|
268
|
+
* @returns the record, or `null` when it is unknown.
|
|
269
|
+
*/
|
|
270
|
+
findAuthToken(tokenHash: string): Promise<AuthTokenRecord | null>;
|
|
271
|
+
/**
|
|
272
|
+
* Marks the one-time token as used only if it has the purpose, is unused and has not expired at `usedAt`, atomically
|
|
273
|
+
* (one `UPDATE` with the conditions on the hash, the purpose, `used_at IS NULL` and the expiry, and `RETURNING`),
|
|
274
|
+
* and returns it; otherwise returns `null`.
|
|
275
|
+
*
|
|
276
|
+
* @param tokenHash - the SHA-256 hash of the token.
|
|
277
|
+
* @param purpose - the purpose the token must have.
|
|
278
|
+
* @param usedAt - the time of use; also the moment against which the expiry is checked.
|
|
279
|
+
* @returns the record marked as used, or `null` when it is unknown, has another purpose, was used or has expired.
|
|
280
|
+
*/
|
|
281
|
+
consumeAuthToken(tokenHash: string, purpose: AuthTokenPurpose, usedAt: Date): Promise<AuthTokenRecord | null>;
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Message the library asks the application to send.
|
|
285
|
+
*
|
|
286
|
+
* @since 2.0.0
|
|
287
|
+
*/
|
|
288
|
+
export type AuthMail = {
|
|
289
|
+
/**
|
|
290
|
+
* What the message is: `email_verification` (the link confirms the address), `password_reset` (the link sets a new
|
|
291
|
+
* password), or `account_exists`: somebody tried to register the address of an existing account, and the link is a
|
|
292
|
+
* password reset link of that account (audit S3). The mailer of the application must handle every kind. The page of
|
|
293
|
+
* the `email_verification` link asks for the password of the account (audit S4). The message of `account_exists` tells the owner that the account
|
|
294
|
+
* exists, that they may ignore the message if it was not them, and that the link sets a new password.
|
|
295
|
+
*/
|
|
296
|
+
kind: AuthMailKind;
|
|
297
|
+
/** Recipient e-mail. */
|
|
298
|
+
to: string;
|
|
299
|
+
/** Link with the one-time token in the fragment (`#token=…`), so the token does not reach server logs. */
|
|
300
|
+
url: string;
|
|
301
|
+
/** Language of the message requested by the client, e.g. `pl` or `en-GB`. */
|
|
302
|
+
locale: string;
|
|
303
|
+
};
|
|
304
|
+
/**
|
|
305
|
+
* Sending of e-mails; the text and translations of the messages belong to the application.
|
|
306
|
+
*
|
|
307
|
+
* @since 2.0.0
|
|
308
|
+
*/
|
|
309
|
+
export interface AuthMailer {
|
|
310
|
+
/**
|
|
311
|
+
* Sends the message; a rejection is passed to the caller.
|
|
312
|
+
*
|
|
313
|
+
* @param mail - the message to send (kind, recipient, link, locale).
|
|
314
|
+
* @returns resolves when the message is sent or handed over for sending; rejects when it fails.
|
|
315
|
+
*/
|
|
316
|
+
send(mail: AuthMail): Promise<void>;
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* Called when an account is deleted, inside the same transaction, to delete the application data of the user.
|
|
320
|
+
*
|
|
321
|
+
* @param userId - the deleted account.
|
|
322
|
+
* @param repository - the repository bound to the open transaction; an application adapter can expose its own
|
|
323
|
+
* transaction handle on it.
|
|
324
|
+
* @returns resolves when the application data of the user is deleted; a rejection rolls back the deletion of the account.
|
|
325
|
+
*
|
|
326
|
+
* @since 2.0.0
|
|
327
|
+
*/
|
|
328
|
+
export type OnUserDeleted = (userId: UserId, repository: AuthRepository) => Promise<void>;
|
|
329
|
+
/**
|
|
330
|
+
* Source of the current time; tests pass a fixed clock (`ts:TST-5`).
|
|
331
|
+
*
|
|
332
|
+
* @since 2.0.0
|
|
333
|
+
*/
|
|
334
|
+
export interface Clock {
|
|
335
|
+
/**
|
|
336
|
+
* Returns the current time.
|
|
337
|
+
*
|
|
338
|
+
* @returns the current time as a `Date`.
|
|
339
|
+
*/
|
|
340
|
+
now(): Date;
|
|
341
|
+
}
|
|
342
|
+
/** Clock of the system. */
|
|
343
|
+
export declare const systemClock: Clock;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ports of the application (plan TASK-191, chapter 2.4): the library does not connect to a database or a mail server
|
|
3
|
+
* itself; the application passes implementations of these interfaces in the configuration.
|
|
4
|
+
*
|
|
5
|
+
* Extension rule: later versions of the library (e.g. external login) add new optional ports or optional members,
|
|
6
|
+
* never new required members of an existing port, so an application implementation of a port stays valid.
|
|
7
|
+
*/
|
|
8
|
+
/** Clock of the system. */
|
|
9
|
+
export const systemClock = {
|
|
10
|
+
now: () => new Date(),
|
|
11
|
+
};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { Request, RequestHandler } from 'express';
|
|
2
|
+
import type { AuthLogger } from './config.js';
|
|
3
|
+
/** Fixed kinds of the warning, logged as the field `proxyCheck`. */
|
|
4
|
+
export type ProxyCheckWarning = 'forwarded_for_without_trust_proxy' | 'trust_proxy_true';
|
|
5
|
+
/**
|
|
6
|
+
* Whether the address is loopback, private, link-local or shared; an IPv4-mapped IPv6 address (`::ffff:127.0.0.1`) is
|
|
7
|
+
* read as its IPv4 address. Anything that is not an IP address counts as non-public.
|
|
8
|
+
*/
|
|
9
|
+
export declare const isNonPublicAddress: (address: string) => boolean;
|
|
10
|
+
/**
|
|
11
|
+
* Creates the middleware of the check. It never answers and never fails the request; each kind of warning is logged
|
|
12
|
+
* at most once by this middleware (so once per router), with the field `proxyCheck` and no address.
|
|
13
|
+
* Logger errors and rejections are ignored.
|
|
14
|
+
*
|
|
15
|
+
* @param logOf - the logger of the request (`req.log` of `@mielk/http` or the logger of the configuration).
|
|
16
|
+
*/
|
|
17
|
+
export declare const createProxyCheck: (logOf: (req: Request) => AuthLogger | undefined) => RequestHandler;
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Check of the Express setting `trust proxy`, on which every limit per IP address depends (audit TASK-191.13, W2). The
|
|
3
|
+
* limiters key on `req.ip`; Express computes it from `X-Forwarded-For` only as far as `trust proxy` allows. Two
|
|
4
|
+
* mistakes break the limits and the library warns about each once per router, without any address in the log:
|
|
5
|
+
*
|
|
6
|
+
* - `forwarded_for_without_trust_proxy`: the request has `X-Forwarded-For`, but `req.ip` is a loopback or private
|
|
7
|
+
* address. Typically the application runs behind a reverse proxy without `trust proxy`, so every client has the
|
|
8
|
+
* address of the proxy and they all share one counter (a few failed logins block the login of everybody).
|
|
9
|
+
* - `trust_proxy_true`: `trust proxy` is `true`, so `req.ip` is the first address of `X-Forwarded-For`, which the client
|
|
10
|
+
* writes itself: it can choose a new address for every request and the limits per address no longer exist.
|
|
11
|
+
*
|
|
12
|
+
* It only warns: the application may have a reason for its setting (a private network behind the proxy), and refusing
|
|
13
|
+
* requests would turn a wrong setting into an outage.
|
|
14
|
+
*/
|
|
15
|
+
import { BlockList, isIP } from 'node:net';
|
|
16
|
+
import { logWarning } from './safe-log.js';
|
|
17
|
+
/** Loopback, private, link-local and shared (carrier-grade NAT) ranges: not the address of a client on the Internet. */
|
|
18
|
+
const NON_PUBLIC = new BlockList();
|
|
19
|
+
for (const [network, prefix] of [
|
|
20
|
+
['127.0.0.0', 8],
|
|
21
|
+
['10.0.0.0', 8],
|
|
22
|
+
['172.16.0.0', 12],
|
|
23
|
+
['192.168.0.0', 16],
|
|
24
|
+
['169.254.0.0', 16],
|
|
25
|
+
['100.64.0.0', 10],
|
|
26
|
+
]) {
|
|
27
|
+
NON_PUBLIC.addSubnet(network, prefix, 'ipv4');
|
|
28
|
+
}
|
|
29
|
+
for (const [network, prefix] of [
|
|
30
|
+
['::1', 128],
|
|
31
|
+
['fc00::', 7],
|
|
32
|
+
['fe80::', 10],
|
|
33
|
+
]) {
|
|
34
|
+
NON_PUBLIC.addSubnet(network, prefix, 'ipv6');
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Whether the address is loopback, private, link-local or shared; an IPv4-mapped IPv6 address (`::ffff:127.0.0.1`) is
|
|
38
|
+
* read as its IPv4 address. Anything that is not an IP address counts as non-public.
|
|
39
|
+
*/
|
|
40
|
+
export const isNonPublicAddress = (address) => {
|
|
41
|
+
const version = isIP(address);
|
|
42
|
+
return version === 0 || NON_PUBLIC.check(address, version === 4 ? 'ipv4' : 'ipv6');
|
|
43
|
+
};
|
|
44
|
+
const MESSAGES = {
|
|
45
|
+
forwarded_for_without_trust_proxy: 'A request has X-Forwarded-For, but its address is a loopback or private one: behind a reverse proxy set the ' +
|
|
46
|
+
'Express setting "trust proxy" to the number of proxy hops, otherwise all clients share one limit per IP address.',
|
|
47
|
+
trust_proxy_true: 'The Express setting "trust proxy" is true: any client can choose its address through X-Forwarded-For and the ' +
|
|
48
|
+
'limits per IP address do not hold. Set it to the number of proxy hops.',
|
|
49
|
+
};
|
|
50
|
+
/** The warning the request shows, if any. */
|
|
51
|
+
const warningOf = (req) => {
|
|
52
|
+
if (req.app.get('trust proxy') === true) {
|
|
53
|
+
return 'trust_proxy_true';
|
|
54
|
+
}
|
|
55
|
+
const forwarded = req.headers['x-forwarded-for'];
|
|
56
|
+
if (forwarded !== undefined && forwarded !== '' && isNonPublicAddress(req.ip ?? '')) {
|
|
57
|
+
return 'forwarded_for_without_trust_proxy';
|
|
58
|
+
}
|
|
59
|
+
return undefined;
|
|
60
|
+
};
|
|
61
|
+
/**
|
|
62
|
+
* Creates the middleware of the check. It never answers and never fails the request; each kind of warning is logged
|
|
63
|
+
* at most once by this middleware (so once per router), with the field `proxyCheck` and no address.
|
|
64
|
+
* Logger errors and rejections are ignored.
|
|
65
|
+
*
|
|
66
|
+
* @param logOf - the logger of the request (`req.log` of `@mielk/http` or the logger of the configuration).
|
|
67
|
+
*/
|
|
68
|
+
export const createProxyCheck = (logOf) => {
|
|
69
|
+
const warned = new Set();
|
|
70
|
+
return (req, _res, next) => {
|
|
71
|
+
if (warned.size < Object.keys(MESSAGES).length) {
|
|
72
|
+
const warning = warningOf(req);
|
|
73
|
+
if (warning !== undefined && !warned.has(warning)) {
|
|
74
|
+
warned.add(warning);
|
|
75
|
+
logWarning(logOf(req), { proxyCheck: warning }, MESSAGES[warning]);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
next();
|
|
79
|
+
};
|
|
80
|
+
};
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import type { AuthRepository, ClientKind, Clock, UserId } from './ports.js';
|
|
2
|
+
/** Issued refresh token; `token` goes to the client (cookie or response body) and is never stored. */
|
|
3
|
+
export type IssuedRefreshToken = {
|
|
4
|
+
userId: UserId;
|
|
5
|
+
token: string;
|
|
6
|
+
expiresAt: Date;
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* A token issued by a rotation, with whether the e-mail of the account was verified, read under the lock of the user in
|
|
10
|
+
* the transaction of the rotation (r1:U2): a confirmation of the e-mail that commits first revokes the presented token,
|
|
11
|
+
* so a rotation that sees the e-mail verified belongs to a session started after the confirmation.
|
|
12
|
+
*/
|
|
13
|
+
export type RotatedRefreshToken = IssuedRefreshToken & {
|
|
14
|
+
emailVerified: boolean;
|
|
15
|
+
};
|
|
16
|
+
/** Refresh tokens: issuing, rotation with reuse detection, revocation (`rest:AUT-3`, `AUT-4`, `AUT-10`, `AUT-11`). */
|
|
17
|
+
export type RefreshTokenService = {
|
|
18
|
+
/**
|
|
19
|
+
* Issues a token of a new session (token family) for the user and the kind of client; `repository`: the repository
|
|
20
|
+
* of an open transaction.
|
|
21
|
+
*/
|
|
22
|
+
issue(userId: UserId, clientKind: ClientKind, repository?: AuthRepository): Promise<IssuedRefreshToken>;
|
|
23
|
+
/**
|
|
24
|
+
* Revokes the presented token and issues a new one of the same session, in one transaction under the lock of the
|
|
25
|
+
* user. A token rotated at most `reuseGraceSeconds` ago gets another new token of its session (two tabs with one
|
|
26
|
+
* cookie, a retry after a lost response; audit W3); the earlier successor stays valid.
|
|
27
|
+
*
|
|
28
|
+
* @throws `InvalidRefreshTokenError` for an unknown token, a token of the other kind of client or a token whose
|
|
29
|
+
* session ended (logout, revoke all, password change; nothing changes), `RefreshTokenExpiredError` for an expired
|
|
30
|
+
* token, checked before anything else (nothing changes), `RefreshTokenReusedError` for a token rotated longer than
|
|
31
|
+
* the grace window ago; the session of the token is ended before it is thrown, the other sessions stay (audit S1).
|
|
32
|
+
*/
|
|
33
|
+
rotate(token: string, clientKind: ClientKind): Promise<RotatedRefreshToken>;
|
|
34
|
+
/**
|
|
35
|
+
* Ends the session of the presented token (logout, plan TASK-191 2.2), with every token of that session, under the
|
|
36
|
+
* lock of the user; the other sessions of the user stay, revoking them is the separate `revokeAll`. Idempotent: an
|
|
37
|
+
* unknown token, a token of the other kind of client and an expired token change nothing (an expired token may be
|
|
38
|
+
* the ancestor of a valid one of the same session, r1:U3), and a repeated logout succeeds; the session of a rotated
|
|
39
|
+
* token that has not expired is ended.
|
|
40
|
+
*/
|
|
41
|
+
revoke(token: string, clientKind: ClientKind): Promise<void>;
|
|
42
|
+
/**
|
|
43
|
+
* Revokes all tokens of the user (change and reset of the password, revoke all sessions); returns their number.
|
|
44
|
+
* Locks the user first (`AuthRepository.lockUser`), as rotation does, so a token issued by a parallel rotation
|
|
45
|
+
* does not stay active. A token issued later by a new login is a new session and stays active.
|
|
46
|
+
* `repository`: the repository of an open transaction; without it the method opens its own.
|
|
47
|
+
*/
|
|
48
|
+
revokeAll(userId: UserId, repository?: AuthRepository): Promise<number>;
|
|
49
|
+
};
|
|
50
|
+
/** Options of `createRefreshTokenService`. */
|
|
51
|
+
export type RefreshTokenOptions = {
|
|
52
|
+
repository: AuthRepository;
|
|
53
|
+
/** Lifetime in seconds, validated by the configuration. */
|
|
54
|
+
ttlSeconds: number;
|
|
55
|
+
/** Grace window for a repeated rotation in seconds, validated by the configuration; default 0 (no window). */
|
|
56
|
+
reuseGraceSeconds?: number;
|
|
57
|
+
clock: Clock;
|
|
58
|
+
};
|
|
59
|
+
/** Creates the refresh token service. */
|
|
60
|
+
export declare const createRefreshTokenService: ({ repository, ttlSeconds, reuseGraceSeconds, clock, }: RefreshTokenOptions) => RefreshTokenService;
|