Canica

Inbox

Feedback from any website, posted to an endpoint with a token, read live in the app.

endpoints (POST and GET)secretsa JSON exporttesting endpoints

12 files, 440 lines. Source on GitHub. To run it, from a clone of the repository: pnpm install, then pnpm dev in examples/inbox.

Files

server/index.ts88 lines
import { boolean, desc, eq, id, mutation, query, sameSignature, schema, table } from "canica/server"
import { messageText, pageUrl, senderEmail, senderName } from "../shared/fields.ts"

/**
 * An inbox for feedback from any website: a form on your site (or a script, Zapier, a cron) posts to
 * `POST /api/feedback` with `Authorization: Bearer <INBOX_TOKEN>`, and the app shows the messages live to its owner.
 * `GET /api/feedback` gives them back as JSON (with the same token), for a spreadsheet or another app.
 *
 * Set the token once: `canica secrets set INBOX_TOKEN` (dev: `INBOX_TOKEN=…` in `.canica/secrets`).
 */
export const { app, Db, tables } = schema({
  messages: table({
    text: messageText,
    name: senderName.optional(),
    email: senderEmail.optional(),
    page: pageUrl.optional(),
    read: boolean().default(false),
  }).index("by_read", ["read"]),
})
const { messages } = tables

/** What the endpoint takes: only `text` is required. */
const incoming = { text: messageText, name: senderName.optional(), email: senderEmail.optional(), page: pageUrl.optional() }

export default app({
  name: "Inbox",
  icon: "inbox",
  // Only the owner (and the people they add) read the messages; the endpoint is how everyone else writes.
  access: "private",
  queries: {
    messages: query({ unread: boolean().default(false) }, function* ({ unread }) {
      const db = yield* Db
      return yield* db
        .select()
        .from(messages)
        .where(unread ? eq(messages.read, false) : undefined)
        .orderBy(desc(messages.createdAt))
        .limit(200)
    }),
    unreadCount: query(function* () {
      const db = yield* Db
      return yield* db.count(messages, eq(messages.read, false))
    }),
  },
  mutations: {
    setRead: mutation({ id: id("messages"), read: boolean() }, function* ({ id, read }) {
      const db = yield* Db
      yield* db.get(messages, id)
      yield* db.update(messages).set({ read }).where(eq(messages.id, id))
    }),
    markAllRead: mutation(function* () {
      const db = yield* Db
      yield* db.update(messages).set({ read: true }).where(eq(messages.read, false))
    }),
    remove: mutation({ id: id("messages") }, function* ({ id }) {
      const db = yield* Db
      yield* db.get(messages, id)
      yield* db.delete(messages).where(eq(messages.id, id))
    }),
  },
  internal: {
    // Only the endpoint (and `canica run receive '{"text":"…"}'`) adds messages.
    receive: mutation(incoming, function* (message) {
      const db = yield* Db
      const [row] = yield* db.insert(messages).values(message).returning({ id: messages.id })
      return row!.id
    }),
  },
  endpoints: (endpoint) => {
    /** The caller sent `Authorization: Bearer <INBOX_TOKEN>` (compared in constant time). */
    const authorized = (ctx: { readonly secrets: Readonly<Record<string, string>> }, headers: Headers) =>
      sameSignature(headers.get("authorization"), `Bearer ${ctx.secrets.INBOX_TOKEN}`)
    return {
      receive: endpoint.post("/api/feedback", function* (ctx, request) {
        if (!authorized(ctx, request.headers)) return Response.json({ error: "Send Authorization: Bearer <token>." }, { status: 401 })
        const message = yield* request.json(incoming) // a body that does not match answers 400 with the issues
        const id = yield* ctx.runMutation("receive", message)
        return Response.json({ id }, { status: 201 })
      }),
      export: endpoint.get("/api/feedback", function* (ctx, request) {
        if (!authorized(ctx, request.headers)) return Response.json({ error: "Send Authorization: Bearer <token>." }, { status: 401 })
        const rows = yield* ctx.runQuery("messages", { unread: request.query.get("unread") === "1" })
        return rows.map(({ id, text, name, email, page, read, createdAt }) => ({ id, text, name, email, page, read, at: new Date(createdAt).toISOString() }))
      }),
    }
  },
})
server/seed.ts13 lines
import { defineSeed } from "canica/testing"
import app from "./index.ts"

// Sample data for `canica storyboard`: messages as the endpoint would add them (`receive` is internal), one read.
export default defineSeed(app, ({ as, run, advance }) => {
  run("receive", { text: "The pricing page doesn't say whether the yearly plan renews automatically.", name: "Ana", email: "ana@example.com", page: "https://example.com/pricing" })
  advance(40 * 60_000)
  run("receive", { text: "Love the new dark mode!", email: "marc@example.com" })
  advance(5 * 60_000)
  const id = run("receive", { text: "Signup button does nothing on Safari 17.", name: "Lucía", page: "https://example.com/signup" }) as string
  as("viewer").mutationOk("setRead", { id: id as never, read: true })
})
shared/fields.ts9 lines
import { string } from "canica/fields"

/** Field schemas shared by the server (args, tables, the endpoint's body) and the UI. */
export const messageText = string().trim().min(1).max(4000)
export const senderName = string().trim().max(120)
export const senderEmail = string().trim().lower().email()
/** The page the message was sent from (a URL, as the website says it). */
export const pageUrl = string().trim().max(2000)
src/main.tsx6 lines
import { start } from "canica/client"
import { routes } from "./routes.gen.ts"
import "./styles.css"

start(routes)
src/routes/__root.tsx15 lines
import { layout, Link } from "canica/client"
import { AppHeader, PageContainer, UserMenu } from "canica/ui"

export default layout({
  view: ({ children }) => (
    <div className="min-h-screen">
      <AppHeader brand={<Link to="/">Inbox</Link>}>
        <UserMenu />
      </AppHeader>
      {/* Frames every page, loading and error states included. */}
      <PageContainer>{children}</PageContainer>
    </div>
  ),
})
src/routes/404.tsx21 lines
import { Link, page } from "canica/client"
import { Button, EmptyBlock, PageContainer } from "canica/ui"

/** Shown for a URL that matches no route, or whose params are invalid. */
export default page({
  title: "Not found",
  view: () => (
    <PageContainer>
      <EmptyBlock
        title="This page does not exist"
        description="The link may be wrong, or what it pointed to was deleted."
        action={
          <Button asChild>
            <Link to="/">Back home</Link>
          </Button>
        }
      />
    </PageContainer>
  ),
})
src/routes/index.tsx99 lines
import { page, useMutation, useQuery, useRelativeFormatter } from "canica/client"
import {
  ActionStatus,
  Badge,
  Button,
  confirm,
  EmptyBlock,
  ErrorState,
  Item,
  ItemActions,
  ItemContent,
  ItemDescription,
  ItemTitle,
  List,
  Loading,
  PageHeader,
} from "canica/ui"
import { CheckCheckIcon, SendIcon } from "canica/icons"
import { HowToSend } from "../components/how-to-send.tsx"

export default page({
  title: "Inbox",
  view: () => {
    const messages = useQuery("messages", {})
    const unread = useQuery("unreadCount")
    const setRead = useMutation("setRead")
    const markAllRead = useMutation("markAllRead")
    const remove = useMutation("remove")
    const ago = useRelativeFormatter()
    const howTo = (
      <Button variant="outline" aria-haspopup="dialog" onClick={() => void HowToSend.open()}>
        <SendIcon />
        How to send
      </Button>
    )
    const unreadCount = unread.match({ loading: () => 0, failure: () => 0, success: (n) => n })

    return (
      <section className="flex flex-col gap-6">
        <PageHeader
          title="Inbox"
          description={unreadCount === 0 ? "Everything read." : `${unreadCount} unread`}
          actions={
            <>
              {howTo}
              <Button disabled={unreadCount === 0 || markAllRead.waiting} onClick={() => void markAllRead()}>
                <CheckCheckIcon />
                Mark all read
              </Button>
            </>
          }
        />
        <ActionStatus status={markAllRead.status} />
        {messages.match({
          loading: () => <Loading shape="list" />,
          failure: (error) => <ErrorState error={error} />,
          success: (list) =>
            list.length === 0 ? (
              <EmptyBlock title="No messages yet" description="Messages your website posts to /api/feedback show up here, live." action={howTo} />
            ) : (
              <List>
                {list.map((m) => (
                  <Item key={m.id} variant={m.read ? "default" : "outline"}>
                    <ItemContent>
                      <ItemTitle>
                        {m.name ?? m.email ?? "Anonymous"}
                        {!m.read && <Badge>New</Badge>}
                      </ItemTitle>
                      <ItemDescription>{m.text}</ItemDescription>
                      <ItemDescription>
                        {[m.email && m.name ? m.email : null, m.page, ago(m.createdAt)].filter(Boolean).join(" · ")}
                      </ItemDescription>
                    </ItemContent>
                    <ItemActions>
                      <Button variant="ghost" size="sm" onClick={() => void setRead({ id: m.id, read: !m.read })}>
                        {m.read ? "Mark unread" : "Mark read"}
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        aria-haspopup="dialog"
                        onClick={async () => {
                          const r = await confirm({ title: "Delete this message?", description: "It cannot be undone.", confirm: "Delete" })
                          if (r._tag === "Done") await remove({ id: m.id })
                        }}
                      >
                        Delete
                      </Button>
                    </ItemActions>
                  </Item>
                ))}
              </List>
            ),
        })}
      </section>
    )
  },
})
src/components/how-to-send.tsx30 lines
import { Button, CopyButton, modal, ModalActions, ModalText, ModalTitle } from "canica/ui"

/** How a website (or a script) sends a message: the endpoint, its token, an example. */
export const HowToSend = modal()(() => {
  const close = HowToSend.useClose()
  const command = `curl -X POST ${location.origin}/api/feedback \\
  -H "Authorization: Bearer $INBOX_TOKEN" \\
  -H "Content-Type: application/json" \\
  -d '{"text": "Love it!", "email": "ana@example.com", "page": "https://example.com/pricing"}'`
  return (
    <>
      <ModalTitle>Send messages here</ModalTitle>
      <ModalText>
        Post JSON to <code>/api/feedback</code> with the token from <code>canica secrets set INBOX_TOKEN</code>. Only{" "}
        <code>text</code> is required; <code>name</code>, <code>email</code> and <code>page</code> are optional.
      </ModalText>
      <pre className="overflow-x-auto rounded-md border bg-muted p-3 text-xs">{command}</pre>
      <ModalText>
        <code>GET /api/feedback</code> (add <code>?unread=1</code> for the unread ones) returns them as JSON, with the same token.
      </ModalText>
      <ModalActions>
        <CopyButton value={command}>Copy command</CopyButton>
        <Button type="button" onClick={() => close()}>
          Done
        </Button>
      </ModalActions>
    </>
  )
})
src/styles.css4 lines
@import "tailwindcss";
@import "canica/ui/theme.css";
@import "./theme.css";
src/theme.css60 lines
/*
 * App theme: shadcn preset b2LoZ7cKjg (style maia, amber on neutral, font noto-serif, radius none).
 * Generated by `canica theme`. Tweak it visually at https://ui.shadcn.com/create?preset=b2LoZ7cKjg
 * and apply the new code with `canica theme <code>`, or edit these tokens by hand.
 */
:root {
  --background: oklch(1 0 0);
  --foreground: oklch(0.145 0 0);
  --card: oklch(1 0 0);
  --card-foreground: oklch(0.145 0 0);
  --popover: oklch(1 0 0);
  --popover-foreground: oklch(0.145 0 0);
  --primary: oklch(0.555 0.163 48.998);
  --primary-foreground: oklch(0.987 0.022 95.277);
  --secondary: oklch(0.967 0.001 286.375);
  --secondary-foreground: oklch(0.21 0.006 285.885);
  --muted: oklch(0.97 0 0);
  --muted-foreground: oklch(0.556 0 0);
  --accent: oklch(0.97 0 0);
  --accent-foreground: oklch(0.205 0 0);
  --destructive: oklch(0.577 0.245 27.325);
  --border: oklch(0.922 0 0);
  --input: oklch(0.922 0 0);
  --ring: oklch(0.708 0 0);
  --chart-1: oklch(0.811 0.111 293.571);
  --chart-2: oklch(0.606 0.25 292.717);
  --chart-3: oklch(0.541 0.281 293.009);
  --chart-4: oklch(0.491 0.27 292.581);
  --chart-5: oklch(0.432 0.232 292.759);
  --radius: 0;
  --font-body: "Noto Serif", ui-sans-serif, system-ui, sans-serif;
  --font-display: "DM Sans", ui-serif, Georgia, serif;
}

.dark {
  --background: oklch(0.145 0 0);
  --foreground: oklch(0.985 0 0);
  --card: oklch(0.205 0 0);
  --card-foreground: oklch(0.985 0 0);
  --popover: oklch(0.205 0 0);
  --popover-foreground: oklch(0.985 0 0);
  --primary: oklch(0.473 0.137 46.201);
  --primary-foreground: oklch(0.987 0.022 95.277);
  --secondary: oklch(0.274 0.006 286.033);
  --secondary-foreground: oklch(0.985 0 0);
  --muted: oklch(0.269 0 0);
  --muted-foreground: oklch(0.708 0 0);
  --accent: oklch(0.269 0 0);
  --accent-foreground: oklch(0.985 0 0);
  --destructive: oklch(0.704 0.191 22.216);
  --border: oklch(1 0 0 / 10%);
  --input: oklch(1 0 0 / 15%);
  --ring: oklch(0.556 0 0);
  --chart-1: oklch(0.811 0.111 293.571);
  --chart-2: oklch(0.606 0.25 292.717);
  --chart-3: oklch(0.541 0.281 293.009);
  --chart-4: oklch(0.491 0.27 292.581);
  --chart-5: oklch(0.432 0.232 292.759);
}
server/index.test.ts56 lines
import { describe, expect, it } from "vitest"
import { testApp } from "canica/testing"
import app from "./index.ts"

const token = "secret-token"
const post = (body: unknown, auth = `Bearer ${token}`) => ({
  method: "POST",
  body: JSON.stringify(body),
  headers: { authorization: auth, "content-type": "application/json" },
})

describe("the endpoint", () => {
  it("adds a message with the right token, and the inbox shows it live", async () => {
    const t = testApp(app, { secrets: { INBOX_TOKEN: token } })
    const res = await t.fetch("/api/feedback", post({ text: " Love it! ", email: "Ana@Example.com" }))
    expect(res.status).toBe(201)
    const { id } = await res.json()
    expect(t.as("owner").queryOk("messages", {})).toMatchObject([{ id, text: "Love it!", email: "ana@example.com", read: false }])
    expect(t.as("owner").queryOk("unreadCount")).toBe(1)
  })

  it("refuses a missing or wrong token, and a body without text", async () => {
    const t = testApp(app, { secrets: { INBOX_TOKEN: token } })
    expect((await t.fetch("/api/feedback", post({ text: "hi" }, "Bearer nope"))).status).toBe(401)
    expect((await t.fetch("/api/feedback", { method: "POST", body: "{}" })).status).toBe(401)
    const bad = await t.fetch("/api/feedback", post({ email: "not an email" }))
    expect(bad.status).toBe(400)
    expect((await bad.json()).error._tag).toBe("InvalidArgs")
    expect(t.as("owner").queryOk("messages", {})).toEqual([])
  })

  it("exports them as JSON, the unread ones with ?unread=1", async () => {
    const t = testApp(app, { secrets: { INBOX_TOKEN: token } })
    const first = (await (await t.fetch("/api/feedback", post({ text: "one" }))).json()).id
    await t.fetch("/api/feedback", post({ text: "two", page: "https://example.com" }))
    t.as("owner").mutationOk("setRead", { id: first, read: true })
    const auth = { headers: { authorization: `Bearer ${token}` } }
    expect(await (await t.fetch("/api/feedback", auth)).json()).toMatchObject([{ text: "two", page: "https://example.com", read: false }, { text: "one", read: true }])
    expect(await (await t.fetch("/api/feedback?unread=1", auth)).json()).toMatchObject([{ text: "two" }])
    expect((await t.fetch("/api/feedback")).status).toBe(401)
  })
})

describe("the inbox", () => {
  it("marks messages read, all at once, and deletes them", async () => {
    const t = testApp(app, { secrets: { INBOX_TOKEN: token } })
    for (const text of ["a", "b"]) await t.fetch("/api/feedback", post({ text }))
    const owner = t.as("owner")
    owner.mutationOk("markAllRead")
    expect(owner.queryOk("unreadCount")).toBe(0)
    const [b] = owner.queryOk("messages", {})
    owner.mutationOk("remove", { id: b!.id })
    expect(owner.queryOk("messages", {}).map((m) => m.text)).toEqual(["a"])
  })
})
src/app.test.tsx39 lines
import { describe, it } from "vitest"
import { as, click, meanwhile, notSee, role, scene, see, testApp, text, visit, within } from "canica/testing"
import app from "../server/index.ts"
import { routes } from "./routes.gen.ts"

const token = "secret-token"

describe("inbox", () => {
  it("messages posted to the endpoint appear live; reading and deleting them", async () => {
    const t = testApp(app, { secrets: { INBOX_TOKEN: token } })
    const send = (body: object) =>
      t.fetch("/api/feedback", { method: "POST", body: JSON.stringify(body), headers: { authorization: `Bearer ${token}` } })
    await scene(t, routes,
      as("owner"),
      visit("/"),
      see(text("No messages yet")),
      meanwhile(() => send({ text: "Signup button does nothing on Safari.", name: "Lucía" })),
      see(text("Signup button does nothing on Safari.")),
      see(text("1 unread")),
      click(role("button", { name: "Mark read" })),
      see(text("Everything read.")),
      click(role("button", { name: "Delete" })),
      within(role("alertdialog"), click(role("button", { name: "Delete" }))),
      see(text("No messages yet")),
    )
  })

  it("explains how to send messages", async () => {
    const t = testApp(app)
    await scene(t, routes,
      as("owner"),
      visit("/"),
      click(role("button", { name: "How to send" })),
      within(role("dialog"), see(text(/Post JSON to/)), click(role("button", { name: "Done" }))),
      notSee(role("dialog")),
    )
  })
})