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
@@ -0,0 +1,157 @@
1
+ /// <reference types="bun" /> // @bun
2
+ // web:begin
3
+ // The one process to run: the API under /api (and /mcp), and the built web
4
+ // app from dist/ for every other path. `dev` runs this next to Vite, which
5
+ // proxies /api to it; `start` serves both from here.
6
+ import { join, normalize } from "node:path"
7
+ // web:end
8
+ // The one process to run: the API under /api (and /mcp). `dev` runs it and // @!web
9
+ // restarts it on change; `start` serves it. // @!web
10
+ // !bun:begin
11
+ import { readFile } from "node:fs/promises" // @web
12
+ import { createServer } from "node:http"
13
+ import { Readable } from "node:stream"
14
+ // !bun:end
15
+ import { createApp } from "./app.ts"
16
+ import { pruneKv, sqlKv } from "./db/kv.ts"
17
+ import { openDb } from "./db/open.ts"
18
+ import { env } from "./env.ts"
19
+
20
+ const { db, query } = openDb(env.DATABASE_PATH)
21
+ // OBSERVABILITY=on adds request logs, spans and /health/live and /health/ready.
22
+ const serviceName = "__APP_NAME__"
23
+ const observability = env.OBSERVABILITY === "on" ? { serviceName } : undefined
24
+ const app = createApp({ db, query, kv: sqlKv(db.orm), observability })
25
+ setInterval(() => pruneKv(db.orm), 60 * 60 * 1000)
26
+
27
+ const DIST = join(import.meta.dirname, "../dist") // @web
28
+
29
+ // bun:begin
30
+ const server = Bun.serve({
31
+ port: env.PORT,
32
+ async fetch(req, srv) { // @web
33
+ fetch(req, srv) { // @!web
34
+ const { pathname } = new URL(req.url)
35
+ if (
36
+ pathname.startsWith("/api/") ||
37
+ pathname.startsWith("/mcp") ||
38
+ (observability && pathname.startsWith("/health/"))
39
+ ) {
40
+ // Overwrite, never append: a client-set x-forwarded-for must not pick its
41
+ // own rate-limit bucket. Behind a proxy of your own, pass the proxy's
42
+ // header through instead and raise TRUST's hops in services.ts.
43
+ const headers = new Headers(req.headers)
44
+ headers.set("x-forwarded-for", srv.requestIP(req)?.address ?? "")
45
+ return app.fetch(new Request(req, { headers }))
46
+ }
47
+ // web:begin
48
+ // A file (it has an extension) or the app's index.html for its routes.
49
+ if (/\.[a-z0-9]+$/i.test(pathname)) {
50
+ const path = normalize(join(DIST, pathname))
51
+ const file = Bun.file(path)
52
+ if (path.startsWith(DIST) && (await file.exists())) return new Response(file)
53
+ return new Response("Not found", { status: 404 })
54
+ }
55
+ const index = Bun.file(join(DIST, "index.html"))
56
+ if (await index.exists()) return new Response(index)
57
+ return new Response("No web build yet: run `build`, or use `dev` and open Vite's URL.", {
58
+ status: 404,
59
+ })
60
+ // web:end
61
+ return new Response("Not found", { status: 404 }) // @!web
62
+ },
63
+ })
64
+
65
+ console.log(`Listening on ${server.url}`)
66
+ // bun:end
67
+ // !bun:begin
68
+ // web:begin
69
+ const TYPES: Record<string, string> = {
70
+ html: "text/html; charset=utf-8",
71
+ js: "text/javascript; charset=utf-8",
72
+ css: "text/css; charset=utf-8",
73
+ json: "application/json",
74
+ webmanifest: "application/manifest+json",
75
+ svg: "image/svg+xml",
76
+ png: "image/png",
77
+ jpg: "image/jpeg",
78
+ webp: "image/webp",
79
+ ico: "image/x-icon",
80
+ woff2: "font/woff2",
81
+ txt: "text/plain; charset=utf-8",
82
+ }
83
+
84
+ /** A file from dist/, or null when there is none. */
85
+ async function file(path: string): Promise<Response | null> {
86
+ const body = await readFile(path).catch(() => null)
87
+ if (!body) return null
88
+ const type = TYPES[path.slice(path.lastIndexOf(".") + 1)] ?? "application/octet-stream"
89
+ return new Response(body, { headers: { "content-type": type } })
90
+ }
91
+ // web:end
92
+
93
+ /** One request: the API, or (with the web app) a file from dist/. */
94
+ async function handle(req: Request, ip: string): Promise<Response> { // @web
95
+ function handle(req: Request, ip: string): Promise<Response> | Response { // @!web
96
+ const { pathname } = new URL(req.url)
97
+ if (
98
+ pathname.startsWith("/api/") ||
99
+ pathname.startsWith("/mcp") ||
100
+ (observability && pathname.startsWith("/health/"))
101
+ ) {
102
+ // Overwrite, never append: a client-set x-forwarded-for must not pick its
103
+ // own rate-limit bucket. Behind a proxy of your own, pass the proxy's
104
+ // header through instead and raise TRUST's hops in services.ts.
105
+ const headers = new Headers(req.headers)
106
+ headers.set("x-forwarded-for", ip)
107
+ return app.fetch(new Request(req, { headers }))
108
+ }
109
+ // web:begin
110
+ // A file (it has an extension) or the app's index.html for its routes.
111
+ if (/\.[a-z0-9]+$/i.test(pathname)) {
112
+ const path = normalize(join(DIST, pathname))
113
+ const found = path.startsWith(DIST) ? await file(path) : null
114
+ return found ?? new Response("Not found", { status: 404 })
115
+ }
116
+ const index = await file(join(DIST, "index.html"))
117
+ if (index) return index
118
+ return new Response("No web build yet: run `build`, or use `dev` and open Vite's URL.", {
119
+ status: 404,
120
+ })
121
+ // web:end
122
+ return new Response("Not found", { status: 404 }) // @!web
123
+ }
124
+
125
+ // node:http runs under Node and Deno alike: requests in, the fetch-style
126
+ // handler above, responses streamed back out.
127
+ const server = createServer(async (req, res) => {
128
+ try {
129
+ const headers = new Headers()
130
+ for (const [key, value] of Object.entries(req.headers))
131
+ if (value !== undefined) headers.set(key, Array.isArray(value) ? value.join(", ") : value)
132
+ const method = req.method ?? "GET"
133
+ const response = await handle(
134
+ new Request(`http://${req.headers.host ?? "localhost"}${req.url ?? "/"}`, {
135
+ method,
136
+ headers,
137
+ body:
138
+ method === "GET" || method === "HEAD"
139
+ ? undefined
140
+ : (Readable.toWeb(req) as unknown as ReadableStream),
141
+ // Required by fetch for a streamed request body.
142
+ duplex: "half",
143
+ } as RequestInit),
144
+ req.socket.remoteAddress ?? "",
145
+ )
146
+ // Headers iterate set-cookie once per cookie; writeHead takes a flat list.
147
+ res.writeHead(response.status, [...response.headers].flat())
148
+ if (response.body) Readable.fromWeb(response.body as never).pipe(res)
149
+ else res.end()
150
+ } catch (err) {
151
+ console.error(err)
152
+ if (!res.headersSent) res.writeHead(500, { "content-type": "application/json" })
153
+ res.end(JSON.stringify({ success: false, error: "Internal error" }))
154
+ }
155
+ })
156
+ server.listen(env.PORT, () => console.log(`Listening on http://localhost:${env.PORT}`))
157
+ // !bun:end
@@ -1,28 +1,52 @@
1
+ // admin:begin
1
2
  import { type AdminContext, type Authorize, defineAdmin, roles } from "@dapplelight/signet-db/admin"
3
+ // admin:end
4
+ // payments:begin
2
5
  import { createEntitlements } from "@dapplelight/signet-db/entitlements"
3
- import { createGrowth } from "@dapplelight/signet-db/growth"
6
+ // payments:end
7
+ import { createGrowth } from "@dapplelight/signet-db/growth" // @growth
8
+ // orgs:begin
4
9
  import { createOrgs } from "@dapplelight/signet-db/orgs"
10
+ // orgs:end
11
+ // privacy:begin
5
12
  import { createPrivacy } from "@dapplelight/signet-db/privacy"
13
+ // privacy:end
14
+ // payments:begin
6
15
  import { createPayments, sqlStore } from "@dapplelight/signet-payments"
7
16
  import { razorpay } from "@dapplelight/signet-payments/razorpay"
17
+ // payments:end
8
18
  import type { KeyValue } from "@dapplelight/signet-server/adapters"
19
+ // auth:begin
9
20
  import { kvRateLimitStore } from "@dapplelight/signet-server/adapters"
21
+ // auth:end
22
+ // account:begin
10
23
  import { kvApiKeyStore } from "@dapplelight/signet-server/auth/api-keys"
24
+ // account:end
25
+ // auth:begin
11
26
  import { devSmsSender, type SmsSender } from "@dapplelight/signet-server/auth/otp"
12
27
  import { kvSessionStore } from "@dapplelight/signet-server/auth/sessions"
28
+ // auth:end
29
+ // notifications:begin
13
30
  import {
14
31
  createNotifier,
15
32
  defineTemplates,
16
33
  kvNotifyStore,
17
34
  } from "@dapplelight/signet-server/notify/notifier"
35
+ // notifications:end
36
+ import type { LevelSetting } from "@dapplelight/signet-server/observability/logger"
37
+ // notifications:begin
18
38
  import { eq } from "drizzle-orm"
19
39
  import { z } from "zod"
40
+ // notifications:end
20
41
  import type { Db } from "./db/index.ts"
21
- import * as schema from "./db/schema.ts"
22
- import { env } from "./env.ts"
42
+ import * as schema from "./db/schema.ts" // @notifications|payments|privacy|growth|orgs|admin
43
+ import { env } from "./env.ts" // @auth
44
+ // payments:begin
23
45
  import { plans } from "./plans.ts"
24
46
 
25
47
  export { PLAN_DISPLAY, type PlanId, plans } from "./plans.ts"
48
+ // payments:end
49
+ // privacy:begin
26
50
 
27
51
  /** DPDP consent purposes the privacy screen lists. Bump NOTICE_VERSION when the notice text changes. */
28
52
  export const PURPOSES = [
@@ -38,6 +62,8 @@ export const PURPOSES = [
38
62
  },
39
63
  ] as const
40
64
  export const NOTICE_VERSION = "2026-01-01"
65
+ // privacy:end
66
+ // notifications:begin
41
67
 
42
68
  /** In-app notification templates. Add email, SMS or WhatsApp variants per event as you need them. */
43
69
  export const templates = defineTemplates({
@@ -52,6 +78,7 @@ export const templates = defineTemplates({
52
78
  },
53
79
  },
54
80
  },
81
+ // payments:begin
55
82
  "billing.plan_changed": {
56
83
  category: "billing",
57
84
  data: z.object({ plan: z.string() }),
@@ -63,13 +90,16 @@ export const templates = defineTemplates({
63
90
  },
64
91
  },
65
92
  },
93
+ // payments:end
66
94
  })
95
+ // notifications:end
67
96
 
68
97
  /**
69
98
  * Where the client IP comes from: server.ts overwrites x-forwarded-for with the
70
99
  * socket's address, so one hop. Behind your own proxy, see server.ts.
71
100
  */
72
101
  export const TRUST = { forwardedHops: 1 } as const
102
+ // admin:begin
73
103
 
74
104
  /** Users' columns only an admin may set: who someone is, and what they may do. */
75
105
  const ADMIN_ONLY_USER_COLUMNS = ["role", "phone"]
@@ -86,19 +116,42 @@ const adminAuthorize: Authorize<AdminContext> = (ctx, check) =>
86
116
  Object.keys(check.input ?? {}).some((k) => ADMIN_ONLY_USER_COLUMNS.includes(k))
87
117
  ? false
88
118
  : byRole(ctx, check)
119
+ // admin:end
89
120
 
90
121
  export type Deps = {
91
122
  db: Db
92
123
  /** Raw SQL with `?` placeholders, for signet-payments' store. */
93
124
  query: (sql: string, params: unknown[]) => Record<string, unknown>[]
94
125
  kv: KeyValue
126
+ // auth:begin
95
127
  /** Sends one-time codes. Default: printed to the console, development only. */
96
128
  sms?: SmsSender
129
+ // auth:end
130
+ /** Request logs, spans and health routes. Absent: none of them, and no /health. */
131
+ observability?: ObservabilityConfig
132
+ }
133
+
134
+ export type ObservabilityConfig = {
135
+ /** Set on every log line and span as the service name. */
136
+ serviceName: string
137
+ /** Log level. Default "info". */
138
+ level?: LevelSetting
139
+ /**
140
+ * Fields added to every log line, e.g. the trace id of the active span:
141
+ * `() => ({ traceId: trace.getActiveSpan()?.spanContext().traceId })` with
142
+ * `trace` from `@opentelemetry/api`. Default: none.
143
+ */
144
+ mixin?: () => Record<string, unknown>
97
145
  }
98
146
 
99
147
  /** Everything the routes use, built once per process. */
100
- export function createServices({ db, query, kv, sms }: Deps) {
148
+ // auth:begin
149
+ export function createServices({ db, query, kv, sms }: Deps) { // @payments
150
+ export function createServices({ db, kv, sms }: Deps) { // @!payments
151
+ // auth:end
152
+ export function createServices({ db, kv }: Deps) { // @!auth
101
153
  const orm = db.orm
154
+ // auth:begin
102
155
  const sessions = {
103
156
  cookieName: "session",
104
157
  secret: env.SESSION_SECRET,
@@ -113,6 +166,8 @@ export function createServices({ db, query, kv, sms }: Deps) {
113
166
  sender: sms ?? devSmsSender({ appEnv: env.APP_ENV }),
114
167
  rateLimit,
115
168
  }
169
+ // auth:end
170
+ // notifications:begin
116
171
  const notifier = createNotifier({
117
172
  channels: {},
118
173
  templates,
@@ -122,6 +177,8 @@ export function createServices({ db, query, kv, sms }: Deps) {
122
177
  return u ? { phone: u.phone, ...(u.email ? { email: u.email } : {}) } : null
123
178
  },
124
179
  })
180
+ // notifications:end
181
+ // payments:begin
125
182
  const entitlements = createEntitlements(db, {
126
183
  plans,
127
184
  default: "free",
@@ -151,34 +208,46 @@ export function createServices({ db, query, kv, sms }: Deps) {
151
208
  await entitlements.applyBillingEvent(event)
152
209
  },
153
210
  })
211
+ // payments:end
154
212
  return {
155
213
  db,
156
214
  orm,
157
215
  kv,
216
+ // auth:begin
158
217
  sessions,
159
218
  rateLimit,
160
219
  otp,
161
- apiKeys: kvApiKeyStore(kv),
162
- notifier,
220
+ // auth:end
221
+ apiKeys: kvApiKeyStore(kv), // @account
222
+ notifier, // @notifications
223
+ // payments:begin
163
224
  entitlements,
164
225
  payments,
226
+ // payments:end
227
+ // privacy:begin
165
228
  privacy: createPrivacy(db, {
166
229
  tables: schema,
167
230
  // What export covers and erasure deletes, children before parents.
168
- userTables: [schema.feedback, [schema.users, schema.users.id]],
231
+ userTables: [schema.feedback, [schema.users, schema.users.id]], // @growth
232
+ userTables: [[schema.users, schema.users.id]], // @!growth
169
233
  respondWithinMs: 30 * 86_400_000,
170
234
  }),
171
- growth: createGrowth(db, { tables: schema }),
235
+ // privacy:end
236
+ growth: createGrowth(db, { tables: schema }), // @growth
237
+ // orgs:begin
172
238
  // Orgs, roles (owner, admin, member) and invites. Add roles with
173
239
  // `roles: defineRoles({ ...DEFAULT_ORG_ROLES, ... })`.
174
240
  orgs: createOrgs(db, { tables: schema }),
175
241
  /** The org switch cookie: Secure everywhere but local http. */
176
242
  orgCookie: { secure: env.APP_ENV !== "development" },
243
+ // orgs:end
244
+ // admin:begin
177
245
  admin: defineAdmin(schema, {
178
246
  authorize: adminAuthorize,
179
247
  // Per table by SQL name: search, readonly, hidden columns, row actions.
180
248
  tables: { kv: false, idempotency_keys: false },
181
249
  }),
250
+ // admin:end
182
251
  }
183
252
  }
184
253
 
@@ -0,0 +1,51 @@
1
+ import { expect, spyOn, test } from "bun:test"
2
+ import { app, createApp, openDb, sqlKv } from "./helpers.ts"
3
+
4
+ test("observability is off unless configured: no /health, no log lines", async () => {
5
+ const lines: string[] = []
6
+ const spy = spyOn(console, "log").mockImplementation((l: string) => void lines.push(l))
7
+ try {
8
+ expect((await app.request("/health/live")).status).toBe(404)
9
+ expect((await app.request("/api/health")).status).toBe(200)
10
+ } finally {
11
+ spy.mockRestore()
12
+ }
13
+ expect(lines).toEqual([])
14
+ })
15
+
16
+ test("observability on: request logs, probes left out, /health/ready checks the database", async () => {
17
+ const lines: string[] = []
18
+ const spy = spyOn(console, "log").mockImplementation((l: string) => void lines.push(l))
19
+ try {
20
+ const { db, query } = openDb(":memory:")
21
+ const on = createApp({
22
+ db,
23
+ query,
24
+ kv: sqlKv(db.orm),
25
+ observability: { serviceName: "demo", mixin: () => ({ region: "test" }) },
26
+ })
27
+ const live = await on.request("/health/live")
28
+ expect(live.status).toBe(200)
29
+ expect(await live.json()).toEqual({ ok: true })
30
+ const ready = await on.request("/health/ready")
31
+ expect(ready.status).toBe(200)
32
+ expect(await ready.json()).toEqual({ ok: true, checks: { db: true } })
33
+ expect(lines).toEqual([]) // probes are not logged
34
+ const headers = { cookie: "session=s" }
35
+ const res = await on.request("/api/health?token=abc", { headers })
36
+ expect([res.status, await res.text()]).toEqual([200, '{"ok":true}'])
37
+ } finally {
38
+ spy.mockRestore()
39
+ }
40
+ const logged = lines.map((l) => JSON.parse(l) as Record<string, unknown>)
41
+ expect(logged.map((l) => l.msg)).toEqual(["request.started", "request.completed"])
42
+ expect(logged[1]).toMatchObject({
43
+ service: "demo",
44
+ region: "test",
45
+ method: "GET",
46
+ route: "/api/health",
47
+ status: 200,
48
+ })
49
+ expect(typeof logged[1]?.reqId).toBe("string")
50
+ expect(lines.join("\n")).not.toMatch(/token=abc|session=s/)
51
+ })
@@ -0,0 +1,51 @@
1
+ import { expect } from "bun:test" // @auth
2
+
3
+ // Shared by the API tests: one app over an in-memory database. bun test runs
4
+ // every file in one process, and the env is validated once, on first read, so
5
+ // it is set here, before the app is imported. CI has no env file; these are
6
+ // throwaway test values.
7
+ export const ADMIN = "+919000000001" // @auth
8
+ Object.assign(process.env, {
9
+ APP_ENV: "development",
10
+ // auth:begin
11
+ SESSION_SECRET: "test-session-secret-0123456789abcdef",
12
+ OTP_SECRET: "test-otp-secret-0123456789abcdef0123",
13
+ ADMIN_PHONES: ADMIN,
14
+ // auth:end
15
+ BILLING: "fake", // @payments
16
+ })
17
+ export const { createApp } = await import("../api/app.ts")
18
+ export const { openDb } = await import("../api/db/open.ts")
19
+ export const { sqlKv } = await import("../api/db/kv.ts")
20
+
21
+ // auth:begin
22
+ /** The last code sent to each phone. */
23
+ export const codes = new Map<string, string>()
24
+ // auth:end
25
+ export const { db, query } = openDb(":memory:")
26
+ export const app = createApp({
27
+ db,
28
+ query,
29
+ kv: sqlKv(db.orm),
30
+ sms: { send: async (to, message) => void codes.set(to, message.match(/\d{6}/)?.[0] ?? "") }, // @auth
31
+ })
32
+
33
+ export const post = (path: string, body: unknown, cookie = "", ip = "") =>
34
+ app.request(path, {
35
+ method: "POST",
36
+ headers: { "content-type": "application/json", cookie, "x-forwarded-for": ip },
37
+ body: JSON.stringify(body),
38
+ })
39
+ // auth:begin
40
+
41
+ let signIns = 0
42
+ /** Sign in with a one-time code; returns the session cookie. Each sign-in
43
+ * comes from its own address: codes are limited to 10 an hour per address. */
44
+ export async function signIn(phone: string): Promise<string> {
45
+ const ip = `10.0.0.${++signIns}`
46
+ expect((await post("/api/auth/otp", { phone }, "", ip)).status).toBe(200)
47
+ const res = await post("/api/auth/verify", { phone, code: codes.get(phone) })
48
+ expect(res.status).toBe(200)
49
+ return (res.headers.get("set-cookie") ?? "").split(";")[0] ?? ""
50
+ }
51
+ // auth:end
@@ -0,0 +1,44 @@
1
+ /// <reference types="bun" /> // @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
+ // bun:begin
6
+ const bun = process.execPath
7
+ const procs = [
8
+ Bun.spawn([bun, "--watch", "api/server.ts"], { stdio: ["inherit", "inherit", "inherit"] }),
9
+ Bun.spawn([bun, "x", "vite"], { stdio: ["inherit", "inherit", "inherit"] }),
10
+ ]
11
+ const stop = () => {
12
+ for (const p of procs) p.kill()
13
+ }
14
+ process.on("SIGINT", stop)
15
+ process.on("SIGTERM", stop)
16
+ const code = await Promise.race(procs.map((p) => p.exited))
17
+ stop()
18
+ process.exit(code)
19
+ // bun:end
20
+ // !bun:begin
21
+ import { spawn } from "node:child_process"
22
+ import { join } from "node:path"
23
+
24
+ const self = process.execPath // node or deno, whichever runs this
25
+ const api = ["--env-file-if-exists=.env", "--watch", "api/server.ts"] // @node
26
+ const api = ["run", "-A", "--env-file=.env", "--watch", "api/server.ts"] // @deno
27
+ const vite = join("node_modules", "vite", "bin", "vite.js") // @node
28
+ const vite = ["run", "-A", join("node_modules", "vite", "bin", "vite.js")] // @deno
29
+ const procs = [
30
+ spawn(self, api, { stdio: "inherit" }),
31
+ spawn(self, [vite], { stdio: "inherit" }), // @node
32
+ spawn(self, vite, { stdio: "inherit" }), // @deno
33
+ ]
34
+ const stop = () => {
35
+ for (const p of procs) p.kill()
36
+ }
37
+ process.on("SIGINT", stop)
38
+ process.on("SIGTERM", stop)
39
+ const code = await Promise.race(
40
+ procs.map((p) => new Promise<number>((done) => p.on("exit", (c) => done(c ?? 0)))),
41
+ )
42
+ stop()
43
+ process.exit(code)
44
+ // !bun:end