@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.
Files changed (67) hide show
  1. package/CHANGELOG.md +84 -0
  2. package/LICENSE +21 -0
  3. package/README.md +673 -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 +45 -0
  54. package/dist/server/password.js +72 -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 +17 -0
  58. package/dist/server/proxy-check.js +80 -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 +329 -0
  63. package/dist/server/safe-log.d.ts +9 -0
  64. package/dist/server/safe-log.js +24 -0
  65. package/dist/server/service.d.ts +153 -0
  66. package/dist/server/service.js +244 -0
  67. package/package.json +136 -5
@@ -0,0 +1,226 @@
1
+ /**
2
+ * Session manager of the authentication API for web and mobile clients (plan TASK-191, 2.6). No `window`, `localStorage`
3
+ * or Expo modules (`rn:DAN-2`): the platform parts (`fetch`, the secure store of the refresh token) are parameters.
4
+ */
5
+ import type { AuthUserResponse, ChangePasswordBody, ConfirmEmailBody, ConfirmPasswordResetBody, DeleteAccountBody, LoginBody, RegisterBody, RequestPasswordResetBody, ResendVerificationBody } from '../schemas/index.js';
6
+ /**
7
+ * Store of the refresh token of a mobile client, implemented by the application (e.g. on `expo-secure-store`, `rn:SES-2`).
8
+ * The client calls it only from its queue of session operations, one call at a time (see `AuthClient`). The calls have
9
+ * no time limit, so a call that never settles holds up the session operations, and a call must not wait for an
10
+ * operation of the client. A rejection with a value that is not an `Error` reaches the caller as an `Error` with that
11
+ * value as its `cause`.
12
+ *
13
+ * @since 2.0.0
14
+ */
15
+ export type RefreshTokenStore = {
16
+ read(): Promise<string | null>;
17
+ save(token: string): Promise<void>;
18
+ remove(): Promise<void>;
19
+ };
20
+ /**
21
+ * Options of `createAuthClient`.
22
+ *
23
+ * @since 2.0.0
24
+ */
25
+ export type AuthClientOptions = {
26
+ /**
27
+ * Address of the API without `/v1/auth`: an absolute http(s) address, e.g. `https://api.example.com` or
28
+ * `https://api.example.com/gateway`, or for the origin of the page (`location.href`) an empty string or a path from
29
+ * the root (`/gateway`); the origin of the page exists in a browser only, so `mobile` mode (React Native, no
30
+ * `location`) needs an absolute address, otherwise a call rejects with a `TypeError` before sending (`restoreSession()` ends
31
+ * `anonymous`, `logout()` still ends the local session, in `web` too, without sending the request (the cookie stays), the revoking of a dropped token sends no request). A trailing slash is ignored; a query, a fragment or a dot segment makes `authorizedFetch` reject.
32
+ */
33
+ baseUrl: string;
34
+ /** `web`: the refresh token lives in the `httpOnly` cookie; `mobile`: it is in `tokenStore`, the `/mobile/*` endpoints are used (`rest:AUT-5`, `AUT-6`). */
35
+ mode: 'web' | 'mobile';
36
+ /** Required in the `mobile` mode, ignored in the `web` mode. */
37
+ tokenStore?: RefreshTokenStore;
38
+ /**
39
+ * The `fetch` to use; default the global one. `authorizedFetch` checks only the first address, so a redirect is
40
+ * followed by this `fetch`: it must, like the `fetch` of the Fetch Standard, drop the `Authorization` header when a
41
+ * redirect leads to another origin (browsers and Node.js do; the redirect handling of React Native is not verified,
42
+ * so the API behind `baseUrl` should not redirect to another origin). Only `authorizedFetch` follows a redirect:
43
+ * every call the library builds itself sends `redirect: 'error'` (DEC-314), so a `fetch` passed here must honour it.
44
+ */
45
+ fetch?: typeof fetch;
46
+ /**
47
+ * Language of the user, sent as `Accept-Language`: the server picks the language of the e-mails with a link by it.
48
+ * An `Accept-Language` the caller put in `init` is sent unchanged. When it throws, the client adds no header and the
49
+ * exception is reported as an uncaught error of the platform, in a microtask (see `AuthClient.subscribe`).
50
+ */
51
+ getLocale?: () => string | undefined;
52
+ };
53
+ /**
54
+ * State of the session as the interface sees it. `loading` lasts until the first `restoreSession` ends.
55
+ *
56
+ * @since 2.0.0
57
+ */
58
+ export type AuthState = {
59
+ status: 'loading';
60
+ } | {
61
+ status: 'anonymous';
62
+ } | {
63
+ status: 'authenticated';
64
+ user: AuthUserResponse;
65
+ };
66
+ /**
67
+ * The client of the authentication API; see `createAuthClient`.
68
+ *
69
+ * The operations that change the session run in one queue of session operations: `login`, `logout`,
70
+ * `refreshAccessToken` and the refresh after a 401, `restoreSession`, `changePassword`, `revokeAllSessions`,
71
+ * `deleteAccount`, `confirmPasswordReset`, and every call of the token store. Each runs whole (its store calls, its
72
+ * requests, the change of the memory and the publication of the state) before the next one starts, in the order they
73
+ * were called; nothing about the session changes at the call. One asked for meanwhile, also by a subscriber or by the
74
+ * token store, waits for its turn, so it acts on the result of the operations asked for before it. Each network request
75
+ * of a session operation has a time limit of 30 seconds, from the call of `fetch` to the end of reading the answer:
76
+ * then the request (with the reading of its body) is aborted through the `signal` of its `RequestInit`, the operation
77
+ * fails as if the network had failed (an `AuthClientError` of the kind `network`), and the queue goes on. An answer
78
+ * that still comes after the limit is ignored (a refresh token in it is neither stored nor revoked). The other
79
+ * requests (`authorizedFetch`, `getMe`, `resendEmailVerification`) are not queued: see `authorizedFetch`.
80
+ *
81
+ * @since 2.0.0
82
+ */
83
+ export type AuthClient = {
84
+ /** The current state. A new object on every change, so it can be a snapshot of an external store. */
85
+ getState: () => AuthState;
86
+ /**
87
+ * Calls `listener` after every change of the state; returns the function that stops it. A listener that throws
88
+ * changes nothing in the client and does not keep the other listeners from being called: its exception is reported
89
+ * as an uncaught error of the platform, in a microtask (as an exception of a DOM event listener is); a value that is
90
+ * not an `Error` is reported as an `Error` with that value as its `cause`. The report goes to the host: in Node.js an
91
+ * uncaught exception ends the process unless the application handles `uncaughtException`.
92
+ */
93
+ subscribe: (listener: () => void) => () => void;
94
+ /** The access token from memory, `null` without a session. For the header `Authorization: Bearer` of the application's API client. */
95
+ getAccessToken: () => string | null;
96
+ /**
97
+ * Restores the session of the previous run with one refresh and `GET /me`, in one session operation. Runs once:
98
+ * later calls return the first result. A refresh that fails for a transient reason (no network, no answer in time,
99
+ * 5xx, 429) leaves the state `anonymous` and keeps
100
+ * the refresh token (the stored one in `mobile`, the cookie in `web`), so the next start can restore the session
101
+ * (decision DEC-271, an exception to `rn:SES-6`); only a refresh answered 401 or 403 ends the session and removes it.
102
+ */
103
+ restoreSession: () => Promise<AuthState>;
104
+ /**
105
+ * Gets a new access token for the session in place at the call, in a session operation. Parallel calls of one
106
+ * session share one request (`rn:SES-5`); so does a refresh after a 401 of that session, which uses the access token
107
+ * an operation queued before it has already renewed instead of asking the server again. Resolves to `null` when the
108
+ * session ended (no refresh token, or the server answered 401 or 403, which also removes the stored token) or was
109
+ * replaced (a logout, or a login that succeeded, queued before it) before its turn; a login that fails does not
110
+ * replace the session in place. A transient failure (no network, no
111
+ * answer in time, 5xx, 429) rejects with `AuthClientError` and changes nothing: the state, the access token and the
112
+ * refresh token stay, so a later call can try again (decision DEC-271, an exception to `rn:SES-6`).
113
+ */
114
+ refreshAccessToken: () => Promise<string | null>;
115
+ /**
116
+ * `fetch` with the access token of the session in place at the call. It is not queued: requests run in parallel.
117
+ * While no session operation is queued it is sent at once; otherwise (the restore while the state is `loading`, a
118
+ * refresh, a login or a logout asked for before it, ...) it waits for the session operations asked for before it.
119
+ * When the session of the call is no longer in place right before the request is handed to `fetch` (a logout, or a
120
+ * login that succeeded, asked for before it), it sends nothing and rejects with an `AuthClientError` of the kind
121
+ * `session-changed`; a login that fails does not end it. A logout or a login asked for after it, also by
122
+ * `getLocale` while the request is prepared, comes after it. On 401 it asks for a refresh in the queue, shared by the parallel 401
123
+ * answers of the session (`rn:SES-5`), and repeats the request once (`react:DAN-6`), only while the session of the
124
+ * call is in place: otherwise it resolves to the first 401 answer, so a request is never repeated with the token of
125
+ * another session. When the refresh fails for a transient reason it rejects with that `AuthClientError`, and the
126
+ * session stays. The body in `init` is sent twice on a repeat, so it must be a string, `FormData` or another
127
+ * reusable body, not a stream. `init.credentials` is passed on unchanged, so without it the default of `fetch`
128
+ * applies (in a browser `same-origin`: cookies of the same origin are sent). It has no time limit of the client:
129
+ * pass a `signal` in `init` for one. The client sends the token to the origin of `baseUrl` only, as far as the
130
+ * `fetch` used keeps it off a redirect to another origin (see `AuthClientOptions.fetch`; not verified in React
131
+ * Native). It hands `fetch` an absolute address it built itself: a relative address (`accounts` or `/accounts`) is
132
+ * appended to the path of `baseUrl` and stays under it; an absolute address must have the origin of `baseUrl` (in
133
+ * its canonical form: the default port left out, IPv6 and IPv4 in their standard notation) and may have any path on
134
+ * it. With an empty or a path-only `baseUrl` the origin is the one of `location.href`, never the base URL of the
135
+ * document; without `location` (Node.js, React Native) such a `baseUrl` makes it reject. A dot segment (`.`, `..`,
136
+ * also `%2e`) is refused, empty segments are kept as given. An address of another origin, one the client does not
137
+ * read the same way as the URL Standard (user information, a backslash, whitespace, a non-ASCII host), and an input
138
+ * that is neither a string nor an object with a string `href` (a `URL`; a `Request` is refused) reject with a
139
+ * `TypeError` without sending anything. The address is read by the client, not by the global `URL`, so it is the
140
+ * same in a browser, Node.js and React Native.
141
+ */
142
+ authorizedFetch: (input: string | URL, init?: RequestInit) => Promise<Response>;
143
+ /**
144
+ * Asks for an account; the user is not signed in. The server answers the same for a new and for a registered
145
+ * e-mail (audit S3): a new one gets the verification link, a registered one a message with a password reset link.
146
+ * The links lead to the mode of the client unless `client` says otherwise.
147
+ */
148
+ register: (body: RegisterBody) => Promise<void>;
149
+ /**
150
+ * Signs the user in with the e-mail and the password, in a session operation: the request is sent after the session
151
+ * operations asked for before it (refresh, logout, password change, account deletion, ...) have ended, so their late
152
+ * answers cannot clear or replace its refresh token or cookie. When it succeeds, its session is put in place in the
153
+ * same operation (in `mobile` after its refresh token is stored), also when a later login or logout was asked for
154
+ * meanwhile: that one then replaces or ends it in its own turn.
155
+ */
156
+ login: (body: LoginBody) => Promise<AuthUserResponse>;
157
+ /**
158
+ * Ends the session, whatever the answer of the server is (`rn:SES-6`), in a session operation: nothing changes at
159
+ * the call. In its turn, after the session operations asked for before it (a login under way is put in place first
160
+ * when it succeeds, and this logout then ends it):
161
+ * 1. The state becomes `anonymous` and the access token is cleared; subscribers hear it, and whatever they ask for
162
+ * then comes after the logout.
163
+ * 2. In `mobile` it reads the stored token, removes it and sends it to the server to be revoked
164
+ * (`/mobile/logout`, ignoring the answer); in `web` it sends the logout request with the cookie (with an empty or path-only `baseUrl` and no `location`
165
+ * the address cannot be built, so the session ends locally without a request and the cookie stays).
166
+ * 3. The promise resolves when that request has been answered, has failed or has run out of time.
167
+ * The `web` mode cannot remove
168
+ * the `httpOnly` cookie itself: the cookie is removed only when an answer that clears it reaches the browser and the
169
+ * browser accepts it. When the request does not reach the server, or the server answers with an error without
170
+ * clearing the cookie, the cookie stays, and a new client (for example after the application restarts) can restore the session with
171
+ * its `restoreSession`. On this client `restoreSession` runs once, so after an earlier restore (also the one of
172
+ * `AuthProvider`) it returns the first result without a new request.
173
+ */
174
+ logout: () => Promise<void>;
175
+ /**
176
+ * Reads the account of the session in place at the call and refreshes the state with it, only while that session is
177
+ * still in place: the profile of an account that was replaced meanwhile is returned, not published.
178
+ */
179
+ getMe: () => Promise<AuthUserResponse>;
180
+ /**
181
+ * Changes the password. The server ends all sessions, so the client becomes `anonymous` and the user signs in with
182
+ * the new password. Like `revokeAllSessions` and `deleteAccount`, it acts only on the session seen at the call: when
183
+ * that session ends or another one starts (a logout, or a login that succeeded) before the request is sent, nothing
184
+ * is sent and the promise rejects with an `AuthClientError` of the kind `session-changed`; a login only asked for
185
+ * does not end it. It runs as a session operation; called while the state is `loading`, it runs after the restore
186
+ * and acts on its result: when the restore found no session, the request is sent without the client's token and
187
+ * the promise rejects with the `AuthClientError` of the API's answer. After a success the session ends on this
188
+ * client in the same operation; a login asked for meanwhile then replaces it if it works.
189
+ */
190
+ changePassword: (body: ChangePasswordBody) => Promise<void>;
191
+ /** Ends all sessions of the user, the current one included; bound to the session of the call (see `changePassword`). */
192
+ revokeAllSessions: () => Promise<void>;
193
+ /** Deletes the account (the password confirms it) and ends the session; bound to the session of the call (see `changePassword`). */
194
+ deleteAccount: (body: DeleteAccountBody) => Promise<void>;
195
+ /** Sends the verification link again. */
196
+ resendEmailVerification: (body?: ResendVerificationBody) => Promise<void>;
197
+ /**
198
+ * Confirms the e-mail with the token from the link and the password of the account (audit S4); a wrong password
199
+ * rejects with `api/auth/password:currentInvalid` and the link stays usable. Both go only to the origin of
200
+ * `baseUrl`, by the address rules of `authorizedFetch` (r1:U4): with an empty or a path-only `baseUrl` to the origin
201
+ * of `location.href`, never to the base URL of the document; without `location` such a `baseUrl` makes it reject
202
+ * with a `TypeError` before anything is sent. A redirect is not followed (`redirect: 'error'`, r2:U2): the answer of
203
+ * a redirect rejects with an `AuthClientError` of the kind `network`, and the body is not sent to its address.
204
+ */
205
+ confirmEmail: (body: ConfirmEmailBody) => Promise<void>;
206
+ /** Asks for the link to reset the password; the server answers the same for an unknown address. */
207
+ requestPasswordReset: (body: RequestPasswordResetBody) => Promise<void>;
208
+ /**
209
+ * Sets a new password with the token from the link, in a session operation. After a success the session of this
210
+ * client, if any, ends in the same operation, also a session the restore has put in place.
211
+ */
212
+ confirmPasswordReset: (body: ConfirmPasswordResetBody) => Promise<void>;
213
+ };
214
+ /**
215
+ * Creates the client of the authentication API.
216
+ *
217
+ * @param options - See `AuthClientOptions`.
218
+ * @returns The client.
219
+ * @throws `Error` when the `mobile` mode has no `tokenStore`.
220
+ * @example
221
+ * ```ts
222
+ * const client = createAuthClient({ baseUrl: 'https://api.example.com', mode: 'web' });
223
+ * ```
224
+ * @since 2.0.0
225
+ */
226
+ export declare const createAuthClient: (options: AuthClientOptions) => AuthClient;