Pay for users
An API pays for a user with an access key that it holds for one connection.
Overview
A connection is an OAuth grant of one user, through one app, to one API, such as a paid MCP server. The API, not the app, holds the access key, and pays from the user's Tempo Account within the limits that the user approved. The app holds only an access token for the API.
Tempo ID discovers the API from metadata that the API publishes, with no registration. These terms name its parts:
| Term | Meaning |
|---|---|
| Discovered resource | An API that Tempo ID knows by its RFC 8707 identifier, such as https://api.example/pay |
| Access key policy | The API's OAuth app, and the limits of each access key that the API holds |
| Connection | One user's approval of one app for the resource |
The approval reaches the API inside the access token. The API redeems the token at Tempo ID with its own client authentication, as in a token exchange, for the key authorization of an access key that it generated:
The demo signs a user in for this site's API, which then pays 1 OUSD on Tempo testnet with the access key that it holds for the connection.
Walkthrough
The steps build the app that opens a connection, then the API with Hono.
Sign the user in for the APIClient
In the app, name the resource in the sign-in. The user's approval of the policy's limits authorizes the API's access key.
import { accounts } from './tempo.config.js'
export function App() {
const { session } = accounts.useSession()
if (!session)
return (
<button
onClick={() =>
accounts.dialog.signIn({
mode: 'popup',
resource: 'https://api.example/pay',
})
}
type="button"
>
Sign in with Tempo
</button>
)
return <p>Signed in as {session.user.email}</p>
}import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
accessKey: false,
chain: 'testnet',
plugins: [react()],
})Tempo ID approves a connection only on its own page, so the sign-in sets mode to 'popup', which opens it in a window. Each access token of the session names the API as its audience. With accessKey set to false, the app requests no access key of its own.
Call the APIClient
session.fetch sends the request with the session's access token.
import { accounts } from './tempo.config.js'
export function Pay() {
return (
<button
onClick={async () => {
const response = await accounts.session.fetch({
init: { method: 'POST' },
url: 'https://api.example/pay',
})
console.log(await response.json())
}}
type="button"
>
Pay 1 OUSD
</button>
)
}import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
accessKey: false,
chain: 'testnet',
plugins: [react()],
})Store the connectionsServer
connections names the resource and the store of the connections. Its metadata names the access key policy and the private key of the API's app, an ES256 JWK with a kid that only the API's server holds.
The private key is a long-lived secret, like a client secret. Generate it once, and store privateKey as the API's API_PRIVATE_KEY secret. The app's document publishes only its public half. Keep publicKey for a later rotation.
import { Base64, Bytes, P256 } from 'ox'
const privateKey = P256.randomPrivateKey()
const { x, y } = P256.getPublicKey({ privateKey })
const base64 = (value: bigint) =>
Base64.fromBytes(Bytes.fromNumber(value, { size: 32 }), {
pad: false,
url: true,
})
const publicKey = {
alg: 'ES256',
crv: 'P-256',
kid: crypto.randomUUID(),
kty: 'EC',
x: base64(x),
y: base64(y),
}
console.log({
privateKey: JSON.stringify({
...publicKey,
d: Base64.fromHex(privateKey, { pad: false, url: true }),
}),
publicKey: JSON.stringify(publicKey),
})npm install ox
node generate-key.tsaccounts.handler serves the API's protected resource metadata with the policy, and the metadata document of its app. The instance authenticates as that app, with client assertions that the private key signs.
import { Accounts, Store } from 'accounts'
import { viem } from 'accounts/plugins'
import { Hono } from 'hono'
const accounts = Accounts.create({
chain: 'testnet',
connections: {
metadata: {
accessKey: { limits: [{ limit: '25', token: 'ousd' }] },
privateKey: JSON.parse(process.env.API_PRIVATE_KEY!),
},
resource: 'https://api.example/pay',
store: Store.memory(),
},
plugins: [viem()],
})
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
app.get('/.well-known/oauth-protected-resource/*', (c) =>
accounts.handler.fetch(c.req.raw),
)
export default appAt the first sign-in that names the resource, Tempo ID reads the metadata and stores the policy, with no registration. It reads the metadata again after 5 minutes, at the next sign-in. The approval page names the API by its host.
The store holds each access key's private key, so it stays on the server. Route every request of a connection to one process, since the instance serializes them in memory.
Read the access tokenServer
The route reads the Bearer token that session.fetch sends.
import { Accounts, Store } from 'accounts'
import { viem } from 'accounts/plugins'
import { Hono } from 'hono'
const accounts = Accounts.create({
chain: 'testnet',
connections: {
metadata: {
accessKey: { limits: [{ limit: '25', token: 'ousd' }] },
privateKey: JSON.parse(process.env.API_PRIVATE_KEY!),
},
resource: 'https://api.example/pay',
store: Store.memory(),
},
plugins: [viem()],
})
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
app.get('/.well-known/oauth-protected-resource/*', (c) =>
accounts.handler.fetch(c.req.raw),
)
app.post('/pay', async (c) => {
const accessToken = c.req.header('authorization')?.replace(/^Bearer /, '')
if (!accessToken) return c.json({ error: 'invalid_token' }, 401)
return c.json({})
})
export default appRedeem the connectionServer
connections.connect verifies the access token, and returns the connection. The first request generates an access key, and redeems the approval for its key authorization. Later requests read the store, with no call to Tempo ID.
import { Accounts, Store } from 'accounts'
import { viem } from 'accounts/plugins'
import { Hono } from 'hono'
const accounts = Accounts.create({
chain: 'testnet',
connections: {
metadata: {
accessKey: { limits: [{ limit: '25', token: 'ousd' }] },
privateKey: JSON.parse(process.env.API_PRIVATE_KEY!),
},
resource: 'https://api.example/pay',
store: Store.memory(),
},
plugins: [viem()],
})
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
app.get('/.well-known/oauth-protected-resource/*', (c) =>
accounts.handler.fetch(c.req.raw),
)
app.post('/pay', async (c) => {
const accessToken = c.req.header('authorization')?.replace(/^Bearer /, '')
if (!accessToken) return c.json({ error: 'invalid_token' }, 401)
const { connection } = await accounts.connections.connect({ accessToken })
return c.json({ userId: connection.userId })
})
export default appTempo ID signs the key authorization at redemption, with the Tempo Account's owner key. A passkey signs only with the user present, so Tempo ID refuses a Tempo Account that only a passkey owns with webauthn_required. With an access key endpoint, the owner signs at the approval instead.
Pay with the access keyServer
accounts.pay takes the connection as session, and the connection's access key sends the transfer. The first transfer carries the key authorization, which registers the access key on the chain.
import { Accounts, Store } from 'accounts'
import { viem } from 'accounts/plugins'
import { Hono } from 'hono'
const accounts = Accounts.create({
chain: 'testnet',
connections: {
metadata: {
accessKey: { limits: [{ limit: '25', token: 'ousd' }] },
privateKey: JSON.parse(process.env.API_PRIVATE_KEY!),
},
resource: 'https://api.example/pay',
store: Store.memory(),
},
plugins: [viem()],
})
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
app.get('/.well-known/oauth-protected-resource/*', (c) =>
accounts.handler.fetch(c.req.raw),
)
app.post('/pay', async (c) => {
const accessToken = c.req.header('authorization')?.replace(/^Bearer /, '')
if (!accessToken) return c.json({ error: 'invalid_token' }, 401)
const { connection } = await accounts.connections.connect({ accessToken })
const { transaction } = await accounts.pay({
amount: '1',
session: connection,
to: '0x000000000000000000000000000000000000dEaD',
token: 'ousd',
})
return c.json({ transaction })
})
export default appAn API shows no payment page, so a payment above the approved limits rejects with Actions.account.PageRequiredError. On testnet, Viem's faucet.fundSync funds the Tempo Account first.
Use cases
Each use case passes the connection that connections.connect returns to another API, or sets one property of the connections option.
Pay an MPP endpoint
accounts.mpp takes the connection as session, and pays an upstream endpoint's 402 charge with the access key.
import { Accounts, Store } from 'accounts'
import { mpp } from 'accounts/mpp'
import { Hono } from 'hono'
const accounts = Accounts.create({
chain: 'testnet',
connections: {
metadata: {
accessKey: { limits: [{ limit: '25', token: 'ousd' }] },
privateKey: JSON.parse(process.env.API_PRIVATE_KEY!),
},
resource: 'https://api.example/pay',
store: Store.memory(),
},
plugins: [mpp({ maxAmount: '1' })],
})
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
app.get('/.well-known/oauth-protected-resource/*', (c) =>
accounts.handler.fetch(c.req.raw),
)
app.post('/tool', async (c) => {
const accessToken = c.req.header('authorization')?.replace(/^Bearer /, '')
if (!accessToken) return c.json({ error: 'invalid_token' }, 401)
const { connection } = await accounts.connections.connect({ accessToken })
const response = await accounts
.mpp({ session: connection })
.fetch('https://upstream.example/tool')
return c.json(await response.json())
})
export default appPay outside a request
connections.get reads the stored connection without an access token, such as in a scheduled job. It returns undefined without a live access key. The client ID and the user ID are those of the token that connections.connect returns.
import { Accounts, Store } from 'accounts'
import { viem } from 'accounts/plugins'
const accounts = Accounts.create({
chain: 'testnet',
connections: {
metadata: {
accessKey: { limits: [{ limit: '25', token: 'ousd' }] },
privateKey: JSON.parse(process.env.API_PRIVATE_KEY!),
},
resource: 'https://api.example/pay',
store: Store.memory(),
},
plugins: [viem()],
})
export async function pay(clientId: string, userId: string) {
const connection = await accounts.connections.get({ clientId, userId })
if (connection)
await accounts.pay({
amount: '1',
session: connection,
to: '0x000000000000000000000000000000000000dEaD',
token: 'ousd',
})
}Accept only named apps
clientIds names the apps whose access tokens the API accepts. It defaults to 'any', since any app may open a connection to the resource. Another app's token then fails connections.connect with AccessToken.InvalidError.
import { Accounts, Store } from 'accounts'
import { viem } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
connections: {
clientIds: ['https://app.example'],
metadata: {
accessKey: { limits: [{ limit: '25', token: 'ousd' }] },
privateKey: JSON.parse(process.env.API_PRIVATE_KEY!),
},
resource: 'https://api.example/pay',
store: Store.memory(),
},
plugins: [viem()],
})Rotate the app's private key
Tempo ID keeps the keys of the app's document for 5 minutes, so an assertion of a new key fails until it reads the document again. publicKeys publishes the next key first:
- Generate the next key with its own
kid, and deploy only itspublicKeyinpublicKeys. The API still signs with the current key, and holds no second private key. - After 5 minutes, deploy the next
privateKey, with the earlier key'spublicKeyinpublicKeys, so that replicas of the earlier deploy still authenticate. - After every replica runs the second deploy, remove the earlier key from
publicKeys.
import { Accounts, Store } from 'accounts'
import { viem } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
connections: {
metadata: {
accessKey: { limits: [{ limit: '25', token: 'ousd' }] },
privateKey: JSON.parse(process.env.API_PRIVATE_KEY!),
publicKeys: [JSON.parse(process.env.API_NEXT_PUBLIC_KEY!)],
},
resource: 'https://api.example/pay',
store: Store.memory(),
},
plugins: [viem()],
})