Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
.git
.context
**/node_modules
**/dist
**/.turbo
**/.wrangler
**/.expo
**/.tanstack
**/coverage
**/.env*
**/*.env
**/*.env.*
**/.dev.vars*
**/*.pem
**/*.p8
**/*.log
apps/mobile
.local
.DS_Store
22 changes: 22 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ jobs:
- name: Build
run: pnpm build

- name: Bundle Node API
run: pnpm --filter @opensociety/api build:node

- name: Type-check
run: pnpm check-types

Expand All @@ -44,3 +47,22 @@ jobs:

- name: Test
run: pnpm test

hosting:
name: Hosting containers
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
- name: Build API image
run: docker build --target api -t opensociety-api:test .
- name: Build staging web image
run: |
docker build --target web -t opensociety-web:test \
--build-arg DEPLOY_ENV=staging \
--build-arg VITE_API_URL=https://api.example.com \
--build-arg VITE_CLERK_PUBLISHABLE_KEY=pk_test_ZXhhbXBsZS5jb20k .
- name: Smoke-test containers without external services
run: node --test scripts/hosting-smoke.test.mjs
44 changes: 44 additions & 0 deletions .github/workflows/containers.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
name: Build hosting images

on:
workflow_dispatch:
inputs:
environment:
description: GitHub environment holding API_ORIGIN and CLERK_PUBLISHABLE_KEY variables
type: choice
options: [staging, production]
required: true
default: staging

permissions:
contents: read
packages: write

jobs:
images:
runs-on: ubuntu-latest
environment: ${{ inputs.environment }}
strategy:
matrix:
target: [api, web]
steps:
- uses: actions/checkout@v4
- uses: docker/setup-buildx-action@v3
- uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- uses: docker/build-push-action@v6
with:
context: .
target: ${{ matrix.target }}
platforms: linux/amd64
push: true
tags: ghcr.io/${{ github.repository }}-${{ matrix.target }}:${{ inputs.environment }}-${{ github.sha }}
build-args: |
DEPLOY_ENV=${{ inputs.environment }}
VITE_API_URL=${{ vars.API_ORIGIN }}
VITE_CLERK_PUBLISHABLE_KEY=${{ vars.CLERK_PUBLISHABLE_KEY }}
cache-from: type=gha,scope=${{ matrix.target }}-${{ inputs.environment }}
cache-to: type=gha,mode=max,scope=${{ matrix.target }}-${{ inputs.environment }}
46 changes: 46 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# syntax=docker/dockerfile:1
FROM node:22-bookworm-slim AS build
ENV PNPM_HOME=/pnpm
ENV PATH=$PNPM_HOME:$PATH
RUN corepack enable && corepack prepare pnpm@10.0.0 --activate
WORKDIR /repo
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
COPY packages ./packages
COPY apps/api ./apps/api
COPY apps/web ./apps/web
RUN --mount=type=cache,id=pnpm,target=/pnpm/store pnpm --filter @opensociety/api... --filter @opensociety/web... install --frozen-lockfile
RUN pnpm --filter @opensociety/shared build && pnpm --filter @opensociety/db build

FROM build AS api-build
RUN pnpm --filter @opensociety/api build && pnpm --filter @opensociety/api build:node

FROM node:22-bookworm-slim AS api
ENV NODE_ENV=production HOST=0.0.0.0 PORT=8787
WORKDIR /app
COPY --from=api-build --chown=node:node /repo/apps/api/dist/node.mjs ./node.mjs
USER node
EXPOSE 8787
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s CMD node -e "fetch('http://127.0.0.1:8787/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
CMD ["node", "node.mjs"]

FROM build AS web-build
ARG DEPLOY_ENV=production
ARG VITE_API_URL
ARG VITE_CLERK_PUBLISHABLE_KEY
ENV DEPLOY_ENV=$DEPLOY_ENV VITE_API_URL=$VITE_API_URL VITE_CLERK_PUBLISHABLE_KEY=$VITE_CLERK_PUBLISHABLE_KEY
# pnpm 10.0's portable deploy requires injection in both config and lockfile.
# Change only that setting in the container; keep every resolved version pinned.
RUN pnpm --filter @opensociety/web build \
&& sed -i '/^settings:/a\ injectWorkspacePackages: true' pnpm-lock.yaml \
&& pnpm --config.inject-workspace-packages=true --filter @opensociety/web deploy --prod /web

FROM node:22-bookworm-slim AS web
ENV NODE_ENV=production HOST=0.0.0.0 PORT=3000
WORKDIR /app
COPY --from=web-build --chown=node:node /web/node_modules ./node_modules
COPY --from=web-build --chown=node:node /repo/apps/web/package.json /repo/apps/web/server.mjs ./
COPY --from=web-build --chown=node:node /repo/apps/web/dist ./dist
USER node
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s CMD node -e "fetch('http://127.0.0.1:3000/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
CMD ["node", "server.mjs"]
30 changes: 17 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
- Mobile: [Expo](https://expo.dev) Router (React Native, SDK 57) + TanStack Query

**Backend:**
- API: [Hono](https://hono.dev) on [Cloudflare Workers](https://workers.cloudflare.com)
- API: [Hono](https://hono.dev) on Node 22 for shared hosting; Cloudflare Workers adapter also available
- Database: [Neon Postgres](https://neon.tech) via [Drizzle ORM](https://orm.drizzle.team) (neon-http driver)
- Shared contracts: Zod (`@opensociety/shared`)

Expand All @@ -31,7 +31,7 @@ See `BLOCKING_DECISIONS.md` (in the Obsidian notes) for the rationale behind ten

```
apps/
api Hono API on Cloudflare Workers (wrangler)
api Hono API with Node and Cloudflare Workers adapters
web TanStack Start admin dashboard
mobile Expo Router app (residents + guards)
packages/
Expand All @@ -42,26 +42,30 @@ packages/

## Quickstart

Use Node 22 and the pinned pnpm 10 workspace install. Local development runs directly on the Mac; Docker builds and container checks run in GitHub Actions.

```sh
pnpm install --frozen-lockfile
cp apps/api/.env.example apps/api/.env
cp apps/web/.env.example apps/web/.env
# Fill in the development Neon/Clerk values, then start both applications:
pnpm dev
```
pnpm install
pnpm check-types # type-check all packages
pnpm --filter @opensociety/db db:generate # generate a migration from the schema
pnpm --filter @opensociety/api dev # wrangler dev (needs apps/api/.dev.vars)
pnpm --filter @opensociety/web dev # http://localhost:3000
```

Then open the admin dashboard at **http://localhost:3000/admin**.
Turborepo builds the shared and database packages before starting the Node API on port 8787 and the web dashboard on port 3000. Its watcher rebuilds workspace dependencies and restarts affected applications when files change. Open **http://localhost:3000/admin**. Start the mobile app separately with `pnpm --filter @opensociety/mobile start` when needed.

Run `pnpm build`, `pnpm check-types`, `pnpm lint`, and `pnpm test` from the root. These reuse the workspace install and Turbo cache. `pnpm --filter @opensociety/api dev:worker` remains available for the Workers adapter.

### Environment

Copy the example env files and fill in real values (all are gitignored):

```
cp apps/api/.dev.vars.example apps/api/.dev.vars # DATABASE_URL, CLERK_* (API)
cp apps/web/.env.example apps/web/.env # VITE_API_URL, VITE_DEV_USER_ID (web)
cp apps/api/.env.example apps/api/.env # DATABASE_URL, CLERK_* (Node API)
cp apps/web/.env.example apps/web/.env # VITE_API_URL, VITE_CLERK_PUBLISHABLE_KEY
```

Per-society secrets (`DATABASE_URL`, `CLERK_*`, R2) go in `apps/api/.dev.vars` for local dev and `wrangler secret put` for production. See `.env.example` for the full list.
Per-society secrets (`DATABASE_URL`, `CLERK_*`, R2) go in `apps/api/.dev.vars` for local Workers development. Node hosting uses runtime environment variables. See [the deployment guide](deploy/README.md) for container builds, configuration, migrations, scheduled jobs, and rollback.

Clerk sessions authenticate web and mobile requests. The API accepts the local `x-user-id` fallback only when no Clerk secret is configured. Keep development identity overrides out of preview and store builds.

Expand Down Expand Up @@ -101,7 +105,7 @@ Configure this app's APNs credential in EAS for iOS. For Android, configure the

Before pilot distribution, verify on physical iOS and Android devices: permission grant/denial; foreground/background/cold-start notification taps; resident and guard event routing; tower targeting; partial/paid/cancelled bill reminders; token refresh; sign-out and account switching. Database integration tests cover queue claims, deduplication, retries, receipts, account reassignment, and dead-token removal; they do not prove delivery through APNs/FCM.

Hosting is not provisioned by these changes. The current API adapter targets Workers/R2/Queues; the shared hosting plan is a DigitalOcean Droplet. Reconcile that deployment adapter, scheduled jobs, and storage before enabling a public backend. Store profiles also need the deployed HTTPS API and live Clerk configuration.
The shared DigitalOcean Droplet is not provisioned yet. A Node API adapter, web server, R2 S3 adapter, restart recovery, and container configuration are prepared in [the deployment guide](deploy/README.md). Store profiles still need the deployed HTTPS API and live Clerk configuration.

## Admin dashboard

Expand Down
17 changes: 17 additions & 0 deletions apps/api/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Local Node API. Copy to .env and use your development Neon branch.
# This placeholder supports /health but cannot serve database-backed routes.
DATABASE_URL=postgresql://test:test@localhost/test
WEB_ORIGINS=http://localhost:3000,http://localhost:8081
BILLING_ENABLED=false
PUSH_ENABLED=false

# Use the same Clerk instance as the web/mobile client.
# CLERK_SECRET_KEY=sk_test_...
# CLERK_PUBLISHABLE_KEY=pk_test_...
# CLERK_WEBHOOK_SECRET=whsec_...

# Optional for local development; required to exercise uploads against R2.
# R2_ACCOUNT_ID=
# R2_BUCKET_NAME=opensociety-uploads
# R2_ACCESS_KEY_ID=
# R2_SECRET_ACCESS_KEY=
7 changes: 7 additions & 0 deletions apps/api/build-node.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { build } from 'esbuild'

await build({
entryPoints: ['src/node/server.ts'], outfile: 'dist/node.mjs', bundle: true,
platform: 'node', target: 'node22', format: 'esm',
banner: { js: "import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);" },
})
12 changes: 10 additions & 2 deletions apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,20 @@
"private": true,
"type": "module",
"scripts": {
"dev": "wrangler dev",
"dev": "tsx --env-file-if-exists=.env src/node/server.ts",
"deploy": "wrangler deploy",
"build": "tsc --noEmit",
"check-types": "tsc --noEmit",
"lint": "eslint .",
"test": "vitest run"
"test": "vitest run",
"build:node": "node build-node.mjs",
"start": "node dist/node.mjs",
"dev:worker": "wrangler dev"
},
"dependencies": {
"@aws-sdk/client-s3": "^3.1145.0",
"@clerk/backend": "^1.21.0",
"@hono/node-server": "^2.1.3",
"@hono/zod-validator": "^0.4.2",
"@opensociety/db": "workspace:*",
"@opensociety/shared": "workspace:*",
Expand All @@ -26,7 +31,10 @@
"@cloudflare/workers-types": "^4.20240512.0",
"@electric-sql/pglite": "^0.5.8",
"@opensociety/eslint-config": "workspace:*",
"@types/node": "^22.10.2",
"esbuild": "^0.28.2",
"eslint": "^9.18.0",
"tsx": "^4.19.2",
"typescript": "^5.7.2",
"vitest": "^3.0.5",
"wrangler": "^3.99.0"
Expand Down
95 changes: 95 additions & 0 deletions apps/api/src/billing-postgres.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import { afterAll, beforeAll, beforeEach, expect, it } from 'vitest'
import { readFileSync } from 'node:fs'
import { randomUUID } from 'node:crypto'
import { PGlite } from '@electric-sql/pglite'
import { drizzle } from 'drizzle-orm/pglite'
import { accounts, apartments, billLineItems, journalEntries, journalLines, maintenanceBills, type Database } from '@opensociety/db'
import { insertJournalEntry, postMonthlyBills } from './lib/ledger-posting'
import { generateMonthlyBills } from './lib/generate-bills'

const postgres = new PGlite()
const pg = drizzle(postgres)
const db = pg as unknown as Database
const options = {
periodMonth: '2026-10', title: 'October maintenance', dueDate: new Date('2026-10-10T00:00:00Z'),
lineItems: [{ description: 'Maintenance', amount: 10000, taxRatePct: 18 }],
}

beforeAll(async () => {
const directory = new URL('../../../packages/db/drizzle/', import.meta.url)
const journal = JSON.parse(readFileSync(new URL('meta/_journal.json', directory), 'utf8'))
for (const entry of journal.entries) await postgres.exec(readFileSync(new URL(`${entry.tag}.sql`, directory), 'utf8'))
}, 30_000)
afterAll(async () => postgres.close())
beforeEach(async () => { await postgres.exec('TRUNCATE apartments, accounts, journal_entries CASCADE') })

it('generates complete monthly bills for 1,000 apartments and safely repeats a run', async () => {
await pg.insert(apartments).values(Array.from({ length: 1000 }, (_, i) => ({ tower: 'A', apartmentNo: String(i + 1) })))
await pg.insert(apartments).values({ tower: 'B', apartmentNo: '1', isActive: false })
const result = await generateMonthlyBills(db, options)
expect(result.created).toBe(1000)
expect(result.skipped).toBe(0)
const bills = await pg.select().from(maintenanceBills)
expect(bills).toHaveLength(1000)
expect(bills.every((bill) => bill.totalAmount === 11800 && bill.taxAmount === 1800)).toBe(true)
expect(await pg.select().from(billLineItems)).toHaveLength(1000)
expect(await generateMonthlyBills(db, options)).toEqual({ created: 0, skipped: 1000, billIds: [] })
}, 15_000)

it('allows only one bill when generation calls overlap', async () => {
await pg.insert(apartments).values({ tower: 'A', apartmentNo: '1' })
const runs = await Promise.all([generateMonthlyBills(db, options), generateMonthlyBills(db, options)])
expect(runs.map((run) => run.created).sort()).toEqual([0, 1])
expect(await pg.select().from(billLineItems)).toHaveLength(1)
})

it('rolls back the bill when a charge references a missing ledger account', async () => {
await pg.insert(apartments).values({ tower: 'A', apartmentNo: '1' })
await expect(generateMonthlyBills(db, {
...options, lineItems: [{ ...options.lineItems[0], accountId: randomUUID() }],
})).rejects.toThrow()
expect(await pg.select().from(maintenanceBills)).toHaveLength(0)
expect(await pg.select().from(billLineItems)).toHaveLength(0)
expect((await generateMonthlyBills(db, options)).created).toBe(1)
})

it('handles a society with no active apartments', async () => {
expect(await generateMonthlyBills(db, options)).toEqual({ created: 0, skipped: 0, billIds: [] })
})


it('keeps journal entries atomic and allows retry after a rejected line', async () => {
const [account] = await pg.insert(accounts).values({ code: '1100', name: 'Receivable', type: 'ASSET' }).returning()
const draft = {
entryDate: '2026-10-01', period: '2026-10', narration: 'Test bill', sourceType: 'BILL' as const, sourceId: randomUUID(),
lines: [{ accountId: account.id, debit: 10000, credit: 0 }, { accountId: randomUUID(), debit: 0, credit: 10000 }],
}
await expect(insertJournalEntry(db, draft)).rejects.toThrow()
expect(await pg.select().from(journalEntries)).toHaveLength(0)
expect(await pg.select().from(journalLines)).toHaveLength(0)
draft.lines[1].accountId = account.id
expect(await insertJournalEntry(db, draft)).toBeTypeOf('string')
expect(await insertJournalEntry(db, draft)).toBeNull()
expect(await pg.select().from(journalEntries)).toHaveLength(1)
expect(await pg.select().from(journalLines)).toHaveLength(2)
})


it('posts 1,000 bills in batches and recovers generation completed before ledger initialization', async () => {
await pg.insert(apartments).values(Array.from({ length: 1000 }, (_, i) => ({ tower: 'A', apartmentNo: String(i + 1) })))
await generateMonthlyBills(db, options)
expect(await postMonthlyBills(db, options.periodMonth)).toBe(0)
await pg.insert(accounts).values([
{ code: '1100', name: 'Receivable', type: 'ASSET' },
{ code: '2200', name: 'GST', type: 'LIABILITY' },
{ code: '4000', name: 'Income', type: 'INCOME' },
])
expect(await postMonthlyBills(db, options.periodMonth)).toBe(1000)
expect(await pg.select().from(journalEntries)).toHaveLength(1000)
const lines = await pg.select().from(journalLines)
expect(lines).toHaveLength(3000)
expect(lines.reduce((sum, line) => sum + line.debit - line.credit, 0)).toBe(0)
expect(lines.reduce((sum, line) => sum + line.debit, 0)).toBe(11800000)
expect(await postMonthlyBills(db, options.periodMonth)).toBe(0)
expect(await pg.select().from(journalLines)).toHaveLength(3000)
}, 15_000)
20 changes: 20 additions & 0 deletions apps/api/src/cors.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { expect, it } from 'vitest'
import { app } from './index'
import type { Bindings } from './types'

it('allows only configured browser origins and keeps native requests working', async () => {
const env = { WEB_ORIGINS: 'https://society.example.com', CLERK_SECRET_KEY: 'sk_live_test' } as Bindings
for (const origin of ['https://society.example.com', 'https://unexpected.example.com', 'http://localhost:3000']) {
const response = await app.request('/health', { headers: { Origin: origin } }, env)
expect(response.status).toBe(200)
expect(response.headers.get('access-control-allow-origin')).toBe(origin === env.WEB_ORIGINS ? origin : null)
}
const response = await app.request('/health', {}, env)
expect(response.status).toBe(200)
expect(await response.json()).toEqual({ status: 'ok' })
})

it('does not allow development origins when Clerk is configured without an allowlist', async () => {
const response = await app.request('/health', { headers: { Origin: 'http://localhost:3000' } }, { CLERK_SECRET_KEY: 'sk_test_test' } as Bindings)
expect(response.headers.get('access-control-allow-origin')).toBeNull()
})
Loading
Loading