Skip to content
LogoLogo

Bind DPoP keys

An app binds its tokens to a DPoP key, and an API verifies a proof of the DPoP key with each request.

Overview

With a DPoP key on the instance, Tempo ID binds the app's tokens to it (DPoP, RFC 9449). The API's verifier checks each request's proof against the DPoP key that the token names, and the API refuses a repeated proof itself.

The demo calls an API route of the site with a bound access token and a proof, then repeats the proof, which the route refuses with 401.

Bind a DPoP keyDemo

Walkthrough

The steps add a DPoP key to the app and the API of Authenticate requests.

Bind the tokens to a DPoP keyClient

The dpop plugin gives the instance a DPoP key that the page cannot export. The instance sends a proof with each token request, and Tempo ID binds the session's tokens to the key. Tokens refresh only with the key that bound them, so the plugin keeps it in IndexedDB, beside the session.

tempo.config.ts
import { Accounts } from 'accounts'
import { dpop } from 'accounts/plugins'
import { react } from 'accounts/react'
 
export const accounts = Accounts.create({
  plugins: [await dpop(), react()], 
})

Call the APIClient

session.fetch sends a bound access token with the DPoP scheme and a new proof, so the call of the app does not change.

import { useState } from 'react'
import { accounts } from './tempo.config.js'
 
export function App() {
  const { isPending, session } = accounts.useSession()
  const [userId, setUserId] = useState<string>()
 
  async function call() {
    const response = await accounts.session.fetch({
      url: 'https://api.example/me',
    })
    const body = (await response.json()) as { userId: string }
    setUserId(body.userId)
  }
 
  if (isPending) return <p>Checking your session…</p>
  if (!session)
    return (
      <button onClick={() => accounts.dialog.signIn()} type="button">
        Sign in
      </button>
    )
  return (
    <>
      <button onClick={call} type="button">
        Call the API
      </button>
      {userId && <p>The API read the user {userId}.</p>}
    </>
  )
}

Verify each proofServer

In the API, tokens.verifyAccessToken checks the proof of a bound token against the DPoP key that the token names, over the method and the URL of the request. It reads the DPoP header and the authorization scheme itself, so the instance does not change. It returns undefined for a bound token without a valid proof, or with the Bearer scheme.

server.ts
import { Accounts } from 'accounts'
import { tokens } from 'accounts/plugins'
 
const accounts = Accounts.create({
  clientId: 'https://app.example',
  plugins: [tokens()],
})

Refuse a repeated proofServer

tokens.verifyAccessToken accepts a proof again within its window of 5 minutes. The API thus records the ID of each proof until the proof expires, and refuses a recorded one. Here Redis records each ID in one atomic step.

server.ts
import { Accounts } from 'accounts'
import { tokens } from 'accounts/plugins'
import { createClient } from 'redis'
 
const redis = await createClient({ url: process.env.REDIS_URL }).connect()
 
const accounts = Accounts.create({
  clientId: 'https://app.example',
  plugins: [tokens()],
})
 
export default {
  async fetch(request: Request) {
    const token = await accounts.tokens.verifyAccessToken(request)
    if (!token)
      return Response.json({ error: 'invalid_token' }, { status: 401 })
 
    if (token.proof) {
      // `NX` sets the ID only if Redis holds none, and returns `null` otherwise.
      const first = await redis.sendCommand([
        'SET',
        `dpop:${token.proof.id}`,
        '1',
        'NX',
        'PXAT',
        String(token.proof.expiresAt),
      ])
      if (!first)
        return Response.json({ error: 'invalid_dpop_proof' }, { status: 401 })
    }
 
    return Response.json({ userId: token.userId })
  },
}

A backend with the backend plugin and its accessToken option verifies each proof too, as Use session cookies shows. Its session.get returns the token with its proof, which the backend records in the same way.

The plugin checks each proof against the URL of the request. Behind a proxy that terminates TLS, accessToken takes the public origin as url, as the tokens plugin does.

server.ts
import { Accounts, Store } from 'accounts'
import { backend } from 'accounts/plugins'
 
const accounts = Accounts.create({
  clientId: 'https://app.example',
  plugins: [
    backend({
      accessToken: { url: 'https://api.example' }, 
      store: Store.memory(),
    }),
  ],
})

Use cases

Each use case sets one option of the dpop plugin, or the DPoP key of the instance itself.

Keep the DPoP key in the app's store

The store option names where the DPoP key stays across runs. An instance with its own store passes the same store, so the DPoP key stays beside the session, such as for a CLI.

tempo.config.ts
import { Accounts, Store } from 'accounts'
import { device, dpop } from 'accounts/plugins'
 
// A file in the user's home directory, which only the user reads.
const store = Store.file('~/.acme/store.json')
 
export const accounts = Accounts.create({
  chain: 'testnet',
  clientId: 'cli:acme-example',
  plugins: [
    device({
      onCode: (code) =>
        console.log(
          `Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`,
        ),
    }),
    await dpop({ store }), 
  ],
  store, 
})

Outside a browser, the wagmi connector's reconnect skips such a session, and its connect signs in again.

Set the DPoP key of the instance

The instance's dpop sets the DPoP key directly, and wins over the plugin's. A DPoP key of Dpop.create lasts as long as the process, so a session that it binds refreshes only in that process.

tempo.config.ts
import { Accounts } from 'accounts'
import { Dpop } from 'accounts/internal'
 
export const accounts = Accounts.create({
  chain: 'testnet',
  dpop: await Dpop.create(), 
})

Next steps