鉴权并入 Auth Broker:委派设备会话统一模型 + 四端迁移
后端(委托 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 必填校验
This commit is contained in:
@@ -1,76 +0,0 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: accounts.sql
|
||||
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
const getAccount = `-- name: GetAccount :one
|
||||
SELECT user_id, match_key, display_name, avatar_url, roles, provider, created_at, last_login_at
|
||||
FROM accounts
|
||||
WHERE user_id = ?
|
||||
`
|
||||
|
||||
func (q *Queries) GetAccount(ctx context.Context, userID string) (Account, error) {
|
||||
row := q.db.QueryRowContext(ctx, getAccount, userID)
|
||||
var i Account
|
||||
err := row.Scan(
|
||||
&i.UserID,
|
||||
&i.MatchKey,
|
||||
&i.DisplayName,
|
||||
&i.AvatarUrl,
|
||||
&i.Roles,
|
||||
&i.Provider,
|
||||
&i.CreatedAt,
|
||||
&i.LastLoginAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const upsertAccount = `-- name: UpsertAccount :exec
|
||||
|
||||
INSERT INTO accounts (user_id, match_key, display_name, avatar_url, roles, provider, created_at, last_login_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(user_id) DO UPDATE SET
|
||||
match_key = excluded.match_key,
|
||||
display_name = excluded.display_name,
|
||||
avatar_url = excluded.avatar_url,
|
||||
roles = excluded.roles,
|
||||
provider = excluded.provider,
|
||||
last_login_at = excluded.last_login_at
|
||||
`
|
||||
|
||||
type UpsertAccountParams struct {
|
||||
UserID string `json:"user_id"`
|
||||
MatchKey string `json:"match_key"`
|
||||
DisplayName string `json:"display_name"`
|
||||
AvatarUrl string `json:"avatar_url"`
|
||||
Roles string `json:"roles"`
|
||||
Provider string `json:"provider"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
LastLoginAt int64 `json:"last_login_at"`
|
||||
}
|
||||
|
||||
// accounts: cdrop-side thin account data (AUTH.md 2.1). Keyed on user_id (= OIDC
|
||||
// sub). No credentials live here; password / second factor stay at the OAuth
|
||||
// provider. Upserted on every successful OIDC exchange.
|
||||
//
|
||||
// ASCII only: sqlc 1.31.x miscomputes byte offsets on multibyte comments and
|
||||
// corrupts every generated SQL const in the file. Keep this file pure ASCII.
|
||||
func (q *Queries) UpsertAccount(ctx context.Context, arg UpsertAccountParams) error {
|
||||
_, err := q.db.ExecContext(ctx, upsertAccount,
|
||||
arg.UserID,
|
||||
arg.MatchKey,
|
||||
arg.DisplayName,
|
||||
arg.AvatarUrl,
|
||||
arg.Roles,
|
||||
arg.Provider,
|
||||
arg.CreatedAt,
|
||||
arg.LastLoginAt,
|
||||
)
|
||||
return err
|
||||
}
|
||||
+41
-18
@@ -59,24 +59,12 @@ func Bootstrap(ctx context.Context, d *sql.DB) error {
|
||||
"ALTER TABLE clipboard_state ADD COLUMN origin_ts INTEGER NOT NULL DEFAULT 0"); err != nil {
|
||||
return fmt.Errorf("migrate clipboard_state.origin_ts: %w", err)
|
||||
}
|
||||
// web_sessions gained kind/scope/granted_by for cdrop self-signed sessions
|
||||
// (AUTH.md §2.2). Existing rows predate these columns; backfill them so a
|
||||
// pre-existing browser session keeps behaving as a normal IdP-backed login.
|
||||
if err := ensureColumn(ctx, tx, "web_sessions", "kind",
|
||||
"ALTER TABLE web_sessions ADD COLUMN kind TEXT NOT NULL DEFAULT 'oidc'"); err != nil {
|
||||
return fmt.Errorf("migrate web_sessions.kind: %w", err)
|
||||
}
|
||||
if err := ensureColumn(ctx, tx, "web_sessions", "scope",
|
||||
"ALTER TABLE web_sessions ADD COLUMN scope TEXT NOT NULL DEFAULT 'full'"); err != nil {
|
||||
return fmt.Errorf("migrate web_sessions.scope: %w", err)
|
||||
}
|
||||
if err := ensureColumn(ctx, tx, "web_sessions", "granted_by",
|
||||
"ALTER TABLE web_sessions ADD COLUMN granted_by TEXT NOT NULL DEFAULT ''"); err != nil {
|
||||
return fmt.Errorf("migrate web_sessions.granted_by: %w", err)
|
||||
}
|
||||
if err := ensureColumn(ctx, tx, "web_sessions", "stepped_up_at",
|
||||
"ALTER TABLE web_sessions ADD COLUMN stepped_up_at INTEGER NOT NULL DEFAULT 0"); err != nil {
|
||||
return fmt.Errorf("migrate web_sessions.stepped_up_at: %w", err)
|
||||
// devices moved to a stable opaque device_id primary key (Auth Broker path A);
|
||||
// the old table was keyed (user_id, name). Device rows are ephemeral registrations
|
||||
// re-created on the next request / scan, so a legacy table is dropped and recreated
|
||||
// rather than column-migrated (SQLite can't ALTER a primary key in place).
|
||||
if err := recreateDevicesIfLegacy(ctx, tx); err != nil {
|
||||
return fmt.Errorf("migrate devices to device_id: %w", err)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return fmt.Errorf("commit bootstrap: %w", err)
|
||||
@@ -84,6 +72,41 @@ func Bootstrap(ctx context.Context, d *sql.DB) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// recreateDevicesIfLegacy drops and recreates the devices table when it predates the
|
||||
// device_id primary key (the legacy (user_id, name) shape). On a fresh DB the init
|
||||
// schema already created the new shape, so device_id is present and this no-ops. The
|
||||
// dropped rows are ephemeral device registrations, re-created on the next request or
|
||||
// scan-login, so no durable data is lost.
|
||||
func recreateDevicesIfLegacy(ctx context.Context, tx *sql.Tx) error {
|
||||
has, err := columnExists(ctx, tx, "devices", "device_id")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if has {
|
||||
return nil
|
||||
}
|
||||
stmts := []string{
|
||||
"DROP TABLE IF EXISTS devices",
|
||||
`CREATE TABLE devices (
|
||||
device_id TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
type TEXT NOT NULL,
|
||||
tier TEXT NOT NULL DEFAULT 'full',
|
||||
broker_sid TEXT NOT NULL DEFAULT '',
|
||||
created_at INTEGER NOT NULL,
|
||||
last_seen INTEGER NOT NULL
|
||||
)`,
|
||||
"CREATE INDEX IF NOT EXISTS idx_devices_user ON devices (user_id)",
|
||||
}
|
||||
for _, s := range stmts {
|
||||
if _, err := tx.ExecContext(ctx, s); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ensureColumn runs addSQL only when table lacks the named column — an idempotent
|
||||
// additive migration for already-created tables.
|
||||
func ensureColumn(ctx context.Context, tx *sql.Tx, table, column, addSQL string) error {
|
||||
|
||||
@@ -19,7 +19,7 @@ func TestBootstrapCreatesAllTables(t *testing.T) {
|
||||
t.Fatalf("bootstrap: %v", err)
|
||||
}
|
||||
|
||||
want := []string{"accounts", "clipboard_state", "devices", "login_requests", "push_subscriptions", "shortcut_tokens", "transfer_sessions", "web_sessions"}
|
||||
want := []string{"clipboard_state", "devices", "login_requests", "push_subscriptions", "transfer_sessions"}
|
||||
rows, err := d.Query("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name")
|
||||
if err != nil {
|
||||
t.Fatalf("query tables: %v", err)
|
||||
@@ -115,10 +115,11 @@ func TestBootstrapAddsClipboardVersionToLegacyDB(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Simulates the prod upgrade for scan-login: a web_sessions table created before
|
||||
// kind/scope/granted_by existed must gain them, with an existing row defaulting
|
||||
// to a normal OIDC-backed full session so its behaviour is unchanged (AUTH.md §2.2).
|
||||
func TestBootstrapAddsWebSessionColumnsToLegacyDB(t *testing.T) {
|
||||
// Simulates the prod upgrade to the Auth Broker model: a legacy devices table keyed
|
||||
// (user_id, name) must be recreated with the device_id primary key. The ephemeral
|
||||
// device rows are dropped (re-created on the next request / scan), and the migration
|
||||
// is idempotent.
|
||||
func TestBootstrapRecreatesLegacyDevices(t *testing.T) {
|
||||
tmp := filepath.Join(t.TempDir(), "legacy.db")
|
||||
d, err := Open(tmp)
|
||||
if err != nil {
|
||||
@@ -126,15 +127,12 @@ func TestBootstrapAddsWebSessionColumnsToLegacyDB(t *testing.T) {
|
||||
}
|
||||
defer d.Close()
|
||||
|
||||
_, err = d.Exec(`CREATE TABLE web_sessions (
|
||||
id TEXT PRIMARY KEY, user_id TEXT NOT NULL, refresh_token TEXT NOT NULL,
|
||||
device_name TEXT NOT NULL DEFAULT '', user_agent TEXT NOT NULL DEFAULT '',
|
||||
created_at INTEGER NOT NULL, last_used_at INTEGER NOT NULL, expires_at INTEGER NOT NULL)`)
|
||||
if err != nil {
|
||||
if _, err := d.Exec(`CREATE TABLE devices (
|
||||
user_id TEXT NOT NULL, name TEXT NOT NULL, type TEXT NOT NULL,
|
||||
last_seen INTEGER NOT NULL, PRIMARY KEY (user_id, name))`); err != nil {
|
||||
t.Fatalf("legacy schema: %v", err)
|
||||
}
|
||||
if _, err := d.Exec(`INSERT INTO web_sessions (id, user_id, refresh_token, created_at, last_used_at, expires_at)
|
||||
VALUES ('s', 'u', 'enc', 1, 1, 9999999999)`); err != nil {
|
||||
if _, err := d.Exec(`INSERT INTO devices (user_id, name, type, last_seen) VALUES ('u','old','browser',1)`); err != nil {
|
||||
t.Fatalf("seed row: %v", err)
|
||||
}
|
||||
|
||||
@@ -142,17 +140,29 @@ func TestBootstrapAddsWebSessionColumnsToLegacyDB(t *testing.T) {
|
||||
t.Fatalf("bootstrap: %v", err)
|
||||
}
|
||||
|
||||
var kind, scope, grantedBy string
|
||||
if err := d.QueryRow(`SELECT kind, scope, granted_by FROM web_sessions WHERE id='s'`).
|
||||
Scan(&kind, &scope, &grantedBy); err != nil {
|
||||
t.Fatalf("select new columns (missing?): %v", err)
|
||||
// The table now has the device_id-keyed shape (this insert would fail otherwise).
|
||||
if _, err := d.Exec(`INSERT INTO devices (device_id, user_id, name, type, tier, broker_sid, created_at, last_seen)
|
||||
VALUES ('dev_1','u','New','browser','full','sid',1,1)`); err != nil {
|
||||
t.Fatalf("new schema insert (device_id missing?): %v", err)
|
||||
}
|
||||
if kind != "oidc" || scope != "full" || grantedBy != "" {
|
||||
t.Errorf("legacy row defaults: got kind=%q scope=%q granted_by=%q, want oidc/full/empty",
|
||||
kind, scope, grantedBy)
|
||||
// The legacy row was dropped with the table.
|
||||
var legacy int
|
||||
if err := d.QueryRow(`SELECT COUNT(*) FROM devices WHERE name='old'`).Scan(&legacy); err != nil {
|
||||
t.Fatalf("count legacy: %v", err)
|
||||
}
|
||||
// Idempotent: second bootstrap must not error on already-present columns.
|
||||
if legacy != 0 {
|
||||
t.Errorf("legacy device row should be dropped on recreate; got %d", legacy)
|
||||
}
|
||||
|
||||
// Idempotent: a second bootstrap leaves the new shape and its rows intact.
|
||||
if err := Bootstrap(context.Background(), d); err != nil {
|
||||
t.Fatalf("second bootstrap: %v", err)
|
||||
}
|
||||
var kept int
|
||||
if err := d.QueryRow(`SELECT COUNT(*) FROM devices WHERE device_id='dev_1'`).Scan(&kept); err != nil {
|
||||
t.Fatalf("count after second bootstrap: %v", err)
|
||||
}
|
||||
if kept != 1 {
|
||||
t.Errorf("device row should survive idempotent bootstrap; got %d", kept)
|
||||
}
|
||||
}
|
||||
|
||||
+116
-43
@@ -9,41 +9,70 @@ import (
|
||||
"context"
|
||||
)
|
||||
|
||||
const createDevice = `-- name: CreateDevice :exec
|
||||
|
||||
INSERT INTO devices (device_id, user_id, name, type, tier, broker_sid, created_at, last_seen)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT (device_id) DO UPDATE SET
|
||||
name = excluded.name,
|
||||
type = excluded.type,
|
||||
tier = excluded.tier,
|
||||
broker_sid = excluded.broker_sid,
|
||||
last_seen = excluded.last_seen
|
||||
WHERE devices.user_id = excluded.user_id
|
||||
`
|
||||
|
||||
type CreateDeviceParams struct {
|
||||
DeviceID string `json:"device_id"`
|
||||
UserID string `json:"user_id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Tier string `json:"tier"`
|
||||
BrokerSid string `json:"broker_sid"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
LastSeen int64 `json:"last_seen"`
|
||||
}
|
||||
|
||||
// devices: cdrop-managed devices (scan-login / native pairing). device_id is a
|
||||
// stable opaque cdrop-generated id that doubles as the session<->device join key
|
||||
// (passed to the broker as meta, echoed back as X-Auth-Meta on /verify). broker_sid
|
||||
// is the broker's session id, stored privately to revoke on device removal. tier is
|
||||
// a redundant cache of the broker scope (full/guest). name is human-readable and can
|
||||
// change without changing the device's identity (device_id is the key).
|
||||
//
|
||||
// ASCII only: sqlc 1.31.x miscomputes byte offsets on multibyte comments and corrupts
|
||||
// every generated SQL const in the file. Keep this file pure ASCII.
|
||||
// CreateDevice records a device on scan-login collect / proxy-mint (or native pairing). Keyed
|
||||
// on device_id, so a re-pair with the same id refreshes the row (incl. the new broker_sid).
|
||||
// The WHERE on the upsert scopes the update to the owning user so a (cryptographically
|
||||
// impossible) cross-user device_id collision can never reassign the row owner; user_id is
|
||||
// immutable for a given device_id.
|
||||
func (q *Queries) CreateDevice(ctx context.Context, arg CreateDeviceParams) error {
|
||||
_, err := q.db.ExecContext(ctx, createDevice,
|
||||
arg.DeviceID,
|
||||
arg.UserID,
|
||||
arg.Name,
|
||||
arg.Type,
|
||||
arg.Tier,
|
||||
arg.BrokerSid,
|
||||
arg.CreatedAt,
|
||||
arg.LastSeen,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const deleteDevice = `-- name: DeleteDevice :execrows
|
||||
DELETE FROM devices
|
||||
WHERE user_id = ? AND name = ?
|
||||
WHERE device_id = ? AND user_id = ?
|
||||
`
|
||||
|
||||
type DeleteDeviceParams struct {
|
||||
UserID string `json:"user_id"`
|
||||
Name string `json:"name"`
|
||||
DeviceID string `json:"device_id"`
|
||||
UserID string `json:"user_id"`
|
||||
}
|
||||
|
||||
func (q *Queries) DeleteDevice(ctx context.Context, arg DeleteDeviceParams) (int64, error) {
|
||||
result, err := q.db.ExecContext(ctx, deleteDevice, arg.UserID, arg.Name)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected()
|
||||
}
|
||||
|
||||
const deleteOrphanBrowserDevices = `-- name: DeleteOrphanBrowserDevices :execrows
|
||||
DELETE FROM devices
|
||||
WHERE type = 'browser'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM web_sessions ws
|
||||
WHERE ws.user_id = devices.user_id
|
||||
AND ws.device_name = devices.name
|
||||
AND ws.expires_at > ?
|
||||
)
|
||||
`
|
||||
|
||||
// DeleteOrphanBrowserDevices removes browser device rows with no live web_session
|
||||
// (the session was revoked or expired), keeping the device list aligned with the
|
||||
// session list. The ? is the current epoch second. Native (macos/windows/linux/ios)
|
||||
// and shortcut devices are left alone: they legitimately keep no web_session.
|
||||
func (q *Queries) DeleteOrphanBrowserDevices(ctx context.Context, expiresAt int64) (int64, error) {
|
||||
result, err := q.db.ExecContext(ctx, deleteOrphanBrowserDevices, expiresAt)
|
||||
result, err := q.db.ExecContext(ctx, deleteDevice, arg.DeviceID, arg.UserID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@@ -60,8 +89,30 @@ func (q *Queries) DeleteStaleDevices(ctx context.Context, lastSeen int64) error
|
||||
return err
|
||||
}
|
||||
|
||||
const getDevice = `-- name: GetDevice :one
|
||||
SELECT device_id, user_id, name, type, tier, broker_sid, created_at, last_seen
|
||||
FROM devices
|
||||
WHERE device_id = ?
|
||||
`
|
||||
|
||||
func (q *Queries) GetDevice(ctx context.Context, deviceID string) (Device, error) {
|
||||
row := q.db.QueryRowContext(ctx, getDevice, deviceID)
|
||||
var i Device
|
||||
err := row.Scan(
|
||||
&i.DeviceID,
|
||||
&i.UserID,
|
||||
&i.Name,
|
||||
&i.Type,
|
||||
&i.Tier,
|
||||
&i.BrokerSid,
|
||||
&i.CreatedAt,
|
||||
&i.LastSeen,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const listDevicesByUser = `-- name: ListDevicesByUser :many
|
||||
SELECT user_id, name, type, last_seen
|
||||
SELECT device_id, user_id, name, type, tier, broker_sid, created_at, last_seen
|
||||
FROM devices
|
||||
WHERE user_id = ?
|
||||
ORDER BY name
|
||||
@@ -77,9 +128,13 @@ func (q *Queries) ListDevicesByUser(ctx context.Context, userID string) ([]Devic
|
||||
for rows.Next() {
|
||||
var i Device
|
||||
if err := rows.Scan(
|
||||
&i.DeviceID,
|
||||
&i.UserID,
|
||||
&i.Name,
|
||||
&i.Type,
|
||||
&i.Tier,
|
||||
&i.BrokerSid,
|
||||
&i.CreatedAt,
|
||||
&i.LastSeen,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
@@ -95,27 +150,45 @@ func (q *Queries) ListDevicesByUser(ctx context.Context, userID string) ([]Devic
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const upsertDevice = `-- name: UpsertDevice :exec
|
||||
INSERT INTO devices (user_id, name, type, last_seen)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT (user_id, name) DO UPDATE SET
|
||||
type = excluded.type,
|
||||
last_seen = excluded.last_seen
|
||||
const renameDevice = `-- name: RenameDevice :execrows
|
||||
UPDATE devices SET name = ?
|
||||
WHERE device_id = ? AND user_id = ?
|
||||
`
|
||||
|
||||
type UpsertDeviceParams struct {
|
||||
UserID string `json:"user_id"`
|
||||
type RenameDeviceParams struct {
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
LastSeen int64 `json:"last_seen"`
|
||||
DeviceID string `json:"device_id"`
|
||||
UserID string `json:"user_id"`
|
||||
}
|
||||
|
||||
func (q *Queries) UpsertDevice(ctx context.Context, arg UpsertDeviceParams) error {
|
||||
_, err := q.db.ExecContext(ctx, upsertDevice,
|
||||
arg.UserID,
|
||||
arg.Name,
|
||||
arg.Type,
|
||||
func (q *Queries) RenameDevice(ctx context.Context, arg RenameDeviceParams) (int64, error) {
|
||||
result, err := q.db.ExecContext(ctx, renameDevice, arg.Name, arg.DeviceID, arg.UserID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected()
|
||||
}
|
||||
|
||||
const touchDevice = `-- name: TouchDevice :exec
|
||||
UPDATE devices SET last_seen = ?, tier = ? WHERE device_id = ? AND user_id = ?
|
||||
`
|
||||
|
||||
type TouchDeviceParams struct {
|
||||
LastSeen int64 `json:"last_seen"`
|
||||
Tier string `json:"tier"`
|
||||
DeviceID string `json:"device_id"`
|
||||
UserID string `json:"user_id"`
|
||||
}
|
||||
|
||||
// TouchDevice refreshes last_seen + tier on each authenticated request. Update-only:
|
||||
// the row is created at collect time, so a missing row (e.g. a device authorized via
|
||||
// the broker's own device flow, not cdrop's) simply isn't cdrop-managed and no-ops.
|
||||
func (q *Queries) TouchDevice(ctx context.Context, arg TouchDeviceParams) error {
|
||||
_, err := q.db.ExecContext(ctx, touchDevice,
|
||||
arg.LastSeen,
|
||||
arg.Tier,
|
||||
arg.DeviceID,
|
||||
arg.UserID,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -1,24 +1,23 @@
|
||||
-- cdrop MVP schema (PROJECT_BRIEF.md §4)
|
||||
-- 以 IF NOT EXISTS 形式由 internal/db/bootstrap.go 启动期单事务执行。
|
||||
|
||||
-- devices:cdrop 托管设备(扫码批准 / 原生配对的设备)。device_id 是 cdrop 生成的
|
||||
-- 稳定不透明 id,作设备身份与「会话↔设备」的 join key——经 broker mint 时作 meta 传入、
|
||||
-- 由 broker /verify 回显成 X-Auth-Meta。broker_sid 是 broker 返回的会话 id,私存用于
|
||||
-- 吊销(删设备)。tier=full/guest(冗余缓存,权威在 broker scope)。name 是人类可读
|
||||
-- 设备名,可重命名而身份不变(device_id 不变)。
|
||||
CREATE TABLE IF NOT EXISTS devices (
|
||||
user_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
type TEXT NOT NULL,
|
||||
last_seen INTEGER NOT NULL,
|
||||
PRIMARY KEY (user_id, name)
|
||||
device_id TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
type TEXT NOT NULL,
|
||||
tier TEXT NOT NULL DEFAULT 'full',
|
||||
broker_sid TEXT NOT NULL DEFAULT '',
|
||||
created_at INTEGER NOT NULL,
|
||||
last_seen INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS shortcut_tokens (
|
||||
jti TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL,
|
||||
label TEXT NOT NULL,
|
||||
scopes TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
expires_at INTEGER NOT NULL,
|
||||
last_used_at INTEGER,
|
||||
revoked INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_devices_user ON devices (user_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS transfer_sessions (
|
||||
id TEXT PRIMARY KEY,
|
||||
@@ -50,37 +49,6 @@ CREATE TABLE IF NOT EXISTS clipboard_state (
|
||||
origin_ts INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
-- web_sessions:浏览器端「免重登」。cookie 里只放不透明随机串,本表 id 存其
|
||||
-- SHA-256,故 DB 单独泄露也换不出可用 cookie;refresh_token 以 AES-256-GCM 落盘
|
||||
-- (密钥在容器环境、不在库内)。仅浏览器使用——桌面端 refresh_token 由 Go keyring
|
||||
-- 持有、走自有 loopback flow,绝不入此表。device_name 随会话存,使 PWA 存储被清后
|
||||
-- 开机仍能恢复本机设备名。
|
||||
CREATE TABLE IF NOT EXISTS web_sessions (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL,
|
||||
refresh_token TEXT NOT NULL,
|
||||
device_name TEXT NOT NULL DEFAULT '',
|
||||
user_agent TEXT NOT NULL DEFAULT '',
|
||||
created_at INTEGER NOT NULL,
|
||||
last_used_at INTEGER NOT NULL,
|
||||
expires_at INTEGER NOT NULL,
|
||||
-- kind 区分会话来源(AUTH.md §2.2):oidc=绑定 IdP refresh_token 的正常浏览器
|
||||
-- 登录(refresh 时向 IdP 续);self/guest=cdrop 自签会话,无 IdP refresh_token,
|
||||
-- refresh 时仅按本行自签 access token、不触 IdP。既有行经 bootstrap 的幂等 ALTER
|
||||
-- 补列后默认视为 oidc/full,行为不变。
|
||||
kind TEXT NOT NULL DEFAULT 'oidc',
|
||||
-- scope=full/guest。guest(扫码受限借用设备)服务端强制受限:能收发文件,
|
||||
-- 但不能改账号、不能再批准别的设备、不能签发长效 token(路由层 requireFullSession 守门)。
|
||||
scope TEXT NOT NULL DEFAULT 'full',
|
||||
-- granted_by=扫码批准者的 session id,供审计与「吊销我批准过的借用设备」连带吊销。
|
||||
granted_by TEXT NOT NULL DEFAULT '',
|
||||
-- stepped_up_at=本会话最近一次通过 step-up 再认证的 Unix 秒(AUTH.md §6)。在
|
||||
-- StepUpMaxAgeSeconds 窗口内,敏感动作不再重复要求再认证(避免每次都弹再登录)。
|
||||
stepped_up_at INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_web_sessions_expires ON web_sessions (expires_at);
|
||||
|
||||
-- push_subscriptions:浏览器 / PWA 的 Web Push 订阅端点。当某设备「页面已关闭」
|
||||
-- (无活的 SSE 连接)时,服务端按此表向其推送系统通知;页面开着时事件仍走 SSE,
|
||||
-- 前端自弹 toast,不触发 push。id 是 SHA-256(endpoint) 的 hex,使同一浏览器重复
|
||||
@@ -105,24 +73,6 @@ CREATE TABLE IF NOT EXISTS push_subscriptions (
|
||||
CREATE INDEX IF NOT EXISTS idx_push_subscriptions_user_device
|
||||
ON push_subscriptions (user_id, device_name);
|
||||
|
||||
-- accounts:cdrop 侧「薄账户数据层」(AUTH.md §2.1)。身份来源仍是 OAuth provider,
|
||||
-- user_id 继续等于 OIDC sub;本表只存 cdrop 自维护的账户元数据,不含任何凭证(密码 /
|
||||
-- 第二因子全在 provider)。OIDC exchange 成功后 upsert:捕获 match_key(默认 email
|
||||
-- claim,仅在管理员开启「迁移标记」时用作跨源关联的 join key)、显示名 / 头像、roles
|
||||
-- (groups claim 缓存,admin 判定用)。
|
||||
CREATE TABLE IF NOT EXISTS accounts (
|
||||
user_id TEXT PRIMARY KEY,
|
||||
match_key TEXT NOT NULL DEFAULT '',
|
||||
display_name TEXT NOT NULL DEFAULT '',
|
||||
avatar_url TEXT NOT NULL DEFAULT '',
|
||||
roles TEXT NOT NULL DEFAULT '',
|
||||
provider TEXT NOT NULL DEFAULT '',
|
||||
created_at INTEGER NOT NULL,
|
||||
last_login_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_accounts_match_key ON accounts (match_key);
|
||||
|
||||
-- login_requests:扫码登录的待批准请求(AUTH.md §2.3、§4)。三方密钥分离——
|
||||
-- poll_secret 存其 SHA-256(新设备私有、QR 不含、领取会话凭它);approval_code 随 QR
|
||||
-- 给批准方。短 TTL(默认 120s),consumed/expired 后不可复用,由 reaper 清理。
|
||||
|
||||
+8
-41
@@ -4,17 +4,6 @@
|
||||
|
||||
package db
|
||||
|
||||
type Account struct {
|
||||
UserID string `json:"user_id"`
|
||||
MatchKey string `json:"match_key"`
|
||||
DisplayName string `json:"display_name"`
|
||||
AvatarUrl string `json:"avatar_url"`
|
||||
Roles string `json:"roles"`
|
||||
Provider string `json:"provider"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
LastLoginAt int64 `json:"last_login_at"`
|
||||
}
|
||||
|
||||
type ClipboardState struct {
|
||||
UserID string `json:"user_id"`
|
||||
ContentType string `json:"content_type"`
|
||||
@@ -26,10 +15,14 @@ type ClipboardState struct {
|
||||
}
|
||||
|
||||
type Device struct {
|
||||
UserID string `json:"user_id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
LastSeen int64 `json:"last_seen"`
|
||||
DeviceID string `json:"device_id"`
|
||||
UserID string `json:"user_id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Tier string `json:"tier"`
|
||||
BrokerSid string `json:"broker_sid"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
LastSeen int64 `json:"last_seen"`
|
||||
}
|
||||
|
||||
type LoginRequest struct {
|
||||
@@ -62,17 +55,6 @@ type PushSubscription struct {
|
||||
LastUsedAt int64 `json:"last_used_at"`
|
||||
}
|
||||
|
||||
type ShortcutToken struct {
|
||||
Jti string `json:"jti"`
|
||||
UserID string `json:"user_id"`
|
||||
Label string `json:"label"`
|
||||
Scopes string `json:"scopes"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
ExpiresAt int64 `json:"expires_at"`
|
||||
LastUsedAt *int64 `json:"last_used_at"`
|
||||
Revoked int64 `json:"revoked"`
|
||||
}
|
||||
|
||||
type TransferSession struct {
|
||||
ID string `json:"id"`
|
||||
UserID string `json:"user_id"`
|
||||
@@ -88,18 +70,3 @@ type TransferSession struct {
|
||||
FinishedAt *int64 `json:"finished_at"`
|
||||
FailReason *string `json:"fail_reason"`
|
||||
}
|
||||
|
||||
type WebSession struct {
|
||||
ID string `json:"id"`
|
||||
UserID string `json:"user_id"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
DeviceName string `json:"device_name"`
|
||||
UserAgent string `json:"user_agent"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
LastUsedAt int64 `json:"last_used_at"`
|
||||
ExpiresAt int64 `json:"expires_at"`
|
||||
Kind string `json:"kind"`
|
||||
Scope string `json:"scope"`
|
||||
GrantedBy string `json:"granted_by"`
|
||||
SteppedUpAt int64 `json:"stepped_up_at"`
|
||||
}
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
-- accounts: cdrop-side thin account data (AUTH.md 2.1). Keyed on user_id (= OIDC
|
||||
-- sub). No credentials live here; password / second factor stay at the OAuth
|
||||
-- provider. Upserted on every successful OIDC exchange.
|
||||
--
|
||||
-- ASCII only: sqlc 1.31.x miscomputes byte offsets on multibyte comments and
|
||||
-- corrupts every generated SQL const in the file. Keep this file pure ASCII.
|
||||
|
||||
-- name: UpsertAccount :exec
|
||||
INSERT INTO accounts (user_id, match_key, display_name, avatar_url, roles, provider, created_at, last_login_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(user_id) DO UPDATE SET
|
||||
match_key = excluded.match_key,
|
||||
display_name = excluded.display_name,
|
||||
avatar_url = excluded.avatar_url,
|
||||
roles = excluded.roles,
|
||||
provider = excluded.provider,
|
||||
last_login_at = excluded.last_login_at;
|
||||
|
||||
-- name: GetAccount :one
|
||||
SELECT user_id, match_key, display_name, avatar_url, roles, provider, created_at, last_login_at
|
||||
FROM accounts
|
||||
WHERE user_id = ?;
|
||||
@@ -1,34 +1,54 @@
|
||||
-- name: UpsertDevice :exec
|
||||
INSERT INTO devices (user_id, name, type, last_seen)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT (user_id, name) DO UPDATE SET
|
||||
-- devices: cdrop-managed devices (scan-login / native pairing). device_id is a
|
||||
-- stable opaque cdrop-generated id that doubles as the session<->device join key
|
||||
-- (passed to the broker as meta, echoed back as X-Auth-Meta on /verify). broker_sid
|
||||
-- is the broker's session id, stored privately to revoke on device removal. tier is
|
||||
-- a redundant cache of the broker scope (full/guest). name is human-readable and can
|
||||
-- change without changing the device's identity (device_id is the key).
|
||||
--
|
||||
-- ASCII only: sqlc 1.31.x miscomputes byte offsets on multibyte comments and corrupts
|
||||
-- every generated SQL const in the file. Keep this file pure ASCII.
|
||||
|
||||
-- CreateDevice records a device on scan-login collect / proxy-mint (or native pairing). Keyed
|
||||
-- on device_id, so a re-pair with the same id refreshes the row (incl. the new broker_sid).
|
||||
-- The WHERE on the upsert scopes the update to the owning user so a (cryptographically
|
||||
-- impossible) cross-user device_id collision can never reassign the row owner; user_id is
|
||||
-- immutable for a given device_id.
|
||||
-- name: CreateDevice :exec
|
||||
INSERT INTO devices (device_id, user_id, name, type, tier, broker_sid, created_at, last_seen)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT (device_id) DO UPDATE SET
|
||||
name = excluded.name,
|
||||
type = excluded.type,
|
||||
last_seen = excluded.last_seen;
|
||||
tier = excluded.tier,
|
||||
broker_sid = excluded.broker_sid,
|
||||
last_seen = excluded.last_seen
|
||||
WHERE devices.user_id = excluded.user_id;
|
||||
|
||||
-- TouchDevice refreshes last_seen + tier on each authenticated request. Update-only:
|
||||
-- the row is created at collect time, so a missing row (e.g. a device authorized via
|
||||
-- the broker's own device flow, not cdrop's) simply isn't cdrop-managed and no-ops.
|
||||
-- name: TouchDevice :exec
|
||||
UPDATE devices SET last_seen = ?, tier = ? WHERE device_id = ? AND user_id = ?;
|
||||
|
||||
-- name: ListDevicesByUser :many
|
||||
SELECT user_id, name, type, last_seen
|
||||
SELECT device_id, user_id, name, type, tier, broker_sid, created_at, last_seen
|
||||
FROM devices
|
||||
WHERE user_id = ?
|
||||
ORDER BY name;
|
||||
|
||||
-- name: DeleteStaleDevices :exec
|
||||
DELETE FROM devices
|
||||
WHERE last_seen < ?;
|
||||
|
||||
-- DeleteOrphanBrowserDevices removes browser device rows with no live web_session
|
||||
-- (the session was revoked or expired), keeping the device list aligned with the
|
||||
-- session list. The ? is the current epoch second. Native (macos/windows/linux/ios)
|
||||
-- and shortcut devices are left alone: they legitimately keep no web_session.
|
||||
-- name: DeleteOrphanBrowserDevices :execrows
|
||||
DELETE FROM devices
|
||||
WHERE type = 'browser'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM web_sessions ws
|
||||
WHERE ws.user_id = devices.user_id
|
||||
AND ws.device_name = devices.name
|
||||
AND ws.expires_at > ?
|
||||
);
|
||||
-- name: GetDevice :one
|
||||
SELECT device_id, user_id, name, type, tier, broker_sid, created_at, last_seen
|
||||
FROM devices
|
||||
WHERE device_id = ?;
|
||||
|
||||
-- name: DeleteDevice :execrows
|
||||
DELETE FROM devices
|
||||
WHERE user_id = ? AND name = ?;
|
||||
WHERE device_id = ? AND user_id = ?;
|
||||
|
||||
-- name: RenameDevice :execrows
|
||||
UPDATE devices SET name = ?
|
||||
WHERE device_id = ? AND user_id = ?;
|
||||
|
||||
-- name: DeleteStaleDevices :exec
|
||||
DELETE FROM devices
|
||||
WHERE last_seen < ?;
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
-- shortcut_tokens: long-lived, scope-limited, revocable HS256 tokens for the
|
||||
-- iOS Shortcut clipboard sync. Count backs the per-user cap; Revoke is scoped by
|
||||
-- user_id to block cross-user revocation; Touch records last use asynchronously.
|
||||
|
||||
-- name: InsertShortcutToken :exec
|
||||
INSERT INTO shortcut_tokens (jti, user_id, label, scopes, created_at, expires_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?);
|
||||
|
||||
-- name: GetShortcutToken :one
|
||||
SELECT jti, user_id, label, scopes, created_at, expires_at, last_used_at, revoked
|
||||
FROM shortcut_tokens
|
||||
WHERE jti = ?;
|
||||
|
||||
-- name: ListShortcutTokensByUser :many
|
||||
SELECT jti, user_id, label, scopes, created_at, expires_at, last_used_at, revoked
|
||||
FROM shortcut_tokens
|
||||
WHERE user_id = ?
|
||||
ORDER BY created_at DESC;
|
||||
|
||||
-- name: CountActiveShortcutTokensByUser :one
|
||||
SELECT COUNT(*) FROM shortcut_tokens
|
||||
WHERE user_id = ? AND revoked = 0 AND expires_at > ?;
|
||||
|
||||
-- name: RevokeShortcutToken :execrows
|
||||
UPDATE shortcut_tokens
|
||||
SET revoked = 1
|
||||
WHERE jti = ? AND user_id = ?;
|
||||
|
||||
-- name: TouchShortcutTokenUsed :exec
|
||||
UPDATE shortcut_tokens
|
||||
SET last_used_at = ?
|
||||
WHERE jti = ?;
|
||||
@@ -1,69 +0,0 @@
|
||||
-- web_sessions: browser "passwordless re-login". The opaque cookie token is
|
||||
-- never stored; id holds its SHA-256, so a DB leak yields no usable cookie.
|
||||
-- refresh_token is AES-256-GCM ciphertext (key lives in the container env, not
|
||||
-- the DB). 7-day sliding window: every refresh rotates the token and pushes
|
||||
-- expires_at forward; idle sessions are reaped by DeleteExpiredWebSessions.
|
||||
|
||||
-- name: CreateWebSession :exec
|
||||
INSERT INTO web_sessions (id, user_id, refresh_token, device_name, user_agent, created_at, last_used_at, expires_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?);
|
||||
|
||||
-- name: GetWebSession :one
|
||||
SELECT id, user_id, refresh_token, device_name, user_agent, created_at, last_used_at, expires_at, kind, scope, granted_by, stepped_up_at
|
||||
FROM web_sessions
|
||||
WHERE id = ?;
|
||||
|
||||
-- SetSessionSteppedUp stamps the moment this session last passed step-up re-auth;
|
||||
-- sensitive actions within the freshness window then skip re-auth (AUTH.md 6).
|
||||
-- name: SetSessionSteppedUp :exec
|
||||
UPDATE web_sessions
|
||||
SET stepped_up_at = ?
|
||||
WHERE id = ?;
|
||||
|
||||
-- name: RotateWebSession :exec
|
||||
UPDATE web_sessions
|
||||
SET refresh_token = ?, last_used_at = ?, expires_at = ?
|
||||
WHERE id = ?;
|
||||
|
||||
-- name: SetWebSessionDevice :exec
|
||||
UPDATE web_sessions
|
||||
SET device_name = ?
|
||||
WHERE id = ?;
|
||||
|
||||
-- name: DeleteWebSession :exec
|
||||
DELETE FROM web_sessions
|
||||
WHERE id = ?;
|
||||
|
||||
-- name: DeleteExpiredWebSessions :execrows
|
||||
DELETE FROM web_sessions
|
||||
WHERE expires_at < ?;
|
||||
|
||||
-- CreateSelfSession inserts a cdrop self-signed session (kind self/guest) that has
|
||||
-- no IdP refresh_token (stored empty): refresh mints a fresh access token straight
|
||||
-- from this row without touching the IdP. Used by QR scan-login (AUTH.md 4).
|
||||
-- name: CreateSelfSession :exec
|
||||
INSERT INTO web_sessions (id, user_id, refresh_token, device_name, user_agent, kind, scope, granted_by, created_at, last_used_at, expires_at)
|
||||
VALUES (?, ?, '', ?, ?, ?, ?, ?, ?, ?, ?);
|
||||
|
||||
-- SlideWebSession pushes a session's sliding window forward without rotating any
|
||||
-- token. Self/guest sessions use it on refresh (they have no refresh_token to
|
||||
-- rotate); oidc sessions keep using RotateWebSession.
|
||||
-- name: SlideWebSession :exec
|
||||
UPDATE web_sessions
|
||||
SET last_used_at = ?, expires_at = ?
|
||||
WHERE id = ?;
|
||||
|
||||
-- ListWebSessionsByUser lists a user's sessions for the management UI (revoke
|
||||
-- borrowed / guest devices). granted_by ties a scan-approved session to its
|
||||
-- approver for cascade revocation.
|
||||
-- name: ListWebSessionsByUser :many
|
||||
SELECT id, user_id, device_name, user_agent, created_at, last_used_at, expires_at, kind, scope, granted_by
|
||||
FROM web_sessions
|
||||
WHERE user_id = ?
|
||||
ORDER BY last_used_at DESC;
|
||||
|
||||
-- DeleteWebSessionForUser drops one session scoped to its owner, so a user can
|
||||
-- only revoke their own.
|
||||
-- name: DeleteWebSessionForUser :execrows
|
||||
DELETE FROM web_sessions
|
||||
WHERE id = ? AND user_id = ?;
|
||||
@@ -1,153 +0,0 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: shortcut_tokens.sql
|
||||
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
const countActiveShortcutTokensByUser = `-- name: CountActiveShortcutTokensByUser :one
|
||||
SELECT COUNT(*) FROM shortcut_tokens
|
||||
WHERE user_id = ? AND revoked = 0 AND expires_at > ?
|
||||
`
|
||||
|
||||
type CountActiveShortcutTokensByUserParams struct {
|
||||
UserID string `json:"user_id"`
|
||||
ExpiresAt int64 `json:"expires_at"`
|
||||
}
|
||||
|
||||
func (q *Queries) CountActiveShortcutTokensByUser(ctx context.Context, arg CountActiveShortcutTokensByUserParams) (int64, error) {
|
||||
row := q.db.QueryRowContext(ctx, countActiveShortcutTokensByUser, arg.UserID, arg.ExpiresAt)
|
||||
var count int64
|
||||
err := row.Scan(&count)
|
||||
return count, err
|
||||
}
|
||||
|
||||
const getShortcutToken = `-- name: GetShortcutToken :one
|
||||
SELECT jti, user_id, label, scopes, created_at, expires_at, last_used_at, revoked
|
||||
FROM shortcut_tokens
|
||||
WHERE jti = ?
|
||||
`
|
||||
|
||||
func (q *Queries) GetShortcutToken(ctx context.Context, jti string) (ShortcutToken, error) {
|
||||
row := q.db.QueryRowContext(ctx, getShortcutToken, jti)
|
||||
var i ShortcutToken
|
||||
err := row.Scan(
|
||||
&i.Jti,
|
||||
&i.UserID,
|
||||
&i.Label,
|
||||
&i.Scopes,
|
||||
&i.CreatedAt,
|
||||
&i.ExpiresAt,
|
||||
&i.LastUsedAt,
|
||||
&i.Revoked,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertShortcutToken = `-- name: InsertShortcutToken :exec
|
||||
|
||||
INSERT INTO shortcut_tokens (jti, user_id, label, scopes, created_at, expires_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
`
|
||||
|
||||
type InsertShortcutTokenParams struct {
|
||||
Jti string `json:"jti"`
|
||||
UserID string `json:"user_id"`
|
||||
Label string `json:"label"`
|
||||
Scopes string `json:"scopes"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
ExpiresAt int64 `json:"expires_at"`
|
||||
}
|
||||
|
||||
// shortcut_tokens: long-lived, scope-limited, revocable HS256 tokens for the
|
||||
// iOS Shortcut clipboard sync. Count backs the per-user cap; Revoke is scoped by
|
||||
// user_id to block cross-user revocation; Touch records last use asynchronously.
|
||||
func (q *Queries) InsertShortcutToken(ctx context.Context, arg InsertShortcutTokenParams) error {
|
||||
_, err := q.db.ExecContext(ctx, insertShortcutToken,
|
||||
arg.Jti,
|
||||
arg.UserID,
|
||||
arg.Label,
|
||||
arg.Scopes,
|
||||
arg.CreatedAt,
|
||||
arg.ExpiresAt,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const listShortcutTokensByUser = `-- name: ListShortcutTokensByUser :many
|
||||
SELECT jti, user_id, label, scopes, created_at, expires_at, last_used_at, revoked
|
||||
FROM shortcut_tokens
|
||||
WHERE user_id = ?
|
||||
ORDER BY created_at DESC
|
||||
`
|
||||
|
||||
func (q *Queries) ListShortcutTokensByUser(ctx context.Context, userID string) ([]ShortcutToken, error) {
|
||||
rows, err := q.db.QueryContext(ctx, listShortcutTokensByUser, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ShortcutToken
|
||||
for rows.Next() {
|
||||
var i ShortcutToken
|
||||
if err := rows.Scan(
|
||||
&i.Jti,
|
||||
&i.UserID,
|
||||
&i.Label,
|
||||
&i.Scopes,
|
||||
&i.CreatedAt,
|
||||
&i.ExpiresAt,
|
||||
&i.LastUsedAt,
|
||||
&i.Revoked,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const revokeShortcutToken = `-- name: RevokeShortcutToken :execrows
|
||||
UPDATE shortcut_tokens
|
||||
SET revoked = 1
|
||||
WHERE jti = ? AND user_id = ?
|
||||
`
|
||||
|
||||
type RevokeShortcutTokenParams struct {
|
||||
Jti string `json:"jti"`
|
||||
UserID string `json:"user_id"`
|
||||
}
|
||||
|
||||
func (q *Queries) RevokeShortcutToken(ctx context.Context, arg RevokeShortcutTokenParams) (int64, error) {
|
||||
result, err := q.db.ExecContext(ctx, revokeShortcutToken, arg.Jti, arg.UserID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected()
|
||||
}
|
||||
|
||||
const touchShortcutTokenUsed = `-- name: TouchShortcutTokenUsed :exec
|
||||
UPDATE shortcut_tokens
|
||||
SET last_used_at = ?
|
||||
WHERE jti = ?
|
||||
`
|
||||
|
||||
type TouchShortcutTokenUsedParams struct {
|
||||
LastUsedAt *int64 `json:"last_used_at"`
|
||||
Jti string `json:"jti"`
|
||||
}
|
||||
|
||||
func (q *Queries) TouchShortcutTokenUsed(ctx context.Context, arg TouchShortcutTokenUsedParams) error {
|
||||
_, err := q.db.ExecContext(ctx, touchShortcutTokenUsed, arg.LastUsedAt, arg.Jti)
|
||||
return err
|
||||
}
|
||||
@@ -1,286 +0,0 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: web_sessions.sql
|
||||
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
const createSelfSession = `-- name: CreateSelfSession :exec
|
||||
INSERT INTO web_sessions (id, user_id, refresh_token, device_name, user_agent, kind, scope, granted_by, created_at, last_used_at, expires_at)
|
||||
VALUES (?, ?, '', ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`
|
||||
|
||||
type CreateSelfSessionParams struct {
|
||||
ID string `json:"id"`
|
||||
UserID string `json:"user_id"`
|
||||
DeviceName string `json:"device_name"`
|
||||
UserAgent string `json:"user_agent"`
|
||||
Kind string `json:"kind"`
|
||||
Scope string `json:"scope"`
|
||||
GrantedBy string `json:"granted_by"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
LastUsedAt int64 `json:"last_used_at"`
|
||||
ExpiresAt int64 `json:"expires_at"`
|
||||
}
|
||||
|
||||
// CreateSelfSession inserts a cdrop self-signed session (kind self/guest) that has
|
||||
// no IdP refresh_token (stored empty): refresh mints a fresh access token straight
|
||||
// from this row without touching the IdP. Used by QR scan-login (AUTH.md 4).
|
||||
func (q *Queries) CreateSelfSession(ctx context.Context, arg CreateSelfSessionParams) error {
|
||||
_, err := q.db.ExecContext(ctx, createSelfSession,
|
||||
arg.ID,
|
||||
arg.UserID,
|
||||
arg.DeviceName,
|
||||
arg.UserAgent,
|
||||
arg.Kind,
|
||||
arg.Scope,
|
||||
arg.GrantedBy,
|
||||
arg.CreatedAt,
|
||||
arg.LastUsedAt,
|
||||
arg.ExpiresAt,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const createWebSession = `-- name: CreateWebSession :exec
|
||||
|
||||
INSERT INTO web_sessions (id, user_id, refresh_token, device_name, user_agent, created_at, last_used_at, expires_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`
|
||||
|
||||
type CreateWebSessionParams struct {
|
||||
ID string `json:"id"`
|
||||
UserID string `json:"user_id"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
DeviceName string `json:"device_name"`
|
||||
UserAgent string `json:"user_agent"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
LastUsedAt int64 `json:"last_used_at"`
|
||||
ExpiresAt int64 `json:"expires_at"`
|
||||
}
|
||||
|
||||
// web_sessions: browser "passwordless re-login". The opaque cookie token is
|
||||
// never stored; id holds its SHA-256, so a DB leak yields no usable cookie.
|
||||
// refresh_token is AES-256-GCM ciphertext (key lives in the container env, not
|
||||
// the DB). 7-day sliding window: every refresh rotates the token and pushes
|
||||
// expires_at forward; idle sessions are reaped by DeleteExpiredWebSessions.
|
||||
func (q *Queries) CreateWebSession(ctx context.Context, arg CreateWebSessionParams) error {
|
||||
_, err := q.db.ExecContext(ctx, createWebSession,
|
||||
arg.ID,
|
||||
arg.UserID,
|
||||
arg.RefreshToken,
|
||||
arg.DeviceName,
|
||||
arg.UserAgent,
|
||||
arg.CreatedAt,
|
||||
arg.LastUsedAt,
|
||||
arg.ExpiresAt,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const deleteExpiredWebSessions = `-- name: DeleteExpiredWebSessions :execrows
|
||||
DELETE FROM web_sessions
|
||||
WHERE expires_at < ?
|
||||
`
|
||||
|
||||
func (q *Queries) DeleteExpiredWebSessions(ctx context.Context, expiresAt int64) (int64, error) {
|
||||
result, err := q.db.ExecContext(ctx, deleteExpiredWebSessions, expiresAt)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected()
|
||||
}
|
||||
|
||||
const deleteWebSession = `-- name: DeleteWebSession :exec
|
||||
DELETE FROM web_sessions
|
||||
WHERE id = ?
|
||||
`
|
||||
|
||||
func (q *Queries) DeleteWebSession(ctx context.Context, id string) error {
|
||||
_, err := q.db.ExecContext(ctx, deleteWebSession, id)
|
||||
return err
|
||||
}
|
||||
|
||||
const deleteWebSessionForUser = `-- name: DeleteWebSessionForUser :execrows
|
||||
DELETE FROM web_sessions
|
||||
WHERE id = ? AND user_id = ?
|
||||
`
|
||||
|
||||
type DeleteWebSessionForUserParams struct {
|
||||
ID string `json:"id"`
|
||||
UserID string `json:"user_id"`
|
||||
}
|
||||
|
||||
// DeleteWebSessionForUser drops one session scoped to its owner, so a user can
|
||||
// only revoke their own.
|
||||
func (q *Queries) DeleteWebSessionForUser(ctx context.Context, arg DeleteWebSessionForUserParams) (int64, error) {
|
||||
result, err := q.db.ExecContext(ctx, deleteWebSessionForUser, arg.ID, arg.UserID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected()
|
||||
}
|
||||
|
||||
const getWebSession = `-- name: GetWebSession :one
|
||||
SELECT id, user_id, refresh_token, device_name, user_agent, created_at, last_used_at, expires_at, kind, scope, granted_by, stepped_up_at
|
||||
FROM web_sessions
|
||||
WHERE id = ?
|
||||
`
|
||||
|
||||
func (q *Queries) GetWebSession(ctx context.Context, id string) (WebSession, error) {
|
||||
row := q.db.QueryRowContext(ctx, getWebSession, id)
|
||||
var i WebSession
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.UserID,
|
||||
&i.RefreshToken,
|
||||
&i.DeviceName,
|
||||
&i.UserAgent,
|
||||
&i.CreatedAt,
|
||||
&i.LastUsedAt,
|
||||
&i.ExpiresAt,
|
||||
&i.Kind,
|
||||
&i.Scope,
|
||||
&i.GrantedBy,
|
||||
&i.SteppedUpAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const listWebSessionsByUser = `-- name: ListWebSessionsByUser :many
|
||||
SELECT id, user_id, device_name, user_agent, created_at, last_used_at, expires_at, kind, scope, granted_by
|
||||
FROM web_sessions
|
||||
WHERE user_id = ?
|
||||
ORDER BY last_used_at DESC
|
||||
`
|
||||
|
||||
type ListWebSessionsByUserRow struct {
|
||||
ID string `json:"id"`
|
||||
UserID string `json:"user_id"`
|
||||
DeviceName string `json:"device_name"`
|
||||
UserAgent string `json:"user_agent"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
LastUsedAt int64 `json:"last_used_at"`
|
||||
ExpiresAt int64 `json:"expires_at"`
|
||||
Kind string `json:"kind"`
|
||||
Scope string `json:"scope"`
|
||||
GrantedBy string `json:"granted_by"`
|
||||
}
|
||||
|
||||
// ListWebSessionsByUser lists a user's sessions for the management UI (revoke
|
||||
// borrowed / guest devices). granted_by ties a scan-approved session to its
|
||||
// approver for cascade revocation.
|
||||
func (q *Queries) ListWebSessionsByUser(ctx context.Context, userID string) ([]ListWebSessionsByUserRow, error) {
|
||||
rows, err := q.db.QueryContext(ctx, listWebSessionsByUser, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListWebSessionsByUserRow
|
||||
for rows.Next() {
|
||||
var i ListWebSessionsByUserRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.UserID,
|
||||
&i.DeviceName,
|
||||
&i.UserAgent,
|
||||
&i.CreatedAt,
|
||||
&i.LastUsedAt,
|
||||
&i.ExpiresAt,
|
||||
&i.Kind,
|
||||
&i.Scope,
|
||||
&i.GrantedBy,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const rotateWebSession = `-- name: RotateWebSession :exec
|
||||
UPDATE web_sessions
|
||||
SET refresh_token = ?, last_used_at = ?, expires_at = ?
|
||||
WHERE id = ?
|
||||
`
|
||||
|
||||
type RotateWebSessionParams struct {
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
LastUsedAt int64 `json:"last_used_at"`
|
||||
ExpiresAt int64 `json:"expires_at"`
|
||||
ID string `json:"id"`
|
||||
}
|
||||
|
||||
func (q *Queries) RotateWebSession(ctx context.Context, arg RotateWebSessionParams) error {
|
||||
_, err := q.db.ExecContext(ctx, rotateWebSession,
|
||||
arg.RefreshToken,
|
||||
arg.LastUsedAt,
|
||||
arg.ExpiresAt,
|
||||
arg.ID,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const setSessionSteppedUp = `-- name: SetSessionSteppedUp :exec
|
||||
UPDATE web_sessions
|
||||
SET stepped_up_at = ?
|
||||
WHERE id = ?
|
||||
`
|
||||
|
||||
type SetSessionSteppedUpParams struct {
|
||||
SteppedUpAt int64 `json:"stepped_up_at"`
|
||||
ID string `json:"id"`
|
||||
}
|
||||
|
||||
// SetSessionSteppedUp stamps the moment this session last passed step-up re-auth;
|
||||
// sensitive actions within the freshness window then skip re-auth (AUTH.md 6).
|
||||
func (q *Queries) SetSessionSteppedUp(ctx context.Context, arg SetSessionSteppedUpParams) error {
|
||||
_, err := q.db.ExecContext(ctx, setSessionSteppedUp, arg.SteppedUpAt, arg.ID)
|
||||
return err
|
||||
}
|
||||
|
||||
const setWebSessionDevice = `-- name: SetWebSessionDevice :exec
|
||||
UPDATE web_sessions
|
||||
SET device_name = ?
|
||||
WHERE id = ?
|
||||
`
|
||||
|
||||
type SetWebSessionDeviceParams struct {
|
||||
DeviceName string `json:"device_name"`
|
||||
ID string `json:"id"`
|
||||
}
|
||||
|
||||
func (q *Queries) SetWebSessionDevice(ctx context.Context, arg SetWebSessionDeviceParams) error {
|
||||
_, err := q.db.ExecContext(ctx, setWebSessionDevice, arg.DeviceName, arg.ID)
|
||||
return err
|
||||
}
|
||||
|
||||
const slideWebSession = `-- name: SlideWebSession :exec
|
||||
UPDATE web_sessions
|
||||
SET last_used_at = ?, expires_at = ?
|
||||
WHERE id = ?
|
||||
`
|
||||
|
||||
type SlideWebSessionParams struct {
|
||||
LastUsedAt int64 `json:"last_used_at"`
|
||||
ExpiresAt int64 `json:"expires_at"`
|
||||
ID string `json:"id"`
|
||||
}
|
||||
|
||||
// SlideWebSession pushes a session's sliding window forward without rotating any
|
||||
// token. Self/guest sessions use it on refresh (they have no refresh_token to
|
||||
// rotate); oidc sessions keep using RotateWebSession.
|
||||
func (q *Queries) SlideWebSession(ctx context.Context, arg SlideWebSessionParams) error {
|
||||
_, err := q.db.ExecContext(ctx, slideWebSession, arg.LastUsedAt, arg.ExpiresAt, arg.ID)
|
||||
return err
|
||||
}
|
||||
Reference in New Issue
Block a user