Skip to content
Source
Sign inSign up

Build an app

Skills, MCP and apps / Apps and webhooks

Build an app

You want your service to react when someone opens a pull request on TanStack Source, and to show its result there. An app hears about the pull request, proves that the message came from Source, and writes back with limited rights.

4 min read

In this guide, you build a small app on Cloudflare Workers. When a pull request opens, the app gets a signed webhook. Then it writes a card on the pull request, with a pending status, then a success status.

You need:

  • A TanStack Source account, and a repository that you own (here alice/app).
  • A Cloudflare account and pnpm.

1. Write the Worker

Make the project:

mkdir hello-app
cd hello-app
pnpm init
pnpm add -D wrangler

Create wrangler.jsonc:

{
  "name": "hello-app",
  "main": "src/index.ts",
  "compatibility_date": "2026-11-01",
  "vars": {
    "SOURCE_URL": "https://source.tanstack.com"
  }
}

Create src/index.ts:

interface Env {
  SOURCE_URL: string
  /** The app secret, tsk_... */
  APP_SECRET: string
  /** The webhook secret. */
  WEBHOOK_SECRET: string
}

/** The fields of a pull_request webhook that this app reads. */
interface PullWebhook {
  event: string
  action?: string
  repository: { id: string; full_name: string }
  pull_request: { number: number; title: string; head_sha: string }
  installation: { id: string }
}

const encoder = new TextEncoder()

/** Whether `header` (sha256=<hex>) is the HMAC-SHA256 of `body` under `secret`. The check takes constant time. */
async function isSigned(secret: string, body: string, header: string | null) {
  const hex = header?.match(/^sha256=([0-9a-f]{64})$/)?.[1]
  if (hex === undefined) return false
  const mac = new Uint8Array(hex.match(/../g)!.map((pair) => parseInt(pair, 16)))
  const key = await crypto.subtle.importKey('raw', encoder.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['verify'])
  return crypto.subtle.verify('HMAC', key, mac, encoder.encode(body))
}

/** Calls the REST API of the forge with `token`, and gives the JSON answer. */
async function source(env: Env, method: string, path: string, token: string, body?: unknown) {
  const response = await fetch(`${env.SOURCE_URL}/api/v1/${path}`, {
    method,
    headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
    body: body === undefined ? undefined : JSON.stringify(body),
  })
  if (!response.ok) throw new Error(`${method} ${path} answered ${response.status}: ${await response.text()}`)
  return (await response.json()) as Record<string, unknown>
}

/** Trades the app secret for an install token of `installId`, good for one hour. */
async function installToken(env: Env, installId: string) {
  const answer = await source(env, 'POST', `app/installs/${installId}/token`, env.APP_SECRET)
  return String(answer.token)
}

/** Writes the card of the pull request: a pending status, a section, then a success status. */
async function onPull(env: Env, hook: PullWebhook) {
  const pull = hook.pull_request
  const token = await installToken(env, hook.installation.id)
  const card = `repos/${hook.repository.full_name}/pulls/${pull.number}/app-card`
  const sha = pull.head_sha
  await source(env, 'PUT', `${card}/status`, token, { sha, state: 'pending', text: 'Checking the pull request' })
  await source(env, 'PUT', `${card}/sections/summary`, token, {
    title: 'Hello from hello-app',
    markdown: `I read pull request #${pull.number} at commit \`${sha.slice(0, 7)}\`.`,
    buttons: [],
  })
  await source(env, 'PUT', `${card}/status`, token, { sha, state: 'success', text: 'All good' })
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const url = new URL(request.url)

    // Source sends the person here after they install the app, with a one-use setup code.
    if (request.method === 'GET' && url.pathname === '/setup') {
      const code = url.searchParams.get('code')
      if (code === null) return new Response('The setup code is missing', { status: 400 })
      const install = await source(env, 'POST', 'app/setup-codes/redeem', env.APP_SECRET, { code })
      return new Response(`hello-app is installed. Install ${install.installId}, account ${install.accountId}.`)
    }

    if (request.method === 'POST' && url.pathname === '/webhook') {
      const body = await request.text()
      const isFromSource = await isSigned(env.WEBHOOK_SECRET, body, request.headers.get('x-source-signature-256'))
      if (!isFromSource) return new Response('The signature is wrong', { status: 401 })
      const hook = JSON.parse(body) as PullWebhook
      const isNewHead = hook.event === 'pull_request' && (hook.action === 'opened' || hook.action === 'synchronize')
      if (!isNewHead) return new Response('ignored')
      try {
        await onPull(env, hook)
        return new Response('done')
      } catch (error) {
        console.error(error)
        // A 5xx answer makes Source send the webhook again later.
        return new Response('failed', { status: 500 })
      }
    }

    return new Response('Not found', { status: 404 })
  },
}

The Worker has two routes:

  • GET /setup: trades the setup code for the install, once.
  • POST /webhook: checks the signature. Then it writes the card for each pull_request webhook with the action opened or synchronize (new commits on the head).

The body names the repository as repository.full_name (owner/name), so the app builds its REST paths from it. installation.id names the install, which gives the token. Each field of the body is in Webhooks.

2. Deploy the Worker

pnpm wrangler deploy

Wrangler prints the URL of the Worker, like https://hello-app.alice.workers.dev. You need it in the next step.

3. Register the app

  1. On TanStack Source, open Settings, then Apps (/settings/apps).
  2. Click New app.
  3. Fill in the form with the values of the table below.
  4. Click Register app.
  5. Copy the app secret (tsk_...) and the webhook secret. The page shows each one once.
FieldValue
OwnerYour account. A private app installs only on its owner.
Slughello-app. The slug names the bot of the app (hello-app[app]) and its status (app:hello-app). It never changes.
Setup URLhttps://hello-app.alice.workers.dev/setup
Webhook URLhttps://hello-app.alice.workers.dev/webhook. It must use https and a public host.
EventsPull requests (pull_request). Every app also gets installation and app_card, with no pick.
Permissionspulls:read and surfaces:write.

4. Give the Worker its secrets

Run each command, and paste the secret when wrangler asks for it:

pnpm wrangler secret put APP_SECRET
pnpm wrangler secret put WEBHOOK_SECRET

5. Install the app

  1. Open the page of the app, /apps/hello-app, and click Install.
  2. Pick your account, then Only picked repositories, then alice/app.
  3. Click Install hello-app.

Source sends you to your setup URL with ?code=...&install=.... The Worker redeems the code, and the page says hello-app is installed.

For each step of the install, see Install an app.

6. Open a pull request

Open a pull request on alice/app, then open its Conversation tab. The hello-app card shows the section Hello from hello-app, and the status All good. The Checks tab shows app:hello-app with success.

Tip

When the card does not come, open /settings/apps/hello-app. Under Deliveries, each webhook shows its status, its tries and the last error. See Webhooks.

What works now

  • Your Worker gets a signed webhook when a pull request opens or gets a new head.
  • It checks the signature, gets an install token, and writes its own card and status.
  • The person who installs the app lands on your setup page, and your app learns the install.

Next: let your app trust uploads from CI with Trust a CI job.

Later: secrets and rotation

App secret. An app has at most two app secrets. The secret is never a login: it works only on the routes of the app server. To rotate it:

  1. Click New secret on /settings/apps/hello-app.
  2. Put the new secret in the Worker.
  3. Delete the old secret.

Webhook secret. Click Rotate to make a new one. The old one stops at once, so update the Worker right after.

Install token. A token lives one hour. An app can ask for 60 tokens a minute. When your app gets many webhooks, keep each token for up to an hour. Do not ask for a new token for each webhook.

To take all access away from the app, see Delete an app.

The routes of the app server

These routes take the app secret in Authorization: Bearer tsk_.... They are REST only.

RouteWhat it does
POST /api/v1/app/installs/<install>/tokenAn install token: { token, expiresAt, actions, repos }. repos is all, or the owner/name of each picked repository.
POST /api/v1/app/setup-codes/redeem ({ "code" }){ installId, accountId, installedBy }. A code works once, for 10 minutes.
GET /api/v1/app/deliveriesThe newest 100 deliveries.
POST /api/v1/app/deliveries/<id>/redeliverSends a delivery again.

With the install token, the app calls the normal REST API as its bot, with the permissions of the install. The card routes are in Cards and statuses.