@lastshotlabs/bunshot 0.0.21 → 0.0.25

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.
Files changed (122) hide show
  1. package/README.md +3035 -1249
  2. package/dist/adapters/localStorage.d.ts +6 -0
  3. package/dist/adapters/localStorage.js +44 -0
  4. package/dist/adapters/memoryAuth.d.ts +7 -0
  5. package/dist/adapters/memoryAuth.js +144 -0
  6. package/dist/adapters/memoryStorage.d.ts +3 -0
  7. package/dist/adapters/memoryStorage.js +44 -0
  8. package/dist/adapters/mongoAuth.js +120 -0
  9. package/dist/adapters/s3Storage.d.ts +14 -0
  10. package/dist/adapters/s3Storage.js +126 -0
  11. package/dist/adapters/sqliteAuth.d.ts +7 -0
  12. package/dist/adapters/sqliteAuth.js +199 -0
  13. package/dist/app.d.ts +100 -3
  14. package/dist/app.js +247 -46
  15. package/dist/cli.js +118 -38
  16. package/dist/index.d.ts +49 -7
  17. package/dist/index.js +35 -5
  18. package/dist/lib/HttpError.d.ts +5 -0
  19. package/dist/lib/HttpError.js +7 -0
  20. package/dist/lib/appConfig.d.ts +44 -0
  21. package/dist/lib/appConfig.js +16 -0
  22. package/dist/lib/auditLog.d.ts +52 -0
  23. package/dist/lib/auditLog.js +201 -0
  24. package/dist/lib/authAdapter.d.ts +69 -0
  25. package/dist/lib/constants.d.ts +4 -0
  26. package/dist/lib/constants.js +4 -0
  27. package/dist/lib/context.d.ts +19 -1
  28. package/dist/lib/context.js +17 -3
  29. package/dist/lib/createRoute.d.ts +28 -2
  30. package/dist/lib/createRoute.js +54 -3
  31. package/dist/lib/deletionCancelToken.d.ts +12 -0
  32. package/dist/lib/deletionCancelToken.js +88 -0
  33. package/dist/lib/groups.d.ts +113 -0
  34. package/dist/lib/groups.js +133 -0
  35. package/dist/lib/idempotency.d.ts +22 -0
  36. package/dist/lib/idempotency.js +182 -0
  37. package/dist/lib/metrics.d.ts +14 -0
  38. package/dist/lib/metrics.js +158 -0
  39. package/dist/lib/pagination.d.ts +119 -0
  40. package/dist/lib/pagination.js +166 -0
  41. package/dist/lib/session.d.ts +4 -0
  42. package/dist/lib/session.js +56 -2
  43. package/dist/lib/signing.d.ts +52 -0
  44. package/dist/lib/signing.js +180 -0
  45. package/dist/lib/storageAdapter.d.ts +30 -0
  46. package/dist/lib/storageAdapter.js +1 -0
  47. package/dist/lib/stripUnreferencedSchemas.d.ts +11 -0
  48. package/dist/lib/stripUnreferencedSchemas.js +79 -0
  49. package/dist/lib/tenant.js +2 -2
  50. package/dist/lib/upload.d.ts +35 -0
  51. package/dist/lib/upload.js +87 -0
  52. package/dist/lib/validate.js +2 -2
  53. package/dist/lib/ws.d.ts +1 -0
  54. package/dist/lib/ws.js +21 -0
  55. package/dist/lib/wsHeartbeat.d.ts +12 -0
  56. package/dist/lib/wsHeartbeat.js +57 -0
  57. package/dist/lib/wsMessages.d.ts +40 -0
  58. package/dist/lib/wsMessages.js +330 -0
  59. package/dist/lib/wsPresence.d.ts +25 -0
  60. package/dist/lib/wsPresence.js +99 -0
  61. package/dist/middleware/auditLog.d.ts +22 -0
  62. package/dist/middleware/auditLog.js +39 -0
  63. package/dist/middleware/cacheResponse.js +5 -1
  64. package/dist/middleware/csrf.js +10 -0
  65. package/dist/middleware/identify.js +57 -9
  66. package/dist/middleware/metrics.d.ts +9 -0
  67. package/dist/middleware/metrics.js +26 -0
  68. package/dist/middleware/requestId.d.ts +3 -0
  69. package/dist/middleware/requestId.js +7 -0
  70. package/dist/middleware/requestLogger.d.ts +38 -0
  71. package/dist/middleware/requestLogger.js +68 -0
  72. package/dist/middleware/requestSigning.d.ts +20 -0
  73. package/dist/middleware/requestSigning.js +99 -0
  74. package/dist/middleware/requireMfaSetup.d.ts +16 -0
  75. package/dist/middleware/requireMfaSetup.js +36 -0
  76. package/dist/middleware/requireRole.d.ts +9 -3
  77. package/dist/middleware/requireRole.js +23 -36
  78. package/dist/middleware/upload.d.ts +5 -0
  79. package/dist/middleware/upload.js +27 -0
  80. package/dist/middleware/webhookAuth.d.ts +30 -0
  81. package/dist/middleware/webhookAuth.js +57 -0
  82. package/dist/models/AuditLog.d.ts +30 -0
  83. package/dist/models/AuditLog.js +39 -0
  84. package/dist/models/Group.d.ts +21 -0
  85. package/dist/models/Group.js +28 -0
  86. package/dist/models/GroupMembership.d.ts +21 -0
  87. package/dist/models/GroupMembership.js +25 -0
  88. package/dist/routes/auth.js +84 -6
  89. package/dist/routes/groups.d.ts +21 -0
  90. package/dist/routes/groups.js +346 -0
  91. package/dist/routes/jobs.js +47 -45
  92. package/dist/routes/metrics.d.ts +7 -0
  93. package/dist/routes/metrics.js +52 -0
  94. package/dist/routes/mfa.js +4 -0
  95. package/dist/routes/uploads.d.ts +2 -0
  96. package/dist/routes/uploads.js +135 -0
  97. package/dist/server.d.ts +26 -0
  98. package/dist/server.js +46 -3
  99. package/dist/ws/index.js +3 -0
  100. package/docs/sections/auth-flow/full.md +779 -634
  101. package/docs/sections/auth-flow/overview.md +2 -2
  102. package/docs/sections/auth-security-examples/full.md +365 -0
  103. package/docs/sections/authentication/full.md +130 -0
  104. package/docs/sections/authentication/overview.md +5 -0
  105. package/docs/sections/cli/full.md +13 -1
  106. package/docs/sections/configuration/full.md +17 -0
  107. package/docs/sections/configuration/overview.md +1 -0
  108. package/docs/sections/exports/full.md +34 -3
  109. package/docs/sections/logging/full.md +83 -0
  110. package/docs/sections/metrics/full.md +127 -0
  111. package/docs/sections/oauth/full.md +189 -189
  112. package/docs/sections/oauth/overview.md +1 -1
  113. package/docs/sections/pagination/full.md +93 -0
  114. package/docs/sections/roles/full.md +224 -135
  115. package/docs/sections/roles/overview.md +3 -1
  116. package/docs/sections/signing/full.md +203 -0
  117. package/docs/sections/uploads/full.md +199 -0
  118. package/docs/sections/versioning/full.md +85 -0
  119. package/docs/sections/webhook-auth/full.md +100 -0
  120. package/docs/sections/websocket/full.md +83 -0
  121. package/docs/sections/websocket-rooms/full.md +6 -1
  122. package/package.json +16 -4
@@ -0,0 +1,199 @@
1
+ ## File Uploads
2
+
3
+ Bunshot provides opt-in file upload handling with pluggable storage adapters (memory, local filesystem, S3/R2), server-side multipart parsing, and optional presigned URL generation for direct client-to-storage uploads.
4
+
5
+ ### Configuration
6
+
7
+ Enable uploads by passing `upload` to `createApp` or `createServer`:
8
+
9
+ ```typescript
10
+ import { createServer, memoryStorage } from "@lastshotlabs/bunshot";
11
+
12
+ await createServer({
13
+ routesDir: import.meta.dir + "/routes",
14
+ upload: {
15
+ storage: memoryStorage(), // swap for localStorage() or s3Storage()
16
+ maxFileSize: 5 * 1024 * 1024, // 5 MB per file
17
+ maxFiles: 3,
18
+ allowedMimeTypes: ["image/*", "application/pdf"],
19
+ keyPrefix: "uploads/",
20
+ tenantScopedKeys: false,
21
+ presignedUrls: true, // mounts POST /uploads/presign and DELETE /uploads/:key
22
+ },
23
+ });
24
+ ```
25
+
26
+ **`UploadConfig` fields:**
27
+
28
+ | Field | Type | Default | Description |
29
+ |-------|------|---------|-------------|
30
+ | `storage` | `StorageAdapter` | required | Storage backend instance |
31
+ | `maxFileSize` | `number` | `10485760` (10 MB) | Max bytes per file |
32
+ | `maxFiles` | `number` | `10` | Max files per request |
33
+ | `allowedMimeTypes` | `string[]` | all allowed | Permitted MIME types (supports wildcards like `image/*`) |
34
+ | `keyPrefix` | `string` | `"uploads/"` | Path prefix prepended to generated keys |
35
+ | `generateKey` | `(file, ctx) => string` | UUID-based | Custom key generation function |
36
+ | `tenantScopedKeys` | `boolean` | `false` | Prepend `tenantId/` to generated keys |
37
+ | `presignedUrls` | `boolean \| PresignedUrlConfig` | `false` | Mount presigned URL routes |
38
+
39
+ ### Storage Adapters
40
+
41
+ #### Memory (testing)
42
+
43
+ ```typescript
44
+ import { memoryStorage, clearMemoryUploadStore } from "@lastshotlabs/bunshot";
45
+
46
+ const storage = memoryStorage();
47
+ // clearMemoryUploadStore() is called automatically by clearMemoryStore() in tests
48
+ ```
49
+
50
+ Does not implement `presignPut` / `presignGet`. The presigned URL route returns `501` when this adapter is used.
51
+
52
+ #### Local Filesystem
53
+
54
+ ```typescript
55
+ import { localStorage } from "@lastshotlabs/bunshot";
56
+
57
+ const storage = localStorage({
58
+ directory: import.meta.dir + "/uploads",
59
+ baseUrl: "https://example.com/files", // optional — appended to key for public URL
60
+ });
61
+ ```
62
+
63
+ #### S3 / R2 / MinIO
64
+
65
+ Requires `@aws-sdk/client-s3`. Presigned URLs additionally require `@aws-sdk/s3-request-presigner`.
66
+
67
+ ```typescript
68
+ import { s3Storage } from "@lastshotlabs/bunshot";
69
+
70
+ const storage = s3Storage({
71
+ bucket: "my-bucket",
72
+ region: "us-east-1",
73
+ credentials: {
74
+ accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
75
+ secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,
76
+ },
77
+ publicUrl: "https://cdn.example.com", // optional — used to build the returned URL
78
+ // For Cloudflare R2 or MinIO:
79
+ // endpoint: "https://<account>.r2.cloudflarestorage.com",
80
+ // forcePathStyle: true,
81
+ });
82
+ ```
83
+
84
+ ### Server-Side Upload (Middleware)
85
+
86
+ Use `handleUpload` middleware in your route handler. It parses the multipart body, validates files, stores them, and sets `uploadResults` on the context.
87
+
88
+ ```typescript
89
+ import { createRoute, handleUpload } from "@lastshotlabs/bunshot";
90
+ import { createRouter } from "@lastshotlabs/bunshot";
91
+
92
+ export const router = createRouter();
93
+
94
+ const uploadRoute = createRoute({
95
+ method: "post",
96
+ path: "/photos",
97
+ summary: "Upload photos",
98
+ responses: {
99
+ 200: { description: "Uploaded", content: { "application/json": { schema: z.object({ keys: z.array(z.string()) }) } } },
100
+ },
101
+ });
102
+
103
+ router.openapi(uploadRoute, handleUpload({ field: "photo", allowedMimeTypes: ["image/*"] }), async (c) => {
104
+ const results = c.get("uploadResults") ?? [];
105
+ return c.json({ keys: results.map((r) => r.key) });
106
+ });
107
+ ```
108
+
109
+ **`UploadResult` fields:**
110
+
111
+ | Field | Type | Description |
112
+ |-------|------|-------------|
113
+ | `key` | `string` | Storage key |
114
+ | `originalName` | `string` | Original filename from the browser |
115
+ | `mimeType` | `string` | Detected MIME type |
116
+ | `size` | `number` | File size in bytes |
117
+ | `url` | `string \| undefined` | Public URL (when adapter returns one) |
118
+
119
+ ### Presigned URL Flow (Client-Side Upload)
120
+
121
+ When `presignedUrls` is set, two routes are mounted (default base path `/uploads`, requires authentication):
122
+
123
+ - `POST /uploads/presign` — returns a time-limited PUT URL
124
+ - `DELETE /uploads/:key` — deletes a stored file
125
+
126
+ ```typescript
127
+ // 1. Client requests a presigned URL from your API
128
+ const { url, key } = await fetch("/uploads/presign", {
129
+ method: "POST",
130
+ headers: { "Content-Type": "application/json" },
131
+ body: JSON.stringify({ key: "photos/my-image.jpg", mimeType: "image/jpeg", expirySeconds: 300 }),
132
+ }).then(r => r.json());
133
+
134
+ // 2. Client uploads directly to storage (no server bandwidth used)
135
+ await fetch(url, { method: "PUT", body: file, headers: { "Content-Type": "image/jpeg" } });
136
+
137
+ // 3. Store the key in your database
138
+ await savePhotoRecord({ key, userId: currentUser.id });
139
+ ```
140
+
141
+ Configure the base path and default expiry:
142
+
143
+ ```typescript
144
+ presignedUrls: {
145
+ path: "/media", // mounts POST /media/presign and DELETE /media/:key
146
+ expirySeconds: 600, // default 10-minute expiry
147
+ }
148
+ ```
149
+
150
+ If the configured storage adapter does not support `presignPut` (e.g., memory or local filesystem), the endpoint returns `501 { error: "Presigned URLs not supported by the configured storage adapter" }`.
151
+
152
+ ### Dynamic Bucket Selection
153
+
154
+ Set `c.set("uploadBucket", "tenant-bucket-name")` before calling `handleUpload` (or `parseUpload`) to override the default bucket on a per-request basis. Supported by `s3Storage` — `meta.bucket` takes priority over `config.bucket`.
155
+
156
+ ```typescript
157
+ router.use("/uploads/*", async (c, next) => {
158
+ const tenant = c.get("tenantId");
159
+ if (tenant) c.set("uploadBucket", `tenant-${tenant}`);
160
+ await next();
161
+ });
162
+ ```
163
+
164
+ ### MIME Type Wildcards
165
+
166
+ `allowedMimeTypes` supports exact matches and `type/*` wildcards:
167
+
168
+ ```typescript
169
+ allowedMimeTypes: ["image/*", "video/mp4", "application/pdf"]
170
+ ```
171
+
172
+ ### Tenant-Scoped Keys
173
+
174
+ When `tenantScopedKeys: true`, generated keys are prefixed with the request's `tenantId`:
175
+
176
+ ```
177
+ uploads/tenant-abc/550e8400-e29b-41d4-a716-446655440000.jpg
178
+ ```
179
+
180
+ ### Context Variables
181
+
182
+ | Variable | Type | Set by |
183
+ |----------|------|--------|
184
+ | `uploadResults` | `UploadResult[] \| null` | `handleUpload` middleware |
185
+ | `uploadBucket` | `string \| undefined` | Application code (per-request bucket override) |
186
+
187
+ ### `parseUpload` (lower-level)
188
+
189
+ `parseUpload(c, opts?)` is the underlying function used by `handleUpload`. It returns `UploadResult[]` directly without touching `c.set("uploadResults", ...)`. Use it when you need more control over the response or want to handle results inline:
190
+
191
+ ```typescript
192
+ import { parseUpload } from "@lastshotlabs/bunshot";
193
+
194
+ router.post("/avatar", async (c) => {
195
+ const [result] = await parseUpload(c, { field: "avatar", maxFiles: 1, allowedMimeTypes: ["image/*"] });
196
+ await db.users.update({ id: c.get("authUserId")! }, { avatar: result.key });
197
+ return c.json({ key: result.key });
198
+ });
199
+ ```
@@ -0,0 +1,85 @@
1
+ ## API Versioning
2
+
3
+ Mount multiple API versions with isolated OpenAPI specs and Scalar docs pages.
4
+
5
+ ### Directory Structure
6
+
7
+ ```
8
+ routes/
9
+ ├── v1/
10
+ │ └── users.ts # v1-specific routes
11
+ ├── v2/
12
+ │ └── users.ts # v2-specific routes (breaking changes)
13
+ └── shared/
14
+ └── health.ts # appears in all versions, unprefixed schemas
15
+ ```
16
+
17
+ ### Configuration
18
+
19
+ ```typescript
20
+ await createServer({
21
+ routesDir: import.meta.dir + "/routes",
22
+ versioning: {
23
+ versions: ["v1", "v2"], // subdirectories under routesDir
24
+ defaultVersion: "v2", // which version /docs and /openapi.json redirect to (default: last)
25
+ sharedDir: "shared", // shared routes dir (default: "shared", set false to disable)
26
+ },
27
+ });
28
+ ```
29
+
30
+ **What gets mounted:**
31
+
32
+ | Path | Description |
33
+ |------|-------------|
34
+ | `/v1/users`, `/v2/users` | Version-specific route handlers |
35
+ | `/v1/openapi.json`, `/v2/openapi.json` | Isolated OpenAPI specs |
36
+ | `/v1/docs`, `/v2/docs` | Scalar docs per version |
37
+ | `/docs` | Version selector page (links to each version's docs) |
38
+ | `/openapi.json` | 302 redirect to `/{defaultVersion}/openapi.json` (no merged spec) |
39
+
40
+ ### Route Files
41
+
42
+ Route files are unchanged — use `createRouter()` and `createRoute()` as normal:
43
+
44
+ ```typescript
45
+ // routes/v2/users.ts
46
+ import { createRouter, createRoute } from "@lastshotlabs/bunshot";
47
+ import { z } from "zod";
48
+
49
+ export const router = createRouter();
50
+
51
+ const ListUsersRoute = createRoute({
52
+ method: "get",
53
+ path: "/users",
54
+ responses: {
55
+ 200: {
56
+ description: "Users",
57
+ content: { "application/json": { schema: z.object({ users: z.array(UserSchema) }) } },
58
+ },
59
+ },
60
+ });
61
+
62
+ router.openapi(ListUsersRoute, (c) => c.json({ users: [] }));
63
+ ```
64
+
65
+ Schema names are automatically prefixed with the version: `GET /users` in v1 → `V1GetUsersResponse`, in v2 → `V2GetUsersResponse`. This prevents phantom types in generated TypeScript clients when both specs share a registry.
66
+
67
+ ### Shared Routes
68
+
69
+ Routes in the `shared/` directory are mounted on every versioned app. Their schemas receive **no version prefix** since they are version-agnostic. Shared route files must be stateless — Hono mounts a reference (not a clone), so the same router instance is shared across all versioned apps. Standard `createRouter()` routers are stateless by design.
70
+
71
+ ### Unreferenced Schema Stripping
72
+
73
+ Each version's spec is post-processed to remove `components/schemas` entries not referenced by that version's routes. This prevents schema bleed from the global OpenAPI registry into specs that don't use them.
74
+
75
+ `stripUnreferencedSchemas` is also exported from the package for apps that serve OpenAPI specs via custom handlers.
76
+
77
+ ### No Merged Spec
78
+
79
+ There is no combined spec at `/openapi.json`. Root `/openapi.json` returns a `302` redirect to the default version's spec. This is intentional — merging specs from multiple versions produces ambiguous schema names and defeats the isolation benefit.
80
+
81
+ ### Notes
82
+
83
+ - **Avoid unbounded top-level `await` in route files.** The framework sets the version prefix module-level before importing each version's route files. A route file whose `createRoute()` calls run synchronously (the normal pattern) works correctly. If `createRoute()` is called after an unbounded top-level `await` (e.g., an unresolved DB call), the prefix may have changed. The framework throws a clear startup error if this is detected.
84
+ - **Non-versioned behavior is unchanged.** If `versioning` is not set, routes are discovered at `routesDir/**/*.ts` and mounted at root exactly as before.
85
+ - **Priority ordering works per-version.** Export `export const priority = <number>` from a versioned route file to control load order within that version.
@@ -0,0 +1,100 @@
1
+ ## Webhook Authentication
2
+
3
+ `webhookAuth` is a middleware that verifies HMAC signatures on incoming webhook requests. It supports GitHub-style signing, multiple algorithms, replay protection, and per-request dynamic secrets.
4
+
5
+ ```ts
6
+ import { webhookAuth } from "@lastshotlabs/bunshot";
7
+ ```
8
+
9
+ ### Basic usage
10
+
11
+ ```ts
12
+ // routes/webhooks.ts
13
+ import { webhookAuth } from "@lastshotlabs/bunshot";
14
+ import { createRouter } from "@lastshotlabs/bunshot";
15
+
16
+ export const router = createRouter();
17
+
18
+ router.post(
19
+ "/webhooks/stripe",
20
+ webhookAuth({ secret: process.env.STRIPE_WEBHOOK_SECRET! }),
21
+ async (c) => {
22
+ const event = await c.req.json();
23
+ // body is still readable — Hono caches it after webhookAuth reads it
24
+ return c.json({ received: true });
25
+ }
26
+ );
27
+ ```
28
+
29
+ ### GitHub-style (prefix + sha256)
30
+
31
+ GitHub sends `X-Hub-Signature-256: sha256=<hex>`. Use `prefix` to strip the `sha256=` before comparing:
32
+
33
+ ```ts
34
+ router.post(
35
+ "/webhooks/github",
36
+ webhookAuth({
37
+ secret: process.env.GITHUB_WEBHOOK_SECRET!,
38
+ header: "x-hub-signature-256",
39
+ prefix: "sha256=",
40
+ algorithm: "sha256",
41
+ }),
42
+ async (c) => c.json({ ok: true })
43
+ );
44
+ ```
45
+
46
+ If the header value does **not** start with the configured prefix, the full value is compared as-is — the prefix is stripped when present, not required.
47
+
48
+ ### Options
49
+
50
+ | Option | Type | Default | Description |
51
+ |--------|------|---------|-------------|
52
+ | `secret` | `string \| (c) => string \| Promise<string>` | — | Shared HMAC secret. Pass a function for dynamic resolution (e.g. per-tenant lookup). |
53
+ | `header` | `string` | `"x-webhook-signature"` | Header that carries the signature. |
54
+ | `algorithm` | `"sha256" \| "sha512" \| "sha1"` | `"sha256"` | HMAC algorithm. |
55
+ | `prefix` | `string` | — | Strip this prefix before comparing (e.g. `"sha256="` for GitHub). |
56
+ | `timestamp` | `{ header, tolerance }` | — | Opt-in replay protection (see below). |
57
+
58
+ ### Replay protection
59
+
60
+ Pass `timestamp` to reject requests with a stale timestamp header:
61
+
62
+ ```ts
63
+ webhookAuth({
64
+ secret: process.env.WEBHOOK_SECRET!,
65
+ timestamp: {
66
+ header: "x-webhook-timestamp", // header name carrying the Unix timestamp
67
+ tolerance: 300_000, // 5 minutes in ms
68
+ },
69
+ })
70
+ ```
71
+
72
+ - Values `< 1e10` in the header are treated as Unix **seconds** and auto-converted to ms
73
+ - Missing or non-numeric timestamps → `401 EXPIRED_TIMESTAMP`
74
+ - Timestamp outside `tolerance` → `401 EXPIRED_TIMESTAMP`
75
+ - Signature check runs after the timestamp check passes
76
+
77
+ ### Dynamic secrets (multi-tenant)
78
+
79
+ Pass a function to resolve the secret per request — useful when each tenant has its own webhook secret:
80
+
81
+ ```ts
82
+ webhookAuth({
83
+ secret: async (c) => {
84
+ const tenantId = c.req.header("x-tenant-id");
85
+ const tenant = await getTenantWebhookSecret(tenantId);
86
+ if (!tenant) throw new Error("unknown tenant");
87
+ return tenant.webhookSecret;
88
+ },
89
+ })
90
+ ```
91
+
92
+ If the function throws, the request receives `500 { code: "WEBHOOK_SECRET_ERROR" }`.
93
+
94
+ ### Error responses
95
+
96
+ | Condition | Status | `code` |
97
+ |-----------|--------|--------|
98
+ | Missing or invalid signature | `401` | `INVALID_SIGNATURE` |
99
+ | Missing, non-numeric, or expired timestamp | `401` | `EXPIRED_TIMESTAMP` |
100
+ | Secret function threw | `500` | `WEBHOOK_SECRET_ERROR` |
@@ -81,6 +81,89 @@ await createServer({
81
81
 
82
82
  You can supply any subset of `open`, `message`, `close`, `drain` — unset handlers fall back to the defaults.
83
83
 
84
+ ### Heartbeat / Ping-Pong Keepalive
85
+
86
+ Opt-in via `ws.heartbeat`. Detects and closes stale connections via ping/pong:
87
+
88
+ ```ts
89
+ await createServer({
90
+ ws: {
91
+ heartbeat: true, // 30s interval, 10s timeout
92
+ // or fine-tune:
93
+ heartbeat: { intervalMs: 15_000, timeoutMs: 5_000 },
94
+ },
95
+ });
96
+ ```
97
+
98
+ Every `intervalMs`, the server pings all connected sockets. If a socket hasn't responded within `timeoutMs`, it's closed with code `1001` ("Heartbeat timeout"). `stopHeartbeat()` is called automatically on SIGTERM/SIGINT and is also exported for custom shutdown logic.
99
+
100
+ ### Presence Tracking
101
+
102
+ Opt-in via `ws.presence`. Tracks which authenticated users are online in each room (multi-tab aware):
103
+
104
+ ```ts
105
+ await createServer({
106
+ ws: {
107
+ presence: true,
108
+ },
109
+ });
110
+ ```
111
+
112
+ When a user's first socket subscribes to a room, all room members receive `{ event: "presence_join", room, userId }`. When the user's last socket leaves (unsubscribe or disconnect), `{ event: "presence_leave", room, userId }` is broadcast.
113
+
114
+ **Query presence:**
115
+
116
+ ```ts
117
+ import { getRoomPresence, getUserPresence } from "@lastshotlabs/bunshot";
118
+
119
+ getRoomPresence("chat:general"); // ["user1", "user2"] — deduplicated userIds
120
+ getUserPresence("user1"); // ["chat:general", "chat:vip"] — rooms where user is present
121
+ ```
122
+
123
+ ### Message Persistence
124
+
125
+ Opt-in via `ws.persistence`. Persists messages for late joiners. Rooms must be individually opted in via `configureRoom()`:
126
+
127
+ ```ts
128
+ import { configureRoom, persistMessage, getMessageHistory } from "@lastshotlabs/bunshot";
129
+
130
+ await createServer({
131
+ ws: {
132
+ persistence: {
133
+ store: "memory", // "redis" | "mongo" | "sqlite" | "memory"
134
+ defaults: { maxCount: 100, ttlSeconds: 86_400 }, // 24h
135
+ },
136
+ },
137
+ });
138
+
139
+ // Opt rooms in
140
+ configureRoom("chat:general", { persist: true });
141
+ configureRoom("chat:vip", { persist: true, maxCount: 50, ttlSeconds: 3600 });
142
+
143
+ // Persist from your custom message handler
144
+ await createServer({
145
+ ws: {
146
+ handler: {
147
+ async message(ws, message) {
148
+ const data = JSON.parse(message as string);
149
+ if (data.type === "chat") {
150
+ await persistMessage(data.room, {
151
+ senderId: ws.data.userId,
152
+ payload: data,
153
+ });
154
+ }
155
+ },
156
+ },
157
+ },
158
+ });
159
+
160
+ // Retrieve history (cursor-based pagination)
161
+ const history = await getMessageHistory("chat:general", { limit: 50 });
162
+ const older = await getMessageHistory("chat:general", { limit: 50, before: history[0].id });
163
+ ```
164
+
165
+ Messages for non-configured rooms are silently ignored. Store errors are caught and logged (non-blocking) — message delivery is never interrupted by a persistence failure.
166
+
84
167
  ### Overriding the upgrade / auth handler
85
168
 
86
169
  Replace the default cookie-JWT handshake entirely via `ws.upgradeHandler`. You must call `server.upgrade()` yourself and include `rooms: new Set()` in data:
@@ -13,6 +13,11 @@ Rooms are built on Bun's native pub/sub. `createServer` always intercepts room a
13
13
  | `getRooms()` | Returns `string[]` of all rooms with at least one active subscriber |
14
14
  | `getRoomSubscribers(room)` | Returns `string[]` of socket IDs currently subscribed to `room` |
15
15
  | `handleRoomActions(ws, message, onSubscribe?)` | Parses and dispatches subscribe/unsubscribe actions. Returns `true` if the message was a room action (consumed), `false` otherwise. Pass an optional async guard as the third argument. |
16
+ | `getRoomPresence(room)` | Returns deduplicated `string[]` of userIds present in room (requires `ws.presence` enabled) |
17
+ | `getUserPresence(userId)` | Returns `string[]` of rooms where user is present (requires `ws.presence` enabled) |
18
+ | `persistMessage(room, data)` | Store a message for a room (requires `ws.persistence` + `configureRoom`). Returns `StoredMessage \| null` |
19
+ | `getMessageHistory(room, opts?)` | Cursor-based retrieval. `opts`: `{ limit?, before?, after? }` (cursors are message IDs) |
20
+ | `configureRoom(room, opts)` | Opt a room into persistence: `{ persist: true, maxCount?, ttlSeconds? }` |
16
21
 
17
22
  ### Client → server: join or leave a room
18
23
 
@@ -94,4 +99,4 @@ await createServer({
94
99
  },
95
100
  },
96
101
  });
97
- ```
102
+ ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lastshotlabs/bunshot",
3
- "version": "0.0.21",
3
+ "version": "0.0.25",
4
4
  "description": "Batteries-included Bun + Hono API framework — auth, sessions, rate limiting, WebSocket, queues, and OpenAPI docs out of the box",
5
5
  "repository": {
6
6
  "type": "git",
@@ -52,8 +52,8 @@
52
52
  "start": "bun src/index.ts",
53
53
  "readme": "bun docs/build-readme.ts",
54
54
  "readme:npm": "bun docs/build-readme.ts npm",
55
- "test": "bun test tests/unit tests/integration && bun test tests/isolated",
56
- "test:isolated": "bun test tests/isolated",
55
+ "test": "bun test tests/unit tests/integration && bun test tests/isolated/optional-deps.test.ts && bun test tests/isolated/jwt-secret.test.ts && bun test tests/isolated/queue.test.ts tests/isolated/jobs-router.test.ts && bun test tests/isolated/queued-deletion.test.ts",
56
+ "test:isolated": "bun test tests/isolated/optional-deps.test.ts && bun test tests/isolated/jwt-secret.test.ts && bun test tests/isolated/queue.test.ts tests/isolated/jobs-router.test.ts && bun test tests/isolated/queued-deletion.test.ts",
57
57
  "test:coverage": "bun test --coverage tests/unit tests/integration",
58
58
  "test:docker:up": "docker compose -f docker-compose.test.yml up -d --wait",
59
59
  "test:docker:down": "docker compose -f docker-compose.test.yml down",
@@ -75,7 +75,10 @@
75
75
  "ioredis": ">=5.0 <6",
76
76
  "bullmq": ">=5.0 <6",
77
77
  "otpauth": ">=9.0 <10",
78
- "@simplewebauthn/server": ">=10.0.0"
78
+ "@simplewebauthn/server": ">=10.0.0",
79
+ "@aws-sdk/client-s3": ">=3.0",
80
+ "@aws-sdk/s3-request-presigner": ">=3.0",
81
+ "@aws-sdk/lib-storage": ">=3.0"
79
82
  },
80
83
  "peerDependenciesMeta": {
81
84
  "mongoose": {
@@ -92,6 +95,15 @@
92
95
  },
93
96
  "@simplewebauthn/server": {
94
97
  "optional": true
98
+ },
99
+ "@aws-sdk/client-s3": {
100
+ "optional": true
101
+ },
102
+ "@aws-sdk/s3-request-presigner": {
103
+ "optional": true
104
+ },
105
+ "@aws-sdk/lib-storage": {
106
+ "optional": true
95
107
  }
96
108
  },
97
109
  "devDependencies": {