Skip to content

feat(webapp): 会话存储与安全 Cookie 中间件(#70 第一批) - #81

Merged
Antruly merged 3 commits into
masterfrom
feat/session
Nov 21, 2026
Merged

Antruly merged 3 commits into
masterfrom
feat/session

Conversation

@Antruly

@Antruly Antruly commented Nov 21, 2026

Copy link
Copy Markdown
Owner

Part of #70(第一批:会话存储与安全 Cookie;Redis/RBAC/CSRF 等留后续)。

内容

  • uvcpp_session:id + 键值数据 + 创建/过期时间;regenerate()(防会话固定)。
  • uvcpp_session_store:可插拔接口;uvcpp_memory_session_store(线程安全、默认上限 10000、按最早过期逐出)。
  • uvcpp_session_middleware(store, opts):
    • 每个请求都有会话(首次访问即建并下发 Set-Cookie);sliding 默认开,每次请求续期;
    • Cookie 属性:HttpOnly(默认)/ Secure / SameSite / Path / Max-Age;
    • 会话数据在响应 on_sent 时落库 —— 实测中间件链的 next() 先返回、下游 handler 后执行,写在 next() 后面的 save 会漏掉处理器里的 set();
    • regenerate() 时旧 id 在响应结束时删除、新 id 由 uvcpp_session_set_cookie() 下发。
  • uvcpp_session_logout(req, resp, store, opts):删 store + 过期 Cookie。
  • uvcpp_web_request 新增请求级属性 API(set_attribute/attribute/attribute_as),take_from() 时清空;中间件与处理器之间传对象不用加基类。

用例

web_app_session_func(真端口 + 真 Cookie):

  1. 首次请求 401,Set-Cookie 带 sid、HttpOnly、SameSite=Lax、Path=/、Max-Age=ttl;
  2. 登录(handler set())后同 Cookie 读得到 uid=42;
  3. 注销响应带 Max-Age=0(第二条 Set-Cookie),旧 Cookie 立即失效、store 删净;
  4. ttl=1 过期后旧 Cookie 被拒;
  5. regenerate() 后旧 id 401、新 id 带原会话数据;
  6. secure=true 时 Cookie 带 Secure;
  7. store 边界:空 id 不落库、destroy 幂等、load 不存在返回 false。

验证

build-all 167/167、build-h3 / build-default 编过;check_docs / check_doc_lines / check_doc_versions / check_ci_layout 全绿。文档 doc/webapp-guide.md §22。

新增 `uvcpp_session` / `uvcpp_session_store` / `uvcpp_memory_session_store` /
`uvcpp_session_middleware`:

- **每个请求都有会话**(首次访问建 + 下发 `Set-Cookie`),`sliding` 默认开;
- Cookie 属性齐全:HttpOnly / Secure / SameSite / Path / Max-Age;
- `uvcpp_session_of(req)` 取当前会话;`set/erase/clear` 在响应 `on_sent` 时
  落库 —— 实测中间件链的 `next()` 会先返回、下游 handler 后跑,写在 `next()`
  后面的 save 拿的是处理前的会话(登录后下一条请求读不到 uid);
- 注销 `uvcpp_session_logout()`(删 store + 过期 Cookie);防会话固定
  `session->regenerate()` + `uvcpp_session_set_cookie()`;
- store 可插拔:内存实现默认上限 10000、按最早过期逐出,接口要求线程安全
  (多循环共用);Redis/MySQL/SQLite 适配器、RBAC/限流/CSRF 留给 #70 后续;
- `uvcpp_web_request` 新增请求级属性 API(`set_attribute/attribute/
  attribute_as`,`take_from` 时清空),中间件与处理器之间传会话不用加基类。

用例 `web_app_session_func`:建会话(HttpOnly/SameSite/Path/Max-Age)、登录后
读 uid、注销后旧 Cookie 失效且 store 删净、ttl=1 过期、regenerate 后旧 id 立即
失效且新 id 带原数据、secure=true 带 Secure、store 边界(空 id/destroy/load)。
文档 `doc/webapp-guide.md` §22。

本地 build-all 167/167、build-h3/default 编过;五条文档门禁全绿。
@Antruly
Antruly merged commit 96c1373 into master Nov 21, 2026
47 of 49 checks passed
@Antruly
Antruly deleted the feat/session branch November 21, 2026 19:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant