Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions PRIVACY.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,14 @@ and nothing else of your account: not its billing, its sign-ins, its export or i
a member and a member can leave at any time; deleting an account removes it from every team, and deletes its own team
and invite links.

## Partners

A partner is a product we agreed with that sets GenClass up for its own users. Its server makes a GenClass app for
each of them in the partner's own account, and the partner reads what that app sends and finds, as any account reads
its own apps. If a partner set GenClass up in your app, your app's data goes to that partner's account, and the
partner's own terms say what it does with it; we collect nothing more for it. We store the partner's id for each app
(its own id for you, which we ask partners not to make your email), and its partner keys only as one-way hashes.

## Paid plans, payments and Stripe

Free costs nothing, Pro (named Team until 12 November 2026) is sold on genclass.dev for an account, per developer
Expand Down
43 changes: 43 additions & 0 deletions telemetry-worker/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1265,6 +1265,49 @@ CLOUDFLARE_ACCOUNT_ID=144bd5f5270b51dbe7faf46227a154f0 npx --yes wrangler@4 d1 e
A worker keeps a key's answer in memory for up to 5 minutes (30 seconds for an unknown key), so a new extra key counts
within 30 seconds.

## Partner API

For a product that builds GenClass in for its own users (a coding-agent tool, a hosting or app-builder platform): its
server makes a GenClass app for each of its users, hands that user's code the app's key, and reads what the app finds.
The partner's account carries the apps and their plan, so its users need no GenClass account and no `genclass`
command (`src/partner.ts`, migration 0023).

**Making an account a partner** is done by hand with the agreement, as a grant is: GenClass's Enterprise grant so
every app is covered, and `partner_apps`, how many apps the account may hold (NULL: not a partner). The account then
sees a Partner API section in its settings on /account, where it makes, names and revokes up to 10 partner keys
(`gcp_` + 32 random bytes, shown once; only the SHA-256 is stored).

```bash
CLOUDFLARE_ACCOUNT_ID=144bd5f5270b51dbe7faf46227a154f0 npx --yes wrangler@4 d1 execute genclass-dashboard --remote \
--command "UPDATE accounts SET comp_plan = 'enterprise', comp_until = '<end of the agreement, ISO>', partner_apps = <n> WHERE lower(email) = lower('<email>')"
```

Ending it: `partner_apps = NULL` (every key stops at once; the apps stay in the account) and the grant's end date.

| route (key: `Authorization: Bearer gcp_...`) | behaviour |
|---|---|
| `POST /api/partner/v1/apps` | `{ ref, name? }`: `ref` is the partner's own id for its user, not an email (1 to 64 of `A-Z a-z 0-9 . _ : @ -`, starting with a letter or digit), unique in the account; `name` defaults to it. 201 `{ created: true, app }` the first time, 200 `{ created: false, app }` for a ref it has made before. `app`: `id, ref, name, key` (the app's public `gc_` key), `created, first_event, last_event, install` (`npx @genclass/runtime@beta init --token <key>`, which needs no sign-in) and `dashboard_url` (the partner's own view). 409 at the account's `partner_apps` (every app of the account counts); 429 under the creation limits every account has |
| `GET /api/partner/v1/apps?ref=&cursor=` | the apps the API made, oldest first, 100 a page: `{ apps, next_cursor, limit: { apps, used } }` |
| `GET /api/partner/v1/apps/<id>?range=24h\|7d\|30d` | the app's dashboard as data, cut by the account's plan: what `/api/cli/app` answers (`src/cli.ts` appView) |
| `GET /api/partner/v1/apps/<id>/events?from&to&format&limit&cursor` | its stored events: the export (`exportFor`, same rules and limits) |
| `POST /api/partner/v1/apps/<id>/link` | 201 `{ dashboard_url }`: a private dashboard link (`/dashboard/<secret>`) to hand that user; the previous link stops working |
| `GET`, `POST /api/account/partner-keys`; `DELETE .../<id>` | browser session on genclass.dev only: list, create (a partner only) and revoke partner keys |

Rules: a key reaches its own account's apps only (any other id is 404); a cookie, a terminal session or an export key
is never a partner key; the routes send no CORS headers, so a key is used from the partner's server, never a page.
Nothing here deletes an app or changes its key (that stays on the website). Every route counts against the account's
per-minute budget (`EXPORT_LIMIT`, bucket `partner`). An app made here is an ordinary app of the account: its plan,
history, analytics, email reports and dashboard are the account's.

How a coding agent uses it, per user: `POST /apps` with the user's id, run the `install` line in the user's project
(or set `token` in `GenClass.init` / `data-token` on the script tag), then read `GET /apps/<id>` for what it found, or
give the user the link from `POST /apps/<id>/link`.

```bash
curl -X POST https://genclass.dev/api/partner/v1/apps -H "Authorization: Bearer $GENCLASS_PARTNER_KEY" \
-H "content-type: application/json" -d '{"ref":"user_42","name":"Ada'"'"'s shop"}'
```

## Reports by email

A GenClass report about an account's apps goes to the account's email on the schedule it chooses, and an alert goes
Expand Down
21 changes: 21 additions & 0 deletions telemetry-worker/migrations/0023_partners.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
-- Partners (owner request, 2026-11-14): an account GenClass lets build GenClass into its own product. Its server makes
-- an app for each of its users through the partner API (src/partner.ts) and reads what those apps find. Set by hand
-- with the agreement, like comp_until (telemetry-worker/README.md "Partner API"). Additive only.

-- How many apps the account may hold when the partner API makes one; NULL: not a partner (every partner route is 403).
ALTER TABLE accounts ADD COLUMN partner_apps INTEGER;

-- The partner's own id for the user an app is for (unique in its account); NULL for every app not made by the API.
ALTER TABLE projects ADD COLUMN partner_ref TEXT;
CREATE UNIQUE INDEX IF NOT EXISTS projects_partner_ref ON projects (account_id, partner_ref) WHERE partner_ref IS NOT NULL;

-- Partner keys: `gcp_` + 32 random bytes, stored as a SHA-256 hex. They reach /api/partner/v1/* and nothing else.
CREATE TABLE IF NOT EXISTS partner_keys (
id TEXT PRIMARY KEY,
hash TEXT NOT NULL UNIQUE,
account_id TEXT NOT NULL,
label TEXT,
created TEXT NOT NULL,
last_used TEXT
);
CREATE INDEX IF NOT EXISTS partner_keys_account ON partner_keys (account_id);
39 changes: 37 additions & 2 deletions telemetry-worker/src/account-pages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -679,6 +679,8 @@ export interface AccountView {
* its first app (the owner's call, 2026-11-13: "our entire goal is for them to put their credit cards in").
*/
trial?: { plan: string; price: string; days: number | null; features: string[]; start: string } | null;
/** The partner API (src/partner.ts): how many apps the account may hold, how many it has, its keys. Null: not a partner. */
partner?: { apps: number; used: number; keys: { id: string; label: string | null; created: string; lastUsed: string | null }[] } | null;
}

const TRANSPORT_WORDS: Record<string, string> = {
Expand Down Expand Up @@ -941,7 +943,7 @@ ${planBlock}
${others ? '<div class="acct-form"><button class="btn ghost" type="button" id="others"><span>Sign out everywhere else</span></button></div>' : ""}
<p class="err" id="clierr" role="alert"></p>
</section>
<section class="blk" id="delete">
${partnerSection(v.partner)}<section class="blk" id="delete">
<div class="blk-h"><h2>Delete account</h2><span class="aside">Cannot be undone</span></div>
<p class="intro">Deletes this account. A paid plan is cancelled at once.</p>
<div class="acct-form"><button class="btn danger" type="button" id="del"><span>Delete account</span></button></div>
Expand All @@ -955,7 +957,7 @@ ${planBlock}
(function(){
gcDropQuery([]);
// views: Projects (the default) and Account settings; the hash names the part, so links and the back button work
var VIEW = { projects: "projects", apps: "projects", claim: "projects", "new-app": "projects", settings: "settings", security: "settings", password: "settings", passkeys: "settings", sessions: "settings", cli: "settings", "delete": "settings" };
var VIEW = { projects: "projects", apps: "projects", claim: "projects", "new-app": "projects", settings: "settings", security: "settings", password: "settings", passkeys: "settings", sessions: "settings", cli: "settings", partner: "settings", "delete": "settings" };
var parts = [].slice.call(document.querySelectorAll("[data-v]"));
function show(id, jump){
if (id === "new-app") { location.replace("/account/new"); return true; }
Expand Down Expand Up @@ -998,6 +1000,17 @@ ${planBlock}
});
}
del("[data-revoke]", "data-revoke", function(id){ return "/api/account/sessions/" + encodeURIComponent(id); }, "clierr", null);
del("[data-revokepk]", "data-revokepk", function(id){ return "/api/account/partner-keys/" + encodeURIComponent(id); }, "pterr", "Revoke? Its server stops at once");
var ptf = document.getElementById("ptf");
if (ptf) ptf.addEventListener("submit", function(ev){
ev.preventDefault();
var b = ptf.querySelector("button"), pe = document.getElementById("pterr"), out = document.getElementById("ptnew");
pe.textContent = ""; gcBusy(b, true, "Working...");
gcPost("/api/account/partner-keys", { label: document.getElementById("ptlabel").value }).then(function(j){
gcBusy(b, false); document.getElementById("ptlabel").value = "";
document.getElementById("ptkey").textContent = j.key; out.classList.remove("hidden");
}, function(e){ pe.textContent = gcWhy(e); gcBusy(b, false); });
});
// removing a passkey asks for a passkey first when this session has not used one in the last few minutes
document.querySelectorAll("[data-rmkey]").forEach(function(b){
b.addEventListener("click", function(){
Expand Down Expand Up @@ -1079,6 +1092,28 @@ ${planBlock}
});
}

/** The Partner API section of /account settings: shown only to an account GenClass made a partner. */
export function partnerSection(p: AccountView["partner"]): string {
if (!p) return "";
const keys = p.keys.length
? `<div class="tablewrap"><table class="dt rows"><thead><tr><th>Partner key</th><th>Created</th><th>Last used</th><th></th></tr></thead><tbody>${p.keys
.map((k) => `<tr><td>${esc(k.label ?? "Partner key")}</td><td data-l="Created">${time(k.created)}</td><td data-l="Last used">${time(k.lastUsed, "ago")}</td><td class="act"><button class="btn sm ghost" type="button" data-revokepk="${esc(k.id)}">Revoke</button></td></tr>`)
.join("")}</tbody></table></div>`
: '<p class="intro">No partner keys yet.</p>';
return `<section class="blk" id="partner">
<div class="blk-h"><h2>Partner API</h2><span class="aside">${p.used} of ${p.apps} apps</span></div>
<p class="intro">Your server makes an app for each of your users and reads what it finds. Keep keys on your server: a page in a browser cannot use them. <a href="${PARTNER_DOCS}">How it works</a></p>
${keys}
<form class="acct-form" id="ptf" novalidate><div class="f"><label for="ptlabel">New partner key</label><input id="ptlabel" type="text" maxlength="60" autocomplete="off" placeholder="Name, e.g. production server"></div><button class="btn ghost" type="submit"><span>Create partner key</span></button></form>
<div class="hidden" id="ptnew" role="status"><p class="intro">Copy it now: it is shown once.</p><pre class="code" id="ptkey"></pre></div>
<p class="err" id="pterr" role="alert"></p>
</section>
`;
}

/** Where the partner API is written down (telemetry-worker/README.md "Partner API"). */
export const PARTNER_DOCS = "https://github.com/genclass-dev/GenClass/blob/main/telemetry-worker/README.md#partner-api";

export interface NewProjectView {
account: AccountView["account"];
/** The account's projects (the header's switcher) and its plan's name (the organization's badge). */
Expand Down
24 changes: 22 additions & 2 deletions telemetry-worker/src/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ export const FRESH_MS = 5 * MINUTE;
/** Where to write about an account whose passkeys are all lost, or whose password is forgotten (no email reset yet). */
export const RECOVERY_CONTACT = "mehar@genclass.dev";
/** Global ceiling on apps created in accounts per minute (anonymous creation has its own, collector.ts). */
const MAX_ACCOUNT_PROJECTS_PER_MINUTE = 60;
export const MAX_ACCOUNT_PROJECTS_PER_MINUTE = 60;

/** The web session cookie: __Host- on HTTPS; the plain name only for plain-HTTP localhost in development. */
export const SESSION_COOKIE = "__Host-gc_session";
Expand Down Expand Up @@ -1808,10 +1808,12 @@ async function deleteAccount(c: C): Promise<Response> {
c.db.prepare(`DELETE FROM integrations WHERE project_id IN (${owned})`).bind(id),
c.db.prepare(`DELETE FROM forward_log WHERE project_id IN (${owned})`).bind(id),
c.db.prepare("DELETE FROM export_keys WHERE account_id = ?").bind(id),
c.db.prepare("DELETE FROM partner_keys WHERE account_id = ?").bind(id),
c.db.prepare("DELETE FROM custom_requests WHERE account_id = ?").bind(id),
...["daily", "hourly", "recent", "sessions", "visits"].map((t) => c.db.prepare(`DELETE FROM ${t} WHERE token IN (${own})`).bind(id)),
c.db.prepare("DELETE FROM projects WHERE account_id = ? AND private_link = 0").bind(id),
c.db.prepare("UPDATE projects SET account_id = NULL WHERE account_id = ?").bind(id),
// an app that keeps its private link (one the partner API handed its user, too) leaves without its partner ref
c.db.prepare("UPDATE projects SET account_id = NULL, partner_ref = NULL WHERE account_id = ?").bind(id),
c.db.prepare("DELETE FROM credentials WHERE account_id = ?").bind(id),
c.db.prepare("DELETE FROM passwords WHERE account_id = ?").bind(id),
c.db.prepare("DELETE FROM password_devices WHERE account_id = ?").bind(id),
Expand Down Expand Up @@ -1883,6 +1885,24 @@ async function accountView(c: C, a: Auth): Promise<AccountView> {
pick: { claim: c.url.searchParams.get("claim") === "1", save: c.url.searchParams.get("save") === "1" },
recovery: RECOVERY_CONTACT,
githubApp: githubApp(c.env) !== null,
partner: await partnerView(c, a.account.id),
};
}

/** The partner API's section of /account (src/partner.ts): only for an account GenClass made a partner. */
async function partnerView(c: C, accountId: string): Promise<AccountView["partner"]> {
const acct = await c.db.prepare("SELECT partner_apps FROM accounts WHERE id = ?").bind(accountId).first<{ partner_apps: number | null }>();
const apps = Number(acct?.partner_apps ?? 0);
if (!(apps > 0)) return null;
const [used, keys] = await c.db.batch([
c.db.prepare("SELECT COUNT(*) AS n FROM projects WHERE account_id = ?").bind(accountId),
c.db.prepare("SELECT id, label, created, last_used FROM partner_keys WHERE account_id = ? ORDER BY created").bind(accountId),
]);
const rows = (r: unknown) => ((r as { results?: Record<string, unknown>[] })?.results ?? []) as Record<string, unknown>[];
return {
apps,
used: Number(rows(used)[0]?.n ?? 0),
keys: rows(keys).map((k) => ({ id: String(k.id), label: (k.label as string | null) ?? null, created: String(k.created), lastUsed: (k.last_used as string | null) ?? null })),
};
}

Expand Down
10 changes: 9 additions & 1 deletion telemetry-worker/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ import { answer, appDigest, MAX_ASK_BYTES, readQuestion } from "./ask.js";
import { accountContext, accountJson, accountProjects, authenticate, fail, lockedJson, makeLinkFor, ownedProject, projectJson, readableProject, readJson, upgradeJson, type Auth, type C } from "./auth.js";
import { exportFor, integrationsFor, overBudget, tooMany, trialFor } from "./billing.js";
import type { Env, HandleOptions } from "./collector.js";
import { putFunnels, stats, stripAnalytics, stripProblems } from "./dashboard.js";
import { putFunnels, stats, stripAnalytics, stripProblems, type Project } from "./dashboard.js";
import { isKind, KINDS } from "./forward.js";
import { githubApp } from "./github/config.js";
import { repoStatusForAccount } from "./github/http.js";
Expand Down Expand Up @@ -228,6 +228,14 @@ async function app(c: C): Promise<Response> {
}
const p = await readableProject(c, a.account.id, c.url.searchParams.get("id") ?? "");
if (!p) return fail(404, "not found");
return appView(c, p);
}

/**
* An app's dashboard as data (?range=), cut by its plan: what the browser dashboard reads. Shared by /api/cli/app and
* the partner API (src/partner.ts); the caller has checked that the account may read the app.
*/
export async function appView(c: C, p: Project): Promise<Response> {
// the same plan rules as the dashboard page's own request (src/auth.ts, /api/account/projects/<id>/stats)
const access = await projectAccess(c.db, p, c.env, c.now);
if (!hasDashboard(access)) return lockedJson(c, access, p.id);
Expand Down
4 changes: 4 additions & 0 deletions telemetry-worker/src/collector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ import type { EmailBinding } from "./report.js";
import type { GithubEnv } from "./github/config.js";
import { routeGithub } from "./github/http.js";
import { routeCli } from "./cli.js";
import { routePartner } from "./partner.js";
import { json, readCapped } from "./http.js";
import { afterBatch } from "./paid.js";
import { dashboardPage, notFoundPage, openSourcePage, ownEndpoint, securityHeaders, setupCommand, setupPage, startPage } from "./pages.js";
Expand Down Expand Up @@ -248,6 +249,9 @@ export async function handle(request: Request, env: Env, opts: HandleOptions = {
// the `genclass` command's routes (src/cli.ts): /api/cli/*
const cli = await routeCli(request, url, path, env, opts);
if (cli) return cli;
// the partner API (src/partner.ts): /api/partner/* and /api/account/partner-keys, before the account routes
const partner = await routePartner(request, url, path, env, opts);
if (partner) return partner;
const billing = await routeBilling(request, url, path, env, opts);
if (billing) return billing;
// teams (src/team-routes.ts): /api/team and the invite page /account/join/<code>, before the account routes
Expand Down
15 changes: 11 additions & 4 deletions telemetry-worker/src/dashboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,13 +129,15 @@ export const PROJECT_COLUMNS = "id, token, name, created, last_event, first_even
/**
* Create a project. Without an account it is reachable through its private dashboard link (the secret, returned once).
* With an account the secret is generated and hashed the same way (the column is required) but the caller does not
* show it and `private_link` is 0: the app is opened from the account only.
* show it and `private_link` is 0: the app is opened from the account only. `partnerRef`: the partner API's id for
* the user the app is for (src/partner.ts), unique in the account, so a second insert for it fails.
*/
export async function createProject(
db: D1Like,
name: string,
now: Date,
accountId: string | null = null,
partnerRef: string | null = null,
): Promise<{ id: string; token: string; secret: string; name: string; created: string }> {
for (let attempt = 0; ; attempt++) {
const id = newProjectId();
Expand All @@ -144,13 +146,18 @@ export async function createProject(
const created = now.toISOString();
try {
await db
.prepare("INSERT INTO projects (id, token, secret_hash, name, created, account_id, private_link) VALUES (?, ?, ?, ?, ?, ?, ?)")
.bind(id, token, await sha256Hex(secret), name, created, accountId, accountId ? 0 : 1)
.prepare(
partnerRef === null
? "INSERT INTO projects (id, token, secret_hash, name, created, account_id, private_link) VALUES (?, ?, ?, ?, ?, ?, ?)"
: "INSERT INTO projects (id, token, secret_hash, name, created, account_id, private_link, partner_ref, plan_chosen) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
)
.bind(id, token, await sha256Hex(secret), name, created, accountId, accountId ? 0 : 1, ...(partnerRef === null ? [] : [partnerRef, created]))
.run();
tokenCache.set(token, { token, exp: now.getTime() + CACHE_OK_MS });
return { id, token, secret, name, created };
} catch (e) {
if (attempt >= 2) throw e; // a collision is astronomically unlikely; anything else is a real error
// a collision is astronomically unlikely; anything else is a real error (for a partner app: most often its ref is taken)
if (attempt >= 2 || partnerRef !== null) throw e;
}
}
}
Expand Down
Loading
Loading