This page gets an org-scoped token for code that runs with nobody at the keyboard: a nightly import, a form handler, a sync with your own records. You need to be on the organization's staff with a role that allows what the job does, and a confidential app registered to the organization.
An org-scoped token comes from exchanging a user token, and a user token comes from somebody signing in. So a staff member authorizes the app once, by hand, the job stores the refresh token, and every run turns it into an org-scoped token:
once staff member → sign in → code → refresh token (stored)
each run refresh token → user access token (store the new refresh token)
user access token → exchange → org-scoped token
org-scoped token → API call
A client credentials token carries no organization, so organization endpoints refuse it.
1. Configure the app
On the app's page under Developer → Apps:
- Add the redirect URI
http://localhost:8765/callback. The one-time authorization below listens there. - Add the scopes the job needs, for example
reward:read reward:redeem. - Enable Token exchange. A new app does not have it, and without it every run fails at the exchange.
2. Authorize once
Save this as connect.mjs and run it with Node 18 or later, on a machine with a
browser:
// node connect.mjs
import { createServer } from "node:http";
import { createHash, randomBytes } from "node:crypto";
import { writeFileSync } from "node:fs";
const CLIENT_ID = process.env.DAVI_CLIENT_ID;
const CLIENT_SECRET = process.env.DAVI_CLIENT_SECRET;
const SCOPES = "reward:read reward:redeem";
const REDIRECT_URI = "http://localhost:8765/callback";
const b64url = (buf) => buf.toString("base64url");
const verifier = b64url(randomBytes(32));
const challenge = b64url(createHash("sha256").update(verifier).digest());
const state = b64url(randomBytes(16));
const url = new URL("https://davi.social/oauth/authorize");
url.search = new URLSearchParams({
response_type: "code",
client_id: CLIENT_ID,
redirect_uri: REDIRECT_URI,
scope: SCOPES,
state,
code_challenge: challenge,
code_challenge_method: "S256",
});
console.log("Open this URL, signed in to Davi:\n" + url);
const server = createServer(async (req, res) => {
const params = new URL(req.url, REDIRECT_URI).searchParams;
if (params.get("state") !== state) return res.end("State mismatch.");
if (params.get("error")) return res.end("Refused: " + params.get("error"));
const response = await fetch("https://api.davi.social/oauth2/token", {
method: "POST",
headers: {
Authorization:
"Basic " + Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString("base64"),
},
body: new URLSearchParams({
grant_type: "authorization_code",
code: params.get("code"),
redirect_uri: REDIRECT_URI,
code_verifier: verifier,
}),
});
const tokens = await response.json();
if (!response.ok) {
res.end("Token request failed: " + JSON.stringify(tokens));
} else {
writeFileSync("davi-refresh-token", tokens.refresh_token, { mode: 0o600 });
console.log("Granted scopes:", tokens.scope);
res.end("Connected to Davi. You can close this tab.");
}
server.close();
});
server.listen(8765);
Open the URL it prints, sign in as the staff member the job acts for, and
approve. The refresh token lands in davi-refresh-token. Move it to wherever
the job keeps secrets, and treat it like the client secret.
Check the granted scopes it prints. A scope the staff member's role does not allow is left out rather than refused.
3. Get an org-scoped token on each run
// davi.mjs
const CLIENT_ID = process.env.DAVI_CLIENT_ID;
const CLIENT_SECRET = process.env.DAVI_CLIENT_SECRET;
const ORG_SLUG = process.env.DAVI_ORG_SLUG;
async function token(form) {
const response = await fetch("https://api.davi.social/oauth2/token", {
method: "POST",
headers: {
Authorization:
"Basic " + Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString("base64"),
},
body: new URLSearchParams(form),
});
const body = await response.json();
if (!response.ok) {
throw new Error(`${form.grant_type} failed: ${body.error_description ?? body.error}`);
}
return body;
}
// store: { read(): Promise<string>, write(value: string): Promise<void> }
export async function getOrgToken(store) {
const user = await token({
grant_type: "refresh_token",
refresh_token: await store.read(),
});
await store.write(user.refresh_token); // before anything else can fail
const org = await token({
grant_type: "urn:ietf:params:oauth:grant-type:token-exchange",
subject_token: user.access_token,
subject_token_type: "urn:ietf:params:oauth:token-type:access_token",
resource: `org:${ORG_SLUG}`,
});
return org.access_token; // valid for expires_in seconds, usually one hour
}
import { readFile, writeFile } from "node:fs/promises";
import { getOrgToken } from "./davi.mjs";
const fileStore = {
read: async () => (await readFile("davi-refresh-token", "utf8")).trim(),
write: (value) => writeFile("davi-refresh-token", value, { mode: 0o600 }),
};
const orgToken = await getOrgToken(fileStore);
const reward = await fetch("https://api.davi.social/api/v1/rewards/REWARD_SLUG", {
headers: { Authorization: `Bearer ${orgToken}` },
});
console.log(reward.status, await reward.json());
Store the new refresh token before using anything else. Each refresh retires the token it was given, and presenting a retired one revokes the session. A run that refreshes, then crashes before saving, leaves the job holding a dead token.
Run one refresh at a time. Two runs that refresh concurrently race, and the
loser's token counts as a replay that revokes the session. If runs can overlap,
take a lock around getOrgToken, and cache the org-scoped token until shortly
before expires_in so most runs skip the refresh entirely.
Keep it connected
The connection lasts until one of these happens, and then the job's calls start
failing and somebody has to run connect.mjs again:
- The refresh token goes unused for 30 days. Each refresh starts a new window, so a job that runs less often than monthly needs a scheduled refresh that does nothing else.
- The staff member leaves the organization's staff, or their role no longer allows what the job does. Authorize as somebody whose place on the team outlasts the job.
- The staff member revokes the app from their Davi settings.
Make the failure loud. The error from the token endpoint names the grant that failed, and a job that logs it and stops is easy to reconnect.
Next
- Rewarding a Google Form Submission: this pattern as a complete Apps Script, with no server.
- Act as an Organization: the exchange in detail.
- Philosophy: making a job safe to re-run.