For apps that connect to zzTakeoff on a user's behalf, such as a desktop app or a web service. Every request acts with only the permissions the user's account already has.
https://www.zztakeoff.com/apiscript/run, marked NEEDS A TAB, runs there, and the event stream reports what happens there. https://www.zztakeoff.com/oauth/authorize with response_type=code, client_id, redirect_uri, state, code_challenge and code_challenge_method=S256. They choose full or read-only access. POST https://www.zztakeoff.com/oauth/token with grant_type=authorization_code, code, client_id, redirect_uri and code_verifier, plus the client secret (HTTP Basic, or client_secret in the body) for a confidential client. Authorization: Bearer <access_token>. Access tokens last 1 hour; renew with grant_type=refresh_token. Refresh tokens rotate, so store the new one every time. Users can see and revoke connected apps in zzTakeoff under Settings → MCP / API. OAuth discovery: https://www.zztakeoff.com/.well-known/oauth-authorization-server.
Either way the user signs in on zzTakeoff in a real browser window, where they can see the address. Never show sign-in in an iframe (zzTakeoff refuses to be framed) or an embedded WebView.
For desktop apps and anything not running in a browser: open the user's normal browser at the authorize URL and catch the redirect on a loopback address.
// Desktop app (Node): open the user's normal browser, catch the redirect on loopback.
const http = require('http'), crypto = require('crypto')
const ZZ = 'https://www.zztakeoff.com', b64 = b => b.toString('base64url')
async function signIn (clientId, openBrowser) {
const verifier = b64(crypto.randomBytes(32)), state = b64(crypto.randomBytes(16))
const challenge = b64(crypto.createHash('sha256').update(verifier).digest())
return new Promise((resolve, reject) => {
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, 'http://127.0.0.1')
if (url.pathname !== '/callback') return res.end()
res.end('Signed in. You can close this tab and go back to the app.')
server.close()
if (url.searchParams.get('state') !== state) return reject(new Error('state mismatch'))
if (url.searchParams.get('error')) return reject(new Error(url.searchParams.get('error')))
const r = await fetch(ZZ + '/oauth/token', {method: 'POST', body: new URLSearchParams({
grant_type: 'authorization_code', code: url.searchParams.get('code'), client_id: clientId,
redirect_uri: redirectUri, code_verifier: verifier
})})
resolve(await r.json()) // {access_token, refresh_token, expires_in, scope}
})
let redirectUri
server.listen(0, '127.0.0.1', () => { // any free port: loopback ports are matched loosely
redirectUri = 'http://127.0.0.1:' + server.address().port + '/callback'
openBrowser(ZZ + '/oauth/authorize?' + new URLSearchParams({
response_type: 'code', client_id: clientId, redirect_uri: redirectUri,
state, code_challenge: challenge, code_challenge_method: 'S256'
}))
})
})
}For web apps: open the authorize URL in a popup so your page stays put. The callback page hands the result back over a same-origin BroadcastChannel and closes itself.
// Web app: sign in in a popup; the page that opened it never navigates.
// Main page. window.open must run straight from the click, or popup blockers stop it.
connectButton.onclick = async () => {
const verifier = b64(crypto.getRandomValues(new Uint8Array(32)))
const state = b64(crypto.getRandomValues(new Uint8Array(16)))
const challenge = b64(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))))
localStorage.setItem('zzt-signin', JSON.stringify({verifier, state}))
window.open('https://www.zztakeoff.com/oauth/authorize?' + new URLSearchParams({
response_type: 'code', client_id: CLIENT_ID, redirect_uri: location.origin + '/callback.html',
state, code_challenge: challenge, code_challenge_method: 'S256'
}), 'zzt-signin', 'popup,width=520,height=720')
}
// Hear back from the popup. BroadcastChannel, not window.opener: a browser may cut
// the opener link when the popup passes through other sites' sign-in pages.
new BroadcastChannel('zzt-signin').onmessage = ({data}) => {
if (data.error) return showError(data.error)
onConnected(data)
}
// callback.html (same origin), in a <script type="module">. localStorage, not
// sessionStorage: the popup's copy of sessionStorage isn't reliable after it has
// been through other sites.
const saved = JSON.parse(localStorage.getItem('zzt-signin') || '{}')
localStorage.removeItem('zzt-signin')
const params = new URLSearchParams(location.search)
const channel = new BroadcastChannel('zzt-signin')
if (params.get('state') !== saved.state) channel.postMessage({error: 'state mismatch'})
else if (params.get('error')) channel.postMessage({error: params.get('error')})
else {
const r = await fetch('https://www.zztakeoff.com/oauth/token', {method: 'POST', body: new URLSearchParams({
grant_type: 'authorization_code', code: params.get('code'), client_id: CLIENT_ID,
redirect_uri: location.origin + '/callback.html', code_verifier: saved.verifier
})})
channel.postMessage(await r.json()) // store the tokens in the main page
}
window.close() // if the browser won't, tell the user to close it; never navigate back
document.body.textContent = 'Done. You can close this window.'
function b64 (bytes) {
return btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
}/api/script/runNEEDS A TABcodestring, requiredPlain JavaScript function body. Commands are globals; a top-level return sets the result. No await./api/eventsEVENT STREAMprojectIdstringOnly this project's eventsGET actions take arguments in the query string; POST actions take a JSON body.
curl -X POST https://www.zztakeoff.com/api/script/run \
-H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
-d '{"code": "return Takeoffs.list().records.length"}'GET /api/events keeps the connection open and sends a Server-Sent Event when the user opens or closes a project in zzTakeoff, changes page, or starts or stops a tool. Add ?projectId=… for one project's events only:
event: tool.started
data: {"projectId": "…", "tabId": "…", "order": 4, "tool": "area", "mode": "…", "pageId": "…", "takeoffId": "…", "drawObjectId": "…"}
event: tool.stopped
data: {"projectId": "…", "tabId": "…", "order": 5, "tool": "area", "pageId": "…", "takeoffId": "…", "drawObjectId": "…"}script/run; if one is already bound, it starts sending at once. You get a bound event once a tab is bound. If no tab is open, nobody picks one within 2 minutes, or the tab can't take it, you get unbound ({reason, message}) and the stream ends; reconnect to ask again.project.opened ({projectId, name}) comes when that tab opens or reloads a project.tool.stopped has a drawObjectId when the drawing was kept, and null when it was discarded.unbound (tab_away) and nothing arrives; bound again when it's back. If it isn't back within 2 minutes (or the user disconnects it), the stream ends; a new stream asks them to pick a tab again. A project stream gets nothing while the tab is on another project.EventSource can't send an Authorization header, so read the stream with fetch or from your own server.: heartbeat) arrive every 25 seconds.tabId; a new one after the tab reloads or reconnects) and its order on this stream (1, 2, 3…), for spotting a gap within one stream; it starts over on every stream.ready event with resumed: false: streams can't be resumed yet, so events from while you were disconnected aren't replayed; re-read what you show after a reconnect. Events carry no id until then, so there is no Last-Event-ID to send.curl -N "https://www.zztakeoff.com/api/events?projectId=PROJECT_ID" -H "Authorization: Bearer $TOKEN"script/run returns the tab's result as JSON, with a context object naming the workspace, project and page it acted on. A script that throws still answers 200 with success: false, error and logs. Other failures answer {error, error_description}:
invalid_requestA required argument is missing or has the wrong type.invalid_tokenMissing, expired or revoked token, or the app was suspended or deleted. Refresh it, or sign in again.insufficient_scopeThe token was issued for MCP, not the API.access_deniedThe user's license, role or workspace settings don't allow it, they can't see the project, or the app is not approved yet and the tab is in another workspace.not_foundNo such endpoint.method_not_allowedThe endpoint does not take that HTTP method; the Allow header lists the ones it does.rate_limitedMore than 60 requests a minute for this user.too_many_streamsThis user already has 10 event streams open.server_errorSomething went wrong on our side.no_tabNo zzTakeoff tab answered. Ask the user to open zzTakeoff and sign in.timeoutThe tab did not finish in time.