@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.
Files changed (69) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/dist/create-asyncapi-mock-server.d.ts +4 -55
  3. package/dist/create-asyncapi-mock-server.d.ts.map +1 -1
  4. package/dist/create-asyncapi-mock-server.js +24 -22
  5. package/dist/create-mock-server.d.ts +4 -3
  6. package/dist/create-mock-server.d.ts.map +1 -1
  7. package/dist/create-mock-server.js +11 -227
  8. package/dist/create-openapi-mock-server.d.ts +10 -0
  9. package/dist/create-openapi-mock-server.d.ts.map +1 -0
  10. package/dist/create-openapi-mock-server.js +227 -0
  11. package/dist/index.d.ts +0 -2
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +0 -2
  14. package/dist/routes/respond-with-authorize-page.d.ts +1 -1
  15. package/dist/routes/respond-with-authorize-page.d.ts.map +1 -1
  16. package/dist/routes/respond-with-authorize-page.js +9 -6
  17. package/dist/routes/respond-with-openapi-document.d.ts +1 -1
  18. package/dist/routes/respond-with-token.d.ts +1 -10
  19. package/dist/routes/respond-with-token.d.ts.map +1 -1
  20. package/dist/routes/respond-with-token.js +8 -5
  21. package/dist/transports/sse.d.ts.map +1 -1
  22. package/dist/transports/sse.js +17 -13
  23. package/dist/transports/types.d.ts +12 -2
  24. package/dist/transports/types.d.ts.map +1 -1
  25. package/dist/transports/websocket.d.ts.map +1 -1
  26. package/dist/transports/websocket.js +38 -30
  27. package/dist/types.d.ts +20 -8
  28. package/dist/types.d.ts.map +1 -1
  29. package/dist/utils/authenticate-asyncapi-channel.d.ts +9 -0
  30. package/dist/utils/authenticate-asyncapi-channel.d.ts.map +1 -0
  31. package/dist/utils/authenticate-asyncapi-channel.js +49 -0
  32. package/dist/utils/digest-authentication.d.ts +6 -0
  33. package/dist/utils/digest-authentication.d.ts.map +1 -0
  34. package/dist/utils/digest-authentication.js +35 -0
  35. package/dist/utils/get-asyncapi-document.d.ts +4 -0
  36. package/dist/utils/get-asyncapi-document.d.ts.map +1 -0
  37. package/dist/utils/get-asyncapi-document.js +47 -0
  38. package/dist/utils/get-asyncapi-security-schemes.d.ts +4 -0
  39. package/dist/utils/get-asyncapi-security-schemes.d.ts.map +1 -0
  40. package/dist/utils/get-asyncapi-security-schemes.js +17 -0
  41. package/dist/utils/handle-authentication.d.ts +14 -0
  42. package/dist/utils/handle-authentication.d.ts.map +1 -1
  43. package/dist/utils/handle-authentication.js +21 -6
  44. package/dist/utils/log-authentication-instructions.d.ts +3 -1
  45. package/dist/utils/log-authentication-instructions.d.ts.map +1 -1
  46. package/dist/utils/log-authentication-instructions.js +10 -2
  47. package/dist/utils/process-document.d.ts +13 -0
  48. package/dist/utils/process-document.d.ts.map +1 -0
  49. package/dist/utils/{process-openapi-document.js → process-document.js} +18 -26
  50. package/dist/utils/resolve-channels.d.ts.map +1 -1
  51. package/dist/utils/resolve-channels.js +39 -11
  52. package/dist/utils/resolve-server-pathnames.d.ts +4 -0
  53. package/dist/utils/resolve-server-pathnames.d.ts.map +1 -0
  54. package/dist/utils/resolve-server-pathnames.js +14 -0
  55. package/dist/utils/set-up-asyncapi-authentication-routes.d.ts +5 -0
  56. package/dist/utils/set-up-asyncapi-authentication-routes.d.ts.map +1 -0
  57. package/dist/utils/set-up-asyncapi-authentication-routes.js +37 -0
  58. package/dist/utils/set-up-authentication-routes.d.ts.map +1 -1
  59. package/dist/utils/set-up-authentication-routes.js +9 -18
  60. package/dist/utils/set-up-device-authorization.js +1 -1
  61. package/dist/utils/set-up-openid-connect.d.ts +4 -0
  62. package/dist/utils/set-up-openid-connect.d.ts.map +1 -0
  63. package/dist/utils/set-up-openid-connect.js +196 -0
  64. package/package.json +10 -10
  65. package/dist/utils/process-asyncapi-document.d.ts +0 -24
  66. package/dist/utils/process-asyncapi-document.d.ts.map +0 -1
  67. package/dist/utils/process-asyncapi-document.js +0 -64
  68. package/dist/utils/process-openapi-document.d.ts +0 -19
  69. package/dist/utils/process-openapi-document.d.ts.map +0 -1
@@ -0,0 +1,227 @@
1
+ import { normalize } from '@scalar/json-magic/helpers/normalize';
2
+ import { getRaw } from '@scalar/json-magic/magic-proxy';
3
+ import { getResolvedRef, mergeSiblingReferences } from '@scalar/workspace-store/helpers/get-resolved-ref';
4
+ import { Hono } from 'hono';
5
+ import { every } from 'hono/combine';
6
+ import { cors } from 'hono/cors';
7
+ import { buildSeedContext } from './utils/build-seed-context.js';
8
+ import { executeSeed } from './utils/execute-seed.js';
9
+ import { getOperations } from './utils/get-operation.js';
10
+ import { handleAuthentication } from './utils/handle-authentication.js';
11
+ import { honoRouteFromPath } from './utils/hono-route-from-path.js';
12
+ import { isAuthenticationRequired } from './utils/is-authentication-required.js';
13
+ import { logAuthenticationInstructions } from './utils/log-authentication-instructions.js';
14
+ import { requestMatchesPinnedQuery } from './utils/request-matches-pinned-query.js';
15
+ import { resolveLogger } from './utils/resolve-logger.js';
16
+ import { setUpAuthenticationRoutes } from './utils/set-up-authentication-routes.js';
17
+ import { splitPathKey } from './utils/split-path-key.js';
18
+ import { validateRequest } from './utils/validate-request.js';
19
+ import { store } from './libs/store.js';
20
+ import { mockAnyResponse } from './routes/mock-any-response.js';
21
+ import { mockHandlerResponse } from './routes/mock-handler-response.js';
22
+ import { respondWithOpenApiDocument } from './routes/respond-with-openapi-document.js';
23
+ /** Record which operation a request matched, so an error escaping it can be named */
24
+ const setMockedOperation = (c, operation) => {
25
+ ;
26
+ c.set('mockedOperation', operation);
27
+ };
28
+ /** Read back the operation a request matched, or `undefined` when it reached no mocked route */
29
+ const getMockedOperation = (c) => c.get('mockedOperation');
30
+ /**
31
+ * Whether an error carries its own response, the way Hono's `HTTPException` does.
32
+ *
33
+ * Checked structurally rather than with `instanceof`, exactly like Hono's own default handler, so an
34
+ * `HTTPException` thrown from a second copy of Hono is still recognized.
35
+ */
36
+ const carriesResponse = (error) => 'getResponse' in error && typeof error.getResponse === 'function';
37
+ /**
38
+ * Create a mock server instance
39
+ */
40
+ export const createOpenApiMockServer = async (configuration, schema) => {
41
+ const app = new Hono();
42
+ // Unhandled errors would otherwise reach Hono's default handler, which answers with a plain-text
43
+ // `Internal Server Error` that says nothing about what broke. A mock server fails for mundane,
44
+ // document-shaped reasons — a response header name the runtime rejects, an example that cannot be
45
+ // serialized — so answer with JSON that names the failing operation and repeats the message,
46
+ // which makes the failure readable in the response instead of something to go reproduce.
47
+ app.onError((error, c) => {
48
+ // The status and body such an error chose are deliberate, not an internal failure, so answer
49
+ // with them. Unlike Hono's default handler, which returns the response directly, it is rebuilt
50
+ // through the context so headers already staged on the response — those from the CORS
51
+ // middleware, most of all — still apply.
52
+ if (carriesResponse(error)) {
53
+ const response = error.getResponse();
54
+ return c.newResponse(response.body, response);
55
+ }
56
+ const operation = getMockedOperation(c);
57
+ // Keep logging the error, as Hono's default handler does, so the stack trace is not lost. Routes
58
+ // added to the returned app are not mocked operations, so name the concrete request instead —
59
+ // the log always points somewhere.
60
+ console.error(operation
61
+ ? `Error while mocking ${operation.method} ${operation.path}:`
62
+ : `Error handling ${c.req.method} ${c.req.path}:`, error);
63
+ return c.json({
64
+ error: 'Internal Server Error',
65
+ message: error.message,
66
+ // Left out entirely rather than sent as `null`, so a client can test for the key.
67
+ ...(operation ? { operation } : {}),
68
+ }, 500);
69
+ });
70
+ const input = configuration?.document ?? configuration?.specification;
71
+ const sourceDocument = typeof input === 'string' ? normalize(input) : input;
72
+ // Source locations need a bundled export so relative references remain usable outside the server.
73
+ const exportDocument = configuration?.origin ||
74
+ (typeof input === 'string' && (sourceDocument === null || typeof sourceDocument !== 'object'))
75
+ ? getRaw(schema)
76
+ : input;
77
+ // Seed data from schemas with x-seed extension
78
+ // This happens before routes are set up so data is available immediately
79
+ const schemas = schema?.components?.schemas;
80
+ if (schemas) {
81
+ for (const [schemaName, schemaObject] of Object.entries(schemas)) {
82
+ // Merge `$ref` siblings so an `x-seed` placed next to a `$ref` is preserved (OpenAPI 3.1 semantics)
83
+ const seedCode = getResolvedRef(schemaObject, mergeSiblingReferences)?.['x-seed'];
84
+ if (seedCode && typeof seedCode === 'string') {
85
+ try {
86
+ // Check if collection is empty (idempotent seeding)
87
+ // Use the schema key directly as the collection name
88
+ const existingItems = store.list(schemaName);
89
+ if (existingItems.length === 0) {
90
+ // Build seed context with schema key (used as collection name)
91
+ const seedContext = buildSeedContext(schemaName);
92
+ // Execute seed code
93
+ await executeSeed(seedCode, seedContext);
94
+ }
95
+ }
96
+ catch (error) {
97
+ // Log error but don't fail server startup
98
+ console.error(`Error seeding schema "${schemaName}":`, error);
99
+ }
100
+ }
101
+ }
102
+ }
103
+ // CORS headers
104
+ const allowedMethods = new Set(['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH', 'QUERY']);
105
+ for (const pathItem of Object.values(schema?.paths ?? {})) {
106
+ for (const method of Object.keys(getOperations(getResolvedRef(pathItem)))) {
107
+ allowedMethods.add(method);
108
+ }
109
+ }
110
+ app.use(cors({ origin: '*', allowMethods: [...allowedMethods], exposeHeaders: ['X-Scalar-XML-Error'] }));
111
+ /** Authentication methods defined in the OpenAPI document */
112
+ setUpAuthenticationRoutes(app, schema);
113
+ // Only the instructions honor `logger` (on by default); the util still prints warnings and errors
114
+ // about security schemes the mock server cannot handle, which a silenced startup should surface.
115
+ logAuthenticationInstructions(schema?.components?.securitySchemes || {}, resolveLogger(configuration.logger, true));
116
+ /** Paths specified in the OpenAPI document */
117
+ const paths = schema?.paths ?? {};
118
+ // A path key may pin query parameters to describe a variant of an operation, for example
119
+ // `/v1/messages?beta=true` next to `/v1/messages`. Hono runs every matching route in registration
120
+ // order, so a variant has to come before the sibling it shares a path with — otherwise the sibling
121
+ // answers its requests too, and the more pinned parameters a key has the more specific it is.
122
+ const pathKeys = Object.keys(paths).map((path) => {
123
+ const { path: pathname, query } = splitPathKey(path);
124
+ return { path, pathname, query };
125
+ });
126
+ /** Where each path first shows up in the document, so its variants stay with it */
127
+ const documentOrder = new Map();
128
+ pathKeys.forEach(({ pathname }, index) => {
129
+ if (!documentOrder.has(pathname)) {
130
+ documentOrder.set(pathname, index);
131
+ }
132
+ });
133
+ // Keys that share a path are grouped where the first of them appears and the most specific one
134
+ // leads the group; a key with a path of its own never moves. So the only keys that change places
135
+ // with anything unrelated are the variants of a path that is described more than once. When two
136
+ // distinct paths overlap — a literal and a parameterized one that pins a query — neither is moved,
137
+ // so whichever the document declares first is matched first, the same as any pair of overlapping
138
+ // Hono routes.
139
+ const orderedPathKeys = [...pathKeys].sort((a, b) => (documentOrder.get(a.pathname) ?? 0) - (documentOrder.get(b.pathname) ?? 0) || b.query.length - a.query.length);
140
+ orderedPathKeys.forEach(({ path, query }) => {
141
+ // A path item may itself be a `$ref`, so resolve it before reading its operations.
142
+ const pathItem = getResolvedRef(paths[path]);
143
+ const operations = getOperations(pathItem);
144
+ /** Keys for all operations of a specified path */
145
+ Object.entries(operations).forEach(([method, operation]) => {
146
+ const route = honoRouteFromPath(path);
147
+ // Remember which operation this route mocks, so the error handler can name it when something
148
+ // fails downstream. Recorded on the context rather than mapped back from the request path,
149
+ // which would not survive the app being mounted under a base path. Registered before the rest
150
+ // of the route so a failure in request validation is named too. The OpenAPI path key is kept
151
+ // (rather than the Hono route) because that is what the document author reads.
152
+ const mockedOperation = {
153
+ method,
154
+ path,
155
+ ...(operation?.operationId ? { operationId: operation.operationId } : {}),
156
+ };
157
+ /** Middleware chain answering this operation, in the order it runs */
158
+ const handlers = [];
159
+ // Runs first, so the error handler can name the operation even when validation fails. For a
160
+ // path key that pins a query it is part of the guarded chain below, so it only fires once the
161
+ // request actually matches the variant rather than for one that is handed on to the sibling.
162
+ handlers.push(async (c, next) => {
163
+ setMockedOperation(c, mockedOperation);
164
+ await next();
165
+ });
166
+ // Operation-level security overrides the global requirement, so fall back to the
167
+ // document-wide `security` when the operation does not define its own.
168
+ const effectiveSecurity = operation.security ?? schema?.security;
169
+ // Check if authentication is required for this operation
170
+ if (isAuthenticationRequired(effectiveSecurity)) {
171
+ handlers.push(handleAuthentication(schema, operation));
172
+ }
173
+ // Notify the `onRequest` callback before validation runs, so it fires for every request —
174
+ // including ones the validation middleware rejects with a `422`.
175
+ if (configuration.onRequest) {
176
+ handlers.push(async (c, next) => {
177
+ configuration.onRequest?.({ context: c, operation });
178
+ await next();
179
+ });
180
+ }
181
+ // Validate the incoming request against the operation contract (on by default;
182
+ // opt out with `validateRequest: false`). Runs after authentication but before the
183
+ // mock handler. Validators are compiled once here, so there is no per-request recompilation.
184
+ if (configuration.validateRequest !== false) {
185
+ handlers.push(validateRequest(operation, pathItem?.parameters));
186
+ }
187
+ // Check if operation has x-handler extension
188
+ // Validate that it's a non-empty string (consistent with x-seed validation)
189
+ const handlerCode = operation?.['x-handler'];
190
+ const hasHandler = handlerCode && typeof handlerCode === 'string' && handlerCode.trim().length > 0;
191
+ // Route to appropriate handler
192
+ if (hasHandler) {
193
+ handlers.push(async (c) => await mockHandlerResponse(c, operation, pathItem?.parameters, schema.openapi));
194
+ }
195
+ else {
196
+ handlers.push(async (c) => await mockAnyResponse(c, operation, schema.openapi));
197
+ }
198
+ // The pinned query parameters are not part of the route, so they are checked here. A request
199
+ // that does not carry them is handed on to the next matching route — usually the sibling path
200
+ // key without the query string.
201
+ const operationChain = every(...handlers);
202
+ // Hono uppercases methods during registration. Match the original method ourselves so
203
+ // additional operations such as COPY and copy remain distinct.
204
+ const register = (handler) => {
205
+ if (method === method.toUpperCase()) {
206
+ app.on(method, route, handler);
207
+ }
208
+ else {
209
+ app.all(route, handler);
210
+ }
211
+ };
212
+ register(async (c, next) => {
213
+ if ((c.req.method !== method && !(method === 'GET' && c.req.method === 'HEAD')) ||
214
+ !requestMatchesPinnedQuery(c, query)) {
215
+ await next();
216
+ return;
217
+ }
218
+ await operationChain(c, next);
219
+ });
220
+ });
221
+ });
222
+ // OpenAPI JSON file
223
+ app.get('/openapi.json', (c) => respondWithOpenApiDocument(c, exportDocument, 'json'));
224
+ // OpenAPI YAML file
225
+ app.get('/openapi.yaml', (c) => respondWithOpenApiDocument(c, exportDocument, 'yaml'));
226
+ return app;
227
+ };
package/dist/index.d.ts CHANGED
@@ -1,7 +1,5 @@
1
- export { type AsyncApiMockServer, type AsyncApiMockServerOptions, createAsyncApiMockServer, } from './create-asyncapi-mock-server.js';
2
1
  export { createMockServer } from './create-mock-server.js';
3
2
  export { defaultTransports, sseTransport, websocketTransport } from './transports/index.js';
4
3
  export type { MessageDirection, MockMessage, MockTransport, ResolvedChannel, ResolvedMessage, ResolvedOperation, TransportContext, } from './transports/types.js';
5
4
  export type { MockServerLogger, MockServerOptions } from './types.js';
6
- export { isAsyncApiDocument } from './utils/process-asyncapi-document.js';
7
5
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,kBAAkB,EACvB,KAAK,yBAAyB,EAC9B,wBAAwB,GACzB,MAAM,+BAA+B,CAAA;AACtC,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAA;AACvD,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAA;AAClF,YAAY,EACV,gBAAgB,EAChB,WAAW,EACX,aAAa,EACb,eAAe,EACf,eAAe,EACf,iBAAiB,EACjB,gBAAgB,GACjB,MAAM,oBAAoB,CAAA;AAC3B,YAAY,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAA;AAClE,OAAO,EAAE,kBAAkB,EAAE,MAAM,mCAAmC,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAA;AACvD,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAA;AAClF,YAAY,EACV,gBAAgB,EAChB,WAAW,EACX,aAAa,EACb,eAAe,EACf,eAAe,EACf,iBAAiB,EACjB,gBAAgB,GACjB,MAAM,oBAAoB,CAAA;AAC3B,YAAY,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAA"}
package/dist/index.js CHANGED
@@ -1,4 +1,2 @@
1
- export { createAsyncApiMockServer, } from './create-asyncapi-mock-server.js';
2
1
  export { createMockServer } from './create-mock-server.js';
3
2
  export { defaultTransports, sseTransport, websocketTransport } from './transports/index.js';
4
- export { isAsyncApiDocument } from './utils/process-asyncapi-document.js';
@@ -2,5 +2,5 @@ import type { Context } from 'hono';
2
2
  /**
3
3
  * Responds with an HTML page that simulates an OAuth 2.0 authorization page.
4
4
  */
5
- export declare function respondWithAuthorizePage(c: Context, title?: string): Response;
5
+ export declare function respondWithAuthorizePage(c: Context, title?: string, authorizationCode?: string): Response;
6
6
  //# sourceMappingURL=respond-with-authorize-page.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"respond-with-authorize-page.d.ts","sourceRoot":"","sources":["../../src/routes/respond-with-authorize-page.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AAgCnC;;GAEG;AACH,wBAAgB,wBAAwB,CAAC,CAAC,EAAE,OAAO,EAAE,KAAK,SAAK,YA4E9D"}
1
+ {"version":3,"file":"respond-with-authorize-page.d.ts","sourceRoot":"","sources":["../../src/routes/respond-with-authorize-page.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AAgCnC;;GAEG;AACH,wBAAgB,wBAAwB,CAAC,CAAC,EAAE,OAAO,EAAE,KAAK,SAAK,EAAE,iBAAiB,SAA6B,YA+E9G"}
@@ -3,7 +3,7 @@ const EXAMPLE_AUTHORIZATION_CODE = 'super-secret-token';
3
3
  /** Always responds with this token for implicit flow */
4
4
  const EXAMPLE_ACCESS_TOKEN = 'super-secret-access-token';
5
5
  /**
6
- * Escapes HTML special characters to prevent XSS when rendering user-controlled scope values.
6
+ * Escapes user-controlled text and quoted HTML attribute values.
7
7
  */
8
8
  function escapeHtml(s) {
9
9
  return s
@@ -28,7 +28,7 @@ function parseScopeParam(scopeQuery) {
28
28
  /**
29
29
  * Responds with an HTML page that simulates an OAuth 2.0 authorization page.
30
30
  */
31
- export function respondWithAuthorizePage(c, title = '') {
31
+ export function respondWithAuthorizePage(c, title = '', authorizationCode = EXAMPLE_AUTHORIZATION_CODE) {
32
32
  const redirectUri = c.req.query('redirect_uri');
33
33
  const responseType = c.req.query('response_type');
34
34
  const scope = c.req.query('scope');
@@ -37,8 +37,11 @@ export function respondWithAuthorizePage(c, title = '') {
37
37
  return c.html(generateErrorHtml('Missing redirect_uri parameter', 'This parameter is required for the OAuth 2.0 authorization flow to function correctly. Please provide a valid redirect URI in your request.'), 400);
38
38
  }
39
39
  try {
40
- // Validate redirect URI against allowed domains
41
40
  const redirectUrl = new URL(redirectUri);
41
+ // Mock callbacks can use any host, but must never execute code in this page.
42
+ if (redirectUrl.protocol !== 'https:' && redirectUrl.protocol !== 'http:') {
43
+ return c.html(generateErrorHtml('Invalid redirect_uri protocol', 'The redirect_uri must use HTTP or HTTPS.'), 400);
44
+ }
42
45
  const isImplicitFlow = responseType === 'token';
43
46
  if (isImplicitFlow) {
44
47
  const fragmentParams = new URLSearchParams();
@@ -54,7 +57,7 @@ export function respondWithAuthorizePage(c, title = '') {
54
57
  redirectUrl.hash = fragmentParams.toString();
55
58
  }
56
59
  else {
57
- redirectUrl.searchParams.set('code', EXAMPLE_AUTHORIZATION_CODE);
60
+ redirectUrl.searchParams.set('code', authorizationCode);
58
61
  if (state) {
59
62
  redirectUrl.searchParams.set('state', state);
60
63
  }
@@ -126,10 +129,10 @@ function generateAuthorizationHtml(redirectUrl, deniedUrl, title = '', scopes =
126
129
  </p>
127
130
  </div>
128
131
  <div class="px-6 py-4 pt-0 flex justify-between">
129
- <a href="${deniedUrl}" class="inline-block px-6 py-2 text-gray-600 rounded border" aria-label="Cancel authorization">
132
+ <a href="${escapeHtml(deniedUrl)}" class="inline-block px-6 py-2 text-gray-600 rounded border" aria-label="Cancel authorization">
130
133
  Cancel
131
134
  </a>
132
- <a href="${redirectUrl}" class="inline-block px-6 py-2 bg-black text-white rounded transition-colors duration-300 hover:bg-gray-800" aria-label="Authorize application">
135
+ <a href="${escapeHtml(redirectUrl)}" class="inline-block px-6 py-2 bg-black text-white rounded transition-colors duration-300 hover:bg-gray-800" aria-label="Authorize application">
133
136
  Authorize
134
137
  </a>
135
138
  </div>
@@ -2,7 +2,7 @@ import type { Context } from 'hono';
2
2
  /**
3
3
  * OpenAPI endpoints
4
4
  */
5
- export declare function respondWithOpenApiDocument(c: Context, input?: string | Record<string, any>, format?: 'json' | 'yaml'): (Response & import("hono").TypedResponse<"Not found", 404, "text">) | (Response & import("hono").TypedResponse<import("hono/utils/types").JSONValue, import("hono/utils/http-status").ContentfulStatusCode, "json">) | (Response & import("hono").TypedResponse<string, 200, "text">) | (Response & import("hono").TypedResponse<{
5
+ export declare function respondWithOpenApiDocument(c: Context, input?: string | Record<string, any>, format?: 'json' | 'yaml'): (Response & import("hono").TypedResponse<string, 200, "text">) | (Response & import("hono").TypedResponse<"Not found", 404, "text">) | (Response & import("hono").TypedResponse<import("hono/utils/types").JSONValue, import("hono/utils/http-status").ContentfulStatusCode, "json">) | (Response & import("hono").TypedResponse<{
6
6
  error: string;
7
7
  message: string;
8
8
  }, 500, "json">) | (Response & import("hono").TypedResponse<{
@@ -2,14 +2,5 @@ import type { Context } from 'hono';
2
2
  /**
3
3
  * Responds with a JSON object simulating an OAuth 2.0 token response.
4
4
  */
5
- export declare function respondWithToken(c: Context): (Response & import("hono").TypedResponse<{
6
- error: string;
7
- error_description: string;
8
- }, 400, "json">) | (Response & import("hono").TypedResponse<{
9
- access_token: string;
10
- token_type: string;
11
- expires_in: number;
12
- refresh_token: string;
13
- scope: string;
14
- }, import("hono/utils/http-status").ContentfulStatusCode, "json">);
5
+ export declare const respondWithToken: (c: Context) => Promise<Response>;
15
6
  //# sourceMappingURL=respond-with-token.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"respond-with-token.d.ts","sourceRoot":"","sources":["../../src/routes/respond-with-token.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AAKnC;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,EAAE,OAAO;;;;;;;;;mEAmD1C"}
1
+ {"version":3,"file":"respond-with-token.d.ts","sourceRoot":"","sources":["../../src/routes/respond-with-token.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AAKnC;;GAEG;AACH,eAAO,MAAM,gBAAgB,GAAU,GAAG,OAAO,KAAG,OAAO,CAAC,QAAQ,CAuDnE,CAAA"}
@@ -3,8 +3,11 @@ const EXAMPLE_ACCESS_TOKEN = 'super-secret-access-token';
3
3
  /**
4
4
  * Responds with a JSON object simulating an OAuth 2.0 token response.
5
5
  */
6
- export function respondWithToken(c) {
7
- const grantType = c.req.query('grant_type');
6
+ export const respondWithToken = async (c) => {
7
+ const body = await c.req.parseBody();
8
+ // OAuth clients send form data; retain query parameters for existing mock consumers.
9
+ const parameter = (name) => typeof body[name] === 'string' ? body[name] : c.req.query(name);
10
+ const grantType = parameter('grant_type');
8
11
  if (!grantType) {
9
12
  return c.json({
10
13
  error: 'invalid_request',
@@ -20,7 +23,7 @@ export function respondWithToken(c) {
20
23
  }, 400);
21
24
  }
22
25
  // Validate required parameters for each grant type
23
- if (grantType === 'authorization_code' && !c.req.query('code')) {
26
+ if (grantType === 'authorization_code' && !parameter('code')) {
24
27
  return c.json({
25
28
  error: 'invalid_request',
26
29
  error_description: 'Missing code parameter',
@@ -32,10 +35,10 @@ export function respondWithToken(c) {
32
35
  token_type: 'Bearer',
33
36
  expires_in: 3600,
34
37
  refresh_token: 'example-refresh-token',
35
- scope: c.req.query('scope') ?? 'read write',
38
+ scope: parameter('scope') ?? 'read write',
36
39
  };
37
40
  // Security headers
38
41
  c.header('Cache-Control', 'no-store');
39
42
  c.header('Pragma', 'no-cache');
40
43
  return c.json(tokenResponse);
41
- }
44
+ };
@@ -1 +1 @@
1
- {"version":3,"file":"sse.d.ts","sourceRoot":"","sources":["../../src/transports/sse.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAqB,MAAM,oBAAoB,CAAA;AAE1E;;;;;;;GAOG;AACH,eAAO,MAAM,YAAY,EAAE,aAmC1B,CAAA"}
1
+ {"version":3,"file":"sse.d.ts","sourceRoot":"","sources":["../../src/transports/sse.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAqB,MAAM,oBAAoB,CAAA;AAG1E;;;;;;;GAOG;AACH,eAAO,MAAM,YAAY,EAAE,aAoC1B,CAAA"}
@@ -1,4 +1,5 @@
1
1
  import { streamSSE } from 'hono/streaming';
2
+ import { getAuthenticatedChannel } from '../utils/authenticate-asyncapi-channel.js';
2
3
  /**
3
4
  * Built-in Server-Sent Events transport. Serves one-way, server-push channels over HTTP: a `GET`
4
5
  * on the channel route opens an SSE stream and emits a generated message per `receive` operation.
@@ -19,19 +20,22 @@ export const sseTransport = {
19
20
  },
20
21
  register: (channel, context) => {
21
22
  const { app, generateMessage, onMessage, log } = context;
22
- const receiveOperations = channel.operations.filter((operation) => operation.action === 'receive');
23
- // Fall back to all channel messages when the channel has no explicit receive operation.
24
- const operations = receiveOperations.length > 0 ? receiveOperations : [{ messages: channel.messages }];
25
- app.get(channel.route, (c) => streamSSE(c, async (stream) => {
26
- log(`[sse] open ${channel.route}`);
27
- for (const operation of operations) {
28
- const message = generateMessage(channel, operation.messages[0]?.id);
29
- if (message) {
30
- await stream.writeSSE({ data: message.data, event: message.event });
31
- onMessage?.({ channel: channel.id, direction: 'out', payload: message.data });
23
+ app.get(channel.route, (c) => {
24
+ const authorized = getAuthenticatedChannel(c, channel);
25
+ const receiveOperations = authorized.operations.filter((operation) => operation.action === 'receive');
26
+ // Fall back to all channel messages when the channel has no explicit receive operation.
27
+ const operations = channel.operations.length > 0 ? receiveOperations : [{ messages: channel.messages }];
28
+ return streamSSE(c, async (stream) => {
29
+ log(`[sse] open ${channel.route}`);
30
+ for (const operation of operations) {
31
+ const message = generateMessage({ ...channel, messages: operation.messages });
32
+ if (message) {
33
+ await stream.writeSSE({ data: message.data, event: message.event });
34
+ onMessage?.({ channel: channel.id, direction: 'out', payload: message.data });
35
+ }
32
36
  }
33
- }
34
- log(`[sse] close ${channel.route}`);
35
- }));
37
+ log(`[sse] close ${channel.route}`);
38
+ });
39
+ });
36
40
  },
37
41
  };
@@ -1,4 +1,5 @@
1
1
  import type { OpenAPIV3_1 } from '@scalar/openapi-types';
2
+ import type { AsyncApiSecuritySchemeObject } from '@scalar/types/asyncapi/3.1';
2
3
  import type { Hono } from 'hono';
3
4
  import type { UpgradeWebSocket } from 'hono/ws';
4
5
  /**
@@ -15,8 +16,12 @@ export type ResolvedMessage = {
15
16
  /** Content type used to encode the payload (defaults to the document's `defaultContentType`). */
16
17
  contentType?: string;
17
18
  };
19
+ /** Alternatives in an AsyncAPI security array; unresolved references remain unsatisfied. */
20
+ export type AsyncApiSecurity = Array<AsyncApiSecuritySchemeObject | undefined>;
18
21
  /** A single AsyncAPI operation (`send`/`receive`) bound to its channel. */
19
22
  export type ResolvedOperation = {
23
+ /** Operation security, after merging traits. Empty or absent means no additional requirement. */
24
+ security?: AsyncApiSecurity;
20
25
  /** The operation id (its key in the document's `operations` map). */
21
26
  id: string;
22
27
  /**
@@ -30,6 +35,11 @@ export type ResolvedOperation = {
30
35
  };
31
36
  /** A normalized, dereferenced view of an AsyncAPI channel that a transport can serve. */
32
37
  export type ResolvedChannel = {
38
+ /** Alternative servers and their security alternatives. */
39
+ security?: Array<{
40
+ protocol: string;
41
+ schemes: AsyncApiSecurity;
42
+ }>;
33
43
  /** The channel id (its key in the document's `channels` map). */
34
44
  id: string;
35
45
  /** The raw channel address, e.g. `user/signedup` or `rooms/{roomId}`. */
@@ -60,7 +70,7 @@ export type TransportContext = {
60
70
  /** The Hono app. HTTP-based transports (SSE, SignalR negotiate) register routes here. */
61
71
  app: Hono;
62
72
  /**
63
- * Hono's WebSocket upgrade helper, bound to the Node adapter. Upgrade-based transports
73
+ * Hono's WebSocket upgrade helper, bound to the host runtime. Upgrade-based transports
64
74
  * (WebSocket, SignalR) register sockets via `app.get(route, upgradeWebSocket(...))`.
65
75
  */
66
76
  upgradeWebSocket: UpgradeWebSocket;
@@ -81,7 +91,7 @@ export type TransportContext = {
81
91
  /**
82
92
  * A pluggable transport that knows how to serve a class of AsyncAPI channels (by protocol).
83
93
  * Built-in transports cover WebSocket and SSE; consumers can append their own (e.g. SignalR)
84
- * via {@link AsyncApiMockServerOptions.transports} without changing the core.
94
+ * via {@link MockServerOptions.transports} without changing the core.
85
95
  */
86
96
  export type MockTransport = {
87
97
  /** Unique transport id, e.g. `websocket`, `sse`. */
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/transports/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAA;AACxD,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAA;AAChC,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAE/C;;;GAGG;AACH,MAAM,MAAM,eAAe,GAAG;IAC5B,sFAAsF;IACtF,EAAE,EAAE,MAAM,CAAA;IACV,+FAA+F;IAC/F,OAAO,CAAC,EAAE,WAAW,CAAC,YAAY,CAAA;IAClC,uFAAuF;IACvF,QAAQ,EAAE,OAAO,EAAE,CAAA;IACnB,iGAAiG;IACjG,WAAW,CAAC,EAAE,MAAM,CAAA;CACrB,CAAA;AAED,2EAA2E;AAC3E,MAAM,MAAM,iBAAiB,GAAG;IAC9B,qEAAqE;IACrE,EAAE,EAAE,MAAM,CAA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AoD;IACpD,IAAI,EAAE,MAAM,CAAA;IACZ,iFAAiF;IACjF,QAAQ,EAAE,CAAC,OAAO,EAAE,eAAe,KAAK,OAAO,CAAA;IAC/C,uFAAuF;IACvF,QAAQ,EAAE,CAAC,OAAO,EAAE,eAAe,EAAE,OAAO,EAAE,gBAAgB,KAAK,IAAI,CAAA;CACxE,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"websocket.d.ts","sourceRoot":"","sources":["../../src/transports/websocket.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA;AAEvD;;;;;;GAMG;AACH,eAAO,MAAM,kBAAkB,EAAE,aA6ChC,CAAA"}
1
+ {"version":3,"file":"websocket.d.ts","sourceRoot":"","sources":["../../src/transports/websocket.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA;AAGvD;;;;;;GAMG;AACH,eAAO,MAAM,kBAAkB,EAAE,aAmDhC,CAAA"}
@@ -1,3 +1,4 @@
1
+ import { getAuthenticatedChannel } from '../utils/authenticate-asyncapi-channel.js';
1
2
  /**
2
3
  * Built-in WebSocket transport. Serves channels whose servers speak `ws`/`wss` by upgrading the
3
4
  * channel route to a WebSocket connection.
@@ -10,36 +11,43 @@ export const websocketTransport = {
10
11
  supports: (channel) => channel.protocols.includes('ws') || channel.protocols.includes('wss'),
11
12
  register: (channel, context) => {
12
13
  const { app, upgradeWebSocket, generateMessage, onMessage, log } = context;
13
- const receiveOperations = channel.operations.filter((operation) => operation.action === 'receive');
14
- const sendOperation = channel.operations.find((operation) => operation.action === 'send');
15
- app.get(channel.route, upgradeWebSocket(() => ({
16
- onOpen: (_event, ws) => {
17
- log(`[ws] open ${channel.route}`);
18
- // Push a single message per receive operation on connect (quiet, deterministic default).
19
- for (const operation of receiveOperations) {
20
- const message = generateMessage(channel, operation.messages[0]?.id);
21
- if (message) {
22
- ws.send(message.data);
23
- onMessage?.({ channel: channel.id, direction: 'out', payload: message.data });
14
+ app.get(channel.route, upgradeWebSocket((c) => {
15
+ const authorized = getAuthenticatedChannel(c, channel);
16
+ const receiveOperations = authorized.operations.filter((operation) => operation.action === 'receive');
17
+ const sendOperation = authorized.operations.find((operation) => operation.action === 'send');
18
+ return {
19
+ onOpen: (_event, ws) => {
20
+ log(`[ws] open ${channel.route}`);
21
+ // Push a single message per receive operation on connect (quiet, deterministic default).
22
+ for (const operation of receiveOperations) {
23
+ const message = generateMessage({ ...channel, messages: operation.messages });
24
+ if (message) {
25
+ ws.send(message.data);
26
+ onMessage?.({ channel: channel.id, direction: 'out', payload: message.data });
27
+ }
24
28
  }
25
- }
26
- },
27
- onMessage: (event, ws) => {
28
- const incoming = typeof event.data === 'string' ? event.data : '[binary]';
29
- log(`[ws] recv ${channel.route}: ${incoming}`);
30
- onMessage?.({ channel: channel.id, direction: 'in', payload: incoming });
31
- // Only echo a reply when the channel declares a `send` operation. Receive-only channels
32
- // (server push) stay quiet on inbound frames instead of fabricating an unsolicited reply.
33
- if (!sendOperation) {
34
- return;
35
- }
36
- const reply = generateMessage(channel, sendOperation.messages[0]?.id);
37
- if (reply) {
38
- ws.send(reply.data);
39
- onMessage?.({ channel: channel.id, direction: 'out', payload: reply.data });
40
- }
41
- },
42
- onClose: () => log(`[ws] close ${channel.route}`),
43
- })));
29
+ },
30
+ onMessage: (event, ws) => {
31
+ if (!sendOperation && channel.operations.some((operation) => operation.action === 'send')) {
32
+ ws.close(1008, 'Not authorized to send messages');
33
+ return;
34
+ }
35
+ const incoming = typeof event.data === 'string' ? event.data : '[binary]';
36
+ log(`[ws] recv ${channel.route}: ${incoming}`);
37
+ onMessage?.({ channel: channel.id, direction: 'in', payload: incoming });
38
+ // Only echo a reply when the channel declares a `send` operation. Receive-only channels
39
+ // (server push) stay quiet on inbound frames instead of fabricating an unsolicited reply.
40
+ if (!sendOperation) {
41
+ return;
42
+ }
43
+ const reply = generateMessage({ ...channel, messages: sendOperation.messages });
44
+ if (reply) {
45
+ ws.send(reply.data);
46
+ onMessage?.({ channel: channel.id, direction: 'out', payload: reply.data });
47
+ }
48
+ },
49
+ onClose: () => log(`[ws] close ${channel.route}`),
50
+ };
51
+ }));
44
52
  },
45
53
  };