create-signet-app 0.2.2 → 0.4.1

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 (76) hide show
  1. package/README.md +128 -7
  2. package/package.json +4 -3
  3. package/src/index.ts +338 -66
  4. package/template-api/_github/workflows/ci.yml +0 -3
  5. package/template-api/_mcp/test/mcp-off.test.ts +13 -0
  6. package/template-api/_mcp/test/mcp.test.ts +49 -0
  7. package/template-api/_targets/bun/Dockerfile +13 -0
  8. package/template-api/_targets/bun/_dockerignore +10 -0
  9. package/template-api/_targets/bun/src/server.ts +32 -0
  10. package/template-api/_targets/cloudflare/_github/workflows/ci.yml +24 -0
  11. package/template-api/_targets/cloudflare/src/index.ts +17 -0
  12. package/template-api/_targets/node/src/server.ts +55 -0
  13. package/template-api/_targets/vercel/index.ts +16 -0
  14. package/template-api/_targets/vercel/vercel.json +4 -0
  15. package/template-api/src/app.ts +77 -0
  16. package/template-api/src/env.ts +4 -0
  17. package/template-api/tsconfig.json +2 -1
  18. package/template-api/tsconfig.test.json +1 -1
  19. package/template-full/README.md +155 -0
  20. package/template-full/_github/workflows/ci.yml +22 -0
  21. package/template-full/_gitignore +9 -0
  22. package/template-full/_mcp/test/mcp.test.ts +55 -0
  23. package/template-full/api/app.ts +132 -0
  24. package/template-full/api/db/index.ts +10 -0
  25. package/template-full/api/db/kv.ts +54 -0
  26. package/template-full/api/db/open.ts +33 -0
  27. package/template-full/api/db/schema.ts +57 -0
  28. package/template-full/api/env.ts +44 -0
  29. package/template-full/api/plans.ts +23 -0
  30. package/template-full/api/routes/account.ts +63 -0
  31. package/template-full/api/routes/auth.ts +134 -0
  32. package/template-full/api/routes/billing.ts +44 -0
  33. package/template-full/api/routes/notifications.ts +59 -0
  34. package/template-full/api/routes/privacy.ts +52 -0
  35. package/template-full/api/server.ts +44 -0
  36. package/template-full/api/services.ts +185 -0
  37. package/template-full/biome.json +50 -0
  38. package/template-full/drizzle/0000_init.sql +155 -0
  39. package/template-full/drizzle/0001_orgs.sql +47 -0
  40. package/template-full/drizzle/meta/0000_snapshot.json +974 -0
  41. package/template-full/drizzle/meta/0001_snapshot.json +1270 -0
  42. package/template-full/drizzle/meta/_journal.json +20 -0
  43. package/template-full/drizzle.config.ts +9 -0
  44. package/template-full/e2e/smoke.spec.ts +152 -0
  45. package/template-full/index.html +17 -0
  46. package/template-full/playwright.config.ts +10 -0
  47. package/template-full/scripts/dev.ts +17 -0
  48. package/template-full/src/app.css +9 -0
  49. package/template-full/src/components/toaster.tsx +13 -0
  50. package/template-full/src/lib/api.ts +40 -0
  51. package/template-full/src/main.tsx +36 -0
  52. package/template-full/src/routeTree.gen.ts +297 -0
  53. package/template-full/src/router.test.ts +23 -0
  54. package/template-full/src/router.ts +17 -0
  55. package/template-full/src/routes/__root.tsx +9 -0
  56. package/template-full/src/routes/_app/account.tsx +64 -0
  57. package/template-full/src/routes/_app/admin.tsx +38 -0
  58. package/template-full/src/routes/_app/billing.tsx +40 -0
  59. package/template-full/src/routes/_app/index.tsx +33 -0
  60. package/template-full/src/routes/_app/notifications.tsx +72 -0
  61. package/template-full/src/routes/_app/org/index.tsx +38 -0
  62. package/template-full/src/routes/_app/org/members.tsx +86 -0
  63. package/template-full/src/routes/_app/org/new.tsx +45 -0
  64. package/template-full/src/routes/_app/privacy.tsx +48 -0
  65. package/template-full/src/routes/_app.tsx +88 -0
  66. package/template-full/src/routes/invite.$token.tsx +55 -0
  67. package/template-full/src/routes/login.tsx +36 -0
  68. package/template-full/test/api.test.ts +189 -0
  69. package/template-full/tsconfig.api.json +19 -0
  70. package/template-full/tsconfig.app.json +26 -0
  71. package/template-full/tsconfig.json +9 -0
  72. package/template-full/tsconfig.node.json +16 -0
  73. package/template-full/tsconfig.test.json +8 -0
  74. package/template-full/vite.config.ts +24 -0
  75. package/template-api/src/index.ts +0 -55
  76. /package/template-api/{wrangler.jsonc → _targets/cloudflare/wrangler.jsonc} +0 -0
@@ -0,0 +1,189 @@
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
+ })
@@ -0,0 +1,19 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "lib": ["ES2022", "DOM", "DOM.Iterable"],
5
+ "module": "ESNext",
6
+ "moduleResolution": "bundler",
7
+ "strict": true,
8
+ "noUnusedLocals": true,
9
+ "noUnusedParameters": true,
10
+ "skipLibCheck": true,
11
+ "allowImportingTsExtensions": true,
12
+ "verbatimModuleSyntax": true,
13
+ "isolatedModules": true,
14
+ "moduleDetection": "force",
15
+ "noEmit": true,
16
+ "types": ["bun"]
17
+ },
18
+ "include": ["api", "scripts", "test", "e2e", "drizzle.config.ts", "playwright.config.ts"]
19
+ }
@@ -0,0 +1,26 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "lib": ["ES2022", "DOM", "DOM.Iterable"],
5
+ "module": "ESNext",
6
+ "moduleResolution": "bundler",
7
+ "jsx": "react-jsx",
8
+ "strict": true,
9
+ "noUnusedLocals": true,
10
+ "noUnusedParameters": true,
11
+ "noFallthroughCasesInSwitch": true,
12
+ "skipLibCheck": true,
13
+ "allowImportingTsExtensions": true,
14
+ "verbatimModuleSyntax": true,
15
+ "isolatedModules": true,
16
+ "moduleDetection": "force",
17
+ "resolveJsonModule": true,
18
+ "noEmit": true,
19
+ "paths": {
20
+ "@/*": ["./src/*"]
21
+ },
22
+ "types": ["vite/client"]
23
+ },
24
+ "include": ["src"],
25
+ "exclude": ["src/**/*.test.ts", "src/**/*.test.tsx"]
26
+ }
@@ -0,0 +1,9 @@
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
+ }
@@ -0,0 +1,16 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "lib": ["ES2023"],
5
+ "module": "ESNext",
6
+ "moduleResolution": "bundler",
7
+ "strict": true,
8
+ "skipLibCheck": true,
9
+ "allowImportingTsExtensions": true,
10
+ "isolatedModules": true,
11
+ "moduleDetection": "force",
12
+ "noEmit": true,
13
+ "types": ["node"]
14
+ },
15
+ "include": ["vite.config.ts"]
16
+ }
@@ -0,0 +1,8 @@
1
+ {
2
+ "extends": "./tsconfig.app.json",
3
+ "compilerOptions": {
4
+ "types": ["vite/client", "bun"]
5
+ },
6
+ "include": ["src/**/*.test.ts", "src/**/*.test.tsx"],
7
+ "exclude": []
8
+ }
@@ -0,0 +1,24 @@
1
+ import path from "node:path"
2
+ import tailwindcss from "@tailwindcss/vite"
3
+ import { tanstackRouter } from "@tanstack/router-plugin/vite"
4
+ import react from "@vitejs/plugin-react"
5
+ import { defineConfig } from "vite"
6
+
7
+ // The API (api/server.ts) listens on PORT, 3000 by default. In dev, Vite
8
+ // proxies /api and /mcp to it, so the browser sees one origin, as it does in
9
+ // production where api/server.ts also serves the built app.
10
+ const api = `http://localhost:${process.env.PORT ?? 3000}`
11
+
12
+ export default defineConfig({
13
+ plugins: [
14
+ // Must come before react(): it generates src/routeTree.gen.ts from
15
+ // src/routes and splits each route into its own chunk.
16
+ tanstackRouter({ target: "react", autoCodeSplitting: true, quoteStyle: "double" }),
17
+ react(),
18
+ tailwindcss(),
19
+ ],
20
+ resolve: {
21
+ alias: { "@": path.resolve(import.meta.dirname, "./src") },
22
+ },
23
+ server: { proxy: { "/api": api, "/mcp": api } },
24
+ })
@@ -1,55 +0,0 @@
1
- import { initRuntimeEnv } from "@dapplelight/signet-server/env"
2
- import { errorHandler } from "@dapplelight/signet-server/http"
3
- import { parseBody } from "@dapplelight/signet-server/http/validate"
4
- import { rateLimit } from "@dapplelight/signet-server/middleware/rate-limit"
5
- import {
6
- durableObjectStore,
7
- type RateLimitNamespace,
8
- } from "@dapplelight/signet-server/middleware/rate-limit-do"
9
- import { requestId } from "@dapplelight/signet-server/middleware/request-id"
10
- import { Hono } from "hono"
11
- import { z } from "zod"
12
- import { env } from "./env"
13
-
14
- // The Durable Object behind the rate limiter. wrangler.jsonc binds it as
15
- // RATE_LIMIT and its first migration creates it. A Worker entry may export only
16
- // handlers and classes like this one — workerd rejects anything else (a string
17
- // constant) with "Incorrect type for map entry".
18
- export { RateLimitCounter } from "@dapplelight/signet-server/middleware/rate-limit-do"
19
-
20
- type AppEnv = {
21
- Bindings: { RATE_LIMIT: RateLimitNamespace; APP_ENV?: string }
22
- Variables: { reqId: string }
23
- }
24
-
25
- const app = new Hono<AppEnv>()
26
- // Bindings arrive per request on Workers. Hand them over first, then read
27
- // vars through the validated `env` from ./env. Reading env.APP_ENV here
28
- // validates on the first request, so a bad or missing var fails loudly
29
- // instead of whenever a handler happens to read it.
30
- .use("*", async (c, next) => {
31
- initRuntimeEnv(c.env)
32
- void env.APP_ENV
33
- await next()
34
- })
35
- .use("*", requestId())
36
- // Exact per-IP limit: one Durable Object per scope:key.
37
- .use("/api/*", rateLimit<AppEnv>({ store: (c) => durableObjectStore(c.env.RATE_LIMIT), max: 60 }))
38
- .get("/api/health", (c) => c.json({ ok: true }))
39
- .post("/api/echo", async (c) => {
40
- const { message } = await parseBody(c, z.object({ message: z.string().min(1) }))
41
- return c.json({ message })
42
- })
43
- .onError(errorHandler({ isProduction }))
44
-
45
- // Fails closed: if the env does not validate, treat it as production so a 500
46
- // hides its message instead of leaking it.
47
- function isProduction(): boolean {
48
- try {
49
- return env.APP_ENV === "production"
50
- } catch {
51
- return true
52
- }
53
- }
54
-
55
- export default app