# Workshare: analysis and production gap report

Scope: `WorkshareServer.zip` (Node server 0.2.0) and `Workshare_7.zip` (Unity client + patched project files).
Date: 21 Nov 2026. Goal: move from the local dev server to a real, internet-facing server.
**Audience: customers of the home designer app (Kavion), not an internal team.** Section 0 says what that changes.

---

## 0. Customers, not a team: what changes

The server was designed for a trusted team: whoever has a join code is a member, the person who created a model is
its only admin, and the key sits in PlayerPrefs on one PC. With **customers** using a shipped app over the internet,
these assumptions break:

| Area | Team assumption (today) | Customer reality | Consequence |
|---|---|---|---|
| **Identity** | Join code + member key per PC | Customers reinstall, change PCs, forget things, share codes | **Customer accounts are required (P0).** A lost PC today = the customer loses admin of their own house. Members must be tied to the Kavion account login (JWT from your login backend), not to a key file |
| **Who may create models** | Anyone (or the create token) | Every customer creates models | The **create token from the kit doesn't work for customers**: it would be built into the app and anyone can extract it. Creation must be allowed per signed-in account, with **quotas** (models, storage, versions per account / plan) |
| **Network** | Office or internet | Always internet, customers' home networks | **Office-only (LAN) setup is not an option.** Domain + HTTPS + ports 80/443 required. Strongly recommended: **Cloudflare in front** (hides the server IP, absorbs DDoS) |
| **Scale** | Up to 50 members, 500 models per server (hard-coded) | Hundreds or thousands of customers | `maxModels: 500` is a hard ceiling for the whole company: must become a config value + per-account quota. **The 6 s sync freeze (#10) becomes P0**: one customer syncing a big house freezes every other customer |
| **Storage cost** | Full 20 MB copy per version is fine | Customers × versions × MB, paid by you | **Version compression + pruning (#13) becomes P1**: gzip alone shrinks versions ~10×; keep e.g. last 50 + daily snapshots |
| **Personal data and the law** | Internal data | Customers' home floor plans, names, possibly addresses | India's **DPDP Act 2023** applies: privacy policy and consent in the app, **delete my data** (account + models + backups within retention), **export my data**, breach procedure, data stays where you declare. Get a legal check. |
| **Abuse** | Colleagues behave | Some users will not | Per-account limits, upload size limits (exist), deny-list accounts, and logs that identify the account (not just IP) |
| **Support** | Ask the colleague | Your support team gets the tickets | An **admin/support console** (find a customer's models, restore a version, reset access) instead of SSH to the server |
| **App versions** | Everyone updates together | Customers run old app versions for months | **API versioning**: the app sends its version (`X-App-Version`); the server refuses too-old clients with a clear "please update" message instead of failing strangely |
| **Availability** | Office hours, someone nearby | 24/7, customers notice outages | Uptime monitoring + alerting, off-site backups **tested**, a written restore procedure, planned-maintenance message |

### Re-prioritised gap list for customers

| Priority | Gap (# from section 2) | Status |
|---|---|---|
| **P0** | Customer accounts: verify the Kavion login on every request; member = account; model creation per account (#9, replaces join-code-only identity and the create token) | **Built in 0.9.0** (`WORKSHARE_KAVION_AUTH`); switch on after `tools/kavion-login-check.js` confirms the real API |
| **P0** | Sync off the main thread (#10): worker threads + per-model queue | **Done in 0.4.0** |
| **P0** | Quotas per account (models, MB, versions); `maxModels` configurable | `WORKSHARE_MAX_MODELS` and `WORKSHARE_MAX_MODELS_PER_ACCOUNT` **done**; storage per account later |
| **P0** | HTTPS on a real domain, Cloudflare in front (#1) | Kit ready (internet mode only) |
| **P0** | Off-site backups, tested restore (#6) | Script ready; destination needed |
| **P1** | Delete-my-data and export-my-data endpoints, privacy policy, retention rules (DPDP) | Open |
| **P1** | Version compression at rest + pruning (#13) | **Done in 0.5.0** |
| **P1** | App version check (`X-App-Version`, minimum supported version) | **Done in 0.6.0** (server + Unity banner) |
| **P1** | **Windows installer** (today only a build folder): Start menu, uninstall, update-in-place | **Done**: Inno Setup script (`UnityInstaller/`) |
| **P1** | **Code signing** of the exe and installer (SmartScreen warning otherwise) | **Decision**: buy an OV/EV certificate for the company |
| **P1** | Monitoring and alerts on `/ready`, disk, error rate (#15) | Partly done |
| **P1** | Admin promote / key reset buttons in the Unity Team tab (#5) | Server done; becomes less important once accounts exist |
| **P2** | Support console (web, staff only) | Open |
| **P1** | Customer data in a database (PostgreSQL): models, members, ownership, history, requests | **Done in 0.7.0** |
| **P2** | Push updates instead of polling (#12), soft delete (#17) | **Done in 0.8.0** |
| **P2** | Audit log (#18) | **Done in 0.7.0** (`audit_log` table; `audit.jsonl` in file mode) |
| **Later** | More than one server (#14): only needed at real scale (object storage + per-model locks; Postgres is in) | Accepted for launch |

**Already OK for customers:** the sync rules, ownership and review logic, HTTPS / proxy / rate-limit handling, gzip,
logs, graceful restarts, backups script, and the Linux installer (internet mode).

---

## 1. What you have

**Server (Node 18+, zero dependencies, ~1,900 lines + 670 lines of tests).**

| File | Role | Quality |
|---|---|---|
| `src/workshare.js` | Pure sync rules: three-way `integrate()` (central / base / local), change sets, dependency grouping for review, patch plans | Strong. Pure, tested (73 checks), deterministic |
| `src/floormap.js` | Floor map model: 13 categories (10 floor map + Wall + Furniture + Appliance), element identity (guid > uniqueID > id), derived-field stripping | Strong |
| `src/central.js` | Store: models, members, worksets, borrows, sync, reload, requests, history, restore, review mode | Good. Synchronous fs, in-memory index |
| `src/http.js` | Routes, `X-Member-Key`, per-IP rate limits, Origin refusal | Dev-grade (see gaps) |
| `src/server.js` | `http.createServer`, binds 127.0.0.1 | Dev-grade |

**Client (Unity C#, ~3,400 lines).** `WorkshareController` (logic, polling `GetState` every 10 s), `WorkshareClient`
(UnityWebRequest coroutines), `WorkshareView` (UI Toolkit panel), `WorkshareGate`/`WorkshareHooks` (ownership checks
wired into 8 patched project scripts), `WorkshareMapIO` (patch vs rebuild), `WorkshareReviewOverlay`, `WorkshareLayers`.

**Data model on disk (per model):** `model.json` (meta: members with SHA-256 key hashes, worksets, borrows,
elementVersion, requests, versions, submissions), `v<N>.json` (full map per version), `h<N>.json` (diff), `s-<id>.json`
(review submissions). Writes are atomic (temp file + rename).

**Security posture already good:** keys stored as hashes and compared in constant time; keys in headers, never URLs;
join codes 10 chars / ~50 bits; body size limits; control-char stripping; browser Origin refusal; brute-force counter.

**Verified:** all existing tests pass (73 + 94) on Node 22.

### Housekeeping found in the archives
- `WorkshareServer/WorkshareServer/` is a byte-identical nested copy of the project. Delete it.
- `data/models/` (5 real dev models) is shipped inside the zip although `.gitignore` excludes it. Do not deploy it;
  if those models matter, copy them to the server's volume deliberately.

---

## 2. Gaps for a real server

Severity: **P0** blocks going live, **P1** needed for a team in daily use, **P2** scale / polish.
Status: **Filled** = done in the production kit delivered with this report; **Decision** = needs your choice;
**Open** = design work left.

| # | Gap | Sev | Why it matters | Status |
|---|---|---|---|---|
| 1 | **No TLS.** Plain HTTP; Unity needs "Allow downloads over HTTP" | P0 | Member keys (admin rights) and full floor maps travel in clear text over the internet | **Filled**: Caddy (auto Let's Encrypt) or nginx+certbot in `deploy/`; client defaults to https and warns on public http |
| 2 | **Rate limit by socket address breaks behind any proxy** | P0 | Behind Caddy/nginx/LB every request comes from the proxy IP: 300 req/min total for *everyone*, and 20 wrong keys from anyone locks out *all users* | **Filled**: `WORKSHARE_TRUST_PROXY` + `PROXY_HOPS` read the real address from `X-Forwarded-For` (rightmost-N, unforgeable) |
| 3 | **Office NAT = one user.** 10 s polling × 50 members = 300 req/min from one office IP, exactly the old limit, before any sync/borrow | P0 | Normal team use gets 429 errors | **Filled**: valid members are limited per key (600/min); per-address limit only applies to key-less calls; a key-guesser at the office address no longer blocks valid colleagues |
| 4 | **Anyone who reaches the server can create models** (up to 500, 20 MB each = 10 GB) | P0 | Open disk-filling endpoint on the internet | **Filled**: `WORKSHARE_CREATE_TOKEN` (header `X-Create-Token`) or `WORKSHARE_ALLOW_CREATE=0`. **Decision** for the long term: tie to Kavion accounts (#9) |
| 5 | **Lost admin key = orphaned model.** Only the creator is admin, no transfer, no key recovery; keys live only in one PC's PlayerPrefs | P0 | Reinstall / new PC and nobody can restore, review, or manage the model again | **Filled**: `POST members/:mid/admin` (promote/demote, last admin protected), `POST members/:mid/reset-key`. UI buttons still to add in `WorkshareView` (Team tab) |
| 6 | **No backups.** Single directory on one disk | P0 | One disk failure loses every model and its history | **Filled**: `deploy/backup.sh` (online, order-consistent, retention, optional rclone to Cloudflare R2/S3). Schedule it with cron |
| 7 | **No deployment artefacts / config.** Hard-coded defaults, plain `console.log`, no graceful stop | P1 | Not runnable as a service; logs not usable | **Filled**: `src/config.js` (all env vars, validated), JSON logs with request ids, `/ready`, graceful SIGTERM (open syncs finish), Dockerfile (non-root, healthcheck), compose, systemd unit with sandboxing |
| 8 | **Large transfers uncompressed.** Every sync uploads and downloads the full map (up to 20 MB each way) | P1 | Slow on home/office uplinks; timeouts at 120 s | **Filled**: gzip both ways (bomb-safe), client timeout raised to 300 s to match the server |
| 9 | **Identity = join code + bearer key in PlayerPrefs.** No accounts, no SSO, keys in plain text in the Windows registry | P1 | No way to know who a member really is, revoke a person across models, or meet a customer's IT policy | **Filled (0.9.0)**: the Kavion login (mobile + login token) is checked with parent.globalinfocloud.in; members are bound to the account; keys only work with their owner's login (`required`); Find my models / device keys on a new PC |
| 10 | **A big sync freezes everyone.** Measured: 1.8 MB map → 0.5 s, 18 MB map → **6.0 s** of blocked event loop per sync; all other users' polls wait | P1 | With several people syncing large houses, the panel stalls for everyone | **Filled (0.4.0)**: worker-thread pool, each worker owns a share of the models and serializes them. While one model ran a 2.1 s sync, another answered in ≤ 43 ms. Benefit scales with workers: use 4 vCPU / 8 GB |
| 11 | **Unsafe automatic retry did not exist; naive retry would be dangerous** | P1 | A repeated POST /sync could run twice | **Filled**: client retries only when the server surely did not run it (429 / 502 / 503; GET also on connection errors / 504), with backoff and `Retry-After` |
| 12 | **Polling instead of push.** Every client asks every 10 s | P2 | Load grows linearly with members; changes appear late | **Filled (0.8.0)**: Server-Sent Events `GET /models/:id/events` after each commit (~25 ms to reach others), polling stays as fallback (60 s while live) |
| 13 | **Full copy per version.** 1,000 versions × 20 MB = up to 20 GB per model; model becomes read-only at version 1,000 | P2 | Disk use; hard stop for long projects | **Filled (0.5.0)**: gzip at rest (~10x on real maps), retention keeps newest 50 + 30 daily restore points + version 1 + every member's base; the limit counts stored versions only. ~16 MB per model for a 2 MB house |
| 14 | **Single process, local disk.** Cannot run two replicas | P2 | No high availability; deploys have ~1 s downtime | **Accepted** for now (documented). Postgres for the records is in (0.7.0); HA still needs object storage for versions + per-model locks across processes |
| 15 | **No monitoring / alerts** | P2 | You learn about outages from users | **Partly filled**: `/health`, `/ready`, structured logs. **Open**: uptime check (UptimeRobot / Better Stack) on `/ready`, disk-space alert |
| 16 | **`/health` exposed the model count** | P2 | Minor information leak | **Filled**: hidden unless `WORKSHARE_PUBLIC_STATS=1` |
| 17 | **Delete model is immediate `rm -rf`** | P2 | An admin mis-click destroys history (backups are the only way back) | **Filled (0.8.0)**: trash for `WORKSHARE_TRASH_DAYS` (30), admin undelete, `?purge=1` for delete-forever, hourly purge |
| 18 | **Removed members' data and audit** | P2 | No audit log of admin actions (restore, remove, trust, review mode) | **Filled (0.7.0)**: `audit_log` table (action, member, client address, never keys) for create, join, admin, trust, key reset, remove, join code, review mode, restore, review, grant, delete; `audit.jsonl` in file mode. Retention `WORKSHARE_AUDIT_DAYS` (365) **filled in 0.8.0** |
| 19 | **Client-side key storage** | P2 | Keys readable by anything running as that Windows user | **Open**: Windows DPAPI via a small native plugin, or solved by #9 (short-lived tokens) |
| 20 | **No certificate pinning** | P2 | Only relevant against a compromised CA / corporate MITM | Optional; standard TLS validation is enough for most |

---

## 3. What is in the production kit

```
WorkshareServer/                       (server 0.3.0, drop-in replacement, data format unchanged)
  src/config.js            NEW   every setting from the environment, validated, documented
  src/http.js              CHANGED  proxy-aware client address, per-member limits, gzip in/out, request ids,
                                    /ready, create token / lock, admin + reset-key routes, access log
  src/server.js            CHANGED  structured logs (text/json), graceful shutdown, socket timeouts tuned for a proxy
  src/central.js           CHANGED  + isMember(), setAdmin(), resetMemberKey()   (sync rules untouched)
  test/production-test.js  NEW   30 checks: NAT office, key guessing, gzip, create lock, admins, health
  Dockerfile, .dockerignore NEW
  deploy/docker-compose.yml, Caddyfile, .env.example, nginx.conf, workshare.service, backup.sh   NEW
UnityClientPatch/
  WorkshareClient.cs       replaces Runtime/WorkshareClient.cs (same public API + SetAdmin / ResetMemberKey)
  WorkshareModelsProd.cs   add to Runtime/ (types for the two new calls)
  WorkshareClient.diff     exactly what changed
```

Tests: 197 pass (73 rules + 94 store/HTTP + 30 production). Existing models on disk load unchanged.

---

## 4. Go-live checklist (Docker on a VM, ~1 hour)

1. **Server**: any Linux VM with 2 vCPU / 4 GB RAM / 40 GB SSD (Hetzner, DigitalOcean, AWS Lightsail, Azure B2s).
   Install Docker. Open ports 80 and 443 only.
2. **DNS**: `A` record `workshare.globalinfocloud.in` → the VM's IP. (With Cloudflare, start with DNS-only/grey cloud;
   orange cloud needs `WORKSHARE_PROXY_HOPS=2` and Caddy `trusted_proxies` set to Cloudflare's ranges.)
3. Copy `WorkshareServer/` to the VM, `cd deploy && cp .env.example .env`, set `WORKSHARE_DOMAIN`, `ACME_EMAIL`,
   and a long random `WORKSHARE_CREATE_TOKEN` (`openssl rand -base64 32`).
4. `docker compose up -d --build`, then `curl https://workshare.globalinfocloud.in/ready` → `{"ok":true}`.
5. **Backups**: cron `deploy/backup.sh` daily with `RCLONE_REMOTE` pointing at an R2/S3 bucket. Test one restore.
6. **Unity**: replace `WorkshareClient.cs`, add `WorkshareModelsProd.cs`; set `WorkshareController.defaultServerUrl`
   to `https://workshare.globalinfocloud.in`; set `WorkshareClient.CreateToken` from your config at startup;
   set "Allow downloads over HTTP" back to **Not allowed**.
7. **Existing dev models** (optional): copy `data/models/<id>/` folders into the volume
   (`docker compose cp`), restart. Members keep their keys; their saved connections point at the old address, so
   they re-open via the new address (same model id + key) or re-join with the join code.
8. **Monitoring**: uptime check on `https://workshare.globalinfocloud.in/ready` every minute; alert on disk > 80 %.
9. **Admins**: in every model, promote a second admin (new endpoint) before anything else.

---

## 5. Decisions needed from you

1. **Customer login**: does the Kavion app already have accounts? Which system (your own backend, Firebase Auth,
   Auth0 / Keycloak / Cognito, Azure AD B2C, other)? The server needs to verify its tokens.
2. **Who works together in one model**: customer + your designer / sales staff? customer + family? customer only,
   across their own PCs? This decides roles (and whether review mode means "the designer approves the customer's changes").
3. **Expected scale at launch and in a year**: number of customers, how many work at the same time, typical house size (MB).
4. **Plans / pricing**: are limits per plan (free vs paid)? This sets the quotas.
5. **Where customer data may be stored** (India only? which provider?) and who handles the privacy policy.
