4.1.1
This commit is contained in:
commit
bd90fe1d65
137 files changed
+12107
No files matched your search
@@ -0,0 +1,7 @@
|
||||
.git
|
||||
.env
|
||||
data
|
||||
*.db
|
||||
*.db-shm
|
||||
*.db-wal
|
||||
balance-server
|
||||
@@ -0,0 +1,6 @@
|
||||
# Generate with: openssl rand -base64 48
|
||||
BALANCE_JWT_SECRET=replace-with-at-least-32-random-characters
|
||||
BALANCE_ALLOW_REGISTRATION=true
|
||||
BALANCE_ACCESS_TTL=15m
|
||||
BALANCE_REFRESH_TTL=720h
|
||||
BALANCE_CORS_ORIGINS=
|
||||
@@ -0,0 +1,8 @@
|
||||
.env
|
||||
data/
|
||||
dist/
|
||||
*.db
|
||||
*.db-shm
|
||||
*.db-wal
|
||||
balance-server
|
||||
balance-server.exe
|
||||
@@ -0,0 +1,15 @@
|
||||
FROM golang:1.25.12-alpine AS build
|
||||
WORKDIR /src
|
||||
COPY go.mod go.sum* ./
|
||||
RUN go mod download
|
||||
COPY . .
|
||||
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/balance-server ./cmd/balance-server
|
||||
|
||||
FROM alpine:3.22
|
||||
RUN addgroup -S balance && adduser -S -G balance balance && mkdir /data && chown balance:balance /data
|
||||
USER balance
|
||||
COPY --from=build /out/balance-server /usr/local/bin/balance-server
|
||||
ENV BALANCE_ADDR=:8080 BALANCE_DB_PATH=/data/balance.db
|
||||
EXPOSE 8080
|
||||
VOLUME ["/data"]
|
||||
ENTRYPOINT ["balance-server"]
|
||||
@@ -0,0 +1,112 @@
|
||||
# Balance Server
|
||||
|
||||
Self-hosted synchronization, account and web server for the Balance iOS, macOS, watchOS and Android applications. It is a single Go process with an embedded SQLite database and a complete browser client, and runs on Linux, Windows and macOS.
|
||||
|
||||
## Quick start with Docker
|
||||
|
||||
```sh
|
||||
cp .env.example .env
|
||||
openssl rand -base64 48
|
||||
# Paste the generated value into BALANCE_JWT_SECRET in .env
|
||||
docker compose up -d --build
|
||||
curl http://localhost:8080/health
|
||||
```
|
||||
|
||||
Open `http://localhost:8080` to register or sign in to the web application. Data is kept in the `balance-data` Docker volume. Back it up while the container is stopped.
|
||||
|
||||
## Run without Docker
|
||||
|
||||
Install Go 1.25 or newer, then run:
|
||||
|
||||
```sh
|
||||
go mod tidy
|
||||
go build -o balance-server ./cmd/balance-server
|
||||
```
|
||||
|
||||
On Linux or macOS:
|
||||
|
||||
```sh
|
||||
export BALANCE_JWT_SECRET="replace-with-a-long-random-secret"
|
||||
export BALANCE_DB_PATH="./data/balance.db"
|
||||
./balance-server
|
||||
```
|
||||
|
||||
On Windows PowerShell:
|
||||
|
||||
```powershell
|
||||
$env:BALANCE_JWT_SECRET = "replace-with-a-long-random-secret"
|
||||
$env:BALANCE_DB_PATH = ".\data\balance.db"
|
||||
.\balance-server.exe
|
||||
```
|
||||
|
||||
Cross-compile release binaries from any Go installation:
|
||||
|
||||
```sh
|
||||
GOOS=linux GOARCH=amd64 go build -o dist/balance-server-linux-amd64 ./cmd/balance-server
|
||||
GOOS=darwin GOARCH=arm64 go build -o dist/balance-server-macos-arm64 ./cmd/balance-server
|
||||
GOOS=windows GOARCH=amd64 go build -o dist/balance-server-windows-amd64.exe ./cmd/balance-server
|
||||
```
|
||||
|
||||
After starting the binary, open `http://localhost:8080` in a browser. The web assets are embedded into the executable, so there is no separate frontend build, Node.js process or static directory to deploy.
|
||||
|
||||
## Web application
|
||||
|
||||
The responsive web client includes:
|
||||
|
||||
- registration, login, automatic session refresh and logout;
|
||||
- dashboard, current balance and manual balance adjustment;
|
||||
- adding, editing, deleting, searching and filtering transactions;
|
||||
- analytics for 1, 3 and 12 months, spending breakdown and savings rate;
|
||||
- monthly category budgets;
|
||||
- custom categories with 50 icons, custom emoji and 24 colors;
|
||||
- light, dark and system themes, plus RUB, EUR, USD and SEK formatting;
|
||||
- automatic synchronization every 30 seconds and whenever the browser tab becomes active;
|
||||
- installable PWA shell for desktop and mobile browsers.
|
||||
|
||||
The browser session uses `HttpOnly`, `SameSite=Strict` cookies. Native applications continue to use Bearer access tokens and are fully backward compatible. Only display preferences are saved in browser local storage; tokens and financial records are not stored there.
|
||||
|
||||
## Configuration
|
||||
|
||||
| Variable | Default | Description |
|
||||
| --- | --- | --- |
|
||||
| `BALANCE_ADDR` | `:8080` | Listen address |
|
||||
| `BALANCE_DB_PATH` | `./data/balance.db` | SQLite file path |
|
||||
| `BALANCE_JWT_SECRET` | required | Random secret of at least 32 characters |
|
||||
| `BALANCE_ALLOW_REGISTRATION` | `true` | Allows new accounts |
|
||||
| `BALANCE_ACCESS_TTL` | `15m` | Access-token lifetime |
|
||||
| `BALANCE_REFRESH_TTL` | `720h` | Refresh-token lifetime |
|
||||
| `BALANCE_CORS_ORIGINS` | empty | Comma-separated browser origins; native apps do not need CORS |
|
||||
|
||||
## HTTPS
|
||||
|
||||
Use HTTPS before exposing the server to a network. The Apple applications accept plain HTTP only for `localhost` and `127.0.0.1`; a physical device should connect through an HTTPS reverse proxy such as Caddy, nginx or a private VPN with TLS. Example Caddy configuration:
|
||||
|
||||
```caddyfile
|
||||
balance.example.com {
|
||||
reverse_proxy 127.0.0.1:8080
|
||||
}
|
||||
```
|
||||
|
||||
Then enter `https://balance.example.com` in each application's Settings → Server account.
|
||||
|
||||
## API
|
||||
|
||||
| Method | Endpoint | Purpose |
|
||||
| --- | --- | --- |
|
||||
| `GET` | `/health` | Health check |
|
||||
| `POST` | `/v1/auth/register` | Create account |
|
||||
| `POST` | `/v1/auth/login` | Sign in |
|
||||
| `POST` | `/v1/auth/refresh` | Rotate session tokens |
|
||||
| `POST` | `/v1/auth/logout` | Revoke refresh token |
|
||||
| `GET` | `/v1/me` | Current account |
|
||||
| `POST` | `/v1/sync` | Push and pull changes |
|
||||
|
||||
The sync endpoint accepts transactions, custom categories and monthly budgets. The server isolates records by account, stores an append-only change cursor, and resolves competing edits with last-write-wins timestamps. Current Apple and Android clients use push-only requests followed by paginated pulls; update the server and applications together.
|
||||
|
||||
## Operational notes
|
||||
|
||||
- Registration can be disabled after the required accounts have been created.
|
||||
- Passwords are stored as salted Argon2id hashes. Refresh tokens are stored only as SHA-256 hashes.
|
||||
- Back up the SQLite database and its `-wal`/`-shm` files together, or stop the server before copying the database.
|
||||
- Changing `BALANCE_JWT_SECRET` invalidates access tokens. Existing refresh sessions remain valid and will receive new access tokens after refresh.
|
||||
- The in-process authentication limiter allows 30 authentication requests per IP per minute. Use a reverse proxy for stronger public rate limiting and request logging.
|
||||
@@ -0,0 +1,19 @@
|
||||
services:
|
||||
balance-server:
|
||||
build: .
|
||||
restart: always
|
||||
ports:
|
||||
- "8123:8080"
|
||||
environment:
|
||||
BALANCE_ADDR: ":8080"
|
||||
BALANCE_DB_PATH: "/data/balance.db"
|
||||
BALANCE_JWT_SECRET: "${BALANCE_JWT_SECRET:?Set BALANCE_JWT_SECRET in .env}"
|
||||
BALANCE_ALLOW_REGISTRATION: "${BALANCE_ALLOW_REGISTRATION:-true}"
|
||||
BALANCE_ACCESS_TTL: "${BALANCE_ACCESS_TTL:-15m}"
|
||||
BALANCE_REFRESH_TTL: "${BALANCE_REFRESH_TTL:-720h}"
|
||||
BALANCE_CORS_ORIGINS: "${BALANCE_CORS_ORIGINS:-}"
|
||||
volumes:
|
||||
- balance-data:/data
|
||||
|
||||
volumes:
|
||||
balance-data:
|
||||
@@ -0,0 +1,21 @@
|
||||
module balance-server
|
||||
|
||||
go 1.25.0
|
||||
|
||||
require (
|
||||
golang.org/x/crypto v0.41.0
|
||||
modernc.org/sqlite v1.39.1
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/ncruces/go-strftime v0.1.9 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b // indirect
|
||||
golang.org/x/sys v0.36.0 // indirect
|
||||
modernc.org/libc v1.66.10 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
modernc.org/memory v1.11.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,51 @@
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
|
||||
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
|
||||
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
golang.org/x/crypto v0.41.0 h1:WKYxWedPGCTVVl5+WHSSrOBT0O8lx32+zxmHxijgXp4=
|
||||
golang.org/x/crypto v0.41.0/go.mod h1:pO5AFd7FA68rFak7rOAGVuygIISepHftHnr8dr6+sUc=
|
||||
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b h1:M2rDM6z3Fhozi9O7NWsxAkg/yqS/lQJ6PmkyIV3YP+o=
|
||||
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b/go.mod h1:3//PLf8L/X+8b4vuAfHzxeRUl04Adcb341+IGKfnqS8=
|
||||
golang.org/x/mod v0.27.0 h1:kb+q2PyFnEADO2IEF935ehFUXlWiNjJWtRNgBLSfbxQ=
|
||||
golang.org/x/mod v0.27.0/go.mod h1:rWI627Fq0DEoudcK+MBkNkCe0EetEaDSwJJkCcjpazc=
|
||||
golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw=
|
||||
golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k=
|
||||
golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/tools v0.36.0 h1:kWS0uv/zsvHEle1LbV5LE8QujrxB3wfQyxHfhOk0Qkg=
|
||||
golang.org/x/tools v0.36.0/go.mod h1:WBDiHKJK8YgLHlcQPYQzNCkUxUypCaa5ZegCVutKm+s=
|
||||
modernc.org/cc/v4 v4.26.5 h1:xM3bX7Mve6G8K8b+T11ReenJOT+BmVqQj0FY5T4+5Y4=
|
||||
modernc.org/cc/v4 v4.26.5/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=
|
||||
modernc.org/ccgo/v4 v4.28.1 h1:wPKYn5EC/mYTqBO373jKjvX2n+3+aK7+sICCv4Fjy1A=
|
||||
modernc.org/ccgo/v4 v4.28.1/go.mod h1:uD+4RnfrVgE6ec9NGguUNdhqzNIeeomeXf6CL0GTE5Q=
|
||||
modernc.org/fileutil v1.3.40 h1:ZGMswMNc9JOCrcrakF1HrvmergNLAmxOPjizirpfqBA=
|
||||
modernc.org/fileutil v1.3.40/go.mod h1:HxmghZSZVAz/LXcMNwZPA/DRrQZEVP9VX0V4LQGQFOc=
|
||||
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
|
||||
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
|
||||
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
|
||||
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
|
||||
modernc.org/libc v1.66.10 h1:yZkb3YeLx4oynyR+iUsXsybsX4Ubx7MQlSYEw4yj59A=
|
||||
modernc.org/libc v1.66.10/go.mod h1:8vGSEwvoUoltr4dlywvHqjtAqHBaw0j1jI7iFBTAr2I=
|
||||
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
|
||||
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
|
||||
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
|
||||
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
|
||||
modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8=
|
||||
modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
|
||||
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
|
||||
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
|
||||
modernc.org/sqlite v1.39.1 h1:H+/wGFzuSCIEVCvXYVHX5RQglwhMOvtHSv+VtidL2r4=
|
||||
modernc.org/sqlite v1.39.1/go.mod h1:9fjQZ0mB1LLP0GYrp39oOJXx/I2sxEnZtzCmEQIKvGE=
|
||||
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
|
||||
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
|
||||
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
|
||||
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
|
||||
@@ -0,0 +1,61 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
const (
|
||||
argonMemory = 64 * 1024
|
||||
argonTime = 3
|
||||
argonThreads = 2
|
||||
argonKeyLen = 32
|
||||
)
|
||||
|
||||
func HashPassword(password string) (string, error) {
|
||||
if len(password) < 8 {
|
||||
return "", errors.New("password must contain at least 8 characters")
|
||||
}
|
||||
if len(password) > 1024 {
|
||||
return "", errors.New("password is too long")
|
||||
}
|
||||
salt := make([]byte, 16)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
hash := argon2.IDKey([]byte(password), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
|
||||
return fmt.Sprintf("$argon2id$v=19$m=%d,t=%d,p=%d$%s$%s", argonMemory, argonTime, argonThreads,
|
||||
base64.RawStdEncoding.EncodeToString(salt), base64.RawStdEncoding.EncodeToString(hash)), nil
|
||||
}
|
||||
|
||||
func VerifyPassword(encoded, password string) bool {
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 6 || parts[1] != "argon2id" || parts[2] != "v=19" {
|
||||
return false
|
||||
}
|
||||
var memory uint32
|
||||
var iterations uint32
|
||||
var threads uint8
|
||||
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &iterations, &threads); err != nil {
|
||||
return false
|
||||
}
|
||||
if memory > 256*1024 || iterations > 10 || threads > 16 {
|
||||
return false
|
||||
}
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
expected, err := base64.RawStdEncoding.DecodeString(parts[5])
|
||||
if err != nil || len(expected) == 0 {
|
||||
return false
|
||||
}
|
||||
actual := argon2.IDKey([]byte(password), salt, iterations, memory, threads, uint32(len(expected)))
|
||||
return subtle.ConstantTimeCompare(actual, expected) == 1
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Claims struct {
|
||||
Subject string `json:"sub"`
|
||||
Email string `json:"email"`
|
||||
Issuer string `json:"iss"`
|
||||
Issued int64 `json:"iat"`
|
||||
Expires int64 `json:"exp"`
|
||||
ID string `json:"jti"`
|
||||
}
|
||||
|
||||
type TokenManager struct {
|
||||
secret []byte
|
||||
accessTTL time.Duration
|
||||
}
|
||||
|
||||
func NewTokenManager(secret string, accessTTL time.Duration) TokenManager {
|
||||
return TokenManager{secret: []byte(secret), accessTTL: accessTTL}
|
||||
}
|
||||
|
||||
func (manager TokenManager) AccessToken(userID, email string) (string, time.Time, error) {
|
||||
now := time.Now().UTC()
|
||||
expires := now.Add(manager.accessTTL)
|
||||
id, err := RandomToken(16)
|
||||
if err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
header, _ := json.Marshal(map[string]string{"alg": "HS256", "typ": "JWT"})
|
||||
claims, _ := json.Marshal(Claims{Subject: userID, Email: email, Issuer: "balance-server", Issued: now.Unix(), Expires: expires.Unix(), ID: id})
|
||||
unsigned := encode(header) + "." + encode(claims)
|
||||
signature := manager.sign(unsigned)
|
||||
return unsigned + "." + signature, expires, nil
|
||||
}
|
||||
|
||||
func (manager TokenManager) Verify(token string) (Claims, error) {
|
||||
parts := strings.Split(token, ".")
|
||||
if len(parts) != 3 {
|
||||
return Claims{}, errors.New("invalid token")
|
||||
}
|
||||
unsigned := parts[0] + "." + parts[1]
|
||||
expected := manager.sign(unsigned)
|
||||
if !hmac.Equal([]byte(parts[2]), []byte(expected)) {
|
||||
return Claims{}, errors.New("invalid token signature")
|
||||
}
|
||||
payload, err := base64.RawURLEncoding.DecodeString(parts[1])
|
||||
if err != nil {
|
||||
return Claims{}, errors.New("invalid token payload")
|
||||
}
|
||||
var claims Claims
|
||||
if err := json.Unmarshal(payload, &claims); err != nil {
|
||||
return Claims{}, errors.New("invalid token claims")
|
||||
}
|
||||
if claims.Issuer != "balance-server" || claims.Subject == "" || time.Now().UTC().Unix() >= claims.Expires {
|
||||
return Claims{}, errors.New("expired or invalid token")
|
||||
}
|
||||
return claims, nil
|
||||
}
|
||||
|
||||
func RandomToken(bytes int) (string, error) {
|
||||
value := make([]byte, bytes)
|
||||
if _, err := rand.Read(value); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(value), nil
|
||||
}
|
||||
|
||||
func TokenHash(token string) string {
|
||||
hash := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(hash[:])
|
||||
}
|
||||
|
||||
func (manager TokenManager) sign(value string) string {
|
||||
mac := hmac.New(sha256.New, manager.secret)
|
||||
_, _ = mac.Write([]byte(value))
|
||||
return base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
|
||||
}
|
||||
|
||||
func encode(value []byte) string { return base64.RawURLEncoding.EncodeToString(value) }
|
||||
@@ -0,0 +1,93 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Address string
|
||||
DatabasePath string
|
||||
JWTSecret string
|
||||
AccessTTL time.Duration
|
||||
RefreshTTL time.Duration
|
||||
AllowRegistration bool
|
||||
CORSOrigins []string
|
||||
}
|
||||
|
||||
func Load() (Config, error) {
|
||||
accessTTL, err := duration("BALANCE_ACCESS_TTL", 15*time.Minute)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
refreshTTL, err := duration("BALANCE_REFRESH_TTL", 30*24*time.Hour)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
allowRegistration, err := boolean("BALANCE_ALLOW_REGISTRATION", true)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
cfg := Config{
|
||||
Address: env("BALANCE_ADDR", ":8080"),
|
||||
DatabasePath: env("BALANCE_DB_PATH", "./data/balance.db"),
|
||||
JWTSecret: strings.TrimSpace(os.Getenv("BALANCE_JWT_SECRET")),
|
||||
AccessTTL: accessTTL,
|
||||
RefreshTTL: refreshTTL,
|
||||
AllowRegistration: allowRegistration,
|
||||
CORSOrigins: split(os.Getenv("BALANCE_CORS_ORIGINS")),
|
||||
}
|
||||
if len(cfg.JWTSecret) < 32 {
|
||||
return Config{}, errors.New("BALANCE_JWT_SECRET must contain at least 32 characters")
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func env(key, fallback string) string {
|
||||
if value := strings.TrimSpace(os.Getenv(key)); value != "" {
|
||||
return value
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func duration(key string, fallback time.Duration) (time.Duration, error) {
|
||||
value := strings.TrimSpace(os.Getenv(key))
|
||||
if value == "" {
|
||||
return fallback, nil
|
||||
}
|
||||
parsed, err := time.ParseDuration(value)
|
||||
if err != nil {
|
||||
return 0, errors.New(key + " must be a Go duration such as 15m or 720h")
|
||||
}
|
||||
return parsed, nil
|
||||
}
|
||||
|
||||
func boolean(key string, fallback bool) (bool, error) {
|
||||
value := strings.TrimSpace(os.Getenv(key))
|
||||
if value == "" {
|
||||
return fallback, nil
|
||||
}
|
||||
parsed, err := strconv.ParseBool(value)
|
||||
if err != nil {
|
||||
return false, errors.New(key + " must be true or false")
|
||||
}
|
||||
return parsed, nil
|
||||
}
|
||||
|
||||
func split(value string) []string {
|
||||
if strings.TrimSpace(value) == "" {
|
||||
return nil
|
||||
}
|
||||
parts := strings.Split(value, ",")
|
||||
result := make([]string, 0, len(parts))
|
||||
for _, part := range parts {
|
||||
if item := strings.TrimSpace(part); item != "" {
|
||||
result = append(result, item)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
func Open(path string) (*sql.DB, error) {
|
||||
directory := filepath.Dir(path)
|
||||
if directory != "." {
|
||||
if err := os.MkdirAll(directory, 0o750); err != nil {
|
||||
return nil, fmt.Errorf("create database directory: %w", err)
|
||||
}
|
||||
}
|
||||
db, err := sql.Open("sqlite", path+"?_pragma=foreign_keys(1)&_pragma=journal_mode(WAL)&_pragma=busy_timeout(5000)")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
db.SetMaxOpenConns(1)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := db.PingContext(ctx); err != nil {
|
||||
_ = db.Close()
|
||||
return nil, err
|
||||
}
|
||||
if err := migrate(ctx, db); err != nil {
|
||||
_ = db.Close()
|
||||
return nil, err
|
||||
}
|
||||
return db, nil
|
||||
}
|
||||
|
||||
func migrate(ctx context.Context, db *sql.DB) error {
|
||||
const schema = `
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id TEXT PRIMARY KEY,
|
||||
email TEXT NOT NULL UNIQUE COLLATE NOCASE,
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS refresh_tokens (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
expires_at TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
revoked_at TEXT
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS refresh_tokens_user_idx ON refresh_tokens(user_id);
|
||||
CREATE TABLE IF NOT EXISTS records (
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
entity TEXT NOT NULL,
|
||||
record_id TEXT NOT NULL,
|
||||
payload TEXT,
|
||||
updated_at TEXT NOT NULL,
|
||||
deleted INTEGER NOT NULL DEFAULT 0,
|
||||
version INTEGER NOT NULL,
|
||||
PRIMARY KEY (user_id, entity, record_id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS changes (
|
||||
sequence INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
entity TEXT NOT NULL,
|
||||
record_id TEXT NOT NULL,
|
||||
payload TEXT,
|
||||
updated_at TEXT NOT NULL,
|
||||
deleted INTEGER NOT NULL,
|
||||
version INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS changes_user_sequence_idx ON changes(user_id, sequence);
|
||||
`
|
||||
_, err := db.ExecContext(ctx, schema)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"balance-server/internal/auth"
|
||||
)
|
||||
|
||||
type credentials struct {
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
type refreshRequest struct {
|
||||
RefreshToken string `json:"refreshToken"`
|
||||
}
|
||||
type userResponse struct {
|
||||
ID string `json:"id"`
|
||||
Email string `json:"email"`
|
||||
}
|
||||
type sessionResponse struct {
|
||||
AccessToken string `json:"accessToken"`
|
||||
RefreshToken string `json:"refreshToken"`
|
||||
ExpiresAt time.Time `json:"expiresAt"`
|
||||
User userResponse `json:"user"`
|
||||
}
|
||||
|
||||
func (api *API) register(w http.ResponseWriter, r *http.Request) {
|
||||
if !api.cfg.AllowRegistration {
|
||||
writeError(w, http.StatusForbidden, "registration_disabled", "Registration is disabled")
|
||||
return
|
||||
}
|
||||
var request credentials
|
||||
if !decodeJSON(w, r, &request) {
|
||||
return
|
||||
}
|
||||
email, err := normalizeEmail(request.Email)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid_email", "Enter a valid email address")
|
||||
return
|
||||
}
|
||||
passwordHash, err := auth.HashPassword(request.Password)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid_password", err.Error())
|
||||
return
|
||||
}
|
||||
userID, err := identifier()
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "internal_error", "Could not create account")
|
||||
return
|
||||
}
|
||||
_, err = api.db.ExecContext(r.Context(), `INSERT INTO users(id,email,password_hash,created_at) VALUES(?,?,?,?)`, userID, email, passwordHash, time.Now().UTC().Format(time.RFC3339Nano))
|
||||
if err != nil {
|
||||
if containsUnique(err) {
|
||||
writeError(w, http.StatusConflict, "email_exists", "An account with this email already exists")
|
||||
return
|
||||
}
|
||||
api.logger.Error("create user", "error", err)
|
||||
writeError(w, http.StatusInternalServerError, "internal_error", "Could not create account")
|
||||
return
|
||||
}
|
||||
response, err := api.createSession(r, userID, email)
|
||||
if err != nil {
|
||||
api.logger.Error("create session", "error", err)
|
||||
writeError(w, http.StatusInternalServerError, "internal_error", "Could not create session")
|
||||
return
|
||||
}
|
||||
api.setSessionCookies(w, r, response)
|
||||
writeJSON(w, http.StatusCreated, response)
|
||||
}
|
||||
|
||||
func (api *API) login(w http.ResponseWriter, r *http.Request) {
|
||||
var request credentials
|
||||
if !decodeJSON(w, r, &request) {
|
||||
return
|
||||
}
|
||||
email, err := normalizeEmail(request.Email)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusUnauthorized, "invalid_credentials", "Email or password is incorrect")
|
||||
return
|
||||
}
|
||||
var userID, passwordHash string
|
||||
err = api.db.QueryRowContext(r.Context(), `SELECT id,password_hash FROM users WHERE email=?`, email).Scan(&userID, &passwordHash)
|
||||
if err != nil || !auth.VerifyPassword(passwordHash, request.Password) {
|
||||
writeError(w, http.StatusUnauthorized, "invalid_credentials", "Email or password is incorrect")
|
||||
return
|
||||
}
|
||||
response, err := api.createSession(r, userID, email)
|
||||
if err != nil {
|
||||
api.logger.Error("create session", "error", err)
|
||||
writeError(w, http.StatusInternalServerError, "internal_error", "Could not create session")
|
||||
return
|
||||
}
|
||||
api.setSessionCookies(w, r, response)
|
||||
writeJSON(w, http.StatusOK, response)
|
||||
}
|
||||
|
||||
func (api *API) refresh(w http.ResponseWriter, r *http.Request) {
|
||||
var request refreshRequest
|
||||
if !decodeJSON(w, r, &request) {
|
||||
return
|
||||
}
|
||||
request.RefreshToken = api.refreshToken(r, request.RefreshToken)
|
||||
if request.RefreshToken == "" {
|
||||
writeError(w, http.StatusBadRequest, "refresh_token_required", "Refresh token is required")
|
||||
return
|
||||
}
|
||||
tx, err := api.db.BeginTx(r.Context(), nil)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "internal_error", "Could not refresh session")
|
||||
return
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var userID, email, expiresText string
|
||||
err = tx.QueryRowContext(r.Context(), `SELECT u.id,u.email,t.expires_at FROM refresh_tokens t JOIN users u ON u.id=t.user_id WHERE t.token_hash=? AND t.revoked_at IS NULL`, auth.TokenHash(request.RefreshToken)).Scan(&userID, &email, &expiresText)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusUnauthorized, "invalid_refresh_token", "Refresh token is invalid or expired")
|
||||
return
|
||||
}
|
||||
expires, err := time.Parse(time.RFC3339Nano, expiresText)
|
||||
if err != nil || !time.Now().UTC().Before(expires) {
|
||||
writeError(w, http.StatusUnauthorized, "invalid_refresh_token", "Refresh token is invalid or expired")
|
||||
return
|
||||
}
|
||||
_, err = tx.ExecContext(r.Context(), `UPDATE refresh_tokens SET revoked_at=? WHERE token_hash=?`, time.Now().UTC().Format(time.RFC3339Nano), auth.TokenHash(request.RefreshToken))
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "internal_error", "Could not refresh session")
|
||||
return
|
||||
}
|
||||
response, err := api.createSessionWithExecutor(r, userID, email, tx)
|
||||
if err != nil || tx.Commit() != nil {
|
||||
writeError(w, http.StatusInternalServerError, "internal_error", "Could not refresh session")
|
||||
return
|
||||
}
|
||||
api.setSessionCookies(w, r, response)
|
||||
writeJSON(w, http.StatusOK, response)
|
||||
}
|
||||
|
||||
func (api *API) logout(w http.ResponseWriter, r *http.Request) {
|
||||
var request refreshRequest
|
||||
if !decodeJSON(w, r, &request) {
|
||||
return
|
||||
}
|
||||
request.RefreshToken = api.refreshToken(r, request.RefreshToken)
|
||||
if request.RefreshToken != "" {
|
||||
_, _ = api.db.ExecContext(r.Context(), `UPDATE refresh_tokens SET revoked_at=? WHERE token_hash=? AND revoked_at IS NULL`, time.Now().UTC().Format(time.RFC3339Nano), auth.TokenHash(request.RefreshToken))
|
||||
}
|
||||
api.clearSessionCookies(w, r)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (api *API) me(w http.ResponseWriter, r *http.Request) {
|
||||
value := claims(r)
|
||||
writeJSON(w, http.StatusOK, userResponse{ID: value.Subject, Email: value.Email})
|
||||
}
|
||||
|
||||
func (api *API) createSession(r *http.Request, userID, email string) (sessionResponse, error) {
|
||||
return api.createSessionWithExecutor(r, userID, email, api.db)
|
||||
}
|
||||
|
||||
func (api *API) createSessionWithExecutor(r *http.Request, userID, email string, executor interface {
|
||||
ExecContext(context.Context, string, ...any) (sql.Result, error)
|
||||
}) (sessionResponse, error) {
|
||||
accessToken, expiresAt, err := api.tokens.AccessToken(userID, email)
|
||||
if err != nil {
|
||||
return sessionResponse{}, err
|
||||
}
|
||||
refreshToken, err := auth.RandomToken(48)
|
||||
if err != nil {
|
||||
return sessionResponse{}, err
|
||||
}
|
||||
refreshExpires := time.Now().UTC().Add(api.cfg.RefreshTTL)
|
||||
_, err = executor.ExecContext(r.Context(), `INSERT INTO refresh_tokens(token_hash,user_id,expires_at,created_at) VALUES(?,?,?,?)`, auth.TokenHash(refreshToken), userID, refreshExpires.Format(time.RFC3339Nano), time.Now().UTC().Format(time.RFC3339Nano))
|
||||
if err != nil {
|
||||
return sessionResponse{}, err
|
||||
}
|
||||
return sessionResponse{AccessToken: accessToken, RefreshToken: refreshToken, ExpiresAt: expiresAt, User: userResponse{ID: userID, Email: email}}, nil
|
||||
}
|
||||
|
||||
func identifier() (string, error) {
|
||||
value := make([]byte, 16)
|
||||
if _, err := rand.Read(value); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(value), nil
|
||||
}
|
||||
func containsUnique(err error) bool {
|
||||
return err != nil && strings.Contains(err.Error(), "UNIQUE constraint failed")
|
||||
}
|
||||
|
||||
const (
|
||||
accessCookieName = "balance_access"
|
||||
refreshCookieName = "balance_refresh"
|
||||
)
|
||||
|
||||
func (api *API) setSessionCookies(w http.ResponseWriter, r *http.Request, session sessionResponse) {
|
||||
secure := requestIsSecure(r)
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: accessCookieName, Value: session.AccessToken, Path: "/", HttpOnly: true,
|
||||
Secure: secure, SameSite: http.SameSiteStrictMode,
|
||||
Expires: session.ExpiresAt, MaxAge: maxAge(session.ExpiresAt),
|
||||
})
|
||||
refreshExpires := time.Now().UTC().Add(api.cfg.RefreshTTL)
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: refreshCookieName, Value: session.RefreshToken, Path: "/", HttpOnly: true,
|
||||
Secure: secure, SameSite: http.SameSiteStrictMode,
|
||||
Expires: refreshExpires, MaxAge: maxAge(refreshExpires),
|
||||
})
|
||||
}
|
||||
|
||||
func (api *API) clearSessionCookies(w http.ResponseWriter, r *http.Request) {
|
||||
for _, name := range []string{accessCookieName, refreshCookieName} {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: name, Value: "", Path: "/", HttpOnly: true, Secure: requestIsSecure(r),
|
||||
SameSite: http.SameSiteStrictMode, MaxAge: -1, Expires: time.Unix(1, 0),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (api *API) refreshToken(r *http.Request, value string) string {
|
||||
if value = strings.TrimSpace(value); value != "" {
|
||||
return value
|
||||
}
|
||||
if cookie, err := r.Cookie(refreshCookieName); err == nil {
|
||||
return strings.TrimSpace(cookie.Value)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func requestIsSecure(r *http.Request) bool {
|
||||
return r.TLS != nil || strings.EqualFold(strings.TrimSpace(r.Header.Get("X-Forwarded-Proto")), "https")
|
||||
}
|
||||
|
||||
func maxAge(expires time.Time) int {
|
||||
seconds := int(time.Until(expires).Seconds())
|
||||
if seconds < 1 {
|
||||
return 1
|
||||
}
|
||||
return seconds
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"balance-server/internal/auth"
|
||||
"balance-server/internal/config"
|
||||
)
|
||||
|
||||
type contextKey string
|
||||
|
||||
const claimsKey contextKey = "claims"
|
||||
|
||||
type API struct {
|
||||
cfg config.Config
|
||||
db *sql.DB
|
||||
tokens auth.TokenManager
|
||||
logger *slog.Logger
|
||||
limiter *rateLimiter
|
||||
}
|
||||
|
||||
func New(cfg config.Config, db *sql.DB, logger *slog.Logger) http.Handler {
|
||||
api := &API{cfg: cfg, db: db, tokens: auth.NewTokenManager(cfg.JWTSecret, cfg.AccessTTL), logger: logger, limiter: newRateLimiter()}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /health", api.health)
|
||||
mux.Handle("POST /v1/auth/register", api.limited(http.HandlerFunc(api.register)))
|
||||
mux.Handle("POST /v1/auth/login", api.limited(http.HandlerFunc(api.login)))
|
||||
mux.Handle("POST /v1/auth/refresh", api.limited(http.HandlerFunc(api.refresh)))
|
||||
mux.HandleFunc("POST /v1/auth/logout", api.logout)
|
||||
mux.Handle("GET /v1/me", api.authorized(http.HandlerFunc(api.me)))
|
||||
mux.Handle("POST /v1/sync", api.authorized(http.HandlerFunc(api.sync)))
|
||||
mux.HandleFunc("GET /", api.webApp)
|
||||
return api.recover(api.security(api.cors(mux)))
|
||||
}
|
||||
|
||||
func (api *API) health(w http.ResponseWriter, _ *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"status": "ok", "time": time.Now().UTC()})
|
||||
}
|
||||
|
||||
func (api *API) authorized(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
header := strings.TrimSpace(r.Header.Get("Authorization"))
|
||||
token := ""
|
||||
if strings.HasPrefix(header, "Bearer ") {
|
||||
token = strings.TrimSpace(strings.TrimPrefix(header, "Bearer "))
|
||||
} else if cookie, err := r.Cookie(accessCookieName); err == nil {
|
||||
token = strings.TrimSpace(cookie.Value)
|
||||
}
|
||||
if token == "" {
|
||||
writeError(w, http.StatusUnauthorized, "authorization_required", "Authorization Bearer token is required")
|
||||
return
|
||||
}
|
||||
claims, err := api.tokens.Verify(token)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusUnauthorized, "invalid_token", "Access token is invalid or expired")
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), claimsKey, claims)))
|
||||
})
|
||||
}
|
||||
|
||||
func claims(r *http.Request) auth.Claims {
|
||||
value, _ := r.Context().Value(claimsKey).(auth.Claims)
|
||||
return value
|
||||
}
|
||||
|
||||
func (api *API) security(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("X-Frame-Options", "DENY")
|
||||
w.Header().Set("Referrer-Policy", "no-referrer")
|
||||
w.Header().Set("Permissions-Policy", "camera=(), microphone=(), geolocation=(), payment=()")
|
||||
w.Header().Set("Content-Security-Policy", "default-src 'self'; base-uri 'none'; connect-src 'self'; font-src 'self'; form-action 'self'; frame-ancestors 'none'; img-src 'self' data:; manifest-src 'self'; script-src 'self'; style-src 'self'; worker-src 'self'")
|
||||
if strings.HasPrefix(r.URL.Path, "/v1/") {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func (api *API) cors(next http.Handler) http.Handler {
|
||||
allowed := make(map[string]bool, len(api.cfg.CORSOrigins))
|
||||
for _, origin := range api.cfg.CORSOrigins {
|
||||
allowed[origin] = true
|
||||
}
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
origin := r.Header.Get("Origin")
|
||||
if origin != "" && (allowed[origin] || allowed["*"]) {
|
||||
w.Header().Set("Access-Control-Allow-Origin", origin)
|
||||
w.Header().Set("Vary", "Origin")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
|
||||
}
|
||||
if r.Method == http.MethodOptions {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func (api *API) recover(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
if value := recover(); value != nil {
|
||||
api.logger.Error("request panic", "value", value)
|
||||
writeError(w, http.StatusInternalServerError, "internal_error", "Internal server error")
|
||||
}
|
||||
}()
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func decodeJSON(w http.ResponseWriter, r *http.Request, destination any) bool {
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 2<<20)
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(destination); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid_json", "Request body is not valid JSON")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, value any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(value)
|
||||
}
|
||||
|
||||
func writeError(w http.ResponseWriter, status int, code, message string) {
|
||||
writeJSON(w, status, map[string]any{"error": map[string]string{"code": code, "message": message}})
|
||||
}
|
||||
|
||||
type rateLimiter struct {
|
||||
mu sync.Mutex
|
||||
clients map[string]*rateBucket
|
||||
}
|
||||
type rateBucket struct {
|
||||
started time.Time
|
||||
count int
|
||||
}
|
||||
|
||||
func newRateLimiter() *rateLimiter { return &rateLimiter{clients: make(map[string]*rateBucket)} }
|
||||
func (api *API) limited(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil {
|
||||
host = r.RemoteAddr
|
||||
}
|
||||
now := time.Now()
|
||||
api.limiter.mu.Lock()
|
||||
bucket := api.limiter.clients[host]
|
||||
if bucket == nil || now.Sub(bucket.started) >= time.Minute {
|
||||
bucket = &rateBucket{started: now}
|
||||
api.limiter.clients[host] = bucket
|
||||
}
|
||||
bucket.count++
|
||||
blocked := bucket.count > 30
|
||||
api.limiter.mu.Unlock()
|
||||
if blocked {
|
||||
w.Header().Set("Retry-After", "60")
|
||||
writeError(w, http.StatusTooManyRequests, "rate_limited", "Too many authentication requests")
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func normalizeEmail(value string) (string, error) {
|
||||
email := strings.ToLower(strings.TrimSpace(value))
|
||||
if len(email) < 3 || len(email) > 254 || !strings.Contains(email, "@") {
|
||||
return "", errors.New("invalid email")
|
||||
}
|
||||
return email, nil
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"balance-server/internal/config"
|
||||
"balance-server/internal/database"
|
||||
)
|
||||
|
||||
func TestRegisterAndSynchronize(t *testing.T) {
|
||||
db, err := database.Open(filepath.Join(t.TempDir(), "test.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
cfg := config.Config{JWTSecret: "test-secret-that-is-longer-than-thirty-two-characters", AccessTTL: 15 * time.Minute, RefreshTTL: time.Hour, AllowRegistration: true}
|
||||
server := httptest.NewServer(New(cfg, db, slog.New(slog.NewTextHandler(io.Discard, nil))))
|
||||
defer server.Close()
|
||||
|
||||
register := request(t, http.MethodPost, server.URL+"/v1/auth/register", map[string]any{"email": "person@example.com", "password": "correct horse battery staple"}, "")
|
||||
if register.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("register status: %d", register.StatusCode)
|
||||
}
|
||||
var session sessionResponse
|
||||
decode(t, register, &session)
|
||||
if session.AccessToken == "" || session.RefreshToken == "" {
|
||||
t.Fatal("session tokens are empty")
|
||||
}
|
||||
|
||||
now := time.Now().UTC().Add(-time.Second)
|
||||
pull := false
|
||||
syncBody := syncRequest{DeviceID: "test", Pull: &pull, Changes: []syncChange{{Entity: "category", ID: "category-1", UpdatedAt: now, Payload: json.RawMessage(`{"name":"Food"}`)}}}
|
||||
synchronized := request(t, http.MethodPost, server.URL+"/v1/sync", syncBody, session.AccessToken)
|
||||
if synchronized.StatusCode != http.StatusOK {
|
||||
t.Fatalf("sync status: %d", synchronized.StatusCode)
|
||||
}
|
||||
var result syncResponse
|
||||
decode(t, synchronized, &result)
|
||||
if result.Cursor != 0 || len(result.Changes) != 0 {
|
||||
t.Fatalf("push-only response included pulled changes: %+v", result)
|
||||
}
|
||||
|
||||
pull = true
|
||||
synchronized = request(t, http.MethodPost, server.URL+"/v1/sync", syncRequest{DeviceID: "test", Pull: &pull}, session.AccessToken)
|
||||
if synchronized.StatusCode != http.StatusOK {
|
||||
t.Fatalf("pull status: %d", synchronized.StatusCode)
|
||||
}
|
||||
decode(t, synchronized, &result)
|
||||
if result.Cursor == 0 || len(result.Changes) != 1 || result.Changes[0].ID != "category-1" {
|
||||
t.Fatalf("unexpected sync response: %+v", result)
|
||||
}
|
||||
|
||||
pageStart := result.Cursor
|
||||
pageChanges := make([]syncChange, syncPageSize+1)
|
||||
for index := range pageChanges {
|
||||
pageChanges[index] = syncChange{
|
||||
Entity: "category", ID: "page-" + time.Unix(int64(index), 0).UTC().Format("150405"),
|
||||
UpdatedAt: now.Add(time.Duration(index+1) * time.Millisecond), Payload: json.RawMessage(`{"name":"Paged"}`),
|
||||
}
|
||||
}
|
||||
pull = false
|
||||
synchronized = request(t, http.MethodPost, server.URL+"/v1/sync", syncRequest{DeviceID: "test", Pull: &pull, Changes: pageChanges}, session.AccessToken)
|
||||
if synchronized.StatusCode != http.StatusOK {
|
||||
t.Fatalf("paged push status: %d", synchronized.StatusCode)
|
||||
}
|
||||
synchronized.Body.Close()
|
||||
|
||||
pull = true
|
||||
synchronized = request(t, http.MethodPost, server.URL+"/v1/sync", syncRequest{Cursor: pageStart, DeviceID: "test", Pull: &pull}, session.AccessToken)
|
||||
decode(t, synchronized, &result)
|
||||
if len(result.Changes) != syncPageSize || !result.HasMore {
|
||||
t.Fatalf("first page mismatch: count=%d hasMore=%v", len(result.Changes), result.HasMore)
|
||||
}
|
||||
synchronized = request(t, http.MethodPost, server.URL+"/v1/sync", syncRequest{Cursor: result.Cursor, DeviceID: "test", Pull: &pull}, session.AccessToken)
|
||||
decode(t, synchronized, &result)
|
||||
if len(result.Changes) != 1 || result.HasMore {
|
||||
t.Fatalf("last page mismatch: count=%d hasMore=%v", len(result.Changes), result.HasMore)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmbeddedWebAppAndCookieSession(t *testing.T) {
|
||||
db, err := database.Open(filepath.Join(t.TempDir(), "web.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
cfg := config.Config{JWTSecret: "test-secret-that-is-longer-than-thirty-two-characters", AccessTTL: 15 * time.Minute, RefreshTTL: time.Hour, AllowRegistration: true}
|
||||
server := httptest.NewServer(New(cfg, db, slog.New(slog.NewTextHandler(io.Discard, nil))))
|
||||
defer server.Close()
|
||||
|
||||
home, err := http.Get(server.URL + "/")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
homeBody, err := io.ReadAll(home.Body)
|
||||
home.Body.Close()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if home.StatusCode != http.StatusOK || !strings.Contains(string(homeBody), "id=\"app-view\"") {
|
||||
t.Fatalf("web app response: status=%d body=%q", home.StatusCode, string(homeBody))
|
||||
}
|
||||
if !strings.Contains(home.Header.Get("Content-Security-Policy"), "script-src 'self'") {
|
||||
t.Fatal("web app is missing its content security policy")
|
||||
}
|
||||
|
||||
register := request(t, http.MethodPost, server.URL+"/v1/auth/register", map[string]any{"email": "web@example.com", "password": "correct horse battery staple"}, "")
|
||||
if register.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("register status: %d", register.StatusCode)
|
||||
}
|
||||
cookies := register.Cookies()
|
||||
var session sessionResponse
|
||||
decode(t, register, &session)
|
||||
var accessCookie, refreshCookie *http.Cookie
|
||||
for _, cookie := range cookies {
|
||||
switch cookie.Name {
|
||||
case accessCookieName:
|
||||
accessCookie = cookie
|
||||
case refreshCookieName:
|
||||
refreshCookie = cookie
|
||||
}
|
||||
if !cookie.HttpOnly || cookie.SameSite != http.SameSiteStrictMode {
|
||||
t.Fatalf("insecure session cookie: %+v", cookie)
|
||||
}
|
||||
}
|
||||
if accessCookie == nil || refreshCookie == nil {
|
||||
t.Fatal("session cookies were not returned")
|
||||
}
|
||||
|
||||
meRequest, err := http.NewRequest(http.MethodGet, server.URL+"/v1/me", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
meRequest.AddCookie(accessCookie)
|
||||
me, err := http.DefaultClient.Do(meRequest)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if me.StatusCode != http.StatusOK {
|
||||
t.Fatalf("cookie authentication status: %d", me.StatusCode)
|
||||
}
|
||||
var user userResponse
|
||||
decode(t, me, &user)
|
||||
if user.Email != "web@example.com" {
|
||||
t.Fatalf("unexpected web user: %+v", user)
|
||||
}
|
||||
|
||||
refreshData, err := json.Marshal(refreshRequest{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
refreshHTTP, err := http.NewRequest(http.MethodPost, server.URL+"/v1/auth/refresh", bytes.NewReader(refreshData))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
refreshHTTP.Header.Set("Content-Type", "application/json")
|
||||
refreshHTTP.AddCookie(refreshCookie)
|
||||
refreshed, err := http.DefaultClient.Do(refreshHTTP)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if refreshed.StatusCode != http.StatusOK {
|
||||
t.Fatalf("cookie refresh status: %d", refreshed.StatusCode)
|
||||
}
|
||||
refreshed.Body.Close()
|
||||
}
|
||||
|
||||
func request(t *testing.T, method, url string, value any, token string) *http.Response {
|
||||
t.Helper()
|
||||
data, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req, err := http.NewRequest(method, url, bytes.NewReader(data))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
response, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
func decode(t *testing.T, response *http.Response, value any) {
|
||||
t.Helper()
|
||||
defer response.Body.Close()
|
||||
if err := json.NewDecoder(response.Body).Decode(value); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
const maxSyncChanges = 5000
|
||||
const syncPageSize = 500
|
||||
|
||||
type syncChange struct {
|
||||
Entity string `json:"entity"`
|
||||
ID string `json:"id"`
|
||||
Deleted bool `json:"deleted"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
Payload json.RawMessage `json:"payload,omitempty"`
|
||||
Version int64 `json:"version,omitempty"`
|
||||
Sequence int64 `json:"sequence,omitempty"`
|
||||
}
|
||||
type syncRequest struct {
|
||||
Cursor int64 `json:"cursor"`
|
||||
DeviceID string `json:"deviceId"`
|
||||
Changes []syncChange `json:"changes"`
|
||||
Pull *bool `json:"pull,omitempty"`
|
||||
}
|
||||
type syncResponse struct {
|
||||
Cursor int64 `json:"cursor"`
|
||||
Changes []syncChange `json:"changes"`
|
||||
ServerTime time.Time `json:"serverTime"`
|
||||
HasMore bool `json:"hasMore"`
|
||||
}
|
||||
|
||||
func (api *API) sync(w http.ResponseWriter, r *http.Request) {
|
||||
var request syncRequest
|
||||
if !decodeJSON(w, r, &request) {
|
||||
return
|
||||
}
|
||||
if request.Cursor < 0 || len(request.Changes) > maxSyncChanges {
|
||||
writeError(w, http.StatusBadRequest, "invalid_sync_request", "Cursor or change count is invalid")
|
||||
return
|
||||
}
|
||||
for index := range request.Changes {
|
||||
if err := validateChange(request.Changes[index]); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid_change", err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
userID := claims(r).Subject
|
||||
tx, err := api.db.BeginTx(r.Context(), nil)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "sync_failed", "Could not begin synchronization")
|
||||
return
|
||||
}
|
||||
defer tx.Rollback()
|
||||
for _, change := range request.Changes {
|
||||
if err := applyChange(r, tx, userID, change); err != nil {
|
||||
api.logger.Error("apply sync change", "error", err)
|
||||
writeError(w, http.StatusInternalServerError, "sync_failed", "Could not apply changes")
|
||||
return
|
||||
}
|
||||
}
|
||||
changes := make([]syncChange, 0)
|
||||
cursor := request.Cursor
|
||||
hasMore := false
|
||||
shouldPull := request.Pull == nil || *request.Pull
|
||||
if shouldPull {
|
||||
changes, cursor, hasMore, err = loadChanges(r, tx, userID, request.Cursor)
|
||||
if err != nil {
|
||||
api.logger.Error("load sync changes", "error", err)
|
||||
writeError(w, http.StatusInternalServerError, "sync_failed", "Could not load changes")
|
||||
return
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "sync_failed", "Could not complete synchronization")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, syncResponse{Cursor: cursor, Changes: changes, ServerTime: time.Now().UTC(), HasMore: hasMore})
|
||||
}
|
||||
|
||||
func validateChange(change syncChange) error {
|
||||
if change.Entity != "transaction" && change.Entity != "category" && change.Entity != "budget" {
|
||||
return errors.New("entity must be transaction, category, or budget")
|
||||
}
|
||||
if len(change.ID) < 1 || len(change.ID) > 128 {
|
||||
return errors.New("record id is invalid")
|
||||
}
|
||||
if change.UpdatedAt.IsZero() {
|
||||
return errors.New("updatedAt is required")
|
||||
}
|
||||
if change.UpdatedAt.After(time.Now().UTC().Add(24 * time.Hour)) {
|
||||
return errors.New("updatedAt is too far in the future")
|
||||
}
|
||||
if !change.Deleted && (len(change.Payload) == 0 || !json.Valid(change.Payload)) {
|
||||
return errors.New("payload is required for active records")
|
||||
}
|
||||
if len(change.Payload) > 256*1024 {
|
||||
return errors.New("payload is too large")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func applyChange(r *http.Request, tx *sql.Tx, userID string, incoming syncChange) error {
|
||||
var currentUpdated string
|
||||
var currentVersion int64
|
||||
err := tx.QueryRowContext(r.Context(), `SELECT updated_at,version FROM records WHERE user_id=? AND entity=? AND record_id=?`, userID, incoming.Entity, incoming.ID).Scan(¤tUpdated, ¤tVersion)
|
||||
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||
return err
|
||||
}
|
||||
if err == nil {
|
||||
parsed, parseErr := time.Parse(time.RFC3339Nano, currentUpdated)
|
||||
if parseErr != nil {
|
||||
return parseErr
|
||||
}
|
||||
if !incoming.UpdatedAt.After(parsed) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
version := currentVersion + 1
|
||||
updated := incoming.UpdatedAt.UTC().Format(time.RFC3339Nano)
|
||||
var payload any
|
||||
if !incoming.Deleted {
|
||||
payload = string(incoming.Payload)
|
||||
}
|
||||
_, err = tx.ExecContext(r.Context(), `INSERT INTO records(user_id,entity,record_id,payload,updated_at,deleted,version) VALUES(?,?,?,?,?,?,?)
|
||||
ON CONFLICT(user_id,entity,record_id) DO UPDATE SET payload=excluded.payload,updated_at=excluded.updated_at,deleted=excluded.deleted,version=excluded.version`,
|
||||
userID, incoming.Entity, incoming.ID, payload, updated, incoming.Deleted, version)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tx.ExecContext(r.Context(), `INSERT INTO changes(user_id,entity,record_id,payload,updated_at,deleted,version) VALUES(?,?,?,?,?,?,?)`, userID, incoming.Entity, incoming.ID, payload, updated, incoming.Deleted, version)
|
||||
return err
|
||||
}
|
||||
|
||||
func loadChanges(r *http.Request, tx *sql.Tx, userID string, after int64) ([]syncChange, int64, bool, error) {
|
||||
rows, err := tx.QueryContext(r.Context(), `SELECT sequence,entity,record_id,payload,updated_at,deleted,version FROM changes WHERE user_id=? AND sequence>? ORDER BY sequence ASC LIMIT ?`, userID, after, syncPageSize+1)
|
||||
if err != nil {
|
||||
return nil, after, false, err
|
||||
}
|
||||
defer rows.Close()
|
||||
result := make([]syncChange, 0)
|
||||
cursor := after
|
||||
hasMore := false
|
||||
for rows.Next() {
|
||||
if len(result) == syncPageSize {
|
||||
hasMore = true
|
||||
break
|
||||
}
|
||||
var item syncChange
|
||||
var payload sql.NullString
|
||||
var updated string
|
||||
if err := rows.Scan(&item.Sequence, &item.Entity, &item.ID, &payload, &updated, &item.Deleted, &item.Version); err != nil {
|
||||
return nil, after, false, err
|
||||
}
|
||||
item.UpdatedAt, err = time.Parse(time.RFC3339Nano, updated)
|
||||
if err != nil {
|
||||
return nil, after, false, err
|
||||
}
|
||||
if payload.Valid {
|
||||
item.Payload = json.RawMessage(payload.String)
|
||||
}
|
||||
cursor = item.Sequence
|
||||
result = append(result, item)
|
||||
}
|
||||
return result, cursor, hasMore, rows.Err()
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"path"
|
||||
"strings"
|
||||
)
|
||||
|
||||
//go:embed web/*
|
||||
var embeddedWeb embed.FS
|
||||
|
||||
var webContent = func() http.Handler {
|
||||
content, err := fs.Sub(embeddedWeb, "web")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return http.FileServer(http.FS(content))
|
||||
}()
|
||||
|
||||
func (api *API) webApp(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.HasPrefix(r.URL.Path, "/v1/") {
|
||||
writeError(w, http.StatusNotFound, "not_found", "Endpoint not found")
|
||||
return
|
||||
}
|
||||
cleaned := path.Clean(r.URL.Path)
|
||||
if cleaned == "." || cleaned == "/" || cleaned == "/index.html" || cleaned == "/service-worker.js" {
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
} else {
|
||||
w.Header().Set("Cache-Control", "public, max-age=3600")
|
||||
}
|
||||
webContent.ServeHTTP(w, r)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,19 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" role="img" aria-labelledby="title">
|
||||
<title id="title">Balance</title>
|
||||
<defs>
|
||||
<linearGradient id="bg" x1="70" y1="36" x2="446" y2="476" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#7777ef"/>
|
||||
<stop offset="1" stop-color="#4242b8"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="shine" x1="144" y1="122" x2="366" y2="386" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#fff"/>
|
||||
<stop offset="1" stop-color="#dedfff"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect x="28" y="28" width="456" height="456" rx="128" fill="url(#bg)"/>
|
||||
<path d="M141 173c0-25 20-45 45-45h140c25 0 45 20 45 45v18H186c-25 0-45 20-45 45v-63Z" fill="#fff" opacity=".5"/>
|
||||
<path d="M116 222c0-28 23-51 51-51h179c28 0 51 23 51 51v126c0 28-23 51-51 51H167c-28 0-51-23-51-51V222Z" fill="url(#shine)"/>
|
||||
<path d="M302 258h95v86h-95c-24 0-43-19-43-43s19-43 43-43Z" fill="#5b5bd6"/>
|
||||
<circle cx="306" cy="301" r="13" fill="#fff"/>
|
||||
<path d="M184 250h44M184 289h44M184 328h44" stroke="#5b5bd6" stroke-width="18" stroke-linecap="round" opacity=".72"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.1 KiB |
@@ -0,0 +1,106 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<meta name="theme-color" content="#5b5bd6">
|
||||
<meta name="description" content="Balance — личные финансы на вашем сервере">
|
||||
<title>Balance</title>
|
||||
<link rel="icon" href="/icon.svg" type="image/svg+xml">
|
||||
<link rel="manifest" href="/manifest.webmanifest">
|
||||
<link rel="stylesheet" href="/styles.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="toast-region" class="toast-region" aria-live="polite" aria-atomic="true"></div>
|
||||
|
||||
<main id="auth-view" class="auth-layout">
|
||||
<section class="auth-card" aria-labelledby="auth-title">
|
||||
<div class="brand brand-auth">
|
||||
<img src="/icon.svg" alt="" width="58" height="58">
|
||||
<div>
|
||||
<span class="brand-name">Balance</span>
|
||||
<span class="brand-caption">Ваши финансы. Ваш сервер.</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="auth-copy">
|
||||
<p class="eyebrow">SELF-HOSTED</p>
|
||||
<h1 id="auth-title">Финансы под вашим контролем</h1>
|
||||
<p>Войдите в аккаунт этого сервера. Операции синхронизируются с iPhone, Apple Watch, Mac и Android.</p>
|
||||
</div>
|
||||
<div class="segmented auth-switch" role="tablist" aria-label="Вход или регистрация">
|
||||
<button type="button" class="is-active" data-auth-mode="login" role="tab">Войти</button>
|
||||
<button type="button" data-auth-mode="register" role="tab">Регистрация</button>
|
||||
</div>
|
||||
<form id="auth-form" class="stack" autocomplete="on">
|
||||
<label class="field">
|
||||
<span>Email</span>
|
||||
<input id="auth-email" name="email" type="email" inputmode="email" autocomplete="email" required maxlength="254" placeholder="name@example.com">
|
||||
</label>
|
||||
<label class="field">
|
||||
<span>Пароль</span>
|
||||
<input id="auth-password" name="password" type="password" autocomplete="current-password" required minlength="8" maxlength="1024" placeholder="Минимум 8 символов">
|
||||
</label>
|
||||
<p id="auth-error" class="form-error" role="alert" hidden></p>
|
||||
<button id="auth-submit" class="button button-primary button-large" type="submit">Войти</button>
|
||||
</form>
|
||||
<p class="security-note"><span aria-hidden="true">🔒</span> Сессия хранится в защищённых HttpOnly-cookie и недоступна JavaScript.</p>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<div id="app-view" class="app-shell" hidden>
|
||||
<aside class="sidebar">
|
||||
<div class="brand sidebar-brand">
|
||||
<img src="/icon.svg" alt="" width="42" height="42">
|
||||
<div>
|
||||
<span class="brand-name">Balance</span>
|
||||
<span class="brand-caption">Личные финансы</span>
|
||||
</div>
|
||||
</div>
|
||||
<nav class="side-nav" aria-label="Основная навигация">
|
||||
<button type="button" data-route="dashboard"><span>⌂</span> Обзор</button>
|
||||
<button type="button" data-route="transactions"><span>↕</span> Операции</button>
|
||||
<button type="button" data-route="analytics"><span>◫</span> Аналитика</button>
|
||||
<button type="button" data-route="budgets"><span>◎</span> Бюджеты</button>
|
||||
<button type="button" data-route="categories"><span>◆</span> Категории</button>
|
||||
<button type="button" data-route="settings"><span>⚙</span> Настройки</button>
|
||||
</nav>
|
||||
<div class="sidebar-footer">
|
||||
<div id="sync-pill" class="sync-pill"><span></span><span>Синхронизировано</span></div>
|
||||
<div class="account-mini">
|
||||
<div class="avatar" id="account-avatar">Б</div>
|
||||
<div>
|
||||
<strong id="account-email">—</strong>
|
||||
<span>Личный аккаунт</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<main class="workspace">
|
||||
<header class="mobile-header">
|
||||
<div class="brand">
|
||||
<img src="/icon.svg" alt="" width="36" height="36">
|
||||
<span class="brand-name">Balance</span>
|
||||
</div>
|
||||
<button type="button" class="icon-button" data-action="sync" aria-label="Синхронизировать">↻</button>
|
||||
</header>
|
||||
<div id="content" class="content" tabindex="-1"></div>
|
||||
</main>
|
||||
|
||||
<nav class="bottom-nav" aria-label="Мобильная навигация">
|
||||
<button type="button" data-route="dashboard"><span>⌂</span><small>Обзор</small></button>
|
||||
<button type="button" data-route="transactions"><span>↕</span><small>Операции</small></button>
|
||||
<button type="button" data-route="analytics"><span>◫</span><small>Аналитика</small></button>
|
||||
<button type="button" data-route="budgets"><span>◎</span><small>Бюджеты</small></button>
|
||||
<button type="button" data-route="settings"><span>⚙</span><small>Ещё</small></button>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
<dialog id="editor-dialog" class="modal">
|
||||
<div id="dialog-content"></div>
|
||||
</dialog>
|
||||
|
||||
<noscript>Для работы Balance необходимо включить JavaScript.</noscript>
|
||||
<script src="/app.js" defer></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"name": "Balance — личные финансы",
|
||||
"short_name": "Balance",
|
||||
"description": "Self-hosted приложение для управления личными финансами",
|
||||
"start_url": "/",
|
||||
"scope": "/",
|
||||
"display": "standalone",
|
||||
"background_color": "#f4f5f8",
|
||||
"theme_color": "#5b5bd6",
|
||||
"icons": [
|
||||
{ "src": "/icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any maskable" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
const CACHE = "balance-shell-v2";
|
||||
const SHELL = ["/", "/styles.css", "/app.js", "/icon.svg", "/manifest.webmanifest"];
|
||||
|
||||
self.addEventListener("install", event => {
|
||||
event.waitUntil(caches.open(CACHE).then(cache => cache.addAll(SHELL)));
|
||||
self.skipWaiting();
|
||||
});
|
||||
|
||||
self.addEventListener("activate", event => {
|
||||
event.waitUntil(caches.keys().then(keys => Promise.all(keys.filter(key => key !== CACHE).map(key => caches.delete(key)))));
|
||||
self.clients.claim();
|
||||
});
|
||||
|
||||
self.addEventListener("fetch", event => {
|
||||
const url = new URL(event.request.url);
|
||||
if (event.request.method !== "GET" || url.origin !== self.location.origin || url.pathname.startsWith("/v1/") || url.pathname === "/health") return;
|
||||
event.respondWith(fetch(event.request).then(response => {
|
||||
const copy = response.clone();
|
||||
caches.open(CACHE).then(cache => cache.put(event.request, copy));
|
||||
return response;
|
||||
}).catch(() => caches.match(event.request).then(response => response || caches.match("/"))));
|
||||
});
|
||||
@@ -0,0 +1,487 @@
|
||||
:root {
|
||||
color-scheme: light;
|
||||
--bg: #f4f5f8;
|
||||
--surface: #ffffff;
|
||||
--surface-soft: #f8f8fb;
|
||||
--surface-strong: #edeef3;
|
||||
--text: #17171c;
|
||||
--muted: #70717c;
|
||||
--border: #e3e4ea;
|
||||
--primary: #5b5bd6;
|
||||
--primary-strong: #4747bd;
|
||||
--primary-soft: #ececfe;
|
||||
--green: #16a36a;
|
||||
--green-soft: #e8f7f0;
|
||||
--red: #e05252;
|
||||
--red-soft: #fcecec;
|
||||
--orange: #f28c38;
|
||||
--shadow: 0 16px 44px rgb(31 35 55 / 8%);
|
||||
--radius: 20px;
|
||||
--sidebar: 252px;
|
||||
font-family: Inter, ui-rounded, "SF Pro Rounded", "SF Pro Display", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
font-synthesis: none;
|
||||
}
|
||||
|
||||
:root[data-theme="dark"] {
|
||||
color-scheme: dark;
|
||||
--bg: #111116;
|
||||
--surface: #1b1b21;
|
||||
--surface-soft: #222229;
|
||||
--surface-strong: #2a2a32;
|
||||
--text: #f5f5f7;
|
||||
--muted: #a6a6b0;
|
||||
--border: #303039;
|
||||
--primary: #8888f5;
|
||||
--primary-strong: #9d9dff;
|
||||
--primary-soft: #29294b;
|
||||
--green-soft: #15392b;
|
||||
--red-soft: #422326;
|
||||
--shadow: 0 18px 50px rgb(0 0 0 / 28%);
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
html { min-height: 100%; background: var(--bg); }
|
||||
body { margin: 0; min-width: 320px; min-height: 100vh; background: var(--bg); color: var(--text); }
|
||||
button, input, select, textarea { font: inherit; }
|
||||
button { color: inherit; }
|
||||
button, select { cursor: pointer; }
|
||||
img { display: block; }
|
||||
[hidden] { display: none !important; }
|
||||
|
||||
:focus-visible { outline: 3px solid color-mix(in srgb, var(--primary) 42%, transparent); outline-offset: 2px; }
|
||||
|
||||
.auth-layout {
|
||||
min-height: 100vh;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 32px 18px;
|
||||
background:
|
||||
radial-gradient(circle at 12% 10%, color-mix(in srgb, var(--primary) 16%, transparent), transparent 32%),
|
||||
radial-gradient(circle at 88% 88%, color-mix(in srgb, var(--green) 10%, transparent), transparent 30%),
|
||||
var(--bg);
|
||||
}
|
||||
|
||||
.auth-card {
|
||||
width: min(100%, 480px);
|
||||
padding: 30px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 30px;
|
||||
background: color-mix(in srgb, var(--surface) 94%, transparent);
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
.brand { display: flex; align-items: center; gap: 11px; }
|
||||
.brand-auth { margin-bottom: 32px; }
|
||||
.brand-name { display: block; font-size: 20px; line-height: 1.05; font-weight: 800; letter-spacing: -.4px; }
|
||||
.brand-caption { display: block; margin-top: 4px; color: var(--muted); font-size: 12px; }
|
||||
.auth-copy h1 { margin: 4px 0 12px; font-size: clamp(30px, 7vw, 42px); line-height: 1.04; letter-spacing: -1.6px; }
|
||||
.auth-copy > p:last-child { margin: 0 0 24px; color: var(--muted); line-height: 1.55; }
|
||||
.eyebrow { margin: 0; color: var(--primary); font-size: 11px; font-weight: 800; letter-spacing: 1.6px; }
|
||||
.security-note { display: flex; gap: 8px; margin: 20px 0 0; color: var(--muted); font-size: 12px; line-height: 1.45; }
|
||||
|
||||
.stack { display: grid; gap: 14px; }
|
||||
.field { display: grid; gap: 7px; }
|
||||
.field > span, .field-label { color: var(--muted); font-size: 12px; font-weight: 700; }
|
||||
.field input, .field select, .field textarea, .select-control, .search-control {
|
||||
width: 100%;
|
||||
min-height: 46px;
|
||||
padding: 11px 13px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 13px;
|
||||
background: var(--surface-soft);
|
||||
color: var(--text);
|
||||
outline: none;
|
||||
transition: border-color .16s, box-shadow .16s, background .16s;
|
||||
}
|
||||
.field textarea { min-height: 88px; resize: vertical; }
|
||||
.field input:focus, .field select:focus, .field textarea:focus, .select-control:focus, .search-control:focus {
|
||||
border-color: var(--primary);
|
||||
box-shadow: 0 0 0 3px color-mix(in srgb, var(--primary) 14%, transparent);
|
||||
background: var(--surface);
|
||||
}
|
||||
.form-error { margin: -2px 0 0; padding: 10px 12px; border-radius: 11px; background: var(--red-soft); color: var(--red); font-size: 13px; }
|
||||
|
||||
.segmented { display: flex; gap: 4px; padding: 4px; border-radius: 13px; background: var(--surface-strong); }
|
||||
.segmented button { flex: 1; min-height: 38px; border: 0; border-radius: 10px; background: transparent; color: var(--muted); font-size: 13px; font-weight: 700; }
|
||||
.segmented button.is-active { background: var(--surface); color: var(--text); box-shadow: 0 2px 10px rgb(0 0 0 / 7%); }
|
||||
.auth-switch { margin-bottom: 17px; }
|
||||
|
||||
.button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
min-height: 40px;
|
||||
padding: 9px 15px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
background: var(--surface);
|
||||
color: var(--text);
|
||||
font-weight: 700;
|
||||
font-size: 13px;
|
||||
text-decoration: none;
|
||||
transition: transform .14s, background .14s, border-color .14s;
|
||||
}
|
||||
.button:hover { background: var(--surface-soft); border-color: color-mix(in srgb, var(--primary) 30%, var(--border)); }
|
||||
.button:active { transform: scale(.98); }
|
||||
.button:disabled { cursor: not-allowed; opacity: .55; }
|
||||
.button-large { min-height: 48px; font-size: 14px; }
|
||||
.button-primary { border-color: var(--primary); background: var(--primary); color: white; }
|
||||
.button-primary:hover { border-color: var(--primary-strong); background: var(--primary-strong); }
|
||||
.button-danger { border-color: color-mix(in srgb, var(--red) 25%, var(--border)); color: var(--red); }
|
||||
.button-ghost { border-color: transparent; background: transparent; color: var(--muted); }
|
||||
.button-row { display: flex; flex-wrap: wrap; gap: 9px; }
|
||||
|
||||
.app-shell { min-height: 100vh; }
|
||||
.sidebar {
|
||||
position: fixed;
|
||||
inset: 0 auto 0 0;
|
||||
z-index: 20;
|
||||
display: flex;
|
||||
width: var(--sidebar);
|
||||
flex-direction: column;
|
||||
padding: 24px 16px 18px;
|
||||
border-right: 1px solid var(--border);
|
||||
background: var(--surface);
|
||||
}
|
||||
.sidebar-brand { padding: 0 8px 24px; }
|
||||
.side-nav { display: grid; gap: 5px; }
|
||||
.side-nav button {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
min-height: 45px;
|
||||
padding: 8px 13px;
|
||||
border: 0;
|
||||
border-radius: 13px;
|
||||
background: transparent;
|
||||
color: var(--muted);
|
||||
text-align: left;
|
||||
font-weight: 700;
|
||||
font-size: 14px;
|
||||
}
|
||||
.side-nav button span { display: grid; width: 22px; place-items: center; font-size: 20px; }
|
||||
.side-nav button:hover { background: var(--surface-soft); color: var(--text); }
|
||||
.side-nav button.is-active { background: var(--primary-soft); color: var(--primary-strong); }
|
||||
.sidebar-footer { display: grid; gap: 14px; margin-top: auto; }
|
||||
.sync-pill { display: flex; align-items: center; gap: 8px; padding: 0 9px; color: var(--muted); font-size: 11px; }
|
||||
.sync-pill > span:first-child { width: 8px; height: 8px; border-radius: 50%; background: var(--green); box-shadow: 0 0 0 4px var(--green-soft); }
|
||||
.sync-pill.is-syncing > span:first-child { background: var(--orange); animation: pulse 1s infinite; }
|
||||
.sync-pill.is-error > span:first-child { background: var(--red); box-shadow: 0 0 0 4px var(--red-soft); }
|
||||
@keyframes pulse { 50% { opacity: .35; } }
|
||||
.account-mini { display: flex; align-items: center; gap: 10px; padding: 12px 9px 0; border-top: 1px solid var(--border); overflow: hidden; }
|
||||
.account-mini > div:last-child { min-width: 0; }
|
||||
.account-mini strong, .account-mini span { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.account-mini strong { font-size: 12px; }
|
||||
.account-mini span { margin-top: 3px; color: var(--muted); font-size: 10px; }
|
||||
.avatar { display: grid; width: 34px; height: 34px; flex: 0 0 auto; place-items: center; border-radius: 11px; background: var(--primary-soft); color: var(--primary-strong); font-weight: 800; }
|
||||
|
||||
.workspace { min-height: 100vh; margin-left: var(--sidebar); }
|
||||
.content { width: min(1180px, 100%); margin: 0 auto; padding: 38px 36px 60px; }
|
||||
.mobile-header, .bottom-nav { display: none; }
|
||||
.page-header { display: flex; align-items: flex-end; justify-content: space-between; gap: 18px; margin-bottom: 25px; }
|
||||
.page-header h1 { margin: 2px 0 0; font-size: clamp(27px, 4vw, 38px); line-height: 1.08; letter-spacing: -1.25px; }
|
||||
.page-header p { margin: 7px 0 0; color: var(--muted); font-size: 13px; }
|
||||
.page-actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 9px; }
|
||||
|
||||
.grid { display: grid; gap: 16px; }
|
||||
.grid-2 { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.grid-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
||||
.grid-4 { grid-template-columns: repeat(4, minmax(0, 1fr)); }
|
||||
.dashboard-grid { grid-template-columns: minmax(0, 1.45fr) minmax(300px, .9fr); align-items: start; }
|
||||
.span-2 { grid-column: span 2; }
|
||||
.card { border: 1px solid var(--border); border-radius: var(--radius); background: var(--surface); box-shadow: 0 8px 30px rgb(31 35 55 / 4%); }
|
||||
.card-body { padding: 20px; }
|
||||
.card-header { display: flex; align-items: center; justify-content: space-between; gap: 14px; padding: 19px 20px 0; }
|
||||
.card-header h2, .card-header h3 { margin: 0; font-size: 16px; letter-spacing: -.25px; }
|
||||
.card-header + .card-body { padding-top: 15px; }
|
||||
.hero-balance {
|
||||
position: relative;
|
||||
min-height: 230px;
|
||||
overflow: hidden;
|
||||
padding: 26px;
|
||||
border: 0;
|
||||
background: linear-gradient(135deg, #6868e9, #4747b9);
|
||||
color: white;
|
||||
box-shadow: 0 20px 42px rgb(70 70 185 / 23%);
|
||||
}
|
||||
.hero-balance::after { content: ""; position: absolute; right: -80px; bottom: -125px; width: 290px; height: 290px; border: 44px solid rgb(255 255 255 / 8%); border-radius: 50%; }
|
||||
.hero-balance .hero-label { position: relative; z-index: 1; margin: 0; color: rgb(255 255 255 / 72%); font-size: 13px; font-weight: 700; }
|
||||
.hero-value { position: relative; z-index: 1; margin: 13px 0 23px; font-size: clamp(33px, 5vw, 50px); font-weight: 850; letter-spacing: -2px; }
|
||||
.hero-meta { position: relative; z-index: 1; display: flex; flex-wrap: wrap; gap: 10px 24px; }
|
||||
.hero-meta div span, .metric-card span { display: block; font-size: 11px; font-weight: 700; }
|
||||
.hero-meta div span { color: rgb(255 255 255 / 66%); }
|
||||
.hero-meta div strong { display: block; margin-top: 5px; font-size: 15px; }
|
||||
.hero-balance .button { position: relative; z-index: 1; margin-top: 22px; border-color: rgb(255 255 255 / 28%); background: rgb(255 255 255 / 13%); color: white; }
|
||||
.hero-balance .button:hover { background: rgb(255 255 255 / 20%); }
|
||||
|
||||
.metric-card { min-height: 118px; padding: 17px; }
|
||||
.metric-card span { color: var(--muted); }
|
||||
.metric-card strong { display: block; margin-top: 12px; font-size: 23px; letter-spacing: -.8px; }
|
||||
.metric-card .metric-foot { margin-top: 6px; color: var(--muted); font-size: 11px; }
|
||||
.metric-card.is-income strong { color: var(--green); }
|
||||
.metric-card.is-expense strong { color: var(--red); }
|
||||
.metric-card.is-primary strong { color: var(--primary); }
|
||||
|
||||
.list { display: grid; }
|
||||
.list-row { display: flex; align-items: center; gap: 12px; min-width: 0; padding: 13px 0; border-bottom: 1px solid var(--border); }
|
||||
.list-row:first-child { padding-top: 3px; }
|
||||
.list-row:last-child { padding-bottom: 3px; border-bottom: 0; }
|
||||
.row-main { min-width: 0; flex: 1; }
|
||||
.row-main strong, .row-main span { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.row-main strong { font-size: 13px; }
|
||||
.row-main span { margin-top: 4px; color: var(--muted); font-size: 11px; }
|
||||
.row-value { flex: 0 0 auto; text-align: right; }
|
||||
.row-value strong, .row-value span { display: block; }
|
||||
.row-value strong { font-size: 13px; }
|
||||
.row-value span { margin-top: 4px; color: var(--muted); font-size: 10px; }
|
||||
.amount-income { color: var(--green); }
|
||||
.amount-expense { color: var(--text); }
|
||||
.row-actions { display: flex; gap: 3px; opacity: .25; transition: opacity .15s; }
|
||||
.list-row:hover .row-actions { opacity: 1; }
|
||||
.icon-button { display: grid; width: 36px; height: 36px; flex: 0 0 auto; place-items: center; border: 0; border-radius: 10px; background: transparent; color: var(--muted); }
|
||||
.icon-button:hover { background: var(--surface-strong); color: var(--text); }
|
||||
.icon-button.is-danger:hover { background: var(--red-soft); color: var(--red); }
|
||||
|
||||
.category-badge { display: grid; width: 43px; height: 43px; flex: 0 0 auto; place-items: center; border-radius: 14px; font-size: 20px; font-weight: 800; }
|
||||
.category-badge.small { width: 34px; height: 34px; border-radius: 11px; font-size: 16px; }
|
||||
.category-badge.large { width: 58px; height: 58px; border-radius: 18px; font-size: 26px; }
|
||||
.category-badge .symbol { font-size: .88em; }
|
||||
.color-red { color: #e05252; background: #e0525222; } .color-orange { color: #f28c38; background: #f28c3822; }
|
||||
.color-yellow { color: #e0ac24; background: #e0ac2422; } .color-green { color: #16a36a; background: #16a36a22; }
|
||||
.color-mint { color: #31b99a; background: #31b99a22; } .color-teal { color: #159eaf; background: #159eaf22; }
|
||||
.color-cyan { color: #209bcc; background: #209bcc22; } .color-blue { color: #3979e9; background: #3979e922; }
|
||||
.color-indigo { color: #5b5bd6; background: #5b5bd622; } .color-purple { color: #8b5cf6; background: #8b5cf622; }
|
||||
.color-pink { color: #e35c9a; background: #e35c9a22; } .color-brown { color: #9b6a4a; background: #9b6a4a22; }
|
||||
.color-gray { color: #7a7a85; background: #7a7a8522; } .color-coral { color: #fa6161; background: #fa616122; }
|
||||
.color-peach { color: #ff9461; background: #ff946122; } .color-gold { color: #e6a314; background: #e6a31422; }
|
||||
.color-lime { color: #85c729; background: #85c72922; } .color-forest { color: #1a7a4d; background: #1a7a4d22; }
|
||||
.color-turquoise { color: #0daba1; background: #0daba122; } .color-sky { color: #2e9ee8; background: #2e9ee822; }
|
||||
.color-navy { color: #365ca8; background: #1f408522; } .color-lavender { color: #8c66d9; background: #8c66d922; }
|
||||
.color-magenta { color: #d1298c; background: #d1298c22; } .color-slate { color: #66758e; background: #4d5c7322; }
|
||||
|
||||
.toolbar { display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 16px; }
|
||||
.toolbar .search-wrap { position: relative; min-width: 220px; flex: 1; }
|
||||
.toolbar .search-wrap::before { content: "⌕"; position: absolute; top: 50%; left: 13px; transform: translateY(-50%); color: var(--muted); }
|
||||
.toolbar .search-control { padding-left: 38px; }
|
||||
.toolbar .select-control { width: auto; min-width: 150px; }
|
||||
.operations-card .card-body { padding-top: 9px; }
|
||||
.operations-card .list-row { padding: 14px 0; }
|
||||
|
||||
.empty-state { display: grid; min-height: 210px; place-items: center; padding: 35px; text-align: center; }
|
||||
.empty-state .empty-icon { display: grid; width: 62px; height: 62px; place-items: center; margin: 0 auto 14px; border-radius: 20px; background: var(--primary-soft); color: var(--primary); font-size: 27px; }
|
||||
.empty-state h3 { margin: 0; font-size: 16px; }
|
||||
.empty-state p { max-width: 390px; margin: 8px auto 0; color: var(--muted); font-size: 13px; line-height: 1.5; }
|
||||
.empty-state .button { margin-top: 17px; }
|
||||
|
||||
.analytics-page { display: grid; row-gap: 24px; padding-bottom: 8px; }
|
||||
.analytics-page > .page-header { margin-bottom: 0; }
|
||||
.analytics-layout { grid-template-columns: minmax(0, 1.25fr) minmax(310px, .75fr); align-items: start; gap: 20px; }
|
||||
.analytics-layout > * { min-width: 0; }
|
||||
.analytics-metrics { gap: 18px; }
|
||||
.analytics-metrics .metric-card { display: flex; min-height: 132px; flex-direction: column; justify-content: center; padding: 20px; }
|
||||
.period-switch { width: fit-content; margin-bottom: 0; }
|
||||
.period-switch button { min-width: 82px; }
|
||||
.breakdown { display: grid; gap: 15px; }
|
||||
.breakdown-row { display: grid; grid-template-columns: minmax(110px, 1fr) minmax(150px, 2fr) auto; align-items: center; gap: 12px; }
|
||||
.breakdown-name { display: flex; min-width: 0; align-items: center; gap: 8px; font-size: 12px; font-weight: 700; }
|
||||
.breakdown-name span:last-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
progress { width: 100%; height: 8px; overflow: hidden; border: 0; border-radius: 999px; background: var(--surface-strong); color: var(--primary); }
|
||||
progress::-webkit-progress-bar { border-radius: 999px; background: var(--surface-strong); }
|
||||
progress::-webkit-progress-value { border-radius: 999px; background: currentColor; }
|
||||
progress::-moz-progress-bar { border-radius: 999px; background: currentColor; }
|
||||
.progress-red { color: var(--red); } .progress-orange { color: var(--orange); } .progress-yellow { color: #e0ac24; }
|
||||
.progress-green { color: var(--green); } .progress-mint { color: #31b99a; } .progress-teal { color: #159eaf; }
|
||||
.progress-cyan { color: #209bcc; } .progress-blue { color: #3979e9; } .progress-indigo { color: var(--primary); }
|
||||
.progress-purple { color: #8b5cf6; } .progress-pink { color: #e35c9a; } .progress-brown { color: #9b6a4a; }
|
||||
.progress-gray { color: #7a7a85; } .progress-coral { color: #fa6161; } .progress-peach { color: #ff9461; }
|
||||
.progress-gold { color: #e6a314; } .progress-lime { color: #85c729; } .progress-forest { color: #1a7a4d; }
|
||||
.progress-turquoise { color: #0daba1; } .progress-sky { color: #2e9ee8; } .progress-navy { color: #365ca8; }
|
||||
.progress-lavender { color: #8c66d9; } .progress-magenta { color: #d1298c; } .progress-slate { color: #66758e; }
|
||||
.breakdown-value { min-width: 85px; text-align: right; font-size: 12px; font-weight: 750; }
|
||||
.insight-card { padding: 20px; background: linear-gradient(145deg, var(--primary-soft), var(--surface)); }
|
||||
.insight-card .insight-icon { display: grid; width: 42px; height: 42px; place-items: center; border-radius: 13px; background: var(--primary); color: white; font-size: 20px; }
|
||||
.insight-card h3 { margin: 16px 0 8px; font-size: 16px; }
|
||||
.insight-card p { margin: 0; color: var(--muted); font-size: 13px; line-height: 1.55; }
|
||||
.analytics-breakdown-card .card-body { padding-top: 18px; padding-bottom: 22px; }
|
||||
|
||||
.budget-list { display: grid; gap: 12px; }
|
||||
.budget-item { padding: 17px; }
|
||||
.budget-top { display: flex; align-items: center; gap: 11px; }
|
||||
.budget-copy { min-width: 0; flex: 1; }
|
||||
.budget-copy strong, .budget-copy span { display: block; }
|
||||
.budget-copy strong { font-size: 13px; }
|
||||
.budget-copy span { margin-top: 4px; color: var(--muted); font-size: 11px; }
|
||||
.budget-values { text-align: right; }
|
||||
.budget-values strong, .budget-values span { display: block; }
|
||||
.budget-values strong { font-size: 13px; }
|
||||
.budget-values span { margin-top: 4px; color: var(--muted); font-size: 10px; }
|
||||
.budget-item progress { margin-top: 13px; }
|
||||
.budget-item.is-over { border-color: color-mix(in srgb, var(--red) 35%, var(--border)); }
|
||||
.budget-item.is-over progress { color: var(--red); }
|
||||
|
||||
.category-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
||||
.category-card { display: flex; align-items: center; gap: 12px; padding: 15px; }
|
||||
.category-card .row-main span { text-transform: capitalize; }
|
||||
.category-card .row-actions { margin-left: auto; }
|
||||
|
||||
.settings-layout { grid-template-columns: minmax(0, 1.1fr) minmax(300px, .7fr); align-items: start; }
|
||||
.settings-section { padding: 20px; }
|
||||
.settings-section h2 { margin: 0 0 4px; font-size: 16px; }
|
||||
.settings-section > p { margin: 0 0 18px; color: var(--muted); font-size: 12px; line-height: 1.45; }
|
||||
.settings-row { display: flex; align-items: center; justify-content: space-between; gap: 18px; padding: 14px 0; border-top: 1px solid var(--border); }
|
||||
.settings-row:first-of-type { border-top: 0; }
|
||||
.settings-row div:first-child { min-width: 0; }
|
||||
.settings-row strong, .settings-row span { display: block; }
|
||||
.settings-row strong { font-size: 13px; }
|
||||
.settings-row span { margin-top: 4px; color: var(--muted); font-size: 11px; }
|
||||
.settings-row .select-control { width: 150px; min-height: 40px; }
|
||||
.account-card { overflow: hidden; }
|
||||
.account-cover { height: 88px; background: linear-gradient(135deg, #7171eb, #4444b4); }
|
||||
.account-content { position: relative; padding: 0 20px 20px; }
|
||||
.account-content .avatar { width: 58px; height: 58px; margin-top: -29px; border: 5px solid var(--surface); border-radius: 19px; background: var(--primary-soft); font-size: 20px; }
|
||||
.account-content h3 { margin: 13px 0 4px; font-size: 16px; overflow-wrap: anywhere; }
|
||||
.account-content p { margin: 0 0 17px; color: var(--muted); font-size: 12px; }
|
||||
.account-content .button { width: 100%; }
|
||||
.status-line { display: flex; align-items: center; gap: 9px; margin: 14px 0; padding: 11px; border-radius: 12px; background: var(--surface-soft); color: var(--muted); font-size: 11px; }
|
||||
.status-line span:first-child { width: 8px; height: 8px; border-radius: 50%; background: var(--green); }
|
||||
|
||||
.modal {
|
||||
width: min(620px, calc(100% - 28px));
|
||||
max-height: min(88vh, 820px);
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 24px;
|
||||
background: var(--surface);
|
||||
color: var(--text);
|
||||
box-shadow: 0 26px 90px rgb(0 0 0 / 30%);
|
||||
}
|
||||
.modal::backdrop { background: rgb(10 10 18 / 48%); backdrop-filter: blur(5px); }
|
||||
.modal-shell { display: flex; max-height: min(88vh, 820px); flex-direction: column; }
|
||||
.modal-header { display: flex; align-items: center; justify-content: space-between; gap: 15px; padding: 20px 22px 15px; border-bottom: 1px solid var(--border); }
|
||||
.modal-header h2 { margin: 0; font-size: 19px; letter-spacing: -.4px; }
|
||||
.modal-body { display: grid; gap: 15px; padding: 20px 22px; overflow-y: auto; }
|
||||
.modal-footer { display: flex; justify-content: flex-end; gap: 9px; padding: 14px 22px 19px; border-top: 1px solid var(--border); background: var(--surface); }
|
||||
.kind-switch { width: 100%; }
|
||||
.kind-switch button { min-height: 40px; }
|
||||
.choice-grid { display: grid; grid-template-columns: repeat(10, minmax(0, 1fr)); gap: 7px; }
|
||||
.choice-grid label { position: relative; }
|
||||
.choice-grid input { position: absolute; opacity: 0; pointer-events: none; }
|
||||
.choice-option { display: grid; aspect-ratio: 1; place-items: center; border: 1px solid var(--border); border-radius: 12px; background: var(--surface-soft); font-size: 18px; transition: border-color .14s, transform .14s; }
|
||||
.choice-grid label:hover .choice-option { transform: translateY(-1px); border-color: var(--primary); }
|
||||
.choice-grid input:checked + .choice-option { border: 2px solid var(--primary); background: var(--primary-soft); }
|
||||
.color-grid { display: grid; grid-template-columns: repeat(12, 1fr); gap: 8px; }
|
||||
.color-grid label { position: relative; }
|
||||
.color-grid input { position: absolute; opacity: 0; pointer-events: none; }
|
||||
.color-swatch { display: block; aspect-ratio: 1; padding: 4px; border: 2px solid transparent; border-radius: 50%; background-clip: content-box; }
|
||||
.color-grid input:checked + .color-swatch { border-color: var(--text); }
|
||||
.swatch-red { background-color: #e05252; } .swatch-orange { background-color: #f28c38; } .swatch-yellow { background-color: #e0ac24; }
|
||||
.swatch-green { background-color: #16a36a; } .swatch-mint { background-color: #31b99a; } .swatch-teal { background-color: #159eaf; }
|
||||
.swatch-cyan { background-color: #209bcc; } .swatch-blue { background-color: #3979e9; } .swatch-indigo { background-color: #5b5bd6; }
|
||||
.swatch-purple { background-color: #8b5cf6; } .swatch-pink { background-color: #e35c9a; } .swatch-brown { background-color: #9b6a4a; }
|
||||
.swatch-gray { background-color: #7a7a85; } .swatch-coral { background-color: #fa6161; } .swatch-peach { background-color: #ff9461; }
|
||||
.swatch-gold { background-color: #e6a314; } .swatch-lime { background-color: #85c729; } .swatch-forest { background-color: #1a7a4d; }
|
||||
.swatch-turquoise { background-color: #0daba1; } .swatch-sky { background-color: #2e9ee8; } .swatch-navy { background-color: #1f4085; }
|
||||
.swatch-lavender { background-color: #8c66d9; } .swatch-magenta { background-color: #d1298c; } .swatch-slate { background-color: #4d5c73; }
|
||||
.helper-text { margin: -7px 0 0; color: var(--muted); font-size: 11px; line-height: 1.45; }
|
||||
.budget-edit-list { display: grid; gap: 9px; }
|
||||
.budget-edit-row { display: grid; grid-template-columns: auto minmax(0, 1fr) 135px; align-items: center; gap: 10px; }
|
||||
.budget-edit-row strong { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12px; }
|
||||
.budget-edit-row input { min-width: 0; }
|
||||
|
||||
.toast-region { position: fixed; top: 18px; right: 18px; z-index: 100; display: grid; width: min(380px, calc(100% - 36px)); gap: 8px; pointer-events: none; }
|
||||
.toast { padding: 12px 14px; border: 1px solid var(--border); border-radius: 13px; background: var(--surface); color: var(--text); box-shadow: var(--shadow); font-size: 12px; animation: toast-in .2s ease-out; }
|
||||
.toast.is-error { border-color: color-mix(in srgb, var(--red) 40%, var(--border)); color: var(--red); }
|
||||
@keyframes toast-in { from { opacity: 0; transform: translateY(-8px); } }
|
||||
|
||||
@media (max-width: 1040px) {
|
||||
.grid-4 { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.dashboard-grid, .analytics-layout, .settings-layout { grid-template-columns: 1fr; }
|
||||
.category-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
}
|
||||
|
||||
@media (max-width: 760px) {
|
||||
:root { --radius: 17px; }
|
||||
.sidebar { display: none; }
|
||||
.workspace { margin-left: 0; }
|
||||
.mobile-header {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 16;
|
||||
display: flex;
|
||||
height: 62px;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: max(10px, env(safe-area-inset-top)) 17px 8px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
background: color-mix(in srgb, var(--surface) 91%, transparent);
|
||||
backdrop-filter: blur(18px);
|
||||
}
|
||||
.mobile-header .brand-name { font-size: 18px; }
|
||||
.content { padding: 23px 15px calc(92px + env(safe-area-inset-bottom)); }
|
||||
.bottom-nav {
|
||||
position: fixed;
|
||||
inset: auto 0 0;
|
||||
z-index: 18;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(5, 1fr);
|
||||
padding: 7px 5px calc(7px + env(safe-area-inset-bottom));
|
||||
border-top: 1px solid var(--border);
|
||||
background: color-mix(in srgb, var(--surface) 92%, transparent);
|
||||
backdrop-filter: blur(18px);
|
||||
}
|
||||
.bottom-nav button { display: grid; place-items: center; gap: 2px; min-height: 43px; border: 0; background: transparent; color: var(--muted); }
|
||||
.bottom-nav button span { font-size: 20px; line-height: 1; }
|
||||
.bottom-nav button small { font-size: 9px; font-weight: 700; }
|
||||
.bottom-nav button.is-active { color: var(--primary); }
|
||||
.page-header { align-items: flex-start; margin-bottom: 18px; }
|
||||
.page-header h1 { font-size: 29px; }
|
||||
.page-header p { font-size: 12px; }
|
||||
.page-actions .button:not(.button-primary) { display: none; }
|
||||
.grid-2, .grid-3, .grid-4, .category-grid { grid-template-columns: 1fr; }
|
||||
.metric-grid-mobile { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.metric-card { min-height: 104px; }
|
||||
.analytics-page { row-gap: 18px; padding-bottom: 4px; }
|
||||
.analytics-page > .page-header { margin-bottom: 2px; }
|
||||
.analytics-metrics { gap: 12px; }
|
||||
.analytics-metrics .metric-card { min-height: 112px; padding: 17px; }
|
||||
.analytics-layout { gap: 16px; }
|
||||
.period-switch { width: 100%; }
|
||||
.hero-balance { min-height: 220px; padding: 23px; }
|
||||
.hero-value { font-size: 36px; }
|
||||
.toolbar { gap: 8px; }
|
||||
.toolbar .search-wrap { flex-basis: 100%; }
|
||||
.toolbar .select-control { min-width: 0; flex: 1; }
|
||||
.row-actions { opacity: 1; }
|
||||
.breakdown-row { grid-template-columns: minmax(100px, 1fr) minmax(90px, 1.2fr); }
|
||||
.breakdown-value { grid-column: 2; margin-top: -7px; text-align: left; color: var(--muted); }
|
||||
.choice-grid { grid-template-columns: repeat(6, minmax(0, 1fr)); }
|
||||
.color-grid { grid-template-columns: repeat(8, 1fr); }
|
||||
.modal { width: 100%; max-width: none; max-height: calc(100vh - 32px); margin: auto 0 0; border-radius: 24px 24px 0 0; }
|
||||
.modal-shell { max-height: calc(100vh - 32px); }
|
||||
.modal-header, .modal-body, .modal-footer { padding-left: 17px; padding-right: 17px; }
|
||||
.budget-edit-row { grid-template-columns: auto minmax(0, 1fr) 105px; }
|
||||
}
|
||||
|
||||
@media (max-width: 430px) {
|
||||
.auth-card { padding: 23px 19px; border-radius: 24px; }
|
||||
.auth-copy h1 { font-size: 32px; }
|
||||
.page-actions .button-primary { min-width: 42px; padding-inline: 12px; font-size: 0; }
|
||||
.page-actions .button-primary::before { content: "+"; font-size: 21px; }
|
||||
.card-body { padding: 17px; }
|
||||
.card-header { padding: 17px 17px 0; }
|
||||
.metric-grid-mobile { gap: 10px; }
|
||||
.analytics-page { row-gap: 16px; }
|
||||
.analytics-metrics { gap: 10px; }
|
||||
.metric-card { padding: 14px; }
|
||||
.analytics-metrics .metric-card { min-height: 108px; padding: 15px; }
|
||||
.metric-card strong { font-size: 19px; }
|
||||
.hero-meta { gap: 10px 18px; }
|
||||
.choice-grid { grid-template-columns: repeat(5, minmax(0, 1fr)); }
|
||||
.color-grid { grid-template-columns: repeat(6, 1fr); }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*, *::before, *::after { scroll-behavior: auto !important; animation-duration: .01ms !important; animation-iteration-count: 1 !important; transition-duration: .01ms !important; }
|
||||
}
|
||||
Reference in new issue
Block a user