@scalar/mock-server 0.17.5 → 0.18.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/CHANGELOG.md +21 -0
- package/dist/create-asyncapi-mock-server.d.ts.map +1 -1
- package/dist/create-asyncapi-mock-server.js +8 -0
- package/dist/routes/mock-handler-response.d.ts.map +1 -1
- package/dist/routes/mock-handler-response.js +7 -5
- package/dist/routes/respond-with-authorize-page.d.ts +1 -1
- package/dist/routes/respond-with-authorize-page.d.ts.map +1 -1
- package/dist/routes/respond-with-authorize-page.js +9 -6
- package/dist/routes/respond-with-token.d.ts +1 -10
- package/dist/routes/respond-with-token.d.ts.map +1 -1
- package/dist/routes/respond-with-token.js +8 -5
- package/dist/transports/sse.d.ts.map +1 -1
- package/dist/transports/sse.js +17 -13
- package/dist/transports/types.d.ts +10 -0
- package/dist/transports/types.d.ts.map +1 -1
- package/dist/transports/websocket.d.ts.map +1 -1
- package/dist/transports/websocket.js +38 -30
- package/dist/utils/authenticate-asyncapi-channel.d.ts +9 -0
- package/dist/utils/authenticate-asyncapi-channel.d.ts.map +1 -0
- package/dist/utils/authenticate-asyncapi-channel.js +49 -0
- package/dist/utils/build-handler-context.d.ts.map +1 -1
- package/dist/utils/build-handler-context.js +6 -5
- package/dist/utils/deserialize-parameter.d.ts.map +1 -1
- package/dist/utils/deserialize-parameter.js +7 -2
- package/dist/utils/digest-authentication.d.ts +6 -0
- package/dist/utils/digest-authentication.d.ts.map +1 -0
- package/dist/utils/digest-authentication.js +35 -0
- package/dist/utils/handle-authentication.d.ts +14 -0
- package/dist/utils/handle-authentication.d.ts.map +1 -1
- package/dist/utils/handle-authentication.js +28 -14
- package/dist/utils/log-authentication-instructions.d.ts +3 -1
- package/dist/utils/log-authentication-instructions.d.ts.map +1 -1
- package/dist/utils/log-authentication-instructions.js +10 -2
- package/dist/utils/querystring-parameter.d.ts.map +1 -1
- package/dist/utils/querystring-parameter.js +13 -11
- package/dist/utils/resolve-channels.d.ts.map +1 -1
- package/dist/utils/resolve-channels.js +16 -1
- package/dist/utils/set-up-asyncapi-authentication-routes.d.ts +5 -0
- package/dist/utils/set-up-asyncapi-authentication-routes.d.ts.map +1 -0
- package/dist/utils/set-up-asyncapi-authentication-routes.js +49 -0
- package/dist/utils/set-up-authentication-routes.d.ts.map +1 -1
- package/dist/utils/set-up-authentication-routes.js +9 -18
- package/dist/utils/set-up-device-authorization.js +1 -1
- package/dist/utils/set-up-openid-connect.d.ts +4 -0
- package/dist/utils/set-up-openid-connect.d.ts.map +1 -0
- package/dist/utils/set-up-openid-connect.js +196 -0
- package/dist/utils/streaming-response.js +1 -1
- package/package.json +7 -7
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref';
|
|
2
2
|
import { getCookie } from 'hono/cookie';
|
|
3
|
+
import { DIGEST_CHALLENGE, isValidDigestAuth } from './digest-authentication.js';
|
|
3
4
|
/** Realm advertised in `WWW-Authenticate` challenges. */
|
|
4
5
|
const REALM = 'Scalar Mock Server';
|
|
5
6
|
/**
|
|
@@ -10,7 +11,7 @@ const REALM = 'Scalar Mock Server';
|
|
|
10
11
|
* well-formed `Basic <base64(user:password)>` value.
|
|
11
12
|
*/
|
|
12
13
|
function isValidBasicAuth(authHeader) {
|
|
13
|
-
if (!authHeader
|
|
14
|
+
if (!authHeader || !/^Basic /i.test(authHeader)) {
|
|
14
15
|
return false;
|
|
15
16
|
}
|
|
16
17
|
const encoded = authHeader.slice('Basic '.length).trim();
|
|
@@ -33,13 +34,13 @@ function isValidBasicAuth(authHeader) {
|
|
|
33
34
|
* token itself (signature, expiry, scopes) is out of scope for a mock server.
|
|
34
35
|
*/
|
|
35
36
|
function isValidBearerAuth(authHeader) {
|
|
36
|
-
if (!authHeader
|
|
37
|
+
if (!authHeader || !/^Bearer /i.test(authHeader)) {
|
|
37
38
|
return false;
|
|
38
39
|
}
|
|
39
40
|
return authHeader.slice('Bearer '.length).trim().length > 0;
|
|
40
41
|
}
|
|
41
42
|
/** Check whether a single security scheme is satisfied by the request. */
|
|
42
|
-
|
|
43
|
+
export const isSchemeSatisfied = (scheme, c) => {
|
|
43
44
|
switch (scheme.type) {
|
|
44
45
|
case 'http': {
|
|
45
46
|
const authHeader = c.req.header('Authorization');
|
|
@@ -49,20 +50,29 @@ function isSchemeSatisfied(scheme, c) {
|
|
|
49
50
|
if ('scheme' in scheme && scheme.scheme?.toLowerCase() === 'bearer') {
|
|
50
51
|
return isValidBearerAuth(authHeader);
|
|
51
52
|
}
|
|
53
|
+
if ('scheme' in scheme && scheme.scheme?.toLowerCase() === 'digest') {
|
|
54
|
+
return isValidDigestAuth(c);
|
|
55
|
+
}
|
|
52
56
|
return false;
|
|
53
57
|
}
|
|
58
|
+
case 'httpApiKey':
|
|
54
59
|
case 'apiKey': {
|
|
55
60
|
if (!('name' in scheme) || !scheme.name || !('in' in scheme)) {
|
|
56
61
|
return false;
|
|
57
62
|
}
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
63
|
+
if (scheme.in === 'header') {
|
|
64
|
+
return Boolean(c.req.header(scheme.name));
|
|
65
|
+
}
|
|
66
|
+
if (scheme.in === 'query') {
|
|
67
|
+
return Boolean(c.req.query(scheme.name));
|
|
68
|
+
}
|
|
69
|
+
return scheme.in === 'cookie' && Boolean(getCookie(c, scheme.name));
|
|
70
|
+
}
|
|
71
|
+
case 'mutualTLS':
|
|
72
|
+
case 'X509': {
|
|
73
|
+
// Only trust the TLS adapter's verified peer, never a client-supplied certificate header.
|
|
74
|
+
const socket = c.env?.incoming?.socket;
|
|
75
|
+
return (socket?.encrypted === true && socket.authorized === true && Boolean(socket.getPeerCertificate?.().raw?.length));
|
|
66
76
|
}
|
|
67
77
|
// OAuth 2.0 and OpenID Connect both carry a bearer token in the `Authorization` header.
|
|
68
78
|
case 'oauth2':
|
|
@@ -71,13 +81,13 @@ function isSchemeSatisfied(scheme, c) {
|
|
|
71
81
|
default:
|
|
72
82
|
return false;
|
|
73
83
|
}
|
|
74
|
-
}
|
|
84
|
+
};
|
|
75
85
|
/**
|
|
76
86
|
* Build the `WWW-Authenticate` challenge for a single security scheme.
|
|
77
87
|
*
|
|
78
88
|
* Returns `null` for schemes that do not map to an HTTP authentication challenge.
|
|
79
89
|
*/
|
|
80
|
-
|
|
90
|
+
export const getChallenge = (scheme) => {
|
|
81
91
|
switch (scheme.type) {
|
|
82
92
|
case 'http':
|
|
83
93
|
if ('scheme' in scheme && scheme.scheme?.toLowerCase() === 'basic') {
|
|
@@ -86,7 +96,11 @@ function getChallenge(scheme) {
|
|
|
86
96
|
if ('scheme' in scheme && scheme.scheme?.toLowerCase() === 'bearer') {
|
|
87
97
|
return `Bearer realm="${REALM}", error="invalid_token", error_description="The access token is invalid or has expired"`;
|
|
88
98
|
}
|
|
99
|
+
if ('scheme' in scheme && scheme.scheme?.toLowerCase() === 'digest') {
|
|
100
|
+
return DIGEST_CHALLENGE;
|
|
101
|
+
}
|
|
89
102
|
return null;
|
|
103
|
+
case 'httpApiKey':
|
|
90
104
|
case 'apiKey':
|
|
91
105
|
if ('name' in scheme && scheme.name) {
|
|
92
106
|
return `ApiKey realm="${REALM}", error="invalid_token", error_description="Invalid or missing API key", name="${scheme.name}"`;
|
|
@@ -98,7 +112,7 @@ function getChallenge(scheme) {
|
|
|
98
112
|
default:
|
|
99
113
|
return null;
|
|
100
114
|
}
|
|
101
|
-
}
|
|
115
|
+
};
|
|
102
116
|
/** Resolve all schemes referenced by a single security requirement object. */
|
|
103
117
|
function resolveSchemes(requirement, schema) {
|
|
104
118
|
return Object.keys(requirement)
|
|
@@ -7,5 +7,7 @@ import type { MockServerLogger } from '../types.js';
|
|
|
7
7
|
* security schemes the mock server cannot handle are printed unconditionally, so a silenced startup
|
|
8
8
|
* still surfaces schemes that will not work.
|
|
9
9
|
*/
|
|
10
|
-
export declare function logAuthenticationInstructions(securitySchemes: Record<string, OpenAPIV3_2.SecuritySchemeObject
|
|
10
|
+
export declare function logAuthenticationInstructions(securitySchemes: Record<string, OpenAPIV3_2.SecuritySchemeObject | {
|
|
11
|
+
type: 'mutualTLS';
|
|
12
|
+
}>, log?: MockServerLogger): void;
|
|
11
13
|
//# sourceMappingURL=log-authentication-instructions.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"log-authentication-instructions.d.ts","sourceRoot":"","sources":["../../src/utils/log-authentication-instructions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAA;AAGxD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAI/C;;;;;;GAMG;AACH,wBAAgB,6BAA6B,CAC3C,eAAe,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,oBAAoB,CAAC,
|
|
1
|
+
{"version":3,"file":"log-authentication-instructions.d.ts","sourceRoot":"","sources":["../../src/utils/log-authentication-instructions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAA;AAGxD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAI/C;;;;;;GAMG;AACH,wBAAgB,6BAA6B,CAC3C,eAAe,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,oBAAoB,GAAG;IAAE,IAAI,EAAE,WAAW,CAAA;CAAE,CAAC,EACzF,GAAG,GAAE,gBAA8C,QAmJpD"}
|
|
@@ -47,24 +47,32 @@ export function logAuthenticationInstructions(securitySchemes, log = (line) => c
|
|
|
47
47
|
}
|
|
48
48
|
break;
|
|
49
49
|
case 'http':
|
|
50
|
-
if (scheme.scheme === 'basic') {
|
|
50
|
+
if (scheme.scheme?.toLowerCase() === 'basic') {
|
|
51
51
|
log('✅ HTTP Basic Authentication');
|
|
52
52
|
log(' Use an Authorization header with any credentials ("username:password" in base64):');
|
|
53
53
|
log('');
|
|
54
54
|
log(' Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=');
|
|
55
55
|
log('');
|
|
56
56
|
}
|
|
57
|
-
else if (scheme.scheme === 'bearer') {
|
|
57
|
+
else if (scheme.scheme?.toLowerCase() === 'bearer') {
|
|
58
58
|
log('✅ Bearer Token Authentication');
|
|
59
59
|
log(' Use an Authorization header with any bearer token');
|
|
60
60
|
log('');
|
|
61
61
|
log(' Authorization: Bearer YOUR_TOKEN_HERE');
|
|
62
62
|
log('');
|
|
63
63
|
}
|
|
64
|
+
else if (scheme.scheme?.toLowerCase() === 'digest') {
|
|
65
|
+
log('✅ HTTP Digest Authentication');
|
|
66
|
+
log(' Answer the MD5/qop=auth challenge with any username and password; the mock checks credential shape.');
|
|
67
|
+
}
|
|
64
68
|
else {
|
|
65
69
|
console.error('❌ Unknown Security Scheme:', scheme);
|
|
66
70
|
}
|
|
67
71
|
break;
|
|
72
|
+
case 'mutualTLS':
|
|
73
|
+
log('✅ Mutual TLS Authentication');
|
|
74
|
+
log(' Use a trusted client certificate with a Node HTTPS server configured with requestCert and ca.');
|
|
75
|
+
break;
|
|
68
76
|
case 'oauth2':
|
|
69
77
|
if ('oauth2MetadataUrl' in scheme &&
|
|
70
78
|
typeof scheme.oauth2MetadataUrl === 'string' &&
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"querystring-parameter.d.ts","sourceRoot":"","sources":["../../src/utils/querystring-parameter.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAA;AAaxD;;;GAGG;AACH,eAAO,MAAM,wBAAwB,GACnC,YAAY,WAAW,CAAC,eAAe,EACvC,iBAAiB,WAAW,CAAC,cAAc,CAAC,YAAY,CAAC,KACxD,WAAW,CAAC,eAAe,GAAG,SAMwB,CAAA;AAkBzD,6GAA6G;AAC7G,eAAO,MAAM,wBAAwB,GACnC,WAAW,WAAW,CAAC,eAAe,GAAG,SAAS,KACjD,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAkC5B,CAAA;AAED,gIAAgI;AAChI,eAAO,MAAM,yBAAyB,GAAI,KAAK,MAAM,EAAE,WAAW,WAAW,CAAC,eAAe,KAAG,
|
|
1
|
+
{"version":3,"file":"querystring-parameter.d.ts","sourceRoot":"","sources":["../../src/utils/querystring-parameter.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAA;AAaxD;;;GAGG;AACH,eAAO,MAAM,wBAAwB,GACnC,YAAY,WAAW,CAAC,eAAe,EACvC,iBAAiB,WAAW,CAAC,cAAc,CAAC,YAAY,CAAC,KACxD,WAAW,CAAC,eAAe,GAAG,SAMwB,CAAA;AAkBzD,6GAA6G;AAC7G,eAAO,MAAM,wBAAwB,GACnC,WAAW,WAAW,CAAC,eAAe,GAAG,SAAS,KACjD,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAkC5B,CAAA;AAED,gIAAgI;AAChI,eAAO,MAAM,yBAAyB,GAAI,KAAK,MAAM,EAAE,WAAW,WAAW,CAAC,eAAe,KAAG,OA2E/F,CAAA"}
|
|
@@ -91,8 +91,9 @@ export const parseQuerystringParameter = (url, parameter) => {
|
|
|
91
91
|
const styleBased = encoding?.style !== undefined || encoding?.explode !== undefined || encoding?.allowReserved !== undefined;
|
|
92
92
|
if (styleBased) {
|
|
93
93
|
const { style, explode } = resolveSerialization('query', encoding?.style, encoding?.explode);
|
|
94
|
-
|
|
95
|
-
|
|
94
|
+
let value = single;
|
|
95
|
+
if (isObjectSchema(property)) {
|
|
96
|
+
value = deserializeObjectParameter({
|
|
96
97
|
style,
|
|
97
98
|
explode,
|
|
98
99
|
single,
|
|
@@ -100,15 +101,16 @@ export const parseQuerystringParameter = (url, parameter) => {
|
|
|
100
101
|
name,
|
|
101
102
|
propertyNames: getObjectPropertyNames(property),
|
|
102
103
|
reservedKeys: new Set(Object.keys(properties)),
|
|
103
|
-
})
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
else if (isArraySchema(property)) {
|
|
107
|
+
value = deserializeArrayParameter({
|
|
108
|
+
style,
|
|
109
|
+
explode,
|
|
110
|
+
single,
|
|
111
|
+
multi: params.has(name) ? params.getAll(name) : undefined,
|
|
112
|
+
});
|
|
113
|
+
}
|
|
112
114
|
if (value !== undefined) {
|
|
113
115
|
if (isObjectSchema(property) &&
|
|
114
116
|
(style === 'deepObject' || (style === 'form' && explode)) &&
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolve-channels.d.ts","sourceRoot":"","sources":["../../src/utils/resolve-channels.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAyB,MAAM,4BAA4B,CAAA;AAWzF,OAAO,KAAK,EAAE,eAAe,EAAsC,MAAM,oBAAoB,CAAA;AAkE7F;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,gBAAgB,GAAG,eAAe,EAAE,
|
|
1
|
+
{"version":3,"file":"resolve-channels.d.ts","sourceRoot":"","sources":["../../src/utils/resolve-channels.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAyB,MAAM,4BAA4B,CAAA;AAWzF,OAAO,KAAK,EAAE,eAAe,EAAsC,MAAM,oBAAoB,CAAA;AAkE7F;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,gBAAgB,GAAG,eAAe,EAAE,CA6D7E"}
|
|
@@ -84,10 +84,25 @@ export function resolveChannels(document) {
|
|
|
84
84
|
.map((ref) => messagesByKey.get(getNameFromRef(ref, ['channels', channelName, 'messages']) ?? ''))
|
|
85
85
|
.filter((message) => message !== undefined)
|
|
86
86
|
: messages;
|
|
87
|
-
return {
|
|
87
|
+
return {
|
|
88
|
+
id: operationName,
|
|
89
|
+
action,
|
|
90
|
+
messages: operationMessages,
|
|
91
|
+
...(operation.security ? { security: operation.security.map((scheme) => getResolvedRef(scheme)) } : {}),
|
|
92
|
+
};
|
|
88
93
|
});
|
|
94
|
+
const servers = getAsyncApiServers(document, { channel, webSocketOnly: false });
|
|
95
|
+
const security = servers.map(({ protocol, server }) => ({
|
|
96
|
+
protocol,
|
|
97
|
+
schemes: (server.security ?? []).map((scheme) => getResolvedRef(scheme)),
|
|
98
|
+
}));
|
|
99
|
+
// A channel restricted to unresolved servers must not accidentally become public.
|
|
100
|
+
if (channel.servers?.length && servers.length === 0) {
|
|
101
|
+
security.push({ protocol: '', schemes: [undefined] });
|
|
102
|
+
}
|
|
89
103
|
return [
|
|
90
104
|
{
|
|
105
|
+
...(security.some(({ schemes }) => schemes.length) ? { security } : {}),
|
|
91
106
|
id: channelName,
|
|
92
107
|
address: channelAddress,
|
|
93
108
|
route: honoRouteFromPath(`/${channelAddress.replace(/^\//, '')}`),
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { AsyncApiDocument } from '@scalar/types/asyncapi/3.1';
|
|
2
|
+
import type { Hono } from 'hono';
|
|
3
|
+
/** Adapt AsyncAPI OAuth and OpenID Connect schemes to the shared mock authorization and token handlers. */
|
|
4
|
+
export declare const setUpAsyncApiAuthenticationRoutes: (app: Hono, document: AsyncApiDocument) => void;
|
|
5
|
+
//# sourceMappingURL=set-up-asyncapi-authentication-routes.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"set-up-asyncapi-authentication-routes.d.ts","sourceRoot":"","sources":["../../src/utils/set-up-asyncapi-authentication-routes.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAA;AAElE,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAA;AAIhC,2GAA2G;AAC3G,eAAO,MAAM,iCAAiC,GAAI,KAAK,IAAI,EAAE,UAAU,gBAAgB,KAAG,IAgDzF,CAAA"}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref';
|
|
2
|
+
import { setUpAuthenticationRoutes } from './set-up-authentication-routes.js';
|
|
3
|
+
/** Adapt AsyncAPI OAuth and OpenID Connect schemes to the shared mock authorization and token handlers. */
|
|
4
|
+
export const setUpAsyncApiAuthenticationRoutes = (app, document) => {
|
|
5
|
+
const components = getResolvedRef(document.components);
|
|
6
|
+
// AsyncAPI also permits inline schemes on servers, operations, and operation traits.
|
|
7
|
+
const schemes = [
|
|
8
|
+
...Object.values(components?.securitySchemes ?? {}),
|
|
9
|
+
...Object.values(document.servers ?? {}).flatMap((server) => getResolvedRef(server)?.security ?? []),
|
|
10
|
+
...Object.values(document.operations ?? {}).flatMap((rawOperation) => {
|
|
11
|
+
const operation = getResolvedRef(rawOperation);
|
|
12
|
+
return [
|
|
13
|
+
...(operation?.security ?? []),
|
|
14
|
+
...(operation?.traits ?? []).flatMap((trait) => getResolvedRef(trait)?.security ?? []),
|
|
15
|
+
];
|
|
16
|
+
}),
|
|
17
|
+
];
|
|
18
|
+
const securitySchemes = {};
|
|
19
|
+
for (const [index, rawScheme] of schemes.entries()) {
|
|
20
|
+
const scheme = getResolvedRef(rawScheme);
|
|
21
|
+
if (scheme?.type === 'openIdConnect') {
|
|
22
|
+
securitySchemes[index] = { type: 'openIdConnect', openIdConnectUrl: scheme.openIdConnectUrl };
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
if (scheme?.type !== 'oauth2') {
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
const sourceFlows = getResolvedRef(scheme.flows);
|
|
29
|
+
const flows = {};
|
|
30
|
+
for (const name of ['authorizationCode', 'implicit', 'password', 'clientCredentials']) {
|
|
31
|
+
const flow = getResolvedRef(sourceFlows?.[name]);
|
|
32
|
+
if (flow) {
|
|
33
|
+
flows[name] = {
|
|
34
|
+
authorizationUrl: flow.authorizationUrl,
|
|
35
|
+
tokenUrl: flow.tokenUrl,
|
|
36
|
+
refreshUrl: flow.refreshUrl,
|
|
37
|
+
scopes: flow.availableScopes,
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
securitySchemes[index] = { type: 'oauth2', flows };
|
|
42
|
+
}
|
|
43
|
+
// Only OAuth and OpenID Connect schemes are adapted; broker authentication has no OpenAPI equivalent.
|
|
44
|
+
setUpAuthenticationRoutes(app, {
|
|
45
|
+
openapi: '3.1.0',
|
|
46
|
+
info: { title: document.info.title, version: document.info.version },
|
|
47
|
+
components: { securitySchemes },
|
|
48
|
+
});
|
|
49
|
+
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"set-up-authentication-routes.d.ts","sourceRoot":"","sources":["../../src/utils/set-up-authentication-routes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAA0B,MAAM,uBAAuB,CAAA;AAE5E,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAA;
|
|
1
|
+
{"version":3,"file":"set-up-authentication-routes.d.ts","sourceRoot":"","sources":["../../src/utils/set-up-authentication-routes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAA0B,MAAM,uBAAuB,CAAA;AAE5E,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAA;AAUhC;;GAEG;AACH,wBAAgB,yBAAyB,CAAC,GAAG,EAAE,IAAI,EAAE,MAAM,CAAC,EAAE,OAAO,CAAC,QAAQ,QA0G7E"}
|
|
@@ -4,11 +4,17 @@ import { respondWithToken } from '../routes/respond-with-token.js';
|
|
|
4
4
|
import { getOAuth2Metadata } from './get-oauth2-metadata.js';
|
|
5
5
|
import { getOpenAuthTokenUrls, getPathFromUrl } from './get-open-auth-token-urls.js';
|
|
6
6
|
import { setUpDeviceAuthorization } from './set-up-device-authorization.js';
|
|
7
|
+
import { setUpOpenIdConnect } from './set-up-openid-connect.js';
|
|
7
8
|
/**
|
|
8
9
|
* Helper function to set up authentication routes for OAuth 2.0 flows
|
|
9
10
|
*/
|
|
10
11
|
export function setUpAuthenticationRoutes(app, schema) {
|
|
11
12
|
const securitySchemes = schema?.components?.securitySchemes || {};
|
|
13
|
+
const discoveryUrls = Object.values(securitySchemes).flatMap((rawScheme) => {
|
|
14
|
+
const scheme = getResolvedRef(rawScheme);
|
|
15
|
+
return scheme?.type === 'openIdConnect' && scheme.openIdConnectUrl ? [scheme.openIdConnectUrl] : [];
|
|
16
|
+
});
|
|
17
|
+
setUpOpenIdConnect(app, discoveryUrls, schema?.info?.title ?? '', Object.values(securitySchemes).some((scheme) => getResolvedRef(scheme)?.type === 'oauth2'));
|
|
12
18
|
setUpDeviceAuthorization(app, schema);
|
|
13
19
|
// Set up authentication routes for OAuth 2.0 flows
|
|
14
20
|
getOpenAuthTokenUrls(schema).forEach((tokenUrl) => {
|
|
@@ -68,25 +74,10 @@ export function setUpAuthenticationRoutes(app, schema) {
|
|
|
68
74
|
}
|
|
69
75
|
}
|
|
70
76
|
else if (scheme.type === 'openIdConnect') {
|
|
71
|
-
//
|
|
77
|
+
// Non-OIDC OAuth requests still use the permissive shared mock handlers.
|
|
72
78
|
if (scheme.openIdConnectUrl) {
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
app.get(configPath, (c) => {
|
|
76
|
-
return c.json({
|
|
77
|
-
issuer: 'https://example.com',
|
|
78
|
-
authorization_endpoint: '/oauth/authorize',
|
|
79
|
-
token_endpoint: '/oauth/token',
|
|
80
|
-
response_types_supported: ['code', 'token', 'id_token'],
|
|
81
|
-
subject_types_supported: ['public'],
|
|
82
|
-
id_token_signing_alg_values_supported: ['RS256'],
|
|
83
|
-
});
|
|
84
|
-
});
|
|
85
|
-
// Add standard endpoints
|
|
86
|
-
const authorizeRoute = '/oauth/authorize';
|
|
87
|
-
const tokenRoute = '/oauth/token';
|
|
88
|
-
authorizeUrls.add(getPathFromUrl(authorizeRoute));
|
|
89
|
-
tokenUrls.add(getPathFromUrl(tokenRoute));
|
|
79
|
+
authorizeUrls.add('/oauth/authorize');
|
|
80
|
+
tokenUrls.add('/oauth/token');
|
|
90
81
|
}
|
|
91
82
|
}
|
|
92
83
|
});
|
|
@@ -6,7 +6,7 @@ const getClientId = (clientId, authorization) => {
|
|
|
6
6
|
if (typeof clientId === 'string') {
|
|
7
7
|
return clientId;
|
|
8
8
|
}
|
|
9
|
-
if (!authorization
|
|
9
|
+
if (!authorization || !/^Basic /i.test(authorization)) {
|
|
10
10
|
return '';
|
|
11
11
|
}
|
|
12
12
|
const credentials = Buffer.from(authorization.slice(6), 'base64').toString();
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { Hono } from 'hono';
|
|
2
|
+
/** Serve a small OIDC code-flow provider with verifiable ID tokens and a stable mock identity. */
|
|
3
|
+
export declare const setUpOpenIdConnect: (app: Hono, discoveryUrls: string[], title: string, allowOAuthFallback?: boolean) => void;
|
|
4
|
+
//# sourceMappingURL=set-up-openid-connect.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"set-up-openid-connect.d.ts","sourceRoot":"","sources":["../../src/utils/set-up-openid-connect.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAW,IAAI,EAAE,MAAM,MAAM,CAAA;AA0CzC,kGAAkG;AAClG,eAAO,MAAM,kBAAkB,GAC7B,KAAK,IAAI,EACT,eAAe,MAAM,EAAE,EACvB,OAAO,MAAM,EACb,4BAA0B,KACzB,IA+LF,CAAA"}
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import { respondWithAuthorizePage } from '../routes/respond-with-authorize-page.js';
|
|
2
|
+
import { getPathFromUrl } from './get-open-auth-token-urls.js';
|
|
3
|
+
const SUBJECT = 'scalar-mock-user';
|
|
4
|
+
const encode = (bytes) => btoa(String.fromCharCode(...bytes))
|
|
5
|
+
.replace(/\+/g, '-')
|
|
6
|
+
.replace(/\//g, '_')
|
|
7
|
+
.replace(/=+$/, '');
|
|
8
|
+
const encodeJson = (value) => encode(new TextEncoder().encode(JSON.stringify(value)));
|
|
9
|
+
const now = () => Math.floor(Date.now() / 1000);
|
|
10
|
+
/** Expiring, bounded state keeps this development provider safe to leave running. */
|
|
11
|
+
const remember = (store, key, value) => {
|
|
12
|
+
for (const [existing, authorization] of store) {
|
|
13
|
+
if (authorization.expiresAt <= now()) {
|
|
14
|
+
store.delete(existing);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
if (store.size >= 1000) {
|
|
18
|
+
const oldest = store.keys().next().value;
|
|
19
|
+
if (oldest) {
|
|
20
|
+
store.delete(oldest);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
store.set(key, value);
|
|
24
|
+
};
|
|
25
|
+
/** Serve a small OIDC code-flow provider with verifiable ID tokens and a stable mock identity. */
|
|
26
|
+
export const setUpOpenIdConnect = (app, discoveryUrls, title, allowOAuthFallback = false) => {
|
|
27
|
+
if (discoveryUrls.length === 0) {
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
// Workers forbid random number generation until a request handler runs.
|
|
31
|
+
let keyId;
|
|
32
|
+
const getKeyId = () => (keyId ??= crypto.randomUUID());
|
|
33
|
+
const codes = new Map();
|
|
34
|
+
const refreshTokens = new Map();
|
|
35
|
+
const accessTokens = new Map();
|
|
36
|
+
let keys;
|
|
37
|
+
const getKeys = () => {
|
|
38
|
+
keys ??= crypto.subtle.generateKey({ name: 'RSASSA-PKCS1-v1_5', modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256' }, true, ['sign', 'verify']);
|
|
39
|
+
return keys;
|
|
40
|
+
};
|
|
41
|
+
const tokenError = (c, error, description) => {
|
|
42
|
+
c.header('Cache-Control', 'no-store');
|
|
43
|
+
return c.json({ error, error_description: description }, 400);
|
|
44
|
+
};
|
|
45
|
+
for (const path of new Set(discoveryUrls.map((url) => getPathFromUrl(url, { preserveTrailingSlash: true })))) {
|
|
46
|
+
app.get(path, (c) => {
|
|
47
|
+
const origin = new URL(c.req.url).origin;
|
|
48
|
+
return c.json({
|
|
49
|
+
issuer: origin,
|
|
50
|
+
authorization_endpoint: `${origin}/oauth/authorize`,
|
|
51
|
+
token_endpoint: `${origin}/oauth/token`,
|
|
52
|
+
jwks_uri: `${origin}/oauth/jwks`,
|
|
53
|
+
userinfo_endpoint: `${origin}/oauth/userinfo`,
|
|
54
|
+
response_types_supported: ['code'],
|
|
55
|
+
grant_types_supported: ['authorization_code', 'refresh_token'],
|
|
56
|
+
subject_types_supported: ['public'],
|
|
57
|
+
id_token_signing_alg_values_supported: ['RS256'],
|
|
58
|
+
token_endpoint_auth_methods_supported: ['none'],
|
|
59
|
+
code_challenge_methods_supported: ['S256'],
|
|
60
|
+
scopes_supported: ['openid', 'profile', 'email'],
|
|
61
|
+
});
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
app.get('/oauth/jwks', async (c) => {
|
|
65
|
+
const key = await crypto.subtle.exportKey('jwk', (await getKeys()).publicKey);
|
|
66
|
+
return c.json({ keys: [{ ...key, kid: getKeyId(), use: 'sig', alg: 'RS256' }] });
|
|
67
|
+
});
|
|
68
|
+
app.get('/oauth/authorize', (c, next) => {
|
|
69
|
+
const scope = c.req.query('scope') ?? '';
|
|
70
|
+
if (!scope.split(/\s+/).includes('openid')) {
|
|
71
|
+
return next();
|
|
72
|
+
}
|
|
73
|
+
const clientId = c.req.query('client_id');
|
|
74
|
+
const redirectUri = c.req.query('redirect_uri');
|
|
75
|
+
if (!clientId || !redirectUri || c.req.query('response_type') !== 'code') {
|
|
76
|
+
return tokenError(c, 'invalid_request', 'OpenID Connect requires client_id, redirect_uri, and response_type=code');
|
|
77
|
+
}
|
|
78
|
+
try {
|
|
79
|
+
if (!['http:', 'https:'].includes(new URL(redirectUri).protocol)) {
|
|
80
|
+
throw new Error('Invalid redirect');
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
return tokenError(c, 'invalid_request', 'redirect_uri must be an HTTP or HTTPS URL');
|
|
85
|
+
}
|
|
86
|
+
const codeChallenge = c.req.query('code_challenge');
|
|
87
|
+
if (codeChallenge && (c.req.query('code_challenge_method') !== 'S256' || !/^[\w-]{43}$/.test(codeChallenge))) {
|
|
88
|
+
return tokenError(c, 'invalid_request', 'Only S256 PKCE challenges are supported');
|
|
89
|
+
}
|
|
90
|
+
const code = `oidc-code-${crypto.randomUUID()}`;
|
|
91
|
+
remember(codes, code, {
|
|
92
|
+
clientId,
|
|
93
|
+
redirectUri,
|
|
94
|
+
scope,
|
|
95
|
+
nonce: c.req.query('nonce'),
|
|
96
|
+
codeChallenge,
|
|
97
|
+
issuer: new URL(c.req.url).origin,
|
|
98
|
+
expiresAt: now() + 300,
|
|
99
|
+
});
|
|
100
|
+
return respondWithAuthorizePage(c, title, code);
|
|
101
|
+
});
|
|
102
|
+
app.post('/oauth/token', async (c, next) => {
|
|
103
|
+
const body = await c.req.parseBody();
|
|
104
|
+
const parameter = (name) => typeof body[name] === 'string' ? body[name] : c.req.query(name);
|
|
105
|
+
const code = parameter('code') ?? '';
|
|
106
|
+
const refresh = parameter('refresh_token') ?? '';
|
|
107
|
+
const scope = parameter('scope');
|
|
108
|
+
const authorization = codes.get(code) ?? refreshTokens.get(refresh);
|
|
109
|
+
// Ordinary OAuth mocks share this path. Claim only OIDC requests or tokens this provider issued.
|
|
110
|
+
if (allowOAuthFallback &&
|
|
111
|
+
!authorization &&
|
|
112
|
+
!code.startsWith('oidc-code-') &&
|
|
113
|
+
!refresh.startsWith('oidc-refresh-') &&
|
|
114
|
+
!scope?.split(/\s+/).includes('openid')) {
|
|
115
|
+
return next();
|
|
116
|
+
}
|
|
117
|
+
const grant = parameter('grant_type');
|
|
118
|
+
if (grant !== 'authorization_code' && grant !== 'refresh_token') {
|
|
119
|
+
return tokenError(c, 'unsupported_grant_type', 'OpenID Connect supports authorization_code and refresh_token');
|
|
120
|
+
}
|
|
121
|
+
const source = grant === 'authorization_code' ? codes : refreshTokens;
|
|
122
|
+
const credential = grant === 'authorization_code' ? code : refresh;
|
|
123
|
+
const session = source.get(credential);
|
|
124
|
+
if (!session ||
|
|
125
|
+
session.expiresAt <= now() ||
|
|
126
|
+
session.issuer !== new URL(c.req.url).origin ||
|
|
127
|
+
parameter('client_id') !== session.clientId) {
|
|
128
|
+
return tokenError(c, 'invalid_grant', 'Invalid or expired authorization for this client');
|
|
129
|
+
}
|
|
130
|
+
if (grant === 'authorization_code') {
|
|
131
|
+
if (parameter('redirect_uri') !== session.redirectUri) {
|
|
132
|
+
return tokenError(c, 'invalid_grant', 'redirect_uri does not match');
|
|
133
|
+
}
|
|
134
|
+
if (session.codeChallenge) {
|
|
135
|
+
const verifier = parameter('code_verifier') ?? '';
|
|
136
|
+
const challenge = encode(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))));
|
|
137
|
+
if (!/^[\w.~-]{43,128}$/.test(verifier) || challenge !== session.codeChallenge) {
|
|
138
|
+
return tokenError(c, 'invalid_grant', 'Invalid PKCE verifier');
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
const effectiveScope = scope ?? session.scope;
|
|
143
|
+
if (effectiveScope.split(/\s+/).some((value) => !session.scope.split(/\s+/).includes(value))) {
|
|
144
|
+
return tokenError(c, 'invalid_scope', 'Requested scope exceeds the authorization');
|
|
145
|
+
}
|
|
146
|
+
// PKCE hashing yields; another exchange may consume this code while it runs.
|
|
147
|
+
if (source.get(credential) !== session) {
|
|
148
|
+
return tokenError(c, 'invalid_grant', 'Authorization has already been used');
|
|
149
|
+
}
|
|
150
|
+
source.delete(credential);
|
|
151
|
+
const issuedAt = now();
|
|
152
|
+
const header = encodeJson({ alg: 'RS256', typ: 'JWT', kid: getKeyId() });
|
|
153
|
+
const claims = encodeJson({
|
|
154
|
+
iss: session.issuer,
|
|
155
|
+
sub: SUBJECT,
|
|
156
|
+
aud: session.clientId,
|
|
157
|
+
iat: issuedAt,
|
|
158
|
+
exp: issuedAt + 3600,
|
|
159
|
+
...(session.nonce ? { nonce: session.nonce } : {}),
|
|
160
|
+
});
|
|
161
|
+
const signingInput = `${header}.${claims}`;
|
|
162
|
+
const signature = await crypto.subtle.sign('RSASSA-PKCS1-v1_5', (await getKeys()).privateKey, new TextEncoder().encode(signingInput));
|
|
163
|
+
const accessToken = crypto.randomUUID();
|
|
164
|
+
const refreshToken = `oidc-refresh-${crypto.randomUUID()}`;
|
|
165
|
+
remember(accessTokens, accessToken, { ...session, scope: effectiveScope, expiresAt: issuedAt + 3600 });
|
|
166
|
+
remember(refreshTokens, refreshToken, { ...session, scope: effectiveScope, expiresAt: issuedAt + 86400 });
|
|
167
|
+
c.header('Cache-Control', 'no-store');
|
|
168
|
+
c.header('Pragma', 'no-cache');
|
|
169
|
+
return c.json({
|
|
170
|
+
access_token: accessToken,
|
|
171
|
+
token_type: 'Bearer',
|
|
172
|
+
expires_in: 3600,
|
|
173
|
+
refresh_token: refreshToken,
|
|
174
|
+
scope: effectiveScope,
|
|
175
|
+
id_token: `${signingInput}.${encode(new Uint8Array(signature))}`,
|
|
176
|
+
});
|
|
177
|
+
});
|
|
178
|
+
app.on(['GET', 'POST'], '/oauth/userinfo', (c) => {
|
|
179
|
+
const token = c.req.header('Authorization')?.match(/^Bearer\s+(\S+)$/i)?.[1];
|
|
180
|
+
const session = token ? accessTokens.get(token) : undefined;
|
|
181
|
+
c.header('Cache-Control', 'no-store');
|
|
182
|
+
if (!session ||
|
|
183
|
+
session.expiresAt <= now() ||
|
|
184
|
+
session.issuer !== new URL(c.req.url).origin ||
|
|
185
|
+
!session.scope.split(/\s+/).includes('openid')) {
|
|
186
|
+
c.header('WWW-Authenticate', 'Bearer error="invalid_token"');
|
|
187
|
+
return c.json({ error: 'invalid_token' }, 401);
|
|
188
|
+
}
|
|
189
|
+
const scopes = session.scope.split(/\s+/);
|
|
190
|
+
return c.json({
|
|
191
|
+
sub: SUBJECT,
|
|
192
|
+
...(scopes.includes('profile') ? { name: 'Scalar Mock User', preferred_username: 'scalar' } : {}),
|
|
193
|
+
...(scopes.includes('email') ? { email: 'mock@example.com', email_verified: true } : {}),
|
|
194
|
+
});
|
|
195
|
+
});
|
|
196
|
+
};
|
|
@@ -43,7 +43,7 @@ export const getStreamingResponse = (mediaType, contentType, options = {}) => {
|
|
|
43
43
|
return generateResponseExample(coerceValue(SchemaObjectSchema, completeSchema), options.variables);
|
|
44
44
|
};
|
|
45
45
|
const body = example ? example.value : generateBody();
|
|
46
|
-
const items =
|
|
46
|
+
const items = Array.isArray(body) ? body : [body];
|
|
47
47
|
const chunks = items
|
|
48
48
|
.filter((item) => item !== undefined)
|
|
49
49
|
.map((item) => serializeStreamExample(item, contentType, true) ?? '');
|
package/package.json
CHANGED
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
"swagger",
|
|
17
17
|
"cli"
|
|
18
18
|
],
|
|
19
|
-
"version": "0.
|
|
19
|
+
"version": "0.18.0",
|
|
20
20
|
"engines": {
|
|
21
21
|
"node": ">=22"
|
|
22
22
|
},
|
|
@@ -53,12 +53,12 @@
|
|
|
53
53
|
"dependencies": {
|
|
54
54
|
"@faker-js/faker": "10.6.0",
|
|
55
55
|
"@hono/node-server": "^2.1.1",
|
|
56
|
-
"@scalar/helpers": "0.16.
|
|
57
|
-
"@scalar/json-magic": "0.
|
|
58
|
-
"@scalar/openapi-types": "0.9.
|
|
59
|
-
"@scalar/openapi-upgrader": "0.4.
|
|
60
|
-
"@scalar/types": "0.
|
|
61
|
-
"@scalar/workspace-store": "0.68.
|
|
56
|
+
"@scalar/helpers": "0.16.4",
|
|
57
|
+
"@scalar/json-magic": "0.16.0",
|
|
58
|
+
"@scalar/openapi-types": "0.9.8",
|
|
59
|
+
"@scalar/openapi-upgrader": "0.4.5",
|
|
60
|
+
"@scalar/types": "0.24.0",
|
|
61
|
+
"@scalar/workspace-store": "0.68.4",
|
|
62
62
|
"ajv": "^8.20.0",
|
|
63
63
|
"ajv-formats": "^3.0.1",
|
|
64
64
|
"hono": "^4.13.8",
|