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.
- package/README.md +128 -7
- package/package.json +4 -3
- package/src/index.ts +338 -66
- package/template-api/_github/workflows/ci.yml +0 -3
- package/template-api/_mcp/test/mcp-off.test.ts +13 -0
- package/template-api/_mcp/test/mcp.test.ts +49 -0
- package/template-api/_targets/bun/Dockerfile +13 -0
- package/template-api/_targets/bun/_dockerignore +10 -0
- package/template-api/_targets/bun/src/server.ts +32 -0
- package/template-api/_targets/cloudflare/_github/workflows/ci.yml +24 -0
- package/template-api/_targets/cloudflare/src/index.ts +17 -0
- package/template-api/_targets/node/src/server.ts +55 -0
- package/template-api/_targets/vercel/index.ts +16 -0
- package/template-api/_targets/vercel/vercel.json +4 -0
- package/template-api/src/app.ts +77 -0
- package/template-api/src/env.ts +4 -0
- package/template-api/tsconfig.json +2 -1
- package/template-api/tsconfig.test.json +1 -1
- package/template-full/README.md +155 -0
- package/template-full/_github/workflows/ci.yml +22 -0
- package/template-full/_gitignore +9 -0
- package/template-full/_mcp/test/mcp.test.ts +55 -0
- package/template-full/api/app.ts +132 -0
- package/template-full/api/db/index.ts +10 -0
- package/template-full/api/db/kv.ts +54 -0
- package/template-full/api/db/open.ts +33 -0
- package/template-full/api/db/schema.ts +57 -0
- package/template-full/api/env.ts +44 -0
- package/template-full/api/plans.ts +23 -0
- package/template-full/api/routes/account.ts +63 -0
- package/template-full/api/routes/auth.ts +134 -0
- package/template-full/api/routes/billing.ts +44 -0
- package/template-full/api/routes/notifications.ts +59 -0
- package/template-full/api/routes/privacy.ts +52 -0
- package/template-full/api/server.ts +44 -0
- package/template-full/api/services.ts +185 -0
- package/template-full/biome.json +50 -0
- package/template-full/drizzle/0000_init.sql +155 -0
- package/template-full/drizzle/0001_orgs.sql +47 -0
- package/template-full/drizzle/meta/0000_snapshot.json +974 -0
- package/template-full/drizzle/meta/0001_snapshot.json +1270 -0
- package/template-full/drizzle/meta/_journal.json +20 -0
- package/template-full/drizzle.config.ts +9 -0
- package/template-full/e2e/smoke.spec.ts +152 -0
- package/template-full/index.html +17 -0
- package/template-full/playwright.config.ts +10 -0
- package/template-full/scripts/dev.ts +17 -0
- package/template-full/src/app.css +9 -0
- package/template-full/src/components/toaster.tsx +13 -0
- package/template-full/src/lib/api.ts +40 -0
- package/template-full/src/main.tsx +36 -0
- package/template-full/src/routeTree.gen.ts +297 -0
- package/template-full/src/router.test.ts +23 -0
- package/template-full/src/router.ts +17 -0
- package/template-full/src/routes/__root.tsx +9 -0
- package/template-full/src/routes/_app/account.tsx +64 -0
- package/template-full/src/routes/_app/admin.tsx +38 -0
- package/template-full/src/routes/_app/billing.tsx +40 -0
- package/template-full/src/routes/_app/index.tsx +33 -0
- package/template-full/src/routes/_app/notifications.tsx +72 -0
- package/template-full/src/routes/_app/org/index.tsx +38 -0
- package/template-full/src/routes/_app/org/members.tsx +86 -0
- package/template-full/src/routes/_app/org/new.tsx +45 -0
- package/template-full/src/routes/_app/privacy.tsx +48 -0
- package/template-full/src/routes/_app.tsx +88 -0
- package/template-full/src/routes/invite.$token.tsx +55 -0
- package/template-full/src/routes/login.tsx +36 -0
- package/template-full/test/api.test.ts +189 -0
- package/template-full/tsconfig.api.json +19 -0
- package/template-full/tsconfig.app.json +26 -0
- package/template-full/tsconfig.json +9 -0
- package/template-full/tsconfig.node.json +16 -0
- package/template-full/tsconfig.test.json +8 -0
- package/template-full/vite.config.ts +24 -0
- package/template-api/src/index.ts +0 -55
- /package/template-api/{wrangler.jsonc → _targets/cloudflare/wrangler.jsonc} +0 -0
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
// Node entry: the app in ./app.ts behind node:http. Node 22.18+ runs this file
|
|
3
|
+
// as is (type stripping), which is why relative imports carry `.ts`.
|
|
4
|
+
// Run `node src/server.ts`.
|
|
5
|
+
import { createServer } from "node:http"
|
|
6
|
+
import { Readable } from "node:stream"
|
|
7
|
+
import { memoryStore } from "@dapplelight/signet-server/middleware/rate-limit"
|
|
8
|
+
import { createApp } from "./app.ts"
|
|
9
|
+
|
|
10
|
+
const hops = process.env.TRUSTED_PROXY_HOPS
|
|
11
|
+
|
|
12
|
+
const app = createApp<Record<string, never>>({
|
|
13
|
+
// One process, so an in-memory count is exact. Running several replicas?
|
|
14
|
+
// Share the count with a store backed by Redis or a Durable Object.
|
|
15
|
+
store: memoryStore(),
|
|
16
|
+
// Behind proxies of your own, set TRUSTED_PROXY_HOPS to how many and the
|
|
17
|
+
// client IP comes from x-forwarded-for. Otherwise the header is replaced
|
|
18
|
+
// with the socket's peer address below.
|
|
19
|
+
trust: { forwardedHops: hops ? Number(hops) : 1 },
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
// A minimal node:http to fetch bridge: IncomingMessage in, Request to Hono,
|
|
23
|
+
// Response back out, streamed both ways.
|
|
24
|
+
const server = createServer(async (req, res) => {
|
|
25
|
+
try {
|
|
26
|
+
const headers = new Headers()
|
|
27
|
+
for (const [key, value] of Object.entries(req.headers)) {
|
|
28
|
+
if (value !== undefined) headers.set(key, Array.isArray(value) ? value.join(", ") : value)
|
|
29
|
+
}
|
|
30
|
+
// Overwrite, never append: a client-supplied x-forwarded-for must not pick its bucket.
|
|
31
|
+
if (!hops) headers.set("x-forwarded-for", req.socket.remoteAddress ?? "")
|
|
32
|
+
const method = req.method ?? "GET"
|
|
33
|
+
const hasBody = method !== "GET" && method !== "HEAD"
|
|
34
|
+
const response = await app.fetch(
|
|
35
|
+
new Request(`http://${req.headers.host ?? "localhost"}${req.url ?? "/"}`, {
|
|
36
|
+
method,
|
|
37
|
+
headers,
|
|
38
|
+
body: hasBody ? (Readable.toWeb(req) as unknown as ReadableStream) : undefined,
|
|
39
|
+
// Required by fetch for a streamed request body.
|
|
40
|
+
duplex: "half",
|
|
41
|
+
} as RequestInit),
|
|
42
|
+
)
|
|
43
|
+
// Headers iterate set-cookie once per cookie; writeHead takes a flat list.
|
|
44
|
+
res.writeHead(response.status, [...response.headers].flat())
|
|
45
|
+
if (response.body) Readable.fromWeb(response.body as never).pipe(res)
|
|
46
|
+
else res.end()
|
|
47
|
+
} catch (err) {
|
|
48
|
+
console.error(err)
|
|
49
|
+
if (!res.headersSent) res.writeHead(500, { "content-type": "application/json" })
|
|
50
|
+
res.end(JSON.stringify({ success: false, error: "Internal error" }))
|
|
51
|
+
}
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
const port = Number(process.env.PORT ?? 3000)
|
|
55
|
+
server.listen(port, () => console.log(`Listening on http://localhost:${port}`))
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// Vercel entry. Vercel deploys a Hono app with zero configuration from the
|
|
2
|
+
// default export of a root index.ts (vercel.json pins the "hono" preset).
|
|
3
|
+
// https://vercel.com/docs/frameworks/backend/hono
|
|
4
|
+
import { memoryStore } from "@dapplelight/signet-server/middleware/rate-limit"
|
|
5
|
+
import { createApp } from "./src/app.ts"
|
|
6
|
+
|
|
7
|
+
export default createApp<Record<string, never>>({
|
|
8
|
+
// Per function instance, so the count is approximate once Vercel runs
|
|
9
|
+
// several. For an exact, shared count use a Redis-backed store: Vercel KV is
|
|
10
|
+
// Upstash Redis from the Marketplace (https://vercel.com/docs/redis).
|
|
11
|
+
store: memoryStore(),
|
|
12
|
+
// Vercel overwrites x-forwarded-for with the client's IP and never forwards
|
|
13
|
+
// one a client sent (https://vercel.com/docs/headers/request-headers#x-forwarded-for),
|
|
14
|
+
// so the single address in it is the one to trust.
|
|
15
|
+
trust: { forwardedHops: 1 },
|
|
16
|
+
})
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { initRuntimeEnv } from "@dapplelight/signet-server/env"
|
|
2
|
+
import { errorHandler } from "@dapplelight/signet-server/http"
|
|
3
|
+
import { zValidator } from "@dapplelight/signet-server/http/validate"
|
|
4
|
+
// mcp:begin
|
|
5
|
+
import { appTools } from "@dapplelight/signet-server/mcp"
|
|
6
|
+
import { mountMcp } from "@dapplelight/signet-server/mcp/hono"
|
|
7
|
+
// mcp:end
|
|
8
|
+
import { csrfMiddleware } from "@dapplelight/signet-server/middleware/csrf"
|
|
9
|
+
import { type RateLimitOptions, rateLimit } from "@dapplelight/signet-server/middleware/rate-limit"
|
|
10
|
+
import { requestId } from "@dapplelight/signet-server/middleware/request-id"
|
|
11
|
+
import { Hono } from "hono"
|
|
12
|
+
import { z } from "zod"
|
|
13
|
+
import { env } from "./env.ts"
|
|
14
|
+
|
|
15
|
+
type AppEnv<B> = { Bindings: B; Variables: { reqId: string } }
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The API. Each target's entry (src/index.ts on Workers, src/server.ts on Bun
|
|
19
|
+
* or Node, index.ts on Vercel) differs only in how it rate limits, so each
|
|
20
|
+
* passes its own store and key.
|
|
21
|
+
*/
|
|
22
|
+
export function createApp<B extends Record<string, unknown>>(
|
|
23
|
+
limit: Pick<RateLimitOptions<AppEnv<B>>, "store" | "trust" | "keyFor">,
|
|
24
|
+
) {
|
|
25
|
+
const app = new Hono<AppEnv<B>>()
|
|
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
|
+
// Blocks cross-site form POSTs that ride a session cookie; bearer-token calls
|
|
37
|
+
// skip it. Trusts only this API's own origin until you list your frontend's
|
|
38
|
+
// env key: csrfMiddleware({ originEnvKeys: ["WEB_URL"] }), the same keys you
|
|
39
|
+
// give corsMiddleware.
|
|
40
|
+
.use("/api/*", csrfMiddleware())
|
|
41
|
+
.use("/api/*", rateLimit<AppEnv<B>>({ ...limit, max: 60 }))
|
|
42
|
+
.get("/api/health", (c) => c.json({ ok: true }))
|
|
43
|
+
// mcp:begin
|
|
44
|
+
// Validated with zValidator, so it is also the MCP tool `post_api_echo`
|
|
45
|
+
// (see below). Describe it for the model with .describe(...).
|
|
46
|
+
// mcp:end
|
|
47
|
+
.post(
|
|
48
|
+
"/api/echo",
|
|
49
|
+
zValidator("json", z.object({ message: z.string().min(1) }).describe("Echo a message back")),
|
|
50
|
+
(c) => c.json({ message: c.req.valid("json").message }),
|
|
51
|
+
)
|
|
52
|
+
.onError(errorHandler({ isProduction }))
|
|
53
|
+
|
|
54
|
+
// mcp:begin
|
|
55
|
+
// MCP: every route validated with zValidator is a tool at /mcp
|
|
56
|
+
// that runs the route as the caller (their auth header and cookie go
|
|
57
|
+
// with it). GET routes are read tools; anything else asks the person first.
|
|
58
|
+
// asTool(false) on a route leaves it out. Turn it all off with MCP=off.
|
|
59
|
+
mountMcp(app, "/mcp", {
|
|
60
|
+
name: "api",
|
|
61
|
+
version: "0.0.0",
|
|
62
|
+
middleware: [async (c, next) => (env.MCP === "off" ? c.notFound() : next())],
|
|
63
|
+
tools: appTools(app),
|
|
64
|
+
})
|
|
65
|
+
// mcp:end
|
|
66
|
+
return app
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Fails closed: if the env does not validate, treat it as production so a 500
|
|
70
|
+
// hides its message instead of leaking it.
|
|
71
|
+
function isProduction(): boolean {
|
|
72
|
+
try {
|
|
73
|
+
return env.APP_ENV === "production"
|
|
74
|
+
} catch {
|
|
75
|
+
return true
|
|
76
|
+
}
|
|
77
|
+
}
|
package/template-api/src/env.ts
CHANGED
|
@@ -6,6 +6,10 @@ import { z } from "zod"
|
|
|
6
6
|
// Bindings that are not strings (RATE_LIMIT) are typed on the Hono app instead.
|
|
7
7
|
export const envSchema = z.object({
|
|
8
8
|
APP_ENV: z.enum(["development", "staging", "production"]).default("development"),
|
|
9
|
+
// mcp:begin
|
|
10
|
+
// The MCP endpoint at /mcp (src/app.ts). "off" answers it with a 404.
|
|
11
|
+
MCP: z.enum(["on", "off"]).default("on"),
|
|
12
|
+
// mcp:end
|
|
9
13
|
})
|
|
10
14
|
|
|
11
15
|
export type Env = z.infer<typeof envSchema>
|
|
@@ -0,0 +1,155 @@
|
|
|
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.
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
pull_request:
|
|
7
|
+
|
|
8
|
+
permissions:
|
|
9
|
+
contents: read
|
|
10
|
+
|
|
11
|
+
jobs:
|
|
12
|
+
verify:
|
|
13
|
+
runs-on: ubuntu-latest
|
|
14
|
+
steps:
|
|
15
|
+
- uses: actions/checkout@v4
|
|
16
|
+
- uses: oven-sh/setup-bun@v2
|
|
17
|
+
# Commit bun.lock: --frozen-lockfile fails the build if it is missing or stale.
|
|
18
|
+
- run: bun install --frozen-lockfile
|
|
19
|
+
- run: bun run lint
|
|
20
|
+
- run: bun run typecheck
|
|
21
|
+
- run: bun run test
|
|
22
|
+
- run: bun run build
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { expect, test } from "bun:test"
|
|
2
|
+
|
|
3
|
+
// The MCP endpoint at /mcp: every zValidator route is a tool that runs as the
|
|
4
|
+
// caller, and a write asks the person first.
|
|
5
|
+
// The same values as api.test.ts: bun test runs both in one process, and the
|
|
6
|
+
// env is validated once.
|
|
7
|
+
Object.assign(process.env, {
|
|
8
|
+
APP_ENV: "development",
|
|
9
|
+
SESSION_SECRET: "test-session-secret-0123456789abcdef",
|
|
10
|
+
OTP_SECRET: "test-otp-secret-0123456789abcdef0123",
|
|
11
|
+
ADMIN_PHONES: "+919000000001",
|
|
12
|
+
BILLING: "fake",
|
|
13
|
+
})
|
|
14
|
+
const { createApp } = await import("../api/app.ts")
|
|
15
|
+
const { openDb } = await import("../api/db/open.ts")
|
|
16
|
+
const { sqlKv } = await import("../api/db/kv.ts")
|
|
17
|
+
|
|
18
|
+
const { db, query } = openDb(":memory:")
|
|
19
|
+
const app = createApp({ db, query, kv: sqlKv(db.orm) })
|
|
20
|
+
|
|
21
|
+
const rpc = async (method: string, params = {}) => {
|
|
22
|
+
const res = await app.request("/mcp", {
|
|
23
|
+
method: "POST",
|
|
24
|
+
headers: {
|
|
25
|
+
"content-type": "application/json",
|
|
26
|
+
accept: "application/json, text/event-stream",
|
|
27
|
+
"mcp-protocol-version": "2025-11-25",
|
|
28
|
+
},
|
|
29
|
+
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
|
|
30
|
+
})
|
|
31
|
+
const text = await res.text()
|
|
32
|
+
const data = text.startsWith("{")
|
|
33
|
+
? text
|
|
34
|
+
: (
|
|
35
|
+
text
|
|
36
|
+
.split("\n")
|
|
37
|
+
.filter((l) => l.startsWith("data: "))
|
|
38
|
+
.pop() ?? ""
|
|
39
|
+
).slice(6)
|
|
40
|
+
return data ? JSON.parse(data) : null
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
test("validated routes are MCP tools", async () => {
|
|
44
|
+
const names = (await rpc("tools/list")).result.tools.map((t: { name: string }) => t.name)
|
|
45
|
+
expect(names).toContain("post_api_billing_checkout")
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
test("a write tool asks for approval first, and does nothing without it", async () => {
|
|
49
|
+
const body = await rpc("tools/call", {
|
|
50
|
+
name: "post_api_billing_checkout",
|
|
51
|
+
arguments: { plan: "pro" },
|
|
52
|
+
})
|
|
53
|
+
expect(body.result.isError).toBe(true)
|
|
54
|
+
expect(body.result.structuredContent.code).toBe("APPROVAL_REQUIRED")
|
|
55
|
+
})
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { sessionRoutes } from "@dapplelight/signet-server/auth/hono"
|
|
2
|
+
import { maskPhone } from "@dapplelight/signet-server/auth/otp"
|
|
3
|
+
import { errorHandler } from "@dapplelight/signet-server/http"
|
|
4
|
+
import { adminRoutes } from "@dapplelight/signet-server/http/admin"
|
|
5
|
+
import { ApiException } from "@dapplelight/signet-server/http/errors"
|
|
6
|
+
import { orgRoutes, tenant } from "@dapplelight/signet-server/http/orgs"
|
|
7
|
+
// mcp:begin
|
|
8
|
+
import { appTools } from "@dapplelight/signet-server/mcp"
|
|
9
|
+
import { mountMcp } from "@dapplelight/signet-server/mcp/hono"
|
|
10
|
+
// mcp:end
|
|
11
|
+
import { csrfMiddleware } from "@dapplelight/signet-server/middleware/csrf"
|
|
12
|
+
import { memoryStore, rateLimit } from "@dapplelight/signet-server/middleware/rate-limit"
|
|
13
|
+
import { requestId } from "@dapplelight/signet-server/middleware/request-id"
|
|
14
|
+
import { inArray } from "drizzle-orm"
|
|
15
|
+
import { Hono } from "hono"
|
|
16
|
+
import { type User, users } from "./db/schema.ts"
|
|
17
|
+
import { env } from "./env.ts"
|
|
18
|
+
import { accountRoutes } from "./routes/account.ts"
|
|
19
|
+
import { authRoutes, requireUser } from "./routes/auth.ts"
|
|
20
|
+
import { billingRoutes, billingWebhooks } from "./routes/billing.ts"
|
|
21
|
+
import { notificationRoutes } from "./routes/notifications.ts"
|
|
22
|
+
import { privacyRoutes } from "./routes/privacy.ts"
|
|
23
|
+
import { createServices, type Deps, TRUST } from "./services.ts"
|
|
24
|
+
|
|
25
|
+
export type AppEnv = { Variables: { reqId: string; user: User } }
|
|
26
|
+
|
|
27
|
+
/** Paths that need a signed-in user. Everything else under /api is public. */
|
|
28
|
+
const SIGNED_IN = [
|
|
29
|
+
"/api/account",
|
|
30
|
+
"/api/notifications",
|
|
31
|
+
"/api/privacy",
|
|
32
|
+
"/api/billing",
|
|
33
|
+
"/api/admin",
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
/** An invite link can be looked at before signing in; everything else under /api/orgs needs a user. */
|
|
37
|
+
const INVITE_PREVIEW = /^\/api\/orgs\/invites\/[^/]+$/
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The API. server.ts serves it (and the built web app) under Bun; tests call
|
|
41
|
+
* `createApp(deps).request(...)` with an in-memory database.
|
|
42
|
+
*/
|
|
43
|
+
export function createApp(deps: Deps) {
|
|
44
|
+
const s = createServices(deps)
|
|
45
|
+
const base = new Hono<AppEnv>()
|
|
46
|
+
.use("*", requestId())
|
|
47
|
+
// Blocks cross-site form posts riding the session cookie. The web app is
|
|
48
|
+
// served from this same origin, so nothing else needs trusting.
|
|
49
|
+
.use("/api/*", csrfMiddleware())
|
|
50
|
+
.use("/api/*", rateLimit<AppEnv>({ store: memoryStore(), trust: TRUST, max: 300 }))
|
|
51
|
+
for (const path of SIGNED_IN) base.use(`${path}/*`, requireUser(s))
|
|
52
|
+
const gate = requireUser(s)
|
|
53
|
+
base.use("/api/orgs/*", (c, next) =>
|
|
54
|
+
c.req.method === "GET" && INVITE_PREVIEW.test(c.req.path) ? next() : gate(c, next),
|
|
55
|
+
)
|
|
56
|
+
// Which org a request is for: the custom domain, a subdomain of
|
|
57
|
+
// ORG_ROOT_DOMAIN, the x-org header, or the cookie the switcher sets. It
|
|
58
|
+
// grants nothing: /api/orgs checks membership on every call.
|
|
59
|
+
base.use("/api/*", tenant({ orgs: s.orgs, rootDomain: env.ORG_ROOT_DOMAIN }))
|
|
60
|
+
|
|
61
|
+
const app = base
|
|
62
|
+
.get("/api/health", (c) => c.json({ ok: true }))
|
|
63
|
+
.route("/api/auth", authRoutes(s))
|
|
64
|
+
.route("/api/sessions", sessionRoutes(s.sessions))
|
|
65
|
+
.route("/api/account", accountRoutes(s))
|
|
66
|
+
.route("/api/notifications", notificationRoutes(s))
|
|
67
|
+
.route("/api/privacy", privacyRoutes(s))
|
|
68
|
+
.route("/api/billing", billingRoutes(s))
|
|
69
|
+
.route("/api/webhooks", billingWebhooks(s))
|
|
70
|
+
// Orgs: switch, settings, members, invites (signet-server orgRoutes).
|
|
71
|
+
// Guard your own org routes the same way: orgGuards({ orgs: s.orgs, userId })
|
|
72
|
+
// .requirePermission("projects:write"), then scoped(s.db, { orgId: currentTenant(c).id }).
|
|
73
|
+
.route(
|
|
74
|
+
"/api/orgs",
|
|
75
|
+
orgRoutes({
|
|
76
|
+
orgs: s.orgs,
|
|
77
|
+
userId: (c) => (c.get("user" as never) as User | undefined)?.id,
|
|
78
|
+
cookieOptions: s.orgCookie,
|
|
79
|
+
// Members are shown by name, else a masked phone.
|
|
80
|
+
users: async (ids) =>
|
|
81
|
+
Object.fromEntries(
|
|
82
|
+
s.orm
|
|
83
|
+
.select()
|
|
84
|
+
.from(users)
|
|
85
|
+
.where(inArray(users.id, ids))
|
|
86
|
+
.all()
|
|
87
|
+
.map((u) => [u.id, { name: u.name ?? maskPhone(u.phone) }]),
|
|
88
|
+
),
|
|
89
|
+
}),
|
|
90
|
+
)
|
|
91
|
+
// The operator's admin API over every org (signet-db defineAdmin, config
|
|
92
|
+
// in services.ts): platform roles readonly, staff and admin (ADMIN_PHONES)
|
|
93
|
+
// only; everyone else gets 403. Org owners manage their org under /org.
|
|
94
|
+
.route(
|
|
95
|
+
"/api/admin",
|
|
96
|
+
adminRoutes(s.admin, {
|
|
97
|
+
db: () => s.db,
|
|
98
|
+
ctx: (c) => {
|
|
99
|
+
const user = c.get("user" as never) as User
|
|
100
|
+
if (user.role === "user") throw new ApiException(403, "Admins only.", "FORBIDDEN")
|
|
101
|
+
return { actor: { type: "user" as const, id: user.id }, role: user.role }
|
|
102
|
+
},
|
|
103
|
+
}),
|
|
104
|
+
)
|
|
105
|
+
.onError(errorHandler({ isProduction }))
|
|
106
|
+
|
|
107
|
+
// mcp:begin
|
|
108
|
+
// MCP: every route validated with zValidator is a tool at /mcp that runs
|
|
109
|
+
// as the caller (their cookie or API key goes with it). GET routes are read
|
|
110
|
+
// tools; anything else asks the person first. Turn it off with MCP=off.
|
|
111
|
+
mountMcp(app, "/mcp", {
|
|
112
|
+
name: "__APP_NAME__",
|
|
113
|
+
version: "0.1.0",
|
|
114
|
+
middleware: [async (c, next) => (env.MCP === "off" ? c.notFound() : next())],
|
|
115
|
+
tools: appTools(app),
|
|
116
|
+
})
|
|
117
|
+
// mcp:end
|
|
118
|
+
return app
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** For the typed client in src/lib/api.ts: import it with `import type`. */
|
|
122
|
+
export type AppType = ReturnType<typeof createApp>
|
|
123
|
+
|
|
124
|
+
// Fails closed: an env that does not validate counts as production, so a 500
|
|
125
|
+
// hides its message instead of leaking it.
|
|
126
|
+
function isProduction(): boolean {
|
|
127
|
+
try {
|
|
128
|
+
return env.APP_ENV === "production"
|
|
129
|
+
} catch {
|
|
130
|
+
return true
|
|
131
|
+
}
|
|
132
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { SignetDb } from "@dapplelight/signet-db"
|
|
2
|
+
import type { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core"
|
|
3
|
+
import type * as schema from "./schema.ts"
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The Drizzle handle, typed without naming bun:sqlite, so the web app can
|
|
7
|
+
* import the API's types (src/lib/api.ts) without pulling in Bun's.
|
|
8
|
+
*/
|
|
9
|
+
export type Orm = BaseSQLiteDatabase<"sync", unknown, typeof schema>
|
|
10
|
+
export type Db = SignetDb<Orm>
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { KeyValue } from "@dapplelight/signet-server/adapters"
|
|
2
|
+
import { and, eq, gt, isNull, lte, or, sql } from "drizzle-orm"
|
|
3
|
+
import type { Orm } from "./index.ts"
|
|
4
|
+
import { kv } from "./schema.ts"
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* signet-server's `KeyValue` over the kv table. bun:sqlite runs each statement
|
|
8
|
+
* synchronously in one process, so `incr` is exact.
|
|
9
|
+
* ponytail: one process per database file; running several API replicas, move
|
|
10
|
+
* this to Upstash (`upstashKv` from @dapplelight/signet-server/adapters/upstash).
|
|
11
|
+
*/
|
|
12
|
+
export function sqlKv(orm: Orm): KeyValue {
|
|
13
|
+
const live = (key: string) =>
|
|
14
|
+
and(eq(kv.key, key), or(isNull(kv.expiresAt), gt(kv.expiresAt, Date.now())))
|
|
15
|
+
const expiry = (ttlSeconds?: number) => (ttlSeconds ? Date.now() + ttlSeconds * 1000 : null)
|
|
16
|
+
return {
|
|
17
|
+
async get(key) {
|
|
18
|
+
return orm.select({ value: kv.value }).from(kv).where(live(key)).get()?.value ?? null
|
|
19
|
+
},
|
|
20
|
+
async set(key, value, opts) {
|
|
21
|
+
const expiresAt = expiry(opts?.ttlSeconds)
|
|
22
|
+
orm
|
|
23
|
+
.insert(kv)
|
|
24
|
+
.values({ key, value, expiresAt })
|
|
25
|
+
.onConflictDoUpdate({ target: kv.key, set: { value, expiresAt } })
|
|
26
|
+
.run()
|
|
27
|
+
},
|
|
28
|
+
async delete(key) {
|
|
29
|
+
orm.delete(kv).where(eq(kv.key, key)).run()
|
|
30
|
+
},
|
|
31
|
+
async incr(key, ttlSeconds) {
|
|
32
|
+
// An expired counter starts again at 1 with a fresh TTL.
|
|
33
|
+
orm
|
|
34
|
+
.delete(kv)
|
|
35
|
+
.where(and(eq(kv.key, key), lte(kv.expiresAt, Date.now())))
|
|
36
|
+
.run()
|
|
37
|
+
const row = orm
|
|
38
|
+
.insert(kv)
|
|
39
|
+
.values({ key, value: "1", expiresAt: expiry(ttlSeconds) })
|
|
40
|
+
.onConflictDoUpdate({
|
|
41
|
+
target: kv.key,
|
|
42
|
+
set: { value: sql`cast(${kv.value} as integer) + 1` },
|
|
43
|
+
})
|
|
44
|
+
.returning({ value: kv.value })
|
|
45
|
+
.get()
|
|
46
|
+
return Number(row?.value)
|
|
47
|
+
},
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Drop expired rows; server.ts runs it hourly. */
|
|
52
|
+
export function pruneKv(orm: Orm): void {
|
|
53
|
+
orm.delete(kv).where(lte(kv.expiresAt, Date.now())).run()
|
|
54
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
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
|
+
}
|