Skip to content
Merged
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
15 changes: 8 additions & 7 deletions packages/app/src/flow-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,14 @@ export class ApiService {

private async authorize(scope: Scope): Promise<void> {
if (!this.auth.scopes.includes(scope)) throw new ServiceError(403, "insufficient_scope", `The ${scope} scope is required.`);
const response = await this.stub().fetch(`https://tenant/members/${encodeURIComponent(this.auth.userId)}`);
if (!response.ok) throw new ServiceError(401, "invalid_token", "The resource owner is no longer a member.");
const member = await response.json() as { role?: string; session_version?: number };
if (member.role !== "owner" || member.session_version !== this.auth.sessionVersion) throw new ServiceError(401, "invalid_token", "The resource owner's session has been revoked.");
if (this.auth.accessTokenId) {
const token = await this.stub().fetch(`https://tenant/access-tokens/${encodeURIComponent(this.auth.accessTokenId)}/active`);
if (!token.ok) throw new ServiceError(401, "invalid_token", "The access token has expired or been revoked.");
const response = await this.stub().fetch("https://tenant/authorize", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ userId: this.auth.userId, sessionVersion: this.auth.sessionVersion, accessTokenId: this.auth.accessTokenId }),
});
if (!response.ok) {
const body = await response.json().catch(() => ({})) as { error?: string };
throw new ServiceError(401, "invalid_token", body.error ?? "The request is not authorized.");
}
}

Expand Down
13 changes: 13 additions & 0 deletions packages/app/src/tenant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,7 @@ export class TenantV2 extends DurableObject<Env> {
if (request.method === "PUT" && url.pathname === "/connections/clickup") return await this.saveClickUp(await request.json());
if (request.method === "PUT" && url.pathname === "/connections/exe") return await this.saveExe(await request.json());
if (request.method === "POST" && url.pathname === "/connections/exe/test") return await this.testExe(await request.json());
if (request.method === "POST" && url.pathname === "/authorize") return this.authorize(await request.json());
const exeModelsMatch = url.pathname.match(/^\/connections\/exe\/([^/]+)\/models$/);
if (request.method === "POST" && exeModelsMatch) return await this.refreshExeModels(decodeURIComponent(exeModelsMatch[1]));
if (request.method === "PUT" && url.pathname === "/connections/amp") return await this.saveAmp(await request.json());
Expand Down Expand Up @@ -1716,6 +1717,18 @@ export class TenantV2 extends DurableObject<Env> {
return member ? json(member) : new Response("Not found", { status: 404 });
}

private authorize(input: unknown): Response {
const value = object(input);
const userId = text(value.userId);
const sessionVersion = Number(value.sessionVersion);
const accessTokenId = text(value.accessTokenId);
const member = this.one("SELECT role,session_version FROM members WHERE user_id = ?", userId) as Row | undefined;
if (!member) return Response.json({ error: "The resource owner is no longer a member." }, { status: 401 });
if (member.role !== "owner" || Number(member.session_version) !== sessionVersion) return Response.json({ error: "The resource owner's session has been revoked." }, { status: 401 });
if (accessTokenId && !this.one("SELECT id FROM access_tokens WHERE id=? AND revoked_at IS NULL AND expires_at>?", accessTokenId, now())) return Response.json({ error: "The access token has expired or been revoked." }, { status: 401 });
return json({ authorized: true });
}

private revokeMember(userId: string): Response {
this.ctx.storage.sql.exec("UPDATE members SET session_version = session_version + 1 WHERE user_id = ?", userId);
return json({ ok: true });
Expand Down
35 changes: 32 additions & 3 deletions packages/app/test/flow-service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,21 @@ const auth: OAuthProps = { tenantId: "tenant-a", userId: "owner-a", sessionVersi

describe("ApiService", () => {
it("invalidates tokens when the owner session version changes", async () => {
const service = new ApiService(environment(() => Response.json({ role: "owner", session_version: 5 })), auth);
const requests: Request[] = [];
const service = new ApiService(environment(request => {
requests.push(request);
return Response.json({ error: "The resource owner's session has been revoked." }, { status: 401 });
}), auth);
await expect(service.listJobs()).rejects.toMatchObject({ status: 401, code: "invalid_token" });
const authorizationRequests = requests.filter(request => new URL(request.url).pathname === "/authorize");
expect(authorizationRequests).toHaveLength(1);
});

it("uses flow scopes for job management and run scopes for invocation", async () => {
const requests: string[] = [];
const service = new ApiService(environment(request => {
const path = new URL(request.url).pathname;
if (path === "/members/owner-a") return Response.json({ role: "owner", session_version: 4 });
if (path === "/authorize") return Response.json({ authorized: true });
requests.push(`${request.method} ${path}`);
return Response.json({ ok: true });
}), { ...auth, scopes: ["flows:read", "flows:write", "runs:write"] });
Expand All @@ -33,7 +39,7 @@ describe("ApiService", () => {
const installations = [{ installationId: 123, accountLogin: "generation", accountType: "Organization", state: "active", updatedAt: "2026-09-17T00:00:00.000Z" }];
const service = new ApiService(environment(request => {
const path = new URL(request.url).pathname;
if (path === "/members/owner-a") return Response.json({ role: "owner", session_version: 4 });
if (path === "/authorize") return Response.json({ authorized: true });
if (path === "/github/installations") return Response.json(installations);
return new Response("Not found", { status: 404 });
}), auth);
Expand All @@ -43,6 +49,29 @@ describe("ApiService", () => {
});
});

describe("authorization round trip", () => {
it.each([
["valid", Response.json({ authorized: true }), undefined],
["revoked token", Response.json({ error: "The access token has expired or been revoked." }, { status: 401 }), "The access token has expired or been revoked."],
["removed member", Response.json({ error: "The resource owner is no longer a member." }, { status: 401 }), "The resource owner is no longer a member."],
["session mismatch", Response.json({ error: "The resource owner's session has been revoked." }, { status: 401 }), "The resource owner's session has been revoked."],
])("handles %s authorization in one request", async (_name, response, message) => {
const requests: Request[] = [];
const service = new ApiService(environment(request => {
requests.push(request);
return new URL(request.url).pathname === "/authorize" ? response : Response.json([]);
}), auth);
if (message) await expect(service.listJobs()).rejects.toMatchObject({ status: 401, message });
else {
const result = await service.listJobs();
expect(result).toEqual([]);
}
const authorizationRequests = requests.filter(request => new URL(request.url).pathname === "/authorize");
expect(authorizationRequests).toHaveLength(1);
expect(new URL(authorizationRequests[0].url).pathname).toBe("/authorize");
});
});

describe("shared API schemas", () => {
it("bounds pagination and run states", () => {
expect(listRunsSchema.parse({ limit: "100", state: "running", contextQuery: "literal.*text" })).toMatchObject({ limit: 100, state: "running", contextQuery: "literal.*text" });
Expand Down