@open-norantec/utilities 2.5.0 → 2.6.1

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.
@@ -1,4 +1,4 @@
1
- import { ExecutionContext, Hono } from 'hono';
1
+ import { Context, ExecutionContext, Hono } from 'hono';
2
2
  import { z } from './zod';
3
3
  import { Bindings as BindingsType } from 'hono/types';
4
4
  import { PartialDeep } from 'type-fest';
@@ -10,30 +10,39 @@ export declare class StatusError extends Error {
10
10
  readonly statusText?: string | undefined;
11
11
  constructor(status: ContentfulStatusCode, statusText?: string | undefined);
12
12
  }
13
- interface ConfigItem<IS extends HTTPBodyType, OS extends HTTPBodyType, Bindings extends BindingsType, SS extends z.ZodObject> {
14
- inputSchema: IS;
15
- outputSchema: OS;
16
- handler: (context: {
17
- env: Bindings;
18
- executionCtx: ExecutionContext;
19
- headers: Record<string, string>;
20
- input: IS extends string ? ReadableStreamDefaultReader<Uint8Array> : z.infer<IS>;
21
- storage: z.infer<SS>;
22
- }) => Promise<z.infer<OS>>;
13
+ type BaseContext<Bindings extends BindingsType, SS extends z.ZodObject> = {
14
+ env: Bindings;
15
+ executionCtx: ExecutionContext;
16
+ headers: Record<string, string>;
17
+ storage: z.infer<SS>;
18
+ queries: Context['req']['queries'];
19
+ query: Context['req']['query'];
20
+ };
21
+ interface AuthenticationMethod<Bindings extends BindingsType, SS extends z.ZodObject> {
22
+ match(authorizationHeaderValue?: string): string | undefined;
23
+ authenticate(context: BaseContext<Bindings, SS>, authenticationValue?: string): string | false | Promise<string | false>;
23
24
  }
25
+ type AuthenticationMethodMap<Bindings extends BindingsType, SS extends z.ZodObject> = Record<string, AuthenticationMethod<Bindings, SS>>;
26
+ type AuthKey<AMM extends AuthenticationMethodMap<{}, z.ZodObject>> = Extract<keyof AMM, string>;
27
+ type HandlerContext<IS extends HTTPBodyType, Bindings extends BindingsType, SS extends z.ZodObject, A extends Array<keyof AuthenticationMethodMap<Bindings, SS>>> = BaseContext<Bindings, SS> & {
28
+ authentication: A extends [] ? null : A[number];
29
+ authenticationValue: string | null;
30
+ input: IS extends string ? ReadableStreamDefaultReader<Uint8Array> : z.infer<IS>;
31
+ };
24
32
  interface HookContext {
25
33
  use: typeof Hono.prototype.use;
26
34
  }
27
35
  export declare class HonoUtil {
28
- static createHelper<Bindings extends BindingsType>(): <SS extends z.ZodObject>({ storageSchema, openAPIObject, openAPIPath, openAPIPrefix, onAfterSetRoutes, onBeforeSetRoutes, }: {
36
+ static createHelper<Bindings extends BindingsType>(): <SS extends z.ZodObject, AMM extends AuthenticationMethodMap<Bindings, SS>>({ storageSchema, openAPIObject, openAPIPath, openAPIPrefix, authenticationMethods, onAfterSetRoutes, onBeforeSetRoutes, }: {
29
37
  storageSchema: SS;
38
+ authenticationMethods?: AMM;
30
39
  openAPIObject?: PartialDeep<Omit<OpenAPIObject, "paths">>;
31
40
  openAPIPath?: string;
32
41
  openAPIPrefix?: string;
33
42
  onAfterSetRoutes?: (context: HookContext) => void;
34
43
  onBeforeSetRoutes?: (context: HookContext) => void;
35
44
  }) => {
36
- register: <IS extends HTTPBodyType, OS extends HTTPBodyType>(pathname: string, inputSchema: IS, outputSchema: OS, handler: ConfigItem<IS, OS, Bindings, SS>["handler"]) => void;
45
+ register: <IS extends HTTPBodyType, OS extends HTTPBodyType, const A extends Array<AuthKey<AMM>>>(pathname: string, inputSchema: IS, outputSchema: OS, authenticationTypes: A, handler: (context: HandlerContext<IS, Bindings, SS, A>) => Promise<z.infer<OS>>) => void;
37
46
  getApp: () => Hono<{
38
47
  Bindings: Bindings;
39
48
  }, import("hono/types").BlankSchema, "/">;
@@ -57,13 +57,14 @@ class StatusError extends Error {
57
57
  exports.StatusError = StatusError;
58
58
  class HonoUtil {
59
59
  static createHelper() {
60
- return function ({ storageSchema, openAPIObject = {}, openAPIPath = '/openapi', openAPIPrefix = '', onAfterSetRoutes, onBeforeSetRoutes, }) {
60
+ return function ({ storageSchema, openAPIObject = {}, openAPIPath = '/openapi', openAPIPrefix = '', authenticationMethods, onAfterSetRoutes, onBeforeSetRoutes, }) {
61
61
  const config = {};
62
62
  return {
63
- register: function (pathname, inputSchema, outputSchema, handler) {
63
+ register: function (pathname, inputSchema, outputSchema, authenticationTypes, handler) {
64
64
  config[pathname] = {
65
65
  inputSchema,
66
66
  outputSchema,
67
+ authenticationTypes,
67
68
  handler,
68
69
  };
69
70
  },
@@ -79,7 +80,7 @@ class HonoUtil {
79
80
  paths: {},
80
81
  }, _.omit(openAPIObject, ['paths']));
81
82
  onBeforeSetRoutes === null || onBeforeSetRoutes === void 0 ? void 0 : onBeforeSetRoutes(hookContext);
82
- Object.entries(config).forEach(([pathname, { inputSchema, outputSchema, handler }]) => {
83
+ Object.entries(config).forEach(([pathname, { inputSchema, outputSchema, authenticationTypes, handler }]) => {
83
84
  openAPIDocument.paths[`${openAPIPrefix}${pathname}`.replace(/^\/+/g, '/')] = {
84
85
  post: {
85
86
  requestBody: {
@@ -114,8 +115,7 @@ class HonoUtil {
114
115
  app.post(pathname, (c) => __awaiter(this, void 0, void 0, function* () {
115
116
  const input = typeof inputSchema === 'string' ? c.req.raw.body.getReader() : inputSchema.parse(yield c.req.json());
116
117
  const headers = c.req.header();
117
- const rawOutput = yield attempt_util_class_1.AttemptUtil.execPromise(handler({
118
- input,
118
+ const baseContext = {
119
119
  headers,
120
120
  env: c.env,
121
121
  executionCtx: c.executionCtx,
@@ -123,7 +123,39 @@ class HonoUtil {
123
123
  result[key] = c.get(key);
124
124
  return result;
125
125
  }, {})),
126
- }));
126
+ query: c.req.query.bind(c.req),
127
+ queries: c.req.queries.bind(c.req),
128
+ };
129
+ const authenticateResult = yield attempt_util_class_1.AttemptUtil.execPromise((() => __awaiter(this, void 0, void 0, function* () {
130
+ let authenticationValue = null;
131
+ if (!Array.isArray(authenticationTypes) || authenticationTypes.length === 0) {
132
+ return {
133
+ authenticationValue,
134
+ authentication: null,
135
+ };
136
+ }
137
+ const authorizationHeaderValue = c.req.header('Authorization');
138
+ const finalResult = yield Promise.all(authenticationTypes.map((authenticationType) => {
139
+ var _a, _b;
140
+ const instance = authenticationMethods === null || authenticationMethods === void 0 ? void 0 : authenticationMethods[authenticationType];
141
+ const matched = (_a = instance === null || instance === void 0 ? void 0 : instance.match) === null || _a === void 0 ? void 0 : _a.call(instance, authorizationHeaderValue);
142
+ if (typeof matched !== 'string') {
143
+ return { type: authenticationType, result: false };
144
+ }
145
+ return Promise.resolve((_b = instance === null || instance === void 0 ? void 0 : instance.authenticate) === null || _b === void 0 ? void 0 : _b.call(instance, baseContext, matched)).then((result) => ({
146
+ type: authenticationType,
147
+ result,
148
+ }));
149
+ })).then((results) => results.find(({ result }) => typeof result === 'string'));
150
+ if (!(finalResult === null || finalResult === void 0 ? void 0 : finalResult.type))
151
+ throw new StatusError(401);
152
+ return { authenticationValue: finalResult.result, authentication: finalResult.type };
153
+ }))());
154
+ if (authenticateResult instanceof Error) {
155
+ return c.json({ error: authenticateResult.message }, authenticateResult instanceof StatusError ? authenticateResult.status : 400);
156
+ }
157
+ const { authentication, authenticationValue } = authenticateResult;
158
+ const rawOutput = yield attempt_util_class_1.AttemptUtil.execPromise(handler(Object.assign({ input, authentication: authentication, authenticationValue }, baseContext)));
127
159
  if (rawOutput instanceof Error) {
128
160
  console.log('Handler error', rawOutput, rawOutput === null || rawOutput === void 0 ? void 0 : rawOutput.message, rawOutput === null || rawOutput === void 0 ? void 0 : rawOutput.stack);
129
161
  return c.json({ error: rawOutput.message }, rawOutput instanceof StatusError ? rawOutput.status : 400);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-norantec/utilities",
3
- "version": "2.5.0",
3
+ "version": "2.6.1",
4
4
  "description": "NoranTec Utilities",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {