@rdyl/node-koa-controller 0.1.6 → 0.1.8

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 CHANGED
@@ -1,4 +1,4 @@
1
- ## 0.1.6 (2025-04-10)
1
+ ## 0.1.8 (2025-04-11)
2
2
 
3
3
 
4
4
 
@@ -0,0 +1,157 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
13
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ var __importDefault = (this && this.__importDefault) || function (mod) {
39
+ return (mod && mod.__esModule) ? mod : { "default": mod };
40
+ };
41
+ Object.defineProperty(exports, "__esModule", { value: true });
42
+ exports.JwtSecretGateway = void 0;
43
+ var crypto_js_1 = __importDefault(require("crypto-js"));
44
+ var JwtTokens = /** @class */ (function () {
45
+ function JwtTokens(KEY, duration) {
46
+ this.KEY = KEY;
47
+ this.duration = duration;
48
+ this.records = [];
49
+ }
50
+ JwtTokens.prototype.encode = function (payload) {
51
+ var KEY = this.KEY;
52
+ var text = JSON.stringify(payload);
53
+ return crypto_js_1.default.AES.encrypt(text, KEY).toString();
54
+ };
55
+ JwtTokens.prototype.decode = function (value) {
56
+ try {
57
+ var KEY = this.KEY;
58
+ var bytes = crypto_js_1.default.AES.decrypt(value, KEY);
59
+ var result = bytes.toString(crypto_js_1.default.enc.Utf8);
60
+ return JSON.parse(result);
61
+ }
62
+ catch (error) {
63
+ return null;
64
+ }
65
+ };
66
+ JwtTokens.prototype.removeBy = function (t) {
67
+ var records = this.records;
68
+ for (var i = 0; i < records.length; i++) {
69
+ var ele = records[i];
70
+ if (ele.token == t) {
71
+ this.records.splice(i, 1);
72
+ break;
73
+ }
74
+ }
75
+ };
76
+ JwtTokens.prototype.find = function (t) {
77
+ var records = this.records;
78
+ var result = null;
79
+ for (var i = 0; i < records.length; i++) {
80
+ var ele = records[i];
81
+ if (ele.token == t) {
82
+ result = ele;
83
+ break;
84
+ }
85
+ }
86
+ return result;
87
+ };
88
+ JwtTokens.prototype.get = function (token) {
89
+ return __awaiter(this, void 0, void 0, function () {
90
+ var result, time;
91
+ return __generator(this, function (_a) {
92
+ result = this.find(token);
93
+ if (!result) {
94
+ return [2 /*return*/, {
95
+ stat: "none",
96
+ value: null,
97
+ }];
98
+ }
99
+ else {
100
+ time = new Date().getTime();
101
+ if (result.expired <= time) {
102
+ this.removeBy(token);
103
+ return [2 /*return*/, {
104
+ stat: "expired",
105
+ value: result.data,
106
+ }];
107
+ }
108
+ return [2 /*return*/, {
109
+ stat: "ok",
110
+ value: result.data,
111
+ }];
112
+ }
113
+ return [2 /*return*/];
114
+ });
115
+ });
116
+ };
117
+ JwtTokens.prototype.authorize = function (data) {
118
+ var token = this.encode(data);
119
+ var created = new Date().getTime();
120
+ var item = {
121
+ token: token,
122
+ data: data,
123
+ created: created,
124
+ expired: created + this.duration,
125
+ };
126
+ this.records.push(item);
127
+ return token;
128
+ };
129
+ return JwtTokens;
130
+ }());
131
+ var JwtSecretGateway = /** @class */ (function () {
132
+ function JwtSecretGateway(headerName, opts) {
133
+ this.headerName = headerName;
134
+ var KEY = opts.KEY, _a = opts.duration, duration = _a === void 0 ? 7 * 24 * 60 * 60 * 1000 : _a;
135
+ this._jwtToken = new JwtTokens(KEY, duration);
136
+ }
137
+ JwtSecretGateway.prototype.use = function (ctx) {
138
+ return __awaiter(this, void 0, void 0, function () {
139
+ var token;
140
+ return __generator(this, function (_a) {
141
+ switch (_a.label) {
142
+ case 0:
143
+ token = ctx.request.headers[this.headerName.toLowerCase()] || "";
144
+ if (!(typeof token === "string")) return [3 /*break*/, 2];
145
+ return [4 /*yield*/, this._jwtToken.get(token)];
146
+ case 1: return [2 /*return*/, _a.sent()];
147
+ case 2: return [2 /*return*/, {
148
+ stat: "none",
149
+ value: null,
150
+ }];
151
+ }
152
+ });
153
+ });
154
+ };
155
+ return JwtSecretGateway;
156
+ }());
157
+ exports.JwtSecretGateway = JwtSecretGateway;
@@ -102,36 +102,32 @@ function RegisterASTCacheRoutes(router, useJwt) {
102
102
  }
103
103
  // @ts-ignore
104
104
  router[method.toLowerCase()](path, function (_ctx) { return __awaiter(_this, void 0, void 0, function () {
105
- var instance, token, jwt, _a;
106
- return __generator(this, function (_b) {
107
- switch (_b.label) {
105
+ var instance, _a, stat, value, _b;
106
+ return __generator(this, function (_c) {
107
+ switch (_c.label) {
108
108
  case 0:
109
- _b.trys.push([0, 4, , 5]);
110
109
  instance = new Instance(_ctx);
111
- if (!useJwt) return [3 /*break*/, 2];
112
- token = _ctx.request.headers[useJwt.name] || "";
113
- return [4 /*yield*/, useJwt.get(token)];
110
+ _c.label = 1;
114
111
  case 1:
115
- jwt = _b.sent();
116
- if (!jwt && !isPublic) {
112
+ _c.trys.push([1, 5, , 6]);
113
+ if (!useJwt) return [3 /*break*/, 3];
114
+ return [4 /*yield*/, useJwt.use(_ctx)];
115
+ case 2:
116
+ _a = _c.sent(), stat = _a.stat, value = _a.value;
117
+ if (stat === "none" || stat === "expired") {
117
118
  return [2 /*return*/, instance.status.unauthorized()];
118
119
  }
119
- instance.jwt = jwt;
120
- _b.label = 2;
121
- case 2: return [4 /*yield*/, Promise.resolve(instance[name]())];
122
- case 3:
123
- _b.sent();
124
- return [3 /*break*/, 5];
120
+ instance.jwt = value;
121
+ _c.label = 3;
122
+ case 3: return [4 /*yield*/, Promise.resolve(instance[name]())];
125
123
  case 4:
126
- _a = _b.sent();
127
- _ctx.response.set("Content-Type", "application/json;charset=utf-8");
128
- _ctx.response.status = 500;
129
- _ctx.body = {
130
- code: 500,
131
- msg: "未知错误",
132
- };
133
- return [3 /*break*/, 5];
134
- case 5: return [2 /*return*/];
124
+ _c.sent();
125
+ return [3 /*break*/, 6];
126
+ case 5:
127
+ _b = _c.sent();
128
+ instance.status.exception();
129
+ return [3 /*break*/, 6];
130
+ case 6: return [2 /*return*/];
135
131
  }
136
132
  });
137
133
  }); });
@@ -140,12 +136,12 @@ function RegisterASTCacheRoutes(router, useJwt) {
140
136
  }
141
137
  function useController(app, opts) {
142
138
  return __awaiter(this, void 0, void 0, function () {
143
- var root, _a, prefix, _b, port, _c, logs, formidable, useJwt, router, rootDir, initAST, ip;
139
+ var root, _a, prefix, _b, port, _c, logs, formidable, jwt, router, rootDir, initAST, ip;
144
140
  var _this = this;
145
141
  return __generator(this, function (_d) {
146
142
  switch (_d.label) {
147
143
  case 0:
148
- root = opts.root, _a = opts.prefix, prefix = _a === void 0 ? "" : _a, _b = opts.port, port = _b === void 0 ? 8080 : _b, _c = opts.logs, logs = _c === void 0 ? true : _c, formidable = opts.formidable, useJwt = opts.useJwt;
144
+ root = opts.root, _a = opts.prefix, prefix = _a === void 0 ? "" : _a, _b = opts.port, port = _b === void 0 ? 8080 : _b, _c = opts.logs, logs = _c === void 0 ? true : _c, formidable = opts.formidable, jwt = opts.jwt;
149
145
  exports.ASTCache.prefix = prefix;
150
146
  router = new koa_router_1.default();
151
147
  rootDir = (0, path_1.resolve)(process.cwd(), root);
@@ -197,7 +193,7 @@ function useController(app, opts) {
197
193
  case 1:
198
194
  _d.sent();
199
195
  // 注册路由
200
- RegisterASTCacheRoutes(router, useJwt);
196
+ RegisterASTCacheRoutes(router, jwt);
201
197
  if (opts.static) {
202
198
  app.use((0, koa_static_1.default)(process.cwd(), {
203
199
  root: opts.static,
@@ -272,3 +268,4 @@ function useController(app, opts) {
272
268
  });
273
269
  }
274
270
  __exportStar(require("./meta"), exports);
271
+ __exportStar(require("./gateway"), exports);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rdyl/node-koa-controller",
3
- "version": "0.1.6",
3
+ "version": "0.1.8",
4
4
  "license": "MIT",
5
5
  "main": "dist/index.js",
6
6
  "types": "types/index.d.ts",
@@ -18,11 +18,13 @@
18
18
  "build": "tsc && copyfiles -u 1 src/**/*.d.ts src/*.d.ts types && npm run changelog && git add CHANGELOG.md"
19
19
  },
20
20
  "dependencies": {
21
+ "@types/crypto-js": "^4.2.2",
21
22
  "@types/koa": "^2.15.0",
22
23
  "@types/koa-router": "^7.4.8",
23
24
  "@types/koa-static": "^4.0.4",
24
25
  "boxen": "^8.0.1",
25
26
  "chalk": "^5.4.1",
27
+ "crypto-js": "^4.2.0",
26
28
  "koa": "^2.15.3",
27
29
  "koa-body": "^6.0.1",
28
30
  "koa-router": "^13.0.1",
@@ -0,0 +1,34 @@
1
+ import { KoaCtx } from "./meta";
2
+ declare class JwtTokens<T> {
3
+ KEY: string;
4
+ duration: number;
5
+ records: JwtTokenItem<T>[];
6
+ constructor(KEY: string, duration: number);
7
+ encode(payload: T): string;
8
+ decode(value: string): T | null;
9
+ removeBy(t: string): void;
10
+ find(t: string): JwtTokenItem<T> | null;
11
+ get(token: string): Promise<JwtResData<T>>;
12
+ authorize(data: T): string;
13
+ }
14
+ export declare class JwtSecretGateway<T extends object> {
15
+ headerName: string;
16
+ _jwtToken: JwtTokens<T>;
17
+ constructor(headerName: string, opts: {
18
+ KEY: string;
19
+ duration?: number;
20
+ });
21
+ use(ctx: KoaCtx): Promise<JwtResData<T>>;
22
+ }
23
+ export interface JwtTokenItem<T> {
24
+ token: string;
25
+ data: T;
26
+ expired: number;
27
+ created: number;
28
+ }
29
+ export type JwtStat = "ok" | "expired" | "none";
30
+ export type JwtResData<T> = {
31
+ stat: JwtStat;
32
+ value: T;
33
+ };
34
+ export {};
@@ -1,5 +1,6 @@
1
1
  import Koa from "koa";
2
2
  import { ASTCacheProp, SyncUseValue, UseProps } from "./meta";
3
3
  export declare const ASTCache: ASTCacheProp;
4
- export declare function useController(app: Koa, opts: UseProps): Promise<SyncUseValue>;
4
+ export declare function useController<U extends object = object>(app: Koa, opts: UseProps<U>): Promise<SyncUseValue>;
5
5
  export * from "./meta";
6
+ export * from "./gateway";
@@ -1,6 +1,8 @@
1
1
  import { ParameterizedContext } from "koa";
2
2
  import { IRouterParamContext } from "koa-router";
3
3
  import { ExtendedFormidableOptions } from "koa-body";
4
+ import { JwtSecretGateway } from "./gateway";
5
+ export type KoaCtx = ParameterizedContext<any, IRouterParamContext<any, {}>, any>;
4
6
  export declare enum HttpMethod {
5
7
  GET = "GET",
6
8
  POST = "POST",
@@ -9,9 +11,9 @@ export declare enum HttpMethod {
9
11
  DELETE = "DELETE"
10
12
  }
11
13
  export declare class BaseController {
12
- _ctx: ParameterizedContext<any, IRouterParamContext<any, {}>, any>;
14
+ _ctx: KoaCtx;
13
15
  jwt: UseJwtValue;
14
- constructor(_ctx: ParameterizedContext<any, IRouterParamContext<any, {}>, any>);
16
+ constructor(_ctx: KoaCtx);
15
17
  get pathname(): string;
16
18
  get query(): {
17
19
  values: import("querystring").ParsedUrlQuery;
@@ -50,17 +52,14 @@ export interface ResData<T> {
50
52
  msg: string;
51
53
  data?: T | null;
52
54
  }
53
- export interface UseProps {
55
+ export interface UseProps<U extends object> {
54
56
  port: number;
55
57
  root: string;
56
58
  prefix?: string;
57
59
  static?: string;
58
60
  logs?: boolean;
59
61
  formidable?: ExtendedFormidableOptions;
60
- useJwt?: {
61
- name: string;
62
- get(n: string): Promise<UseJwtValue | null>;
63
- };
62
+ jwt?: JwtSecretGateway<U>;
64
63
  }
65
64
  export interface SyncUseValue {
66
65
  port: number;