@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,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One violation of a validation in a 400 answer: the path of the field (e.g. `body.email`) and the message key of the condition.
|
|
3
|
+
*
|
|
4
|
+
* @since 2.0.0
|
|
5
|
+
*/
|
|
6
|
+
export type AuthClientIssue = {
|
|
7
|
+
path: string;
|
|
8
|
+
message: string;
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* What went wrong with a request of the client (`ts:ERR-6`: the field `kind` tells the cases apart, not the message).
|
|
12
|
+
*
|
|
13
|
+
* @since 2.0.0
|
|
14
|
+
*/
|
|
15
|
+
export type AuthClientErrorKind =
|
|
16
|
+
/** The request did not reach the server or the connection broke (`status` is 0). */
|
|
17
|
+
'network'
|
|
18
|
+
/** The response is not in the shape of `ApiResponse` or lacks the data the endpoint promises (`rest:RES-1`). */
|
|
19
|
+
| 'invalid-response'
|
|
20
|
+
/** The server answered with an error status. */
|
|
21
|
+
| 'api'
|
|
22
|
+
/**
|
|
23
|
+
* Not sent: the session seen when the operation was called ended or was replaced (a login or a logout) before its
|
|
24
|
+
* turn came (`status` is 0).
|
|
25
|
+
*/
|
|
26
|
+
| 'session-changed';
|
|
27
|
+
/**
|
|
28
|
+
* Fields of an `AuthClientError` besides the message key.
|
|
29
|
+
*
|
|
30
|
+
* @since 2.0.0
|
|
31
|
+
*/
|
|
32
|
+
export type AuthClientErrorDetails = {
|
|
33
|
+
kind: AuthClientErrorKind;
|
|
34
|
+
/** HTTP status of the response, 0 when there was none. */
|
|
35
|
+
status: number;
|
|
36
|
+
/** Parameters of the message key for the translation. */
|
|
37
|
+
params?: Record<string, unknown> | undefined;
|
|
38
|
+
/** Violations of a validation (400), with the message key of each condition. */
|
|
39
|
+
issues?: AuthClientIssue[] | undefined;
|
|
40
|
+
/** Value of `Retry-After` in seconds (429, 423, 503), when the server sent a number. */
|
|
41
|
+
retryAfterSeconds?: number | undefined;
|
|
42
|
+
/** The error behind this one (`ts:ERR-4`). */
|
|
43
|
+
cause?: unknown;
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* Error of a request to the authentication API. `message` is a message key (`api/auth/<area>:<name>`, `rest:RES-9`),
|
|
47
|
+
* never a text for the user: the interface translates it with the translations from `@mielk/auth/locales/*`.
|
|
48
|
+
*
|
|
49
|
+
* @since 2.0.0
|
|
50
|
+
*/
|
|
51
|
+
export declare class AuthClientError extends Error {
|
|
52
|
+
readonly kind: AuthClientErrorKind;
|
|
53
|
+
readonly status: number;
|
|
54
|
+
readonly params: Record<string, unknown> | undefined;
|
|
55
|
+
readonly issues: AuthClientIssue[] | undefined;
|
|
56
|
+
readonly retryAfterSeconds: number | undefined;
|
|
57
|
+
constructor(messageKey: string, details: AuthClientErrorDetails);
|
|
58
|
+
/** The message key (the same as `message`). */
|
|
59
|
+
get messageKey(): string;
|
|
60
|
+
}
|
|
61
|
+
/** The request did not get an answer: the key `api/auth/client:networkError`. */
|
|
62
|
+
export declare const networkError: (cause: unknown) => AuthClientError;
|
|
63
|
+
/** The answer is not what the endpoint promises: the key `api/auth/client:invalidResponse`. */
|
|
64
|
+
export declare const invalidResponseError: (status: number) => AuthClientError;
|
|
65
|
+
/** The session of the call is gone before the request was sent: the key `api/auth/client:sessionChanged`. */
|
|
66
|
+
export declare const sessionChangedError: () => AuthClientError;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { Msg } from '../messages.js';
|
|
2
|
+
/**
|
|
3
|
+
* Error of a request to the authentication API. `message` is a message key (`api/auth/<area>:<name>`, `rest:RES-9`),
|
|
4
|
+
* never a text for the user: the interface translates it with the translations from `@mielk/auth/locales/*`.
|
|
5
|
+
*
|
|
6
|
+
* @since 2.0.0
|
|
7
|
+
*/
|
|
8
|
+
export class AuthClientError extends Error {
|
|
9
|
+
kind;
|
|
10
|
+
status;
|
|
11
|
+
params;
|
|
12
|
+
issues;
|
|
13
|
+
retryAfterSeconds;
|
|
14
|
+
constructor(messageKey, details) {
|
|
15
|
+
super(messageKey, details.cause === undefined ? undefined : { cause: details.cause });
|
|
16
|
+
this.name = 'AuthClientError';
|
|
17
|
+
this.kind = details.kind;
|
|
18
|
+
this.status = details.status;
|
|
19
|
+
this.params = details.params;
|
|
20
|
+
this.issues = details.issues;
|
|
21
|
+
this.retryAfterSeconds = details.retryAfterSeconds;
|
|
22
|
+
}
|
|
23
|
+
/** The message key (the same as `message`). */
|
|
24
|
+
get messageKey() {
|
|
25
|
+
return this.message;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
/** The request did not get an answer: the key `api/auth/client:networkError`. */
|
|
29
|
+
export const networkError = (cause) => new AuthClientError(Msg.client.networkError, { kind: 'network', status: 0, cause });
|
|
30
|
+
/** The answer is not what the endpoint promises: the key `api/auth/client:invalidResponse`. */
|
|
31
|
+
export const invalidResponseError = (status) => new AuthClientError(Msg.client.invalidResponse, { kind: 'invalid-response', status });
|
|
32
|
+
/** The session of the call is gone before the request was sent: the key `api/auth/client:sessionChanged`. */
|
|
33
|
+
export const sessionChangedError = () => new AuthClientError(Msg.client.sessionChanged, { kind: 'session-changed', status: 0 });
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Checks of the response bodies of the authentication API. The client has no runtime dependencies (`./client` needs
|
|
3
|
+
* neither `zod` nor `@mielk/http`), so the shape of `ApiResponse` (`rest:RES-1`) is checked by hand, as the standard
|
|
4
|
+
* wants the body validated instead of cast (`react:DAN-5`).
|
|
5
|
+
*/
|
|
6
|
+
import type { AuthUserResponse, LoginResponse, MobileLoginResponse, MobileRefreshResponse, RefreshResponse, UserResponse } from '../schemas/index.js';
|
|
7
|
+
import type { AuthClientIssue } from './errors.js';
|
|
8
|
+
/** The body `{ success: true, data }`. */
|
|
9
|
+
export declare const isApiSuccess: (body: unknown) => body is {
|
|
10
|
+
success: true;
|
|
11
|
+
data: unknown;
|
|
12
|
+
};
|
|
13
|
+
/** The parts of the body `{ success: false, message, params?, issues? }` the client uses. */
|
|
14
|
+
export type ApiFailureBody = {
|
|
15
|
+
message: string;
|
|
16
|
+
params: Record<string, unknown> | undefined;
|
|
17
|
+
issues: AuthClientIssue[] | undefined;
|
|
18
|
+
};
|
|
19
|
+
/** Reads the failure body; `undefined` when the body is not one. */
|
|
20
|
+
export declare const readApiFailure: (body: unknown) => ApiFailureBody | undefined;
|
|
21
|
+
export declare const isAuthUser: (value: unknown) => value is AuthUserResponse;
|
|
22
|
+
export declare const isUserResponse: (value: unknown) => value is UserResponse;
|
|
23
|
+
export declare const isLoginResponse: (value: unknown) => value is LoginResponse;
|
|
24
|
+
export declare const isRefreshResponse: (value: unknown) => value is RefreshResponse;
|
|
25
|
+
export declare const isMobileLoginResponse: (value: unknown) => value is MobileLoginResponse;
|
|
26
|
+
export declare const isMobileRefreshResponse: (value: unknown) => value is MobileRefreshResponse;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
const isRecord = (value) => typeof value === 'object' && value !== null;
|
|
2
|
+
const isNonEmptyString = (value) => typeof value === 'string' && value.length > 0;
|
|
3
|
+
/** The body `{ success: true, data }`. */
|
|
4
|
+
export const isApiSuccess = (body) => isRecord(body) && body['success'] === true && 'data' in body;
|
|
5
|
+
const isIssue = (value) => isRecord(value) && typeof value['path'] === 'string' && typeof value['message'] === 'string';
|
|
6
|
+
/** Reads the failure body; `undefined` when the body is not one. */
|
|
7
|
+
export const readApiFailure = (body) => {
|
|
8
|
+
if (!isRecord(body) || body['success'] !== false || !isNonEmptyString(body['message']))
|
|
9
|
+
return undefined;
|
|
10
|
+
const params = body['params'];
|
|
11
|
+
const issues = body['issues'];
|
|
12
|
+
return {
|
|
13
|
+
message: body['message'],
|
|
14
|
+
params: isRecord(params) ? params : undefined,
|
|
15
|
+
issues: Array.isArray(issues) ? issues.filter(isIssue) : undefined,
|
|
16
|
+
};
|
|
17
|
+
};
|
|
18
|
+
export const isAuthUser = (value) => isRecord(value) &&
|
|
19
|
+
isNonEmptyString(value['userId']) &&
|
|
20
|
+
typeof value['email'] === 'string' &&
|
|
21
|
+
typeof value['emailVerified'] === 'boolean' &&
|
|
22
|
+
typeof value['createdAt'] === 'string';
|
|
23
|
+
export const isUserResponse = (value) => isRecord(value) && isAuthUser(value['user']);
|
|
24
|
+
export const isLoginResponse = (value) => isRecord(value) && isNonEmptyString(value['accessToken']) && isAuthUser(value['user']);
|
|
25
|
+
export const isRefreshResponse = (value) => isRecord(value) && isNonEmptyString(value['accessToken']);
|
|
26
|
+
export const isMobileLoginResponse = (value) => isLoginResponse(value) && isNonEmptyString(Reflect.get(value, 'refreshToken'));
|
|
27
|
+
export const isMobileRefreshResponse = (value) => isRefreshResponse(value) && isNonEmptyString(Reflect.get(value, 'refreshToken'));
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { createAuthClient } from './auth-client.js';
|
|
2
|
+
export type { AuthClient, AuthClientOptions, AuthState, RefreshTokenStore } from './auth-client.js';
|
|
3
|
+
export { AuthClientError } from './errors.js';
|
|
4
|
+
export type { AuthClientErrorDetails, AuthClientErrorKind, AuthClientIssue } from './errors.js';
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { Msg, type MessageKey } from './messages.js';
|
|
2
|
+
export { createAuth, type Auth } from './server/create-auth.js';
|
|
3
|
+
export { mobileOriginGuard } from './server/router.js';
|
|
4
|
+
export type { AuthenticatedUser } from './server/auth-middleware.js';
|
|
5
|
+
export type { AuthConfig, AuthLimitsConfig, AuthLogger, LimitSetting } from './server/config.js';
|
|
6
|
+
export { AccessTokenExpiredError, AccountBusyError, AuthConfigError, AuthError, CurrentPasswordInvalidError, EmailNotVerifiedError, EmailTakenError, InvalidAccessTokenError, InvalidAuthTokenError, InvalidCredentialsError, InvalidRefreshTokenError, PasswordHashingBusyError, PasswordTooLongError, RefreshTokenExpiredError, RefreshTokenReusedError, type AuthErrorCode, } from './server/errors.js';
|
|
7
|
+
export type { AuthMail, AuthMailer, AuthMailKind, AuthRepository, AuthTokenPurpose, AuthTokenRecord, AuthUser, ClientKind, Clock, NewAuthToken, NewRefreshToken, NewUser, OnUserDeleted, RefreshTokenRecord, UserId, } from './server/ports.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { Msg } from './messages.js';
|
|
2
|
+
export { createAuth } from './server/create-auth.js';
|
|
3
|
+
export { mobileOriginGuard } from './server/router.js';
|
|
4
|
+
export { AccessTokenExpiredError, AccountBusyError, AuthConfigError, AuthError, CurrentPasswordInvalidError, EmailNotVerifiedError, EmailTakenError, InvalidAccessTokenError, InvalidAuthTokenError, InvalidCredentialsError, InvalidRefreshTokenError, PasswordHashingBusyError, PasswordTooLongError, RefreshTokenExpiredError, RefreshTokenReusedError, } from './server/errors.js';
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
{
|
|
2
|
+
"api/auth/config": {
|
|
3
|
+
"invalid": "The authentication is not configured correctly."
|
|
4
|
+
},
|
|
5
|
+
"api/auth/login": {
|
|
6
|
+
"invalidCredentials": "Incorrect e-mail address or password."
|
|
7
|
+
},
|
|
8
|
+
"api/auth/password": {
|
|
9
|
+
"tooLong": "The password is too long (at most 72 bytes).",
|
|
10
|
+
"tooShort": "The password must have at least 10 characters.",
|
|
11
|
+
"required": "Enter the password.",
|
|
12
|
+
"currentInvalid": "The current password is incorrect.",
|
|
13
|
+
"busy": "The server is busy at the moment. Try again shortly."
|
|
14
|
+
},
|
|
15
|
+
"api/auth/validation": {
|
|
16
|
+
"emailInvalid": "Enter a valid e-mail address.",
|
|
17
|
+
"tokenRequired": "The link is incomplete or invalid."
|
|
18
|
+
},
|
|
19
|
+
"api/auth/mobile": {
|
|
20
|
+
"originForbidden": "This request is not allowed from a browser."
|
|
21
|
+
},
|
|
22
|
+
"api/auth/register": {
|
|
23
|
+
"emailTaken": "An account with this e-mail address already exists."
|
|
24
|
+
},
|
|
25
|
+
"api/auth/account": {
|
|
26
|
+
"busy": "The account is busy with another operation at the moment. Try again shortly."
|
|
27
|
+
},
|
|
28
|
+
"api/auth/accessToken": {
|
|
29
|
+
"missing": "You are not signed in.",
|
|
30
|
+
"invalid": "Your session is not valid. Sign in again.",
|
|
31
|
+
"expired": "Your session has expired. Sign in again."
|
|
32
|
+
},
|
|
33
|
+
"api/auth/refreshToken": {
|
|
34
|
+
"invalid": "Your session is not valid. Sign in again.",
|
|
35
|
+
"expired": "Your session has expired. Sign in again.",
|
|
36
|
+
"reused": "Your session was ended for security reasons. Sign in again."
|
|
37
|
+
},
|
|
38
|
+
"api/auth/emailVerification": {
|
|
39
|
+
"invalidToken": "The verification link is invalid or has expired.",
|
|
40
|
+
"required": "Confirm your e-mail address to continue."
|
|
41
|
+
},
|
|
42
|
+
"api/auth/passwordReset": {
|
|
43
|
+
"invalidToken": "The password reset link is invalid or has expired."
|
|
44
|
+
},
|
|
45
|
+
"api/auth/client": {
|
|
46
|
+
"networkError": "Cannot connect to the server. Check your connection and try again.",
|
|
47
|
+
"invalidResponse": "The server answered in an unexpected way. Try again later.",
|
|
48
|
+
"sessionChanged": "The session changed before the request was sent (someone signed in or out). Check who is signed in and try again."
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
{
|
|
2
|
+
"api/auth/config": {
|
|
3
|
+
"invalid": "Uwierzytelnianie jest błędnie skonfigurowane."
|
|
4
|
+
},
|
|
5
|
+
"api/auth/login": {
|
|
6
|
+
"invalidCredentials": "Nieprawidłowy adres e-mail lub hasło."
|
|
7
|
+
},
|
|
8
|
+
"api/auth/password": {
|
|
9
|
+
"tooLong": "Hasło jest za długie (najwyżej 72 bajty).",
|
|
10
|
+
"tooShort": "Hasło musi mieć co najmniej 10 znaków.",
|
|
11
|
+
"required": "Podaj hasło.",
|
|
12
|
+
"currentInvalid": "Obecne hasło jest nieprawidłowe.",
|
|
13
|
+
"busy": "Serwer jest chwilowo przeciążony. Spróbuj ponownie za chwilę."
|
|
14
|
+
},
|
|
15
|
+
"api/auth/validation": {
|
|
16
|
+
"emailInvalid": "Podaj poprawny adres e-mail.",
|
|
17
|
+
"tokenRequired": "Link jest niekompletny lub nieprawidłowy."
|
|
18
|
+
},
|
|
19
|
+
"api/auth/mobile": {
|
|
20
|
+
"originForbidden": "To żądanie jest niedozwolone z przeglądarki."
|
|
21
|
+
},
|
|
22
|
+
"api/auth/register": {
|
|
23
|
+
"emailTaken": "Konto z tym adresem e-mail już istnieje."
|
|
24
|
+
},
|
|
25
|
+
"api/auth/account": {
|
|
26
|
+
"busy": "Konto jest chwilowo zajęte inną operacją. Spróbuj ponownie za chwilę."
|
|
27
|
+
},
|
|
28
|
+
"api/auth/accessToken": {
|
|
29
|
+
"missing": "Nie jesteś zalogowany.",
|
|
30
|
+
"invalid": "Sesja jest nieprawidłowa. Zaloguj się ponownie.",
|
|
31
|
+
"expired": "Sesja wygasła. Zaloguj się ponownie."
|
|
32
|
+
},
|
|
33
|
+
"api/auth/refreshToken": {
|
|
34
|
+
"invalid": "Sesja jest nieprawidłowa. Zaloguj się ponownie.",
|
|
35
|
+
"expired": "Sesja wygasła. Zaloguj się ponownie.",
|
|
36
|
+
"reused": "Sesja została zakończona ze względów bezpieczeństwa. Zaloguj się ponownie."
|
|
37
|
+
},
|
|
38
|
+
"api/auth/emailVerification": {
|
|
39
|
+
"invalidToken": "Link weryfikacyjny jest nieprawidłowy lub wygasł.",
|
|
40
|
+
"required": "Potwierdź adres e-mail, aby kontynuować."
|
|
41
|
+
},
|
|
42
|
+
"api/auth/passwordReset": {
|
|
43
|
+
"invalidToken": "Link do zmiany hasła jest nieprawidłowy lub wygasł."
|
|
44
|
+
},
|
|
45
|
+
"api/auth/client": {
|
|
46
|
+
"networkError": "Nie można połączyć się z serwerem. Sprawdź połączenie i spróbuj ponownie.",
|
|
47
|
+
"invalidResponse": "Serwer odpowiedział w nieoczekiwany sposób. Spróbuj ponownie później.",
|
|
48
|
+
"sessionChanged": "Sesja zmieniła się przed wysłaniem żądania (zalogowano lub wylogowano). Sprawdź, kto jest zalogowany, i spróbuj ponownie."
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Message keys of the library (`rest:ERR-3`): `api/auth/<area>:<name>`, where `api/auth/<area>` is the i18next
|
|
3
|
+
* namespace of the client translation file and `<name>` is the key in it. Errors of the library carry one of these keys
|
|
4
|
+
* in `messageKey`; the code uses these constants, never string literals.
|
|
5
|
+
*
|
|
6
|
+
* @since 2.0.0
|
|
7
|
+
*/
|
|
8
|
+
export declare const Msg: {
|
|
9
|
+
readonly config: {
|
|
10
|
+
readonly invalid: "api/auth/config:invalid";
|
|
11
|
+
};
|
|
12
|
+
readonly login: {
|
|
13
|
+
readonly invalidCredentials: "api/auth/login:invalidCredentials";
|
|
14
|
+
};
|
|
15
|
+
readonly password: {
|
|
16
|
+
readonly tooLong: "api/auth/password:tooLong";
|
|
17
|
+
readonly tooShort: "api/auth/password:tooShort";
|
|
18
|
+
readonly required: "api/auth/password:required";
|
|
19
|
+
readonly currentInvalid: "api/auth/password:currentInvalid";
|
|
20
|
+
readonly busy: "api/auth/password:busy";
|
|
21
|
+
};
|
|
22
|
+
readonly validation: {
|
|
23
|
+
readonly emailInvalid: "api/auth/validation:emailInvalid";
|
|
24
|
+
readonly tokenRequired: "api/auth/validation:tokenRequired";
|
|
25
|
+
};
|
|
26
|
+
readonly mobile: {
|
|
27
|
+
readonly originForbidden: "api/auth/mobile:originForbidden";
|
|
28
|
+
};
|
|
29
|
+
readonly register: {
|
|
30
|
+
readonly emailTaken: "api/auth/register:emailTaken";
|
|
31
|
+
};
|
|
32
|
+
readonly account: {
|
|
33
|
+
readonly busy: "api/auth/account:busy";
|
|
34
|
+
};
|
|
35
|
+
readonly accessToken: {
|
|
36
|
+
readonly missing: "api/auth/accessToken:missing";
|
|
37
|
+
readonly invalid: "api/auth/accessToken:invalid";
|
|
38
|
+
readonly expired: "api/auth/accessToken:expired";
|
|
39
|
+
};
|
|
40
|
+
readonly refreshToken: {
|
|
41
|
+
readonly invalid: "api/auth/refreshToken:invalid";
|
|
42
|
+
readonly expired: "api/auth/refreshToken:expired";
|
|
43
|
+
readonly reused: "api/auth/refreshToken:reused";
|
|
44
|
+
};
|
|
45
|
+
readonly emailVerification: {
|
|
46
|
+
readonly invalidToken: "api/auth/emailVerification:invalidToken";
|
|
47
|
+
readonly required: "api/auth/emailVerification:required";
|
|
48
|
+
};
|
|
49
|
+
readonly passwordReset: {
|
|
50
|
+
readonly invalidToken: "api/auth/passwordReset:invalidToken";
|
|
51
|
+
};
|
|
52
|
+
readonly client: {
|
|
53
|
+
readonly networkError: "api/auth/client:networkError";
|
|
54
|
+
readonly invalidResponse: "api/auth/client:invalidResponse";
|
|
55
|
+
readonly sessionChanged: "api/auth/client:sessionChanged";
|
|
56
|
+
};
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* Union of all message keys of the library.
|
|
60
|
+
*
|
|
61
|
+
* @since 2.0.0
|
|
62
|
+
*/
|
|
63
|
+
export type MessageKey = {
|
|
64
|
+
[Area in keyof typeof Msg]: (typeof Msg)[Area][keyof (typeof Msg)[Area]];
|
|
65
|
+
}[keyof typeof Msg];
|
package/dist/messages.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Message keys of the library (`rest:ERR-3`): `api/auth/<area>:<name>`, where `api/auth/<area>` is the i18next
|
|
3
|
+
* namespace of the client translation file and `<name>` is the key in it. Errors of the library carry one of these keys
|
|
4
|
+
* in `messageKey`; the code uses these constants, never string literals.
|
|
5
|
+
*
|
|
6
|
+
* @since 2.0.0
|
|
7
|
+
*/
|
|
8
|
+
export const Msg = {
|
|
9
|
+
config: {
|
|
10
|
+
invalid: 'api/auth/config:invalid',
|
|
11
|
+
},
|
|
12
|
+
login: {
|
|
13
|
+
invalidCredentials: 'api/auth/login:invalidCredentials',
|
|
14
|
+
},
|
|
15
|
+
password: {
|
|
16
|
+
tooLong: 'api/auth/password:tooLong',
|
|
17
|
+
tooShort: 'api/auth/password:tooShort',
|
|
18
|
+
required: 'api/auth/password:required',
|
|
19
|
+
currentInvalid: 'api/auth/password:currentInvalid',
|
|
20
|
+
busy: 'api/auth/password:busy',
|
|
21
|
+
},
|
|
22
|
+
validation: {
|
|
23
|
+
emailInvalid: 'api/auth/validation:emailInvalid',
|
|
24
|
+
tokenRequired: 'api/auth/validation:tokenRequired',
|
|
25
|
+
},
|
|
26
|
+
mobile: {
|
|
27
|
+
originForbidden: 'api/auth/mobile:originForbidden',
|
|
28
|
+
},
|
|
29
|
+
register: {
|
|
30
|
+
emailTaken: 'api/auth/register:emailTaken',
|
|
31
|
+
},
|
|
32
|
+
account: {
|
|
33
|
+
busy: 'api/auth/account:busy',
|
|
34
|
+
},
|
|
35
|
+
accessToken: {
|
|
36
|
+
missing: 'api/auth/accessToken:missing',
|
|
37
|
+
invalid: 'api/auth/accessToken:invalid',
|
|
38
|
+
expired: 'api/auth/accessToken:expired',
|
|
39
|
+
},
|
|
40
|
+
refreshToken: {
|
|
41
|
+
invalid: 'api/auth/refreshToken:invalid',
|
|
42
|
+
expired: 'api/auth/refreshToken:expired',
|
|
43
|
+
reused: 'api/auth/refreshToken:reused',
|
|
44
|
+
},
|
|
45
|
+
emailVerification: {
|
|
46
|
+
invalidToken: 'api/auth/emailVerification:invalidToken',
|
|
47
|
+
required: 'api/auth/emailVerification:required',
|
|
48
|
+
},
|
|
49
|
+
passwordReset: {
|
|
50
|
+
invalidToken: 'api/auth/passwordReset:invalidToken',
|
|
51
|
+
},
|
|
52
|
+
client: {
|
|
53
|
+
networkError: 'api/auth/client:networkError',
|
|
54
|
+
invalidResponse: 'api/auth/client:invalidResponse',
|
|
55
|
+
sessionChanged: 'api/auth/client:sessionChanged',
|
|
56
|
+
},
|
|
57
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { PgAuthRepository, createPgAuthRepository, type PgAuthRepositoryOptions } from './pg-auth-repository.js';
|
package/dist/pg/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { PgAuthRepository, createPgAuthRepository } from './pg-auth-repository.js';
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
-- 0001_mielk_auth: tables of the mielk-auth library: users, refresh tokens and one-time tokens (TASK-191.5, plan TASK-191, 2.5).
|
|
2
|
+
-- Reference migration of the library: the application copies it to its own migrations as schema/NNNN_mielk_auth.sql with
|
|
3
|
+
-- the next number of its sequence (pg:MIG-1) and runs it in one transaction as the owner role of its schema (pg:MIG-4).
|
|
4
|
+
-- Replace `app` in the next line with the schema of the application. An application that already has the table `users`
|
|
5
|
+
-- adapts the migration (it adds the missing columns and the index instead of creating the table).
|
|
6
|
+
|
|
7
|
+
SET LOCAL search_path = app, pg_catalog;
|
|
8
|
+
|
|
9
|
+
CREATE TABLE users (
|
|
10
|
+
user_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
|
11
|
+
email text NOT NULL,
|
|
12
|
+
password_hash text,
|
|
13
|
+
email_verified_at timestamptz,
|
|
14
|
+
created_at timestamptz NOT NULL DEFAULT now(),
|
|
15
|
+
updated_at timestamptz NOT NULL DEFAULT now()
|
|
16
|
+
);
|
|
17
|
+
-- The e-mail is unique regardless of the letter case; the library looks the account up with lower(email).
|
|
18
|
+
CREATE UNIQUE INDEX users_email_lower_key ON users (lower(email));
|
|
19
|
+
|
|
20
|
+
COMMENT ON TABLE users IS 'DELETE-ALLOWED: the library deletes the account on request of its owner (the right to erasure), no history is kept here. Accounts of the application; the library uses only the columns listed here, the application may add its own.';
|
|
21
|
+
COMMENT ON COLUMN users.email IS 'E-mail address, stored in lower case by the library.';
|
|
22
|
+
COMMENT ON COLUMN users.password_hash IS 'bcrypt hash; NULL for an account without a password (external login, later versions).';
|
|
23
|
+
|
|
24
|
+
CREATE TABLE refresh_tokens (
|
|
25
|
+
refresh_token_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
|
26
|
+
user_id bigint NOT NULL REFERENCES users ON DELETE CASCADE,
|
|
27
|
+
token_hash text NOT NULL,
|
|
28
|
+
family_id uuid NOT NULL,
|
|
29
|
+
client_kind text NOT NULL,
|
|
30
|
+
expires_at timestamptz NOT NULL,
|
|
31
|
+
revoked_at timestamptz,
|
|
32
|
+
revoked_reason text,
|
|
33
|
+
last_used_at timestamptz,
|
|
34
|
+
created_at timestamptz NOT NULL DEFAULT now(),
|
|
35
|
+
CONSTRAINT refresh_tokens_token_hash_key UNIQUE (token_hash),
|
|
36
|
+
CONSTRAINT refresh_tokens_client_kind_check CHECK (client_kind IN ('web', 'mobile')),
|
|
37
|
+
CONSTRAINT refresh_tokens_revoked_reason_check CHECK (revoked_reason IN ('rotated', 'revoked')),
|
|
38
|
+
CONSTRAINT refresh_tokens_revoked_check CHECK ((revoked_at IS NULL) = (revoked_reason IS NULL))
|
|
39
|
+
);
|
|
40
|
+
CREATE INDEX refresh_tokens_user_id_idx ON refresh_tokens (user_id);
|
|
41
|
+
CREATE INDEX refresh_tokens_family_id_idx ON refresh_tokens (family_id);
|
|
42
|
+
|
|
43
|
+
COMMENT ON TABLE refresh_tokens IS 'DELETE-ALLOWED: session tokens without value after expiry or after the account is deleted (ON DELETE CASCADE). Refresh tokens of the sessions.';
|
|
44
|
+
COMMENT ON COLUMN refresh_tokens.token_hash IS 'SHA-256 of the token; the token itself is never stored.';
|
|
45
|
+
COMMENT ON COLUMN refresh_tokens.client_kind IS 'Kind of client the token was issued to: web or mobile; a token works only on the endpoints of its kind.';
|
|
46
|
+
COMMENT ON COLUMN refresh_tokens.family_id IS 'Session (token family): a login starts a new one, a rotation keeps it; a detected reuse ends only this session.';
|
|
47
|
+
COMMENT ON COLUMN refresh_tokens.revoked_at IS 'When the token was revoked (rotation, logout, reuse detection); NULL while it is valid.';
|
|
48
|
+
COMMENT ON COLUMN refresh_tokens.revoked_reason IS 'rotated: replaced by a newer token of a live session (a repeated use after the grace window is a reuse); revoked: the session ended. NULL while the token is valid.';
|
|
49
|
+
|
|
50
|
+
CREATE TABLE auth_tokens (
|
|
51
|
+
auth_token_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
|
52
|
+
user_id bigint NOT NULL REFERENCES users ON DELETE CASCADE,
|
|
53
|
+
purpose text NOT NULL,
|
|
54
|
+
token_hash text NOT NULL,
|
|
55
|
+
expires_at timestamptz NOT NULL,
|
|
56
|
+
used_at timestamptz,
|
|
57
|
+
created_at timestamptz NOT NULL DEFAULT now(),
|
|
58
|
+
CONSTRAINT auth_tokens_token_hash_key UNIQUE (token_hash),
|
|
59
|
+
CONSTRAINT auth_tokens_purpose_check CHECK (purpose IN ('email_verification', 'password_reset'))
|
|
60
|
+
);
|
|
61
|
+
CREATE INDEX auth_tokens_user_id_idx ON auth_tokens (user_id);
|
|
62
|
+
|
|
63
|
+
COMMENT ON TABLE auth_tokens IS 'DELETE-ALLOWED: one-time tokens without value after use or after the account is deleted (ON DELETE CASCADE). Sent by e-mail (e-mail verification, password reset); only the hash is stored.';
|
|
64
|
+
COMMENT ON COLUMN auth_tokens.token_hash IS 'SHA-256 of the token; the token itself is never stored.';
|
|
65
|
+
COMMENT ON COLUMN auth_tokens.used_at IS 'When the token was used or invalidated by a newer one; NULL while it can still be used.';
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import type { AuthRepository, AuthTokenPurpose, AuthTokenRecord, AuthUser, NewAuthToken, NewRefreshToken, NewUser, RefreshTokenRecord, RefreshTokenRevocation, UserId } from '../server/ports.js';
|
|
2
|
+
/** Default of `PgAuthRepositoryOptions.lockTimeoutMs`. */
|
|
3
|
+
export declare const LOCK_TIMEOUT_DEFAULT_MS = 3000;
|
|
4
|
+
/**
|
|
5
|
+
* Options of the PostgreSQL adapter.
|
|
6
|
+
*
|
|
7
|
+
* @since 2.0.0
|
|
8
|
+
*/
|
|
9
|
+
export type PgAuthRepositoryOptions = {
|
|
10
|
+
/**
|
|
11
|
+
* How long `lockUser` waits for the lock of the user, in milliseconds (1-60000); default 3000. When it passes, the
|
|
12
|
+
* operation fails with `AccountBusyError` (503) instead of holding a connection of the pool (audit S8). The timeout
|
|
13
|
+
* applies to that lock only; the rest of the transaction keeps the `lock_timeout` it had.
|
|
14
|
+
*/
|
|
15
|
+
lockTimeoutMs?: number;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* `AuthRepository` on PostgreSQL, on the connection pool of `@mielk/db/pg` (the application calls `initDb`).
|
|
19
|
+
*
|
|
20
|
+
* Every statement runs on the executor of the current call chain (`getQueryExecutor`): the pool outside a transaction
|
|
21
|
+
* and the client of the transaction inside `withTransaction`. So the repository passed to `work` and this one see the
|
|
22
|
+
* same transaction, and a `withTransaction` of the application around it joins that transaction. The tables are the
|
|
23
|
+
* ones of the reference migration `migrations/0001_mielk_auth.sql`; the connection must find them on its `search_path`.
|
|
24
|
+
*
|
|
25
|
+
* @since 2.0.0
|
|
26
|
+
*/
|
|
27
|
+
export declare class PgAuthRepository implements AuthRepository {
|
|
28
|
+
#private;
|
|
29
|
+
/** @throws `RangeError` when `lockTimeoutMs` is not an integer from 1 to 60000. */
|
|
30
|
+
constructor(options?: PgAuthRepositoryOptions);
|
|
31
|
+
/** {@inheritDoc AuthRepository.withTransaction} */
|
|
32
|
+
withTransaction<T>(work: (repository: AuthRepository) => Promise<T>): Promise<T>;
|
|
33
|
+
/**
|
|
34
|
+
* Locks the row of the user with `FOR NO KEY UPDATE`: the lock excludes another `lockUser` of the same user and the
|
|
35
|
+
* updates of the row, but not the inserts of tokens of other transactions (their foreign keys take the weaker
|
|
36
|
+
* `FOR KEY SHARE`). The next statement of the transaction takes a new snapshot (`READ COMMITTED`), so it sees what
|
|
37
|
+
* the previous holder committed.
|
|
38
|
+
*
|
|
39
|
+
* The wait is bounded by `lockTimeoutMs` (`SET LOCAL lock_timeout` for this statement only; the previous value is
|
|
40
|
+
* restored after the lock is granted), so requests of one account cannot queue up and take the whole pool (audit S8).
|
|
41
|
+
*
|
|
42
|
+
* @returns resolves when the lock is held, or at once when the user does not exist: nothing is locked then.
|
|
43
|
+
* @throws `Error` when called outside `withTransaction`: the lock would be released at once; `AccountBusyError` when
|
|
44
|
+
* the lock is not granted within `lockTimeoutMs` (the transaction is aborted then and rolls back).
|
|
45
|
+
*/
|
|
46
|
+
lockUser(userId: UserId): Promise<void>;
|
|
47
|
+
/** {@inheritDoc AuthRepository.findUserByEmail} */
|
|
48
|
+
findUserByEmail(email: string): Promise<AuthUser | null>;
|
|
49
|
+
/** {@inheritDoc AuthRepository.findUserById} */
|
|
50
|
+
findUserById(userId: UserId): Promise<AuthUser | null>;
|
|
51
|
+
/** {@inheritDoc AuthRepository.createUser} */
|
|
52
|
+
createUser(user: NewUser): Promise<AuthUser>;
|
|
53
|
+
/** {@inheritDoc AuthRepository.updatePasswordHash} */
|
|
54
|
+
updatePasswordHash(userId: UserId, passwordHash: string, updatedAt: Date): Promise<void>;
|
|
55
|
+
/** {@inheritDoc AuthRepository.markEmailVerified} */
|
|
56
|
+
markEmailVerified(userId: UserId, verifiedAt: Date): Promise<void>;
|
|
57
|
+
/** {@inheritDoc AuthRepository.deleteUser} */
|
|
58
|
+
deleteUser(userId: UserId): Promise<void>;
|
|
59
|
+
/** {@inheritDoc AuthRepository.createRefreshToken} */
|
|
60
|
+
createRefreshToken(token: NewRefreshToken): Promise<void>;
|
|
61
|
+
/** {@inheritDoc AuthRepository.findRefreshToken} */
|
|
62
|
+
findRefreshToken(tokenHash: string): Promise<RefreshTokenRecord | null>;
|
|
63
|
+
/** {@inheritDoc AuthRepository.revokeRefreshToken} */
|
|
64
|
+
revokeRefreshToken(tokenHash: string, revokedAt: Date, reason: RefreshTokenRevocation): Promise<RefreshTokenRecord | null>;
|
|
65
|
+
/** {@inheritDoc AuthRepository.revokeRefreshTokenFamily} */
|
|
66
|
+
revokeRefreshTokenFamily(familyId: string, revokedAt: Date): Promise<number>;
|
|
67
|
+
/** {@inheritDoc AuthRepository.revokeAllRefreshTokens} */
|
|
68
|
+
revokeAllRefreshTokens(userId: UserId, revokedAt: Date): Promise<number>;
|
|
69
|
+
/** {@inheritDoc AuthRepository.createAuthToken} */
|
|
70
|
+
createAuthToken(token: NewAuthToken): Promise<void>;
|
|
71
|
+
/** {@inheritDoc AuthRepository.invalidateAuthTokens} */
|
|
72
|
+
invalidateAuthTokens(userId: UserId, purpose: AuthTokenPurpose, usedAt: Date): Promise<void>;
|
|
73
|
+
/** {@inheritDoc AuthRepository.findAuthToken} */
|
|
74
|
+
findAuthToken(tokenHash: string): Promise<AuthTokenRecord | null>;
|
|
75
|
+
/** {@inheritDoc AuthRepository.consumeAuthToken} */
|
|
76
|
+
consumeAuthToken(tokenHash: string, purpose: AuthTokenPurpose, usedAt: Date): Promise<AuthTokenRecord | null>;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Creates the PostgreSQL adapter of `AuthRepository` for `AuthConfig.repository`.
|
|
80
|
+
*
|
|
81
|
+
* @param options - `lockTimeoutMs`, how long `lockUser` waits for the lock of a user (default 3000).
|
|
82
|
+
* @returns A repository on the pool of `@mielk/db/pg`; the application calls `initDb` before the first request.
|
|
83
|
+
* @throws `RangeError` when `lockTimeoutMs` is not an integer from 1 to 60000.
|
|
84
|
+
* @example
|
|
85
|
+
* ```ts
|
|
86
|
+
* await initDb(dbConfig);
|
|
87
|
+
* const auth = createAuth({ ...config, repository: createPgAuthRepository() });
|
|
88
|
+
* ```
|
|
89
|
+
* @since 2.0.0
|
|
90
|
+
*/
|
|
91
|
+
export declare const createPgAuthRepository: (options?: PgAuthRepositoryOptions) => AuthRepository;
|