[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
@@ -2,60 +2,160 @@
id: wiki-2026-0508-session-lifecycle
title: Session Lifecycle
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [550e8400-e29b-41d4-a716-446655440004]
aliases: [Session Management, Session State, Login Session]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [Governance, Git, Automation, Session Management]
confidence_score: 0.9
verification_status: applied
tags: [security, web, authentication, session]
raw_sources: []
last_reinforced: 2026-04-21
github_commit: initial
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: typescript
framework: nextjs-redis
---
# [[Session Lifecycle|Session Lifecycle]]
# Session Lifecycle
## 📌 한 줄 통찰 (The Karpathy Summary)
> 업무의 시작과 끝을 Git 동기화 자동화와 결합하여 데이터 무결성을 보장하고 개발 환경 세팅 시간을 제로화하는 세션 관리 프로토콜.
## 한 줄
> **"매 user 의 매 authenticated state 의 매 birth → death"**. Session lifecycle 는 매 login 으로 매 시작, 매 idle/absolute timeout 또는 매 explicit logout 으로 매 끝. 2026 현재 매 stateless JWT 의 매 short-lived access token (15 min) + 매 stateful refresh token (rotating, server-revocable) 의 매 hybrid 가 매 dominant; 매 OWASP ASVS V3 가 매 baseline.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** 세션의 생명주기(Start/End)를 명시적인 트리거와 연결하여 멀티 리포지토리 환경에서의 관리 복잡성을 해결함.
- **세부 내용:**
- **Start Session**: "일 시작하자" 트리거 시 모든 프로젝트(Wiki, Skybound, Agent, Datacollector)의 최신 데이터를 확보(`git pull`).
- **End Session**: "마무리 하자" 트리거 시 모든 변경 사항을 일괄 커밋 및 푸시(`git push`)하고 미처리 원시 데이터를 점검.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **정책 변화**: 수동 Git 관리에서 세션 기반 자동 동기화로 전환하여 커밋 누락 및 컨플릭트 위험을 사전에 차단.
### 매 Phases
1. **Auth**: credential verify (password, MFA, passkey).
2. **Issue**: session token (cookie / JWT) + binding (UA, IP optional).
3. **Validate**: per-request check + refresh.
4. **Refresh**: rotation on each use.
5. **Terminate**: logout, idle (15-30min), absolute (12-24h), forced (admin, breach).
## 🔗 지식 연결 (Graph)
- **Parent**: Governance & Reliability
- **Related**: [[Autonomous Logging|Autonomous Logging]], Git Protocol
- **Raw Source**: 00_Raw/2026-04-21-Session_Lifecycle_Protocol_Update
### 매 Token strategies
- **Stateful (DB session)**: server stores; revocable instantly; scale via Redis.
- **Stateless JWT**: signed token; revocation via short TTL or blocklist.
- **Hybrid**: short JWT access + opaque refresh in DB.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 Cookie attributes
- `HttpOnly` — XSS protection.
- `Secure` — TLS only.
- `SameSite=Lax` (or Strict) — CSRF.
- `__Host-` prefix — domain lock.
- `Path=/` and reasonable `Max-Age`.
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 응용
1. Web SPA + cookie session.
2. Mobile app + refresh-token rotation.
3. SSO (SAML/OIDC) federated.
4. Service mesh (mTLS-based).
**언제 쓰면 안 되는가:**
- *(TODO)*
## 💻 패턴
## 🧪 검증 상태 (Validation)
### Cookie session (Express + Redis)
```typescript
import session from "express-session";
import RedisStore from "connect-redis";
app.use(session({
store: new RedisStore({ client: redis, prefix: "sess:" }),
secret: process.env.SESSION_SECRET!,
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true, secure: true, sameSite: "lax",
maxAge: 30 * 60_000, // idle timeout via touch
},
rolling: true,
}));
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### JWT access + rotating refresh
```typescript
function issueTokens(userId: string) {
const access = jwt.sign({ sub: userId }, ACCESS_SECRET, { expiresIn: "15m" });
const refresh = crypto.randomUUID();
redis.set(`refresh:${refresh}`, userId, "EX", 60 * 60 * 24 * 14);
return { access, refresh };
}
async function rotate(oldRefresh: string) {
const userId = await redis.get(`refresh:${oldRefresh}`);
if (!userId) throw new Error("invalid");
await redis.del(`refresh:${oldRefresh}`); // single-use
return issueTokens(userId);
}
```
## 🧬 중복 검사 (Duplicate Check)
### Idle + absolute timeout
```typescript
type Session = { userId: string; createdAt: number; lastSeenAt: number };
const ABSOLUTE = 24 * 3600_000;
const IDLE = 30 * 60_000;
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
function valid(s: Session): boolean {
const now = Date.now();
return now - s.createdAt < ABSOLUTE && now - s.lastSeenAt < IDLE;
}
```
## 🕓 변경 이력 (Changelog)
### Global logout (token version)
```typescript
// User table column: tokenVersion (incremented on logout-everywhere)
const access = jwt.sign({ sub: user.id, ver: user.tokenVersion }, SECRET);
// On verify
if (decoded.ver !== currentUser.tokenVersion) throw new Error("revoked");
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### Session hijack defense (binding)
```typescript
function bindClaims(req: Request) {
return crypto.createHash("sha256")
.update(req.headers["user-agent"] + req.ip).digest("hex");
}
// On issue: store. On validate: compare. Mismatch → require re-auth.
```
### Concurrent session limit
```typescript
const sessions = await redis.smembers(`user_sessions:${userId}`);
if (sessions.length >= 5) {
const oldest = sessions[0];
await redis.del(`sess:${oldest}`);
await redis.srem(`user_sessions:${userId}`, oldest);
}
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| 매 Web SPA, 매 same domain | Cookie + CSRF token |
| 매 mobile / cross-origin | JWT access + refresh in secure storage |
| 매 high-security (banking) | Short access (5m) + step-up auth |
| 매 SSO required | OIDC + IdP-managed session |
**기본값**: HttpOnly Secure SameSite=Lax cookie + Redis-backed session, 30m idle / 24h absolute.
## 🔗 Graph
- 부모: [[Authentication]] · [[Application Security]]
- 변형: [[JWT]] · [[OAuth 2.0]] · [[Passkeys]]
- 응용: [[OWASP Top 10]] · [[Zero-Trust Architecture]]
- Adjacent: [[CSRF]] · [[XSS]]
## 🤖 LLM 활용
**언제**: Session anomaly detection (매 sudden geo / device shift), suspicious-activity summary for support.
**언제 X**: 매 token issuance / signing — 매 deterministic crypto only.
## ❌ 안티패턴
- **localStorage JWT**: 매 XSS → 매 token theft. 매 HttpOnly cookie.
- **No refresh rotation**: 매 leaked refresh = 매 forever access.
- **No absolute timeout**: 매 1년 session — 매 dormant account hijack.
- **Client-side only check**: 매 every request server-side.
## 🧪 검증 / 중복
- Verified (OWASP Session Management Cheat Sheet, ASVS V3, NIST SP 800-63B).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — JWT+refresh hybrid + passkey-era state |