CLI
A CLI signs a user in with a code that the user approves in a browser.
Overview
A CLI has no page for Tempo ID to redirect back to, and the package supports no loopback redirect.
A CLI thus signs in with the device grant (RFC 8628): the user approves the CLI's code on Tempo ID's device page, in a browser on any device, and the CLI receives the session.
Choose this flow over the other sign-in flows for a terminal program, or another client without a browser. It is the only flow of a cli: client ID, which needs no registration.
No demo runs in this page, since the client is a terminal program. The program below signs a user in and saves the session. The output is of one run against id.tempo.xyz.
$ node --import tsx index.ts whoami
Not signed in. Run `login`.
$ node --import tsx index.ts login
Open https://id.tempo.xyz/device?code=ZZVF-JWQT and confirm the code ZZVF-JWQT.
Signed in as alice@example.com.
$ node --import tsx index.ts whoami
alice@example.com 0xB93163e0dbC07Ee5744Fb519907ed922d0F1Cc1Cimport { accounts } from './tempo.config.js'
const [command] = process.argv.slice(2)
const session = await accounts.session.get()
if (command === 'login') {
const { user } = await accounts.device.signIn()
console.log(`Signed in as ${user.email}.`)
} else if (!session?.accessKey) {
console.log('Not signed in. Run `login`.')
} else if (command === 'whoami') {
console.log(`${session.user.email} ${session.accessKey.account}`)
}import { Accounts } from 'accounts'
import { device } from 'accounts/plugins'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for 7 days.
accessKey: () => ({
expiry: '7d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
clientId: 'cli:acme-example',
plugins: [
device({
onCode: (code) =>
console.log(
`Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`,
),
}),
],
})The cli example is this program, with send and logout commands.
Walkthrough
The CLI tab of Getting started installs the packages. These steps build the cli example's sign-in.
Create the instance
The device plugin adds the device grant.
import { Accounts } from 'accounts'
import { device } from 'accounts/plugins'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for 7 days.
accessKey: () => ({
expiry: '7d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
clientId: 'cli:acme-example',
plugins: [device()],
})For a local Tempo ID or another chain, Use another Tempo ID or chain sets the instance.
The client ID is cli: and the CLI's name: 3 to 32 lowercase letters, digits, or -, which start with a letter and hold no tempo. Tempo ID's device page marks such an unregistered CLI as unverified. If its access key names no limits, Tempo ID refuses the code request with missing_permissions.
Request a code
device.signIn passes the code to onCode before it waits. Print the code and the device page's URL. Without onCode, device.signIn throws.
import { Accounts } from 'accounts'
import { device } from 'accounts/plugins'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for 7 days.
accessKey: () => ({
expiry: '7d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
clientId: 'cli:acme-example',
plugins: [device()],
plugins: [
device({
onCode: (code) =>
console.log(
`Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`,
),
}),
],
})| Property | Value |
|---|---|
expiresIn | Seconds until the code expires, such as 600 |
userCode | Code that the user confirms, such as ZZVF-JWQT |
verificationUri | URL of the device page, where the user enters a code |
verificationUriComplete | URL of the device page, with the code filled in |
The device page shows the code, the CLI's name, the access key's limits, and the request's device, place, and age. The user thus recognizes a code that another person started.
Wait for the approval
device.signIn polls until the user decides, and returns the session.
import { accounts } from './tempo.config.js'
const { user } = await accounts.device.signIn()
console.log(`Signed in as ${user.email}.`)import { Accounts } from 'accounts'
import { device } from 'accounts/plugins'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for 7 days.
accessKey: () => ({
expiry: '7d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
clientId: 'cli:acme-example',
plugins: [
device({
onCode: (code) =>
console.log(
`Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`,
),
}),
],
})If the user denies the code, or the code expires, device.signIn throws Accounts.RequestError. Its code names the fault, and Errors lists the others.
Read the saved session
With a cli: client ID and no store option, the instance saves its session to ~/.tempo/id/store.json. Every CLI of the user shares the file, with one session for each client ID and chain.
Only the user can read the file and its folder, since the file holds a refresh token and the access key's private key.
A command that sends with the access key, such as the example's send, awaits session.get() first. A transfer before the read throws Accounts.SignedOutError. The viem plugin adds the token actions, as Send with Viem's token actions shows.
import { accounts } from './tempo.config.js'
const session = await accounts.session.get()
if (session?.accessKey)
console.log(`${session.user.email} ${session.accessKey.account}`)
else console.log('Not signed in. Run `login`.')import { Accounts } from 'accounts'
import { device } from 'accounts/plugins'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for 7 days.
accessKey: () => ({
expiry: '7d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
clientId: 'cli:acme-example',
plugins: [
device({
onCode: (code) =>
console.log(
`Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`,
),
}),
],
})Use cases
Each use case sets one option of device.signIn, or uses an action of the device plugin.
Request another access key
accessKey names the access key of one sign-in, in place of the instance's accessKey. The device page shows its limits for approval.
import { accounts } from './tempo.config.js'
const { user } = await accounts.device.signIn({
// The access key sends up to 500 OUSD for a day.
accessKey: {
expiry: '1d',
limits: [{ limit: '500', token: 'ousd' }],
},
})
console.log(`Signed in as ${user.email}.`)import { Accounts } from 'accounts'
import { device } from 'accounts/plugins'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for 7 days.
accessKey: () => ({
expiry: '7d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
clientId: 'cli:acme-example',
plugins: [
device({
onCode: (code) =>
console.log(
`Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`,
),
}),
],
})Stop waiting for the approval
signal stops the polls, such as at a timeout or at Ctrl+C. The sign-in then rejects with the signal's reason. If a poll in flight returns an approval, the sign-in still signs the user in.
import { accounts } from './tempo.config.js'
const controller = new AbortController()
const cancel = () => controller.abort(new Error('Cancelled.'))
process.once('SIGINT', cancel)
try {
const { user } = await accounts.device.signIn({
// Stops the polls after 2 minutes, or at Ctrl+C.
signal: AbortSignal.any([controller.signal, AbortSignal.timeout(120_000)]),
})
console.log(`Signed in as ${user.email}.`)
} finally {
// Ctrl+C ends the process again once the sign-in settles.
process.off('SIGINT', cancel)
}import { Accounts } from 'accounts'
import { device } from 'accounts/plugins'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for 7 days.
accessKey: () => ({
expiry: '7d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
clientId: 'cli:acme-example',
plugins: [
device({
onCode: (code) =>
console.log(
`Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`,
),
}),
],
})Bind a challenge
challenge has the user sign a server's message on the device page. The session's challengeSignature holds the signature, which the server checks, as Sign challenges shows.
import { accounts } from './tempo.config.js'
// The server issues the message to sign.
const response = await fetch('https://api.example.com/challenge', {
method: 'POST',
})
const session = await accounts.device.signIn({
challenge: await response.text(),
})
await fetch('https://api.example.com/verify', {
body: JSON.stringify({
address: session.address,
signature: session.challengeSignature,
}),
headers: { 'content-type': 'application/json' },
method: 'POST',
})import { Accounts } from 'accounts'
import { device } from 'accounts/plugins'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for 7 days.
accessKey: () => ({
expiry: '7d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
clientId: 'cli:acme-example',
plugins: [
device({
onCode: (code) =>
console.log(
`Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`,
),
}),
],
})Ask for funds
funding names the amount that the CLI needs in the user's Tempo Account. If the account holds less, the device page opens Tempo ID's deposit page after the approval.
import { accounts } from './tempo.config.js'
const { user } = await accounts.device.signIn({
funding: { amount: '10', currency: 'USD' },
})
console.log(`Signed in as ${user.email}.`)import { Accounts } from 'accounts'
import { device } from 'accounts/plugins'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for 7 days.
accessKey: () => ({
expiry: '7d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
clientId: 'cli:acme-example',
plugins: [
device({
onCode: (code) =>
console.log(
`Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`,
),
}),
],
})Sign in for an API
resource names a registered resource, such as an MCP server. Each access token then names it as its audience, so only that API accepts the token.
import { accounts } from './tempo.config.js'
const { user } = await accounts.device.signIn({
resource: 'https://mcp.example.com/mcp',
})
console.log(`Signed in as ${user.email}.`)import { Accounts } from 'accounts'
import { device } from 'accounts/plugins'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for 7 days.
accessKey: () => ({
expiry: '7d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
clientId: 'cli:acme-example',
plugins: [
device({
onCode: (code) =>
console.log(
`Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`,
),
}),
],
})Send above the limit or the balance
With the viem plugin, a transfer above the limit of the access key, or above the balance, starts a new device grant. onCode shows its code. After the approval, the transfer sends again.
| Refusal | The grant requests |
|---|---|
| Spent limit | A new access key with a higher limit of the token |
| Low balance | A new access key with the same limits, and a deposit on Tempo ID's page after the approval |
After a deposit grant, the transfer waits up to 10 minutes for the deposit. If the user denies the code, or no deposit arrives, the transfer rejects with Plugins.viem.RetryClosedError. If the session holds another user or Tempo Account after the approval, the transfer rejects with Plugins.viem.RetryAccountError.
import { parseUnits } from 'viem'
import { Addresses } from 'viem/tempo'
import { accounts } from './tempo.config.js'
// A transfer before the read of the session throws `Accounts.SignedOutError`.
await accounts.session.get()
try {
await accounts.token.transferSync({
amount: parseUnits('150', 6),
to: '0x000000000000000000000000000000000000dEaD',
token: Addresses.ousd,
})
} catch (error) {
if ((error as Error).name !== 'Plugins.viem.RetryClosedError') throw error
console.error('Approve the code to send the transfer.')
process.exitCode = 1
}import { Accounts } from 'accounts'
import { device, viem } from 'accounts/plugins'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for 7 days.
accessKey: () => ({
expiry: '7d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
clientId: 'cli:acme-example',
plugins: [
device({
onCode: (code) =>
console.log(
`Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`,
),
}),
viem(),
],
})Poll across requests
A server cannot hold one request open until the user approves. device.authorize starts the grant in one request, and device.poll sends one poll in each later request.
Neither call sets a session. poll names the access key of authorize again, so the server generates the access key, and keeps its private key with the device code until the code expires.
import { Store } from 'accounts'
import { Hono } from 'hono'
import { generatePrivateKey } from 'viem/accounts'
import { Account } from 'viem/tempo'
import { accounts } from './tempo.config.js'
/** What the server keeps of a grant until a poll redeems it. */
type Grant = { deviceCode: string; privateKey: `0x${string}` }
const grants = Store.memory()
export default new Hono()
// The first request starts the grant, with an access key that the server holds.
.post('/login', async (c) => {
const privateKey = generatePrivateKey()
const grant = await accounts.device.authorize({
accessKey: {
account: Account.fromSecp256k1(privateKey),
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
},
})
const id = crypto.randomUUID()
await grants.setItem(
id,
{ deviceCode: grant.deviceCode, privateKey },
{ expiresAt: Date.now() + grant.expiresIn * 1000 },
)
return c.json({
id,
interval: grant.interval,
userCode: grant.userCode,
verificationUriComplete: grant.verificationUriComplete,
})
})
// Each later request sends one poll.
.get('/login/:id', async (c) => {
const id = c.req.param('id')
const grant = (await grants.getItem(id)) as Grant | undefined
if (!grant) return c.json({ error: 'not_found' }, 404)
const result = await accounts.device.poll({
accessKey: { account: Account.fromSecp256k1(grant.privateKey) },
deviceCode: grant.deviceCode,
})
if (result.status === 'pending') return c.json(result)
await grants.removeItem(id)
const { accessKey, user } = result.authorization
return c.json({
account: accessKey.account,
email: user.email,
status: result.status,
})
})import { Accounts } from 'accounts'
import { device } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
clientId: 'cli:acme-example',
plugins: [device()],
})- The client waits
intervalseconds between requests. An earlier poll returnsslowDown. authorization.signeris a Viem account that signs with the access key.- A poll of a denied or an expired code throws, as Wait for the approval lists.