@conciergeprotocol/server 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,156 @@
1
- # Temporary Holding Version
1
+ # @conciergeprotocol/server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Run a [Concierge Agent Protocol](https://conciergeprotocol.org) front door. You write one function, `answer`. The package serves `agent.txt`, keeps the thread, hides one caller's reply from another, and enforces the daily message cap.
4
+
5
+ The protocol is at [conciergeprotocol.org](https://conciergeprotocol.org). Publishing a door is described in [Publish a door](https://conciergeprotocol.org/publish).
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm install @conciergeprotocol/server
11
+ ```
12
+
13
+ Node.js 22 or newer. Messages are stored in SQLite. Set `DATABASE_URL` to a Postgres connection string to use Postgres, and install `pg`.
14
+
15
+ ## Answer
16
+
17
+ `answer` receives the question and returns the reply. A string, or `{ reply }`. Keys, tools, and records stay inside this function. The caller only sees the reply.
18
+
19
+ ```js
20
+ import { createCapServer } from '@conciergeprotocol/server'
21
+
22
+ const cap = await createCapServer({
23
+ agent: { name: 'Harbor Goods', chat: 'https://harborgoods.example/chat' },
24
+ answer: async ({ message, context, history }) => {
25
+ const res = await fetch('https://support.example/api/ask', {
26
+ method: 'POST',
27
+ headers: {
28
+ 'content-type': 'application/json',
29
+ authorization: `Bearer ${process.env.SUPPORT_BOT_KEY}`,
30
+ },
31
+ body: JSON.stringify({ question: message, brief: context, history }),
32
+ })
33
+ if (!res.ok) return { error: { code: 'failed', message: 'The agent could not answer.' } }
34
+ const { text } = await res.json()
35
+ return { reply: text }
36
+ },
37
+ })
38
+
39
+ await cap.listen(8088)
40
+ ```
41
+
42
+ `history` is the earlier turns, oldest first. The caller sends `previous_message_id` and does not resend them. `context` is the optional brief from the visiting agent. `account` and `scope` are null until someone logs in.
43
+
44
+ Return `{ error: { code: 'login_required', message: '...' } }` when the question needs an account. While a message is still running, the caller gets `202` and no reply.
45
+
46
+ The server waits `waitSeconds` (default 20). A longer answer finishes in the background. `dailyLimit` caps messages per caller per UTC day. `0` turns the cap off. Finished messages stay readable for `retentionHours` (default 24).
47
+
48
+ Without `sqlitePath` or `DATABASE_URL`, messages go to `data/cap.sqlite` in the working directory. Pass `sqlitePath: ':memory:'` for a process that keeps nothing.
49
+
50
+ ## The file on the company domain
51
+
52
+ This process can run on any host. The company domain still serves `agent.txt`. Point `CAP` at this server, or rewrite `/cap/v1` to it. Set `publicUrl` when the public origin differs from the request host.
53
+
54
+ ```text
55
+ Protocol: CAP/1.0
56
+ Name: Harbor Goods
57
+ Chat: https://harborgoods.example/chat
58
+ CAP: https://cap.harborgoods.example/cap/v1
59
+ Spec: https://conciergeprotocol.org/cap.txt
60
+ ```
61
+
62
+ Check it:
63
+
64
+ ```sh
65
+ npx cap-check https://cap.harborgoods.example
66
+ ```
67
+
68
+ `cap-check` reads `agent.txt`, asks one question, and confirms a second caller cannot read the reply.
69
+
70
+ ## Next.js
71
+
72
+ `createCapHandler` returns a Fetch handler. Use a durable store (`sqlitePath` on a disk, or `databaseUrl`). A memory store loses an in-flight answer when the function instance stops.
73
+
74
+ ```js
75
+ import { createCapHandler } from '@conciergeprotocol/server'
76
+ import { answer } from './answer.js'
77
+
78
+ const door = await createCapHandler({
79
+ agent: { name: 'Harbor Goods' },
80
+ answer,
81
+ databaseUrl: process.env.DATABASE_URL,
82
+ })
83
+
84
+ export const GET = (request) => door.handle(request)
85
+ export const POST = (request) => door.handle(request)
86
+ export const OPTIONS = (request) => door.handle(request)
87
+ ```
88
+
89
+ Serve `agent.txt` from the company domain. The handler above also serves it at `/agent.txt` on this app.
90
+
91
+ ## Log in
92
+
93
+ Pass `login` to turn on the built-in OAuth server. It adds the `OAuth` line to `agent.txt`. `login` checks the company's own user store and returns an account id, or null.
94
+
95
+ ```js
96
+ const cap = await createCapServer({
97
+ agent: { name: 'Harbor Goods' },
98
+ answer,
99
+ login: async ({ username, password }) => verifyUser(username, password),
100
+ })
101
+ ```
102
+
103
+ With a token, `answer` receives `account` and `scope` (`read` or `write`). A token sent by a different agent is `403`.
104
+
105
+ If people are usually signed in to your site already, pass `currentAccount` too. It reads your own session from the request headers and returns the account id, or null. When it finds one, the login and confirm pages show only Allow or Approve. Without a session, they fall back to `login`. A confirm page asks for a login when the session is for a different account than the request.
106
+
107
+ ```js
108
+ const cap = await createCapServer({
109
+ agent: { name: 'Harbor Goods' },
110
+ answer,
111
+ login: async ({ username, password }) => verifyUser(username, password),
112
+ currentAccount: async ({ headers }) => accountFromSessionCookie(headers.cookie),
113
+ })
114
+ ```
115
+
116
+ Serve `/oauth` on the same origin as your sign-in, so your session cookie reaches it. A signed-in approval also needs a `SameSite=Strict` cookie the page sets, so a form on another site cannot submit it.
117
+
118
+ To hold a change for the person's approval, return `{ confirm: { summary, authorization_details }, reply }` instead of running it. After they approve, the server calls `act` once.
119
+
120
+ ## Account routes
121
+
122
+ Another agent can call your own JSON routes with the same token, for example a hosted agent that answers public questions itself and fetches account data from you. `accountFor(request)` checks the bearer token against the agent in `CAP-From` and returns `{ account, scope, caller }`, or null. Filter every query by `account`.
123
+
124
+ ```js
125
+ export async function GET(request) {
126
+ const access = await door.accountFor(request)
127
+ if (!access) return Response.json({ error: { code: 'login_required' } }, { status: 401 })
128
+ return Response.json({ account: access.account, orders: await ordersFor(access.account) })
129
+ }
130
+ ```
131
+
132
+ `requestApproval(request, { summary, authorization_details })` holds a change for the person's OK and returns `{ confirmation: { id, url, summary } }`. It needs a write login and `act`, which runs once after approval.
133
+
134
+ ## cap.json
135
+
136
+ `cap-server` reads `cap.json` from the working directory, or `CAP_CONFIG`. The same file the reference server uses:
137
+
138
+ ```json
139
+ {
140
+ "agent": { "name": "Harbor Goods", "chat": "https://harborgoods.example/chat" },
141
+ "handler": { "type": "http", "url": "https://support.example/cap-hook" },
142
+ "daily_limit": 500
143
+ }
144
+ ```
145
+
146
+ `static` returns fixed text. `echo` returns the message. `http` POSTs `{ message, context, history, account, scope }` to a URL and expects `{ "reply": "..." }`. Set `handler.secret_env` to send that environment variable as `X-Cap-Secret`.
147
+
148
+ ```sh
149
+ npx cap-server
150
+ ```
151
+
152
+ The HTTP, storage, and OAuth modules match the reference server in the protocol repository. A spec change belongs in both places.
153
+
154
+ ## License
155
+
156
+ Apache 2.0
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "@conciergeprotocol/server",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.0",
4
+ "description": "Run a Concierge Agent Protocol front door. You write the answer.",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./src/index.d.ts",
9
+ "import": "./src/index.js"
10
+ }
11
+ },
12
+ "bin": {
13
+ "cap-server": "./src/cli.js",
14
+ "cap-check": "./src/check.js"
15
+ },
16
+ "files": [
17
+ "src"
18
+ ],
19
+ "engines": {
20
+ "node": ">=22"
21
+ },
22
+ "license": "Apache-2.0",
23
+ "homepage": "https://conciergeprotocol.org",
24
+ "keywords": [
25
+ "concierge",
26
+ "cap",
27
+ "agents",
28
+ "protocol",
29
+ "server"
30
+ ],
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "git+https://github.com/conciergeprotocol/js.git",
34
+ "directory": "packages/server"
35
+ },
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "optionalDependencies": {
40
+ "pg": "^8.16.0"
41
+ }
42
+ }
package/src/check.js ADDED
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env node
2
+ import { checkDoor } from './check.mjs'
3
+
4
+ const origin = process.argv[2]
5
+ if (!origin) {
6
+ console.error('Usage: cap-check <origin>')
7
+ process.exit(1)
8
+ }
9
+
10
+ const result = await checkDoor(origin)
11
+ if (result.ok) {
12
+ console.log(`${origin} passes.`)
13
+ } else {
14
+ for (const failure of result.failures) console.error(failure)
15
+ process.exit(1)
16
+ }
package/src/check.mjs ADDED
@@ -0,0 +1,91 @@
1
+ const FROM = 'agent:cap-check'
2
+ const OTHER = 'agent:cap-check-other'
3
+
4
+ /**
5
+ * Four checks a door has to pass: agent.txt, one answered question,
6
+ * and a second caller who cannot read that reply.
7
+ */
8
+ export async function checkDoor(origin, options = {}) {
9
+ const fetchImpl = options.fetch || fetch
10
+ const root = String(origin || '').replace(/\/$/, '')
11
+ const failures = []
12
+ const fail = (message) => failures.push(message)
13
+ if (!root) return { ok: false, failures: ['Pass the door origin, such as http://127.0.0.1:8088.'] }
14
+
15
+ let card = ''
16
+ try {
17
+ const cardRes = await fetchImpl(`${root}/agent.txt`)
18
+ card = await cardRes.text()
19
+ if (cardRes.status !== 200) fail(`agent.txt returned ${cardRes.status}.`)
20
+ } catch (err) {
21
+ fail(`agent.txt could not be fetched: ${err.message}`)
22
+ }
23
+ if (card && !card.startsWith('Protocol: CAP/1.0')) fail('agent.txt must start with Protocol: CAP/1.0.')
24
+ const capLine = card.split('\n').find((line) => line.startsWith('CAP: '))
25
+ const capUrl = capLine ? capLine.slice(5).trim() : ''
26
+ if (capLine && !/^https?:\/\//.test(capUrl)) fail('agent.txt needs an http or https CAP URL.')
27
+ if (card && !capLine) fail('agent.txt needs a CAP line.')
28
+
29
+ const headers = {
30
+ 'content-type': 'application/json',
31
+ 'cap-version': '1.0',
32
+ 'cap-from': FROM,
33
+ }
34
+ const timeoutMs = options.timeoutMs ?? 25_000
35
+ let id = ''
36
+ try {
37
+ const done = await ask(fetchImpl, root, headers, options.message || 'What can you help with?', timeoutMs)
38
+ if (done.body?.status !== 'done' || typeof done.body.reply !== 'string') {
39
+ fail('The question did not finish with a reply.')
40
+ }
41
+ id = done.body?.id || ''
42
+ } catch (err) {
43
+ fail(err.message)
44
+ }
45
+
46
+ if (id) {
47
+ try {
48
+ const other = await fetchImpl(`${root}/cap/v1/messages/${encodeURIComponent(id)}`, {
49
+ headers: { ...headers, 'cap-from': OTHER },
50
+ })
51
+ if (other.status !== 404) fail('A second caller could read the reply.')
52
+ } catch (err) {
53
+ fail(`The second caller check failed: ${err.message}`)
54
+ }
55
+ }
56
+
57
+ return { ok: failures.length === 0, failures }
58
+ }
59
+
60
+ async function ask(fetchImpl, root, headers, message, timeoutMs) {
61
+ let res = await fetchImpl(`${root}/cap/v1/messages`, {
62
+ method: 'POST',
63
+ headers,
64
+ body: JSON.stringify({ message }),
65
+ })
66
+ let body = await readJson(res)
67
+ const deadline = Date.now() + timeoutMs
68
+ while (res.status === 202 || body?.status === 'working') {
69
+ if (Date.now() > deadline) throw new Error('The question was not answered in time.')
70
+ const loc = res.headers.get('location')
71
+ const url = loc
72
+ ? (loc.startsWith('http') ? loc : `${root}${loc.startsWith('/') ? '' : '/'}${loc}`)
73
+ : `${root}/cap/v1/messages/${encodeURIComponent(body?.id || '')}`
74
+ const retryAfter = Number(res.headers.get('retry-after') || 1)
75
+ const wait = Math.min((Number.isFinite(retryAfter) ? retryAfter : 1) * 1000, 2000)
76
+ await new Promise((resolve) => setTimeout(resolve, wait))
77
+ res = await fetchImpl(url, { headers })
78
+ body = await readJson(res)
79
+ }
80
+ return { res, body }
81
+ }
82
+
83
+ async function readJson(res) {
84
+ const text = await res.text()
85
+ if (!text) return null
86
+ try {
87
+ return JSON.parse(text)
88
+ } catch {
89
+ return null
90
+ }
91
+ }
package/src/cli.js ADDED
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ import { boot } from './config.mjs'
3
+
4
+ const { server } = await boot()
5
+ const port = Number(process.env.PORT || 8088)
6
+ const host = process.env.HOST || '0.0.0.0'
7
+ server.listen(port, host, () => {
8
+ console.log(`CAP server on http://${host}:${port}`)
9
+ })
package/src/config.mjs ADDED
@@ -0,0 +1,112 @@
1
+ import { timingSafeEqual } from 'node:crypto'
2
+ import { readFileSync } from 'node:fs'
3
+ import { join } from 'node:path'
4
+ import { createOAuth } from './oauth.mjs'
5
+ import { createCapServer } from './node-server.mjs'
6
+ import { createStore } from './store.mjs'
7
+
8
+ const HANDLERS = ['static', 'echo', 'http']
9
+
10
+ export function loadConfig(path) {
11
+ const config = JSON.parse(readFileSync(path, 'utf8'))
12
+ if (!config.agent?.name) throw new Error('cap.json needs agent.name.')
13
+ config.agent.status = config.agent.status || 'active'
14
+ const type = config.handler?.type || 'echo'
15
+ if (!HANDLERS.includes(type)) throw new Error(`Unknown handler type: ${type}.`)
16
+ return config
17
+ }
18
+
19
+ async function postHook(handler, payload) {
20
+ const url = handler.url || process.env[handler.url_env || 'HOOK_URL']
21
+ if (!url) return { error: { code: 'failed', message: 'The agent could not answer.' } }
22
+ const secret = process.env[handler.secret_env || 'HOOK_SECRET'] || ''
23
+ const headers = { 'content-type': 'application/json' }
24
+ if (secret) headers['x-cap-secret'] = secret
25
+ const res = await fetch(url, { method: 'POST', headers, body: JSON.stringify(payload) })
26
+ const body = await res.json().catch(() => ({}))
27
+ if (!res.ok || body.error) return { error: body.error || { code: 'failed', message: 'The agent could not answer.' } }
28
+ return body
29
+ }
30
+
31
+ export function handlerAnswer(handler = { type: 'echo' }) {
32
+ const login = { error: { code: 'login_required', message: 'Log in to your account to ask about it.' } }
33
+ return async ({ message, context, history, account, scope }) => {
34
+ if (handler.account && !account) return login
35
+ if (handler.type === 'static') return { reply: String(handler.reply ?? '') }
36
+ if (handler.type === 'echo') return { reply: message }
37
+ const body = await postHook(handler, { message, context, history, account, scope })
38
+ if (body.error) return body
39
+ if (body.confirm) return { confirm: body.confirm, reply: typeof body.reply === 'string' ? body.reply : '' }
40
+ return { reply: typeof body.reply === 'string' ? body.reply : '' }
41
+ }
42
+ }
43
+
44
+ /** With `http`, an approved action goes back to the same hook as `{ confirmed }`. */
45
+ export function handlerAct(handler = { type: 'echo' }) {
46
+ if (handler.type !== 'http') return null
47
+ return async ({ account, authorization_details, caller }) => {
48
+ const body = await postHook(handler, { confirmed: { account, authorization_details, caller } })
49
+ if (body.error) return { error: { message: body.error.message } }
50
+ return { message: typeof body.message === 'string' ? body.message : '' }
51
+ }
52
+ }
53
+
54
+ const sameText = (a, b) => {
55
+ const left = Buffer.from(String(a))
56
+ const right = Buffer.from(String(b))
57
+ return left.length === right.length && timingSafeEqual(left, right)
58
+ }
59
+
60
+ /** Demo logins from cap.json. A real owner passes `boot({ login })` and checks its own user store. */
61
+ export function accountsLogin(accounts = []) {
62
+ return async ({ username, password }) => {
63
+ const match = accounts.find((entry) => entry.account === username)
64
+ const expected = match ? (match.password_env ? process.env[match.password_env] : match.password) : ''
65
+ return match && expected && sameText(password, expected) ? match.account : null
66
+ }
67
+ }
68
+
69
+ export async function boot(options = {}) {
70
+ const configPath = options.configPath || process.env.CAP_CONFIG || join(process.cwd(), 'cap.json')
71
+ const config = options.config || loadConfig(configPath)
72
+ const store = await createStore({
73
+ databaseUrl: options.databaseUrl ?? process.env.DATABASE_URL,
74
+ sqlitePath: options.sqlitePath ?? process.env.SQLITE_PATH ?? join(process.cwd(), 'data', 'cap.sqlite'),
75
+ })
76
+ for (const grant of config.grants || []) {
77
+ if (grant.token && grant.account && grant.client) {
78
+ await store.upsertGrant({ token: grant.token, account: grant.account, clientId: grant.client, scope: grant.scope === 'write' ? 'write' : 'read' })
79
+ }
80
+ }
81
+ const oauthConfig = config.oauth
82
+ const oauth = oauthConfig || options.login || options.currentAccount
83
+ ? createOAuth({
84
+ store,
85
+ agentName: config.agent.name,
86
+ login: options.login || accountsLogin(oauthConfig?.accounts),
87
+ currentAccount: options.currentAccount || null,
88
+ write: Boolean(oauthConfig?.write),
89
+ act: options.act || handlerAct(config.handler),
90
+ accessTokenSeconds: oauthConfig?.access_token_seconds ?? 3600,
91
+ writeAccessTokenSeconds: oauthConfig?.write_access_token_seconds ?? 900,
92
+ allowHttpClients: Boolean(oauthConfig?.allow_http_clients),
93
+ hint: oauthConfig?.hint || '',
94
+ fetchImpl: options.fetch,
95
+ deviceInterval: oauthConfig?.device_interval ?? 5,
96
+ })
97
+ : null
98
+ const cap = createCapServer({
99
+ store,
100
+ agent: config.agent,
101
+ answer: options.answer || handlerAnswer(config.handler),
102
+ waitMs: options.waitMs ?? (config.wait_seconds ?? 20) * 1000,
103
+ retryAfter: config.retry_after ?? 5,
104
+ retentionHours: config.retention_hours ?? 24,
105
+ dailyLimit: config.daily_limit ?? 0,
106
+ maxTurns: config.max_turns ?? 20,
107
+ oauth,
108
+ publicUrl: options.publicUrl ?? process.env.PUBLIC_URL ?? '',
109
+ extraRoutes: options.extraRoutes,
110
+ })
111
+ return { store, config, ...cap }
112
+ }
package/src/http.mjs ADDED
@@ -0,0 +1,43 @@
1
+ const MAX_BODY = 1_000_000
2
+
3
+ export function send(res, status, body, extra = {}) {
4
+ res.writeHead(status, {
5
+ 'content-type': extra.type || 'application/json; charset=utf-8',
6
+ 'access-control-allow-origin': '*',
7
+ 'access-control-allow-headers': 'authorization, content-type, cap-version, cap-from, idempotency-key',
8
+ 'access-control-allow-methods': 'GET, POST, OPTIONS',
9
+ 'access-control-expose-headers': 'location, retry-after',
10
+ 'cache-control': 'no-store',
11
+ ...(extra.headers || {}),
12
+ })
13
+ res.end(extra.raw ?? JSON.stringify(body))
14
+ }
15
+
16
+ export function fail(res, status, code, message, headers) {
17
+ send(res, status, { error: { code, message } }, { headers })
18
+ }
19
+
20
+ export function readBody(req) {
21
+ return new Promise((resolve, reject) => {
22
+ const chunks = []
23
+ let size = 0
24
+ req.on('data', (chunk) => {
25
+ size += chunk.length
26
+ if (size > MAX_BODY) {
27
+ reject(Object.assign(new Error('Body is too large.'), { status: 400 }))
28
+ req.destroy()
29
+ return
30
+ }
31
+ chunks.push(chunk)
32
+ })
33
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
34
+ req.on('error', reject)
35
+ })
36
+ }
37
+
38
+ export function requestOrigin(req, publicUrl = '') {
39
+ if (publicUrl) return publicUrl.replace(/\/$/, '')
40
+ const host = req.headers['x-forwarded-host'] || req.headers.host || '127.0.0.1'
41
+ const proto = req.headers['x-forwarded-proto'] || 'http'
42
+ return `${proto}://${host}`
43
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,106 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http'
2
+
3
+ export type AgentCard = {
4
+ name: string
5
+ chat?: string
6
+ status?: 'active' | 'paused' | 'draft' | 'archived' | string
7
+ spec?: string
8
+ oauth?: string
9
+ }
10
+
11
+ export type Turn = {
12
+ message: string
13
+ context: Record<string, unknown>
14
+ reply: string | null
15
+ }
16
+
17
+ export type AnswerInput = {
18
+ message: string
19
+ context: Record<string, unknown>
20
+ history: Turn[]
21
+ account: string | null
22
+ scope: 'read' | 'write' | null
23
+ caller: string
24
+ }
25
+
26
+ export type AnswerError = { error: { code: string; message: string } }
27
+
28
+ export type AnswerResult =
29
+ | string
30
+ | { reply: string }
31
+ | AnswerError
32
+ | { confirm: { summary: string; authorization_details?: unknown[] }; reply?: string }
33
+
34
+ export type Answer = (input: AnswerInput) => AnswerResult | Promise<AnswerResult>
35
+
36
+ export type CapServerOptions = {
37
+ agent: AgentCard
38
+ answer: Answer
39
+ /** Checks the company's own user store. Returning an account id turns on OAuth. */
40
+ login?: (input: { username: string; password: string }) => string | null | Promise<string | null>
41
+ /**
42
+ * Reads the company's own session from the request headers and returns the
43
+ * signed-in account id. The login and confirm pages then ask only for the decision.
44
+ */
45
+ currentAccount?: (input: { headers: Record<string, string | string[] | undefined> }) => string | null | Promise<string | null>
46
+ /** Runs once after a person approves a held action. */
47
+ act?: (input: { account: string; authorization_details: unknown; caller: string }) => { message: string } | { error: { message: string } } | Promise<{ message: string } | { error: { message: string } }>
48
+ write?: boolean
49
+ allowHttpClients?: boolean
50
+ grants?: { token: string; account: string; client: string; scope?: 'read' | 'write' }[]
51
+ waitSeconds?: number
52
+ waitMs?: number
53
+ retryAfter?: number
54
+ retentionHours?: number
55
+ dailyLimit?: number
56
+ maxTurns?: number
57
+ publicUrl?: string
58
+ databaseUrl?: string
59
+ /** SQLite file, or `:memory:`. Ignored when databaseUrl is a Postgres URL. */
60
+ sqlitePath?: string
61
+ accessTokenSeconds?: number
62
+ writeAccessTokenSeconds?: number
63
+ deviceInterval?: number
64
+ hint?: string
65
+ fetch?: typeof fetch
66
+ extraRoutes?: (req: IncomingMessage, res: ServerResponse, url: URL) => boolean | Promise<boolean>
67
+ }
68
+
69
+ export type ListenAddress = {
70
+ port: number
71
+ address: string
72
+ family: string
73
+ }
74
+
75
+ export type AccountAccess = { account: string; scope: 'read' | 'write'; caller: string }
76
+
77
+ export type ApprovalResult =
78
+ | { confirmation: { id: string; status: 'pending'; url: string; summary: string; expires_at: string } }
79
+ | AnswerError
80
+
81
+ export type AccountHelpers = {
82
+ /** The account behind the request's bearer token, for your own account routes. Null without a valid token for the agent in CAP-From. */
83
+ accountFor(request: Request | IncomingMessage): Promise<AccountAccess | null>
84
+ /** Holds an action until the person approves it on the confirm page. `act` runs it once after. */
85
+ requestApproval(request: Request | IncomingMessage, input: { summary: string; authorization_details?: unknown[] }): Promise<ApprovalResult>
86
+ }
87
+
88
+ export type CapServer = AccountHelpers & {
89
+ listen(port?: number, host?: string): Promise<ListenAddress | string | null>
90
+ close(): Promise<void>
91
+ fetch(request: Request): Promise<Response>
92
+ handle(req: IncomingMessage, res: ServerResponse): Promise<void>
93
+ }
94
+
95
+ export function createCapServer(options: CapServerOptions): Promise<CapServer>
96
+
97
+ export function createCapHandler(options: CapServerOptions): Promise<AccountHelpers & {
98
+ handle(request: Request): Promise<Response>
99
+ close(): Promise<void>
100
+ }>
101
+
102
+ export function checkDoor(origin: string, options?: {
103
+ message?: string
104
+ timeoutMs?: number
105
+ fetch?: typeof fetch
106
+ }): Promise<{ ok: boolean; failures: string[] }>