@dapplelight/signet-server 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1403 -5
- package/dist/abuse/captcha.d.ts +46 -0
- package/dist/abuse/captcha.d.ts.map +1 -0
- package/dist/abuse/captcha.js +123 -0
- package/dist/abuse/captcha.js.map +1 -0
- package/dist/abuse/disposable-domains.d.ts +2 -0
- package/dist/abuse/disposable-domains.d.ts.map +1 -0
- package/dist/abuse/disposable-domains.js +2 -0
- package/dist/abuse/disposable-domains.js.map +1 -0
- package/dist/abuse/email.d.ts +15 -0
- package/dist/abuse/email.d.ts.map +1 -0
- package/dist/abuse/email.js +87 -0
- package/dist/abuse/email.js.map +1 -0
- package/dist/adapters/cloudflare.d.ts +43 -0
- package/dist/adapters/cloudflare.d.ts.map +1 -0
- package/dist/adapters/cloudflare.js +36 -0
- package/dist/adapters/cloudflare.js.map +1 -0
- package/dist/adapters/index.d.ts +39 -0
- package/dist/adapters/index.d.ts.map +1 -0
- package/dist/adapters/index.js +80 -0
- package/dist/adapters/index.js.map +1 -0
- package/dist/adapters/node.d.ts +3 -0
- package/dist/adapters/node.d.ts.map +1 -0
- package/dist/adapters/node.js +37 -0
- package/dist/adapters/node.js.map +1 -0
- package/dist/adapters/s3.d.ts +25 -0
- package/dist/adapters/s3.d.ts.map +1 -0
- package/dist/adapters/s3.js +102 -0
- package/dist/adapters/s3.js.map +1 -0
- package/dist/adapters/supabase.d.ts +20 -0
- package/dist/adapters/supabase.d.ts.map +1 -0
- package/dist/adapters/supabase.js +88 -0
- package/dist/adapters/supabase.js.map +1 -0
- package/dist/adapters/upstash.d.ts +15 -0
- package/dist/adapters/upstash.d.ts.map +1 -0
- package/dist/adapters/upstash.js +63 -0
- package/dist/adapters/upstash.js.map +1 -0
- package/dist/adapters/vercel.d.ts +3 -0
- package/dist/adapters/vercel.d.ts.map +1 -0
- package/dist/adapters/vercel.js +4 -0
- package/dist/adapters/vercel.js.map +1 -0
- package/dist/analytics/engine.d.ts +3 -0
- package/dist/analytics/engine.d.ts.map +1 -1
- package/dist/analytics/engine.js +2 -1
- package/dist/analytics/engine.js.map +1 -1
- package/dist/analytics/index.d.ts +2 -0
- package/dist/analytics/index.d.ts.map +1 -1
- package/dist/analytics/index.js +2 -0
- package/dist/analytics/index.js.map +1 -1
- package/dist/analytics/ingest.d.ts +6 -2
- package/dist/analytics/ingest.d.ts.map +1 -1
- package/dist/analytics/ingest.js +11 -2
- package/dist/analytics/ingest.js.map +1 -1
- package/dist/analytics/session.d.ts +23 -0
- package/dist/analytics/session.d.ts.map +1 -0
- package/dist/analytics/session.js +26 -0
- package/dist/analytics/session.js.map +1 -0
- package/dist/analytics/sinks.d.ts +21 -0
- package/dist/analytics/sinks.d.ts.map +1 -0
- package/dist/analytics/sinks.js +58 -0
- package/dist/analytics/sinks.js.map +1 -0
- package/dist/auth/api-keys.d.ts +49 -0
- package/dist/auth/api-keys.d.ts.map +1 -0
- package/dist/auth/api-keys.js +111 -0
- package/dist/auth/api-keys.js.map +1 -0
- package/dist/auth/client-login.d.ts +89 -0
- package/dist/auth/client-login.d.ts.map +1 -0
- package/dist/auth/client-login.js +293 -0
- package/dist/auth/client-login.js.map +1 -0
- package/dist/auth/hono.d.ts +167 -1
- package/dist/auth/hono.d.ts.map +1 -1
- package/dist/auth/hono.js +162 -3
- package/dist/auth/hono.js.map +1 -1
- package/dist/auth/index.d.ts +4 -0
- package/dist/auth/index.d.ts.map +1 -1
- package/dist/auth/index.js +4 -0
- package/dist/auth/index.js.map +1 -1
- package/dist/auth/mcp.d.ts +10 -0
- package/dist/auth/mcp.d.ts.map +1 -0
- package/dist/auth/mcp.js +81 -0
- package/dist/auth/mcp.js.map +1 -0
- package/dist/auth/otp.d.ts +63 -0
- package/dist/auth/otp.d.ts.map +1 -0
- package/dist/auth/otp.js +132 -0
- package/dist/auth/otp.js.map +1 -0
- package/dist/auth/session.d.ts +12 -2
- package/dist/auth/session.d.ts.map +1 -1
- package/dist/auth/session.js +32 -16
- package/dist/auth/session.js.map +1 -1
- package/dist/auth/sessions.d.ts +65 -0
- package/dist/auth/sessions.d.ts.map +1 -0
- package/dist/auth/sessions.js +194 -0
- package/dist/auth/sessions.js.map +1 -0
- package/dist/http/admin.d.ts +21 -0
- package/dist/http/admin.d.ts.map +1 -0
- package/dist/http/admin.js +49 -0
- package/dist/http/admin.js.map +1 -0
- package/dist/http/ai-spend.d.ts +127 -0
- package/dist/http/ai-spend.d.ts.map +1 -0
- package/dist/http/ai-spend.js +109 -0
- package/dist/http/ai-spend.js.map +1 -0
- package/dist/http/cache.d.ts +26 -0
- package/dist/http/cache.d.ts.map +1 -0
- package/dist/http/cache.js +143 -0
- package/dist/http/cache.js.map +1 -0
- package/dist/http/collab.d.ts +229 -0
- package/dist/http/collab.d.ts.map +1 -0
- package/dist/http/collab.js +154 -0
- package/dist/http/collab.js.map +1 -0
- package/dist/http/errors.d.ts.map +1 -1
- package/dist/http/errors.js +20 -0
- package/dist/http/errors.js.map +1 -1
- package/dist/http/experiments.d.ts +174 -0
- package/dist/http/experiments.d.ts.map +1 -0
- package/dist/http/experiments.js +78 -0
- package/dist/http/experiments.js.map +1 -0
- package/dist/http/funnels.d.ts +207 -0
- package/dist/http/funnels.d.ts.map +1 -0
- package/dist/http/funnels.js +366 -0
- package/dist/http/funnels.js.map +1 -0
- package/dist/http/monetisation.d.ts +504 -0
- package/dist/http/monetisation.d.ts.map +1 -0
- package/dist/http/monetisation.js +323 -0
- package/dist/http/monetisation.js.map +1 -0
- package/dist/http/openapi.d.ts +112 -0
- package/dist/http/openapi.d.ts.map +1 -0
- package/dist/http/openapi.js +247 -0
- package/dist/http/openapi.js.map +1 -0
- package/dist/http/orgs.d.ts +605 -0
- package/dist/http/orgs.d.ts.map +1 -0
- package/dist/http/orgs.js +241 -0
- package/dist/http/orgs.js.map +1 -0
- package/dist/http/routes.d.ts +90 -0
- package/dist/http/routes.d.ts.map +1 -0
- package/dist/http/routes.js +29 -0
- package/dist/http/routes.js.map +1 -0
- package/dist/http/sanitize.d.ts +3 -0
- package/dist/http/sanitize.d.ts.map +1 -0
- package/dist/http/sanitize.js +158 -0
- package/dist/http/sanitize.js.map +1 -0
- package/dist/http/status.d.ts +157 -0
- package/dist/http/status.d.ts.map +1 -0
- package/dist/http/status.js +53 -0
- package/dist/http/status.js.map +1 -0
- package/dist/http/store-helpers.d.ts +9 -0
- package/dist/http/store-helpers.d.ts.map +1 -0
- package/dist/http/store-helpers.js +28 -0
- package/dist/http/store-helpers.js.map +1 -0
- package/dist/http/validate.d.ts +13 -1
- package/dist/http/validate.d.ts.map +1 -1
- package/dist/http/validate.js +12 -0
- package/dist/http/validate.js.map +1 -1
- package/dist/http/webhooks.d.ts +206 -0
- package/dist/http/webhooks.d.ts.map +1 -0
- package/dist/http/webhooks.js +91 -0
- package/dist/http/webhooks.js.map +1 -0
- package/dist/http/workflows.d.ts +182 -0
- package/dist/http/workflows.d.ts.map +1 -0
- package/dist/http/workflows.js +109 -0
- package/dist/http/workflows.js.map +1 -0
- package/dist/jobs/cron.d.ts +40 -0
- package/dist/jobs/cron.d.ts.map +1 -0
- package/dist/jobs/cron.js +106 -0
- package/dist/jobs/cron.js.map +1 -0
- package/dist/jobs/index.d.ts +6 -0
- package/dist/jobs/index.d.ts.map +1 -0
- package/dist/jobs/index.js +5 -0
- package/dist/jobs/index.js.map +1 -0
- package/dist/jobs/jobs.d.ts +206 -0
- package/dist/jobs/jobs.d.ts.map +1 -0
- package/dist/jobs/jobs.js +439 -0
- package/dist/jobs/jobs.js.map +1 -0
- package/dist/jobs/runtimes.d.ts +51 -0
- package/dist/jobs/runtimes.d.ts.map +1 -0
- package/dist/jobs/runtimes.js +162 -0
- package/dist/jobs/runtimes.js.map +1 -0
- package/dist/jobs/steps.d.ts +64 -0
- package/dist/jobs/steps.d.ts.map +1 -0
- package/dist/jobs/steps.js +143 -0
- package/dist/jobs/steps.js.map +1 -0
- package/dist/jobs/tools.d.ts +7 -0
- package/dist/jobs/tools.d.ts.map +1 -0
- package/dist/jobs/tools.js +110 -0
- package/dist/jobs/tools.js.map +1 -0
- package/dist/mcp/approvals.d.ts +46 -0
- package/dist/mcp/approvals.d.ts.map +1 -0
- package/dist/mcp/approvals.js +116 -0
- package/dist/mcp/approvals.js.map +1 -0
- package/dist/mcp/client.d.ts +43 -0
- package/dist/mcp/client.d.ts.map +1 -0
- package/dist/mcp/client.js +175 -0
- package/dist/mcp/client.js.map +1 -0
- package/dist/mcp/errors.d.ts +1 -0
- package/dist/mcp/errors.d.ts.map +1 -1
- package/dist/mcp/errors.js +4 -1
- package/dist/mcp/errors.js.map +1 -1
- package/dist/mcp/hono.d.ts +12 -3
- package/dist/mcp/hono.d.ts.map +1 -1
- package/dist/mcp/hono.js +45 -7
- package/dist/mcp/hono.js.map +1 -1
- package/dist/mcp/index.d.ts +3 -1
- package/dist/mcp/index.d.ts.map +1 -1
- package/dist/mcp/index.js +3 -1
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/interaction.d.ts +9 -1
- package/dist/mcp/interaction.d.ts.map +1 -1
- package/dist/mcp/interaction.js +75 -0
- package/dist/mcp/interaction.js.map +1 -1
- package/dist/mcp/routes.d.ts +40 -0
- package/dist/mcp/routes.d.ts.map +1 -0
- package/dist/mcp/routes.js +190 -0
- package/dist/mcp/routes.js.map +1 -0
- package/dist/mcp/server.d.ts +65 -2
- package/dist/mcp/server.d.ts.map +1 -1
- package/dist/mcp/server.js +135 -9
- package/dist/mcp/server.js.map +1 -1
- package/dist/middleware/index.d.ts +1 -0
- package/dist/middleware/index.d.ts.map +1 -1
- package/dist/middleware/index.js +1 -0
- package/dist/middleware/index.js.map +1 -1
- package/dist/middleware/maintenance.d.ts +18 -0
- package/dist/middleware/maintenance.d.ts.map +1 -0
- package/dist/middleware/maintenance.js +38 -0
- package/dist/middleware/maintenance.js.map +1 -0
- package/dist/notify/channels.d.ts +61 -0
- package/dist/notify/channels.d.ts.map +1 -0
- package/dist/notify/channels.js +239 -0
- package/dist/notify/channels.js.map +1 -0
- package/dist/notify/notifier.d.ts +326 -0
- package/dist/notify/notifier.d.ts.map +1 -0
- package/dist/notify/notifier.js +610 -0
- package/dist/notify/notifier.js.map +1 -0
- package/dist/notify/tools.d.ts +9 -0
- package/dist/notify/tools.d.ts.map +1 -0
- package/dist/notify/tools.js +122 -0
- package/dist/notify/tools.js.map +1 -0
- package/dist/notify/webhooks.d.ts +65 -0
- package/dist/notify/webhooks.d.ts.map +1 -0
- package/dist/notify/webhooks.js +201 -0
- package/dist/notify/webhooks.js.map +1 -0
- package/dist/realtime/bun.d.ts +33 -0
- package/dist/realtime/bun.d.ts.map +1 -0
- package/dist/realtime/bun.js +38 -0
- package/dist/realtime/bun.js.map +1 -0
- package/dist/realtime/cloudflare.d.ts +28 -0
- package/dist/realtime/cloudflare.d.ts.map +1 -0
- package/dist/realtime/cloudflare.js +60 -0
- package/dist/realtime/cloudflare.js.map +1 -0
- package/dist/realtime/index.d.ts +118 -0
- package/dist/realtime/index.d.ts.map +1 -0
- package/dist/realtime/index.js +397 -0
- package/dist/realtime/index.js.map +1 -0
- package/dist/realtime/node.d.ts +8 -0
- package/dist/realtime/node.d.ts.map +1 -0
- package/dist/realtime/node.js +153 -0
- package/dist/realtime/node.js.map +1 -0
- package/dist/storage/index.d.ts +3 -0
- package/dist/storage/index.d.ts.map +1 -0
- package/dist/storage/index.js +3 -0
- package/dist/storage/index.js.map +1 -0
- package/dist/storage/metadata.d.ts +3 -0
- package/dist/storage/metadata.d.ts.map +1 -0
- package/dist/storage/metadata.js +183 -0
- package/dist/storage/metadata.js.map +1 -0
- package/dist/storage/uploads.d.ts +146 -0
- package/dist/storage/uploads.d.ts.map +1 -0
- package/dist/storage/uploads.js +315 -0
- package/dist/storage/uploads.js.map +1 -0
- package/package.json +170 -2
package/README.md
CHANGED
|
@@ -28,8 +28,24 @@ package ships all three rather than forcing them together.
|
|
|
28
28
|
| `@dapplelight/signet-server/auth/bearer` | none | API tokens, prefixed and stored hashed. |
|
|
29
29
|
| `@dapplelight/signet-server/auth/guards` | none | Config guards that fail loudly. |
|
|
30
30
|
| `@dapplelight/signet-server/auth/better-auth` | none | Opinionated Better Auth options object. |
|
|
31
|
-
| `@dapplelight/signet-server/auth/
|
|
31
|
+
| `@dapplelight/signet-server/auth/sessions` | none | Stored sessions: devices list, revoke, id rotation. See [Stored sessions](#stored-sessions-devices-and-revocation). |
|
|
32
|
+
| `@dapplelight/signet-server/auth/otp` | none | Phone one-time codes over a pluggable `SmsSender`. |
|
|
33
|
+
| `@dapplelight/signet-server/auth/api-keys` | none | API-key manager: scoped, expiring, stored as hashes. |
|
|
34
|
+
| `@dapplelight/signet-server/auth/mcp` | `@modelcontextprotocol/server`, `zod` (optional peers) | `authTools`: per-user session and API-key tools for agents. |
|
|
35
|
+
| `@dapplelight/signet-server/auth/hono` | `hono` (optional peer) | `requireAuth`, `requireSession`, `requireStoredSession`, `sessionRoutes`, `requireApiKey`. |
|
|
36
|
+
| `@dapplelight/signet-server/http/openapi` | `hono`, `zod` >=4.2 (optional peers) | `openApiSpec`, `serveOpenApi`, `apiDoc`, `apiDocsHtml`: OpenAPI 3.1 and HTML docs from `zValidator` routes. See [Public API](#public-api-openapi-docs-webhooks-caching). |
|
|
37
|
+
| `@dapplelight/signet-server/http/cache` | `hono` (optional peer) | `httpCache` (Cache-Control, ETag, 304, Vary), `cachedResponse` (stale-while-revalidate on a `KeyValue`). |
|
|
38
|
+
| `@dapplelight/signet-server/http/webhooks` | `hono`, `zod` (optional peers) | `webhookRoutes`: admin routes for signet-db's outbound webhooks. |
|
|
39
|
+
| `@dapplelight/signet-server/http/orgs` | `hono` (optional peer) | `tenant`, `orgGuards` (`requireMember`, `requireRole`, `requirePermission`), `orgRoutes`: multi-tenant orgs on signet-db's `createOrgs`. See [Organisations](#organisations-and-tenants). |
|
|
40
|
+
| `@dapplelight/signet-server/http/monetisation` | `hono` (optional peer) | `monetisationRoutes` (offerings, anonymous ids, merge, Customer Center) and `monetisationAdminRoutes` (offerings, placements, timelines, requests) on signet-db's `createOfferings` and `createCustomers`. See [Monetisation routes](#monetisation-routes). |
|
|
41
|
+
| `@dapplelight/signet-server/abuse/captcha` | `hono` (optional peer) | `captchaVerifier` (Cloudflare Turnstile, hCaptcha, test mode) and `requireCaptcha` middleware. See [Bot checks](#bot-checks). |
|
|
42
|
+
| `@dapplelight/signet-server/abuse/email` | `hono` (optional peer) | `isDisposableEmail`, `disposableEmailChecker`, `normalizeEmail`, `blockDisposableEmail` middleware, with a bundled CC0 domain list. See [Disposable email](#disposable-email). |
|
|
43
|
+
| `@dapplelight/signet-server/http/ai-spend` | `hono` (optional peer) | `requireAiSpend` middleware and `aiSpendAdminRoutes` on signet-db's `createAiSpend`. See [AI spend routes](#ai-spend-routes). |
|
|
32
44
|
| `@dapplelight/signet-server/mcp` | `@modelcontextprotocol/server` ^2.1, `zod` >=4.2 (optional peers; not `hono`) | `defineTool`, `createMcpServer`; stdio via the SDK's `serveStdio`. See [MCP servers](#mcp-servers). |
|
|
45
|
+
| `@dapplelight/signet-server/jobs` | `zod` (optional peer) | `defineJob`, `createJobs`, retries, schedules, Cloudflare/QStash/Node runtimes. See [Jobs](#jobs). |
|
|
46
|
+
| `@dapplelight/signet-server/http/workflows` | `hono` (optional peer) | `workflowRoutes` for signet-db's durable workflows: start, status, events, approve/reject, cancel, admin list. See [Workflow routes](#workflow-routes). |
|
|
47
|
+
| `@dapplelight/signet-server/realtime` | none | `createRealtime` hub: channels per resource scoped to the tenant, presence, live updates, shared state; `sessionAuth`, `realtimeOutbox`. `/bun`, `/node` (no dependency) and `/cloudflare` (Durable Object) connect sockets. See [Real-time](#real-time-presence-live-updates-shared-state). |
|
|
48
|
+
| `@dapplelight/signet-server/storage` | none | `createUploads`: checked presigned or streamed uploads. See [Storage](#storage). |
|
|
33
49
|
| `@dapplelight/signet-server/mcp/hono` | the above, plus `hono` | `mountMcp`, `mcpHandler`: streamable HTTP through the SDK's `createMcpHandler`, 2026-07-28 and 2025 clients, per request. |
|
|
34
50
|
|
|
35
51
|
Everything but the Hono middleware is dependency-free Web Crypto.
|
|
@@ -81,6 +97,138 @@ would have quietly weakened every other app. Each option says what it costs:
|
|
|
81
97
|
| `rateLimit` | Better Auth's own limiter on `/api/auth/*` | a second limiter on top of the app's |
|
|
82
98
|
| `baseURL`, `trustedOrigins` | override `BETTER_AUTH_URL` / `WEB_URL` and the env-built origin list | |
|
|
83
99
|
|
|
100
|
+
## Stored sessions, devices and revocation
|
|
101
|
+
|
|
102
|
+
A stateless cookie (`./auth/session`) cannot be listed or revoked before it
|
|
103
|
+
expires. Stored sessions are the opt-in answer: the cookie is still an
|
|
104
|
+
HMAC-signed token, but it carries a session id (`sid`) and is only valid while
|
|
105
|
+
that id is in a `SessionStore`. Nothing changes for apps that do not opt in.
|
|
106
|
+
|
|
107
|
+
```ts
|
|
108
|
+
import { kvSessionStore, startSession, rotateSession } from "@dapplelight/signet-server/auth/sessions"
|
|
109
|
+
import { requireStoredSession, sessionRoutes } from "@dapplelight/signet-server/auth/hono"
|
|
110
|
+
import { readSessionCookie, sessionCookie } from "@dapplelight/signet-server/auth/session"
|
|
111
|
+
import { clientIp } from "@dapplelight/signet-server/middleware/rate-limit"
|
|
112
|
+
|
|
113
|
+
const sessions = (env: Env) => ({
|
|
114
|
+
cookieName: "app_session",
|
|
115
|
+
secret: env.SESSION_SECRET,
|
|
116
|
+
store: kvSessionStore(cloudflareKv(env.SESSIONS)), // or memoryKv(), upstashKv(...)
|
|
117
|
+
trust: "cloudflare" as const,
|
|
118
|
+
})
|
|
119
|
+
|
|
120
|
+
// sign-in: always a new id; the cookie the request came with is revoked (no fixation)
|
|
121
|
+
const { token } = await startSession(sessions(env), {
|
|
122
|
+
sub: user.id,
|
|
123
|
+
userAgent: c.req.header("user-agent"),
|
|
124
|
+
ip: clientIp(c, "cloudflare"),
|
|
125
|
+
previousToken: readSessionCookie(c.req.header("cookie"), sessions(env)),
|
|
126
|
+
})
|
|
127
|
+
c.header("Set-Cookie", sessionCookie(token, sessions(env)))
|
|
128
|
+
|
|
129
|
+
// password / passcode change: new id, old one dead
|
|
130
|
+
const rotated = await rotateSession(currentToken, sessions(env))
|
|
131
|
+
|
|
132
|
+
app.use("/api/*", (c, next) => requireStoredSession(sessions(c.env))(c, next))
|
|
133
|
+
app.route("/api/sessions", sessionRoutes(sessions(env)))
|
|
134
|
+
// GET / · DELETE /:id · POST /revoke-others
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
- **Records** hold `device` ("Chrome on macOS", parsed from the user agent
|
|
138
|
+
without a dependency), `ip` (from `clientIp` under your `trust` setting),
|
|
139
|
+
`createdAt`, `lastSeenAt` and `expiresAt`. `lastSeenAt` is written at most
|
|
140
|
+
once per `touchEverySeconds` (default 300), in its own key so a late write
|
|
141
|
+
can never bring a revoked session back.
|
|
142
|
+
- **Reads per request.** Validation costs one store read. `cachedSessionStore(store, { seconds })`
|
|
143
|
+
caches it in memory; the cost is that a session revoked through another
|
|
144
|
+
isolate stays valid here for up to `seconds`. Revokes through the wrapper
|
|
145
|
+
apply at once. Off unless you wrap the store.
|
|
146
|
+
- **The KV index is best-effort.** Each user's list of ids is
|
|
147
|
+
read-modify-write, so two sign-ins in the same instant can drop one from the
|
|
148
|
+
list (and from `revokeAll`). Revoking by id is always exact. Where "sign out
|
|
149
|
+
everywhere" must be exact, implement `SessionStore` over SQL.
|
|
150
|
+
- **Stateless verify refuses stored tokens.** `verifySession` and
|
|
151
|
+
`requireSession` reject a token that carries `sid`, so a route wired to the
|
|
152
|
+
wrong guard fails closed instead of skipping the revocation check.
|
|
153
|
+
- `sessionRoutes` are cookie-authenticated writes: add `csrfMiddleware` when the
|
|
154
|
+
cookie is `SameSite=None`.
|
|
155
|
+
|
|
156
|
+
### Signing-key rotation
|
|
157
|
+
|
|
158
|
+
Both cookie kinds accept `previousSecrets`. A cookie signed with an old key
|
|
159
|
+
still verifies, and `requireSession` / `requireStoredSession` send it back
|
|
160
|
+
signed with the current `secret` (same `exp`), so rotating a key signs nobody
|
|
161
|
+
out. Remove an old key once `ttlSeconds` has passed.
|
|
162
|
+
|
|
163
|
+
```ts
|
|
164
|
+
{ cookieName: "app_session", secret: env.SESSION_SECRET, previousSecrets: [env.SESSION_SECRET_OLD] }
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
## Phone one-time codes
|
|
168
|
+
|
|
169
|
+
```ts
|
|
170
|
+
import { requestPhoneOtp, verifyPhoneOtp, devSmsSender } from "@dapplelight/signet-server/auth/otp"
|
|
171
|
+
import { upstashRateLimitStore } from "@dapplelight/signet-server/adapters/upstash"
|
|
172
|
+
|
|
173
|
+
const otp = {
|
|
174
|
+
kv,
|
|
175
|
+
secret: env.OTP_SECRET,
|
|
176
|
+
sender: devSmsSender({ appEnv: env.APP_ENV }), // your SMS provider in production
|
|
177
|
+
rateLimit: upstashRateLimitStore(upstash), // an exact store: this is a security control
|
|
178
|
+
}
|
|
179
|
+
const sent = await requestPhoneOtp(otp, { phone: body.phone, ip: clientIp(c, "cloudflare") })
|
|
180
|
+
const checked = await verifyPhoneOtp(otp, { phone: body.phone, code: body.code, ip: clientIp(c, "cloudflare") })
|
|
181
|
+
if (checked.ok) // sign in checked.phone with startSession
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
- Codes are stored as an HMAC keyed by `secret` and the phone, with an expiry
|
|
185
|
+
(default 5 minutes). Verify compares in constant time, is single use and
|
|
186
|
+
destroys the code after `maxAttempts` (default 5) wrong guesses.
|
|
187
|
+
- Requests are limited per IP (default 10 an hour) and per phone (default 3 per
|
|
188
|
+
15 minutes). A new request replaces the old code.
|
|
189
|
+
- Verifies are limited per IP with `verifyFailuresPerIp` (default 30 an hour),
|
|
190
|
+
so one address cannot spread 5 guesses across many numbers. The slot is
|
|
191
|
+
taken before the code is checked and the decision comes from the store's
|
|
192
|
+
atomic count, so a parallel burst is held to the limit too; the cost is that
|
|
193
|
+
successful verifies use a slot as well. Past it, verify answers
|
|
194
|
+
`TOO_MANY_ATTEMPTS` without checking the code or using up that phone's
|
|
195
|
+
attempts. Pass `ip` to `verifyPhoneOtp`; without one this limit is skipped,
|
|
196
|
+
since a shared bucket would let anyone lock every user out.
|
|
197
|
+
- `normalizePhone` gives E.164: Indian numbers in their national forms
|
|
198
|
+
(`98765 43210`, `098765…`, `91…`), everything else with `+` or `00`.
|
|
199
|
+
- Results carry `INVALID_PHONE`, `RATE_LIMITED`, `INVALID_CODE`, `CODE_EXPIRED`
|
|
200
|
+
and `TOO_MANY_ATTEMPTS`, all with default copy in `signet-lib/api`.
|
|
201
|
+
- No code is ever logged. `devSmsSender` prints the SMS for local work and
|
|
202
|
+
throws when `appEnv` is production or staging. A real SMS sender is a
|
|
203
|
+
`{ send(to, message) }` object.
|
|
204
|
+
- On Workers KV the attempt counter is read-modify-write, so concurrent guesses
|
|
205
|
+
can pass the cap by a few; keep OTP state in a store with `incr`.
|
|
206
|
+
|
|
207
|
+
## API keys
|
|
208
|
+
|
|
209
|
+
```ts
|
|
210
|
+
import { createApiKey, kvApiKeyStore, listApiKeys, revokeApiKey } from "@dapplelight/signet-server/auth/api-keys"
|
|
211
|
+
import { requireApiKey } from "@dapplelight/signet-server/auth/hono"
|
|
212
|
+
|
|
213
|
+
const keys = kvApiKeyStore(kv)
|
|
214
|
+
const { token, key } = await createApiKey(keys, { sub: user.id, name: "CI", prefix: "app", scopes: ["read"], expiresInSeconds: 90 * 86400 })
|
|
215
|
+
// show `token` once. `key` (id, name, start, scopes, createdAt, lastUsedAt, expiresAt) is safe to list.
|
|
216
|
+
|
|
217
|
+
app.use("/api/export/*", requireApiKey({ store: keys, prefix: "app", scopes: ["read"] }))
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
Only the SHA-256 hash is stored (`createApiToken` from `./auth/bearer`). A
|
|
221
|
+
missing, revoked or expired key is 401; a missing scope is 403. `lastUsedAt` is
|
|
222
|
+
written at most once a minute per key, in its own key, and `defer` moves the
|
|
223
|
+
write off the response.
|
|
224
|
+
|
|
225
|
+
### For agents
|
|
226
|
+
|
|
227
|
+
`authTools({ sessions, apiKeys })` from `./auth/mcp` gives `list_my_sessions`,
|
|
228
|
+
`revoke_session`, `list_api_keys` and `revoke_api_key`, scoped to the caller's
|
|
229
|
+
token `sub`. Revokes go through `requireApproval`; no tool returns a secret, a
|
|
230
|
+
hash or a code.
|
|
231
|
+
|
|
84
232
|
## Carried forward deliberately
|
|
85
233
|
|
|
86
234
|
Things one product got right that the others lacked:
|
|
@@ -112,6 +260,10 @@ app, not here.
|
|
|
112
260
|
secrets, constant-time compare, passcode salting, token prefixes and the
|
|
113
261
|
production guard.
|
|
114
262
|
|
|
263
|
+
`node test/node-smoke.mjs`, after `bun run build`, loads the built `dist`
|
|
264
|
+
under plain Node through the package's own exports map and exercises the
|
|
265
|
+
adapters, analytics sinks and jobs. CI runs it on Node 22 and 24.
|
|
266
|
+
|
|
115
267
|
## HTTP — error envelope and validation
|
|
116
268
|
|
|
117
269
|
`@dapplelight/signet-server/http` is the server half of the contract in `@dapplelight/signet-lib/api`.
|
|
@@ -140,6 +292,630 @@ Validation failures put `flatten()` output in `details`, where the envelope has
|
|
|
140
292
|
a place for it. app-a stringified it into the message field, forcing the client
|
|
141
293
|
to `JSON.parse` an error string to render field errors.
|
|
142
294
|
|
|
295
|
+
### Typed routes for `hc`
|
|
296
|
+
|
|
297
|
+
`parseBody` reads inside the handler, so Hono cannot see the type. For routes a
|
|
298
|
+
typed client calls, use `zValidator`: the same envelope on failure, and the
|
|
299
|
+
schema's input becomes the client's request type.
|
|
300
|
+
|
|
301
|
+
```ts
|
|
302
|
+
import { zValidator } from "@dapplelight/signet-server/http/validate"
|
|
303
|
+
|
|
304
|
+
const app = new Hono()
|
|
305
|
+
.post("/api/notes", zValidator("json", NoteInput), (c) => c.json(save(c.req.valid("json")), 201))
|
|
306
|
+
.get("/api/notes/:id", zValidator("param", z.object({ id: z.string() })), (c) => c.json(get(c.req.valid("param").id)))
|
|
307
|
+
export type AppType = typeof app
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
Query, param and header values arrive as strings, so coerce them
|
|
311
|
+
(`z.coerce.number()`). A JSON body needs a JSON `Content-Type`.
|
|
312
|
+
|
|
313
|
+
Signet's own route groups mount into the same chain, and their types come with
|
|
314
|
+
them. `SessionRoutes` (`./auth/hono`), `EntitlementRoutes` and `FlagRoutes`
|
|
315
|
+
(`./http/routes`) type a group on its own. Import them with `import type` so no
|
|
316
|
+
server code reaches a browser bundle.
|
|
317
|
+
|
|
318
|
+
```ts
|
|
319
|
+
import { entitlementRoutes, flagRoutes } from "@dapplelight/signet-server/http/routes"
|
|
320
|
+
|
|
321
|
+
app
|
|
322
|
+
.use("/api/me/*", requireStoredSession(sessionOpts))
|
|
323
|
+
.route("/api/me/entitlements", entitlementRoutes({ entitlements, subject: (c) => c.get("session").record.sub }))
|
|
324
|
+
.route("/api/me/flags", flagRoutes({ flags, subject: (c) => ({ id: c.get("session").record.sub }) }))
|
|
325
|
+
```
|
|
326
|
+
|
|
327
|
+
The client half is `createRpcClient` in `@dapplelight/signet-lib/api`.
|
|
328
|
+
### Admin routes
|
|
329
|
+
|
|
330
|
+
`@dapplelight/signet-server/http/admin` mounts signet-db's `defineAdmin(...)`
|
|
331
|
+
as Hono routes. Typed by shape, so this package does not depend on signet-db.
|
|
332
|
+
|
|
333
|
+
```ts
|
|
334
|
+
import { adminRoutes } from "@dapplelight/signet-server/http/admin"
|
|
335
|
+
|
|
336
|
+
app.onError(errorHandler({ isProduction }))
|
|
337
|
+
app.route("/admin", adminRoutes(admin, {
|
|
338
|
+
db: (c) => createDb(c.env.DB, { audit }),
|
|
339
|
+
ctx: async (c) => {
|
|
340
|
+
const user = await currentUser(c)
|
|
341
|
+
return user ? { actor: { type: "user", id: user.id }, role: user.role } : undefined
|
|
342
|
+
},
|
|
343
|
+
}))
|
|
344
|
+
```
|
|
345
|
+
|
|
346
|
+
`GET /` metadata; `GET|POST /:table` list (`?limit&cursor&sort&order&q&withDeleted&filter=<json>`)
|
|
347
|
+
and create; `GET|PATCH|DELETE /:table/:id`; `POST /:table/bulk-delete` with
|
|
348
|
+
`{ ids }`; `POST /:table/:id/:action`. A missing context is 401; signet-db's
|
|
349
|
+
`AdminError` becomes an `ApiException`, so the envelope carries its status,
|
|
350
|
+
code, field `details` and the request id.
|
|
351
|
+
|
|
352
|
+
### Workflow routes
|
|
353
|
+
|
|
354
|
+
`@dapplelight/signet-server/http/workflows` mounts signet-db's
|
|
355
|
+
`createWorkflows(...)` (durable runs with approval steps; see signet-db's
|
|
356
|
+
README) over HTTP. Typed by shape, so this package does not depend on signet-db.
|
|
357
|
+
|
|
358
|
+
```ts
|
|
359
|
+
import { workflowRoutes } from "@dapplelight/signet-server/http/workflows"
|
|
360
|
+
|
|
361
|
+
app.use("/api/workflows/*", requireStoredSession(sessionOpts))
|
|
362
|
+
app.route("/api/workflows", workflowRoutes({
|
|
363
|
+
workflows: wf, // createWorkflows(db, { ..., approvals, notify })
|
|
364
|
+
subject: (c) => c.get("session").payload.sub,
|
|
365
|
+
isAdmin: (c) => c.get("session").payload.role === "admin", // default: nobody
|
|
366
|
+
canStart: (c, workflow) => workflow === "expense", // default: admins only
|
|
367
|
+
}))
|
|
368
|
+
```
|
|
369
|
+
|
|
370
|
+
| Route | Who |
|
|
371
|
+
|---|---|
|
|
372
|
+
| `GET /runs` (`?status&workflow&before&limit`) | admins: every run; everyone else: runs they started |
|
|
373
|
+
| `POST /runs` `{ workflow, input }` | `canStart` |
|
|
374
|
+
| `GET /runs/:id` (run plus step history) | admins, the starter, the run's approvers |
|
|
375
|
+
| `POST /runs/:id/cancel` | admins, the starter |
|
|
376
|
+
| `POST /runs/:id/steps/:step/approve` and `/reject` `{ reason? }` | a listed approver; 409 once decided or timed out |
|
|
377
|
+
| `POST /events` `{ name, payload?, runId? }` | admins (apps usually call `wf.sendEvent` from their own code) |
|
|
378
|
+
| `GET /approvals` | approval steps waiting on the caller |
|
|
379
|
+
|
|
380
|
+
A run the caller may not see is 404. Approval steps tie into the MCP approval
|
|
381
|
+
primitive: pass `approvals: kvApprovals(kv)` to `createWorkflows` and each
|
|
382
|
+
approver also gets a record in `approvalRoutes`' inbox; approving there or
|
|
383
|
+
here settles the step. Pass `notify: (to, r) => notifier.notify(to,
|
|
384
|
+
"workflow.approval", r)` with a `workflow.approval` template (data:
|
|
385
|
+
`{ runId, stepId, workflow, summary, approvers, expiresAt }`) to tell them.
|
|
386
|
+
Nothing runs until something calls `wf.tick()`: a cron trigger on Workers,
|
|
387
|
+
`wf.poll()` on Bun or Node.
|
|
388
|
+
|
|
389
|
+
### Organisations and tenants
|
|
390
|
+
|
|
391
|
+
`@dapplelight/signet-server/http/orgs` puts signet-db's `createOrgs` on Hono,
|
|
392
|
+
typed by shape. One app serves many orgs, each on its own domain.
|
|
393
|
+
|
|
394
|
+
```ts
|
|
395
|
+
import { orgGuards, orgRoutes, tenant, currentTenant } from "@dapplelight/signet-server/http/orgs"
|
|
396
|
+
|
|
397
|
+
const userId = (c) => c.get("session")?.sub
|
|
398
|
+
app.use("/api/*", tenant({ orgs, rootDomain: "app.example" })) // c.get("tenant")
|
|
399
|
+
const { requirePermission, requireRole } = orgGuards({ orgs, userId })
|
|
400
|
+
app.get("/api/projects", requirePermission("projects:read"), async (c) =>
|
|
401
|
+
c.json(await scoped(db, { orgId: currentTenant(c).id }).select(projects)))
|
|
402
|
+
app.route("/api/orgs", orgRoutes({ orgs, userId, email: (c) => c.get("session")?.email }))
|
|
403
|
+
// org-scoped admin: pass the tenant into the admin context
|
|
404
|
+
app.use("/admin/*", requirePermission("admin:access"))
|
|
405
|
+
app.route("/admin", adminRoutes(admin, { db, ctx: (c) => ({ actor: { type: "user", id: userId(c) }, role: "admin", orgId: currentTenant(c).id }) }))
|
|
406
|
+
```
|
|
407
|
+
|
|
408
|
+
- `tenant()` resolves, first match wins: custom domain, subdomain of
|
|
409
|
+
`rootDomain`, a route `param`, the `x-org` header, the `signet_org` cookie
|
|
410
|
+
that `POST /api/orgs/switch` sets. It names the org; it grants nothing.
|
|
411
|
+
- Guards: 401 signed out, 404 when the caller is not a member (an outsider
|
|
412
|
+
learns nothing about the org), 403 for a member without the role or
|
|
413
|
+
permission. `currentMembership(c)` has the role and permissions.
|
|
414
|
+
- `orgRoutes`: my orgs, create, switch, current org and settings (name, slug,
|
|
415
|
+
theme, brand colour; a `domain` in the body gets 400, because whoever holds
|
|
416
|
+
a host decides the tenant, so set it with `orgs.update` from an operator
|
|
417
|
+
or verified-DNS flow), members (change role, remove, leave), invites
|
|
418
|
+
(create, list, revoke, preview, accept). Every `/current` route checks
|
|
419
|
+
membership in the tenant, and signet-db refuses role escalation and
|
|
420
|
+
removing the last owner. `OrgError` becomes the envelope.
|
|
421
|
+
|
|
422
|
+
### Comments, mentions, activity and history routes
|
|
423
|
+
|
|
424
|
+
`@dapplelight/signet-server/http/collab` mounts signet-db's `createCollab`
|
|
425
|
+
(comments, mentions, timeline, versions) over HTTP, typed by shape. Mount it
|
|
426
|
+
after `tenant()`; every route acts in the request's org.
|
|
427
|
+
|
|
428
|
+
```ts
|
|
429
|
+
import { collabRoutes, mentionTemplates, notifyMentions } from "@dapplelight/signet-server/http/collab"
|
|
430
|
+
|
|
431
|
+
const templates = { ...appTemplates, ...mentionTemplates({ url: (m) => `https://app.example/${m.table}/${m.rowId}` }) }
|
|
432
|
+
const notifier = createNotifier({ templates, /* channels, store, recipients… */ })
|
|
433
|
+
const collab = createCollab(db, { tables: { comments }, records: { tasks }, orgs, notify: notifyMentions(notifier) })
|
|
434
|
+
app.use("/api/*", tenant({ orgs, rootDomain: "app.example" }))
|
|
435
|
+
app.route("/api/collab", collabRoutes({ collab, userId: (c) => c.get("session")?.sub }))
|
|
436
|
+
```
|
|
437
|
+
|
|
438
|
+
| Route | Who |
|
|
439
|
+
|---|---|
|
|
440
|
+
| `GET /mentions?q=` | members: org members to mention |
|
|
441
|
+
| `GET /:table/:id/comments` | members who can read the record |
|
|
442
|
+
| `POST /:table/:id/comments` `{ body, parentId? }` | the same |
|
|
443
|
+
| `PATCH /comments/:commentId` `{ body }` | its author |
|
|
444
|
+
| `DELETE /comments/:commentId` | its author, or `comments:moderate` |
|
|
445
|
+
| `GET /:table/:id/timeline?before&limit` | readers: `{ items, nextCursor }` |
|
|
446
|
+
| `GET /:table/:id/versions?before&limit` | readers |
|
|
447
|
+
| `GET /:table/:id/versions/diff?from&to` | readers |
|
|
448
|
+
| `POST /:table/:id/versions/:n/restore` | `<table>:write` |
|
|
449
|
+
| `POST /:table/:id/undo` `{ expected? }` | `<table>:write`; 409 when the record moved on |
|
|
450
|
+
|
|
451
|
+
Signed out is 401. Another org's record, a table not in `records`, or a
|
|
452
|
+
caller who is not a member is 404, whatever header or cookie names the org.
|
|
453
|
+
`mentionTemplates()` is a `comment.mention` template for email and the
|
|
454
|
+
in-app inbox in the `mentions` category, so people can turn it off per
|
|
455
|
+
channel in their preferences. `notifyMentions(notifier)` sends it with the
|
|
456
|
+
mention's `key` as the idempotency key, so a person is told once.
|
|
457
|
+
`hc<CollabRoutes>` types a client.
|
|
458
|
+
|
|
459
|
+
### Monetisation routes
|
|
460
|
+
|
|
461
|
+
`@dapplelight/signet-server/http/monetisation` serves signet-db's
|
|
462
|
+
`createOfferings` and `createCustomers`, typed by shape.
|
|
463
|
+
|
|
464
|
+
```ts
|
|
465
|
+
import { monetisationAdminRoutes, monetisationRoutes } from "@dapplelight/signet-server/http/monetisation"
|
|
466
|
+
|
|
467
|
+
const me = (c) => c.get("session")?.sub
|
|
468
|
+
app.route("/api/billing", monetisationRoutes({
|
|
469
|
+
offerings, customers,
|
|
470
|
+
subject: (c) => me(c) ?? c.req.header("x-app-user"), // signed in, or the device's anonymous id
|
|
471
|
+
userId: me, // merge targets only a signed-in user
|
|
472
|
+
orgId: (c) => currentTenant(c).id, // multi-tenant apps
|
|
473
|
+
}))
|
|
474
|
+
app.route("/api/admin/billing", monetisationAdminRoutes({
|
|
475
|
+
offerings, customers,
|
|
476
|
+
charts, // signet-db createCharts: charts, audiences, CSV
|
|
477
|
+
pricing, // signet-db createPricing: pricing experiments
|
|
478
|
+
authorize: (c) => c.get("session")?.role === "admin", // deny by default: anything but true is 403
|
|
479
|
+
actor: (c) => ({ type: "user", id: me(c) }),
|
|
480
|
+
}))
|
|
481
|
+
```
|
|
482
|
+
|
|
483
|
+
| Route | What |
|
|
484
|
+
|---|---|
|
|
485
|
+
| `GET /offerings/:placement` | The offering and paywall for this audience (404 none). Country from `cf-ipcountry`, else `?country`; platform from `?platform`. Attributes come only from your `audience(c)`, never the query. Each product's `offers` are cut to the ones this customer may see (`customers.withOffers`; no subject is a new visitor). A placement running a pricing experiment assigns the subject sticky, records the exposure and says so in `offering.experiment`. |
|
|
486
|
+
| `POST /offerings/:placement/impression` | Log that the customer saw this placement's paywall, for paywall conversion (204; once per customer, offering and day). |
|
|
487
|
+
| `POST /offerings/:placement/redeem` | `{ offerId }`: claim an offer once, before applying it at checkout; refused is 409 `OFFER_REFUSED` with the reason (`not_eligible`, `already_used`, `no_such_offer`). |
|
|
488
|
+
| `POST /anonymous` | `{ anonymousId }` for a device before sign-in. |
|
|
489
|
+
| `POST /merge` | `{ anonymousId }` into the signed-in user; refused is 409 `MERGE_REFUSED` with the reason. |
|
|
490
|
+
| `GET /customer`, `GET /customer/timeline` | The Customer Center overview; the customer's own history. |
|
|
491
|
+
| `POST /customer/cancel` | Web: cancelled at the gateway. Store: `{ cancelled: false, reason: "store", manageUrl }`. |
|
|
492
|
+
| `POST /customer/retention` | Accept the retention offer. |
|
|
493
|
+
| `POST /customer/refund`, `POST /customer/support` | Recorded and sent to the team through `notify`. A refund for a payment that is not the caller's is 404. |
|
|
494
|
+
| Admin: `GET/POST /offerings/:key`, `GET /placements`, `PUT /placements/:placement`, `GET /customers/:subject[/timeline]`, `GET /requests`, `PATCH /requests/:id` | Publish versions, point placements, read any customer's timeline, close requests. |
|
|
495
|
+
| Admin: `POST /customers/:subject/promotional`, `DELETE /customers/:subject/promotional/:id` | `{ plan, days \| expiresAt, note? }`: grant a promotional plan that lapses on its own; end one early. |
|
|
496
|
+
| Admin: `GET /charts`, `GET /charts/csv` | `?from=&to=` (YYYY-MM-DD, default the last 30 days) `&store=&plan=&country=&offering=&audience=`: subscription charts, or one CSV row per day as an attachment. |
|
|
497
|
+
| Admin: `GET /audiences`, `POST /audiences`, `DELETE /audiences/:id` | Saved chart filters: `{ name, filter: { store?, plan?, country?, offering? } }`. |
|
|
498
|
+
| Admin: `PUT /placements/:placement` with `{ ..., experiment }` | Run a pricing experiment on the placement (it replaces the placement, so omit `experiment` to unlink). |
|
|
499
|
+
| Admin: `GET /pricing/:experiment[?alpha=]` | `{ readout }`: per variant the offering, exposures, conversion with lift and p-value, trial conversion, revenue per exposed user and an LTV estimate. |
|
|
500
|
+
| Admin: `POST /pricing/:experiment/rollout` | `{ variant }`: the placement serves that variant's offering and the experiment stops. Not running on a placement is 400. |
|
|
501
|
+
|
|
502
|
+
signet-db errors become the envelope (`BAD_VALUE` is 400 `VALIDATION_FAILED`,
|
|
503
|
+
`NOT_FOUND` 404). These are cookie-authenticated writes: put
|
|
504
|
+
`csrfMiddleware` in front when the session cookie is `SameSite=None`.
|
|
505
|
+
|
|
506
|
+
### Experiment routes
|
|
507
|
+
|
|
508
|
+
`@dapplelight/signet-server/http/experiments` serves signet-db's
|
|
509
|
+
`createExperiments`, typed by shape.
|
|
510
|
+
|
|
511
|
+
```ts
|
|
512
|
+
import { experimentAdminRoutes, experimentRoutes } from "@dapplelight/signet-server/http/experiments"
|
|
513
|
+
|
|
514
|
+
app.route("/api/experiments", experimentRoutes({
|
|
515
|
+
experiments,
|
|
516
|
+
subject: (c) => ({ id: me(c) ?? c.req.header("x-app-user"), plan: c.get("session")?.plan }),
|
|
517
|
+
}))
|
|
518
|
+
app.route("/api/admin/experiments", experimentAdminRoutes({
|
|
519
|
+
experiments,
|
|
520
|
+
authorize: (c) => c.get("session")?.role === "admin", // deny by default
|
|
521
|
+
actor: (c) => ({ type: "user", id: me(c) }),
|
|
522
|
+
}))
|
|
523
|
+
```
|
|
524
|
+
|
|
525
|
+
| Route | What |
|
|
526
|
+
|---|---|
|
|
527
|
+
| `GET /:key` | The caller's `{ assignment }`; nothing recorded. No subject is 401, an unknown key 404. |
|
|
528
|
+
| `POST /:key/exposure` | Records the exposure (once per subject, only while running). |
|
|
529
|
+
| Admin: `GET /`, `POST /` | List; create a draft `{ key, variants, goal, description?, audience?, salt? }`. |
|
|
530
|
+
| Admin: `GET /:key[?goal=]`, `PATCH /:key` | `{ experiment, results }` (results null without the events table); edit a draft. |
|
|
531
|
+
| Admin: `POST /:key/start`, `/stop`, `/rollout` | Start or resume, stop, `{ variant }` for everyone. A wrong move is 409 `CONFLICT`. |
|
|
532
|
+
|
|
533
|
+
Subject plan and attributes come from your `subject(c)`, never the query.
|
|
534
|
+
|
|
535
|
+
### Status page and maintenance mode
|
|
536
|
+
|
|
537
|
+
`@dapplelight/signet-server/http/status` serves signet-db's `createStatus`;
|
|
538
|
+
`@dapplelight/signet-server/middleware/maintenance` turns the API off for
|
|
539
|
+
everyone but the allowlist.
|
|
540
|
+
|
|
541
|
+
```ts
|
|
542
|
+
import { statusAdminRoutes, statusRoutes } from "@dapplelight/signet-server/http/status"
|
|
543
|
+
import { maintenanceMode } from "@dapplelight/signet-server/middleware/maintenance"
|
|
544
|
+
|
|
545
|
+
app.use("*", maintenanceMode({
|
|
546
|
+
state: () => status.maintenance(),
|
|
547
|
+
paths: ["/health", "/api/status", "/api/admin"], // always pass: health checks, status page, admin
|
|
548
|
+
allow: (c) => c.get("session")?.role === "admin", // admins pass everywhere
|
|
549
|
+
}))
|
|
550
|
+
app.route("/api/status", statusRoutes({ status })) // public, Cache-Control: public, max-age=30
|
|
551
|
+
app.route("/api/admin/status", statusAdminRoutes({ status, authorize, actor }))
|
|
552
|
+
```
|
|
553
|
+
|
|
554
|
+
| Route | What |
|
|
555
|
+
|---|---|
|
|
556
|
+
| `GET /` (public) | `{ status, components, incidents, maintenance }` for the status page. |
|
|
557
|
+
| Admin: `GET /components`, `PUT /components/:key`, `DELETE /components/:key` | Components and their status. |
|
|
558
|
+
| Admin: `GET /incidents?days=`, `POST /incidents`, `POST /incidents/:id/updates` | Open an incident, post updates; `resolved` closes it. |
|
|
559
|
+
| Admin: `GET /maintenance`, `PUT /maintenance` | `{ on, message?, until? }`: the maintenance switch. |
|
|
560
|
+
|
|
561
|
+
While on, a request outside the allowlist gets 503 with the standard
|
|
562
|
+
envelope (`code: "MAINTENANCE"`, the state's message) and `Retry-After`:
|
|
563
|
+
seconds until `until`, else `retryAfterSeconds` (300). A path prefix
|
|
564
|
+
matches itself and what is under it. The state is read at most once per
|
|
565
|
+
`cacheMs` (5000) per isolate, so a toggle reaches every isolate within that.
|
|
566
|
+
### Funnel routes
|
|
567
|
+
|
|
568
|
+
`@dapplelight/signet-server/http/funnels` serves signet-db's `createFunnels`
|
|
569
|
+
as a public hosted checkout and the redemption the app calls after install.
|
|
570
|
+
|
|
571
|
+
```ts
|
|
572
|
+
import { funnelRoutes, redemptionLink } from "@dapplelight/signet-server/http/funnels"
|
|
573
|
+
|
|
574
|
+
app.route("/f", funnelRoutes({
|
|
575
|
+
funnels,
|
|
576
|
+
secret: env.FUNNEL_SECRET, // 32+ characters
|
|
577
|
+
redeemUrl: "https://app.example.com/redeem", // a universal / app link, or example://redeem
|
|
578
|
+
userId: (c) => c.get("session")?.sub,
|
|
579
|
+
page: { stripePublishableKey: env.STRIPE_PUBLISHABLE_KEY, razorpayKeyId: env.RAZORPAY_KEY_ID },
|
|
580
|
+
}))
|
|
581
|
+
app.post("/webhooks/:gateway", (c) => payments.handleWebhook(c.req.param("gateway"), c.req.raw))
|
|
582
|
+
```
|
|
583
|
+
|
|
584
|
+
| Route | What |
|
|
585
|
+
|---|---|
|
|
586
|
+
| `GET /:key` | The hosted page: questions, plan picker, email and code, then the gateway. Plain HTML with one nonce'd script and a strict CSP. |
|
|
587
|
+
| `GET /:key/config?code=` | Funnel, priced web products, the code priced per product. |
|
|
588
|
+
| `POST /:key/events` | `{ step }`: a step view (only that funnel's steps). |
|
|
589
|
+
| `POST /:key/checkout` | `{ productId, answers?, code?, email? }`: `{ session, checkout }`; a refused code is 400. |
|
|
590
|
+
| `GET /sessions/:id` | Status; once paid, and only to the browser that started the checkout, `{ redemption: { link, token, expiresAt } }`. |
|
|
591
|
+
| `POST /redeem` | `{ token }` as the signed-in user. 400 `BAD_TOKEN` (forged, expired), 409 `REDEEM_REFUSED` with the reason. |
|
|
592
|
+
|
|
593
|
+
The page finishes the checkout the way the gateway answers: Stripe's
|
|
594
|
+
**Express Checkout Element** (Apple Pay, Google Pay) and Payment Element,
|
|
595
|
+
with Stripe.js loaded from Stripe at runtime; Razorpay Checkout for an
|
|
596
|
+
order; a redirect `url`; or a POSTed `form` (PayU). Back from the gateway it
|
|
597
|
+
waits for the webhook, then shows "Open the app" and the code to paste.
|
|
598
|
+
|
|
599
|
+
**Redemption tokens** (`redemptionToken`, `readRedemptionToken`,
|
|
600
|
+
`redemptionLink`): HMAC-signed with `secret`, expiring (`ttlSeconds`, default
|
|
601
|
+
7 days), bound to their purpose so a session cookie signed with the same
|
|
602
|
+
secret never passes as one. `previousSecrets` rotates keys. A token works
|
|
603
|
+
once because redeeming claims its session for one account; `GET
|
|
604
|
+
/sessions/:id` stops issuing them after that.
|
|
605
|
+
|
|
606
|
+
The session id sits in the gateway's return URL, so it is not a secret.
|
|
607
|
+
`POST /:key/checkout` sets an HttpOnly, SameSite=Lax cookie (`signet_funnel`,
|
|
608
|
+
an HMAC of the session id under `secret`, scoped to the mount path), and
|
|
609
|
+
`GET /sessions/:id` issues a redemption link only to the browser that holds
|
|
610
|
+
it. Anyone else gets the status; a buyer who finishes on another device gets
|
|
611
|
+
the link from the `onPaid` email.
|
|
612
|
+
|
|
613
|
+
**Apple Pay domain verification.** Stripe needs no file: register the page's
|
|
614
|
+
domain once with `stripe.raw("POST", "/payment_method_domains", { domain_name })`.
|
|
615
|
+
Razorpay, PayPal and Dodo Payments hand you a file; serve it with
|
|
616
|
+
signet-payments' `applePayDomainAssociation(file)` in front of the app:
|
|
617
|
+
`applePayDomainAssociation(file)(request) ?? app.fetch(request)`.
|
|
618
|
+
|
|
619
|
+
Put `rateLimit` in front of `/:key/checkout` and `/redeem`. Nothing is
|
|
620
|
+
granted until signet-payments verifies the gateway's webhook signature.
|
|
621
|
+
|
|
622
|
+
## Real-time: presence, live updates, shared state
|
|
623
|
+
|
|
624
|
+
One hub, the same protocol on every runtime. The hub owns channels,
|
|
625
|
+
presence and state; an adapter connects real WebSockets to it.
|
|
626
|
+
|
|
627
|
+
```ts
|
|
628
|
+
import { createRealtime, sessionAuth, realtimeOutbox, REALTIME_TOPIC } from "@dapplelight/signet-server/realtime"
|
|
629
|
+
import { verifySession } from "@dapplelight/signet-server/auth/session"
|
|
630
|
+
import { grants } from "@dapplelight/signet-server/http/orgs"
|
|
631
|
+
|
|
632
|
+
const hub = createRealtime({
|
|
633
|
+
// Deny by default: without authorize, every join is refused.
|
|
634
|
+
authorize: (who, channel) => channel.startsWith("record:") && grants(who.permissions ?? [], "records:read"),
|
|
635
|
+
})
|
|
636
|
+
const authenticate = sessionAuth({ verify: (t) => verifySession(t, sessionOpts), cookieName: "app_session", orgs })
|
|
637
|
+
|
|
638
|
+
// Bun
|
|
639
|
+
import { bunRealtime } from "@dapplelight/signet-server/realtime/bun"
|
|
640
|
+
const live = bunRealtime(hub, { authenticate })
|
|
641
|
+
Bun.serve({ fetch: (req, srv) => (new URL(req.url).pathname === "/realtime" ? live.upgrade(req, srv) : app.fetch(req)), websocket: live.websocket })
|
|
642
|
+
|
|
643
|
+
// Node: http.Server, or @hono/node-server's
|
|
644
|
+
import { attachRealtime } from "@dapplelight/signet-server/realtime/node"
|
|
645
|
+
attachRealtime(server, hub, { path: "/realtime", authenticate })
|
|
646
|
+
|
|
647
|
+
// Cloudflare: one Durable Object per org
|
|
648
|
+
import { realtimeRoom, connectRoom, roomPublisher } from "@dapplelight/signet-server/realtime/cloudflare"
|
|
649
|
+
export const RealtimeRoom = realtimeRoom({ authorize }) // export from the worker entry; bind as REALTIME
|
|
650
|
+
app.get("/realtime", (c) => connectRoom(c.env.REALTIME, c.req.raw, { authenticate }))
|
|
651
|
+
```
|
|
652
|
+
|
|
653
|
+
- **Tenancy.** A connection's org comes from `authenticate`, never from
|
|
654
|
+
the client, and channels live under it: org A's `record:docs:1` and org
|
|
655
|
+
B's are different channels, and no message names an org. `sessionAuth`
|
|
656
|
+
takes the org from `?org=` or the `signet_org` cookie and refuses a user
|
|
657
|
+
who is not a member. `hub.disconnect(orgId, userId)` closes a removed
|
|
658
|
+
member's sockets; a session's `exp` closes them when it passes.
|
|
659
|
+
- **Origins.** Browsers send cookies on cross-site WebSocket handshakes, so
|
|
660
|
+
`admit` (every adapter calls it) refuses an `Origin` other than the
|
|
661
|
+
request's host unless it is in `origins`.
|
|
662
|
+
- **Live updates.** `hub.publish(orgId, channel, event, data)` after a
|
|
663
|
+
write, or in the same atomic write through signet-db's outbox:
|
|
664
|
+
|
|
665
|
+
```ts
|
|
666
|
+
await db.batch([(tx) => tx.update(docs).set(patch).where(eq(docs.id, id)),
|
|
667
|
+
enqueue(db, REALTIME_TOPIC, { orgId, channel: `record:docs:${id}`, event: "updated", data: { id, by: userId } })])
|
|
668
|
+
const live = realtimeOutbox(hub) // or realtimeOutbox(roomPublisher(env.REALTIME))
|
|
669
|
+
await drainOutbox(db, { send: (m) => (m.topic === REALTIME_TOPIC ? live.send(m) : queue.send(m)) })
|
|
670
|
+
```
|
|
671
|
+
|
|
672
|
+
The outbox row id becomes the event id, and the client drops a redelivered
|
|
673
|
+
one.
|
|
674
|
+
- **Resume.** Each channel keeps its last `history` (100) events with a
|
|
675
|
+
sequence number and an epoch. A client rejoins with `since` and gets
|
|
676
|
+
exactly what it missed, or `reset` when the gap is older than the history
|
|
677
|
+
or the channel was recreated: reload the record.
|
|
678
|
+
- **Presence.** Members per channel, one entry per user with a tab count,
|
|
679
|
+
`joined` / `left` on change, `typing` (clears itself after `typingMs`, 6 s)
|
|
680
|
+
and `editing` (a field name, until cleared). A connection silent for
|
|
681
|
+
`timeoutMs` (45 s) is closed and leaves; clients ping every `heartbeatMs`
|
|
682
|
+
(15 s).
|
|
683
|
+
- **Shared state.** `{ type: "set", key, value, base }` on a joined channel:
|
|
684
|
+
last writer wins in the hub's arrival order, each write bumps the key's
|
|
685
|
+
version, everyone receives `{ key, value, version, by }`, and a writer
|
|
686
|
+
whose `base` was older is sent `conflict` with the write it replaced.
|
|
687
|
+
State is in memory and dropped with the channel after `idleMs` (5 min)
|
|
688
|
+
empty; persist what matters in the database.
|
|
689
|
+
- **Limits.** `maxMessageBytes` (16 KiB, closes 1009), `messagesPerSecond`
|
|
690
|
+
(20, burst 40, closes 1008), `maxChannels` (20 per connection),
|
|
691
|
+
`maxStateKeys` (100), and `maxBufferedBytes` (1 MiB): a slow consumer is
|
|
692
|
+
closed 1013 and resumes on reconnect instead of buffering without bound.
|
|
693
|
+
- **Runtimes.** Bun uses `Bun.serve`'s WebSockets (with its own
|
|
694
|
+
backpressure limit). Node ships only a WebSocket client, so `/node` is a
|
|
695
|
+
small RFC 6455 server over the `upgrade` event: text frames,
|
|
696
|
+
fragmentation, ping/pong, close, no compression. On Cloudflare the worker
|
|
697
|
+
authenticates and hands the socket to the org's Durable Object; each
|
|
698
|
+
instance holds one org. Bun and Node hubs live in one process: run one
|
|
699
|
+
instance; fan-out across instances (a pub/sub between hubs) is not
|
|
700
|
+
included.
|
|
701
|
+
|
|
702
|
+
The React side is signet-ui's `hooks/use-channel` and
|
|
703
|
+
`screens/realtime-screens`.
|
|
704
|
+
|
|
705
|
+
## Rich text sanitiser
|
|
706
|
+
|
|
707
|
+
`sanitizeMarkdown(text)` from `./http/sanitize` cleans rich text stored as
|
|
708
|
+
markdown (signet-ui's `RichTextEditor` value, comment bodies) before you save
|
|
709
|
+
it. The editor's own output is already clean, but anything can POST to your
|
|
710
|
+
route, and stored markdown may later meet a renderer that passes raw HTML
|
|
711
|
+
through.
|
|
712
|
+
|
|
713
|
+
```ts
|
|
714
|
+
import { sanitizeMarkdown } from "@dapplelight/signet-server/http/sanitize"
|
|
715
|
+
|
|
716
|
+
const body = z.object({ body: z.string().max(20_000).transform(sanitizeMarkdown) })
|
|
717
|
+
```
|
|
718
|
+
|
|
719
|
+
- Raw HTML outside code (`<script>`, `<img onerror>`, comments,
|
|
720
|
+
`<javascript:…>` autolinks) is escaped, so it shows as text.
|
|
721
|
+
- Link, image and reference targets that are not http(s), mailto, tel or
|
|
722
|
+
relative become `#`, judged after decoding entities and percent-encoding
|
|
723
|
+
and dropping the whitespace and control characters browsers ignore
|
|
724
|
+
(`javascript:`, `java\tscript:`, `javascript%3A`).
|
|
725
|
+
- Mention tokens (`@[Name](user:<id>)`) are kept; control characters and
|
|
726
|
+
bidirectional overrides are removed; code spans and fenced code blocks are
|
|
727
|
+
left as written. Running it twice changes nothing more.
|
|
728
|
+
- `isSafeLinkTarget(url)` is the link rule on its own.
|
|
729
|
+
|
|
730
|
+
## Public API: OpenAPI, docs, webhooks, caching
|
|
731
|
+
|
|
732
|
+
Three modules for an API other developers call: the spec and docs come from
|
|
733
|
+
the routes you already wrote, outbound webhooks run on signet-db's outbox,
|
|
734
|
+
and GET routes get correct cache headers.
|
|
735
|
+
|
|
736
|
+
### OpenAPI from the validators
|
|
737
|
+
|
|
738
|
+
`@dapplelight/signet-server/http/openapi` reads `app.routes` and the
|
|
739
|
+
`zValidator` schemas on them, and converts each with zod's own
|
|
740
|
+
`z.toJSONSchema` (zod 4.2+, already a peer). No second schema to keep in step.
|
|
741
|
+
|
|
742
|
+
```ts
|
|
743
|
+
import { apiDoc, serveOpenApi } from "@dapplelight/signet-server/http/openapi"
|
|
744
|
+
import { zValidator } from "@dapplelight/signet-server/http/validate"
|
|
745
|
+
|
|
746
|
+
app.get("/notes/:id", apiDoc({ summary: "Get a note", tags: ["Notes"], response: Note }), zValidator("param", Id), get)
|
|
747
|
+
app.post("/notes", apiDoc({ responses: { 201: { description: "Created", schema: Note } } }), zValidator("json", NoteInput), create)
|
|
748
|
+
app.get("/health", apiDoc({ security: false }), health) // public
|
|
749
|
+
app.post("/internal/sync", apiDoc(false), sync) // not in the spec
|
|
750
|
+
|
|
751
|
+
serveOpenApi(app, {
|
|
752
|
+
info: { title: "Notes API", version: "1.0.0" },
|
|
753
|
+
security: { session: { cookieName: "sid" }, apiKey: { prefix: "app" } },
|
|
754
|
+
})
|
|
755
|
+
// GET /openapi.json OpenAPI 3.1 GET /docs an HTML reference: no script, no dependency
|
|
756
|
+
```
|
|
757
|
+
|
|
758
|
+
| From | Becomes |
|
|
759
|
+
|---|---|
|
|
760
|
+
| `param`, `query`, `header`, `cookie` validators | parameters (a path parameter without one is a required string) |
|
|
761
|
+
| `json` / `form` validator | the request body (`application/json` / `multipart/form-data`), input side: defaults are optional |
|
|
762
|
+
| `apiDoc({ response })` | the 200 body, output side |
|
|
763
|
+
| any validator | a 400; auth on the route a 401; every route a `default`. All three are `#/components/responses/Error`, the envelope `errorHandler` writes |
|
|
764
|
+
| `security` | `sessionCookie` (apiKey in cookie) and `apiKey` (HTTP bearer, `./auth/api-keys`), either accepted on every route |
|
|
765
|
+
| `.describe()` on a schema or field | `summary` / `description` |
|
|
766
|
+
|
|
767
|
+
`openApiSpec(app, options)` returns the document without serving it, for a
|
|
768
|
+
build step or a client generator. The spec is built on the first request, so
|
|
769
|
+
routes added after `serveOpenApi` are in it. `apiDocsHtml(spec, { stylesheet })`
|
|
770
|
+
links the app's theme CSS so the page picks up Signet tokens. In React,
|
|
771
|
+
`ApiReference` from `@dapplelight/signet-ui/screens/api-screens` renders the
|
|
772
|
+
same document on Signet tokens.
|
|
773
|
+
|
|
774
|
+
### Outbound webhooks
|
|
775
|
+
|
|
776
|
+
Endpoints, secrets, the delivery log and retries live in signet-db
|
|
777
|
+
(`@dapplelight/signet-db/webhooks`, see its README). This package has the
|
|
778
|
+
admin routes, typed by shape so it does not depend on signet-db:
|
|
779
|
+
|
|
780
|
+
```ts
|
|
781
|
+
import { webhookRoutes } from "@dapplelight/signet-server/http/webhooks"
|
|
782
|
+
|
|
783
|
+
app.use("/api/webhooks/*", requireStoredSession(sessionOpts))
|
|
784
|
+
app.route("/api/webhooks", webhookRoutes({ webhooks, owner: (c) => c.get("session").payload.sub }))
|
|
785
|
+
```
|
|
786
|
+
|
|
787
|
+
`GET|POST /endpoints` (the POST answers 201 with the secret, once),
|
|
788
|
+
`PATCH|DELETE /endpoints/:id` (`{ enabled: true }` re-enables),
|
|
789
|
+
`POST /endpoints/:id/rotate-secret`, `GET /deliveries?endpointId&status&limit&before`
|
|
790
|
+
and `POST /deliveries/:id/redeliver`. Another owner's ids are 404; a private or
|
|
791
|
+
non-https url is 400 `VALIDATION_FAILED` on `url`; redelivering to a disabled
|
|
792
|
+
endpoint is 409. The routes carry `apiDoc` tags, so they document themselves.
|
|
793
|
+
`WebhookDeliveryLog` in `@dapplelight/signet-ui/screens/api-screens` is the screen.
|
|
794
|
+
|
|
795
|
+
Receivers verify with `verifyWebhook(secret, req.headers, rawBody)` from
|
|
796
|
+
`@dapplelight/signet-lib/webhooks` and dedupe on `webhook-id`.
|
|
797
|
+
|
|
798
|
+
### HTTP caching
|
|
799
|
+
|
|
800
|
+
`@dapplelight/signet-server/http/cache`:
|
|
801
|
+
|
|
802
|
+
```ts
|
|
803
|
+
import { cachedResponse, httpCache } from "@dapplelight/signet-server/http/cache"
|
|
804
|
+
|
|
805
|
+
app.get("/plans", httpCache({ maxAge: 300, staleWhileRevalidate: 60 }), listPlans)
|
|
806
|
+
app.get("/me/orders", requireStoredSession(sessionOpts), httpCache({ private: true }), myOrders)
|
|
807
|
+
app.get("/stats", (c) =>
|
|
808
|
+
cachedResponse(c, { kv, freshSeconds: 60, staleSeconds: 600, varyBy: orgId(c) }, async () => c.json(await buildStats())),
|
|
809
|
+
)
|
|
810
|
+
```
|
|
811
|
+
|
|
812
|
+
- `httpCache` on GET and HEAD 2xx: `Cache-Control` (default `public, no-cache`:
|
|
813
|
+
always revalidate, which the ETag makes cheap), an `ETag` from a SHA-256 of
|
|
814
|
+
the body, and a 304 for a matching `If-None-Match` (weak comparison) that
|
|
815
|
+
keeps `Cache-Control`, `Vary` and `ETag`. A handler's own `Cache-Control` or
|
|
816
|
+
`ETag` wins.
|
|
817
|
+
- Per-user responses: `private: true` sends `Cache-Control: private` (no CDN
|
|
818
|
+
stores it) and `Vary: Cookie, Authorization`; `mergeVary` adds more names
|
|
819
|
+
without duplicates.
|
|
820
|
+
- `cachedResponse` is stale-while-revalidate on any `KeyValue` (`memoryKv`,
|
|
821
|
+
`cloudflareKv`, `upstashKv`): fresh hits skip the handler, stale hits answer
|
|
822
|
+
at once while one background render refreshes the entry (`waitUntil` on
|
|
823
|
+
Workers), and `varyBy` (the user or org) is part of the key. Only 200s
|
|
824
|
+
without `Set-Cookie` are stored. `X-Cache` says `HIT`, `STALE` or `MISS`.
|
|
825
|
+
|
|
826
|
+
|
|
827
|
+
## Abuse: bot checks, disposable email, AI spend caps
|
|
828
|
+
|
|
829
|
+
Three guards for the routes bots and freeloaders aim at. Pair them with
|
|
830
|
+
`rateLimit` (see [Middleware](#middleware)) on the same routes: this kit
|
|
831
|
+
does not count requests itself.
|
|
832
|
+
|
|
833
|
+
### Bot checks
|
|
834
|
+
|
|
835
|
+
`@dapplelight/signet-server/abuse/captcha` verifies a Cloudflare Turnstile
|
|
836
|
+
or hCaptcha token with a plain `fetch` to the provider's siteverify
|
|
837
|
+
endpoint, and `requireCaptcha` refuses a route without a valid one.
|
|
838
|
+
|
|
839
|
+
```ts
|
|
840
|
+
import { captchaVerifier, requireCaptcha } from "@dapplelight/signet-server/abuse/captcha"
|
|
841
|
+
|
|
842
|
+
const captcha = (c) =>
|
|
843
|
+
env(c).APP_ENV === "local"
|
|
844
|
+
? captchaVerifier({ provider: "test" })
|
|
845
|
+
: captchaVerifier({ provider: "turnstile", secret: env(c).TURNSTILE_SECRET, hostname: "app.example.com" })
|
|
846
|
+
const bots = requireCaptcha({ verifier: captcha, trust: "cloudflare" })
|
|
847
|
+
app.use("/api/auth/sign-up/*", bots)
|
|
848
|
+
app.use("/api/auth/forget-password", bots)
|
|
849
|
+
```
|
|
850
|
+
|
|
851
|
+
The token is read from the `x-captcha-token` header, else the JSON or form
|
|
852
|
+
body field `captchaToken`, `cf-turnstile-response` or `h-captcha-response`
|
|
853
|
+
(from a clone, so Better Auth's handler still reads the body). Refusals use
|
|
854
|
+
the error envelope: 400 `CAPTCHA_REQUIRED` (no token), 403 `CAPTCHA_FAILED`
|
|
855
|
+
(refused, or the wrong `hostname` or Turnstile `action`), 503
|
|
856
|
+
`CAPTCHA_UNAVAILABLE` (the provider could not be reached: it fails closed).
|
|
857
|
+
|
|
858
|
+
Test mode (`provider: "test"`) passes `CAPTCHA_TEST_PASS` and refuses every
|
|
859
|
+
other token, with no network; it throws when `appEnv` is production or
|
|
860
|
+
staging. In the browser, `CaptchaWidget` from
|
|
861
|
+
`@dapplelight/signet-ui/screens/abuse-screens` loads the provider's script
|
|
862
|
+
and hands you the token; `provider="test"` reports the test token at once.
|
|
863
|
+
|
|
864
|
+
### Disposable email
|
|
865
|
+
|
|
866
|
+
`@dapplelight/signet-server/abuse/email` blocks sign-ups from throwaway
|
|
867
|
+
inboxes and gives you one key per inbox.
|
|
868
|
+
|
|
869
|
+
```ts
|
|
870
|
+
import { blockDisposableEmail, normalizeEmail } from "@dapplelight/signet-server/abuse/email"
|
|
871
|
+
|
|
872
|
+
app.use("/api/auth/sign-up/*", blockDisposableEmail({ add: ["burner.example"], allow: ["partner.example"] }))
|
|
873
|
+
// Store and look up normalizeEmail(email) to catch me+1@ and m.e@gmail.com as the same person.
|
|
874
|
+
```
|
|
875
|
+
|
|
876
|
+
A blocked address is 400 `DISPOSABLE_EMAIL` with `details.fieldErrors.email`.
|
|
877
|
+
A subdomain of a listed domain is blocked too; `allow` beats both the list
|
|
878
|
+
and `add`. `isDisposableEmail(email, { add, allow })` is the same check for
|
|
879
|
+
your own handler (build one `disposableEmailChecker(opts)` to reuse).
|
|
880
|
+
`normalizeEmail` lowercases, drops `+tag`, and for Gmail drops dots and
|
|
881
|
+
reads googlemail.com as gmail.com; send mail to what the person typed.
|
|
882
|
+
|
|
883
|
+
The bundled list (about 10,000 domains) comes from
|
|
884
|
+
[disposable-email-domains](https://github.com/disposable-email-domains/disposable-email-domains),
|
|
885
|
+
dedicated to the public domain (CC0). Refresh it with
|
|
886
|
+
`bun run scripts/disposable-domains.ts` in this package and commit the result.
|
|
887
|
+
|
|
888
|
+
### AI spend routes
|
|
889
|
+
|
|
890
|
+
`@dapplelight/signet-server/http/ai-spend` serves signet-db's
|
|
891
|
+
`createAiSpend` (see signet-db's AI spend caps), typed by shape.
|
|
892
|
+
|
|
893
|
+
```ts
|
|
894
|
+
import { aiSpendAdminRoutes, requireAiSpend } from "@dapplelight/signet-server/http/ai-spend"
|
|
895
|
+
|
|
896
|
+
app.use("/api/ai/*", requireAiSpend({ spend, subject: (c) => ({ userId: me(c), orgId: currentTenant(c).id }) }))
|
|
897
|
+
app.route("/api/admin/ai-spend", aiSpendAdminRoutes({
|
|
898
|
+
spend,
|
|
899
|
+
authorize: (c) => c.get("session")?.role === "admin", // deny by default: anything but true is 403
|
|
900
|
+
actor: (c) => ({ type: "user", id: me(c) }),
|
|
901
|
+
}))
|
|
902
|
+
```
|
|
903
|
+
|
|
904
|
+
Over a cap, `requireAiSpend` answers 429 `AI_SPEND_CAP_EXCEEDED` in the
|
|
905
|
+
envelope, with `details.formErrors` naming the cap (`user:day`,
|
|
906
|
+
`org:month`, `global:day`...) and `Retry-After` until the period rolls
|
|
907
|
+
over. A store error is 503 `AI_SPEND_UNAVAILABLE`: it fails closed.
|
|
908
|
+
|
|
909
|
+
| Route | What |
|
|
910
|
+
|---|---|
|
|
911
|
+
| `GET /usage` | Global spend and caps today and this month, and the top users and orgs this month. |
|
|
912
|
+
| `GET /usage/:scope/:id` | One user's or org's spend and caps (`global/*` for the app). |
|
|
913
|
+
| `GET /caps`, `PUT /caps` | Stored caps; `{ scope, subject?, period, units }` sets one (`units: null` is unlimited). |
|
|
914
|
+
| `DELETE /caps/:scope/:subject/:period` | Back to the `*` row or the app's default. |
|
|
915
|
+
|
|
916
|
+
`AiSpendAdmin` from `@dapplelight/signet-ui/screens/abuse-screens` is the
|
|
917
|
+
admin screen for these routes.
|
|
918
|
+
|
|
143
919
|
## Env — Workers-safe configuration
|
|
144
920
|
|
|
145
921
|
```ts
|
|
@@ -263,6 +1039,245 @@ built-in `memoryStore` is a fixed window, not a sliding one.
|
|
|
263
1039
|
429s use the same error envelope as everything else, so the client's `ApiError`
|
|
264
1040
|
path handles them without a special case.
|
|
265
1041
|
|
|
1042
|
+
## Portability adapters
|
|
1043
|
+
|
|
1044
|
+
Server pieces default to Cloudflare. These plugs let the same app run on
|
|
1045
|
+
Node/Bun (Docker included), Vercel, Upstash, Supabase and Netlify. Four interfaces in
|
|
1046
|
+
`@dapplelight/signet-server/adapters`: `KeyValue`, `Queue<T>`, `BlobStore` and
|
|
1047
|
+
`Defer`. No adapter adds a dependency (each is fetch or a structural binding
|
|
1048
|
+
type) and each takes its config as an argument, never from env at import.
|
|
1049
|
+
|
|
1050
|
+
| Import | Adapter | Runtime |
|
|
1051
|
+
|---|---|---|
|
|
1052
|
+
| `…/adapters` | `memoryKv`, `memoryQueue(handler)` | one process: tests, dev, a single container |
|
|
1053
|
+
| `…/adapters` | `processDefer()` | Node/Bun: run work after the response, errors caught |
|
|
1054
|
+
| `…/adapters` | `waitUntilDefer(ctx)` | Workers `ctx`, Netlify Functions `context`: anything with `waitUntil` |
|
|
1055
|
+
| `…/adapters` | `kvRateLimitStore(kv)` | any `KeyValue`; exact with `incr`, approximate without |
|
|
1056
|
+
| `…/adapters/node` | `fsBlobStore(dir)` | Node/Bun/Docker (mount a volume); rejects `..` and absolute keys |
|
|
1057
|
+
| `…/adapters/cloudflare` | `cloudflareKv(ns)`, `r2BlobStore(bucket)`, `cloudflareQueue(binding)` | Workers KV, R2, Queues producer |
|
|
1058
|
+
| `…/adapters/upstash` | `upstashKv`, `upstashRateLimitStore`, `qstashQueue` | anywhere fetch runs |
|
|
1059
|
+
| `…/adapters/supabase` | `supabaseBlobStore` | Supabase Storage, incl. signed GET and upload URLs and TUS resumable targets |
|
|
1060
|
+
| `…/adapters/vercel` | `vercelDefer(waitUntil)` | Vercel Functions: pass `waitUntil` from `@vercel/functions` |
|
|
1061
|
+
| `…/adapters/s3` | `s3BlobStore` | S3, R2's S3 API, MinIO: SigV4 presigned GET/PUT and multipart, fetch only |
|
|
1062
|
+
|
|
1063
|
+
```ts
|
|
1064
|
+
// Exact shared rate limiting off Cloudflare
|
|
1065
|
+
rateLimit({ store: (c) => upstashRateLimitStore({ url: c.env.UPSTASH_URL, token: c.env.UPSTASH_TOKEN }), trust: { forwardedHops: 1 } })
|
|
1066
|
+
```
|
|
1067
|
+
|
|
1068
|
+
A Cloudflare Queues binding can be passed as a `Queue<T>` as is;
|
|
1069
|
+
`cloudflareQueue(binding)` adds whole-second delays and a `sendBatch` split
|
|
1070
|
+
into Cloudflare's 100-message calls. `cloudflareConsumer` in `./jobs` is the
|
|
1071
|
+
receiving end.
|
|
1072
|
+
Workers KV has no atomic increment, so `kvRateLimitStore(cloudflareKv(ns))` is
|
|
1073
|
+
approximate; use the Durable Object store for an exact count there.
|
|
1074
|
+
`@dapplelight/signet-ai`'s `kvCache` and `kvBudgetStore` take any of these
|
|
1075
|
+
`KeyValue`s.
|
|
1076
|
+
|
|
1077
|
+
**On Vercel**, background work is `vercelDefer(waitUntil)` with `waitUntil`
|
|
1078
|
+
from [`@vercel/functions`](https://vercel.com/docs/functions/functions-api-reference/vercel-functions-package#waituntil)
|
|
1079
|
+
(Signet takes the function, so it does not depend on the package). Key-value
|
|
1080
|
+
and rate limiting are the Upstash adapters: [Vercel KV is now Upstash
|
|
1081
|
+
Redis](https://vercel.com/docs/redis) from the Marketplace, so pass the REST URL
|
|
1082
|
+
and token the integration adds to `upstashKv` / `upstashRateLimitStore`, and use
|
|
1083
|
+
`qstashQueue` for a queue. **No Vercel Blob adapter**: Vercel documents
|
|
1084
|
+
[Blob](https://vercel.com/docs/vercel-blob) only through its SDKs, not as an
|
|
1085
|
+
HTTP API, so there is nothing stable to call over fetch. Use `s3BlobStore`,
|
|
1086
|
+
`supabaseBlobStore`, or `@vercel/blob` directly.
|
|
1087
|
+
|
|
1088
|
+
**No Netlify Blobs adapter.** Netlify documents Blobs only through its
|
|
1089
|
+
`@netlify/blobs` SDK, not as an HTTP API, so there is nothing stable to call
|
|
1090
|
+
without that dependency. On Netlify, use Upstash or Supabase for storage, and
|
|
1091
|
+
`waitUntilDefer(context)` for background work.
|
|
1092
|
+
|
|
1093
|
+
## Jobs
|
|
1094
|
+
|
|
1095
|
+
`@dapplelight/signet-server/jobs`: background work over any `Queue` (Cloudflare
|
|
1096
|
+
Queues, QStash, `memoryQueue`). Typed input checked at enqueue, retries with
|
|
1097
|
+
backoff, a timeout that aborts `ctx.signal`, a dead-letter list, pause/resume,
|
|
1098
|
+
idempotent keys and cron schedules. No dependency: the store is any
|
|
1099
|
+
`KeyValue`, and zod is the peer you already have.
|
|
1100
|
+
|
|
1101
|
+
**Jobs or workflows?** Use signet-server `jobs` for quick fire-and-forget
|
|
1102
|
+
background tasks; use signet-db workflows for long-running, multi-step,
|
|
1103
|
+
crash-safe work or work that needs a person's approval.
|
|
1104
|
+
|
|
1105
|
+
- Job: `await sendReceipt.enqueue({ orderId })`
|
|
1106
|
+
- Workflow: `await wf.start(refund, { orderId })`, where `refund` calls `step.approval({ approvers: [managerId] })`
|
|
1107
|
+
|
|
1108
|
+
```ts
|
|
1109
|
+
const sendReceipt = defineJob({
|
|
1110
|
+
name: "send-receipt",
|
|
1111
|
+
input: z.object({ orderId: z.string() }),
|
|
1112
|
+
retry: { attempts: 5, backoff: "exponential", baseSeconds: 30 },
|
|
1113
|
+
timeoutSeconds: 20,
|
|
1114
|
+
run: async ({ orderId }, ctx) => mailer.receipt(orderId, { signal: ctx.signal }),
|
|
1115
|
+
})
|
|
1116
|
+
const nightly = defineSchedule({ name: "nightly", cron: "30 2 * * *", job: cleanup, input: {} })
|
|
1117
|
+
|
|
1118
|
+
// per request / per isolate, from env
|
|
1119
|
+
const jobs = createJobs({ jobs: [sendReceipt, cleanup], schedules: [nightly], queue, store })
|
|
1120
|
+
await sendReceipt.enqueue({ orderId }, { key: orderId }) // once per key
|
|
1121
|
+
```
|
|
1122
|
+
|
|
1123
|
+
- **Retries.** A failed run is re-sent with `attempt + 1` after
|
|
1124
|
+
`baseSeconds × 2^(attempt-1)` (or fixed), capped at 12 h. After the last
|
|
1125
|
+
attempt it goes to the dead-letter list with its input and error:
|
|
1126
|
+
`jobs.listDead()`, `jobs.retryDead(id)`. Default 3 attempts, 10 s base.
|
|
1127
|
+
- **Idempotency.** `enqueue(input, { key })` sends once per key for
|
|
1128
|
+
`keyTtlSeconds` (exact with a store that has `incr`). To dedupe the *run*
|
|
1129
|
+
in your database instead, pass
|
|
1130
|
+
`idempotency: (key, scope, fn) => withIdempotency(db, key, scope, fn)` from signet-db.
|
|
1131
|
+
- **Outbox.** Enqueue in the same write as the data change, then drain into the jobs queue:
|
|
1132
|
+
```ts
|
|
1133
|
+
const m = jobs.outboxMessage(sendReceipt, { orderId }) // validated now
|
|
1134
|
+
await db.batch([(tx) => tx.insert(orders).values(order), enqueue(db, m.topic, m.payload)])
|
|
1135
|
+
await drainOutbox(db, jobs.outboxQueue) // dedupes on the outbox row id
|
|
1136
|
+
```
|
|
1137
|
+
- **Schedules.** 5-field UTC cron (lists, ranges, steps; dom/dow either-matches
|
|
1138
|
+
like Vixie cron). `jobs.runDueSchedules(now)` enqueues each due schedule
|
|
1139
|
+
keyed by minute, so a double tick runs it once.
|
|
1140
|
+
- **Pause.** `jobs.pause(name)`: queued runs come back every `pausedDelaySeconds` until `resume`.
|
|
1141
|
+
- **`onJobRun`**: name, id, attempt, duration, ok, error code, actor
|
|
1142
|
+
(`{ type: "user" | "agent" | "system", id }`, same as signet-db's audit actor;
|
|
1143
|
+
pass `actor` at enqueue, default system).
|
|
1144
|
+
- **Agent tools.** `jobTools(jobs)` returns plain MCP tools: `list_failed_jobs`,
|
|
1145
|
+
`retry_job` (gated by `requireApproval`; `retryWithoutApproval` to skip),
|
|
1146
|
+
`pause_job`, `resume_job`.
|
|
1147
|
+
|
|
1148
|
+
- **Steps (durable workflows).** `run: async (input, { step }) => …` with
|
|
1149
|
+
`step.run(name, fn)` (result memoised in the store, so a retry resumes after
|
|
1150
|
+
the last finished step), `step.sleep(name, seconds)` (re-enqueues, any
|
|
1151
|
+
length), `step.waitFor(name, { event, timeoutSeconds })` (resumes on
|
|
1152
|
+
`jobs.emit(event, payload)`, null on timeout) and
|
|
1153
|
+
`step.waitForApproval(name, summary)` (resumes on `jobs.approve(id, step)`
|
|
1154
|
+
or the `decide_job_approval` agent tool, which asks the person via
|
|
1155
|
+
`requireApproval`). Step results replay as JSON.
|
|
1156
|
+
- **Concurrency and rate limits.** `concurrency: { key: (input) => input.accountId, limit: 1 }`
|
|
1157
|
+
and `rateLimit: { key, max, windowSeconds }` (any `RateLimitStore`). Over the
|
|
1158
|
+
limit the message is re-enqueued with a delay, never dropped. Every wake-up
|
|
1159
|
+
of a stepped job counts as a run.
|
|
1160
|
+
- **Events.** `jobs.on("user.signup", [welcome, crm])` (or `triggers`), then
|
|
1161
|
+
`jobs.emit("user.signup", payload)` starts each job and wakes runs waiting
|
|
1162
|
+
on that event. Through the outbox: `const e = jobs.outboxEvent(event, payload)`, then `enqueue(db, e.topic, e.payload)`.
|
|
1163
|
+
- **Progress and cancel.** `ctx.progress(done, total, note)`; `jobs.status(id)`
|
|
1164
|
+
returns state, attempt, progress and last error (`trackStatus: false` to
|
|
1165
|
+
skip the writes). `jobs.cancel(id)`: the run does not start, stops at its
|
|
1166
|
+
next step, and in this process `ctx.signal` aborts. `JobRuns` in
|
|
1167
|
+
`@dapplelight/signet-ui/domain/job-runs` renders these rows.
|
|
1168
|
+
- **AI budget.** `budget: { key: (i) => i.userId, limitUsd: 1, windowSeconds: 86_400 }`
|
|
1169
|
+
plus `budgetStore` (signet-ai's `kvBudgetStore` or `durableObjectBudgetStore`
|
|
1170
|
+
fit as-is). Spend comes from `ctx.recordCost(usd)` and shows in `onJobRun`
|
|
1171
|
+
as `costUsd`. Checked before the run and between steps: a run already
|
|
1172
|
+
under way can overshoot by its own spend. Exhausted: dead-lettered as
|
|
1173
|
+
`BUDGET_EXCEEDED`, never retried.
|
|
1174
|
+
- **Tests.** `createTestJobs({ jobs })` queues in memory with a virtual
|
|
1175
|
+
clock; `await jobs.runAll()` runs everything, retries, sleeps and timeouts
|
|
1176
|
+
included (`{ advanceTime: false }` runs only what is due now).
|
|
1177
|
+
|
|
1178
|
+
Delivery is at least once. Make `run` safe to repeat, or key it.
|
|
1179
|
+
|
|
1180
|
+
### Wiring: Cloudflare (Queues + KV + cron trigger)
|
|
1181
|
+
|
|
1182
|
+
```ts
|
|
1183
|
+
// wrangler: [[queues.producers]] binding = "JOBS"; [[queues.consumers]] queue = "jobs";
|
|
1184
|
+
// [triggers] crons = ["* * * * *"]
|
|
1185
|
+
const make = (env: Env) =>
|
|
1186
|
+
createJobs({ jobs: [sendReceipt, cleanup], schedules: [nightly], queue: env.JOBS, store: cloudflareKv(env.KV) })
|
|
1187
|
+
|
|
1188
|
+
export default {
|
|
1189
|
+
fetch: app.fetch,
|
|
1190
|
+
queue: (batch: MessageBatch, env: Env) => cloudflareConsumer(make(env))(batch),
|
|
1191
|
+
scheduled: (event: ScheduledEvent, env: Env, ctx: ExecutionContext) => cloudflareScheduled(make(env))(event, env, ctx),
|
|
1192
|
+
}
|
|
1193
|
+
```
|
|
1194
|
+
|
|
1195
|
+
### Wiring: Upstash (QStash + Redis), any fetch runtime
|
|
1196
|
+
|
|
1197
|
+
```ts
|
|
1198
|
+
const make = (env: Env) =>
|
|
1199
|
+
createJobs({
|
|
1200
|
+
jobs: [sendReceipt],
|
|
1201
|
+
queue: qstashQueue({ token: env.QSTASH_TOKEN, destinationUrl: "https://app.example/api/jobs" }),
|
|
1202
|
+
store: upstashKv({ url: env.UPSTASH_URL, token: env.UPSTASH_TOKEN }),
|
|
1203
|
+
})
|
|
1204
|
+
|
|
1205
|
+
app.post("/api/jobs", (c) =>
|
|
1206
|
+
qstashReceiver(make(c.env), {
|
|
1207
|
+
keys: { currentSigningKey: c.env.QSTASH_CURRENT_SIGNING_KEY, nextSigningKey: c.env.QSTASH_NEXT_SIGNING_KEY },
|
|
1208
|
+
url: "https://app.example/api/jobs", // what QStash signed, if a proxy rewrites request.url
|
|
1209
|
+
})(c.req.raw),
|
|
1210
|
+
)
|
|
1211
|
+
```
|
|
1212
|
+
|
|
1213
|
+
The receiver verifies `Upstash-Signature` (HS256 JWT, current or next key,
|
|
1214
|
+
issuer, expiry, body SHA-256) with Web Crypto and answers 401 on a bad one.
|
|
1215
|
+
|
|
1216
|
+
### Wiring: Docker / Node / Bun, one container
|
|
1217
|
+
|
|
1218
|
+
```ts
|
|
1219
|
+
const jobs = inProcessJobs({ jobs: [sendReceipt], schedules: [nightly], store: upstashKv(cfg) })
|
|
1220
|
+
const stop = startScheduler(jobs)
|
|
1221
|
+
process.on("SIGTERM", stop)
|
|
1222
|
+
```
|
|
1223
|
+
|
|
1224
|
+
`inProcessJobs` runs on `memoryQueue`: pending runs die with the process.
|
|
1225
|
+
For more than one container, use QStash as above, or `startWorker(jobs, { receive, ack })`
|
|
1226
|
+
over a queue you own.
|
|
1227
|
+
|
|
1228
|
+
## Storage
|
|
1229
|
+
|
|
1230
|
+
`@dapplelight/signet-server/storage`: uploads over any `BlobStore`, checked
|
|
1231
|
+
before they land. Size and type are validated before a signed PUT URL is
|
|
1232
|
+
issued; `confirmUpload` re-checks what actually arrived (a signed URL cannot
|
|
1233
|
+
enforce either) and deletes it if it fails. Stores that cannot presign
|
|
1234
|
+
(`fsBlobStore`, an R2 binding) throw `PRESIGN_UNSUPPORTED`: use
|
|
1235
|
+
`acceptUpload(ctx, request)`, which streams the body through the server, stops
|
|
1236
|
+
at `maxBytes`, and sniffs magic bytes (PNG, JPEG, GIF, WebP, PDF) so a renamed
|
|
1237
|
+
file is rejected.
|
|
1238
|
+
|
|
1239
|
+
```ts
|
|
1240
|
+
const uploads = createUploads({
|
|
1241
|
+
store: supabaseBlobStore({ url, serviceRoleKey, bucket: "avatars" }),
|
|
1242
|
+
maxBytes: 5_000_000,
|
|
1243
|
+
allowedTypes: ["image/png", "image/jpeg", "image/webp"],
|
|
1244
|
+
afterUpload: (u) => makeThumbnail.enqueue({ key: u.key }),
|
|
1245
|
+
})
|
|
1246
|
+
const { url: putUrl, key } = await uploads.presignUpload({ userId }, { name, type, size })
|
|
1247
|
+
// browser: fetch(putUrl, { method: "PUT", body: file, headers: { "Content-Type": type } })
|
|
1248
|
+
await uploads.confirmUpload({ userId }, key)
|
|
1249
|
+
```
|
|
1250
|
+
|
|
1251
|
+
- **Metadata.** `acceptUpload` strips EXIF/XMP/IPTC (GPS included) from
|
|
1252
|
+
JPEG, PNG and WebP by walking the container; pixels and colour profiles
|
|
1253
|
+
stay, and so does orientation: when the source has an Orientation tag, the
|
|
1254
|
+
EXIF block is rewritten to hold only that. After a direct upload, run
|
|
1255
|
+
`stripMetadata(bytes)` from a job.
|
|
1256
|
+
- **Quotas.** `quota: { bytes }` with a `kv` counts each user's bytes
|
|
1257
|
+
(confirm and accept add, `remove` releases), or pass `usage: (ctx) => …`
|
|
1258
|
+
to count from your own table. Checked before presign and accept: `QUOTA_EXCEEDED`.
|
|
1259
|
+
- **Abandoned uploads.** With a `kv`, presigned but unconfirmed keys are
|
|
1260
|
+
tracked; `abandonedUploadsJob(uploads)` on a schedule deletes those older
|
|
1261
|
+
than `abandonAfterHours` (default 24) and aborts unfinished multipart uploads.
|
|
1262
|
+
- **Dedupe.** `dedupe: true` stores identical content once at
|
|
1263
|
+
`sha256/<hash>`, reference-counted in `kv`; each user's key still resolves
|
|
1264
|
+
to it, and the bytes go when the last reference is removed.
|
|
1265
|
+
- **Resumable.** `startResumable(ctx, file)`: on `s3BlobStore` (S3, R2's S3
|
|
1266
|
+
API, MinIO) presigned multipart part URLs, then `completeMultipart`; on
|
|
1267
|
+
`supabaseBlobStore` a TUS target (`/upload/resumable/sign` with a signed
|
|
1268
|
+
token as `x-signature`, 6 MiB chunks), then `confirmUpload`.
|
|
1269
|
+
- **Resize.** `uploads.resize(ctx, key, { width })` writes `<key>@<width>w`
|
|
1270
|
+
through a `resizer`: `cloudflareImagesResizer(env.IMAGES)` on Workers; on
|
|
1271
|
+
Node, wrap the image library you already have (Signet adds none). Call it
|
|
1272
|
+
from a job enqueued in `afterUpload`.
|
|
1273
|
+
- **UI.** `@dapplelight/signet-ui/domain/upload` (`Upload`): drag and drop,
|
|
1274
|
+
per-file XHR progress to the presigned URL, retry, size and type hints.
|
|
1275
|
+
|
|
1276
|
+
Keys are `<userId>/<uuid>-<safe name>` by default and pass `assertBlobKey`;
|
|
1277
|
+
every method refuses a key outside the caller's prefix (`canAccess` to
|
|
1278
|
+
change that). Errors are `UploadError` with a `code` and the HTTP `status`
|
|
1279
|
+
to answer with (413 too large, 415 type, 403 not yours, 501 no presign).
|
|
1280
|
+
|
|
266
1281
|
## Logging
|
|
267
1282
|
|
|
268
1283
|
```ts
|
|
@@ -470,6 +1485,148 @@ c.executionCtx.waitUntil(sentry.captureException(err, { job: "sync" }))
|
|
|
470
1485
|
(`zerodha-sync`, `monthly-reports`). The pattern is trivial and the content is
|
|
471
1486
|
entirely product-specific, so there is nothing general to share.
|
|
472
1487
|
|
|
1488
|
+
## Notifications: templates, preferences, inbox, delivery tracking
|
|
1489
|
+
|
|
1490
|
+
```ts
|
|
1491
|
+
import { createNotifier, defineTemplates, kvNotifyStore, notifyJob } from "@dapplelight/signet-server/notify/notifier"
|
|
1492
|
+
import { resendSender, msg91Sms, twilioSms, whatsappSender, pushSender, smsSenderFor, devSender } from "@dapplelight/signet-server/notify/channels"
|
|
1493
|
+
import { resendWebhook, twilioWebhook, metaWebhook, unsubscribeRoute } from "@dapplelight/signet-server/notify/webhooks"
|
|
1494
|
+
import { notifyTools } from "@dapplelight/signet-server/notify/tools"
|
|
1495
|
+
```
|
|
1496
|
+
|
|
1497
|
+
One call, `notifier.notify(userId, "event.key", data, { channels?, priority?, idempotencyKey? })`,
|
|
1498
|
+
validates `data` against the template's zod schema, then for each channel the
|
|
1499
|
+
template has: checks preferences, suppression, WhatsApp opt-in, quiet hours and
|
|
1500
|
+
the per-user rate limit, renders the variant for the user's locale (English as
|
|
1501
|
+
the fallback), records a `queued` delivery and hands the send to `defer` (or a
|
|
1502
|
+
job). The request never waits on a provider. It returns what happened per
|
|
1503
|
+
channel: `queued`, or `skipped` with a reason (`PREFS`, `SUPPRESSED`,
|
|
1504
|
+
`NO_OPT_IN`, `QUIET_HOURS`, `RATE_LIMITED`, `NO_ADDRESS`, `NO_SENDER`, `DUPLICATE`).
|
|
1505
|
+
|
|
1506
|
+
```ts
|
|
1507
|
+
const templates = defineTemplates({
|
|
1508
|
+
"order.shipped": {
|
|
1509
|
+
category: "orders",
|
|
1510
|
+
data: z.object({ orderId: z.string(), url: z.string().url() }),
|
|
1511
|
+
en: {
|
|
1512
|
+
email: { subject: (d) => `Order ${d.orderId} shipped`, html: (d) => `<p>On its way.</p>`,
|
|
1513
|
+
action: { label: () => "Track", url: (d) => d.url } },
|
|
1514
|
+
sms: { text: (d) => `Order ${d.orderId} shipped`, dltTemplateId: "1107…", senderId: "ACMEIN",
|
|
1515
|
+
providerTemplateId: "msg91-flow-id", params: (d) => ({ order: d.orderId }) },
|
|
1516
|
+
whatsapp: { template: { name: "order_shipped", language: "en", params: (d) => [d.orderId] } },
|
|
1517
|
+
push: { title: () => "Shipped", body: (d) => `Order ${d.orderId}`, url: (d) => d.url },
|
|
1518
|
+
inApp: { title: () => "Shipped", body: (d) => `Order ${d.orderId}`, link: (d) => d.url },
|
|
1519
|
+
},
|
|
1520
|
+
locales: { hi: { inApp: { title: () => "भेज दिया", body: (d) => `ऑर्डर ${d.orderId}` } } },
|
|
1521
|
+
},
|
|
1522
|
+
})
|
|
1523
|
+
|
|
1524
|
+
const store = kvNotifyStore(kv)
|
|
1525
|
+
const notifier = createNotifier({
|
|
1526
|
+
templates, store,
|
|
1527
|
+
channels: { email: resendSender({ apiKey, from }), sms: msg91Sms({ authKey }),
|
|
1528
|
+
whatsapp: whatsappSender({ accessToken, phoneNumberId, apiVersion: "v23.0", isWindowOpen: store.isWindowOpen }) },
|
|
1529
|
+
recipients: async (userId) => db.contactFor(userId), // { email, phone, locale, timezone }
|
|
1530
|
+
defer: waitUntilDefer(c.executionCtx),
|
|
1531
|
+
secret: env.NOTIFY_SECRET, unsubscribeUrl: "https://api.example.com/unsubscribe",
|
|
1532
|
+
rateLimitStore: kvRateLimitStore(kv),
|
|
1533
|
+
})
|
|
1534
|
+
```
|
|
1535
|
+
|
|
1536
|
+
**Sending.** Without a job queue, sends run in `defer` with a few in-process
|
|
1537
|
+
retries. Register `notifyJob(notifier, z)` with `createJobs` and every send
|
|
1538
|
+
becomes a job instead: the jobs backoff, dead-letter list and restarts apply,
|
|
1539
|
+
and quiet hours delay the send instead of skipping it. Each delivery id is a
|
|
1540
|
+
hash of user, event, idempotency key and channel, so a repeated `notify` with
|
|
1541
|
+
the same key sends nothing, and `deliver` leaves a delivery that is past
|
|
1542
|
+
`queued` alone, so a redelivered job does not send twice. Resend also gets the
|
|
1543
|
+
id as its `Idempotency-Key`.
|
|
1544
|
+
|
|
1545
|
+
**Preferences** are per user × category × channel, absent meaning allowed.
|
|
1546
|
+
`security`, `otp` and `billing` are required (`required` option): they cannot be
|
|
1547
|
+
turned off, skip the rate limit and carry no unsubscribe link. Quiet hours
|
|
1548
|
+
(`{ start: "22:00", end: "08:00", timezone? }`, per user or a notifier default)
|
|
1549
|
+
are read in the user's zone, default Asia/Kolkata; `priority: "urgent"` bypasses
|
|
1550
|
+
them, and in-app messages ignore them.
|
|
1551
|
+
|
|
1552
|
+
**One-click unsubscribe.** Non-required email carries `List-Unsubscribe` and
|
|
1553
|
+
`List-Unsubscribe-Post: List-Unsubscribe=One-Click` (RFC 8058) with a signed
|
|
1554
|
+
token. Mount `unsubscribeRoute(notifier)` at `unsubscribeUrl`: the POST turns
|
|
1555
|
+
that category's email off; a GET only shows a confirm button, because mail
|
|
1556
|
+
scanners prefetch links.
|
|
1557
|
+
|
|
1558
|
+
**Email** is wrapped in a themed layout (`emailLayout`) whose colours are
|
|
1559
|
+
signet-tokens' editorial theme (`DEFAULT_EMAIL_THEME`; pass `emailTheme` for
|
|
1560
|
+
another). Plain text is derived from the HTML when a variant gives none.
|
|
1561
|
+
|
|
1562
|
+
**Inbox.** `notifier.inbox.list(userId, { cursor, limit, archived })`,
|
|
1563
|
+
`unreadCount`, `markRead(ids)`, `markAllRead`, `archive(id)`. Polling only.
|
|
1564
|
+
|
|
1565
|
+
**Delivery tracking.** Each send is a record (`queued`, `sent`, `delivered`,
|
|
1566
|
+
`opened`, `failed`, `bounced`, `skipped`) with a masked address and a reason
|
|
1567
|
+
code, never the body. Webhook handlers verify the provider's signature, then
|
|
1568
|
+
normalise events into `notifier.recordEvents`; a status never moves backwards.
|
|
1569
|
+
A hard bounce or complaint (Resend) or STOP (Twilio, WhatsApp) suppresses that
|
|
1570
|
+
address on that channel. Suppressions are keyed by a hash of the address.
|
|
1571
|
+
|
|
1572
|
+
**India.** SMS to `+91` is refused without `dltTemplateId` and `senderId` on
|
|
1573
|
+
the template (TRAI DLT), before any request is made. WhatsApp sends need
|
|
1574
|
+
`notifier.setOptIn(userId, "whatsapp", { source })` first. Free text goes only
|
|
1575
|
+
while the user's 24 h service window is open (inbound messages through
|
|
1576
|
+
`metaWebhook` open it); otherwise the approved template is sent.
|
|
1577
|
+
|
|
1578
|
+
**OTP.** `smsSenderFor(msg91Sms(...), { dltTemplateId, senderId, providerTemplateId, params })`
|
|
1579
|
+
is an auth `SmsSender`, so `requestPhoneOtp` sends through a real provider.
|
|
1580
|
+
|
|
1581
|
+
**Data export and erasure.** `notifier.exportUser(userId)` returns prefs,
|
|
1582
|
+
opt-ins, inbox and delivery history; `notifier.deleteUser(userId)` erases them.
|
|
1583
|
+
Call both next to signet-db's `exportUser` / `deleteUser`; server does not
|
|
1584
|
+
depend on db.
|
|
1585
|
+
|
|
1586
|
+
**Agent tools.** `notifyTools({ notifier, isStaff })`: `list_my_notifications`,
|
|
1587
|
+
`notification_prefs`, `update_prefs` for the signed-in user, and
|
|
1588
|
+
`send_notification` for staff only, through `requireApproval`.
|
|
1589
|
+
|
|
1590
|
+
**Safety.** `onEvent` gets ids, channels, statuses and reason codes; bodies and
|
|
1591
|
+
codes are never logged, and a queued body is deleted once sent (or expires).
|
|
1592
|
+
`devSender(channel)` prints messages locally and throws in production and
|
|
1593
|
+
staging. Provider errors are classified by status (4xx permanent except 408 and
|
|
1594
|
+
429) and their response bodies are dropped, since they can echo the message.
|
|
1595
|
+
|
|
1596
|
+
### Providers and their docs
|
|
1597
|
+
|
|
1598
|
+
| Channel | Sender | Docs |
|
|
1599
|
+
|---|---|---|
|
|
1600
|
+
| Email | `resendSender` | https://resend.com/docs/api-reference/emails/send-email |
|
|
1601
|
+
| Email | `postmarkSender` | https://postmarkapp.com/developer/api/email-api |
|
|
1602
|
+
| SMS | `twilioSms` | https://www.twilio.com/docs/messaging/api/message-resource |
|
|
1603
|
+
| SMS | `msg91Sms` | https://control.msg91.com/apidoc/textsms/send-sms-flow.php |
|
|
1604
|
+
| WhatsApp | `whatsappSender` | https://developers.facebook.com/documentation/business-messaging/whatsapp/messages/send-messages |
|
|
1605
|
+
| Push | `pushSender` | existing `webCryptoPushSender` (RFC 8291/8292) |
|
|
1606
|
+
| Telegram | `telegramSender` | https://core.telegram.org/bots/api#sendmessage |
|
|
1607
|
+
|
|
1608
|
+
| Webhook | Scheme | Docs |
|
|
1609
|
+
|---|---|---|
|
|
1610
|
+
| `resendWebhook` | Svix HMAC-SHA256, 5 min tolerance | https://docs.svix.com/receiving/verifying-payloads/how-manual |
|
|
1611
|
+
| `twilioWebhook` | `X-Twilio-Signature`, HMAC-SHA1 | https://www.twilio.com/docs/usage/security |
|
|
1612
|
+
| `metaWebhook` | `X-Hub-Signature-256`, HMAC-SHA256 | https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/create-webhook-endpoint |
|
|
1613
|
+
|
|
1614
|
+
### Not supported
|
|
1615
|
+
|
|
1616
|
+
- **AWS SES.** Needs SigV4 request signing and SNS message verification for its
|
|
1617
|
+
events; left out rather than half done.
|
|
1618
|
+
- **MSG91 delivery webhooks.** MSG91 documents no signature scheme, and an
|
|
1619
|
+
unverified status endpoint lets anyone mark messages delivered or suppress
|
|
1620
|
+
numbers. MSG91's newer docs also name the flow field `template_id` where the
|
|
1621
|
+
API reference says `flow_id`; this follows the reference.
|
|
1622
|
+
- **Postmark webhooks.** Postmark documents basic auth and IP ranges, not a
|
|
1623
|
+
signature.
|
|
1624
|
+
- **Twilio idempotency, Postmark idempotency.** Neither documents one, so a
|
|
1625
|
+
retry after a network timeout can send twice.
|
|
1626
|
+
- **A SQL store.** `NotifyStore` is an interface; only the KeyValue store ships.
|
|
1627
|
+
Its per-user lists are read-modify-write and capped (`maxItems`, default 200).
|
|
1628
|
+
- Campaigns, segments, digests and UI are out of scope.
|
|
1629
|
+
|
|
473
1630
|
## OAuth 2.1 resource server
|
|
474
1631
|
|
|
475
1632
|
For making a product **agent-reachable**: an MCP server, or any API an agent
|
|
@@ -642,7 +1799,7 @@ const prompts = [
|
|
|
642
1799
|
unexpected. `onError` hears the last case with `meta.kind` set to "resource"
|
|
643
1800
|
or "prompt". `errorResult` is for tools only.
|
|
644
1801
|
- The resources and prompts capabilities are declared only when there are
|
|
645
|
-
some, with `listChanged
|
|
1802
|
+
some, with `listChanged` as for tools.
|
|
646
1803
|
|
|
647
1804
|
**Confirm before a destructive action, and report progress.** Plain
|
|
648
1805
|
functions a handler calls with its `ToolContext` — no new registration shape:
|
|
@@ -708,6 +1865,246 @@ endpoint 2026-07-28 only (a 2025 client gets `-32022`), `responseMode: "sse"`
|
|
|
708
1865
|
always streams, and `maxRequestBodySize` / `keepAliveMs` / `onerror` are the
|
|
709
1866
|
SDK's.
|
|
710
1867
|
|
|
1868
|
+
### Apps inside agents
|
|
1869
|
+
|
|
1870
|
+
Everything below is opt-in and composes with the above.
|
|
1871
|
+
|
|
1872
|
+
**Per-user tools.** `tools`, `resources` and `prompts` take a function of the
|
|
1873
|
+
caller (`{ c, token }`), resolved per request. A function list advertises
|
|
1874
|
+
`listChanged: true`.
|
|
1875
|
+
|
|
1876
|
+
```ts
|
|
1877
|
+
mountMcp(app, "/mcp", {
|
|
1878
|
+
name, version, middleware: [requireToken({ verifier, resourceMetadataUrl })],
|
|
1879
|
+
tools: async ({ token }) => (await isAdmin(token!.claims.sub) ? [...base, ...admin] : base),
|
|
1880
|
+
})
|
|
1881
|
+
```
|
|
1882
|
+
|
|
1883
|
+
A tool left out of a caller's list is not callable by them either: the server
|
|
1884
|
+
is built from that list. For stdio, `serveStdio(() => resolveMcpServer({...}))`.
|
|
1885
|
+
|
|
1886
|
+
Or gate single tools with `visible(caller)`: their role, plan or feature. A
|
|
1887
|
+
hidden tool is neither listed nor callable. `resolveMcpServer` / `mcpHandler`
|
|
1888
|
+
check it per request; `createMcpServer` throws on a tool with `visible`,
|
|
1889
|
+
since it has no caller to check.
|
|
1890
|
+
|
|
1891
|
+
```ts
|
|
1892
|
+
const proOnly = ({ token }: McpCaller) => entitlements.can(token?.claims.sub ?? "", "export") // signet-db
|
|
1893
|
+
defineTool({ name: "export_all", visible: proOnly, ... })
|
|
1894
|
+
```
|
|
1895
|
+
|
|
1896
|
+
**list_changed.** Create one notifier at module scope and pass it as `changes`;
|
|
1897
|
+
call it when someone's tools change:
|
|
1898
|
+
|
|
1899
|
+
```ts
|
|
1900
|
+
const changes = createMcpChanges() // from /mcp/hono
|
|
1901
|
+
mountMcp(app, "/mcp", { name, version, tools: toolsFor, changes })
|
|
1902
|
+
changes.toolsChanged(userId) // that user's listen streams; no argument = everyone
|
|
1903
|
+
```
|
|
1904
|
+
|
|
1905
|
+
2026-07-28 clients hear `notifications/tools/list_changed` on their
|
|
1906
|
+
`subscriptions/listen` stream (the SDK serves it; streams are keyed by
|
|
1907
|
+
`principal`, default the token's `sub`). 2025-era clients over stateless HTTP
|
|
1908
|
+
have no stream and pick the change up on their next `tools/list`.
|
|
1909
|
+
`createMcpChanges` is in-process: where listen streams and publishers live in
|
|
1910
|
+
different isolates (Workers across POPs), implement `McpChanges` (four
|
|
1911
|
+
methods) over a Durable Object or Redis.
|
|
1912
|
+
|
|
1913
|
+
**Plain tool objects.** Any object shaped `{ name, description, inputSchema, run }`
|
|
1914
|
+
goes straight into `tools`, beside `defineTool`s. `inputSchema` is JSON Schema
|
|
1915
|
+
(validated by the SDK before `run`) or a zod object; `annotations`, `scopes`,
|
|
1916
|
+
`rateLimit`, `timeoutMs` and `outputSchema` work as on `defineTool`. This is
|
|
1917
|
+
the shape another package's `agentTools(...)` returns, so it plugs in with no glue:
|
|
1918
|
+
|
|
1919
|
+
```ts
|
|
1920
|
+
const add = {
|
|
1921
|
+
name: "add", description: "Add two numbers",
|
|
1922
|
+
inputSchema: { type: "object", properties: { a: { type: "number" }, b: { type: "number" } }, required: ["a", "b"] },
|
|
1923
|
+
run: ({ a, b }: { a: number; b: number }, ctx: ToolContext) => ({ sum: a + b }),
|
|
1924
|
+
}
|
|
1925
|
+
createMcpServer({ name, version, tools: [add, ...agentTools(db), getOrder] })
|
|
1926
|
+
```
|
|
1927
|
+
|
|
1928
|
+
**Routes as tools, automatically.** `appTools(app)` turns every route
|
|
1929
|
+
validated with `zValidator` into a tool. Call it after the routes are
|
|
1930
|
+
registered:
|
|
1931
|
+
|
|
1932
|
+
```ts
|
|
1933
|
+
const app = new Hono()
|
|
1934
|
+
.get("/api/notes", zValidator("query", z.object({ q: z.string().optional() }).describe("Search my notes")), list)
|
|
1935
|
+
.post("/api/notes", asTool({ description: "Save a note" }), zValidator("json", Note), save)
|
|
1936
|
+
.post("/api/webhook", asTool(false), zValidator("json", Event), hook) // never a tool
|
|
1937
|
+
.get("/api/me", asTool({ name: "whoami", description: "Who is signed in" }), me) // no validator: opt in
|
|
1938
|
+
mountMcp(app, "/mcp", { name, version, tools: appTools(app) })
|
|
1939
|
+
```
|
|
1940
|
+
|
|
1941
|
+
- **name**: `asTool({ name })`, else method + path (`get_api_notes_by_id`).
|
|
1942
|
+
- **description**: `asTool({ description })`, else the schema's `.describe()`, else `GET /api/notes/:id`.
|
|
1943
|
+
- **input**: the json, query and param `z.object`s, merged. A route whose
|
|
1944
|
+
validators are not all objects on those targets (a form, header or cookie
|
|
1945
|
+
validator), a GET or DELETE with a json validator (its arguments go in the
|
|
1946
|
+
query string), or with a path parameter no schema covers, is skipped: give
|
|
1947
|
+
it `asTool({ input })`.
|
|
1948
|
+
- **read vs write**: GET is `readOnlyHint` and runs. Every other method is a
|
|
1949
|
+
write and goes through `requireApproval` first (`asTool({ approval: false })`
|
|
1950
|
+
per route, `appTools(app, { approval: false })` for all).
|
|
1951
|
+
- `appTools(app, { optIn: true })` takes only routes marked `asTool(...)`.
|
|
1952
|
+
- `asTool` also takes `title`, `annotations`, `scopes`, `rateLimit`,
|
|
1953
|
+
`timeoutMs` and `visible`.
|
|
1954
|
+
|
|
1955
|
+
Each call runs the route in-process with the caller's `authorization` and
|
|
1956
|
+
`cookie`, so it runs as the signed-in user (session or API key) and sees only
|
|
1957
|
+
what the route would show them.
|
|
1958
|
+
|
|
1959
|
+
**Routes as tools, spelled out.** `routesAsTools` exposes the routes you list,
|
|
1960
|
+
calling each in-process with the caller's `authorization` and `cookie`, so
|
|
1961
|
+
the route's own auth and validation decide:
|
|
1962
|
+
|
|
1963
|
+
```ts
|
|
1964
|
+
const tools = routesAsTools(app, [
|
|
1965
|
+
{ name: "get_order", description: "Read an order", method: "GET", path: "/api/orders/:id",
|
|
1966
|
+
input: z.object({ id: z.string() }) },
|
|
1967
|
+
{ name: "refund_order", description: "Refund an order", method: "POST", path: "/api/orders/:id/refund",
|
|
1968
|
+
input: z.object({ id: z.string(), amount: z.number() }) },
|
|
1969
|
+
])
|
|
1970
|
+
```
|
|
1971
|
+
|
|
1972
|
+
Path parameters come from the input; the rest is the query string (GET,
|
|
1973
|
+
DELETE) or a JSON body (`query: ["dry"]` sends those in the query string for
|
|
1974
|
+
any method). The route's JSON is the result; a non-2xx is an error result with
|
|
1975
|
+
the envelope's `code`. GET defaults to `readOnlyHint`, PUT to
|
|
1976
|
+
`idempotentHint`, DELETE to `destructiveHint` + `idempotentHint`; `annotations`
|
|
1977
|
+
overrides. `approval: true` asks through `requireApproval` before the call.
|
|
1978
|
+
|
|
1979
|
+
**Approval for risky actions.** `requireApproval` is `confirm` shaped for a
|
|
1980
|
+
gate: undefined means approved, anything else is returned as-is.
|
|
1981
|
+
|
|
1982
|
+
```ts
|
|
1983
|
+
handler: async (input, ctx) => {
|
|
1984
|
+
const gate = await requireApproval(ctx, { summary: `Refund ${input.amount} to ${input.id}`,
|
|
1985
|
+
details: { order: input.id, amount: input.amount }, args: input })
|
|
1986
|
+
if (gate) return gate
|
|
1987
|
+
await refund(input.id, input.amount)
|
|
1988
|
+
return "Refunded."
|
|
1989
|
+
}
|
|
1990
|
+
```
|
|
1991
|
+
|
|
1992
|
+
With elicitation the person is asked (and with `confirm.key` the answer is
|
|
1993
|
+
bound to `args`). A no is `APPROVAL_DECLINED`. A client without elicitation
|
|
1994
|
+
gets `APPROVAL_REQUIRED` with `structuredContent.approval: { summary, details }`
|
|
1995
|
+
and nothing is done: the tool never acts on an approval it could not ask for.
|
|
1996
|
+
|
|
1997
|
+
It is the one approval step for every write tool: `appTools` writes,
|
|
1998
|
+
`authTools`, `jobTools`, and signet-db's and signet-payments' tool factories,
|
|
1999
|
+
which take it as `approve: approvalGate`.
|
|
2000
|
+
|
|
2001
|
+
**Approvals: pending, approve or deny, expiry, audit.** Most agents cannot
|
|
2002
|
+
ask the person mid-call. Give the server an approvals store and they get a
|
|
2003
|
+
pending record the person decides in the app, instead of a refusal:
|
|
2004
|
+
|
|
2005
|
+
```ts
|
|
2006
|
+
import { approvalGate, appTools, kvApprovals } from "@dapplelight/signet-server/mcp"
|
|
2007
|
+
import { approvalRoutes } from "@dapplelight/signet-server/http/routes"
|
|
2008
|
+
|
|
2009
|
+
const approvals = kvApprovals(kv, { // any KeyValue: memoryKv, Workers KV, Upstash
|
|
2010
|
+
ttlSeconds: 86_400, // how long it can be approved, then used (default a day)
|
|
2011
|
+
onEvent: ({ type, record }) => audit.write({ type, ...record }), // requested, approved, denied, used
|
|
2012
|
+
})
|
|
2013
|
+
mountMcp(app, "/mcp", {
|
|
2014
|
+
name, version, approvals,
|
|
2015
|
+
// Records belong to the principal: the token's `sub` behind oauth-rs
|
|
2016
|
+
// requireToken, or say who it is. With no principal there is no one to
|
|
2017
|
+
// decide a record, so anonymous calls get APPROVAL_REQUIRED instead.
|
|
2018
|
+
middleware: [requireStoredSession(sessions)],
|
|
2019
|
+
principal: ({ c }) => c?.get("session")?.payload.sub,
|
|
2020
|
+
tools: [...appTools(app), ...paymentTools(payments, { userId, approve: approvalGate })],
|
|
2021
|
+
})
|
|
2022
|
+
app.use("/api/approvals/*", requireStoredSession(sessions))
|
|
2023
|
+
app.route("/api/approvals", approvalRoutes({ approvals, subject: (c) => c.get("session").payload.sub }))
|
|
2024
|
+
```
|
|
2025
|
+
|
|
2026
|
+
1. The agent calls a write tool. A client that can ask still asks
|
|
2027
|
+
(elicitation), and the answer is recorded (`via: "elicitation"`).
|
|
2028
|
+
2. Otherwise the result is `APPROVAL_PENDING` with
|
|
2029
|
+
`structuredContent.approval: { id, summary, details, status, expiresAt }`,
|
|
2030
|
+
and nothing changed.
|
|
2031
|
+
3. The person sees it at `GET /api/approvals` and posts
|
|
2032
|
+
`/api/approvals/:id/approve` or `/deny`. They can only decide their own;
|
|
2033
|
+
another user's id is a 404, a decided or expired one a 409.
|
|
2034
|
+
4. The agent calls the same tool with the same arguments. Approved: it runs,
|
|
2035
|
+
once (the record becomes `used`). Denied: `APPROVAL_DECLINED`. Different
|
|
2036
|
+
arguments never match an approval: it is bound to the tool, the principal
|
|
2037
|
+
and a SHA-256 of the arguments.
|
|
2038
|
+
|
|
2039
|
+
Records past `expiresAt` read as `expired` and are kept `keepSeconds` (default
|
|
2040
|
+
7 days) for the person's history. `kvApprovals` is read-modify-write: two
|
|
2041
|
+
retries racing on one approval could both run on a store without
|
|
2042
|
+
transactions; implement `Approvals` over SQL for a strict once-only.
|
|
2043
|
+
|
|
2044
|
+
**Annotations.** `readOnlyHint`, `destructiveHint`, `idempotentHint` and
|
|
2045
|
+
`openWorldHint` are hints to the client, not enforcement. Set them honestly —
|
|
2046
|
+
clients use them to decide when to ask the person — and treat them as a floor:
|
|
2047
|
+
a `destructiveHint` tool that moves money or deletes data should still call
|
|
2048
|
+
`requireApproval`.
|
|
2049
|
+
|
|
2050
|
+
**Guardrails.** Per-tool rate limits (per principal, any `RateLimitStore`), a
|
|
2051
|
+
timeout, and one hook for every call:
|
|
2052
|
+
|
|
2053
|
+
```ts
|
|
2054
|
+
mountMcp(app, "/mcp", {
|
|
2055
|
+
name, version, tools,
|
|
2056
|
+
rateLimit: { store: upstashRateLimitStore(...) }, // default: per-isolate memory
|
|
2057
|
+
timeoutMs: 10_000, // a tool's own timeoutMs overrides
|
|
2058
|
+
onToolCall: ({ tool, principal, actor, durationMs, ok, code }) =>
|
|
2059
|
+
audit.write({ tool, principal, client: actor?.clientId, durationMs, ok, code }),
|
|
2060
|
+
})
|
|
2061
|
+
defineTool({ name: "send_invoice", rateLimit: { max: 5, windowSeconds: 3600 }, ... })
|
|
2062
|
+
```
|
|
2063
|
+
|
|
2064
|
+
Over the limit is `RATE_LIMITED`, a timeout is `TIMEOUT` (and `ctx.signal`
|
|
2065
|
+
aborts), and both reach `onToolCall` with their code. `actor` is the token's
|
|
2066
|
+
`client_id` (or `azp`) and RFC 8693 `act` claim: which agent acted for the user.
|
|
2067
|
+
`principal(caller)` sets the key when auth is not a bearer token.
|
|
2068
|
+
|
|
2069
|
+
**Calling another MCP server.** `@dapplelight/signet-server/mcp/client`,
|
|
2070
|
+
fetch only:
|
|
2071
|
+
|
|
2072
|
+
```ts
|
|
2073
|
+
import { createMcpClient } from "@dapplelight/signet-server/mcp/client"
|
|
2074
|
+
|
|
2075
|
+
const remote = createMcpClient({ url: "https://tools.example.com/mcp", token: () => getToken() })
|
|
2076
|
+
const tools = await remote.listTools()
|
|
2077
|
+
const r = await remote.callTool<{ total: number }>("get_report", { month: "2026-10" })
|
|
2078
|
+
if (!r.isError) r.structuredContent?.total
|
|
2079
|
+
```
|
|
2080
|
+
|
|
2081
|
+
It speaks 2025-11-25 by default (`era: "modern"` for a 2026-07-28-only
|
|
2082
|
+
server), throws `McpClientError` for JSON-RPC and HTTP failures, and returns
|
|
2083
|
+
`isError` results rather than throwing. It declares no capabilities, so it is
|
|
2084
|
+
never asked for input.
|
|
2085
|
+
|
|
2086
|
+
#### Notes for agents using this toolkit
|
|
2087
|
+
|
|
2088
|
+
- One module-scope tools array (or one `(caller) => tools` function) feeds HTTP
|
|
2089
|
+
and stdio. Do not build tools inside a handler.
|
|
2090
|
+
- Per-user means a function list; a static list is the same for everyone.
|
|
2091
|
+
- Anything that writes, spends or deletes: `destructiveHint: true` and
|
|
2092
|
+
`requireApproval`. Return the gate result unchanged.
|
|
2093
|
+
- Throw `ApiException(status, message, CODE)` for errors the model should see;
|
|
2094
|
+
anything else is `INTERNAL_ERROR` and goes to `onError`.
|
|
2095
|
+
- Prefer `appTools` / `routesAsTools` over re-implementing a route's logic in
|
|
2096
|
+
a tool: the route's auth stays the single check.
|
|
2097
|
+
- Give the server `approvals` so agents without elicitation get a pending
|
|
2098
|
+
approval instead of a refusal, and mount `approvalRoutes` for the person.
|
|
2099
|
+
- Plain tool objects need no import from this package; match `PlainTool`.
|
|
2100
|
+
- Never read env at module scope; take keys (`confirm.key`, stores) from `c.env`
|
|
2101
|
+
in a factory or from config.
|
|
2102
|
+
- Background work goes through `defineJob` (`./jobs`), not a bare `waitUntil`:
|
|
2103
|
+
it retries and lands in a dead-letter list. Give `jobTools(jobs)` to agents;
|
|
2104
|
+
`retry_job` asks for approval.
|
|
2105
|
+
- File uploads go through `createUploads` (`./storage`), never a raw
|
|
2106
|
+
`BlobStore.put` with a client-chosen key.
|
|
2107
|
+
|
|
711
2108
|
### stdio
|
|
712
2109
|
|
|
713
2110
|
app-a's server is stdio. The same tools, through the SDK's `serveStdio`, which
|
|
@@ -744,9 +2141,10 @@ session operations) get its 405, `server/discover` and the 2026 header checks
|
|
|
744
2141
|
are its own, and a 2026 POST without `Mcp-Method`, or with an `Mcp-Name` that
|
|
745
2142
|
disagrees with the body, is refused before a tool runs.
|
|
746
2143
|
|
|
747
|
-
|
|
748
|
-
2026 client opens no `subscriptions/listen` stream waiting for a change that
|
|
749
|
-
cannot come — and a Worker is not billed for holding one open.
|
|
2144
|
+
A static tool list is advertised as fixed (`tools: { listChanged: false }`), so
|
|
2145
|
+
a 2026 client opens no `subscriptions/listen` stream waiting for a change that
|
|
2146
|
+
cannot come — and a Worker is not billed for holding one open. A list given as
|
|
2147
|
+
a function advertises `listChanged: true` (see Apps inside agents).
|
|
750
2148
|
|
|
751
2149
|
**Response shape.** A 2026 request is answered with one JSON body unless a tool
|
|
752
2150
|
sends progress first (`responseMode: "auto"`). A 2025 request is answered as a
|