Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/deploy-modelscope.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ on:
- 'chapters/**'
- 'CONTRIBUTING.md'
- 'scripts/build-content.py'
- 'scripts/version-assets.mjs'
- 'scripts/chapter_markdown.py'
- 'scripts/test_chapter_markdown.py'
- 'scripts/build-content.mjs'
Expand Down Expand Up @@ -56,6 +57,8 @@ jobs:
.venv/bin/python -m pytest tests -q
- name: Verify chapter data and local resources
run: |
python3 scripts/build-content.py
node scripts/version-assets.mjs
python3 scripts/test_chapter_markdown.py
node scripts/build-content.mjs --check
node scripts/check-site.mjs
Expand Down
10 changes: 9 additions & 1 deletion AUTH-AND-DISCUSSION.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
- 游客可阅读正文、公开划线评论与章节留言。
- 登录后可选中同一段落内最多 2000 字:保存仅自己可见的划线,或发表公开想法。
- 章节末尾可留言,按最新优先显示;支持加载更多。点击引用可回到原文。
- 公开留言可点击“回复”,回复引用原留言并显示在其下方;父留言还没加载时先显示引用,加载更多后归入对应讨论。原留言删除后保留其他读者的回复,并提示原留言已删除。
- 用户名链接到魔搭个人主页。主页使用验证后的 `preferred_username`,不会从昵称或 OIDC sub 猜测。旧账号再次登录后,历史留言和愿望同步获得主页链接。
- 作者可删除自己的记录。`MODERATOR_SUBS` 可配置管理员的 OIDC sub(逗号分隔),管理员可删除公开内容。
- 原文变更后先校验段落、偏移和引用;无法唯一匹配时保留笔记并提示无法定位,不把划线错误应用到其他文字。

Expand Down Expand Up @@ -51,7 +53,7 @@ Docker 监听 7860,持久化数据目录固定为 `/mnt/workspace/purplebook`
## 身份与安全

使用 Authlib 完成 OIDC state、nonce、签名及身份校验。Cookie 中只保存随机服务端会话 ID、CSRF 与短期授权事务;不保存访问令牌。
数据库保存随机用户 ID、OIDC sub、显示名称和评论;用户 ID 只取自验证后的服务端身份。退出时撤销服务端会话。
数据库保存随机用户 ID、OIDC sub、显示名称、魔搭用户名和评论;用户 ID 只取自验证后的服务端身份。需要补取 userinfo 时校验其 sub 与已验证身份一致。退出时撤销服务端会话。
写操作要求有效登录、同源 Origin 和 CSRF token。每位用户每分钟最多 10 次写入。静态文件仅通过显式允许的目录提供,源代码、数据库、密钥不会作为静态文件暴露。
前端通过 textContent 渲染用户内容,拒绝将评论作为 HTML 执行。
生产会话使用 HTTPS Secure、HttpOnly、SameSite=Lax Cookie。
Expand All @@ -78,3 +80,9 @@ node tests/discussion-browser.cjs
该验证会启动 7861 端口的隔离测试服务并生成测试会话,仅写入临时目录;结束后清理,不往真实评论库写入测试内容。

创空间提供方兼容:认证发现固定使用 `https://www.modelscope.cn/.well-known/openid-configuration`,避免平台内部提供方别名触发地址白名单或浏览器跳转问题。客户端 ID 和密钥仍取自平台注入。

## 正文链接与首页数字

构建时自动把正文及代码里的裸 HTTP(S)/www 网址转换为可点击链接,保留文字、代码复制内容和原有链接。外部链接在新窗口打开。

首页数字随每次仓库部署重新生成:社区共建按 `assets/contributors/profiles.json` 的 handle 去重;真实任务按 `content/practice.json` 中指向已开放章节的任务计数;合计字数统计所有已开放章节(含标题与代码),汉字逐字计、英文及数字按词计,符号和空白不计。首页以万字显示两位小数,悬停可见精确数字。新任务需加入 `content/practice.json`,任务卡片和首页数量使用同一份数据。
39 changes: 35 additions & 4 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
import threading
import time
from pathlib import Path
from urllib.parse import urlparse
from urllib.parse import quote, urlparse
from zoneinfo import ZoneInfo

from authlib.integrations.starlette_client import OAuth, OAuthError
Expand All @@ -37,6 +37,7 @@

class Entry(BaseModel):
kind: str
parentId: str | None = Field(default=None, max_length=64)
text: str = Field(default='', max_length=2000)
quote: str = Field(default='', max_length=2000)
block: int = Field(default=0, ge=0, le=100000)
Expand Down Expand Up @@ -88,6 +89,8 @@ def db():
CREATE INDEX IF NOT EXISTS entries_user_time ON entries(user_id, created);
CREATE TABLE IF NOT EXISTS wishes(id TEXT PRIMARY KEY, user_id TEXT NOT NULL REFERENCES users(id), text TEXT NOT NULL, created INTEGER NOT NULL);
CREATE INDEX IF NOT EXISTS wishes_user_time ON wishes(user_id, created);
CREATE TABLE IF NOT EXISTS user_profiles(user_id TEXT PRIMARY KEY REFERENCES users(id), username TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS entry_replies(entry_id TEXT PRIMARY KEY REFERENCES entries(id) ON DELETE CASCADE, parent_id TEXT REFERENCES entries(id) ON DELETE SET NULL);
''')

@contextmanager
Expand Down Expand Up @@ -306,7 +309,12 @@ def user(request):
row = conn.execute('SELECT users.* FROM sessions JOIN users ON users.id=sessions.user_id WHERE sessions.id=? AND expires>?', (sid,int(time.time()))).fetchone()
return dict(row) if row else None
def public_user(u):
return {'id':u['id'],'name':u['name'],'moderator':u['sub'] in admins} if u else None
if not u: return None
with db() as conn:
profile=conn.execute('SELECT username FROM user_profiles WHERE user_id=?',(u['id'],)).fetchone()
return {'id':u['id'],'name':u['name'],'moderator':u['sub'] in admins,'profileUrl':profile_url(profile['username']) if profile else None}
def profile_url(username):
return 'https://modelscope.cn/profile/'+quote(username,safe='') if username else None
def require_user(request):
u=user(request)
if not u: raise HTTPException(401,'请先使用魔搭账号登录')
Expand Down Expand Up @@ -467,6 +475,12 @@ async def callback(request: Request):
token = await oauth.modelscope.authorize_access_token(request)
info = token.get('userinfo')
if not info or not info.get('sub'): raise ValueError('Missing validated identity')
# ID tokens may omit profile claims. Fetch them server-side and bind
# the result to the already validated subject before saving a handle.
if not info.get('preferred_username') and token.get('access_token'):
profile = await oauth.modelscope.userinfo(token=token)
if str(profile.get('sub')) != str(info['sub']): raise ValueError('Identity mismatch')
info = {**info, **profile}
except (OAuthError, ValueError):
return RedirectResponse('/?login=failed#home',status_code=303)
sub=str(info['sub'])
Expand All @@ -475,6 +489,9 @@ async def callback(request: Request):
with db() as conn:
conn.execute('INSERT INTO users VALUES (?,?,?) ON CONFLICT(sub) DO UPDATE SET name=excluded.name',(secrets.token_hex(16),sub,name))
uid=conn.execute('SELECT id FROM users WHERE sub=?',(sub,)).fetchone()['id']
username=info.get('preferred_username')
if isinstance(username,str) and username.strip():
conn.execute('INSERT INTO user_profiles VALUES (?,?) ON CONFLICT(user_id) DO UPDATE SET username=excluded.username',(uid,username.strip()))
conn.execute('DELETE FROM sessions WHERE expires<=? OR id=?',(now,request.session.get('sid','')))
conn.execute('INSERT INTO sessions VALUES (?,?,?)',(sid,uid,now+7*86400))
target=request.session.get('return_to','#home')
Expand All @@ -494,29 +511,42 @@ def list_entries(chapter: str, request: Request, before: int = 0):
storage_chapter=check_chapter(chapter); u=user(request); uid=u['id'] if u else ''
# Rowid cursor remains stable even when multiple entries share a timestamp.
with db() as conn:
rows=conn.execute('SELECT e.rowid cursor,e.*,u.name FROM entries e JOIN users u ON u.id=e.user_id WHERE e.chapter=? AND (e.kind!=\'highlight\' OR e.user_id=?) AND (?=0 OR e.rowid<?) ORDER BY e.rowid DESC LIMIT 101',(storage_chapter,uid,before,before)).fetchall()
rows=conn.execute('''SELECT e.rowid cursor,e.*,u.name,p.username,r.entry_id reply_id,r.parent_id,
parent.text parent_text,author.name parent_name FROM entries e JOIN users u ON u.id=e.user_id
LEFT JOIN user_profiles p ON p.user_id=u.id LEFT JOIN entry_replies r ON r.entry_id=e.id
LEFT JOIN entries parent ON parent.id=r.parent_id LEFT JOIN users author ON author.id=parent.user_id
WHERE e.chapter=? AND (e.kind!='highlight' OR e.user_id=?) AND (?=0 OR e.rowid<?)
ORDER BY e.rowid DESC LIMIT 101''',(storage_chapter,uid,before,before)).fetchall()
items=[]
for row in rows[:100]:
item=dict(row); item['chapter']=chapter; item['mine']=item['user_id']==uid
item['canDelete']=item['mine'] or bool(u and u['sub'] in admins)
item['profileUrl']=profile_url(item.pop('username'))
item['replyTo']={'id':item.pop('parent_id'),'name':item.pop('parent_name'),'text':item.pop('parent_text')} if item.pop('reply_id') else None
for field in ('parent_id','parent_name','parent_text'): item.pop(field,None)
item.pop('user_id'); items.append(item)
return {'items':items,'next':items[-1]['cursor'] if len(rows)>100 else None}

@app.post('/api/chapters/{chapter}/entries',status_code=201)
def add_entry(chapter: str, entry: Entry, request: Request):
u=require_user(request); chapter=check_chapter(chapter)
if entry.kind not in ('highlight','annotation','comment'): raise HTTPException(422,'不支持的笔记类型')
if entry.parentId and entry.kind!='comment': raise HTTPException(422,'只能回复公开留言')
if entry.kind!='highlight' and not entry.text.strip(): raise HTTPException(422,'请填写内容')
if entry.kind!='comment' and (not entry.quote.strip() or entry.end<=entry.start): raise HTTPException(422,'请先选择正文中的文字')
now=int(time.time()); eid=secrets.token_hex(16)
with db() as conn:
conn.execute('BEGIN IMMEDIATE')
if entry.parentId:
parent=conn.execute('SELECT chapter,kind FROM entries WHERE id=?',(entry.parentId,)).fetchone()
if not parent or parent['chapter']!=chapter or parent['kind']!='comment': raise HTTPException(422,'这条留言已删除或不在本章')
count=conn.execute('SELECT count(*) FROM entries WHERE user_id=? AND created>?',(u['id'],now-60)).fetchone()[0]
if count>=10: raise HTTPException(429,'操作太频繁,请稍后再试')
if entry.kind=='highlight':
existing=conn.execute('SELECT id FROM entries WHERE chapter=? AND user_id=? AND kind=? AND block=? AND start=? AND end=? AND quote=?',(chapter,u['id'],entry.kind,entry.block,entry.start,entry.end,entry.quote)).fetchone()
if existing: return {'id':existing['id']}
conn.execute('INSERT INTO entries VALUES (?,?,?,?,?,?,?,?,?,?)',(eid,chapter,u['id'],entry.kind,entry.text.strip(),entry.quote,entry.block,entry.start,entry.end,now))
if entry.parentId: conn.execute('INSERT INTO entry_replies VALUES (?,?)',(eid,entry.parentId))
return {'id':eid}

@app.delete('/api/entries/{entry_id}')
Expand All @@ -533,11 +563,12 @@ def delete_entry(entry_id: str, request: Request):
def list_wishes(request: Request, before: int = 0):
u=user(request)
with db() as conn:
rows=conn.execute('SELECT w.rowid cursor,w.*,u.name FROM wishes w JOIN users u ON u.id=w.user_id WHERE (?=0 OR w.rowid<?) ORDER BY w.rowid DESC LIMIT 21',(before,before)).fetchall()
rows=conn.execute('SELECT w.rowid cursor,w.*,u.name,p.username FROM wishes w JOIN users u ON u.id=w.user_id LEFT JOIN user_profiles p ON p.user_id=u.id WHERE (?=0 OR w.rowid<?) ORDER BY w.rowid DESC LIMIT 21',(before,before)).fetchall()
items=[]
for row in rows[:20]:
item=dict(row)
item['canDelete']=bool(u and (item['user_id']==u['id'] or u['sub'] in admins))
item['profileUrl']=profile_url(item.pop('username'))
item.pop('user_id'); items.append(item)
return {'items':items,'next':items[-1]['cursor'] if len(rows)>20 else None}

Expand Down
2 changes: 1 addition & 1 deletion assets/content.js

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions assets/discussion.css

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading