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,57 @@
|
|
|
1
|
+
import {
|
|
2
|
+
auditLog,
|
|
3
|
+
entitlementTables,
|
|
4
|
+
growthTables,
|
|
5
|
+
id,
|
|
6
|
+
idempotencyKeys,
|
|
7
|
+
orgTables,
|
|
8
|
+
privacyTables,
|
|
9
|
+
timestamps,
|
|
10
|
+
} from "@dapplelight/signet-db/columns/sqlite"
|
|
11
|
+
import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core"
|
|
12
|
+
|
|
13
|
+
// The whole database. Change a table here, then `db:generate` writes the
|
|
14
|
+
// migration into drizzle/ and the API applies it on its next start.
|
|
15
|
+
|
|
16
|
+
export const ROLES = ["user", "readonly", "staff", "admin"] as const
|
|
17
|
+
|
|
18
|
+
export const users = sqliteTable("users", {
|
|
19
|
+
id: id(),
|
|
20
|
+
phone: text("phone").notNull().unique(),
|
|
21
|
+
name: text("name"),
|
|
22
|
+
email: text("email"),
|
|
23
|
+
/** readonly, staff and admin can open /admin (signet-db's DEFAULT_ROLES). */
|
|
24
|
+
role: text("role", { enum: ROLES }).notNull().default("user"),
|
|
25
|
+
...timestamps(),
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Sessions, one-time codes, API keys, the notification inbox and prefs, and
|
|
30
|
+
* rate-limit counters: signet-server keeps each in a key-value store, and this
|
|
31
|
+
* table is that store (api/db/kv.ts). Rows past expires_at are ignored, then
|
|
32
|
+
* pruned hourly.
|
|
33
|
+
*/
|
|
34
|
+
export const kv = sqliteTable("kv", {
|
|
35
|
+
key: text("key").primaryKey(),
|
|
36
|
+
value: text("value").notNull(),
|
|
37
|
+
/** Epoch ms; null never expires. */
|
|
38
|
+
expiresAt: integer("expires_at"),
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
/** Every admin, plan and privacy write, with before and after. */
|
|
42
|
+
export const audit = auditLog()
|
|
43
|
+
/** Billing events apply once. */
|
|
44
|
+
export const idempotency = idempotencyKeys()
|
|
45
|
+
|
|
46
|
+
export const { subjectPlans, entitlementOverrides, usageCounters } = entitlementTables()
|
|
47
|
+
export const { waitlist, invites, referralCodes, referrals, marks, feedback } = growthTables()
|
|
48
|
+
export const { consents, dataRequests } = privacyTables()
|
|
49
|
+
/**
|
|
50
|
+
* Organisations: every user gets a personal one at sign-up and can make more,
|
|
51
|
+
* invite people and give them roles (api/services.ts, routes under /api/orgs).
|
|
52
|
+
* Give your own tables an `orgId: text("org_id").notNull()` column and read
|
|
53
|
+
* them through `scoped(s.db, { orgId })`, so each org only sees its own rows.
|
|
54
|
+
*/
|
|
55
|
+
export const { organizations, memberships, invitations, orgRoles } = orgTables()
|
|
56
|
+
|
|
57
|
+
export type User = typeof users.$inferSelect
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { createEnv } from "@dapplelight/signet-server/env"
|
|
2
|
+
import { z } from "zod"
|
|
3
|
+
|
|
4
|
+
// Every var and secret the API reads, declared once. Read them as `env.KEY`,
|
|
5
|
+
// never from process.env directly. Bun loads the env file on its own;
|
|
6
|
+
// create-signet-app wrote one with fresh secrets. It is gitignored, so set
|
|
7
|
+
// these on your host too.
|
|
8
|
+
export const envSchema = z.object({
|
|
9
|
+
APP_ENV: z.enum(["development", "staging", "production"]).default("development"),
|
|
10
|
+
PORT: z.coerce.number().default(3000),
|
|
11
|
+
/** The SQLite file. ":memory:" for a throwaway database. */
|
|
12
|
+
DATABASE_PATH: z.string().default("data/app.db"),
|
|
13
|
+
/** Signs session cookies. 32+ random characters, different per environment. */
|
|
14
|
+
SESSION_SECRET: z.string().min(32),
|
|
15
|
+
/** Keys the stored one-time-code hashes. 32+ random characters. */
|
|
16
|
+
OTP_SECRET: z.string().min(32),
|
|
17
|
+
/** Comma-separated phone numbers (E.164) that get the admin role on sign-in. */
|
|
18
|
+
ADMIN_PHONES: z.string().default(""),
|
|
19
|
+
/**
|
|
20
|
+
* "fake": Upgrade switches the plan at once and no money moves. Refused in
|
|
21
|
+
* staging and production. "razorpay": webhooks through signet-payments
|
|
22
|
+
* (see README).
|
|
23
|
+
*/
|
|
24
|
+
BILLING: z.enum(["fake", "razorpay"]).default("fake"),
|
|
25
|
+
/**
|
|
26
|
+
* Your app's own domain, e.g. "app.example.com": then acme.app.example.com
|
|
27
|
+
* opens the org with slug "acme". Hosts outside it are looked up as an
|
|
28
|
+
* org's custom domain (Org settings). Unset, the org comes from the
|
|
29
|
+
* x-org header or the switch cookie, which is all local development needs.
|
|
30
|
+
*/
|
|
31
|
+
ORG_ROOT_DOMAIN: z.string().optional(),
|
|
32
|
+
RAZORPAY_KEY_ID: z.string().optional(),
|
|
33
|
+
RAZORPAY_KEY_SECRET: z.string().optional(),
|
|
34
|
+
RAZORPAY_WEBHOOK_SECRET: z.string().optional(),
|
|
35
|
+
// mcp:begin
|
|
36
|
+
/** The MCP endpoint at /mcp (api/app.ts). "off" answers it with a 404. */
|
|
37
|
+
MCP: z.enum(["on", "off"]).default("on"),
|
|
38
|
+
// mcp:end
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
export type Env = z.infer<typeof envSchema>
|
|
42
|
+
|
|
43
|
+
/** Validated on first read, not at import. */
|
|
44
|
+
export const env = createEnv(envSchema)
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { definePlans } from "@dapplelight/signet-db/entitlements"
|
|
2
|
+
|
|
3
|
+
// Shared by the API and the billing page, so keep it free of server code.
|
|
4
|
+
|
|
5
|
+
/** The plans. Declare lowest first; `free` is what everyone starts on. */
|
|
6
|
+
export const plans = definePlans({
|
|
7
|
+
free: { features: [], limits: { projects: 3 } },
|
|
8
|
+
pro: { features: ["export", "priority-support"], limits: { projects: 100 } },
|
|
9
|
+
})
|
|
10
|
+
export type PlanId = keyof typeof plans
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* What the billing page shows for each plan, merged with `plans` by
|
|
14
|
+
* `plansFromEntitlements`. Amounts in minor units (paise).
|
|
15
|
+
*/
|
|
16
|
+
export const PLAN_DISPLAY = {
|
|
17
|
+
free: { name: "Free", description: "Three projects, to try it out" },
|
|
18
|
+
pro: {
|
|
19
|
+
name: "Pro",
|
|
20
|
+
description: "A hundred projects, export, priority support",
|
|
21
|
+
prices: { month: { amount: 49900, currency: "INR" } },
|
|
22
|
+
},
|
|
23
|
+
} satisfies Record<PlanId, { name: string; description: string; prices?: object }>
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { createApiKey, listApiKeys, revokeApiKey } from "@dapplelight/signet-server/auth/api-keys"
|
|
2
|
+
import { ApiException } from "@dapplelight/signet-server/http"
|
|
3
|
+
import { zValidator } from "@dapplelight/signet-server/http/validate"
|
|
4
|
+
import { eq } from "drizzle-orm"
|
|
5
|
+
import { Hono } from "hono"
|
|
6
|
+
import { z } from "zod"
|
|
7
|
+
import type { AppEnv } from "../app.ts"
|
|
8
|
+
import { users } from "../db/schema.ts"
|
|
9
|
+
import type { Services } from "../services.ts"
|
|
10
|
+
import { publicUser } from "./auth.ts"
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* GET /me the signed-in user and their plan
|
|
14
|
+
* PATCH /me { name?, email? }
|
|
15
|
+
* GET /api-keys { keys }
|
|
16
|
+
* POST /api-keys { name } → { token } (shown once)
|
|
17
|
+
* DELETE /api-keys/:id
|
|
18
|
+
*/
|
|
19
|
+
export const accountRoutes = (s: Services) =>
|
|
20
|
+
new Hono<AppEnv>()
|
|
21
|
+
.get("/me", async (c) => {
|
|
22
|
+
const user = c.get("user")
|
|
23
|
+
const { plan } = await s.entitlements.get(user.id)
|
|
24
|
+
return c.json({ user: publicUser(user), plan })
|
|
25
|
+
})
|
|
26
|
+
.patch(
|
|
27
|
+
"/me",
|
|
28
|
+
zValidator(
|
|
29
|
+
"json",
|
|
30
|
+
z.object({
|
|
31
|
+
name: z.string().trim().min(1).max(80).optional(),
|
|
32
|
+
email: z.email().optional(),
|
|
33
|
+
}),
|
|
34
|
+
),
|
|
35
|
+
(c) => {
|
|
36
|
+
const user = s.orm
|
|
37
|
+
.update(users)
|
|
38
|
+
.set(c.req.valid("json"))
|
|
39
|
+
.where(eq(users.id, c.get("user").id))
|
|
40
|
+
.returning()
|
|
41
|
+
.get()
|
|
42
|
+
if (!user) throw new ApiException(404, "Account not found.", "NOT_FOUND")
|
|
43
|
+
return c.json({ user: publicUser(user) })
|
|
44
|
+
},
|
|
45
|
+
)
|
|
46
|
+
.get("/api-keys", async (c) => c.json({ keys: await listApiKeys(s.apiKeys, c.get("user").id) }))
|
|
47
|
+
.post(
|
|
48
|
+
"/api-keys",
|
|
49
|
+
zValidator("json", z.object({ name: z.string().trim().min(1).max(100) })),
|
|
50
|
+
async (c) => {
|
|
51
|
+
const { token, key } = await createApiKey(s.apiKeys, {
|
|
52
|
+
sub: c.get("user").id,
|
|
53
|
+
name: c.req.valid("json").name,
|
|
54
|
+
prefix: "app",
|
|
55
|
+
})
|
|
56
|
+
return c.json({ token, key }, 201)
|
|
57
|
+
},
|
|
58
|
+
)
|
|
59
|
+
.delete("/api-keys/:id", async (c) => {
|
|
60
|
+
if (!(await revokeApiKey(s.apiKeys, c.get("user").id, c.req.param("id"))))
|
|
61
|
+
throw new ApiException(404, "Key not found.", "NOT_FOUND")
|
|
62
|
+
return c.json({ revoked: 1 })
|
|
63
|
+
})
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { requireStoredSession } from "@dapplelight/signet-server/auth/hono"
|
|
2
|
+
import {
|
|
3
|
+
maskPhone,
|
|
4
|
+
type OtpVerifyResult,
|
|
5
|
+
requestPhoneOtp,
|
|
6
|
+
verifyPhoneOtp,
|
|
7
|
+
} from "@dapplelight/signet-server/auth/otp"
|
|
8
|
+
import {
|
|
9
|
+
clearCookie,
|
|
10
|
+
readSessionCookie,
|
|
11
|
+
sessionCookie,
|
|
12
|
+
} from "@dapplelight/signet-server/auth/session"
|
|
13
|
+
import {
|
|
14
|
+
startSession,
|
|
15
|
+
type ValidSession,
|
|
16
|
+
validateSession,
|
|
17
|
+
} from "@dapplelight/signet-server/auth/sessions"
|
|
18
|
+
import { ApiException } from "@dapplelight/signet-server/http"
|
|
19
|
+
import { orgCookie } from "@dapplelight/signet-server/http/orgs"
|
|
20
|
+
import { zValidator } from "@dapplelight/signet-server/http/validate"
|
|
21
|
+
import { clientIp } from "@dapplelight/signet-server/middleware/rate-limit"
|
|
22
|
+
import { eq } from "drizzle-orm"
|
|
23
|
+
import { Hono, type MiddlewareHandler } from "hono"
|
|
24
|
+
import { z } from "zod"
|
|
25
|
+
import type { AppEnv } from "../app.ts"
|
|
26
|
+
import { type User, users } from "../db/schema.ts"
|
|
27
|
+
import { env } from "../env.ts"
|
|
28
|
+
import { type Services, TRUST } from "../services.ts"
|
|
29
|
+
|
|
30
|
+
/** The user fields the web app sees. */
|
|
31
|
+
export const publicUser = ({ id, phone, name, email, role }: User) => ({
|
|
32
|
+
id,
|
|
33
|
+
phone,
|
|
34
|
+
name,
|
|
35
|
+
email,
|
|
36
|
+
role,
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
const VERIFY_ERRORS: Record<Exclude<OtpVerifyResult, { ok: true }>["code"], string> = {
|
|
40
|
+
INVALID_PHONE: "Enter a valid phone number.",
|
|
41
|
+
CODE_EXPIRED: "That code has expired. Send a new one.",
|
|
42
|
+
INVALID_CODE: "That code is not right.",
|
|
43
|
+
TOO_MANY_ATTEMPTS: "Too many tries. Send a new code.",
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Gate on a live stored session, then load its user into `c.get("user")`. */
|
|
47
|
+
export function requireUser(s: Services): MiddlewareHandler<AppEnv> {
|
|
48
|
+
const gate = requireStoredSession(s.sessions)
|
|
49
|
+
return (c, next) =>
|
|
50
|
+
gate(c, async () => {
|
|
51
|
+
const session = c.get("session" as never) as ValidSession
|
|
52
|
+
const user = s.orm.select().from(users).where(eq(users.id, session.record.sub)).get()
|
|
53
|
+
if (!user) throw new ApiException(401, "Sign in again.", "UNAUTHORIZED")
|
|
54
|
+
c.set("user", user)
|
|
55
|
+
await next()
|
|
56
|
+
})
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Phone one-time-code sign-in. A first sign-in creates the user and their
|
|
61
|
+
* personal org (they own it); numbers in ADMIN_PHONES get the platform admin
|
|
62
|
+
* role, which opens /admin across every org.
|
|
63
|
+
*
|
|
64
|
+
* POST /otp { phone } sends a code (printed to the console in development)
|
|
65
|
+
* POST /verify { phone, code } sets the session cookie, returns the user
|
|
66
|
+
* POST /sign-out revokes this session
|
|
67
|
+
*/
|
|
68
|
+
export const authRoutes = (s: Services) =>
|
|
69
|
+
new Hono<AppEnv>()
|
|
70
|
+
.post("/otp", zValidator("json", z.object({ phone: z.string().min(6).max(20) })), async (c) => {
|
|
71
|
+
const r = await requestPhoneOtp(s.otp, {
|
|
72
|
+
phone: c.req.valid("json").phone,
|
|
73
|
+
ip: clientIp(c, TRUST),
|
|
74
|
+
})
|
|
75
|
+
if (!r.ok)
|
|
76
|
+
throw r.code === "RATE_LIMITED"
|
|
77
|
+
? new ApiException(429, "Too many codes. Try again later.", "RATE_LIMITED")
|
|
78
|
+
: new ApiException(400, VERIFY_ERRORS.INVALID_PHONE, r.code)
|
|
79
|
+
return c.json({ to: maskPhone(r.phone), expiresInSeconds: r.expiresInSeconds })
|
|
80
|
+
})
|
|
81
|
+
.post(
|
|
82
|
+
"/verify",
|
|
83
|
+
zValidator("json", z.object({ phone: z.string().min(6).max(20), code: z.string().min(4) })),
|
|
84
|
+
async (c) => {
|
|
85
|
+
const { phone, code } = c.req.valid("json")
|
|
86
|
+
const r = await verifyPhoneOtp(s.otp, { phone, code, ip: clientIp(c, TRUST) })
|
|
87
|
+
if (!r.ok) throw new ApiException(400, VERIFY_ERRORS[r.code], r.code)
|
|
88
|
+
|
|
89
|
+
const admin = env.ADMIN_PHONES.split(",")
|
|
90
|
+
.map((p) => p.trim())
|
|
91
|
+
.includes(r.phone)
|
|
92
|
+
let user = s.orm.select().from(users).where(eq(users.phone, r.phone)).get()
|
|
93
|
+
const isNew = !user
|
|
94
|
+
if (!user)
|
|
95
|
+
user = s.orm
|
|
96
|
+
.insert(users)
|
|
97
|
+
.values({ phone: r.phone, role: admin ? "admin" : "user" })
|
|
98
|
+
.returning()
|
|
99
|
+
.get()
|
|
100
|
+
else if (admin && user.role !== "admin")
|
|
101
|
+
user = s.orm
|
|
102
|
+
.update(users)
|
|
103
|
+
.set({ role: "admin" })
|
|
104
|
+
.where(eq(users.id, user.id))
|
|
105
|
+
.returning()
|
|
106
|
+
.get()
|
|
107
|
+
if (!user) throw new Error("Could not create the account.")
|
|
108
|
+
|
|
109
|
+
const { token } = await startSession(s.sessions, {
|
|
110
|
+
sub: user.id,
|
|
111
|
+
userAgent: c.req.header("user-agent"),
|
|
112
|
+
previousToken: readSessionCookie(c.req.header("cookie"), s.sessions),
|
|
113
|
+
})
|
|
114
|
+
c.header("Set-Cookie", sessionCookie(token, s.sessions))
|
|
115
|
+
// Everyone has an org: a personal one on first sign-in (or for an
|
|
116
|
+
// account from before orgs). Sign-in lands in the first one.
|
|
117
|
+
const mine = await s.orgs.listForUser(user.id)
|
|
118
|
+
const org =
|
|
119
|
+
mine[0]?.org ??
|
|
120
|
+
(await s.orgs.create({ name: "Personal", ownerId: user.id, personal: true }))
|
|
121
|
+
c.header("Set-Cookie", orgCookie(org.id, s.orgCookie), { append: true })
|
|
122
|
+
if (isNew) await s.notifier.notify(user.id, "account.welcome", { name: maskPhone(r.phone) })
|
|
123
|
+
return c.json({ user: publicUser(user) })
|
|
124
|
+
},
|
|
125
|
+
)
|
|
126
|
+
.post("/sign-out", async (c) => {
|
|
127
|
+
const session = await validateSession(
|
|
128
|
+
readSessionCookie(c.req.header("cookie"), s.sessions),
|
|
129
|
+
s.sessions,
|
|
130
|
+
)
|
|
131
|
+
if (session) await s.sessions.store.revoke(session.record.id)
|
|
132
|
+
c.header("Set-Cookie", clearCookie(s.sessions))
|
|
133
|
+
return c.json({ ok: true })
|
|
134
|
+
})
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { ApiException } from "@dapplelight/signet-server/http"
|
|
2
|
+
import { zValidator } from "@dapplelight/signet-server/http/validate"
|
|
3
|
+
import { Hono } from "hono"
|
|
4
|
+
import { z } from "zod"
|
|
5
|
+
import type { AppEnv } from "../app.ts"
|
|
6
|
+
import { env } from "../env.ts"
|
|
7
|
+
import { PLAN_DISPLAY, type PlanId, plans, type Services } from "../services.ts"
|
|
8
|
+
|
|
9
|
+
const PLAN_IDS = Object.keys(plans) as [PlanId, ...PlanId[]]
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Plans and the signed-in user's entitlement (signet-db entitlements).
|
|
13
|
+
*
|
|
14
|
+
* GET / { subscription, usage } (the plans themselves are in api/plans.ts)
|
|
15
|
+
* POST /checkout { plan } BILLING=fake: switches now. BILLING=razorpay: see README.
|
|
16
|
+
*/
|
|
17
|
+
export const billingRoutes = (s: Services) =>
|
|
18
|
+
new Hono<AppEnv>()
|
|
19
|
+
.get("/", async (c) => {
|
|
20
|
+
const id = c.get("user").id
|
|
21
|
+
const { plan, status, currentPeriodEnd, graceUntil, source } = await s.entitlements.get(id)
|
|
22
|
+
return c.json({
|
|
23
|
+
subscription: { plan, status, currentPeriodEnd, graceUntil, source },
|
|
24
|
+
usage: await s.entitlements.usage(id),
|
|
25
|
+
})
|
|
26
|
+
})
|
|
27
|
+
.post("/checkout", zValidator("json", z.object({ plan: z.enum(PLAN_IDS) })), async (c) => {
|
|
28
|
+
const user = c.get("user")
|
|
29
|
+
const { plan } = c.req.valid("json")
|
|
30
|
+
if (env.BILLING !== "fake")
|
|
31
|
+
// TODO(billing): create the gateway subscription here and return its
|
|
32
|
+
// checkout for the browser (README, "Taking real payments"). The
|
|
33
|
+
// webhook at /api/billing/webhooks/razorpay then moves the plan.
|
|
34
|
+
throw new ApiException(409, "Real checkout is not wired yet.", "NOT_IMPLEMENTED")
|
|
35
|
+
await s.entitlements.setPlan(user.id, plan, { actor: { type: "user", id: user.id } })
|
|
36
|
+
await s.notifier.notify(user.id, "billing.plan_changed", { plan: PLAN_DISPLAY[plan].name })
|
|
37
|
+
return c.json({ plan })
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
/** Gateway webhooks: verified, deduped and applied by signet-payments. No session. */
|
|
41
|
+
export const billingWebhooks = (s: Services) =>
|
|
42
|
+
new Hono<AppEnv>().post("/:gateway", (c) =>
|
|
43
|
+
s.payments.handleWebhook(c.req.param("gateway"), c.req.raw),
|
|
44
|
+
)
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { ApiException } from "@dapplelight/signet-server/http"
|
|
2
|
+
import { zValidator } from "@dapplelight/signet-server/http/validate"
|
|
3
|
+
import { CHANNELS, type Channel, NotifyError } from "@dapplelight/signet-server/notify/notifier"
|
|
4
|
+
import { Hono } from "hono"
|
|
5
|
+
import { z } from "zod"
|
|
6
|
+
import type { AppEnv } from "../app.ts"
|
|
7
|
+
import type { Services } from "../services.ts"
|
|
8
|
+
|
|
9
|
+
const channelPrefs = z.record(
|
|
10
|
+
z.string(),
|
|
11
|
+
z.partialRecord(z.enum(CHANNELS as [Channel, ...Channel[]]), z.boolean()),
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* The in-app inbox and notification preferences, for the signed-in user.
|
|
16
|
+
*
|
|
17
|
+
* GET /?cursor= { items, nextCursor, unreadCount }
|
|
18
|
+
* POST /read { ids }
|
|
19
|
+
* POST /read-all
|
|
20
|
+
* POST /:id/archive
|
|
21
|
+
* GET /prefs { channels, required }
|
|
22
|
+
* PUT /prefs { channels } (a required category cannot be turned off)
|
|
23
|
+
*/
|
|
24
|
+
export const notificationRoutes = (s: Services) =>
|
|
25
|
+
new Hono<AppEnv>()
|
|
26
|
+
.get("/", zValidator("query", z.object({ cursor: z.string().optional() })), async (c) => {
|
|
27
|
+
const id = c.get("user").id
|
|
28
|
+
const page = await s.notifier.inbox.list(id, c.req.valid("query"))
|
|
29
|
+
return c.json({ ...page, unreadCount: await s.notifier.inbox.unreadCount(id) })
|
|
30
|
+
})
|
|
31
|
+
.post(
|
|
32
|
+
"/read",
|
|
33
|
+
zValidator("json", z.object({ ids: z.array(z.string()).max(100) })),
|
|
34
|
+
async (c) => {
|
|
35
|
+
await s.notifier.inbox.markRead(c.get("user").id, c.req.valid("json").ids)
|
|
36
|
+
return c.json({ ok: true })
|
|
37
|
+
},
|
|
38
|
+
)
|
|
39
|
+
.post("/read-all", async (c) => {
|
|
40
|
+
await s.notifier.inbox.markAllRead(c.get("user").id)
|
|
41
|
+
return c.json({ ok: true })
|
|
42
|
+
})
|
|
43
|
+
.post("/:id/archive", async (c) => {
|
|
44
|
+
await s.notifier.inbox.archive(c.get("user").id, c.req.param("id"))
|
|
45
|
+
return c.json({ ok: true })
|
|
46
|
+
})
|
|
47
|
+
.get("/prefs", async (c) => {
|
|
48
|
+
const { channels } = await s.notifier.getPrefs(c.get("user").id)
|
|
49
|
+
return c.json({ channels, required: s.notifier.required })
|
|
50
|
+
})
|
|
51
|
+
.put("/prefs", zValidator("json", z.object({ channels: channelPrefs })), async (c) => {
|
|
52
|
+
const { channels } = await s.notifier
|
|
53
|
+
.updatePrefs(c.get("user").id, c.req.valid("json"))
|
|
54
|
+
.catch((e: unknown) => {
|
|
55
|
+
if (e instanceof NotifyError) throw new ApiException(400, e.message, e.code)
|
|
56
|
+
throw e
|
|
57
|
+
})
|
|
58
|
+
return c.json({ channels, required: s.notifier.required })
|
|
59
|
+
})
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { zValidator } from "@dapplelight/signet-server/http/validate"
|
|
2
|
+
import { Hono } from "hono"
|
|
3
|
+
import { z } from "zod"
|
|
4
|
+
import type { AppEnv } from "../app.ts"
|
|
5
|
+
import { NOTICE_VERSION, PURPOSES, type Services } from "../services.ts"
|
|
6
|
+
|
|
7
|
+
const purpose = z.object({ purpose: z.enum(PURPOSES.map((p) => p.id) as [string, ...string[]]) })
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* DPDP consent and data requests for the signed-in user (signet-db privacy).
|
|
11
|
+
* Fulfilling a request is a staff action: open it in /admin, or call
|
|
12
|
+
* `privacy.fulfil(id, { actor })` from a job.
|
|
13
|
+
*
|
|
14
|
+
* GET / { purposes, consents, requests }
|
|
15
|
+
* POST /consents/:purpose give
|
|
16
|
+
* DELETE /consents/:purpose withdraw, as easy as giving
|
|
17
|
+
* POST /requests { kind: "export" | "erasure" }
|
|
18
|
+
*/
|
|
19
|
+
export const privacyRoutes = (s: Services) =>
|
|
20
|
+
new Hono<AppEnv>()
|
|
21
|
+
.get("/", async (c) => {
|
|
22
|
+
const id = c.get("user").id
|
|
23
|
+
return c.json({
|
|
24
|
+
purposes: PURPOSES,
|
|
25
|
+
consents: await s.privacy.history(id),
|
|
26
|
+
requests: await s.privacy.listRequests({ subject: id }),
|
|
27
|
+
})
|
|
28
|
+
})
|
|
29
|
+
.post("/consents/:purpose", zValidator("param", purpose), async (c) => {
|
|
30
|
+
const consent = await s.privacy.give(c.get("user").id, c.req.valid("param").purpose, {
|
|
31
|
+
noticeVersion: NOTICE_VERSION,
|
|
32
|
+
source: "settings",
|
|
33
|
+
})
|
|
34
|
+
return c.json({ consent })
|
|
35
|
+
})
|
|
36
|
+
.delete("/consents/:purpose", zValidator("param", purpose), async (c) => {
|
|
37
|
+
await s.privacy.withdraw(c.get("user").id, c.req.valid("param").purpose)
|
|
38
|
+
return c.json({ ok: true })
|
|
39
|
+
})
|
|
40
|
+
.post(
|
|
41
|
+
"/requests",
|
|
42
|
+
zValidator("json", z.object({ kind: z.enum(["export", "erasure"]) })),
|
|
43
|
+
async (c) => {
|
|
44
|
+
const id = c.get("user").id
|
|
45
|
+
const request =
|
|
46
|
+
c.req.valid("json").kind === "export"
|
|
47
|
+
? await s.privacy.requestExport(id)
|
|
48
|
+
: await s.privacy.requestErasure(id)
|
|
49
|
+
if (!request) throw new Error("Could not open the request.")
|
|
50
|
+
return c.json({ request }, 201)
|
|
51
|
+
},
|
|
52
|
+
)
|
|
@@ -0,0 +1,44 @@
|
|
|
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}`)
|