topbit 3.0.5 → 3.0.6
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/LICENSE +15 -122
- package/README.cn.md +1 -1
- package/README.md +1 -1
- package/docs/README.md +16 -0
- package/docs/en/topbit-loader.md +305 -0
- package/docs/en/topbit-token.md +136 -0
- package/docs/topbit-loader.md +302 -0
- package/docs/topbit-token.md +166 -0
- package/images/topbit-middleware.webp +0 -0
- package/package.json +1 -1
- package/src/token/token.js +2 -2
package/LICENSE
CHANGED
|
@@ -1,128 +1,21 @@
|
|
|
1
|
-
|
|
1
|
+
Copyright (c) [2025] [Copyright Holder]
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
Permission to use, copy, modify, and/or distribute this software for any
|
|
4
|
+
purpose with or without fee is hereby granted, provided that the above
|
|
5
|
+
copyright notice and this permission notice appear in all copies.
|
|
5
6
|
|
|
7
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
|
8
|
+
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
|
9
|
+
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
|
10
|
+
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
|
11
|
+
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
|
12
|
+
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
|
13
|
+
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
|
6
14
|
|
|
7
|
-
|
|
15
|
+
---------------------------------------------
|
|
8
16
|
|
|
9
|
-
|
|
17
|
+
版权所有 (c) [2025] [版权所有者]
|
|
10
18
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
“贡献”是指由任一“贡献者”许可在“本许可证”下的受版权法保护的作品。
|
|
14
|
-
|
|
15
|
-
“贡献者”是指将受版权法保护的作品许可在“本许可证”下的自然人或“法人实体”。
|
|
16
|
-
|
|
17
|
-
“法人实体”是指提交贡献的机构及其“关联实体”。
|
|
18
|
-
|
|
19
|
-
“关联实体”是指,对“本许可证”下的行为方而言,控制、受控制或与其共同受控制的机构,此处的控制是指有受控方或共同受控方至少50%直接或间接的投票权、资金或其他有价证券。
|
|
20
|
-
|
|
21
|
-
1. 授予版权许可
|
|
22
|
-
|
|
23
|
-
每个“贡献者”根据“本许可证”授予您永久性的、全球性的、免费的、非独占的、不可撤销的版权许可,您可以复制、使用、修改、分发其“贡献”,不论修改与否。
|
|
24
|
-
|
|
25
|
-
2. 授予专利许可
|
|
26
|
-
|
|
27
|
-
每个“贡献者”根据“本许可证”授予您永久性的、全球性的、免费的、非独占的、不可撤销的(根据本条规定撤销除外)专利许可,供您制造、委托制造、使用、许诺销售、销售、进口其“贡献”或以其他方式转移其“贡献”。前述专利许可仅限于“贡献者”现在或将来拥有或控制的其“贡献”本身或其“贡献”与许可“贡献”时的“软件”结合而将必然会侵犯的专利权利要求,不包括对“贡献”的修改或包含“贡献”的其他结合。如果您或您的“关联实体”直接或间接地,就“软件”或其中的“贡献”对任何人发起专利侵权诉讼(包括反诉或交叉诉讼)或其他专利维权行动,指控其侵犯专利权,则“本许可证”授予您对“软件”的专利许可自您提起诉讼或发起维权行动之日终止。
|
|
28
|
-
|
|
29
|
-
3. 无商标许可
|
|
30
|
-
|
|
31
|
-
“本许可证”不提供对“贡献者”的商品名称、商标、服务标志或产品名称的商标许可,但您为满足第4条规定的声明义务而必须使用除外。
|
|
32
|
-
|
|
33
|
-
4. 分发限制
|
|
34
|
-
|
|
35
|
-
您可以在任何媒介中将“软件”以源程序形式或可执行形式重新分发,不论修改与否,但您必须向接收者提供“本许可证”的副本,并保留“软件”中的版权、商标、专利及免责声明。
|
|
36
|
-
|
|
37
|
-
5. 免责声明与责任限制
|
|
38
|
-
|
|
39
|
-
“软件”及其中的“贡献”在提供时不带任何明示或默示的担保。在任何情况下,“贡献者”或版权所有者不对任何人因使用“软件”或其中的“贡献”而引发的任何直接或间接损失承担责任,不论因何种原因导致或者基于何种法律理论,即使其曾被建议有此种损失的可能性。
|
|
40
|
-
|
|
41
|
-
6. 语言
|
|
42
|
-
“本许可证”以中英文双语表述,中英文版本具有同等法律效力。如果中英文版本存在任何冲突不一致,以中文版为准。
|
|
43
|
-
|
|
44
|
-
条款结束
|
|
45
|
-
|
|
46
|
-
如何将木兰宽松许可证,第2版,应用到您的软件
|
|
47
|
-
|
|
48
|
-
如果您希望将木兰宽松许可证,第2版,应用到您的新软件,为了方便接收者查阅,建议您完成如下三步:
|
|
49
|
-
|
|
50
|
-
1, 请您补充如下声明中的空白,包括软件名、软件的首次发表年份以及您作为版权人的名字;
|
|
51
|
-
|
|
52
|
-
2, 请您在软件包的一级目录下创建以“LICENSE”为名的文件,将整个许可证文本放入该文件中;
|
|
53
|
-
|
|
54
|
-
3, 请将如下声明文本放入每个源文件的头部注释中。
|
|
55
|
-
|
|
56
|
-
Copyright (c) [Year] [name of copyright holder]
|
|
57
|
-
[Software Name] is licensed under Mulan PSL v2.
|
|
58
|
-
You can use this software according to the terms and conditions of the Mulan PSL v2.
|
|
59
|
-
You may obtain a copy of Mulan PSL v2 at:
|
|
60
|
-
http://license.coscl.org.cn/MulanPSL2
|
|
61
|
-
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
|
|
62
|
-
See the Mulan PSL v2 for more details.
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
Mulan Permissive Software License,Version 2
|
|
66
|
-
|
|
67
|
-
Mulan Permissive Software License,Version 2 (Mulan PSL v2)
|
|
68
|
-
January 2020 http://license.coscl.org.cn/MulanPSL2
|
|
69
|
-
|
|
70
|
-
Your reproduction, use, modification and distribution of the Software shall be subject to Mulan PSL v2 (this License) with the following terms and conditions:
|
|
71
|
-
|
|
72
|
-
0. Definition
|
|
73
|
-
|
|
74
|
-
Software means the program and related documents which are licensed under this License and comprise all Contribution(s).
|
|
75
|
-
|
|
76
|
-
Contribution means the copyrightable work licensed by a particular Contributor under this License.
|
|
77
|
-
|
|
78
|
-
Contributor means the Individual or Legal Entity who licenses its copyrightable work under this License.
|
|
79
|
-
|
|
80
|
-
Legal Entity means the entity making a Contribution and all its Affiliates.
|
|
81
|
-
|
|
82
|
-
Affiliates means entities that control, are controlled by, or are under common control with the acting entity under this License, ‘control’ means direct or indirect ownership of at least fifty percent (50%) of the voting power, capital or other securities of controlled or commonly controlled entity.
|
|
83
|
-
|
|
84
|
-
1. Grant of Copyright License
|
|
85
|
-
|
|
86
|
-
Subject to the terms and conditions of this License, each Contributor hereby grants to you a perpetual, worldwide, royalty-free, non-exclusive, irrevocable copyright license to reproduce, use, modify, or distribute its Contribution, with modification or not.
|
|
87
|
-
|
|
88
|
-
2. Grant of Patent License
|
|
89
|
-
|
|
90
|
-
Subject to the terms and conditions of this License, each Contributor hereby grants to you a perpetual, worldwide, royalty-free, non-exclusive, irrevocable (except for revocation under this Section) patent license to make, have made, use, offer for sale, sell, import or otherwise transfer its Contribution, where such patent license is only limited to the patent claims owned or controlled by such Contributor now or in future which will be necessarily infringed by its Contribution alone, or by combination of the Contribution with the Software to which the Contribution was contributed. The patent license shall not apply to any modification of the Contribution, and any other combination which includes the Contribution. If you or your Affiliates directly or indirectly institute patent litigation (including a cross claim or counterclaim in a litigation) or other patent enforcement activities against any individual or entity by alleging that the Software or any Contribution in it infringes patents, then any patent license granted to you under this License for the Software shall terminate as of the date such litigation or activity is filed or taken.
|
|
91
|
-
|
|
92
|
-
3. No Trademark License
|
|
93
|
-
|
|
94
|
-
No trademark license is granted to use the trade names, trademarks, service marks, or product names of Contributor, except as required to fulfill notice requirements in Section 4.
|
|
95
|
-
|
|
96
|
-
4. Distribution Restriction
|
|
97
|
-
|
|
98
|
-
You may distribute the Software in any medium with or without modification, whether in source or executable forms, provided that you provide recipients with a copy of this License and retain copyright, patent, trademark and disclaimer statements in the Software.
|
|
99
|
-
|
|
100
|
-
5. Disclaimer of Warranty and Limitation of Liability
|
|
101
|
-
|
|
102
|
-
THE SOFTWARE AND CONTRIBUTION IN IT ARE PROVIDED WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED. IN NO EVENT SHALL ANY CONTRIBUTOR OR COPYRIGHT HOLDER BE LIABLE TO YOU FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO ANY DIRECT, OR INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING FROM YOUR USE OR INABILITY TO USE THE SOFTWARE OR THE CONTRIBUTION IN IT, NO MATTER HOW IT’S CAUSED OR BASED ON WHICH LEGAL THEORY, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
|
103
|
-
|
|
104
|
-
6. Language
|
|
105
|
-
|
|
106
|
-
THIS LICENSE IS WRITTEN IN BOTH CHINESE AND ENGLISH, AND THE CHINESE VERSION AND ENGLISH VERSION SHALL HAVE THE SAME LEGAL EFFECT. IN THE CASE OF DIVERGENCE BETWEEN THE CHINESE AND ENGLISH VERSIONS, THE CHINESE VERSION SHALL PREVAIL.
|
|
107
|
-
|
|
108
|
-
END OF THE TERMS AND CONDITIONS
|
|
109
|
-
|
|
110
|
-
How to Apply the Mulan Permissive Software License,Version 2 (Mulan PSL v2) to Your Software
|
|
111
|
-
|
|
112
|
-
To apply the Mulan PSL v2 to your work, for easy identification by recipients, you are suggested to complete following three steps:
|
|
113
|
-
|
|
114
|
-
i Fill in the blanks in following statement, including insert your software name, the year of the first publication of your software, and your name identified as the copyright owner;
|
|
115
|
-
|
|
116
|
-
ii Create a file named “LICENSE” which contains the whole context of this License in the first directory of your software package;
|
|
117
|
-
|
|
118
|
-
iii Attach the statement to the appropriate annotated syntax at the beginning of each source file.
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
Copyright (c) [Year] [name of copyright holder]
|
|
122
|
-
[Software Name] is licensed under Mulan PSL v2.
|
|
123
|
-
You can use this software according to the terms and conditions of the Mulan PSL v2.
|
|
124
|
-
You may obtain a copy of Mulan PSL v2 at:
|
|
125
|
-
http://license.coscl.org.cn/MulanPSL2
|
|
126
|
-
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
|
|
127
|
-
See the Mulan PSL v2 for more details.
|
|
19
|
+
特此授权,允许出于任何目的使用、复制、修改和/或分发本软件,无论是否收费,前提是必须在所有副本中保留上述版权声明和本许可声明。
|
|
128
20
|
|
|
21
|
+
本软件按“原样”提供,作者不作任何明示或暗示的保证,包括但不限于适销性和特定用途适用性的暗示保证。在任何情况下,作者均不对因使用或运行本软件而引起的或与之相关的任何特殊、直接、间接或后果性损害,或因使用、数据或利润损失而导致的任何损害承担责任,无论是在合同诉讼、疏忽或其他侵权行为诉讼中。
|
package/README.cn.md
CHANGED
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
# Topbit
|
|
4
4
|
|
|
5
|
-
[中文文档](README.cn.md)
|
|
5
|
+
#### [🪭 中文文档 ☯️](README.cn.md)
|
|
6
6
|
|
|
7
7
|
Topbit is a server-side Web framework based on Node.js. It has no third-party dependencies and is optimized for extreme performance with a unique routing and middleware grouping execution mechanism.
|
|
8
8
|
|
package/docs/README.md
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
# TopbitLoader Complete User Manual
|
|
2
|
+
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
### 1. What is TopbitLoader?
|
|
6
|
+
|
|
7
|
+
TopbitLoader is the official recommended auto-loading extension for the Topbit framework. It completely eliminates the need to manually write `app.get()`, `app.post()`, `app.use()`, etc.
|
|
8
|
+
|
|
9
|
+
It implements a true MCM pattern (Middleware → Controller → Model) — lightweight, ultra-fast, and perfectly aligned with Topbit’s extreme-performance philosophy.
|
|
10
|
+
|
|
11
|
+
**One sentence summary:**
|
|
12
|
+
> Write your project following the conventional directory structure, then just call `new Loader().init(app)` once — all routes, middlewares, and models are automatically loaded.
|
|
13
|
+
|
|
14
|
+
---
|
|
15
|
+
|
|
16
|
+
### 2. Recommended Project Structure
|
|
17
|
+
|
|
18
|
+
```
|
|
19
|
+
project/
|
|
20
|
+
├── app.js # Entry file (full example below)
|
|
21
|
+
├── controller/ # Controllers (required)
|
|
22
|
+
│ ├── __mid.js # Global middleware list (optional)
|
|
23
|
+
│ ├── user.js # → /user group
|
|
24
|
+
│ ├── admin/ # Sub-group
|
|
25
|
+
│ │ ├── __mid.js # Middleware only for admin group
|
|
26
|
+
│ │ └── index.js # → /admin
|
|
27
|
+
│ └── api/
|
|
28
|
+
│ ├── __mid.js
|
|
29
|
+
│ └── v1/
|
|
30
|
+
│ └── post.js # → /api/v1/post
|
|
31
|
+
├── middleware/ # Class-style middlewares (required)
|
|
32
|
+
│ ├── @auth.js # Must start with @
|
|
33
|
+
│ ├── @cors.js
|
|
34
|
+
│ └── rate-limit.js # Plain function middleware (less common)
|
|
35
|
+
└── model/ # Models (optional)
|
|
36
|
+
└── user.js
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
---
|
|
40
|
+
|
|
41
|
+
### 3. 30-Second Quick Start
|
|
42
|
+
|
|
43
|
+
```js
|
|
44
|
+
// app.js
|
|
45
|
+
'use strict'
|
|
46
|
+
process.chdir(__dirname)
|
|
47
|
+
|
|
48
|
+
const Topbit = require('topbit')
|
|
49
|
+
const { Loader } = Topbit
|
|
50
|
+
|
|
51
|
+
const app = new Topbit({
|
|
52
|
+
debug: true,
|
|
53
|
+
http2: true,
|
|
54
|
+
allowHTTP1: true,
|
|
55
|
+
cert: './cert/fullchain.pem',
|
|
56
|
+
key: './cert/privkey.pem'
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
if (app.isWorker) {
|
|
60
|
+
// One line only – everything is auto-loaded
|
|
61
|
+
new Loader().init(app)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
app.autoWorker(16) // Max elastic workers
|
|
65
|
+
app.daemon(443, 4) // 4 base workers
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Run `node app.js` → full-featured service is up!
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
### 4. Configuration Options
|
|
73
|
+
|
|
74
|
+
| Option | Type | Default | Description |
|
|
75
|
+
|----------------------|--------------------|---------------|-------------------------------------------------------------------------------------------------|
|
|
76
|
+
| `appPath` | string | `.` | Project root directory |
|
|
77
|
+
| `controllerPath` | string | `./controller`| Controller folder |
|
|
78
|
+
| `midwarePath` | string | `./middleware`| Middleware class folder |
|
|
79
|
+
| `prePath` | string | `''` | Global route prefix (e.g. `/api/v1`) |
|
|
80
|
+
| `subgroup` | string\|Array | `null` | Load only specified subdirectories (e.g. `['admin','api']`) |
|
|
81
|
+
| `fileAsGroup` | boolean | `true` | Highly recommended – each controller file becomes its own route group (precise middleware) |
|
|
82
|
+
| `optionsRoute` | boolean | `true` | Auto-add `OPTIONS /*` routes for CORS preflight |
|
|
83
|
+
| `multi` | boolean | `false` | Allow multiple `init()` calls (keep `false` in production) |
|
|
84
|
+
| `homeFile` | string | `''` | Which file serves the root `/` route (e.g. `'index.js'`) |
|
|
85
|
+
| `initArgs` | any | `app.service` | Arguments passed to every controller’s `init()` method |
|
|
86
|
+
| `beforeController` | function | `null` | Hook executed after controller instantiation, before route registration |
|
|
87
|
+
| `afterController` | function | `null` | Hook executed after route registration |
|
|
88
|
+
| `modelLoader` | async function | `null` | Powerful extension point – custom model loading (recommended with topbit-model) |
|
|
89
|
+
|
|
90
|
+
**Most common production config:**
|
|
91
|
+
|
|
92
|
+
```js
|
|
93
|
+
new Loader({
|
|
94
|
+
prePath: '/api/v1',
|
|
95
|
+
fileAsGroup: true,
|
|
96
|
+
optionsRoute: true,
|
|
97
|
+
modelLoader: async (service) => {
|
|
98
|
+
const UserModel = require('./model/user')
|
|
99
|
+
service.userModel = new UserModel(service)
|
|
100
|
+
}
|
|
101
|
+
}).init(app)
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
---
|
|
105
|
+
|
|
106
|
+
### 5. Controller Writing Guide
|
|
107
|
+
|
|
108
|
+
#### 5.1 Minimal RESTful Style (Recommended)
|
|
109
|
+
|
|
110
|
+
```js
|
|
111
|
+
// controller/user.js
|
|
112
|
+
class User {
|
|
113
|
+
async get(c) { // GET /user/:id
|
|
114
|
+
c.to({ id: c.param.id })
|
|
115
|
+
}
|
|
116
|
+
async list(c) { // GET /user
|
|
117
|
+
c.to(['alice', 'bob'])
|
|
118
|
+
}
|
|
119
|
+
async post(c) { // POST /user
|
|
120
|
+
c.to({ saved: true })
|
|
121
|
+
}
|
|
122
|
+
async put(c) { // PUT /user/:id
|
|
123
|
+
c.to({ updated: true })
|
|
124
|
+
}
|
|
125
|
+
async delete(c) { // DELETE /user/:id
|
|
126
|
+
c.to({ deleted: true })
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
module.exports = User
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
#### 5.2 Custom Path Parameters
|
|
133
|
+
|
|
134
|
+
```js
|
|
135
|
+
class User {
|
|
136
|
+
static param = '/:uid/profile' // overrides default /:id
|
|
137
|
+
static postParam = '/register' // POST /user/register
|
|
138
|
+
|
|
139
|
+
async post(c) {
|
|
140
|
+
c.ok('registered')
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
#### 5.3 File-Specific Middleware
|
|
146
|
+
|
|
147
|
+
```js
|
|
148
|
+
class User {
|
|
149
|
+
static __mid() {
|
|
150
|
+
return [
|
|
151
|
+
[require('../middleware/@auth'), { pre: true }],
|
|
152
|
+
require('../middleware/rate-limit')
|
|
153
|
+
]
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
#### 5.4 Homepage Controller
|
|
159
|
+
|
|
160
|
+
```js
|
|
161
|
+
// controller/index.js
|
|
162
|
+
class Index {
|
|
163
|
+
async get(c) {
|
|
164
|
+
c.html('<h1>Welcome to Topbit</h1>')
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
module.exports = Index
|
|
168
|
+
|
|
169
|
+
// In Loader config:
|
|
170
|
+
new Loader({ homeFile: 'index.js' }).init(app)
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
---
|
|
174
|
+
|
|
175
|
+
### 6. Middleware Writing Guide
|
|
176
|
+
|
|
177
|
+
#### 6.1 Class-Style Middleware (Recommended – file name starts with `@`)
|
|
178
|
+
|
|
179
|
+
```js
|
|
180
|
+
// middleware/@auth.js
|
|
181
|
+
class Auth {
|
|
182
|
+
async middleware(c, next) {
|
|
183
|
+
if (!c.headers.token) return c.status(401).to('Token required')
|
|
184
|
+
c.user = { id: 1 }
|
|
185
|
+
await next(c)
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
module.exports = Auth
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
#### 6.2 Global / Group Middleware via `__mid.js`
|
|
192
|
+
|
|
193
|
+
```js
|
|
194
|
+
// controller/__mid.js (global) or controller/admin/__mid.js (group)
|
|
195
|
+
module.exports = [
|
|
196
|
+
{ name: '@auth' }, // class middleware
|
|
197
|
+
{ name: 'rate-limit', method: ['GET','POST'] }, // plain function
|
|
198
|
+
{ middleware: async (c, next) => { // inline
|
|
199
|
+
console.log('global mid')
|
|
200
|
+
await next(c)
|
|
201
|
+
}, pre: true }
|
|
202
|
+
]
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
#### 6.3 File-Level Middleware (Most Precise)
|
|
206
|
+
|
|
207
|
+
```js
|
|
208
|
+
// Inside any controller file
|
|
209
|
+
static __mid() {
|
|
210
|
+
return [
|
|
211
|
+
{ name: '@vip-auth', pre: true },
|
|
212
|
+
{ name: 'log', method: 'POST' }
|
|
213
|
+
]
|
|
214
|
+
}
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
---
|
|
218
|
+
|
|
219
|
+
### 7. Model Loading (modelLoader) Best Practice
|
|
220
|
+
|
|
221
|
+
```js
|
|
222
|
+
new Loader({
|
|
223
|
+
modelLoader: async (service) => {
|
|
224
|
+
const glob = require('glob')
|
|
225
|
+
const path = require('path')
|
|
226
|
+
const files = glob.sync('model/**/*.js', { cwd: __dirname })
|
|
227
|
+
|
|
228
|
+
for (const f of files) {
|
|
229
|
+
const Model = require(path.resolve(__dirname, f))
|
|
230
|
+
const name = path.basename(f, '.js')
|
|
231
|
+
service[name + 'Model'] = new Model(service)
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}).init(app)
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
---
|
|
238
|
+
|
|
239
|
+
### 8. Naming & Safety Rules
|
|
240
|
+
|
|
241
|
+
- Folder and file names may only contain: `a-z 0-9 _ -` and must start with a letter
|
|
242
|
+
- No spaces, Chinese characters, uppercase letters, or special symbols
|
|
243
|
+
- Files/folders starting with `!` are automatically ignored
|
|
244
|
+
- Violation → red warning + skip loading
|
|
245
|
+
|
|
246
|
+
---
|
|
247
|
+
|
|
248
|
+
### 9. Advanced Tips Collection
|
|
249
|
+
|
|
250
|
+
| Need | Solution |
|
|
251
|
+
|---------------------------------|-------------------------------------------------------------------------------------------------------|
|
|
252
|
+
| Multiple API versions coexist | Use different `prePath` and create multiple Loader instances |
|
|
253
|
+
| Canary / gray release | `subgroup: ['v2']` + Nginx traffic split |
|
|
254
|
+
| Plugin system | Each plugin has its own folder → `new Loader({ appPath: './plugins/xxx' }).init(app)` |
|
|
255
|
+
| Hot reload (dev) | Set `multi: true` + watch files with chokidar and re-call `init()` |
|
|
256
|
+
|
|
257
|
+
---
|
|
258
|
+
|
|
259
|
+
### 10. Production-Grade Full Entry Example
|
|
260
|
+
|
|
261
|
+
```js
|
|
262
|
+
// app.js (Ultimate production version)
|
|
263
|
+
'use strict'
|
|
264
|
+
process.chdir(__dirname)
|
|
265
|
+
|
|
266
|
+
const Topbit = require('topbit')
|
|
267
|
+
const { Loader } = Topbit
|
|
268
|
+
|
|
269
|
+
const app = new Topbit({
|
|
270
|
+
debug: false,
|
|
271
|
+
http2: true,
|
|
272
|
+
allowHTTP1: true,
|
|
273
|
+
cert: '/etc/ssl/certs/fullchain.pem',
|
|
274
|
+
key: '/etc/ssl/private/privkey.pem',
|
|
275
|
+
globalLog: true,
|
|
276
|
+
logType: 'file',
|
|
277
|
+
logFile: '/var/log/topbit/access.log',
|
|
278
|
+
errorLogFile: '/var/log/topbit/error.log'
|
|
279
|
+
})
|
|
280
|
+
|
|
281
|
+
if (app.isWorker) {
|
|
282
|
+
new Loader({
|
|
283
|
+
prePath: '/api',
|
|
284
|
+
fileAsGroup: true,
|
|
285
|
+
optionsRoute: true,
|
|
286
|
+
modelLoader: async (svc) => {
|
|
287
|
+
svc.db = require('./lib/mysql-pool')
|
|
288
|
+
svc.redis = require('./lib/redis-client')
|
|
289
|
+
}
|
|
290
|
+
}).init(app)
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
app.sched('none')
|
|
294
|
+
app.autoWorker(32)
|
|
295
|
+
app.daemon(443, 8)
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
---
|
|
299
|
+
|
|
300
|
+
**You have now mastered the complete essence of TopbitLoader!**
|
|
301
|
+
|
|
302
|
+
Start using it today and you’ll find:
|
|
303
|
+
> Topbit + TopbitLoader = possibly the best developer experience + highest performance backend combination in the current Node.js ecosystem.
|
|
304
|
+
|
|
305
|
+
Happy coding and may your services fly!
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
# TopbitToken – Ultra-Fast & Secure Token System for Topbit
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
### 1. What is TopbitToken?
|
|
5
|
+
|
|
6
|
+
TopbitToken is a zero-dependency, minimalist, high-security encrypted token system designed specifically for the Topbit framework.
|
|
7
|
+
|
|
8
|
+
Built entirely on Node.js native `crypto`, supports:
|
|
9
|
+
|
|
10
|
+
- AES-256-GCM (default, recommended)
|
|
11
|
+
- AES-192-GCM / AES-128-CBC / AES-256-CBC
|
|
12
|
+
- SM4-CBC (China GM standard)
|
|
13
|
+
|
|
14
|
+
**One-sentence summary:**
|
|
15
|
+
> 3 lines of code = Issue + Verify + Auto-refresh + Instant revocation (hot-swappable keys)
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
### 2. Why Choose TopbitToken?
|
|
20
|
+
|
|
21
|
+
| Feature | Description |
|
|
22
|
+
|--------------------------------|----------------------------------------------------------------------------------|
|
|
23
|
+
| **Zero Dependencies** | Pure native crypto, no jwt/jsonwebtoken |
|
|
24
|
+
| **Lightning Fast** | AES-NI + GCM mode, < 0.05ms per verification |
|
|
25
|
+
| **Refresh Auto Token Refresh** | Automatically issues new token when nearing expiry |
|
|
26
|
+
| **Key Multiple Keys (tokenId)**| Supports multiple key sets, switch master key = instantly invalidate all old tokens |
|
|
27
|
+
| **Shield Tamper-proof** | Built-in timestamp + expiry + tokenId validation |
|
|
28
|
+
| **Lock Instant Revocation** | Remove a tokenId → all related tokens die immediately, no waiting |
|
|
29
|
+
| **Gear SM4 Support** | Full support for China national crypto standard |
|
|
30
|
+
|
|
31
|
+
---
|
|
32
|
+
|
|
33
|
+
### 3. 30-Second Quick Start
|
|
34
|
+
|
|
35
|
+
```js
|
|
36
|
+
// middleware/@token.js
|
|
37
|
+
const TopbitToken = require('topbit-token')
|
|
38
|
+
|
|
39
|
+
const token = new TopbitToken({
|
|
40
|
+
key : 'your-very-strong-32-byte-secret!!',
|
|
41
|
+
expires : 60 * 60 * 24, // 24 hours
|
|
42
|
+
refresh : true // Enable auto refresh
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
module.exports = token
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
```js
|
|
49
|
+
// controller/user.js
|
|
50
|
+
async post(c) {
|
|
51
|
+
// After successful login
|
|
52
|
+
const userinfo = { uid: 1, name: 'Alice', role: 'admin' }
|
|
53
|
+
const t = token.make(userinfo)
|
|
54
|
+
c.setHeader('authorization', t)
|
|
55
|
+
c.to({ok: true})
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// All protected routes automatically use token.mid()
|
|
59
|
+
// Verified user info → c.user
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
---
|
|
63
|
+
|
|
64
|
+
### 4. Full Configuration Options
|
|
65
|
+
|
|
66
|
+
| Option | Type | Default | Description |
|
|
67
|
+
|----------------|----------------|-------------------|----------------------------------------------------------|
|
|
68
|
+
| `key` | string | random 32 bytes | Master encryption key (32 bytes recommended) |
|
|
69
|
+
| `algorithm` | string | `aes-256-gcm` | Supported: `aes-256-gcm`, `sm4-cbc`, etc. |
|
|
70
|
+
| `expires` | number (sec) | 3 hours | Default token lifetime |
|
|
71
|
+
| `refresh` | boolean | `false` | Auto refresh in last 1/5 of lifetime |
|
|
72
|
+
| `encoding` | string | `base64url` | Output encoding |
|
|
73
|
+
| `failedCode` | number | `401` | HTTP status on auth failure |
|
|
74
|
+
|
|
75
|
+
---
|
|
76
|
+
|
|
77
|
+
### 5. Advanced: Multi-Key + Instant Revocation
|
|
78
|
+
|
|
79
|
+
```js
|
|
80
|
+
const token = new TopbitToken({ key: 'current-master-key' })
|
|
81
|
+
|
|
82
|
+
// Add multiple key versions
|
|
83
|
+
token.addTokenId({
|
|
84
|
+
'v2024' : 'old-key-jan-2024',
|
|
85
|
+
'mobile': 'mobile-app-key'
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
// Key leaked? Kill instantly:
|
|
89
|
+
token.removeTokenId('v2024') // All tokens issued with v2024 die now
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
---
|
|
93
|
+
|
|
94
|
+
### 6. Auto Token Refresh
|
|
95
|
+
|
|
96
|
+
```js
|
|
97
|
+
new TopbitToken({
|
|
98
|
+
expires: 24*3600,
|
|
99
|
+
refresh: true
|
|
100
|
+
})
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
→ When remaining time < 20%, server returns:
|
|
104
|
+
`x-refresh-token: new-long-lived-token`
|
|
105
|
+
|
|
106
|
+
Frontend just replaces the old one → seamless “never expire” experience.
|
|
107
|
+
|
|
108
|
+
---
|
|
109
|
+
|
|
110
|
+
### 7. Production Recommended Setup
|
|
111
|
+
|
|
112
|
+
```js
|
|
113
|
+
// middleware/@auth.js
|
|
114
|
+
const TopbitToken = require('topbit-token')
|
|
115
|
+
|
|
116
|
+
const token = new TopbitToken({
|
|
117
|
+
algorithm : 'aes-256-gcm',
|
|
118
|
+
key : process.env.TOKEN_SECRET,
|
|
119
|
+
expires : 30 * 24 * 3600, // 30 days
|
|
120
|
+
refresh : true
|
|
121
|
+
})
|
|
122
|
+
|
|
123
|
+
if (process.env.TOKEN_ID) {
|
|
124
|
+
token.addTokenId(process.env.TOKEN_ID)
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
module.exports = token
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
---
|
|
131
|
+
|
|
132
|
+
**TopbitToken is currently the fastest, safest, and most operations-friendly authentication solution in the Topbit ecosystem.**
|
|
133
|
+
|
|
134
|
+
With TopbitLoader, you get a true zero-config, fully automatic, high-performance authentication system.
|
|
135
|
+
|
|
136
|
+
Enjoy secure, blazing-fast services!
|
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
# TopbitLoader 完全使用手册
|
|
2
|
+
|
|
3
|
+
### 一、TopbitLoader 是什么?
|
|
4
|
+
|
|
5
|
+
TopbitLoader 是 Topbit 框架官方推荐的「自动化加载器」扩展,彻底告别手动 `app.get()`、`app.use()` 的繁琐写法。
|
|
6
|
+
|
|
7
|
+
它实现了真正的 **MCM 模式**(Middleware → Controller → Model),类似 MVC 但更轻量、更符合 Topbit 的极致性能哲学。
|
|
8
|
+
|
|
9
|
+
一句话总结:
|
|
10
|
+
> **把整个项目按约定目录结构写好,一个 `ld.init(app)` 就自动完成所有路由 + 中间件 + 模型的加载。**
|
|
11
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
### 二、推荐项目结构
|
|
15
|
+
|
|
16
|
+
```
|
|
17
|
+
project/
|
|
18
|
+
├── app.js # 入口文件(下面有完整示例)
|
|
19
|
+
├── controller/ # 控制器目录(必须)
|
|
20
|
+
│ ├── __mid.js # 全局中间件(可选)
|
|
21
|
+
│ ├── user.js # /user 路由组
|
|
22
|
+
│ ├── admin/ # /admin 路由组(子目录自动识别)
|
|
23
|
+
│ │ ├── __mid.js # admin 组专用中间件
|
|
24
|
+
│ │ └── index.js # /admin
|
|
25
|
+
│ └── api/
|
|
26
|
+
│ ├── __mid.js
|
|
27
|
+
│ └── v1/
|
|
28
|
+
│ └── post.js # /api/v1/post
|
|
29
|
+
├── middleware/ # 中间件类目录(必须)
|
|
30
|
+
│ ├── @auth.js # 必须以 @ 开头,类式中间件
|
|
31
|
+
│ ├── @cors.js
|
|
32
|
+
│ └── rate-limit.js # 普通函数式中间件(不推荐)
|
|
33
|
+
└── model/ # 模型目录(可选,配合 modelLoader)
|
|
34
|
+
└── user.js
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
---
|
|
38
|
+
|
|
39
|
+
### 三、快速上手
|
|
40
|
+
|
|
41
|
+
```js
|
|
42
|
+
// app.js
|
|
43
|
+
'use strict'
|
|
44
|
+
process.chdir(__dirname)
|
|
45
|
+
|
|
46
|
+
const Topbit = require('topbit')
|
|
47
|
+
const { Loader } = Topbit // 关键:直接从 topbit 导出
|
|
48
|
+
|
|
49
|
+
const app = new Topbit({
|
|
50
|
+
debug: true,
|
|
51
|
+
http2: true,
|
|
52
|
+
allowHTTP1: true,
|
|
53
|
+
cert: './cert/fullchain.pem',
|
|
54
|
+
key: './cert/privkey.pem'
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
if (app.isWorker) {
|
|
58
|
+
// 只需要这一行,所有路由、中间件、模型全部自动加载
|
|
59
|
+
new Loader().init(app)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
app.autoWorker(16) // 最大弹性进程数
|
|
63
|
+
app.daemon(443, 4) // 4 个基础进程
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
只需执行 `node app.js` 即可启动完整服务!
|
|
67
|
+
|
|
68
|
+
---
|
|
69
|
+
|
|
70
|
+
### 四、核心配置项详解
|
|
71
|
+
|
|
72
|
+
| 配置项 | 类型 | 默认值 | 说明 |
|
|
73
|
+
|----------------------|--------------------|----------------|-------------------------------------------------------------------------------------------------------------------------|
|
|
74
|
+
| `appPath` | string | `.` | 项目根目录(一般不用改) |
|
|
75
|
+
| `controllerPath` | string | `./controller` | 控制器目录 |
|
|
76
|
+
| `midwarePath` | string | `./middleware` | 中间件类目录 |
|
|
77
|
+
| `prePath` | string | `''` | 全局路由前缀,例如 `/api/v1` |
|
|
78
|
+
| `subgroup` | string\|Array | `null` | 只加载指定子目录,例如 `['admin', 'api']` |
|
|
79
|
+
| `fileAsGroup` | boolean | `true` | **强烈推荐开启**,每个控制器文件自动成为一个路由分组,中间件更精准 |
|
|
80
|
+
| `optionsRoute` | boolean | `true` | 自动为每个分组添加 `OPTIONS /*` 路由(CORS 预检必备) |
|
|
81
|
+
| `multi` | boolean | `false` | 是否允许重复调用 `init()`,生产环境保持 `false` |
|
|
82
|
+
| `homeFile` | string | `''` | 指定哪个文件作为首页路由 `/`,例如 `'index.js'` |
|
|
83
|
+
| `initArgs` | any | `app.service` | 传给每个控制器的 `init()` 参数 |
|
|
84
|
+
| `beforeController` | function | `null` | 控制器实例化后、注册路由前执行 |
|
|
85
|
+
| `afterController` | function | `null` | 路由注册完成后执行 |
|
|
86
|
+
| `modelLoader` | async function | `null` | **最强大的扩展点**:自定义模型加载逻辑,推荐配合 `topbit-model` 使用 |
|
|
87
|
+
|
|
88
|
+
**最常用配置示例**:
|
|
89
|
+
|
|
90
|
+
```js
|
|
91
|
+
new Loader({
|
|
92
|
+
prePath: '/api/v1',
|
|
93
|
+
fileAsGroup: true,
|
|
94
|
+
optionsRoute: true,
|
|
95
|
+
modelLoader: async (service) => {
|
|
96
|
+
const UserModel = require('./model/user')
|
|
97
|
+
service.userModel = new UserModel(service)
|
|
98
|
+
}
|
|
99
|
+
}).init(app)
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
---
|
|
103
|
+
|
|
104
|
+
### 五、控制器(Controller)写法大全
|
|
105
|
+
|
|
106
|
+
#### 1. 最简 RESTful 写法(推荐)
|
|
107
|
+
|
|
108
|
+
```js
|
|
109
|
+
// controller/user.js
|
|
110
|
+
class User {
|
|
111
|
+
async get(ctx) { // GET /user/:id
|
|
112
|
+
ctx.to({ id: ctx.param.id })
|
|
113
|
+
}
|
|
114
|
+
async list(ctx) { // GET /user
|
|
115
|
+
ctx.to(['user1', 'user2'])
|
|
116
|
+
}
|
|
117
|
+
async post(ctx) { // POST /user
|
|
118
|
+
ctx.to({ saved: true })
|
|
119
|
+
}
|
|
120
|
+
async put(ctx) { // PUT /user/:id
|
|
121
|
+
ctx.to({ updated: true })
|
|
122
|
+
}
|
|
123
|
+
async delete(ctx) { // DELETE /user/:id
|
|
124
|
+
ctx.to({ deleted: true })
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
module.exports = User
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
#### 2. 自定义路径
|
|
131
|
+
|
|
132
|
+
```js
|
|
133
|
+
class User {
|
|
134
|
+
static param = '/:uid/info' // 自定义参数路径
|
|
135
|
+
static postParam = '/create' // POST 专用路径
|
|
136
|
+
|
|
137
|
+
async post(ctx) { // POST /user/create
|
|
138
|
+
ctx.ok('created')
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
#### 3. 为当前文件添加专属中间件
|
|
144
|
+
|
|
145
|
+
```js
|
|
146
|
+
class User {
|
|
147
|
+
// 返回中间件数组,只作用于本文件的所有路由
|
|
148
|
+
static __mid() {
|
|
149
|
+
return [
|
|
150
|
+
[require('../middleware/@auth'), { pre: true }],
|
|
151
|
+
require('../middleware/rate-limit')
|
|
152
|
+
]
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
#### 4. 首页控制器
|
|
158
|
+
|
|
159
|
+
```js
|
|
160
|
+
// controller/index.js
|
|
161
|
+
class Index {
|
|
162
|
+
async get() {
|
|
163
|
+
this.ctx.html('<h1>Welcome to Topbit</h1>')
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
module.exports = Index
|
|
167
|
+
|
|
168
|
+
// 在 Loader 配置中指定
|
|
169
|
+
new Loader({ homeFile: 'index.js' }).init(app)
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
---
|
|
173
|
+
|
|
174
|
+
### 六、中间件(Middleware)写法
|
|
175
|
+
|
|
176
|
+
#### 1. 类式中间件(推荐,以 @ 开头)
|
|
177
|
+
|
|
178
|
+
```js
|
|
179
|
+
// middleware/@auth.js
|
|
180
|
+
class Auth {
|
|
181
|
+
async middleware(c, next) {
|
|
182
|
+
if (!c.headers.token) return c.status(401).to('need token')
|
|
183
|
+
c.user = { id: 1 }
|
|
184
|
+
await next(c)
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
module.exports = Auth
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
#### 2. 全局中间件 __mid.js
|
|
191
|
+
|
|
192
|
+
```js
|
|
193
|
+
// controller/__mid.js 或 controller/admin/__mid.js
|
|
194
|
+
module.exports = [
|
|
195
|
+
{ name: '@auth' }, // 类式中间件
|
|
196
|
+
{ name: 'rate-limit', method: ['GET','POST'] }, // 普通函数中间件
|
|
197
|
+
{ middleware: async (c, next) => { // 直接写函数
|
|
198
|
+
console.log('global mid')
|
|
199
|
+
await next(c)
|
|
200
|
+
}, pre: true }
|
|
201
|
+
]
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
#### 3. 文件级中间件(最精准)
|
|
205
|
+
|
|
206
|
+
```js
|
|
207
|
+
// 在 controller/user.js 中
|
|
208
|
+
static __mid() {
|
|
209
|
+
return [
|
|
210
|
+
{ name: '@vip-auth', pre: true }, // 只在本文件生效
|
|
211
|
+
{ name: 'log', method: 'POST' }
|
|
212
|
+
]
|
|
213
|
+
}
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
---
|
|
217
|
+
|
|
218
|
+
### 七、模型加载(modelLoader)最佳实践
|
|
219
|
+
|
|
220
|
+
```js
|
|
221
|
+
new Loader({
|
|
222
|
+
modelLoader: async (service) => {
|
|
223
|
+
const glob = require('glob')
|
|
224
|
+
const path = require('path')
|
|
225
|
+
|
|
226
|
+
const files = glob.sync('model/**/*.js', { cwd: __dirname })
|
|
227
|
+
for (const file of files) {
|
|
228
|
+
const Model = require(path.resolve(__dirname, file))
|
|
229
|
+
const name = path.basename(file, '.js')
|
|
230
|
+
service[name + 'Model'] = new Model(service)
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}).init(app)
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
---
|
|
237
|
+
|
|
238
|
+
### 八、安全与命名规范
|
|
239
|
+
|
|
240
|
+
- 文件夹名、文件名只能包含:`a-z 0-9 _ -`,且必须字母开头
|
|
241
|
+
- 禁止空格、汉字、大写、特殊符号
|
|
242
|
+
- 违反命名规范会直接报红字警告
|
|
243
|
+
- 以 `!` 开头的文件/文件夹会被自动忽略(用于临时禁用)
|
|
244
|
+
|
|
245
|
+
---
|
|
246
|
+
|
|
247
|
+
### 九、高级技巧合集
|
|
248
|
+
|
|
249
|
+
| 需求 | 解决方案 |
|
|
250
|
+
|-------------------------------|--------------------------------------------------------------------------|
|
|
251
|
+
| 多个版本 API 并行 | 使用 `prePath: '/v1'`, `prePath: '/v2'` 分别创建多个 Loader 实例 |
|
|
252
|
+
| 灰度发布 | `subgroup: ['v2']` 只加载 v2 目录,配合 Nginx 分流 |
|
|
253
|
+
| 插件化开发 | 每个插件一个独立目录,`new Loader({ appPath: './plugins/xxx' }).init(app)` |
|
|
254
|
+
| 热更新(开发环境) | `multi: true` + chokidar 监听文件变更重新调用 `init()` |
|
|
255
|
+
|
|
256
|
+
---
|
|
257
|
+
|
|
258
|
+
### 十、完整生产级入口示例
|
|
259
|
+
|
|
260
|
+
```js
|
|
261
|
+
// app.js(生产环境终极版本)
|
|
262
|
+
'use strict'
|
|
263
|
+
process.chdir(__dirname)
|
|
264
|
+
|
|
265
|
+
const Topbit = require('topbit')
|
|
266
|
+
const { Loader } = Topbit
|
|
267
|
+
|
|
268
|
+
const app = new Topbit({
|
|
269
|
+
debug: false,
|
|
270
|
+
http2: true,
|
|
271
|
+
allowHTTP1: true,
|
|
272
|
+
cert: '/etc/ssl/fullchain.pem',
|
|
273
|
+
key: '/etc/ssl/privkey.pem',
|
|
274
|
+
globalLog: true,
|
|
275
|
+
logType: 'file',
|
|
276
|
+
logFile: '/var/log/topbit/access.log',
|
|
277
|
+
errorLogFile: '/var/log/topbit/error.log'
|
|
278
|
+
})
|
|
279
|
+
|
|
280
|
+
if (app.isWorker) {
|
|
281
|
+
new Loader({
|
|
282
|
+
prePath: '/api',
|
|
283
|
+
fileAsGroup: true,
|
|
284
|
+
optionsRoute: true,
|
|
285
|
+
modelLoader: async (svc) => {
|
|
286
|
+
svc.db = require('./lib/mysql-pool')
|
|
287
|
+
svc.redis = require('./lib/redis')
|
|
288
|
+
}
|
|
289
|
+
}).init(app)
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
app.sched('none')
|
|
293
|
+
app.autoWorker(32)
|
|
294
|
+
app.daemon(443, 8)
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
---
|
|
298
|
+
|
|
299
|
+
**至此,你已经掌握了 TopbitLoader 的全部精髓!**
|
|
300
|
+
|
|
301
|
+
把它用起来,你会发现:
|
|
302
|
+
> **Topbit + TopbitLoader = 可能是目前 Node.js 生态里开发体验最好、性能最强的后端组合。**
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
# TopbitToken – 极简、高性能、可刷新的加密 Token 解决方案
|
|
2
|
+
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
### 一、TopbitToken 是什么?
|
|
6
|
+
|
|
7
|
+
TopbitToken 是专为 Topbit 框架打造的零依赖、极简、高安全的加密用户凭证(Token)系统。
|
|
8
|
+
|
|
9
|
+
它完全基于 Node.js 原生 `crypto` 实现,支持:
|
|
10
|
+
|
|
11
|
+
- AES-256-GCM(默认,推荐)
|
|
12
|
+
- AES-192-GCM / AES-128-CBC / AES-256-CBC
|
|
13
|
+
- 国密 SM4-CBC
|
|
14
|
+
|
|
15
|
+
一句话总结:
|
|
16
|
+
> **3 行代码实现:签发 + 验证 + 自动刷新 + 即时失效(支持热更换密钥)**
|
|
17
|
+
|
|
18
|
+
---
|
|
19
|
+
|
|
20
|
+
### 二、核心特性(为什么选择它?)
|
|
21
|
+
|
|
22
|
+
| 特性 | 说明 |
|
|
23
|
+
|------------------------------|----------------------------------------------------------------------------------------|
|
|
24
|
+
| **零依赖** | 完全原生实现,不依赖 jwt、jsonwebtoken 等第三方库 |
|
|
25
|
+
| **闪电 超快加密解密** | AES-NI 硬件加速 + GCM 模式,单次验证 < 0.05ms |
|
|
26
|
+
| **更新 自动刷新 Token** | 接近过期时自动下发新 Token(`x-refresh-token` 头) |
|
|
27
|
+
| **钥匙 支持多套密钥(tokenId)** | 可同时存在多套密钥,随时切换主密钥,所有旧 Token 立即失效(防泄漏神器) |
|
|
28
|
+
| **盾牌 防篡改 + 防重放** | 内置时间戳 + 有效期 + tokenId 校验 |
|
|
29
|
+
| **锁 即时失效** | 修改 `tokenIds` 或删除某个 `tokenId`,对应 Token 立刻失效,无需等待过期 |
|
|
30
|
+
| **设置 灵活算法支持** | 支持国密 SM4,满足合规需求 |
|
|
31
|
+
|
|
32
|
+
---
|
|
33
|
+
|
|
34
|
+
### 三、快速上手(30 秒搞定登录认证)
|
|
35
|
+
|
|
36
|
+
```js
|
|
37
|
+
// middleware/@token.js
|
|
38
|
+
const TopbitToken = require('topbit-token')
|
|
39
|
+
|
|
40
|
+
const token = new TopbitToken({
|
|
41
|
+
key : 'your-32-byte-secret-key-here!!', // 必须 32 字节(AES-256)
|
|
42
|
+
expires : 60 * 60 * 24, // 24 小时(单位:秒)
|
|
43
|
+
refresh : true // 开启自动刷新(最后 1/5 时间刷新)
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
module.exports = token // 直接导出实例,TopbitLoader 自动识别
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
```js
|
|
50
|
+
// controller/user.js
|
|
51
|
+
class User {
|
|
52
|
+
async post(c) { // POST /user/login
|
|
53
|
+
// 登录验证成功后
|
|
54
|
+
let userinfo = {
|
|
55
|
+
uid : 10010,
|
|
56
|
+
name : 'Alice',
|
|
57
|
+
role : 'admin',
|
|
58
|
+
// expires 可单独设置更长时间
|
|
59
|
+
}
|
|
60
|
+
let t = token.make(userinfo) // 签发 Token
|
|
61
|
+
c.setHeader('authorization', t)
|
|
62
|
+
c.to({ok: true, msg: 'login success'})
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// 所有需要登录的接口自动加上 token.mid()
|
|
67
|
+
token.mid() 会自动把验证后的用户信息挂到 c.user
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
### 四、配置项全解析
|
|
73
|
+
|
|
74
|
+
| 参数 | 类型 | 默认值 | 说明 |
|
|
75
|
+
|----------------|------------------|------------------------|--------------------------------------------------------------------------------------|
|
|
76
|
+
| `key` | string | 随机32字节 | 主加密密钥(建议 32 字节) |
|
|
77
|
+
| `iv` | string | 随机12/16字节 | 初始化向量(GCM=12,CBC=16) |
|
|
78
|
+
| `algorithm` | string | `aes-256-gcm` | 支持:`aes-256-gcm`(推荐)、`aes-192-gcm`、`sm4-cbc` 等 |
|
|
79
|
+
| `expires` | number(秒) | 3小时 | Token 默认有效期 |
|
|
80
|
+
| `refresh` | boolean | `false` | 是否开启自动刷新(设为 `true` 则最后 1/5 时间自动刷新) |
|
|
81
|
+
| `encoding` | string | `base64url` | Token 输出编码(`base64url`、`hex`、`base64`) |
|
|
82
|
+
| `failedCode` | number | `401` | 验证失败时返回的 HTTP 状态码 |
|
|
83
|
+
| `tokenIds` | array | `[]` | 多密钥 ID 列表,用于支持密钥轮换 |
|
|
84
|
+
|
|
85
|
+
---
|
|
86
|
+
|
|
87
|
+
### 五、高级功能:多密钥 + 即时失效(防泄漏神器)
|
|
88
|
+
|
|
89
|
+
```js
|
|
90
|
+
const token = new TopbitToken({
|
|
91
|
+
key: 'master-key-2025-01-01',
|
|
92
|
+
expires: 3600 * 24 * 30
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
// 添加多套密钥(可随时动态添加)
|
|
96
|
+
token.addTokenId({
|
|
97
|
+
'user-v1' : 'old-key-2024-v1',
|
|
98
|
+
'admin-v2' : 'new-strong-key-2025',
|
|
99
|
+
'mobile' : 'mobile-special-key'
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
// 如果发现密钥泄漏,立即执行:
|
|
103
|
+
token.removeTokenId('user-v1') // 所有使用 user-v1 签发的 Token 立刻失效!
|
|
104
|
+
|
|
105
|
+
// 或者直接清空所有旧密钥,只保留当前主密钥
|
|
106
|
+
token.tokenIds = []
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
---
|
|
110
|
+
|
|
111
|
+
### 六、自动刷新 Token 机制
|
|
112
|
+
|
|
113
|
+
```js
|
|
114
|
+
const token = new TopbitToken({
|
|
115
|
+
expires: 3600 * 24, // 24小时有效
|
|
116
|
+
refresh: true // 开启自动刷新
|
|
117
|
+
})
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
- 当剩余时间 < 24小时 × 1/5 = 4.8小时 时
|
|
121
|
+
- 服务器自动返回新 Token:`x-refresh-token: new-token-here`
|
|
122
|
+
- 前端收到后替换旧 Token 即可实现“永不过期”体验
|
|
123
|
+
|
|
124
|
+
---
|
|
125
|
+
|
|
126
|
+
### 七、最佳实践(生产级推荐配置)
|
|
127
|
+
|
|
128
|
+
```js
|
|
129
|
+
// middleware/@auth.js
|
|
130
|
+
const TopbitToken = require('topbit-token')
|
|
131
|
+
|
|
132
|
+
const token = new TopbitToken({
|
|
133
|
+
algorithm : 'aes-256-gcm',
|
|
134
|
+
key : process.env.TOKEN_KEY, // 从环境变量读取
|
|
135
|
+
expires : 60 * 60 * 24 * 30, // 30天
|
|
136
|
+
refresh : true,
|
|
137
|
+
failedCode: 401
|
|
138
|
+
})
|
|
139
|
+
|
|
140
|
+
// 支持密钥轮换(每月换一次)
|
|
141
|
+
if (process.env.TOKEN_ID) {
|
|
142
|
+
token.addTokenId(process.env.TOKEN_ID)
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
module.exports = token
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
---
|
|
149
|
+
|
|
150
|
+
### 八、常见问题(FAQ)
|
|
151
|
+
|
|
152
|
+
| 问题 | 解答 |
|
|
153
|
+
|--------------------------------|----------------------------------------------------------------------|
|
|
154
|
+
| 是否比 JWT 更快? | 是!原生 crypto + GCM 模式,比 jwt 快 3~10 倍 |
|
|
155
|
+
| 是否支持 Redis 黑名单? | 不需要!通过 `removeTokenId()` 即可实现即时失效 |
|
|
156
|
+
| 是否支持单点登录退出? | 是!删除对应 `tokenId` 或修改密钥,所有设备立即退出 |
|
|
157
|
+
| 是否支持国密 SM4? | 支持!`algorithm: 'sm4-cbc'` 即可 |
|
|
158
|
+
|
|
159
|
+
---
|
|
160
|
+
|
|
161
|
+
**结论:TopbitToken 是目前 Topbit 生态中最快、最安全、最易用的认证方案。**
|
|
162
|
+
|
|
163
|
+
配合 TopbitLoader 使用,真正实现:
|
|
164
|
+
> **零配置、全自动、高性能、可运维的现代化认证系统**
|
|
165
|
+
|
|
166
|
+
---
|
|
Binary file
|
package/package.json
CHANGED
package/src/token/token.js
CHANGED
|
@@ -426,10 +426,10 @@ class TopbitToken {
|
|
|
426
426
|
return c.status(self.failedCode).to(uinfo.errcode)
|
|
427
427
|
}
|
|
428
428
|
|
|
429
|
-
c.
|
|
429
|
+
c.user = uinfo
|
|
430
430
|
|
|
431
431
|
if (uinfo.data.expires + uinfo.data.timestamp - uinfo.now < self.refresh) {
|
|
432
|
-
let new_token = self.
|
|
432
|
+
let new_token = self.makeToken(uinfo.data, uinfo.data.__tokenId__)
|
|
433
433
|
c.setHeader('x-refresh-token', new_token)
|
|
434
434
|
}
|
|
435
435
|
|