remove preact and create setup wizard
This commit is contained in:
@@ -100,6 +100,93 @@ func (r *Repository) CountAdmins(ctx context.Context) (int, error) {
|
||||
return count, nil
|
||||
}
|
||||
|
||||
func (r *Repository) GetInstanceSettings(ctx context.Context) (InstanceSettings, error) {
|
||||
var setupCompleted string
|
||||
var signupsEnabled int
|
||||
if err := r.db.QueryRowContext(ctx, `
|
||||
SELECT COALESCE(setup_completed_at, ''), signups_enabled
|
||||
FROM instance_settings
|
||||
WHERE id = 1
|
||||
`).Scan(&setupCompleted, &signupsEnabled); err != nil {
|
||||
return InstanceSettings{}, fmt.Errorf("get instance settings: %w", err)
|
||||
}
|
||||
return InstanceSettings{
|
||||
SetupComplete: setupCompleted != "",
|
||||
SignupsEnabled: signupsEnabled == 1,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *Repository) CompleteInitialSetup(ctx context.Context, user User, signupsEnabled bool) (User, error) {
|
||||
now := time.Now().UTC()
|
||||
if user.ID == "" {
|
||||
user.ID = "user:" + user.Email
|
||||
}
|
||||
if user.DisplayName == "" {
|
||||
user.DisplayName = user.Email
|
||||
}
|
||||
|
||||
tx, err := r.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return User{}, fmt.Errorf("begin initial setup: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
|
||||
var setupCompleted string
|
||||
if err := tx.QueryRowContext(ctx, `
|
||||
SELECT COALESCE(setup_completed_at, '')
|
||||
FROM instance_settings
|
||||
WHERE id = 1
|
||||
`).Scan(&setupCompleted); err != nil {
|
||||
return User{}, fmt.Errorf("get initial setup state: %w", err)
|
||||
}
|
||||
if setupCompleted != "" {
|
||||
return User{}, fmt.Errorf("initial setup has already been completed")
|
||||
}
|
||||
|
||||
var userCount int
|
||||
if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM users`).Scan(&userCount); err != nil {
|
||||
return User{}, fmt.Errorf("count users during initial setup: %w", err)
|
||||
}
|
||||
if userCount != 0 {
|
||||
return User{}, fmt.Errorf("initial setup requires an empty user database")
|
||||
}
|
||||
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO users (id, email, display_name, password_hash, role, created_at, last_seen_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
`, user.ID, user.Email, user.DisplayName, nullString(user.PasswordHash), string(RoleAdmin), now.Format(time.RFC3339), now.Format(time.RFC3339)); err != nil {
|
||||
return User{}, fmt.Errorf("create initial admin: %w", err)
|
||||
}
|
||||
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
UPDATE instance_settings
|
||||
SET setup_completed_at = ?, signups_enabled = ?, updated_at = ?
|
||||
WHERE id = 1 AND setup_completed_at IS NULL
|
||||
`, now.Format(time.RFC3339), boolInt(signupsEnabled), now.Format(time.RFC3339)); err != nil {
|
||||
return User{}, fmt.Errorf("complete initial setup: %w", err)
|
||||
}
|
||||
|
||||
if err := tx.Commit(); err != nil {
|
||||
return User{}, fmt.Errorf("commit initial setup: %w", err)
|
||||
}
|
||||
return r.GetUserByEmail(ctx, user.Email)
|
||||
}
|
||||
|
||||
func (r *Repository) UpdateSignupsEnabled(ctx context.Context, enabled bool) error {
|
||||
result, err := r.db.ExecContext(ctx, `
|
||||
UPDATE instance_settings
|
||||
SET signups_enabled = ?, updated_at = ?
|
||||
WHERE id = 1 AND setup_completed_at IS NOT NULL
|
||||
`, boolInt(enabled), time.Now().UTC().Format(time.RFC3339))
|
||||
if err != nil {
|
||||
return fmt.Errorf("update signup setting: %w", err)
|
||||
}
|
||||
if rows, _ := result.RowsAffected(); rows == 0 {
|
||||
return fmt.Errorf("initial setup is required")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Repository) ListUsers(ctx context.Context) ([]User, error) {
|
||||
rows, err := r.db.QueryContext(ctx, `
|
||||
SELECT id, email, COALESCE(display_name, ''), COALESCE(password_hash, ''), COALESCE(role, 'viewer'), created_at, COALESCE(last_seen_at, '')
|
||||
@@ -522,6 +609,13 @@ func nullString(value string) any {
|
||||
return value
|
||||
}
|
||||
|
||||
func boolInt(value bool) int {
|
||||
if value {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func timePtrString(value *time.Time) any {
|
||||
if value == nil {
|
||||
return nil
|
||||
|
||||
@@ -55,7 +55,34 @@ func NewService(repo *Repository, publicOrigin string) (*Service, error) {
|
||||
return &Service{repo: repo, webauthn: web, publicOrigin: publicOrigin}, nil
|
||||
}
|
||||
|
||||
func (s *Service) GetInstanceSettings(ctx context.Context) (InstanceSettings, error) {
|
||||
return s.repo.GetInstanceSettings(ctx)
|
||||
}
|
||||
|
||||
func (s *Service) CompleteInitialSetup(ctx context.Context, email, displayName, password string, signupsEnabled bool) (User, error) {
|
||||
email = normalizeEmail(email)
|
||||
if email == "" {
|
||||
return User{}, fmt.Errorf("email is required")
|
||||
}
|
||||
if len(password) < 12 {
|
||||
return User{}, fmt.Errorf("password must be at least 12 characters")
|
||||
}
|
||||
passwordHash, err := hashPassword(password)
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
return s.repo.CompleteInitialSetup(ctx, User{
|
||||
Email: email,
|
||||
DisplayName: strings.TrimSpace(displayName),
|
||||
PasswordHash: passwordHash,
|
||||
Role: RoleAdmin,
|
||||
}, signupsEnabled)
|
||||
}
|
||||
|
||||
func (s *Service) RegisterPasswordUser(ctx context.Context, email, displayName, password, role string) (User, error) {
|
||||
if err := s.requirePublicSignups(ctx); err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
email = normalizeEmail(email)
|
||||
if email == "" {
|
||||
return User{}, fmt.Errorf("email is required")
|
||||
@@ -72,21 +99,11 @@ func (s *Service) RegisterPasswordUser(ctx context.Context, email, displayName,
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
userCount, err := s.repo.CountUsers(ctx)
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
normalizedRole := RoleViewer
|
||||
if userCount == 0 {
|
||||
normalizedRole = RoleAdmin
|
||||
} else if strings.EqualFold(role, string(RoleViewer)) {
|
||||
normalizedRole = RoleViewer
|
||||
}
|
||||
return s.repo.UpsertUser(ctx, User{
|
||||
Email: email,
|
||||
DisplayName: strings.TrimSpace(displayName),
|
||||
PasswordHash: passwordHash,
|
||||
Role: normalizedRole,
|
||||
Role: RoleViewer,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -113,23 +130,18 @@ func (s *Service) LoginPassword(ctx context.Context, email, password, ip, userAg
|
||||
}
|
||||
|
||||
func (s *Service) BeginPasskeyRegistration(ctx context.Context, email, displayName, role string) (any, string, error) {
|
||||
if err := s.requirePublicSignups(ctx); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
user, err := s.repo.GetUserByEmail(ctx, normalizeEmail(email))
|
||||
if err != nil {
|
||||
if !isNoRows(err) {
|
||||
return nil, "", err
|
||||
}
|
||||
userCount, err := s.repo.CountUsers(ctx)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
normalizedRole := RoleViewer
|
||||
if userCount == 0 {
|
||||
normalizedRole = RoleAdmin
|
||||
}
|
||||
user, err = s.repo.UpsertUser(ctx, User{
|
||||
Email: normalizeEmail(email),
|
||||
DisplayName: strings.TrimSpace(displayName),
|
||||
Role: normalizedRole,
|
||||
Role: RoleViewer,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
@@ -278,6 +290,43 @@ func (s *Service) ListUsers(ctx context.Context) ([]User, error) {
|
||||
return s.repo.ListUsers(ctx)
|
||||
}
|
||||
|
||||
func (s *Service) UpdateSignupsEnabled(ctx context.Context, actor Principal, enabled bool) (InstanceSettings, error) {
|
||||
if !Allows(actor, ScopeAdmin) {
|
||||
return InstanceSettings{}, fmt.Errorf("admin role required")
|
||||
}
|
||||
if err := s.repo.UpdateSignupsEnabled(ctx, enabled); err != nil {
|
||||
return InstanceSettings{}, err
|
||||
}
|
||||
return s.repo.GetInstanceSettings(ctx)
|
||||
}
|
||||
|
||||
func (s *Service) EnsureDevUser(ctx context.Context) (User, error) {
|
||||
const email = "dev@localhost"
|
||||
settings, err := s.repo.GetInstanceSettings(ctx)
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
if !settings.SetupComplete {
|
||||
return s.CompleteInitialSetup(ctx, email, "Development Admin", "development-only-password", true)
|
||||
}
|
||||
user, err := s.repo.GetUserByEmail(ctx, email)
|
||||
if err == nil {
|
||||
return user, nil
|
||||
}
|
||||
if !isNoRows(err) {
|
||||
return User{}, err
|
||||
}
|
||||
return s.repo.UpsertUser(ctx, User{Email: email, DisplayName: "Development Admin", Role: RoleAdmin})
|
||||
}
|
||||
|
||||
func (s *Service) PrincipalForUser(ctx context.Context, userID string) (Principal, error) {
|
||||
user, err := s.repo.GetUserByID(ctx, userID)
|
||||
if err != nil {
|
||||
return Principal{}, err
|
||||
}
|
||||
return principalFromUser(user, "dev", "", "", nil, time.Time{}), nil
|
||||
}
|
||||
|
||||
func (s *Service) UpdateUserRole(ctx context.Context, actor Principal, userID, role string) (User, error) {
|
||||
if !Allows(actor, ScopeAdmin) {
|
||||
return User{}, fmt.Errorf("admin role required")
|
||||
@@ -453,6 +502,20 @@ func (s *Service) createSession(ctx context.Context, user User, ip, userAgent st
|
||||
return principalFromUser(user, "session", session.ID, "", nil, session.ExpiresAt), token, nil
|
||||
}
|
||||
|
||||
func (s *Service) requirePublicSignups(ctx context.Context) error {
|
||||
settings, err := s.repo.GetInstanceSettings(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !settings.SetupComplete {
|
||||
return fmt.Errorf("initial setup is required")
|
||||
}
|
||||
if !settings.SignupsEnabled {
|
||||
return fmt.Errorf("signups are disabled")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func principalFromUser(user User, method, sessionID, apiKeyID string, scopes []Scope, expiresAt time.Time) Principal {
|
||||
return Principal{
|
||||
UserID: user.ID,
|
||||
|
||||
@@ -28,13 +28,23 @@ func setupAuthTestService(t *testing.T) *Service {
|
||||
return service
|
||||
}
|
||||
|
||||
func setupInitialAdmin(t *testing.T, service *Service, signupsEnabled bool) User {
|
||||
t.Helper()
|
||||
|
||||
user, err := service.CompleteInitialSetup(context.Background(), "admin@example.com", "Admin", "correct horse battery staple", signupsEnabled)
|
||||
if err != nil {
|
||||
t.Fatalf("CompleteInitialSetup() error = %v", err)
|
||||
}
|
||||
return user
|
||||
}
|
||||
|
||||
func TestPasswordLoginCreatesValidSession(t *testing.T) {
|
||||
service := setupAuthTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
user, err := service.RegisterPasswordUser(ctx, "Dev@Example.com", "Dev User", "correct horse battery staple", "editor")
|
||||
user, err := service.CompleteInitialSetup(ctx, "Dev@Example.com", "Dev User", "correct horse battery staple", true)
|
||||
if err != nil {
|
||||
t.Fatalf("RegisterPasswordUser() error = %v", err)
|
||||
t.Fatalf("CompleteInitialSetup() error = %v", err)
|
||||
}
|
||||
if user.Email != "dev@example.com" {
|
||||
t.Fatalf("email = %q, want normalized", user.Email)
|
||||
@@ -48,7 +58,7 @@ func TestPasswordLoginCreatesValidSession(t *testing.T) {
|
||||
t.Fatal("expected session token")
|
||||
}
|
||||
if principal.Role != RoleAdmin {
|
||||
t.Fatalf("role = %s, want first registered user to bootstrap as admin", principal.Role)
|
||||
t.Fatalf("role = %s, want initial setup user to be admin", principal.Role)
|
||||
}
|
||||
|
||||
validated, err := service.ValidateSessionToken(ctx, token)
|
||||
@@ -64,10 +74,7 @@ func TestAPIKeyUsesShownOnceBearerToken(t *testing.T) {
|
||||
service := setupAuthTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
user, err := service.RegisterPasswordUser(ctx, "admin@example.com", "Admin", "correct horse battery staple", "admin")
|
||||
if err != nil {
|
||||
t.Fatalf("RegisterPasswordUser() error = %v", err)
|
||||
}
|
||||
user := setupInitialAdmin(t, service, true)
|
||||
expires := time.Now().UTC().Add(time.Hour)
|
||||
created, err := service.CreateAPIKey(ctx, user.ID, "CLI", []Scope{ScopeDocsRead, ScopeSyncWrite}, &expires)
|
||||
if err != nil {
|
||||
@@ -99,10 +106,7 @@ func TestDeviceFlowMintsAPIKeyAfterApproval(t *testing.T) {
|
||||
service := setupAuthTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
user, err := service.RegisterPasswordUser(ctx, "admin@example.com", "Admin", "correct horse battery staple", "admin")
|
||||
if err != nil {
|
||||
t.Fatalf("RegisterPasswordUser() error = %v", err)
|
||||
}
|
||||
user := setupInitialAdmin(t, service, true)
|
||||
start, err := service.StartDeviceFlow(ctx, "Laptop", []Scope{ScopeSyncRead})
|
||||
if err != nil {
|
||||
t.Fatalf("StartDeviceFlow() error = %v", err)
|
||||
@@ -132,10 +136,7 @@ func TestPasswordChangeInvalidatesOldPassword(t *testing.T) {
|
||||
service := setupAuthTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
user, err := service.RegisterPasswordUser(ctx, "admin@example.com", "Admin", "correct horse battery staple", "admin")
|
||||
if err != nil {
|
||||
t.Fatalf("RegisterPasswordUser() error = %v", err)
|
||||
}
|
||||
user := setupInitialAdmin(t, service, true)
|
||||
principal := principalFromUser(user, "session", "sess:test", "", nil, time.Now().Add(time.Hour))
|
||||
if err := service.ChangePassword(ctx, principal, "correct horse battery staple", "new correct horse battery staple"); err != nil {
|
||||
t.Fatalf("ChangePassword() error = %v", err)
|
||||
@@ -152,10 +153,7 @@ func TestCannotDemoteOrDeleteLastAdmin(t *testing.T) {
|
||||
service := setupAuthTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
user, err := service.RegisterPasswordUser(ctx, "admin@example.com", "Admin", "correct horse battery staple", "admin")
|
||||
if err != nil {
|
||||
t.Fatalf("RegisterPasswordUser() error = %v", err)
|
||||
}
|
||||
user := setupInitialAdmin(t, service, true)
|
||||
principal := principalFromUser(user, "session", "sess:test", "", nil, time.Now().Add(time.Hour))
|
||||
if _, err := service.UpdateUserRole(ctx, principal, user.ID, string(RoleEditor)); err == nil {
|
||||
t.Fatal("expected demoting last admin to fail")
|
||||
@@ -169,6 +167,7 @@ func TestPublicRegistrationCannotAttachCredentialsToExistingUser(t *testing.T) {
|
||||
service := setupAuthTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
setupInitialAdmin(t, service, true)
|
||||
if _, err := service.RegisterPasswordUser(ctx, "dev@example.com", "Dev", "correct horse battery staple", "admin"); err != nil {
|
||||
t.Fatalf("RegisterPasswordUser() error = %v", err)
|
||||
}
|
||||
@@ -179,3 +178,32 @@ func TestPublicRegistrationCannotAttachCredentialsToExistingUser(t *testing.T) {
|
||||
t.Fatal("expected public passkey registration for existing account to fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitialSetupCanDisablePublicRegistration(t *testing.T) {
|
||||
service := setupAuthTestService(t)
|
||||
ctx := context.Background()
|
||||
admin := setupInitialAdmin(t, service, false)
|
||||
|
||||
if admin.Role != RoleAdmin {
|
||||
t.Fatalf("initial role = %s, want admin", admin.Role)
|
||||
}
|
||||
if _, err := service.RegisterPasswordUser(ctx, "viewer@example.com", "Viewer", "correct horse battery staple", "viewer"); err == nil || err.Error() != "signups are disabled" {
|
||||
t.Fatalf("RegisterPasswordUser() error = %v, want signups are disabled", err)
|
||||
}
|
||||
|
||||
principal := principalFromUser(admin, "session", "sess:test", "", nil, time.Now().Add(time.Hour))
|
||||
settings, err := service.UpdateSignupsEnabled(ctx, principal, true)
|
||||
if err != nil {
|
||||
t.Fatalf("UpdateSignupsEnabled() error = %v", err)
|
||||
}
|
||||
if !settings.SignupsEnabled {
|
||||
t.Fatal("expected signups to be enabled")
|
||||
}
|
||||
viewer, err := service.RegisterPasswordUser(ctx, "viewer@example.com", "Viewer", "correct horse battery staple", "admin")
|
||||
if err != nil {
|
||||
t.Fatalf("RegisterPasswordUser() after enabling signups error = %v", err)
|
||||
}
|
||||
if viewer.Role != RoleViewer {
|
||||
t.Fatalf("public signup role = %s, want viewer", viewer.Role)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,6 +92,11 @@ type CreatedAPIKey struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
type InstanceSettings struct {
|
||||
SetupComplete bool `json:"setupComplete"`
|
||||
SignupsEnabled bool `json:"signupsEnabled"`
|
||||
}
|
||||
|
||||
type DeviceCode struct {
|
||||
ID string
|
||||
UserID string
|
||||
|
||||
@@ -12,10 +12,10 @@ type Config struct {
|
||||
Server ServerConfig `json:"server"`
|
||||
Database DatabaseConfig `json:"database"`
|
||||
Content ContentConfig `json:"content"`
|
||||
Web WebConfig `json:"web"`
|
||||
Auth AuthConfig `json:"auth"`
|
||||
Email EmailConfig `json:"email"`
|
||||
LogLevel string `json:"logLevel"`
|
||||
DevMode bool `json:"devMode"`
|
||||
}
|
||||
|
||||
type ServerConfig struct {
|
||||
@@ -33,11 +33,6 @@ type ContentConfig struct {
|
||||
StoreDir string `json:"storeDir"`
|
||||
}
|
||||
|
||||
type WebConfig struct {
|
||||
DistDir string `json:"distDir"`
|
||||
DevViteURL string `json:"devViteUrl"`
|
||||
}
|
||||
|
||||
type AuthConfig struct {
|
||||
PublicOrigin string `json:"publicOrigin"`
|
||||
}
|
||||
@@ -60,10 +55,6 @@ func Default() Config {
|
||||
SourceDir: filepath.Join("..", "..", "content"),
|
||||
StoreDir: filepath.Join("..", "..", "data", "files"),
|
||||
},
|
||||
Web: WebConfig{
|
||||
DistDir: filepath.Join("..", "web", "dist"),
|
||||
DevViteURL: os.Getenv("CAIRNQUIRE_DEV_VITE_URL"),
|
||||
},
|
||||
Auth: AuthConfig{
|
||||
PublicOrigin: "http://localhost:8080",
|
||||
},
|
||||
@@ -91,8 +82,6 @@ func Load() (Config, error) {
|
||||
overrideString(&cfg.Database.AuthToken, "CAIRNQUIRE_DATABASE_AUTH_TOKEN")
|
||||
overrideString(&cfg.Content.SourceDir, "CAIRNQUIRE_CONTENT_SOURCE_DIR")
|
||||
overrideString(&cfg.Content.StoreDir, "CAIRNQUIRE_CONTENT_STORE_DIR")
|
||||
overrideString(&cfg.Web.DistDir, "CAIRNQUIRE_WEB_DIST_DIR")
|
||||
overrideString(&cfg.Web.DevViteURL, "CAIRNQUIRE_DEV_VITE_URL")
|
||||
overrideString(&cfg.Auth.PublicOrigin, "CAIRNQUIRE_PUBLIC_ORIGIN")
|
||||
overrideString(&cfg.Email.SMTPHost, "CAIRNQUIRE_EMAIL_SMTP_HOST")
|
||||
if port := os.Getenv("CAIRNQUIRE_EMAIL_SMTP_PORT"); port != "" {
|
||||
@@ -102,6 +91,13 @@ func Load() (Config, error) {
|
||||
}
|
||||
overrideString(&cfg.Email.From, "CAIRNQUIRE_EMAIL_FROM")
|
||||
overrideString(&cfg.LogLevel, "CAIRNQUIRE_LOG_LEVEL")
|
||||
if devMode := os.Getenv("CAIRNQUIRE_DEV_MODE"); devMode != "" {
|
||||
parsed, err := strconv.ParseBool(devMode)
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("parse CAIRNQUIRE_DEV_MODE: %w", err)
|
||||
}
|
||||
cfg.DevMode = parsed
|
||||
}
|
||||
|
||||
if cfg.Server.Addr == "" {
|
||||
return Config{}, fmt.Errorf("server.addr must not be empty")
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
DROP TABLE IF EXISTS instance_settings;
|
||||
@@ -0,0 +1,13 @@
|
||||
CREATE TABLE IF NOT EXISTS instance_settings (
|
||||
id INTEGER PRIMARY KEY CHECK(id = 1),
|
||||
setup_completed_at TEXT,
|
||||
signups_enabled INTEGER NOT NULL DEFAULT 0 CHECK(signups_enabled IN (0, 1)),
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
INSERT OR IGNORE INTO instance_settings (id, setup_completed_at, signups_enabled, updated_at)
|
||||
SELECT
|
||||
1,
|
||||
CASE WHEN EXISTS(SELECT 1 FROM users) THEN datetime('now') ELSE NULL END,
|
||||
CASE WHEN EXISTS(SELECT 1 FROM users) THEN 1 ELSE 0 END,
|
||||
datetime('now');
|
||||
@@ -271,6 +271,33 @@ func (r *Repository) GetAttachment(ctx context.Context, hash string) (*Attachmen
|
||||
return &record, nil
|
||||
}
|
||||
|
||||
func (r *Repository) ListAttachments(ctx context.Context) ([]AttachmentRecord, error) {
|
||||
rows, err := r.db.QueryContext(ctx, `
|
||||
SELECT hash, original_name, content_type, size_bytes, created_at
|
||||
FROM attachments
|
||||
ORDER BY created_at DESC
|
||||
`)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list attachments: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var attachments []AttachmentRecord
|
||||
for rows.Next() {
|
||||
var record AttachmentRecord
|
||||
var created string
|
||||
if err := rows.Scan(&record.Hash, &record.OriginalName, &record.ContentType, &record.SizeBytes, &created); err != nil {
|
||||
return nil, fmt.Errorf("scan attachment: %w", err)
|
||||
}
|
||||
record.CreatedAt, err = time.Parse(time.RFC3339, created)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse attachment created_at: %w", err)
|
||||
}
|
||||
attachments = append(attachments, record)
|
||||
}
|
||||
return attachments, rows.Err()
|
||||
}
|
||||
|
||||
type SearchResult struct {
|
||||
Path string `json:"path"`
|
||||
Title string `json:"title"`
|
||||
|
||||
@@ -15,6 +15,10 @@ type adminUserInput struct {
|
||||
Role string `json:"role"`
|
||||
}
|
||||
|
||||
type adminSettingsInput struct {
|
||||
SignupsEnabled bool `json:"signupsEnabled"`
|
||||
}
|
||||
|
||||
func (s *Server) handleAdminLogin(w http.ResponseWriter, r *http.Request) {
|
||||
var input adminUserInput
|
||||
if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
|
||||
@@ -95,7 +99,6 @@ func (s *Server) handleAdminWorkspace(w http.ResponseWriter, r *http.Request) {
|
||||
"databasePath": s.config.Database.Path,
|
||||
"documentCount": len(documents),
|
||||
"userCount": len(users),
|
||||
"webDistDir": s.config.Web.DistDir,
|
||||
},
|
||||
"documents": documents,
|
||||
})
|
||||
@@ -113,6 +116,30 @@ func (s *Server) handleAdminWorkspaceSync(w http.ResponseWriter, r *http.Request
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleAdminSettings(w http.ResponseWriter, r *http.Request) {
|
||||
settings, err := s.auth.GetInstanceSettings(r.Context())
|
||||
if err != nil {
|
||||
writeJSONWithStatus(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"settings": settings})
|
||||
}
|
||||
|
||||
func (s *Server) handleAdminSettingsUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
principal, _ := requirePrincipal(r)
|
||||
var input adminSettingsInput
|
||||
if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
|
||||
writeJSONWithStatus(w, http.StatusBadRequest, map[string]string{"error": "invalid json"})
|
||||
return
|
||||
}
|
||||
settings, err := s.auth.UpdateSignupsEnabled(r.Context(), principal, input.SignupsEnabled)
|
||||
if err != nil {
|
||||
writeJSONWithStatus(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"settings": settings})
|
||||
}
|
||||
|
||||
func (s *Server) normalizeAdminUserInput(input adminUserInput) (docs.UserRecord, bool) {
|
||||
email := strings.TrimSpace(strings.ToLower(input.Email))
|
||||
if email == "" {
|
||||
|
||||
@@ -32,6 +32,10 @@ type apiTestServer struct {
|
||||
}
|
||||
|
||||
func newAPITestServer(t *testing.T) *apiTestServer {
|
||||
return newAPITestServerWithSetup(t, true)
|
||||
}
|
||||
|
||||
func newAPITestServerWithSetup(t *testing.T, setupComplete bool) *apiTestServer {
|
||||
t.Helper()
|
||||
|
||||
ctx := context.Background()
|
||||
@@ -69,9 +73,12 @@ func newAPITestServer(t *testing.T) *apiTestServer {
|
||||
if err != nil {
|
||||
t.Fatalf("create auth service: %v", err)
|
||||
}
|
||||
user, err := authService.RegisterPasswordUser(ctx, "editor@example.com", "Editor", "very secure password", string(auth.RoleEditor))
|
||||
if err != nil {
|
||||
t.Fatalf("create test user: %v", err)
|
||||
var user auth.User
|
||||
if setupComplete {
|
||||
user, err = authService.CompleteInitialSetup(ctx, "editor@example.com", "Editor", "very secure password", false)
|
||||
if err != nil {
|
||||
t.Fatalf("create test user: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
syncRepo := sync.NewRepository(db.SQL())
|
||||
@@ -81,7 +88,6 @@ func newAPITestServer(t *testing.T) *apiTestServer {
|
||||
SourceDir: sourceDir,
|
||||
StoreDir: storeDir,
|
||||
},
|
||||
Web: config.WebConfig{DistDir: filepath.Join(root, "web-dist")},
|
||||
Auth: config.AuthConfig{PublicOrigin: "http://localhost:8080"},
|
||||
},
|
||||
Logger: logger,
|
||||
@@ -106,6 +112,54 @@ func newAPITestServer(t *testing.T) *apiTestServer {
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitialSetupWizardCreatesAdminAndPersistsSignupPolicy(t *testing.T) {
|
||||
server := newAPITestServerWithSetup(t, false)
|
||||
|
||||
index := httptest.NewRecorder()
|
||||
server.handler.ServeHTTP(index, httptest.NewRequest(http.MethodGet, "/", nil))
|
||||
if index.Code != http.StatusSeeOther || index.Header().Get("Location") != "/setup" {
|
||||
t.Fatalf("initial index response = %d %q, want redirect to /setup", index.Code, index.Header().Get("Location"))
|
||||
}
|
||||
|
||||
setupPage := httptest.NewRecorder()
|
||||
server.handler.ServeHTTP(setupPage, httptest.NewRequest(http.MethodGet, "/setup", nil))
|
||||
if setupPage.Code != http.StatusOK || !bytes.Contains(setupPage.Body.Bytes(), []byte("Initial setup")) {
|
||||
t.Fatalf("setup page response = %d %q", setupPage.Code, setupPage.Body.String())
|
||||
}
|
||||
|
||||
setup := httptest.NewRecorder()
|
||||
server.handler.ServeHTTP(setup, jsonRequest(http.MethodPost, "/api/setup", map[string]any{
|
||||
"email": "owner@example.com",
|
||||
"displayName": "Owner",
|
||||
"password": "correct horse battery staple",
|
||||
"signupsEnabled": false,
|
||||
}))
|
||||
if setup.Code != http.StatusCreated {
|
||||
t.Fatalf("setup status = %d, want %d; body=%s", setup.Code, http.StatusCreated, setup.Body.String())
|
||||
}
|
||||
if len(setup.Result().Cookies()) == 0 {
|
||||
t.Fatal("expected setup to create a browser session")
|
||||
}
|
||||
|
||||
settings, err := server.auth.GetInstanceSettings(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("GetInstanceSettings() error = %v", err)
|
||||
}
|
||||
if !settings.SetupComplete || settings.SignupsEnabled {
|
||||
t.Fatalf("settings = %#v, want setup complete with signups disabled", settings)
|
||||
}
|
||||
|
||||
register := httptest.NewRecorder()
|
||||
server.handler.ServeHTTP(register, jsonRequest(http.MethodPost, "/api/auth/register/password", map[string]any{
|
||||
"email": "viewer@example.com",
|
||||
"displayName": "Viewer",
|
||||
"password": "correct horse battery staple",
|
||||
}))
|
||||
if register.Code != http.StatusBadRequest || !bytes.Contains(register.Body.Bytes(), []byte("signups are disabled")) {
|
||||
t.Fatalf("register response = %d %q, want disabled signup error", register.Code, register.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func (s *apiTestServer) token(t *testing.T, scopes ...auth.Scope) string {
|
||||
t.Helper()
|
||||
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
package httpserver
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func (s *Server) appFileServer() http.Handler {
|
||||
if s.config.Web.DevViteURL != "" {
|
||||
viteURL, err := url.Parse(s.config.Web.DevViteURL)
|
||||
if err == nil {
|
||||
proxy := httputil.NewSingleHostReverseProxy(viteURL)
|
||||
originalDirector := proxy.Director
|
||||
proxy.Director = func(req *http.Request) {
|
||||
originalDirector(req)
|
||||
req.Host = viteURL.Host
|
||||
// Add back the /app/ prefix that was stripped by http.StripPrefix
|
||||
req.URL.Path = "/app" + req.URL.Path
|
||||
}
|
||||
return proxy
|
||||
}
|
||||
}
|
||||
|
||||
files := http.FileServer(http.Dir(s.config.Web.DistDir))
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
cleanPath := filepath.Clean(strings.TrimPrefix(r.URL.Path, "/"))
|
||||
if cleanPath == "." {
|
||||
cleanPath = "index.html"
|
||||
}
|
||||
|
||||
target := filepath.Join(s.config.Web.DistDir, cleanPath)
|
||||
if info, err := os.Stat(target); err == nil && !info.IsDir() {
|
||||
files.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
http.ServeFile(w, r, filepath.Join(s.config.Web.DistDir, "index.html"))
|
||||
})
|
||||
}
|
||||
@@ -24,6 +24,13 @@ type passwordLoginRequest struct {
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
type initialSetupRequest struct {
|
||||
Email string `json:"email"`
|
||||
DisplayName string `json:"displayName"`
|
||||
Password string `json:"password"`
|
||||
SignupsEnabled bool `json:"signupsEnabled"`
|
||||
}
|
||||
|
||||
type passkeyBeginRequest struct {
|
||||
Email string `json:"email"`
|
||||
DisplayName string `json:"displayName"`
|
||||
@@ -67,17 +74,61 @@ func (s *Server) handleLoginPage(w http.ResponseWriter, r *http.Request) {
|
||||
if !strings.HasPrefix(nextPath, "/") || strings.HasPrefix(nextPath, "//") {
|
||||
nextPath = "/account"
|
||||
}
|
||||
settings, err := s.auth.GetInstanceSettings(r.Context())
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "load registration settings")
|
||||
return
|
||||
}
|
||||
s.renderTemplate(w, http.StatusOK, "login.gohtml", layoutData{
|
||||
Title: "Sign in",
|
||||
WebEnabled: s.webEnabled,
|
||||
BodyClass: "page-auth",
|
||||
BodyTemplate: "login_content",
|
||||
Data: struct {
|
||||
Next string
|
||||
}{Next: nextPath},
|
||||
Next string
|
||||
SignupsEnabled bool
|
||||
}{Next: nextPath, SignupsEnabled: settings.SignupsEnabled},
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleSetupPage(w http.ResponseWriter, r *http.Request) {
|
||||
settings, err := s.auth.GetInstanceSettings(r.Context())
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "load initial setup state")
|
||||
return
|
||||
}
|
||||
if settings.SetupComplete {
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
s.renderTemplate(w, http.StatusOK, "setup.gohtml", layoutData{
|
||||
Title: "Initial setup",
|
||||
BodyClass: "page-auth",
|
||||
BodyTemplate: "setup_content",
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleSetup(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.allowAuthAttempt(w, r) {
|
||||
return
|
||||
}
|
||||
var req initialSetupRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeJSONWithStatus(w, http.StatusBadRequest, map[string]string{"error": "invalid json"})
|
||||
return
|
||||
}
|
||||
if _, err := s.auth.CompleteInitialSetup(r.Context(), req.Email, req.DisplayName, req.Password, req.SignupsEnabled); err != nil {
|
||||
writeJSONWithStatus(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
principal, token, err := s.auth.LoginPassword(r.Context(), req.Email, req.Password, requestIP(r), r.UserAgent())
|
||||
if err != nil {
|
||||
writeJSONWithStatus(w, http.StatusInternalServerError, map[string]string{"error": "initial admin created; sign in to continue"})
|
||||
return
|
||||
}
|
||||
setSessionCookie(w, r, token, principal.ExpiresAt)
|
||||
writeJSONWithStatus(w, http.StatusCreated, map[string]any{"principal": principal})
|
||||
}
|
||||
|
||||
func (s *Server) handleAccountPage(w http.ResponseWriter, r *http.Request) {
|
||||
principal, ok := requirePrincipal(r)
|
||||
if !ok {
|
||||
@@ -86,7 +137,6 @@ func (s *Server) handleAccountPage(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
s.renderTemplate(w, http.StatusOK, "account.gohtml", layoutData{
|
||||
Title: "Account",
|
||||
WebEnabled: s.webEnabled,
|
||||
BodyClass: "page-account",
|
||||
BodyTemplate: "account_content",
|
||||
Data: principal,
|
||||
@@ -377,7 +427,6 @@ func (s *Server) handleDeviceVerifyPage(w http.ResponseWriter, r *http.Request)
|
||||
userCode := strings.TrimSpace(r.URL.Query().Get("user_code"))
|
||||
s.renderTemplate(w, http.StatusOK, "device_verify.gohtml", layoutData{
|
||||
Title: "Approve device",
|
||||
WebEnabled: s.webEnabled,
|
||||
BodyClass: "page-auth",
|
||||
BodyTemplate: "device_verify_content",
|
||||
Data: struct {
|
||||
|
||||
@@ -23,7 +23,6 @@ import (
|
||||
|
||||
type layoutData struct {
|
||||
Title string
|
||||
WebEnabled bool
|
||||
BodyClass string
|
||||
BodyTemplate string
|
||||
Data any
|
||||
@@ -98,7 +97,6 @@ func (s *Server) handleIndex(w http.ResponseWriter, r *http.Request) {
|
||||
activeFolder := strings.Trim(r.URL.Query().Get("folder"), "/")
|
||||
s.renderTemplate(w, http.StatusOK, "index.gohtml", layoutData{
|
||||
Title: "Cairnquire",
|
||||
WebEnabled: s.webEnabled,
|
||||
BodyClass: "page-index",
|
||||
BodyTemplate: "index_content",
|
||||
Data: indexData{
|
||||
@@ -118,7 +116,6 @@ func (s *Server) handleSearchPage(w http.ResponseWriter, r *http.Request, query
|
||||
|
||||
s.renderTemplate(w, http.StatusOK, "search.gohtml", layoutData{
|
||||
Title: "Search: " + query,
|
||||
WebEnabled: s.webEnabled,
|
||||
BodyClass: "page-search",
|
||||
BodyTemplate: "search_content",
|
||||
Data: struct {
|
||||
@@ -225,7 +222,6 @@ func (s *Server) renderDocumentEditor(w http.ResponseWriter, r *http.Request, pa
|
||||
|
||||
s.renderTemplate(w, http.StatusOK, "document_edit.gohtml", layoutData{
|
||||
Title: "Edit: " + page.Title,
|
||||
WebEnabled: s.webEnabled,
|
||||
BodyClass: "page-document-edit",
|
||||
BodyTemplate: "document_edit_content",
|
||||
Data: documentEditData{
|
||||
@@ -259,7 +255,6 @@ func (s *Server) renderDocumentPage(w http.ResponseWriter, r *http.Request, page
|
||||
|
||||
s.renderTemplate(w, http.StatusOK, "document.gohtml", layoutData{
|
||||
Title: page.Title,
|
||||
WebEnabled: s.webEnabled,
|
||||
BodyClass: "page-document",
|
||||
BodyTemplate: "document_content",
|
||||
Data: documentData{
|
||||
@@ -403,6 +398,15 @@ func (s *Server) handleAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write(content)
|
||||
}
|
||||
|
||||
func (s *Server) handleAttachmentsList(w http.ResponseWriter, r *http.Request) {
|
||||
attachments, err := s.repository.ListAttachments(r.Context())
|
||||
if err != nil {
|
||||
writeJSONWithStatus(w, http.StatusInternalServerError, map[string]string{"error": "list attachments"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"attachments": attachments})
|
||||
}
|
||||
|
||||
func (s *Server) renderTemplate(w http.ResponseWriter, status int, name string, data layoutData) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
@@ -414,7 +418,6 @@ func (s *Server) renderTemplate(w http.ResponseWriter, status int, name string,
|
||||
func (s *Server) renderError(w http.ResponseWriter, r *http.Request, status int, message string) {
|
||||
s.renderTemplate(w, status, "error.gohtml", layoutData{
|
||||
Title: http.StatusText(status),
|
||||
WebEnabled: s.webEnabled,
|
||||
BodyClass: "page-error",
|
||||
BodyTemplate: "error_content",
|
||||
Data: errorData{
|
||||
|
||||
@@ -76,6 +76,33 @@ func (s *Server) authMiddleware(next http.Handler) http.Handler {
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) setupMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
settings, err := s.auth.GetInstanceSettings(r.Context())
|
||||
if err != nil {
|
||||
writeJSONWithStatus(w, http.StatusInternalServerError, map[string]string{"error": "lookup initial setup state"})
|
||||
return
|
||||
}
|
||||
if settings.SetupComplete || isSetupAllowedPath(r.URL.Path) {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
if r.Method == http.MethodGet && !strings.HasPrefix(r.URL.Path, "/api/") {
|
||||
http.Redirect(w, r, "/setup", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
writeJSONWithStatus(w, http.StatusServiceUnavailable, map[string]string{"error": "initial setup is required"})
|
||||
})
|
||||
}
|
||||
|
||||
func isSetupAllowedPath(path string) bool {
|
||||
return path == "/setup" ||
|
||||
path == "/api/setup" ||
|
||||
path == "/health" ||
|
||||
path == "/sw.js" ||
|
||||
strings.HasPrefix(path, "/static/")
|
||||
}
|
||||
|
||||
func (s *Server) authenticateRequest(r *http.Request) (auth.Principal, bool) {
|
||||
if header := r.Header.Get("Authorization"); strings.HasPrefix(header, "Bearer ") {
|
||||
principal, err := s.auth.ValidateBearerToken(r.Context(), strings.TrimSpace(strings.TrimPrefix(header, "Bearer ")))
|
||||
@@ -87,7 +114,11 @@ func (s *Server) authenticateRequest(r *http.Request) (auth.Principal, bool) {
|
||||
}
|
||||
cookie, err := r.Cookie(auth.SessionCookieName)
|
||||
if err != nil || cookie.Value == "" {
|
||||
return auth.Principal{}, false
|
||||
if s.devUserID == "" {
|
||||
return auth.Principal{}, false
|
||||
}
|
||||
principal, err := s.auth.PrincipalForUser(r.Context(), s.devUserID)
|
||||
return principal, err == nil
|
||||
}
|
||||
principal, err := s.auth.ValidateSessionToken(r.Context(), cookie.Value)
|
||||
if err != nil {
|
||||
@@ -120,6 +151,8 @@ func requiredScopeForPath(r *http.Request) (auth.Scope, bool) {
|
||||
return auth.ScopeDocsWrite, true
|
||||
case strings.HasPrefix(path, "/api/uploads"):
|
||||
return auth.ScopeDocsWrite, true
|
||||
case path == "/api/attachments":
|
||||
return auth.ScopeDocsRead, true
|
||||
case strings.HasPrefix(path, "/api/sync/"):
|
||||
if method == http.MethodPost {
|
||||
return auth.ScopeSyncWrite, true
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
package httpserver
|
||||
|
||||
import (
|
||||
"context"
|
||||
"embed"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -50,7 +51,7 @@ type Server struct {
|
||||
collaboration *collaboration.Service
|
||||
authLimiter *rateLimiter
|
||||
templates *template.Template
|
||||
webEnabled bool
|
||||
devUserID string
|
||||
}
|
||||
|
||||
func New(deps Dependencies) (http.Handler, error) {
|
||||
@@ -81,8 +82,13 @@ func New(deps Dependencies) (http.Handler, error) {
|
||||
templates: templates,
|
||||
}
|
||||
|
||||
if _, err := os.Stat(deps.Config.Web.DistDir); err == nil {
|
||||
server.webEnabled = true
|
||||
if deps.Config.DevMode {
|
||||
devUser, err := deps.Auth.EnsureDevUser(context.Background())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ensure dev user: %w", err)
|
||||
}
|
||||
server.devUserID = devUser.ID
|
||||
deps.Logger.Info("dev mode enabled", "dev_user_id", devUser.ID)
|
||||
}
|
||||
|
||||
router := chi.NewRouter()
|
||||
@@ -92,9 +98,11 @@ func New(deps Dependencies) (http.Handler, error) {
|
||||
router.Use(server.timeoutExceptWebSocket(30 * time.Second))
|
||||
router.Use(server.requestLogger)
|
||||
router.Use(server.securityHeaders)
|
||||
router.Use(server.setupMiddleware)
|
||||
router.Use(server.authMiddleware)
|
||||
|
||||
router.Get("/", server.handleIndex)
|
||||
router.Get("/setup", server.handleSetupPage)
|
||||
router.Get("/login", server.handleLoginPage)
|
||||
router.Get("/account", server.handleAccountPage)
|
||||
router.Get("/device/verify", server.handleDeviceVerifyPage)
|
||||
@@ -102,6 +110,7 @@ func New(deps Dependencies) (http.Handler, error) {
|
||||
router.Get("/sw.js", server.handleServiceWorker)
|
||||
router.Get("/ws", server.handleWebSocket)
|
||||
router.Get("/api/auth/me", server.handleAuthMe)
|
||||
router.Post("/api/setup", server.handleSetup)
|
||||
router.Post("/api/auth/register/password", server.handlePasswordRegister)
|
||||
router.Post("/api/auth/login/password", server.handlePasswordLogin)
|
||||
router.Post("/api/auth/logout", server.handleLogout)
|
||||
@@ -123,6 +132,8 @@ func New(deps Dependencies) (http.Handler, error) {
|
||||
router.Post("/api/admin/users", server.handleAdminCreateUser)
|
||||
router.Patch("/api/admin/users/{id}/role", server.handleAdminUpdateUserRole)
|
||||
router.Get("/api/admin/auth-users", server.handleAdminAuthUsers)
|
||||
router.Get("/api/admin/settings", server.handleAdminSettings)
|
||||
router.Patch("/api/admin/settings", server.handleAdminSettingsUpdate)
|
||||
router.Get("/api/admin/workspace", server.handleAdminWorkspace)
|
||||
router.Post("/api/admin/workspace/sync", server.handleAdminWorkspaceSync)
|
||||
router.Get("/docs", server.handleDocsIndex)
|
||||
@@ -131,6 +142,7 @@ func New(deps Dependencies) (http.Handler, error) {
|
||||
router.Post("/api/documents/*", server.handleDocumentSave)
|
||||
router.Get("/api/search", server.handleSearch)
|
||||
router.Post("/api/uploads", server.handleUpload)
|
||||
router.Get("/api/attachments", server.handleAttachmentsList)
|
||||
router.Get("/attachments/{hash}", server.handleAttachment)
|
||||
|
||||
// Collaboration endpoints
|
||||
@@ -155,18 +167,9 @@ func New(deps Dependencies) (http.Handler, error) {
|
||||
|
||||
router.Handle("/static/*", http.StripPrefix("/static/", http.FileServer(mustSub("static"))))
|
||||
|
||||
if server.webEnabled {
|
||||
router.Get("/app", server.handleAppRedirect)
|
||||
router.Handle("/app/*", http.StripPrefix("/app/", server.appFileServer()))
|
||||
}
|
||||
|
||||
return router, nil
|
||||
}
|
||||
|
||||
func (s *Server) handleAppRedirect(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, "/app/", http.StatusMovedPermanently)
|
||||
}
|
||||
|
||||
func mustSub(path string) http.FileSystem {
|
||||
sub, err := fsSub(path)
|
||||
if err != nil {
|
||||
|
||||
@@ -78,6 +78,22 @@
|
||||
|
||||
const formJSON = (form) => Object.fromEntries(new FormData(form).entries());
|
||||
|
||||
document.querySelector("[data-initial-setup]")?.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
const form = event.currentTarget;
|
||||
try {
|
||||
await postJSON("/api/setup", {
|
||||
email: form.elements.email.value,
|
||||
displayName: form.elements.displayName.value,
|
||||
password: form.elements.password.value,
|
||||
signupsEnabled: form.elements.signupsEnabled.checked,
|
||||
});
|
||||
window.location.href = "/account";
|
||||
} catch (error) {
|
||||
setStatus("[data-setup-status]", error.message, true);
|
||||
}
|
||||
});
|
||||
|
||||
const base64URLToBuffer = (value) => {
|
||||
const padded = value.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(value.length / 4) * 4, "=");
|
||||
const binary = atob(padded);
|
||||
@@ -350,6 +366,29 @@
|
||||
);
|
||||
};
|
||||
|
||||
const loadAdminSettings = async () => {
|
||||
const section = document.querySelector("[data-admin-settings-section]");
|
||||
const form = document.querySelector("[data-admin-settings]");
|
||||
if (!section || !form) return;
|
||||
const me = await fetch("/api/auth/me", { credentials: "same-origin" }).then((response) => response.json()).catch(() => null);
|
||||
if (me?.principal?.role !== "admin") return;
|
||||
section.hidden = false;
|
||||
const data = await fetch("/api/admin/settings", { credentials: "same-origin" }).then((response) => response.json());
|
||||
form.elements.signupsEnabled.checked = Boolean(data.settings?.signupsEnabled);
|
||||
};
|
||||
|
||||
document.querySelector("[data-admin-settings]")?.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
try {
|
||||
const form = event.currentTarget;
|
||||
await postJSON("/api/admin/settings", { signupsEnabled: form.elements.signupsEnabled.checked }, { method: "PATCH" });
|
||||
setStatus("[data-admin-settings-status]", "Registration setting saved.");
|
||||
} catch (error) {
|
||||
setStatus("[data-admin-settings-status]", error.message, true);
|
||||
}
|
||||
});
|
||||
|
||||
loadTokens().catch(() => {});
|
||||
loadAdminUsers().catch(() => {});
|
||||
loadAdminSettings().catch(() => {});
|
||||
})();
|
||||
|
||||
@@ -240,6 +240,16 @@ code {
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.auth-form .auth-choice {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.55rem;
|
||||
}
|
||||
|
||||
.auth-choice input {
|
||||
width: auto;
|
||||
}
|
||||
|
||||
.auth-form input,
|
||||
.auth-form select,
|
||||
.user-row select {
|
||||
@@ -1817,4 +1827,3 @@ code {
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -56,6 +56,18 @@
|
||||
<p class="form-status" data-admin-users-status></p>
|
||||
</section>
|
||||
|
||||
<section class="account-section" data-admin-settings-section hidden>
|
||||
<h2>Registration</h2>
|
||||
<form class="auth-form" data-admin-settings>
|
||||
<label class="auth-choice">
|
||||
<input type="checkbox" name="signupsEnabled" />
|
||||
Allow visitors to create accounts
|
||||
</label>
|
||||
<button type="submit">Save registration setting</button>
|
||||
<p class="form-status" data-admin-settings-status></p>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section class="account-section account-section--danger">
|
||||
<h2>Delete Account</h2>
|
||||
<form class="auth-form" data-account-delete>
|
||||
|
||||
@@ -50,6 +50,8 @@
|
||||
{{ template "search_content" .Data }}
|
||||
{{ else if eq .BodyTemplate "login_content" }}
|
||||
{{ template "login_content" .Data }}
|
||||
{{ else if eq .BodyTemplate "setup_content" }}
|
||||
{{ template "setup_content" .Data }}
|
||||
{{ else if eq .BodyTemplate "account_content" }}
|
||||
{{ template "account_content" .Data }}
|
||||
{{ else if eq .BodyTemplate "device_verify_content" }}
|
||||
|
||||
@@ -43,12 +43,12 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="auth-register-cta">
|
||||
{{ if .SignupsEnabled }}<div class="auth-register-cta">
|
||||
<button type="button" class="btn-cta" data-register-toggle>Create an Account</button>
|
||||
</div>
|
||||
</div>{{ end }}
|
||||
</div>
|
||||
|
||||
<div class="auth-register-panel" data-register-panel hidden>
|
||||
{{ if .SignupsEnabled }}<div class="auth-register-panel" data-register-panel hidden>
|
||||
<div class="auth-tabs">
|
||||
<div class="auth-tab-list" role="tablist">
|
||||
<button type="button" class="auth-tab is-active" role="tab" aria-selected="true" data-tab="passkey-register">Passkey</button>
|
||||
@@ -93,7 +93,7 @@
|
||||
<div class="auth-register-cancel">
|
||||
<button type="button" class="btn-secondary" data-register-cancel>Cancel — Back to Log In</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>{{ end }}
|
||||
</div>
|
||||
</section>
|
||||
{{ end }}
|
||||
|
||||
34
apps/server/internal/httpserver/templates/setup.gohtml
Normal file
34
apps/server/internal/httpserver/templates/setup.gohtml
Normal file
@@ -0,0 +1,34 @@
|
||||
{{ define "setup.gohtml" }}{{ template "base" . }}{{ end }}
|
||||
|
||||
{{ define "setup_content" }}
|
||||
<section class="auth-shell">
|
||||
<div class="auth-panel">
|
||||
<div class="auth-panel__header">
|
||||
<p class="eyebrow">Cairnquire</p>
|
||||
<h1>Initial setup</h1>
|
||||
<p class="auth-note">Create the first administrator account and choose whether visitors can register their own accounts.</p>
|
||||
</div>
|
||||
|
||||
<form class="auth-form" data-initial-setup>
|
||||
<label>
|
||||
Admin email
|
||||
<input type="email" name="email" autocomplete="email" required />
|
||||
</label>
|
||||
<label>
|
||||
Display name
|
||||
<input type="text" name="displayName" autocomplete="name" />
|
||||
</label>
|
||||
<label>
|
||||
Password
|
||||
<input type="password" name="password" autocomplete="new-password" minlength="12" required />
|
||||
</label>
|
||||
<label class="auth-choice">
|
||||
<input type="checkbox" name="signupsEnabled" />
|
||||
Allow visitors to create accounts
|
||||
</label>
|
||||
<button type="submit" class="btn-primary">Finish setup</button>
|
||||
<p class="form-status" data-setup-status></p>
|
||||
</form>
|
||||
</div>
|
||||
</section>
|
||||
{{ end }}
|
||||
@@ -1,2 +0,0 @@
|
||||
dist/
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Cairnquire App</title>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,25 +0,0 @@
|
||||
{
|
||||
"name": "cairnquire-web",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"format": "prettier --check .",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"katex": "^0.16.45",
|
||||
"lucide-preact": "^1.14.0",
|
||||
"mermaid": "^11.14.0",
|
||||
"preact": "^10.27.2",
|
||||
"preact-iso": "^2.9.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@preact/preset-vite": "^2.10.2",
|
||||
"prettier": "^3.6.2",
|
||||
"typescript": "^6.0.3",
|
||||
"vite": "^7.1.12"
|
||||
}
|
||||
}
|
||||
@@ -1,725 +0,0 @@
|
||||
import {
|
||||
ChevronRight,
|
||||
Clock3,
|
||||
Database,
|
||||
FileText,
|
||||
Folder,
|
||||
FolderGit2,
|
||||
FolderOpen,
|
||||
LogIn,
|
||||
LogOut,
|
||||
PanelLeftClose,
|
||||
PanelLeftOpen,
|
||||
RefreshCw,
|
||||
Shield,
|
||||
UserPlus,
|
||||
Users,
|
||||
} from "lucide-preact";
|
||||
import { useEffect, useState } from "preact/hooks";
|
||||
|
||||
type Role = "admin" | "editor" | "viewer";
|
||||
type View = "workspace" | "users";
|
||||
|
||||
type User = {
|
||||
id: string;
|
||||
email: string;
|
||||
displayName: string;
|
||||
role: Role;
|
||||
createdAt: string;
|
||||
lastSeenAt?: string;
|
||||
};
|
||||
|
||||
type DocumentRecord = {
|
||||
path: string;
|
||||
title: string;
|
||||
currentHash: string;
|
||||
updatedAt: string;
|
||||
};
|
||||
|
||||
type Workspace = {
|
||||
sourceDir: string;
|
||||
storeDir: string;
|
||||
databasePath: string;
|
||||
documentCount: number;
|
||||
userCount: number;
|
||||
webDistDir: string;
|
||||
};
|
||||
|
||||
type WorkspaceResponse = {
|
||||
workspace: Workspace;
|
||||
documents: DocumentRecord[];
|
||||
};
|
||||
|
||||
type Session = {
|
||||
user: User;
|
||||
};
|
||||
|
||||
type BrowserItem = {
|
||||
type: "folder" | "document";
|
||||
name: string;
|
||||
path: string;
|
||||
document?: DocumentRecord;
|
||||
indexDocument?: DocumentRecord;
|
||||
};
|
||||
|
||||
type BrowserColumn = {
|
||||
title: string;
|
||||
prefix: string;
|
||||
items: BrowserItem[];
|
||||
};
|
||||
|
||||
const sessionKey = "mdhub.admin.session";
|
||||
|
||||
export function App() {
|
||||
const [session, setSession] = useState<Session | null>(() => readSession());
|
||||
const [activeView, setActiveView] = useState<View>("workspace");
|
||||
const [sidebarOpen, setSidebarOpen] = useState(true);
|
||||
const [users, setUsers] = useState<User[]>([]);
|
||||
const [workspace, setWorkspace] = useState<WorkspaceResponse | null>(null);
|
||||
const [syncing, setSyncing] = useState(false);
|
||||
const [lastSyncedAt, setLastSyncedAt] = useState("");
|
||||
const [activePath, setActivePath] = useState("");
|
||||
const [selectedUserId, setSelectedUserId] = useState("");
|
||||
|
||||
async function refresh() {
|
||||
if (!session) {
|
||||
return;
|
||||
}
|
||||
const [usersResponse, workspaceResponse] = await Promise.all([
|
||||
api<{ users: User[] }>("/api/admin/users"),
|
||||
api<WorkspaceResponse>("/api/admin/workspace"),
|
||||
]);
|
||||
setUsers(usersResponse.users);
|
||||
setWorkspace(workspaceResponse);
|
||||
setLastSyncedAt(new Date().toISOString());
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
void refresh();
|
||||
}, [session?.user.email]);
|
||||
|
||||
useEffect(() => {
|
||||
const documents = workspace?.documents ?? [];
|
||||
if (
|
||||
documents.length > 0 &&
|
||||
!isKnownDocumentLocation(documents, activePath)
|
||||
) {
|
||||
setActivePath(documents[0].path);
|
||||
}
|
||||
}, [workspace?.documents, activePath]);
|
||||
|
||||
useEffect(() => {
|
||||
if (users.length > 0 && !users.some((user) => user.id === selectedUserId)) {
|
||||
setSelectedUserId(users[0].id);
|
||||
}
|
||||
}, [users, selectedUserId]);
|
||||
|
||||
async function handleLogin(email: string, displayName: string) {
|
||||
const response = await api<{ user: User }>("/api/admin/login", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ email, displayName, role: "admin" }),
|
||||
});
|
||||
const next = { user: response.user };
|
||||
localStorage.setItem(sessionKey, JSON.stringify(next));
|
||||
setSession(next);
|
||||
}
|
||||
|
||||
async function handleCreateUser(input: {
|
||||
email: string;
|
||||
displayName: string;
|
||||
role: Role;
|
||||
}) {
|
||||
const response = await api<{ user: User }>("/api/admin/users", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(input),
|
||||
});
|
||||
await refresh();
|
||||
setSelectedUserId(response.user.id);
|
||||
}
|
||||
|
||||
async function handleSync() {
|
||||
setSyncing(true);
|
||||
try {
|
||||
await api("/api/admin/workspace/sync", { method: "POST" });
|
||||
await refresh();
|
||||
} finally {
|
||||
setSyncing(false);
|
||||
}
|
||||
}
|
||||
|
||||
function logout() {
|
||||
localStorage.removeItem(sessionKey);
|
||||
setSession(null);
|
||||
setUsers([]);
|
||||
setWorkspace(null);
|
||||
setActivePath("");
|
||||
setSelectedUserId("");
|
||||
}
|
||||
|
||||
if (!session) {
|
||||
return <LoginScreen onLogin={handleLogin} />;
|
||||
}
|
||||
|
||||
const selectedDocument = selectDocument(
|
||||
workspace?.documents ?? [],
|
||||
activePath,
|
||||
);
|
||||
const selectedUser =
|
||||
users.find((user) => user.id === selectedUserId) ?? users[0];
|
||||
|
||||
return (
|
||||
<main class={`admin-shell ${sidebarOpen ? "" : "is-collapsed"}`}>
|
||||
<aside class="admin-sidebar">
|
||||
<div class="sidebar-header">
|
||||
<a class="brand" href="/docs" title="Open public docs">
|
||||
<Shield size={18} />
|
||||
<span>MD Hub</span>
|
||||
</a>
|
||||
<button
|
||||
class="icon-button"
|
||||
type="button"
|
||||
onClick={() => setSidebarOpen((open) => !open)}
|
||||
aria-label={sidebarOpen ? "Collapse sidebar" : "Expand sidebar"}
|
||||
>
|
||||
{sidebarOpen ? (
|
||||
<PanelLeftClose size={17} />
|
||||
) : (
|
||||
<PanelLeftOpen size={17} />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<nav class="nav-list" aria-label="Admin sections">
|
||||
<button
|
||||
class={activeView === "workspace" ? "is-active" : ""}
|
||||
type="button"
|
||||
onClick={() => setActiveView("workspace")}
|
||||
title="Workspace"
|
||||
>
|
||||
<FolderGit2 size={17} />
|
||||
<span>Workspace</span>
|
||||
</button>
|
||||
<button
|
||||
class={activeView === "users" ? "is-active" : ""}
|
||||
type="button"
|
||||
onClick={() => setActiveView("users")}
|
||||
title="Users"
|
||||
>
|
||||
<Users size={17} />
|
||||
<span>Users</span>
|
||||
</button>
|
||||
</nav>
|
||||
|
||||
<button
|
||||
class="nav-button"
|
||||
type="button"
|
||||
onClick={logout}
|
||||
title="Sign out"
|
||||
>
|
||||
<LogOut size={16} />
|
||||
<span>Sign out</span>
|
||||
</button>
|
||||
</aside>
|
||||
|
||||
<section class="admin-main">
|
||||
<header class="compact-topbar">
|
||||
<div>
|
||||
<span class="section-label">{activeView}</span>
|
||||
<strong>
|
||||
{activeView === "workspace" ? "Documents" : "Accounts"}
|
||||
</strong>
|
||||
</div>
|
||||
<div class="topbar-actions">
|
||||
{activeView === "workspace" && (
|
||||
<button
|
||||
type="button"
|
||||
class="primary-button sync-button"
|
||||
onClick={handleSync}
|
||||
disabled={syncing}
|
||||
aria-label="Sync workspace"
|
||||
>
|
||||
<RefreshCw size={15} />
|
||||
<span>Sync</span>
|
||||
</button>
|
||||
)}
|
||||
<span class="sync-label">
|
||||
<Clock3 size={14} />
|
||||
{syncing
|
||||
? "Syncing"
|
||||
: lastSyncedAt
|
||||
? `Synced ${formatTime(lastSyncedAt)}`
|
||||
: "Not synced"}
|
||||
</span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{activeView === "workspace" ? (
|
||||
<WorkspaceView
|
||||
data={workspace}
|
||||
activePath={activePath}
|
||||
selectedDocument={selectedDocument}
|
||||
onSelectPath={setActivePath}
|
||||
/>
|
||||
) : (
|
||||
<UsersView
|
||||
users={users}
|
||||
selectedUser={selectedUser}
|
||||
onSelectUser={setSelectedUserId}
|
||||
onCreateUser={handleCreateUser}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
function LoginScreen(props: {
|
||||
onLogin: (email: string, displayName: string) => Promise<void>;
|
||||
}) {
|
||||
const [email, setEmail] = useState("admin@example.com");
|
||||
const [displayName, setDisplayName] = useState("Admin");
|
||||
const [error, setError] = useState("");
|
||||
|
||||
async function submit(event: Event) {
|
||||
event.preventDefault();
|
||||
setError("");
|
||||
try {
|
||||
await props.onLogin(email, displayName);
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : "Login failed");
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<main class="login-shell">
|
||||
<form class="login-panel" onSubmit={submit}>
|
||||
<div class="login-mark">
|
||||
<Shield size={20} />
|
||||
</div>
|
||||
<h1>Admin login</h1>
|
||||
<label>
|
||||
Email
|
||||
<input
|
||||
type="email"
|
||||
value={email}
|
||||
onInput={(event) => setEmail(event.currentTarget.value)}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Display name
|
||||
<input
|
||||
type="text"
|
||||
value={displayName}
|
||||
onInput={(event) => setDisplayName(event.currentTarget.value)}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
{error && <p class="form-error">{error}</p>}
|
||||
<button type="submit" class="primary-button">
|
||||
<LogIn size={15} />
|
||||
Sign in
|
||||
</button>
|
||||
</form>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
function WorkspaceView(props: {
|
||||
data: WorkspaceResponse | null;
|
||||
activePath: string;
|
||||
selectedDocument?: DocumentRecord;
|
||||
onSelectPath: (path: string) => void;
|
||||
}) {
|
||||
const documents = props.data?.documents ?? [];
|
||||
const columns = buildDocumentColumns(documents, props.activePath);
|
||||
|
||||
return (
|
||||
<div class="workspace-grid">
|
||||
<section class="column-browser" aria-label="Workspace files">
|
||||
{columns.map((column) => (
|
||||
<div class="browser-column" key={column.prefix || "root"}>
|
||||
<header>
|
||||
<Folder size={15} />
|
||||
{column.title}
|
||||
</header>
|
||||
<div class="item-list">
|
||||
{column.items.map((item) => (
|
||||
<button
|
||||
class={
|
||||
isActiveItem(item, props.activePath)
|
||||
? "list-item is-active"
|
||||
: "list-item"
|
||||
}
|
||||
type="button"
|
||||
key={`${item.type}:${item.path}`}
|
||||
onClick={() =>
|
||||
props.onSelectPath(item.indexDocument?.path ?? item.path)
|
||||
}
|
||||
>
|
||||
{item.type === "folder" ? (
|
||||
isActiveItem(item, props.activePath) ? (
|
||||
<FolderOpen size={15} />
|
||||
) : (
|
||||
<Folder size={15} />
|
||||
)
|
||||
) : (
|
||||
<FileText size={15} />
|
||||
)}
|
||||
<span>{item.name}</span>
|
||||
{item.type === "folder" && <ChevronRight size={14} />}
|
||||
</button>
|
||||
))}
|
||||
{column.items.length === 0 && (
|
||||
<p class="empty-state">No documents</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
|
||||
<WorkspaceDetails
|
||||
workspace={props.data?.workspace}
|
||||
document={props.selectedDocument}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function WorkspaceDetails(props: {
|
||||
workspace?: Workspace;
|
||||
document?: DocumentRecord;
|
||||
}) {
|
||||
return (
|
||||
<aside class="detail-panel">
|
||||
<header class="detail-header">
|
||||
<Database size={17} />
|
||||
<span>Details</span>
|
||||
</header>
|
||||
|
||||
{props.document ? (
|
||||
<>
|
||||
<h2>{props.document.title}</h2>
|
||||
<a class="open-link" href={documentHref(props.document.path)}>
|
||||
Open document
|
||||
</a>
|
||||
<dl class="detail-list">
|
||||
<div>
|
||||
<dt>File</dt>
|
||||
<dd>{props.document.path}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Hash</dt>
|
||||
<dd>
|
||||
<code>{props.document.currentHash.slice(0, 12)}</code>
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Updated</dt>
|
||||
<dd>{formatDate(props.document.updatedAt)}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</>
|
||||
) : (
|
||||
<p class="empty-state">Select a document.</p>
|
||||
)}
|
||||
|
||||
{props.workspace && (
|
||||
<dl class="detail-list compact">
|
||||
<div>
|
||||
<dt>Documents</dt>
|
||||
<dd>{props.workspace.documentCount}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Content</dt>
|
||||
<dd>{props.workspace.sourceDir}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Storage</dt>
|
||||
<dd>{props.workspace.storeDir}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Database</dt>
|
||||
<dd>{props.workspace.databasePath}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
)}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
function UsersView(props: {
|
||||
users: User[];
|
||||
selectedUser?: User;
|
||||
onSelectUser: (id: string) => void;
|
||||
onCreateUser: (input: {
|
||||
email: string;
|
||||
displayName: string;
|
||||
role: Role;
|
||||
}) => Promise<void>;
|
||||
}) {
|
||||
return (
|
||||
<div class="workspace-grid">
|
||||
<section class="browser-column user-column" aria-label="Users">
|
||||
<header>Users</header>
|
||||
<div class="item-list">
|
||||
{props.users.map((user) => (
|
||||
<button
|
||||
class={
|
||||
user.id === props.selectedUser?.id
|
||||
? "list-item is-active"
|
||||
: "list-item"
|
||||
}
|
||||
type="button"
|
||||
key={user.id}
|
||||
onClick={() => props.onSelectUser(user.id)}
|
||||
>
|
||||
<Users size={15} />
|
||||
<span>{user.displayName}</span>
|
||||
<small>{user.role}</small>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<UserDetails
|
||||
selectedUser={props.selectedUser}
|
||||
onCreateUser={props.onCreateUser}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function UserDetails(props: {
|
||||
selectedUser?: User;
|
||||
onCreateUser: (input: {
|
||||
email: string;
|
||||
displayName: string;
|
||||
role: Role;
|
||||
}) => Promise<void>;
|
||||
}) {
|
||||
const [email, setEmail] = useState("");
|
||||
const [displayName, setDisplayName] = useState("");
|
||||
const [role, setRole] = useState<Role>("viewer");
|
||||
|
||||
async function submit(event: Event) {
|
||||
event.preventDefault();
|
||||
await props.onCreateUser({ email, displayName, role });
|
||||
setEmail("");
|
||||
setDisplayName("");
|
||||
setRole("viewer");
|
||||
}
|
||||
|
||||
return (
|
||||
<aside class="detail-panel">
|
||||
<header class="detail-header">
|
||||
<UserPlus size={17} />
|
||||
<span>Add user</span>
|
||||
</header>
|
||||
|
||||
<form class="stack-form" onSubmit={submit}>
|
||||
<input
|
||||
type="email"
|
||||
placeholder="email@example.com"
|
||||
value={email}
|
||||
onInput={(event) => setEmail(event.currentTarget.value)}
|
||||
required
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Display name"
|
||||
value={displayName}
|
||||
onInput={(event) => setDisplayName(event.currentTarget.value)}
|
||||
required
|
||||
/>
|
||||
<select
|
||||
value={role}
|
||||
onChange={(event) => setRole(event.currentTarget.value as Role)}
|
||||
>
|
||||
<option value="viewer">Viewer</option>
|
||||
<option value="editor">Editor</option>
|
||||
<option value="admin">Admin</option>
|
||||
</select>
|
||||
<button type="submit" class="primary-button">
|
||||
<UserPlus size={15} />
|
||||
Add
|
||||
</button>
|
||||
</form>
|
||||
|
||||
{props.selectedUser && (
|
||||
<>
|
||||
<h2>{props.selectedUser.displayName}</h2>
|
||||
<dl class="detail-list">
|
||||
<div>
|
||||
<dt>Email</dt>
|
||||
<dd>{props.selectedUser.email}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Role</dt>
|
||||
<dd>{props.selectedUser.role}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Created</dt>
|
||||
<dd>{formatDate(props.selectedUser.createdAt)}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</>
|
||||
)}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
function buildDocumentColumns(
|
||||
documents: DocumentRecord[],
|
||||
activePath: string,
|
||||
): BrowserColumn[] {
|
||||
const activeSegments = activePath.split("/").filter(Boolean);
|
||||
const prefixes = [""];
|
||||
const maxFolderDepth = activePath.endsWith(".md")
|
||||
? activeSegments.length - 1
|
||||
: activeSegments.length;
|
||||
|
||||
for (let index = 0; index < maxFolderDepth; index += 1) {
|
||||
prefixes.push(activeSegments.slice(0, index + 1).join("/"));
|
||||
}
|
||||
|
||||
return prefixes.map((prefix) => ({
|
||||
title: prefix ? folderLabel(prefix) : "Documents",
|
||||
prefix,
|
||||
items: collectItems(documents, prefix),
|
||||
}));
|
||||
}
|
||||
|
||||
function collectItems(
|
||||
documents: DocumentRecord[],
|
||||
prefix: string,
|
||||
): BrowserItem[] {
|
||||
const items = new Map<string, BrowserItem>();
|
||||
const prefixWithSlash = prefix ? `${prefix}/` : "";
|
||||
|
||||
for (const document of documents) {
|
||||
if (!document.path.startsWith(prefixWithSlash)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const remainder = document.path.slice(prefixWithSlash.length);
|
||||
if (!remainder || remainder === "index.md") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const [nextSegment, ...rest] = remainder.split("/");
|
||||
if (rest.length > 0) {
|
||||
const folderPath = `${prefixWithSlash}${nextSegment}`;
|
||||
const indexDocument = documents.find(
|
||||
(candidate) => candidate.path === `${folderPath}/index.md`,
|
||||
);
|
||||
items.set(folderPath, {
|
||||
type: "folder",
|
||||
name: folderLabel(nextSegment),
|
||||
path: folderPath,
|
||||
indexDocument,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
items.set(document.path, {
|
||||
type: "document",
|
||||
name: document.title || fileLabel(document.path),
|
||||
path: document.path,
|
||||
document,
|
||||
});
|
||||
}
|
||||
|
||||
return [...items.values()].sort((left, right) => {
|
||||
if (left.type !== right.type) {
|
||||
return left.type === "folder" ? -1 : 1;
|
||||
}
|
||||
return left.name.localeCompare(right.name);
|
||||
});
|
||||
}
|
||||
|
||||
function selectDocument(documents: DocumentRecord[], activePath: string) {
|
||||
if (!activePath) {
|
||||
return documents[0];
|
||||
}
|
||||
return (
|
||||
documents.find((document) => document.path === activePath) ??
|
||||
documents.find((document) => document.path === `${activePath}/index.md`)
|
||||
);
|
||||
}
|
||||
|
||||
function isKnownDocumentLocation(documents: DocumentRecord[], path: string) {
|
||||
if (!path) {
|
||||
return false;
|
||||
}
|
||||
return documents.some(
|
||||
(document) =>
|
||||
document.path === path ||
|
||||
document.path === `${path}/index.md` ||
|
||||
document.path.startsWith(`${path}/`),
|
||||
);
|
||||
}
|
||||
|
||||
function isActiveItem(item: BrowserItem, activePath: string) {
|
||||
return (
|
||||
activePath === item.path ||
|
||||
activePath === item.indexDocument?.path ||
|
||||
activePath.startsWith(`${item.path}/`)
|
||||
);
|
||||
}
|
||||
|
||||
function documentHref(path: string) {
|
||||
return `/docs/${path.replace(/(^|\/)index\.md$/, "").replace(/\.md$/, "")}`;
|
||||
}
|
||||
|
||||
function folderLabel(path: string) {
|
||||
return fileLabel(path.split("/").filter(Boolean).at(-1) ?? path);
|
||||
}
|
||||
|
||||
function fileLabel(path: string) {
|
||||
return path
|
||||
.replace(/\.md$/, "")
|
||||
.replace(/[-_]/g, " ")
|
||||
.replace(/\b\w/g, (match) => match.toUpperCase());
|
||||
}
|
||||
|
||||
async function api<T = unknown>(path: string, init?: RequestInit): Promise<T> {
|
||||
const response = await fetch(path, {
|
||||
...init,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...(init?.headers ?? {}),
|
||||
},
|
||||
});
|
||||
if (!response.ok) {
|
||||
const text = await response.text();
|
||||
throw new Error(text || response.statusText);
|
||||
}
|
||||
return response.json() as Promise<T>;
|
||||
}
|
||||
|
||||
function readSession(): Session | null {
|
||||
try {
|
||||
const raw = localStorage.getItem(sessionKey);
|
||||
return raw ? (JSON.parse(raw) as Session) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function formatDate(value: string) {
|
||||
if (!value) {
|
||||
return "";
|
||||
}
|
||||
return new Intl.DateTimeFormat(undefined, {
|
||||
dateStyle: "medium",
|
||||
timeStyle: "short",
|
||||
}).format(new Date(value));
|
||||
}
|
||||
|
||||
function formatTime(value: string) {
|
||||
return new Intl.DateTimeFormat(undefined, {
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
}).format(new Date(value));
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
import { render } from "preact";
|
||||
import { LocationProvider, Route, Router } from "preact-iso";
|
||||
import { App } from "./app";
|
||||
import "./styles.css";
|
||||
|
||||
render(
|
||||
<LocationProvider scope="/app">
|
||||
<Router>{[<Route path="/*" component={App} />]}</Router>
|
||||
</LocationProvider>,
|
||||
document.getElementById("app")!,
|
||||
);
|
||||
@@ -1,504 +0,0 @@
|
||||
:root {
|
||||
color-scheme: light;
|
||||
--bg: #f4f1ea;
|
||||
--surface: rgba(255, 255, 255, 0.76);
|
||||
--surface-strong: #ffffff;
|
||||
--text: #202227;
|
||||
--muted: #626775;
|
||||
--accent: #1947e5;
|
||||
--accent-soft: rgba(25, 71, 229, 0.1);
|
||||
--border: rgba(32, 34, 39, 0.12);
|
||||
--shadow: 0 18px 54px rgba(25, 71, 229, 0.1);
|
||||
font-family: "Iowan Old Style", "Palatino Linotype", "Book Antiqua", serif;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
color: var(--text);
|
||||
background:
|
||||
radial-gradient(
|
||||
circle at top left,
|
||||
rgba(25, 71, 229, 0.12),
|
||||
transparent 34%
|
||||
),
|
||||
radial-gradient(
|
||||
circle at bottom right,
|
||||
rgba(15, 138, 108, 0.14),
|
||||
transparent 30%
|
||||
),
|
||||
linear-gradient(180deg, #fbf8f2 0%, var(--bg) 100%);
|
||||
}
|
||||
|
||||
button,
|
||||
input,
|
||||
select {
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
button {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
cursor: wait;
|
||||
opacity: 0.72;
|
||||
}
|
||||
|
||||
a {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
code {
|
||||
font-family: ui-monospace, SFMono-Regular, monospace;
|
||||
}
|
||||
|
||||
.admin-shell {
|
||||
display: grid;
|
||||
grid-template-columns: 11rem minmax(0, 1fr);
|
||||
min-height: 100vh;
|
||||
transition: grid-template-columns 160ms ease;
|
||||
}
|
||||
|
||||
.admin-shell.is-collapsed {
|
||||
grid-template-columns: 4rem minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.admin-sidebar {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
padding: 0.8rem;
|
||||
border-right: 1px solid var(--border);
|
||||
background: rgba(255, 255, 255, 0.55);
|
||||
backdrop-filter: blur(14px);
|
||||
}
|
||||
|
||||
.sidebar-header,
|
||||
.compact-topbar,
|
||||
.topbar-actions,
|
||||
.detail-header,
|
||||
.brand,
|
||||
.nav-list button,
|
||||
.nav-button,
|
||||
.icon-button,
|
||||
.primary-button,
|
||||
.sync-label,
|
||||
.list-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.sidebar-header {
|
||||
justify-content: space-between;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
|
||||
.brand {
|
||||
min-width: 0;
|
||||
gap: 0.5rem;
|
||||
color: var(--text);
|
||||
font-weight: 700;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.brand span,
|
||||
.nav-list span,
|
||||
.nav-button span {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.icon-button,
|
||||
.nav-list button,
|
||||
.nav-button {
|
||||
border: 0;
|
||||
color: var(--text);
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.icon-button {
|
||||
justify-content: center;
|
||||
width: 2rem;
|
||||
height: 2rem;
|
||||
flex: 0 0 auto;
|
||||
border-radius: 0.45rem;
|
||||
}
|
||||
|
||||
.icon-button:hover,
|
||||
.nav-list button:hover,
|
||||
.nav-button:hover,
|
||||
.nav-list button.is-active {
|
||||
color: var(--accent);
|
||||
background: var(--accent-soft);
|
||||
}
|
||||
|
||||
.nav-list {
|
||||
display: grid;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.nav-list button,
|
||||
.nav-button {
|
||||
min-width: 0;
|
||||
min-height: 2.25rem;
|
||||
gap: 0.55rem;
|
||||
padding: 0.45rem 0.55rem;
|
||||
border-radius: 0.5rem;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.nav-button {
|
||||
margin-top: auto;
|
||||
}
|
||||
|
||||
.admin-shell.is-collapsed .brand span,
|
||||
.admin-shell.is-collapsed .nav-list span,
|
||||
.admin-shell.is-collapsed .nav-button span {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.admin-shell.is-collapsed .sidebar-header,
|
||||
.admin-shell.is-collapsed .nav-list button,
|
||||
.admin-shell.is-collapsed .nav-button {
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.admin-main {
|
||||
min-width: 0;
|
||||
padding: 0.85rem;
|
||||
}
|
||||
|
||||
.compact-topbar {
|
||||
min-height: 3rem;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
margin-bottom: 0.8rem;
|
||||
}
|
||||
|
||||
.compact-topbar > div:first-child {
|
||||
display: grid;
|
||||
gap: 0.1rem;
|
||||
}
|
||||
|
||||
.section-label {
|
||||
color: var(--accent);
|
||||
font-family: ui-monospace, SFMono-Regular, monospace;
|
||||
font-size: 0.7rem;
|
||||
letter-spacing: 0.12em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.topbar-actions {
|
||||
gap: 0.55rem;
|
||||
}
|
||||
|
||||
.sync-label {
|
||||
gap: 0.4rem;
|
||||
min-height: 2.1rem;
|
||||
padding: 0.25rem 0.55rem;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
color: var(--muted);
|
||||
background: rgba(255, 255, 255, 0.58);
|
||||
font-size: 0.92rem;
|
||||
}
|
||||
|
||||
.primary-button {
|
||||
justify-content: center;
|
||||
gap: 0.45rem;
|
||||
min-height: 2.25rem;
|
||||
padding: 0.45rem 0.75rem;
|
||||
border: 0;
|
||||
border-radius: 0.5rem;
|
||||
color: white;
|
||||
background: var(--accent);
|
||||
}
|
||||
|
||||
.sync-button {
|
||||
width: 2.25rem;
|
||||
padding-inline: 0;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.sync-button span {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.workspace-grid {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(12rem, 1fr) clamp(11.5rem, 20vw, 15rem);
|
||||
gap: 0.65rem;
|
||||
min-height: calc(100vh - 4.8rem);
|
||||
}
|
||||
|
||||
.column-browser {
|
||||
display: grid;
|
||||
grid-auto-columns: minmax(11rem, 1fr);
|
||||
grid-auto-flow: column;
|
||||
gap: 0.65rem;
|
||||
min-width: 0;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.browser-column,
|
||||
.detail-panel,
|
||||
.login-panel {
|
||||
min-width: 0;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 0.55rem;
|
||||
background: var(--surface);
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
.browser-column,
|
||||
.detail-panel {
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.browser-column > header,
|
||||
.detail-header {
|
||||
min-height: 2.5rem;
|
||||
padding: 0.7rem 0.8rem;
|
||||
border-bottom: 1px solid var(--border);
|
||||
color: var(--muted);
|
||||
font-family: ui-monospace, SFMono-Regular, monospace;
|
||||
font-size: 0.72rem;
|
||||
letter-spacing: 0.1em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.detail-header {
|
||||
gap: 0.45rem;
|
||||
}
|
||||
|
||||
.item-list {
|
||||
display: grid;
|
||||
gap: 0.15rem;
|
||||
padding: 0.45rem;
|
||||
}
|
||||
|
||||
.list-item {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
gap: 0.45rem;
|
||||
min-height: 2.35rem;
|
||||
padding: 0.45rem 0.5rem;
|
||||
border: 0;
|
||||
border-radius: 0.42rem;
|
||||
color: var(--text);
|
||||
background: transparent;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.list-item:hover,
|
||||
.list-item.is-active {
|
||||
color: var(--accent);
|
||||
background: var(--accent-soft);
|
||||
}
|
||||
|
||||
.list-item span {
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.list-item small {
|
||||
color: var(--muted);
|
||||
font-family: ui-monospace, SFMono-Regular, monospace;
|
||||
font-size: 0.72rem;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.user-column {
|
||||
min-height: 22rem;
|
||||
}
|
||||
|
||||
.detail-panel {
|
||||
padding-bottom: 0.9rem;
|
||||
}
|
||||
|
||||
.detail-panel h2 {
|
||||
margin: 0.85rem 0.85rem 0.35rem;
|
||||
font-size: 1.45rem;
|
||||
line-height: 1.05;
|
||||
}
|
||||
|
||||
.open-link {
|
||||
display: inline-flex;
|
||||
margin: 0 0.85rem 0.7rem;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.detail-list {
|
||||
display: grid;
|
||||
gap: 0.5rem;
|
||||
margin: 0;
|
||||
padding: 0.85rem;
|
||||
}
|
||||
|
||||
.detail-list.compact {
|
||||
margin-top: 0.35rem;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.detail-list div {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.detail-list dt {
|
||||
margin-bottom: 0.16rem;
|
||||
color: var(--muted);
|
||||
font-family: ui-monospace, SFMono-Regular, monospace;
|
||||
font-size: 0.72rem;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.detail-list dd {
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.stack-form {
|
||||
display: grid;
|
||||
gap: 0.5rem;
|
||||
padding: 0.85rem;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.stack-form input,
|
||||
.stack-form select,
|
||||
.login-panel input {
|
||||
width: 100%;
|
||||
min-height: 2.25rem;
|
||||
padding: 0.45rem 0.6rem;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 0.45rem;
|
||||
color: var(--text);
|
||||
background: rgba(255, 255, 255, 0.72);
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
margin: 0;
|
||||
padding: 0.8rem;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.login-shell {
|
||||
display: grid;
|
||||
min-height: 100vh;
|
||||
place-items: center;
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.login-panel {
|
||||
display: grid;
|
||||
width: min(23rem, 100%);
|
||||
gap: 0.75rem;
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.login-panel h1 {
|
||||
margin: 0;
|
||||
font-size: 1.6rem;
|
||||
}
|
||||
|
||||
.login-panel label {
|
||||
display: grid;
|
||||
gap: 0.3rem;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.login-mark {
|
||||
display: inline-flex;
|
||||
width: 2.4rem;
|
||||
height: 2.4rem;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 0.5rem;
|
||||
color: white;
|
||||
background: var(--accent);
|
||||
}
|
||||
|
||||
.form-error {
|
||||
margin: 0;
|
||||
color: #a43131;
|
||||
}
|
||||
|
||||
@media (max-width: 1080px) {
|
||||
.admin-shell,
|
||||
.admin-shell.is-collapsed {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.admin-sidebar {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 2;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.nav-list {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.nav-button {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.admin-shell.is-collapsed .brand span,
|
||||
.admin-shell.is-collapsed .nav-list span,
|
||||
.admin-shell.is-collapsed .nav-button span {
|
||||
display: inline;
|
||||
}
|
||||
|
||||
.workspace-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.sync-label {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.column-browser {
|
||||
min-height: 18rem;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.admin-sidebar,
|
||||
.compact-topbar {
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.sidebar-header,
|
||||
.topbar-actions,
|
||||
.nav-list {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.nav-list button,
|
||||
.nav-button,
|
||||
.primary-button {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.column-browser {
|
||||
grid-auto-flow: row;
|
||||
grid-auto-columns: auto;
|
||||
}
|
||||
}
|
||||
6
apps/web/src/vite-env.d.ts
vendored
6
apps/web/src/vite-env.d.ts
vendored
@@ -1,6 +0,0 @@
|
||||
/// <reference types="vite/client" />
|
||||
|
||||
declare module "*.css" {
|
||||
const content: string;
|
||||
export default content;
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["DOM", "ES2022"],
|
||||
"allowJs": false,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"strict": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
"jsxImportSource": "preact"
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
import { defineConfig } from "vite";
|
||||
import preact from "@preact/preset-vite";
|
||||
|
||||
const serverTarget = "http://localhost:8080";
|
||||
|
||||
export default defineConfig({
|
||||
base: "/app/",
|
||||
plugins: [preact()],
|
||||
build: {
|
||||
outDir: "dist",
|
||||
sourcemap: true,
|
||||
},
|
||||
server: {
|
||||
port: 5173,
|
||||
proxy: {
|
||||
"/api": {
|
||||
target: serverTarget,
|
||||
changeOrigin: true,
|
||||
},
|
||||
"/attachments": {
|
||||
target: serverTarget,
|
||||
changeOrigin: true,
|
||||
},
|
||||
"/docs": {
|
||||
target: serverTarget,
|
||||
changeOrigin: true,
|
||||
},
|
||||
"/health": {
|
||||
target: serverTarget,
|
||||
changeOrigin: true,
|
||||
},
|
||||
"/static": {
|
||||
target: serverTarget,
|
||||
changeOrigin: true,
|
||||
},
|
||||
"/sw.js": {
|
||||
target: serverTarget,
|
||||
changeOrigin: true,
|
||||
},
|
||||
"/ws": {
|
||||
target: "ws://localhost:8080",
|
||||
ws: true,
|
||||
},
|
||||
"^/app$": {
|
||||
target: serverTarget,
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user