@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,17 @@
1
+ /** The canonical origin (`scheme://host[:port]`) of an absolute http(s) address; `null` when it has none or the client does not take its notation. */
2
+ export declare const originOf: (address: string) => string | null;
3
+ /**
4
+ * The text of an input of `authorizedFetch`: a string, or an object with a string `href` (a `URL`, also one of another
5
+ * realm or a polyfill), read through its `href`. The client sends the text it checked, not the object. Anything else,
6
+ * a `Request` included, would be turned into a path nobody asked for, so it throws.
7
+ */
8
+ export declare const inputText: (input: unknown) => string;
9
+ /**
10
+ * The absolute address to send to. `base` (the base URL without the trailing slash) is an absolute http(s) address, an
11
+ * empty string or a path from the root (`/gateway`); the last two take the origin of `pageHref` (`location.href`, not
12
+ * the base URL of the document) and need it. A relative address is appended to the path of `base` and stays under it;
13
+ * an absolute one must have the origin of `base` and may have any path on it. Dot segments (`.`, `..`, also
14
+ * `%2e`) are refused in both and in `base`; empty segments are kept as given. Throws a `TypeError` for anything else,
15
+ * before anything is sent.
16
+ */
17
+ export declare const apiAddress: (input: unknown, base: string, pageHref: string | undefined) => string;
@@ -0,0 +1,434 @@
1
+ /*
2
+ * The target of an `authorizedFetch` call, decided without the global `URL` (r1:U1): its behaviour differs between
3
+ * the platforms (React Native resolves relative addresses and compares origins in its own way), and this decides where
4
+ * the access token goes. The client reads the text of the address the way the URL Standard does for the parts that
5
+ * decide the origin and the path (https://url.spec.whatwg.org/#concept-url-origin), refuses every notation it does not
6
+ * read the same way, and hands `fetch` an absolute address it built itself: the canonical origin of the API and a path
7
+ * without dot segments. `fetch` then resolves nothing (not against the base URL of a document either, r2:U1), and any
8
+ * parser of the URL Standard reads the same origin and the same path segments from it.
9
+ */
10
+ const ABSOLUTE = /^([a-z][a-z0-9+.-]*):\/\/([^/?#]*)(.*)$/is;
11
+ const SCHEME = /^[a-z][a-z0-9+.-]*:/i;
12
+ /** The default port of `http` and `https`, `undefined` for any other scheme (no lookup in an object: inherited names such as `constructor` would pass, r3:U1). */
13
+ const defaultPortOf = (scheme) => scheme === 'http' ? 80 : scheme === 'https' ? 443 : undefined;
14
+ // Whitespace, control characters and a backslash: parsers read them differently (the URL Standard drops tabs and new
15
+ // lines and reads a backslash as `/`).
16
+ const BACKSLASH = String.fromCharCode(92);
17
+ const FORBIDDEN = {
18
+ test: (text) => text.includes(BACKSLASH) ||
19
+ [...text].some((ch) => ch.trim() === '' || ch.charCodeAt(0) < 32 || ch.charCodeAt(0) === 127),
20
+ };
21
+ // The host names the client takes: ASCII letters, digits, `-`, `_` and `.` (an internationalised name is written in
22
+ // its `xn--` form, checked by `validAceLabel`); anything else, a non-ASCII letter included, is refused.
23
+ const DOMAIN = /^[a-z0-9._-]+$/;
24
+ /** Punycode (RFC 3492) bias adaptation. */
25
+ const adaptBias = (delta, count, first) => {
26
+ let d = first ? Math.floor(delta / 700) : Math.floor(delta / 2);
27
+ d += Math.floor(d / count);
28
+ let k = 0;
29
+ while (d > 455) {
30
+ d = Math.floor(d / 35);
31
+ k += 36;
32
+ }
33
+ return k + Math.floor((36 * d) / (d + 38));
34
+ };
35
+ /** The Punycode threshold for the digit position `k`. */
36
+ const threshold = (k, bias) => (k <= bias ? 1 : k >= bias + 26 ? 26 : k - bias);
37
+ /** Punycode (RFC 3492) decoding of a label without its `xn--` prefix (lower case); `null` when it is not valid Punycode. */
38
+ const punycodeDecode = (text) => {
39
+ const dash = text.lastIndexOf('-');
40
+ const output = dash < 0 ? [] : [...text.slice(0, dash)].map((ch) => ch.charCodeAt(0));
41
+ let n = 128;
42
+ let i = 0;
43
+ let bias = 72;
44
+ for (let pointer = dash < 0 ? 0 : dash + 1; pointer < text.length;) {
45
+ const start = i;
46
+ let w = 1;
47
+ for (let k = 36;; k += 36) {
48
+ if (pointer >= text.length)
49
+ return null;
50
+ const code = text.charCodeAt(pointer);
51
+ pointer += 1;
52
+ const digit = code >= 97 && code <= 122 ? code - 97 : code >= 48 && code <= 57 ? code - 22 : -1;
53
+ if (digit < 0)
54
+ return null;
55
+ i += digit * w;
56
+ const t = threshold(k, bias);
57
+ if (digit < t)
58
+ break;
59
+ w *= 36 - t;
60
+ if (i > 0x10ffff * 64 || w > 0x10ffff * 64)
61
+ return null;
62
+ }
63
+ bias = adaptBias(i - start, output.length + 1, start === 0);
64
+ n += Math.floor(i / (output.length + 1));
65
+ i %= output.length + 1;
66
+ if (n > 0x10ffff)
67
+ return null;
68
+ output.splice(i, 0, n);
69
+ i += 1;
70
+ }
71
+ return output;
72
+ };
73
+ /** Punycode (RFC 3492) encoding of code points, without the `xn--` prefix. */
74
+ const punycodeEncode = (points) => {
75
+ let output = points
76
+ .filter((p) => p < 0x80)
77
+ .map((p) => String.fromCharCode(p))
78
+ .join('');
79
+ const basic = output.length;
80
+ let handled = basic;
81
+ if (basic > 0)
82
+ output += '-';
83
+ let n = 128;
84
+ let delta = 0;
85
+ let bias = 72;
86
+ const digit = (d) => String.fromCharCode(d < 26 ? 97 + d : 22 + d);
87
+ while (handled < points.length) {
88
+ const m = Math.min(...points.filter((p) => p >= n));
89
+ delta += (m - n) * (handled + 1);
90
+ n = m;
91
+ for (const p of points) {
92
+ if (p < n)
93
+ delta += 1;
94
+ if (p !== n)
95
+ continue;
96
+ let q = delta;
97
+ for (let k = 36;; k += 36) {
98
+ const t = threshold(k, bias);
99
+ if (q < t)
100
+ break;
101
+ output += digit(t + ((q - t) % (36 - t)));
102
+ q = Math.floor((q - t) / (36 - t));
103
+ }
104
+ output += digit(q);
105
+ bias = adaptBias(delta, handled + 1, handled === basic);
106
+ delta = 0;
107
+ handled += 1;
108
+ }
109
+ delta += 1;
110
+ n += 1;
111
+ }
112
+ return output;
113
+ };
114
+ // Code points of right-to-left scripts (Hebrew, Arabic, Syriac, Thaana, NKo and the like, also their digits): a label
115
+ // with them is subject to the Bidi rule of IDNA, which the client does not check, so it refuses them.
116
+ const RIGHT_TO_LEFT = /[\u0590-\u08ff\ufb1d-\ufdff\ufe70-\ufeff\u{10800}-\u{10fff}\u{1e800}-\u{1efff}]/u;
117
+ // What a decoded label may hold: lower-case letters and other letters without case, modifier letters, combining marks
118
+ // and decimal digits (no symbols, punctuation, format characters such as joiners, spaces or controls).
119
+ const LABEL_CHARACTER = /^[\p{Ll}\p{Lo}\p{Lm}\p{Mn}\p{Mc}\p{Nd}a-z0-9-]$/u;
120
+ // A code point the mapping of UTS #46 changes or removes (upper case, compatibility forms, default ignorable ones such
121
+ // as variation selectors): an `xn--` label holding one is invalid.
122
+ const CHANGED_BY_MAPPING = /\p{Changes_When_NFKC_Casefolded}/u;
123
+ /**
124
+ * Whether an `xn--` label passes a strict check (r2:U2). The URL Standard reads such a label through UTS #46
125
+ * (domain to ASCII) and refuses the host when the label is invalid; the client does not have the IDNA tables, so it
126
+ * takes only a subset it can check, and refuses the rest (the access token is then not sent): valid Punycode in its
127
+ * canonical encoding, with at least one non-ASCII code point, in NFC, not starting with a combining mark, of letters,
128
+ * marks and digits only, none of them changed by NFKC case folding, none of a right-to-left script. The Punycode part
129
+ * must not start with `xn--` again (nested ACE prefix, r4 to r2:U2): the decoded text then starts with `xn--`, which
130
+ * UTS #46 (validity criterion 4) forbids, or the ASCII letters copied first into the Punycode part spell `xn--`, which
131
+ * the parser of Node.js (Ada) refuses too.
132
+ */
133
+ const validAceLabel = (label) => {
134
+ if (label.startsWith('xn--', 4))
135
+ return false;
136
+ const points = punycodeDecode(label.slice(4));
137
+ if (points === null || !points.some((p) => p >= 0x80) || punycodeEncode(points) !== label.slice(4))
138
+ return false;
139
+ const text = String.fromCodePoint(...points);
140
+ if (text.normalize('NFC') !== text || /^\p{M}/u.test(text) || RIGHT_TO_LEFT.test(text))
141
+ return false;
142
+ return [...text].every((ch) => LABEL_CHARACTER.test(ch) && !CHANGED_BY_MAPPING.test(ch));
143
+ };
144
+ /** A number of an IPv4 address part (decimal, `0x` hexadecimal or `0` octal, as the URL Standard reads it); `null` when it is not one. */
145
+ const ipv4Number = (part) => {
146
+ let text = part;
147
+ let radix = 10;
148
+ if (/^0x/i.test(text)) {
149
+ text = text.slice(2);
150
+ radix = 16;
151
+ }
152
+ else if (text.length > 1 && text.startsWith('0')) {
153
+ text = text.slice(1);
154
+ radix = 8;
155
+ }
156
+ if (text === '')
157
+ return 0;
158
+ const digits = radix === 16 ? /^[0-9a-f]+$/i : radix === 8 ? /^[0-7]+$/ : /^[0-9]+$/;
159
+ if (!digits.test(text))
160
+ return null;
161
+ // More digits than any IPv4 part may have: the number is too large anyway (and would lose its precision).
162
+ if (text.length > 12)
163
+ return Number.POSITIVE_INFINITY;
164
+ return parseInt(text, radix);
165
+ };
166
+ /** Whether the URL Standard reads the host as an IPv4 address: its last label is a number. */
167
+ const endsInNumber = (host) => {
168
+ const labels = host.split('.');
169
+ if (labels.length > 1 && labels[labels.length - 1] === '')
170
+ labels.pop();
171
+ const last = labels[labels.length - 1] ?? '';
172
+ return /^[0-9]+$/.test(last) || /^0x[0-9a-f]*$/i.test(last);
173
+ };
174
+ /** The IPv4 parser of the URL Standard, serialised in dotted decimal; `null` for a failure. */
175
+ const ipv4 = (host) => {
176
+ const parts = host.split('.');
177
+ if (parts.length > 1 && parts[parts.length - 1] === '')
178
+ parts.pop();
179
+ if (parts.length > 4)
180
+ return null;
181
+ const numbers = [];
182
+ for (const part of parts) {
183
+ if (part === '')
184
+ return null;
185
+ const value = ipv4Number(part);
186
+ if (value === null)
187
+ return null;
188
+ numbers.push(value);
189
+ }
190
+ const last = numbers.pop() ?? 0;
191
+ if (numbers.some((n) => n > 255) || last >= 256 ** (4 - numbers.length))
192
+ return null;
193
+ let address = last;
194
+ numbers.forEach((n, i) => {
195
+ address += n * 256 ** (3 - i);
196
+ });
197
+ return [24, 16, 8, 0].map((shift) => Math.floor(address / 2 ** shift) % 256).join('.');
198
+ };
199
+ /** The IPv6 parser of the URL Standard (https://url.spec.whatwg.org/#concept-ipv6-parser); `null` for a failure. */
200
+ const ipv6Pieces = (text) => {
201
+ const address = [0, 0, 0, 0, 0, 0, 0, 0];
202
+ let pieceIndex = 0;
203
+ let compress = null;
204
+ let pointer = 0;
205
+ const at = (i) => text.charAt(i);
206
+ const isHex = (c) => /^[0-9a-f]$/i.test(c);
207
+ const isDigit = (c) => /^[0-9]$/.test(c);
208
+ if (at(pointer) === ':') {
209
+ if (at(pointer + 1) !== ':')
210
+ return null;
211
+ pointer += 2;
212
+ pieceIndex += 1;
213
+ compress = pieceIndex;
214
+ }
215
+ while (pointer < text.length) {
216
+ if (pieceIndex === 8)
217
+ return null;
218
+ if (at(pointer) === ':') {
219
+ if (compress !== null)
220
+ return null;
221
+ pointer += 1;
222
+ pieceIndex += 1;
223
+ compress = pieceIndex;
224
+ continue;
225
+ }
226
+ let value = 0;
227
+ let length = 0;
228
+ while (length < 4 && isHex(at(pointer))) {
229
+ value = value * 16 + parseInt(at(pointer), 16);
230
+ pointer += 1;
231
+ length += 1;
232
+ }
233
+ if (at(pointer) === '.') {
234
+ if (length === 0)
235
+ return null;
236
+ pointer -= length;
237
+ if (pieceIndex > 6)
238
+ return null;
239
+ let numbersSeen = 0;
240
+ while (pointer < text.length) {
241
+ let piece = null;
242
+ if (numbersSeen > 0) {
243
+ if (at(pointer) === '.' && numbersSeen < 4)
244
+ pointer += 1;
245
+ else
246
+ return null;
247
+ }
248
+ if (!isDigit(at(pointer)))
249
+ return null;
250
+ while (isDigit(at(pointer))) {
251
+ const digit = parseInt(at(pointer), 10);
252
+ if (piece === null)
253
+ piece = digit;
254
+ else if (piece === 0)
255
+ return null;
256
+ else
257
+ piece = piece * 10 + digit;
258
+ if (piece > 255)
259
+ return null;
260
+ pointer += 1;
261
+ }
262
+ address[pieceIndex] = (address[pieceIndex] ?? 0) * 0x100 + (piece ?? 0);
263
+ numbersSeen += 1;
264
+ if (numbersSeen === 2 || numbersSeen === 4)
265
+ pieceIndex += 1;
266
+ }
267
+ if (numbersSeen !== 4)
268
+ return null;
269
+ break;
270
+ }
271
+ else if (at(pointer) === ':') {
272
+ pointer += 1;
273
+ if (pointer >= text.length)
274
+ return null;
275
+ }
276
+ else if (pointer < text.length) {
277
+ return null;
278
+ }
279
+ address[pieceIndex] = value;
280
+ pieceIndex += 1;
281
+ }
282
+ if (compress !== null) {
283
+ let swaps = pieceIndex - compress;
284
+ pieceIndex = 7;
285
+ while (pieceIndex !== 0 && swaps > 0) {
286
+ const other = compress + swaps - 1;
287
+ [address[pieceIndex], address[other]] = [address[other] ?? 0, address[pieceIndex] ?? 0];
288
+ pieceIndex -= 1;
289
+ swaps -= 1;
290
+ }
291
+ }
292
+ else if (pieceIndex !== 8) {
293
+ return null;
294
+ }
295
+ return address;
296
+ };
297
+ /** The IPv6 serialiser of the URL Standard: lower-case hexadecimal, the first longest run of two or more zeros as `::`. */
298
+ const ipv6Text = (pieces) => {
299
+ let start = -1;
300
+ let best = 1;
301
+ for (let i = 0; i < 8;) {
302
+ let j = i;
303
+ while (j < 8 && pieces[j] === 0)
304
+ j += 1;
305
+ if (j - i > best) {
306
+ start = i;
307
+ best = j - i;
308
+ }
309
+ i = j === i ? i + 1 : j;
310
+ }
311
+ let text = '';
312
+ for (let i = 0; i < 8; i += 1) {
313
+ if (i === start) {
314
+ text += i === 0 ? '::' : ':';
315
+ i += best - 1;
316
+ continue;
317
+ }
318
+ text += (pieces[i] ?? 0).toString(16);
319
+ if (i < 7)
320
+ text += ':';
321
+ }
322
+ return text;
323
+ };
324
+ /** The canonical host of a special URL (`http`, `https`): a domain in lower case or an IP address; `null` when the client does not take it. */
325
+ const canonicalHost = (raw) => {
326
+ if (raw.startsWith('[')) {
327
+ if (!raw.endsWith(']'))
328
+ return null;
329
+ const pieces = ipv6Pieces(raw.slice(1, -1));
330
+ return pieces === null ? null : `[${ipv6Text(pieces)}]`;
331
+ }
332
+ // Percent-encoded ASCII is decoded, as the URL Standard does; an invalid escape or a non-ASCII byte is refused.
333
+ let invalid = false;
334
+ const decoded = raw.replace(/%([0-9a-f]{2})?/gi, (_, hex) => {
335
+ const code = hex === undefined ? 0x80 : parseInt(hex, 16);
336
+ if (code >= 0x80)
337
+ invalid = true;
338
+ return String.fromCharCode(code);
339
+ });
340
+ const host = decoded.toLowerCase();
341
+ if (invalid || host === '' || !DOMAIN.test(host))
342
+ return null;
343
+ if (host.split('.').some((label) => label.startsWith('xn--') && !validAceLabel(label)))
344
+ return null;
345
+ return endsInNumber(host) ? ipv4(host) : host;
346
+ };
347
+ /** The canonical origin and the rest (path, query, fragment; the path starts with `/`) of an absolute http(s) address. */
348
+ const splitAbsolute = (address) => {
349
+ if (FORBIDDEN.test(address))
350
+ return null;
351
+ const match = ABSOLUTE.exec(address);
352
+ if (match === null)
353
+ return null;
354
+ const scheme = (match[1] ?? '').toLowerCase();
355
+ const authority = match[2] ?? '';
356
+ const defaultPort = defaultPortOf(scheme);
357
+ // User information (`user@host`) is refused: it hides the host from a reader.
358
+ if (defaultPort === undefined || authority.includes('@'))
359
+ return null;
360
+ const closing = authority.lastIndexOf(']');
361
+ const colon = authority.lastIndexOf(':');
362
+ const hasPort = colon > closing;
363
+ const host = canonicalHost(hasPort ? authority.slice(0, colon) : authority);
364
+ const portText = hasPort ? authority.slice(colon + 1) : '';
365
+ if (host === null || !/^[0-9]*$/.test(portText))
366
+ return null;
367
+ const port = portText === '' ? defaultPort : parseInt(portText, 10);
368
+ if (port > 65535)
369
+ return null;
370
+ const rest = match[3] ?? '';
371
+ return {
372
+ origin: `${scheme}://${host}${port === defaultPort ? '' : `:${port}`}`,
373
+ rest: rest.startsWith('/') ? rest : `/${rest}`,
374
+ };
375
+ };
376
+ /** The canonical origin (`scheme://host[:port]`) of an absolute http(s) address; `null` when it has none or the client does not take its notation. */
377
+ export const originOf = (address) => splitAbsolute(address)?.origin ?? null;
378
+ /** Whether the path of `rest` (up to `?` or `#`) has a dot segment (`.` or `..`, also percent-encoded as `%2e`). */
379
+ const hasDotSegment = (rest) => (rest.split(/[?#]/)[0] ?? '').split('/').some((segment) => /^(\.|%2e){1,2}$/i.test(segment));
380
+ /**
381
+ * The text of an input of `authorizedFetch`: a string, or an object with a string `href` (a `URL`, also one of another
382
+ * realm or a polyfill), read through its `href`. The client sends the text it checked, not the object. Anything else,
383
+ * a `Request` included, would be turned into a path nobody asked for, so it throws.
384
+ */
385
+ export const inputText = (input) => {
386
+ if (typeof input === 'string')
387
+ return input;
388
+ if (typeof input === 'object' && input !== null && typeof input.href === 'string') {
389
+ // Narrowed above: `href` is a string (the check in the condition).
390
+ return input.href;
391
+ }
392
+ throw new TypeError('authorizedFetch takes an address as a string or a URL object.');
393
+ };
394
+ /**
395
+ * The absolute address to send to. `base` (the base URL without the trailing slash) is an absolute http(s) address, an
396
+ * empty string or a path from the root (`/gateway`); the last two take the origin of `pageHref` (`location.href`, not
397
+ * the base URL of the document) and need it. A relative address is appended to the path of `base` and stays under it;
398
+ * an absolute one must have the origin of `base` and may have any path on it. Dot segments (`.`, `..`, also
399
+ * `%2e`) are refused in both and in `base`; empty segments are kept as given. Throws a `TypeError` for anything else,
400
+ * before anything is sent.
401
+ */
402
+ export const apiAddress = (input, base, pageHref) => {
403
+ const text = inputText(input);
404
+ const refuse = () => {
405
+ throw new TypeError('authorizedFetch sends the access token only to the origin of baseUrl.');
406
+ };
407
+ let api;
408
+ if (base === '' || (base.startsWith('/') && !base.startsWith('//'))) {
409
+ const page = pageHref === undefined ? null : originOf(pageHref);
410
+ api = page === null || FORBIDDEN.test(base) ? null : { origin: page, rest: base };
411
+ }
412
+ else {
413
+ api = splitAbsolute(base);
414
+ if (api !== null)
415
+ api = { origin: api.origin, rest: api.rest.replace(/\/+$/, '') };
416
+ }
417
+ if (api === null || /[?#]/.test(api.rest) || hasDotSegment(api.rest))
418
+ return refuse();
419
+ if (FORBIDDEN.test(text))
420
+ return refuse();
421
+ if (ABSOLUTE.test(text)) {
422
+ const target = splitAbsolute(text);
423
+ if (target === null || target.origin !== api.origin || hasDotSegment(target.rest))
424
+ return refuse();
425
+ return `${target.origin}${target.rest}`;
426
+ }
427
+ // Protocol-relative (`//host`), another scheme (`javascript:`) and the like are not paths of the API.
428
+ if (text.startsWith('//') || SCHEME.test(text))
429
+ return refuse();
430
+ const relative = `/${text.replace(/^\//, '')}`;
431
+ if (hasDotSegment(relative))
432
+ return refuse();
433
+ return `${api.origin}${api.rest}${relative}`;
434
+ };