diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index aa2047c..9268336 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -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 diff --git a/CollabTableServer/.dockerignore b/CollabTableServer/.dockerignore index c1fab6a..5d84af8 100644 --- a/CollabTableServer/.dockerignore +++ b/CollabTableServer/.dockerignore @@ -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 diff --git a/CollabTableServer/.env.example b/CollabTableServer/.env.example index f351423..8a86188 100644 --- a/CollabTableServer/.env.example +++ b/CollabTableServer/.env.example @@ -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 diff --git a/CollabTableServer/.eslintrc.cjs b/CollabTableServer/.eslintrc.cjs deleted file mode 100644 index b68065f..0000000 --- a/CollabTableServer/.eslintrc.cjs +++ /dev/null @@ -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', - }, -}; \ No newline at end of file diff --git a/CollabTableServer/.gitignore b/CollabTableServer/.gitignore index 36e0c64..d3633d8 100644 --- a/CollabTableServer/.gitignore +++ b/CollabTableServer/.gitignore @@ -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 diff --git a/CollabTableServer/.prettierrc b/CollabTableServer/.prettierrc deleted file mode 100644 index b537842..0000000 --- a/CollabTableServer/.prettierrc +++ /dev/null @@ -1,6 +0,0 @@ -{ - "singleQuote": true, - "semi": true, - "trailingComma": "all", - "printWidth": 100 -} \ No newline at end of file diff --git a/CollabTableServer/Dockerfile b/CollabTableServer/Dockerfile index 7795529..d9724a7 100644 --- a/CollabTableServer/Dockerfile +++ b/CollabTableServer/Dockerfile @@ -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"] diff --git a/CollabTableServer/README.md b/CollabTableServer/README.md index b702121..a385021 100644 --- a/CollabTableServer/README.md +++ b/CollabTableServer/README.md @@ -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":"", "payload": { ...SyncRequest }}` → `{"type":"syncResponse", "id":"", "payload": { ...SyncResponse }}` - -Authentication: include header `Authorization: Bearer ` 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 ` 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 +``` + +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=` + +### 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 diff --git a/CollabTableServer/auth.go b/CollabTableServer/auth.go new file mode 100644 index 0000000..72d888b --- /dev/null +++ b/CollabTableServer/auth.go @@ -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}) +} diff --git a/CollabTableServer/data.go b/CollabTableServer/data.go new file mode 100644 index 0000000..27820f1 --- /dev/null +++ b/CollabTableServer/data.go @@ -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") + } +} diff --git a/CollabTableServer/db.go b/CollabTableServer/db.go new file mode 100644 index 0000000..08c4c30 --- /dev/null +++ b/CollabTableServer/db.go @@ -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 +} diff --git a/CollabTableServer/entrypoint.sh b/CollabTableServer/entrypoint.sh deleted file mode 100644 index 909e7d7..0000000 --- a/CollabTableServer/entrypoint.sh +++ /dev/null @@ -1,2 +0,0 @@ -# Ensure data directory exists -mkdir -p /data diff --git a/CollabTableServer/go.mod b/CollabTableServer/go.mod new file mode 100644 index 0000000..817d68a --- /dev/null +++ b/CollabTableServer/go.mod @@ -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 +) diff --git a/CollabTableServer/go.sum b/CollabTableServer/go.sum new file mode 100644 index 0000000..4988e5c --- /dev/null +++ b/CollabTableServer/go.sum @@ -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= diff --git a/CollabTableServer/models.go b/CollabTableServer/models.go new file mode 100644 index 0000000..8c2ab02 --- /dev/null +++ b/CollabTableServer/models.go @@ -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"` +} diff --git a/CollabTableServer/models_test.go b/CollabTableServer/models_test.go new file mode 100644 index 0000000..e075b07 --- /dev/null +++ b/CollabTableServer/models_test.go @@ -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) + } +} diff --git a/CollabTableServer/notifications.go b/CollabTableServer/notifications.go new file mode 100644 index 0000000..ddb151d --- /dev/null +++ b/CollabTableServer/notifications.go @@ -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 +} diff --git a/CollabTableServer/package-lock.json b/CollabTableServer/package-lock.json deleted file mode 100644 index 5fba58d..0000000 --- a/CollabTableServer/package-lock.json +++ /dev/null @@ -1,3402 +0,0 @@ -{ - "name": "collabtable-server", - "version": "1.0.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "collabtable-server", - "version": "1.0.0", - "license": "MIT", - "dependencies": { - "@typescript-eslint/eslint-plugin": "^7.0.2", - "@typescript-eslint/parser": "^7.0.2", - "bcryptjs": "^2.4.3", - "cookie-parser": "^1.4.6", - "cors": "^2.8.5", - "dotenv": "^16.3.1", - "eslint": "^8.57.0", - "eslint-config-prettier": "^9.1.0", - "express": "^4.18.2", - "pg": "^8.11.3", - "prettier": "^3.3.3" - }, - "devDependencies": { - "@types/bcryptjs": "^2.4.6", - "@types/cookie-parser": "^1.4.7", - "@types/cors": "^2.8.17", - "@types/express": "^4.17.21", - "@types/node": "^20.10.6", - "@types/pg": "^8.10.2", - "ts-node-dev": "^2.0.0", - "typescript": "5.5.4" - } - }, - "node_modules/@cspotcode/source-map-support": { - "version": "0.8.1", - "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", - "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/trace-mapping": "0.3.9" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/@eslint-community/eslint-utils": { - "version": "4.9.0", - "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.0.tgz", - "integrity": "sha512-ayVFHdtZ+hsq1t2Dy24wCmGXGe4q9Gu3smhLYALJrr473ZH27MsnSL+LKUlimp4BWJqMDMLmPpx/Q9R3OAlL4g==", - "license": "MIT", - "dependencies": { - "eslint-visitor-keys": "^3.4.3" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - }, - "peerDependencies": { - "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" - } - }, - "node_modules/@eslint-community/regexpp": { - "version": "4.12.2", - "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz", - "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==", - "license": "MIT", - "engines": { - "node": "^12.0.0 || ^14.0.0 || >=16.0.0" - } - }, - "node_modules/@eslint/eslintrc": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-2.1.4.tgz", - "integrity": "sha512-269Z39MS6wVJtsoUl10L60WdkhJVdPG24Q4eZTH3nnF6lpvSShEK3wQjDX9JRWAUPvPh7COouPpU9IrqaZFvtQ==", - "license": "MIT", - "dependencies": { - "ajv": "^6.12.4", - "debug": "^4.3.2", - "espree": "^9.6.0", - "globals": "^13.19.0", - "ignore": "^5.2.0", - "import-fresh": "^3.2.1", - "js-yaml": "^4.1.0", - "minimatch": "^3.1.2", - "strip-json-comments": "^3.1.1" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/@eslint/eslintrc/node_modules/debug": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", - "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", - "license": "MIT", - "dependencies": { - "ms": "^2.1.3" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/@eslint/eslintrc/node_modules/ms": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", - "license": "MIT" - }, - "node_modules/@eslint/eslintrc/node_modules/strip-json-comments": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", - "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", - "license": "MIT", - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/@eslint/js": { - "version": "8.57.1", - "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.57.1.tgz", - "integrity": "sha512-d9zaMRSTIKDLhctzH12MtXvJKSSUhaHcjV+2Z+GK+EEY7XKpP5yR4x+N3TAcHTcu963nIr+TMcCb4DBCYX1z6Q==", - "license": "MIT", - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - } - }, - "node_modules/@humanwhocodes/config-array": { - "version": "0.13.0", - "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.13.0.tgz", - "integrity": "sha512-DZLEEqFWQFiyK6h5YIeynKx7JlvCYWL0cImfSRXZ9l4Sg2efkFGTuFf6vzXjK1cq6IYkU+Eg/JizXw+TD2vRNw==", - "deprecated": "Use @eslint/config-array instead", - "license": "Apache-2.0", - "dependencies": { - "@humanwhocodes/object-schema": "^2.0.3", - "debug": "^4.3.1", - "minimatch": "^3.0.5" - }, - "engines": { - "node": ">=10.10.0" - } - }, - "node_modules/@humanwhocodes/config-array/node_modules/debug": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", - "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", - "license": "MIT", - "dependencies": { - "ms": "^2.1.3" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/@humanwhocodes/config-array/node_modules/ms": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", - "license": "MIT" - }, - "node_modules/@humanwhocodes/module-importer": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", - "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", - "license": "Apache-2.0", - "engines": { - "node": ">=12.22" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/nzakas" - } - }, - "node_modules/@humanwhocodes/object-schema": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-2.0.3.tgz", - "integrity": "sha512-93zYdMES/c1D69yZiKDBj0V24vqNzB/koF26KPaagAfd3P/4gUlh3Dys5ogAK+Exi9QyzlD8x/08Zt7wIKcDcA==", - "deprecated": "Use @eslint/object-schema instead", - "license": "BSD-3-Clause" - }, - "node_modules/@jridgewell/resolve-uri": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", - "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.5.5", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", - "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", - "dev": true, - "license": "MIT" - }, - "node_modules/@jridgewell/trace-mapping": { - "version": "0.3.9", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", - "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/resolve-uri": "^3.0.3", - "@jridgewell/sourcemap-codec": "^1.4.10" - } - }, - "node_modules/@nodelib/fs.scandir": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", - "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", - "license": "MIT", - "dependencies": { - "@nodelib/fs.stat": "2.0.5", - "run-parallel": "^1.1.9" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/@nodelib/fs.stat": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", - "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", - "license": "MIT", - "engines": { - "node": ">= 8" - } - }, - "node_modules/@nodelib/fs.walk": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", - "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", - "license": "MIT", - "dependencies": { - "@nodelib/fs.scandir": "2.1.5", - "fastq": "^1.6.0" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/@tsconfig/node10": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.11.tgz", - "integrity": "sha512-DcRjDCujK/kCk/cUe8Xz8ZSpm8mS3mNNpta+jGCA6USEDfktlNvm1+IuZ9eTcDbNk41BHwpHHeW+N1lKCz4zOw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@tsconfig/node12": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz", - "integrity": "sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==", - "dev": true, - "license": "MIT" - }, - "node_modules/@tsconfig/node14": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz", - "integrity": "sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==", - "dev": true, - "license": "MIT" - }, - "node_modules/@tsconfig/node16": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.4.tgz", - "integrity": "sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/bcryptjs": { - "version": "2.4.6", - "resolved": "https://registry.npmjs.org/@types/bcryptjs/-/bcryptjs-2.4.6.tgz", - "integrity": "sha512-9xlo6R2qDs5uixm0bcIqCeMCE6HiQsIyel9KQySStiyqNl2tnj2mP3DX1Nf56MD6KMenNNlBBsy3LJ7gUEQPXQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/body-parser": { - "version": "1.19.6", - "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz", - "integrity": "sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/connect": "*", - "@types/node": "*" - } - }, - "node_modules/@types/connect": { - "version": "3.4.38", - "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz", - "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@types/cookie-parser": { - "version": "1.4.10", - "resolved": "https://registry.npmjs.org/@types/cookie-parser/-/cookie-parser-1.4.10.tgz", - "integrity": "sha512-B4xqkqfZ8Wek+rCOeRxsjMS9OgvzebEzzLYw7NHYuvzb7IdxOkI0ZHGgeEBX4PUM7QGVvNSK60T3OvWj3YfBRg==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "@types/express": "*" - } - }, - "node_modules/@types/cors": { - "version": "2.8.19", - "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.19.tgz", - "integrity": "sha512-mFNylyeyqN93lfe/9CSxOGREz8cpzAhH+E93xJ4xWQf62V8sQ/24reV2nyzUWM6H6Xji+GGHpkbLe7pVoUEskg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@types/express": { - "version": "4.17.24", - "resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.24.tgz", - "integrity": "sha512-Mbrt4SRlXSTWryOnHAh2d4UQ/E7n9lZyGSi6KgX+4hkuL9soYbLOVXVhnk/ODp12YsGc95f4pOvqywJ6kngUwg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/body-parser": "*", - "@types/express-serve-static-core": "^4.17.33", - "@types/qs": "*", - "@types/serve-static": "*" - } - }, - "node_modules/@types/express-serve-static-core": { - "version": "4.19.7", - "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.19.7.tgz", - "integrity": "sha512-FvPtiIf1LfhzsaIXhv/PHan/2FeQBbtBDtfX2QfvPxdUelMDEckK08SM6nqo1MIZY3RUlfA+HV8+hFUSio78qg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*", - "@types/qs": "*", - "@types/range-parser": "*", - "@types/send": "*" - } - }, - "node_modules/@types/http-errors": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.5.tgz", - "integrity": "sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/mime": { - "version": "1.3.5", - "resolved": "https://registry.npmjs.org/@types/mime/-/mime-1.3.5.tgz", - "integrity": "sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/node": { - "version": "20.19.23", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.23.tgz", - "integrity": "sha512-yIdlVVVHXpmqRhtyovZAcSy0MiPcYWGkoO4CGe/+jpP0hmNuihm4XhHbADpK++MsiLHP5MVlv+bcgdF99kSiFQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "undici-types": "~6.21.0" - } - }, - "node_modules/@types/pg": { - "version": "8.15.5", - "resolved": "https://registry.npmjs.org/@types/pg/-/pg-8.15.5.tgz", - "integrity": "sha512-LF7lF6zWEKxuT3/OR8wAZGzkg4ENGXFNyiV/JeOt9z5B+0ZVwbql9McqX5c/WStFq1GaGso7H1AzP/qSzmlCKQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*", - "pg-protocol": "*", - "pg-types": "^2.2.0" - } - }, - "node_modules/@types/qs": { - "version": "6.14.0", - "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.14.0.tgz", - "integrity": "sha512-eOunJqu0K1923aExK6y8p6fsihYEn/BYuQ4g0CxAAgFc4b/ZLN4CrsRZ55srTdqoiLzU2B2evC+apEIxprEzkQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/range-parser": { - "version": "1.2.7", - "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz", - "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/send": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@types/send/-/send-1.2.1.tgz", - "integrity": "sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@types/serve-static": { - "version": "1.15.10", - "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.15.10.tgz", - "integrity": "sha512-tRs1dB+g8Itk72rlSI2ZrW6vZg0YrLI81iQSTkMmOqnqCaNr/8Ek4VwWcN5vZgCYWbg/JJSGBlUaYGAOP73qBw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/http-errors": "*", - "@types/node": "*", - "@types/send": "<1" - } - }, - "node_modules/@types/serve-static/node_modules/@types/send": { - "version": "0.17.6", - "resolved": "https://registry.npmjs.org/@types/send/-/send-0.17.6.tgz", - "integrity": "sha512-Uqt8rPBE8SY0RK8JB1EzVOIZ32uqy8HwdxCnoCOsYrvnswqmFZ/k+9Ikidlk/ImhsdvBsloHbAlewb2IEBV/Og==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/mime": "^1", - "@types/node": "*" - } - }, - "node_modules/@types/strip-bom": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/@types/strip-bom/-/strip-bom-3.0.0.tgz", - "integrity": "sha512-xevGOReSYGM7g/kUBZzPqCrR/KYAo+F0yiPc85WFTJa0MSLtyFTVTU6cJu/aV4mid7IffDIWqo69THF2o4JiEQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/strip-json-comments": { - "version": "0.0.30", - "resolved": "https://registry.npmjs.org/@types/strip-json-comments/-/strip-json-comments-0.0.30.tgz", - "integrity": "sha512-7NQmHra/JILCd1QqpSzl8+mJRc8ZHz3uDm8YV1Ks9IhK0epEiTw8aIErbvH9PI+6XbqhyIQy3462nEsn7UVzjQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@typescript-eslint/eslint-plugin": { - "version": "7.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-7.18.0.tgz", - "integrity": "sha512-94EQTWZ40mzBc42ATNIBimBEDltSJ9RQHCC8vc/PDbxi4k8dVwUAv4o98dk50M1zB+JGFxp43FP7f8+FP8R6Sw==", - "license": "MIT", - "dependencies": { - "@eslint-community/regexpp": "^4.10.0", - "@typescript-eslint/scope-manager": "7.18.0", - "@typescript-eslint/type-utils": "7.18.0", - "@typescript-eslint/utils": "7.18.0", - "@typescript-eslint/visitor-keys": "7.18.0", - "graphemer": "^1.4.0", - "ignore": "^5.3.1", - "natural-compare": "^1.4.0", - "ts-api-utils": "^1.3.0" - }, - "engines": { - "node": "^18.18.0 || >=20.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "@typescript-eslint/parser": "^7.0.0", - "eslint": "^8.56.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@typescript-eslint/parser": { - "version": "7.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-7.18.0.tgz", - "integrity": "sha512-4Z+L8I2OqhZV8qA132M4wNL30ypZGYOQVBfMgxDH/K5UX0PNqTu1c6za9ST5r9+tavvHiTWmBnKzpCJ/GlVFtg==", - "license": "BSD-2-Clause", - "dependencies": { - "@typescript-eslint/scope-manager": "7.18.0", - "@typescript-eslint/types": "7.18.0", - "@typescript-eslint/typescript-estree": "7.18.0", - "@typescript-eslint/visitor-keys": "7.18.0", - "debug": "^4.3.4" - }, - "engines": { - "node": "^18.18.0 || >=20.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "^8.56.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@typescript-eslint/parser/node_modules/debug": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", - "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", - "license": "MIT", - "dependencies": { - "ms": "^2.1.3" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/@typescript-eslint/parser/node_modules/ms": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", - "license": "MIT" - }, - "node_modules/@typescript-eslint/scope-manager": { - "version": "7.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-7.18.0.tgz", - "integrity": "sha512-jjhdIE/FPF2B7Z1uzc6i3oWKbGcHb87Qw7AWj6jmEqNOfDFbJWtjt/XfwCpvNkpGWlcJaog5vTR+VV8+w9JflA==", - "license": "MIT", - "dependencies": { - "@typescript-eslint/types": "7.18.0", - "@typescript-eslint/visitor-keys": "7.18.0" - }, - "engines": { - "node": "^18.18.0 || >=20.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "node_modules/@typescript-eslint/type-utils": { - "version": "7.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-7.18.0.tgz", - "integrity": "sha512-XL0FJXuCLaDuX2sYqZUUSOJ2sG5/i1AAze+axqmLnSkNEVMVYLF+cbwlB2w8D1tinFuSikHmFta+P+HOofrLeA==", - "license": "MIT", - "dependencies": { - "@typescript-eslint/typescript-estree": "7.18.0", - "@typescript-eslint/utils": "7.18.0", - "debug": "^4.3.4", - "ts-api-utils": "^1.3.0" - }, - "engines": { - "node": "^18.18.0 || >=20.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "^8.56.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@typescript-eslint/type-utils/node_modules/debug": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", - "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", - "license": "MIT", - "dependencies": { - "ms": "^2.1.3" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/@typescript-eslint/type-utils/node_modules/ms": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", - "license": "MIT" - }, - "node_modules/@typescript-eslint/types": { - "version": "7.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-7.18.0.tgz", - "integrity": "sha512-iZqi+Ds1y4EDYUtlOOC+aUmxnE9xS/yCigkjA7XpTKV6nCBd3Hp/PRGGmdwnfkV2ThMyYldP1wRpm/id99spTQ==", - "license": "MIT", - "engines": { - "node": "^18.18.0 || >=20.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "node_modules/@typescript-eslint/typescript-estree": { - "version": "7.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-7.18.0.tgz", - "integrity": "sha512-aP1v/BSPnnyhMHts8cf1qQ6Q1IFwwRvAQGRvBFkWlo3/lH29OXA3Pts+c10nxRxIBrDnoMqzhgdwVe5f2D6OzA==", - "license": "BSD-2-Clause", - "dependencies": { - "@typescript-eslint/types": "7.18.0", - "@typescript-eslint/visitor-keys": "7.18.0", - "debug": "^4.3.4", - "globby": "^11.1.0", - "is-glob": "^4.0.3", - "minimatch": "^9.0.4", - "semver": "^7.6.0", - "ts-api-utils": "^1.3.0" - }, - "engines": { - "node": "^18.18.0 || >=20.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz", - "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==", - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0" - } - }, - "node_modules/@typescript-eslint/typescript-estree/node_modules/debug": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", - "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", - "license": "MIT", - "dependencies": { - "ms": "^2.1.3" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": { - "version": "9.0.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", - "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", - "license": "ISC", - "dependencies": { - "brace-expansion": "^2.0.1" - }, - "engines": { - "node": ">=16 || 14 >=14.17" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/@typescript-eslint/typescript-estree/node_modules/ms": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", - "license": "MIT" - }, - "node_modules/@typescript-eslint/utils": { - "version": "7.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-7.18.0.tgz", - "integrity": "sha512-kK0/rNa2j74XuHVcoCZxdFBMF+aq/vH83CXAOHieC+2Gis4mF8jJXT5eAfyD3K0sAxtPuwxaIOIOvhwzVDt/kw==", - "license": "MIT", - "dependencies": { - "@eslint-community/eslint-utils": "^4.4.0", - "@typescript-eslint/scope-manager": "7.18.0", - "@typescript-eslint/types": "7.18.0", - "@typescript-eslint/typescript-estree": "7.18.0" - }, - "engines": { - "node": "^18.18.0 || >=20.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "^8.56.0" - } - }, - "node_modules/@typescript-eslint/visitor-keys": { - "version": "7.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-7.18.0.tgz", - "integrity": "sha512-cDF0/Gf81QpY3xYyJKDV14Zwdmid5+uuENhjH2EqFaF0ni+yAyq/LzMaIJdhNJXZI7uLzwIlA+V7oWoyn6Curg==", - "license": "MIT", - "dependencies": { - "@typescript-eslint/types": "7.18.0", - "eslint-visitor-keys": "^3.4.3" - }, - "engines": { - "node": "^18.18.0 || >=20.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "node_modules/@ungap/structured-clone": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.0.tgz", - "integrity": "sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==", - "license": "ISC" - }, - "node_modules/accepts": { - "version": "1.3.8", - "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", - "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", - "license": "MIT", - "dependencies": { - "mime-types": "~2.1.34", - "negotiator": "0.6.3" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/acorn": { - "version": "8.15.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz", - "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", - "license": "MIT", - "bin": { - "acorn": "bin/acorn" - }, - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/acorn-jsx": { - "version": "5.3.2", - "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", - "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", - "license": "MIT", - "peerDependencies": { - "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" - } - }, - "node_modules/acorn-walk": { - "version": "8.3.4", - "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.4.tgz", - "integrity": "sha512-ueEepnujpqee2o5aIYnvHU6C0A42MNdsIDeqy5BydrkuC5R1ZuUFnm27EeFJGoEHJQgn3uleRvmTXaJgfXbt4g==", - "dev": true, - "license": "MIT", - "dependencies": { - "acorn": "^8.11.0" - }, - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/ajv": { - "version": "6.12.6", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", - "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", - "license": "MIT", - "dependencies": { - "fast-deep-equal": "^3.1.1", - "fast-json-stable-stringify": "^2.0.0", - "json-schema-traverse": "^0.4.1", - "uri-js": "^4.2.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" - } - }, - "node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "license": "MIT", - "dependencies": { - "color-convert": "^2.0.1" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/anymatch": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", - "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", - "dev": true, - "license": "ISC", - "dependencies": { - "normalize-path": "^3.0.0", - "picomatch": "^2.0.4" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/arg": { - "version": "4.1.3", - "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", - "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==", - "dev": true, - "license": "MIT" - }, - "node_modules/argparse": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", - "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", - "license": "Python-2.0" - }, - "node_modules/array-flatten": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", - "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==", - "license": "MIT" - }, - "node_modules/array-union": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz", - "integrity": "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/balanced-match": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", - "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", - "license": "MIT" - }, - "node_modules/bcryptjs": { - "version": "2.4.3", - "resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-2.4.3.tgz", - "integrity": "sha512-V/Hy/X9Vt7f3BbPJEi8BdVFMByHi+jNXrYkW3huaybV/kQ0KJg0Y6PkEMbn+zeT+i+SiKZ/HMqJGIIt4LZDqNQ==", - "license": "MIT" - }, - "node_modules/binary-extensions": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", - "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/body-parser": { - "version": "1.20.3", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.3.tgz", - "integrity": "sha512-7rAxByjUMqQ3/bHJy7D6OGXvx/MMc4IqBn/X0fcM1QUcAItpZrBEYhWGem+tzXH90c+G01ypMcYJBO9Y30203g==", - "license": "MIT", - "dependencies": { - "bytes": "3.1.2", - "content-type": "~1.0.5", - "debug": "2.6.9", - "depd": "2.0.0", - "destroy": "1.2.0", - "http-errors": "2.0.0", - "iconv-lite": "0.4.24", - "on-finished": "2.4.1", - "qs": "6.13.0", - "raw-body": "2.5.2", - "type-is": "~1.6.18", - "unpipe": "1.0.0" - }, - "engines": { - "node": ">= 0.8", - "npm": "1.2.8000 || >= 1.4.16" - } - }, - "node_modules/brace-expansion": { - "version": "1.1.12", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", - "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "node_modules/braces": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", - "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", - "license": "MIT", - "dependencies": { - "fill-range": "^7.1.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/buffer-from": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", - "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/bytes": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", - "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/call-bind-apply-helpers": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", - "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "function-bind": "^1.1.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/call-bound": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", - "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", - "license": "MIT", - "dependencies": { - "call-bind-apply-helpers": "^1.0.2", - "get-intrinsic": "^1.3.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/callsites": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", - "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/chalk": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", - "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", - "license": "MIT", - "dependencies": { - "ansi-styles": "^4.1.0", - "supports-color": "^7.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/chalk?sponsor=1" - } - }, - "node_modules/chokidar": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", - "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", - "dev": true, - "license": "MIT", - "dependencies": { - "anymatch": "~3.1.2", - "braces": "~3.0.2", - "glob-parent": "~5.1.2", - "is-binary-path": "~2.1.0", - "is-glob": "~4.0.1", - "normalize-path": "~3.0.0", - "readdirp": "~3.6.0" - }, - "engines": { - "node": ">= 8.10.0" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - }, - "optionalDependencies": { - "fsevents": "~2.3.2" - } - }, - "node_modules/color-convert": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "license": "MIT", - "dependencies": { - "color-name": "~1.1.4" - }, - "engines": { - "node": ">=7.0.0" - } - }, - "node_modules/color-name": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "license": "MIT" - }, - "node_modules/concat-map": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", - "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", - "license": "MIT" - }, - "node_modules/content-disposition": { - "version": "0.5.4", - "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", - "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", - "license": "MIT", - "dependencies": { - "safe-buffer": "5.2.1" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/content-type": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", - "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/cookie": { - "version": "0.7.1", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.1.tgz", - "integrity": "sha512-6DnInpx7SJ2AK3+CTUE/ZM0vWTUboZCegxhC2xiIydHR9jNuTAASBrfEpHhiGOZw/nX51bHt6YQl8jsGo4y/0w==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/cookie-parser": { - "version": "1.4.7", - "resolved": "https://registry.npmjs.org/cookie-parser/-/cookie-parser-1.4.7.tgz", - "integrity": "sha512-nGUvgXnotP3BsjiLX2ypbQnWoGUPIIfHQNZkkC668ntrzGWEZVW70HDEB1qnNGMicPje6EttlIgzo51YSwNQGw==", - "license": "MIT", - "dependencies": { - "cookie": "0.7.2", - "cookie-signature": "1.0.6" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/cookie-parser/node_modules/cookie": { - "version": "0.7.2", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", - "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/cookie-signature": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", - "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==", - "license": "MIT" - }, - "node_modules/cors": { - "version": "2.8.5", - "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", - "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", - "license": "MIT", - "dependencies": { - "object-assign": "^4", - "vary": "^1" - }, - "engines": { - "node": ">= 0.10" - } - }, - "node_modules/create-require": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz", - "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/cross-spawn": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", - "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", - "license": "MIT", - "dependencies": { - "path-key": "^3.1.0", - "shebang-command": "^2.0.0", - "which": "^2.0.1" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "license": "MIT", - "dependencies": { - "ms": "2.0.0" - } - }, - "node_modules/deep-is": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", - "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", - "license": "MIT" - }, - "node_modules/depd": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", - "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/destroy": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", - "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", - "license": "MIT", - "engines": { - "node": ">= 0.8", - "npm": "1.2.8000 || >= 1.4.16" - } - }, - "node_modules/diff": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz", - "integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">=0.3.1" - } - }, - "node_modules/dir-glob": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-3.0.1.tgz", - "integrity": "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==", - "license": "MIT", - "dependencies": { - "path-type": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/doctrine": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz", - "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==", - "license": "Apache-2.0", - "dependencies": { - "esutils": "^2.0.2" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/dotenv": { - "version": "16.6.1", - "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz", - "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==", - "license": "BSD-2-Clause", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://dotenvx.com" - } - }, - "node_modules/dunder-proto": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", - "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", - "license": "MIT", - "dependencies": { - "call-bind-apply-helpers": "^1.0.1", - "es-errors": "^1.3.0", - "gopd": "^1.2.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/dynamic-dedupe": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/dynamic-dedupe/-/dynamic-dedupe-0.3.0.tgz", - "integrity": "sha512-ssuANeD+z97meYOqd50e04Ze5qp4bPqo8cCkI4TRjZkzAUgIDTrXV1R8QCdINpiI+hw14+rYazvTRdQrz0/rFQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "xtend": "^4.0.0" - } - }, - "node_modules/ee-first": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", - "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", - "license": "MIT" - }, - "node_modules/encodeurl": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", - "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/es-define-property": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", - "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-errors": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", - "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-object-atoms": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", - "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/escape-html": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", - "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", - "license": "MIT" - }, - "node_modules/escape-string-regexp": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", - "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/eslint": { - "version": "8.57.1", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.57.1.tgz", - "integrity": "sha512-ypowyDxpVSYpkXr9WPv2PAZCtNip1Mv5KTW0SCurXv/9iOpcrH9PaqUElksqEB6pChqHGDRCFTyrZlGhnLNGiA==", - "deprecated": "This version is no longer supported. Please see https://eslint.org/version-support for other options.", - "license": "MIT", - "dependencies": { - "@eslint-community/eslint-utils": "^4.2.0", - "@eslint-community/regexpp": "^4.6.1", - "@eslint/eslintrc": "^2.1.4", - "@eslint/js": "8.57.1", - "@humanwhocodes/config-array": "^0.13.0", - "@humanwhocodes/module-importer": "^1.0.1", - "@nodelib/fs.walk": "^1.2.8", - "@ungap/structured-clone": "^1.2.0", - "ajv": "^6.12.4", - "chalk": "^4.0.0", - "cross-spawn": "^7.0.2", - "debug": "^4.3.2", - "doctrine": "^3.0.0", - "escape-string-regexp": "^4.0.0", - "eslint-scope": "^7.2.2", - "eslint-visitor-keys": "^3.4.3", - "espree": "^9.6.1", - "esquery": "^1.4.2", - "esutils": "^2.0.2", - "fast-deep-equal": "^3.1.3", - "file-entry-cache": "^6.0.1", - "find-up": "^5.0.0", - "glob-parent": "^6.0.2", - "globals": "^13.19.0", - "graphemer": "^1.4.0", - "ignore": "^5.2.0", - "imurmurhash": "^0.1.4", - "is-glob": "^4.0.0", - "is-path-inside": "^3.0.3", - "js-yaml": "^4.1.0", - "json-stable-stringify-without-jsonify": "^1.0.1", - "levn": "^0.4.1", - "lodash.merge": "^4.6.2", - "minimatch": "^3.1.2", - "natural-compare": "^1.4.0", - "optionator": "^0.9.3", - "strip-ansi": "^6.0.1", - "text-table": "^0.2.0" - }, - "bin": { - "eslint": "bin/eslint.js" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/eslint-config-prettier": { - "version": "9.1.2", - "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-9.1.2.tgz", - "integrity": "sha512-iI1f+D2ViGn+uvv5HuHVUamg8ll4tN+JRHGc6IJi4TP9Kl976C57fzPXgseXNs8v0iA8aSJpHsTWjDb9QJamGQ==", - "license": "MIT", - "bin": { - "eslint-config-prettier": "bin/cli.js" - }, - "peerDependencies": { - "eslint": ">=7.0.0" - } - }, - "node_modules/eslint-scope": { - "version": "7.2.2", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-7.2.2.tgz", - "integrity": "sha512-dOt21O7lTMhDM+X9mB4GX+DZrZtCUJPL/wlcTqxyrx5IvO0IYtILdtrQGQp+8n5S0gwSVmOf9NQrjMOgfQZlIg==", - "license": "BSD-2-Clause", - "dependencies": { - "esrecurse": "^4.3.0", - "estraverse": "^5.2.0" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/eslint-visitor-keys": { - "version": "3.4.3", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", - "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", - "license": "Apache-2.0", - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/eslint/node_modules/debug": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", - "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", - "license": "MIT", - "dependencies": { - "ms": "^2.1.3" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/eslint/node_modules/glob-parent": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", - "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", - "license": "ISC", - "dependencies": { - "is-glob": "^4.0.3" - }, - "engines": { - "node": ">=10.13.0" - } - }, - "node_modules/eslint/node_modules/ms": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", - "license": "MIT" - }, - "node_modules/espree": { - "version": "9.6.1", - "resolved": "https://registry.npmjs.org/espree/-/espree-9.6.1.tgz", - "integrity": "sha512-oruZaFkjorTpF32kDSI5/75ViwGeZginGGy2NoOSg3Q9bnwlnmDm4HLnkl0RE3n+njDXR037aY1+x58Z/zFdwQ==", - "license": "BSD-2-Clause", - "dependencies": { - "acorn": "^8.9.0", - "acorn-jsx": "^5.3.2", - "eslint-visitor-keys": "^3.4.1" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/esquery": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.6.0.tgz", - "integrity": "sha512-ca9pw9fomFcKPvFLXhBKUK90ZvGibiGOvRJNbjljY7s7uq/5YO4BOzcYtJqExdx99rF6aAcnRxHmcUHcz6sQsg==", - "license": "BSD-3-Clause", - "dependencies": { - "estraverse": "^5.1.0" - }, - "engines": { - "node": ">=0.10" - } - }, - "node_modules/esrecurse": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", - "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", - "license": "BSD-2-Clause", - "dependencies": { - "estraverse": "^5.2.0" - }, - "engines": { - "node": ">=4.0" - } - }, - "node_modules/estraverse": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", - "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", - "license": "BSD-2-Clause", - "engines": { - "node": ">=4.0" - } - }, - "node_modules/esutils": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", - "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", - "license": "BSD-2-Clause", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/etag": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", - "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/express": { - "version": "4.21.2", - "resolved": "https://registry.npmjs.org/express/-/express-4.21.2.tgz", - "integrity": "sha512-28HqgMZAmih1Czt9ny7qr6ek2qddF4FclbMzwhCREB6OFfH+rXAnuNCwo1/wFvrtbgsQDb4kSbX9de9lFbrXnA==", - "license": "MIT", - "dependencies": { - "accepts": "~1.3.8", - "array-flatten": "1.1.1", - "body-parser": "1.20.3", - "content-disposition": "0.5.4", - "content-type": "~1.0.4", - "cookie": "0.7.1", - "cookie-signature": "1.0.6", - "debug": "2.6.9", - "depd": "2.0.0", - "encodeurl": "~2.0.0", - "escape-html": "~1.0.3", - "etag": "~1.8.1", - "finalhandler": "1.3.1", - "fresh": "0.5.2", - "http-errors": "2.0.0", - "merge-descriptors": "1.0.3", - "methods": "~1.1.2", - "on-finished": "2.4.1", - "parseurl": "~1.3.3", - "path-to-regexp": "0.1.12", - "proxy-addr": "~2.0.7", - "qs": "6.13.0", - "range-parser": "~1.2.1", - "safe-buffer": "5.2.1", - "send": "0.19.0", - "serve-static": "1.16.2", - "setprototypeof": "1.2.0", - "statuses": "2.0.1", - "type-is": "~1.6.18", - "utils-merge": "1.0.1", - "vary": "~1.1.2" - }, - "engines": { - "node": ">= 0.10.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/fast-deep-equal": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", - "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", - "license": "MIT" - }, - "node_modules/fast-glob": { - "version": "3.3.3", - "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", - "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", - "license": "MIT", - "dependencies": { - "@nodelib/fs.stat": "^2.0.2", - "@nodelib/fs.walk": "^1.2.3", - "glob-parent": "^5.1.2", - "merge2": "^1.3.0", - "micromatch": "^4.0.8" - }, - "engines": { - "node": ">=8.6.0" - } - }, - "node_modules/fast-json-stable-stringify": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", - "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", - "license": "MIT" - }, - "node_modules/fast-levenshtein": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", - "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", - "license": "MIT" - }, - "node_modules/fastq": { - "version": "1.19.1", - "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.19.1.tgz", - "integrity": "sha512-GwLTyxkCXjXbxqIhTsMI2Nui8huMPtnxg7krajPJAjnEG/iiOS7i+zCtWGZR9G0NBKbXKh6X9m9UIsYX/N6vvQ==", - "license": "ISC", - "dependencies": { - "reusify": "^1.0.4" - } - }, - "node_modules/file-entry-cache": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz", - "integrity": "sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==", - "license": "MIT", - "dependencies": { - "flat-cache": "^3.0.4" - }, - "engines": { - "node": "^10.12.0 || >=12.0.0" - } - }, - "node_modules/fill-range": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", - "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", - "license": "MIT", - "dependencies": { - "to-regex-range": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/finalhandler": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.1.tgz", - "integrity": "sha512-6BN9trH7bp3qvnrRyzsBz+g3lZxTNZTbVO2EV1CS0WIcDbawYVdYvGflME/9QP0h0pYlCDBCTjYa9nZzMDpyxQ==", - "license": "MIT", - "dependencies": { - "debug": "2.6.9", - "encodeurl": "~2.0.0", - "escape-html": "~1.0.3", - "on-finished": "2.4.1", - "parseurl": "~1.3.3", - "statuses": "2.0.1", - "unpipe": "~1.0.0" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/find-up": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", - "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", - "license": "MIT", - "dependencies": { - "locate-path": "^6.0.0", - "path-exists": "^4.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/flat-cache": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.2.0.tgz", - "integrity": "sha512-CYcENa+FtcUKLmhhqyctpclsq7QF38pKjZHsGNiSQF5r4FtoKDWabFDl3hzaEQMvT1LHEysw5twgLvpYYb4vbw==", - "license": "MIT", - "dependencies": { - "flatted": "^3.2.9", - "keyv": "^4.5.3", - "rimraf": "^3.0.2" - }, - "engines": { - "node": "^10.12.0 || >=12.0.0" - } - }, - "node_modules/flat-cache/node_modules/rimraf": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", - "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", - "deprecated": "Rimraf versions prior to v4 are no longer supported", - "license": "ISC", - "dependencies": { - "glob": "^7.1.3" - }, - "bin": { - "rimraf": "bin.js" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/flatted": { - "version": "3.3.3", - "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.3.tgz", - "integrity": "sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==", - "license": "ISC" - }, - "node_modules/forwarded": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", - "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/fresh": { - "version": "0.5.2", - "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", - "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/fs.realpath": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", - "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", - "license": "ISC" - }, - "node_modules/fsevents": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", - "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" - } - }, - "node_modules/function-bind": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", - "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/get-intrinsic": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", - "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", - "license": "MIT", - "dependencies": { - "call-bind-apply-helpers": "^1.0.2", - "es-define-property": "^1.0.1", - "es-errors": "^1.3.0", - "es-object-atoms": "^1.1.1", - "function-bind": "^1.1.2", - "get-proto": "^1.0.1", - "gopd": "^1.2.0", - "has-symbols": "^1.1.0", - "hasown": "^2.0.2", - "math-intrinsics": "^1.1.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/get-proto": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", - "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", - "license": "MIT", - "dependencies": { - "dunder-proto": "^1.0.1", - "es-object-atoms": "^1.0.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/glob": { - "version": "7.2.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", - "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "deprecated": "Glob versions prior to v9 are no longer supported", - "license": "ISC", - "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - }, - "engines": { - "node": "*" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/glob-parent": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", - "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", - "license": "ISC", - "dependencies": { - "is-glob": "^4.0.1" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/globals": { - "version": "13.24.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-13.24.0.tgz", - "integrity": "sha512-AhO5QUcj8llrbG09iWhPU2B204J1xnPeL8kQmVorSsy+Sjj1sk8gIyh6cUocGmH4L0UuhAJy+hJMRA4mgA4mFQ==", - "license": "MIT", - "dependencies": { - "type-fest": "^0.20.2" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/globby": { - "version": "11.1.0", - "resolved": "https://registry.npmjs.org/globby/-/globby-11.1.0.tgz", - "integrity": "sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==", - "license": "MIT", - "dependencies": { - "array-union": "^2.1.0", - "dir-glob": "^3.0.1", - "fast-glob": "^3.2.9", - "ignore": "^5.2.0", - "merge2": "^1.4.1", - "slash": "^3.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/gopd": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", - "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/graphemer": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz", - "integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==", - "license": "MIT" - }, - "node_modules/has-flag": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", - "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/has-symbols": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", - "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/hasown": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", - "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", - "license": "MIT", - "dependencies": { - "function-bind": "^1.1.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/http-errors": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", - "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", - "license": "MIT", - "dependencies": { - "depd": "2.0.0", - "inherits": "2.0.4", - "setprototypeof": "1.2.0", - "statuses": "2.0.1", - "toidentifier": "1.0.1" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/iconv-lite": { - "version": "0.4.24", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", - "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", - "license": "MIT", - "dependencies": { - "safer-buffer": ">= 2.1.2 < 3" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/ignore": { - "version": "5.3.2", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", - "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", - "license": "MIT", - "engines": { - "node": ">= 4" - } - }, - "node_modules/import-fresh": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", - "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", - "license": "MIT", - "dependencies": { - "parent-module": "^1.0.0", - "resolve-from": "^4.0.0" - }, - "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/imurmurhash": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", - "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", - "license": "MIT", - "engines": { - "node": ">=0.8.19" - } - }, - "node_modules/inflight": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", - "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", - "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", - "license": "ISC", - "dependencies": { - "once": "^1.3.0", - "wrappy": "1" - } - }, - "node_modules/inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "license": "ISC" - }, - "node_modules/ipaddr.js": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", - "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", - "license": "MIT", - "engines": { - "node": ">= 0.10" - } - }, - "node_modules/is-binary-path": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", - "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", - "dev": true, - "license": "MIT", - "dependencies": { - "binary-extensions": "^2.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/is-core-module": { - "version": "2.16.1", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz", - "integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==", - "dev": true, - "license": "MIT", - "dependencies": { - "hasown": "^2.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-extglob": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", - "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/is-glob": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", - "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", - "license": "MIT", - "dependencies": { - "is-extglob": "^2.1.1" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/is-number": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", - "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", - "license": "MIT", - "engines": { - "node": ">=0.12.0" - } - }, - "node_modules/is-path-inside": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz", - "integrity": "sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/isexe": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", - "license": "ISC" - }, - "node_modules/js-yaml": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", - "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", - "license": "MIT", - "dependencies": { - "argparse": "^2.0.1" - }, - "bin": { - "js-yaml": "bin/js-yaml.js" - } - }, - "node_modules/json-buffer": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", - "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", - "license": "MIT" - }, - "node_modules/json-schema-traverse": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", - "license": "MIT" - }, - "node_modules/json-stable-stringify-without-jsonify": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", - "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", - "license": "MIT" - }, - "node_modules/keyv": { - "version": "4.5.4", - "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", - "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", - "license": "MIT", - "dependencies": { - "json-buffer": "3.0.1" - } - }, - "node_modules/levn": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", - "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", - "license": "MIT", - "dependencies": { - "prelude-ls": "^1.2.1", - "type-check": "~0.4.0" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/locate-path": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", - "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", - "license": "MIT", - "dependencies": { - "p-locate": "^5.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/lodash.merge": { - "version": "4.6.2", - "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", - "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", - "license": "MIT" - }, - "node_modules/make-error": { - "version": "1.3.6", - "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", - "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", - "dev": true, - "license": "ISC" - }, - "node_modules/math-intrinsics": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", - "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/media-typer": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", - "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/merge-descriptors": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz", - "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/merge2": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", - "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", - "license": "MIT", - "engines": { - "node": ">= 8" - } - }, - "node_modules/methods": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", - "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/micromatch": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", - "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", - "license": "MIT", - "dependencies": { - "braces": "^3.0.3", - "picomatch": "^2.3.1" - }, - "engines": { - "node": ">=8.6" - } - }, - "node_modules/mime": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", - "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", - "license": "MIT", - "bin": { - "mime": "cli.js" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/mime-db": { - "version": "1.52.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", - "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mime-types": { - "version": "2.1.35", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", - "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", - "license": "MIT", - "dependencies": { - "mime-db": "1.52.0" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", - "license": "ISC", - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, - "node_modules/minimist": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", - "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/mkdirp": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", - "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", - "dev": true, - "license": "MIT", - "bin": { - "mkdirp": "bin/cmd.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", - "license": "MIT" - }, - "node_modules/natural-compare": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", - "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", - "license": "MIT" - }, - "node_modules/negotiator": { - "version": "0.6.3", - "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", - "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/normalize-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", - "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/object-assign": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", - "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/object-inspect": { - "version": "1.13.4", - "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", - "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/on-finished": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", - "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", - "license": "MIT", - "dependencies": { - "ee-first": "1.1.1" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/once": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", - "license": "ISC", - "dependencies": { - "wrappy": "1" - } - }, - "node_modules/optionator": { - "version": "0.9.4", - "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", - "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", - "license": "MIT", - "dependencies": { - "deep-is": "^0.1.3", - "fast-levenshtein": "^2.0.6", - "levn": "^0.4.1", - "prelude-ls": "^1.2.1", - "type-check": "^0.4.0", - "word-wrap": "^1.2.5" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/p-limit": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", - "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", - "license": "MIT", - "dependencies": { - "yocto-queue": "^0.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/p-locate": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", - "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", - "license": "MIT", - "dependencies": { - "p-limit": "^3.0.2" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/parent-module": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", - "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", - "license": "MIT", - "dependencies": { - "callsites": "^3.0.0" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/parseurl": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", - "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/path-exists": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", - "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/path-is-absolute": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/path-key": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", - "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/path-parse": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", - "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", - "dev": true, - "license": "MIT" - }, - "node_modules/path-to-regexp": { - "version": "0.1.12", - "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.12.tgz", - "integrity": "sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ==", - "license": "MIT" - }, - "node_modules/path-type": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz", - "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/pg": { - "version": "8.16.3", - "resolved": "https://registry.npmjs.org/pg/-/pg-8.16.3.tgz", - "integrity": "sha512-enxc1h0jA/aq5oSDMvqyW3q89ra6XIIDZgCX9vkMrnz5DFTw/Ny3Li2lFQ+pt3L6MCgm/5o2o8HW9hiJji+xvw==", - "license": "MIT", - "dependencies": { - "pg-connection-string": "^2.9.1", - "pg-pool": "^3.10.1", - "pg-protocol": "^1.10.3", - "pg-types": "2.2.0", - "pgpass": "1.0.5" - }, - "engines": { - "node": ">= 16.0.0" - }, - "optionalDependencies": { - "pg-cloudflare": "^1.2.7" - }, - "peerDependencies": { - "pg-native": ">=3.0.1" - }, - "peerDependenciesMeta": { - "pg-native": { - "optional": true - } - } - }, - "node_modules/pg-cloudflare": { - "version": "1.2.7", - "resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.2.7.tgz", - "integrity": "sha512-YgCtzMH0ptvZJslLM1ffsY4EuGaU0cx4XSdXLRFae8bPP4dS5xL1tNB3k2o/N64cHJpwU7dxKli/nZ2lUa5fLg==", - "license": "MIT", - "optional": true - }, - "node_modules/pg-connection-string": { - "version": "2.9.1", - "resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.9.1.tgz", - "integrity": "sha512-nkc6NpDcvPVpZXxrreI/FOtX3XemeLl8E0qFr6F2Lrm/I8WOnaWNhIPK2Z7OHpw7gh5XJThi6j6ppgNoaT1w4w==", - "license": "MIT" - }, - "node_modules/pg-int8": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz", - "integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==", - "license": "ISC", - "engines": { - "node": ">=4.0.0" - } - }, - "node_modules/pg-pool": { - "version": "3.10.1", - "resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.10.1.tgz", - "integrity": "sha512-Tu8jMlcX+9d8+QVzKIvM/uJtp07PKr82IUOYEphaWcoBhIYkoHpLXN3qO59nAI11ripznDsEzEv8nUxBVWajGg==", - "license": "MIT", - "peerDependencies": { - "pg": ">=8.0" - } - }, - "node_modules/pg-protocol": { - "version": "1.10.3", - "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.10.3.tgz", - "integrity": "sha512-6DIBgBQaTKDJyxnXaLiLR8wBpQQcGWuAESkRBX/t6OwA8YsqP+iVSiond2EDy6Y/dsGk8rh/jtax3js5NeV7JQ==", - "license": "MIT" - }, - "node_modules/pg-types": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz", - "integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==", - "license": "MIT", - "dependencies": { - "pg-int8": "1.0.1", - "postgres-array": "~2.0.0", - "postgres-bytea": "~1.0.0", - "postgres-date": "~1.0.4", - "postgres-interval": "^1.1.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/pgpass": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz", - "integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==", - "license": "MIT", - "dependencies": { - "split2": "^4.1.0" - } - }, - "node_modules/picomatch": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", - "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", - "license": "MIT", - "engines": { - "node": ">=8.6" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/postgres-array": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz", - "integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==", - "license": "MIT", - "engines": { - "node": ">=4" - } - }, - "node_modules/postgres-bytea": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.0.tgz", - "integrity": "sha512-xy3pmLuQqRBZBXDULy7KbaitYqLcmxigw14Q5sj8QBVLqEwXfeybIKVWiqAXTlcvdvb0+xkOtDbfQMOf4lST1w==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/postgres-date": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz", - "integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/postgres-interval": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz", - "integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==", - "license": "MIT", - "dependencies": { - "xtend": "^4.0.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/prelude-ls": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", - "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", - "license": "MIT", - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/prettier": { - "version": "3.6.2", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.6.2.tgz", - "integrity": "sha512-I7AIg5boAr5R0FFtJ6rCfD+LFsWHp81dolrFD8S79U9tb8Az2nGrJncnMSnys+bpQJfRUzqs9hnA81OAA3hCuQ==", - "license": "MIT", - "bin": { - "prettier": "bin/prettier.cjs" - }, - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/prettier/prettier?sponsor=1" - } - }, - "node_modules/proxy-addr": { - "version": "2.0.7", - "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", - "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", - "license": "MIT", - "dependencies": { - "forwarded": "0.2.0", - "ipaddr.js": "1.9.1" - }, - "engines": { - "node": ">= 0.10" - } - }, - "node_modules/punycode": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", - "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/qs": { - "version": "6.13.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz", - "integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==", - "license": "BSD-3-Clause", - "dependencies": { - "side-channel": "^1.0.6" - }, - "engines": { - "node": ">=0.6" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/queue-microtask": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", - "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/range-parser": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", - "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/raw-body": { - "version": "2.5.2", - "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz", - "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==", - "license": "MIT", - "dependencies": { - "bytes": "3.1.2", - "http-errors": "2.0.0", - "iconv-lite": "0.4.24", - "unpipe": "1.0.0" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/readdirp": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", - "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", - "dev": true, - "license": "MIT", - "dependencies": { - "picomatch": "^2.2.1" - }, - "engines": { - "node": ">=8.10.0" - } - }, - "node_modules/resolve": { - "version": "1.22.11", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.11.tgz", - "integrity": "sha512-RfqAvLnMl313r7c9oclB1HhUEAezcpLjz95wFH4LVuhk9JF/r22qmVP9AMmOU4vMX7Q8pN8jwNg/CSpdFnMjTQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-core-module": "^2.16.1", - "path-parse": "^1.0.7", - "supports-preserve-symlinks-flag": "^1.0.0" - }, - "bin": { - "resolve": "bin/resolve" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/resolve-from": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", - "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", - "license": "MIT", - "engines": { - "node": ">=4" - } - }, - "node_modules/reusify": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", - "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", - "license": "MIT", - "engines": { - "iojs": ">=1.0.0", - "node": ">=0.10.0" - } - }, - "node_modules/rimraf": { - "version": "2.7.1", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz", - "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==", - "deprecated": "Rimraf versions prior to v4 are no longer supported", - "dev": true, - "license": "ISC", - "dependencies": { - "glob": "^7.1.3" - }, - "bin": { - "rimraf": "bin.js" - } - }, - "node_modules/run-parallel": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", - "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "dependencies": { - "queue-microtask": "^1.2.2" - } - }, - "node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/safer-buffer": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", - "license": "MIT" - }, - "node_modules/semver": { - "version": "7.7.3", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", - "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/send": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/send/-/send-0.19.0.tgz", - "integrity": "sha512-dW41u5VfLXu8SJh5bwRmyYUbAoSB3c9uQh6L8h/KtsFREPWpbX1lrljJo186Jc4nmci/sGUZ9a0a0J2zgfq2hw==", - "license": "MIT", - "dependencies": { - "debug": "2.6.9", - "depd": "2.0.0", - "destroy": "1.2.0", - "encodeurl": "~1.0.2", - "escape-html": "~1.0.3", - "etag": "~1.8.1", - "fresh": "0.5.2", - "http-errors": "2.0.0", - "mime": "1.6.0", - "ms": "2.1.3", - "on-finished": "2.4.1", - "range-parser": "~1.2.1", - "statuses": "2.0.1" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/send/node_modules/encodeurl": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", - "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/send/node_modules/ms": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", - "license": "MIT" - }, - "node_modules/serve-static": { - "version": "1.16.2", - "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.2.tgz", - "integrity": "sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==", - "license": "MIT", - "dependencies": { - "encodeurl": "~2.0.0", - "escape-html": "~1.0.3", - "parseurl": "~1.3.3", - "send": "0.19.0" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/setprototypeof": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", - "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", - "license": "ISC" - }, - "node_modules/shebang-command": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", - "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", - "license": "MIT", - "dependencies": { - "shebang-regex": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/shebang-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", - "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/side-channel": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", - "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "object-inspect": "^1.13.3", - "side-channel-list": "^1.0.0", - "side-channel-map": "^1.0.1", - "side-channel-weakmap": "^1.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/side-channel-list": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", - "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "object-inspect": "^1.13.3" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/side-channel-map": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", - "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", - "license": "MIT", - "dependencies": { - "call-bound": "^1.0.2", - "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.5", - "object-inspect": "^1.13.3" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/side-channel-weakmap": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", - "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", - "license": "MIT", - "dependencies": { - "call-bound": "^1.0.2", - "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.5", - "object-inspect": "^1.13.3", - "side-channel-map": "^1.0.1" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/slash": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", - "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/source-map": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", - "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/source-map-support": { - "version": "0.5.21", - "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", - "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", - "dev": true, - "license": "MIT", - "dependencies": { - "buffer-from": "^1.0.0", - "source-map": "^0.6.0" - } - }, - "node_modules/split2": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", - "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==", - "license": "ISC", - "engines": { - "node": ">= 10.x" - } - }, - "node_modules/statuses": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", - "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "license": "MIT", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/strip-bom": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", - "integrity": "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=4" - } - }, - "node_modules/strip-json-comments": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", - "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/supports-color": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", - "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", - "license": "MIT", - "dependencies": { - "has-flag": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/supports-preserve-symlinks-flag": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", - "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/text-table": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", - "integrity": "sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==", - "license": "MIT" - }, - "node_modules/to-regex-range": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", - "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", - "license": "MIT", - "dependencies": { - "is-number": "^7.0.0" - }, - "engines": { - "node": ">=8.0" - } - }, - "node_modules/toidentifier": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", - "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", - "license": "MIT", - "engines": { - "node": ">=0.6" - } - }, - "node_modules/tree-kill": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz", - "integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==", - "dev": true, - "license": "MIT", - "bin": { - "tree-kill": "cli.js" - } - }, - "node_modules/ts-api-utils": { - "version": "1.4.3", - "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-1.4.3.tgz", - "integrity": "sha512-i3eMG77UTMD0hZhgRS562pv83RC6ukSAC2GMNWc+9dieh/+jDM5u5YG+NHX6VNDRHQcHwmsTHctP9LhbC3WxVw==", - "license": "MIT", - "engines": { - "node": ">=16" - }, - "peerDependencies": { - "typescript": ">=4.2.0" - } - }, - "node_modules/ts-node": { - "version": "10.9.2", - "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz", - "integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@cspotcode/source-map-support": "^0.8.0", - "@tsconfig/node10": "^1.0.7", - "@tsconfig/node12": "^1.0.7", - "@tsconfig/node14": "^1.0.0", - "@tsconfig/node16": "^1.0.2", - "acorn": "^8.4.1", - "acorn-walk": "^8.1.1", - "arg": "^4.1.0", - "create-require": "^1.1.0", - "diff": "^4.0.1", - "make-error": "^1.1.1", - "v8-compile-cache-lib": "^3.0.1", - "yn": "3.1.1" - }, - "bin": { - "ts-node": "dist/bin.js", - "ts-node-cwd": "dist/bin-cwd.js", - "ts-node-esm": "dist/bin-esm.js", - "ts-node-script": "dist/bin-script.js", - "ts-node-transpile-only": "dist/bin-transpile.js", - "ts-script": "dist/bin-script-deprecated.js" - }, - "peerDependencies": { - "@swc/core": ">=1.2.50", - "@swc/wasm": ">=1.2.50", - "@types/node": "*", - "typescript": ">=2.7" - }, - "peerDependenciesMeta": { - "@swc/core": { - "optional": true - }, - "@swc/wasm": { - "optional": true - } - } - }, - "node_modules/ts-node-dev": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ts-node-dev/-/ts-node-dev-2.0.0.tgz", - "integrity": "sha512-ywMrhCfH6M75yftYvrvNarLEY+SUXtUvU8/0Z6llrHQVBx12GiFk5sStF8UdfE/yfzk9IAq7O5EEbTQsxlBI8w==", - "dev": true, - "license": "MIT", - "dependencies": { - "chokidar": "^3.5.1", - "dynamic-dedupe": "^0.3.0", - "minimist": "^1.2.6", - "mkdirp": "^1.0.4", - "resolve": "^1.0.0", - "rimraf": "^2.6.1", - "source-map-support": "^0.5.12", - "tree-kill": "^1.2.2", - "ts-node": "^10.4.0", - "tsconfig": "^7.0.0" - }, - "bin": { - "ts-node-dev": "lib/bin.js", - "tsnd": "lib/bin.js" - }, - "engines": { - "node": ">=0.8.0" - }, - "peerDependencies": { - "node-notifier": "*", - "typescript": "*" - }, - "peerDependenciesMeta": { - "node-notifier": { - "optional": true - } - } - }, - "node_modules/tsconfig": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/tsconfig/-/tsconfig-7.0.0.tgz", - "integrity": "sha512-vZXmzPrL+EmC4T/4rVlT2jNVMWCi/O4DIiSj3UHg1OE5kCKbk4mfrXc6dZksLgRM/TZlKnousKH9bbTazUWRRw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/strip-bom": "^3.0.0", - "@types/strip-json-comments": "0.0.30", - "strip-bom": "^3.0.0", - "strip-json-comments": "^2.0.0" - } - }, - "node_modules/type-check": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", - "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", - "license": "MIT", - "dependencies": { - "prelude-ls": "^1.2.1" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/type-fest": { - "version": "0.20.2", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", - "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", - "license": "(MIT OR CC0-1.0)", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/type-is": { - "version": "1.6.18", - "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", - "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", - "license": "MIT", - "dependencies": { - "media-typer": "0.3.0", - "mime-types": "~2.1.24" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/typescript": { - "version": "5.5.4", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.5.4.tgz", - "integrity": "sha512-Mtq29sKDAEYP7aljRgtPOpTvOfbwRWlS6dPRzwjdE+C0R4brX/GUyhHSecbHMFLNBLcJIPt9nl9yG5TZ1weH+Q==", - "license": "Apache-2.0", - "bin": { - "tsc": "bin/tsc", - "tsserver": "bin/tsserver" - }, - "engines": { - "node": ">=14.17" - } - }, - "node_modules/undici-types": { - "version": "6.21.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", - "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/unpipe": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", - "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/uri-js": { - "version": "4.4.1", - "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", - "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", - "license": "BSD-2-Clause", - "dependencies": { - "punycode": "^2.1.0" - } - }, - "node_modules/utils-merge": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", - "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", - "license": "MIT", - "engines": { - "node": ">= 0.4.0" - } - }, - "node_modules/v8-compile-cache-lib": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", - "integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==", - "dev": true, - "license": "MIT" - }, - "node_modules/vary": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", - "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/which": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", - "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "license": "ISC", - "dependencies": { - "isexe": "^2.0.0" - }, - "bin": { - "node-which": "bin/node-which" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/word-wrap": { - "version": "1.2.5", - "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", - "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/wrappy": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", - "license": "ISC" - }, - "node_modules/xtend": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", - "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", - "license": "MIT", - "engines": { - "node": ">=0.4" - } - }, - "node_modules/yn": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", - "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/yocto-queue": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", - "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - } - } -} diff --git a/CollabTableServer/package.json b/CollabTableServer/package.json deleted file mode 100644 index e11a825..0000000 --- a/CollabTableServer/package.json +++ /dev/null @@ -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" - } -} diff --git a/CollabTableServer/routes_test.go b/CollabTableServer/routes_test.go new file mode 100644 index 0000000..4ceed6b --- /dev/null +++ b/CollabTableServer/routes_test.go @@ -0,0 +1,11 @@ +package main + +import ( + "net/http" + "testing" +) + +func TestRegisterRoutes(t *testing.T) { + server := &Server{auth: &AuthService{}} + server.registerRoutes(http.NewServeMux(), webFS) +} diff --git a/CollabTableServer/server.go b/CollabTableServer/server.go new file mode 100644 index 0000000..68fcf72 --- /dev/null +++ b/CollabTableServer/server.go @@ -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)"}, + }, + }) +} diff --git a/CollabTableServer/src/db.ts b/CollabTableServer/src/db.ts deleted file mode 100644 index fe82115..0000000 --- a/CollabTableServer/src/db.ts +++ /dev/null @@ -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; - queryOne(sql: string, params?: Param[]): Promise; - execute(sql: string, params?: Param[]): Promise; - transaction(fn: (tx: DBAdapter) => Promise): Promise; - initialize(): Promise; -} - -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 { - // 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> { - // 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 { - const res = await this.runQuery(sql, params); - return res.rows; - } - - async queryOne(sql: string, params: Param[] = []): Promise { - const res = await this.runQuery(sql, params); - return res.rows[0]; - } - - async execute(sql: string, params: Param[] = []): Promise { - const res = await this.runQuery(sql, params); - return { changes: res.rowCount || 0 }; - } - - async transaction(fn: (tx: DBAdapter) => Promise): Promise { - 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 }; diff --git a/CollabTableServer/src/index.ts b/CollabTableServer/src/index.ts deleted file mode 100644 index 3921c0e..0000000 --- a/CollabTableServer/src/index.ts +++ /dev/null @@ -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; diff --git a/CollabTableServer/src/middleware/auth.ts b/CollabTableServer/src/middleware/auth.ts deleted file mode 100644 index d480970..0000000 --- a/CollabTableServer/src/middleware/auth.ts +++ /dev/null @@ -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(); -} diff --git a/CollabTableServer/src/middleware/device.ts b/CollabTableServer/src/middleware/device.ts deleted file mode 100644 index 96be62a..0000000 --- a/CollabTableServer/src/middleware/device.ts +++ /dev/null @@ -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(); -} diff --git a/CollabTableServer/src/notifications.ts b/CollabTableServer/src/notifications.ts deleted file mode 100644 index 2c38c4f..0000000 --- a/CollabTableServer/src/notifications.ts +++ /dev/null @@ -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?.(); -} diff --git a/CollabTableServer/src/routes/authRoutes.ts b/CollabTableServer/src/routes/authRoutes.ts deleted file mode 100644 index b26ee23..0000000 --- a/CollabTableServer/src/routes/authRoutes.ts +++ /dev/null @@ -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; diff --git a/CollabTableServer/src/routes/fieldRoutes.ts b/CollabTableServer/src/routes/fieldRoutes.ts deleted file mode 100644 index 08fbba3..0000000 --- a/CollabTableServer/src/routes/fieldRoutes.ts +++ /dev/null @@ -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; diff --git a/CollabTableServer/src/routes/itemRoutes.ts b/CollabTableServer/src/routes/itemRoutes.ts deleted file mode 100644 index acf8c0c..0000000 --- a/CollabTableServer/src/routes/itemRoutes.ts +++ /dev/null @@ -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; diff --git a/CollabTableServer/src/routes/listRoutes.ts b/CollabTableServer/src/routes/listRoutes.ts deleted file mode 100644 index bfcaa52..0000000 --- a/CollabTableServer/src/routes/listRoutes.ts +++ /dev/null @@ -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; diff --git a/CollabTableServer/src/routes/notificationRoutes.ts b/CollabTableServer/src/routes/notificationRoutes.ts deleted file mode 100644 index 667209f..0000000 --- a/CollabTableServer/src/routes/notificationRoutes.ts +++ /dev/null @@ -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; diff --git a/CollabTableServer/src/routes/syncRoutes.ts b/CollabTableServer/src/routes/syncRoutes.ts deleted file mode 100644 index a02d3a2..0000000 --- a/CollabTableServer/src/routes/syncRoutes.ts +++ /dev/null @@ -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 = 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(); - let existingFieldIds = new Set(); - const fieldToList: Record = {}; - 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; diff --git a/CollabTableServer/src/routes/webRoutes.ts b/CollabTableServer/src/routes/webRoutes.ts deleted file mode 100644 index 827e291..0000000 --- a/CollabTableServer/src/routes/webRoutes.ts +++ /dev/null @@ -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; - devDependencies?: Record; -} - -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(); - for (const it of formattedItems as any[]) { - if (it && it.id && it.listId) itemIdToListId.set(it.id, it.listId); - } - const listToMaxField = new Map(); - 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(); - 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(); - 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; diff --git a/CollabTableServer/sync.go b/CollabTableServer/sync.go new file mode 100644 index 0000000..8dba43b --- /dev/null +++ b/CollabTableServer/sync.go @@ -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(), + }) +} diff --git a/CollabTableServer/sync_test.go b/CollabTableServer/sync_test.go new file mode 100644 index 0000000..2a650e3 --- /dev/null +++ b/CollabTableServer/sync_test.go @@ -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) + } +} diff --git a/CollabTableServer/tsconfig.json b/CollabTableServer/tsconfig.json deleted file mode 100644 index 6d52522..0000000 --- a/CollabTableServer/tsconfig.json +++ /dev/null @@ -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"] -} diff --git a/CollabTableServer/web.go b/CollabTableServer/web.go new file mode 100644 index 0000000..e003af9 --- /dev/null +++ b/CollabTableServer/web.go @@ -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()}) +} diff --git a/CollabTableServer/web/.gitkeep b/CollabTableServer/web/.gitkeep new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/CollabTableServer/web/.gitkeep @@ -0,0 +1 @@ + diff --git a/CollabTableServer/webui/src/routes/+layout.js b/CollabTableServer/webui/src/routes/+layout.js index e14246f..2ebd9bc 100644 --- a/CollabTableServer/webui/src/routes/+layout.js +++ b/CollabTableServer/webui/src/routes/+layout.js @@ -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; diff --git a/CollabTableServer/webui/svelte.config.js b/CollabTableServer/webui/svelte.config.js index b54e381..3fb87b1 100644 --- a/CollabTableServer/webui/svelte.config.js +++ b/CollabTableServer/webui/svelte.config.js @@ -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', diff --git a/README.md b/README.md index 33bee20..85a31b9 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![Android](https://img.shields.io/badge/Android-26%2B-green.svg)](https://android.com) -[![Node.js](https://img.shields.io/badge/Node.js-20%2B-brightgreen.svg)](https://nodejs.org) +[![Go](https://img.shields.io/badge/Go-1.26%2B-00ADD8.svg)](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=` - 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