create-signet-app 0.4.7 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/README.md +160 -28
  2. package/{template-full → base/api}/api/app.ts +93 -15
  3. package/base/api/api/db/open.ts +121 -0
  4. package/{template-full → base/api}/api/db/schema.ts +22 -7
  5. package/{template-full → base/api}/api/env.ts +13 -0
  6. package/base/api/api/server.ts +157 -0
  7. package/{template-full → base/api}/api/services.ts +77 -8
  8. package/base/api/test/api.test.ts +51 -0
  9. package/base/api/test/helpers.ts +51 -0
  10. package/base/both/scripts/dev.ts +44 -0
  11. package/base/shared/README.md +298 -0
  12. package/{template-full → base/shared}/_github/workflows/ci.yml +1 -1
  13. package/{template-full → base/shared}/biome.json +1 -1
  14. package/{template-full → base/web}/src/lib/api.ts +28 -1
  15. package/{template-full → base/web}/src/main.tsx +4 -1
  16. package/{template-full → base/web}/src/routeTree.gen.ts +130 -90
  17. package/{template-full → base/web}/src/router.test.ts +12 -9
  18. package/base/web/src/routes/_app/index.tsx +55 -0
  19. package/{template-full → base/web}/src/routes/_app.tsx +39 -16
  20. package/{template-full → base/web}/vite.config.ts +3 -1
  21. package/package.json +9 -5
  22. package/parts/account/api/test/account.test.ts +30 -0
  23. package/parts/account/part.ts +6 -0
  24. package/parts/admin/api/test/admin.test.ts +35 -0
  25. package/parts/admin/part.ts +6 -0
  26. package/{template-full → parts/admin/web}/src/routes/_app/admin.tsx +2 -1
  27. package/{template-full → parts/auth/api}/api/routes/account.ts +32 -3
  28. package/{template-full → parts/auth/api}/api/routes/auth.ts +5 -3
  29. package/parts/auth/api/test/auth.test.ts +28 -0
  30. package/{template-full → parts/auth/both}/e2e/smoke.spec.ts +21 -7
  31. package/parts/auth/part.ts +22 -0
  32. package/parts/growth/part.ts +7 -0
  33. package/{template-full/_mcp → parts/mcp/api}/test/mcp.test.ts +25 -16
  34. package/parts/mcp/part.ts +8 -0
  35. package/parts/notifications/api/test/notifications.test.ts +18 -0
  36. package/parts/notifications/part.ts +6 -0
  37. package/{template-full → parts/notifications/web}/src/routes/_app/notifications.tsx +1 -1
  38. package/parts/orgs/api/test/orgs.test.ts +56 -0
  39. package/parts/orgs/part.ts +7 -0
  40. package/{template-full → parts/payments/api}/api/routes/billing.ts +3 -2
  41. package/parts/payments/api/test/payments.test.ts +31 -0
  42. package/parts/payments/part.ts +12 -0
  43. package/{template-full → parts/payments/web}/src/routes/_app/billing.tsx +6 -3
  44. package/parts/privacy/api/test/privacy.test.ts +20 -0
  45. package/parts/privacy/part.ts +7 -0
  46. package/src/compose.ts +369 -0
  47. package/src/describe.ts +200 -0
  48. package/src/desktop.ts +10 -10
  49. package/src/index.ts +433 -159
  50. package/template/biome.json +1 -1
  51. package/template-api/_targets/deno/Dockerfile +12 -0
  52. package/template-api/_targets/deno/_dockerignore +10 -0
  53. package/template-api/_targets/deno/src/server.ts +43 -0
  54. package/template-api/biome.json +1 -1
  55. package/template-cli/biome.json +1 -1
  56. package/template-extension/biome.json +1 -1
  57. package/template-full/README.md +0 -155
  58. package/template-full/api/db/open.ts +0 -33
  59. package/template-full/api/server.ts +0 -44
  60. package/template-full/scripts/dev.ts +0 -17
  61. package/template-full/src/routes/_app/index.tsx +0 -33
  62. package/template-full/test/api.test.ts +0 -189
  63. package/template-full/tsconfig.json +0 -9
  64. /package/{template-full → base/api}/api/db/index.ts +0 -0
  65. /package/{template-full → base/api}/api/db/kv.ts +0 -0
  66. /package/{template-full → base/api}/drizzle/0000_init.sql +0 -0
  67. /package/{template-full → base/api}/drizzle/0001_orgs.sql +0 -0
  68. /package/{template-full → base/api}/drizzle/meta/0000_snapshot.json +0 -0
  69. /package/{template-full → base/api}/drizzle/meta/0001_snapshot.json +0 -0
  70. /package/{template-full → base/api}/drizzle/meta/_journal.json +0 -0
  71. /package/{template-full → base/api}/drizzle.config.ts +0 -0
  72. /package/{template-full → base/api}/tsconfig.api.json +0 -0
  73. /package/{template-full → base/shared}/_gitignore +0 -0
  74. /package/{template-full → base/web}/index.html +0 -0
  75. /package/{template-full → base/web}/src/app.css +0 -0
  76. /package/{template-full → base/web}/src/components/toaster.tsx +0 -0
  77. /package/{template-full → base/web}/src/router.ts +0 -0
  78. /package/{template-full → base/web}/src/routes/__root.tsx +0 -0
  79. /package/{template-full → base/web}/tsconfig.app.json +0 -0
  80. /package/{template-full → base/web}/tsconfig.node.json +0 -0
  81. /package/{template-full → base/web}/tsconfig.test.json +0 -0
  82. /package/{template-full → parts/account/web}/src/routes/_app/account.tsx +0 -0
  83. /package/{template-full → parts/auth/both}/playwright.config.ts +0 -0
  84. /package/{template-full → parts/auth/web}/src/routes/login.tsx +0 -0
  85. /package/{template-full → parts/notifications/api}/api/routes/notifications.ts +0 -0
  86. /package/{template-full → parts/orgs/web}/src/routes/_app/org/index.tsx +0 -0
  87. /package/{template-full → parts/orgs/web}/src/routes/_app/org/members.tsx +0 -0
  88. /package/{template-full → parts/orgs/web}/src/routes/_app/org/new.tsx +0 -0
  89. /package/{template-full → parts/orgs/web}/src/routes/invite.$token.tsx +0 -0
  90. /package/{template-full → parts/payments/api}/api/plans.ts +0 -0
  91. /package/{template-full → parts/privacy/api}/api/routes/privacy.ts +0 -0
  92. /package/{template-full → parts/privacy/web}/src/routes/_app/privacy.tsx +0 -0
@@ -1,5 +1,5 @@
1
1
  {
2
- "$schema": "https://biomejs.dev/schemas/2.5.14/schema.json",
2
+ "$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
3
3
  "vcs": {
4
4
  "enabled": true,
5
5
  "clientKind": "git",
@@ -0,0 +1,12 @@
1
+ # Runs the API under Deno (src/server.ts), not as a Worker.
2
+ # docker build -t __APP_NAME__ .
3
+ # docker run -p 3000:3000 __APP_NAME__
4
+ FROM denoland/deno:2
5
+ WORKDIR /app
6
+ COPY package.json ./
7
+ RUN deno install --prod
8
+ COPY src ./src
9
+ ENV APP_ENV=production PORT=3000
10
+ EXPOSE 3000
11
+ USER deno
12
+ CMD ["deno", "run", "--allow-net", "--allow-env", "--allow-read", "--allow-sys", "src/server.ts"]
@@ -0,0 +1,10 @@
1
+ node_modules
2
+ dist
3
+ .out
4
+ .wrangler
5
+ .dev.vars
6
+ .env
7
+ .env.local
8
+ .git
9
+ .github
10
+ *.log
@@ -0,0 +1,43 @@
1
+ // Deno and Docker entry: the app in ./app.ts, served by Deno.serve.
2
+ // Run `deno run -A src/server.ts`, or build the Dockerfile.
3
+ import { memoryStore } from "@dapplelight/signet-server/middleware/rate-limit"
4
+ import { createApp } from "./app.ts"
5
+
6
+ /** The slice of Deno's global this file uses (tsc has no Deno types). */
7
+ declare const Deno: {
8
+ env: { get(key: string): string | undefined }
9
+ serve(
10
+ options: { port: number; onListen?: (addr: { port: number }) => void },
11
+ handler: (
12
+ req: Request,
13
+ info: { remoteAddr: { hostname: string } },
14
+ ) => Response | Promise<Response>,
15
+ ): unknown
16
+ }
17
+
18
+ const hops = Deno.env.get("TRUSTED_PROXY_HOPS")
19
+
20
+ const app = createApp<Record<string, never>>({
21
+ // One process, so an in-memory count is exact. Running several replicas?
22
+ // Share the count: upstashRateLimitStore from @dapplelight/signet-server/adapters/upstash.
23
+ store: memoryStore(),
24
+ // Behind proxies of your own (a load balancer, a PaaS router), set
25
+ // TRUSTED_PROXY_HOPS to how many, and the client IP comes from
26
+ // x-forwarded-for. Otherwise the handler below replaces that header with
27
+ // the socket's peer address, so one hop (this server) is all there is to trust.
28
+ trust: { forwardedHops: hops ? Number(hops) : 1 },
29
+ })
30
+
31
+ Deno.serve(
32
+ {
33
+ port: Number(Deno.env.get("PORT") ?? 3000),
34
+ onListen: ({ port }) => console.log(`Listening on http://localhost:${port}`),
35
+ },
36
+ (req, info) => {
37
+ if (hops) return app.fetch(req)
38
+ // Overwrite, never append: a client-supplied x-forwarded-for must not pick its bucket.
39
+ const headers = new Headers(req.headers)
40
+ headers.set("x-forwarded-for", info.remoteAddr.hostname)
41
+ return app.fetch(new Request(req, { headers }))
42
+ },
43
+ )
@@ -1,5 +1,5 @@
1
1
  {
2
- "$schema": "https://biomejs.dev/schemas/2.5.14/schema.json",
2
+ "$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
3
3
  "vcs": {
4
4
  "enabled": true,
5
5
  "clientKind": "git",
@@ -1,5 +1,5 @@
1
1
  {
2
- "$schema": "https://biomejs.dev/schemas/2.5.14/schema.json",
2
+ "$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
3
3
  "vcs": {
4
4
  "enabled": true,
5
5
  "clientKind": "git",
@@ -1,5 +1,5 @@
1
1
  {
2
- "$schema": "https://biomejs.dev/schemas/2.5.14/schema.json",
2
+ "$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
3
3
  "vcs": {
4
4
  "enabled": true,
5
5
  "clientKind": "git",
@@ -1,155 +0,0 @@
1
- # __APP_NAME__
2
-
3
- A web app and its API in one project, on Signet: phone sign-in, organisations
4
- with members, roles and invite links, an account page with devices and API
5
- keys, an in-app inbox, privacy (DPDP consent and data requests), plans and
6
- billing, and an admin panel over the whole database.
7
-
8
- The API runs on [Bun](https://bun.sh), whichever package manager installed it.
9
-
10
- ## First day
11
-
12
- ### 1. Run it (5 minutes)
13
-
14
- ```sh
15
- __PM_INSTALL__
16
- __PM_RUN__ dev
17
- ```
18
-
19
- `dev` starts the API on port 3000 and Vite next to it; open the URL Vite
20
- prints. Sign in with any phone number. In development no SMS is sent: the
21
- code is printed in the terminal running `dev`.
22
-
23
- The env file at the project root was written for you with fresh
24
- `SESSION_SECRET` and `OTP_SECRET` values. It is gitignored. Every variable is
25
- declared, with its default, in `api/env.ts`.
26
-
27
- ### 2. Organisations (5 minutes)
28
-
29
- Signing up made you a **Personal** org, and you own it. The switcher in the
30
- header lists your orgs; **New organisation** makes another and moves you into
31
- it. **Org** has its settings (name, theme, brand colour) and
32
- **Members and invites**: create an invite link, open it in a private window,
33
- sign in as another number and accept. That person sees the orgs they belong
34
- to and nothing else.
35
-
36
- - Roles are `owner` (everything), `admin` (settings, members, invites) and
37
- `member` (sees the member list), from signet-db's `DEFAULT_ORG_ROLES`. No
38
- one can hand out a role with more permissions than their own, and an org
39
- always keeps an owner.
40
- - Which org a request is for: in development, the `signet_org` cookie the
41
- switcher sets, or an `x-org` header. In production, also the org's custom
42
- domain, or `<slug>.<ORG_ROOT_DOMAIN>` when you set `ORG_ROOT_DOMAIN`.
43
- - Every org write (create, settings, roles, members, invites) is in the
44
- audit log.
45
-
46
- ### 3. Make yourself platform admin (2 minutes)
47
-
48
- Put your number in `ADMIN_PHONES` (E.164, comma-separated, e.g.
49
- `+919876543210`) and sign in again. **Admin** appears in the header: the
50
- operator's view of every table across every org, searchable and editable, with
51
- each write in the audit log. Platform roles live in `users.role`: `admin` does
52
- everything, `staff` all but delete, `readonly` looks. They are separate from
53
- org roles: an org owner is not a platform admin.
54
-
55
- ### 4. Try billing (2 minutes)
56
-
57
- Open **Billing**, pick Pro and continue. `BILLING=fake` switches the plan at once, no
58
- money moves, and the inbox gets a "Plan changed" notice. The API refuses to
59
- start with `BILLING=fake` in staging or production.
60
-
61
- Plans are in `api/plans.ts`: `definePlans` says what each plan allows,
62
- `PLAN_DISPLAY` the name, description and price the page shows. Check a plan anywhere in the API:
63
-
64
- ```ts
65
- await s.entitlements.can(userId, "export")
66
- await s.entitlements.consume(userId, "projects", 1) // { ok, remaining }
67
- ```
68
-
69
- ### 5. Build your first feature (the rest of the day)
70
-
71
- 1. **Table.** Add it to `api/db/schema.ts` (see `users` for the column
72
- helpers). If it belongs to an org, give it
73
- `orgId: text("org_id").notNull()`. Then run `__PM_RUN__ db:generate`. The migration lands in `drizzle/`;
74
- the API applies it on its next start. `__PM_RUN__ db:check` flags migrations
75
- that drop or rename data.
76
- 2. **Route.** Add a file in `api/routes/` like `account.ts` and mount it in
77
- `api/app.ts`. List its path in `SIGNED_IN` if it needs a user;
78
- `c.get("user")` is then the signed-in user. For org data, guard the route
79
- with `orgGuards({ orgs: s.orgs, userId }).requirePermission("projects:write")`
80
- and read and write through `scoped(s.db, { orgId: currentTenant(c).id })`.
81
- Another org's rows are then unreachable, and a table without `orgId`
82
- throws instead of leaking. Validate input with `zValidator`: the route is
83
- then also typed for the client and, with MCP on, a tool.
84
- 3. **Page.** Add `src/routes/_app/<name>.tsx`. Call the route through `api`
85
- from `src/lib/api.ts`: the path, input and response are typed from the
86
- server, so a renamed field fails typecheck instead of production.
87
- 4. **Notify.** Add a template to `templates` in `api/services.ts` and call
88
- `s.notifier.notify(userId, "your.event", data)`. In-app works now; add
89
- `email`, `sms` or `whatsapp` variants and senders from
90
- `@dapplelight/signet-server/notify/channels` when you have provider keys.
91
-
92
- The admin panel picks up new tables by itself.
93
-
94
- ### 6. Check it
95
-
96
- ```sh
97
- __PM_RUN__ lint && __PM_RUN__ typecheck && __PM_RUN__ test && __PM_RUN__ build
98
- __PM_X__ playwright install chromium # once
99
- __PM_RUN__ test:e2e # sign-in, admin, billing, then orgs: a second org, an invite, isolation
100
- ```
101
-
102
- CI (`.github/workflows/ci.yml`) runs the first line on every push. Commit
103
- your lockfile.
104
-
105
- ## Layout
106
-
107
- ```
108
- api/
109
- app.ts routes, auth gate, admin, MCP; exports AppType for the client
110
- plans.ts plans and what the billing page shows (shared with the browser)
111
- services.ts notification templates, consent purposes, admin config
112
- routes/ auth, account, notifications, privacy, billing (orgs: signet-server's orgRoutes)
113
- db/schema.ts every table; drizzle/ holds the migrations
114
- db/kv.ts sessions, codes, API keys, inbox and rate limits live in the kv table
115
- server.ts Bun entry: the API under /api, the built app for every other path
116
- src/
117
- routes/login.tsx sign-in
118
- routes/_app/ the signed-in pages: home, account, notifications, privacy, billing, admin, org/
119
- routes/invite.$token.tsx the invite link
120
- lib/api.ts the typed client
121
- test/ API tests (in-memory database)
122
- e2e/ the browser smoke test
123
- ```
124
-
125
- ## Deploying
126
-
127
- `__PM_RUN__ build`, then `__PM_RUN__ start` serves the API and the built app from one
128
- Bun process. Mount a volume for `DATABASE_PATH` (default `data/app.db`) and set
129
- `APP_ENV=production`, `SESSION_SECRET`, `OTP_SECRET` and `ADMIN_PHONES` on the
130
- host, and `ORG_ROOT_DOMAIN` if orgs get subdomains. For an org's custom
131
- domain, point its DNS at the host and serve TLS for it there. SQLite wants one writer: run one instance.
132
-
133
- Before production:
134
-
135
- - **SMS.** `api/services.ts` uses `devSmsSender`, which refuses to run in
136
- staging or production. Swap in a real sender, e.g. `smsSenderFor(msg91Sms(...))`
137
- from `@dapplelight/signet-server/notify/channels` (Indian numbers need DLT
138
- template ids).
139
- - **Taking real payments.** Set `BILLING=razorpay` and the `RAZORPAY_*` keys.
140
- Gateway webhooks arrive at `/api/webhooks/razorpay`; signet-payments verifies
141
- them and each subscription event moves the user's plan through
142
- `entitlements.applyBillingEvent`. Map your Razorpay plan ids to plans in
143
- `billing.plans` (`api/services.ts`). Creating the subscription at checkout is
144
- the one step left to you: see the `TODO(billing)` in `api/routes/billing.ts`
145
- (pass the user id in the subscription's notes and read it back with
146
- `billing.subjectOf`).
147
- - **Privacy requests.** Users open export and erasure requests from Privacy.
148
- Fulfil them with `privacy.fulfil(id, { actor })` (export returns the data to
149
- send; erasure deletes the user's rows listed in `userTables`).
150
-
151
- ## Themes
152
-
153
- `src/app.css` imports the __THEME__ theme from `@dapplelight/signet-tokens`.
154
- Swap the import (`editorial`, `cinematic`, `finance`) and every component
155
- reshapes. No component changes.
@@ -1,33 +0,0 @@
1
- import { Database } from "bun:sqlite"
2
- import { mkdirSync } from "node:fs"
3
- import { dirname, join } from "node:path"
4
- import { createDb } from "@dapplelight/signet-db/sqlite"
5
- import { paymentsSchema } from "@dapplelight/signet-payments"
6
- import { migrate } from "drizzle-orm/bun-sqlite/migrator"
7
- import type { Db } from "./index.ts"
8
- import * as schema from "./schema.ts"
9
-
10
- const MIGRATIONS = join(import.meta.dirname, "../../drizzle")
11
-
12
- /**
13
- * Open (or create) the database and bring it up to date. `query` runs raw SQL
14
- * with `?` placeholders, for signet-payments' store.
15
- */
16
- export function openDb(path: string): {
17
- db: Db
18
- query: (sql: string, params: unknown[]) => Record<string, unknown>[]
19
- } {
20
- if (path !== ":memory:") mkdirSync(dirname(path), { recursive: true })
21
- const sqlite = new Database(path)
22
- if (path !== ":memory:") sqlite.run("pragma journal_mode = wal")
23
- const db = createDb(sqlite, { schema, audit: schema.audit, idempotency: schema.idempotency })
24
- // Your tables: the migrations drizzle-kit writes from api/db/schema.ts.
25
- migrate(db.orm, { migrationsFolder: MIGRATIONS })
26
- // signet-payments' webhook inbox, payment records and ledger: its own
27
- // CREATE TABLE IF NOT EXISTS statements, versioned with the package.
28
- for (const statement of paymentsSchema("sqlite")) sqlite.run(statement)
29
- return {
30
- db,
31
- query: (s, p) => sqlite.query<Record<string, unknown>, never[]>(s).all(...(p as never[])),
32
- }
33
- }
@@ -1,44 +0,0 @@
1
- /// <reference types="bun" />
2
- // The one process to run: the API under /api (and /mcp), and the built web
3
- // app from dist/ for every other path. `dev` runs this next to Vite, which
4
- // proxies /api to it; `start` serves both from here.
5
- import { join, normalize } from "node:path"
6
- import { createApp } from "./app.ts"
7
- import { pruneKv, sqlKv } from "./db/kv.ts"
8
- import { openDb } from "./db/open.ts"
9
- import { env } from "./env.ts"
10
-
11
- const { db, query } = openDb(env.DATABASE_PATH)
12
- const app = createApp({ db, query, kv: sqlKv(db.orm) })
13
- setInterval(() => pruneKv(db.orm), 60 * 60 * 1000)
14
-
15
- const DIST = join(import.meta.dirname, "../dist")
16
-
17
- const server = Bun.serve({
18
- port: env.PORT,
19
- async fetch(req, srv) {
20
- const { pathname } = new URL(req.url)
21
- if (pathname.startsWith("/api/") || pathname.startsWith("/mcp")) {
22
- // Overwrite, never append: a client-set x-forwarded-for must not pick its
23
- // own rate-limit bucket. Behind a proxy of your own, pass the proxy's
24
- // header through instead and raise TRUST's hops in services.ts.
25
- const headers = new Headers(req.headers)
26
- headers.set("x-forwarded-for", srv.requestIP(req)?.address ?? "")
27
- return app.fetch(new Request(req, { headers }))
28
- }
29
- // A file (it has an extension) or the app's index.html for its routes.
30
- if (/\.[a-z0-9]+$/i.test(pathname)) {
31
- const path = normalize(join(DIST, pathname))
32
- const file = Bun.file(path)
33
- if (path.startsWith(DIST) && (await file.exists())) return new Response(file)
34
- return new Response("Not found", { status: 404 })
35
- }
36
- const index = Bun.file(join(DIST, "index.html"))
37
- if (await index.exists()) return new Response(index)
38
- return new Response("No web build yet: run `build`, or use `dev` and open Vite's URL.", {
39
- status: 404,
40
- })
41
- },
42
- })
43
-
44
- console.log(`Listening on ${server.url}`)
@@ -1,17 +0,0 @@
1
- /// <reference types="bun" />
2
- // `dev`: the API (restarting on change) and Vite, which proxies /api to it.
3
- // A script rather than `a & b` so it runs the same on Windows; when either
4
- // stops, so does the other.
5
- const bun = process.execPath
6
- const procs = [
7
- Bun.spawn([bun, "--watch", "api/server.ts"], { stdio: ["inherit", "inherit", "inherit"] }),
8
- Bun.spawn([bun, "x", "vite"], { stdio: ["inherit", "inherit", "inherit"] }),
9
- ]
10
- const stop = () => {
11
- for (const p of procs) p.kill()
12
- }
13
- process.on("SIGINT", stop)
14
- process.on("SIGTERM", stop)
15
- const code = await Promise.race(procs.map((p) => p.exited))
16
- stop()
17
- process.exit(code)
@@ -1,33 +0,0 @@
1
- import { Card, CardContent, CardHeader, CardTitle } from "@dapplelight/signet-ui/components/card"
2
- import { useQuery } from "@tanstack/react-query"
3
- import { createFileRoute, Link } from "@tanstack/react-router"
4
- import { meQuery } from "../../lib/api"
5
-
6
- export const Route = createFileRoute("/_app/")({
7
- component: Home,
8
- })
9
-
10
- // Your product goes here. Sign-in, account, inbox, privacy, billing and admin
11
- // are already wired; this page is the one that is yours.
12
- function Home() {
13
- const me = useQuery(meQuery).data
14
- return (
15
- <Card>
16
- <CardHeader>
17
- <CardTitle>Hello{me?.user.name ? `, ${me.user.name}` : ""}</CardTitle>
18
- </CardHeader>
19
- <CardContent className="space-y-2 text-sm text-muted-foreground">
20
- <p>
21
- You are on the <strong className="text-foreground">{me?.plan ?? "…"}</strong> plan.{" "}
22
- <Link to="/billing" className="underline">
23
- See plans
24
- </Link>
25
- </p>
26
- <p>
27
- Replace this page with your product: <code>src/routes/_app/index.tsx</code>, backed by a
28
- route in <code>api/app.ts</code>.
29
- </p>
30
- </CardContent>
31
- </Card>
32
- )
33
- }
@@ -1,189 +0,0 @@
1
- import { expect, test } from "bun:test"
2
-
3
- // The env is read on first use, so set it before the app is imported. CI has
4
- // no env file; these are throwaway test values.
5
- const ADMIN = "+919000000001"
6
- Object.assign(process.env, {
7
- APP_ENV: "development",
8
- SESSION_SECRET: "test-session-secret-0123456789abcdef",
9
- OTP_SECRET: "test-otp-secret-0123456789abcdef0123",
10
- ADMIN_PHONES: ADMIN,
11
- BILLING: "fake",
12
- })
13
- const { createApp } = await import("../api/app.ts")
14
- const { openDb } = await import("../api/db/open.ts")
15
- const { sqlKv } = await import("../api/db/kv.ts")
16
-
17
- const codes = new Map<string, string>()
18
- const { db, query } = openDb(":memory:")
19
- const app = createApp({
20
- db,
21
- query,
22
- kv: sqlKv(db.orm),
23
- sms: { send: async (to, message) => void codes.set(to, message.match(/\d{6}/)?.[0] ?? "") },
24
- })
25
-
26
- const post = (path: string, body: unknown, cookie = "") =>
27
- app.request(path, {
28
- method: "POST",
29
- headers: { "content-type": "application/json", cookie },
30
- body: JSON.stringify(body),
31
- })
32
-
33
- /** Sign in with a one-time code; returns the session cookie. */
34
- async function signIn(phone: string): Promise<string> {
35
- expect((await post("/api/auth/otp", { phone })).status).toBe(200)
36
- const res = await post("/api/auth/verify", { phone, code: codes.get(phone) })
37
- expect(res.status).toBe(200)
38
- return (res.headers.get("set-cookie") ?? "").split(";")[0] ?? ""
39
- }
40
-
41
- test("signed-out calls are 401 in the error envelope", async () => {
42
- const res = await app.request("/api/account/me")
43
- expect(res.status).toBe(401)
44
- expect(((await res.json()) as { code: string }).code).toBe("UNAUTHORIZED")
45
- })
46
-
47
- test("a wrong code is refused", async () => {
48
- await post("/api/auth/otp", { phone: "+919000000009" })
49
- const res = await post("/api/auth/verify", { phone: "+919000000009", code: "000000" })
50
- expect(res.status).toBe(400)
51
- })
52
-
53
- test("sign in, see the plan, upgrade, get notified", async () => {
54
- const cookie = await signIn("+919000000002")
55
- const me = (await (await app.request("/api/account/me", { headers: { cookie } })).json()) as {
56
- user: { role: string }
57
- plan: string
58
- }
59
- expect(me).toMatchObject({ user: { role: "user" }, plan: "free" })
60
-
61
- expect((await post("/api/billing/checkout", { plan: "pro" }, cookie)).status).toBe(200)
62
- const billing = (await (await app.request("/api/billing", { headers: { cookie } })).json()) as {
63
- subscription: { plan: string }
64
- }
65
- expect(billing.subscription.plan).toBe("pro")
66
-
67
- // Sends are deferred; the welcome and plan notices land in the inbox shortly.
68
- await Bun.sleep(100)
69
- const inbox = (await (
70
- await app.request("/api/notifications", { headers: { cookie } })
71
- ).json()) as {
72
- items: { event: string }[]
73
- }
74
- expect(inbox.items.map((i) => i.event).sort()).toEqual([
75
- "account.welcome",
76
- "billing.plan_changed",
77
- ])
78
- })
79
-
80
- test("admin is for ADMIN_PHONES (and other staff roles) only", async () => {
81
- const user = await signIn("+919000000003")
82
- expect((await app.request("/api/admin", { headers: { cookie: user } })).status).toBe(403)
83
- const admin = await signIn(ADMIN)
84
- const res = await app.request("/api/admin/users", { headers: { cookie: admin } })
85
- expect(res.status).toBe(200)
86
- expect(((await res.json()) as { rows: unknown[] }).rows.length).toBeGreaterThan(0)
87
- })
88
-
89
- test("consent is given and withdrawn; an erasure request opens", async () => {
90
- const cookie = await signIn("+919000000004")
91
- expect((await post("/api/privacy/consents/analytics", {}, cookie)).status).toBe(200)
92
- // A browser sends Origin on a DELETE; the CSRF guard refuses one without it.
93
- const withdraw = await app.request("/api/privacy/consents/analytics", {
94
- method: "DELETE",
95
- headers: { cookie, origin: "http://localhost" },
96
- })
97
- expect(withdraw.status).toBe(200)
98
- expect((await post("/api/privacy/requests", { kind: "erasure" }, cookie)).status).toBe(201)
99
- const p = (await (await app.request("/api/privacy", { headers: { cookie } })).json()) as {
100
- consents: { withdrawnAt: string | null }[]
101
- requests: { kind: string }[]
102
- }
103
- expect(p.consents[0]?.withdrawnAt).not.toBeNull()
104
- expect(p.requests[0]?.kind).toBe("erasure")
105
- })
106
-
107
- test("sign-out revokes the session", async () => {
108
- const cookie = await signIn("+919000000005")
109
- await post("/api/auth/sign-out", {}, cookie)
110
- expect((await app.request("/api/account/me", { headers: { cookie } })).status).toBe(401)
111
- })
112
-
113
- test("staff cannot change a role or phone; an admin can", async () => {
114
- const { users } = await import("../api/db/schema.ts")
115
- const { eq } = await import("drizzle-orm")
116
- const staff = await signIn("+919000000006")
117
- const staffRow = db.orm.select().from(users).where(eq(users.phone, "+919000000006")).get()
118
- db.orm.update(users).set({ role: "staff" }).where(eq(users.phone, "+919000000006")).run()
119
- const patch = (cookie: string, id: string, body: unknown) =>
120
- app.request(`/api/admin/users/${id}`, {
121
- method: "PATCH",
122
- headers: { "content-type": "application/json", cookie },
123
- body: JSON.stringify(body),
124
- })
125
- const id = staffRow?.id ?? ""
126
-
127
- expect((await patch(staff, id, { role: "admin" })).status).toBe(403)
128
- expect((await patch(staff, id, { phone: "+919000000099" })).status).toBe(403)
129
- expect((await patch(staff, id, { name: "Staff" })).status).toBe(200)
130
- expect(db.orm.select().from(users).where(eq(users.id, id)).get()?.role).toBe("staff")
131
-
132
- const admin = await signIn(ADMIN)
133
- expect((await patch(admin, id, { role: "readonly" })).status).toBe(200)
134
- expect(db.orm.select().from(users).where(eq(users.id, id)).get()?.role).toBe("readonly")
135
- })
136
-
137
- test("sign-up makes a personal org; another org's data is 404", async () => {
138
- const get = (path: string, cookie: string, org?: string) =>
139
- app.request(path, { headers: { cookie, ...(org ? { "x-org": org } : {}) } })
140
- const signInWithOrg = async (phone: string) => {
141
- expect((await post("/api/auth/otp", { phone })).status).toBe(200)
142
- const res = await post("/api/auth/verify", { phone, code: codes.get(phone) })
143
- // Two cookies: the session, and the org the user lands in.
144
- const cookies = res.headers.getSetCookie().map((c) => c.split(";")[0])
145
- expect(cookies.some((c) => c?.startsWith("signet_org="))).toBe(true)
146
- return cookies.join("; ")
147
- }
148
- const a = await signInWithOrg("+919000000010")
149
- const b = await signInWithOrg("+919000000011")
150
- const mine = (await (await get("/api/orgs", a)).json()) as {
151
- orgs: { org: { id: string; personal: boolean }; role: string }[]
152
- }
153
- expect(mine.orgs).toHaveLength(1)
154
- expect(mine.orgs[0]).toMatchObject({ role: "owner", org: { personal: true } })
155
- const aOrg = mine.orgs[0]?.org.id as string
156
- expect((await get("/api/orgs/current", a)).status).toBe(200)
157
- // B pointing at A's org, by header: not found, and nothing leaks.
158
- for (const path of [
159
- "/api/orgs/current",
160
- "/api/orgs/current/members",
161
- "/api/orgs/current/invites",
162
- ])
163
- expect((await get(path, b, aOrg)).status).toBe(404)
164
- const join = (await post("/api/orgs/switch", { orgId: aOrg }, b)).status
165
- expect(join).toBe(404)
166
-
167
- // A invites B by link; B joins A's org and sees it.
168
- const invite = await app.request("/api/orgs/current/invites", {
169
- method: "POST",
170
- headers: { "content-type": "application/json", cookie: a },
171
- body: JSON.stringify({ role: "member" }),
172
- })
173
- const { token } = (await invite.json()) as { token: string }
174
- expect((await app.request(`/api/orgs/invites/${token}`)).status).toBe(200) // preview, signed out
175
- expect((await post(`/api/orgs/invites/${token}/accept`, {}, b)).status).toBe(200)
176
- expect((await get("/api/orgs/current/members", b, aOrg)).status).toBe(200)
177
- // A member cannot change settings.
178
- const patch = await app.request("/api/orgs/current", {
179
- method: "PATCH",
180
- headers: {
181
- "content-type": "application/json",
182
- cookie: b,
183
- "x-org": aOrg,
184
- origin: "http://localhost",
185
- },
186
- body: JSON.stringify({ name: "x" }),
187
- })
188
- expect(patch.status).toBe(403)
189
- })
@@ -1,9 +0,0 @@
1
- {
2
- "files": [],
3
- "references": [
4
- { "path": "./tsconfig.app.json" },
5
- { "path": "./tsconfig.node.json" },
6
- { "path": "./tsconfig.test.json" },
7
- { "path": "./tsconfig.api.json" }
8
- ]
9
- }
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes