feat: initialize CollabTableServer with models, sync, and notification handling
- Add go.mod and go.sum for dependency management - Implement models for List, Field, Item, ItemValue, SyncRequest, SyncResponse, and NotificationEvent - Create notification handling functions including enqueueNotification and ignoreNotificationError - Implement sync functionality to handle data synchronization between client and server - Add web data handling and notification polling endpoints - Include tests for timestamp normalization and sync logic - Embed web assets for serving the frontend application
This commit is contained in:
1 parent
e12940fef0
commit
cac2faae2e
41 files changed
+2535
-5502
No files matched your search
+30
-15
@@ -17,8 +17,8 @@ on:
|
||||
workflow_dispatch: {}
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: Test
|
||||
backend:
|
||||
name: Go backend
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
@@ -30,22 +30,37 @@ jobs:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: CollabTableServer/go.mod
|
||||
cache: true
|
||||
|
||||
- name: Test
|
||||
run: go test ./...
|
||||
|
||||
webui:
|
||||
name: Dashboard checks
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: CollabTableServer/webui
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: CollabTableServer/package-lock.json
|
||||
node-version: '22'
|
||||
cache: npm
|
||||
cache-dependency-path: CollabTableServer/webui/package-lock.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Run tests
|
||||
run: |
|
||||
if find src -iname '*.test.ts' -o -iname '*.spec.ts' | grep -q .; then
|
||||
echo "Test files found for CollabTableServer — running npm test."
|
||||
npm test
|
||||
else
|
||||
echo "No test suite configured for CollabTableServer yet — skipping."
|
||||
exit 0
|
||||
fi
|
||||
- name: Check dashboard
|
||||
run: npm run check
|
||||
@@ -1,12 +1,11 @@
|
||||
node_modules
|
||||
dist
|
||||
*.log
|
||||
.env
|
||||
.git
|
||||
.gitignore
|
||||
.vscode
|
||||
.idea
|
||||
README.md
|
||||
Dockerfile
|
||||
data/
|
||||
collabtable.db
|
||||
.git
|
||||
.gitignore
|
||||
.gocache
|
||||
.env
|
||||
*.log
|
||||
node_modules
|
||||
webui/node_modules
|
||||
webui/.svelte-kit
|
||||
webui/build
|
||||
data/
|
||||
collabtable.db
|
||||
@@ -2,7 +2,7 @@
|
||||
# Server
|
||||
#################################################################
|
||||
PORT=3000
|
||||
NODE_ENV=production
|
||||
APP_VERSION=dev
|
||||
|
||||
# Set to "true" once served over HTTPS - marks the admin session cookie Secure.
|
||||
COOKIE_SECURE=false
|
||||
@@ -26,3 +26,6 @@ DB_INIT_RETRY_MAX_ATTEMPTS=0
|
||||
# Allow at most this much client clock skew into sync timestamps (default: 0)
|
||||
# Keep this at 0 to prevent future-dated rows from being re-sent in hot loops.
|
||||
SYNC_MAX_FUTURE_SKEW_MS=0
|
||||
|
||||
# Notification retention period in milliseconds (default: 7 days)
|
||||
NOTIF_RETENTION_MS=604800000
|
||||
@@ -1,22 +0,0 @@
|
||||
module.exports = {
|
||||
root: true,
|
||||
env: {
|
||||
es2021: true,
|
||||
node: true,
|
||||
},
|
||||
parser: '@typescript-eslint/parser',
|
||||
parserOptions: {
|
||||
ecmaVersion: 'latest',
|
||||
sourceType: 'module',
|
||||
project: null,
|
||||
},
|
||||
plugins: ['@typescript-eslint'],
|
||||
extends: [
|
||||
'eslint:recommended',
|
||||
'plugin:@typescript-eslint/recommended',
|
||||
'prettier',
|
||||
],
|
||||
rules: {
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
},
|
||||
};
|
||||
@@ -1,9 +1,11 @@
|
||||
node_modules
|
||||
dist
|
||||
.env
|
||||
*.log
|
||||
.DS_Store
|
||||
.env
|
||||
*.log
|
||||
.DS_Store
|
||||
|
||||
# Local Go build/test cache
|
||||
.gocache/
|
||||
|
||||
# Generated: webui build output, copied to ./web (sibling of dist/) before `npm start`
|
||||
# by the Dockerfile / local dev workflow - see webui/README or Dockerfile.
|
||||
web/
|
||||
# Generated: webui build output, copied to ./web before the Go build.
|
||||
web/
|
||||
!web/
|
||||
!web/.gitkeep
|
||||
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"singleQuote": true,
|
||||
"semi": true,
|
||||
"trailingComma": "all",
|
||||
"printWidth": 100
|
||||
}
|
||||
@@ -1,31 +1,24 @@
|
||||
FROM node:20-alpine AS webui-builder
|
||||
WORKDIR /webui
|
||||
COPY webui/package*.json ./
|
||||
RUN npm install
|
||||
COPY webui/ .
|
||||
RUN npm run build
|
||||
|
||||
FROM node:20-alpine
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Copy package files
|
||||
COPY package*.json ./
|
||||
|
||||
# Install dependencies
|
||||
RUN npm install
|
||||
|
||||
# Copy source code
|
||||
COPY . .
|
||||
|
||||
# Build TypeScript
|
||||
RUN npm run build
|
||||
|
||||
# Built webui, served by webRoutes.ts from ./web (sibling of dist/)
|
||||
COPY --from=webui-builder /webui/build ./web
|
||||
|
||||
# Expose port
|
||||
EXPOSE 3000
|
||||
|
||||
# Start the application
|
||||
CMD ["npm", "start"]
|
||||
FROM node:22-alpine AS webui-builder
|
||||
WORKDIR /webui
|
||||
COPY webui/package*.json ./
|
||||
RUN npm ci
|
||||
COPY webui/ ./
|
||||
RUN npm run build
|
||||
|
||||
FROM golang:1.26-alpine AS builder
|
||||
WORKDIR /app
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
COPY *.go ./
|
||||
COPY --from=webui-builder /webui/build ./web
|
||||
RUN apk add --no-cache ca-certificates && \
|
||||
CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o server .
|
||||
|
||||
FROM scratch
|
||||
COPY --from=builder /app/server /server
|
||||
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
|
||||
USER 65534:65534
|
||||
EXPOSE 3000
|
||||
VOLUME ["/data"]
|
||||
ENV PORT=3000
|
||||
ENTRYPOINT ["/server"]
|
||||
+116
-245
@@ -1,245 +1,116 @@
|
||||
# CollabTable Server
|
||||
|
||||
A collaborative table management server built with Node.js, Express, TypeScript, and PostgreSQL.
|
||||
|
||||
## Features
|
||||
|
||||
- RESTful API for managing lists, fields, items, and values
|
||||
- Real-time synchronization via WebSocket (primary) with HTTP fallback
|
||||
- PostgreSQL (pg) database backend
|
||||
- Single-admin-account web dashboard login (session cookie, bcrypt-hashed password) plus a
|
||||
long-lived API token for sync clients/devices, generated from the dashboard
|
||||
- Dockerized deployment (bring your own PostgreSQL instance)
|
||||
- TypeScript for type safety
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Docker and a PostgreSQL instance (bring your own - this app does not run Postgres for you)
|
||||
- Or Node.js 20+ and a PostgreSQL instance (for local development)
|
||||
|
||||
## Quick Start with Docker
|
||||
|
||||
1. Clone the repository
|
||||
2. Navigate to the server directory:
|
||||
```bash
|
||||
cd CollabTableServer
|
||||
```
|
||||
|
||||
3. Build the image:
|
||||
```bash
|
||||
docker build -t collabtable-server .
|
||||
```
|
||||
|
||||
4. Run it, pointing at your own Postgres instance:
|
||||
```bash
|
||||
docker run -d --name collabtable-server --restart unless-stopped \
|
||||
-p 3000:3000 \
|
||||
-e DATABASE_URL=postgres://user:password@host:5432/collabtable \
|
||||
-e COOKIE_SECURE=false \
|
||||
collabtable-server
|
||||
```
|
||||
|
||||
The server will be available at `http://localhost:3000`. Open it in a browser to create the
|
||||
admin account, then generate an API token from the dashboard for your sync clients/devices.
|
||||
|
||||
## Local Development
|
||||
|
||||
1. Install dependencies:
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
2. Create a `.env` file:
|
||||
```bash
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
3. Point it at a PostgreSQL instance in `.env`:
|
||||
```
|
||||
DATABASE_URL=postgres://user:password@localhost:5432/collabtable
|
||||
|
||||
# Set to "true" once served over HTTPS
|
||||
COOKIE_SECURE=false
|
||||
```
|
||||
|
||||
4. Start the development server:
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
## API Endpoints
|
||||
|
||||
### Lists
|
||||
- `GET /api/lists` - Get all lists
|
||||
- `GET /api/lists/:id` - Get a specific list
|
||||
- `POST /api/lists` - Create a new list
|
||||
- `PUT /api/lists/:id` - Update a list
|
||||
- `DELETE /api/lists/:id` - Delete a list (soft delete)
|
||||
|
||||
### Fields
|
||||
- `GET /api/fields/list/:listId` - Get all fields for a list
|
||||
- `POST /api/fields` - Create a new field
|
||||
- `PUT /api/fields/:id` - Update a field
|
||||
- `DELETE /api/fields/:id` - Delete a field (soft delete)
|
||||
|
||||
### Items
|
||||
- `GET /api/items/list/:listId` - Get all items for a list
|
||||
- `GET /api/items/:itemId/values` - Get all values for an item
|
||||
- `POST /api/items` - Create a new item
|
||||
- `POST /api/items/values` - Create/update an item value
|
||||
- `PUT /api/items/:id` - Update an item
|
||||
- `DELETE /api/items/:id` - Delete an item (soft delete)
|
||||
|
||||
### Sync
|
||||
- `POST /api/sync` - Synchronize data between client and server
|
||||
|
||||
### WebSocket
|
||||
- `GET /api/ws` - WebSocket endpoint. Send JSON messages:
|
||||
- `{"type":"ping"}` → `{"type":"pong"}`
|
||||
- `{"type":"sync", "id":"<uuid>", "payload": { ...SyncRequest }}` → `{"type":"syncResponse", "id":"<uuid>", "payload": { ...SyncResponse }}`
|
||||
|
||||
Authentication: include header `Authorization: Bearer <api-token>` on sync/collaboration API requests, using the API token generated from the web dashboard's Settings page (see "Authentication" below).
|
||||
|
||||
### Health Check
|
||||
- `GET /health` - Check server health
|
||||
|
||||
## Data Models
|
||||
|
||||
### List
|
||||
```typescript
|
||||
{
|
||||
id: string;
|
||||
name: string;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
isDeleted: boolean;
|
||||
}
|
||||
```
|
||||
|
||||
### Field
|
||||
```typescript
|
||||
{
|
||||
id: string;
|
||||
listId: string;
|
||||
name: string;
|
||||
order: number;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
isDeleted: boolean;
|
||||
}
|
||||
```
|
||||
|
||||
### Item
|
||||
```typescript
|
||||
{
|
||||
id: string;
|
||||
listId: string;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
isDeleted: boolean;
|
||||
}
|
||||
```
|
||||
|
||||
### ItemValue
|
||||
```typescript
|
||||
{
|
||||
id: string;
|
||||
itemId: string;
|
||||
fieldId: string;
|
||||
value: string;
|
||||
updatedAt: number;
|
||||
}
|
||||
```
|
||||
|
||||
## Sync Protocol
|
||||
|
||||
The sync endpoint accepts a POST request with the following structure:
|
||||
|
||||
```json
|
||||
{
|
||||
"lastSyncTimestamp": 1234567890,
|
||||
"lists": [...],
|
||||
"fields": [...],
|
||||
"items": [...],
|
||||
"itemValues": [...]
|
||||
}
|
||||
```
|
||||
|
||||
The server responds with:
|
||||
|
||||
```json
|
||||
{
|
||||
"lists": [...],
|
||||
"fields": [...],
|
||||
"items": [...],
|
||||
"itemValues": [...],
|
||||
"serverTimestamp": 1234567890
|
||||
}
|
||||
```
|
||||
|
||||
The sync process:
|
||||
1. Client sends all local changes since the last sync
|
||||
2. Server saves the client's changes
|
||||
3. Server returns all changes made on the server since the client's last sync
|
||||
4. Client applies the server's changes locally
|
||||
|
||||
## Building for Production
|
||||
|
||||
Build the TypeScript code:
|
||||
```bash
|
||||
npm run build
|
||||
```
|
||||
|
||||
Start the production server:
|
||||
```bash
|
||||
npm start
|
||||
```
|
||||
|
||||
## Docker Commands
|
||||
|
||||
Stop the container:
|
||||
```bash
|
||||
docker stop collabtable-server
|
||||
```
|
||||
|
||||
View logs:
|
||||
```bash
|
||||
docker logs -f collabtable-server
|
||||
```
|
||||
|
||||
Rebuild and restart:
|
||||
```bash
|
||||
docker build -t collabtable-server . && docker restart collabtable-server
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
- `PORT` - Server port (default: 3000)
|
||||
- `NODE_ENV` - Environment (development/production)
|
||||
- `COOKIE_SECURE` - Set to `true` to mark the admin session cookie `Secure` (requires HTTPS); default `false`
|
||||
- `DATABASE_URL` - PostgreSQL connection URL (required; bring your own Postgres instance)
|
||||
- `DB_INIT_RETRY_INTERVAL_MS` - Delay between DB init retries in ms (default: `5000`)
|
||||
- `DB_INIT_RETRY_MAX_ATTEMPTS` - Max DB init retries; `0` retries forever (default: `0`)
|
||||
- `SYNC_MAX_FUTURE_SKEW_MS` - Allowed future timestamp skew from clients during sync (default: `0`)
|
||||
|
||||
## Authentication
|
||||
|
||||
There is a single admin account for the web dashboard (username + password, bcrypt-hashed,
|
||||
session cookie - no accounts beyond the one admin). The first time you open the dashboard
|
||||
you're walked through creating it; there is no default/seeded account.
|
||||
|
||||
Sync clients and devices (the mobile app, or anything hitting the `/api/lists` /
|
||||
`/api/fields` / `/api/items` / `/api/sync` / `/api/notifications` endpoints) authenticate
|
||||
with a separate long-lived API token instead - generate or regenerate it from the
|
||||
dashboard's Settings page, then set `Authorization: Bearer <token>` on those requests. This
|
||||
replaces the old optional `SERVER_PASSWORD` scheme, which silently disabled auth entirely
|
||||
when left unset.
|
||||
|
||||
## Data Persistence
|
||||
|
||||
Use your normal PostgreSQL backup/restore procedures (e.g., `pg_dump`, `pg_restore`) against
|
||||
your own Postgres instance - this app does not manage Postgres storage itself.
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
# CollabTable Server
|
||||
|
||||
The CollabTable backend is a small Go `net/http` service backed by PostgreSQL. It serves the
|
||||
Svelte dashboard and the Android synchronization API from one container.
|
||||
|
||||
## Features
|
||||
|
||||
- REST API for lists, fields, items, and item values
|
||||
- Transactional HTTP synchronization with soft-delete tombstones
|
||||
- Notification polling for background refreshes
|
||||
- Single-admin browser session with bcrypt-hashed credentials
|
||||
- Long-lived bearer API token for Android and other sync clients
|
||||
- Embedded SvelteKit dashboard
|
||||
- Idempotent PostgreSQL schema initialization
|
||||
|
||||
## Quick start with Docker
|
||||
|
||||
```bash
|
||||
docker build -t collabtable-server .
|
||||
docker run -d --name collabtable-server --restart unless-stopped \
|
||||
-p 3000:3000 \
|
||||
-e DATABASE_URL=postgres://user:password@host:5432/collabtable \
|
||||
-e COOKIE_SECURE=false \
|
||||
collabtable-server
|
||||
```
|
||||
|
||||
Open `http://localhost:3000` to create the administrator account. Generate an API token from
|
||||
the dashboard's Settings menu and enter it in the Android app.
|
||||
|
||||
## Local development
|
||||
|
||||
The backend requires Go 1.26+ and PostgreSQL. The dashboard requires Node.js 22+.
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
go test ./...
|
||||
go run .
|
||||
```
|
||||
|
||||
To build the dashboard for the embedded production binary:
|
||||
|
||||
```bash
|
||||
cd webui
|
||||
npm ci
|
||||
npm run check
|
||||
npm run build
|
||||
cd ..
|
||||
Copy-Item -Recurse -Force webui/build web
|
||||
go build -o collabtable-server .
|
||||
```
|
||||
|
||||
The Dockerfile performs those dashboard and Go build steps automatically.
|
||||
|
||||
## API
|
||||
|
||||
All Android synchronization routes are prefixed with `/api/` and require:
|
||||
|
||||
```text
|
||||
Authorization: Bearer <api-token>
|
||||
```
|
||||
|
||||
The Android app also sends `x-device-id`, which is used to avoid showing a device its own
|
||||
notification events.
|
||||
|
||||
### Authentication
|
||||
|
||||
- `GET /api/auth/status`
|
||||
- `POST /api/auth/setup`
|
||||
- `POST /api/auth/login`
|
||||
- `POST /api/auth/logout`
|
||||
- `POST /api/auth/credentials`
|
||||
- `GET /api/auth/token/status`
|
||||
- `POST /api/auth/token/regenerate`
|
||||
|
||||
Browser authentication uses the `collabtable_session` HTTP-only cookie. There is one admin
|
||||
account per database. API tokens are hashed at rest and shown only when generated.
|
||||
|
||||
### Data
|
||||
|
||||
- `GET|POST /api/lists`
|
||||
- `GET|PUT|DELETE /api/lists/:id`
|
||||
- `GET /api/fields/list/:listId`
|
||||
- `POST /api/fields`
|
||||
- `PUT|DELETE /api/fields/:id`
|
||||
- `GET /api/items/list/:listId`
|
||||
- `GET /api/items/:itemId/values`
|
||||
- `POST /api/items`
|
||||
- `POST /api/items/values`
|
||||
- `PUT|DELETE /api/items/:id`
|
||||
- `POST /api/sync`
|
||||
- `GET /api/notifications/poll?since=<timestamp-ms>`
|
||||
|
||||
### Dashboard and health
|
||||
|
||||
- `GET /health` is public.
|
||||
- `GET /web/data` requires the admin session.
|
||||
- `GET /web/info` requires the admin session.
|
||||
- `/`, `/about`, and `/lists/:id` serve the embedded dashboard SPA.
|
||||
|
||||
## Environment variables
|
||||
|
||||
- `PORT` — HTTP port, default `3000`
|
||||
- `APP_VERSION` — optional version displayed in the dashboard, default `dev`
|
||||
- `COOKIE_SECURE` — set to `true` when served over HTTPS
|
||||
- `DATABASE_URL` — PostgreSQL connection string, required
|
||||
- `DB_INIT_RETRY_INTERVAL_MS` — startup retry delay, default `5000`
|
||||
- `DB_INIT_RETRY_MAX_ATTEMPTS` — maximum startup attempts, `0` retries forever
|
||||
- `SYNC_MAX_FUTURE_SKEW_MS` — allowed client timestamp skew, default `0`
|
||||
- `NOTIF_RETENTION_MS` — notification retention period, default seven days
|
||||
|
||||
The Go server initializes the existing CollabTable tables in place, so switching from the
|
||||
previous server does not require a data export or schema conversion.
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
@@ -0,0 +1,351 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
const (
|
||||
sessionCookieName = "collabtable_session"
|
||||
sessionTTL = 24 * time.Hour
|
||||
minPasswordLength = 8
|
||||
maxUsernameLength = 64
|
||||
)
|
||||
|
||||
var (
|
||||
errAuthRequired = errors.New("Authentication required")
|
||||
errSetupComplete = errors.New("Setup has already been completed.")
|
||||
errInvalidCredentials = errors.New("Invalid username or password.")
|
||||
errUsernameRequired = errors.New("Username is required.")
|
||||
errPasswordTooShort = errors.New("Password must be at least 8 characters.")
|
||||
errCurrentPasswordBad = errors.New("Current password is incorrect.")
|
||||
)
|
||||
|
||||
type AuthService struct {
|
||||
db *DB
|
||||
secureCookie bool
|
||||
}
|
||||
|
||||
func newAuthService(db *DB, secureCookie bool) *AuthService {
|
||||
return &AuthService{db: db, secureCookie: secureCookie}
|
||||
}
|
||||
|
||||
func normalizeUsername(value string) (string, error) {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" || len([]rune(value)) > maxUsernameLength {
|
||||
return "", errUsernameRequired
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func validatePassword(value string) error {
|
||||
if len([]rune(value)) < minPasswordLength {
|
||||
return errPasswordTooShort
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func randomToken() (string, error) {
|
||||
buffer := make([]byte, 32)
|
||||
if _, err := rand.Read(buffer); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(buffer), nil
|
||||
}
|
||||
|
||||
func hashToken(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func (a *AuthService) setSessionCookie(w http.ResponseWriter, token string, expiresAt time.Time) {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: sessionCookieName,
|
||||
Value: token,
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
Secure: a.secureCookie,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
Expires: expiresAt,
|
||||
})
|
||||
}
|
||||
|
||||
func (a *AuthService) clearSessionCookie(w http.ResponseWriter) {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: sessionCookieName,
|
||||
Value: "",
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
Secure: a.secureCookie,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
MaxAge: -1,
|
||||
})
|
||||
}
|
||||
|
||||
func (a *AuthService) startSession(ctx context.Context, w http.ResponseWriter, userID int64) error {
|
||||
token, err := randomToken()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
expiresAt := time.Now().Add(sessionTTL)
|
||||
if err := a.db.createSession(ctx, userID, hashToken(token), expiresAt); err != nil {
|
||||
return err
|
||||
}
|
||||
a.setSessionCookie(w, token, expiresAt)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *AuthService) currentUser(r *http.Request) (*AuthUser, error) {
|
||||
cookie, err := r.Cookie(sessionCookieName)
|
||||
if err != nil || cookie.Value == "" {
|
||||
return nil, nil
|
||||
}
|
||||
return a.db.getSessionUser(r.Context(), hashToken(cookie.Value))
|
||||
}
|
||||
|
||||
func (a *AuthService) requireSession(next func(http.ResponseWriter, *http.Request, *AuthUser)) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
user, err := a.currentUser(r)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
if user == nil {
|
||||
writeJSONError(w, http.StatusUnauthorized, errAuthRequired.Error())
|
||||
return
|
||||
}
|
||||
next(w, r, user)
|
||||
})
|
||||
}
|
||||
|
||||
func (a *AuthService) requireAPIToken(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
token := extractBearer(r)
|
||||
if token == "" {
|
||||
writeJSONError(w, http.StatusUnauthorized, "No bearer token provided")
|
||||
return
|
||||
}
|
||||
userID, err := a.db.getAPITokenUserID(r.Context(), hashToken(token))
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
if userID == 0 {
|
||||
writeJSONError(w, http.StatusUnauthorized, "Invalid API token")
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func extractBearer(r *http.Request) string {
|
||||
header := r.Header.Get("Authorization")
|
||||
if !strings.HasPrefix(header, "Bearer ") {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(strings.TrimPrefix(header, "Bearer "))
|
||||
}
|
||||
|
||||
type authStatusResponse struct {
|
||||
SetupRequired bool `json:"setupRequired"`
|
||||
Authenticated bool `json:"authenticated"`
|
||||
Username string `json:"username,omitempty"`
|
||||
}
|
||||
|
||||
type credentialsRequest struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
func (a *AuthService) handleStatus(w http.ResponseWriter, r *http.Request) {
|
||||
count, err := a.db.countUsers(r.Context())
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
if count == 0 {
|
||||
writeJSON(w, http.StatusOK, authStatusResponse{SetupRequired: true})
|
||||
return
|
||||
}
|
||||
|
||||
user, err := a.currentUser(r)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
if user == nil {
|
||||
writeJSON(w, http.StatusOK, authStatusResponse{})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, Username: user.Username})
|
||||
}
|
||||
|
||||
func (a *AuthService) handleSetup(w http.ResponseWriter, r *http.Request) {
|
||||
var request credentialsRequest
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
|
||||
count, err := a.db.countUsers(r.Context())
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
if count > 0 {
|
||||
writeJSONError(w, http.StatusConflict, errSetupComplete.Error())
|
||||
return
|
||||
}
|
||||
|
||||
username, err := normalizeUsername(request.Username)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
if err := validatePassword(request.Password); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(request.Password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
user, err := a.db.createUser(r.Context(), username, string(hash))
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrSingletonUserExists) {
|
||||
writeJSONError(w, http.StatusConflict, errSetupComplete.Error())
|
||||
return
|
||||
}
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
if err := a.startSession(r.Context(), w, user.ID); err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, Username: user.Username})
|
||||
}
|
||||
|
||||
func (a *AuthService) handleLogin(w http.ResponseWriter, r *http.Request) {
|
||||
var request credentialsRequest
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
|
||||
username, err := normalizeUsername(request.Username)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusUnauthorized, errInvalidCredentials.Error())
|
||||
return
|
||||
}
|
||||
user, err := a.db.getUserByUsername(r.Context(), username)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
if user == nil || bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(request.Password)) != nil {
|
||||
writeJSONError(w, http.StatusUnauthorized, errInvalidCredentials.Error())
|
||||
return
|
||||
}
|
||||
if err := a.startSession(r.Context(), w, user.ID); err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, Username: user.Username})
|
||||
}
|
||||
|
||||
func (a *AuthService) handleLogout(w http.ResponseWriter, r *http.Request, _ *AuthUser) {
|
||||
if cookie, err := r.Cookie(sessionCookieName); err == nil && cookie.Value != "" {
|
||||
if err := a.db.deleteSession(r.Context(), hashToken(cookie.Value)); err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
}
|
||||
a.clearSessionCookie(w)
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
type updateCredentialsRequest struct {
|
||||
CurrentPassword string `json:"currentPassword"`
|
||||
NewUsername *string `json:"newUsername"`
|
||||
NewPassword *string `json:"newPassword"`
|
||||
}
|
||||
|
||||
func (a *AuthService) handleUpdateCredentials(w http.ResponseWriter, r *http.Request, user *AuthUser) {
|
||||
var request updateCredentialsRequest
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
if bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(request.CurrentPassword)) != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, errCurrentPasswordBad.Error())
|
||||
return
|
||||
}
|
||||
|
||||
username := user.Username
|
||||
if request.NewUsername != nil {
|
||||
username, _ = normalizeUsername(*request.NewUsername)
|
||||
if username == "" {
|
||||
writeJSONError(w, http.StatusBadRequest, errUsernameRequired.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
passwordHash := user.PasswordHash
|
||||
if request.NewPassword != nil && *request.NewPassword != "" {
|
||||
if err := validatePassword(*request.NewPassword); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(*request.NewPassword), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
passwordHash = string(hash)
|
||||
}
|
||||
|
||||
if err := a.db.updateUserCredentials(r.Context(), user.ID, username, passwordHash); err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
if err := a.db.deleteSessionsForUser(r.Context(), user.ID); err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
a.clearSessionCookie(w)
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
func (a *AuthService) handleTokenStatus(w http.ResponseWriter, r *http.Request, user *AuthUser) {
|
||||
hasToken, err := a.db.hasAPIToken(r.Context(), user.ID)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"hasToken": hasToken})
|
||||
}
|
||||
|
||||
func (a *AuthService) handleTokenRegenerate(w http.ResponseWriter, r *http.Request, user *AuthUser) {
|
||||
token, err := randomToken()
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
if err := a.db.regenerateAPIToken(r.Context(), user.ID, hashToken(token)); err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"token": token})
|
||||
}
|
||||
@@ -0,0 +1,640 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
type rowScanner interface {
|
||||
Scan(...any) error
|
||||
}
|
||||
|
||||
func scanList(row rowScanner) (List, error) {
|
||||
var list List
|
||||
var deleted int
|
||||
err := row.Scan(&list.ID, &list.Name, &list.CreatedAt, &list.UpdatedAt, &deleted)
|
||||
list.IsDeleted = deleted != 0
|
||||
return list, err
|
||||
}
|
||||
|
||||
func scanField(row rowScanner) (Field, error) {
|
||||
var field Field
|
||||
var deleted int
|
||||
err := row.Scan(
|
||||
&field.ID,
|
||||
&field.Name,
|
||||
&field.FieldType,
|
||||
&field.FieldOptions,
|
||||
&field.Alignment,
|
||||
&field.ListID,
|
||||
&field.Order,
|
||||
&field.CreatedAt,
|
||||
&field.UpdatedAt,
|
||||
&deleted,
|
||||
)
|
||||
field.IsDeleted = deleted != 0
|
||||
return field, err
|
||||
}
|
||||
|
||||
func scanItem(row rowScanner) (Item, error) {
|
||||
var item Item
|
||||
var deleted int
|
||||
err := row.Scan(&item.ID, &item.ListID, &item.CreatedAt, &item.UpdatedAt, &deleted)
|
||||
item.IsDeleted = deleted != 0
|
||||
return item, err
|
||||
}
|
||||
|
||||
func scanItemValue(row rowScanner) (ItemValue, error) {
|
||||
var value ItemValue
|
||||
err := row.Scan(&value.ID, &value.ItemID, &value.FieldID, &value.Value, &value.UpdatedAt)
|
||||
return value, err
|
||||
}
|
||||
|
||||
const listColumns = `id, name, createdat, updatedat, COALESCE(isdeleted, 0)`
|
||||
const fieldColumns = `id, name, fieldtype, COALESCE(fieldoptions, ''), COALESCE(alignment, 'start'), listid, "order", createdat, updatedat, COALESCE(isdeleted, 0)`
|
||||
const itemColumns = `id, listid, createdat, updatedat, COALESCE(isdeleted, 0)`
|
||||
const valueColumns = `id, itemid, fieldid, COALESCE(value, ''), updatedat`
|
||||
|
||||
func (d *DB) getList(ctx context.Context, id string) (List, error) {
|
||||
return scanList(d.pool.QueryRow(ctx, `SELECT `+listColumns+` FROM lists WHERE id = $1`, id))
|
||||
}
|
||||
|
||||
func (d *DB) queryLists(ctx context.Context, includeDeleted bool, since *int64) ([]List, error) {
|
||||
conditions := make([]string, 0, 2)
|
||||
args := make([]any, 0, 1)
|
||||
if !includeDeleted {
|
||||
conditions = append(conditions, "isdeleted = 0")
|
||||
}
|
||||
if since != nil {
|
||||
conditions = append(conditions, "updatedat >= $1")
|
||||
args = append(args, *since)
|
||||
}
|
||||
query := `SELECT ` + listColumns + ` FROM lists`
|
||||
if len(conditions) > 0 {
|
||||
query += " WHERE " + strings.Join(conditions, " AND ")
|
||||
}
|
||||
query += " ORDER BY updatedat DESC"
|
||||
|
||||
rows, err := d.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
lists := make([]List, 0)
|
||||
for rows.Next() {
|
||||
list, err := scanList(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
lists = append(lists, list)
|
||||
}
|
||||
return lists, rows.Err()
|
||||
}
|
||||
|
||||
func (d *DB) queryFields(ctx context.Context, includeDeleted bool, since *int64, listID string) ([]Field, error) {
|
||||
conditions := make([]string, 0, 3)
|
||||
args := make([]any, 0, 2)
|
||||
if !includeDeleted {
|
||||
conditions = append(conditions, "isdeleted = 0")
|
||||
}
|
||||
if since != nil {
|
||||
args = append(args, *since)
|
||||
conditions = append(conditions, fmt.Sprintf("updatedat >= $%d", len(args)))
|
||||
}
|
||||
if listID != "" {
|
||||
args = append(args, listID)
|
||||
conditions = append(conditions, fmt.Sprintf("listid = $%d", len(args)))
|
||||
}
|
||||
query := `SELECT ` + fieldColumns + ` FROM fields`
|
||||
if len(conditions) > 0 {
|
||||
query += " WHERE " + strings.Join(conditions, " AND ")
|
||||
}
|
||||
query += ` ORDER BY "order" ASC`
|
||||
|
||||
rows, err := d.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
fields := make([]Field, 0)
|
||||
for rows.Next() {
|
||||
field, err := scanField(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fields = append(fields, field)
|
||||
}
|
||||
return fields, rows.Err()
|
||||
}
|
||||
|
||||
func (d *DB) queryItems(ctx context.Context, includeDeleted bool, since *int64, listID string) ([]Item, error) {
|
||||
conditions := make([]string, 0, 3)
|
||||
args := make([]any, 0, 2)
|
||||
if !includeDeleted {
|
||||
conditions = append(conditions, "isdeleted = 0")
|
||||
}
|
||||
if since != nil {
|
||||
args = append(args, *since)
|
||||
conditions = append(conditions, fmt.Sprintf("updatedat >= $%d", len(args)))
|
||||
}
|
||||
if listID != "" {
|
||||
args = append(args, listID)
|
||||
conditions = append(conditions, fmt.Sprintf("listid = $%d", len(args)))
|
||||
}
|
||||
query := `SELECT ` + itemColumns + ` FROM items`
|
||||
if len(conditions) > 0 {
|
||||
query += " WHERE " + strings.Join(conditions, " AND ")
|
||||
}
|
||||
query += " ORDER BY updatedat DESC"
|
||||
|
||||
rows, err := d.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := make([]Item, 0)
|
||||
for rows.Next() {
|
||||
item, err := scanItem(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
return items, rows.Err()
|
||||
}
|
||||
|
||||
func (d *DB) queryValues(ctx context.Context, since *int64, itemID string) ([]ItemValue, error) {
|
||||
conditions := make([]string, 0, 2)
|
||||
args := make([]any, 0, 2)
|
||||
if since != nil {
|
||||
args = append(args, *since)
|
||||
conditions = append(conditions, fmt.Sprintf("updatedat >= $%d", len(args)))
|
||||
}
|
||||
if itemID != "" {
|
||||
args = append(args, itemID)
|
||||
conditions = append(conditions, fmt.Sprintf("itemid = $%d", len(args)))
|
||||
}
|
||||
query := `SELECT ` + valueColumns + ` FROM item_values`
|
||||
if len(conditions) > 0 {
|
||||
query += " WHERE " + strings.Join(conditions, " AND ")
|
||||
}
|
||||
query += " ORDER BY updatedat ASC"
|
||||
|
||||
rows, err := d.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
values := make([]ItemValue, 0)
|
||||
for rows.Next() {
|
||||
value, err := scanItemValue(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
values = append(values, value)
|
||||
}
|
||||
return values, rows.Err()
|
||||
}
|
||||
|
||||
func requestDeviceID(r *http.Request, bodyValue string) string {
|
||||
if value := strings.TrimSpace(r.Header.Get("X-Device-Id")); value != "" {
|
||||
return value
|
||||
}
|
||||
if value := strings.TrimSpace(r.URL.Query().Get("deviceId")); value != "" {
|
||||
return value
|
||||
}
|
||||
return strings.TrimSpace(bodyValue)
|
||||
}
|
||||
|
||||
func boolInt(value bool) int {
|
||||
if value {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
type listMutation struct {
|
||||
List
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Server) handleListCollection(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodGet {
|
||||
lists, err := s.db.queryLists(r.Context(), false, nil)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch lists")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, lists)
|
||||
return
|
||||
}
|
||||
|
||||
var request listMutation
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
if request.ID == "" || request.Name == "" {
|
||||
writeJSONError(w, http.StatusBadRequest, "List id and name are required")
|
||||
return
|
||||
}
|
||||
_, err := s.db.pool.Exec(r.Context(), `
|
||||
INSERT INTO lists (id, name, createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
`, request.ID, request.Name, int64(request.CreatedAt), int64(request.UpdatedAt), boolInt(request.IsDeleted))
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create list")
|
||||
return
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "created", "list", request.ID, request.ID, time.Now().UnixMilli()))
|
||||
list, err := s.db.getList(r.Context(), request.ID)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create list")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, list)
|
||||
}
|
||||
|
||||
func (s *Server) handleListItem(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.PathValue("id")
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
list, err := s.db.getList(r.Context(), id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||
return
|
||||
}
|
||||
if err != nil || list.IsDeleted {
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch list")
|
||||
} else {
|
||||
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||
}
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, list)
|
||||
case http.MethodPut:
|
||||
var request struct {
|
||||
Name string `json:"name"`
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
}
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
updatedAt := time.Now().UnixMilli()
|
||||
result, err := s.db.pool.Exec(r.Context(), `UPDATE lists SET name = $1, updatedat = $2 WHERE id = $3`, request.Name, updatedAt, id)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update list")
|
||||
return
|
||||
}
|
||||
if result.RowsAffected() == 0 {
|
||||
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||
return
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "updated", "list", id, id, updatedAt))
|
||||
list, err := s.db.getList(r.Context(), id)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update list")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, list)
|
||||
case http.MethodDelete:
|
||||
updatedAt := time.Now().UnixMilli()
|
||||
result, err := s.db.pool.Exec(r.Context(), `UPDATE lists SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to delete list")
|
||||
return
|
||||
}
|
||||
if result.RowsAffected() == 0 {
|
||||
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||
return
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, ""), "deleted", "list", id, id, updatedAt))
|
||||
writeJSON(w, http.StatusOK, map[string]string{"message": "List deleted successfully"})
|
||||
}
|
||||
}
|
||||
|
||||
type fieldMutation struct {
|
||||
Field
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Server) handleFieldsForList(w http.ResponseWriter, r *http.Request) {
|
||||
fields, err := s.db.queryFields(r.Context(), false, nil, r.PathValue("listId"))
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch fields")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, fields)
|
||||
}
|
||||
|
||||
func (s *Server) handleFieldCollection(w http.ResponseWriter, r *http.Request) {
|
||||
var request fieldMutation
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
if request.ID == "" || request.ListID == "" || request.Name == "" {
|
||||
writeJSONError(w, http.StatusBadRequest, "Field id, listId, and name are required")
|
||||
return
|
||||
}
|
||||
if request.Alignment == "" {
|
||||
request.Alignment = "start"
|
||||
}
|
||||
if request.FieldType == "" {
|
||||
request.FieldType = "TEXT"
|
||||
}
|
||||
_, err := s.db.pool.Exec(r.Context(), `
|
||||
INSERT INTO fields
|
||||
(id, name, fieldtype, fieldoptions, alignment, listid, "order", createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||
`, request.ID, request.Name, request.FieldType, request.FieldOptions, request.Alignment, request.ListID, request.Order, int64(request.CreatedAt), int64(request.UpdatedAt), boolInt(request.IsDeleted))
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create field")
|
||||
return
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "created", "field", request.ID, request.ListID, time.Now().UnixMilli()))
|
||||
field, err := s.getField(r.Context(), request.ID)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create field")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, field)
|
||||
}
|
||||
|
||||
func (s *Server) getField(ctx context.Context, id string) (Field, error) {
|
||||
return scanField(s.db.pool.QueryRow(ctx, `SELECT `+fieldColumns+` FROM fields WHERE id = $1`, id))
|
||||
}
|
||||
|
||||
func (s *Server) handleFieldItem(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.PathValue("id")
|
||||
switch r.Method {
|
||||
case http.MethodPut:
|
||||
var request struct {
|
||||
Name string `json:"name"`
|
||||
FieldType string `json:"fieldType"`
|
||||
FieldOptions string `json:"fieldOptions"`
|
||||
Alignment string `json:"alignment"`
|
||||
Order int `json:"order"`
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
}
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
if request.Alignment == "" {
|
||||
request.Alignment = "start"
|
||||
}
|
||||
if request.FieldType == "" {
|
||||
request.FieldType = "TEXT"
|
||||
}
|
||||
updatedAt := time.Now().UnixMilli()
|
||||
result, err := s.db.pool.Exec(r.Context(), `
|
||||
UPDATE fields
|
||||
SET name = $1, fieldtype = $2, fieldoptions = $3, alignment = $4, "order" = $5, updatedat = $6
|
||||
WHERE id = $7
|
||||
`, request.Name, request.FieldType, request.FieldOptions, request.Alignment, request.Order, updatedAt, id)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update field")
|
||||
return
|
||||
}
|
||||
if result.RowsAffected() == 0 {
|
||||
writeJSONError(w, http.StatusNotFound, "Field not found")
|
||||
return
|
||||
}
|
||||
field, err := s.getField(r.Context(), id)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update field")
|
||||
return
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "updated", "field", id, field.ListID, updatedAt))
|
||||
writeJSON(w, http.StatusOK, field)
|
||||
case http.MethodDelete:
|
||||
var request struct {
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
}
|
||||
_ = decodeJSON(r, &request) // DELETE bodies are optional.
|
||||
updatedAt := time.Now().UnixMilli()
|
||||
var field Field
|
||||
cascade := false
|
||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||
var err error
|
||||
field, err = scanField(tx.QueryRow(r.Context(), `SELECT `+fieldColumns+` FROM fields WHERE id = $1`, id))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(r.Context(), `UPDATE fields SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE fieldid = $1`, id); err != nil {
|
||||
return err
|
||||
}
|
||||
var remaining int
|
||||
if err := tx.QueryRow(r.Context(), `SELECT count(*) FROM fields WHERE listid = $1 AND isdeleted = 0`, field.ListID).Scan(&remaining); err != nil {
|
||||
return err
|
||||
}
|
||||
if remaining == 0 {
|
||||
cascade = true
|
||||
if _, err := tx.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, field.ListID); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE itemid IN (SELECT id FROM items WHERE listid = $1)`, field.ListID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), tx, requestDeviceID(r, request.DeviceID), "deleted", "field", id, field.ListID, updatedAt))
|
||||
return nil
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeJSONError(w, http.StatusNotFound, "Field not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to delete field")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"message": "Field deleted successfully", "cascadeItemsDeleted": cascade})
|
||||
}
|
||||
}
|
||||
|
||||
type itemMutation struct {
|
||||
Item
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Server) handleItemsForList(w http.ResponseWriter, r *http.Request) {
|
||||
listID := r.PathValue("listId")
|
||||
if listID == "" {
|
||||
parts := strings.Split(strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/items/"), "/"), "/")
|
||||
if len(parts) == 2 && parts[0] == "list" {
|
||||
listID = parts[1]
|
||||
}
|
||||
}
|
||||
items, err := s.db.queryItems(r.Context(), false, nil, listID)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch items")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, items)
|
||||
}
|
||||
|
||||
func (s *Server) handleItemCollection(w http.ResponseWriter, r *http.Request) {
|
||||
var request itemMutation
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
if request.ID == "" || request.ListID == "" {
|
||||
writeJSONError(w, http.StatusBadRequest, "Item id and listId are required")
|
||||
return
|
||||
}
|
||||
_, err := s.db.pool.Exec(r.Context(), `
|
||||
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
`, request.ID, request.ListID, int64(request.CreatedAt), int64(request.UpdatedAt), boolInt(request.IsDeleted))
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create item")
|
||||
return
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "created", "item", request.ID, request.ListID, time.Now().UnixMilli()))
|
||||
item, err := s.getItem(r.Context(), request.ID)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create item")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, item)
|
||||
}
|
||||
|
||||
func (s *Server) getItem(ctx context.Context, id string) (Item, error) {
|
||||
return scanItem(s.db.pool.QueryRow(ctx, `SELECT `+itemColumns+` FROM items WHERE id = $1`, id))
|
||||
}
|
||||
|
||||
func (s *Server) handleValuesForItem(w http.ResponseWriter, r *http.Request) {
|
||||
itemID := r.PathValue("itemId")
|
||||
if itemID == "" {
|
||||
parts := strings.Split(strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/items/"), "/"), "/")
|
||||
if len(parts) == 2 && parts[1] == "values" {
|
||||
itemID = parts[0]
|
||||
}
|
||||
}
|
||||
values, err := s.db.queryValues(r.Context(), nil, itemID)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch item values")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, values)
|
||||
}
|
||||
|
||||
func (s *Server) handleItemValueCollection(w http.ResponseWriter, r *http.Request) {
|
||||
var request struct {
|
||||
ItemValue
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
}
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
if request.ID == "" || request.ItemID == "" || request.FieldID == "" {
|
||||
writeJSONError(w, http.StatusBadRequest, "Value id, itemId, and fieldId are required")
|
||||
return
|
||||
}
|
||||
_, err := s.db.pool.Exec(r.Context(), `
|
||||
INSERT INTO item_values (id, itemid, fieldid, value, updatedat)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (id) DO UPDATE
|
||||
SET value = EXCLUDED.value, updatedat = EXCLUDED.updatedat
|
||||
`, request.ID, request.ItemID, request.FieldID, request.Value, int64(request.UpdatedAt))
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to save item value")
|
||||
return
|
||||
}
|
||||
var listID string
|
||||
if err := s.db.pool.QueryRow(r.Context(), `SELECT listid FROM fields WHERE id = $1`, request.FieldID).Scan(&listID); err == nil {
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "listContentUpdated", "value", request.ID, listID, time.Now().UnixMilli()))
|
||||
}
|
||||
var value ItemValue
|
||||
err = s.db.pool.QueryRow(r.Context(), `SELECT `+valueColumns+` FROM item_values WHERE id = $1`, request.ID).Scan(
|
||||
&value.ID,
|
||||
&value.ItemID,
|
||||
&value.FieldID,
|
||||
&value.Value,
|
||||
&value.UpdatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to save item value")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, value)
|
||||
}
|
||||
|
||||
func (s *Server) handleItem(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.PathValue("id")
|
||||
if id == "" {
|
||||
id = strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/items/"), "/")
|
||||
}
|
||||
var request struct {
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
}
|
||||
if r.Method == http.MethodPut || r.Method == http.MethodDelete {
|
||||
_ = decodeJSON(r, &request)
|
||||
}
|
||||
updatedAt := time.Now().UnixMilli()
|
||||
if r.Method == http.MethodPut {
|
||||
result, err := s.db.pool.Exec(r.Context(), `UPDATE items SET updatedat = $1 WHERE id = $2`, updatedAt, id)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update item")
|
||||
return
|
||||
}
|
||||
if result.RowsAffected() == 0 {
|
||||
writeJSONError(w, http.StatusNotFound, "Item not found")
|
||||
return
|
||||
}
|
||||
item, err := s.getItem(r.Context(), id)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update item")
|
||||
return
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "updated", "item", id, item.ListID, updatedAt))
|
||||
writeJSON(w, http.StatusOK, item)
|
||||
return
|
||||
}
|
||||
result, err := s.db.pool.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to delete item")
|
||||
return
|
||||
}
|
||||
if result.RowsAffected() == 0 {
|
||||
writeJSONError(w, http.StatusNotFound, "Item not found")
|
||||
return
|
||||
}
|
||||
item, itemErr := s.getItem(r.Context(), id)
|
||||
if itemErr == nil {
|
||||
_, _ = s.db.pool.Exec(r.Context(), `DELETE FROM item_values WHERE itemid = $1`, id)
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "deleted", "item", id, item.ListID, updatedAt))
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"message": "Item deleted successfully"})
|
||||
}
|
||||
|
||||
func (s *Server) handleItemPath(w http.ResponseWriter, r *http.Request) {
|
||||
suffix := strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/items/"), "/")
|
||||
parts := strings.Split(suffix, "/")
|
||||
|
||||
switch {
|
||||
case r.Method == http.MethodGet && len(parts) == 2 && parts[0] == "list":
|
||||
s.handleItemsForList(w, r)
|
||||
case r.Method == http.MethodGet && len(parts) == 2 && parts[1] == "values":
|
||||
s.handleValuesForItem(w, r)
|
||||
case (r.Method == http.MethodPut || r.Method == http.MethodDelete) && len(parts) == 1 && parts[0] != "":
|
||||
s.handleItem(w, r)
|
||||
default:
|
||||
writeJSONError(w, http.StatusNotFound, "Not found")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// DB owns the PostgreSQL pool. The schema deliberately uses the same physical
|
||||
// column names as the existing Node service: PostgreSQL lowercases unquoted
|
||||
// camelCase identifiers, so createdAt is stored as createdat, etc.
|
||||
type DB struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func connectDB(ctx context.Context, connectionString string) (*DB, error) {
|
||||
pool, err := pgxpool.New(ctx, connectionString)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create pool: %w", err)
|
||||
}
|
||||
if err := pool.Ping(ctx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("ping database: %w", err)
|
||||
}
|
||||
return &DB{pool: pool}, nil
|
||||
}
|
||||
|
||||
func (d *DB) close() {
|
||||
d.pool.Close()
|
||||
}
|
||||
|
||||
func (d *DB) withTx(ctx context.Context, fn func(pgx.Tx) error) error {
|
||||
tx, err := d.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("begin transaction: %w", err)
|
||||
}
|
||||
defer tx.Rollback(ctx) // harmless after a successful commit
|
||||
|
||||
if err := fn(tx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("commit transaction: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// initSchema is idempotent so an existing CollabTable PostgreSQL database can
|
||||
// be used by the Go server without a separate migration step.
|
||||
func (d *DB) initSchema(ctx context.Context) error {
|
||||
_, err := d.pool.Exec(ctx, `
|
||||
CREATE TABLE IF NOT EXISTS lists (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
createdat BIGINT NOT NULL,
|
||||
updatedat BIGINT NOT NULL,
|
||||
isdeleted INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS fields (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
fieldtype TEXT NOT NULL,
|
||||
fieldoptions TEXT,
|
||||
alignment TEXT NOT NULL DEFAULT 'start',
|
||||
listid TEXT NOT NULL,
|
||||
"order" INTEGER NOT NULL,
|
||||
createdat BIGINT NOT NULL,
|
||||
updatedat BIGINT NOT NULL,
|
||||
isdeleted INTEGER NOT NULL DEFAULT 0,
|
||||
FOREIGN KEY (listid) REFERENCES lists(id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS items (
|
||||
id TEXT PRIMARY KEY,
|
||||
listid TEXT NOT NULL,
|
||||
createdat BIGINT NOT NULL,
|
||||
updatedat BIGINT NOT NULL,
|
||||
isdeleted INTEGER NOT NULL DEFAULT 0,
|
||||
FOREIGN KEY (listid) REFERENCES lists(id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS item_values (
|
||||
id TEXT PRIMARY KEY,
|
||||
itemid TEXT NOT NULL,
|
||||
fieldid TEXT NOT NULL,
|
||||
value TEXT,
|
||||
updatedat BIGINT NOT NULL,
|
||||
FOREIGN KEY (itemid) REFERENCES items(id),
|
||||
FOREIGN KEY (fieldid) REFERENCES fields(id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_fields_listid ON fields(listid);
|
||||
CREATE INDEX IF NOT EXISTS idx_items_listid ON items(listid);
|
||||
CREATE INDEX IF NOT EXISTS idx_item_values_itemid ON item_values(itemid);
|
||||
CREATE INDEX IF NOT EXISTS idx_item_values_fieldid ON item_values(fieldid);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS notifications (
|
||||
id TEXT PRIMARY KEY,
|
||||
deviceidorigin TEXT,
|
||||
eventtype TEXT NOT NULL,
|
||||
entitytype TEXT NOT NULL,
|
||||
entityid TEXT,
|
||||
listid TEXT,
|
||||
createdat BIGINT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_notifications_createdat ON notifications(createdat);
|
||||
CREATE INDEX IF NOT EXISTS idx_notifications_listid ON notifications(listid);
|
||||
|
||||
ALTER TABLE fields ADD COLUMN IF NOT EXISTS alignment TEXT NOT NULL DEFAULT 'start';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS auth_users (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true));
|
||||
|
||||
CREATE TABLE IF NOT EXISTS auth_sessions (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS auth_sessions_expiry_idx ON auth_sessions(expires_at);
|
||||
CREATE INDEX IF NOT EXISTS auth_sessions_user_idx ON auth_sessions(user_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS api_tokens (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS api_tokens_user_idx ON api_tokens(user_id);
|
||||
`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("initialize schema: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *DB) pruneExpiredSessions(ctx context.Context) {
|
||||
ticker := time.NewTicker(time.Hour)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
if _, err := d.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE expires_at < now()`); err != nil {
|
||||
fmt.Printf("[db] session prune failed: %v\n", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (d *DB) cleanupNotifications(ctx context.Context) {
|
||||
retention := envInt64("NOTIF_RETENTION_MS", 7*24*60*60*1000)
|
||||
if retention < 0 {
|
||||
retention = 0
|
||||
}
|
||||
ticker := time.NewTicker(time.Hour)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
cutoff := time.Now().UnixMilli() - retention
|
||||
if _, err := d.pool.Exec(ctx, `DELETE FROM notifications WHERE createdat < $1`, cutoff); err != nil {
|
||||
fmt.Printf("[db] notification cleanup failed: %v\n", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type AuthUser struct {
|
||||
ID int64
|
||||
Username string
|
||||
PasswordHash string
|
||||
}
|
||||
|
||||
var ErrSingletonUserExists = errors.New("a user already exists")
|
||||
|
||||
func (d *DB) countUsers(ctx context.Context) (int, error) {
|
||||
var count int
|
||||
if err := d.pool.QueryRow(ctx, `SELECT count(*) FROM auth_users`).Scan(&count); err != nil {
|
||||
return 0, fmt.Errorf("count users: %w", err)
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
|
||||
func (d *DB) createUser(ctx context.Context, username, passwordHash string) (*AuthUser, error) {
|
||||
var user AuthUser
|
||||
err := d.pool.QueryRow(ctx, `
|
||||
INSERT INTO auth_users (username, password_hash, updated_at)
|
||||
VALUES ($1, $2, now())
|
||||
RETURNING id, username
|
||||
`, username, passwordHash).Scan(&user.ID, &user.Username)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||
return nil, ErrSingletonUserExists
|
||||
}
|
||||
return nil, fmt.Errorf("create user: %w", err)
|
||||
}
|
||||
user.PasswordHash = passwordHash
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (d *DB) getUserByUsername(ctx context.Context, username string) (*AuthUser, error) {
|
||||
var user AuthUser
|
||||
err := d.pool.QueryRow(ctx, `
|
||||
SELECT id, username, password_hash
|
||||
FROM auth_users
|
||||
WHERE username = $1
|
||||
`, username).Scan(&user.ID, &user.Username, &user.PasswordHash)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get user: %w", err)
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (d *DB) getSessionUser(ctx context.Context, tokenHash string) (*AuthUser, error) {
|
||||
var user AuthUser
|
||||
err := d.pool.QueryRow(ctx, `
|
||||
SELECT u.id, u.username, u.password_hash
|
||||
FROM auth_sessions s
|
||||
JOIN auth_users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = $1 AND s.expires_at > now()
|
||||
`, tokenHash).Scan(&user.ID, &user.Username, &user.PasswordHash)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get session user: %w", err)
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (d *DB) createSession(ctx context.Context, userID int64, tokenHash string, expiresAt time.Time) error {
|
||||
_, err := d.pool.Exec(ctx, `
|
||||
INSERT INTO auth_sessions (user_id, token_hash, expires_at)
|
||||
VALUES ($1, $2, $3)
|
||||
`, userID, tokenHash, expiresAt)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create session: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *DB) deleteSession(ctx context.Context, tokenHash string) error {
|
||||
_, err := d.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE token_hash = $1`, tokenHash)
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete session: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *DB) updateUserCredentials(ctx context.Context, userID int64, username, passwordHash string) error {
|
||||
_, err := d.pool.Exec(ctx, `
|
||||
UPDATE auth_users
|
||||
SET username = $1, password_hash = $2, updated_at = now()
|
||||
WHERE id = $3
|
||||
`, username, passwordHash, userID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("update user credentials: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *DB) deleteSessionsForUser(ctx context.Context, userID int64) error {
|
||||
_, err := d.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE user_id = $1`, userID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete sessions for user: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *DB) hasAPIToken(ctx context.Context, userID int64) (bool, error) {
|
||||
var exists bool
|
||||
if err := d.pool.QueryRow(ctx, `
|
||||
SELECT EXISTS(SELECT 1 FROM api_tokens WHERE user_id = $1)
|
||||
`, userID).Scan(&exists); err != nil {
|
||||
return false, fmt.Errorf("check API token: %w", err)
|
||||
}
|
||||
return exists, nil
|
||||
}
|
||||
|
||||
func (d *DB) regenerateAPIToken(ctx context.Context, userID int64, tokenHash string) error {
|
||||
return d.withTx(ctx, func(tx pgx.Tx) error {
|
||||
if _, err := tx.Exec(ctx, `DELETE FROM api_tokens WHERE user_id = $1`, userID); err != nil {
|
||||
return fmt.Errorf("delete old API token: %w", err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO api_tokens (user_id, token_hash)
|
||||
VALUES ($1, $2)
|
||||
`, userID, tokenHash); err != nil {
|
||||
return fmt.Errorf("insert API token: %w", err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (d *DB) getAPITokenUserID(ctx context.Context, tokenHash string) (int64, error) {
|
||||
var userID int64
|
||||
err := d.pool.QueryRow(ctx, `
|
||||
SELECT user_id FROM api_tokens WHERE token_hash = $1
|
||||
`, tokenHash).Scan(&userID)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return 0, nil
|
||||
}
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("get API token owner: %w", err)
|
||||
}
|
||||
return userID, nil
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
# Ensure data directory exists
|
||||
mkdir -p /data
|
||||
@@ -0,0 +1,17 @@
|
||||
module collabtable/server
|
||||
|
||||
go 1.26.5
|
||||
|
||||
require (
|
||||
github.com/jackc/pgx/v5 v5.10.0
|
||||
github.com/joho/godotenv v1.5.1
|
||||
golang.org/x/crypto v0.54.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
golang.org/x/sync v0.22.0 // indirect
|
||||
golang.org/x/text v0.40.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,30 @@
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0=
|
||||
github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
|
||||
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
|
||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
|
||||
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,125 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// Timestamp accepts the millisecond timestamps emitted by the Android client as
|
||||
// well as the older string/second-based representations accepted by the Node
|
||||
// server. It marshals back as a JSON number for the mobile client.
|
||||
type Timestamp int64
|
||||
|
||||
func (t *Timestamp) UnmarshalJSON(data []byte) error {
|
||||
value := bytes.TrimSpace(data)
|
||||
if len(value) == 0 || bytes.Equal(value, []byte("null")) {
|
||||
*t = 0
|
||||
return nil
|
||||
}
|
||||
|
||||
if value[0] == '"' {
|
||||
var stringValue string
|
||||
if err := json.Unmarshal(value, &stringValue); err != nil {
|
||||
return err
|
||||
}
|
||||
parsed, err := parseTimestamp(stringValue)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*t = Timestamp(parsed)
|
||||
return nil
|
||||
}
|
||||
|
||||
parsed, err := strconv.ParseFloat(string(value), 64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid timestamp %q: %w", string(value), err)
|
||||
}
|
||||
*t = Timestamp(parsed)
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseTimestamp(value string) (int64, error) {
|
||||
if numeric, err := strconv.ParseFloat(value, 64); err == nil {
|
||||
return int64(numeric), nil
|
||||
}
|
||||
return 0, fmt.Errorf("invalid timestamp %q", value)
|
||||
}
|
||||
|
||||
type List struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
CreatedAt Timestamp `json:"createdAt"`
|
||||
UpdatedAt Timestamp `json:"updatedAt"`
|
||||
IsDeleted bool `json:"isDeleted"`
|
||||
}
|
||||
|
||||
type Field struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
FieldType string `json:"fieldType"`
|
||||
FieldOptions string `json:"fieldOptions"`
|
||||
Alignment string `json:"alignment"`
|
||||
ListID string `json:"listId"`
|
||||
Order int `json:"order"`
|
||||
CreatedAt Timestamp `json:"createdAt"`
|
||||
UpdatedAt Timestamp `json:"updatedAt"`
|
||||
IsDeleted bool `json:"isDeleted"`
|
||||
}
|
||||
|
||||
type Item struct {
|
||||
ID string `json:"id"`
|
||||
ListID string `json:"listId"`
|
||||
CreatedAt Timestamp `json:"createdAt"`
|
||||
UpdatedAt Timestamp `json:"updatedAt"`
|
||||
IsDeleted bool `json:"isDeleted"`
|
||||
}
|
||||
|
||||
type ItemValue struct {
|
||||
ID string `json:"id"`
|
||||
ItemID string `json:"itemId"`
|
||||
FieldID string `json:"fieldId"`
|
||||
Value string `json:"value"`
|
||||
UpdatedAt Timestamp `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type SyncRequest struct {
|
||||
LastSyncTimestamp Timestamp `json:"lastSyncTimestamp"`
|
||||
Lists []List `json:"lists"`
|
||||
Fields []Field `json:"fields"`
|
||||
Items []Item `json:"items"`
|
||||
ItemValues []ItemValue `json:"itemValues"`
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
}
|
||||
|
||||
type SyncResponse struct {
|
||||
Lists []List `json:"lists"`
|
||||
Fields []Field `json:"fields"`
|
||||
Items []Item `json:"items"`
|
||||
ItemValues []ItemValue `json:"itemValues"`
|
||||
OrphanItemValues []OrphanValue `json:"orphanItemValues"`
|
||||
ServerTimestamp int64 `json:"serverTimestamp"`
|
||||
}
|
||||
|
||||
type OrphanValue struct {
|
||||
ID string `json:"id"`
|
||||
ItemID string `json:"itemId"`
|
||||
FieldID string `json:"fieldId"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
type NotificationEvent struct {
|
||||
ID string `json:"id"`
|
||||
DeviceIDOrigin string `json:"deviceIdOrigin,omitempty"`
|
||||
EventType string `json:"eventType"`
|
||||
EntityType string `json:"entityType"`
|
||||
EntityID string `json:"entityId,omitempty"`
|
||||
ListID string `json:"listId,omitempty"`
|
||||
CreatedAt int64 `json:"createdAt"`
|
||||
}
|
||||
|
||||
type PollResponse struct {
|
||||
Notifications []NotificationEvent `json:"notifications"`
|
||||
ServerTimestamp int64 `json:"serverTimestamp"`
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTimestampAcceptsNumericAndStringValues(t *testing.T) {
|
||||
for _, input := range []string{`1700000000000`, `"1700000000000"`} {
|
||||
var timestamp Timestamp
|
||||
if err := json.Unmarshal([]byte(input), ×tamp); err != nil {
|
||||
t.Fatalf("unmarshal %s: %v", input, err)
|
||||
}
|
||||
if timestamp != 1700000000000 {
|
||||
t.Fatalf("unmarshal %s = %d, want 1700000000000", input, timestamp)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTimestampAcceptsNullAsZero(t *testing.T) {
|
||||
var timestamp Timestamp = 42
|
||||
if err := json.Unmarshal([]byte(`null`), ×tamp); err != nil {
|
||||
t.Fatalf("unmarshal null: %v", err)
|
||||
}
|
||||
if timestamp != 0 {
|
||||
t.Fatalf("null timestamp = %d, want 0", timestamp)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
type queryExecutor interface {
|
||||
Exec(context.Context, string, ...any) (pgconn.CommandTag, error)
|
||||
}
|
||||
|
||||
func notificationID() string {
|
||||
buffer := make([]byte, 16)
|
||||
if _, err := rand.Read(buffer); err == nil {
|
||||
return hex.EncodeToString(buffer)
|
||||
}
|
||||
return fmt.Sprintf("%d", time.Now().UnixNano())
|
||||
}
|
||||
|
||||
func enqueueNotification(
|
||||
ctx context.Context,
|
||||
executor queryExecutor,
|
||||
deviceID string,
|
||||
eventType string,
|
||||
entityType string,
|
||||
entityID string,
|
||||
listID string,
|
||||
createdAt int64,
|
||||
) error {
|
||||
_, err := executor.Exec(ctx, `
|
||||
INSERT INTO notifications
|
||||
(id, deviceidorigin, eventtype, entitytype, entityid, listid, createdat)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
`, notificationID(), nullableString(deviceID), eventType, entityType, nullableString(entityID), nullableString(listID), createdAt)
|
||||
return err
|
||||
}
|
||||
|
||||
func nullableString(value string) any {
|
||||
if value == "" {
|
||||
return nil
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func ignoreNotificationError(err error) {
|
||||
if err != nil {
|
||||
// Notifications are an acceleration path for clients that poll. A failed
|
||||
// notification must never roll back the data mutation that produced it.
|
||||
fmt.Printf("[notifications] enqueue failed: %v\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
func isNoRows(err error) bool {
|
||||
return err == pgx.ErrNoRows
|
||||
}
|
||||
Generated
-3402
File diff suppressed because it is too large.
Load diff
@@ -1,40 +0,0 @@
|
||||
{
|
||||
"name": "collabtable-server",
|
||||
"version": "1.0.0",
|
||||
"description": "Collaborative list management server",
|
||||
"main": "dist/index.js",
|
||||
"scripts": {
|
||||
"start": "node dist/index.js",
|
||||
"dev": "ts-node-dev --respawn --transpile-only src/index.ts",
|
||||
"build": "tsc",
|
||||
"lint": "eslint src --ext .ts",
|
||||
"format": "prettier --write \"**/*.{ts,js,json,md,yml,yaml}\"",
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"keywords": ["collaboration", "api", "express"],
|
||||
"author": "",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"express": "^4.18.2",
|
||||
"cors": "^2.8.5",
|
||||
"cookie-parser": "^1.4.6",
|
||||
"bcryptjs": "^2.4.3",
|
||||
"dotenv": "^16.3.1",
|
||||
"@typescript-eslint/eslint-plugin": "^7.0.2",
|
||||
"@typescript-eslint/parser": "^7.0.2",
|
||||
"eslint": "^8.57.0",
|
||||
"eslint-config-prettier": "^9.1.0",
|
||||
"prettier": "^3.3.3",
|
||||
"pg": "^8.11.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/express": "^4.17.21",
|
||||
"@types/cors": "^2.8.17",
|
||||
"@types/cookie-parser": "^1.4.7",
|
||||
"@types/bcryptjs": "^2.4.6",
|
||||
"@types/node": "^20.10.6",
|
||||
"@types/pg": "^8.10.2",
|
||||
"typescript": "5.5.4",
|
||||
"ts-node-dev": "^2.0.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRegisterRoutes(t *testing.T) {
|
||||
server := &Server{auth: &AuthService{}}
|
||||
server.registerRoutes(http.NewServeMux(), webFS)
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"embed"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
_ "github.com/joho/godotenv/autoload"
|
||||
)
|
||||
|
||||
// The SvelteKit build is copied here by the Docker builder before go build.
|
||||
// Keeping a tiny tracked placeholder in web/ also lets go test run from a
|
||||
// checkout before the dashboard has been built.
|
||||
//
|
||||
//go:embed all:web
|
||||
var webFS embed.FS
|
||||
|
||||
type Server struct {
|
||||
db *DB
|
||||
auth *AuthService
|
||||
startTime time.Time
|
||||
}
|
||||
|
||||
func main() {
|
||||
port := envOrDefault("PORT", "3000")
|
||||
connectionString := strings.TrimSpace(os.Getenv("DATABASE_URL"))
|
||||
if connectionString == "" {
|
||||
fmt.Fprintln(os.Stderr, "DATABASE_URL environment variable is required")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
database, err := connectWithRetry(ctx, connectionString)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "database initialization failed: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer database.close()
|
||||
go database.pruneExpiredSessions(ctx)
|
||||
go database.cleanupNotifications(ctx)
|
||||
|
||||
auth := newAuthService(database, strings.EqualFold(os.Getenv("COOKIE_SECURE"), "true"))
|
||||
server := &Server{db: database, auth: auth, startTime: time.Now()}
|
||||
|
||||
webRoot, err := fs.Sub(webFS, "web")
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "embedded web assets missing: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
server.registerRoutes(mux, webRoot)
|
||||
|
||||
httpServer := &http.Server{
|
||||
Addr: ":" + port,
|
||||
Handler: withCORS(mux),
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
ReadTimeout: 60 * time.Second,
|
||||
WriteTimeout: 60 * time.Second,
|
||||
IdleTimeout: 120 * time.Second,
|
||||
}
|
||||
|
||||
fmt.Printf("CollabTable Go server listening on :%s\n", port)
|
||||
fmt.Printf("Database: PostgreSQL (pgx)\n")
|
||||
if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
fmt.Fprintf(os.Stderr, "server error: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func connectWithRetry(ctx context.Context, connectionString string) (*DB, error) {
|
||||
interval := time.Duration(envInt64("DB_INIT_RETRY_INTERVAL_MS", 5000)) * time.Millisecond
|
||||
if interval < 250*time.Millisecond {
|
||||
interval = 250 * time.Millisecond
|
||||
}
|
||||
maxAttempts := envInt64("DB_INIT_RETRY_MAX_ATTEMPTS", 0)
|
||||
|
||||
for attempt := int64(1); ; attempt++ {
|
||||
database, err := connectDB(ctx, connectionString)
|
||||
if err == nil {
|
||||
if schemaErr := database.initSchema(ctx); schemaErr == nil {
|
||||
if attempt > 1 {
|
||||
fmt.Printf("[DB] Connected after %d attempt(s)\n", attempt)
|
||||
}
|
||||
return database, nil
|
||||
} else {
|
||||
database.close()
|
||||
err = schemaErr
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Fprintf(os.Stderr, "[DB] Initialization attempt %d failed: %v\n", attempt, err)
|
||||
if maxAttempts > 0 && attempt >= maxAttempts {
|
||||
return nil, err
|
||||
}
|
||||
fmt.Printf("[DB] Retrying in %s...\n", interval)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-time.After(interval):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) registerRoutes(mux *http.ServeMux, webRoot fs.FS) {
|
||||
// Health and auth bootstrap routes are intentionally public.
|
||||
mux.HandleFunc("GET /health", s.handleHealth)
|
||||
mux.HandleFunc("GET /api/auth/status", s.auth.handleStatus)
|
||||
mux.HandleFunc("POST /api/auth/setup", s.auth.handleSetup)
|
||||
mux.HandleFunc("POST /api/auth/login", s.auth.handleLogin)
|
||||
mux.Handle("POST /api/auth/logout", s.auth.requireSession(s.auth.handleLogout))
|
||||
mux.Handle("POST /api/auth/credentials", s.auth.requireSession(s.auth.handleUpdateCredentials))
|
||||
mux.Handle("GET /api/auth/token/status", s.auth.requireSession(s.auth.handleTokenStatus))
|
||||
mux.Handle("POST /api/auth/token/regenerate", s.auth.requireSession(s.auth.handleTokenRegenerate))
|
||||
|
||||
// Sync/collaboration API routes use a long-lived bearer token shared by the
|
||||
// user's devices. This is deliberately separate from browser sessions.
|
||||
api := func(handler http.Handler) http.Handler {
|
||||
return s.auth.requireAPIToken(handler)
|
||||
}
|
||||
mux.Handle("GET /api/lists", api(http.HandlerFunc(s.handleListCollection)))
|
||||
mux.Handle("POST /api/lists", api(http.HandlerFunc(s.handleListCollection)))
|
||||
mux.Handle("GET /api/lists/{id}", api(http.HandlerFunc(s.handleListItem)))
|
||||
mux.Handle("PUT /api/lists/{id}", api(http.HandlerFunc(s.handleListItem)))
|
||||
mux.Handle("DELETE /api/lists/{id}", api(http.HandlerFunc(s.handleListItem)))
|
||||
|
||||
mux.Handle("POST /api/fields", api(http.HandlerFunc(s.handleFieldCollection)))
|
||||
mux.Handle("GET /api/fields/list/{listId}", api(http.HandlerFunc(s.handleFieldsForList)))
|
||||
mux.Handle("PUT /api/fields/{id}", api(http.HandlerFunc(s.handleFieldItem)))
|
||||
mux.Handle("DELETE /api/fields/{id}", api(http.HandlerFunc(s.handleFieldItem)))
|
||||
|
||||
mux.Handle("POST /api/items", api(http.HandlerFunc(s.handleItemCollection)))
|
||||
mux.Handle("POST /api/items/values", api(http.HandlerFunc(s.handleItemValueCollection)))
|
||||
// These item paths overlap under the Go ServeMux pattern rules (for
|
||||
// example /items/list/values), so dispatch the legacy subroutes in one
|
||||
// prefix handler while keeping /items/values exact for POST.
|
||||
mux.Handle("/api/items/", api(http.HandlerFunc(s.handleItemPath)))
|
||||
|
||||
mux.Handle("POST /api/sync", api(http.HandlerFunc(s.handleSync)))
|
||||
mux.Handle("GET /api/notifications/poll", api(http.HandlerFunc(s.handleNotificationPoll)))
|
||||
|
||||
// The dashboard is a public SPA shell, but its data and tech-stack endpoints
|
||||
// are protected by the browser session.
|
||||
mux.Handle("GET /web/info", s.auth.requireSession(s.handleWebInfo))
|
||||
mux.Handle("GET /web/data", s.auth.requireSession(s.handleWebData))
|
||||
mux.Handle("/", spaFileServer(webRoot))
|
||||
}
|
||||
|
||||
func (s *Server) handleHealth(w http.ResponseWriter, _ *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"status": "ok",
|
||||
"timestamp": time.Now().UnixMilli(),
|
||||
})
|
||||
}
|
||||
|
||||
func envOrDefault(name, fallback string) string {
|
||||
if value := strings.TrimSpace(os.Getenv(name)); value != "" {
|
||||
return value
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func envInt64(name string, fallback int64) int64 {
|
||||
value := strings.TrimSpace(os.Getenv(name))
|
||||
if value == "" {
|
||||
return fallback
|
||||
}
|
||||
var parsed int64
|
||||
if _, err := fmt.Sscan(value, &parsed); err != nil {
|
||||
return fallback
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
|
||||
func decodeJSON(r *http.Request, target any) error {
|
||||
decoder := json.NewDecoder(io.LimitReader(r.Body, 50*1024*1024))
|
||||
if err := decoder.Decode(target); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, value any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(value)
|
||||
}
|
||||
|
||||
func writeJSONError(w http.ResponseWriter, status int, message string) {
|
||||
writeJSON(w, status, map[string]string{
|
||||
"error": message,
|
||||
"message": message,
|
||||
})
|
||||
}
|
||||
|
||||
func withCORS(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
origin := r.Header.Get("Origin")
|
||||
if origin != "" {
|
||||
w.Header().Set("Access-Control-Allow-Origin", origin)
|
||||
w.Header().Set("Access-Control-Allow-Credentials", "true")
|
||||
w.Header().Add("Vary", "Origin")
|
||||
}
|
||||
if r.Method == http.MethodOptions {
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Device-Id")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func spaFileServer(root fs.FS) http.Handler {
|
||||
fileServer := http.FileServer(http.FS(root))
|
||||
serveIndex := func(w http.ResponseWriter, r *http.Request) {
|
||||
data, err := fs.ReadFile(root, "index.html")
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
_, _ = w.Write(data)
|
||||
}
|
||||
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
cleanPath := strings.TrimPrefix(path.Clean(r.URL.Path), "/")
|
||||
if cleanPath == "" || cleanPath == "." || cleanPath == "index.html" {
|
||||
serveIndex(w, r)
|
||||
return
|
||||
}
|
||||
if _, err := fs.Stat(root, cleanPath); err != nil {
|
||||
serveIndex(w, r)
|
||||
return
|
||||
}
|
||||
fileServer.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
type dependency struct {
|
||||
Name string `json:"name"`
|
||||
Version string `json:"version"`
|
||||
}
|
||||
|
||||
type techStackResponse struct {
|
||||
AppVersion string `json:"appVersion"`
|
||||
Stack []stackEntry `json:"stack"`
|
||||
}
|
||||
|
||||
type stackEntry struct {
|
||||
Label string `json:"label"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
func (s *Server) handleWebInfo(w http.ResponseWriter, _ *http.Request, _ *AuthUser) {
|
||||
writeJSON(w, http.StatusOK, techStackResponse{
|
||||
AppVersion: envOrDefault("APP_VERSION", "dev"),
|
||||
Stack: []stackEntry{
|
||||
{Label: "Runtime", Value: "Go " + runtime.Version()},
|
||||
{Label: "Language", Value: "Go " + runtime.Version()},
|
||||
{Label: "Web Framework", Value: "net/http"},
|
||||
{Label: "Database", Value: "PostgreSQL (pgx/v5)"},
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -1,220 +0,0 @@
|
||||
import dotenv from 'dotenv';
|
||||
import { Pool, PoolClient, QueryResult, types as pgTypes } from 'pg';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
type Param = any;
|
||||
|
||||
type ExecResult = { changes: number };
|
||||
|
||||
|
||||
interface DBAdapter {
|
||||
queryAll(sql: string, params?: Param[]): Promise<any[]>;
|
||||
queryOne(sql: string, params?: Param[]): Promise<any | undefined>;
|
||||
execute(sql: string, params?: Param[]): Promise<ExecResult>;
|
||||
transaction<T>(fn: (tx: DBAdapter) => Promise<T>): Promise<T>;
|
||||
initialize(): Promise<void>;
|
||||
}
|
||||
|
||||
function replaceQuotedIdentifiers(sql: string) {
|
||||
// Convert backticks to double quotes for portability
|
||||
return sql.replace(/`([^`]+)`/g, '"$1"');
|
||||
}
|
||||
|
||||
function convertQMarksToPg(sql: string) {
|
||||
// Replace each ? with $1, $2, ...
|
||||
let idx = 0;
|
||||
return sql.replace(/\?/g, () => `$${++idx}`);
|
||||
}
|
||||
|
||||
// ---------- Postgres Adapter ----------
|
||||
class PostgresAdapter implements DBAdapter {
|
||||
private pool: Pool;
|
||||
|
||||
constructor() {
|
||||
// Ensure BIGINT (int8) is parsed as number to avoid string timestamps
|
||||
// OID 20 = INT8, OID 1700 = NUMERIC (keep default for now)
|
||||
pgTypes.setTypeParser(20, (val: string) => parseInt(val, 10));
|
||||
const connectionString = process.env.DATABASE_URL;
|
||||
if (!connectionString) {
|
||||
throw new Error('DATABASE_URL environment variable is required');
|
||||
}
|
||||
this.pool = new Pool({ connectionString });
|
||||
}
|
||||
|
||||
async initialize(): Promise<void> {
|
||||
// Create tables if not exist
|
||||
const client = await this.pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
await client.query(`
|
||||
CREATE TABLE IF NOT EXISTS lists (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
createdAt BIGINT NOT NULL,
|
||||
updatedAt BIGINT NOT NULL,
|
||||
isDeleted INTEGER DEFAULT 0
|
||||
);
|
||||
`);
|
||||
await client.query(`
|
||||
CREATE TABLE IF NOT EXISTS fields (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
fieldType TEXT NOT NULL,
|
||||
fieldOptions TEXT,
|
||||
alignment TEXT NOT NULL DEFAULT 'start',
|
||||
listId TEXT NOT NULL,
|
||||
"order" INTEGER NOT NULL,
|
||||
createdAt BIGINT NOT NULL,
|
||||
updatedAt BIGINT NOT NULL,
|
||||
isDeleted INTEGER DEFAULT 0,
|
||||
FOREIGN KEY (listId) REFERENCES lists(id)
|
||||
);
|
||||
`);
|
||||
await client.query(`
|
||||
CREATE TABLE IF NOT EXISTS items (
|
||||
id TEXT PRIMARY KEY,
|
||||
listId TEXT NOT NULL,
|
||||
createdAt BIGINT NOT NULL,
|
||||
updatedAt BIGINT NOT NULL,
|
||||
isDeleted INTEGER DEFAULT 0,
|
||||
FOREIGN KEY (listId) REFERENCES lists(id)
|
||||
);
|
||||
`);
|
||||
await client.query(`
|
||||
CREATE TABLE IF NOT EXISTS item_values (
|
||||
id TEXT PRIMARY KEY,
|
||||
itemId TEXT NOT NULL,
|
||||
fieldId TEXT NOT NULL,
|
||||
value TEXT,
|
||||
updatedAt BIGINT NOT NULL,
|
||||
FOREIGN KEY (itemId) REFERENCES items(id),
|
||||
FOREIGN KEY (fieldId) REFERENCES fields(id)
|
||||
);
|
||||
`);
|
||||
await client.query(`CREATE INDEX IF NOT EXISTS idx_fields_listId ON fields(listId);`);
|
||||
await client.query(`CREATE INDEX IF NOT EXISTS idx_items_listId ON items(listId);`);
|
||||
await client.query(`CREATE INDEX IF NOT EXISTS idx_item_values_itemId ON item_values(itemId);`);
|
||||
await client.query(`CREATE INDEX IF NOT EXISTS idx_item_values_fieldId ON item_values(fieldId);`);
|
||||
// Notifications table
|
||||
await client.query(`
|
||||
CREATE TABLE IF NOT EXISTS notifications (
|
||||
id TEXT PRIMARY KEY,
|
||||
deviceIdOrigin TEXT,
|
||||
eventType TEXT NOT NULL,
|
||||
entityType TEXT NOT NULL,
|
||||
entityId TEXT,
|
||||
listId TEXT,
|
||||
createdAt BIGINT NOT NULL
|
||||
);
|
||||
`);
|
||||
await client.query(`CREATE INDEX IF NOT EXISTS idx_notifications_createdAt ON notifications(createdAt);`);
|
||||
await client.query(`CREATE INDEX IF NOT EXISTS idx_notifications_listId ON notifications(listId);`);
|
||||
// Migrate existing DBs: ensure alignment column exists
|
||||
await client.query(`ALTER TABLE fields ADD COLUMN IF NOT EXISTS alignment TEXT NOT NULL DEFAULT 'start';`);
|
||||
|
||||
// ---- Auth (single admin account for the web dashboard) ----
|
||||
// Matches the Bitmagnet/UnraidMonitor pattern: opaque session-cookie tokens (no JWT),
|
||||
// bcrypt-hashed passwords, schema created idempotently on every startup.
|
||||
await client.query(`
|
||||
CREATE TABLE IF NOT EXISTS auth_users (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
`);
|
||||
// Enforces a single admin account, matching a single-tenant dashboard.
|
||||
await client.query(`
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true));
|
||||
`);
|
||||
await client.query(`
|
||||
CREATE TABLE IF NOT EXISTS auth_sessions (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
`);
|
||||
await client.query(`CREATE INDEX IF NOT EXISTS auth_sessions_expiry_idx ON auth_sessions (expires_at);`);
|
||||
await client.query(`CREATE INDEX IF NOT EXISTS auth_sessions_user_idx ON auth_sessions (user_id);`);
|
||||
// Long-lived credential for sync clients/devices (replaces the old optional
|
||||
// SERVER_PASSWORD scheme, which silently disabled auth entirely when unset). Only
|
||||
// the SHA-256 hash is stored; the raw token is shown once, at creation/regeneration.
|
||||
await client.query(`
|
||||
CREATE TABLE IF NOT EXISTS api_tokens (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
`);
|
||||
await client.query(`CREATE INDEX IF NOT EXISTS api_tokens_user_idx ON api_tokens (user_id);`);
|
||||
|
||||
await client.query('COMMIT');
|
||||
} catch (e) {
|
||||
await client.query('ROLLBACK');
|
||||
throw e;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
private async runQuery(sql: string, params: Param[] = [], client?: PoolClient): Promise<QueryResult<any>> {
|
||||
// Replace backticks and convert ? to $1..$n
|
||||
const text = convertQMarksToPg(replaceQuotedIdentifiers(sql));
|
||||
const runner: Pool | PoolClient = client || this.pool;
|
||||
return runner.query(text, params);
|
||||
}
|
||||
|
||||
async queryAll(sql: string, params: Param[] = []): Promise<any[]> {
|
||||
const res = await this.runQuery(sql, params);
|
||||
return res.rows;
|
||||
}
|
||||
|
||||
async queryOne(sql: string, params: Param[] = []): Promise<any | undefined> {
|
||||
const res = await this.runQuery(sql, params);
|
||||
return res.rows[0];
|
||||
}
|
||||
|
||||
async execute(sql: string, params: Param[] = []): Promise<ExecResult> {
|
||||
const res = await this.runQuery(sql, params);
|
||||
return { changes: res.rowCount || 0 };
|
||||
}
|
||||
|
||||
async transaction<T>(fn: (tx: DBAdapter) => Promise<T>): Promise<T> {
|
||||
const client = await this.pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const txAdapter: DBAdapter = {
|
||||
initialize: async () => {},
|
||||
queryAll: (sql, params) => this.runQuery(sql, params, client).then(r => r.rows),
|
||||
queryOne: (sql, params) => this.runQuery(sql, params, client).then(r => r.rows[0]),
|
||||
execute: (sql, params) => this.runQuery(sql, params, client).then(r => ({ changes: r.rowCount || 0 })),
|
||||
transaction: async (inner) => {
|
||||
// Nested transactions are treated as flat for simplicity
|
||||
return inner(txAdapter);
|
||||
}
|
||||
} as DBAdapter;
|
||||
const result = await fn(txAdapter);
|
||||
await client.query('COMMIT');
|
||||
return result;
|
||||
} catch (e) {
|
||||
await client.query('ROLLBACK');
|
||||
throw e;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const dbEngine = 'PostgreSQL';
|
||||
export const dbAdapter: DBAdapter = new PostgresAdapter();
|
||||
|
||||
export async function initializeDatabase() {
|
||||
await dbAdapter.initialize();
|
||||
}
|
||||
|
||||
export type { DBAdapter };
|
||||
@@ -1,113 +0,0 @@
|
||||
import express from 'express';
|
||||
import cors from 'cors';
|
||||
import cookieParser from 'cookie-parser';
|
||||
import dotenv from 'dotenv';
|
||||
import { initializeDatabase } from './db';
|
||||
import { requireApiToken } from './middleware/auth';
|
||||
import { deviceIdMiddleware } from './middleware/device';
|
||||
import authRoutes from './routes/authRoutes';
|
||||
import listRoutes from './routes/listRoutes';
|
||||
import fieldRoutes from './routes/fieldRoutes';
|
||||
import itemRoutes from './routes/itemRoutes';
|
||||
import syncRoutes from './routes/syncRoutes';
|
||||
import webRoutes from './routes/webRoutes';
|
||||
import notificationRoutes from './routes/notificationRoutes';
|
||||
import { startNotificationCleanup } from './notifications';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const app = express();
|
||||
const PORT = process.env.PORT || 3000;
|
||||
const DB_INIT_RETRY_INTERVAL_MS = Math.max(250, Number(process.env.DB_INIT_RETRY_INTERVAL_MS || 5000));
|
||||
const DB_INIT_RETRY_MAX_ATTEMPTS = Math.max(0, Number(process.env.DB_INIT_RETRY_MAX_ATTEMPTS || 0));
|
||||
|
||||
function sleep(ms: number) {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
async function initializeDatabaseWithRetry() {
|
||||
let attempt = 0;
|
||||
|
||||
for (;;) {
|
||||
attempt += 1;
|
||||
|
||||
try {
|
||||
await initializeDatabase();
|
||||
if (attempt > 1) {
|
||||
console.log(`[DB] Connected after ${attempt} attempt(s)`);
|
||||
}
|
||||
return;
|
||||
} catch (error) {
|
||||
const reachedLimit = DB_INIT_RETRY_MAX_ATTEMPTS > 0 && attempt >= DB_INIT_RETRY_MAX_ATTEMPTS;
|
||||
|
||||
console.error(`[DB] Initialization attempt ${attempt} failed`, error);
|
||||
|
||||
if (reachedLimit) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
console.log(`[DB] Retrying in ${DB_INIT_RETRY_INTERVAL_MS}ms...`);
|
||||
await sleep(DB_INIT_RETRY_INTERVAL_MS);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Middleware
|
||||
app.use(cors({ credentials: true, origin: true }));
|
||||
app.use(express.json());
|
||||
app.use(cookieParser());
|
||||
|
||||
// Health check (no auth required)
|
||||
app.get('/health', (req, res) => {
|
||||
res.json({ status: 'ok', timestamp: Date.now() });
|
||||
});
|
||||
|
||||
// Auth bootstrap routes (status/setup/login/logout/credentials/token) - must stay
|
||||
// reachable without a token or session, mounted before the API-token gate below.
|
||||
app.use('/api', authRoutes);
|
||||
|
||||
// Sync/collaboration API: gated by a long-lived API token shared by every collaborating
|
||||
// device (see middleware/auth.ts) - this replaces the old optional SERVER_PASSWORD scheme,
|
||||
// which silently disabled auth entirely when unset.
|
||||
app.use('/api', requireApiToken);
|
||||
// Attach device id for downstream routes
|
||||
app.use('/api', deviceIdMiddleware);
|
||||
|
||||
// Routes (protected by the API token above)
|
||||
app.use('/api/lists', listRoutes);
|
||||
app.use('/api/fields', fieldRoutes);
|
||||
app.use('/api/items', itemRoutes);
|
||||
app.use('/api', syncRoutes);
|
||||
app.use('/api', notificationRoutes);
|
||||
|
||||
// Web UI (static SPA shell is public; its /web/info and /web/data JSON endpoints require
|
||||
// the admin session - see webRoutes.ts. Mounted last to not interfere with API routes.)
|
||||
app.use('/', webRoutes);
|
||||
|
||||
// Initialize database and start server
|
||||
(async () => {
|
||||
try {
|
||||
await initializeDatabaseWithRetry();
|
||||
console.log('Database synchronized successfully');
|
||||
console.log('Database models loaded:');
|
||||
console.log('- Lists');
|
||||
console.log('- Fields');
|
||||
console.log('- Items');
|
||||
console.log('- ItemValues');
|
||||
|
||||
// Start retention cleanup for notifications
|
||||
startNotificationCleanup();
|
||||
|
||||
// Start HTTP server (WebSocket removed)
|
||||
app.listen(PORT, () => {
|
||||
console.log(`Server is running on port ${PORT}`);
|
||||
console.log(`Environment: ${process.env.NODE_ENV || 'development'}`);
|
||||
console.log('Database: PostgreSQL (DATABASE_URL)');
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Database initialization error:', error);
|
||||
process.exit(1);
|
||||
}
|
||||
})();
|
||||
|
||||
export default app;
|
||||
@@ -1,54 +0,0 @@
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import crypto from 'crypto';
|
||||
import { dbAdapter } from '../db';
|
||||
|
||||
export const SESSION_COOKIE_NAME = 'collabtable_session';
|
||||
|
||||
export function hashToken(token: string): string {
|
||||
return crypto.createHash('sha256').update(token).digest('hex');
|
||||
}
|
||||
|
||||
export function randomToken(): string {
|
||||
return crypto.randomBytes(32).toString('base64url');
|
||||
}
|
||||
|
||||
/**
|
||||
* Gates the web dashboard (webRoutes' JSON endpoints) behind the single admin account's
|
||||
* session cookie. Matches the Bitmagnet/UnraidMonitor pattern - opaque cookie tokens, not JWT.
|
||||
*/
|
||||
export async function requireSession(req: Request, res: Response, next: NextFunction) {
|
||||
const token = req.cookies?.[SESSION_COOKIE_NAME];
|
||||
if (!token) {
|
||||
return res.status(401).json({ error: 'Unauthorized', message: 'Authentication required' });
|
||||
}
|
||||
const user = await dbAdapter.queryOne(
|
||||
`SELECT u.id, u.username FROM auth_sessions s
|
||||
JOIN auth_users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = ? AND s.expires_at > now()`,
|
||||
[hashToken(token)]
|
||||
);
|
||||
if (!user) {
|
||||
return res.status(401).json({ error: 'Unauthorized', message: 'Session expired or invalid' });
|
||||
}
|
||||
(req as any).user = user;
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gates the sync/collaboration API (lists/fields/items/sync/notifications) behind a
|
||||
* long-lived API token tied to the admin account - this is machine/multi-device traffic
|
||||
* shared by every collaborating client, not an interactive browser login. Replaces the old
|
||||
* optional SERVER_PASSWORD scheme, which silently disabled auth entirely when unset.
|
||||
*/
|
||||
export async function requireApiToken(req: Request, res: Response, next: NextFunction) {
|
||||
const authHeader = req.headers.authorization;
|
||||
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
||||
return res.status(401).json({ error: 'Unauthorized', message: 'No bearer token provided' });
|
||||
}
|
||||
const token = authHeader.slice('Bearer '.length);
|
||||
const row = await dbAdapter.queryOne('SELECT user_id FROM api_tokens WHERE token_hash = ?', [hashToken(token)]);
|
||||
if (!row) {
|
||||
return res.status(401).json({ error: 'Unauthorized', message: 'Invalid API token' });
|
||||
}
|
||||
next();
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
|
||||
/**
|
||||
* Extracts device identifier from headers/body and attaches it to req as `deviceId`.
|
||||
* - Preferred: `x-device-id` header
|
||||
* - Fallback: `req.body.deviceId` or `req.query.deviceId`
|
||||
*/
|
||||
export function deviceIdMiddleware(req: Request, _res: Response, next: NextFunction) {
|
||||
const headerId = (req.headers['x-device-id'] || req.headers['X-Device-Id']) as string | undefined;
|
||||
const bodyId = (req.body && typeof req.body === 'object') ? (req.body.deviceId as string | undefined) : undefined;
|
||||
const queryId = (req.query?.deviceId as string | undefined);
|
||||
const id = (headerId || bodyId || queryId || '').toString().trim();
|
||||
(req as any).deviceId = id.length > 0 ? id : undefined;
|
||||
next();
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
import { dbAdapter, DBAdapter } from './db';
|
||||
import crypto from 'crypto';
|
||||
|
||||
export type NotificationEvent = {
|
||||
id: string;
|
||||
deviceIdOrigin?: string;
|
||||
eventType: string; // created | updated | deleted | listContentUpdated | listEdited ...
|
||||
entityType: string; // list | field | item | value
|
||||
entityId?: string;
|
||||
listId?: string;
|
||||
createdAt: number; // ms epoch
|
||||
};
|
||||
|
||||
function genId() {
|
||||
try {
|
||||
return crypto.randomUUID();
|
||||
} catch {
|
||||
return `${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
|
||||
}
|
||||
}
|
||||
|
||||
export async function enqueueNotification(
|
||||
adapter: DBAdapter,
|
||||
deviceIdOrigin: string | undefined,
|
||||
eventType: string,
|
||||
entityType: string,
|
||||
entityId?: string,
|
||||
listId?: string,
|
||||
createdAt?: number
|
||||
) {
|
||||
const id = genId();
|
||||
const ts = createdAt ?? Date.now();
|
||||
await adapter.execute(
|
||||
'INSERT INTO notifications (id, deviceIdOrigin, eventType, entityType, entityId, listId, createdAt) VALUES (?, ?, ?, ?, ?, ?, ?)',
|
||||
[id, deviceIdOrigin ?? null, eventType, entityType, entityId ?? null, listId ?? null, ts]
|
||||
);
|
||||
}
|
||||
|
||||
// Retention policy
|
||||
const DEFAULT_RETENTION_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
|
||||
const CLEAN_INTERVAL_MS = 60 * 60 * 1000; // hourly
|
||||
|
||||
export function startNotificationCleanup() {
|
||||
const retentionMs = Number(process.env.NOTIF_RETENTION_MS || DEFAULT_RETENTION_MS);
|
||||
setInterval(async () => {
|
||||
try {
|
||||
const cutoff = Date.now() - retentionMs;
|
||||
await dbAdapter.execute('DELETE FROM notifications WHERE createdAt < ?', [cutoff]);
|
||||
} catch (e) {
|
||||
console.warn('[NOTIF] Retention cleanup failed:', e);
|
||||
}
|
||||
}, CLEAN_INTERVAL_MS).unref?.();
|
||||
}
|
||||
@@ -1,185 +0,0 @@
|
||||
import { Router, Request, Response } from 'express';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import { dbAdapter } from '../db';
|
||||
import { SESSION_COOKIE_NAME, hashToken, randomToken, requireSession } from '../middleware/auth';
|
||||
|
||||
const router = Router();
|
||||
|
||||
const SESSION_TTL_MS = 24 * 60 * 60 * 1000;
|
||||
const MIN_PASSWORD_LEN = 8;
|
||||
const MAX_USERNAME_LEN = 64;
|
||||
const SECURE_COOKIE = process.env.COOKIE_SECURE === 'true';
|
||||
|
||||
function normalizeUsername(username: unknown): string | null {
|
||||
if (typeof username !== 'string') return null;
|
||||
const trimmed = username.trim();
|
||||
if (!trimmed || trimmed.length > MAX_USERNAME_LEN) return null;
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
function isValidPassword(password: unknown): password is string {
|
||||
return typeof password === 'string' && password.length >= MIN_PASSWORD_LEN;
|
||||
}
|
||||
|
||||
function setSessionCookie(res: Response, token: string, expiresAt: Date) {
|
||||
res.cookie(SESSION_COOKIE_NAME, token, {
|
||||
httpOnly: true,
|
||||
secure: SECURE_COOKIE,
|
||||
sameSite: 'lax',
|
||||
path: '/',
|
||||
expires: expiresAt,
|
||||
});
|
||||
}
|
||||
|
||||
function clearSessionCookie(res: Response) {
|
||||
res.clearCookie(SESSION_COOKIE_NAME, { path: '/' });
|
||||
}
|
||||
|
||||
async function startSession(userId: number, res: Response) {
|
||||
const token = randomToken();
|
||||
const expiresAt = new Date(Date.now() + SESSION_TTL_MS);
|
||||
await dbAdapter.execute('INSERT INTO auth_sessions (user_id, token_hash, expires_at) VALUES (?, ?, ?)', [
|
||||
userId,
|
||||
hashToken(token),
|
||||
expiresAt,
|
||||
]);
|
||||
setSessionCookie(res, token, expiresAt);
|
||||
}
|
||||
|
||||
router.get('/auth/status', async (req: Request, res: Response) => {
|
||||
const countRow = await dbAdapter.queryOne('SELECT count(*) as count FROM auth_users');
|
||||
const count = Number(countRow?.count ?? 0);
|
||||
if (count === 0) {
|
||||
return res.json({ setupRequired: true, authenticated: false });
|
||||
}
|
||||
const token = req.cookies?.[SESSION_COOKIE_NAME];
|
||||
if (!token) {
|
||||
return res.json({ setupRequired: false, authenticated: false });
|
||||
}
|
||||
const user = await dbAdapter.queryOne(
|
||||
`SELECT u.username FROM auth_sessions s JOIN auth_users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = ? AND s.expires_at > now()`,
|
||||
[hashToken(token)]
|
||||
);
|
||||
if (!user) {
|
||||
return res.json({ setupRequired: false, authenticated: false });
|
||||
}
|
||||
res.json({ setupRequired: false, authenticated: true, username: user.username });
|
||||
});
|
||||
|
||||
router.post('/auth/setup', async (req: Request, res: Response) => {
|
||||
const countRow = await dbAdapter.queryOne('SELECT count(*) as count FROM auth_users');
|
||||
if (Number(countRow?.count ?? 0) > 0) {
|
||||
return res.status(409).json({ error: 'Conflict', message: 'Setup has already been completed.' });
|
||||
}
|
||||
|
||||
const username = normalizeUsername(req.body?.username);
|
||||
if (!username) {
|
||||
return res.status(400).json({ error: 'Bad Request', message: 'Username is required.' });
|
||||
}
|
||||
if (!isValidPassword(req.body?.password)) {
|
||||
return res.status(400).json({ error: 'Bad Request', message: 'Password must be at least 8 characters.' });
|
||||
}
|
||||
|
||||
const passwordHash = await bcrypt.hash(req.body.password, 12);
|
||||
let created;
|
||||
try {
|
||||
created = await dbAdapter.queryOne(
|
||||
'INSERT INTO auth_users (username, password_hash, updated_at) VALUES (?, ?, now()) RETURNING id, username',
|
||||
[username, passwordHash]
|
||||
);
|
||||
} catch (e: any) {
|
||||
if (e?.code === '23505') {
|
||||
return res.status(409).json({ error: 'Conflict', message: 'Setup has already been completed.' });
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
|
||||
await startSession(created.id, res);
|
||||
res.json({ setupRequired: false, authenticated: true, username: created.username });
|
||||
});
|
||||
|
||||
router.post('/auth/login', async (req: Request, res: Response) => {
|
||||
const username = normalizeUsername(req.body?.username);
|
||||
const password = req.body?.password;
|
||||
const invalid = () => res.status(401).json({ error: 'Unauthorized', message: 'Invalid username or password.' });
|
||||
if (!username || typeof password !== 'string') return invalid();
|
||||
|
||||
const user = await dbAdapter.queryOne('SELECT id, username, password_hash FROM auth_users WHERE username = ?', [
|
||||
username,
|
||||
]);
|
||||
if (!user || !(await bcrypt.compare(password, user.password_hash))) {
|
||||
return invalid();
|
||||
}
|
||||
|
||||
await startSession(user.id, res);
|
||||
res.json({ setupRequired: false, authenticated: true, username: user.username });
|
||||
});
|
||||
|
||||
router.post('/auth/logout', requireSession, async (req: Request, res: Response) => {
|
||||
const token = req.cookies?.[SESSION_COOKIE_NAME];
|
||||
if (token) {
|
||||
await dbAdapter.execute('DELETE FROM auth_sessions WHERE token_hash = ?', [hashToken(token)]);
|
||||
}
|
||||
clearSessionCookie(res);
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
router.post('/auth/credentials', requireSession, async (req: Request, res: Response) => {
|
||||
const user = (req as any).user as { id: number; username: string };
|
||||
const currentUser = await dbAdapter.queryOne('SELECT id, username, password_hash FROM auth_users WHERE id = ?', [
|
||||
user.id,
|
||||
]);
|
||||
if (!currentUser || !(await bcrypt.compare(req.body?.currentPassword ?? '', currentUser.password_hash))) {
|
||||
return res.status(400).json({ error: 'Bad Request', message: 'Current password is incorrect.' });
|
||||
}
|
||||
|
||||
let username = currentUser.username;
|
||||
if (req.body?.newUsername !== undefined) {
|
||||
const normalized = normalizeUsername(req.body.newUsername);
|
||||
if (!normalized) {
|
||||
return res.status(400).json({ error: 'Bad Request', message: 'Username is required.' });
|
||||
}
|
||||
username = normalized;
|
||||
}
|
||||
|
||||
let passwordHash = currentUser.password_hash;
|
||||
if (req.body?.newPassword) {
|
||||
if (!isValidPassword(req.body.newPassword)) {
|
||||
return res.status(400).json({ error: 'Bad Request', message: 'Password must be at least 8 characters.' });
|
||||
}
|
||||
passwordHash = await bcrypt.hash(req.body.newPassword, 12);
|
||||
}
|
||||
|
||||
await dbAdapter.execute('UPDATE auth_users SET username = ?, password_hash = ?, updated_at = now() WHERE id = ?', [
|
||||
username,
|
||||
passwordHash,
|
||||
currentUser.id,
|
||||
]);
|
||||
|
||||
// Force re-login everywhere (including this browser) after a credential change,
|
||||
// matching the Bitmagnet/UnraidMonitor reference behavior.
|
||||
await dbAdapter.execute('DELETE FROM auth_sessions WHERE user_id = ?', [currentUser.id]);
|
||||
clearSessionCookie(res);
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
router.get('/auth/token/status', requireSession, async (req: Request, res: Response) => {
|
||||
const user = (req as any).user as { id: number };
|
||||
const row = await dbAdapter.queryOne('SELECT 1 FROM api_tokens WHERE user_id = ?', [user.id]);
|
||||
res.json({ hasToken: !!row });
|
||||
});
|
||||
|
||||
// Issues a brand new API token for sync clients/devices, invalidating any previous one.
|
||||
// The raw token is returned exactly once and is never retrievable again.
|
||||
router.post('/auth/token/regenerate', requireSession, async (req: Request, res: Response) => {
|
||||
const user = (req as any).user as { id: number };
|
||||
const token = randomToken();
|
||||
await dbAdapter.transaction(async (tx) => {
|
||||
await tx.execute('DELETE FROM api_tokens WHERE user_id = ?', [user.id]);
|
||||
await tx.execute('INSERT INTO api_tokens (user_id, token_hash) VALUES (?, ?)', [user.id, hashToken(token)]);
|
||||
});
|
||||
res.json({ token });
|
||||
});
|
||||
|
||||
export default router;
|
||||
@@ -1,98 +0,0 @@
|
||||
import { Router, Request, Response } from 'express';
|
||||
import { dbAdapter } from '../db';
|
||||
import { enqueueNotification } from '../notifications';
|
||||
|
||||
const router = Router();
|
||||
|
||||
// Get fields for a list
|
||||
router.get('/list/:listId', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const fields = await dbAdapter.queryAll('SELECT * FROM fields WHERE listId = ? AND isDeleted = 0 ORDER BY "order" ASC', [req.params.listId]);
|
||||
const formattedFields = (fields as any[]).map(field => ({ ...field, isDeleted: !!field.isDeleted }));
|
||||
res.json(formattedFields);
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Failed to fetch fields' });
|
||||
}
|
||||
});
|
||||
|
||||
// Create field
|
||||
router.post('/', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { id, name, fieldType, fieldOptions, alignment, listId, order, createdAt, updatedAt, isDeleted } = req.body;
|
||||
await dbAdapter.execute(
|
||||
'INSERT INTO fields (id, name, fieldType, fieldOptions, alignment, listId, "order", createdAt, updatedAt, isDeleted) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
|
||||
[id, name, fieldType, fieldOptions, alignment ?? 'start', listId, order, createdAt, updatedAt, isDeleted ? 1 : 0]
|
||||
);
|
||||
const field = await dbAdapter.queryOne('SELECT * FROM fields WHERE id = ?', [id]);
|
||||
await enqueueNotification(dbAdapter, (req as any).deviceId, 'created', 'field', id, listId, Date.now());
|
||||
res.status(201).json({ ...(field as any), isDeleted: !!(field as any).isDeleted });
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Failed to create field' });
|
||||
}
|
||||
});
|
||||
|
||||
// Update field
|
||||
router.put('/:id', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const updatedAt = Date.now();
|
||||
const { name, fieldType, fieldOptions, alignment, order } = req.body;
|
||||
const result = await dbAdapter.execute(
|
||||
'UPDATE fields SET name = ?, fieldType = ?, fieldOptions = ?, alignment = ?, "order" = ?, updatedAt = ? WHERE id = ?',
|
||||
[name, fieldType, fieldOptions, alignment ?? 'start', order, updatedAt, req.params.id]
|
||||
);
|
||||
|
||||
if (result.changes === 0) {
|
||||
return res.status(404).json({ error: 'Field not found' });
|
||||
}
|
||||
|
||||
const field = await dbAdapter.queryOne('SELECT * FROM fields WHERE id = ?', [req.params.id]);
|
||||
await enqueueNotification(dbAdapter, (req as any).deviceId, 'updated', 'field', req.params.id, (field as any)?.listId ?? (field as any)?.listid, updatedAt);
|
||||
res.json({ ...(field as any), isDeleted: !!(field as any).isDeleted });
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Failed to update field' });
|
||||
}
|
||||
});
|
||||
|
||||
// Delete field (soft delete)
|
||||
router.delete('/:id', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const updatedAt = Date.now();
|
||||
// Soft delete the field first
|
||||
const field = await dbAdapter.queryOne('SELECT * FROM fields WHERE id = ?', [req.params.id]);
|
||||
if (!field) {
|
||||
return res.status(404).json({ error: 'Field not found' });
|
||||
}
|
||||
await dbAdapter.execute(
|
||||
'UPDATE fields SET isDeleted = 1, updatedAt = ? WHERE id = ?',
|
||||
[updatedAt, req.params.id]
|
||||
);
|
||||
|
||||
// Remove any item_values referencing this field (already handled in sync route, but ensure consistency for direct REST usage)
|
||||
await dbAdapter.execute('DELETE FROM item_values WHERE fieldId = ?', [req.params.id]);
|
||||
|
||||
// Determine if this was the last remaining (non-deleted) field in its list.
|
||||
const listId = field.listId;
|
||||
const remaining = await dbAdapter.queryOne(
|
||||
'SELECT COUNT(*) as cnt FROM fields WHERE listId = ? AND isDeleted = 0',
|
||||
[listId]
|
||||
);
|
||||
const remainingCount = remaining ? (remaining.cnt ?? remaining.CNT ?? remaining.count ?? 0) : 0;
|
||||
|
||||
if (remainingCount === 0) {
|
||||
// Last field deleted -> soft delete all items and purge their values for this list
|
||||
try {
|
||||
await dbAdapter.execute('UPDATE items SET isDeleted = 1, updatedAt = ? WHERE listId = ?', [updatedAt, listId]);
|
||||
await dbAdapter.execute('DELETE FROM item_values WHERE itemId IN (SELECT id FROM items WHERE listId = ?)', [listId]);
|
||||
} catch (cascadeErr) {
|
||||
console.warn('[FIELD DELETE] Cascade item cleanup failed:', cascadeErr);
|
||||
}
|
||||
}
|
||||
|
||||
await enqueueNotification(dbAdapter, (req as any).deviceId, 'deleted', 'field', req.params.id, (field as any).listId ?? (field as any).listid, updatedAt);
|
||||
res.json({ message: 'Field deleted successfully', cascadeItemsDeleted: remainingCount === 0 });
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Failed to delete field' });
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
@@ -1,115 +0,0 @@
|
||||
import { Router, Request, Response } from 'express';
|
||||
import { dbAdapter } from '../db';
|
||||
import { enqueueNotification } from '../notifications';
|
||||
|
||||
const router = Router();
|
||||
|
||||
// Get items for a list
|
||||
router.get('/list/:listId', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const items = await dbAdapter.queryAll('SELECT * FROM items WHERE listId = ? AND isDeleted = 0 ORDER BY updatedAt DESC', [req.params.listId]);
|
||||
const formattedItems = (items as any[]).map(item => ({ ...item, isDeleted: !!item.isDeleted }));
|
||||
res.json(formattedItems);
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Failed to fetch items' });
|
||||
}
|
||||
});
|
||||
|
||||
// Get item values
|
||||
router.get('/:itemId/values', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const values = await dbAdapter.queryAll('SELECT * FROM item_values WHERE itemId = ?', [req.params.itemId]);
|
||||
res.json(values);
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Failed to fetch item values' });
|
||||
}
|
||||
});
|
||||
|
||||
// Create item
|
||||
router.post('/', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { id, listId, createdAt, updatedAt, isDeleted } = req.body;
|
||||
await dbAdapter.execute(
|
||||
'INSERT INTO items (id, listId, createdAt, updatedAt, isDeleted) VALUES (?, ?, ?, ?, ?)',
|
||||
[id, listId, createdAt, updatedAt, isDeleted ? 1 : 0]
|
||||
);
|
||||
const item = await dbAdapter.queryOne('SELECT * FROM items WHERE id = ?', [id]);
|
||||
await enqueueNotification(dbAdapter, (req as any).deviceId, 'created', 'item', id, listId, Date.now());
|
||||
res.status(201).json({ ...(item as any), isDeleted: !!(item as any).isDeleted });
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Failed to create item' });
|
||||
}
|
||||
});
|
||||
|
||||
// Create/update item value
|
||||
router.post('/values', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { id, itemId, fieldId, value, updatedAt } = req.body;
|
||||
await dbAdapter.execute(
|
||||
'INSERT INTO item_values (id, itemId, fieldId, value, updatedAt) VALUES (?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET value = ?, updatedAt = ?',
|
||||
[id, itemId, fieldId, value, updatedAt, value, updatedAt]
|
||||
);
|
||||
const itemValue = await dbAdapter.queryOne('SELECT * FROM item_values WHERE id = ?', [id]);
|
||||
// Notify list content updated (coarse event) using field's listId
|
||||
try {
|
||||
const field = await dbAdapter.queryOne('SELECT listId FROM fields WHERE id = ?', [fieldId]);
|
||||
const listId = field ? ((field as any).listId ?? (field as any).listid) : undefined;
|
||||
if (listId) {
|
||||
await enqueueNotification(dbAdapter, (req as any).deviceId, 'listContentUpdated', 'value', id, listId, Date.now());
|
||||
}
|
||||
} catch (notificationError) {
|
||||
void notificationError;
|
||||
}
|
||||
res.json(itemValue);
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Failed to save item value' });
|
||||
}
|
||||
});
|
||||
|
||||
// Update item
|
||||
router.put('/:id', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const updatedAt = Date.now();
|
||||
const result = await dbAdapter.execute(
|
||||
'UPDATE items SET updatedAt = ? WHERE id = ?',
|
||||
[updatedAt, req.params.id]
|
||||
);
|
||||
|
||||
if (result.changes === 0) {
|
||||
return res.status(404).json({ error: 'Item not found' });
|
||||
}
|
||||
|
||||
const item = await dbAdapter.queryOne('SELECT * FROM items WHERE id = ?', [req.params.id]);
|
||||
await enqueueNotification(dbAdapter, (req as any).deviceId, 'updated', 'item', req.params.id, (item as any)?.listId ?? (item as any)?.listid, updatedAt);
|
||||
res.json({ ...(item as any), isDeleted: !!(item as any).isDeleted });
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Failed to update item' });
|
||||
}
|
||||
});
|
||||
|
||||
// Delete item (soft delete)
|
||||
router.delete('/:id', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const updatedAt = Date.now();
|
||||
const result = await dbAdapter.execute(
|
||||
'UPDATE items SET isDeleted = 1, updatedAt = ? WHERE id = ?',
|
||||
[updatedAt, req.params.id]
|
||||
);
|
||||
|
||||
if (result.changes === 0) {
|
||||
return res.status(404).json({ error: 'Item not found' });
|
||||
}
|
||||
try {
|
||||
const item = await dbAdapter.queryOne('SELECT * FROM items WHERE id = ?', [req.params.id]);
|
||||
const listId = item ? ((item as any).listId ?? (item as any).listid) : undefined;
|
||||
await enqueueNotification(dbAdapter, (req as any).deviceId, 'deleted', 'item', req.params.id, listId, updatedAt);
|
||||
} catch (notificationError) {
|
||||
void notificationError;
|
||||
}
|
||||
res.json({ message: 'Item deleted successfully' });
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Failed to delete item' });
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
@@ -1,88 +0,0 @@
|
||||
import { Router, Request, Response } from 'express';
|
||||
import { dbAdapter } from '../db';
|
||||
import { enqueueNotification } from '../notifications';
|
||||
|
||||
const router = Router();
|
||||
|
||||
// Get all lists
|
||||
router.get('/', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const lists = await dbAdapter.queryAll('SELECT * FROM lists WHERE isDeleted = 0 ORDER BY updatedAt DESC');
|
||||
// Convert isDeleted from INTEGER to BOOLEAN
|
||||
const formattedLists = (lists as any[]).map(list => ({ ...list, isDeleted: !!list.isDeleted }));
|
||||
res.json(formattedLists);
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Failed to fetch lists' });
|
||||
}
|
||||
});
|
||||
|
||||
// Get single list
|
||||
router.get('/:id', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const list = await dbAdapter.queryOne('SELECT * FROM lists WHERE id = ? AND isDeleted = 0', [req.params.id]);
|
||||
if (!list) {
|
||||
return res.status(404).json({ error: 'List not found' });
|
||||
}
|
||||
res.json({ ...(list as any), isDeleted: !!(list as any).isDeleted });
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Failed to fetch list' });
|
||||
}
|
||||
});
|
||||
|
||||
// Create list
|
||||
router.post('/', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { id, name, createdAt, updatedAt, isDeleted } = req.body;
|
||||
await dbAdapter.execute(
|
||||
'INSERT INTO lists (id, name, createdAt, updatedAt, isDeleted) VALUES (?, ?, ?, ?, ?)',
|
||||
[id, name, createdAt, updatedAt, isDeleted ? 1 : 0]
|
||||
);
|
||||
const list = await dbAdapter.queryOne('SELECT * FROM lists WHERE id = ?', [id]);
|
||||
// Notify others
|
||||
await enqueueNotification(dbAdapter, (req as any).deviceId, 'created', 'list', id, id, Date.now());
|
||||
res.status(201).json({ ...(list as any), isDeleted: !!(list as any).isDeleted });
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Failed to create list' });
|
||||
}
|
||||
});
|
||||
|
||||
// Update list
|
||||
router.put('/:id', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const updatedAt = Date.now();
|
||||
const result = await dbAdapter.execute(
|
||||
'UPDATE lists SET name = ?, updatedAt = ? WHERE id = ?',
|
||||
[req.body.name, updatedAt, req.params.id]
|
||||
);
|
||||
|
||||
if (result.changes === 0) {
|
||||
return res.status(404).json({ error: 'List not found' });
|
||||
}
|
||||
const list = await dbAdapter.queryOne('SELECT * FROM lists WHERE id = ?', [req.params.id]);
|
||||
await enqueueNotification(dbAdapter, (req as any).deviceId, 'updated', 'list', req.params.id, req.params.id, updatedAt);
|
||||
res.json({ ...(list as any), isDeleted: !!(list as any).isDeleted });
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Failed to update list' });
|
||||
}
|
||||
});
|
||||
|
||||
// Delete list (soft delete)
|
||||
router.delete('/:id', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const updatedAt = Date.now();
|
||||
const result = await dbAdapter.execute(
|
||||
'UPDATE lists SET isDeleted = 1, updatedAt = ? WHERE id = ?',
|
||||
[updatedAt, req.params.id]
|
||||
);
|
||||
|
||||
if (result.changes === 0) {
|
||||
return res.status(404).json({ error: 'List not found' });
|
||||
}
|
||||
await enqueueNotification(dbAdapter, (req as any).deviceId, 'deleted', 'list', req.params.id, req.params.id, updatedAt);
|
||||
res.json({ message: 'List deleted successfully' });
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Failed to delete list' });
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
@@ -1,44 +0,0 @@
|
||||
import { Router, Request, Response } from 'express';
|
||||
import { dbAdapter } from '../db';
|
||||
|
||||
const router = Router();
|
||||
|
||||
// GET /api/notifications/poll?since=timestampMs
|
||||
router.get('/notifications/poll', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const sinceRaw = (req.query.since as string) || '0';
|
||||
const since = Number(sinceRaw);
|
||||
const deviceId = (req as any).deviceId as string | undefined;
|
||||
|
||||
const params: any[] = [isFinite(since) && since > 0 ? since : 0];
|
||||
let sql = 'SELECT * FROM notifications WHERE createdAt > ?';
|
||||
|
||||
if (deviceId && deviceId.length > 0) {
|
||||
sql += ' AND (deviceIdOrigin IS NULL OR deviceIdOrigin <> ?)';
|
||||
params.push(deviceId);
|
||||
}
|
||||
|
||||
sql += ' ORDER BY createdAt ASC LIMIT 500';
|
||||
|
||||
const rows = await dbAdapter.queryAll(sql, params);
|
||||
|
||||
// Normalize keys in case of differing DB casing
|
||||
const pick = (obj: any, a: string, b: string) => obj[a] ?? obj[b];
|
||||
const events = (rows as any[]).map(r => ({
|
||||
id: r.id,
|
||||
deviceIdOrigin: pick(r, 'deviceIdOrigin', 'deviceidorigin') || undefined,
|
||||
eventType: pick(r, 'eventType', 'eventtype'),
|
||||
entityType: pick(r, 'entityType', 'entitytype'),
|
||||
entityId: pick(r, 'entityId', 'entityid') || undefined,
|
||||
listId: pick(r, 'listId', 'listid') || undefined,
|
||||
createdAt: pick(r, 'createdAt', 'createdat')
|
||||
}));
|
||||
|
||||
res.json({ notifications: events, serverTimestamp: Date.now() });
|
||||
} catch (e) {
|
||||
console.error('[NOTIF] Poll failed:', e);
|
||||
res.status(500).json({ error: 'Failed to poll notifications' });
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
@@ -1,456 +0,0 @@
|
||||
import { Router, Request, Response } from 'express';
|
||||
import { dbAdapter } from '../db';
|
||||
import { enqueueNotification } from '../notifications';
|
||||
|
||||
const router = Router();
|
||||
|
||||
interface SyncRequest {
|
||||
lastSyncTimestamp: number;
|
||||
lists: any[];
|
||||
fields: any[];
|
||||
items: any[];
|
||||
itemValues: any[];
|
||||
}
|
||||
|
||||
const SYNC_MAX_FUTURE_SKEW_MS = Math.max(0, Number(process.env.SYNC_MAX_FUTURE_SKEW_MS || 0));
|
||||
|
||||
function normalizeTimestamp(raw: any, fallback: number, nowMs: number) {
|
||||
const numeric = Number(raw);
|
||||
if (!Number.isFinite(numeric) || numeric <= 0) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
let ts = Math.trunc(numeric);
|
||||
if (ts < 1e12) {
|
||||
ts *= 1000;
|
||||
}
|
||||
|
||||
const maxAllowed = nowMs + SYNC_MAX_FUTURE_SKEW_MS;
|
||||
if (ts > maxAllowed) {
|
||||
return maxAllowed;
|
||||
}
|
||||
|
||||
return ts;
|
||||
}
|
||||
|
||||
function normalizeEntityTimestamps(createdAtRaw: any, updatedAtRaw: any, nowMs: number) {
|
||||
const createdAt = normalizeTimestamp(createdAtRaw, nowMs, nowMs);
|
||||
const updatedAt = normalizeTimestamp(updatedAtRaw, createdAt, nowMs);
|
||||
return {
|
||||
createdAt,
|
||||
updatedAt: Math.max(createdAt, updatedAt)
|
||||
};
|
||||
}
|
||||
|
||||
// Stats tracking
|
||||
let syncStats = {
|
||||
totalSyncs: 0,
|
||||
listsReceived: 0,
|
||||
fieldsReceived: 0,
|
||||
itemsReceived: 0,
|
||||
valuesReceived: 0,
|
||||
listsSent: 0,
|
||||
fieldsSent: 0,
|
||||
itemsSent: 0,
|
||||
valuesSent: 0,
|
||||
lastReset: Date.now()
|
||||
};
|
||||
|
||||
// Print stats every 60 seconds (reduced spam)
|
||||
setInterval(() => {
|
||||
if (syncStats.totalSyncs > 0) {
|
||||
const elapsed = Math.round((Date.now() - syncStats.lastReset) / 1000);
|
||||
console.log(`\n[STATS] Sync Summary (last ${elapsed}s):`);
|
||||
console.log(` ${syncStats.totalSyncs} sync requests processed`);
|
||||
|
||||
if (syncStats.listsReceived > 0 || syncStats.fieldsReceived > 0 || syncStats.itemsReceived > 0 || syncStats.valuesReceived > 0) {
|
||||
console.log(` [IN] Received: ${syncStats.listsReceived} lists, ${syncStats.fieldsReceived} fields, ${syncStats.itemsReceived} items, ${syncStats.valuesReceived} values`);
|
||||
}
|
||||
|
||||
if (syncStats.listsSent > 0 || syncStats.fieldsSent > 0 || syncStats.itemsSent > 0 || syncStats.valuesSent > 0) {
|
||||
console.log(` [OUT] Sent: ${syncStats.listsSent} lists, ${syncStats.fieldsSent} fields, ${syncStats.itemsSent} items, ${syncStats.valuesSent} values`);
|
||||
}
|
||||
|
||||
// Reset stats
|
||||
syncStats = {
|
||||
totalSyncs: 0,
|
||||
listsReceived: 0,
|
||||
fieldsReceived: 0,
|
||||
itemsReceived: 0,
|
||||
valuesReceived: 0,
|
||||
listsSent: 0,
|
||||
fieldsSent: 0,
|
||||
itemsSent: 0,
|
||||
valuesSent: 0,
|
||||
lastReset: Date.now()
|
||||
};
|
||||
}
|
||||
}, 60000).unref?.(); // Changed from 30s to 60s
|
||||
|
||||
// Helper function to get prepared statements (lazy initialization)
|
||||
// We'll perform upserts with positional params for cross-DB portability
|
||||
const UPSERT_LIST = 'INSERT INTO lists (id, name, createdAt, updatedAt, isDeleted) VALUES (?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET name = EXCLUDED.name, updatedAt = EXCLUDED.updatedAt, isDeleted = EXCLUDED.isDeleted';
|
||||
const UPSERT_FIELD = 'INSERT INTO fields (id, name, fieldType, fieldOptions, alignment, listId, "order", createdAt, updatedAt, isDeleted) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET name = EXCLUDED.name, fieldType = EXCLUDED.fieldType, fieldOptions = EXCLUDED.fieldOptions, alignment = EXCLUDED.alignment, "order" = EXCLUDED."order", updatedAt = EXCLUDED.updatedAt, isDeleted = EXCLUDED.isDeleted';
|
||||
const UPSERT_ITEM = 'INSERT INTO items (id, listId, createdAt, updatedAt, isDeleted) VALUES (?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET updatedAt = EXCLUDED.updatedAt, isDeleted = EXCLUDED.isDeleted';
|
||||
const UPSERT_ITEM_VALUE = 'INSERT INTO item_values (id, itemId, fieldId, value, updatedAt) VALUES (?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET value = EXCLUDED.value, updatedAt = EXCLUDED.updatedAt';
|
||||
|
||||
router.post('/sync', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const {
|
||||
lastSyncTimestamp,
|
||||
lists = [],
|
||||
fields = [],
|
||||
items = [],
|
||||
itemValues = []
|
||||
}: Partial<SyncRequest> = req.body || {};
|
||||
const deviceId = (req as any).deviceId as string | undefined;
|
||||
const nowMs = Date.now();
|
||||
const safeLastSyncTimestamp = normalizeTimestamp(lastSyncTimestamp, 0, nowMs);
|
||||
|
||||
// Track stats
|
||||
syncStats.totalSyncs++;
|
||||
const incomingLists = lists.length;
|
||||
const incomingFields = fields.length;
|
||||
const incomingItems = items.length;
|
||||
const incomingValues = itemValues.length;
|
||||
|
||||
syncStats.listsReceived += incomingLists;
|
||||
syncStats.fieldsReceived += incomingFields;
|
||||
syncStats.itemsReceived += incomingItems;
|
||||
syncStats.valuesReceived += incomingValues;
|
||||
|
||||
// Only log significant sync events (not empty syncs)
|
||||
const hasIncomingData = incomingLists > 0 || incomingFields > 0 || incomingItems > 0 || incomingValues > 0;
|
||||
const isInitialSync = safeLastSyncTimestamp === 0;
|
||||
|
||||
if (hasIncomingData) {
|
||||
const timestamp = new Date().toLocaleTimeString();
|
||||
console.log(`\n[SYNC] [${timestamp}] Receiving data from client`);
|
||||
|
||||
if (incomingLists > 0) {
|
||||
console.log(` [LISTS] ${incomingLists} list(s)`);
|
||||
lists.forEach(list => {
|
||||
const action = list.isDeleted ? 'Deleted' : (safeLastSyncTimestamp === 0 ? 'Created' : 'Updated');
|
||||
console.log(` ${action}: "${list.name}"`);
|
||||
});
|
||||
}
|
||||
|
||||
if (incomingFields > 0) {
|
||||
console.log(` [FIELDS] ${incomingFields} field(s)`);
|
||||
}
|
||||
|
||||
if (incomingItems > 0) {
|
||||
console.log(` [ITEMS] ${incomingItems} item(s)`);
|
||||
}
|
||||
|
||||
if (incomingValues > 0) {
|
||||
console.log(` [VALUES] ${incomingValues} value(s)`);
|
||||
}
|
||||
} else if (isInitialSync) {
|
||||
const timestamp = new Date().toLocaleTimeString();
|
||||
console.log(`\n[SYNC] [${timestamp}] Initial sync from new client`);
|
||||
}
|
||||
|
||||
// Save incoming data from client using a transaction
|
||||
await dbAdapter.transaction(async (tx) => {
|
||||
if (lists && lists.length > 0) {
|
||||
for (const list of lists) {
|
||||
const listTs = normalizeEntityTimestamps(list.createdAt, list.updatedAt, nowMs);
|
||||
await tx.execute(UPSERT_LIST, [
|
||||
list.id,
|
||||
list.name,
|
||||
listTs.createdAt,
|
||||
listTs.updatedAt,
|
||||
list.isDeleted ? 1 : 0
|
||||
]);
|
||||
// enqueue list-level notifications
|
||||
try {
|
||||
const ev = list.isDeleted ? 'deleted' : (safeLastSyncTimestamp === 0 ? 'created' : 'updated');
|
||||
await enqueueNotification(tx, deviceId, ev, 'list', list.id, list.id, listTs.updatedAt);
|
||||
} catch (notificationError) {
|
||||
void notificationError;
|
||||
}
|
||||
// If a list was deleted, cascade the deletion to child records on server
|
||||
// - mark fields and items as deleted (tombstones) so other clients learn about them
|
||||
// - remove item_values belonging to items under this list (no tombstone support for values)
|
||||
if (list.isDeleted) {
|
||||
try {
|
||||
await tx.execute('UPDATE fields SET isDeleted = 1, updatedAt = ? WHERE listId = ?', [listTs.updatedAt, list.id]);
|
||||
await tx.execute('UPDATE items SET isDeleted = 1, updatedAt = ? WHERE listId = ?', [listTs.updatedAt, list.id]);
|
||||
await tx.execute('DELETE FROM item_values WHERE itemId IN (SELECT id FROM items WHERE listId = ?)', [list.id]);
|
||||
} catch (err) {
|
||||
console.warn('[SYNC] Cascade delete for list failed:', String(err));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (fields && fields.length > 0) {
|
||||
for (const field of fields) {
|
||||
const fieldTs = normalizeEntityTimestamps(field.createdAt, field.updatedAt, nowMs);
|
||||
await tx.execute(UPSERT_FIELD, [
|
||||
field.id,
|
||||
field.name,
|
||||
field.fieldType,
|
||||
field.fieldOptions,
|
||||
(field.alignment ?? 'start'),
|
||||
field.listId,
|
||||
field.order,
|
||||
fieldTs.createdAt,
|
||||
fieldTs.updatedAt,
|
||||
field.isDeleted ? 1 : 0
|
||||
]);
|
||||
try {
|
||||
const ev = field.isDeleted ? 'deleted' : (safeLastSyncTimestamp === 0 ? 'created' : 'updated');
|
||||
await enqueueNotification(tx, deviceId, ev, 'field', field.id, field.listId, fieldTs.updatedAt);
|
||||
} catch (notificationError) {
|
||||
void notificationError;
|
||||
}
|
||||
if (field.isDeleted) {
|
||||
// Remove item_values for this field
|
||||
try {
|
||||
await tx.execute('DELETE FROM item_values WHERE fieldId = ?', [field.id]);
|
||||
} catch (err) {
|
||||
console.warn('[SYNC] Cascade delete for field failed:', String(err));
|
||||
}
|
||||
// Check if this was the last remaining non-deleted field for the list
|
||||
try {
|
||||
const remaining = await tx.queryOne('SELECT COUNT(*) as cnt FROM fields WHERE listId = ? AND isDeleted = 0', [field.listId]);
|
||||
const remainingCount = remaining ? (remaining.cnt ?? remaining.CNT ?? remaining.count ?? 0) : 0;
|
||||
if (remainingCount === 0) {
|
||||
// Soft delete items in this list and purge their values
|
||||
await tx.execute('UPDATE items SET isDeleted = 1, updatedAt = ? WHERE listId = ?', [fieldTs.updatedAt, field.listId]);
|
||||
await tx.execute('DELETE FROM item_values WHERE itemId IN (SELECT id FROM items WHERE listId = ?)', [field.listId]);
|
||||
console.log('[SYNC] Last field deleted; cascaded item+value cleanup for list', field.listId);
|
||||
}
|
||||
} catch (cascadeErr) {
|
||||
console.warn('[SYNC] Cascade last-field cleanup failed:', cascadeErr);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (items && items.length > 0) {
|
||||
for (const item of items) {
|
||||
const itemTs = normalizeEntityTimestamps(item.createdAt, item.updatedAt, nowMs);
|
||||
await tx.execute(UPSERT_ITEM, [
|
||||
item.id,
|
||||
item.listId,
|
||||
itemTs.createdAt,
|
||||
itemTs.updatedAt,
|
||||
item.isDeleted ? 1 : 0
|
||||
]);
|
||||
try {
|
||||
const ev = item.isDeleted ? 'deleted' : (safeLastSyncTimestamp === 0 ? 'created' : 'updated');
|
||||
await enqueueNotification(tx, deviceId, ev, 'item', item.id, item.listId, itemTs.updatedAt);
|
||||
} catch (notificationError) {
|
||||
void notificationError;
|
||||
}
|
||||
// If an item was deleted, remove its values (no tombstone support for values)
|
||||
if (item.isDeleted) {
|
||||
try {
|
||||
await tx.execute('DELETE FROM item_values WHERE itemId = ?', [item.id]);
|
||||
} catch (err) {
|
||||
console.warn('[SYNC] Cascade delete for item failed:', String(err));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Before inserting item values, verify parent item and field existence to avoid FK violations (PG strictness)
|
||||
const orphanValues: any[] = [];
|
||||
if (itemValues && itemValues.length > 0) {
|
||||
// Build distinct parent id lists
|
||||
const distinctItemIds = [...new Set(itemValues.map(v => v.itemId).filter(Boolean))];
|
||||
const distinctFieldIds = [...new Set(itemValues.map(v => v.fieldId).filter(Boolean))];
|
||||
|
||||
// Helper to build IN clause placeholders (?,?,?) matching adapter's ? substitution
|
||||
const makeIn = (arr: string[]) => arr.map(() => '?').join(', ');
|
||||
|
||||
let existingItemIds = new Set<string>();
|
||||
let existingFieldIds = new Set<string>();
|
||||
const fieldToList: Record<string, string> = {};
|
||||
try {
|
||||
if (distinctItemIds.length > 0) {
|
||||
const rows = await tx.queryAll(`SELECT id FROM items WHERE id IN (${makeIn(distinctItemIds)})`, distinctItemIds);
|
||||
existingItemIds = new Set(rows.map((r: any) => r.id));
|
||||
}
|
||||
if (distinctFieldIds.length > 0) {
|
||||
const rows = await tx.queryAll(`SELECT id, listId FROM fields WHERE id IN (${makeIn(distinctFieldIds)})`, distinctFieldIds);
|
||||
existingFieldIds = new Set(rows.map((r: any) => r.id));
|
||||
rows.forEach((r: any) => { fieldToList[r.id] = r.listid ?? r.listId; });
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('[SYNC] Failed preloading parent ids for values:', e);
|
||||
}
|
||||
|
||||
for (const value of itemValues) {
|
||||
const valueUpdatedAt = normalizeTimestamp(value.updatedAt, nowMs, nowMs);
|
||||
const hasItem = existingItemIds.has(value.itemId);
|
||||
const hasField = existingFieldIds.has(value.fieldId);
|
||||
if (!hasField) {
|
||||
// Missing field -> skip value
|
||||
orphanValues.push({ id: value.id, itemId: value.itemId, fieldId: value.fieldId, reason: 'missingField' });
|
||||
continue;
|
||||
}
|
||||
// If item missing but field exists, synthesize a stub item to preserve referential integrity
|
||||
if (!hasItem) {
|
||||
const inferredListId = fieldToList[value.fieldId];
|
||||
if (!inferredListId) {
|
||||
orphanValues.push({ id: value.id, itemId: value.itemId, fieldId: value.fieldId, reason: 'missingItemNoList' });
|
||||
continue;
|
||||
}
|
||||
const ts = valueUpdatedAt;
|
||||
try {
|
||||
await tx.execute(UPSERT_ITEM, [
|
||||
value.itemId,
|
||||
inferredListId,
|
||||
ts,
|
||||
ts,
|
||||
0
|
||||
]);
|
||||
existingItemIds.add(value.itemId);
|
||||
console.warn('[SYNC] Created stub item for orphan value:', value.itemId, 'in list', inferredListId);
|
||||
} catch (e) {
|
||||
orphanValues.push({ id: value.id, itemId: value.itemId, fieldId: value.fieldId, reason: 'failedCreateStubItem' });
|
||||
continue;
|
||||
}
|
||||
}
|
||||
try {
|
||||
await tx.execute(UPSERT_ITEM_VALUE, [
|
||||
value.id,
|
||||
value.itemId,
|
||||
value.fieldId,
|
||||
value.value,
|
||||
valueUpdatedAt
|
||||
]);
|
||||
// Coarse list content update notification
|
||||
try {
|
||||
const lId = fieldToList[value.fieldId];
|
||||
if (lId) {
|
||||
await enqueueNotification(tx, deviceId, 'listContentUpdated', 'value', value.id, lId, valueUpdatedAt);
|
||||
}
|
||||
} catch (notificationError) {
|
||||
void notificationError;
|
||||
}
|
||||
} catch (err: any) {
|
||||
// Catch FK violation just in case race or deletion happened inside same sync
|
||||
if (err && err.code === '23503') {
|
||||
orphanValues.push({ id: value.id, itemId: value.itemId, fieldId: value.fieldId, reason: 'fkViolation' });
|
||||
console.warn('[SYNC] Skipped value due to FK violation:', value.id, '->', err.detail || err.message);
|
||||
continue;
|
||||
}
|
||||
throw err; // rethrow other errors
|
||||
}
|
||||
}
|
||||
|
||||
if (orphanValues.length > 0) {
|
||||
console.warn(`[SYNC] Skipped ${orphanValues.length} orphan item_value record(s); will inform client.`);
|
||||
}
|
||||
// Attach orphanValues to request context (not ideal, but simplest without altering adapter signature)
|
||||
// We'll include them in response below.
|
||||
(req as any)._orphanValues = orphanValues;
|
||||
}
|
||||
});
|
||||
|
||||
// IMPORTANT: Get updates from server AFTER saving incoming data
|
||||
// This ensures clients receive back any data they just sent (for confirmation)
|
||||
// If lastSyncTimestamp is 0, get all data (initial sync)
|
||||
// IMPORTANT: Include deleted items so clients can sync deletions
|
||||
let serverLists, serverFields, serverItems, serverItemValues;
|
||||
|
||||
if (safeLastSyncTimestamp === 0) {
|
||||
// Include deleted rows on initial sync to propagate tombstones
|
||||
serverLists = await dbAdapter.queryAll('SELECT * FROM lists');
|
||||
serverFields = await dbAdapter.queryAll('SELECT * FROM fields');
|
||||
serverItems = await dbAdapter.queryAll('SELECT * FROM items');
|
||||
serverItemValues = await dbAdapter.queryAll('SELECT * FROM item_values');
|
||||
} else {
|
||||
serverLists = await dbAdapter.queryAll('SELECT * FROM lists WHERE updatedAt >= ?', [safeLastSyncTimestamp]);
|
||||
serverFields = await dbAdapter.queryAll('SELECT * FROM fields WHERE updatedAt >= ?', [safeLastSyncTimestamp]);
|
||||
serverItems = await dbAdapter.queryAll('SELECT * FROM items WHERE updatedAt >= ?', [safeLastSyncTimestamp]);
|
||||
serverItemValues = await dbAdapter.queryAll('SELECT * FROM item_values WHERE updatedAt >= ?', [safeLastSyncTimestamp]);
|
||||
}
|
||||
|
||||
// Normalize output for clients (camelCase keys, ms timestamps, boolean isDeleted)
|
||||
const toMillis = (v: any): number | null => {
|
||||
if (v === null || v === undefined) return null;
|
||||
if (typeof v === 'number') return v < 1e12 ? Math.trunc(v * 1000) : Math.trunc(v);
|
||||
if (typeof v === 'string') {
|
||||
if (/^\d+$/.test(v)) {
|
||||
const n = Number(v);
|
||||
return n < 1e12 ? Math.trunc(n * 1000) : Math.trunc(n);
|
||||
}
|
||||
const t = Date.parse(v);
|
||||
return Number.isNaN(t) ? null : Math.trunc(t);
|
||||
}
|
||||
return null;
|
||||
};
|
||||
const pick = (obj: any, a: string, b: string) => obj[a] ?? obj[b];
|
||||
|
||||
const normLists = (serverLists as any[]).map(l => ({
|
||||
id: l.id,
|
||||
name: l.name,
|
||||
createdAt: toMillis(pick(l, 'createdAt', 'createdat')),
|
||||
updatedAt: toMillis(pick(l, 'updatedAt', 'updatedat')),
|
||||
isDeleted: !!pick(l, 'isDeleted', 'isdeleted'),
|
||||
// orderIndex is local-only, do not include
|
||||
}));
|
||||
const normFields = (serverFields as any[]).map(f => ({
|
||||
id: f.id,
|
||||
listId: pick(f, 'listId', 'listid'),
|
||||
name: f.name,
|
||||
fieldType: f.fieldType ?? f.fieldtype,
|
||||
fieldOptions: f.fieldOptions ?? f.fieldoptions ?? '',
|
||||
alignment: f.alignment ?? 'start',
|
||||
order: f.order,
|
||||
createdAt: toMillis(pick(f, 'createdAt', 'createdat')),
|
||||
updatedAt: toMillis(pick(f, 'updatedAt', 'updatedat')),
|
||||
isDeleted: !!pick(f, 'isDeleted', 'isdeleted'),
|
||||
}));
|
||||
const normItems = (serverItems as any[]).map(i => ({
|
||||
id: i.id,
|
||||
listId: pick(i, 'listId', 'listid'),
|
||||
createdAt: toMillis(pick(i, 'createdAt', 'createdat')),
|
||||
updatedAt: toMillis(pick(i, 'updatedAt', 'updatedat')),
|
||||
isDeleted: !!pick(i, 'isDeleted', 'isdeleted'),
|
||||
}));
|
||||
const normValues = (serverItemValues as any[]).map(v => ({
|
||||
id: v.id,
|
||||
itemId: pick(v, 'itemId', 'itemid'),
|
||||
fieldId: pick(v, 'fieldId', 'fieldid'),
|
||||
value: v.value,
|
||||
updatedAt: toMillis(pick(v, 'updatedAt', 'updatedat')),
|
||||
}));
|
||||
|
||||
const serverTimestamp = Date.now();
|
||||
|
||||
// Track outgoing stats
|
||||
syncStats.listsSent += (serverLists as any[]).length;
|
||||
syncStats.fieldsSent += (serverFields as any[]).length;
|
||||
syncStats.itemsSent += (serverItems as any[]).length;
|
||||
syncStats.valuesSent += (serverItemValues as any[]).length;
|
||||
|
||||
// Only log when sending significant data back
|
||||
const hasOutgoingData = (serverLists as any[]).length > 0 || (serverFields as any[]).length > 0 || (serverItems as any[]).length > 0 || (serverItemValues as any[]).length > 0;
|
||||
if (hasOutgoingData && !isInitialSync && hasIncomingData) {
|
||||
console.log(` [OUT] Sending back: ${(serverLists as any[]).length} lists, ${(serverFields as any[]).length} fields, ${(serverItems as any[]).length} items, ${(serverItemValues as any[]).length} values`);
|
||||
} else if (isInitialSync && hasOutgoingData) {
|
||||
console.log(` [OUT] Sending initial data: ${(serverLists as any[]).length} lists, ${(serverFields as any[]).length} fields, ${(serverItems as any[]).length} items, ${(serverItemValues as any[]).length} values`);
|
||||
}
|
||||
|
||||
res.json({
|
||||
lists: normLists,
|
||||
fields: normFields,
|
||||
items: normItems,
|
||||
itemValues: normValues,
|
||||
orphanItemValues: (req as any)._orphanValues || [],
|
||||
serverTimestamp
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('[ERROR] Sync error:', error);
|
||||
res.status(500).json({ error: 'Sync failed' });
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
@@ -1,169 +0,0 @@
|
||||
import express, { Router, Request, Response } from 'express';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { dbAdapter, dbEngine } from '../db';
|
||||
import { requireSession } from '../middleware/auth';
|
||||
|
||||
const router = Router();
|
||||
|
||||
// Serve the built SvelteKit SPA. The webui is built separately and its output copied to
|
||||
// ../../web (a sibling of dist/) before the server starts - see Dockerfile / README.
|
||||
const webDir = path.join(__dirname, '../../web');
|
||||
router.use(express.static(webDir));
|
||||
|
||||
interface PackageJson {
|
||||
version?: string;
|
||||
dependencies?: Record<string, string>;
|
||||
devDependencies?: Record<string, string>;
|
||||
}
|
||||
|
||||
let packageJson: PackageJson = {};
|
||||
try {
|
||||
packageJson = JSON.parse(fs.readFileSync(path.join(__dirname, '../../package.json'), 'utf-8'));
|
||||
} catch (error) {
|
||||
console.error('Error reading package.json:', error);
|
||||
}
|
||||
|
||||
function depVersion(name: string): string {
|
||||
const deps = { ...packageJson.devDependencies, ...packageJson.dependencies };
|
||||
return deps[name] ? deps[name].replace(/^[^\d]*/, '') : 'unknown';
|
||||
}
|
||||
|
||||
// API endpoint to get server tech stack info (requires the admin session)
|
||||
router.get('/web/info', requireSession, (req: Request, res: Response) => {
|
||||
res.json({
|
||||
appVersion: packageJson.version ?? 'unknown',
|
||||
stack: [
|
||||
{ label: 'Runtime', value: `Node.js ${process.version}` },
|
||||
{ label: 'Language', value: `TypeScript ${depVersion('typescript')}` },
|
||||
{ label: 'Web Framework', value: `Express ${depVersion('express')}` },
|
||||
{ label: 'Database', value: `${dbEngine} (pg ${depVersion('pg')})` },
|
||||
{ label: 'CORS', value: `cors ${depVersion('cors')}` },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
// API endpoint to get all data (requires the admin session)
|
||||
router.get('/web/data', requireSession, async (req: Request, res: Response) => {
|
||||
try {
|
||||
// Add cache control headers to prevent stale data
|
||||
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
|
||||
res.setHeader('Pragma', 'no-cache');
|
||||
res.setHeader('Expires', '0');
|
||||
|
||||
// Exclude deleted lists/items/fields from web UI
|
||||
const lists = await dbAdapter.queryAll('SELECT * FROM lists WHERE isDeleted = 0 ORDER BY updatedAt DESC');
|
||||
const fields = await dbAdapter.queryAll('SELECT * FROM fields WHERE isDeleted = 0 ORDER BY listId ASC, "order" ASC');
|
||||
const items = await dbAdapter.queryAll('SELECT * FROM items WHERE isDeleted = 0 ORDER BY listId ASC, updatedAt DESC');
|
||||
const values = await dbAdapter.queryAll('SELECT * FROM item_values');
|
||||
|
||||
// Convert isDeleted from INTEGER to BOOLEAN
|
||||
// Normalize timestamps to milliseconds since epoch
|
||||
const toMillis = (v: any): number | null => {
|
||||
if (v === null || v === undefined) return null;
|
||||
if (typeof v === 'number') {
|
||||
return v < 1e12 ? Math.trunc(v * 1000) : Math.trunc(v);
|
||||
}
|
||||
if (typeof v === 'string') {
|
||||
if (/^\d+$/.test(v)) {
|
||||
const n = Number(v);
|
||||
return n < 1e12 ? Math.trunc(n * 1000) : Math.trunc(n);
|
||||
}
|
||||
const t = Date.parse(v);
|
||||
return Number.isNaN(t) ? null : Math.trunc(t);
|
||||
}
|
||||
return null;
|
||||
};
|
||||
// Normalize key casing across SQLite (camelCase) and Postgres (lowercase)
|
||||
const pick = (obj: any, a: string, b: string) => obj[a] ?? obj[b];
|
||||
let formattedLists = (lists as any[]).map(list => ({
|
||||
...list,
|
||||
isDeleted: !!pick(list, 'isDeleted', 'isdeleted'),
|
||||
createdAt: toMillis(pick(list, 'createdAt', 'createdat')),
|
||||
updatedAt: toMillis(pick(list, 'updatedAt', 'updatedat'))
|
||||
}));
|
||||
const formattedFields = (fields as any[]).map(field => ({
|
||||
...field,
|
||||
listId: pick(field, 'listId', 'listid'),
|
||||
// Normalize fieldType casing across DBs and provide a sensible default
|
||||
fieldType: pick(field, 'fieldType', 'fieldtype') ?? 'STRING',
|
||||
isDeleted: !!pick(field, 'isDeleted', 'isdeleted'),
|
||||
createdAt: toMillis(pick(field, 'createdAt', 'createdat')),
|
||||
updatedAt: toMillis(pick(field, 'updatedAt', 'updatedat'))
|
||||
}));
|
||||
const formattedItems = (items as any[]).map(item => ({
|
||||
...item,
|
||||
listId: pick(item, 'listId', 'listid'),
|
||||
isDeleted: !!pick(item, 'isDeleted', 'isdeleted'),
|
||||
createdAt: toMillis(pick(item, 'createdAt', 'createdat')),
|
||||
updatedAt: toMillis(pick(item, 'updatedAt', 'updatedat'))
|
||||
}));
|
||||
const formattedValues = (values as any[]).map(v => ({
|
||||
...v,
|
||||
itemId: pick(v, 'itemId', 'itemid'),
|
||||
fieldId: pick(v, 'fieldId', 'fieldid'),
|
||||
updatedAt: toMillis(pick(v, 'updatedAt', 'updatedat'))
|
||||
}));
|
||||
// Compute effective updatedAt for lists based on latest change in the list itself or its children
|
||||
const itemIdToListId = new Map<string, string>();
|
||||
for (const it of formattedItems as any[]) {
|
||||
if (it && it.id && it.listId) itemIdToListId.set(it.id, it.listId);
|
||||
}
|
||||
const listToMaxField = new Map<string, number>();
|
||||
for (const f of formattedFields as any[]) {
|
||||
if (!f || !f.listId) continue;
|
||||
const t = typeof f.updatedAt === 'number' ? f.updatedAt : 0;
|
||||
const prev = listToMaxField.get(f.listId) || 0;
|
||||
if (t > prev) listToMaxField.set(f.listId, t);
|
||||
}
|
||||
const listToMaxItem = new Map<string, number>();
|
||||
for (const it of formattedItems as any[]) {
|
||||
if (!it || !it.listId) continue;
|
||||
const t = typeof it.updatedAt === 'number' ? it.updatedAt : 0;
|
||||
const prev = listToMaxItem.get(it.listId) || 0;
|
||||
if (t > prev) listToMaxItem.set(it.listId, t);
|
||||
}
|
||||
const listToMaxValue = new Map<string, number>();
|
||||
for (const val of formattedValues as any[]) {
|
||||
if (!val || !val.itemId) continue;
|
||||
const lId = itemIdToListId.get(val.itemId);
|
||||
if (!lId) continue;
|
||||
const t = typeof val.updatedAt === 'number' ? val.updatedAt : 0;
|
||||
const prev = listToMaxValue.get(lId) || 0;
|
||||
if (t > prev) listToMaxValue.set(lId, t);
|
||||
}
|
||||
formattedLists = formattedLists.map((l: any) => {
|
||||
const fMax = listToMaxField.get(l.id) || 0;
|
||||
const iMax = listToMaxItem.get(l.id) || 0;
|
||||
const vMax = listToMaxValue.get(l.id) || 0;
|
||||
const base = typeof l.updatedAt === 'number' ? l.updatedAt : 0;
|
||||
const eff = Math.max(base, fMax, iMax, vMax);
|
||||
return { ...l, effectiveUpdatedAt: eff === 0 ? l.updatedAt : eff };
|
||||
});
|
||||
|
||||
res.json({
|
||||
lists: formattedLists,
|
||||
fields: formattedFields,
|
||||
items: formattedItems,
|
||||
values: formattedValues,
|
||||
stats: {
|
||||
lists: formattedLists.length,
|
||||
fields: formattedFields.length,
|
||||
items: formattedItems.length,
|
||||
values: formattedValues.length
|
||||
},
|
||||
timestamp: Date.now() // Add timestamp for debugging
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error fetching data:', error);
|
||||
res.status(500).json({ error: 'Failed to fetch data' });
|
||||
}
|
||||
});
|
||||
|
||||
// SPA fallback: any other GET request (client-side routes like /about, /lists/:id) gets
|
||||
// index.html so SvelteKit's router can take over.
|
||||
router.get('*', (req: Request, res: Response) => {
|
||||
res.sendFile(path.join(webDir, 'index.html'));
|
||||
});
|
||||
|
||||
export default router;
|
||||
@@ -0,0 +1,249 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func syncMaxFutureSkew() int64 {
|
||||
value := envInt64("SYNC_MAX_FUTURE_SKEW_MS", 0)
|
||||
if value < 0 {
|
||||
return 0
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func normalizeTimestamp(raw, fallback, now int64) int64 {
|
||||
if raw <= 0 {
|
||||
return fallback
|
||||
}
|
||||
|
||||
ts := raw
|
||||
if ts < 1_000_000_000_000 {
|
||||
ts *= 1000
|
||||
}
|
||||
maxAllowed := now + syncMaxFutureSkew()
|
||||
if ts > maxAllowed {
|
||||
return maxAllowed
|
||||
}
|
||||
return ts
|
||||
}
|
||||
|
||||
func normalizeEntityTimestamps(createdAt, updatedAt, now int64) (int64, int64) {
|
||||
created := normalizeTimestamp(createdAt, now, now)
|
||||
updated := normalizeTimestamp(updatedAt, created, now)
|
||||
if updated < created {
|
||||
updated = created
|
||||
}
|
||||
return created, updated
|
||||
}
|
||||
|
||||
func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
|
||||
var request SyncRequest
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid sync request")
|
||||
return
|
||||
}
|
||||
|
||||
now := time.Now().UnixMilli()
|
||||
lastSync := normalizeTimestamp(int64(request.LastSyncTimestamp), 0, now)
|
||||
deviceID := requestDeviceID(r, request.DeviceID)
|
||||
orphans := make([]OrphanValue, 0)
|
||||
incoming := len(request.Lists) + len(request.Fields) + len(request.Items) + len(request.ItemValues)
|
||||
if incoming > 0 {
|
||||
fmt.Printf("[SYNC] Received lists=%d fields=%d items=%d values=%d\n", len(request.Lists), len(request.Fields), len(request.Items), len(request.ItemValues))
|
||||
}
|
||||
|
||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||
for _, list := range request.Lists {
|
||||
createdAt, updatedAt := normalizeEntityTimestamps(int64(list.CreatedAt), int64(list.UpdatedAt), now)
|
||||
if _, err := tx.Exec(r.Context(), `
|
||||
INSERT INTO lists (id, name, createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (id) DO UPDATE
|
||||
SET name = EXCLUDED.name, updatedat = EXCLUDED.updatedat, isdeleted = EXCLUDED.isdeleted
|
||||
`, list.ID, list.Name, createdAt, updatedAt, boolInt(list.IsDeleted)); err != nil {
|
||||
return err
|
||||
}
|
||||
event := "updated"
|
||||
if lastSync == 0 {
|
||||
event = "created"
|
||||
}
|
||||
if list.IsDeleted {
|
||||
event = "deleted"
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), tx, deviceID, event, "list", list.ID, list.ID, updatedAt))
|
||||
|
||||
if list.IsDeleted {
|
||||
if _, err := tx.Exec(r.Context(), `UPDATE fields SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, list.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, list.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE itemid IN (SELECT id FROM items WHERE listid = $1)`, list.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, field := range request.Fields {
|
||||
createdAt, updatedAt := normalizeEntityTimestamps(int64(field.CreatedAt), int64(field.UpdatedAt), now)
|
||||
fieldType := field.FieldType
|
||||
if fieldType == "" {
|
||||
fieldType = "TEXT"
|
||||
}
|
||||
alignment := field.Alignment
|
||||
if alignment == "" {
|
||||
alignment = "start"
|
||||
}
|
||||
if _, err := tx.Exec(r.Context(), `
|
||||
INSERT INTO fields
|
||||
(id, name, fieldtype, fieldoptions, alignment, listid, "order", createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||
ON CONFLICT (id) DO UPDATE
|
||||
SET name = EXCLUDED.name,
|
||||
fieldtype = EXCLUDED.fieldtype,
|
||||
fieldoptions = EXCLUDED.fieldoptions,
|
||||
alignment = EXCLUDED.alignment,
|
||||
"order" = EXCLUDED."order",
|
||||
updatedat = EXCLUDED.updatedat,
|
||||
isdeleted = EXCLUDED.isdeleted
|
||||
`, field.ID, field.Name, fieldType, field.FieldOptions, alignment, field.ListID, field.Order, createdAt, updatedAt, boolInt(field.IsDeleted)); err != nil {
|
||||
return err
|
||||
}
|
||||
event := "updated"
|
||||
if lastSync == 0 {
|
||||
event = "created"
|
||||
}
|
||||
if field.IsDeleted {
|
||||
event = "deleted"
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), tx, deviceID, event, "field", field.ID, field.ListID, updatedAt))
|
||||
|
||||
if field.IsDeleted {
|
||||
if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE fieldid = $1`, field.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
var remaining int
|
||||
if err := tx.QueryRow(r.Context(), `SELECT count(*) FROM fields WHERE listid = $1 AND isdeleted = 0`, field.ListID).Scan(&remaining); err != nil {
|
||||
return err
|
||||
}
|
||||
if remaining == 0 {
|
||||
if _, err := tx.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, field.ListID); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE itemid IN (SELECT id FROM items WHERE listid = $1)`, field.ListID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, item := range request.Items {
|
||||
createdAt, updatedAt := normalizeEntityTimestamps(int64(item.CreatedAt), int64(item.UpdatedAt), now)
|
||||
if _, err := tx.Exec(r.Context(), `
|
||||
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (id) DO UPDATE
|
||||
SET updatedat = EXCLUDED.updatedat, isdeleted = EXCLUDED.isdeleted
|
||||
`, item.ID, item.ListID, createdAt, updatedAt, boolInt(item.IsDeleted)); err != nil {
|
||||
return err
|
||||
}
|
||||
event := "updated"
|
||||
if lastSync == 0 {
|
||||
event = "created"
|
||||
}
|
||||
if item.IsDeleted {
|
||||
event = "deleted"
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), tx, deviceID, event, "item", item.ID, item.ListID, updatedAt))
|
||||
if item.IsDeleted {
|
||||
if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE itemid = $1`, item.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, value := range request.ItemValues {
|
||||
updatedAt := normalizeTimestamp(int64(value.UpdatedAt), now, now)
|
||||
var listID string
|
||||
fieldErr := tx.QueryRow(r.Context(), `SELECT listid FROM fields WHERE id = $1`, value.FieldID).Scan(&listID)
|
||||
if errors.Is(fieldErr, pgx.ErrNoRows) {
|
||||
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "missingField"})
|
||||
continue
|
||||
}
|
||||
if fieldErr != nil {
|
||||
return fieldErr
|
||||
}
|
||||
|
||||
var itemExists bool
|
||||
if err := tx.QueryRow(r.Context(), `SELECT EXISTS(SELECT 1 FROM items WHERE id = $1)`, value.ItemID).Scan(&itemExists); err != nil {
|
||||
return err
|
||||
}
|
||||
if !itemExists {
|
||||
if _, err := tx.Exec(r.Context(), `
|
||||
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $3, 0)
|
||||
ON CONFLICT (id) DO NOTHING
|
||||
`, value.ItemID, listID, updatedAt); err != nil {
|
||||
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "failedCreateStubItem"})
|
||||
continue
|
||||
}
|
||||
}
|
||||
if _, err := tx.Exec(r.Context(), `
|
||||
INSERT INTO item_values (id, itemid, fieldid, value, updatedat)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (id) DO UPDATE
|
||||
SET value = EXCLUDED.value, updatedat = EXCLUDED.updatedat
|
||||
`, value.ID, value.ItemID, value.FieldID, value.Value, updatedAt); err != nil {
|
||||
return err
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), tx, deviceID, "listContentUpdated", "value", value.ID, listID, updatedAt))
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
fmt.Printf("[SYNC] Failed: %v\n", err)
|
||||
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
||||
return
|
||||
}
|
||||
|
||||
var since *int64
|
||||
if lastSync != 0 {
|
||||
since = &lastSync
|
||||
}
|
||||
lists, err := s.db.queryLists(r.Context(), true, since)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
||||
return
|
||||
}
|
||||
fields, err := s.db.queryFields(r.Context(), true, since, "")
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
||||
return
|
||||
}
|
||||
items, err := s.db.queryItems(r.Context(), true, since, "")
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
||||
return
|
||||
}
|
||||
values, err := s.db.queryValues(r.Context(), since, "")
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, SyncResponse{
|
||||
Lists: lists,
|
||||
Fields: fields,
|
||||
Items: items,
|
||||
ItemValues: values,
|
||||
OrphanItemValues: orphans,
|
||||
ServerTimestamp: time.Now().UnixMilli(),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package main
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestNormalizeTimestampConvertsSeconds(t *testing.T) {
|
||||
const now = int64(1_700_000_000_000)
|
||||
if got := normalizeTimestamp(1_700_000_000, 0, now); got != 1_700_000_000_000 {
|
||||
t.Fatalf("normalizeTimestamp() = %d, want %d", got, 1_700_000_000_000)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeTimestampClampsFutureValues(t *testing.T) {
|
||||
t.Setenv("SYNC_MAX_FUTURE_SKEW_MS", "0")
|
||||
const now = int64(1_700_000_000_000)
|
||||
if got := normalizeTimestamp(now+1000, 0, now); got != now {
|
||||
t.Fatalf("normalizeTimestamp() = %d, want %d", got, now)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeEntityTimestampsKeepsUpdatedAfterCreated(t *testing.T) {
|
||||
t.Setenv("SYNC_MAX_FUTURE_SKEW_MS", "0")
|
||||
const now = int64(1_700_000_000_000)
|
||||
created, updated := normalizeEntityTimestamps(now-100, now-200, now)
|
||||
if created != now-100 || updated != created {
|
||||
t.Fatalf("timestamps = (%d, %d), want (%d, %d)", created, updated, now-100, now-100)
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"module": "commonjs",
|
||||
"lib": ["ES2020"],
|
||||
"types": ["node"],
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"resolveJsonModule": true,
|
||||
"moduleResolution": "node"
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (s *Server) handleWebData(w http.ResponseWriter, r *http.Request, _ *AuthUser) {
|
||||
lists, err := s.db.queryLists(r.Context(), false, nil)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
||||
return
|
||||
}
|
||||
fields, err := s.db.queryFields(r.Context(), false, nil, "")
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
||||
return
|
||||
}
|
||||
items, err := s.db.queryItems(r.Context(), false, nil, "")
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
||||
return
|
||||
}
|
||||
values, err := s.db.queryValues(r.Context(), nil, "")
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
||||
return
|
||||
}
|
||||
|
||||
itemToList := make(map[string]string, len(items))
|
||||
for _, item := range items {
|
||||
itemToList[item.ID] = item.ListID
|
||||
}
|
||||
fieldMax := make(map[string]int64)
|
||||
for _, field := range fields {
|
||||
if int64(field.UpdatedAt) > fieldMax[field.ListID] {
|
||||
fieldMax[field.ListID] = int64(field.UpdatedAt)
|
||||
}
|
||||
}
|
||||
itemMax := make(map[string]int64)
|
||||
for _, item := range items {
|
||||
if int64(item.UpdatedAt) > itemMax[item.ListID] {
|
||||
itemMax[item.ListID] = int64(item.UpdatedAt)
|
||||
}
|
||||
}
|
||||
valueMax := make(map[string]int64)
|
||||
for _, value := range values {
|
||||
listID := itemToList[value.ItemID]
|
||||
if listID != "" && int64(value.UpdatedAt) > valueMax[listID] {
|
||||
valueMax[listID] = int64(value.UpdatedAt)
|
||||
}
|
||||
}
|
||||
|
||||
type webList struct {
|
||||
List
|
||||
EffectiveUpdatedAt int64 `json:"effectiveUpdatedAt"`
|
||||
}
|
||||
webLists := make([]webList, 0, len(lists))
|
||||
for _, list := range lists {
|
||||
effective := int64(list.UpdatedAt)
|
||||
if fieldMax[list.ID] > effective {
|
||||
effective = fieldMax[list.ID]
|
||||
}
|
||||
if itemMax[list.ID] > effective {
|
||||
effective = itemMax[list.ID]
|
||||
}
|
||||
if valueMax[list.ID] > effective {
|
||||
effective = valueMax[list.ID]
|
||||
}
|
||||
webLists = append(webLists, webList{List: list, EffectiveUpdatedAt: effective})
|
||||
}
|
||||
|
||||
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
|
||||
w.Header().Set("Pragma", "no-cache")
|
||||
w.Header().Set("Expires", "0")
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"lists": webLists,
|
||||
"fields": fields,
|
||||
"items": items,
|
||||
"values": values,
|
||||
"stats": map[string]int{
|
||||
"lists": len(lists),
|
||||
"fields": len(fields),
|
||||
"items": len(items),
|
||||
"values": len(values),
|
||||
},
|
||||
"timestamp": time.Now().UnixMilli(),
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleNotificationPoll(w http.ResponseWriter, r *http.Request) {
|
||||
since, err := strconv.ParseInt(r.URL.Query().Get("since"), 10, 64)
|
||||
if err != nil || since < 0 {
|
||||
since = 0
|
||||
}
|
||||
deviceID := requestDeviceID(r, "")
|
||||
|
||||
query := `
|
||||
SELECT id, deviceidorigin, eventtype, entitytype, entityid, listid, createdat
|
||||
FROM notifications
|
||||
WHERE createdat > $1
|
||||
`
|
||||
args := []any{since}
|
||||
if deviceID != "" {
|
||||
query += ` AND (deviceidorigin IS NULL OR deviceidorigin <> $2)`
|
||||
args = append(args, deviceID)
|
||||
}
|
||||
query += ` ORDER BY createdat ASC LIMIT 500`
|
||||
|
||||
rows, err := s.db.pool.Query(r.Context(), query, args...)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to poll notifications")
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
events := make([]NotificationEvent, 0)
|
||||
for rows.Next() {
|
||||
var event NotificationEvent
|
||||
var origin, entityID, listID *string
|
||||
if err := rows.Scan(&event.ID, &origin, &event.EventType, &event.EntityType, &entityID, &listID, &event.CreatedAt); err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to poll notifications")
|
||||
return
|
||||
}
|
||||
if origin != nil {
|
||||
event.DeviceIDOrigin = *origin
|
||||
}
|
||||
if entityID != nil {
|
||||
event.EntityID = *entityID
|
||||
}
|
||||
if listID != nil {
|
||||
event.ListID = *listID
|
||||
}
|
||||
events = append(events, event)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to poll notifications")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, PollResponse{Notifications: events, ServerTimestamp: time.Now().UnixMilli()})
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
// Fully client-rendered SPA — the Express server only ever serves the static build plus
|
||||
// Fully client-rendered SPA — the Go server only ever serves the static build plus
|
||||
// its JSON/API routes, so there is no server to render against.
|
||||
export const ssr = false;
|
||||
@@ -3,7 +3,7 @@ import adapter from '@sveltejs/adapter-static';
|
||||
/** @type {import('@sveltejs/kit').Config} */
|
||||
const config = {
|
||||
kit: {
|
||||
// Static SPA build: the Express server serves this output and falls back to
|
||||
// Static SPA build: the Go server serves this output and falls back to
|
||||
// index.html for any path so SvelteKit's client-side router can take over.
|
||||
adapter: adapter({
|
||||
fallback: 'index.html',
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
[](https://opensource.org/licenses/MIT)
|
||||
[](https://android.com)
|
||||
[](https://nodejs.org)
|
||||
[](https://go.dev)
|
||||
|
||||
A collaborative list management system with Android app and server for creating and managing shared lists with custom fields and items.
|
||||
|
||||
@@ -20,7 +20,7 @@ CollabTable allows multiple users to collaboratively create and manage lists wit
|
||||
- ✨ **Beautiful Material 3 design** with dynamic colors
|
||||
- 📱 **Native Android app** built with Jetpack Compose
|
||||
- 💾 **Offline-first** with Room database
|
||||
- 🔄 **Real-time synchronization** via WebSocket (with HTTP fallback)
|
||||
- 🔄 **Synchronization** via transactional HTTP sync and notification polling
|
||||
- 🎨 **Custom fields** (name, link, price, category, etc.)
|
||||
- ✏️ **Inline editing** of items with auto-save
|
||||
- 📤 **Export functionality** (CSV format)
|
||||
@@ -30,11 +30,11 @@ CollabTable allows multiple users to collaboratively create and manage lists wit
|
||||
- 🎯 **Column alignment** options (left, center, right)
|
||||
|
||||
### Server
|
||||
- 🚀 **Express.js REST API** with TypeScript
|
||||
- 🚀 **Go REST API** built with `net/http`
|
||||
- 🐳 **Fully containerized** with Docker
|
||||
- 💾 **PostgreSQL** database (bring your own instance)
|
||||
- 🔄 **Advanced sync protocol** for conflict resolution
|
||||
- 🔌 **WebSocket support** for real-time updates
|
||||
- 🔔 **Notification polling** for background updates
|
||||
- 🔐 **Single-admin-account dashboard login** (session cookie) plus long-lived API tokens for sync clients/devices
|
||||
- 📊 **Complete CRUD operations** for all entities
|
||||
|
||||
@@ -42,7 +42,7 @@ CollabTable allows multiple users to collaboratively create and manage lists wit
|
||||
|
||||
### Server
|
||||
- **Docker** and a PostgreSQL instance (bring your own - this app does not run Postgres for you)
|
||||
- Or **Node.js 20+** for local development
|
||||
- Or **Go 1.26+** and Node.js 22+ for local development
|
||||
|
||||
### Android App
|
||||
- **Android Studio** Hedgehog or later
|
||||
@@ -119,11 +119,9 @@ CollabTable/
|
||||
│ │ └── build.gradle
|
||||
│ └── README.md
|
||||
│
|
||||
└── CollabTableServer/ # Node.js server
|
||||
├── src/
|
||||
│ ├── models/ # Data models & database logic
|
||||
│ ├── routes/ # API endpoints
|
||||
│ └── index.ts # Server entry point
|
||||
└── CollabTableServer/ # Go server
|
||||
├── *.go # HTTP handlers, auth, sync, and database layer
|
||||
├── go.mod # Go dependencies
|
||||
├── webui/ # SvelteKit web dashboard (read-only database viewer)
|
||||
├── Dockerfile
|
||||
└── README.md
|
||||
@@ -135,18 +133,18 @@ CollabTable/
|
||||
- **Language:** Kotlin
|
||||
- **UI Framework:** Jetpack Compose with Material 3
|
||||
- **Database:** Room (SQLite)
|
||||
- **Networking:** Retrofit (HTTP), OkHttp WebSocket
|
||||
- **Networking:** Retrofit and OkHttp (HTTP)
|
||||
- **Async:** Coroutines & Flow
|
||||
- **Architecture:** MVVM with Repository pattern
|
||||
- **Build System:** Gradle with Kotlin DSL
|
||||
|
||||
### Server
|
||||
- **Runtime:** Node.js 20+
|
||||
- **Framework:** Express.js
|
||||
- **Language:** TypeScript
|
||||
- **Database:** PostgreSQL (pg)
|
||||
- **Runtime:** Go 1.26+
|
||||
- **Framework:** Go `net/http`
|
||||
- **Language:** Go
|
||||
- **Database:** PostgreSQL (pgx)
|
||||
- **Containerization:** Docker
|
||||
- **Real-time:** WebSocket support
|
||||
- **Updates:** HTTP notification polling
|
||||
|
||||
## API Endpoints
|
||||
|
||||
@@ -179,15 +177,15 @@ bearer token) — see `CollabTableServer/README.md`'s "Authentication" section.
|
||||
- `PUT /api/items/:id` - Update an item
|
||||
- `DELETE /api/items/:id` - Delete an item (soft delete)
|
||||
|
||||
### Sync
|
||||
- `POST /api/sync` - Synchronize data (HTTP fallback)
|
||||
- `WebSocket /api/ws` - WebSocket endpoint for real-time sync
|
||||
### Sync
|
||||
- `POST /api/sync` - Synchronize data
|
||||
- `GET /api/notifications/poll?since=<timestamp-ms>` - Poll for remote changes
|
||||
|
||||
### Health
|
||||
- `GET /health` - Server health check
|
||||
|
||||
### Web UI
|
||||
`/`, `/about`, and `/lists/:id` serve a SvelteKit dashboard (a single-page app with client-side routing) for browsing lists/fields/items read-only. It's unauthenticated, same as before this endpoint existed.
|
||||
`/`, `/about`, and `/lists/:id` serve an embedded SvelteKit dashboard (a single-page app with client-side routing) for browsing lists/fields/items read-only. The dashboard shell is public; its data endpoints require the admin session.
|
||||
- `GET /web/data` - JSON snapshot of all lists, fields, items, and values, used by the dashboard
|
||||
- `GET /web/info` - JSON tech stack info, shown on the dashboard's About page
|
||||
|
||||
@@ -199,35 +197,36 @@ See [Server README](CollabTableServer/README.md) for detailed API documentation.
|
||||
|
||||
**Local development without Docker:**
|
||||
|
||||
1. Install dependencies:
|
||||
```bash
|
||||
cd CollabTableServer
|
||||
npm install
|
||||
```
|
||||
1. Run the Go backend:
|
||||
```bash
|
||||
cd CollabTableServer
|
||||
go test ./...
|
||||
go run .
|
||||
```
|
||||
|
||||
2. Create `.env` file:
|
||||
```bash
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
3. Start development server with hot reload:
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
4. Build for production:
|
||||
```bash
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
**Useful commands:**
|
||||
```bash
|
||||
npm run lint # Check code style
|
||||
npm run format # Auto-format code
|
||||
```
|
||||
|
||||
### Android Development
|
||||
3. Check and build the dashboard when changing web UI code:
|
||||
```bash
|
||||
cd webui
|
||||
npm ci
|
||||
npm run check
|
||||
npm run build
|
||||
cd ..
|
||||
cp -R webui/build web
|
||||
go build -o collabtable-server .
|
||||
```
|
||||
|
||||
**Useful backend commands:**
|
||||
```bash
|
||||
go test ./... # Run Go tests
|
||||
go vet ./... # Run static checks
|
||||
```
|
||||
|
||||
### Android Development
|
||||
|
||||
1. Open `CollabTableAndroid` in Android Studio
|
||||
|
||||
@@ -370,10 +369,10 @@ docker build -t collabtable-server . && docker run -d --name collabtable-server
|
||||
|
||||
CollabTable uses a sophisticated sync protocol to keep data consistent across clients:
|
||||
|
||||
### Sync Strategy
|
||||
- **Primary:** WebSocket (`/api/ws`) for real-time, low-latency sync
|
||||
- **Fallback:** HTTP POST (`/api/sync`) when WebSocket fails
|
||||
- **Conflict Resolution:** Latest timestamp wins
|
||||
### Sync Strategy
|
||||
- **Transport:** HTTP POST (`/api/sync`)
|
||||
- **Background updates:** Notification polling (`/api/notifications/poll`)
|
||||
- **Conflict Resolution:** Latest timestamp wins
|
||||
|
||||
### How It Works
|
||||
1. **Client → Server:** Client sends all local changes since last sync timestamp
|
||||
@@ -394,38 +393,7 @@ Client Server
|
||||
| |
|
||||
```
|
||||
|
||||
### WebSocket Protocol
|
||||
Send JSON messages to `/api/ws`:
|
||||
```json
|
||||
{
|
||||
"type": "sync",
|
||||
"id": "unique-request-id",
|
||||
"payload": {
|
||||
"lastSyncTimestamp": 1234567890,
|
||||
"lists": [...],
|
||||
"fields": [...],
|
||||
"items": [...],
|
||||
"itemValues": [...]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"type": "syncResponse",
|
||||
"id": "unique-request-id",
|
||||
"payload": {
|
||||
"lists": [...],
|
||||
"fields": [...],
|
||||
"items": [...],
|
||||
"itemValues": [...],
|
||||
"serverTimestamp": 1234567890
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Features
|
||||
### Features
|
||||
- **Automatic Sync:** Triggered on app start and after local changes
|
||||
- **Soft Deletes:** Deleted items can be recovered on server
|
||||
- **Optimistic Updates:** UI updates immediately, syncs in background
|
||||
@@ -466,9 +434,9 @@ docker ps
|
||||
**Environment Variables**
|
||||
Configure these in `.env` or your `docker run` command:
|
||||
```env
|
||||
PORT=3000 # Server port
|
||||
NODE_ENV=production # Environment
|
||||
DATABASE_URL=postgres://user:pass@postgres:5432/collabtable
|
||||
PORT=3000 # Server port
|
||||
APP_VERSION=dev # Dashboard version label
|
||||
DATABASE_URL=postgres://user:pass@postgres:5432/collabtable
|
||||
COOKIE_SECURE=true # Requires HTTPS
|
||||
```
|
||||
|
||||
@@ -487,11 +455,7 @@ server {
|
||||
|
||||
location / {
|
||||
proxy_pass http://localhost:3000;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection 'upgrade';
|
||||
proxy_set_header Host $host;
|
||||
proxy_cache_bypass $http_upgrade;
|
||||
proxy_set_header Host $host;
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -513,7 +477,7 @@ Contributions are welcome! Here's how you can help:
|
||||
|
||||
**Code Style**
|
||||
- **Android:** Follow Kotlin conventions, use ktlint for formatting
|
||||
- **Server:** Follow TypeScript/JavaScript conventions, use Prettier
|
||||
- **Server:** Follow Go conventions, run `gofmt`, and keep handlers testable
|
||||
- Keep functions small and focused
|
||||
- Write meaningful variable and function names
|
||||
- Add comments for complex logic
|
||||
|
||||
Reference in new issue
Block a user