@scalar/mock-server 0.17.6 → 0.19.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 +25 -0
- package/dist/create-asyncapi-mock-server.d.ts +4 -55
- package/dist/create-asyncapi-mock-server.d.ts.map +1 -1
- package/dist/create-asyncapi-mock-server.js +24 -22
- package/dist/create-mock-server.d.ts +4 -3
- package/dist/create-mock-server.d.ts.map +1 -1
- package/dist/create-mock-server.js +11 -227
- package/dist/create-openapi-mock-server.d.ts +10 -0
- package/dist/create-openapi-mock-server.d.ts.map +1 -0
- package/dist/create-openapi-mock-server.js +227 -0
- package/dist/index.d.ts +0 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +0 -2
- 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-openapi-document.d.ts +1 -1
- 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 +12 -2
- 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/types.d.ts +20 -8
- package/dist/types.d.ts.map +1 -1
- 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/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/get-asyncapi-document.d.ts +4 -0
- package/dist/utils/get-asyncapi-document.d.ts.map +1 -0
- package/dist/utils/get-asyncapi-document.js +47 -0
- package/dist/utils/get-asyncapi-security-schemes.d.ts +4 -0
- package/dist/utils/get-asyncapi-security-schemes.d.ts.map +1 -0
- package/dist/utils/get-asyncapi-security-schemes.js +17 -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 +21 -6
- 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/process-document.d.ts +13 -0
- package/dist/utils/process-document.d.ts.map +1 -0
- package/dist/utils/{process-openapi-document.js → process-document.js} +18 -26
- package/dist/utils/resolve-channels.d.ts.map +1 -1
- package/dist/utils/resolve-channels.js +39 -11
- package/dist/utils/resolve-server-pathnames.d.ts +4 -0
- package/dist/utils/resolve-server-pathnames.d.ts.map +1 -0
- package/dist/utils/resolve-server-pathnames.js +14 -0
- 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 +37 -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/package.json +10 -10
- package/dist/utils/process-asyncapi-document.d.ts +0 -24
- package/dist/utils/process-asyncapi-document.d.ts.map +0 -1
- package/dist/utils/process-asyncapi-document.js +0 -64
- package/dist/utils/process-openapi-document.d.ts +0 -19
- package/dist/utils/process-openapi-document.d.ts.map +0 -1
package/dist/types.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import type { OpenAPIV3_1 } from '@scalar/openapi-types';
|
|
2
2
|
import type { Context } from 'hono';
|
|
3
|
+
import type { UpgradeWebSocket } from 'hono/ws';
|
|
4
|
+
import type { MessageDirection, MockTransport } from './transports/types.js';
|
|
3
5
|
/** Available HTTP methods for Hono routes */
|
|
4
6
|
export declare const httpMethods: readonly ["get", "put", "post", "delete", "options", "patch"];
|
|
5
7
|
/**
|
|
@@ -11,29 +13,39 @@ type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<T, Exclude<keyo
|
|
|
11
13
|
/** A sink for the informational log lines the mock servers print while starting up. */
|
|
12
14
|
export type MockServerLogger = (line: string) => void;
|
|
13
15
|
type BaseMockServerOptions = {
|
|
16
|
+
/** Runtime adapter for AsyncAPI WebSocket channels. It must invoke onOpen after accepting a connection. */
|
|
17
|
+
upgradeWebSocket?: UpgradeWebSocket;
|
|
18
|
+
/** Additional AsyncAPI transports, tried after the built-in WebSocket and SSE transports. */
|
|
19
|
+
transports?: MockTransport[];
|
|
20
|
+
/** Observe messages flowing through AsyncAPI channels. */
|
|
21
|
+
onMessage?: (event: {
|
|
22
|
+
channel: string;
|
|
23
|
+
direction: MessageDirection;
|
|
24
|
+
payload: unknown;
|
|
25
|
+
}) => void;
|
|
14
26
|
/** Source file path or URL used to resolve relative references in an already loaded document. */
|
|
15
27
|
origin?: string;
|
|
16
28
|
/**
|
|
17
|
-
* The OpenAPI document to use for mocking.
|
|
18
|
-
* Can be a
|
|
29
|
+
* The OpenAPI or AsyncAPI document to use for mocking.
|
|
30
|
+
* Can be an object, inline JSON/YAML, a URL, or a file path.
|
|
19
31
|
*
|
|
20
32
|
* @deprecated Use `document` instead
|
|
21
33
|
*/
|
|
22
34
|
specification?: string | Record<string, any>;
|
|
23
35
|
/**
|
|
24
|
-
* The OpenAPI document to use for mocking.
|
|
25
|
-
* Can be a
|
|
36
|
+
* The OpenAPI or AsyncAPI document to use for mocking.
|
|
37
|
+
* Can be an object, inline JSON/YAML, a URL, or a file path.
|
|
26
38
|
*/
|
|
27
39
|
document?: string | Record<string, any>;
|
|
28
40
|
/**
|
|
29
|
-
* Callback function
|
|
41
|
+
* Callback function called before each OpenAPI request is processed.
|
|
30
42
|
*/
|
|
31
43
|
onRequest?: (data: {
|
|
32
44
|
context: Context;
|
|
33
45
|
operation: OpenAPIV3_1.OperationObject;
|
|
34
46
|
}) => void;
|
|
35
47
|
/**
|
|
36
|
-
* Validate the incoming request against the matched operation's schema. When the request
|
|
48
|
+
* Validate the incoming OpenAPI request against the matched operation's schema. When the request
|
|
37
49
|
* violates the contract, the server responds with `422` and a `application/problem+json`
|
|
38
50
|
* body describing the violations, instead of returning a mock response.
|
|
39
51
|
*
|
|
@@ -47,8 +59,8 @@ type BaseMockServerOptions = {
|
|
|
47
59
|
validateRequest?: boolean;
|
|
48
60
|
/**
|
|
49
61
|
* Control the informational output the server prints while starting up, which is currently the
|
|
50
|
-
* authentication instructions for
|
|
51
|
-
*
|
|
62
|
+
* authentication instructions for OpenAPI and transport lifecycle lines for AsyncAPI.
|
|
63
|
+
* Defaults to console logging for OpenAPI and silence for AsyncAPI.
|
|
52
64
|
*
|
|
53
65
|
* Pass `false` to silence it — handy when the mock server runs inside a test harness or another
|
|
54
66
|
* program, where the instructions are noise — or a `(line) => void` sink to route the lines
|
package/dist/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAA;AACxD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAA;AACxD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AACnC,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAE/C,OAAO,KAAK,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA;AAEzE,6CAA6C;AAC7C,eAAO,MAAM,WAAW,+DAAgE,CAAA;AAExF;;GAEG;AACH,KAAK,iBAAiB,CAAC,CAAC,EAAE,IAAI,SAAS,MAAM,CAAC,GAAG,MAAM,CAAC,IAAI,IAAI,CAAC,CAAC,EAAE,OAAO,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC,CAAC,GACzF;KACG,CAAC,IAAI,IAAI,CAAC,CAAC,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,EAAE,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC;CACzE,CAAC,IAAI,CAAC,CAAA;AAET,uFAAuF;AACvF,MAAM,MAAM,gBAAgB,GAAG,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAA;AAErD,KAAK,qBAAqB,GAAG;IAC3B,2GAA2G;IAC3G,gBAAgB,CAAC,EAAE,gBAAgB,CAAA;IAEnC,6FAA6F;IAC7F,UAAU,CAAC,EAAE,aAAa,EAAE,CAAA;IAE5B,0DAA0D;IAC1D,SAAS,CAAC,EAAE,CAAC,KAAK,EAAE;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,gBAAgB,CAAC;QAAC,OAAO,EAAE,OAAO,CAAA;KAAE,KAAK,IAAI,CAAA;IAE/F,iGAAiG;IACjG,MAAM,CAAC,EAAE,MAAM,CAAA;IAEf;;;;;OAKG;IACH,aAAa,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;IAE5C;;;OAGG;IACH,QAAQ,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;IAEvC;;OAEG;IACH,SAAS,CAAC,EAAE,CAAC,IAAI,EAAE;QAAE,OAAO,EAAE,OAAO,CAAC;QAAC,SAAS,EAAE,WAAW,CAAC,eAAe,CAAA;KAAE,KAAK,IAAI,CAAA;IAExF;;;;;;;;;;;OAWG;IACH,eAAe,CAAC,EAAE,OAAO,CAAA;IAEzB;;;;;;;;;;;OAWG;IACH,MAAM,CAAC,EAAE,OAAO,GAAG,gBAAgB,CAAA;CACpC,CAAA;AAED,MAAM,MAAM,iBAAiB,GAAG,iBAAiB,CAAC,qBAAqB,EAAE,eAAe,GAAG,UAAU,CAAC,CAAA"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Context, MiddlewareHandler } from 'hono';
|
|
2
|
+
import type { ResolvedChannel } from '../transports/types.js';
|
|
3
|
+
/** Return the operations permitted for this connection, without modifying the shared channel. */
|
|
4
|
+
export declare const getAuthenticatedChannel: (c: Context, channel: ResolvedChannel) => ResolvedChannel;
|
|
5
|
+
/** Check server security before SSE or WebSocket upgrade and hide unauthorized operations. */
|
|
6
|
+
export declare const authenticateAsyncApiChannel: (channel: ResolvedChannel, filterOperations?: boolean) => MiddlewareHandler;
|
|
7
|
+
/** Report schemes that HTTP transports cannot authenticate instead of silently ignoring them. */
|
|
8
|
+
export declare const warnUnsupportedAsyncApiSecurity: (channel: ResolvedChannel) => void;
|
|
9
|
+
//# sourceMappingURL=authenticate-asyncapi-channel.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"authenticate-asyncapi-channel.d.ts","sourceRoot":"","sources":["../../src/utils/authenticate-asyncapi-channel.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAA;AAEtD,OAAO,KAAK,EAAoB,eAAe,EAAE,MAAM,oBAAoB,CAAA;AAM3E,iGAAiG;AACjG,eAAO,MAAM,uBAAuB,GAAI,GAAG,OAAO,EAAE,SAAS,eAAe,KAAG,eACf,CAAA;AAEhE,8FAA8F;AAC9F,eAAO,MAAM,2BAA2B,GACrC,SAAS,eAAe,EAAE,0BAAwB,KAAG,iBAyBrD,CAAA;AAEH,iGAAiG;AACjG,eAAO,MAAM,+BAA+B,GAAI,SAAS,eAAe,KAAG,IA0B1E,CAAA"}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { getChallenge, isSchemeSatisfied } from './handle-authentication.js';
|
|
2
|
+
const CHANNEL_KEY = 'scalarAuthenticatedChannel';
|
|
3
|
+
/** Return the operations permitted for this connection, without modifying the shared channel. */
|
|
4
|
+
export const getAuthenticatedChannel = (c, channel) => c.get(CHANNEL_KEY) ?? channel;
|
|
5
|
+
/** Check server security before SSE or WebSocket upgrade and hide unauthorized operations. */
|
|
6
|
+
export const authenticateAsyncApiChannel = (channel, filterOperations = false) => async (c, next) => {
|
|
7
|
+
const satisfies = (alternatives = []) => alternatives.length === 0 || alternatives.some((scheme) => scheme !== undefined && isSchemeSatisfied(scheme, c));
|
|
8
|
+
const serverAllowed = !channel.security?.length || channel.security.some(({ schemes }) => satisfies(schemes));
|
|
9
|
+
const operations = channel.operations.filter((operation) => satisfies(operation.security));
|
|
10
|
+
if (!serverAllowed ||
|
|
11
|
+
(channel.operations.length > 0 && operations.length === 0) ||
|
|
12
|
+
(!filterOperations && operations.length !== channel.operations.length)) {
|
|
13
|
+
const schemes = [
|
|
14
|
+
...(channel.security ?? []).flatMap(({ schemes }) => schemes),
|
|
15
|
+
...channel.operations.flatMap((operation) => operation.security ?? []),
|
|
16
|
+
];
|
|
17
|
+
const challenges = new Set(schemes.flatMap((scheme) => (scheme ? [getChallenge(scheme)].filter((value) => value !== null) : [])));
|
|
18
|
+
for (const challenge of challenges) {
|
|
19
|
+
c.header('WWW-Authenticate', challenge, { append: true });
|
|
20
|
+
}
|
|
21
|
+
return c.json({ error: 'Unauthorized', message: 'Authentication is required to access this channel.' }, 401);
|
|
22
|
+
}
|
|
23
|
+
c.set(CHANNEL_KEY, { ...channel, operations });
|
|
24
|
+
return await next();
|
|
25
|
+
};
|
|
26
|
+
/** Report schemes that HTTP transports cannot authenticate instead of silently ignoring them. */
|
|
27
|
+
export const warnUnsupportedAsyncApiSecurity = (channel) => {
|
|
28
|
+
const schemes = [
|
|
29
|
+
...(channel.security ?? []).flatMap(({ schemes }) => schemes),
|
|
30
|
+
...channel.operations.flatMap((operation) => operation.security ?? []),
|
|
31
|
+
];
|
|
32
|
+
const unsupported = new Set(schemes.flatMap((scheme) => {
|
|
33
|
+
if (!scheme) {
|
|
34
|
+
return ['unresolved security reference'];
|
|
35
|
+
}
|
|
36
|
+
if (scheme.type === 'http') {
|
|
37
|
+
return ['basic', 'bearer', 'digest'].includes(scheme.scheme?.toLowerCase() ?? '')
|
|
38
|
+
? []
|
|
39
|
+
: [`http/${scheme.scheme}`];
|
|
40
|
+
}
|
|
41
|
+
if (['httpApiKey', 'oauth2', 'openIdConnect', 'X509'].includes(scheme.type)) {
|
|
42
|
+
return [];
|
|
43
|
+
}
|
|
44
|
+
return [scheme.type];
|
|
45
|
+
}));
|
|
46
|
+
for (const type of unsupported) {
|
|
47
|
+
console.warn(`[asyncapi] channel "${channel.id}" uses unsupported security: ${type}. WebSocket/SSE cannot authenticate this scheme; it will not satisfy a security requirement.`);
|
|
48
|
+
}
|
|
49
|
+
};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { Context } from 'hono';
|
|
2
|
+
/** A deterministic challenge lets HTTP clients exercise Digest without a credential database. */
|
|
3
|
+
export declare const DIGEST_CHALLENGE = "Digest realm=\"Scalar Mock Server\", nonce=\"scalar-mock-nonce\", algorithm=MD5, qop=\"auth\"";
|
|
4
|
+
/** Validate the Digest exchange shape, like the mock's Basic and Bearer credential checks. */
|
|
5
|
+
export declare const isValidDigestAuth: (c: Context) => boolean;
|
|
6
|
+
//# sourceMappingURL=digest-authentication.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"digest-authentication.d.ts","sourceRoot":"","sources":["../../src/utils/digest-authentication.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AAKnC,iGAAiG;AACjG,eAAO,MAAM,gBAAgB,kGAAyE,CAAA;AAEtG,8FAA8F;AAC9F,eAAO,MAAM,iBAAiB,GAAI,GAAG,OAAO,KAAG,OA+B9C,CAAA"}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
const REALM = 'Scalar Mock Server';
|
|
2
|
+
const NONCE = 'scalar-mock-nonce';
|
|
3
|
+
/** A deterministic challenge lets HTTP clients exercise Digest without a credential database. */
|
|
4
|
+
export const DIGEST_CHALLENGE = `Digest realm="${REALM}", nonce="${NONCE}", algorithm=MD5, qop="auth"`;
|
|
5
|
+
/** Validate the Digest exchange shape, like the mock's Basic and Bearer credential checks. */
|
|
6
|
+
export const isValidDigestAuth = (c) => {
|
|
7
|
+
const header = c.req.header('Authorization');
|
|
8
|
+
if (!header || !/^Digest\s+/i.test(header)) {
|
|
9
|
+
return false;
|
|
10
|
+
}
|
|
11
|
+
const parameters = new Map();
|
|
12
|
+
const input = header.replace(/^Digest\s+/i, '');
|
|
13
|
+
const pattern = /\s*([\w-]+)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^\s,]+))\s*(?:,|$)/gy;
|
|
14
|
+
let consumed = 0;
|
|
15
|
+
for (const match of input.matchAll(pattern)) {
|
|
16
|
+
const name = match[1].toLowerCase();
|
|
17
|
+
if (parameters.has(name)) {
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
parameters.set(name, (match[2] ?? match[3] ?? '').replace(/\\(.)/g, '$1'));
|
|
21
|
+
consumed = match.index + match[0].length;
|
|
22
|
+
}
|
|
23
|
+
const url = new URL(c.req.url);
|
|
24
|
+
return (consumed === input.length &&
|
|
25
|
+
Boolean(parameters.get('username')) &&
|
|
26
|
+
parameters.get('realm') === REALM &&
|
|
27
|
+
parameters.get('nonce') === NONCE &&
|
|
28
|
+
parameters.get('uri') === `${url.pathname}${url.search}` &&
|
|
29
|
+
(parameters.get('algorithm') ?? 'MD5').toUpperCase() === 'MD5' &&
|
|
30
|
+
parameters.get('qop') === 'auth' &&
|
|
31
|
+
Boolean(parameters.get('cnonce')) &&
|
|
32
|
+
/^[0-9a-f]{8}$/i.test(parameters.get('nc') ?? '') &&
|
|
33
|
+
parameters.get('nc') !== '00000000' &&
|
|
34
|
+
/^[0-9a-f]{32}$/i.test(parameters.get('response') ?? ''));
|
|
35
|
+
};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { AsyncApiDocument } from '@scalar/types/asyncapi/3.1';
|
|
2
|
+
/** Serve a separate document for each mock origin without mutating the loaded API description. */
|
|
3
|
+
export declare const getAsyncApiDocument: (document: AsyncApiDocument, url: string) => AsyncApiDocument;
|
|
4
|
+
//# sourceMappingURL=get-asyncapi-document.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"get-asyncapi-document.d.ts","sourceRoot":"","sources":["../../src/utils/get-asyncapi-document.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAA;AAKlE,kGAAkG;AAClG,eAAO,MAAM,mBAAmB,GAAI,UAAU,gBAAgB,EAAE,KAAK,MAAM,KAAG,gBAmC7E,CAAA"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { createMagicProxy, getRaw } from '@scalar/json-magic/magic-proxy';
|
|
2
|
+
import { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref';
|
|
3
|
+
import { getAsyncApiSecuritySchemes } from './get-asyncapi-security-schemes.js';
|
|
4
|
+
/** Serve a separate document for each mock origin without mutating the loaded API description. */
|
|
5
|
+
export const getAsyncApiDocument = (document, url) => {
|
|
6
|
+
const origin = new URL(url);
|
|
7
|
+
const copy = createMagicProxy(structuredClone(getRaw(document)));
|
|
8
|
+
for (const rawServer of Object.values(copy.servers ?? {})) {
|
|
9
|
+
const server = getResolvedRef(rawServer);
|
|
10
|
+
if (!server)
|
|
11
|
+
continue;
|
|
12
|
+
const protocol = server.protocol.toLowerCase();
|
|
13
|
+
if (!['ws', 'wss', 'http', 'https', 'sse'].includes(protocol))
|
|
14
|
+
continue;
|
|
15
|
+
server.host = origin.host;
|
|
16
|
+
server.protocol =
|
|
17
|
+
protocol === 'ws' || protocol === 'wss'
|
|
18
|
+
? origin.protocol === 'https:'
|
|
19
|
+
? 'wss'
|
|
20
|
+
: 'ws'
|
|
21
|
+
: protocol === 'sse'
|
|
22
|
+
? 'sse'
|
|
23
|
+
: origin.protocol.slice(0, -1);
|
|
24
|
+
}
|
|
25
|
+
const rebase = (value) => {
|
|
26
|
+
const endpoint = new URL(value, origin);
|
|
27
|
+
return new URL(`${endpoint.pathname}${endpoint.search}${endpoint.hash}`, origin).href;
|
|
28
|
+
};
|
|
29
|
+
for (const scheme of getAsyncApiSecuritySchemes(copy)) {
|
|
30
|
+
if (scheme?.type === 'openIdConnect' && scheme.openIdConnectUrl)
|
|
31
|
+
scheme.openIdConnectUrl = rebase(scheme.openIdConnectUrl);
|
|
32
|
+
if (scheme?.type !== 'oauth2')
|
|
33
|
+
continue;
|
|
34
|
+
for (const rawFlow of Object.values(getResolvedRef(scheme.flows) ?? {})) {
|
|
35
|
+
const flow = getResolvedRef(rawFlow);
|
|
36
|
+
if (!flow)
|
|
37
|
+
continue;
|
|
38
|
+
if (flow.authorizationUrl)
|
|
39
|
+
flow.authorizationUrl = rebase(flow.authorizationUrl);
|
|
40
|
+
if (flow.tokenUrl)
|
|
41
|
+
flow.tokenUrl = rebase(flow.tokenUrl);
|
|
42
|
+
if (flow.refreshUrl)
|
|
43
|
+
flow.refreshUrl = rebase(flow.refreshUrl);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return getRaw(copy);
|
|
47
|
+
};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { AsyncApiDocument, AsyncApiSecuritySchemeObject } from '@scalar/types/asyncapi/3.1';
|
|
2
|
+
/** Collect component and inline security schemes, including operation traits. */
|
|
3
|
+
export declare const getAsyncApiSecuritySchemes: (document: AsyncApiDocument) => Array<AsyncApiSecuritySchemeObject | undefined>;
|
|
4
|
+
//# sourceMappingURL=get-asyncapi-security-schemes.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"get-asyncapi-security-schemes.d.ts","sourceRoot":"","sources":["../../src/utils/get-asyncapi-security-schemes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,4BAA4B,EAAE,MAAM,4BAA4B,CAAA;AAGhG,iFAAiF;AACjF,eAAO,MAAM,0BAA0B,GACrC,UAAU,gBAAgB,KACzB,KAAK,CAAC,4BAA4B,GAAG,SAAS,CAchD,CAAA"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref';
|
|
2
|
+
/** Collect component and inline security schemes, including operation traits. */
|
|
3
|
+
export const getAsyncApiSecuritySchemes = (document) => {
|
|
4
|
+
const components = getResolvedRef(document.components);
|
|
5
|
+
// AsyncAPI also permits inline schemes on servers, operations, and operation traits.
|
|
6
|
+
return [
|
|
7
|
+
...Object.values(components?.securitySchemes ?? {}),
|
|
8
|
+
...Object.values(document.servers ?? {}).flatMap((server) => getResolvedRef(server)?.security ?? []),
|
|
9
|
+
...Object.values(document.operations ?? {}).flatMap((rawOperation) => {
|
|
10
|
+
const operation = getResolvedRef(rawOperation);
|
|
11
|
+
return [
|
|
12
|
+
...(operation?.security ?? []),
|
|
13
|
+
...(operation?.traits ?? []).flatMap((trait) => getResolvedRef(trait)?.security ?? []),
|
|
14
|
+
];
|
|
15
|
+
}),
|
|
16
|
+
].map((scheme) => getResolvedRef(scheme));
|
|
17
|
+
};
|
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
import type { OpenAPIV3_1, OpenAPIV3_2 } from '@scalar/openapi-types';
|
|
2
|
+
import type { AsyncApiSecuritySchemeObject } from '@scalar/types/asyncapi/3.1';
|
|
2
3
|
import type { Context } from 'hono';
|
|
4
|
+
/** Security shapes understood by HTTP and AsyncAPI transports. */
|
|
5
|
+
type SecurityScheme = OpenAPIV3_2.SecuritySchemeObject | AsyncApiSecuritySchemeObject | {
|
|
6
|
+
type: 'mutualTLS';
|
|
7
|
+
};
|
|
8
|
+
/** Check whether a single security scheme is satisfied by the request. */
|
|
9
|
+
export declare const isSchemeSatisfied: (scheme: SecurityScheme, c: Context) => boolean;
|
|
10
|
+
/**
|
|
11
|
+
* Build the `WWW-Authenticate` challenge for a single security scheme.
|
|
12
|
+
*
|
|
13
|
+
* Returns `null` for schemes that do not map to an HTTP authentication challenge.
|
|
14
|
+
*/
|
|
15
|
+
export declare const getChallenge: (scheme: SecurityScheme) => string | null;
|
|
3
16
|
/**
|
|
4
17
|
* Handles authentication for incoming requests based on the OpenAPI document.
|
|
5
18
|
*
|
|
@@ -9,4 +22,5 @@ import type { Context } from 'hono';
|
|
|
9
22
|
* means authentication is optional and always passes.
|
|
10
23
|
*/
|
|
11
24
|
export declare function handleAuthentication(schema?: OpenAPIV3_1.Document | OpenAPIV3_2.Document, operation?: OpenAPIV3_2.OperationObject): (c: Context, next: () => Promise<void>) => Promise<Response | void>;
|
|
25
|
+
export {};
|
|
12
26
|
//# sourceMappingURL=handle-authentication.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handle-authentication.d.ts","sourceRoot":"","sources":["../../src/utils/handle-authentication.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"handle-authentication.d.ts","sourceRoot":"","sources":["../../src/utils/handle-authentication.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAa,WAAW,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAA;AAChF,OAAO,KAAK,EAAE,4BAA4B,EAAE,MAAM,4BAA4B,CAAA;AAE9E,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AAKnC,kEAAkE;AAClE,KAAK,cAAc,GAAG,WAAW,CAAC,oBAAoB,GAAG,4BAA4B,GAAG;IAAE,IAAI,EAAE,WAAW,CAAA;CAAE,CAAA;AA8C7G,0EAA0E;AAC1E,eAAO,MAAM,iBAAiB,GAAI,QAAQ,cAAc,EAAE,GAAG,OAAO,KAAG,OAgDtE,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,YAAY,GAAI,QAAQ,cAAc,KAAG,MAAM,GAAG,IA6B9D,CAAA;AAYD;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAClC,MAAM,CAAC,EAAE,WAAW,CAAC,QAAQ,GAAG,WAAW,CAAC,QAAQ,EACpD,SAAS,CAAC,EAAE,WAAW,CAAC,eAAe,IAEzB,GAAG,OAAO,EAAE,MAAM,MAAM,OAAO,CAAC,IAAI,CAAC,KAAG,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,CA4D/E"}
|
|
@@ -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,8 +50,12 @@ 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;
|
|
@@ -63,6 +68,12 @@ function isSchemeSatisfied(scheme, c) {
|
|
|
63
68
|
}
|
|
64
69
|
return scheme.in === 'cookie' && Boolean(getCookie(c, scheme.name));
|
|
65
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));
|
|
76
|
+
}
|
|
66
77
|
// OAuth 2.0 and OpenID Connect both carry a bearer token in the `Authorization` header.
|
|
67
78
|
case 'oauth2':
|
|
68
79
|
case 'openIdConnect':
|
|
@@ -70,13 +81,13 @@ function isSchemeSatisfied(scheme, c) {
|
|
|
70
81
|
default:
|
|
71
82
|
return false;
|
|
72
83
|
}
|
|
73
|
-
}
|
|
84
|
+
};
|
|
74
85
|
/**
|
|
75
86
|
* Build the `WWW-Authenticate` challenge for a single security scheme.
|
|
76
87
|
*
|
|
77
88
|
* Returns `null` for schemes that do not map to an HTTP authentication challenge.
|
|
78
89
|
*/
|
|
79
|
-
|
|
90
|
+
export const getChallenge = (scheme) => {
|
|
80
91
|
switch (scheme.type) {
|
|
81
92
|
case 'http':
|
|
82
93
|
if ('scheme' in scheme && scheme.scheme?.toLowerCase() === 'basic') {
|
|
@@ -85,7 +96,11 @@ function getChallenge(scheme) {
|
|
|
85
96
|
if ('scheme' in scheme && scheme.scheme?.toLowerCase() === 'bearer') {
|
|
86
97
|
return `Bearer realm="${REALM}", error="invalid_token", error_description="The access token is invalid or has expired"`;
|
|
87
98
|
}
|
|
99
|
+
if ('scheme' in scheme && scheme.scheme?.toLowerCase() === 'digest') {
|
|
100
|
+
return DIGEST_CHALLENGE;
|
|
101
|
+
}
|
|
88
102
|
return null;
|
|
103
|
+
case 'httpApiKey':
|
|
89
104
|
case 'apiKey':
|
|
90
105
|
if ('name' in scheme && scheme.name) {
|
|
91
106
|
return `ApiKey realm="${REALM}", error="invalid_token", error_description="Invalid or missing API key", name="${scheme.name}"`;
|
|
@@ -97,7 +112,7 @@ function getChallenge(scheme) {
|
|
|
97
112
|
default:
|
|
98
113
|
return null;
|
|
99
114
|
}
|
|
100
|
-
}
|
|
115
|
+
};
|
|
101
116
|
/** Resolve all schemes referenced by a single security requirement object. */
|
|
102
117
|
function resolveSchemes(requirement, schema) {
|
|
103
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' &&
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { OpenAPIV3_1, OpenAPIV3_2 } from '@scalar/openapi-types';
|
|
2
|
+
import type { AsyncApiDocument } from '@scalar/types/asyncapi/3.1';
|
|
3
|
+
/** A processed API description, tagged so each mock engine receives its own document type. */
|
|
4
|
+
export type ProcessedDocument = {
|
|
5
|
+
type: 'openapi';
|
|
6
|
+
document: OpenAPIV3_1.Document | OpenAPIV3_2.Document;
|
|
7
|
+
} | {
|
|
8
|
+
type: 'asyncapi';
|
|
9
|
+
document: AsyncApiDocument;
|
|
10
|
+
};
|
|
11
|
+
/** Bundle API descriptions once, retaining AsyncAPI and upgrading compatible OpenAPI input. */
|
|
12
|
+
export declare const processDocument: (document: string | Record<string, unknown> | undefined, origin?: string) => Promise<ProcessedDocument>;
|
|
13
|
+
//# sourceMappingURL=process-document.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"process-document.d.ts","sourceRoot":"","sources":["../../src/utils/process-document.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAA;AAErE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAA;AAGlE,8FAA8F;AAC9F,MAAM,MAAM,iBAAiB,GACzB;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,QAAQ,EAAE,WAAW,CAAC,QAAQ,GAAG,WAAW,CAAC,QAAQ,CAAA;CAAE,GAC1E;IAAE,IAAI,EAAE,UAAU,CAAC;IAAC,QAAQ,EAAE,gBAAgB,CAAA;CAAE,CAAA;AAEpD,+FAA+F;AAC/F,eAAO,MAAM,eAAe,GAC1B,UAAU,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,EACtD,SAAS,MAAM,KACd,OAAO,CAAC,iBAAiB,CAyE3B,CAAA"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import path from 'node:path';
|
|
2
2
|
import { cwd } from 'node:process';
|
|
3
|
+
import { isObjectLike } from '@scalar/helpers/object/is-object';
|
|
3
4
|
import { bundle } from '@scalar/json-magic/bundle';
|
|
4
5
|
import { fetchUrls, parseJson, parseYaml, readFiles } from '@scalar/json-magic/bundle/plugins/node';
|
|
5
6
|
import { isFilePath } from '@scalar/json-magic/helpers/is-file-path';
|
|
@@ -7,33 +8,21 @@ import { isHttpUrl } from '@scalar/json-magic/helpers/is-http-url';
|
|
|
7
8
|
import { createMagicProxy } from '@scalar/json-magic/magic-proxy';
|
|
8
9
|
import { upgrade } from '@scalar/openapi-upgrader';
|
|
9
10
|
import { openApiDocument, resolveOpenApiDocument } from '@scalar/workspace-store/plugins/bundler';
|
|
10
|
-
/**
|
|
11
|
-
|
|
12
|
-
* and wrapping it so internal references stay intact but resolve lazily.
|
|
13
|
-
*
|
|
14
|
-
* Unlike a full dereference, the returned document keeps `$ref` nodes in place. Consumers
|
|
15
|
-
* resolve them on demand with `getResolvedRef` from `@scalar/workspace-store`, which reads the
|
|
16
|
-
* `$ref-value` exposed by the magic proxy. This avoids eagerly flattening (and duplicating)
|
|
17
|
-
* the whole document up front.
|
|
18
|
-
*
|
|
19
|
-
* Compatibility failures retain the OpenAPI 3.1 document and its version, without applying partial migrations.
|
|
20
|
-
*
|
|
21
|
-
* @param document - The OpenAPI document to process. Can be a string (URL/path) or an object.
|
|
22
|
-
* @param origin - Source file path or URL for resolving references in an already loaded document.
|
|
23
|
-
* @returns A promise that resolves to the document with lazily resolvable references.
|
|
24
|
-
* @throws Error if the document cannot be processed or is invalid.
|
|
25
|
-
*/
|
|
26
|
-
export async function processOpenApiDocument(document, origin) {
|
|
11
|
+
/** Bundle API descriptions once, retaining AsyncAPI and upgrading compatible OpenAPI input. */
|
|
12
|
+
export const processDocument = async (document, origin) => {
|
|
27
13
|
// Handle empty/undefined input gracefully
|
|
28
14
|
if (!document || (typeof document === 'object' && Object.keys(document).length === 0)) {
|
|
29
15
|
// Return a minimal valid OpenAPI 3.2 document
|
|
30
16
|
return {
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
17
|
+
type: 'openapi',
|
|
18
|
+
document: {
|
|
19
|
+
openapi: '3.2.0',
|
|
20
|
+
info: {
|
|
21
|
+
title: 'Mock API',
|
|
22
|
+
version: '1.0.0',
|
|
23
|
+
},
|
|
24
|
+
paths: {},
|
|
35
25
|
},
|
|
36
|
-
paths: {},
|
|
37
26
|
};
|
|
38
27
|
}
|
|
39
28
|
let bundled;
|
|
@@ -58,11 +47,14 @@ export async function processOpenApiDocument(document, origin) {
|
|
|
58
47
|
});
|
|
59
48
|
}
|
|
60
49
|
catch (error) {
|
|
61
|
-
throw new Error(`Failed to bundle
|
|
50
|
+
throw new Error(`Failed to bundle API document: ${error instanceof Error ? error.message : String(error)}`);
|
|
62
51
|
}
|
|
63
|
-
if (!bundled
|
|
52
|
+
if (!isObjectLike(bundled)) {
|
|
64
53
|
throw new Error('Bundled document is invalid: expected an object');
|
|
65
54
|
}
|
|
55
|
+
if ('asyncapi' in bundled) {
|
|
56
|
+
return { type: 'asyncapi', document: createMagicProxy(bundled) };
|
|
57
|
+
}
|
|
66
58
|
// Upgrading must not activate a $self field authored in an older OpenAPI version.
|
|
67
59
|
const retrievalUri = origin ?? (typeof document === 'string' && (isFilePath(document) || isHttpUrl(document)) ? document : '/');
|
|
68
60
|
const documentUri = resolveOpenApiDocument(bundled, retrievalUri)?.baseUri;
|
|
@@ -78,5 +70,5 @@ export async function processOpenApiDocument(document, origin) {
|
|
|
78
70
|
}
|
|
79
71
|
// Wrap the document in a magic proxy so internal references resolve lazily via `$ref-value`.
|
|
80
72
|
// External references were already pulled inline by `bundle` above, so only local `$ref`s remain.
|
|
81
|
-
return createMagicProxy(upgraded, { documentUri });
|
|
82
|
-
}
|
|
73
|
+
return { type: 'openapi', document: createMagicProxy(upgraded, { documentUri }) };
|
|
74
|
+
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolve-channels.d.ts","sourceRoot":"","sources":["../../src/utils/resolve-channels.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"resolve-channels.d.ts","sourceRoot":"","sources":["../../src/utils/resolve-channels.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,gBAAgB,EAAyB,MAAM,4BAA4B,CAAA;AAWzF,OAAO,KAAK,EAAE,eAAe,EAAsC,MAAM,oBAAoB,CAAA;AAoE7F;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,gBAAgB,GAAG,eAAe,EAAE,CAuE7E"}
|
|
@@ -1,7 +1,9 @@
|
|
|
1
|
+
import { combineUrlAndPath } from '@scalar/helpers/url/merge-urls';
|
|
1
2
|
import { ASYNCAPI_WEBSOCKET_PROTOCOLS, getAllChannelMessages, getAsyncApiServers, getChannelOperations, resolveChannel, } from '@scalar/workspace-store/channel-example';
|
|
2
3
|
import { getNameFromRef } from '@scalar/workspace-store/helpers/get-name-from-ref';
|
|
3
4
|
import { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref';
|
|
4
5
|
import { honoRouteFromPath } from '../utils/hono-route-from-path.js';
|
|
6
|
+
import { resolveServerPathnames } from './resolve-server-pathnames.js';
|
|
5
7
|
/** Extract a plain JSON Schema from a message `payload`, unwrapping the Multi Format Schema Object. */
|
|
6
8
|
function extractPayloadSchema(payload) {
|
|
7
9
|
const resolved = getResolvedRef(payload);
|
|
@@ -84,17 +86,43 @@ export function resolveChannels(document) {
|
|
|
84
86
|
.map((ref) => messagesByKey.get(getNameFromRef(ref, ['channels', channelName, 'messages']) ?? ''))
|
|
85
87
|
.filter((message) => message !== undefined)
|
|
86
88
|
: messages;
|
|
87
|
-
return {
|
|
89
|
+
return {
|
|
90
|
+
id: operationName,
|
|
91
|
+
action,
|
|
92
|
+
messages: operationMessages,
|
|
93
|
+
...(operation.security ? { security: operation.security.map((scheme) => getResolvedRef(scheme)) } : {}),
|
|
94
|
+
};
|
|
88
95
|
});
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
96
|
+
// An empty server list means all servers, just like an omitted list.
|
|
97
|
+
const serverChannel = channel.servers?.length ? channel : { ...channel, servers: undefined };
|
|
98
|
+
const servers = getAsyncApiServers(document, { channel: serverChannel, webSocketOnly: false });
|
|
99
|
+
const routes = new Map();
|
|
100
|
+
for (const entry of servers.length ? servers : [undefined]) {
|
|
101
|
+
for (const pathname of entry ? resolveServerPathnames(entry.server) : ['']) {
|
|
102
|
+
const route = honoRouteFromPath(combineUrlAndPath(pathname || '/', channelAddress));
|
|
103
|
+
const security = entry
|
|
104
|
+
? { protocol: entry.protocol, schemes: (entry.server.security ?? []).map((scheme) => getResolvedRef(scheme)) }
|
|
105
|
+
: { protocol: '', schemes: channel.servers?.length ? [undefined] : [] };
|
|
106
|
+
const existing = routes.get(route);
|
|
107
|
+
if (existing) {
|
|
108
|
+
existing.protocols = [...new Set([...existing.protocols, entry.protocol])];
|
|
109
|
+
existing.security.push(security);
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
routes.set(route, {
|
|
113
|
+
security: [security],
|
|
114
|
+
id: channelName,
|
|
115
|
+
address: channelAddress,
|
|
116
|
+
route: route.startsWith('/') ? route : `/${route}`,
|
|
117
|
+
protocols: entry ? [entry.protocol] : resolveProtocols(document, serverChannel),
|
|
118
|
+
operations,
|
|
119
|
+
messages,
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return [...routes.values()].map(({ security, ...channel }) => ({
|
|
124
|
+
...channel,
|
|
125
|
+
...(security?.some(({ schemes }) => schemes.length) ? { security } : {}),
|
|
126
|
+
}));
|
|
99
127
|
});
|
|
100
128
|
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { AsyncApiServerObject } from '@scalar/types/asyncapi/3.1';
|
|
2
|
+
/** Expand server pathname variables without expanding channel parameters or host variables. */
|
|
3
|
+
export declare const resolveServerPathnames: (server: AsyncApiServerObject) => string[];
|
|
4
|
+
//# sourceMappingURL=resolve-server-pathnames.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resolve-server-pathnames.d.ts","sourceRoot":"","sources":["../../src/utils/resolve-server-pathnames.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAA;AAGtE,+FAA+F;AAC/F,eAAO,MAAM,sBAAsB,GAAI,QAAQ,oBAAoB,KAAG,MAAM,EAa3E,CAAA"}
|