mm_session 1.5.1 → 1.5.3

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/README.md ADDED
@@ -0,0 +1,298 @@
1
+ # mm_session
2
+
3
+ [中文](./README.md) | [English](./README_EN.md)
4
+
5
+ ## 概述
6
+
7
+ `mm_session` 是一个专为 Koa.js 框架设计的轻量级 session 管理中间件。它提供了简单易用的 session 管理功能,支持自定义存储后端,适用于各种规模的 Web 应用。
8
+
9
+ 这是超级美眉session函数模块,用于web服务端session缓存。
10
+
11
+ ## 特性
12
+
13
+ - ✅ **Koa 中间件标准** - 符合 `app.use(session({ key: 'test_session', max_age: 3600 }))` 使用方式
14
+ - ✅ **存储抽象层** - 支持自定义存储后端
15
+ - ✅ **自动 session 管理** - 自动创建、保存、销毁 session
16
+ - ✅ **Cookie 自动处理** - 自动设置和读取 session cookie
17
+ - ✅ **安全 session ID** - 基于 IP + 时间戳 + AES 加密生成
18
+ - ✅ **异步支持** - 完整的 async/await 支持
19
+ - ✅ **轻量级** - 无冗余依赖,代码简洁
20
+ - ✅ **生产就绪** - 经过充分测试,稳定可靠
21
+
22
+ ## 安装
23
+
24
+ ```bash
25
+ npm install mm_session
26
+ ```
27
+
28
+ ## 快速开始
29
+
30
+ ### 基本用法
31
+
32
+ ```javascript
33
+ const Koa = require('koa');
34
+ const { session } = require('mm_session');
35
+
36
+ const app = new Koa();
37
+
38
+ // 注册中间件
39
+ app.use(session({
40
+ key: 'my_session', // cookie 名称
41
+ max_age: 3600 // session 过期时间(秒)
42
+ }));
43
+
44
+ // 业务路由
45
+ app.use(async (ctx) => {
46
+ // 设置 session 数据
47
+ if (!ctx.session.user_id) {
48
+ ctx.session.user_id = 123;
49
+ ctx.session.username = 'test_user';
50
+ }
51
+
52
+ // 读取 session 数据
53
+ ctx.body = {
54
+ user_id: ctx.session.user_id,
55
+ username: ctx.session.username
56
+ };
57
+ });
58
+
59
+ app.listen(3000);
60
+ ```
61
+
62
+ ### 高级配置
63
+
64
+ ```javascript
65
+ const { Session, Store } = require('mm_session');
66
+
67
+ // 自定义配置
68
+ const session = new Session({
69
+ key: 'app_session', // cookie 键名
70
+ max_age: 7200, // 过期时间:2小时
71
+ http_only: true, // 仅 HTTP 访问
72
+ secure: process.env.NODE_ENV === 'production', // 生产环境 HTTPS
73
+ same_site: 'strict' // 同站策略
74
+ });
75
+
76
+ // 自定义存储(可选)
77
+ const customStore = new Store('custom_prefix');
78
+ session.init(customStore);
79
+ ```
80
+
81
+ ## API 文档
82
+
83
+ ### Session 类
84
+
85
+ #### 构造函数
86
+
87
+ ```javascript
88
+ new Session(config)
89
+ ```
90
+
91
+ **参数:**
92
+ - `config` (Object) - 配置对象
93
+ - `key` (String) - session cookie 名称,默认: 'mm:uuid'
94
+ - `max_age` (Number) - session 过期时间(秒)
95
+ - 其他 cookie 配置选项
96
+
97
+ #### 方法
98
+
99
+ ##### middleware()
100
+ 返回 Koa 中间件函数。
101
+
102
+ ```javascript
103
+ app.use(session.middleware());
104
+ ```
105
+
106
+ ##### init(store)
107
+ 初始化自定义存储后端。
108
+
109
+ ```javascript
110
+ session.init(new CustomStore());
111
+ ```
112
+
113
+ ### Store 类
114
+
115
+ 存储抽象类,支持自定义存储实现。
116
+
117
+ ```javascript
118
+ const { Store } = require('mm_session');
119
+ const store = new Store('prefix_');
120
+ ```
121
+
122
+ ## 配置选项
123
+
124
+ ### Session 配置
125
+
126
+ | 选项 | 类型 | 默认值 | 描述 |
127
+ |------|------|--------|------|
128
+ | key | String | 'mm:uuid' | session cookie 名称 |
129
+ | max_age | Number | - | session 过期时间(秒) |
130
+ | http_only | Boolean | true | 仅 HTTP 访问 |
131
+ | secure | Boolean | false | 仅 HTTPS 传输 |
132
+ | same_site | String | 'lax' | 同站策略 |
133
+
134
+ ### Cookie 配置
135
+
136
+ 支持所有 [cookie](https://github.com/jshttp/cookie) 库的配置选项。
137
+
138
+ ## 存储后端
139
+
140
+ ### 默认存储
141
+ 默认使用 `mm_cachebase` 作为存储后端,支持内存和文件持久化。
142
+
143
+ ### 自定义存储
144
+ 可以实现自定义存储类,只需实现以下接口:
145
+
146
+ ```javascript
147
+ class CustomStore {
148
+ async get(sessionId) {}
149
+ async set(sessionData, options, ctx) {}
150
+ async destroy(sessionId, ctx) {}
151
+ async getID(ctx) {}
152
+ }
153
+ ```
154
+
155
+ ## 示例应用
156
+
157
+ ### 用户登录系统
158
+
159
+ ```javascript
160
+ const session = new Session({
161
+ key: 'user_session',
162
+ max_age: 86400 // 24小时
163
+ });
164
+
165
+ app.use(session.middleware());
166
+
167
+ // 登录路由
168
+ app.use(async (ctx, next) => {
169
+ if (ctx.path === '/login' && ctx.method === 'POST') {
170
+ const { username, password } = ctx.request.body;
171
+
172
+ // 验证用户(示例)
173
+ if (username === 'admin' && password === 'password') {
174
+ ctx.session.user = {
175
+ id: 1,
176
+ username: 'admin',
177
+ role: 'administrator'
178
+ };
179
+ ctx.body = { success: true };
180
+ } else {
181
+ ctx.body = { success: false, error: '认证失败' };
182
+ }
183
+ } else {
184
+ await next();
185
+ }
186
+ });
187
+
188
+ // 需要认证的路由
189
+ app.use(async (ctx, next) => {
190
+ if (!ctx.session.user) {
191
+ ctx.status = 401;
192
+ ctx.body = { error: '请先登录' };
193
+ return;
194
+ }
195
+ await next();
196
+ });
197
+ ```
198
+
199
+ ## 测试
200
+
201
+ ```bash
202
+ # 运行测试
203
+ npm test
204
+
205
+ # 或直接运行
206
+ node test.js
207
+ ```
208
+
209
+ ## 开发
210
+
211
+ ### 代码规范
212
+
213
+ 项目使用 ESLint 进行代码规范检查:
214
+
215
+ ```bash
216
+ # 检查代码规范
217
+ npx eslint lib/session.js
218
+
219
+ # 自动修复
220
+ npx eslint lib/session.js --fix
221
+ ```
222
+
223
+ ### 项目结构
224
+
225
+ ```
226
+ mm_session/
227
+ ├── lib/
228
+ │ ├── session.js # Session 类实现
229
+ │ └── store.js # Store 类实现
230
+ ├── index.js # 模块入口
231
+ ├── test.js # 测试文件
232
+ ├── eslint.config.js # ESLint 配置
233
+ └── package.json # 项目配置
234
+ ```
235
+
236
+ ## 贡献
237
+
238
+ 欢迎贡献!请随时提交 Issue 和 Pull Request。
239
+
240
+ ### 开发环境设置
241
+
242
+ 1. 克隆仓库:
243
+ ```bash
244
+ git clone https://gitee.com/qiuwenwu91/mm_session.git
245
+ cd mm_session
246
+ ```
247
+
248
+ 2. 安装依赖:
249
+ ```bash
250
+ npm install
251
+ ```
252
+
253
+ 3. 运行测试:
254
+ ```bash
255
+ npm test
256
+ ```
257
+
258
+ ## 许可证
259
+
260
+ ISC License
261
+
262
+ 版权所有 (c) 2024 邱文武
263
+
264
+ 特此免费授予任何获得本软件副本和相关文档文件(以下简称"软件")的人不受限制地处理本软件的权限,包括但不限于使用、复制、修改、合并、发布、分发、再许可和/或销售本软件的副本,以及允许提供本软件的人员这样做,但须符合以下条件:
265
+
266
+ 上述版权声明和本许可声明应包含在本软件的所有副本或重要部分中。
267
+
268
+ ## 作者
269
+
270
+ 邱文武
271
+
272
+ ## 更新日志
273
+
274
+ ### v1.5.3
275
+ - 当前稳定版本
276
+
277
+ ### v1.5.1
278
+ - 修复 session 保存逻辑
279
+ - 优化 cookie 设置机制
280
+ - 改进测试用例
281
+
282
+ ### v1.5.0
283
+ - 重构为类+原型函数模式
284
+ - 符合 Koa 中间件标准使用方式
285
+ - 增强代码可维护性
286
+
287
+ ## 错误报告
288
+
289
+ 如果您遇到任何错误或有功能请求,请在 [Git 仓库](https://gitee.com/qiuwenwu91/mm_session/issues) 上提交 Issue。
290
+
291
+ ## 相关项目
292
+
293
+ - [mm_cache](https://www.npmjs.com/package/mm_cache) - 缓存库(依赖项)
294
+ - [mm_eslint](https://www.npmjs.com/package/mm_eslint) - ESLint 配置(开发依赖项)
295
+
296
+ ## 支持
297
+
298
+ 如需支持和问题解答,请查阅文档或在项目仓库中创建 Issue。
package/README_EN.md ADDED
@@ -0,0 +1,296 @@
1
+ # mm_session
2
+
3
+ [中文](README.md) | [English](README_EN.md)
4
+
5
+ ## Overview
6
+
7
+ `mm_session` is a lightweight session management middleware designed specifically for the Koa.js framework. It provides simple and easy-to-use session management functionality with support for custom storage backends, suitable for web applications of all sizes.
8
+
9
+ This is a super session function module for web server-side session caching.
10
+
11
+ ## Features
12
+
13
+ - ✅ **Koa Middleware Standard** - Compatible with `app.use(session({ key: 'test_session', max_age: 3600 }))` usage
14
+ - ✅ **Storage Abstraction Layer** - Supports custom storage backends
15
+ - ✅ **Automatic Session Management** - Automatic session creation, saving, and destruction
16
+ - ✅ **Cookie Auto-handling** - Automatic session cookie setting and reading
17
+ - ✅ **Secure Session ID** - Generated based on IP + timestamp + AES encryption
18
+ - ✅ **Async Support** - Full async/await support
19
+ - ✅ **Lightweight** - No redundant dependencies, clean codebase
20
+ - ✅ **Production Ready** - Well-tested and stable for production use
21
+
22
+ ## Installation
23
+
24
+ ```bash
25
+ npm install mm_session
26
+ ```
27
+
28
+ ## Quick Start
29
+
30
+ ### Basic Usage
31
+
32
+ ```javascript
33
+ const Koa = require('koa');
34
+ const { session } = require('mm_session');
35
+
36
+ const app = new Koa();
37
+
38
+ // Register middleware
39
+ app.use(session({
40
+ key: 'my_session', // cookie name
41
+ max_age: 3600 // session expiration time (seconds)
42
+ }));
43
+
44
+ // Business routes
45
+ app.use(async (ctx) => {
46
+ // Set session data
47
+ if (!ctx.session.user_id) {
48
+ ctx.session.user_id = 123;
49
+ ctx.session.username = 'test_user';
50
+ }
51
+
52
+ // Read session data
53
+ ctx.body = {
54
+ user_id: ctx.session.user_id,
55
+ username: ctx.session.username
56
+ };
57
+ });
58
+
59
+ app.listen(3000);
60
+ ```
61
+
62
+ ### Advanced Configuration
63
+
64
+ ```javascript
65
+ const { Session, Store } = require('mm_session');
66
+
67
+ // Custom configuration
68
+ const session = new Session({
69
+ key: 'app_session', // cookie key name
70
+ max_age: 7200, // expiration time: 2 hours
71
+ http_only: true, // HTTP-only access
72
+ secure: process.env.NODE_ENV === 'production', // HTTPS in production
73
+ same_site: 'strict' // same-site policy
74
+ });
75
+
76
+ // Custom storage (optional)
77
+ const customStore = new Store('custom_prefix');
78
+ session.init(customStore);
79
+ ```
80
+
81
+ ## API Documentation
82
+
83
+ ### Session Class
84
+
85
+ #### Constructor
86
+
87
+ ```javascript
88
+ new Session(config)
89
+ ```
90
+
91
+ **Parameters:**
92
+ - `config` (Object) - Configuration object
93
+ - `key` (String) - Session cookie name, default: 'mm:uuid'
94
+ - `max_age` (Number) - Session expiration time (seconds)
95
+ - Other cookie configuration options
96
+
97
+ #### Methods
98
+
99
+ ##### middleware()
100
+ Returns Koa middleware function.
101
+
102
+ ```javascript
103
+ app.use(session.middleware());
104
+ ```
105
+
106
+ ##### init(store)
107
+ Initialize custom storage backend.
108
+
109
+ ```javascript
110
+ session.init(new CustomStore());
111
+ ```
112
+
113
+ ### Store Class
114
+
115
+ Storage abstraction class supporting custom storage implementations.
116
+
117
+ ```javascript
118
+ const { Store } = require('mm_session');
119
+ const store = new Store('prefix_');
120
+ ```
121
+
122
+ ## Configuration Options
123
+
124
+ ### Session Configuration
125
+
126
+ | Option | Type | Default | Description |
127
+ |--------|------|---------|-------------|
128
+ | key | String | 'mm:uuid' | Session cookie name |
129
+ | max_age | Number | - | Session expiration time (seconds) |
130
+ | http_only | Boolean | true | HTTP-only access |
131
+ | secure | Boolean | false | HTTPS-only transmission |
132
+ | same_site | String | 'lax' | Same-site policy |
133
+
134
+ ### Cookie Configuration
135
+
136
+ Supports all [cookie](https://github.com/jshttp/cookie) library configuration options.
137
+
138
+ ## Storage Backends
139
+
140
+ ### Default Storage
141
+ Uses `mm_cachebase` as the default storage backend, supporting both memory and file persistence.
142
+
143
+ ### Custom Storage
144
+ You can implement custom storage classes by implementing the following interface:
145
+
146
+ ```javascript
147
+ class CustomStore {
148
+ async get(sessionId) {}
149
+ async set(sessionData, options, ctx) {}
150
+ async destroy(sessionId, ctx) {}
151
+ async getID(ctx) {}
152
+ }
153
+ ```
154
+
155
+ ## Example Applications
156
+
157
+ ### User Login System
158
+
159
+ ```javascript
160
+ const session = new Session({
161
+ key: 'user_session',
162
+ max_age: 86400 // 24 hours
163
+ });
164
+
165
+ app.use(session.middleware());
166
+
167
+ // Login route
168
+ app.use(async (ctx, next) => {
169
+ if (ctx.path === '/login' && ctx.method === 'POST') {
170
+ const { username, password } = ctx.request.body;
171
+
172
+ // User authentication (example)
173
+ if (username === 'admin' && password === 'password') {
174
+ ctx.session.user = {
175
+ id: 1,
176
+ username: 'admin',
177
+ role: 'administrator'
178
+ };
179
+ ctx.body = { success: true };
180
+ } else {
181
+ ctx.body = { success: false, error: 'Authentication failed' };
182
+ }
183
+ } else {
184
+ await next();
185
+ }
186
+ });
187
+
188
+ // Routes requiring authentication
189
+ app.use(async (ctx, next) => {
190
+ if (!ctx.session.user) {
191
+ ctx.status = 401;
192
+ ctx.body = { error: 'Please login first' };
193
+ return;
194
+ }
195
+ await next();
196
+ });
197
+ ```
198
+
199
+ ## Testing
200
+
201
+ ```bash
202
+ # Run tests
203
+ npm test
204
+
205
+ # Or run directly
206
+ node test.js
207
+ ```
208
+
209
+ ## Development
210
+
211
+ ### Code Style
212
+
213
+ The project uses ESLint for code style checking:
214
+
215
+ ```bash
216
+ # Check code style
217
+ npx eslint lib/session.js
218
+
219
+ # Auto-fix issues
220
+ npx eslint lib/session.js --fix
221
+ ```
222
+
223
+ ### Project Structure
224
+
225
+ ```
226
+ mm_session/
227
+ ├── lib/
228
+ │ ├── session.js # Session class implementation
229
+ │ └── store.js # Store class implementation
230
+ ├── index.js # Module entry point
231
+ ├── test.js # Test file
232
+ ├── eslint.config.js # ESLint configuration
233
+ └── package.json # Project configuration
234
+ ```
235
+
236
+ ## Contributing
237
+
238
+ We welcome contributions! Please feel free to submit issues and pull requests.
239
+
240
+ ### Development Setup
241
+
242
+ 1. Clone the repository:
243
+ ```bash
244
+ git clone https://gitee.com/qiuwenwu91/mm_session.git
245
+ cd mm_session
246
+ ```
247
+
248
+ 2. Install dependencies:
249
+ ```bash
250
+ npm install
251
+ ```
252
+
253
+ 3. Run tests:
254
+ ```bash
255
+ npm test
256
+ ```
257
+
258
+ ## License
259
+
260
+ ISC License
261
+
262
+ Copyright (c) 2024 Qiu Wenwu
263
+
264
+ Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
265
+
266
+ ## Author
267
+
268
+ Qiu Wenwu
269
+
270
+ ## Changelog
271
+
272
+ ### v1.5.3
273
+ - Current stable version
274
+
275
+ ### v1.5.1
276
+ - Fixed session saving logic
277
+ - Optimized cookie setting mechanism
278
+ - Improved test cases
279
+
280
+ ### v1.5.0
281
+ - Refactored to class + prototype function pattern
282
+ - Compatible with Koa middleware standard usage
283
+ - Enhanced code maintainability
284
+
285
+ ## Bug Reports
286
+
287
+ If you encounter any bugs or have feature requests, please file an issue on the [Git repository](https://gitee.com/qiuwenwu91/mm_session/issues).
288
+
289
+ ## Related Projects
290
+
291
+ - [mm_cache](https://www.npmjs.com/package/mm_cache) - Cache library (dependency)
292
+ - [mm_eslint](https://www.npmjs.com/package/mm_eslint) - ESLint configuration (dev dependency)
293
+
294
+ ## Support
295
+
296
+ For support and questions, please check the documentation or create an issue on the project repository.
package/eslint.config.js CHANGED
@@ -27,13 +27,13 @@ module.exports = [
27
27
  rules: {
28
28
  // 自定义命名规范插件规则(优先使用)
29
29
  'naming-convention/class-name': 'error',
30
- 'naming-convention/function-name': 'off', // 禁用函数命名规则,私有方法以下划线开头
30
+ 'naming-convention/function-name': 'error', // 启用函数命名规则
31
31
  'naming-convention/method-name': 'error',
32
32
  'naming-convention/variable-name': 'warn',
33
33
  'naming-convention/constant-name': 'error',
34
34
  'naming-convention/private-method-naming': 'warn',
35
35
  'naming-convention/private-variable-naming': 'warn',
36
- 'naming-convention/param-name': 'off', // 禁用入参名规则,私有方法入参以下划线开头
36
+ 'naming-convention/param-name': 'error', // 启用入参名规则
37
37
  'naming-convention/property-name': 'warn',
38
38
  'naming-convention/instance-property': 'warn',
39
39
 
@@ -102,8 +102,7 @@ module.exports = [
102
102
  rules: {
103
103
  // 必须进行参数校验
104
104
  'no-unused-vars': ['error', {
105
- args: 'all',
106
- argsIgnorePattern: '^_',
105
+ args: 'none', // 不检查未使用的参数
107
106
  caughtErrors: 'all',
108
107
  caughtErrorsIgnorePattern: '^_',
109
108
  destructuredArrayIgnorePattern: '^_',
package/index.js CHANGED
@@ -1,10 +1,11 @@
1
1
  const { Store } = require('./lib/store.js');
2
2
  const { Session } = require('./lib/session.js');
3
3
 
4
- let session = new Session();
5
-
6
4
  module.exports = {
7
5
  Session,
8
6
  Store,
9
- session
7
+ session: function(config) {
8
+ let session = new Session(config);
9
+ return session.middleware();
10
+ }
10
11
  };