create-signet-app 0.9.2 → 0.9.4

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 CHANGED
@@ -266,16 +266,21 @@ files are written:
266
266
  | `--target` | Entry | Config | Rate limit store |
267
267
  |---|---|---|---|
268
268
  | `cloudflare` (default) | `src/index.ts` (Worker) | `wrangler.jsonc` | `RateLimitCounter` Durable Object: exact across all instances |
269
- | `bun` | `src/server.ts` (`Bun.serve`) | `Dockerfile` | in-process: exact for one process only |
270
- | `node` | `src/server.ts` (`node:http`) | `engines.node >= 22.18` | in-process: exact for one process only |
271
- | `vercel` | `index.ts` (default export) | `vercel.json` (Hono preset) | in-process: per function instance, so not exact |
272
-
273
- **Rate limits are not equivalent across targets.** An in-process store is safe
274
- for a single `bun` or `node` process. Run more than one instance (replicas,
275
- serverless, a load balancer) and each keeps its own count, so the real limit is
276
- the configured one times the number of instances. When the limit is an abuse or
277
- security control, use `cloudflare`, or pass a shared `store` (Redis; Vercel KV is
278
- [Upstash](https://vercel.com/docs/redis)) to `rateLimit`. Behind a proxy,
269
+ | `bun` | `src/server.ts` (`Bun.serve`) | `Dockerfile` | `memoryStore`: per process, swap in `upstashRateLimitStore` for more than one instance |
270
+ | `deno` | `src/server.ts` (`Deno.serve`) | `Dockerfile` | `memoryStore`: per process, swap in `upstashRateLimitStore` for more than one instance |
271
+ | `node` | `src/server.ts` (`node:http`) | `engines.node >= 22.18` | `memoryStore`: per process, swap in `upstashRateLimitStore` for more than one instance |
272
+ | `vercel` | `index.ts` (default export) | `vercel.json` (Hono preset) | `upstashRateLimitStore` (exact, shared) when `KV_REST_API_URL` and `KV_REST_API_TOKEN` are set; `memoryStore` (per instance) until then |
273
+
274
+ **Rate limits are not equivalent across targets.** The `memoryStore` that `bun`,
275
+ `deno` and `node` start with counts per process: right for a single process.
276
+ Run more than one instance (replicas, a load balancer) and each keeps its own
277
+ count, so the real limit is the configured one times the number of instances.
278
+ For that, pass `upstashRateLimitStore({ url, token })` from
279
+ `@dapplelight/signet-server/adapters/upstash` as the `store` in `src/server.ts`
280
+ (exact, shared, anywhere `fetch` runs), or use `cloudflare`. On `vercel` the
281
+ scaffold already does this: add Upstash Redis from the
282
+ [Vercel Marketplace](https://vercel.com/docs/redis), which sets the two env vars;
283
+ without them `index.ts` falls back to the per-instance `memoryStore`. Behind a proxy,
279
284
  the client IP is trusted only as far as you say: on `bun` and `node` set
280
285
  `TRUSTED_PROXY_HOPS` to the number of proxies in front, otherwise the socket
281
286
  address is used; on Vercel one forwarded hop is trusted.
@@ -286,8 +291,8 @@ from 22.18), so relative imports in the template carry `.ts`. It bridges
286
291
  `@hono/node-server`. `vercel` follows [Hono on
287
292
  Vercel](https://vercel.com/docs/frameworks/backend/hono); Vercel overwrites
288
293
  `x-forwarded-for` with the client IP, so one forwarded hop is trusted. On Vercel
289
- the in-memory count is per instance; share it through Redis (Vercel KV is
290
- [Upstash](https://vercel.com/docs/redis)) when it must be exact.
294
+ the count is shared through Upstash Redis once its env vars are set, and per
295
+ instance (`memoryStore`) until then.
291
296
 
292
297
  The `cloudflare` target is a Hono Worker with:
293
298
 
@@ -340,6 +345,15 @@ to check the envelope and that exactly 60 requests pass before a 429. `bun` and
340
345
  export fails it: wrangler refuses to bundle a Worker whose Durable Object is
341
346
  not exported.
342
347
 
348
+ The same `wrangler dev` run covers web push on Workers. The test adds one route
349
+ to its scaffolded copy (never to the template) that calls `webCryptoPushSender`
350
+ inside workerd, then checks the encrypted body against the RFC 8291 Appendix A
351
+ test vector and verifies the signature of the VAPID JWT. What it cannot check
352
+ is delivery to a real push service (FCM, Mozilla autopush, Apple). That is a
353
+ one-time manual check by the owner: subscribe a browser, send one notification
354
+ from a deployed Worker, see it arrive. The push-on-Workers goal can close
355
+ without it.
356
+
343
357
  ## Two bugs this fixes in the copied setup
344
358
 
345
359
  **`import.meta.env` did not typecheck.** The copied `tsconfig.app.json` omits
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-signet-app",
3
- "version": "0.9.2",
3
+ "version": "0.9.4",
4
4
  "license": "MIT",
5
5
  "description": "Scaffold a Vite + React + Tailwind app wired to Signet.",
6
6
  "keywords": [
@@ -7,8 +7,9 @@ import type { Services } from "../services.ts"
7
7
 
8
8
  /**
9
9
  * AI routes. app.ts refuses any /api/ai call once the caller's or the app's
10
- * spend cap is reached (requireAiSpend, 429 with Retry-After); each call is
11
- * charged to the caller through `spendKey`. Copy this one for your own.
10
+ * spend cap is reached (requireAiSpend, 429 with Retry-After); each call holds
11
+ * `maxCostUsd` against the caps while it runs, then is charged to the caller
12
+ * through `spendKey`. Copy this one for your own.
12
13
  *
13
14
  * POST /summary { text } → { summary, costUsd }
14
15
  */
@@ -21,7 +22,10 @@ export const aiRoutes = (s: Services) =>
21
22
  schema: z.object({ summary: z.string() }),
22
23
  instructions: "Summarise the text in one sentence.",
23
24
  input: c.req.valid("json").text,
24
- budget: { key: spendKey({ userId: c.get("user").id }) },
25
+ // maxCostUsd is held against the caps before the call runs, so calls
26
+ // fired at once cannot all pass a cap that has room for one. Set it to
27
+ // the most one call can cost; without it nothing is held.
28
+ budget: { key: spendKey({ userId: c.get("user").id }), maxCostUsd: 0.01 },
25
29
  })
26
30
  return c.json({ summary: value.summary, costUsd: meta.costUsd })
27
31
  },
@@ -29,6 +29,22 @@ test("over the caller's cap: 429 with Retry-After, and the route does not run",
29
29
  expect(Number(res.headers.get("retry-after"))).toBeGreaterThan(0)
30
30
  expect(((await res.json()) as { code: string }).code).toBe("AI_SPEND_CAP_EXCEEDED")
31
31
  })
32
+
33
+ test("20 parallel calls with room for one: at most one gets through", async () => {
34
+ const cookie = await signIn("+919000000045")
35
+ const id = await userId(cookie)
36
+ // 10,000 units is $0.01: room for one call's hold (route's maxCostUsd), no more.
37
+ db.orm
38
+ .insert(spendCaps)
39
+ .values({ id: `user:${id}:day`, scope: "user", subject: id, period: "day", units: 10_000 })
40
+ .run()
41
+ const res = await Promise.all(
42
+ Array.from({ length: 20 }, () => post("/api/ai/summary", { text: "Some text." }, cookie)),
43
+ )
44
+ const statuses = res.map((r) => r.status)
45
+ expect(statuses.filter((s) => s === 200).length).toBe(1)
46
+ expect(statuses.filter((s) => s === 429).length).toBe(19)
47
+ })
32
48
  // admin:begin
33
49
 
34
50
  test("admins read AI spend and set caps; everyone else gets 403", async () => {
@@ -1,10 +1,14 @@
1
+ import { ErrorState } from "@dapplelight/signet-ui/components/error-state"
2
+ import { Skeleton } from "@dapplelight/signet-ui/components/skeleton"
1
3
  import {
2
4
  NotificationInbox,
3
5
  NotificationPreferences,
4
6
  } from "@dapplelight/signet-ui/screens/notification-screens"
5
7
  import { useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query"
6
8
  import { createFileRoute, useNavigate } from "@tanstack/react-router"
7
- import { api } from "../../lib/api"
9
+ import type { ReactNode } from "react"
10
+ import { toast } from "sonner"
11
+ import { ApiError, api } from "../../lib/api"
8
12
 
9
13
  export const Route = createFileRoute("/_app/notifications")({
10
14
  component: Notifications,
@@ -16,6 +20,12 @@ const CATEGORIES = [
16
20
  { id: "billing", label: "Billing", description: "Plan changes and receipts", required: true }, // @payments
17
21
  ]
18
22
 
23
+ const SURFACE = "rounded-xl bg-bg-surface p-2 ring-1 ring-foreground/10"
24
+
25
+ /** Toast the ApiError's message, else the fallback. */
26
+ const fail = (e: unknown, fallback: string) =>
27
+ toast.error(e instanceof ApiError && e.message ? e.message : fallback)
28
+
19
29
  function Notifications() {
20
30
  const qc = useQueryClient()
21
31
  const navigate = useNavigate()
@@ -26,44 +36,102 @@ function Notifications() {
26
36
  (await api.notifications.$get({ query: pageParam ? { cursor: pageParam } : {} })).json(),
27
37
  getNextPageParam: (last) => last.nextCursor,
28
38
  })
29
- const prefs = useQuery({
39
+ const prefsQuery = useQuery({
30
40
  queryKey: ["notification-prefs"],
31
41
  queryFn: async () => (await api.notifications.prefs.$get()).json(),
32
- }).data
42
+ })
43
+ const prefs = prefsQuery.data
33
44
  const refresh = () => qc.invalidateQueries({ queryKey: ["notifications"] })
45
+ // Toast, then swallow: the inbox's inline line stays empty, so the user sees one message.
46
+ const act = async (fallback: string, run: () => Promise<unknown>) => {
47
+ try {
48
+ await run()
49
+ await refresh()
50
+ } catch (e) {
51
+ fail(e, fallback)
52
+ }
53
+ }
34
54
 
35
- return (
36
- <div className="space-y-10">
55
+ let inboxView: ReactNode
56
+ if (inbox.isPending) {
57
+ inboxView = (
58
+ <div
59
+ data-state="loading"
60
+ role="status"
61
+ aria-label="Loading notifications"
62
+ className={`flex flex-col gap-2 ${SURFACE}`}
63
+ >
64
+ {[0, 1, 2].map((i) => (
65
+ <Skeleton key={i} className="h-16" />
66
+ ))}
67
+ </div>
68
+ )
69
+ } else if (!inbox.data) {
70
+ // a failed refetch or load-more keeps the old data: only show the error when there is none
71
+ inboxView = (
72
+ <div data-state="error" className={SURFACE}>
73
+ <ErrorState message="Your notifications did not load." onRetry={() => inbox.refetch()} />
74
+ </div>
75
+ )
76
+ } else {
77
+ inboxView = (
37
78
  <NotificationInbox
38
- items={inbox.data?.pages.flatMap((p) => p.items) ?? []}
39
- unreadCount={inbox.data?.pages[0]?.unreadCount}
79
+ items={inbox.data.pages.flatMap((p) => p.items)}
80
+ unreadCount={inbox.data.pages[0]?.unreadCount}
40
81
  hasMore={inbox.hasNextPage}
41
- onLoadMore={() => inbox.fetchNextPage()}
42
- onMarkRead={async (ids) => {
43
- await api.notifications.read.$post({ json: { ids } })
44
- await refresh()
45
- }}
46
- onMarkAllRead={async () => {
47
- await api.notifications["read-all"].$post()
48
- await refresh()
49
- }}
50
- onArchive={async (item) => {
51
- await api.notifications[":id"].archive.$post({ param: { id: item.id } })
52
- await refresh()
82
+ onLoadMore={async () => {
83
+ try {
84
+ await inbox.fetchNextPage({ throwOnError: true })
85
+ } catch (e) {
86
+ fail(e, "Couldn't load more notifications.")
87
+ }
53
88
  }}
89
+ onMarkRead={(ids) =>
90
+ act("Couldn't mark as read.", () => api.notifications.read.$post({ json: { ids } }))
91
+ }
92
+ onMarkAllRead={() =>
93
+ act("Couldn't mark all as read.", () => api.notifications["read-all"].$post())
94
+ }
95
+ onArchive={(item) =>
96
+ act("Couldn't archive that notification.", () =>
97
+ api.notifications[":id"].archive.$post({ param: { id: item.id } }),
98
+ )
99
+ }
54
100
  onOpen={(item) => {
55
101
  if (item.link) navigate({ to: item.link })
56
102
  }}
57
103
  />
58
- {prefs ? (
104
+ )
105
+ }
106
+
107
+ return (
108
+ <div className="space-y-10" aria-busy={inbox.isPending || prefsQuery.isPending || undefined}>
109
+ {inboxView}
110
+ {prefsQuery.isPending ? (
111
+ <div data-state="loading" role="status" aria-label="Loading notification settings">
112
+ <Skeleton className="h-40" />
113
+ </div>
114
+ ) : prefsQuery.isError && !prefs ? (
115
+ <div data-state="error" className={SURFACE}>
116
+ <ErrorState
117
+ message="Your notification settings did not load."
118
+ onRetry={() => prefsQuery.refetch()}
119
+ />
120
+ </div>
121
+ ) : prefs ? (
59
122
  <NotificationPreferences
60
123
  categories={CATEGORIES}
61
124
  channels={["inApp", "email", "sms"]}
62
125
  defaultValue={prefs.channels}
63
126
  onToggle={async ({ category, channel, on }) => {
64
- await api.notifications.prefs.$put({
65
- json: { channels: { [category]: { [channel]: on } } },
66
- })
127
+ try {
128
+ await api.notifications.prefs.$put({
129
+ json: { channels: { [category]: { [channel]: on } } },
130
+ })
131
+ } catch (e) {
132
+ fail(e, "Couldn't save that setting.")
133
+ throw e // rethrow: the switch flips back
134
+ }
67
135
  }}
68
136
  />
69
137
  ) : null}
package/src/index.ts CHANGED
@@ -239,20 +239,27 @@ const API_TARGETS: Record<
239
239
  // Runs src/server.ts as is: type stripping is on by default from 22.18.
240
240
  engines: { node: ">=22.18" },
241
241
  },
242
- vercel: { scripts: { dev: "bunx vercel dev", deploy: "bunx vercel deploy" } },
242
+ vercel: {
243
+ scripts: { dev: "bunx vercel dev", deploy: "bunx vercel deploy" },
244
+ devDeps: { "@types/node": "^26.6.6" },
245
+ },
243
246
  }
244
247
 
245
248
  const API_NEXT_STEPS: Record<Target, string> = {
246
249
  cloudflare: `Rate limiting is exact and per IP, backed by the RateLimitCounter Durable
247
250
  Object in wrangler.jsonc. Append migration tags; never edit a deployed one.`,
248
251
  bun: `bun run start serves src/server.ts under Bun.serve; the Dockerfile runs the same.
249
- Rate limiting is in-process and keyed by the socket address.`,
252
+ Rate limiting is in-process and keyed by the socket address; per process, so for
253
+ more than one instance pass upstashRateLimitStore (see the comment in src/server.ts).`,
250
254
  deno: `bun run start serves src/server.ts under Deno.serve (Deno 2); the Dockerfile runs the same.
251
- Rate limiting is in-process and keyed by the socket address.`,
255
+ Rate limiting is in-process and keyed by the socket address; per process, so for
256
+ more than one instance pass upstashRateLimitStore (see the comment in src/server.ts).`,
252
257
  node: `bun run start runs src/server.ts with node 22.18+ (node:http, no extra dependency).
253
- Rate limiting is in-process and keyed by the socket address.`,
258
+ Rate limiting is in-process and keyed by the socket address; per process, so for
259
+ more than one instance pass upstashRateLimitStore (see the comment in src/server.ts).`,
254
260
  vercel: `index.ts is the Vercel entry (Hono preset, vercel.json). Deploy with bun run deploy.
255
- Rate limiting is per function instance; see the comment in index.ts.`,
261
+ Rate limiting is shared through Upstash Redis once KV_REST_API_URL and KV_REST_API_TOKEN
262
+ are set (Vercel Marketplace); until then it is per function instance. See index.ts.`,
256
263
  }
257
264
 
258
265
  const DEPS = {
@@ -7,8 +7,8 @@ import { createApp } from "./app.ts"
7
7
  const hops = process.env.TRUSTED_PROXY_HOPS
8
8
 
9
9
  const app = createApp<Record<string, never>>({
10
- // One process, so an in-memory count is exact. Running several replicas?
11
- // Share the count: upstashRateLimitStore from @dapplelight/signet-server/adapters/upstash.
10
+ // The memory store counts per process, so with more than one instance each keeps
11
+ // its own count. Swap in upstashRateLimitStore from @dapplelight/signet-server/adapters/upstash.
12
12
  store: memoryStore(),
13
13
  // Behind proxies of your own (a load balancer, a PaaS router), set
14
14
  // TRUSTED_PROXY_HOPS to how many, and the client IP comes from
@@ -18,8 +18,8 @@ declare const Deno: {
18
18
  const hops = Deno.env.get("TRUSTED_PROXY_HOPS")
19
19
 
20
20
  const app = createApp<Record<string, never>>({
21
- // One process, so an in-memory count is exact. Running several replicas?
22
- // Share the count: upstashRateLimitStore from @dapplelight/signet-server/adapters/upstash.
21
+ // The memory store counts per process, so with more than one instance each keeps
22
+ // its own count. Swap in upstashRateLimitStore from @dapplelight/signet-server/adapters/upstash.
23
23
  store: memoryStore(),
24
24
  // Behind proxies of your own (a load balancer, a PaaS router), set
25
25
  // TRUSTED_PROXY_HOPS to how many, and the client IP comes from
@@ -10,8 +10,8 @@ import { createApp } from "./app.ts"
10
10
  const hops = process.env.TRUSTED_PROXY_HOPS
11
11
 
12
12
  const app = createApp<Record<string, never>>({
13
- // One process, so an in-memory count is exact. Running several replicas?
14
- // Share the count with a store backed by Redis or a Durable Object.
13
+ // The memory store counts per process, so with more than one instance each keeps
14
+ // its own count. Swap in upstashRateLimitStore from @dapplelight/signet-server/adapters/upstash.
15
15
  store: memoryStore(),
16
16
  // Behind proxies of your own, set TRUSTED_PROXY_HOPS to how many and the
17
17
  // client IP comes from x-forwarded-for. Otherwise the header is replaced
@@ -1,14 +1,25 @@
1
+ /// <reference types="node" />
1
2
  // Vercel entry. Vercel deploys a Hono app with zero configuration from the
2
3
  // default export of a root index.ts (vercel.json pins the "hono" preset).
3
4
  // https://vercel.com/docs/frameworks/backend/hono
5
+ import { upstashRateLimitStore } from "@dapplelight/signet-server/adapters/upstash"
4
6
  import { memoryStore } from "@dapplelight/signet-server/middleware/rate-limit"
5
7
  import { createApp } from "./src/app.ts"
6
8
 
9
+ const local = memoryStore()
10
+ let shared: ReturnType<typeof upstashRateLimitStore> | undefined
11
+
7
12
  export default createApp<Record<string, never>>({
8
- // Per function instance, so the count is approximate once Vercel runs
9
- // several. For an exact, shared count use a Redis-backed store: Vercel KV is
10
- // Upstash Redis from the Marketplace (https://vercel.com/docs/redis).
11
- store: memoryStore(),
13
+ // Shared across all function instances through Upstash Redis (the Vercel
14
+ // Marketplace sets KV_REST_API_URL and KV_REST_API_TOKEN). Without them this
15
+ // falls back to memoryStore, which counts per instance, so set them before
16
+ // relying on the limit. Read per request: env is not safe at module scope.
17
+ store: () => {
18
+ const url = process.env.KV_REST_API_URL ?? process.env.UPSTASH_REDIS_REST_URL
19
+ const token = process.env.KV_REST_API_TOKEN ?? process.env.UPSTASH_REDIS_REST_TOKEN
20
+ if (!url || !token) return local
21
+ return (shared ??= upstashRateLimitStore({ url, token }))
22
+ },
12
23
  // Vercel overwrites x-forwarded-for with the client's IP and never forwards
13
24
  // one a client sent (https://vercel.com/docs/headers/request-headers#x-forwarded-for),
14
25
  // so the single address in it is the one to trust.
@@ -20,7 +20,7 @@ type AppEnv<B> = { Bindings: B; Variables: { reqId: string } }
20
20
  * passes its own store and key.
21
21
  */
22
22
  export function createApp<B extends Record<string, unknown>>(
23
- limit: Pick<RateLimitOptions<AppEnv<B>>, "store" | "trust" | "keyFor">,
23
+ limit: Pick<RateLimitOptions<AppEnv<B>>, "store" | "trust" | "keyFor" | "onNoIp">,
24
24
  ) {
25
25
  const app = new Hono<AppEnv<B>>()
26
26
  // Bindings arrive per request on Workers. Hand them over first, then read
@@ -38,6 +38,7 @@ export function createApp<B extends Record<string, unknown>>(
38
38
  // env key: csrfMiddleware({ originEnvKeys: ["WEB_URL"] }), the same keys you
39
39
  // give corsMiddleware.
40
40
  .use("/api/*", csrfMiddleware())
41
+ // Smoothing only, not a security control: an in-memory store counts per process or isolate. Use a durable store for login or other limits that must hold.
41
42
  .use("/api/*", rateLimit<AppEnv<B>>({ ...limit, max: 60 }))
42
43
  .get("/api/health", (c) => c.json({ ok: true }))
43
44
  // mcp:begin
@@ -0,0 +1,23 @@
1
+ import { expect, test } from "bun:test"
2
+ import { memoryStore } from "@dapplelight/signet-server/middleware/rate-limit"
3
+ import { createApp } from "../src/app.ts"
4
+
5
+ // Requests that reach the app without cf-connecting-ip (a proxy that strips it,
6
+ // a health checker, a local call) all share one bucket. Once it is full, the
7
+ // next caller without the header is told to back off, whoever they are; callers
8
+ // with an address are untouched. onNoIp: "reject" or "allow" on rateLimit
9
+ // changes this.
10
+ test("60 requests without cf-connecting-ip fill the shared bucket; a bystander without it gets 429", async () => {
11
+ const app = createApp({ store: memoryStore(), trust: "cloudflare" })
12
+ for (let i = 0; i < 60; i++) expect((await app.request("/api/health")).status).toBe(200)
13
+ expect((await app.request("/api/health")).status).toBe(429)
14
+ const withIp = await app.request("/api/health", { headers: { "cf-connecting-ip": "203.0.113.9" } })
15
+ expect(withIp.status).toBe(200)
16
+ })
17
+
18
+ test("onNoIp: reject answers 400 instead of filling the shared bucket", async () => {
19
+ const app = createApp({ store: memoryStore(), trust: "cloudflare", onNoIp: "reject" })
20
+ for (let i = 0; i < 61; i++) expect((await app.request("/api/health")).status).toBe(400)
21
+ const withIp = await app.request("/api/health", { headers: { "cf-connecting-ip": "203.0.113.9" } })
22
+ expect(withIp.status).toBe(200)
23
+ })
@@ -1,4 +1,5 @@
1
1
  {
2
+ "$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
2
3
  "vcs": {
3
4
  "enabled": true,
4
5
  "clientKind": "git",