create-signet-app 0.5.0 → 0.6.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.
- package/README.md +27 -8
- package/base/api/api/app.ts +57 -8
- package/base/api/api/db/schema.ts +16 -4
- package/base/api/api/env.ts +8 -0
- package/base/api/api/server.ts +6 -0
- package/base/api/api/services.ts +43 -3
- package/base/api/drizzle/0002_ai_paywalls_workflows.sql +77 -0
- package/base/api/drizzle/meta/0002_snapshot.json +1759 -0
- package/base/api/drizzle/meta/_journal.json +7 -0
- package/base/shared/README.md +87 -0
- package/base/web/src/routeTree.gen.ts +25 -0
- package/base/web/src/router.test.ts +1 -0
- package/base/web/src/routes/_app.tsx +1 -0
- package/package.json +5 -2
- package/parts/ai/api/api/routes/ai.ts +28 -0
- package/parts/ai/api/test/ai.test.ts +52 -0
- package/parts/ai/part.ts +16 -0
- package/parts/paywalls/api/api/routes/paywall.ts +126 -0
- package/parts/paywalls/api/test/paywalls.test.ts +71 -0
- package/parts/paywalls/part.ts +8 -0
- package/parts/workflows/api/api/workflows.ts +33 -0
- package/parts/workflows/api/test/workflows.test.ts +44 -0
- package/parts/workflows/part.ts +7 -0
- package/parts/workflows/web/src/routes/_app/approvals.tsx +34 -0
- package/src/compose.ts +87 -30
- package/src/desktop.ts +1 -1
- package/src/index.ts +46 -7
package/base/shared/README.md
CHANGED
|
@@ -14,6 +14,9 @@ It has:
|
|
|
14
14
|
- an in-app inbox <!-- @notifications -->
|
|
15
15
|
- privacy (DPDP consent and data requests) <!-- @privacy -->
|
|
16
16
|
- plans and billing <!-- @payments -->
|
|
17
|
+
- remote paywalls <!-- @paywalls -->
|
|
18
|
+
- AI spend caps and a sample AI route <!-- @ai -->
|
|
19
|
+
- durable workflows with approval steps <!-- @workflows -->
|
|
17
20
|
- an admin panel over the whole database <!-- @admin -->
|
|
18
21
|
- MCP for agents at `/mcp` <!-- @mcp -->
|
|
19
22
|
<!-- auth:end -->
|
|
@@ -134,6 +137,84 @@ each plan allows, `PLAN_DISPLAY` the name, description and price the page shows.
|
|
|
134
137
|
Keep it in step with the API.
|
|
135
138
|
<!-- !api:end -->
|
|
136
139
|
<!-- payments:end -->
|
|
140
|
+
<!-- paywalls:begin -->
|
|
141
|
+
|
|
142
|
+
### Paywalls (2 minutes)
|
|
143
|
+
|
|
144
|
+
A placement ("onboarding", "upgrade") serves an offering: products mapped to
|
|
145
|
+
plans, and what the paywall says. `GET /api/paywall/<placement>?country=IN&platform=web`
|
|
146
|
+
returns the one for the caller: the first audience override that matches,
|
|
147
|
+
else the placement's own, and 404 until the placement exists. Each publish is
|
|
148
|
+
a new version and a published one never changes, so what a paywall sells
|
|
149
|
+
changes without a release.
|
|
150
|
+
<!-- admin:begin -->
|
|
151
|
+
|
|
152
|
+
Admins and staff publish with `POST /api/admin/paywalls/offerings/<key>`
|
|
153
|
+
(`{ products, paywall }`) and point a placement at it with
|
|
154
|
+
`PUT /api/admin/paywalls/placements/<placement>` (`{ offering, overrides? }`).
|
|
155
|
+
The admin panel lists both tables read only.
|
|
156
|
+
<!-- admin:end -->
|
|
157
|
+
<!-- !admin:begin -->
|
|
158
|
+
|
|
159
|
+
Publish from code, e.g. in a seed script:
|
|
160
|
+
|
|
161
|
+
```ts
|
|
162
|
+
const actor = { type: "system" as const, id: "seed" }
|
|
163
|
+
const products = [{ id: "plan_pro_monthly", store: "web", plan: "pro" }]
|
|
164
|
+
await s.offerings.publish("standard", { products, paywall: { title: "Go further" } }, { actor })
|
|
165
|
+
await s.offerings.setPlacement("upgrade", { offering: "standard" }, { actor })
|
|
166
|
+
```
|
|
167
|
+
<!-- !admin:end -->
|
|
168
|
+
<!-- paywalls:end -->
|
|
169
|
+
<!-- ai:begin -->
|
|
170
|
+
|
|
171
|
+
### AI (2 minutes)
|
|
172
|
+
|
|
173
|
+
`POST /api/ai/summary` with `{ "text": "..." }` answers from a canned
|
|
174
|
+
provider, so it runs with no key. Each call costs $0.001, charged to the
|
|
175
|
+
caller's daily cap (`AI_CAP_USER_DAY`) and the app's monthly one
|
|
176
|
+
(`AI_CAP_GLOBAL_MONTH`), in cost units: 1,000,000 is one US dollar. Over a
|
|
177
|
+
cap, every `/api/ai` route answers 429 with `Retry-After` before it runs.
|
|
178
|
+
Spend is counted in `usage_counters`; a cap stored in `ai_spend_caps` wins
|
|
179
|
+
over the env ones.
|
|
180
|
+
Admins read spend and set caps per user or for the app under <!-- @admin -->
|
|
181
|
+
`/api/admin/ai-spend` (`GET /usage`, `GET /caps`, `PUT /caps`). <!-- @admin -->
|
|
182
|
+
Set one from code with `s.aiSpend.setCap({ scope, subject, period, units })`. <!-- @!admin -->
|
|
183
|
+
|
|
184
|
+
For a real model, replace the fake provider in `api/services.ts` with yours
|
|
185
|
+
(a signet-ai `Provider`: name, model, `pricing`, and `generate`); its pricing
|
|
186
|
+
is what the caps count. Copy `api/routes/ai.ts` for your own AI routes.
|
|
187
|
+
<!-- ai:end -->
|
|
188
|
+
<!-- workflows:begin -->
|
|
189
|
+
|
|
190
|
+
### Workflows (5 minutes)
|
|
191
|
+
|
|
192
|
+
<!-- api:begin -->
|
|
193
|
+
`api/workflows.ts` has one workflow, a generic approval request: someone
|
|
194
|
+
asks, one of the listed approvers approves or rejects, and the run ends with
|
|
195
|
+
the decision. `api/server.ts` runs the runner: every second it takes the runs
|
|
196
|
+
that are due, including any a restart cut short.
|
|
197
|
+
<!-- web:begin -->
|
|
198
|
+
**Approvals** lists the approval steps waiting on you.
|
|
199
|
+
<!-- web:end -->
|
|
200
|
+
|
|
201
|
+
Start one with `POST /api/workflows/runs` and
|
|
202
|
+
`{ "workflow": "approval-request", "input": { "summary": "...", "approvers": ["<user id>"] } }`.
|
|
203
|
+
Approvers find it at `GET /api/workflows/approvals` and decide with
|
|
204
|
+
`POST /api/workflows/runs/<id>/steps/approval/approve` (or `reject`); admins
|
|
205
|
+
see every run at `GET /api/workflows/runs`.
|
|
206
|
+
|
|
207
|
+
Add your own with `defineWorkflow` in `api/workflows.ts` and list it in
|
|
208
|
+
`WORKFLOWS`. Put each side effect in `step.run`, so a replay after a restart
|
|
209
|
+
does not repeat it. Who may start which workflow over HTTP is `canStart` in
|
|
210
|
+
`api/app.ts`.
|
|
211
|
+
<!-- api:end -->
|
|
212
|
+
<!-- !api:begin -->
|
|
213
|
+
**Approvals** lists the approval steps waiting on you, from your API's
|
|
214
|
+
`/api/workflows` (an app made with `--api --with workflows` serves it), each
|
|
215
|
+
with Approve and Reject.
|
|
216
|
+
<!-- !api:end -->
|
|
217
|
+
<!-- workflows:end -->
|
|
137
218
|
|
|
138
219
|
### Build your first feature (the rest of the day)
|
|
139
220
|
|
|
@@ -208,6 +289,7 @@ your lockfile.
|
|
|
208
289
|
api/
|
|
209
290
|
app.ts routes, the signed-in gate, MCP; exports AppType for the client
|
|
210
291
|
plans.ts plans and what the billing page shows (shared with the browser) <!-- @payments -->
|
|
292
|
+
workflows.ts the workflows the runner runs <!-- @workflows -->
|
|
211
293
|
services.ts what the routes use, built once per process
|
|
212
294
|
routes/ one file per area <!-- @auth -->
|
|
213
295
|
db/schema.ts every table; drizzle/ holds the migrations
|
|
@@ -267,6 +349,11 @@ Before production:
|
|
|
267
349
|
Fulfil them with `privacy.fulfil(id, { actor })` (export returns the data to
|
|
268
350
|
send; erasure deletes the user's rows listed in `userTables`).
|
|
269
351
|
<!-- privacy:end -->
|
|
352
|
+
<!-- ai:begin -->
|
|
353
|
+
- **AI.** `api/services.ts` answers from a canned provider. Put a real one
|
|
354
|
+
there, and set `AI_CAP_USER_DAY` and `AI_CAP_GLOBAL_MONTH` to what you will
|
|
355
|
+
pay.
|
|
356
|
+
<!-- ai:end -->
|
|
270
357
|
<!-- auth:end -->
|
|
271
358
|
<!-- api:end -->
|
|
272
359
|
<!-- !api:begin -->
|
|
@@ -14,6 +14,7 @@ import { Route as LoginRouteImport } from "./routes/login" // @auth
|
|
|
14
14
|
import { Route as AppIndexRouteImport } from "./routes/_app/index"
|
|
15
15
|
import { Route as AppAccountRouteImport } from "./routes/_app/account" // @account
|
|
16
16
|
import { Route as AppAdminRouteImport } from "./routes/_app/admin" // @admin
|
|
17
|
+
import { Route as AppApprovalsRouteImport } from "./routes/_app/approvals" // @workflows
|
|
17
18
|
import { Route as AppBillingRouteImport } from "./routes/_app/billing" // @payments
|
|
18
19
|
import { Route as AppNotificationsRouteImport } from "./routes/_app/notifications" // @notifications
|
|
19
20
|
import { Route as AppPrivacyRouteImport } from "./routes/_app/privacy" // @privacy
|
|
@@ -52,6 +53,13 @@ const AppAdminRoute = AppAdminRouteImport.update({
|
|
|
52
53
|
getParentRoute: () => AppRoute,
|
|
53
54
|
} as any)
|
|
54
55
|
// admin:end
|
|
56
|
+
// workflows:begin
|
|
57
|
+
const AppApprovalsRoute = AppApprovalsRouteImport.update({
|
|
58
|
+
id: "/approvals",
|
|
59
|
+
path: "/approvals",
|
|
60
|
+
getParentRoute: () => AppRoute,
|
|
61
|
+
} as any)
|
|
62
|
+
// workflows:end
|
|
55
63
|
// payments:begin
|
|
56
64
|
const AppBillingRoute = AppBillingRouteImport.update({
|
|
57
65
|
id: "/billing",
|
|
@@ -107,6 +115,7 @@ export interface FileRoutesByFullPath {
|
|
|
107
115
|
"/login": typeof LoginRoute // @auth
|
|
108
116
|
"/account": typeof AppAccountRoute // @account
|
|
109
117
|
"/admin": typeof AppAdminRoute // @admin
|
|
118
|
+
"/approvals": typeof AppApprovalsRoute // @workflows
|
|
110
119
|
"/billing": typeof AppBillingRoute // @payments
|
|
111
120
|
"/notifications": typeof AppNotificationsRoute // @notifications
|
|
112
121
|
"/privacy": typeof AppPrivacyRoute // @privacy
|
|
@@ -119,6 +128,7 @@ export interface FileRoutesByTo {
|
|
|
119
128
|
"/login": typeof LoginRoute // @auth
|
|
120
129
|
"/account": typeof AppAccountRoute // @account
|
|
121
130
|
"/admin": typeof AppAdminRoute // @admin
|
|
131
|
+
"/approvals": typeof AppApprovalsRoute // @workflows
|
|
122
132
|
"/billing": typeof AppBillingRoute // @payments
|
|
123
133
|
"/notifications": typeof AppNotificationsRoute // @notifications
|
|
124
134
|
"/privacy": typeof AppPrivacyRoute // @privacy
|
|
@@ -134,6 +144,7 @@ export interface FileRoutesById {
|
|
|
134
144
|
"/login": typeof LoginRoute // @auth
|
|
135
145
|
"/_app/account": typeof AppAccountRoute // @account
|
|
136
146
|
"/_app/admin": typeof AppAdminRoute // @admin
|
|
147
|
+
"/_app/approvals": typeof AppApprovalsRoute // @workflows
|
|
137
148
|
"/_app/billing": typeof AppBillingRoute // @payments
|
|
138
149
|
"/_app/notifications": typeof AppNotificationsRoute // @notifications
|
|
139
150
|
"/_app/privacy": typeof AppPrivacyRoute // @privacy
|
|
@@ -150,6 +161,7 @@ export interface FileRouteTypes {
|
|
|
150
161
|
| "/login" // @auth
|
|
151
162
|
| "/account" // @account
|
|
152
163
|
| "/admin" // @admin
|
|
164
|
+
| "/approvals" // @workflows
|
|
153
165
|
| "/billing" // @payments
|
|
154
166
|
| "/notifications" // @notifications
|
|
155
167
|
| "/privacy" // @privacy
|
|
@@ -162,6 +174,7 @@ export interface FileRouteTypes {
|
|
|
162
174
|
| "/login" // @auth
|
|
163
175
|
| "/account" // @account
|
|
164
176
|
| "/admin" // @admin
|
|
177
|
+
| "/approvals" // @workflows
|
|
165
178
|
| "/billing" // @payments
|
|
166
179
|
| "/notifications" // @notifications
|
|
167
180
|
| "/privacy" // @privacy
|
|
@@ -176,6 +189,7 @@ export interface FileRouteTypes {
|
|
|
176
189
|
| "/login" // @auth
|
|
177
190
|
| "/_app/account" // @account
|
|
178
191
|
| "/_app/admin" // @admin
|
|
192
|
+
| "/_app/approvals" // @workflows
|
|
179
193
|
| "/_app/billing" // @payments
|
|
180
194
|
| "/_app/notifications" // @notifications
|
|
181
195
|
| "/_app/privacy" // @privacy
|
|
@@ -235,6 +249,15 @@ declare module "@tanstack/react-router" {
|
|
|
235
249
|
parentRoute: typeof AppRoute
|
|
236
250
|
}
|
|
237
251
|
// admin:end
|
|
252
|
+
// workflows:begin
|
|
253
|
+
"/_app/approvals": {
|
|
254
|
+
id: "/_app/approvals"
|
|
255
|
+
path: "/approvals"
|
|
256
|
+
fullPath: "/approvals"
|
|
257
|
+
preLoaderRoute: typeof AppApprovalsRouteImport
|
|
258
|
+
parentRoute: typeof AppRoute
|
|
259
|
+
}
|
|
260
|
+
// workflows:end
|
|
238
261
|
// payments:begin
|
|
239
262
|
"/_app/billing": {
|
|
240
263
|
id: "/_app/billing"
|
|
@@ -304,6 +327,7 @@ declare module "@tanstack/react-router" {
|
|
|
304
327
|
interface AppRouteChildren {
|
|
305
328
|
AppAccountRoute: typeof AppAccountRoute // @account
|
|
306
329
|
AppAdminRoute: typeof AppAdminRoute // @admin
|
|
330
|
+
AppApprovalsRoute: typeof AppApprovalsRoute // @workflows
|
|
307
331
|
AppBillingRoute: typeof AppBillingRoute // @payments
|
|
308
332
|
AppNotificationsRoute: typeof AppNotificationsRoute // @notifications
|
|
309
333
|
AppPrivacyRoute: typeof AppPrivacyRoute // @privacy
|
|
@@ -316,6 +340,7 @@ interface AppRouteChildren {
|
|
|
316
340
|
const AppRouteChildren: AppRouteChildren = {
|
|
317
341
|
AppAccountRoute: AppAccountRoute, // @account
|
|
318
342
|
AppAdminRoute: AppAdminRoute, // @admin
|
|
343
|
+
AppApprovalsRoute: AppApprovalsRoute, // @workflows
|
|
319
344
|
AppBillingRoute: AppBillingRoute, // @payments
|
|
320
345
|
AppNotificationsRoute: AppNotificationsRoute, // @notifications
|
|
321
346
|
AppPrivacyRoute: AppPrivacyRoute, // @privacy
|
|
@@ -13,6 +13,7 @@ test.each([
|
|
|
13
13
|
["/privacy", "/_app/privacy"], // @privacy
|
|
14
14
|
["/billing", "/_app/billing"], // @payments
|
|
15
15
|
["/admin", "/_app/admin"], // @admin
|
|
16
|
+
["/approvals", "/_app/approvals"], // @workflows
|
|
16
17
|
// orgs:begin
|
|
17
18
|
["/org", "/_app/org/"],
|
|
18
19
|
["/org/members", "/_app/org/members"],
|
|
@@ -29,6 +29,7 @@ const NAV = [
|
|
|
29
29
|
{ to: "/billing", label: "Billing" }, // @payments
|
|
30
30
|
{ to: "/account", label: "Account" }, // @account
|
|
31
31
|
{ to: "/privacy", label: "Privacy" }, // @privacy
|
|
32
|
+
{ to: "/approvals", label: "Approvals" }, // @workflows
|
|
32
33
|
{ to: "/org", label: "Org" }, // @orgs
|
|
33
34
|
] as const
|
|
34
35
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "create-signet-app",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"description": "Scaffold a Vite + React + Tailwind app wired to Signet.",
|
|
6
6
|
"keywords": [
|
|
@@ -38,7 +38,10 @@
|
|
|
38
38
|
],
|
|
39
39
|
"scripts": {
|
|
40
40
|
"typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json",
|
|
41
|
-
"test": "bun run test/scaffold.ts && bun run test/scaffold-api.ts && bun run test/scaffold-full.ts && bun run test/scaffold-cli.ts && bun run test/scaffold-extension.ts && bun run test/scaffold-desktop.ts && bun run test/describe.ts"
|
|
41
|
+
"test": "bun run test/scaffold.ts && bun run test/scaffold-api.ts && bun run test/scaffold-full.ts && bun run test/scaffold-cli.ts && bun run test/scaffold-extension.ts && bun run test/scaffold-desktop.ts && bun run test/describe.ts",
|
|
42
|
+
"test:parts": "bun run test/scaffold-parts.ts",
|
|
43
|
+
"test:pm": "bun run test/scaffold-pm.ts",
|
|
44
|
+
"test:runtime": "bun run test/scaffold-runtime.ts"
|
|
42
45
|
},
|
|
43
46
|
"dependencies": {
|
|
44
47
|
"@dapplelight/signet-mcp": "^0.1.5"
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { spendKey } from "@dapplelight/signet-db/ai-spend"
|
|
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 type { Services } from "../services.ts"
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* AI routes. app.ts refuses any /api/ai call once the caller's or the app's
|
|
10
|
+
* spend cap is reached (requireAiSpend, 429 with Retry-After); each call is
|
|
11
|
+
* charged to the caller through `spendKey`. Copy this one for your own.
|
|
12
|
+
*
|
|
13
|
+
* POST /summary { text } → { summary, costUsd }
|
|
14
|
+
*/
|
|
15
|
+
export const aiRoutes = (s: Services) =>
|
|
16
|
+
new Hono<AppEnv>().post(
|
|
17
|
+
"/summary",
|
|
18
|
+
zValidator("json", z.object({ text: z.string().min(1).max(10_000) })),
|
|
19
|
+
async (c) => {
|
|
20
|
+
const { value, meta } = await s.ai.extract({
|
|
21
|
+
schema: z.object({ summary: z.string() }),
|
|
22
|
+
instructions: "Summarise the text in one sentence.",
|
|
23
|
+
input: c.req.valid("json").text,
|
|
24
|
+
budget: { key: spendKey({ userId: c.get("user").id }) },
|
|
25
|
+
})
|
|
26
|
+
return c.json({ summary: value.summary, costUsd: meta.costUsd })
|
|
27
|
+
},
|
|
28
|
+
)
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { expect, test } from "bun:test"
|
|
2
|
+
import { eq } from "drizzle-orm" // @admin
|
|
3
|
+
import { spendCaps, users } from "../api/db/schema.ts" // @admin
|
|
4
|
+
import { spendCaps } from "../api/db/schema.ts" // @!admin
|
|
5
|
+
import { app, db, post, signIn } from "./helpers.ts"
|
|
6
|
+
|
|
7
|
+
const userId = async (cookie: string) => {
|
|
8
|
+
const me = await app.request("/api/account/me", { headers: { cookie } })
|
|
9
|
+
return ((await me.json()) as { user: { id: string } }).user.id
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
test("an AI call answers with no provider key, charged to the caller", async () => {
|
|
13
|
+
expect((await post("/api/ai/summary", { text: "Some text." })).status).toBe(401)
|
|
14
|
+
const cookie = await signIn("+919000000041")
|
|
15
|
+
const res = await post("/api/ai/summary", { text: "Some text to sum up." }, cookie)
|
|
16
|
+
expect(res.status).toBe(200)
|
|
17
|
+
expect(await res.json()).toEqual({ summary: "Some text to sum up.", costUsd: 0.001 })
|
|
18
|
+
})
|
|
19
|
+
|
|
20
|
+
test("over the caller's cap: 429 with Retry-After, and the route does not run", async () => {
|
|
21
|
+
const cookie = await signIn("+919000000042")
|
|
22
|
+
const id = await userId(cookie)
|
|
23
|
+
db.orm
|
|
24
|
+
.insert(spendCaps)
|
|
25
|
+
.values({ id: `user:${id}:day`, scope: "user", subject: id, period: "day", units: 0 })
|
|
26
|
+
.run()
|
|
27
|
+
const res = await post("/api/ai/summary", { text: "Some text." }, cookie)
|
|
28
|
+
expect(res.status).toBe(429)
|
|
29
|
+
expect(Number(res.headers.get("retry-after"))).toBeGreaterThan(0)
|
|
30
|
+
expect(((await res.json()) as { code: string }).code).toBe("AI_SPEND_CAP_EXCEEDED")
|
|
31
|
+
})
|
|
32
|
+
// admin:begin
|
|
33
|
+
|
|
34
|
+
test("admins read AI spend and set caps; everyone else gets 403", async () => {
|
|
35
|
+
const user = await signIn("+919000000043")
|
|
36
|
+
const headers = { cookie: user }
|
|
37
|
+
expect((await app.request("/api/admin/ai-spend/usage", { headers })).status).toBe(403)
|
|
38
|
+
const admin = await signIn("+919000000044")
|
|
39
|
+
db.orm.update(users).set({ role: "admin" }).where(eq(users.phone, "+919000000044")).run()
|
|
40
|
+
const cap = { scope: "user", subject: "*", period: "month", units: 50_000_000 }
|
|
41
|
+
const put = await app.request("/api/admin/ai-spend/caps", {
|
|
42
|
+
method: "PUT",
|
|
43
|
+
headers: { "content-type": "application/json", cookie: admin },
|
|
44
|
+
body: JSON.stringify(cap),
|
|
45
|
+
})
|
|
46
|
+
expect(put.status).toBe(200)
|
|
47
|
+
const caps = (await (
|
|
48
|
+
await app.request("/api/admin/ai-spend/caps", { headers: { cookie: admin } })
|
|
49
|
+
).json()) as { caps: { id: string }[] }
|
|
50
|
+
expect(caps.caps.map((c) => c.id)).toContain("user:*:month")
|
|
51
|
+
})
|
|
52
|
+
// admin:end
|
package/parts/ai/part.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { Part } from "../../src/compose.js"
|
|
2
|
+
|
|
3
|
+
export default {
|
|
4
|
+
description: "AI spend caps per user and app, and a sample /api/ai route on signet-ai",
|
|
5
|
+
needs: ["auth"],
|
|
6
|
+
apiOnly: true,
|
|
7
|
+
// signet-ai's main entry needs signet-lib (its error type) as a peer.
|
|
8
|
+
api: { deps: { "@dapplelight/signet-ai": "^0.5.0", "@dapplelight/signet-lib": "^0.4.0" } },
|
|
9
|
+
env: () => [
|
|
10
|
+
"# AI spend caps in cost units (1000000 = one US dollar); a cap stored in ai_spend_caps wins.",
|
|
11
|
+
"AI_CAP_USER_DAY=200000",
|
|
12
|
+
"AI_CAP_GLOBAL_MONTH=50000000",
|
|
13
|
+
],
|
|
14
|
+
// usage_counters is payments' table too: it stays when either part is chosen.
|
|
15
|
+
tables: ["usage_counters", "ai_spend_caps"],
|
|
16
|
+
} satisfies Part
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { ApiException } from "@dapplelight/signet-server/http/errors"
|
|
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 type { Services } from "../services.ts"
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The paywall a placement ("onboarding", "upgrade") serves the caller now:
|
|
10
|
+
* the first audience override that matches, else the placement's offering.
|
|
11
|
+
* What it serves changes without a release: publish a new offering version
|
|
12
|
+
* and point the placement at it, from code with `s.offerings.publish(...)`
|
|
13
|
+
* and `s.offerings.setPlacement(...)` (see README, "Paywalls"). // @!admin
|
|
14
|
+
* and point the placement at it, through /api/admin/paywalls (below) or from // @admin
|
|
15
|
+
* code with `s.offerings.publish(...)` and `setPlacement(...)`. // @admin
|
|
16
|
+
*
|
|
17
|
+
* GET /:placement?country=IN&platform=web { offering }, or 404
|
|
18
|
+
*/
|
|
19
|
+
export const paywallRoutes = (s: Services) =>
|
|
20
|
+
new Hono<AppEnv>().get(
|
|
21
|
+
"/:placement",
|
|
22
|
+
zValidator("param", z.object({ placement: z.string().min(1).max(64) })),
|
|
23
|
+
zValidator(
|
|
24
|
+
"query",
|
|
25
|
+
z.object({
|
|
26
|
+
country: z.string().length(2).optional(),
|
|
27
|
+
platform: z.string().min(1).max(32).optional(),
|
|
28
|
+
}),
|
|
29
|
+
),
|
|
30
|
+
async (c) => {
|
|
31
|
+
const offering = await s.offerings.current(
|
|
32
|
+
c.req.valid("param").placement,
|
|
33
|
+
c.req.valid("query"),
|
|
34
|
+
c.get("user").id,
|
|
35
|
+
)
|
|
36
|
+
if (!offering) throw new ApiException(404, "No paywall for this placement.", "NOT_FOUND")
|
|
37
|
+
return c.json({ offering })
|
|
38
|
+
},
|
|
39
|
+
)
|
|
40
|
+
// admin:begin
|
|
41
|
+
|
|
42
|
+
const product = z.object({
|
|
43
|
+
/** The store product id, or the web gateway's plan id. */
|
|
44
|
+
id: z.string(),
|
|
45
|
+
store: z.string(),
|
|
46
|
+
/** A plan from api/plans.ts. */
|
|
47
|
+
plan: z.string(),
|
|
48
|
+
interval: z.enum(["month", "year", "once"]).optional(),
|
|
49
|
+
/** What the paywall shows, in minor units. */
|
|
50
|
+
price: z.object({ amount: z.number().int(), currency: z.string() }).optional(),
|
|
51
|
+
/** Trials, intro and win-back offers; checked by signet-db's offerings. */
|
|
52
|
+
offers: z.array(z.any()).optional(),
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
const paywall = z
|
|
56
|
+
.object({
|
|
57
|
+
title: z.string(),
|
|
58
|
+
subtitle: z.string(),
|
|
59
|
+
plans: z.array(z.string()),
|
|
60
|
+
highlight: z.string(),
|
|
61
|
+
badge: z.string(),
|
|
62
|
+
trial: z.string(),
|
|
63
|
+
cta: z.string(),
|
|
64
|
+
})
|
|
65
|
+
.partial()
|
|
66
|
+
|
|
67
|
+
/** signet-db refuses a product, plan or placement that does not check out: a 400. */
|
|
68
|
+
const invalid = (e: unknown): never => {
|
|
69
|
+
if (e instanceof Error && e.name === "SignetDbError")
|
|
70
|
+
throw new ApiException(400, e.message, "VALIDATION_FAILED")
|
|
71
|
+
throw e
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Publishing, for platform admins and staff. A publish is a new version; a
|
|
76
|
+
* published version never changes, so the admin panel only reads these tables.
|
|
77
|
+
*
|
|
78
|
+
* POST /offerings/:key { products, paywall?, note? } the next version
|
|
79
|
+
* PUT /placements/:placement { offering, version?, overrides? }
|
|
80
|
+
*/
|
|
81
|
+
export const paywallAdminRoutes = (s: Services) =>
|
|
82
|
+
new Hono<AppEnv>()
|
|
83
|
+
.use(async (c, next) => {
|
|
84
|
+
const { role } = c.get("user")
|
|
85
|
+
if (role !== "admin" && role !== "staff")
|
|
86
|
+
throw new ApiException(403, "Admins only.", "FORBIDDEN")
|
|
87
|
+
await next()
|
|
88
|
+
})
|
|
89
|
+
.post(
|
|
90
|
+
"/offerings/:key",
|
|
91
|
+
zValidator(
|
|
92
|
+
"json",
|
|
93
|
+
z.object({
|
|
94
|
+
products: z.array(product),
|
|
95
|
+
paywall: paywall.nullish(),
|
|
96
|
+
note: z.string().optional(),
|
|
97
|
+
}),
|
|
98
|
+
),
|
|
99
|
+
async (c) => {
|
|
100
|
+
const actor = { type: "user" as const, id: c.get("user").id }
|
|
101
|
+
const offering = await s.offerings
|
|
102
|
+
.publish(c.req.param("key"), c.req.valid("json"), { actor })
|
|
103
|
+
.catch(invalid)
|
|
104
|
+
return c.json({ offering }, 201)
|
|
105
|
+
},
|
|
106
|
+
)
|
|
107
|
+
.put(
|
|
108
|
+
"/placements/:placement",
|
|
109
|
+
zValidator(
|
|
110
|
+
"json",
|
|
111
|
+
z.object({
|
|
112
|
+
offering: z.string(),
|
|
113
|
+
version: z.number().int().nullish(),
|
|
114
|
+
/** [{ when: { country?, platform?, attributes? }, offering, version? }], first match wins. */
|
|
115
|
+
overrides: z.array(z.any()).optional(),
|
|
116
|
+
}),
|
|
117
|
+
),
|
|
118
|
+
async (c) => {
|
|
119
|
+
const actor = { type: "user" as const, id: c.get("user").id }
|
|
120
|
+
const placement = await s.offerings
|
|
121
|
+
.setPlacement(c.req.param("placement"), c.req.valid("json"), { actor })
|
|
122
|
+
.catch(invalid)
|
|
123
|
+
return c.json({ placement })
|
|
124
|
+
},
|
|
125
|
+
)
|
|
126
|
+
// admin:end
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { expect, test } from "bun:test"
|
|
2
|
+
import { createOfferings } from "@dapplelight/signet-db/offerings"
|
|
3
|
+
import { eq } from "drizzle-orm" // @admin
|
|
4
|
+
import * as schema from "../api/db/schema.ts"
|
|
5
|
+
import { app, db, signIn } from "./helpers.ts"
|
|
6
|
+
|
|
7
|
+
const get = (path: string, cookie: string) => app.request(path, { headers: { cookie } })
|
|
8
|
+
|
|
9
|
+
test("a placement serves its offering per audience; an unknown one is a 404", async () => {
|
|
10
|
+
// Published from code, as an app does without the admin panel.
|
|
11
|
+
const offerings = createOfferings(db, { tables: schema })
|
|
12
|
+
const actor = { actor: { type: "system" as const, id: "test" } }
|
|
13
|
+
const products = [
|
|
14
|
+
{ id: "plan_pro_monthly", store: "web", plan: "pro", interval: "month" as const },
|
|
15
|
+
]
|
|
16
|
+
await offerings.publish("standard", { products, paywall: { title: "Go further" } }, actor)
|
|
17
|
+
await offerings.publish("regional", { products, paywall: { title: "Regional" } }, actor)
|
|
18
|
+
await offerings.setPlacement(
|
|
19
|
+
"upgrade",
|
|
20
|
+
{ offering: "standard", overrides: [{ when: { country: ["IN"] }, offering: "regional" }] },
|
|
21
|
+
actor,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
expect((await app.request("/api/paywall/upgrade")).status).toBe(401)
|
|
25
|
+
const cookie = await signIn("+919000000051")
|
|
26
|
+
const res = await get("/api/paywall/upgrade", cookie)
|
|
27
|
+
expect(res.status).toBe(200)
|
|
28
|
+
expect(await res.json()).toMatchObject({
|
|
29
|
+
offering: { key: "standard", version: 1, paywall: { title: "Go further" } },
|
|
30
|
+
})
|
|
31
|
+
expect(await (await get("/api/paywall/upgrade?country=IN", cookie)).json()).toMatchObject({
|
|
32
|
+
offering: { key: "regional" },
|
|
33
|
+
})
|
|
34
|
+
expect((await get("/api/paywall/nowhere", cookie)).status).toBe(404)
|
|
35
|
+
})
|
|
36
|
+
// admin:begin
|
|
37
|
+
|
|
38
|
+
test("admins publish offerings and place them; users get 403", async () => {
|
|
39
|
+
const send = (method: string, path: string, cookie: string, body: unknown) =>
|
|
40
|
+
app.request(path, {
|
|
41
|
+
method,
|
|
42
|
+
headers: { "content-type": "application/json", cookie },
|
|
43
|
+
body: JSON.stringify(body),
|
|
44
|
+
})
|
|
45
|
+
const offering = {
|
|
46
|
+
products: [{ id: "plan_pro_monthly", store: "web", plan: "pro" }],
|
|
47
|
+
paywall: { title: "Pro" },
|
|
48
|
+
}
|
|
49
|
+
const user = await signIn("+919000000052")
|
|
50
|
+
expect((await send("POST", "/api/admin/paywalls/offerings/launch", user, offering)).status).toBe(
|
|
51
|
+
403,
|
|
52
|
+
)
|
|
53
|
+
const staffPhone = "+919000000053"
|
|
54
|
+
const admin = await signIn(staffPhone)
|
|
55
|
+
db.orm.update(schema.users).set({ role: "staff" }).where(eq(schema.users.phone, staffPhone)).run()
|
|
56
|
+
expect((await send("POST", "/api/admin/paywalls/offerings/launch", admin, offering)).status).toBe(
|
|
57
|
+
201,
|
|
58
|
+
)
|
|
59
|
+
const unknownPlan = { products: [{ id: "x", store: "web", plan: "none" }] }
|
|
60
|
+
expect(
|
|
61
|
+
(await send("POST", "/api/admin/paywalls/offerings/launch", admin, unknownPlan)).status,
|
|
62
|
+
).toBe(400)
|
|
63
|
+
const placed = await send("PUT", "/api/admin/paywalls/placements/onboarding", admin, {
|
|
64
|
+
offering: "launch",
|
|
65
|
+
})
|
|
66
|
+
expect(placed.status).toBe(200)
|
|
67
|
+
expect(await (await get("/api/paywall/onboarding", user)).json()).toMatchObject({
|
|
68
|
+
offering: { key: "launch", version: 1 },
|
|
69
|
+
})
|
|
70
|
+
})
|
|
71
|
+
// admin:end
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { createWorkflows, defineWorkflow } from "@dapplelight/signet-db/workflows"
|
|
2
|
+
import { z } from "zod"
|
|
3
|
+
import type { Db } from "./db/index.ts"
|
|
4
|
+
import * as schema from "./db/schema.ts"
|
|
5
|
+
|
|
6
|
+
const request = z.object({
|
|
7
|
+
/** What is being asked, as the approvers see it. */
|
|
8
|
+
summary: z.string().min(1).max(200),
|
|
9
|
+
/** User ids; any one of them decides. */
|
|
10
|
+
approvers: z.array(z.string().min(1)).min(1).max(20),
|
|
11
|
+
})
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* The example: someone asks, one of the approvers approves or rejects, and
|
|
15
|
+
* the run ends with the decision (a week without one counts as rejected).
|
|
16
|
+
* Copy it for your own: put each side effect in `step.run`, so a replay after
|
|
17
|
+
* a restart does not repeat it.
|
|
18
|
+
*/
|
|
19
|
+
export const approvalRequest = defineWorkflow("approval-request", async (step, input: unknown) => {
|
|
20
|
+
const { summary, approvers } = request.parse(input)
|
|
21
|
+
const decision = await step.approval({ approvers, summary, timeout: 7 * 86_400_000 })
|
|
22
|
+
return { approved: decision.approved, by: decision.by ?? null, reason: decision.reason ?? null }
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
/** Every workflow the app runs. A run of one not listed here fails. */
|
|
26
|
+
export const WORKFLOWS = [approvalRequest]
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The engine over the workflow tables. services.ts serves it to the routes;
|
|
30
|
+
* server.ts runs another over the same database, ticking every second.
|
|
31
|
+
*/
|
|
32
|
+
export const createAppWorkflows = (db: Db) =>
|
|
33
|
+
createWorkflows(db, { tables: schema, workflows: WORKFLOWS })
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { expect, test } from "bun:test"
|
|
2
|
+
import { createAppWorkflows } from "../api/workflows.ts"
|
|
3
|
+
import { app, db, post, signIn } from "./helpers.ts"
|
|
4
|
+
|
|
5
|
+
// server.ts runs the runner; the tests tick it by hand.
|
|
6
|
+
const runner = createAppWorkflows(db)
|
|
7
|
+
const get = (path: string, cookie: string) => app.request(path, { headers: { cookie } })
|
|
8
|
+
const userId = async (cookie: string) =>
|
|
9
|
+
((await (await get("/api/account/me", cookie)).json()) as { user: { id: string } }).user.id
|
|
10
|
+
|
|
11
|
+
test("an approval request: started, waiting on its approver, decided, finished", async () => {
|
|
12
|
+
const asker = await signIn("+919000000061")
|
|
13
|
+
const approver = await signIn("+919000000062")
|
|
14
|
+
const other = await signIn("+919000000063")
|
|
15
|
+
const input = { summary: "Approve this request", approvers: [await userId(approver)] }
|
|
16
|
+
const started = await post("/api/workflows/runs", { workflow: "approval-request", input }, asker)
|
|
17
|
+
expect(started.status).toBe(201)
|
|
18
|
+
const run = (await started.json()) as { id: string }
|
|
19
|
+
await runner.tick()
|
|
20
|
+
|
|
21
|
+
expect(await (await get("/api/workflows/approvals", approver)).json()).toMatchObject([
|
|
22
|
+
{ runId: run.id, stepId: "approval", summary: "Approve this request" },
|
|
23
|
+
])
|
|
24
|
+
// Someone else's run reads as missing; only a listed approver decides.
|
|
25
|
+
expect((await get(`/api/workflows/runs/${run.id}`, other)).status).toBe(404)
|
|
26
|
+
const approve = `/api/workflows/runs/${run.id}/steps/approval/approve`
|
|
27
|
+
expect((await post(approve, {}, asker)).status).toBe(403)
|
|
28
|
+
expect((await post(approve, { reason: "Looks right" }, approver)).status).toBe(200)
|
|
29
|
+
await runner.tick()
|
|
30
|
+
|
|
31
|
+
const done = (await (await get(`/api/workflows/runs/${run.id}`, asker)).json()) as {
|
|
32
|
+
run: { status: string; output: unknown }
|
|
33
|
+
}
|
|
34
|
+
expect(done.run).toMatchObject({
|
|
35
|
+
status: "completed",
|
|
36
|
+
output: { approved: true, reason: "Looks right" },
|
|
37
|
+
})
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
test("over HTTP, people start the example workflow and nothing else", async () => {
|
|
41
|
+
const cookie = await signIn("+919000000064")
|
|
42
|
+
const res = await post("/api/workflows/runs", { workflow: "something-else", input: {} }, cookie)
|
|
43
|
+
expect(res.status).toBe(403)
|
|
44
|
+
})
|