@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,676 @@
|
|
|
1
|
+
import { apiAddress } from './api-address.js';
|
|
2
|
+
import { AuthClientError, invalidResponseError, networkError, sessionChangedError } from './errors.js';
|
|
3
|
+
import { isApiSuccess, isLoginResponse, isMobileLoginResponse, isMobileRefreshResponse, isRefreshResponse, isUserResponse, readApiFailure, } from './guards.js';
|
|
4
|
+
const API_PREFIX = '/v1/auth';
|
|
5
|
+
const JSON_HEADERS = { 'Content-Type': 'application/json' };
|
|
6
|
+
/**
|
|
7
|
+
* Statuses of a refresh answer that mean the refresh token is no good. Any other failure (no network, 5xx, 429, no answer
|
|
8
|
+
* in time) may pass by itself, so the token is kept (decision DEC-271, an exception to the letter of `rn:SES-6`).
|
|
9
|
+
*/
|
|
10
|
+
const REFRESH_REJECTED = new Set([401, 403]);
|
|
11
|
+
/**
|
|
12
|
+
* Time limit of one network request of a session operation, from the call of `fetch` to the end of reading the answer.
|
|
13
|
+
* It keeps a request that hangs from holding up the session operations queued after it (see `AuthClient`).
|
|
14
|
+
*/
|
|
15
|
+
const SESSION_REQUEST_TIMEOUT_MS = 30_000;
|
|
16
|
+
/** Statuses whose `Response` cannot have a body. */
|
|
17
|
+
const NULL_BODY_STATUSES = new Set([101, 103, 204, 205, 304]);
|
|
18
|
+
/** The value thrown by application code, or rejected by the token store, as an `Error` (`ts:ERR-1`, `ts:ERR-4`). */
|
|
19
|
+
const asError = (value, message) => value instanceof Error ? value : new Error(message, { cause: value });
|
|
20
|
+
/**
|
|
21
|
+
* A queue that runs operations one after another, in the order they were queued; a failed operation does not stop the
|
|
22
|
+
* next one. `busy()` tells whether an operation is queued or running; `idle()` resolves when every operation queued so
|
|
23
|
+
* far has ended.
|
|
24
|
+
*/
|
|
25
|
+
const createSerialQueue = () => {
|
|
26
|
+
let tail = Promise.resolve();
|
|
27
|
+
let pending = 0;
|
|
28
|
+
const ended = () => {
|
|
29
|
+
pending -= 1;
|
|
30
|
+
};
|
|
31
|
+
return {
|
|
32
|
+
run: (op) => {
|
|
33
|
+
pending += 1;
|
|
34
|
+
const run = tail.then(op);
|
|
35
|
+
tail = run.then(ended, ended);
|
|
36
|
+
return run;
|
|
37
|
+
},
|
|
38
|
+
busy: () => pending > 0,
|
|
39
|
+
idle: () => tail,
|
|
40
|
+
};
|
|
41
|
+
};
|
|
42
|
+
const retryAfterOf = (res) => {
|
|
43
|
+
const header = res.headers.get('Retry-After');
|
|
44
|
+
if (header === null)
|
|
45
|
+
return undefined;
|
|
46
|
+
const value = Number(header);
|
|
47
|
+
return Number.isFinite(value) && value >= 0 ? value : undefined;
|
|
48
|
+
};
|
|
49
|
+
/**
|
|
50
|
+
* Creates the client of the authentication API.
|
|
51
|
+
*
|
|
52
|
+
* @param options - See `AuthClientOptions`.
|
|
53
|
+
* @returns The client.
|
|
54
|
+
* @throws `Error` when the `mobile` mode has no `tokenStore`.
|
|
55
|
+
* @example
|
|
56
|
+
* ```ts
|
|
57
|
+
* const client = createAuthClient({ baseUrl: 'https://api.example.com', mode: 'web' });
|
|
58
|
+
* ```
|
|
59
|
+
* @since 2.0.0
|
|
60
|
+
*/
|
|
61
|
+
export const createAuthClient = (options) => {
|
|
62
|
+
const { mode, tokenStore } = options;
|
|
63
|
+
if (mode === 'mobile' && tokenStore === undefined) {
|
|
64
|
+
throw new Error('createAuthClient: the mobile mode needs tokenStore.');
|
|
65
|
+
}
|
|
66
|
+
const base = options.baseUrl.replace(/\/+$/, '');
|
|
67
|
+
const doFetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
|
|
68
|
+
const mobile = mode === 'mobile';
|
|
69
|
+
/*
|
|
70
|
+
* One queue of session operations keeps one session from touching another (cr:SEC-2, rn:SES-6), by construction:
|
|
71
|
+
*
|
|
72
|
+
* - Every operation that changes the session or the token store runs in `session`, the queue of session operations:
|
|
73
|
+
* login, logout (its server and store part), refresh, restore, the privileged operations and the password reset.
|
|
74
|
+
* Each runs whole, from its first store read to its last store write, its requests, the change of the memory and
|
|
75
|
+
* the publication of the state, before the next one starts. No other code touches the token store, so at the
|
|
76
|
+
* start of each operation the store holds the token of the session in memory, or of no session (a stored token
|
|
77
|
+
* the restore kept after a transient failure). A login that puts its session in place overwrites it and
|
|
78
|
+
* revokes the token it overwrote (TASK-191.10); an operation that does not put its session in place leaves the store as it found it.
|
|
79
|
+
* - Nothing about the session changes at the call of an operation: `login` and `logout` change it only in their
|
|
80
|
+
* turn (r9:U1), so a login is put in place when it succeeds and a later login or logout, also one asked for by a
|
|
81
|
+
* subscriber or by the token store during the login, replaces or ends it in its own turn.
|
|
82
|
+
* - `sid` is the identity of the session in memory; only an operation in its turn changes it (a login put in place,
|
|
83
|
+
* a session ended). While an operation runs, nothing else changes it: what application code asks for meanwhile
|
|
84
|
+
* is queued after it. An operation or a request of a session notes `sid` when it is called and checks it with
|
|
85
|
+
* `current(seen)`: an operation when its turn starts (later in its turn only it changes the session), a request
|
|
86
|
+
* outside the queue right before each effect (a request sent or repeated, a token used, a profile published).
|
|
87
|
+
* One whose session was ended or replaced by an operation queued before it changes nothing.
|
|
88
|
+
* - "Right before" means in the same synchronous step as the effect: a request of a session goes only through
|
|
89
|
+
* `sendFor`, which checks the session after the request is prepared and right before `fetch`; a change of the
|
|
90
|
+
* session (`sid`, `accessToken`, the state) is one synchronous step after its last check.
|
|
91
|
+
* - Code of the application never runs inside a `try` whose `catch` changes the session, and what it throws never
|
|
92
|
+
* reaches the client: `notify` calls each subscriber on its own and reports what it throws (`report`, an uncaught
|
|
93
|
+
* error in a microtask, always an `Error`); an exception of `getLocale`, or a value of it the headers refuse, is
|
|
94
|
+
* reported the same way and the request goes without the client's `Accept-Language`. The token store is the one exception: what it throws is the failure
|
|
95
|
+
* of the store operation and is handled as such.
|
|
96
|
+
* - Requests outside the queue (`authorizedFetch`, `getMe`, `resendEmailVerification`) run in parallel. Each waits
|
|
97
|
+
* only for the session operations queued before its call, then goes with the access token of the session of its
|
|
98
|
+
* call; a 401 asks for the shared refresh of that session through the queue (`refreshFor`: one refresh for all the
|
|
99
|
+
* requests of a session, `rn:SES-5`), and the request is repeated once, only while that session is in place. A
|
|
100
|
+
* refresh after a 401 checks in its turn whether an operation queued before it has already refreshed that
|
|
101
|
+
* session, and then uses its token (`refreshAfter401`, r9:U3).
|
|
102
|
+
* - Every network request of a session operation, with the reading of its answer, has one time limit and one abort
|
|
103
|
+
* signal (`limited`), so a request that hangs cannot stop the queue; the token store has none.
|
|
104
|
+
*/
|
|
105
|
+
let state = { status: 'loading' };
|
|
106
|
+
let accessToken = null;
|
|
107
|
+
let sid = 0;
|
|
108
|
+
/** The refresh asked for and not yet ended, and the session it is for; a caller of another session queues its own. */
|
|
109
|
+
/** Counts the refreshes that have put a new access token in place; unlike the token's text it never repeats (r9:U3). */
|
|
110
|
+
let refreshes = 0;
|
|
111
|
+
let refreshing;
|
|
112
|
+
let restoring;
|
|
113
|
+
const listeners = new Set();
|
|
114
|
+
const session = createSerialQueue();
|
|
115
|
+
/** True while the session noted as `seen` is still the one in place. */
|
|
116
|
+
const current = (seen) => sid === seen;
|
|
117
|
+
/** Reports an exception of application code as an uncaught error of the platform, without letting it change the client. */
|
|
118
|
+
const report = (error) => {
|
|
119
|
+
const reported = asError(error, 'Application code called by the auth client threw a value that is not an Error.');
|
|
120
|
+
queueMicrotask(() => {
|
|
121
|
+
throw reported;
|
|
122
|
+
});
|
|
123
|
+
};
|
|
124
|
+
/** Calls every subscriber; one that throws does not stop the others (its exception is reported). */
|
|
125
|
+
const notify = () => {
|
|
126
|
+
for (const listener of [...listeners]) {
|
|
127
|
+
try {
|
|
128
|
+
listener();
|
|
129
|
+
}
|
|
130
|
+
catch (error) {
|
|
131
|
+
report(error);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
const setState = (next) => {
|
|
136
|
+
state = next;
|
|
137
|
+
notify();
|
|
138
|
+
};
|
|
139
|
+
/**
|
|
140
|
+
* The address of an endpoint for the calls that send no `authorizedFetch` input: absolute like in `authorizedFetch`
|
|
141
|
+
* (`apiTarget`), so an empty or path-only base URL never gives a relative address, which a browser would resolve
|
|
142
|
+
* against the `<base>` of the document (TASK-191.14, DEC-293). Without `location` it throws a `TypeError`.
|
|
143
|
+
*/
|
|
144
|
+
const url = (path) => apiTarget(apiPath(path));
|
|
145
|
+
/**
|
|
146
|
+
* The address of an endpoint of the library for `authorizedFor`, relative to the base URL: `apiAddress` puts it under
|
|
147
|
+
* the path of the base URL itself, so the prefix of a path-only base URL is not added twice (audit S9).
|
|
148
|
+
*/
|
|
149
|
+
const apiPath = (path) => `${API_PREFIX}${path}`;
|
|
150
|
+
/**
|
|
151
|
+
* The request with `Accept-Language`; calls application code (`getLocale`, the headers of `init`). An
|
|
152
|
+
* `Accept-Language` given in `init` stays; when `getLocale` throws or gives a value the headers refuse, the client
|
|
153
|
+
* adds none and reports the exception.
|
|
154
|
+
*/
|
|
155
|
+
const prepare = (init) => {
|
|
156
|
+
const headers = new Headers(init.headers);
|
|
157
|
+
let locale;
|
|
158
|
+
try {
|
|
159
|
+
locale = options.getLocale?.();
|
|
160
|
+
}
|
|
161
|
+
catch (error) {
|
|
162
|
+
report(error);
|
|
163
|
+
}
|
|
164
|
+
if (locale !== undefined && !headers.has('Accept-Language')) {
|
|
165
|
+
try {
|
|
166
|
+
headers.set('Accept-Language', locale);
|
|
167
|
+
}
|
|
168
|
+
catch (error) {
|
|
169
|
+
// A value the headers refuse (e.g. with a line break) is a fault of getLocale too (r9:U2).
|
|
170
|
+
report(error);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
return { ...init, headers };
|
|
174
|
+
};
|
|
175
|
+
/** Hands a prepared request to `fetch`, which is called in the same synchronous step. */
|
|
176
|
+
const dispatch = async (target, init) => {
|
|
177
|
+
try {
|
|
178
|
+
return await doFetch(target, init);
|
|
179
|
+
}
|
|
180
|
+
catch (err) {
|
|
181
|
+
throw networkError(err);
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
/** Sends a request that belongs to no session. */
|
|
185
|
+
const send = (target, init) => dispatch(target, prepare(init));
|
|
186
|
+
/**
|
|
187
|
+
* Sends a request of the session `seen`, or returns null and sends nothing when that session is no longer current.
|
|
188
|
+
* The check comes after the request is prepared, in the same synchronous step as `fetch`, so an application callback
|
|
189
|
+
* that ends or replaces the session while the request is prepared stops it.
|
|
190
|
+
*/
|
|
191
|
+
const sendFor = (seen, target, init) => {
|
|
192
|
+
const prepared = prepare(init);
|
|
193
|
+
return current(seen) ? dispatch(target, prepared) : null;
|
|
194
|
+
};
|
|
195
|
+
/**
|
|
196
|
+
* Runs one network step of a session operation (one request and the whole reading of its answer) with the time
|
|
197
|
+
* limit `SESSION_REQUEST_TIMEOUT_MS`, one limit and one `signal` for the whole step. When the limit passes first,
|
|
198
|
+
* the request is aborted through `signal` (so is the reading of its body) and the step rejects with an
|
|
199
|
+
* `AuthClientError` of the kind `network`; an answer that still comes is ignored. The timer is cleared however the
|
|
200
|
+
* step ends, also when it throws before it returns its promise.
|
|
201
|
+
*/
|
|
202
|
+
const limited = async (step) => {
|
|
203
|
+
const controller = new AbortController();
|
|
204
|
+
let timer;
|
|
205
|
+
try {
|
|
206
|
+
const expired = new Promise((_resolve, reject) => {
|
|
207
|
+
timer = setTimeout(() => {
|
|
208
|
+
controller.abort();
|
|
209
|
+
reject(networkError(new Error(`No answer in ${String(SESSION_REQUEST_TIMEOUT_MS)} ms.`)));
|
|
210
|
+
}, SESSION_REQUEST_TIMEOUT_MS);
|
|
211
|
+
});
|
|
212
|
+
const work = step(controller.signal);
|
|
213
|
+
// After the limit the step is no longer awaited: its late answer or the error of the aborted request is dropped.
|
|
214
|
+
void work.catch(() => undefined);
|
|
215
|
+
return await Promise.race([work, expired]);
|
|
216
|
+
}
|
|
217
|
+
finally {
|
|
218
|
+
clearTimeout(timer);
|
|
219
|
+
}
|
|
220
|
+
};
|
|
221
|
+
/**
|
|
222
|
+
* The answer with its body read to the end, so the caller reads it without the network. In a session operation the
|
|
223
|
+
* reading of the body belongs to the step of its request, inside one time limit (r9:U2).
|
|
224
|
+
*/
|
|
225
|
+
const readWhole = async (res) => {
|
|
226
|
+
let body;
|
|
227
|
+
try {
|
|
228
|
+
body = await res.text();
|
|
229
|
+
}
|
|
230
|
+
catch (err) {
|
|
231
|
+
// The contract of every operation is an `AuthClientError`, also when the body cannot be read.
|
|
232
|
+
throw networkError(err);
|
|
233
|
+
}
|
|
234
|
+
const init = { status: res.status, statusText: res.statusText, headers: res.headers };
|
|
235
|
+
return new Response(NULL_BODY_STATUSES.has(res.status) ? null : body, init);
|
|
236
|
+
};
|
|
237
|
+
/**
|
|
238
|
+
* `sendFor` as a promise of the response, or of null when it was not sent. In a session operation (`inQueue`) the
|
|
239
|
+
* request and the reading of its body run in one step with the time limit, and the answer comes read to the end.
|
|
240
|
+
*/
|
|
241
|
+
const sendOf = (seen, target, init, inQueue) => inQueue
|
|
242
|
+
? limited(async (signal) => {
|
|
243
|
+
const sending = sendFor(seen, target, { ...init, signal });
|
|
244
|
+
return sending === null ? null : readWhole(await sending);
|
|
245
|
+
})
|
|
246
|
+
: (sendFor(seen, target, init) ?? Promise.resolve(null));
|
|
247
|
+
/**
|
|
248
|
+
* The request of a call the library builds itself. A redirect is refused, not followed (DEC-314): a 307 or 308 keeps
|
|
249
|
+
* the method and the body, so the password or the token would go to the address of the redirect, of any origin; the
|
|
250
|
+
* API of the library never redirects. `fetch` rejects, as for a network failure, before it sends anything there.
|
|
251
|
+
* `authorizedFetch` is the one exception: its request is the application's own and keeps the default.
|
|
252
|
+
*/
|
|
253
|
+
const jsonInit = (method, body) => body === undefined
|
|
254
|
+
? { method, redirect: 'error' }
|
|
255
|
+
: { method, headers: JSON_HEADERS, body: JSON.stringify(body), redirect: 'error' };
|
|
256
|
+
const readJson = async (res) => {
|
|
257
|
+
try {
|
|
258
|
+
return await res.json();
|
|
259
|
+
}
|
|
260
|
+
catch {
|
|
261
|
+
// Not JSON (e.g. a page of a proxy): the caller reports an invalid response.
|
|
262
|
+
return undefined;
|
|
263
|
+
}
|
|
264
|
+
};
|
|
265
|
+
const apiError = async (res) => {
|
|
266
|
+
const failure = readApiFailure(await readJson(res));
|
|
267
|
+
if (failure === undefined)
|
|
268
|
+
return invalidResponseError(res.status);
|
|
269
|
+
return new AuthClientError(failure.message, {
|
|
270
|
+
kind: 'api',
|
|
271
|
+
status: res.status,
|
|
272
|
+
params: failure.params,
|
|
273
|
+
issues: failure.issues,
|
|
274
|
+
retryAfterSeconds: retryAfterOf(res),
|
|
275
|
+
});
|
|
276
|
+
};
|
|
277
|
+
/** The data of a successful answer, checked by `guard`; any other answer is an `AuthClientError`. */
|
|
278
|
+
const dataOf = async (res, guard) => {
|
|
279
|
+
if (!res.ok)
|
|
280
|
+
throw await apiError(res);
|
|
281
|
+
const body = await readJson(res);
|
|
282
|
+
if (isApiSuccess(body) && guard(body.data))
|
|
283
|
+
return body.data;
|
|
284
|
+
throw invalidResponseError(res.status);
|
|
285
|
+
};
|
|
286
|
+
/** A successful answer without a body (202, 204); any other answer is an `AuthClientError`. */
|
|
287
|
+
const expectEmpty = async (res) => {
|
|
288
|
+
if (!res.ok)
|
|
289
|
+
throw await apiError(res);
|
|
290
|
+
};
|
|
291
|
+
/*
|
|
292
|
+
* The functions below up to `refreshFor` run inside a session operation only: they use the token store, and their
|
|
293
|
+
* requests have the time limit.
|
|
294
|
+
*/
|
|
295
|
+
/** The stored refresh token; an unreadable store means no session (`rn:SES-7`), and the caller then ends it. */
|
|
296
|
+
const readStored = async () => {
|
|
297
|
+
if (tokenStore === undefined)
|
|
298
|
+
return null;
|
|
299
|
+
try {
|
|
300
|
+
// An empty string is no token: it must not be sent to the server as one.
|
|
301
|
+
return (await tokenStore.read()) || null;
|
|
302
|
+
}
|
|
303
|
+
catch {
|
|
304
|
+
// Reported as "no token": the entry is removed when the session ends.
|
|
305
|
+
return null;
|
|
306
|
+
}
|
|
307
|
+
};
|
|
308
|
+
/** Removes the stored token; a store that cannot delete leaves a token that is revoked or rejected by the server. */
|
|
309
|
+
const removeStored = async () => {
|
|
310
|
+
if (tokenStore === undefined)
|
|
311
|
+
return;
|
|
312
|
+
try {
|
|
313
|
+
await tokenStore.remove();
|
|
314
|
+
}
|
|
315
|
+
catch {
|
|
316
|
+
// The session is over for this client either way.
|
|
317
|
+
}
|
|
318
|
+
};
|
|
319
|
+
/**
|
|
320
|
+
* Ends the session in memory and publishes `anonymous`, in one synchronous step. `sid` changes when a session was in
|
|
321
|
+
* place (an access token or the state `authenticated`), and always on `logout` (`byUser`), so what was asked for
|
|
322
|
+
* before the turn of the logout for no session yet, such as a restore called after the logout, finds no session.
|
|
323
|
+
*/
|
|
324
|
+
const dropSession = (byUser) => {
|
|
325
|
+
// Ending "no session" otherwise (e.g. a restore whose token is rejected) changes no identity.
|
|
326
|
+
if (byUser || accessToken !== null || state.status === 'authenticated')
|
|
327
|
+
sid += 1;
|
|
328
|
+
accessToken = null;
|
|
329
|
+
if (state.status !== 'anonymous')
|
|
330
|
+
setState({ status: 'anonymous' });
|
|
331
|
+
};
|
|
332
|
+
/** Ends the session on this client, in a session operation: memory, the state, then the stored token (`rn:SES-6`). */
|
|
333
|
+
const endSession = async () => {
|
|
334
|
+
dropSession(false);
|
|
335
|
+
await removeStored();
|
|
336
|
+
};
|
|
337
|
+
/**
|
|
338
|
+
* Revokes on the server a refresh token that is no longer kept (of a login or a refresh that was dropped, or of a
|
|
339
|
+
* session the logout ends), so it does not stay valid until it expires; the answer is ignored.
|
|
340
|
+
*/
|
|
341
|
+
const revokeDropped = async (refreshToken) => {
|
|
342
|
+
try {
|
|
343
|
+
await limited((signal) => send(url('/mobile/logout'), { ...jsonInit('POST', { refreshToken }), signal }));
|
|
344
|
+
}
|
|
345
|
+
catch {
|
|
346
|
+
// Not reachable or no answer in time: the token expires by itself, as after a logout that does not reach the server.
|
|
347
|
+
}
|
|
348
|
+
};
|
|
349
|
+
/**
|
|
350
|
+
* Stores the refresh token of a mobile login and puts its session in place (`commit`), in the operation of the login.
|
|
351
|
+
* When the save fails, the store holds again what it held before (the token read first, or nothing) and the new
|
|
352
|
+
* token is revoked; when that put-back fails too, the session whose token it was can no longer be restored: it ends
|
|
353
|
+
* here, and its token is revoked. Rejects with the error of a failed read or save (as an `Error`). When the save
|
|
354
|
+
* succeeds, the token it overwrote (of the session in place, of another account or of the same one, or a stored
|
|
355
|
+
* token not restored yet) is kept nowhere any more: it is revoked after the new session is put in place
|
|
356
|
+
* (TASK-191.10, DEC-315).
|
|
357
|
+
*/
|
|
358
|
+
const storeLogin = async (refreshToken, commit) => {
|
|
359
|
+
if (tokenStore === undefined)
|
|
360
|
+
return;
|
|
361
|
+
const store = tokenStore;
|
|
362
|
+
let previous;
|
|
363
|
+
try {
|
|
364
|
+
previous = (await store.read()) || null;
|
|
365
|
+
}
|
|
366
|
+
catch (error) {
|
|
367
|
+
// Nothing was written: the store still holds what it held.
|
|
368
|
+
await revokeDropped(refreshToken);
|
|
369
|
+
throw asError(error, 'The token store could not read the refresh token.');
|
|
370
|
+
}
|
|
371
|
+
try {
|
|
372
|
+
await store.save(refreshToken);
|
|
373
|
+
}
|
|
374
|
+
catch (error) {
|
|
375
|
+
try {
|
|
376
|
+
await (previous === null ? store.remove() : store.save(previous));
|
|
377
|
+
}
|
|
378
|
+
catch {
|
|
379
|
+
if (previous !== null)
|
|
380
|
+
await revokeDropped(previous);
|
|
381
|
+
await endSession();
|
|
382
|
+
}
|
|
383
|
+
await revokeDropped(refreshToken);
|
|
384
|
+
throw asError(error, 'The token store could not save the refresh token.');
|
|
385
|
+
}
|
|
386
|
+
commit();
|
|
387
|
+
if (previous !== null && previous !== refreshToken)
|
|
388
|
+
await revokeDropped(previous);
|
|
389
|
+
};
|
|
390
|
+
/** The answer of a refresh request: the new tokens, `rejected` (401, 403), or null when it was not sent. */
|
|
391
|
+
const requestRefresh = (seen, stored) => limited(async (signal) => {
|
|
392
|
+
const sending = mobile
|
|
393
|
+
? sendFor(seen, url('/mobile/refresh'), { ...jsonInit('POST', { refreshToken: stored }), signal })
|
|
394
|
+
: sendFor(seen, url('/refresh'), { method: 'POST', credentials: 'include', redirect: 'error', signal });
|
|
395
|
+
if (sending === null)
|
|
396
|
+
return null;
|
|
397
|
+
const res = await sending;
|
|
398
|
+
if (REFRESH_REJECTED.has(res.status))
|
|
399
|
+
return 'rejected';
|
|
400
|
+
return mobile ? dataOf(res, isMobileRefreshResponse) : dataOf(res, isRefreshResponse);
|
|
401
|
+
});
|
|
402
|
+
/**
|
|
403
|
+
* One refresh for the session `seen`, inside a session operation. Null when that session ended (no stored token, or
|
|
404
|
+
* the server rejected it, which also ends it here) or was ended or replaced by an operation queued before it;
|
|
405
|
+
* rejects on a transient failure, which changes nothing (DEC-271), and with the error of a failed save of the new
|
|
406
|
+
* token, which ends the session. The session is checked once, at the start (and by `sendFor` before the request):
|
|
407
|
+
* while the operation runs, only the operation itself changes the session (r9:U1).
|
|
408
|
+
*/
|
|
409
|
+
const doRefresh = async (seen) => {
|
|
410
|
+
if (!current(seen))
|
|
411
|
+
return null;
|
|
412
|
+
const stored = await readStored();
|
|
413
|
+
if (mobile && stored === null) {
|
|
414
|
+
await endSession();
|
|
415
|
+
return null;
|
|
416
|
+
}
|
|
417
|
+
const answer = await requestRefresh(seen, stored);
|
|
418
|
+
if (answer === null)
|
|
419
|
+
return null;
|
|
420
|
+
if (answer === 'rejected') {
|
|
421
|
+
await endSession();
|
|
422
|
+
return null;
|
|
423
|
+
}
|
|
424
|
+
const { refreshToken } = answer;
|
|
425
|
+
if (refreshToken !== undefined && tokenStore !== undefined) {
|
|
426
|
+
// Saved before the new access token can be used (`rn:SES-5`). The server has replaced the stored token, so
|
|
427
|
+
// a failed save leaves no usable token: the session ends.
|
|
428
|
+
try {
|
|
429
|
+
await tokenStore.save(refreshToken);
|
|
430
|
+
}
|
|
431
|
+
catch (error) {
|
|
432
|
+
await revokeDropped(refreshToken);
|
|
433
|
+
await endSession();
|
|
434
|
+
throw asError(error, 'The token store could not save the refresh token.');
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
accessToken = answer.accessToken;
|
|
438
|
+
refreshes += 1;
|
|
439
|
+
return answer.accessToken;
|
|
440
|
+
};
|
|
441
|
+
/** Registers `promise` as the refresh of the session `seen` until it ends, so other callers of that session join it. */
|
|
442
|
+
const shareRefresh = (seen, promise) => {
|
|
443
|
+
const entry = {
|
|
444
|
+
sid: seen,
|
|
445
|
+
promise: promise.finally(() => {
|
|
446
|
+
if (refreshing === entry)
|
|
447
|
+
refreshing = undefined;
|
|
448
|
+
}),
|
|
449
|
+
};
|
|
450
|
+
// Each caller handles the rejection of the promise it got; this only keeps a refresh nobody waits for any more
|
|
451
|
+
// from being reported as unhandled.
|
|
452
|
+
void entry.promise.catch(() => undefined);
|
|
453
|
+
refreshing = entry;
|
|
454
|
+
return entry.promise;
|
|
455
|
+
};
|
|
456
|
+
/**
|
|
457
|
+
* The refresh after a 401 to a request sent when `sent` refreshes had ended, inside a session operation. When
|
|
458
|
+
* another refresh has ended since (an operation queued before it renewed the session), the access token in place
|
|
459
|
+
* is the result, without a second refresh of the same session. The refreshes are counted, not compared by the text
|
|
460
|
+
* of the token, which the server may issue again unchanged (r9:U3).
|
|
461
|
+
*/
|
|
462
|
+
const refreshAfter401 = (seen, sent) => current(seen) && accessToken !== null && refreshes !== sent ? Promise.resolve(accessToken) : doRefresh(seen);
|
|
463
|
+
/**
|
|
464
|
+
* The refresh of the session `seen`, queued once and shared by its callers (`rn:SES-5`). With `sent` (the count
|
|
465
|
+
* of refreshes when the request that got the 401 was sent) it is the refresh after that 401 (`refreshAfter401`), checked in its turn; without it, as
|
|
466
|
+
* asked for by `refreshAccessToken`, it always asks the server.
|
|
467
|
+
*/
|
|
468
|
+
const refreshFor = (seen, sent) => refreshing?.sid === seen
|
|
469
|
+
? refreshing.promise
|
|
470
|
+
: shareRefresh(seen, session.run(() => (sent === undefined ? doRefresh(seen) : refreshAfter401(seen, sent))));
|
|
471
|
+
const withBearer = (init, token) => {
|
|
472
|
+
const headers = new Headers(init?.headers);
|
|
473
|
+
if (token !== null)
|
|
474
|
+
headers.set('Authorization', `Bearer ${token}`);
|
|
475
|
+
return { ...init, headers };
|
|
476
|
+
};
|
|
477
|
+
/**
|
|
478
|
+
* A request of the session `seen` with its access token, repeated once after a refresh on 401. Not sent when the
|
|
479
|
+
* session is no longer current (`session-changed`); not repeated when it stopped being current. `refresh` gets the
|
|
480
|
+
* number of refreshes ended when the request was sent; it is the shared refresh of the session or, inside a session operation
|
|
481
|
+
* (`inQueue`), one that runs in the same operation.
|
|
482
|
+
*/
|
|
483
|
+
const sendAuthorized = async (seen, input, init, refresh, inQueue) => {
|
|
484
|
+
// The token changes only together with `sid`, or by a refresh of this same session: one read is enough.
|
|
485
|
+
const token = accessToken;
|
|
486
|
+
const sent = refreshes;
|
|
487
|
+
const target = String(input);
|
|
488
|
+
const first = await sendOf(seen, target, withBearer(init, token), inQueue);
|
|
489
|
+
if (first === null)
|
|
490
|
+
throw sessionChangedError();
|
|
491
|
+
if (first.status !== 401 || token === null || !current(seen))
|
|
492
|
+
return first;
|
|
493
|
+
// Another request of the same session may have refreshed the token while this one was on its way; `refresh`
|
|
494
|
+
// checks it again in its turn.
|
|
495
|
+
const fresh = accessToken !== null && refreshes !== sent ? accessToken : await refresh(sent);
|
|
496
|
+
if (fresh === null)
|
|
497
|
+
return first;
|
|
498
|
+
return (await sendOf(seen, target, withBearer(init, fresh), inQueue)) ?? first;
|
|
499
|
+
};
|
|
500
|
+
/**
|
|
501
|
+
* The absolute address of an `authorizedFetch` call (`apiAddress`): a relative address under the path of the base
|
|
502
|
+
* URL, an absolute one on its origin, without the global `URL` (r1:U1). The origin of an empty or path-only base URL
|
|
503
|
+
* is the one of `location.href` (r2:U1). Anything else throws a `TypeError` before anything is sent.
|
|
504
|
+
*/
|
|
505
|
+
const apiTarget = (input) =>
|
|
506
|
+
// `location` exists only in browsers: the cast names the one property read, the optional chain handles its absence.
|
|
507
|
+
apiAddress(input, base, globalThis.location?.href);
|
|
508
|
+
/** Queues the restore first when the state is still `loading`, so what is queued next acts on its result. */
|
|
509
|
+
const restoreFirst = () => (state.status === 'loading' ? restoreSession() : Promise.resolve());
|
|
510
|
+
/**
|
|
511
|
+
* A request outside the queue for the session `seen`. While a session operation is queued or running (the restore
|
|
512
|
+
* included), it waits for the operations queued before it; otherwise it is sent in the step of the call. Then it
|
|
513
|
+
* goes with the token of that session.
|
|
514
|
+
*/
|
|
515
|
+
const authorizedFor = async (seen, input, init) => {
|
|
516
|
+
const target = apiTarget(input);
|
|
517
|
+
const restored = restoreFirst();
|
|
518
|
+
if (session.busy())
|
|
519
|
+
await Promise.all([restored, session.idle()]);
|
|
520
|
+
return sendAuthorized(seen, target, init, (sent) => refreshFor(seen, sent), false);
|
|
521
|
+
};
|
|
522
|
+
/**
|
|
523
|
+
* A privileged request that ends the session on the server, sent in a session operation for the session seen at
|
|
524
|
+
* the call; on success that session ends here too, while it is current.
|
|
525
|
+
*/
|
|
526
|
+
const privilegedCall = async (method, path, body) => {
|
|
527
|
+
// The address first, as for `authorizedFetch`: a `TypeError` leaves before the restore sends anything (DEC-293).
|
|
528
|
+
const target = apiTarget(apiPath(path));
|
|
529
|
+
const seen = sid;
|
|
530
|
+
const restored = restoreFirst();
|
|
531
|
+
const operation = session.run(async () => {
|
|
532
|
+
const refresh = (sent) => refreshAfter401(seen, sent);
|
|
533
|
+
// The answer comes read to the end, inside the time limit of its request (r9:U2).
|
|
534
|
+
const res = await sendAuthorized(seen, target, jsonInit(method, body), refresh, true);
|
|
535
|
+
await expectEmpty(res);
|
|
536
|
+
if (current(seen))
|
|
537
|
+
await endSession();
|
|
538
|
+
});
|
|
539
|
+
await Promise.all([restored, operation]);
|
|
540
|
+
};
|
|
541
|
+
function restoreSession() {
|
|
542
|
+
if (restoring !== undefined)
|
|
543
|
+
return restoring;
|
|
544
|
+
const seen = sid;
|
|
545
|
+
// The refresh of the restore is the shared refresh of its session (`rn:SES-5`): a refresh asked for before the
|
|
546
|
+
// restore runs joins it instead of queueing a second one.
|
|
547
|
+
const earlier = refreshing?.sid === seen ? refreshing.promise : undefined;
|
|
548
|
+
let share = () => undefined;
|
|
549
|
+
if (earlier === undefined) {
|
|
550
|
+
// Its callers get the promise from `refreshing`; the restore uses the refresh it runs itself.
|
|
551
|
+
void shareRefresh(seen, new Promise((resolve) => {
|
|
552
|
+
share = resolve;
|
|
553
|
+
}));
|
|
554
|
+
}
|
|
555
|
+
restoring = session.run(async () => {
|
|
556
|
+
const refreshed = earlier ?? doRefresh(seen);
|
|
557
|
+
share(refreshed);
|
|
558
|
+
let restored;
|
|
559
|
+
try {
|
|
560
|
+
const token = await refreshed;
|
|
561
|
+
// One refresh at start: the first `GET /me` is sent directly, without the repeat after a 401.
|
|
562
|
+
const res = token === null ? null : await sendOf(seen, url('/me'), withBearer(jsonInit('GET'), token), true);
|
|
563
|
+
// Read to the end inside the time limit of the request (r9:U2).
|
|
564
|
+
if (res !== null)
|
|
565
|
+
restored = (await dataOf(res, isUserResponse)).user;
|
|
566
|
+
}
|
|
567
|
+
catch {
|
|
568
|
+
// A transient failure: no session for now, the stored refresh token stays for the next start (see the type).
|
|
569
|
+
// The access token is dropped, so the state `anonymous` never goes with a token that is still sent.
|
|
570
|
+
if (current(seen))
|
|
571
|
+
accessToken = null;
|
|
572
|
+
}
|
|
573
|
+
// Published after the handling of the failures, so no subscriber runs inside it (r7:U2).
|
|
574
|
+
if (restored !== undefined && current(seen) && state.status === 'loading') {
|
|
575
|
+
setState({ status: 'authenticated', user: restored });
|
|
576
|
+
}
|
|
577
|
+
else if (state.status === 'loading') {
|
|
578
|
+
setState({ status: 'anonymous' });
|
|
579
|
+
}
|
|
580
|
+
return state;
|
|
581
|
+
});
|
|
582
|
+
return restoring;
|
|
583
|
+
}
|
|
584
|
+
return {
|
|
585
|
+
getState: () => state,
|
|
586
|
+
subscribe: (listener) => {
|
|
587
|
+
listeners.add(listener);
|
|
588
|
+
return () => {
|
|
589
|
+
listeners.delete(listener);
|
|
590
|
+
};
|
|
591
|
+
},
|
|
592
|
+
getAccessToken: () => accessToken,
|
|
593
|
+
restoreSession,
|
|
594
|
+
refreshAccessToken: () => refreshFor(sid),
|
|
595
|
+
authorizedFetch: (input, init) => authorizedFor(sid, input, init),
|
|
596
|
+
register: async (body) => {
|
|
597
|
+
const target = apiTarget(apiPath('/register'));
|
|
598
|
+
await expectEmpty(await send(target, jsonInit('POST', { ...body, client: body.client ?? mode })));
|
|
599
|
+
},
|
|
600
|
+
login: async (body) => {
|
|
601
|
+
// The password goes in this request: the address is checked before the call is queued (DEC-293).
|
|
602
|
+
const target = apiTarget(apiPath(mobile ? '/mobile/login' : '/login'));
|
|
603
|
+
return session.run(async () => {
|
|
604
|
+
// The identity, the token and the state of the new session in one step, then the subscribers.
|
|
605
|
+
const commitFor = (token, user) => () => {
|
|
606
|
+
sid += 1;
|
|
607
|
+
accessToken = token;
|
|
608
|
+
setState({ status: 'authenticated', user });
|
|
609
|
+
};
|
|
610
|
+
if (mobile) {
|
|
611
|
+
const data = await limited(async (signal) => dataOf(await send(target, { ...jsonInit('POST', body), signal }), isMobileLoginResponse));
|
|
612
|
+
await storeLogin(data.refreshToken, commitFor(data.accessToken, data.user));
|
|
613
|
+
return data.user;
|
|
614
|
+
}
|
|
615
|
+
const data = await limited(async (signal) => dataOf(await send(target, { ...jsonInit('POST', body), credentials: 'include', signal }), isLoginResponse));
|
|
616
|
+
commitFor(data.accessToken, data.user)();
|
|
617
|
+
return data.user;
|
|
618
|
+
});
|
|
619
|
+
},
|
|
620
|
+
logout: () => session.run(async () => {
|
|
621
|
+
// In its turn, after the operations asked for before it: what a subscriber asks for when it hears
|
|
622
|
+
// `anonymous` is queued after this logout, on the server and in the store.
|
|
623
|
+
dropSession(true);
|
|
624
|
+
if (!mobile) {
|
|
625
|
+
try {
|
|
626
|
+
await limited((signal) => send(url('/logout'), { method: 'POST', credentials: 'include', redirect: 'error', signal }));
|
|
627
|
+
}
|
|
628
|
+
catch {
|
|
629
|
+
// The session has ended for this client whether or not the server heard (`rn:SES-6`).
|
|
630
|
+
}
|
|
631
|
+
return;
|
|
632
|
+
}
|
|
633
|
+
// The store holds the token of the session this logout ended (see the model above).
|
|
634
|
+
const stored = await readStored();
|
|
635
|
+
await removeStored();
|
|
636
|
+
if (stored !== null)
|
|
637
|
+
await revokeDropped(stored);
|
|
638
|
+
}),
|
|
639
|
+
getMe: async () => {
|
|
640
|
+
const seen = sid;
|
|
641
|
+
const { user } = await dataOf(await authorizedFor(seen, apiPath('/me'), jsonInit('GET')), isUserResponse);
|
|
642
|
+
// The profile of a session that has ended or been replaced does not reach the state of the current one.
|
|
643
|
+
if (current(seen) && state.status === 'authenticated')
|
|
644
|
+
setState({ status: 'authenticated', user });
|
|
645
|
+
return user;
|
|
646
|
+
},
|
|
647
|
+
changePassword: (body) => privilegedCall('PUT', '/password', body),
|
|
648
|
+
revokeAllSessions: () => privilegedCall('POST', '/sessions/revoke-all'),
|
|
649
|
+
deleteAccount: (body) => privilegedCall('DELETE', '/me', body),
|
|
650
|
+
resendEmailVerification: async (body) => {
|
|
651
|
+
const res = await authorizedFor(sid, apiPath('/email-verification'), jsonInit('POST', { client: body?.client ?? mode }));
|
|
652
|
+
await expectEmpty(res);
|
|
653
|
+
},
|
|
654
|
+
confirmEmail: async (body) => {
|
|
655
|
+
// The password of the account goes with the token, so the address is made absolute as for `authorizedFetch`:
|
|
656
|
+
// a relative one would be resolved against the base URL of the document, which may be another origin (r1:U4).
|
|
657
|
+
const target = apiTarget(apiPath('/email-verification/confirm'));
|
|
658
|
+
// No redirect is followed, as in every call of the library (`jsonInit`, r2:U2, DEC-314).
|
|
659
|
+
await expectEmpty(await send(target, jsonInit('POST', body)));
|
|
660
|
+
},
|
|
661
|
+
requestPasswordReset: async (body) => {
|
|
662
|
+
await expectEmpty(await send(url('/password-reset'), jsonInit('POST', { ...body, client: body.client ?? mode })));
|
|
663
|
+
},
|
|
664
|
+
confirmPasswordReset: async (body) => {
|
|
665
|
+
const target = apiTarget(apiPath('/password-reset/confirm'));
|
|
666
|
+
const seen = sid;
|
|
667
|
+
// The session ends in the operation of the reset, before the next session operation starts. A session in
|
|
668
|
+
// memory counts even before it is shown: the token a restore has put in place.
|
|
669
|
+
await session.run(async () => {
|
|
670
|
+
await limited(async (signal) => expectEmpty(await send(target, { ...jsonInit('POST', body), signal })));
|
|
671
|
+
if (current(seen) && (accessToken !== null || state.status === 'authenticated'))
|
|
672
|
+
await endSession();
|
|
673
|
+
});
|
|
674
|
+
},
|
|
675
|
+
};
|
|
676
|
+
};
|