Skip to content

An open-source, faster Devin alternative

TypeScript

api-edge: accept team invitations on login and create WorkOS org lazily

Devin AI1f753e7bd904
diff --git a/cloudflare-workers/api-edge/src/cli_auth.test.ts b/cloudflare-workers/api-edge/src/cli_auth.test.ts
index 946c84f0..97e5ca67 100644
--- a/cloudflare-workers/api-edge/src/cli_auth.test.ts
+++ b/cloudflare-workers/api-edge/src/cli_auth.test.ts
@@ -58,6 +58,9 @@ class FakeStatement {
}
async all<T>(): Promise<{ results: T[] }> {
+ if (this.sql.includes("FROM invitations")) {
+ return { results: this.db.pendingInvitations as T[] };
+ }
if (this.sql.includes("JOIN org_memberships")) {
return { results: this.db.memberships as T[] };
}
@@ -88,6 +91,7 @@ class FakeStatement {
class FakeDB {
executed: CapturedStatement[] = [];
memberships: FakeMembership[];
+ pendingInvitations: { id: string; org_id: string; role: string }[] = [];
user: { id: string; email: string; name: string } | null;
constructor(
@@ -113,6 +117,10 @@ class FakeDB {
prepare(sql: string): FakeStatement {
return new FakeStatement(this, sql);
}
+
+ async batch(stmts: FakeStatement[]): Promise<Record<string, never>[]> {
+ return Promise.all(stmts.map((s) => s.run()));
+ }
}
function testEnv(db = new FakeDB()): Env {
@@ -509,6 +517,36 @@ describe("CLI device authorization edge contract", () => {
expect(insert?.args[1]).toBe(mappedOrgID);
});
+ it("accepts pending invitations for the login email and lands in the invited org", async () => {
+ const teamOrgID = "44444444-4444-4444-8444-444444444444";
+ const db = new FakeDB([
+ {
+ id: orgID,
+ name: "Personal",
+ plan: "free",
+ is_personal: 1,
+ workos_org_id: null,
+ membership_created_at: 1,
+ org_created_at: 1,
+ },
+ ]);
+ db.pendingInvitations = [{ id: "inv-1", org_id: teamOrgID, role: "admin" }];
+ vi.stubGlobal("fetch", vi.fn(async () => Response.json({
+ user: { id: "workos-user", email: "[email protected]", first_name: "Igor" },
+ })));
+ const resp = await worker.fetch(request("/auth/cli/device/exchange", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ device_code: "opaque", credential_name: "oc CLI" }),
+ }), testEnv(db), ctx);
+ expect(resp.status).toBe(200);
+
+ const membershipInsert = db.executed.find((entry) => entry.sql.includes("INSERT INTO org_memberships"));
+ expect(membershipInsert?.args.slice(0, 3)).toEqual([teamOrgID, userID, "admin"]);
+ const accepted = db.executed.find((entry) => entry.sql.includes("SET status = 'accepted'"));
+ expect(accepted?.args[1]).toBe("inv-1");
+ });
+
it("provisions a first-login user, personal org, owner membership, and key", async () => {
const db = new FakeDB([], null);
vi.stubGlobal("fetch", vi.fn(async () => Response.json({
diff --git a/cloudflare-workers/api-edge/src/dashboard.ts b/cloudflare-workers/api-edge/src/dashboard.ts
index 5575b6a7..63e16b3f 100644
--- a/cloudflare-workers/api-edge/src/dashboard.ts
+++ b/cloudflare-workers/api-edge/src/dashboard.ts
@@ -549,15 +549,26 @@ async function handleSendInvitation(req: Request, env: DashboardEnv, caller: Cal
if (!email) return json({ error: "email required" }, 400);
if (!["owner", "admin", "member"].includes(role)) return json({ error: "invalid role" }, 400);
+ const now = Math.floor(Date.now() / 1000);
// WorkOS invitation send. Returns the WorkOS invitation ID we mirror in D1.
- const org = await env.OPENCOMPUTER_DB.prepare(`SELECT workos_org_id FROM orgs WHERE id = ?1`).bind(caller.orgID).first<{ workos_org_id: string | null }>();
+ // Orgs provisioned at the edge have no WorkOS org yet; create one lazily so
+ // WorkOS can deliver the invitation email.
+ const org = await env.OPENCOMPUTER_DB.prepare(`SELECT name, workos_org_id FROM orgs WHERE id = ?1`).bind(caller.orgID).first<{ name: string; workos_org_id: string | null }>();
+ let workosOrgID = org?.workos_org_id ?? null;
+ if (org && !workosOrgID) {
+ workosOrgID = await workosCreateOrg(env, org.name);
+ if (workosOrgID) {
+ await env.OPENCOMPUTER_DB.prepare(`UPDATE orgs SET workos_org_id = ?1, updated_at = ?2 WHERE id = ?3 AND workos_org_id IS NULL`)
+ .bind(workosOrgID, now, caller.orgID).run();
+ }
+ }
let workosInviteID: string | null = null;
- if (org?.workos_org_id) {
+ if (workosOrgID) {
try {
const r = await fetch("https://api.workos.com/user_management/invitations", {
method: "POST",
headers: { "content-type": "application/json", authorization: `Bearer ${env.WORKOS_API_KEY}` },
- body: JSON.stringify({ email, organization_id: org.workos_org_id, expires_in_days: 7, role_slug: role }),
+ body: JSON.stringify({ email, organization_id: workosOrgID, expires_in_days: 7, role_slug: role }),
});
if (r.ok) {
const data = await r.json<{ id: string }>();
@@ -571,7 +582,6 @@ async function handleSendInvitation(req: Request, env: DashboardEnv, caller: Cal
}
const id = crypto.randomUUID();
- const now = Math.floor(Date.now() / 1000);
await env.OPENCOMPUTER_DB.prepare(
`INSERT INTO invitations (id, org_id, email, role, invited_by, workos_invitation_id, status, expires_at, created_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, 'pending', ?7, ?8)`,
@@ -867,6 +877,25 @@ async function handleListAgentSubscriptions(_req: Request, env: DashboardEnv, ca
// ── WorkOS helpers ───────────────────────────────────────────────────────
+async function workosCreateOrg(env: DashboardEnv, name: string): Promise<string | null> {
+ try {
+ const r = await fetch("https://api.workos.com/organizations", {
+ method: "POST",
+ headers: { "content-type": "application/json", authorization: `Bearer ${env.WORKOS_API_KEY}` },
+ body: JSON.stringify({ name }),
+ });
+ if (!r.ok) {
+ console.error(`workos org create returned ${r.status}: ${await r.text()}`);
+ return null;
+ }
+ const data = await r.json<{ id?: string }>();
+ return data.id ?? null;
+ } catch (e) {
+ console.error("workos org create threw", e);
+ return null;
+ }
+}
+
async function workosUpdateOrg(env: DashboardEnv, workosOrgID: string, name: string): Promise<void> {
await fetch(`https://api.workos.com/organizations/${workosOrgID}`, {
method: "PUT",
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index bd30e151..52b89161 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -3770,6 +3770,48 @@ async function authLogin(req: Request, env: Env): Promise<Response> {
return Response.redirect(authURL.toString(), 302);
}
+/**
+ * Converts every pending, unexpired invitation addressed to `email` into an
+ * org membership. Returns the most recently invited org's id (if any) so the
+ * login can land the user in the team they were invited to.
+ */
+export async function acceptPendingInvitations(
+ env: Pick<Env, "OPENCOMPUTER_DB">,
+ userID: string,
+ email: string,
+ nowSec: number,
+): Promise<string | null> {
+ const normalized = email.trim().toLowerCase();
+ if (!normalized) return null;
+ const { results } = await env.OPENCOMPUTER_DB.prepare(
+ `SELECT id, org_id, role FROM invitations
+ WHERE lower(email) = ?1 AND status = 'pending'
+ AND (expires_at IS NULL OR expires_at > ?2)
+ ORDER BY created_at DESC`,
+ )
+ .bind(normalized, nowSec)
+ .all<{ id: string; org_id: string; role: string }>();
+ const pending = results ?? [];
+ if (pending.length === 0) return null;
+
+ const statements: D1PreparedStatement[] = [];
+ for (const inv of pending) {
+ const role = ["owner", "admin", "member"].includes(inv.role) ? inv.role : "member";
+ statements.push(
+ env.OPENCOMPUTER_DB.prepare(
+ `INSERT INTO org_memberships (org_id, user_id, role, created_at)
+ VALUES (?1, ?2, ?3, ?4)
+ ON CONFLICT(org_id, user_id) DO NOTHING`,
+ ).bind(inv.org_id, userID, role, nowSec),
+ env.OPENCOMPUTER_DB.prepare(
+ `UPDATE invitations SET status = 'accepted', accepted_at = ?1 WHERE id = ?2 AND status = 'pending'`,
+ ).bind(nowSec, inv.id),
+ );
+ }
+ await env.OPENCOMPUTER_DB.batch(statements);
+ return pending[0].org_id;
+}
+
/**
* Upserts the WorkOS user and guarantees at least one local membership.
* Browser login deliberately preserves its historical "first membership"
@@ -3819,6 +3861,12 @@ async function provisionWorkOSIdentity(
}
const userID = userRow.id;
+ const invitedOrgID = await acceptPendingInvitations(
+ env,
+ userID,
+ userRow.email || profile.email,
+ nowSec,
+ );
type MembershipRow = {
id: string;
name: string;
@@ -3829,8 +3877,21 @@ async function provisionWorkOSIdentity(
org_created_at: number;
};
- const selectBrowserMembership = () =>
- env.OPENCOMPUTER_DB.prepare(
+ const selectBrowserMembership = async (): Promise<MembershipRow | null> => {
+ if (invitedOrgID) {
+ const invited = await env.OPENCOMPUTER_DB.prepare(
+ `SELECT o.id, o.name, o.plan, o.is_personal, o.workos_org_id,
+ m.created_at AS membership_created_at, o.created_at AS org_created_at
+ FROM orgs o
+ JOIN org_memberships m ON m.org_id = o.id
+ WHERE m.user_id = ?1 AND o.id = ?2
+ LIMIT 1`,
+ )
+ .bind(userID, invitedOrgID)
+ .first<MembershipRow>();
+ if (invited) return invited;
+ }
+ return env.OPENCOMPUTER_DB.prepare(
`SELECT o.id, o.name, o.plan, o.is_personal, o.workos_org_id,
m.created_at AS membership_created_at, o.created_at AS org_created_at
FROM orgs o
@@ -3840,6 +3901,7 @@ async function provisionWorkOSIdentity(
)
.bind(userID)
.first<MembershipRow>();
+ };
const selectCLIMembership = async (): Promise<MembershipRow | null> => {
const { results } = await env.OPENCOMPUTER_DB.prepare(