10cf36ecee
后端(委托 Auth Broker,路径 A): - 删自建鉴权(OIDC exchange / 自签会话 / step-up / shortcut / web_sessions / accounts),cdrop 不再存任何凭证;鉴权中间件改读边缘注入的 X-Auth-Subject/Scope/Meta/Name/Roles 头(dev 旁路保留);Claims 加 Tier() / Guest() - internal/brokerclient:mint / revoke(带 X-Broker-App)/ refresh / ListSessions(R1 列举),直连内网、吊销幂等 统一会话模型“委派设备会话”(Delegated Device Sessions): - 每个客户端(浏览器 / 桌面 / 扫码设备)=一条带 meta(device_id) + label 的 broker 机器会话;Broker 作设备会话唯一注册表(R1 按用户+app 列举 + R2 按 (user,app,meta) 幂等铸造),cdrop 退化为薄覆盖层、不再自存权威会话表 - 新增代铸端点 POST /api/auth/device-session:凭边缘已验明的 X-Auth-Subject 委托 broker 铸 / 轮换设备会话(meta=device_id、按调用方 tier 防越权、sameOrigin CSRF、per-IP 限流);R2 幂等保证同一 device_id 重登原地轮换、不堆重复设备 - 会话列表=R1 权威 + 叠加 type(本地缓存)/ online(Hub presence,按设备名)/ current(meta 匹配本请求 X-Auth-Meta)+ 过滤 meta=""(device-authorize 引导会话残留);devices 表降级为 type/presence 薄缓存(非会话权威),device_id 主键、upsert 按 user 限定 - 吊销按 device_id → 缓存优先 / R1 兜底解析 sid → broker 吊销 + X-Broker-App;扫码登录保留三密钥编排,collect 改委托 broker 铸 + 落缓存行 Web 前端: - 登录走 broker 全局 SSO 代跳(/api/auth/login 302);bootstrap 经 /api/me 注入身份后代铸设备会话(稳定 device_id 存 localStorage、Web Locks 跨 tab 串行防重复铸造);refresh 走 /api/auth/refresh - 设备管理按 device_id;改名=同 device_id 重代铸(R2 原地轮换换 label、不产生重复行);登录页反应式守卫修登录回环 - 去 OIDC PKCE / step-up(删 oauth.callback / stepUp) 桌面客户端(Wails): - loopback PKCE(RFC 8252)改指 broker 设备授权流(/device/authorize + /device/token)拿引导令牌,再代铸出带 meta 的托管设备会话——与浏览器同模型、同管理、同吊销;身份取自代铸响应(修“显示名显示为 UUID”);refresh 保留显示名;稳定 device_id 入桌面配置 iOS 客户端(arch A,原生 SwiftUI + 离屏无头 WebView 引擎 + 原生↔JS 桥): - 引擎 / 文件管理 / 设备管理 / 应用图标 / 本地化(此前实现,随本次落入版本库) - 鉴权=引擎自刷(boot 注入 refresh_token)+ broker 轮换经 sessionRotated 回报原生更新 Keychain;去 cookie 同步;Session 加 refreshToken / deviceId 实时 / 健壮性: - presence 走 Hub union(设备表行 ∪ 表外实时连接,按名去重、live-only 标在线) - Hub 通道 close 一律在写锁内、非阻塞 send 一律在读锁内,消除 close-vs-send 闭通道 send panic(revoke 每次 Kick 后该路径变热) 配置 / 删旧栈: - config 改 broker 接入(CDROP_BROKER_* / CDROP_PUBLIC_URL / 按档 TTL),prod 强校验 broker 配置 + PUBLIC_URL(CSRF Origin 守卫不失效) - 删 auth.go / selftoken.go / shortcut.go / jwks.go + 三表(web_sessions / accounts / shortcut_tokens)及验证链;.env.example / compose.snippet.yaml / Caddyfile.snippet 更新为 broker 模型(人机分流 + 公开端点放行 + X-Auth-Meta 透传) - 测试全重写:QR / 会话含 mock broker(R1 列举 + R2 幂等);hub 加 close-vs-send 并发回归;config 加 prod 必填校验
218 lines
9.4 KiB
Go
218 lines
9.4 KiB
Go
package config
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"net/url"
|
|
"os"
|
|
"strings"
|
|
|
|
"github.com/knadh/koanf/parsers/yaml"
|
|
"github.com/knadh/koanf/providers/env/v2"
|
|
"github.com/knadh/koanf/providers/file"
|
|
"github.com/knadh/koanf/v2"
|
|
)
|
|
|
|
const envPrefix = "CDROP_"
|
|
|
|
type Config struct {
|
|
AuthMode string `koanf:"auth_mode"`
|
|
DevToken string `koanf:"dev_token"`
|
|
|
|
DBPath string `koanf:"db_path"`
|
|
Listen string `koanf:"listen"`
|
|
|
|
// DeviceTTLHours is the maximum age of a row in `devices` before the
|
|
// background sweeper deletes it. Brief §2 sets the refresh_token sliding
|
|
// window at 196h (≈8 days) — devices must not outlive that. Default 196h.
|
|
DeviceTTLHours int `koanf:"device_ttl_hours"`
|
|
|
|
// PublicURL 是部署的公开源(scheme://host),如 https://drop.commilitia.net。
|
|
// 用于拼扫码登录的 QR 链接、作 Web Push 的默认联系标识。dev 留空时回退到请求自身
|
|
// 的 Host。
|
|
PublicURL string `koanf:"public_url"`
|
|
|
|
// Auth Broker 接入(路径 A)。cdrop 把身份与会话生命周期委托给 broker:每个受控
|
|
// 请求在边缘由 broker /verify(经 Caddy)鉴权并注入 X-Auth-* 头,cdrop 直接信任;
|
|
// 扫码批准时经 broker 内部 API 委托签发会话,cdrop 不再自签。
|
|
// BrokerBaseURL —— broker 内网地址(如 http://broker-internal-ip:8080),在 docker
|
|
// 内网直连(绝不经公网反代,以保 /internal/* 与 /refresh 可达)。
|
|
// BrokerInternalKey —— broker /internal/* 端点的共享密钥(作 X-Internal-Key 发送),
|
|
// prod 必填。
|
|
// BrokerApp —— 本应用在 broker apps 注册表里的 key(默认 "cdrop")。
|
|
BrokerBaseURL string `koanf:"broker_base_url"`
|
|
BrokerInternalKey string `koanf:"broker_internal_key"`
|
|
BrokerApp string `koanf:"broker_app"`
|
|
|
|
// BrokerPublicURL is the broker's PUBLIC origin (e.g. https://sso.commilitia.net)
|
|
// — where a browser is sent to log in via global SSO. Distinct from BrokerBaseURL
|
|
// (the internal address cdrop's server-to-server calls use). GET /api/auth/login
|
|
// 302-redirects here; empty disables that redirect (native-only deployments).
|
|
BrokerPublicURL string `koanf:"broker_public_url"`
|
|
|
|
// 按档令牌 TTL(秒):cdrop 经 broker 委托签发会话时请求的 access / refresh 寿命。
|
|
// full=可信设备(access 短、refresh 一周、滑动);guest=扫码借用(同样的短 access、
|
|
// refresh 一天)。两档都在 broker 的 app 上限内(access 3600 / refresh 604800),
|
|
// clampTTL 不会压它们。broker /verify 每请求查活,短 access 只决定续期频率、不影响
|
|
// 吊销即时性。
|
|
FullAccessTTLSeconds int `koanf:"full_access_ttl_seconds"`
|
|
FullRefreshTTLSeconds int `koanf:"full_refresh_ttl_seconds"`
|
|
GuestAccessTTLSeconds int `koanf:"guest_access_ttl_seconds"`
|
|
GuestRefreshTTLSeconds int `koanf:"guest_refresh_ttl_seconds"`
|
|
|
|
// Cloudflare Realtime TURN (https://developers.cloudflare.com/realtime/turn/).
|
|
// When both fields are set, /api/calls/credentials returns short-lived
|
|
// TLS-capable TURN creds (turns:turn.cloudflare.com:5349); otherwise the
|
|
// endpoint serves a STUN-only fallback so dev / no-CF deploys still work.
|
|
CFTurnKeyID string `koanf:"cf_turn_key_id"`
|
|
CFTurnAPIToken string `koanf:"cf_turn_api_token"`
|
|
|
|
// Clipboard:单条覆写式同步。MaxBytes 限制单次写入字节数;DebounceSec 是
|
|
// 收到 PUT 后等待"无新写入稳定窗口"的秒数,到期才广播 SSE。同窗口内的
|
|
// 后续 PUT 直接刷新 generation 让旧广播取消。
|
|
ClipboardMaxBytes int `koanf:"clipboard_max_bytes"`
|
|
ClipboardDebounceSec int `koanf:"clipboard_debounce_sec"`
|
|
// ClipboardTTLSec 是云剪贴板内容的存活秒数。因为无法可靠区分密码与普通
|
|
// 文本(密码.app / 浏览器扩展复制都不打敏感标记),改以短 TTL 限制暴露面:
|
|
// 内容超过 TTL 后 GET 返回空,后台 sweeper 亦清除其 content。0 = 不过期。
|
|
ClipboardTTLSec int `koanf:"clipboard_ttl_sec"`
|
|
|
|
// Web Push (RFC 8291/8292):浏览器 / PWA 在页面关闭时仍能收到系统通知。
|
|
// 公私钥是自签的 VAPID 密钥对(与 Apple/Google 账号无关),用 `just vapid-keygen`
|
|
// 生成一次后固定——更换会使所有既有订阅失效。两者皆设才启用推送,缺一即整体
|
|
// 关闭(订阅端点返回 503,事件回退为「仅在线设备收 SSE」)。Subject 是 VAPID
|
|
// 要求的联系标识(mailto: 或站点 URL);留空时回退为部署站点 URL。
|
|
VAPIDPublicKey string `koanf:"vapid_public_key"`
|
|
VAPIDPrivateKey string `koanf:"vapid_private_key"`
|
|
VAPIDSubject string `koanf:"vapid_subject"`
|
|
|
|
// 扫码登录(QR):新设备出码、已登录设备扫码批准,经 Auth Broker 委托签发会话。
|
|
// QRLoginEnabled 关闭则 /api/auth/qr/* 返回 503。QRRequestTTLSeconds 是一条扫码
|
|
// 请求的存活秒数(默认 120)。批准后铸的会话寿命取上面的按档 TTL(full / guest)。
|
|
QRLoginEnabled bool `koanf:"qr_login_enabled"`
|
|
QRRequestTTLSeconds int `koanf:"qr_request_ttl_seconds"`
|
|
}
|
|
|
|
// QRLoginOn reports whether scan-login is enabled and the broker it delegates
|
|
// minting to is configured. Without BrokerBaseURL cdrop can't mint a session on
|
|
// approval, so QR stays off regardless of the flag.
|
|
func (c *Config) QRLoginOn() bool {
|
|
return c.QRLoginEnabled && c.BrokerBaseURL != ""
|
|
}
|
|
|
|
// BrokerAppOrDefault returns the configured broker app key, defaulting to "cdrop".
|
|
func (c *Config) BrokerAppOrDefault() string {
|
|
if c.BrokerApp != "" {
|
|
return c.BrokerApp
|
|
}
|
|
return "cdrop"
|
|
}
|
|
|
|
// Load reads config from optional ./config.yaml then overrides with CDROP_* env.
|
|
// Validates dev/prod invariants; returns error if invariants are violated.
|
|
func Load() (*Config, error) {
|
|
k := koanf.New(".")
|
|
|
|
k.Set("auth_mode", "prod")
|
|
k.Set("db_path", "./cdrop.db")
|
|
k.Set("listen", ":8080")
|
|
k.Set("device_ttl_hours", 196)
|
|
k.Set("clipboard_max_bytes", 65536)
|
|
k.Set("clipboard_debounce_sec", 3)
|
|
k.Set("qr_login_enabled", true)
|
|
k.Set("qr_request_ttl_seconds", 120)
|
|
k.Set("broker_app", "cdrop")
|
|
k.Set("full_access_ttl_seconds", 900)
|
|
k.Set("full_refresh_ttl_seconds", 604800)
|
|
k.Set("guest_access_ttl_seconds", 900)
|
|
k.Set("guest_refresh_ttl_seconds", 86400)
|
|
|
|
if _, err := os.Stat("config.yaml"); err == nil {
|
|
if err := k.Load(file.Provider("config.yaml"), yaml.Parser()); err != nil {
|
|
return nil, fmt.Errorf("load config.yaml: %w", err)
|
|
}
|
|
}
|
|
|
|
envProvider := env.Provider(".", env.Opt{
|
|
Prefix: envPrefix,
|
|
TransformFunc: func(key, value string) (string, any) {
|
|
return strings.ToLower(strings.TrimPrefix(key, envPrefix)), value
|
|
},
|
|
})
|
|
if err := k.Load(envProvider, nil); err != nil {
|
|
return nil, fmt.Errorf("load env: %w", err)
|
|
}
|
|
|
|
cfg := &Config{}
|
|
if err := k.Unmarshal("", cfg); err != nil {
|
|
return nil, fmt.Errorf("unmarshal config: %w", err)
|
|
}
|
|
|
|
if err := cfg.validate(); err != nil {
|
|
return nil, err
|
|
}
|
|
return cfg, nil
|
|
}
|
|
|
|
func (c *Config) validate() error {
|
|
switch c.AuthMode {
|
|
case "dev":
|
|
if c.DevToken == "" {
|
|
return errors.New("CDROP_AUTH_MODE=dev requires CDROP_DEV_TOKEN; refusing to start")
|
|
}
|
|
case "prod":
|
|
// cdrop delegates identity + session lifecycle to the Auth Broker (path A):
|
|
// without its internal address and shared key, QR-approve can't mint and the
|
|
// service is non-functional. Refuse to boot rather than half-run.
|
|
if c.BrokerBaseURL == "" {
|
|
return errors.New(
|
|
"CDROP_AUTH_MODE=prod requires CDROP_BROKER_BASE_URL " +
|
|
"(the Auth Broker internal address); refusing to start")
|
|
}
|
|
if c.BrokerInternalKey == "" {
|
|
return errors.New(
|
|
"CDROP_AUTH_MODE=prod requires CDROP_BROKER_INTERNAL_KEY " +
|
|
"(shared secret for the broker /internal/* API); refusing to start")
|
|
}
|
|
// PublicURL fixes the deployment origin the CSRF Origin check compares against
|
|
// (deriveSiteOrigin → sameOrigin). Without it sameOrigin fails OPEN, silently
|
|
// disabling the only cdrop-side CSRF guard on the state-changing POST endpoints
|
|
// (device-session mint, logout). Require it in prod so the guard never fails open.
|
|
if c.PublicURL == "" {
|
|
return errors.New(
|
|
"CDROP_AUTH_MODE=prod requires CDROP_PUBLIC_URL " +
|
|
"(the deployment origin, used for the CSRF check); refusing to start")
|
|
}
|
|
default:
|
|
return fmt.Errorf("CDROP_AUTH_MODE must be \"dev\" or \"prod\", got %q", c.AuthMode)
|
|
}
|
|
|
|
// Web Push is optional, but a half-configured pair is always an operator
|
|
// mistake: with only one key set, every push send would fail at runtime
|
|
// while the feature looks "on". Fail fast instead of silently degrading.
|
|
if (c.VAPIDPublicKey == "") != (c.VAPIDPrivateKey == "") {
|
|
return errors.New(
|
|
"CDROP_VAPID_PUBLIC_KEY and CDROP_VAPID_PRIVATE_KEY must be set together " +
|
|
"(run `just vapid-keygen`); set neither to disable Web Push")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// PushEnabled reports whether Web Push is configured (both VAPID keys present).
|
|
func (c *Config) PushEnabled() bool {
|
|
return c.VAPIDPublicKey != "" && c.VAPIDPrivateKey != ""
|
|
}
|
|
|
|
// VAPIDSubjectOrDefault returns the VAPID contact identity. Push services want a
|
|
// way to reach the operator; the configured value wins, else the deployment's
|
|
// own origin (derived from the OIDC redirect URI), else the product URL.
|
|
func (c *Config) VAPIDSubjectOrDefault() string {
|
|
if c.VAPIDSubject != "" {
|
|
return c.VAPIDSubject
|
|
}
|
|
if u, err := url.Parse(c.PublicURL); err == nil && u.Scheme != "" && u.Host != "" {
|
|
return u.Scheme + "://" + u.Host
|
|
}
|
|
return "https://drop.commilitia.net"
|
|
}
|