@mielk/auth 0.0.0-stage → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/LICENSE +21 -0
  3. package/README.md +670 -2
  4. package/dist/client/api-address.d.ts +17 -0
  5. package/dist/client/api-address.js +434 -0
  6. package/dist/client/auth-client.d.ts +226 -0
  7. package/dist/client/auth-client.js +676 -0
  8. package/dist/client/errors.d.ts +66 -0
  9. package/dist/client/errors.js +33 -0
  10. package/dist/client/guards.d.ts +26 -0
  11. package/dist/client/guards.js +27 -0
  12. package/dist/client/index.d.ts +4 -0
  13. package/dist/client/index.js +2 -0
  14. package/dist/index.d.ts +7 -0
  15. package/dist/index.js +4 -0
  16. package/dist/locales/en-GB.json +50 -0
  17. package/dist/locales/pl.json +50 -0
  18. package/dist/messages.d.ts +65 -0
  19. package/dist/messages.js +57 -0
  20. package/dist/pg/index.d.ts +1 -0
  21. package/dist/pg/index.js +1 -0
  22. package/dist/pg/migrations/0001_mielk_auth.sql +65 -0
  23. package/dist/pg/pg-auth-repository.d.ts +91 -0
  24. package/dist/pg/pg-auth-repository.js +252 -0
  25. package/dist/react/auth-provider.d.ts +70 -0
  26. package/dist/react/auth-provider.js +72 -0
  27. package/dist/react/index.d.ts +2 -0
  28. package/dist/react/index.js +1 -0
  29. package/dist/schemas/index.d.ts +234 -0
  30. package/dist/schemas/index.js +145 -0
  31. package/dist/server/access-token.d.ts +48 -0
  32. package/dist/server/access-token.js +54 -0
  33. package/dist/server/auth-middleware.d.ts +40 -0
  34. package/dist/server/auth-middleware.js +61 -0
  35. package/dist/server/config.d.ts +231 -0
  36. package/dist/server/config.js +250 -0
  37. package/dist/server/cookies.d.ts +13 -0
  38. package/dist/server/cookies.js +35 -0
  39. package/dist/server/core.d.ts +20 -0
  40. package/dist/server/core.js +32 -0
  41. package/dist/server/create-auth.d.ts +38 -0
  42. package/dist/server/create-auth.js +33 -0
  43. package/dist/server/errors.d.ts +177 -0
  44. package/dist/server/errors.js +201 -0
  45. package/dist/server/http-errors.d.ts +9 -0
  46. package/dist/server/http-errors.js +34 -0
  47. package/dist/server/limits.d.ts +95 -0
  48. package/dist/server/limits.js +98 -0
  49. package/dist/server/one-time-token.d.ts +49 -0
  50. package/dist/server/one-time-token.js +60 -0
  51. package/dist/server/opaque-token.d.ts +6 -0
  52. package/dist/server/opaque-token.js +7 -0
  53. package/dist/server/password.d.ts +43 -0
  54. package/dist/server/password.js +78 -0
  55. package/dist/server/ports.d.ts +343 -0
  56. package/dist/server/ports.js +11 -0
  57. package/dist/server/proxy-check.d.ts +16 -0
  58. package/dist/server/proxy-check.js +78 -0
  59. package/dist/server/refresh-token.d.ts +60 -0
  60. package/dist/server/refresh-token.js +122 -0
  61. package/dist/server/router.d.ts +29 -0
  62. package/dist/server/router.js +331 -0
  63. package/dist/server/service.d.ts +158 -0
  64. package/dist/server/service.js +270 -0
  65. package/package.json +136 -5
@@ -0,0 +1,270 @@
1
+ import { AuthError, CurrentPasswordInvalidError, EmailTakenError, InvalidAccessTokenError, InvalidAuthTokenError, InvalidCredentialsError, } from './errors.js';
2
+ import { buildAuthLink } from './one-time-token.js';
3
+ /**
4
+ * Failure of the mailer. It carries no cause, message, name or address of the original error: the errors of mail ports
5
+ * tend to quote the recipient or the link with the token, and their names are chosen by foreign code, so only a fixed
6
+ * category is kept; this error is logged and reaches the final error handler.
7
+ */
8
+ export class LinkDeliveryError extends Error {
9
+ name = 'LinkDeliveryError';
10
+ /** Fixed category of the original failure, safe to log. */
11
+ reason;
12
+ constructor(original) {
13
+ super('The e-mail with the link could not be sent.');
14
+ this.reason = original instanceof Error ? 'mailer_error' : 'mailer_non_error';
15
+ }
16
+ }
17
+ /**
18
+ * What of an error may be logged: a fixed category only. The message, name and fields of an error from a dependency
19
+ * (repository, mailer, Redis) may quote an address, a key or a token, and the name is chosen by foreign code too.
20
+ */
21
+ export const safeErrorInfo = (err) => ({
22
+ errorCategory: err instanceof LinkDeliveryError
23
+ ? 'link_delivery'
24
+ : err instanceof AuthError
25
+ ? 'library_error'
26
+ : 'unexpected_error',
27
+ });
28
+ /**
29
+ * Logs a failure without letting the logger fail the work (r3:U1): a logger that throws is ignored, and so is one whose
30
+ * method returns a promise that rejects (an `async` method fits the `void` contract of `AuthLogger`), so neither can
31
+ * become an unhandled rejection that ends the process of Node.js after the answer.
32
+ */
33
+ export const logError = (log, info, message) => {
34
+ logSafely(log, 'error', info, message);
35
+ };
36
+ /** Logs a warning with the same protection against a failing logger as `logError`. */
37
+ export const logWarning = (log, info, message) => {
38
+ logSafely(log, 'warn', info, message);
39
+ };
40
+ const logSafely = (log, level, info, message) => {
41
+ try {
42
+ const result = log?.[level](info, message);
43
+ // A logger that is declared to return `void` may return a promise anyway: the cast only reads `then`, and the check is the `typeof`.
44
+ if (typeof result?.then === 'function') {
45
+ result.then(undefined, () => undefined);
46
+ }
47
+ }
48
+ catch {
49
+ // The logger itself fails: nothing else could report it, the process goes on.
50
+ }
51
+ };
52
+ /** Creates the service on the core of the library. */
53
+ export const createAuthService = (core, options = {}) => {
54
+ const { config, accessTokens, refreshTokens, oneTimeTokens, passwords } = core;
55
+ const { repository, mailer, clock } = config;
56
+ const allowResetEmail = options.allowPasswordResetEmail ?? (() => Promise.resolve(true));
57
+ const linkBase = (client) => client === 'mobile' && config.links.mobile !== undefined ? config.links.mobile : config.links.web;
58
+ const sendLink = async (user, purpose, client, ctx, kind = purpose) => {
59
+ const issued = await oneTimeTokens.issue(user.userId, purpose);
60
+ try {
61
+ await mailer.send({
62
+ kind,
63
+ to: user.email,
64
+ url: buildAuthLink(linkBase(client), purpose, issued.token),
65
+ locale: ctx.locale,
66
+ });
67
+ }
68
+ catch (err) {
69
+ throw new LinkDeliveryError(err);
70
+ }
71
+ };
72
+ /** Sends a link without failing the caller; the failure is logged (the logged error carries no token or link). */
73
+ const trySendLink = async (user, purpose, client, ctx, kind = purpose) => {
74
+ try {
75
+ await sendLink(user, purpose, client, ctx, kind);
76
+ }
77
+ catch (err) {
78
+ logError(ctx.log, {
79
+ ...safeErrorInfo(err),
80
+ ...(err instanceof LinkDeliveryError ? { reason: err.reason } : {}),
81
+ purpose,
82
+ kind,
83
+ }, 'The e-mail with the link could not be sent.');
84
+ }
85
+ };
86
+ /**
87
+ * Sends the owner of a registered address the `account_exists` notice within the limit per account; never rejects
88
+ * (failures are logged).
89
+ */
90
+ const trySendAccountNotice = async (email, client, ctx) => {
91
+ let user;
92
+ try {
93
+ user = await repository.findUserByEmail(email);
94
+ }
95
+ catch (err) {
96
+ logError(ctx.log, safeErrorInfo(err), 'The registered account could not be read; nothing is sent.');
97
+ return;
98
+ }
99
+ if (user === null) {
100
+ // Deleted between the registration and this reading: nobody to notify.
101
+ return;
102
+ }
103
+ let allowed;
104
+ try {
105
+ allowed = await allowResetEmail(user.userId);
106
+ }
107
+ catch (err) {
108
+ logError(ctx.log, safeErrorInfo(err), 'The limit of reset links could not be checked; nothing is sent.');
109
+ return;
110
+ }
111
+ if (allowed) {
112
+ await trySendLink(user, 'password_reset', client, ctx, 'account_exists');
113
+ }
114
+ };
115
+ const requireUser = async (userId, source = repository) => {
116
+ const user = await source.findUserById(userId);
117
+ if (user === null) {
118
+ throw new InvalidAccessTokenError();
119
+ }
120
+ return user;
121
+ };
122
+ const requirePassword = async (user, password) => {
123
+ if (!(await passwords.verify(password, user.passwordHash))) {
124
+ throw new CurrentPasswordInvalidError();
125
+ }
126
+ };
127
+ return {
128
+ register: async (email, password, client, ctx) => {
129
+ const passwordHash = await passwords.hash(password);
130
+ let user = null;
131
+ try {
132
+ user = await repository.createUser({ email, passwordHash, createdAt: clock.now() });
133
+ }
134
+ catch (err) {
135
+ if (!(err instanceof EmailTakenError)) {
136
+ throw err;
137
+ }
138
+ }
139
+ // The answer waits for the same steps in both cases; what differs (the token and the mailer for a new
140
+ // account; the reading of the account, the limit and the mailer for a taken address, whose owner gets a
141
+ // reset link, audit S3) runs on in `delivery`, not awaited here (r1:U1).
142
+ const delivery = user === null
143
+ ? trySendAccountNotice(email, client, ctx)
144
+ : trySendLink(user, 'email_verification', client, ctx);
145
+ return { delivery };
146
+ },
147
+ login: async (email, password, clientKind, afterPasswordCheck) => {
148
+ const found = await repository.findUserByEmail(email);
149
+ // The password is checked before the transaction, so no connection and no lock of the user wait for bcrypt
150
+ // (audit S8). An unknown account is compared with a dummy hash, so the time does not reveal it (rest:AUT-8).
151
+ if (!(await passwords.verify(password, found?.passwordHash ?? null)) || found === null) {
152
+ throw new InvalidCredentialsError();
153
+ }
154
+ await afterPasswordCheck?.();
155
+ // The session is issued under the lock of the user, only while the stored hash is still the checked one: a
156
+ // parallel change or reset of the password either comes first (this login is refused) or revokes the session
157
+ // this login has just issued (AuthRepository.lockUser).
158
+ const { user, refreshToken } = await repository.withTransaction(async (tx) => {
159
+ await tx.lockUser(found.userId);
160
+ const current = await tx.findUserById(found.userId);
161
+ if (current === null || current.passwordHash !== found.passwordHash) {
162
+ throw new InvalidCredentialsError();
163
+ }
164
+ return { user: current, refreshToken: await refreshTokens.issue(current.userId, clientKind, tx) };
165
+ });
166
+ // The state of the e-mail is the one read under the lock with the session (r1:U2).
167
+ return {
168
+ user,
169
+ accessToken: await accessTokens.issue(user.userId, user.emailVerifiedAt !== null),
170
+ refreshToken,
171
+ };
172
+ },
173
+ refresh: async (refreshToken, clientKind) => {
174
+ const { emailVerified, ...rotated } = await refreshTokens.rotate(refreshToken, clientKind);
175
+ return { accessToken: await accessTokens.issue(rotated.userId, emailVerified), refreshToken: rotated };
176
+ },
177
+ logout: (refreshToken, clientKind) => refreshTokens.revoke(refreshToken, clientKind),
178
+ revokeAllSessions: async (userId) => {
179
+ await refreshTokens.revokeAll(userId);
180
+ },
181
+ getUser: (userId) => requireUser(userId),
182
+ resendVerification: async (userId, client, ctx) => {
183
+ const user = await requireUser(userId);
184
+ if (user.emailVerifiedAt === null) {
185
+ await sendLink(user, 'email_verification', client, ctx);
186
+ }
187
+ },
188
+ emailVerificationOwner: (token) => oneTimeTokens.check(token, 'email_verification'),
189
+ confirmEmail: async (token, password) => {
190
+ const owner = await oneTimeTokens.check(token, 'email_verification');
191
+ const checked = await repository.findUserById(owner);
192
+ if (checked === null) {
193
+ throw new InvalidAuthTokenError('email_verification');
194
+ }
195
+ await requirePassword(checked, password);
196
+ await repository.withTransaction(async (tx) => {
197
+ // `consume` locks the user, so a parallel login issues its session either before (revoked here) or after
198
+ // the commit, and a parallel change of the password either comes first (refused here) or after.
199
+ const userId = await oneTimeTokens.consume(token, 'email_verification', tx);
200
+ const current = await tx.findUserById(userId);
201
+ if (current === null || current.passwordHash !== checked.passwordHash) {
202
+ throw new CurrentPasswordInvalidError();
203
+ }
204
+ await tx.markEmailVerified(userId, clock.now());
205
+ await refreshTokens.revokeAll(userId, tx);
206
+ });
207
+ },
208
+ requestPasswordReset: async (email, client, ctx) => {
209
+ try {
210
+ const user = await repository.findUserByEmail(email);
211
+ // Over the limit per account no token is issued, so the last link sent is not replaced (audit S5).
212
+ if (user !== null && (await allowResetEmail(user.userId))) {
213
+ await sendLink(user, 'password_reset', client, ctx);
214
+ }
215
+ }
216
+ catch (err) {
217
+ logError(ctx.log, safeErrorInfo(err), 'The password reset request could not be handled.');
218
+ }
219
+ },
220
+ confirmPasswordReset: async (token, password) => {
221
+ // A token that cannot be used is refused before bcrypt, so an unknown token costs no hash; the new password is
222
+ // hashed before the transaction, so no connection and no lock of the user wait for bcrypt (audit S8). The
223
+ // token is checked again when it is used in the transaction.
224
+ await oneTimeTokens.check(token, 'password_reset');
225
+ const passwordHash = await passwords.hash(password);
226
+ return repository.withTransaction(async (tx) => {
227
+ // `consume` locks the user before it touches the token row (the same order as `issue`).
228
+ const userId = await oneTimeTokens.consume(token, 'password_reset', tx);
229
+ const user = await requireUser(userId, tx);
230
+ await tx.updatePasswordHash(userId, passwordHash, clock.now());
231
+ await refreshTokens.revokeAll(userId, tx);
232
+ return user;
233
+ });
234
+ },
235
+ changePassword: async (userId, currentPassword, newPassword) => {
236
+ // The current password is checked first and the new one is hashed only after it matched (audit W1), both
237
+ // outside the transaction, so no connection and no lock of the user wait for bcrypt.
238
+ const checked = await requireUser(userId);
239
+ await requirePassword(checked, currentPassword);
240
+ const passwordHash = await passwords.hash(newPassword);
241
+ await repository.withTransaction(async (tx) => {
242
+ // Under the lock of the user the stored hash must still be the checked one: a parallel change or reset
243
+ // that came first fails this one as a wrong current password, so two parallel changes with the same
244
+ // current password cannot both succeed, and a parallel login cannot slip a session in.
245
+ await tx.lockUser(userId);
246
+ const current = await requireUser(userId, tx);
247
+ if (current.passwordHash !== checked.passwordHash) {
248
+ throw new CurrentPasswordInvalidError();
249
+ }
250
+ await tx.updatePasswordHash(userId, passwordHash, clock.now());
251
+ await refreshTokens.revokeAll(userId, tx);
252
+ });
253
+ },
254
+ deleteAccount: async (userId, password) => {
255
+ // The password is checked before the transaction (audit S8); under the lock of the user the stored hash must
256
+ // still be the checked one, so a parallel change or reset of the password that came first fails this one.
257
+ const checked = await requireUser(userId);
258
+ await requirePassword(checked, password);
259
+ await repository.withTransaction(async (tx) => {
260
+ await tx.lockUser(userId);
261
+ const current = await requireUser(userId, tx);
262
+ if (current.passwordHash !== checked.passwordHash) {
263
+ throw new CurrentPasswordInvalidError();
264
+ }
265
+ await config.onUserDeleted?.(userId, tx);
266
+ await tx.deleteUser(userId);
267
+ });
268
+ },
269
+ };
270
+ };
package/package.json CHANGED
@@ -1,6 +1,137 @@
1
1
  {
2
- "name": "@mielk/auth",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@mielk/auth",
3
+ "version": "2.0.0",
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
+ }