transit-kit 0.3.1 → 0.4.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/dist/cli/generateOpenApi.js +47 -0
- package/dist/cli/generateOpenApi.spec.js +1 -0
- package/dist/server/handlers/api/EndpointDefinition.d.ts +3 -1
- package/dist/server/handlers/api/EndpointHandler.d.ts +6 -1
- package/dist/server/handlers/api/HandlerFromDefinition.d.ts +3 -2
- package/dist/server/handlers/api/createApiHandler.d.ts +3 -1
- package/dist/server/handlers/api/createApiHandler.js +8 -1
- package/dist/server/index.d.ts +1 -0
- package/dist/server/index.js +1 -0
- package/dist/server/middleware/auth.d.ts +2 -0
- package/dist/server/middleware/auth.js +13 -0
- package/dist/server/security/SecuritySchema.d.ts +5 -0
- package/dist/server/security/SecuritySchema.js +14 -0
- package/dist/server/security/basicAuth.d.ts +9 -0
- package/dist/server/security/basicAuth.js +21 -0
- package/dist/server/security/bearerAuth.d.ts +9 -0
- package/dist/server/security/bearerAuth.js +18 -0
- package/dist/server/server.js +5 -0
- package/package.json +1 -1
|
@@ -31,6 +31,24 @@ function extractQueryParameters(querySchema) {
|
|
|
31
31
|
return [];
|
|
32
32
|
}
|
|
33
33
|
}
|
|
34
|
+
function extractRequestSecuritySchemes(definition) {
|
|
35
|
+
const securitySchemes = definition.securitySchemes;
|
|
36
|
+
if (hasValue(securitySchemes)) {
|
|
37
|
+
return securitySchemes.map((schema) => {
|
|
38
|
+
switch (schema.type) {
|
|
39
|
+
case "http":
|
|
40
|
+
return {
|
|
41
|
+
[schema.name]: [],
|
|
42
|
+
};
|
|
43
|
+
default:
|
|
44
|
+
throw new Error(`Unsupported security scheme type: ${schema.type}`);
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
else {
|
|
49
|
+
return [];
|
|
50
|
+
}
|
|
51
|
+
}
|
|
34
52
|
function translateToOpenAPIPathItem(definition) {
|
|
35
53
|
const { meta, path, method, requestBodySchema, querySchema, responseSchemas, } = definition;
|
|
36
54
|
// 1. Path and Parameter extraction
|
|
@@ -80,6 +98,8 @@ function translateToOpenAPIPathItem(definition) {
|
|
|
80
98
|
.reduce((acc, resp) => {
|
|
81
99
|
return { ...acc, ...resp };
|
|
82
100
|
}, {});
|
|
101
|
+
// 5. Security Requirements
|
|
102
|
+
const securityRequirements = extractRequestSecuritySchemes(definition);
|
|
83
103
|
const operation = {
|
|
84
104
|
operationId: meta.name,
|
|
85
105
|
summary: meta.description,
|
|
@@ -88,12 +108,35 @@ function translateToOpenAPIPathItem(definition) {
|
|
|
88
108
|
parameters: operationParameters,
|
|
89
109
|
...requestBody,
|
|
90
110
|
responses,
|
|
111
|
+
security: securityRequirements,
|
|
91
112
|
};
|
|
92
113
|
const pathItem = {
|
|
93
114
|
[method.toLowerCase()]: operation,
|
|
94
115
|
};
|
|
95
116
|
return [openApiPath, pathItem];
|
|
96
117
|
}
|
|
118
|
+
function extractSecuritySchemes(endpointDefinitions) {
|
|
119
|
+
const securitySchemes = Array.from(new Set(endpointDefinitions
|
|
120
|
+
.map((def) => def.securitySchemes)
|
|
121
|
+
.filter(hasValue)
|
|
122
|
+
.flat()));
|
|
123
|
+
const openApiSecuritySchemes = securitySchemes.map((scheme) => {
|
|
124
|
+
switch (scheme.type) {
|
|
125
|
+
case "http":
|
|
126
|
+
return {
|
|
127
|
+
[scheme.name]: {
|
|
128
|
+
type: "http",
|
|
129
|
+
scheme: scheme.scheme,
|
|
130
|
+
},
|
|
131
|
+
};
|
|
132
|
+
default:
|
|
133
|
+
throw new Error(`Unsupported security scheme type: ${scheme.type}`);
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
return openApiSecuritySchemes.reduce((acc, scheme) => {
|
|
137
|
+
return { ...acc, ...scheme };
|
|
138
|
+
}, {});
|
|
139
|
+
}
|
|
97
140
|
export async function generateOpenApiDoc(targetPath) {
|
|
98
141
|
const serverModule = await import(path.resolve(process.cwd(), targetPath));
|
|
99
142
|
const server = serverModule.default;
|
|
@@ -114,6 +157,7 @@ export async function generateOpenApiDoc(targetPath) {
|
|
|
114
157
|
}
|
|
115
158
|
return acc;
|
|
116
159
|
}, {});
|
|
160
|
+
const securitySchemes = extractSecuritySchemes(endpointDefinitions);
|
|
117
161
|
const openApiDocument = {
|
|
118
162
|
openapi: "3.0.0",
|
|
119
163
|
info: {
|
|
@@ -121,6 +165,9 @@ export async function generateOpenApiDoc(targetPath) {
|
|
|
121
165
|
version: "1.0.0",
|
|
122
166
|
},
|
|
123
167
|
paths: paths,
|
|
168
|
+
components: {
|
|
169
|
+
securitySchemes,
|
|
170
|
+
},
|
|
124
171
|
};
|
|
125
172
|
return openApiDocument;
|
|
126
173
|
}
|
|
@@ -1,16 +1,18 @@
|
|
|
1
1
|
import z from "zod";
|
|
2
2
|
import { HttpMethod } from "../../constants/HttpMethods";
|
|
3
|
+
import { SecurityScheme } from "../../security/SecuritySchema";
|
|
3
4
|
import { GenericResponseSchemaMap } from "./responses/index";
|
|
4
5
|
export interface ApiEndpointMeta {
|
|
5
6
|
name: string;
|
|
6
7
|
group: string;
|
|
7
8
|
description: string;
|
|
8
9
|
}
|
|
9
|
-
export type ApiEndpointDefinition<Path extends string = string, Method extends HttpMethod = HttpMethod, RequestBody extends z.ZodType | undefined = z.ZodType | undefined, Query extends z.ZodType | undefined = z.ZodType | undefined, ResponseMap extends GenericResponseSchemaMap = GenericResponseSchemaMap> = {
|
|
10
|
+
export type ApiEndpointDefinition<Path extends string = string, Method extends HttpMethod = HttpMethod, RequestBody extends z.ZodType | undefined = z.ZodType | undefined, Query extends z.ZodType | undefined = z.ZodType | undefined, ResponseMap extends GenericResponseSchemaMap = GenericResponseSchemaMap, SecuritySchemes extends SecurityScheme<unknown>[] = SecurityScheme<unknown>[]> = {
|
|
10
11
|
meta: ApiEndpointMeta;
|
|
11
12
|
path: Path;
|
|
12
13
|
method: Method;
|
|
13
14
|
requestBodySchema?: RequestBody;
|
|
14
15
|
querySchema?: Query;
|
|
15
16
|
responseSchemas: ResponseMap;
|
|
17
|
+
securitySchemes?: SecuritySchemes;
|
|
16
18
|
};
|
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
import { Request } from "express";
|
|
2
2
|
import { HttpStatusCodes } from "../../constants/HttpStatusCodes";
|
|
3
3
|
import { GenericResponse } from "./responses";
|
|
4
|
-
export type ApiEndpointHandler<PathParams extends Record<string, string> = {}, RequestBody = unknown, Query = unknown, Responses extends GenericResponse = never> = (request: Request<PathParams, unknown, RequestBody, Query, Record<string, unknown
|
|
4
|
+
export type ApiEndpointHandler<PathParams extends Record<string, string> = {}, RequestBody = unknown, Query = unknown, Responses extends GenericResponse = never, Caller = unknown> = (request: Request<PathParams, unknown, RequestBody, Query, Record<string, unknown>>, extractedRequestData: {
|
|
5
|
+
parameters: PathParams;
|
|
6
|
+
query: Query;
|
|
7
|
+
body: RequestBody;
|
|
8
|
+
caller: Caller;
|
|
9
|
+
}) => Promise<Responses | {
|
|
5
10
|
code: (typeof HttpStatusCodes)["InternalServerError_500"];
|
|
6
11
|
}>;
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import z from "zod";
|
|
2
2
|
import { HttpStatusCode } from "../../constants/HttpStatusCodes";
|
|
3
|
+
import { SecurityScheme } from "../../security/SecuritySchema";
|
|
3
4
|
import { Prettify } from "../../utils/types";
|
|
4
5
|
import { ApiEndpointHandler } from "./EndpointHandler";
|
|
5
6
|
import { ExtractPathParams } from "./PathParameters";
|
|
6
7
|
import { EmptyResponse, EmptyResponseSchema } from "./responses/emptyResponse";
|
|
7
8
|
import { GenericResponse, GenericResponseSchemaMap } from "./responses/index";
|
|
8
9
|
import { JsonResponseSchema, JsonResponseSchemaToResponseType } from "./responses/jsonResponse";
|
|
9
|
-
export type HandlerForDefinition<Path extends string, RequestBody extends z.ZodType | undefined, Query extends z.ZodType | undefined, ResponsesMap extends GenericResponseSchemaMap> = ApiEndpointHandler<ExtractPathParams<Path>, RequestBody extends undefined ? undefined : z.infer<RequestBody>, Query extends undefined ? undefined : z.infer<Query>, Exclude<Prettify<{
|
|
10
|
+
export type HandlerForDefinition<Path extends string, RequestBody extends z.ZodType | undefined, Query extends z.ZodType | undefined, ResponsesMap extends GenericResponseSchemaMap, SecuritySchemas extends SecurityScheme<unknown>[] = []> = ApiEndpointHandler<ExtractPathParams<Path>, RequestBody extends undefined ? undefined : z.infer<RequestBody>, Query extends undefined ? undefined : z.infer<Query>, Exclude<Prettify<{
|
|
10
11
|
[K in keyof ResponsesMap]: K extends HttpStatusCode ? ResponsesMap[K] extends JsonResponseSchema ? JsonResponseSchemaToResponseType<K, ResponsesMap[K]> : ResponsesMap[K] extends EmptyResponseSchema ? EmptyResponse<K> : ResponsesMap[K] extends undefined ? never : GenericResponse : never;
|
|
11
|
-
}[keyof ResponsesMap]>, undefined
|
|
12
|
+
}[keyof ResponsesMap]>, undefined>, SecuritySchemas extends SecurityScheme<infer Caller>[] ? Caller : unknown>;
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import z from "zod";
|
|
2
2
|
import { HttpMethod } from "../../constants/HttpMethods";
|
|
3
|
+
import { SecurityScheme } from "../../security/SecuritySchema";
|
|
3
4
|
import { Prettify } from "../../utils/types";
|
|
4
5
|
import { ApiEndpointDefinition } from "./EndpointDefinition";
|
|
5
6
|
import { ApiEndpointHandler } from "./EndpointHandler";
|
|
6
7
|
import { HandlerForDefinition } from "./HandlerFromDefinition";
|
|
7
8
|
import { GenericResponse, GenericResponseSchemaMap } from "./responses";
|
|
8
|
-
export declare function createApiEndpointHandler<const ResponsesMap extends GenericResponseSchemaMap, const Path extends string, const Method extends HttpMethod, const RequestBody extends z.ZodType | undefined = undefined, const Query extends z.ZodType | undefined = undefined>(definition: Prettify<ApiEndpointDefinition<Path, Method, RequestBody, Query, ResponsesMap>>, handler: HandlerForDefinition<Path, RequestBody, Query, ResponsesMap>): {
|
|
9
|
+
export declare function createApiEndpointHandler<const ResponsesMap extends GenericResponseSchemaMap, const Path extends string, const Method extends HttpMethod, const RequestBody extends z.ZodType | undefined = undefined, const Query extends z.ZodType | undefined = undefined, const SecuritySchemas extends SecurityScheme<unknown>[] = []>(definition: Prettify<ApiEndpointDefinition<Path, Method, RequestBody, Query, ResponsesMap, SecuritySchemas>>, handler: HandlerForDefinition<Path, RequestBody, Query, ResponsesMap>): {
|
|
9
10
|
definition: {
|
|
10
11
|
meta: import("./EndpointDefinition").ApiEndpointMeta;
|
|
11
12
|
path: Path;
|
|
@@ -13,6 +14,7 @@ export declare function createApiEndpointHandler<const ResponsesMap extends Gene
|
|
|
13
14
|
requestBodySchema?: RequestBody | undefined;
|
|
14
15
|
querySchema?: Query | undefined;
|
|
15
16
|
responseSchemas: ResponsesMap;
|
|
17
|
+
securitySchemes?: SecuritySchemas | undefined;
|
|
16
18
|
};
|
|
17
19
|
handler: HandlerForDefinition<Path, RequestBody, Query, ResponsesMap>;
|
|
18
20
|
};
|
|
@@ -8,7 +8,14 @@ export function createApiEndpointHandler(definition, handler) {
|
|
|
8
8
|
}
|
|
9
9
|
export function buildApiEndpointHandler(handler) {
|
|
10
10
|
return expressAsyncHandler(async (request, response) => {
|
|
11
|
-
const
|
|
11
|
+
const caller = response.locals.caller;
|
|
12
|
+
const extractedRequestData = {
|
|
13
|
+
parameters: request.params,
|
|
14
|
+
query: request.query,
|
|
15
|
+
body: request.body,
|
|
16
|
+
caller,
|
|
17
|
+
};
|
|
18
|
+
const result = await handler(request, extractedRequestData);
|
|
12
19
|
if (isJsonResponse(result)) {
|
|
13
20
|
response.status(result.code).json(result.json);
|
|
14
21
|
}
|
package/dist/server/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export { createApiEndpointHandler } from "./handlers/api/createApiHandler";
|
|
2
|
+
export { buildAuthenticationMiddleware } from "./middleware/auth";
|
|
2
3
|
export { createServer, type Server, type ServerConfig } from "./server";
|
|
3
4
|
declare const _default: {};
|
|
4
5
|
export default _default;
|
package/dist/server/index.js
CHANGED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { SecurityScheme } from "../security/SecuritySchema";
|
|
2
|
+
export declare function buildAuthenticationMiddleware<Caller>(schemes: SecurityScheme<Caller>[]): import("express").RequestHandler<import("express-serve-static-core").ParamsDictionary, any, any, import("qs").ParsedQs, Record<string, any>>;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import expressAsyncHandler from "express-async-handler";
|
|
2
|
+
import { authenticate } from "../security/SecuritySchema";
|
|
3
|
+
export function buildAuthenticationMiddleware(schemes) {
|
|
4
|
+
return expressAsyncHandler(async (request, response, next) => {
|
|
5
|
+
const caller = await authenticate(schemes, request);
|
|
6
|
+
if (caller == null) {
|
|
7
|
+
response.status(401).json({ message: "Unauthorized" });
|
|
8
|
+
return;
|
|
9
|
+
}
|
|
10
|
+
response.locals.caller = caller;
|
|
11
|
+
next();
|
|
12
|
+
});
|
|
13
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { Request } from "express";
|
|
2
|
+
import { BasicAuthScheme } from "./basicAuth";
|
|
3
|
+
import { BearerAuthScheme } from "./bearerAuth";
|
|
4
|
+
export type SecurityScheme<Caller> = BasicAuthScheme<Caller> | BearerAuthScheme<Caller>;
|
|
5
|
+
export declare function authenticate<Caller>(schemes: SecurityScheme<Caller>[], request: Request): Promise<Caller | null>;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { buildBasicAuthenticator } from "./basicAuth";
|
|
2
|
+
import { buildBearerAuthenticator } from "./bearerAuth";
|
|
3
|
+
export async function authenticate(schemes, request) {
|
|
4
|
+
const authenticationResults = await Promise.all(schemes.map((scheme) => {
|
|
5
|
+
switch (scheme.scheme) {
|
|
6
|
+
case "basic":
|
|
7
|
+
return buildBasicAuthenticator(scheme)(request);
|
|
8
|
+
case "bearer":
|
|
9
|
+
return buildBearerAuthenticator(scheme)(request);
|
|
10
|
+
}
|
|
11
|
+
}));
|
|
12
|
+
const successfulAuthentication = authenticationResults.find((result) => result !== null);
|
|
13
|
+
return successfulAuthentication ?? null;
|
|
14
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { Request } from "express";
|
|
2
|
+
export interface BasicAuthScheme<Caller = unknown> {
|
|
3
|
+
name: string;
|
|
4
|
+
type: "http";
|
|
5
|
+
scheme: "basic";
|
|
6
|
+
validateCaller: (username: string, password: string) => Promise<Caller | null>;
|
|
7
|
+
}
|
|
8
|
+
export declare function createBasicAuthSchema<Caller>(name: string, validateCaller: (username: string, password: string) => Promise<Caller | null>): BasicAuthScheme<Caller>;
|
|
9
|
+
export declare function buildBasicAuthenticator<Caller>(scheme: BasicAuthScheme<Caller>): (request: Request) => Promise<Caller | null>;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { hasNoValue } from "../utils/typeGuards";
|
|
2
|
+
export function createBasicAuthSchema(name, validateCaller) {
|
|
3
|
+
return {
|
|
4
|
+
name,
|
|
5
|
+
type: "http",
|
|
6
|
+
scheme: "basic",
|
|
7
|
+
validateCaller,
|
|
8
|
+
};
|
|
9
|
+
}
|
|
10
|
+
export function buildBasicAuthenticator(scheme) {
|
|
11
|
+
return async (request) => {
|
|
12
|
+
const authHeader = request.headers.authorization;
|
|
13
|
+
if (hasNoValue(authHeader) || !authHeader.startsWith("Basic ")) {
|
|
14
|
+
return null;
|
|
15
|
+
}
|
|
16
|
+
const base64Credentials = authHeader.slice("Basic ".length);
|
|
17
|
+
const credentials = Buffer.from(base64Credentials, "base64").toString("utf-8");
|
|
18
|
+
const [username, password] = credentials.split(":", 2);
|
|
19
|
+
return scheme.validateCaller(username, password);
|
|
20
|
+
};
|
|
21
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { Request } from "express";
|
|
2
|
+
export interface BearerAuthScheme<Caller = unknown> {
|
|
3
|
+
name: string;
|
|
4
|
+
type: "http";
|
|
5
|
+
scheme: "bearer";
|
|
6
|
+
validateCaller: (token: string) => Promise<Caller | null>;
|
|
7
|
+
}
|
|
8
|
+
export declare function createBearerAuthSchema<Caller>(name: string, validateCaller: (token: string) => Promise<Caller | null>): BearerAuthScheme<Caller>;
|
|
9
|
+
export declare function buildBearerAuthenticator<Caller>(scheme: BearerAuthScheme<Caller>): (request: Request) => Promise<Caller | null>;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export function createBearerAuthSchema(name, validateCaller) {
|
|
2
|
+
return {
|
|
3
|
+
name,
|
|
4
|
+
type: "http",
|
|
5
|
+
scheme: "bearer",
|
|
6
|
+
validateCaller,
|
|
7
|
+
};
|
|
8
|
+
}
|
|
9
|
+
export function buildBearerAuthenticator(scheme) {
|
|
10
|
+
return async (request) => {
|
|
11
|
+
const authHeader = request.headers.authorization;
|
|
12
|
+
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
|
|
13
|
+
return null;
|
|
14
|
+
}
|
|
15
|
+
const token = authHeader.slice("Bearer ".length);
|
|
16
|
+
return scheme.validateCaller(token);
|
|
17
|
+
};
|
|
18
|
+
}
|
package/dist/server/server.js
CHANGED
|
@@ -1,13 +1,18 @@
|
|
|
1
1
|
import cookieParser from "cookie-parser";
|
|
2
2
|
import express from "express";
|
|
3
3
|
import { buildApiEndpointHandler } from "./handlers/api/createApiHandler";
|
|
4
|
+
import { buildAuthenticationMiddleware } from "./middleware/auth";
|
|
4
5
|
import { buildRequestLogger, buildResponseLogger } from "./middleware/logging";
|
|
5
6
|
import { buildBodyValidatorMiddleware, buildQueryValidatorMiddleware, } from "./middleware/validation";
|
|
7
|
+
import { isEmpty } from "./utils/funcs";
|
|
6
8
|
import { NoOpLogger } from "./utils/logging";
|
|
7
9
|
import { hasNoValue, hasValue } from "./utils/typeGuards";
|
|
8
10
|
function registerApiEndpoint(expressApp, endpoint) {
|
|
9
11
|
const { definition, handler } = endpoint;
|
|
10
12
|
const handlerStack = [
|
|
13
|
+
hasValue(definition.securitySchemes) && !isEmpty(definition.securitySchemes)
|
|
14
|
+
? buildAuthenticationMiddleware(definition.securitySchemes)
|
|
15
|
+
: null,
|
|
11
16
|
hasValue(definition.querySchema)
|
|
12
17
|
? buildQueryValidatorMiddleware(definition.querySchema)
|
|
13
18
|
: null,
|