-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path04-code-understanding.html
More file actions
491 lines (448 loc) · 17.4 KB
/
Copy path04-code-understanding.html
File metadata and controls
491 lines (448 loc) · 17.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>acme/web 中的认证流程</title>
<style>
:root {
--ivory: #FAF9F5;
--slate: #141413;
--clay: #D97757;
--oat: #E3DACC;
--olive: #788C5D;
--rust: #B04A3F;
--gray-150: #F0EEE6;
--gray-300: #D1CFC5;
--gray-500: #87867F;
--gray-700: #3D3D3A;
--serif: ui-serif, Georgia, 'Times New Roman', serif;
--sans: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
--mono: ui-monospace, 'SF Mono', Menlo, Monaco, monospace;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
background: var(--ivory);
color: var(--gray-700);
font-family: var(--sans);
font-size: 15px;
line-height: 1.65;
padding: 48px 24px 80px;
}
.page {
max-width: 1080px;
margin: 0 auto;
display: grid;
grid-template-columns: minmax(0, 1fr) 280px;
gap: 40px;
}
@media (max-width: 960px) {
.page { grid-template-columns: 1fr; }
}
/* ---------- Header ---------- */
header {
grid-column: 1 / -1;
margin-bottom: 8px;
}
.repo-line {
font-family: var(--mono);
font-size: 12.5px;
color: var(--gray-500);
margin-bottom: 10px;
}
h1 {
font-family: var(--serif);
font-weight: 500;
font-size: 32px;
line-height: 1.25;
color: var(--slate);
margin-bottom: 16px;
}
.summary {
max-width: 760px;
font-size: 15.5px;
}
.summary code { font-family: var(--mono); font-size: 13px; }
h2 {
font-family: var(--serif);
font-weight: 500;
font-size: 22px;
color: var(--slate);
margin: 36px 0 16px;
}
/* ---------- Diagram ---------- */
.diagram-panel {
border: 1.5px solid var(--gray-300);
border-radius: 12px;
background: #fff;
padding: 20px;
overflow-x: auto;
}
svg.flow { display: block; max-width: 100%; }
.flow text {
font-family: var(--mono);
font-size: 12px;
fill: var(--slate);
}
.flow .sub { font-size: 10px; fill: var(--gray-500); }
.flow .box { fill: #fff; stroke: var(--gray-300); stroke-width: 1.5; }
.flow .box.hot { fill: rgba(217,119,87,0.10); stroke: var(--clay); }
.flow .arrow { stroke: var(--gray-500); stroke-width: 1.5; fill: none; }
/* ---------- Walkthrough ---------- */
.step {
display: grid;
grid-template-columns: 44px 1fr;
gap: 18px;
padding: 20px 0;
border-bottom: 1.5px solid var(--gray-150);
}
.step:last-of-type { border-bottom: none; }
.badge {
width: 34px;
height: 34px;
border-radius: 50%;
background: var(--oat);
border: 1.5px solid var(--gray-300);
display: flex;
align-items: center;
justify-content: center;
font-family: var(--mono);
font-weight: 600;
color: var(--slate);
font-size: 14px;
}
.step.hot .badge {
background: rgba(217,119,87,0.14);
border-color: var(--clay);
color: var(--clay);
}
.step-loc {
font-family: var(--mono);
font-size: 13px;
color: var(--slate);
margin-bottom: 6px;
}
.step-loc .range { color: var(--gray-500); }
.step-body p { margin-bottom: 10px; }
details.snippet { margin-top: 6px; }
details.snippet summary {
list-style: none;
cursor: pointer;
font-size: 12.5px;
color: var(--gray-500);
font-family: var(--mono);
display: inline-flex;
align-items: center;
gap: 6px;
padding: 4px 0;
user-select: none;
}
details.snippet summary::-webkit-details-marker { display: none; }
details.snippet summary::before {
content: "▸";
font-size: 10px;
transition: transform 0.15s ease;
}
details.snippet[open] summary::before { transform: rotate(90deg); }
pre.code {
background: var(--slate);
color: #E8E6DC;
font-family: var(--mono);
font-size: 12.5px;
line-height: 1.7;
border-radius: 8px;
padding: 14px 16px;
overflow-x: auto;
margin-top: 10px;
}
pre.code .dim { color: var(--gray-500); }
pre.code .kw { color: #C9B98A; }
pre.code .str { color: #A8BC8C; }
/* ---------- Sidebar ---------- */
aside {
position: sticky;
top: 24px;
align-self: start;
}
.panel {
border: 1.5px solid var(--gray-300);
border-radius: 12px;
background: #fff;
padding: 18px 20px;
margin-bottom: 20px;
}
.panel h3 {
font-family: var(--sans);
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.08em;
color: var(--gray-500);
margin-bottom: 12px;
}
.key-files { list-style: none; padding: 0; }
.key-files li { margin-bottom: 12px; }
.key-files li:last-child { margin-bottom: 0; }
.key-files .path {
font-family: var(--mono);
font-size: 12px;
color: var(--slate);
display: block;
margin-bottom: 2px;
word-break: break-all;
}
.key-files .desc {
font-size: 12.5px;
color: var(--gray-500);
line-height: 1.45;
}
.gotchas {
border: 1.5px solid var(--clay);
border-radius: 12px;
background: rgba(217,119,87,0.06);
padding: 18px 20px;
}
.gotchas h3 {
font-family: var(--sans);
font-size: 11px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.08em;
color: var(--clay);
margin-bottom: 10px;
}
.gotchas ul { list-style: none; padding: 0; }
.gotchas li {
position: relative;
padding-left: 16px;
font-size: 13px;
margin-bottom: 8px;
}
.gotchas li::before {
content: "";
position: absolute;
left: 0; top: 8px;
width: 5px; height: 5px;
background: var(--clay);
border-radius: 2px;
}
.gotchas code { font-family: var(--mono); font-size: 11.5px; }
</style>
</head>
<body>
<div class="page">
<header>
<div class="repo-line">acme/web · 架构笔记</div>
<h1>认证在代码库中如何流转</h1>
<p class="summary">
Acme 使用基于 cookie 的会话机制:浏览器不直接持有 bearer token。每个需要认证的请求都会打到 <code>/api/*</code>,经过唯一的 <code>verifyToken()</code> 中间件,解析到一行 <code>Session</code> 记录,下游 handler 从 <code>req.ctx</code> 上读取它。中间件是唯一跟 session store 打交道的地方,而 session store 是唯一跟 <code>sessions</code> 表打交道的地方,所以你只需要关注一条信任边界。
</p>
</header>
<main>
<h2 style="margin-top:0">请求路径</h2>
<div class="diagram-panel">
<svg class="flow" viewBox="0 0 720 280" width="720" height="280" role="img" aria-label="Authentication flow diagram">
<defs>
<marker id="arrowHead" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
<path d="M 0 0 L 10 5 L 0 10 z" fill="#87867F"></path>
</marker>
</defs>
<!-- Row 1 -->
<g>
<rect class="box" x="30" y="40" width="150" height="64" rx="10"></rect>
<text x="105" y="68" text-anchor="middle">Browser</text>
<text class="sub" x="105" y="84" text-anchor="middle">acme.app</text>
</g>
<g>
<rect class="box" x="245" y="40" width="150" height="64" rx="10"></rect>
<text x="320" y="68" text-anchor="middle">/api/session</text>
<text class="sub" x="320" y="84" text-anchor="middle">route handler</text>
</g>
<g>
<rect class="box hot" x="460" y="40" width="180" height="64" rx="10"></rect>
<text x="550" y="68" text-anchor="middle">verifyToken()</text>
<text class="sub" x="550" y="84" text-anchor="middle">middleware/auth.ts</text>
</g>
<!-- Row 2 -->
<g>
<rect class="box" x="460" y="170" width="180" height="64" rx="10"></rect>
<text x="550" y="198" text-anchor="middle">SessionStore</text>
<text class="sub" x="550" y="214" text-anchor="middle">lib/sessionStore.ts</text>
</g>
<g>
<rect class="box" x="245" y="170" width="150" height="64" rx="10"></rect>
<text x="320" y="198" text-anchor="middle">Postgres</text>
<text class="sub" x="320" y="214" text-anchor="middle">sessions table</text>
</g>
<!-- Arrows -->
<line class="arrow" x1="180" y1="72" x2="245" y2="72" marker-end="url(#arrowHead)"></line>
<line class="arrow" x1="395" y1="72" x2="460" y2="72" marker-end="url(#arrowHead)"></line>
<line class="arrow" x1="550" y1="104" x2="550" y2="170" marker-end="url(#arrowHead)"></line>
<line class="arrow" x1="460" y1="202" x2="395" y2="202" marker-end="url(#arrowHead)"></line>
<text class="sub" x="212" y="62" text-anchor="middle">cookie</text>
<text class="sub" x="560" y="140" text-anchor="start">lookup</text>
</svg>
</div>
<h2>调用栈逐步解析</h2>
<!-- Step 1 -->
<div class="step">
<div class="badge">1</div>
<div class="step-body">
<div class="step-loc">src/app/providers/AuthProvider.tsx<span class="range"> :22-48</span></div>
<p>组件挂载时,React provider 发起 <code style="font-family:var(--mono);font-size:12.5px">GET /api/session</code> 请求,带上 <code style="font-family:var(--mono);font-size:12.5px">credentials: 'include'</code>,这样 <code style="font-family:var(--mono);font-size:12.5px">fw_sid</code> cookie 会自动附带。响应要么把 <code style="font-family:var(--mono);font-size:12.5px">currentUser</code> 注入上下文,要么留空为 <code style="font-family:var(--mono);font-size:12.5px">null</code>,路由层会据此显示登录页面。</p>
<details class="snippet">
<summary>查看源码</summary>
<pre class="code"><span class="dim">// src/app/providers/AuthProvider.tsx</span>
<span class="kw">export function</span> AuthProvider({ children }: Props) {
<span class="kw">const</span> [user, setUser] = useState<User | <span class="kw">null</span>>(<span class="kw">null</span>);
useEffect(() => {
fetch(<span class="str">'/api/session'</span>, { credentials: <span class="str">'include'</span> })
.then(r => r.ok ? r.json() : <span class="kw">null</span>)
.then(setUser);
}, []);
<span class="kw">return</span> <AuthCtx.Provider value={{ user }}>{children}</AuthCtx.Provider>;
}</pre>
</details>
</div>
</div>
<!-- Step 2 -->
<div class="step">
<div class="badge">2</div>
<div class="step-body">
<div class="step-loc">src/server/routes/session.ts<span class="range"> :9-27</span></div>
<p>这个路由本身很薄:只返回中间件附加在 <code style="font-family:var(--mono);font-size:12.5px">req.ctx.session</code> 上的内容。如果中间件已经返回了 401,这个 handler 根本不会执行,所以这里没有重复的认证逻辑。</p>
<details class="snippet">
<summary>查看源码</summary>
<pre class="code"><span class="dim">// src/server/routes/session.ts</span>
router.get(<span class="str">'/session'</span>, verifyToken, (req, res) => {
<span class="kw">const</span> { session } = req.ctx;
res.json({
id: session.userId,
email: session.email,
role: session.role,
exp: session.expiresAt,
});
});</pre>
</details>
</div>
</div>
<!-- Step 3 -->
<div class="step hot">
<div class="badge">3</div>
<div class="step-body">
<div class="step-loc">src/middleware/auth.ts<span class="range"> :14-31</span></div>
<p>这里是信任边界。<code style="font-family:var(--mono);font-size:12.5px">verifyToken</code> 读取签名的 <code style="font-family:var(--mono);font-size:12.5px">fw_sid</code> cookie,让 <code style="font-family:var(--mono);font-size:12.5px">SessionStore</code> 去解析,然后要么填充 <code style="font-family:var(--mono);font-size:12.5px">req.ctx.session</code>,要么返回 401。应用里所有受保护的路由都挂在这个函数后面,改它就等于改了全局认证行为。</p>
<details class="snippet" open>
<summary>查看源码</summary>
<pre class="code"><span class="dim">// src/middleware/auth.ts</span>
<span class="kw">export async function</span> verifyToken(req, res, next) {
<span class="kw">const</span> raw = req.signedCookies[<span class="str">'fw_sid'</span>];
<span class="kw">if</span> (!raw) <span class="kw">return</span> res.status(401).end();
<span class="kw">const</span> session = <span class="kw">await</span> SessionStore.get(raw);
<span class="kw">if</span> (!session || session.expiresAt < Date.now()) {
<span class="kw">return</span> res.status(401).end();
}
req.ctx = { session };
next();
}</pre>
</details>
</div>
</div>
<!-- Step 4 -->
<div class="step">
<div class="badge">4</div>
<div class="step-body">
<div class="step-loc">src/lib/sessionStore.ts<span class="range"> :8-52</span></div>
<p><code style="font-family:var(--mono);font-size:12.5px">SessionStore</code> 是一个小型读穿缓存:先查进程内 LRU,命中就返回,未命中则回退到 Postgres。写操作(<code style="font-family:var(--mono);font-size:12.5px">create</code>、<code style="font-family:var(--mono);font-size:12.5px">revoke</code>)始终直接写库并清除对应缓存条目,以防其他 worker 继续使用过期会话。</p>
<details class="snippet">
<summary>查看源码</summary>
<pre class="code"><span class="dim">// src/lib/sessionStore.ts</span>
<span class="kw">const</span> cache = <span class="kw">new</span> LRU<string, Session>({ max: 5000, ttl: 60_000 });
<span class="kw">export const</span> SessionStore = {
<span class="kw">async</span> get(id: string) {
<span class="kw">const</span> hit = cache.get(id);
<span class="kw">if</span> (hit) <span class="kw">return</span> hit;
<span class="kw">const</span> row = <span class="kw">await</span> db.one(SELECT_SESSION, [id]);
<span class="kw">if</span> (row) cache.set(id, row);
<span class="kw">return</span> row ?? <span class="kw">null</span>;
},
<span class="dim">/* create, revoke, touch ... */</span>
};</pre>
</details>
</div>
</div>
<!-- Step 5 -->
<div class="step">
<div class="badge">5</div>
<div class="step-body">
<div class="step-loc">db/migrations/004_sessions.sql<span class="range"> :1-18</span></div>
<p><code style="font-family:var(--mono);font-size:12.5px">sessions</code> 表以随机 32 字节 id(即 cookie 值)为主键,在 <code style="font-family:var(--mono);font-size:12.5px">user_id</code> 上建了覆盖索引,用于「全部登出」功能。过期策略在这里(<code style="font-family:var(--mono);font-size:12.5px">expires_at</code>)和中间件中都有强制执行,做双重防护。</p>
<details class="snippet">
<summary>查看源码</summary>
<pre class="code"><span class="dim">-- db/migrations/004_sessions.sql</span>
<span class="kw">create table</span> sessions (
id <span class="kw">text primary key</span>,
user_id <span class="kw">uuid not null references</span> users(id),
created_at <span class="kw">timestamptz default</span> now(),
expires_at <span class="kw">timestamptz not null</span>,
ip <span class="kw">inet</span>,
user_agent <span class="kw">text</span>
);
<span class="kw">create index</span> sessions_user_id_idx <span class="kw">on</span> sessions(user_id);</pre>
</details>
</div>
</div>
</main>
<aside>
<div class="panel">
<h3>关键文件</h3>
<ul class="key-files">
<li>
<span class="path">src/middleware/auth.ts</span>
<span class="desc">请求认证的唯一入口。</span>
</li>
<li>
<span class="path">src/lib/sessionStore.ts</span>
<span class="desc">LRU + Postgres 会话查找;唯一的数据库调用方。</span>
</li>
<li>
<span class="path">src/server/routes/session.ts</span>
<span class="desc">向客户端返回当前会话。</span>
</li>
<li>
<span class="path">src/server/routes/login.ts</span>
<span class="desc">通过 SessionStore.create 将凭证换成 cookie。</span>
</li>
<li>
<span class="path">src/app/providers/AuthProvider.tsx</span>
<span class="desc">镜像服务端会话的客户端上下文。</span>
</li>
<li>
<span class="path">db/migrations/004_sessions.sql</span>
<span class="desc">sessions 表和索引的 Schema。</span>
</li>
</ul>
</div>
<div class="gotchas">
<h3>注意事项</h3>
<ul>
<li><code>SessionStore</code> 的 LRU 是进程级的。撤销会话只会清除本地缓存,其他 worker 可能在 TTL(60 秒)过期前继续使用该会话。</li>
<li><code>verifyToken</code> 用 <code>Date.now()</code> 比较 <code>expiresAt</code>,但该列类型是 <code>timestamptz</code>。驱动返回的是 <code>Date</code> 对象,所以比较能正常工作。但如果重构成原始字符串比较,就要同步调整逻辑。</li>
</ul>
</div>
</aside>
</div>
<script>
// Keep at most one snippet open at a time so the walkthrough stays scannable.
var snippets = document.querySelectorAll('details.snippet');
snippets.forEach(function (d) {
d.addEventListener('toggle', function () {
if (!d.open) return;
snippets.forEach(function (other) {
if (other !== d) other.open = false;
});
});
});
</script>
</body>
</html>