create-efforge 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +140 -2
- package/dist/addon.js +115 -0
- package/dist/bin.js +6 -0
- package/dist/cli.js +9 -0
- package/dist/commands/add.js +440 -0
- package/dist/commands/create.js +186 -0
- package/dist/diff.js +72 -0
- package/dist/exec.js +20 -0
- package/dist/generate.js +181 -0
- package/dist/manifest.js +14 -0
- package/dist/projectName.js +41 -0
- package/dist/prompts/flow.js +111 -0
- package/dist/prompts/navigable.js +97 -0
- package/dist/routeTree.js +7 -0
- package/dist/rules.js +24 -0
- package/dist/slots.js +96 -0
- package/dist/stack.js +68 -0
- package/dist/transforms/addAlchemyResource.js +71 -0
- package/dist/transforms/addArrayItem.js +31 -0
- package/dist/transforms/addAuthPlugin.js +77 -0
- package/dist/transforms/addDevVar.js +18 -0
- package/dist/transforms/addExport.js +46 -0
- package/dist/transforms/addImport.js +11 -0
- package/dist/transforms/addLayer.js +31 -0
- package/dist/transforms/addServerFnMiddleware.js +62 -0
- package/dist/transforms/addWorkflowSecret.js +43 -0
- package/dist/transforms/addWranglerBinding.js +61 -0
- package/dist/transforms/appendAgentsSection.js +26 -0
- package/dist/transforms/errors.js +7 -0
- package/dist/transforms/index.js +40 -0
- package/dist/transforms/setWranglerValue.js +40 -0
- package/dist/transforms/util.js +219 -0
- package/dist/tree.js +1 -0
- package/dist/versions.js +73 -0
- package/dist/write.js +26 -0
- package/package.json +63 -4
- package/templates/ai/effect-ai-byok/addon.json +619 -0
- package/templates/ai/effect-ai-byok/files/core/llm-crypto.test.ts +47 -0
- package/templates/ai/effect-ai-byok/files/core/llm-crypto.ts +76 -0
- package/templates/ai/effect-ai-byok/files/core/llm-store.ts +21 -0
- package/templates/ai/effect-ai-byok/files/core/llm.ts +32 -0
- package/templates/ai/effect-ai-byok/files/drizzle/d1/20261018161056_llm_credential/migration.sql +9 -0
- package/templates/ai/effect-ai-byok/files/drizzle/d1/20261018161056_llm_credential/snapshot.json +944 -0
- package/templates/ai/effect-ai-byok/files/drizzle/pg/20261018161056_llm_credential/migration.sql +10 -0
- package/templates/ai/effect-ai-byok/files/drizzle/pg/20261018161056_llm_credential/snapshot.json +1232 -0
- package/templates/ai/effect-ai-byok/files/routes/ai.tsx +193 -0
- package/templates/ai/effect-ai-byok/files/schema/d1.ts +16 -0
- package/templates/ai/effect-ai-byok/files/schema/pg.ts +14 -0
- package/templates/ai/effect-ai-byok/files/server/ai-settings.ts +129 -0
- package/templates/ai/effect-ai-byok/files/server/ai.ts +25 -0
- package/templates/ai/effect-ai-byok/files/server/llm-env.ts +48 -0
- package/templates/ai/effect-ai-byok/files/server/llm-orgs.ts +146 -0
- package/templates/ai/effect-ai-byok/files/server/llm-provider.ts +56 -0
- package/templates/ai/effect-ai-byok/files/server/llm-store-drizzle.ts +48 -0
- package/templates/ai/effect-ai-byok/files/server/llm-store-sql-d1.ts +41 -0
- package/templates/ai/effect-ai-byok/files/server/llm-store-sql-pg.ts +41 -0
- package/templates/ai/effect-ai-byok/files/sql/d1.sql +8 -0
- package/templates/ai/effect-ai-byok/files/sql/pg.sql +8 -0
- package/templates/auth/better-auth/addon.json +424 -0
- package/templates/auth/better-auth/files/core/Auth.ts +18 -0
- package/templates/auth/better-auth/files/drizzle/d1/20261018161054_auth/migration.sql +51 -0
- package/templates/auth/better-auth/files/drizzle/d1/20261018161054_auth/snapshot.json +522 -0
- package/templates/auth/better-auth/files/drizzle/pg/20261018161053_auth/migration.sql +51 -0
- package/templates/auth/better-auth/files/drizzle/pg/20261018161053_auth/snapshot.json +680 -0
- package/templates/auth/better-auth/files/lib/auth-client.ts +4 -0
- package/templates/auth/better-auth/files/routes/app.tsx +54 -0
- package/templates/auth/better-auth/files/schema/d1/auth-schema.ts +86 -0
- package/templates/auth/better-auth/files/schema/pg/auth-schema.ts +73 -0
- package/templates/auth/better-auth/files/server/auth-live.ts +47 -0
- package/templates/auth/better-auth/files/server/session.ts +14 -0
- package/templates/auth/better-auth/files/shared/components/auth-card.tsx +32 -0
- package/templates/auth/better-auth/files/shared/components/user-menu.tsx +44 -0
- package/templates/auth/better-auth/files/shared/drizzle/d1/drizzle.config.ts +7 -0
- package/templates/auth/better-auth/files/shared/drizzle/pg/drizzle.config.ts +10 -0
- package/templates/auth/better-auth/files/shared/lib/form.ts +5 -0
- package/templates/auth/better-auth/files/shared/lib/redirect.ts +6 -0
- package/templates/auth/better-auth/files/shared/routes/app/index.tsx +54 -0
- package/templates/auth/better-auth/files/shared/routes/sign-in.tsx +85 -0
- package/templates/auth/better-auth/files/shared/routes/sign-up.tsx +91 -0
- package/templates/auth/better-auth/files/shared/server/auth-route.ts +15 -0
- package/templates/auth/better-auth/files/shared/server/auth.ts +22 -0
- package/templates/auth/better-auth/files/shared/server/db/d1-drizzle.ts +25 -0
- package/templates/auth/better-auth/files/shared/server/db/d1-effect-sql.ts +17 -0
- package/templates/auth/better-auth/files/shared/server/db/pg-drizzle.ts +32 -0
- package/templates/auth/better-auth/files/shared/server/db/pg-effect-sql.ts +29 -0
- package/templates/auth/better-auth/files/shared/server/require-session.ts +20 -0
- package/templates/auth/better-auth/files/sql/d1/0002_auth.sql +13 -0
- package/templates/auth/better-auth/files/sql/pg/0002_auth.sql +13 -0
- package/templates/auth/better-auth-orgs/addon.json +463 -0
- package/templates/auth/better-auth-orgs/files/components/org-switcher.tsx +65 -0
- package/templates/auth/better-auth-orgs/files/core/Auth.ts +20 -0
- package/templates/auth/better-auth-orgs/files/drizzle/d1/20261018161055_auth/migration.sql +88 -0
- package/templates/auth/better-auth-orgs/files/drizzle/d1/20261018161055_auth/snapshot.json +862 -0
- package/templates/auth/better-auth-orgs/files/drizzle/pg/20261018161055_auth/migration.sql +88 -0
- package/templates/auth/better-auth-orgs/files/drizzle/pg/20261018161055_auth/snapshot.json +1127 -0
- package/templates/auth/better-auth-orgs/files/lib/auth-client.ts +5 -0
- package/templates/auth/better-auth-orgs/files/routes/accept-invite.$id.tsx +68 -0
- package/templates/auth/better-auth-orgs/files/routes/app/settings/index.tsx +27 -0
- package/templates/auth/better-auth-orgs/files/routes/app/settings/members.tsx +198 -0
- package/templates/auth/better-auth-orgs/files/routes/app/settings.tsx +30 -0
- package/templates/auth/better-auth-orgs/files/routes/app.tsx +58 -0
- package/templates/auth/better-auth-orgs/files/routes/onboarding.tsx +66 -0
- package/templates/auth/better-auth-orgs/files/schema/d1/auth-schema.ts +139 -0
- package/templates/auth/better-auth-orgs/files/schema/pg/auth-schema.ts +124 -0
- package/templates/auth/better-auth-orgs/files/server/auth-live.ts +52 -0
- package/templates/auth/better-auth-orgs/files/server/session.ts +44 -0
- package/templates/auth/better-auth-orgs/files/sql/d1/0002_auth.sql +27 -0
- package/templates/auth/better-auth-orgs/files/sql/pg/0002_auth.sql +27 -0
- package/templates/base/addon.json +212 -0
- package/templates/base/files/AGENTS.md +70 -0
- package/templates/base/files/CLAUDE.md +1 -0
- package/templates/base/files/README.md +28 -0
- package/templates/base/files/core/package.json +13 -0
- package/templates/base/files/core/src/index.ts +2 -0
- package/templates/base/files/core/test/core.test.ts +4 -0
- package/templates/base/files/core/tsconfig.json +6 -0
- package/templates/base/files/gitignore +11 -0
- package/templates/base/files/pnpm-workspace.yaml +11 -0
- package/templates/base/files/root/package.json +16 -0
- package/templates/base/files/root/tsconfig.base.json +19 -0
- package/templates/base/files/root/turbo.json +9 -0
- package/templates/base/files/root/vite.config.ts +61 -0
- package/templates/base/files/web/components.json +21 -0
- package/templates/base/files/web/package.json +17 -0
- package/templates/base/files/web/src/components/theme-provider.tsx +57 -0
- package/templates/base/files/web/src/components/theme-toggle.tsx +34 -0
- package/templates/base/files/web/src/components/ui/avatar.tsx +93 -0
- package/templates/base/files/web/src/components/ui/button.tsx +61 -0
- package/templates/base/files/web/src/components/ui/card.tsx +74 -0
- package/templates/base/files/web/src/components/ui/dialog.tsx +141 -0
- package/templates/base/files/web/src/components/ui/dropdown-menu.tsx +225 -0
- package/templates/base/files/web/src/components/ui/input.tsx +20 -0
- package/templates/base/files/web/src/components/ui/label.tsx +18 -0
- package/templates/base/files/web/src/components/ui/sonner.tsx +45 -0
- package/templates/base/files/web/src/components/widgets.tsx +4 -0
- package/templates/base/files/web/src/lib/utils.ts +6 -0
- package/templates/base/files/web/src/router.tsx +12 -0
- package/templates/base/files/web/src/routes/__root.tsx +42 -0
- package/templates/base/files/web/src/routes/app/index.tsx +27 -0
- package/templates/base/files/web/src/routes/app/settings.tsx +29 -0
- package/templates/base/files/web/src/routes/app.tsx +47 -0
- package/templates/base/files/web/src/routes/index.tsx +51 -0
- package/templates/base/files/web/src/server/greeting.ts +12 -0
- package/templates/base/files/web/src/server/layers.ts +10 -0
- package/templates/base/files/web/src/server/runtime.ts +5 -0
- package/templates/base/files/web/src/styles.css +81 -0
- package/templates/base/files/web/tsconfig.json +11 -0
- package/templates/base/files/web/vite.config.ts +9 -0
- package/templates/database/d1/addon.json +118 -0
- package/templates/database/d1/files/package.json +12 -0
- package/templates/database/d1/files/tsconfig.json +5 -0
- package/templates/database/postgres/addon.json +142 -0
- package/templates/database/postgres/files/docker-compose.yml +21 -0
- package/templates/database/postgres/files/package.json +12 -0
- package/templates/database/postgres/files/runtime.ts +12 -0
- package/templates/database/postgres/files/tsconfig.json +5 -0
- package/templates/extras/browser/addon.json +173 -0
- package/templates/extras/browser/files/BrowserContainer.ts +14 -0
- package/templates/extras/browser/files/app/Dockerfile +15 -0
- package/templates/extras/browser/files/app/dockerignore +1 -0
- package/templates/extras/browser/files/app/package-lock +605 -0
- package/templates/extras/browser/files/app/package.json +9 -0
- package/templates/extras/browser/files/app/src/server.ts +78 -0
- package/templates/extras/browser/files/app/src/url-policy.ts +115 -0
- package/templates/extras/browser/files/app/tsconfig.json +6 -0
- package/templates/extras/browser/files/browser.ts +34 -0
- package/templates/extras/browser/files/core-browser.ts +21 -0
- package/templates/extras/browser/files/run-browser.ts +25 -0
- package/templates/extras/email/addon.json +182 -0
- package/templates/extras/email/files/core-mailer.ts +28 -0
- package/templates/extras/email/files/invitation-email.ts +38 -0
- package/templates/extras/email/files/mailer.ts +58 -0
- package/templates/extras/realtime/addon.json +135 -0
- package/templates/extras/realtime/files/Room.ts +46 -0
- package/templates/extras/realtime/files/core-realtime.ts +19 -0
- package/templates/extras/realtime/files/realtime-demo.tsx +40 -0
- package/templates/extras/realtime/files/realtime-limits.test.ts +32 -0
- package/templates/extras/realtime/files/realtime-limits.ts +35 -0
- package/templates/extras/realtime/files/realtime-route.ts +39 -0
- package/templates/extras/realtime/files/realtime.ts +39 -0
- package/templates/extras/realtime/files/use-room.ts +67 -0
- package/templates/extras/storage/addon.json +132 -0
- package/templates/extras/storage/files/core-storage.ts +64 -0
- package/templates/extras/storage/files/storage-route.ts +50 -0
- package/templates/extras/storage/files/storage-security.test.ts +71 -0
- package/templates/extras/storage/files/storage-security.ts +92 -0
- package/templates/extras/storage/files/storage.ts +84 -0
- package/templates/extras/workflows/addon.json +95 -0
- package/templates/extras/workflows/files/Example.ts +42 -0
- package/templates/extras/workflows/files/core-jobs.ts +45 -0
- package/templates/extras/workflows/files/example-job.ts +36 -0
- package/templates/extras/workflows/files/jobs.ts +34 -0
- package/templates/infra/alchemy/addon.json +37 -0
- package/templates/infra/alchemy/files/README.md +27 -0
- package/templates/infra/alchemy/files/alchemy.run.ts +36 -0
- package/templates/infra/alchemy/files/github/deploy.yml +63 -0
- package/templates/infra/alchemy/files/tsconfig.json +5 -0
- package/templates/infra/alchemy/files/vite.config.ts +30 -0
- package/templates/orm/drizzle/addon.json +188 -0
- package/templates/orm/drizzle/files/d1/Database.ts +7 -0
- package/templates/orm/drizzle/files/d1/drizzle/20261018154417_init/migration.sql +10 -0
- package/templates/orm/drizzle/files/d1/drizzle/20261018154417_init/snapshot.json +60 -0
- package/templates/orm/drizzle/files/d1/drizzle.config.ts +7 -0
- package/templates/orm/drizzle/files/d1/layer.ts +13 -0
- package/templates/orm/drizzle/files/d1/migrate.ts +37 -0
- package/templates/orm/drizzle/files/d1/schema.ts +15 -0
- package/templates/orm/drizzle/files/pg/Database.ts +7 -0
- package/templates/orm/drizzle/files/pg/drizzle/20261018154416_init/migration.sql +10 -0
- package/templates/orm/drizzle/files/pg/drizzle/20261018154416_init/snapshot.json +75 -0
- package/templates/orm/drizzle/files/pg/drizzle.config.ts +10 -0
- package/templates/orm/drizzle/files/pg/layer.ts +16 -0
- package/templates/orm/drizzle/files/pg/migrate.ts +24 -0
- package/templates/orm/drizzle/files/pg/schema.ts +11 -0
- package/templates/orm/drizzle/files/shared/index.ts +2 -0
- package/templates/orm/drizzle/files/shared/notes.ts +15 -0
- package/templates/orm/drizzle/files/shared/page.tsx +50 -0
- package/templates/orm/effect-sql/addon.json +124 -0
- package/templates/orm/effect-sql/files/d1/layer.ts +13 -0
- package/templates/orm/effect-sql/files/d1/migrate.ts +20 -0
- package/templates/orm/effect-sql/files/d1/schema.ts +7 -0
- package/templates/orm/effect-sql/files/d1-sql/0001_init.sql +10 -0
- package/templates/orm/effect-sql/files/pg/layer.ts +16 -0
- package/templates/orm/effect-sql/files/pg/migrate.ts +66 -0
- package/templates/orm/effect-sql/files/pg/schema.ts +7 -0
- package/templates/orm/effect-sql/files/pg-sql/0001_init.sql +10 -0
- package/templates/orm/effect-sql/files/shared/Database.ts +7 -0
- package/templates/orm/effect-sql/files/shared/index.ts +2 -0
- package/templates/orm/effect-sql/files/shared/notes.ts +18 -0
- package/templates/orm/effect-sql/files/shared/page.tsx +50 -0
- package/templates/runtime/cloudflare/addon.json +52 -0
- package/templates/runtime/cloudflare/files/cloudflare.ts +10 -0
- package/templates/runtime/cloudflare/files/routes.ts +5 -0
- package/templates/runtime/cloudflare/files/server.ts +22 -0
- package/templates/runtime/cloudflare/files/tsconfig.json +12 -0
- package/templates/runtime/cloudflare/files/vite.config.ts +20 -0
- package/templates/runtime/cloudflare/files/wrangler.jsonc +8 -0
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { isMessageTooLarge, MAX_ROOM_CONNECTIONS } from "@repo/core/realtime-limits"
|
|
2
|
+
import { Effect, Layer, Schema } from "effect"
|
|
3
|
+
import { DurableObject, DurableObjectState, DurableObjectWebSocket, Worker } from "effect-cf"
|
|
4
|
+
|
|
5
|
+
export class RoomNamespace extends DurableObject.Tag<RoomNamespace>()("Room", {
|
|
6
|
+
broadcast: DurableObject.method({ args: [Schema.String], success: Schema.Void }),
|
|
7
|
+
connections: DurableObject.method({ success: Schema.Finite }),
|
|
8
|
+
}) {}
|
|
9
|
+
|
|
10
|
+
const sockets = Effect.flatMap(DurableObjectState.DurableObjectState, (state) =>
|
|
11
|
+
state.getWebSockets(),
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
const broadcast = (message: string) =>
|
|
15
|
+
Effect.gen(function* () {
|
|
16
|
+
for (const socket of yield* sockets) yield* Effect.ignore(socket.send(message))
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* One chat room. Sockets are hibernating: Cloudflare keeps them open while the object is evicted
|
|
21
|
+
* from memory and wakes it only when a client sends a message, so idle rooms cost nothing.
|
|
22
|
+
* Bound as ROOM in wrangler.jsonc and exported from `src/server.ts`.
|
|
23
|
+
*/
|
|
24
|
+
export class Room extends RoomNamespace.make(Layer.empty, {
|
|
25
|
+
// ping/pong keepalives are answered by Cloudflare without waking the object
|
|
26
|
+
initialize: DurableObjectWebSocket.installKeepalive(),
|
|
27
|
+
rpc: {
|
|
28
|
+
broadcast,
|
|
29
|
+
connections: () => Effect.map(sockets, (all) => all.length),
|
|
30
|
+
},
|
|
31
|
+
fetch: Effect.gen(function* () {
|
|
32
|
+
const request = yield* Worker.NativeRequest
|
|
33
|
+
if (request.headers.get("Upgrade") !== "websocket")
|
|
34
|
+
return new Response("Expected a WebSocket upgrade", { status: 426 })
|
|
35
|
+
if ((yield* sockets).length >= MAX_ROOM_CONNECTIONS)
|
|
36
|
+
return new Response("Room is full", { status: 503 })
|
|
37
|
+
return (yield* DurableObjectWebSocket.acceptUpgrade()).response
|
|
38
|
+
}),
|
|
39
|
+
// binary frames are ignored; oversized text closes the sender (1009 = message too big)
|
|
40
|
+
webSocketMessage: (socket, message) => {
|
|
41
|
+
if (typeof message !== "string") return Effect.void
|
|
42
|
+
if (isMessageTooLarge(message)) return Effect.ignore(socket.close(1009, "Message too big"))
|
|
43
|
+
return broadcast(message)
|
|
44
|
+
},
|
|
45
|
+
webSocketClose: (socket, code, reason) => Effect.ignore(socket.close(code, reason)),
|
|
46
|
+
}) {}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { Context, Data, type Effect } from "effect"
|
|
2
|
+
|
|
3
|
+
export class RealtimeError extends Data.TaggedError("RealtimeError")<{
|
|
4
|
+
readonly operation: string
|
|
5
|
+
readonly cause: unknown
|
|
6
|
+
}> {}
|
|
7
|
+
|
|
8
|
+
/** Rooms of WebSocket clients. The Cloudflare layer keeps each room in a Durable Object. */
|
|
9
|
+
export class Realtime extends Context.Service<
|
|
10
|
+
Realtime,
|
|
11
|
+
{
|
|
12
|
+
/** Forwards a WebSocket upgrade request to the room; the response completes the handshake. */
|
|
13
|
+
readonly connect: (roomId: string, request: Request) => Effect.Effect<Response, RealtimeError>
|
|
14
|
+
/** Sends `message` to every client connected to the room. */
|
|
15
|
+
readonly broadcast: (roomId: string, message: string) => Effect.Effect<void, RealtimeError>
|
|
16
|
+
/** Number of clients currently connected to the room. */
|
|
17
|
+
readonly connections: (roomId: string) => Effect.Effect<number, RealtimeError>
|
|
18
|
+
}
|
|
19
|
+
>()("@repo/core/Realtime") {}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { type FormEvent, useState } from "react"
|
|
2
|
+
import { Button } from "@/components/ui/button"
|
|
3
|
+
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
|
4
|
+
import { Input } from "@/components/ui/input"
|
|
5
|
+
import { useRoom } from "@/lib/use-room"
|
|
6
|
+
|
|
7
|
+
/** Open this page in two tabs: messages sent in one appear in the other, through a Durable Object. */
|
|
8
|
+
export function RealtimeDemo() {
|
|
9
|
+
const { messages, status, send } = useRoom("demo")
|
|
10
|
+
const [text, setText] = useState("")
|
|
11
|
+
|
|
12
|
+
const submit = (event: FormEvent) => {
|
|
13
|
+
event.preventDefault()
|
|
14
|
+
if (text.trim() === "") return
|
|
15
|
+
send(text)
|
|
16
|
+
setText("")
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
return (
|
|
20
|
+
<Card>
|
|
21
|
+
<CardHeader>
|
|
22
|
+
<CardTitle>Realtime room</CardTitle>
|
|
23
|
+
<CardDescription>Connection: {status}</CardDescription>
|
|
24
|
+
</CardHeader>
|
|
25
|
+
<CardContent className="space-y-4">
|
|
26
|
+
<ul className="max-h-40 space-y-1 overflow-y-auto text-sm">
|
|
27
|
+
{messages.map((message) => (
|
|
28
|
+
<li key={message.id}>{message.text}</li>
|
|
29
|
+
))}
|
|
30
|
+
</ul>
|
|
31
|
+
<form onSubmit={submit} className="flex gap-2">
|
|
32
|
+
<Input value={text} onChange={(e) => setText(e.target.value)} placeholder="Say hi" />
|
|
33
|
+
<Button type="submit" disabled={status !== "open"}>
|
|
34
|
+
Send
|
|
35
|
+
</Button>
|
|
36
|
+
</form>
|
|
37
|
+
</CardContent>
|
|
38
|
+
</Card>
|
|
39
|
+
)
|
|
40
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { expect, it } from "vitest"
|
|
2
|
+
import {
|
|
3
|
+
isMessageTooLarge,
|
|
4
|
+
isValidRoomId,
|
|
5
|
+
MAX_MESSAGE_BYTES,
|
|
6
|
+
reconnectDelay,
|
|
7
|
+
} from "../src/realtime-limits"
|
|
8
|
+
|
|
9
|
+
it("accepts word and dash room ids up to 64 characters", () => {
|
|
10
|
+
for (const id of ["demo", "room_1", "a-b", "x".repeat(64)]) expect(isValidRoomId(id)).toBe(true)
|
|
11
|
+
})
|
|
12
|
+
|
|
13
|
+
it("rejects empty, long, or unusual room ids", () => {
|
|
14
|
+
for (const id of ["", "x".repeat(65), "a/b", "a b", "../x", "é", "a\n"])
|
|
15
|
+
expect(isValidRoomId(id)).toBe(false)
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
it("measures message size in bytes, not characters", () => {
|
|
19
|
+
expect(isMessageTooLarge("a".repeat(MAX_MESSAGE_BYTES))).toBe(false)
|
|
20
|
+
expect(isMessageTooLarge("a".repeat(MAX_MESSAGE_BYTES + 1))).toBe(true)
|
|
21
|
+
expect(isMessageTooLarge("é".repeat(MAX_MESSAGE_BYTES / 2 + 1))).toBe(true)
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
it("backs off exponentially, jittered, never past 30 seconds", () => {
|
|
25
|
+
expect(reconnectDelay(0, () => 0)).toBe(500)
|
|
26
|
+
expect(reconnectDelay(0, () => 1)).toBe(1000)
|
|
27
|
+
expect(reconnectDelay(3, () => 1)).toBe(8000)
|
|
28
|
+
expect(reconnectDelay(50, () => 1)).toBe(30_000)
|
|
29
|
+
expect(reconnectDelay(50, () => 0)).toBe(15_000)
|
|
30
|
+
for (let attempt = 0; attempt < 40; attempt++)
|
|
31
|
+
expect(reconnectDelay(attempt)).toBeLessThanOrEqual(30_000)
|
|
32
|
+
})
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Limits and pure helpers shared by the room (server) and `useRoom` (browser). No imports, so the
|
|
3
|
+
* client bundle stays free of Effect.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/** Room ids: 1-64 letters, digits, `_` or `-`. */
|
|
7
|
+
export const ROOM_ID_PATTERN = /^[\w-]{1,64}$/
|
|
8
|
+
|
|
9
|
+
export const isValidRoomId = (roomId: string): boolean => ROOM_ID_PATTERN.test(roomId)
|
|
10
|
+
|
|
11
|
+
/** Largest message a client may send, in UTF-8 bytes. */
|
|
12
|
+
export const MAX_MESSAGE_BYTES = 4096
|
|
13
|
+
|
|
14
|
+
/** Most clients connected to one room at a time. */
|
|
15
|
+
export const MAX_ROOM_CONNECTIONS = 100
|
|
16
|
+
|
|
17
|
+
/** Messages `useRoom` keeps in memory. */
|
|
18
|
+
export const MAX_KEPT_MESSAGES = 200
|
|
19
|
+
|
|
20
|
+
const encoder = new TextEncoder()
|
|
21
|
+
|
|
22
|
+
export const isMessageTooLarge = (message: string): boolean =>
|
|
23
|
+
encoder.encode(message).byteLength > MAX_MESSAGE_BYTES
|
|
24
|
+
|
|
25
|
+
const BASE_DELAY_MS = 1000
|
|
26
|
+
const MAX_DELAY_MS = 30_000
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Milliseconds to wait before reconnect number `attempt` (0 for the first): exponential from 1 s,
|
|
30
|
+
* capped at 30 s, with half of it randomised so dropped clients don't all return at once.
|
|
31
|
+
*/
|
|
32
|
+
export const reconnectDelay = (attempt: number, random: () => number = Math.random): number => {
|
|
33
|
+
const ceiling = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** Math.max(0, attempt))
|
|
34
|
+
return Math.round(ceiling / 2 + (random() * ceiling) / 2)
|
|
35
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { Realtime } from "@repo/core"
|
|
2
|
+
import { isValidRoomId } from "@repo/core/realtime-limits"
|
|
3
|
+
import { Effect } from "effect"
|
|
4
|
+
import type { WorkerRoute } from "./routes"
|
|
5
|
+
import { runtime } from "./runtime"
|
|
6
|
+
|
|
7
|
+
const pattern = /^\/ws\/rooms\/([^/]+)$/
|
|
8
|
+
|
|
9
|
+
const decodeRoomId = (encoded: string) => {
|
|
10
|
+
try {
|
|
11
|
+
return decodeURIComponent(encoded)
|
|
12
|
+
} catch {
|
|
13
|
+
return undefined
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* WebSocket upgrades on `/ws/rooms/<roomId>` go to that room's Durable Object. Room ids are 1-64
|
|
19
|
+
* word characters or dashes (400 otherwise); the room caps connections and message size.
|
|
20
|
+
*/
|
|
21
|
+
export const realtimeRoute: WorkerRoute = async (request) => {
|
|
22
|
+
const match = pattern.exec(new URL(request.url).pathname)
|
|
23
|
+
if (match?.[1] === undefined) return undefined
|
|
24
|
+
const roomId = decodeRoomId(match[1])
|
|
25
|
+
if (roomId === undefined || !isValidRoomId(roomId))
|
|
26
|
+
return new Response("Invalid room id", { status: 400 })
|
|
27
|
+
return runtime
|
|
28
|
+
.runPromise(
|
|
29
|
+
Effect.gen(function* () {
|
|
30
|
+
const realtime = yield* Realtime
|
|
31
|
+
return yield* realtime.connect(roomId, request)
|
|
32
|
+
}).pipe(Effect.orElseSucceed(() => new Response("Realtime error", { status: 502 }))),
|
|
33
|
+
)
|
|
34
|
+
.catch((error: unknown) => {
|
|
35
|
+
// the runtime failed to build (a layer is misconfigured)
|
|
36
|
+
console.error("Realtime unavailable:", error)
|
|
37
|
+
return new Response("Server is not configured", { status: 500 })
|
|
38
|
+
})
|
|
39
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { Realtime, RealtimeError } from "@repo/core"
|
|
2
|
+
import { isValidRoomId } from "@repo/core/realtime-limits"
|
|
3
|
+
import { Effect, Layer } from "effect"
|
|
4
|
+
import { RoomNamespace } from "../realtime/Room"
|
|
5
|
+
import { WorkerEnvLive } from "./cloudflare"
|
|
6
|
+
|
|
7
|
+
const fail = (operation: string) => (cause: unknown) => new RealtimeError({ operation, cause })
|
|
8
|
+
|
|
9
|
+
const make = Effect.gen(function* () {
|
|
10
|
+
const namespace = yield* RoomNamespace
|
|
11
|
+
// room ids reach here from URLs and server functions: only accept the documented shape
|
|
12
|
+
const room = (
|
|
13
|
+
operation: string,
|
|
14
|
+
roomId: string,
|
|
15
|
+
): Effect.Effect<ReturnType<typeof namespace.byName>, RealtimeError> =>
|
|
16
|
+
isValidRoomId(roomId)
|
|
17
|
+
? Effect.succeed(namespace.byName(roomId))
|
|
18
|
+
: Effect.fail(new RealtimeError({ operation, cause: `invalid room id: ${roomId}` }))
|
|
19
|
+
return Realtime.of({
|
|
20
|
+
connect: (roomId, request) =>
|
|
21
|
+
room("connect", roomId).pipe(
|
|
22
|
+
Effect.flatMap((stub) => stub.fetch(request).pipe(Effect.mapError(fail("connect")))),
|
|
23
|
+
),
|
|
24
|
+
broadcast: (roomId, message) =>
|
|
25
|
+
room("broadcast", roomId).pipe(
|
|
26
|
+
Effect.flatMap((stub) => stub.broadcast(message).pipe(Effect.mapError(fail("broadcast")))),
|
|
27
|
+
),
|
|
28
|
+
connections: (roomId) =>
|
|
29
|
+
room("connections", roomId).pipe(
|
|
30
|
+
Effect.flatMap((stub) => stub.connections().pipe(Effect.mapError(fail("connections")))),
|
|
31
|
+
),
|
|
32
|
+
})
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
/** `Realtime` on the ROOM Durable Object namespace. */
|
|
36
|
+
export const RealtimeLive = Layer.effect(Realtime, make).pipe(
|
|
37
|
+
Layer.provide(RoomNamespace.layer({ binding: "ROOM" })),
|
|
38
|
+
Layer.provide(WorkerEnvLive),
|
|
39
|
+
)
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { MAX_KEPT_MESSAGES, reconnectDelay } from "@repo/core/realtime-limits"
|
|
2
|
+
import { useCallback, useEffect, useRef, useState } from "react"
|
|
3
|
+
|
|
4
|
+
export interface RoomMessage {
|
|
5
|
+
readonly id: number
|
|
6
|
+
readonly text: string
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export type RoomStatus = "connecting" | "open" | "closed"
|
|
10
|
+
|
|
11
|
+
// answered by Cloudflare without waking the room (see `installKeepalive` in realtime/Room.ts)
|
|
12
|
+
const PING = "effect-cf:ping"
|
|
13
|
+
const PONG = "effect-cf:pong"
|
|
14
|
+
|
|
15
|
+
/** Connects to a room and returns its last 200 messages. Reconnects with exponential backoff and jitter (up to 30 s). */
|
|
16
|
+
export function useRoom(roomId: string) {
|
|
17
|
+
const [messages, setMessages] = useState<ReadonlyArray<RoomMessage>>([])
|
|
18
|
+
const [status, setStatus] = useState<RoomStatus>("connecting")
|
|
19
|
+
const nextId = useRef(0)
|
|
20
|
+
const socket = useRef<WebSocket | null>(null)
|
|
21
|
+
|
|
22
|
+
useEffect(() => {
|
|
23
|
+
let closed = false
|
|
24
|
+
let attempt = 0
|
|
25
|
+
let retry: ReturnType<typeof setTimeout> | undefined
|
|
26
|
+
let ping: ReturnType<typeof setInterval> | undefined
|
|
27
|
+
|
|
28
|
+
const connect = () => {
|
|
29
|
+
setStatus("connecting")
|
|
30
|
+
const scheme = location.protocol === "https:" ? "wss" : "ws"
|
|
31
|
+
const ws = new WebSocket(
|
|
32
|
+
`${scheme}://${location.host}/ws/rooms/${encodeURIComponent(roomId)}`,
|
|
33
|
+
)
|
|
34
|
+
socket.current = ws
|
|
35
|
+
ws.addEventListener("open", () => {
|
|
36
|
+
setStatus("open")
|
|
37
|
+
attempt = 0
|
|
38
|
+
ping = setInterval(() => ws.send(PING), 30_000)
|
|
39
|
+
})
|
|
40
|
+
ws.addEventListener("message", ({ data }: MessageEvent) => {
|
|
41
|
+
if (typeof data === "string" && data !== PONG) {
|
|
42
|
+
const id = nextId.current++
|
|
43
|
+
setMessages((all) => [...all, { id, text: data }].slice(-MAX_KEPT_MESSAGES))
|
|
44
|
+
}
|
|
45
|
+
})
|
|
46
|
+
ws.addEventListener("close", () => {
|
|
47
|
+
clearInterval(ping)
|
|
48
|
+
setStatus("closed")
|
|
49
|
+
if (!closed) retry = setTimeout(connect, reconnectDelay(attempt++))
|
|
50
|
+
})
|
|
51
|
+
}
|
|
52
|
+
connect()
|
|
53
|
+
|
|
54
|
+
return () => {
|
|
55
|
+
closed = true
|
|
56
|
+
clearTimeout(retry)
|
|
57
|
+
clearInterval(ping)
|
|
58
|
+
socket.current?.close()
|
|
59
|
+
}
|
|
60
|
+
}, [roomId])
|
|
61
|
+
|
|
62
|
+
const send = useCallback((message: string) => {
|
|
63
|
+
if (socket.current?.readyState === WebSocket.OPEN) socket.current.send(message)
|
|
64
|
+
}, [])
|
|
65
|
+
|
|
66
|
+
return { messages, status, send }
|
|
67
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
{
|
|
2
|
+
"id": "extras/storage",
|
|
3
|
+
"title": "Storage",
|
|
4
|
+
"description": "Object storage: a Storage service on R2 with Worker-served signed download URLs.",
|
|
5
|
+
"files": [
|
|
6
|
+
{
|
|
7
|
+
"path": "files/storage-security.ts",
|
|
8
|
+
"target": "packages/core/src/storage-security.ts"
|
|
9
|
+
},
|
|
10
|
+
{
|
|
11
|
+
"path": "files/storage-security.test.ts",
|
|
12
|
+
"target": "packages/core/test/storage-security.test.ts"
|
|
13
|
+
},
|
|
14
|
+
{
|
|
15
|
+
"path": "files/core-storage.ts",
|
|
16
|
+
"target": "packages/core/src/storage.ts"
|
|
17
|
+
},
|
|
18
|
+
{
|
|
19
|
+
"path": "files/storage.ts",
|
|
20
|
+
"target": "apps/web/src/server/storage.ts"
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
"path": "files/storage-route.ts",
|
|
24
|
+
"target": "apps/web/src/server/storage-route.ts"
|
|
25
|
+
}
|
|
26
|
+
],
|
|
27
|
+
"dependencies": {},
|
|
28
|
+
"devDependencies": {},
|
|
29
|
+
"envVars": [
|
|
30
|
+
{
|
|
31
|
+
"name": "STORAGE_SIGNING_SECRET",
|
|
32
|
+
"example": "change-me-to-a-long-random-string",
|
|
33
|
+
"description": "HMAC secret for signed download URLs (wrangler secret put STORAGE_SIGNING_SECRET)"
|
|
34
|
+
}
|
|
35
|
+
],
|
|
36
|
+
"requires": [],
|
|
37
|
+
"conflicts": [],
|
|
38
|
+
"transforms": [
|
|
39
|
+
{
|
|
40
|
+
"name": "addExport",
|
|
41
|
+
"args": {
|
|
42
|
+
"file": "packages/core/src/index.ts",
|
|
43
|
+
"export": "*",
|
|
44
|
+
"from": "./storage"
|
|
45
|
+
}
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
"name": "addLayer",
|
|
49
|
+
"args": {
|
|
50
|
+
"file": "apps/web/src/server/layers.ts",
|
|
51
|
+
"import": "StorageLive",
|
|
52
|
+
"from": "./storage",
|
|
53
|
+
"layer": "StorageLive"
|
|
54
|
+
}
|
|
55
|
+
},
|
|
56
|
+
{
|
|
57
|
+
"name": "addArrayItem",
|
|
58
|
+
"args": {
|
|
59
|
+
"file": "apps/web/src/server/routes.ts",
|
|
60
|
+
"name": "workerRoutes",
|
|
61
|
+
"item": "storageRoute",
|
|
62
|
+
"import": "storageRoute",
|
|
63
|
+
"from": "./storage-route"
|
|
64
|
+
}
|
|
65
|
+
},
|
|
66
|
+
{
|
|
67
|
+
"name": "addWranglerBinding",
|
|
68
|
+
"args": {
|
|
69
|
+
"key": "r2_buckets",
|
|
70
|
+
"value": "{\"binding\":\"STORAGE\"}"
|
|
71
|
+
},
|
|
72
|
+
"when": {
|
|
73
|
+
"infra": [
|
|
74
|
+
"none"
|
|
75
|
+
]
|
|
76
|
+
}
|
|
77
|
+
},
|
|
78
|
+
{
|
|
79
|
+
"name": "addImport",
|
|
80
|
+
"args": {
|
|
81
|
+
"file": "infra/alchemy.run.ts",
|
|
82
|
+
"import": "* as Config",
|
|
83
|
+
"from": "effect/Config"
|
|
84
|
+
},
|
|
85
|
+
"when": {
|
|
86
|
+
"infra": [
|
|
87
|
+
"alchemy"
|
|
88
|
+
]
|
|
89
|
+
}
|
|
90
|
+
},
|
|
91
|
+
{
|
|
92
|
+
"name": "addAlchemyResource",
|
|
93
|
+
"args": {
|
|
94
|
+
"name": "storage",
|
|
95
|
+
"code": "const storage = yield* Cloudflare.R2.Bucket(\"Storage\", {\n // preview stages are destroyed with their PR, even when files were uploaded\n forceDestroy: (yield* Alchemy.Stack).stage !== \"prod\",\n})",
|
|
96
|
+
"binding": "STORAGE"
|
|
97
|
+
},
|
|
98
|
+
"when": {
|
|
99
|
+
"infra": [
|
|
100
|
+
"alchemy"
|
|
101
|
+
]
|
|
102
|
+
}
|
|
103
|
+
},
|
|
104
|
+
{
|
|
105
|
+
"name": "addAlchemyResource",
|
|
106
|
+
"args": {
|
|
107
|
+
"name": "storageSigningSecret",
|
|
108
|
+
"code": "const storageSigningSecret = yield* Config.Redacted(\"STORAGE_SIGNING_SECRET\")",
|
|
109
|
+
"binding": "STORAGE_SIGNING_SECRET"
|
|
110
|
+
},
|
|
111
|
+
"when": {
|
|
112
|
+
"infra": [
|
|
113
|
+
"alchemy"
|
|
114
|
+
]
|
|
115
|
+
}
|
|
116
|
+
},
|
|
117
|
+
{
|
|
118
|
+
"name": "addDevVar",
|
|
119
|
+
"args": {
|
|
120
|
+
"name": "STORAGE_SIGNING_SECRET",
|
|
121
|
+
"value": "dev-only-storage-signing-secret-replace-me"
|
|
122
|
+
}
|
|
123
|
+
},
|
|
124
|
+
{
|
|
125
|
+
"name": "appendAgentsSection",
|
|
126
|
+
"args": {
|
|
127
|
+
"id": "storage",
|
|
128
|
+
"content": "## Storage\n\n- Use the `Storage` service from `@repo/core` (put, get, delete, signedUrl, verify); do not touch the R2 binding directly.\n- The implementation is `apps/web/src/server/storage.ts` on the `STORAGE` R2 binding; downloads are served by the Worker route in `storage-route.ts`.\n- Signed URLs are HMAC-signed with the `STORAGE_SIGNING_SECRET` secret (at least 32 characters; the app fails to start without it). Never log or return it.\n- Storage keys are opaque: generate them on the server, never from raw user input. Files are served as attachments with `nosniff`, inline only for raster images."
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
]
|
|
132
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { Context, Data, type Effect, type Option } from "effect"
|
|
2
|
+
|
|
3
|
+
export class StorageError extends Data.TaggedError("StorageError")<{
|
|
4
|
+
readonly operation: string
|
|
5
|
+
readonly cause: unknown
|
|
6
|
+
}> {}
|
|
7
|
+
|
|
8
|
+
export interface StoredObject {
|
|
9
|
+
readonly key: string
|
|
10
|
+
readonly size: number
|
|
11
|
+
readonly contentType: string | undefined
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface StoredFile extends StoredObject {
|
|
15
|
+
/** Streamed from the bucket, not buffered; it can be read once. */
|
|
16
|
+
readonly body: ReadableStream
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** The Storage layer could not be built: a required secret is missing or too weak. */
|
|
20
|
+
export class StorageConfigError extends Data.TaggedError("StorageConfigError")<{
|
|
21
|
+
readonly message: string
|
|
22
|
+
}> {}
|
|
23
|
+
|
|
24
|
+
export interface PutOptions {
|
|
25
|
+
readonly contentType?: string
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface SignedUrlOptions {
|
|
29
|
+
/** Defaults to one hour. */
|
|
30
|
+
readonly expiresInSeconds?: number
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Object storage. The Cloudflare layer is backed by R2.
|
|
35
|
+
*
|
|
36
|
+
* R2 bindings can't presign URLs (that needs S3 API credentials), so `signedUrl` returns a path on
|
|
37
|
+
* this Worker (`/files/<key>?expires=..&signature=..`) that serves the object while the HMAC
|
|
38
|
+
* signature is valid. `verify` checks one (constant-time, rejects expired and malformed ones).
|
|
39
|
+
*
|
|
40
|
+
* Keys are opaque: generate them on the server (for example `crypto.randomUUID()`), never from
|
|
41
|
+
* raw user input, because anyone holding a signed URL can read exactly that key. The Worker serves
|
|
42
|
+
* files as attachments with `nosniff`, and inline only for raster images.
|
|
43
|
+
*/
|
|
44
|
+
export class Storage extends Context.Service<
|
|
45
|
+
Storage,
|
|
46
|
+
{
|
|
47
|
+
readonly put: (
|
|
48
|
+
key: string,
|
|
49
|
+
body: string | Uint8Array,
|
|
50
|
+
options?: PutOptions,
|
|
51
|
+
) => Effect.Effect<StoredObject, StorageError>
|
|
52
|
+
readonly get: (key: string) => Effect.Effect<Option.Option<StoredFile>, StorageError>
|
|
53
|
+
readonly delete: (key: string) => Effect.Effect<void, StorageError>
|
|
54
|
+
readonly signedUrl: (
|
|
55
|
+
key: string,
|
|
56
|
+
options?: SignedUrlOptions,
|
|
57
|
+
) => Effect.Effect<string, StorageError>
|
|
58
|
+
readonly verify: (
|
|
59
|
+
key: string,
|
|
60
|
+
expires: string | null,
|
|
61
|
+
signature: string | null,
|
|
62
|
+
) => Effect.Effect<boolean, StorageError>
|
|
63
|
+
}
|
|
64
|
+
>()("@repo/core/Storage") {}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { Storage } from "@repo/core"
|
|
2
|
+
import { downloadHeaders, parseSignedParams } from "@repo/core/storage-security"
|
|
3
|
+
import { Effect, Option } from "effect"
|
|
4
|
+
import type { WorkerRoute } from "./routes"
|
|
5
|
+
import { runtime } from "./runtime"
|
|
6
|
+
|
|
7
|
+
const prefix = "/files/"
|
|
8
|
+
|
|
9
|
+
const decodeKey = (encoded: string) => {
|
|
10
|
+
try {
|
|
11
|
+
return decodeURIComponent(encoded)
|
|
12
|
+
} catch {
|
|
13
|
+
return undefined
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Serves `/files/<key>?expires=..&signature=..` (see `Storage.signedUrl`) straight from the bucket.
|
|
19
|
+
* Keys are opaque: whoever holds a signed URL can read that key, so never build keys from user input.
|
|
20
|
+
* Malformed URLs get 400, bad or expired signatures 403, a missing signing secret 500.
|
|
21
|
+
*/
|
|
22
|
+
export const storageRoute: WorkerRoute = async (request) => {
|
|
23
|
+
const url = new URL(request.url)
|
|
24
|
+
if (request.method !== "GET" || !url.pathname.startsWith(prefix)) return undefined
|
|
25
|
+
const key = decodeKey(url.pathname.slice(prefix.length))
|
|
26
|
+
const params = parseSignedParams(
|
|
27
|
+
url.searchParams.get("expires"),
|
|
28
|
+
url.searchParams.get("signature"),
|
|
29
|
+
)
|
|
30
|
+
if (key === undefined || key === "" || params === undefined)
|
|
31
|
+
return new Response("Bad request", { status: 400 })
|
|
32
|
+
return runtime
|
|
33
|
+
.runPromise(
|
|
34
|
+
Effect.gen(function* () {
|
|
35
|
+
const storage = yield* Storage
|
|
36
|
+
const valid = yield* storage.verify(key, params.expires, params.signature)
|
|
37
|
+
if (!valid) return new Response("Forbidden", { status: 403 })
|
|
38
|
+
const file = yield* storage.get(key)
|
|
39
|
+
if (Option.isNone(file)) return new Response("Not found", { status: 404 })
|
|
40
|
+
return new Response(file.value.body, {
|
|
41
|
+
headers: downloadHeaders(key, file.value.contentType),
|
|
42
|
+
})
|
|
43
|
+
}).pipe(Effect.orElseSucceed(() => new Response("Storage error", { status: 502 }))),
|
|
44
|
+
)
|
|
45
|
+
.catch((error: unknown) => {
|
|
46
|
+
// the runtime failed to build, e.g. STORAGE_SIGNING_SECRET is missing or too short
|
|
47
|
+
console.error("Storage unavailable:", error)
|
|
48
|
+
return new Response("Storage is not configured", { status: 500 })
|
|
49
|
+
})
|
|
50
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { expect, it } from "vitest"
|
|
2
|
+
import {
|
|
3
|
+
downloadHeaders,
|
|
4
|
+
parseSignedParams,
|
|
5
|
+
signPayload,
|
|
6
|
+
verifyPayload,
|
|
7
|
+
} from "../src/storage-security"
|
|
8
|
+
|
|
9
|
+
const secret = "0123456789abcdef0123456789abcdef"
|
|
10
|
+
const future = String(Math.floor(Date.now() / 1000) + 600)
|
|
11
|
+
const past = String(Math.floor(Date.now() / 1000) - 600)
|
|
12
|
+
|
|
13
|
+
it("accepts a fresh signature", async () => {
|
|
14
|
+
const signature = await signPayload(secret, "a/b.txt", future)
|
|
15
|
+
expect(signature).toMatch(/^[0-9a-f]{64}$/)
|
|
16
|
+
expect(await verifyPayload(secret, "a/b.txt", future, signature)).toBe(true)
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
it("rejects tampered keys, expiry, secrets and signatures", async () => {
|
|
20
|
+
const signature = await signPayload(secret, "a.txt", future)
|
|
21
|
+
expect(await verifyPayload(secret, "b.txt", future, signature)).toBe(false)
|
|
22
|
+
expect(await verifyPayload(secret, "a.txt", String(Number(future) + 1), signature)).toBe(false)
|
|
23
|
+
expect(await verifyPayload("x".repeat(32), "a.txt", future, signature)).toBe(false)
|
|
24
|
+
const flipped = (signature.startsWith("0") ? "1" : "0") + signature.slice(1)
|
|
25
|
+
expect(await verifyPayload(secret, "a.txt", future, flipped)).toBe(false)
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
it("rejects expired signatures even when they are valid", async () => {
|
|
29
|
+
const signature = await signPayload(secret, "a.txt", past)
|
|
30
|
+
expect(await verifyPayload(secret, "a.txt", past, signature)).toBe(false)
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
it("rejects malformed input without throwing", async () => {
|
|
34
|
+
const cases = [
|
|
35
|
+
["1e12", "00"],
|
|
36
|
+
["-5", "00"],
|
|
37
|
+
["12 ", "zz"],
|
|
38
|
+
[future, "not-hex"],
|
|
39
|
+
[future, "abc"],
|
|
40
|
+
[future, ""],
|
|
41
|
+
] as const
|
|
42
|
+
const results = await Promise.all(
|
|
43
|
+
cases.map(([expires, signature]) => verifyPayload(secret, "a.txt", expires, signature)),
|
|
44
|
+
)
|
|
45
|
+
expect(results).toEqual(cases.map(() => false))
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
it("parseSignedParams separates malformed (400) from merely wrong (403)", async () => {
|
|
49
|
+
const signature = await signPayload(secret, "a.txt", future)
|
|
50
|
+
expect(parseSignedParams(future, signature)).toEqual({ expires: future, signature })
|
|
51
|
+
expect(parseSignedParams(null, signature)).toBeUndefined()
|
|
52
|
+
expect(parseSignedParams(future, null)).toBeUndefined()
|
|
53
|
+
expect(parseSignedParams("1e9", signature)).toBeUndefined()
|
|
54
|
+
expect(parseSignedParams(future, "short")).toBeUndefined()
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
it("serves everything as an attachment except raster images", () => {
|
|
58
|
+
const html = downloadHeaders("x/evil.html", "text/html")
|
|
59
|
+
expect(html["content-disposition"]).toBe('attachment; filename="evil.html"')
|
|
60
|
+
expect(html["x-content-type-options"]).toBe("nosniff")
|
|
61
|
+
expect(downloadHeaders("logo.svg", "image/svg+xml")["content-disposition"]).toContain(
|
|
62
|
+
"attachment",
|
|
63
|
+
)
|
|
64
|
+
expect(downloadHeaders("a.png", "image/png")["content-disposition"]).toBe("inline")
|
|
65
|
+
expect(downloadHeaders("a.png", "image/png; charset=binary")["content-disposition"]).toBe(
|
|
66
|
+
"inline",
|
|
67
|
+
)
|
|
68
|
+
expect(downloadHeaders('we"ird\r\n.bin', undefined)["content-disposition"]).toBe(
|
|
69
|
+
'attachment; filename="we_ird__.bin"',
|
|
70
|
+
)
|
|
71
|
+
})
|