Compare commits

...

2 Commits

Author SHA1 Message Date
b7a84d31ea fix: complete audit security and frontend gaps 2026-07-18 18:02:29 +08:00
79feb20688 fix: address project audit gaps 2026-07-18 17:42:50 +08:00
33 changed files with 736 additions and 106 deletions

View File

@@ -26,6 +26,11 @@ The product is a private-deployment, project-centered workbench for individual k
- Keep task sharing conservative: assignees see the task and only explicitly shared linked objects.
- AI must not create official objects without user confirmation.
- AI calls must record provider, key type, action, status, and errors.
- Auth session tokens must be signed, expiring bearer tokens; do not accept forgeable `user:<id>` strings.
- HTTP handlers must read the current user from auth middleware and must not hard-code user IDs.
- Generated tasks, notes, and sources from inbox confirmation should retain their source inbox item ID.
- Task sharing must verify that the shared note/source belongs to the same project as the task.
- User AI keys must be encrypted at rest and AI calls should pass through rate-limit checks before provider execution.
## Frontend Rules
@@ -58,7 +63,7 @@ Do not add these unless a later approved spec says so:
## Verification
- Backend changes should run `go test ./...` from `backend`.
- PostgreSQL integration checks can use `postgres://postgres:Weidong2023~!@8.137.107.29:19432/agent_dev?sslmode=disable` when a live database is required.
- PostgreSQL integration checks should read a live test database URL from `DATABASE_URL`; do not commit real credentials.
- Web changes should run tests and build from `apps/web`.
- Tauri changes should build the web app first, then run the Tauri verification command from `apps/desktop`.
- Each implementation task should end with a focused commit.

View File

@@ -14,6 +14,14 @@ go run ./cmd/api
The web client uses Svelte and TypeScript only. The login shell lets users enter a server IP address or domain name, which is saved as the API base URL.
## Backend Configuration
- `PORT`: API listen port, default `8080`.
- `DATABASE_URL`: PostgreSQL connection string. Do not commit real credentials.
- `AUTH_SECRET`: HMAC secret for invite and session tokens.
- `SYSTEM_AI_KEY`: optional fallback AI provider key.
- `AI_KEY_ENCRYPTION_SECRET`: secret used to encrypt user AI keys at rest.
## Verification
See `docs/mvp-verification.md` for backend, web, desktop, PostgreSQL, and manual MVP verification steps.

View File

@@ -7,3 +7,11 @@ test('project workbench shell renders', async ({ page }) => {
await expect(page.getByLabel('服务器 IP 或域名')).toBeVisible();
await expect(page.getByLabel('项目总览')).toBeVisible();
});
test('inbox suggestions require explicit confirmation', async ({ page }) => {
await page.goto('/');
await page.getByLabel('选择 跟进报价').check();
await page.getByRole('button', { name: '创建选中项' }).click();
await expect(page.getByText('已选择 1 项')).toBeVisible();
});

View File

@@ -1,12 +1,60 @@
<script lang="ts">
import { onMount } from 'svelte';
import ProjectDashboard from '../features/projects/ProjectDashboard.svelte';
import ServerLogin from '../features/auth/ServerLogin.svelte';
import SuggestionList from '../features/inbox/SuggestionList.svelte';
import type { Suggestion } from '../features/inbox/types';
import { createApi, type ProjectDashboardSummary } from '../lib/api';
const emptyDashboard: ProjectDashboardSummary = {
project_id: 1,
pending_inbox_count: 0,
open_task_count: 0,
recent_note_count: 0,
recent_session_count: 0,
};
let apiBase = localStorage.getItem('apiBase') ?? 'http://localhost:8080';
let dashboard = emptyDashboard;
let connectionStatus = '未连接';
let selectedSuggestionCount = 0;
const sampleSuggestions: Suggestion[] = [
{
kind: 'task',
title: '跟进报价',
body: '从项目 inbox 确认后创建任务,并保留来源记录。',
},
{
kind: 'note',
title: '客户背景',
body: '把对话中的背景信息沉淀成项目笔记。',
},
];
onMount(() => {
void loadDashboard();
});
function handleServerChange(event: CustomEvent<{ apiBase: string }>) {
apiBase = event.detail.apiBase;
localStorage.setItem('apiBase', apiBase);
void loadDashboard();
}
async function loadDashboard() {
connectionStatus = '连接中';
try {
dashboard = await createApi(apiBase).getProjectDashboard(1);
connectionStatus = '已连接';
} catch {
dashboard = emptyDashboard;
connectionStatus = '无法连接服务器';
}
}
function handleConfirm(selected: Suggestion[]) {
selectedSuggestionCount = selected.length;
}
</script>
@@ -14,17 +62,15 @@
<aside class="sidebar">
<h1>项目工作台</h1>
<ServerLogin {apiBase} on:serverChange={handleServerChange} />
<p class="connection-status" aria-live="polite">{connectionStatus}</p>
</aside>
<section class="workspace">
<ProjectDashboard
summary={{
project_id: 1,
pending_inbox_count: 0,
open_task_count: 0,
recent_note_count: 0,
recent_session_count: 0,
}}
/>
<ProjectDashboard summary={dashboard} />
<section class="inbox-review" aria-label="项目 inbox">
<h2>AI 整理建议</h2>
<SuggestionList suggestions={sampleSuggestions} onConfirm={handleConfirm} />
<p class="selection-status" aria-live="polite">已选择 {selectedSuggestionCount}</p>
</section>
</section>
</main>

View File

@@ -1,9 +1,5 @@
<script lang="ts">
export type Suggestion = {
kind: 'task' | 'note' | 'source';
title: string;
body: string;
};
import type { Suggestion } from './types';
export let suggestions: Suggestion[] = [];
export let onConfirm: (selected: Suggestion[]) => void;

View File

@@ -0,0 +1,5 @@
export type Suggestion = {
kind: 'task' | 'note' | 'source';
title: string;
body: string;
};

View File

@@ -41,9 +41,18 @@ select {
}
.workspace {
display: grid;
gap: 24px;
padding: 24px;
}
.connection-status,
.selection-status {
margin: 12px 0 0;
color: #5f6673;
font-size: 13px;
}
.server-login {
display: grid;
gap: 8px;
@@ -95,6 +104,51 @@ select {
font-size: 28px;
}
.inbox-review {
display: grid;
gap: 12px;
}
.inbox-review h2 {
margin: 0;
font-size: 18px;
}
.suggestions {
display: grid;
gap: 10px;
}
.suggestion {
display: grid;
grid-template-columns: 20px 1fr;
gap: 10px;
align-items: start;
border: 1px solid #d9dde3;
border-radius: 8px;
background: white;
padding: 12px;
}
.suggestion-body {
display: grid;
gap: 4px;
}
.suggestion-body small {
color: #5f6673;
}
.suggestions button {
justify-self: start;
border: 1px solid #1f2937;
border-radius: 6px;
background: #1f2937;
color: white;
padding: 9px 12px;
cursor: pointer;
}
@media (max-width: 760px) {
.shell {
grid-template-columns: 1fr;

View File

@@ -8,9 +8,11 @@ export type ProjectDashboardSummary = {
recent_session_count: number;
};
export function createApi(apiBase: string) {
export function createApi(apiBase: string, token?: string) {
async function request<T>(path: string): Promise<T> {
const response = await fetch(`${apiBase}${path}`);
const response = await fetch(`${apiBase}/api${path}`, {
headers: token ? { Authorization: `Bearer ${token}` } : {},
});
if (!response.ok) throw new Error(`API request failed: ${response.status}`);
return response.json() as Promise<T>;
}

View File

@@ -13,6 +13,5 @@
"noEmit": true,
"strict": true
},
"include": ["src/**/*.d.ts", "src/**/*.ts", "src/**/*.js", "src/**/*.svelte"],
"references": [{ "path": "./tsconfig.node.json" }]
"include": ["src/**/*.d.ts", "src/**/*.ts", "src/**/*.js", "src/**/*.svelte"]
}

View File

@@ -3,14 +3,30 @@ package main
import (
"log"
"senlinai-agent/backend/internal/auth"
"senlinai-agent/backend/internal/config"
"senlinai-agent/backend/internal/db"
"senlinai-agent/backend/internal/domain"
"senlinai-agent/backend/internal/httpx"
"senlinai-agent/backend/internal/inbox"
"senlinai-agent/backend/internal/projects"
)
func main() {
cfg := config.Load()
router := httpx.NewRouter(cfg)
if err := router.Run(":8080"); err != nil {
database, err := db.Open(cfg.DatabaseURL)
if err != nil {
log.Fatal(err)
}
if err := domain.AutoMigrate(database); err != nil {
log.Fatal(err)
}
authService := auth.NewService(database, cfg.AuthSecret)
projectHandler := projects.NewHandler(projects.NewService(database))
inboxHandler := inbox.NewHandler(inbox.NewService(database, inbox.StaticAnalyzer{}))
router := httpx.NewProtectedRouter(cfg, authService.VerifySession, projectHandler, inboxHandler)
if err := router.Run(":" + cfg.Port); err != nil {
log.Fatal(err)
}
}

View File

@@ -1,15 +1,24 @@
package ai
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"errors"
"io"
"time"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"senlinai-agent/backend/internal/domain"
)
type Gateway struct {
db *gorm.DB
systemKey string
db *gorm.DB
systemKey string
encryptionSecret string
}
type SelectedKey struct {
@@ -19,13 +28,33 @@ type SelectedKey struct {
}
func NewGateway(database *gorm.DB, systemKey string) *Gateway {
return &Gateway{db: database, systemKey: systemKey}
return NewGatewayWithSecret(database, systemKey, "development-ai-key-secret-change-me")
}
func NewGatewayWithSecret(database *gorm.DB, systemKey string, encryptionSecret string) *Gateway {
return &Gateway{db: database, systemKey: systemKey, encryptionSecret: encryptionSecret}
}
func (g *Gateway) SaveUserKey(userID uint, provider string, apiKey string) error {
encrypted, err := encryptAPIKey(apiKey, g.encryptionSecret)
if err != nil {
return err
}
key := domain.AIKey{UserID: userID, Provider: provider, EncryptedAPIKey: encrypted}
return g.db.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "user_id"}},
DoUpdates: clause.AssignmentColumns([]string{"provider", "encrypted_api_key", "updated_at"}),
}).Create(&key).Error
}
func (g *Gateway) SelectKey(userID uint) (SelectedKey, error) {
var userKey domain.AIKey
if err := g.db.Where("user_id = ?", userID).First(&userKey).Error; err == nil {
return SelectedKey{Provider: userKey.Provider, APIKey: userKey.EncryptedAPIKey, KeyType: "user"}, nil
apiKey, err := decryptAPIKey(userKey.EncryptedAPIKey, g.encryptionSecret)
if err != nil {
return SelectedKey{}, err
}
return SelectedKey{Provider: userKey.Provider, APIKey: apiKey, KeyType: "user"}, nil
}
if g.systemKey == "" {
return SelectedKey{}, errors.New("no ai key available")
@@ -43,3 +72,72 @@ func (g *Gateway) RecordCall(userID uint, provider string, usedKeyType string, a
Error: errText,
}).Error
}
func (g *Gateway) CheckRateLimit(userID uint, action string, limit int, window time.Duration) error {
if limit <= 0 {
return nil
}
var count int64
if err := g.db.Model(&domain.AICallLog{}).
Where("user_id = ? AND action = ? AND created_at >= ?", userID, action, time.Now().Add(-window)).
Count(&count).Error; err != nil {
return err
}
if count >= int64(limit) {
return errors.New("ai rate limit exceeded")
}
return nil
}
func encryptAPIKey(apiKey string, secret string) (string, error) {
if apiKey == "" {
return "", errors.New("api key is required")
}
block, err := aes.NewCipher(encryptionKey(secret))
if err != nil {
return "", err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
nonce := make([]byte, gcm.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return "", err
}
ciphertext := gcm.Seal(nil, nonce, []byte(apiKey), nil)
return "v1:" + base64.RawURLEncoding.EncodeToString(append(nonce, ciphertext...)), nil
}
func decryptAPIKey(encrypted string, secret string) (string, error) {
if len(encrypted) < 3 || encrypted[:3] != "v1:" {
return encrypted, nil
}
raw, err := base64.RawURLEncoding.DecodeString(encrypted[3:])
if err != nil {
return "", errors.New("invalid encrypted api key")
}
block, err := aes.NewCipher(encryptionKey(secret))
if err != nil {
return "", err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
if len(raw) < gcm.NonceSize() {
return "", errors.New("invalid encrypted api key")
}
nonce := raw[:gcm.NonceSize()]
ciphertext := raw[gcm.NonceSize():]
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return "", errors.New("invalid encrypted api key")
}
return string(plaintext), nil
}
func encryptionKey(secret string) []byte {
sum := sha256.Sum256([]byte(secret))
return sum[:]
}

View File

@@ -3,6 +3,7 @@ package ai
import (
"fmt"
"testing"
"time"
"github.com/glebarez/sqlite"
"github.com/stretchr/testify/require"
@@ -22,6 +23,21 @@ func TestSelectKeyPrefersUserKey(t *testing.T) {
require.Equal(t, "user-key", selected.APIKey)
}
func TestSaveUserKeyEncryptsStoredKey(t *testing.T) {
database := newTestDB(t)
gateway := NewGatewayWithSecret(database, "system-key", "test-encryption-secret")
require.NoError(t, gateway.SaveUserKey(3, "openai", "user-key"))
var stored domain.AIKey
require.NoError(t, database.Where("user_id = ?", 3).First(&stored).Error)
require.NotEqual(t, "user-key", stored.EncryptedAPIKey)
require.Contains(t, stored.EncryptedAPIKey, "v1:")
selected, err := gateway.SelectKey(3)
require.NoError(t, err)
require.Equal(t, "user-key", selected.APIKey)
}
func TestSelectKeyFallsBackToSystemKey(t *testing.T) {
database := newTestDB(t)
gateway := NewGateway(database, "system-key")
@@ -58,6 +74,16 @@ func TestRecordCallStoresAuditFields(t *testing.T) {
require.Equal(t, "rate limited", log.Error)
}
func TestCheckRateLimitRejectsCallsOverWindow(t *testing.T) {
database := newTestDB(t)
gateway := NewGateway(database, "system-key")
require.NoError(t, gateway.RecordCall(3, "openai", "system", "inbox_analyze", "succeeded", ""))
err := gateway.CheckRateLimit(3, "inbox_analyze", 1, time.Hour)
require.ErrorContains(t, err, "ai rate limit exceeded")
}
func TestCreateAISession(t *testing.T) {
database := newTestDB(t)
service := NewSessionService(database)

View File

@@ -26,3 +26,12 @@ func RequireUser(tokenVerifier func(string) (uint, error)) gin.HandlerFunc {
c.Next()
}
}
func CurrentUserID(c *gin.Context) (uint, bool) {
value, ok := c.Get(CurrentUserIDKey)
if !ok {
return 0, false
}
userID, ok := value.(uint)
return userID, ok && userID > 0
}

View File

@@ -3,10 +3,13 @@ package auth
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
@@ -14,12 +17,14 @@ import (
)
type Service struct {
db *gorm.DB
secret string
db *gorm.DB
secret string
inviteTokenTTL time.Duration
sessionTTL time.Duration
}
func NewService(database *gorm.DB, secret string) *Service {
return &Service{db: database, secret: secret}
return &Service{db: database, secret: secret, inviteTokenTTL: 7 * 24 * time.Hour, sessionTTL: 24 * time.Hour}
}
func (s *Service) CreateInvite(adminID uint, email string) (string, error) {
@@ -27,20 +32,20 @@ func (s *Service) CreateInvite(adminID uint, email string) (string, error) {
if normalized == "" {
return "", errors.New("email is required")
}
return normalized + "." + s.sign(normalized), nil
return s.signToken(tokenPayload{
Type: "invite",
Subject: normalized,
IssuerID: adminID,
ExpiresAt: time.Now().Add(s.inviteTokenTTL).Unix(),
})
}
func (s *Service) RegisterWithInvite(token, email, displayName, password string) (*domain.User, error) {
separator := strings.LastIndex(token, ".")
if separator < 1 || separator == len(token)-1 {
return nil, errors.New("invalid invite token")
payload, err := s.verifyToken(token, "invite")
if err != nil {
return nil, err
}
inviteEmail := token[:separator]
signature := token[separator+1:]
if !hmac.Equal([]byte(signature), []byte(s.sign(inviteEmail))) {
return nil, errors.New("invalid invite signature")
}
if inviteEmail != strings.ToLower(strings.TrimSpace(email)) {
if payload.Subject != strings.ToLower(strings.TrimSpace(email)) {
return nil, errors.New("invite email mismatch")
}
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
@@ -48,7 +53,7 @@ func (s *Service) RegisterWithInvite(token, email, displayName, password string)
return nil, err
}
user := &domain.User{
Email: inviteEmail,
Email: payload.Subject,
DisplayName: strings.TrimSpace(displayName),
PasswordHash: string(hash),
Role: "user",
@@ -64,7 +69,66 @@ func (s *Service) Login(email, password string) (string, error) {
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(password)); err != nil {
return "", errors.New("invalid credentials")
}
return fmt.Sprintf("user:%d", user.ID), nil
return s.signToken(tokenPayload{
Type: "session",
Subject: fmt.Sprintf("%d", user.ID),
ExpiresAt: time.Now().Add(s.sessionTTL).Unix(),
})
}
func (s *Service) VerifySession(token string) (uint, error) {
payload, err := s.verifyToken(token, "session")
if err != nil {
return 0, err
}
var userID uint
if _, err := fmt.Sscanf(payload.Subject, "%d", &userID); err != nil || userID == 0 {
return 0, errors.New("invalid session subject")
}
return userID, nil
}
type tokenPayload struct {
Type string `json:"type"`
Subject string `json:"subject"`
IssuerID uint `json:"issuer_id,omitempty"`
ExpiresAt int64 `json:"expires_at"`
}
func (s *Service) signToken(payload tokenPayload) (string, error) {
body, err := json.Marshal(payload)
if err != nil {
return "", err
}
encoded := base64.RawURLEncoding.EncodeToString(body)
return encoded + "." + s.sign(encoded), nil
}
func (s *Service) verifyToken(token string, expectedType string) (tokenPayload, error) {
separator := strings.LastIndex(token, ".")
if separator < 1 || separator == len(token)-1 {
return tokenPayload{}, errors.New("invalid token")
}
encoded := token[:separator]
signature := token[separator+1:]
if !hmac.Equal([]byte(signature), []byte(s.sign(encoded))) {
return tokenPayload{}, errors.New("invalid token signature")
}
body, err := base64.RawURLEncoding.DecodeString(encoded)
if err != nil {
return tokenPayload{}, errors.New("invalid token payload")
}
var payload tokenPayload
if err := json.Unmarshal(body, &payload); err != nil {
return tokenPayload{}, errors.New("invalid token payload")
}
if payload.Type != expectedType {
return tokenPayload{}, errors.New("invalid token type")
}
if payload.ExpiresAt <= time.Now().Unix() {
return tokenPayload{}, errors.New("token expired")
}
return payload, nil
}
func (s *Service) sign(value string) string {

View File

@@ -48,6 +48,32 @@ func TestLoginRejectsInvalidPassword(t *testing.T) {
require.ErrorContains(t, err, "invalid credentials")
}
func TestLoginReturnsSignedSessionToken(t *testing.T) {
database := newTestDB(t)
service := NewService(database, "test-secret")
token, err := service.CreateInvite(1, "lead@example.com")
require.NoError(t, err)
user, err := service.RegisterWithInvite(token, "lead@example.com", "Lead", "password123")
require.NoError(t, err)
sessionToken, err := service.Login("lead@example.com", "password123")
require.NoError(t, err)
userID, err := service.VerifySession(sessionToken)
require.NoError(t, err)
require.Equal(t, user.ID, userID)
require.NotEqual(t, fmt.Sprintf("user:%d", user.ID), sessionToken)
}
func TestVerifySessionRejectsForgeableLegacyToken(t *testing.T) {
database := newTestDB(t)
service := NewService(database, "test-secret")
_, err := service.VerifySession("user:1")
require.ErrorContains(t, err, "invalid token")
}
func newTestDB(t *testing.T) *gorm.DB {
t.Helper()
database, err := gorm.Open(sqlite.Open(fmt.Sprintf("file:%s?mode=memory&cache=shared", t.Name())), &gorm.Config{})

View File

@@ -3,18 +3,24 @@ package config
import "os"
type Config struct {
Env string
DatabaseURL string
StorageDir string
SystemAIKey string
Env string
Port string
DatabaseURL string
StorageDir string
AuthSecret string
SystemAIKey string
AIKeyEncryptionSecret string
}
func Load() Config {
return Config{
Env: getenv("APP_ENV", "development"),
DatabaseURL: getenv("DATABASE_URL", "postgres://agent:agent@localhost:5432/agent?sslmode=disable"),
StorageDir: getenv("STORAGE_DIR", "./data/files"),
SystemAIKey: os.Getenv("SYSTEM_AI_KEY"),
Env: getenv("APP_ENV", "development"),
Port: getenv("PORT", "8080"),
DatabaseURL: getenv("DATABASE_URL", "postgres://agent:agent@localhost:5432/agent?sslmode=disable"),
StorageDir: getenv("STORAGE_DIR", "./data/files"),
AuthSecret: getenv("AUTH_SECRET", "development-auth-secret-change-me"),
SystemAIKey: os.Getenv("SYSTEM_AI_KEY"),
AIKeyEncryptionSecret: getenv("AI_KEY_ENCRYPTION_SECRET", "development-ai-key-secret-change-me"),
}
}

View File

@@ -38,40 +38,43 @@ type InboxItem struct {
}
type Task struct {
ID uint `gorm:"primaryKey"`
ProjectID uint `gorm:"index;not null"`
CreatedBy uint `gorm:"index;not null"`
AssigneeID *uint `gorm:"index"`
Title string `gorm:"not null"`
Description string
Status string `gorm:"not null;default:open"`
SortOrder int `gorm:"not null;default:0"`
DueAt *time.Time
CreatedAt time.Time
UpdatedAt time.Time
ID uint `gorm:"primaryKey"`
ProjectID uint `gorm:"index;not null"`
CreatedBy uint `gorm:"index;not null"`
AssigneeID *uint `gorm:"index"`
SourceInboxItemID *uint `gorm:"index"`
Title string `gorm:"not null"`
Description string
Status string `gorm:"not null;default:open"`
SortOrder int `gorm:"not null;default:0"`
DueAt *time.Time
CreatedAt time.Time
UpdatedAt time.Time
}
type Note struct {
ID uint `gorm:"primaryKey"`
ProjectID uint `gorm:"index;not null"`
CreatedBy uint `gorm:"index;not null"`
Title string `gorm:"not null"`
Markdown string `gorm:"type:text"`
CreatedAt time.Time
UpdatedAt time.Time
ID uint `gorm:"primaryKey"`
ProjectID uint `gorm:"index;not null"`
CreatedBy uint `gorm:"index;not null"`
SourceInboxItemID *uint `gorm:"index"`
Title string `gorm:"not null"`
Markdown string `gorm:"type:text"`
CreatedAt time.Time
UpdatedAt time.Time
}
type Source struct {
ID uint `gorm:"primaryKey"`
ProjectID uint `gorm:"index;not null"`
CreatedBy uint `gorm:"index;not null"`
Kind string `gorm:"not null"`
Title string `gorm:"not null"`
URL string
FilePath string
ContentText string `gorm:"type:text"`
CreatedAt time.Time
UpdatedAt time.Time
ID uint `gorm:"primaryKey"`
ProjectID uint `gorm:"index;not null"`
CreatedBy uint `gorm:"index;not null"`
SourceInboxItemID *uint `gorm:"index"`
Kind string `gorm:"not null"`
Title string `gorm:"not null"`
URL string
FilePath string
ContentText string `gorm:"type:text"`
CreatedAt time.Time
UpdatedAt time.Time
}
type AISession struct {

View File

@@ -4,10 +4,23 @@ import (
"net/http"
"github.com/gin-gonic/gin"
"senlinai-agent/backend/internal/auth"
"senlinai-agent/backend/internal/config"
)
func NewRouter(cfg config.Config) *gin.Engine {
type RouteRegistrar interface {
Register(router gin.IRouter)
}
func NewRouter(cfg config.Config, registrars ...RouteRegistrar) *gin.Engine {
return newRouter(cfg, nil, registrars...)
}
func NewProtectedRouter(cfg config.Config, tokenVerifier func(string) (uint, error), registrars ...RouteRegistrar) *gin.Engine {
return newRouter(cfg, tokenVerifier, registrars...)
}
func newRouter(cfg config.Config, tokenVerifier func(string) (uint, error), registrars ...RouteRegistrar) *gin.Engine {
if cfg.Env == "test" {
gin.SetMode(gin.TestMode)
}
@@ -18,6 +31,13 @@ func NewRouter(cfg config.Config) *gin.Engine {
router.GET("/healthz", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "ok"})
})
api := router.Group("/api")
if tokenVerifier != nil {
api.Use(auth.RequireUser(tokenVerifier))
}
for _, registrar := range registrars {
registrar.Register(api)
}
return router
}

View File

@@ -5,6 +5,7 @@ import (
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"senlinai-agent/backend/internal/config"
)
@@ -19,3 +20,22 @@ func TestHealthz(t *testing.T) {
require.Equal(t, http.StatusOK, rec.Code)
require.JSONEq(t, `{"status":"ok"}`, rec.Body.String())
}
func TestNewRouterRegistersFeatureRoutesUnderAPI(t *testing.T) {
router := NewRouter(config.Config{Env: "test"}, testRegistrar{})
req := httptest.NewRequest(http.MethodGet, "/api/ping", nil)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
require.JSONEq(t, `{"pong":true}`, rec.Body.String())
}
type testRegistrar struct{}
func (testRegistrar) Register(router gin.IRouter) {
router.GET("/ping", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"pong": true})
})
}

View File

@@ -5,6 +5,7 @@ import (
"strconv"
"github.com/gin-gonic/gin"
"senlinai-agent/backend/internal/auth"
)
type Handler struct {
@@ -22,6 +23,11 @@ func (h *Handler) Register(router gin.IRouter) {
}
func (h *Handler) capture(c *gin.Context) {
userID, ok := auth.CurrentUserID(c)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "missing current user"})
return
}
projectID, err := strconv.ParseUint(c.Param("projectID"), 10, 64)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid project id"})
@@ -36,7 +42,7 @@ func (h *Handler) capture(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
return
}
item, err := h.service.Capture(CaptureInput{ProjectID: uint(projectID), UserID: 1, SourceType: input.SourceType, Title: input.Title, Body: input.Body})
item, err := h.service.Capture(CaptureInput{ProjectID: uint(projectID), UserID: userID, SourceType: input.SourceType, Title: input.Title, Body: input.Body})
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
@@ -45,12 +51,17 @@ func (h *Handler) capture(c *gin.Context) {
}
func (h *Handler) analyze(c *gin.Context) {
userID, ok := auth.CurrentUserID(c)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "missing current user"})
return
}
itemID, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid inbox id"})
return
}
suggestions, err := h.service.Analyze(uint(itemID), 1)
suggestions, err := h.service.Analyze(uint(itemID), userID)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return

View File

@@ -77,18 +77,19 @@ func (s *Service) Confirm(itemID uint, selected []Suggestion) error {
if err := tx.First(&item, itemID).Error; err != nil {
return err
}
sourceInboxItemID := item.ID
for _, suggestion := range selected {
switch suggestion.Kind {
case "task":
if err := tx.Create(&domain.Task{ProjectID: item.ProjectID, CreatedBy: item.CreatedBy, Title: suggestion.Title, Description: suggestion.Body}).Error; err != nil {
if err := tx.Create(&domain.Task{ProjectID: item.ProjectID, CreatedBy: item.CreatedBy, SourceInboxItemID: &sourceInboxItemID, Title: suggestion.Title, Description: suggestion.Body}).Error; err != nil {
return err
}
case "note":
if err := tx.Create(&domain.Note{ProjectID: item.ProjectID, CreatedBy: item.CreatedBy, Title: suggestion.Title, Markdown: suggestion.Body}).Error; err != nil {
if err := tx.Create(&domain.Note{ProjectID: item.ProjectID, CreatedBy: item.CreatedBy, SourceInboxItemID: &sourceInboxItemID, Title: suggestion.Title, Markdown: suggestion.Body}).Error; err != nil {
return err
}
case "source":
if err := tx.Create(&domain.Source{ProjectID: item.ProjectID, CreatedBy: item.CreatedBy, Kind: "link", Title: suggestion.Title, ContentText: suggestion.Body}).Error; err != nil {
if err := tx.Create(&domain.Source{ProjectID: item.ProjectID, CreatedBy: item.CreatedBy, SourceInboxItemID: &sourceInboxItemID, Kind: "link", Title: suggestion.Title, ContentText: suggestion.Body}).Error; err != nil {
return err
}
default:

View File

@@ -44,6 +44,8 @@ func TestConfirmCreatesSelectedObjectsAndKeepsInboxItem(t *testing.T) {
require.NoError(t, database.Find(&tasks).Error)
require.Len(t, tasks, 1)
require.Equal(t, "跟进报价", tasks[0].Title)
require.NotNil(t, tasks[0].SourceInboxItemID)
require.Equal(t, item.ID, *tasks[0].SourceInboxItemID)
var reloaded domain.InboxItem
require.NoError(t, database.First(&reloaded, item.ID).Error)
require.Equal(t, "processed", reloaded.Status)

View File

@@ -5,6 +5,7 @@ import (
"strconv"
"github.com/gin-gonic/gin"
"senlinai-agent/backend/internal/auth"
)
type Handler struct {
@@ -22,6 +23,11 @@ func (h *Handler) Register(router gin.IRouter) {
}
func (h *Handler) createProject(c *gin.Context) {
userID, ok := auth.CurrentUserID(c)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "missing current user"})
return
}
var input struct {
Name string `json:"name"`
Description string `json:"description"`
@@ -30,7 +36,7 @@ func (h *Handler) createProject(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
return
}
project, err := h.service.CreateProject(1, input.Name, input.Description)
project, err := h.service.CreateProject(userID, input.Name, input.Description)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
@@ -39,7 +45,12 @@ func (h *Handler) createProject(c *gin.Context) {
}
func (h *Handler) listProjects(c *gin.Context) {
projects, err := h.service.ListProjects(1)
userID, ok := auth.CurrentUserID(c)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "missing current user"})
return
}
projects, err := h.service.ListProjects(userID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list projects"})
return
@@ -48,12 +59,17 @@ func (h *Handler) listProjects(c *gin.Context) {
}
func (h *Handler) dashboard(c *gin.Context) {
userID, ok := auth.CurrentUserID(c)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "missing current user"})
return
}
projectID, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid project id"})
return
}
dashboard, err := h.service.Dashboard(uint(projectID))
dashboard, err := h.service.Dashboard(userID, uint(projectID))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to load dashboard"})
return

View File

@@ -54,7 +54,11 @@ func (s *Service) ListTags(projectID uint) ([]domain.Tag, error) {
return tags, err
}
func (s *Service) Dashboard(projectID uint) (Dashboard, error) {
func (s *Service) Dashboard(ownerID uint, projectID uint) (Dashboard, error) {
var project domain.Project
if err := s.db.Where("id = ? AND owner_id = ?", projectID, ownerID).First(&project).Error; err != nil {
return Dashboard{}, err
}
dashboard := Dashboard{ProjectID: projectID}
if err := s.db.Model(&domain.InboxItem{}).Where("project_id = ? AND status = ?", projectID, "open").Count(&dashboard.PendingInboxCount).Error; err != nil {
return dashboard, err

View File

@@ -41,13 +41,24 @@ func TestDashboardCountsOnlyRequestedProject(t *testing.T) {
require.NoError(t, database.Create(&domain.Task{ProjectID: first.ID, CreatedBy: 1, Title: "A", Status: "open"}).Error)
require.NoError(t, database.Create(&domain.Task{ProjectID: second.ID, CreatedBy: 1, Title: "B", Status: "open"}).Error)
dashboard, err := service.Dashboard(first.ID)
dashboard, err := service.Dashboard(1, first.ID)
require.NoError(t, err)
require.Equal(t, int64(1), dashboard.PendingInboxCount)
require.Equal(t, int64(1), dashboard.OpenTaskCount)
}
func TestDashboardRejectsProjectOwnedByAnotherUser(t *testing.T) {
database := newTestDB(t)
service := NewService(database)
project, err := service.CreateProject(2, "Beta", "")
require.NoError(t, err)
_, err = service.Dashboard(1, project.ID)
require.Error(t, err)
}
func newTestDB(t *testing.T) *gorm.DB {
t.Helper()
database, err := gorm.Open(sqlite.Open(fmt.Sprintf("file:%s?mode=memory&cache=shared", t.Name())), &gorm.Config{})

View File

@@ -32,30 +32,106 @@ func (s *Service) Search(userID uint, query string) ([]Result, error) {
return s.searchPostgres(userID, query)
}
like := "%" + query + "%"
results := []Result{}
var projects []domain.Project
if err := s.db.Where("owner_id = ? AND (name LIKE ? OR description LIKE ?)", userID, like, like).Find(&projects).Error; err != nil {
return nil, err
}
for _, project := range projects {
results = append(results, Result{Type: "project", ID: project.ID, ProjectID: project.ID, Title: project.Name, Snippet: project.Description})
}
var tasks []domain.Task
if err := s.db.Joins("JOIN projects ON projects.id = tasks.project_id").
Where("projects.owner_id = ? AND (tasks.title LIKE ? OR tasks.description LIKE ?)", userID, like, like).
Find(&tasks).Error; err != nil {
return nil, err
}
for _, task := range tasks {
results = append(results, Result{Type: "task", ID: task.ID, ProjectID: task.ProjectID, Title: task.Title, Snippet: task.Description})
}
var notes []domain.Note
if err := s.db.Joins("JOIN projects ON projects.id = notes.project_id").
Where("projects.owner_id = ? AND (notes.title LIKE ? OR notes.markdown LIKE ?)", userID, "%"+query+"%", "%"+query+"%").
Where("projects.owner_id = ? AND (notes.title LIKE ? OR notes.markdown LIKE ?)", userID, like, like).
Find(&notes).Error; err != nil {
return nil, err
}
results := make([]Result, 0, len(notes))
for _, note := range notes {
results = append(results, Result{Type: "note", ID: note.ID, ProjectID: note.ProjectID, Title: note.Title, Snippet: note.Markdown})
}
var sources []domain.Source
if err := s.db.Joins("JOIN projects ON projects.id = sources.project_id").
Where("projects.owner_id = ? AND (sources.title LIKE ? OR sources.url LIKE ? OR sources.content_text LIKE ?)", userID, like, like, like).
Find(&sources).Error; err != nil {
return nil, err
}
for _, source := range sources {
results = append(results, Result{Type: "source", ID: source.ID, ProjectID: source.ProjectID, Title: source.Title, Snippet: source.ContentText})
}
var inboxItems []domain.InboxItem
if err := s.db.Joins("JOIN projects ON projects.id = inbox_items.project_id").
Where("projects.owner_id = ? AND (inbox_items.title LIKE ? OR inbox_items.body LIKE ?)", userID, like, like).
Find(&inboxItems).Error; err != nil {
return nil, err
}
for _, item := range inboxItems {
results = append(results, Result{Type: "inbox", ID: item.ID, ProjectID: item.ProjectID, Title: item.Title, Snippet: item.Body})
}
var sessions []domain.AISession
if err := s.db.Joins("JOIN projects ON projects.id = ai_sessions.project_id").
Where("projects.owner_id = ? AND (ai_sessions.title LIKE ? OR ai_sessions.context LIKE ?)", userID, like, like).
Find(&sessions).Error; err != nil {
return nil, err
}
for _, session := range sessions {
results = append(results, Result{Type: "ai_session", ID: session.ID, ProjectID: session.ProjectID, Title: session.Title, Snippet: session.Context})
}
return results, nil
}
func (s *Service) searchPostgres(userID uint, query string) ([]Result, error) {
var results []Result
err := s.db.Raw(`
SELECT 'project' AS type, projects.id, projects.id AS project_id, projects.name AS title, projects.description AS snippet
FROM projects
WHERE projects.owner_id = ?
AND to_tsvector('simple', coalesce(projects.name, '') || ' ' || coalesce(projects.description, '')) @@ plainto_tsquery('simple', ?)
UNION ALL
SELECT 'task' AS type, tasks.id, tasks.project_id, tasks.title, tasks.description AS snippet
FROM tasks
JOIN projects ON projects.id = tasks.project_id
WHERE projects.owner_id = ?
AND to_tsvector('simple', coalesce(tasks.title, '') || ' ' || coalesce(tasks.description, '')) @@ plainto_tsquery('simple', ?)
UNION ALL
SELECT 'note' AS type, notes.id, notes.project_id, notes.title, notes.markdown AS snippet
FROM notes
JOIN projects ON projects.id = notes.project_id
WHERE projects.owner_id = ?
AND to_tsvector('simple', coalesce(notes.title, '') || ' ' || coalesce(notes.markdown, ''))
@@ plainto_tsquery('simple', ?)
ORDER BY notes.updated_at DESC
AND to_tsvector('simple', coalesce(notes.title, '') || ' ' || coalesce(notes.markdown, '')) @@ plainto_tsquery('simple', ?)
UNION ALL
SELECT 'source' AS type, sources.id, sources.project_id, sources.title, sources.content_text AS snippet
FROM sources
JOIN projects ON projects.id = sources.project_id
WHERE projects.owner_id = ?
AND to_tsvector('simple', coalesce(sources.title, '') || ' ' || coalesce(sources.url, '') || ' ' || coalesce(sources.content_text, '')) @@ plainto_tsquery('simple', ?)
UNION ALL
SELECT 'inbox' AS type, inbox_items.id, inbox_items.project_id, inbox_items.title, inbox_items.body AS snippet
FROM inbox_items
JOIN projects ON projects.id = inbox_items.project_id
WHERE projects.owner_id = ?
AND to_tsvector('simple', coalesce(inbox_items.title, '') || ' ' || coalesce(inbox_items.body, '')) @@ plainto_tsquery('simple', ?)
UNION ALL
SELECT 'ai_session' AS type, ai_sessions.id, ai_sessions.project_id, ai_sessions.title, ai_sessions.context AS snippet
FROM ai_sessions
JOIN projects ON projects.id = ai_sessions.project_id
WHERE projects.owner_id = ?
AND to_tsvector('simple', coalesce(ai_sessions.title, '') || ' ' || coalesce(ai_sessions.context, '')) @@ plainto_tsquery('simple', ?)
LIMIT 50
`, userID, query).Scan(&results).Error
`, userID, query, userID, query, userID, query, userID, query, userID, query, userID, query).Scan(&results).Error
return results, err
}

View File

@@ -24,3 +24,27 @@ func TestSearchFindsNoteBody(t *testing.T) {
require.Len(t, results, 1)
require.Equal(t, "note", results[0].Type)
}
func TestSearchFindsCoreProjectObjects(t *testing.T) {
database, err := gorm.Open(sqlite.Open(fmt.Sprintf("file:%s?mode=memory&cache=shared", t.Name())), &gorm.Config{})
require.NoError(t, err)
require.NoError(t, domain.AutoMigrate(database))
require.NoError(t, database.Create(&domain.Project{ID: 1, OwnerID: 7, Name: "支付项目"}).Error)
require.NoError(t, database.Create(&domain.Task{ProjectID: 1, CreatedBy: 7, Title: "回调任务", Description: "检查 webhook"}).Error)
require.NoError(t, database.Create(&domain.Source{ProjectID: 1, CreatedBy: 7, Kind: "link", Title: "支付文档", URL: "https://example.com/pay", ContentText: "webhook 签名"}).Error)
require.NoError(t, database.Create(&domain.InboxItem{ProjectID: 1, CreatedBy: 7, SourceType: "text", Title: "收集项", Body: "webhook 待整理"}).Error)
require.NoError(t, database.Create(&domain.AISession{ProjectID: 1, CreatedBy: 7, Title: "AI 分析", Context: "webhook 问答"}).Error)
service := NewService(database)
results, err := service.Search(7, "webhook")
require.NoError(t, err)
types := make(map[string]bool)
for _, result := range results {
types[result.Type] = true
}
require.True(t, types["task"])
require.True(t, types["source"])
require.True(t, types["inbox"])
require.True(t, types["ai_session"])
}

View File

@@ -50,6 +50,9 @@ func (s *Service) ShareObject(taskID uint, objectType string, objectID uint) err
if err := tx.First(&task, taskID).Error; err != nil {
return err
}
if err := ensureSharedObjectInProject(tx, task.ProjectID, objectType, objectID); err != nil {
return err
}
if err := tx.Create(&domain.TaskShare{TaskID: taskID, ObjectType: objectType, ObjectID: objectID}).Error; err != nil {
return err
}
@@ -82,3 +85,25 @@ func (s *Service) VisibleLinkedObjects(taskID uint, viewerID uint) ([]LinkedObje
}
return objects, nil
}
func ensureSharedObjectInProject(tx *gorm.DB, projectID uint, objectType string, objectID uint) error {
switch objectType {
case "note":
var count int64
if err := tx.Model(&domain.Note{}).Where("id = ? AND project_id = ?", objectID, projectID).Count(&count).Error; err != nil {
return err
}
if count == 0 {
return errors.New("shared object not found in task project")
}
case "source":
var count int64
if err := tx.Model(&domain.Source{}).Where("id = ? AND project_id = ?", objectID, projectID).Count(&count).Error; err != nil {
return err
}
if count == 0 {
return errors.New("shared object not found in task project")
}
}
return nil
}

View File

@@ -40,6 +40,19 @@ func TestShareObjectRejectsUnsupportedType(t *testing.T) {
require.ErrorContains(t, err, "unsupported shared object type")
}
func TestShareObjectRejectsObjectFromAnotherProject(t *testing.T) {
database := newTestDB(t)
task := domain.Task{ProjectID: 1, CreatedBy: 1, Title: "Review"}
note := domain.Note{ProjectID: 2, CreatedBy: 1, Title: "Other project", Markdown: "Private context"}
require.NoError(t, database.Create(&task).Error)
require.NoError(t, database.Create(&note).Error)
service := NewService(database)
err := service.ShareObject(task.ID, "note", note.ID)
require.ErrorContains(t, err, "shared object not found in task project")
}
func TestAssignRecordsProjectEvent(t *testing.T) {
database := newTestDB(t)
task := domain.Task{ProjectID: 7, CreatedBy: 1, Title: "安排评审"}

View File

@@ -1,3 +1,7 @@
CREATE INDEX IF NOT EXISTS idx_projects_search
ON projects
USING gin (to_tsvector('simple', coalesce(name, '') || ' ' || coalesce(description, '')));
CREATE INDEX IF NOT EXISTS idx_notes_search
ON notes
USING gin (to_tsvector('simple', coalesce(title, '') || ' ' || coalesce(markdown, '')));

View File

@@ -13,19 +13,12 @@ Expected: all backend tests pass.
## PostgreSQL Integration
Use this test database URL when live PostgreSQL verification is required:
```text
postgres://postgres:Weidong2023~!@8.137.107.29:19432/agent_dev?sslmode=disable
```
Do not hardcode this value into application source files. Pass it through `DATABASE_URL`.
Set `DATABASE_URL` to the live PostgreSQL test database before running integration checks. Do not commit real credentials.
Run:
```powershell
Set-Location backend
$env:DATABASE_URL='postgres://postgres:Weidong2023~!@8.137.107.29:19432/agent_dev?sslmode=disable'
go test -tags integration ./internal/db -run TestPostgresPing -v
```
@@ -39,12 +32,13 @@ Run:
```powershell
Set-Location apps/web
npx tsc --noEmit -p tsconfig.app.json
npm test -- --run
npm run build
npx playwright test
```
Expected: component tests, production build, and smoke test pass.
Expected: TypeScript check, component tests, production build, and Playwright smoke/E2E tests pass.
## Desktop
@@ -61,8 +55,29 @@ Expected: Tauri desktop bundle builds when Rust/Cargo is installed and the stabl
Current machine status:
- `rustup` was installed through winget.
- The stable toolchain install repeatedly timed out and currently reports `Missing manifest in toolchain 'stable-x86_64-pc-windows-msvc'`.
- Desktop verification remains blocked until `rustup toolchain install stable-x86_64-pc-windows-msvc --profile minimal --force` completes successfully.
- The latest desktop build attempt fails before project compilation because `cargo` is not available on PATH: `program not found`.
- Desktop verification remains blocked until Rust/Cargo is installed and visible to the shell. Then run `npm run build` from `apps/desktop`.
## Latest Audit Verification
Last audited: 2026-07-18.
- `backend`: `go test ./... -v` passed.
- `apps/web`: `npx tsc --noEmit -p tsconfig.app.json` passed.
- `apps/web`: `npm test -- --run` passed.
- `apps/web`: `npm run build` passed.
- `apps/web`: `npx playwright test` passed.
- `apps/desktop`: `npm run build` blocked by missing Cargo/Rust toolchain on the current machine.
Audit fixes included:
- Signed expiring auth session tokens replaced forgeable `user:<id>` tokens.
- Project and inbox HTTP handlers now read the authenticated user from bearer middleware instead of hard-coding user `1`.
- Project dashboard loading now checks project ownership before returning counters.
- Inbox confirmation preserves provenance with `source_inbox_item_id` on generated tasks, notes, and sources.
- Task sharing now rejects note/source links from another project.
- AI user keys are encrypted before storage, decrypted on selection, and can be checked with a per-user action rate limit.
- Web API calls now use the backend `/api` prefix and the Svelte shell includes an inbox suggestion confirmation E2E path.
## Manual MVP Flow

View File

@@ -20,7 +20,7 @@
- 全局搜索使用 PostgreSQL 关键词和全文搜索,语义搜索不进入 MVP。
- 前端只使用 Svelte不使用 React。
- 登录页必须允许用户填写服务器 IP 或域名,并将其保存为 API base URL。
- PostgreSQL 集成验证使用 `postgres://postgres:Weidong2023~!@8.137.107.29:19432/agent_dev?sslmode=disable`
- PostgreSQL 集成验证通过 `DATABASE_URL` 读取测试服务器地址;不要提交真实凭据
- 前端桌面优先,同时保持移动浏览器可用。
- 每个任务结束时运行该任务列出的验证命令并提交。
@@ -663,6 +663,9 @@ Last updated: 2026-07-18.
- [x] Checkpoint 10: Svelte Inbox、AI 建议确认、任务列表、Markdown 编辑器、AI session 卡片和快速收集组件已完成。
- [x] Checkpoint 11: Tauri 2 桌面壳文件已完成Web 构建可供 Tauri 使用。
- [x] Checkpoint 12: 后端单元测试、PostgreSQL integration ping、Web component tests、Web build 和 Playwright smoke test 已完成。
- [x] Router/main wiring audit: `/api` route registrar 已接入,`cmd/api` 启动时连接 PostgreSQL、执行 AutoMigrate并注册项目与 Inbox handlers。
- [x] Search coverage audit: 搜索 service 已覆盖 project、task、note、source、inbox 和 AI session。
- [x] Credential hygiene audit: 当前文档不再保存真实 PostgreSQL 测试库连接串,集成验证统一通过 `DATABASE_URL` 注入。
- [ ] Desktop binary verification: blocked by local Rust toolchain state. `rustup` is installed, but `stable-x86_64-pc-windows-msvc` reports `Missing manifest in toolchain`. Run `rustup toolchain install stable-x86_64-pc-windows-msvc --profile minimal --force` until it completes, then run `npm run build` from `apps/desktop`.
Verification evidence from the latest run:
@@ -673,3 +676,17 @@ Verification evidence from the latest run:
- `apps/web`: `npm run build` passed.
- `apps/web`: `npx playwright test` passed.
- `apps/desktop`: `npm run build` is blocked before compilation by incomplete Rust stable toolchain.
## 2026-07-18 Full Audit Follow-Up
- [x] Backend API startup now wires PostgreSQL, AutoMigrate, project routes, and inbox routes through `/api`.
- [x] Auth sessions are signed and expiring; legacy forgeable `user:<id>` tokens are rejected.
- [x] Project and inbox HTTP handlers use the authenticated bearer-token user instead of a hard-coded user ID.
- [x] Project dashboard reads are owner-scoped before counters are returned.
- [x] Search now covers projects, tasks, notes, sources, inbox items, and AI sessions.
- [x] Inbox confirmation keeps provenance through `source_inbox_item_id` on generated tasks, notes, and sources.
- [x] Task sharing rejects note/source objects from a different project.
- [x] AI user keys are encrypted at rest and gateway rate-limit checks are covered by tests.
- [x] Svelte web client calls the backend `/api` prefix, passes type checking, and has Playwright coverage for inbox suggestion confirmation.
- [x] Current Markdown docs no longer include the live PostgreSQL test credential; integration tests must receive it through `DATABASE_URL`.
- [ ] Desktop binary build remains blocked on this machine because Cargo/Rust is not available to the shell. Install a complete Rust stable toolchain, then rerun `npm run build` from `apps/desktop`.

View File

@@ -225,7 +225,7 @@ MVP 使用保守共享模型:
后端:
- AI key 选择、inbox 处理、任务共享可见性、标签项目隔离、文件元数据处理的单元测试。
- 项目搜索、任务分发、inbox 转对象的集成测试。
- 需要真实 PostgreSQL 时,使用测试服务器 `postgres://postgres:Weidong2023~!@8.137.107.29:19432/agent_dev?sslmode=disable`
- 需要真实 PostgreSQL 时,通过 `DATABASE_URL` 指向测试服务器;不要把真实凭据写入仓库
前端:
- 项目 Dashboard、inbox 建议确认、AI session 列表、任务列表、快速收集表单的组件测试。