@tessellation/http 0.0.0-stage → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +412 -2
- package/dist/index.d.ts +20 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +16 -0
- package/dist/lib/auth/api-key.d.ts +17 -0
- package/dist/lib/auth/api-key.d.ts.map +1 -0
- package/dist/lib/auth/api-key.js +48 -0
- package/dist/lib/auth/jwt.d.ts +33 -0
- package/dist/lib/auth/jwt.d.ts.map +1 -0
- package/dist/lib/auth/jwt.js +227 -0
- package/dist/lib/auth/provide-auth.d.ts +30 -0
- package/dist/lib/auth/provide-auth.d.ts.map +1 -0
- package/dist/lib/auth/provide-auth.js +69 -0
- package/dist/lib/auth/strategy.d.ts +47 -0
- package/dist/lib/auth/strategy.d.ts.map +1 -0
- package/dist/lib/auth/strategy.js +18 -0
- package/dist/lib/compile.d.ts +46 -0
- package/dist/lib/compile.d.ts.map +1 -0
- package/dist/lib/compile.js +126 -0
- package/dist/lib/compression.d.ts +23 -0
- package/dist/lib/compression.d.ts.map +1 -0
- package/dist/lib/compression.js +86 -0
- package/dist/lib/config.d.ts +173 -0
- package/dist/lib/config.d.ts.map +1 -0
- package/dist/lib/config.js +93 -0
- package/dist/lib/cors.d.ts +41 -0
- package/dist/lib/cors.d.ts.map +1 -0
- package/dist/lib/cors.js +101 -0
- package/dist/lib/docs.d.ts +15 -0
- package/dist/lib/docs.d.ts.map +1 -0
- package/dist/lib/docs.js +93 -0
- package/dist/lib/engine.d.ts +83 -0
- package/dist/lib/engine.d.ts.map +1 -0
- package/dist/lib/engine.js +562 -0
- package/dist/lib/errors.d.ts +31 -0
- package/dist/lib/errors.d.ts.map +1 -0
- package/dist/lib/errors.js +55 -0
- package/dist/lib/etag.d.ts +5 -0
- package/dist/lib/etag.d.ts.map +1 -0
- package/dist/lib/etag.js +30 -0
- package/dist/lib/headers.d.ts +3 -0
- package/dist/lib/headers.d.ts.map +1 -0
- package/dist/lib/headers.js +14 -0
- package/dist/lib/json-schema.d.ts +11 -0
- package/dist/lib/json-schema.d.ts.map +1 -0
- package/dist/lib/json-schema.js +23 -0
- package/dist/lib/openapi.d.ts +18 -0
- package/dist/lib/openapi.d.ts.map +1 -0
- package/dist/lib/openapi.js +218 -0
- package/dist/lib/rate-limit.d.ts +52 -0
- package/dist/lib/rate-limit.d.ts.map +1 -0
- package/dist/lib/rate-limit.js +87 -0
- package/dist/lib/reply.d.ts +27 -0
- package/dist/lib/reply.d.ts.map +1 -0
- package/dist/lib/reply.js +52 -0
- package/dist/lib/request.d.ts +55 -0
- package/dist/lib/request.d.ts.map +1 -0
- package/dist/lib/request.js +36 -0
- package/dist/lib/router.d.ts +35 -0
- package/dist/lib/router.d.ts.map +1 -0
- package/dist/lib/router.js +173 -0
- package/dist/lib/routes.d.ts +196 -0
- package/dist/lib/routes.d.ts.map +1 -0
- package/dist/lib/routes.js +98 -0
- package/dist/lib/security-headers.d.ts +19 -0
- package/dist/lib/security-headers.d.ts.map +1 -0
- package/dist/lib/security-headers.js +22 -0
- package/dist/lib/serializer.d.ts +35 -0
- package/dist/lib/serializer.d.ts.map +1 -0
- package/dist/lib/serializer.js +147 -0
- package/dist/lib/server.d.ts +86 -0
- package/dist/lib/server.d.ts.map +1 -0
- package/dist/lib/server.js +255 -0
- package/dist/lib/testing.d.ts +21 -0
- package/dist/lib/testing.d.ts.map +1 -0
- package/dist/lib/testing.js +62 -0
- package/dist/lib/transports/node.d.ts +4 -0
- package/dist/lib/transports/node.d.ts.map +1 -0
- package/dist/lib/transports/node.js +249 -0
- package/dist/lib/transports/transport.d.ts +32 -0
- package/dist/lib/transports/transport.d.ts.map +1 -0
- package/dist/lib/transports/transport.js +1 -0
- package/dist/lib/transports/uws.d.ts +8 -0
- package/dist/lib/transports/uws.d.ts.map +1 -0
- package/dist/lib/transports/uws.js +246 -0
- package/dist/lib/websocket.d.ts +71 -0
- package/dist/lib/websocket.d.ts.map +1 -0
- package/dist/lib/websocket.js +125 -0
- package/package.json +67 -3
- package/src/index.ts +103 -0
- package/src/lib/auth/api-key.ts +73 -0
- package/src/lib/auth/jwt.ts +339 -0
- package/src/lib/auth/provide-auth.ts +99 -0
- package/src/lib/auth/strategy.ts +66 -0
- package/src/lib/compile.ts +207 -0
- package/src/lib/compression.ts +121 -0
- package/src/lib/config.ts +107 -0
- package/src/lib/cors.ts +146 -0
- package/src/lib/docs.ts +115 -0
- package/src/lib/engine.ts +770 -0
- package/src/lib/errors.ts +84 -0
- package/src/lib/etag.ts +37 -0
- package/src/lib/headers.ts +18 -0
- package/src/lib/json-schema.ts +36 -0
- package/src/lib/openapi.ts +299 -0
- package/src/lib/rate-limit.ts +142 -0
- package/src/lib/reply.ts +70 -0
- package/src/lib/request.ts +83 -0
- package/src/lib/router.ts +217 -0
- package/src/lib/routes.ts +414 -0
- package/src/lib/security-headers.ts +38 -0
- package/src/lib/serializer.ts +203 -0
- package/src/lib/server.ts +352 -0
- package/src/lib/testing.ts +88 -0
- package/src/lib/transports/node.ts +315 -0
- package/src/lib/transports/transport.ts +39 -0
- package/src/lib/transports/uws.ts +310 -0
- package/src/lib/websocket.ts +184 -0
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
import {
|
|
2
|
+
constants,
|
|
3
|
+
createHmac,
|
|
4
|
+
createPublicKey,
|
|
5
|
+
type KeyObject,
|
|
6
|
+
timingSafeEqual,
|
|
7
|
+
verify,
|
|
8
|
+
} from 'node:crypto';
|
|
9
|
+
|
|
10
|
+
import { HttpError } from '../errors.js';
|
|
11
|
+
import type { AuthStrategy, Principal } from './strategy.js';
|
|
12
|
+
|
|
13
|
+
/** A JSON Web Key, as found in JWKS documents. */
|
|
14
|
+
export type JsonWebKey = Readonly<Record<string, unknown>>;
|
|
15
|
+
|
|
16
|
+
type Algorithm =
|
|
17
|
+
| 'HS256'
|
|
18
|
+
| 'HS384'
|
|
19
|
+
| 'HS512'
|
|
20
|
+
| 'RS256'
|
|
21
|
+
| 'RS384'
|
|
22
|
+
| 'RS512'
|
|
23
|
+
| 'PS256'
|
|
24
|
+
| 'PS384'
|
|
25
|
+
| 'PS512'
|
|
26
|
+
| 'ES256'
|
|
27
|
+
| 'ES384'
|
|
28
|
+
| 'ES512'
|
|
29
|
+
| 'EdDSA';
|
|
30
|
+
|
|
31
|
+
/** Each algorithm, the key type it needs and its hash. */
|
|
32
|
+
const ALGORITHMS: Record<
|
|
33
|
+
Algorithm,
|
|
34
|
+
{ kind: 'secret' | 'rsa' | 'rsa-pss' | 'ec' | 'ed'; hash: string | null }
|
|
35
|
+
> = {
|
|
36
|
+
HS256: { kind: 'secret', hash: 'sha256' },
|
|
37
|
+
HS384: { kind: 'secret', hash: 'sha384' },
|
|
38
|
+
HS512: { kind: 'secret', hash: 'sha512' },
|
|
39
|
+
RS256: { kind: 'rsa', hash: 'sha256' },
|
|
40
|
+
RS384: { kind: 'rsa', hash: 'sha384' },
|
|
41
|
+
RS512: { kind: 'rsa', hash: 'sha512' },
|
|
42
|
+
PS256: { kind: 'rsa-pss', hash: 'sha256' },
|
|
43
|
+
PS384: { kind: 'rsa-pss', hash: 'sha384' },
|
|
44
|
+
PS512: { kind: 'rsa-pss', hash: 'sha512' },
|
|
45
|
+
ES256: { kind: 'ec', hash: 'sha256' },
|
|
46
|
+
ES384: { kind: 'ec', hash: 'sha384' },
|
|
47
|
+
ES512: { kind: 'ec', hash: 'sha512' },
|
|
48
|
+
EdDSA: { kind: 'ed', hash: null },
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
export type JwtClaims = Readonly<Record<string, unknown>>;
|
|
52
|
+
|
|
53
|
+
export interface JwtAuthOptions {
|
|
54
|
+
/** Strategy name, used in OpenAPI. Defaults to `bearer`. */
|
|
55
|
+
name?: string;
|
|
56
|
+
/** Shared secret for HS256/384/512. */
|
|
57
|
+
secret?: string | Uint8Array;
|
|
58
|
+
/** Public key (PEM, JWK or KeyObject) for RS*, PS*, ES* or EdDSA. */
|
|
59
|
+
publicKey?: string | JsonWebKey | KeyObject;
|
|
60
|
+
/** A JWKS endpoint (as published by OIDC providers); keys are cached and refreshed on rotation. */
|
|
61
|
+
jwksUrl?: string;
|
|
62
|
+
/** Accepted algorithms. Defaults to HS256 with a secret, otherwise RS256, PS256, ES256 and EdDSA. */
|
|
63
|
+
algorithms?: readonly Algorithm[];
|
|
64
|
+
/** Required `iss`, one of these values. */
|
|
65
|
+
issuer?: string | readonly string[];
|
|
66
|
+
/** Required `aud`, at least one of these values. */
|
|
67
|
+
audience?: string | readonly string[];
|
|
68
|
+
/** Allowed clock skew for `exp`/`nbf`, in milliseconds. Defaults to 5 seconds. */
|
|
69
|
+
clockTolerance?: number;
|
|
70
|
+
/**
|
|
71
|
+
* Turns verified claims into a principal. Defaults to `sub` as the id and
|
|
72
|
+
* roles from a `roles` array claim or a space-separated `scope`.
|
|
73
|
+
*/
|
|
74
|
+
principal?: (claims: JwtClaims) => Omit<Principal, 'strategy'>;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Authenticates `Authorization: Bearer <JWT>` requests. */
|
|
78
|
+
export function jwtAuth(options: JwtAuthOptions): AuthStrategy {
|
|
79
|
+
const name = options.name ?? 'bearer';
|
|
80
|
+
const sources = [options.secret, options.publicKey, options.jwksUrl].filter(
|
|
81
|
+
(s) => s !== undefined,
|
|
82
|
+
);
|
|
83
|
+
if (sources.length !== 1) {
|
|
84
|
+
throw new Error(
|
|
85
|
+
'jwtAuth() needs exactly one of secret, publicKey or jwksUrl.',
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const algorithms = new Set<Algorithm>(
|
|
90
|
+
options.algorithms ??
|
|
91
|
+
(options.secret !== undefined
|
|
92
|
+
? ['HS256']
|
|
93
|
+
: ['RS256', 'PS256', 'ES256', 'EdDSA']),
|
|
94
|
+
);
|
|
95
|
+
for (const algorithm of algorithms) {
|
|
96
|
+
const known = ALGORITHMS[algorithm] as
|
|
97
|
+
(typeof ALGORITHMS)[Algorithm] | undefined;
|
|
98
|
+
if (known === undefined) {
|
|
99
|
+
throw new Error(`Unsupported JWT algorithm "${algorithm}".`);
|
|
100
|
+
}
|
|
101
|
+
if ((known.kind === 'secret') !== (options.secret !== undefined)) {
|
|
102
|
+
throw new Error(
|
|
103
|
+
`JWT algorithm ${algorithm} ${known.kind === 'secret' ? 'needs a secret' : 'needs a public key'}.`,
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const secret =
|
|
109
|
+
options.secret === undefined ? undefined : Buffer.from(options.secret);
|
|
110
|
+
const publicKey =
|
|
111
|
+
options.publicKey === undefined ? undefined : toKey(options.publicKey);
|
|
112
|
+
const jwks =
|
|
113
|
+
options.jwksUrl === undefined ? undefined : new Jwks(options.jwksUrl);
|
|
114
|
+
const issuers = toList(options.issuer);
|
|
115
|
+
const audiences = toList(options.audience);
|
|
116
|
+
const tolerance = options.clockTolerance ?? 5000;
|
|
117
|
+
const toPrincipal = options.principal ?? defaultPrincipal;
|
|
118
|
+
|
|
119
|
+
return {
|
|
120
|
+
name,
|
|
121
|
+
scheme: { type: 'http', scheme: 'bearer', bearerFormat: 'JWT' },
|
|
122
|
+
async authenticate(request) {
|
|
123
|
+
const authorization = request.headers['authorization'];
|
|
124
|
+
if (authorization === undefined || !/^bearer\s/i.test(authorization)) {
|
|
125
|
+
return undefined;
|
|
126
|
+
}
|
|
127
|
+
const token = authorization.slice(7).trim();
|
|
128
|
+
|
|
129
|
+
const parts = token.split('.');
|
|
130
|
+
if (parts.length !== 3) {
|
|
131
|
+
throw invalid('The token is malformed.');
|
|
132
|
+
}
|
|
133
|
+
const [encodedHeader, encodedPayload, encodedSignature] = parts as [
|
|
134
|
+
string,
|
|
135
|
+
string,
|
|
136
|
+
string,
|
|
137
|
+
];
|
|
138
|
+
const header = decodeJson(encodedHeader);
|
|
139
|
+
const algorithm = header['alg'] as Algorithm;
|
|
140
|
+
if (typeof algorithm !== 'string' || !algorithms.has(algorithm)) {
|
|
141
|
+
throw invalid('The token algorithm is not accepted.');
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const { kind, hash } = ALGORITHMS[algorithm];
|
|
145
|
+
const data = Buffer.from(`${encodedHeader}.${encodedPayload}`);
|
|
146
|
+
const signature = Buffer.from(encodedSignature, 'base64url');
|
|
147
|
+
|
|
148
|
+
let valid: boolean;
|
|
149
|
+
if (kind === 'secret') {
|
|
150
|
+
const expected = createHmac(hash as string, secret as Buffer)
|
|
151
|
+
.update(data)
|
|
152
|
+
.digest();
|
|
153
|
+
valid =
|
|
154
|
+
expected.length === signature.length &&
|
|
155
|
+
timingSafeEqual(expected, signature);
|
|
156
|
+
} else {
|
|
157
|
+
const key =
|
|
158
|
+
publicKey ??
|
|
159
|
+
(await (jwks as Jwks).key(
|
|
160
|
+
typeof header['kid'] === 'string' ? header['kid'] : undefined,
|
|
161
|
+
));
|
|
162
|
+
if (!keyMatches(key, kind)) {
|
|
163
|
+
throw invalid('The token algorithm does not match the key.');
|
|
164
|
+
}
|
|
165
|
+
valid = verify(
|
|
166
|
+
hash,
|
|
167
|
+
data,
|
|
168
|
+
kind === 'rsa-pss'
|
|
169
|
+
? {
|
|
170
|
+
key,
|
|
171
|
+
padding: constants.RSA_PKCS1_PSS_PADDING,
|
|
172
|
+
saltLength: constants.RSA_PSS_SALTLEN_DIGEST,
|
|
173
|
+
}
|
|
174
|
+
: kind === 'ec'
|
|
175
|
+
? { key, dsaEncoding: 'ieee-p1363' }
|
|
176
|
+
: key,
|
|
177
|
+
signature,
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
if (!valid) {
|
|
181
|
+
throw invalid('The token signature is not valid.');
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const claims = decodeJson(encodedPayload);
|
|
185
|
+
const now = Date.now();
|
|
186
|
+
if (
|
|
187
|
+
claims['exp'] !== undefined &&
|
|
188
|
+
(typeof claims['exp'] !== 'number' ||
|
|
189
|
+
now > claims['exp'] * 1000 + tolerance)
|
|
190
|
+
) {
|
|
191
|
+
throw invalid('The token has expired.');
|
|
192
|
+
}
|
|
193
|
+
if (
|
|
194
|
+
claims['nbf'] !== undefined &&
|
|
195
|
+
(typeof claims['nbf'] !== 'number' ||
|
|
196
|
+
now < claims['nbf'] * 1000 - tolerance)
|
|
197
|
+
) {
|
|
198
|
+
throw invalid('The token is not valid yet.');
|
|
199
|
+
}
|
|
200
|
+
if (issuers !== undefined && !issuers.includes(claims['iss'] as string)) {
|
|
201
|
+
throw invalid('The token issuer is not accepted.');
|
|
202
|
+
}
|
|
203
|
+
if (audiences !== undefined) {
|
|
204
|
+
const audience =
|
|
205
|
+
toList(claims['aud'] as string | string[] | undefined) ?? [];
|
|
206
|
+
if (!audience.some((value) => audiences.includes(value))) {
|
|
207
|
+
throw invalid('The token audience is not accepted.');
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
return { ...toPrincipal(claims), strategy: name };
|
|
212
|
+
},
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function defaultPrincipal(claims: JwtClaims): Omit<Principal, 'strategy'> {
|
|
217
|
+
if (typeof claims['sub'] !== 'string') {
|
|
218
|
+
throw invalid('The token has no subject.');
|
|
219
|
+
}
|
|
220
|
+
const roles = Array.isArray(claims['roles'])
|
|
221
|
+
? claims['roles'].filter((role): role is string => typeof role === 'string')
|
|
222
|
+
: typeof claims['scope'] === 'string'
|
|
223
|
+
? claims['scope'].split(' ').filter((scope) => scope !== '')
|
|
224
|
+
: [];
|
|
225
|
+
return { id: claims['sub'], roles, claims };
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function invalid(message: string): HttpError {
|
|
229
|
+
return new HttpError(401, message, {
|
|
230
|
+
headers: { 'www-authenticate': 'Bearer error="invalid_token"' },
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function decodeJson(part: string): Record<string, unknown> {
|
|
235
|
+
try {
|
|
236
|
+
const value: unknown = JSON.parse(
|
|
237
|
+
Buffer.from(part, 'base64url').toString('utf8'),
|
|
238
|
+
);
|
|
239
|
+
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
|
|
240
|
+
return value as Record<string, unknown>;
|
|
241
|
+
}
|
|
242
|
+
} catch {
|
|
243
|
+
// reported below
|
|
244
|
+
}
|
|
245
|
+
throw invalid('The token is malformed.');
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function toKey(key: string | JsonWebKey | KeyObject): KeyObject {
|
|
249
|
+
if (typeof key === 'string') {
|
|
250
|
+
return createPublicKey(key);
|
|
251
|
+
}
|
|
252
|
+
if ('asymmetricKeyType' in key) {
|
|
253
|
+
return key as KeyObject;
|
|
254
|
+
}
|
|
255
|
+
return createPublicKey({ key: key as never, format: 'jwk' });
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function keyMatches(key: KeyObject, kind: string): boolean {
|
|
259
|
+
const type = key.asymmetricKeyType;
|
|
260
|
+
switch (kind) {
|
|
261
|
+
case 'rsa':
|
|
262
|
+
case 'rsa-pss':
|
|
263
|
+
return type === 'rsa' || type === 'rsa-pss';
|
|
264
|
+
case 'ec':
|
|
265
|
+
return type === 'ec';
|
|
266
|
+
case 'ed':
|
|
267
|
+
return type === 'ed25519' || type === 'ed448';
|
|
268
|
+
default:
|
|
269
|
+
return false;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function toList(
|
|
274
|
+
value: string | readonly string[] | undefined,
|
|
275
|
+
): readonly string[] | undefined {
|
|
276
|
+
return value === undefined
|
|
277
|
+
? undefined
|
|
278
|
+
: typeof value === 'string'
|
|
279
|
+
? [value]
|
|
280
|
+
: value;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** Keys from a JWKS endpoint, cached and refreshed when an unknown key id appears. */
|
|
284
|
+
class Jwks {
|
|
285
|
+
private keys = new Map<string, KeyObject>();
|
|
286
|
+
private fetched = 0;
|
|
287
|
+
private pending: Promise<void> | undefined;
|
|
288
|
+
|
|
289
|
+
constructor(private readonly url: string) {}
|
|
290
|
+
|
|
291
|
+
async key(kid: string | undefined): Promise<KeyObject> {
|
|
292
|
+
const stale = Date.now() - this.fetched > 10 * 60_000;
|
|
293
|
+
// Refresh for unknown ids (key rotation), at most every 30 seconds.
|
|
294
|
+
const unknown =
|
|
295
|
+
kid !== undefined &&
|
|
296
|
+
!this.keys.has(kid) &&
|
|
297
|
+
Date.now() - this.fetched > 30_000;
|
|
298
|
+
if (stale || unknown) {
|
|
299
|
+
this.pending ??= this.refresh().finally(() => {
|
|
300
|
+
this.pending = undefined;
|
|
301
|
+
});
|
|
302
|
+
await this.pending;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
const key =
|
|
306
|
+
kid === undefined
|
|
307
|
+
? this.keys.size === 1
|
|
308
|
+
? [...this.keys.values()][0]
|
|
309
|
+
: undefined
|
|
310
|
+
: this.keys.get(kid);
|
|
311
|
+
if (key === undefined) {
|
|
312
|
+
throw invalid('The token was signed with an unknown key.');
|
|
313
|
+
}
|
|
314
|
+
return key;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
private async refresh(): Promise<void> {
|
|
318
|
+
const response = await fetch(this.url, {
|
|
319
|
+
signal: AbortSignal.timeout(5000),
|
|
320
|
+
});
|
|
321
|
+
if (!response.ok) {
|
|
322
|
+
throw new HttpError(503, 'The signing keys could not be loaded.');
|
|
323
|
+
}
|
|
324
|
+
const { keys = [] } = (await response.json()) as {
|
|
325
|
+
keys?: (JsonWebKey & { kid?: string; use?: string })[];
|
|
326
|
+
};
|
|
327
|
+
const next = new Map<string, KeyObject>();
|
|
328
|
+
for (const jwk of keys) {
|
|
329
|
+
if (jwk.use === undefined || jwk.use === 'sig') {
|
|
330
|
+
next.set(
|
|
331
|
+
jwk.kid ?? '',
|
|
332
|
+
createPublicKey({ key: jwk as never, format: 'jwk' }),
|
|
333
|
+
);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
this.keys = next;
|
|
337
|
+
this.fetched = Date.now();
|
|
338
|
+
}
|
|
339
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import {
|
|
2
|
+
addLogFields,
|
|
3
|
+
inject,
|
|
4
|
+
provide,
|
|
5
|
+
type Provider,
|
|
6
|
+
} from '@tessellation/core';
|
|
7
|
+
|
|
8
|
+
import { forbidden } from '../errors.js';
|
|
9
|
+
import type { Middleware } from '../routes.js';
|
|
10
|
+
import { provideHttpMiddleware } from '../server.js';
|
|
11
|
+
import {
|
|
12
|
+
AUTH_STRATEGIES,
|
|
13
|
+
type AuthStrategy,
|
|
14
|
+
CurrentPrincipal,
|
|
15
|
+
type Principal,
|
|
16
|
+
requirePrincipal,
|
|
17
|
+
} from './strategy.js';
|
|
18
|
+
|
|
19
|
+
/** Marks middleware that requires authentication, for OpenAPI `security`. */
|
|
20
|
+
export const SECURED = Symbol('secured');
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Authenticates every request with the first strategy that recognizes its
|
|
24
|
+
* credentials. The principal is then available through `principal()`,
|
|
25
|
+
* `requirePrincipal()` and `CurrentPrincipal`, and logs written while
|
|
26
|
+
* handling the request carry its id. Unauthenticated requests continue
|
|
27
|
+
* anonymously; protect routes with `authenticated()` or `requireRoles()`.
|
|
28
|
+
*
|
|
29
|
+
* Strategies can be given as factories, which run in the injection context
|
|
30
|
+
* (to read config, for example):
|
|
31
|
+
*
|
|
32
|
+
* ```ts
|
|
33
|
+
* provideAuth(
|
|
34
|
+
* () => apiKeyAuth({ keys: inject(AuthConfig).apiKeys }),
|
|
35
|
+
* () => jwtAuth({ jwksUrl: inject(AuthConfig).jwksUrl }),
|
|
36
|
+
* )
|
|
37
|
+
* ```
|
|
38
|
+
*/
|
|
39
|
+
export function provideAuth(
|
|
40
|
+
...strategies: (AuthStrategy | (() => AuthStrategy))[]
|
|
41
|
+
): Provider[] {
|
|
42
|
+
return [
|
|
43
|
+
...strategies.map((strategy) =>
|
|
44
|
+
typeof strategy === 'function'
|
|
45
|
+
? provide(AUTH_STRATEGIES, { useFactory: strategy, multi: true })
|
|
46
|
+
: provide(AUTH_STRATEGIES, { useValue: strategy, multi: true }),
|
|
47
|
+
),
|
|
48
|
+
provideHttpMiddleware(authenticate),
|
|
49
|
+
];
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const authenticate: Middleware = async (context, next) => {
|
|
53
|
+
const strategies = inject(AUTH_STRATEGIES);
|
|
54
|
+
for (const strategy of strategies) {
|
|
55
|
+
let found = strategy.authenticate(context.request);
|
|
56
|
+
if (found instanceof Promise) {
|
|
57
|
+
found = await found;
|
|
58
|
+
}
|
|
59
|
+
if (found !== undefined) {
|
|
60
|
+
// Request logs from here on (and the access log) carry the principal.
|
|
61
|
+
addLogFields({ principal: found.id });
|
|
62
|
+
return CurrentPrincipal.run(found, next);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return next();
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
function secured(middleware: Middleware): Middleware {
|
|
69
|
+
return Object.assign(middleware, { [SECURED]: true });
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Rejects unauthenticated requests with 401. */
|
|
73
|
+
export function authenticated(): Middleware {
|
|
74
|
+
return secured((_context, next) => {
|
|
75
|
+
requirePrincipal();
|
|
76
|
+
return next();
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Rejects requests whose principal lacks any of `roles` (401 if unauthenticated, 403 otherwise). */
|
|
81
|
+
export function requireRoles(...roles: string[]): Middleware {
|
|
82
|
+
return authorize(
|
|
83
|
+
(current) => roles.every((role) => current.roles.includes(role)),
|
|
84
|
+
`This requires the role${roles.length === 1 ? '' : 's'} ${roles.join(', ')}.`,
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Rejects requests whose principal fails `check` (401 if unauthenticated, 403 otherwise). */
|
|
89
|
+
export function authorize(
|
|
90
|
+
check: (principal: Principal) => boolean | Promise<boolean>,
|
|
91
|
+
message = 'You are not allowed to do this.',
|
|
92
|
+
): Middleware {
|
|
93
|
+
return secured(async (_context, next) => {
|
|
94
|
+
if (!(await check(requirePrincipal()))) {
|
|
95
|
+
throw forbidden(message);
|
|
96
|
+
}
|
|
97
|
+
return next();
|
|
98
|
+
});
|
|
99
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { AsyncContext, InjectionToken } from '@tessellation/core';
|
|
2
|
+
|
|
3
|
+
import { unauthorized } from '../errors.js';
|
|
4
|
+
import type { HttpRequest } from '../request.js';
|
|
5
|
+
|
|
6
|
+
/** Who is making the request. */
|
|
7
|
+
export interface Principal {
|
|
8
|
+
/** A stable identifier, such as a user id or JWT `sub`. */
|
|
9
|
+
readonly id: string;
|
|
10
|
+
/** The name of the strategy that authenticated the request. */
|
|
11
|
+
readonly strategy: string;
|
|
12
|
+
readonly roles: readonly string[];
|
|
13
|
+
/** Everything else known about the principal, such as JWT claims. */
|
|
14
|
+
readonly claims: Readonly<Record<string, unknown>>;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* A way of authenticating requests. `authenticate()` returns a principal
|
|
19
|
+
* for valid credentials, `undefined` when the request carries no
|
|
20
|
+
* credentials for this strategy (so the next one is tried), and throws
|
|
21
|
+
* (such as `unauthorized()`) for invalid ones.
|
|
22
|
+
*
|
|
23
|
+
* ```ts
|
|
24
|
+
* const sessionAuth: AuthStrategy = {
|
|
25
|
+
* name: 'session',
|
|
26
|
+
* scheme: { type: 'apiKey', in: 'cookie', name: 'sid' },
|
|
27
|
+
* async authenticate(request) {
|
|
28
|
+
* const sid = parseCookies(request.header('cookie')).sid;
|
|
29
|
+
* if (sid === undefined) return undefined;
|
|
30
|
+
* const session = await sessions.find(sid);
|
|
31
|
+
* if (session === undefined) throw unauthorized('Session expired.');
|
|
32
|
+
* return { id: session.userId, strategy: 'session', roles: session.roles, claims: {} };
|
|
33
|
+
* },
|
|
34
|
+
* };
|
|
35
|
+
* ```
|
|
36
|
+
*/
|
|
37
|
+
export interface AuthStrategy {
|
|
38
|
+
readonly name: string;
|
|
39
|
+
/** The OpenAPI security scheme describing this strategy. */
|
|
40
|
+
readonly scheme?: Readonly<Record<string, unknown>>;
|
|
41
|
+
authenticate(
|
|
42
|
+
request: HttpRequest,
|
|
43
|
+
): Principal | undefined | Promise<Principal | undefined>;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The strategies registered with `provideAuth()`, tried in order. */
|
|
47
|
+
export const AUTH_STRATEGIES = new InjectionToken<AuthStrategy[]>(
|
|
48
|
+
'AUTH_STRATEGIES',
|
|
49
|
+
);
|
|
50
|
+
|
|
51
|
+
/** The principal of the current request, set by `provideAuth()`. */
|
|
52
|
+
export const CurrentPrincipal = new AsyncContext<Principal>('principal');
|
|
53
|
+
|
|
54
|
+
/** The current request's principal, if it is authenticated. */
|
|
55
|
+
export function principal(): Principal | undefined {
|
|
56
|
+
return CurrentPrincipal.get();
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The current request's principal; throws 401 if it is not authenticated. */
|
|
60
|
+
export function requirePrincipal(): Principal {
|
|
61
|
+
const current = CurrentPrincipal.get();
|
|
62
|
+
if (current === undefined) {
|
|
63
|
+
throw unauthorized('Authentication is required.');
|
|
64
|
+
}
|
|
65
|
+
return current;
|
|
66
|
+
}
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import type { Provider, StandardSchemaV1 } from '@tessellation/core';
|
|
2
|
+
|
|
3
|
+
import { jsonSchemaOf } from './json-schema.js';
|
|
4
|
+
import { SECURED } from './auth/provide-auth.js';
|
|
5
|
+
import { parsePattern } from './router.js';
|
|
6
|
+
import type {
|
|
7
|
+
GroupDefinition,
|
|
8
|
+
HttpMethod,
|
|
9
|
+
Middleware,
|
|
10
|
+
RouteDefinition,
|
|
11
|
+
RouteDocs,
|
|
12
|
+
RouteNode,
|
|
13
|
+
} from './routes.js';
|
|
14
|
+
import { compileSerializer, type Serializer } from './serializer.js';
|
|
15
|
+
import type { WebSocketHandlers } from './websocket.js';
|
|
16
|
+
|
|
17
|
+
type Schema = StandardSchemaV1;
|
|
18
|
+
|
|
19
|
+
/** A level of the path that declared a params schema. */
|
|
20
|
+
export interface ParamLevel {
|
|
21
|
+
/** The params introduced by this level's path segment. */
|
|
22
|
+
readonly names: readonly string[];
|
|
23
|
+
readonly schema: Schema;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface CompiledRoute {
|
|
27
|
+
readonly method: HttpMethod;
|
|
28
|
+
/** Full path pattern, such as `/api/users/:userId`. */
|
|
29
|
+
readonly path: string;
|
|
30
|
+
/** Param names in the order the router returns their values. */
|
|
31
|
+
readonly paramNames: readonly string[];
|
|
32
|
+
readonly paramLevels: readonly ParamLevel[];
|
|
33
|
+
readonly query: Schema | undefined;
|
|
34
|
+
readonly body: Schema | undefined;
|
|
35
|
+
/** Response schemas by status code. */
|
|
36
|
+
readonly responses: ReadonlyMap<number, Schema>;
|
|
37
|
+
readonly middleware: readonly Middleware[];
|
|
38
|
+
readonly providers: readonly Provider[];
|
|
39
|
+
readonly handler: RouteDefinition['options']['handler'];
|
|
40
|
+
readonly docs: RouteDocs & {
|
|
41
|
+
readonly tags: readonly string[];
|
|
42
|
+
/** Whether middleware on the route requires authentication. */
|
|
43
|
+
readonly secured: boolean;
|
|
44
|
+
};
|
|
45
|
+
/** Compiled JSON serializers by status code. */
|
|
46
|
+
readonly serializers: Map<number, Serializer>;
|
|
47
|
+
/** Handlers for WebSocket routes. */
|
|
48
|
+
readonly websocket: WebSocketHandlers<unknown> | undefined;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
interface Scope {
|
|
52
|
+
path: string;
|
|
53
|
+
paramLevels: ParamLevel[];
|
|
54
|
+
middleware: Middleware[];
|
|
55
|
+
providers: Provider[];
|
|
56
|
+
tags: string[];
|
|
57
|
+
hidden: boolean;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Flattens route trees into routes with their full paths and inherited settings. */
|
|
61
|
+
export function compileRoutes(
|
|
62
|
+
trees: readonly GroupDefinition[],
|
|
63
|
+
options: { prefix?: string; middleware?: readonly Middleware[] } = {},
|
|
64
|
+
): CompiledRoute[] {
|
|
65
|
+
const compiled: CompiledRoute[] = [];
|
|
66
|
+
const root: Scope = {
|
|
67
|
+
path: normalizePath(options.prefix ?? '/'),
|
|
68
|
+
paramLevels: [],
|
|
69
|
+
middleware: [...(options.middleware ?? [])],
|
|
70
|
+
providers: [],
|
|
71
|
+
tags: [],
|
|
72
|
+
hidden: false,
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
for (const tree of trees) {
|
|
76
|
+
visit(tree, root, compiled);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
return compiled;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function visit(node: RouteNode, scope: Scope, out: CompiledRoute[]): void {
|
|
83
|
+
const path = joinPaths(scope.path, node.path);
|
|
84
|
+
const levels = [...scope.paramLevels];
|
|
85
|
+
const paramsSchema = node.options.params as Schema | undefined;
|
|
86
|
+
|
|
87
|
+
if (paramsSchema !== undefined) {
|
|
88
|
+
const names = parsePattern(normalizePath(node.path))
|
|
89
|
+
.filter((segment) => segment.kind !== 'static')
|
|
90
|
+
.map((segment) => segment.value);
|
|
91
|
+
if (names.length === 0) {
|
|
92
|
+
throw new Error(
|
|
93
|
+
`"${path}" declares a params schema but its own path "${node.path}" has no parameters.`,
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
levels.push({ names, schema: paramsSchema });
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const middleware = [...scope.middleware, ...(node.options.middleware ?? [])];
|
|
100
|
+
const providers = [...scope.providers, ...(node.options.providers ?? [])];
|
|
101
|
+
const tags = [...scope.tags, ...(node.options.tags ?? [])];
|
|
102
|
+
const hidden = scope.hidden || node.options.hidden === true;
|
|
103
|
+
|
|
104
|
+
if (node.kind === 'group') {
|
|
105
|
+
const child: Scope = {
|
|
106
|
+
path,
|
|
107
|
+
paramLevels: levels,
|
|
108
|
+
middleware,
|
|
109
|
+
providers,
|
|
110
|
+
tags,
|
|
111
|
+
hidden,
|
|
112
|
+
};
|
|
113
|
+
for (const childNode of node.children) {
|
|
114
|
+
visit(childNode, child, out);
|
|
115
|
+
}
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const { options } = node;
|
|
120
|
+
const responses = responseSchemas(options.response);
|
|
121
|
+
out.push({
|
|
122
|
+
method: node.method,
|
|
123
|
+
path,
|
|
124
|
+
paramNames: parsePattern(path)
|
|
125
|
+
.filter((segment) => segment.kind !== 'static')
|
|
126
|
+
.map((segment) => segment.value),
|
|
127
|
+
paramLevels: levels,
|
|
128
|
+
query: options.query as Schema | undefined,
|
|
129
|
+
body: options.body as Schema | undefined,
|
|
130
|
+
responses,
|
|
131
|
+
middleware,
|
|
132
|
+
providers,
|
|
133
|
+
handler: options.handler,
|
|
134
|
+
docs: {
|
|
135
|
+
summary: options.summary,
|
|
136
|
+
description: options.description,
|
|
137
|
+
operationId: options.operationId,
|
|
138
|
+
deprecated: options.deprecated,
|
|
139
|
+
hidden,
|
|
140
|
+
tags: [...new Set(tags)],
|
|
141
|
+
secured: middleware.some((entry) => SECURED in entry),
|
|
142
|
+
},
|
|
143
|
+
serializers: serializersFor(responses),
|
|
144
|
+
websocket: options.websocket,
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Serializers for response schemas that can be expressed as JSON Schema. */
|
|
149
|
+
function serializersFor(
|
|
150
|
+
responses: Map<number, Schema>,
|
|
151
|
+
): Map<number, Serializer> {
|
|
152
|
+
const serializers = new Map<number, Serializer>();
|
|
153
|
+
for (const [status, schema] of responses) {
|
|
154
|
+
const json = jsonSchemaOf(schema, 'output');
|
|
155
|
+
if (json !== undefined) {
|
|
156
|
+
serializers.set(status, compileSerializer(json));
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return serializers;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function responseSchemas(response: unknown): Map<number, Schema> {
|
|
163
|
+
const result = new Map<number, Schema>();
|
|
164
|
+
if (response === undefined) {
|
|
165
|
+
return result;
|
|
166
|
+
}
|
|
167
|
+
if (isSchema(response)) {
|
|
168
|
+
result.set(200, response);
|
|
169
|
+
return result;
|
|
170
|
+
}
|
|
171
|
+
for (const [status, schema] of Object.entries(
|
|
172
|
+
response as Record<string, Schema>,
|
|
173
|
+
)) {
|
|
174
|
+
const code = Number(status);
|
|
175
|
+
if (!Number.isInteger(code) || code < 100 || code > 599) {
|
|
176
|
+
throw new Error(`Invalid response status "${status}".`);
|
|
177
|
+
}
|
|
178
|
+
result.set(code, schema);
|
|
179
|
+
}
|
|
180
|
+
return result;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export function isSchema(value: unknown): value is Schema {
|
|
184
|
+
return (
|
|
185
|
+
typeof value === 'object' &&
|
|
186
|
+
value !== null &&
|
|
187
|
+
'~standard' in value &&
|
|
188
|
+
typeof (value as Schema)['~standard'].validate === 'function'
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Ensures a leading slash and no trailing slash (except for the root). */
|
|
193
|
+
export function normalizePath(path: string): string {
|
|
194
|
+
const trimmed = path.replace(/\/+$/, '');
|
|
195
|
+
if (trimmed === '') {
|
|
196
|
+
return '/';
|
|
197
|
+
}
|
|
198
|
+
return trimmed.startsWith('/') ? trimmed : `/${trimmed}`;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export function joinPaths(base: string, path: string): string {
|
|
202
|
+
const joined = `${normalizePath(base)}/${normalizePath(path)}`.replace(
|
|
203
|
+
/\/{2,}/g,
|
|
204
|
+
'/',
|
|
205
|
+
);
|
|
206
|
+
return normalizePath(joined);
|
|
207
|
+
}
|