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
4 changes: 2 additions & 2 deletions .github/workflows/e2e-api.yml
Original file line number Diff line number Diff line change
Expand Up @@ -96,9 +96,9 @@ jobs:
if: steps.doc_check.outputs.run_tests == 'true'
run: bun install --frozen-lockfile

- name: Install Chromium
- name: Install Playwright browsers
if: steps.doc_check.outputs.run_tests == 'true'
run: bunx playwright install --with-deps chromium
run: ./packages/backend/node_modules/.bin/playwright install --with-deps

- name: Install Venom
if: steps.doc_check.outputs.run_tests == 'true'
Expand Down
119 changes: 119 additions & 0 deletions apps/web/src/app/api/auth/refresh/route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import { beforeEach, describe, expect, it, vi } from "vitest";

const refreshWorkOsAccessToken = vi.fn();

vi.mock("@/lib/workos-device-auth", () => ({
refreshWorkOsAccessToken,
}));

describe("POST /api/auth/refresh", () => {
beforeEach(() => {
refreshWorkOsAccessToken.mockReset();
});

it("returns 400 for invalid JSON payloads", async () => {
const { POST } = await import("./route");
const traceId = "11111111-1111-4111-8111-111111111111";

const response = await POST(
new Request("http://localhost/api/auth/refresh", {
method: "POST",
headers: {
"content-type": "application/json",
"x-trace-id": traceId,
},
body: "{",
})
);

expect(response.status).toBe(400);
expect(response.headers.get("x-trace-id")).toBe(traceId);
await expect(response.json()).resolves.toEqual({
error: "Invalid JSON payload",
});
});

it("returns 400 when refreshToken is missing", async () => {
const { POST } = await import("./route");
const traceId = "22222222-2222-4222-8222-222222222222";

const response = await POST(
new Request("http://localhost/api/auth/refresh", {
method: "POST",
headers: {
"content-type": "application/json",
"x-trace-id": traceId,
},
body: JSON.stringify({}),
})
);

expect(response.status).toBe(400);
expect(response.headers.get("x-trace-id")).toBe(traceId);
await expect(response.json()).resolves.toEqual({
error: "refreshToken is required",
});
expect(refreshWorkOsAccessToken).not.toHaveBeenCalled();
});

it("returns refreshed credentials on success", async () => {
refreshWorkOsAccessToken.mockResolvedValue({
status: "success",
accessToken: "fresh-access",
refreshToken: "fresh-refresh",
accessTokenExpiresAt: 123,
});

const { POST } = await import("./route");
const traceId = "33333333-3333-4333-8333-333333333333";

const response = await POST(
new Request("http://localhost/api/auth/refresh", {
method: "POST",
headers: {
"content-type": "application/json",
"x-trace-id": traceId,
},
body: JSON.stringify({ refreshToken: "stored-refresh-token" }),
})
);

expect(response.status).toBe(200);
expect(response.headers.get("x-trace-id")).toBe(traceId);
expect(refreshWorkOsAccessToken).toHaveBeenCalledWith({
refreshToken: "stored-refresh-token",
});
await expect(response.json()).resolves.toEqual({
status: "success",
accessToken: "fresh-access",
refreshToken: "fresh-refresh",
accessTokenExpiresAt: 123,
});
});

it("passes through invalid_grant responses", async () => {
refreshWorkOsAccessToken.mockResolvedValue({
status: "invalid_grant",
});

const { POST } = await import("./route");
const traceId = "44444444-4444-4444-8444-444444444444";

const response = await POST(
new Request("http://localhost/api/auth/refresh", {
method: "POST",
headers: {
"content-type": "application/json",
"x-trace-id": traceId,
},
body: JSON.stringify({ refreshToken: "expired-refresh-token" }),
})
);

expect(response.status).toBe(200);
expect(response.headers.get("x-trace-id")).toBe(traceId);
await expect(response.json()).resolves.toEqual({
status: "invalid_grant",
});
});
});
69 changes: 69 additions & 0 deletions apps/web/src/app/api/auth/refresh/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { createTraceId, normalizeTraceId } from "@sketchi/shared";

import { refreshWorkOsAccessToken } from "@/lib/workos-device-auth";

export async function POST(request: Request) {
const traceId =
normalizeTraceId(request.headers.get("x-trace-id")) ?? createTraceId();

let payload: unknown;
try {
payload = await request.json();
} catch {
return Response.json(
{ error: "Invalid JSON payload" },
{
status: 400,
headers: {
"cache-control": "no-store",
"x-trace-id": traceId,
},
}
);
}

const refreshToken =
payload && typeof payload === "object" && "refreshToken" in payload
? (payload.refreshToken as string)
: undefined;

if (!(typeof refreshToken === "string" && refreshToken.trim().length > 0)) {
return Response.json(
{ error: "refreshToken is required" },
{
status: 400,
headers: {
"cache-control": "no-store",
"x-trace-id": traceId,
},
}
);
}

try {
const result = await refreshWorkOsAccessToken({
refreshToken,
});

return Response.json(result, {
headers: {
"cache-control": "no-store",
"x-trace-id": traceId,
},
});
} catch (error) {
const message =
error instanceof Error ? error.message : "Failed to refresh access token";

return Response.json(
{ error: message },
{
status: 500,
headers: {
"cache-control": "no-store",
"x-trace-id": traceId,
},
}
);
}
}
96 changes: 94 additions & 2 deletions apps/web/src/lib/orpc/openapi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,11 @@ function withDeviceAuthPaths(spec: unknown): unknown {
},
DeviceAuthTokenSuccessResponse: {
type: "object",
required: ["status", "accessToken"],
required: ["status", "accessToken", "refreshToken"],
properties: {
status: { type: "string", enum: ["success"] },
accessToken: { type: "string" },
refreshToken: { type: "string" },
accessTokenExpiresAt: {
type: "integer",
description:
Expand All @@ -103,6 +104,22 @@ function withDeviceAuthPaths(spec: unknown): unknown {
},
additionalProperties: false,
},
DeviceAuthRefreshRequest: {
type: "object",
required: ["refreshToken"],
properties: {
refreshToken: { type: "string" },
},
additionalProperties: false,
},
DeviceAuthRefreshInvalidGrantResponse: {
type: "object",
required: ["status"],
properties: {
status: { type: "string", enum: ["invalid_grant"] },
},
additionalProperties: false,
},
DeviceAuthTokenInvalidGrantResponse: {
type: "object",
required: ["status"],
Expand Down Expand Up @@ -278,12 +295,87 @@ function withDeviceAuthPaths(spec: unknown): unknown {
},
},
},
"/auth/refresh": {
post: {
tags: ["Device Auth"],
summary: "Refresh access token",
description:
"Exchanges a stored WorkOS refresh token for a new access token and rotated refresh token. This endpoint does not require user bearer auth.",
requestBody: {
required: true,
content: {
"application/json": {
schema: {
$ref: "#/components/schemas/DeviceAuthRefreshRequest",
},
example: {
refreshToken: "workos_refresh_token",
},
},
},
},
responses: {
200: {
description: "Refresh result.",
headers: {
"x-trace-id": {
schema: { type: "string" },
},
},
content: {
"application/json": {
schema: {
oneOf: [
{
$ref: "#/components/schemas/DeviceAuthTokenSuccessResponse",
},
{
$ref: "#/components/schemas/DeviceAuthRefreshInvalidGrantResponse",
},
],
},
},
},
},
400: {
description: "Invalid request payload.",
headers: {
"x-trace-id": {
schema: { type: "string" },
},
},
content: {
"application/json": {
schema: {
$ref: "#/components/schemas/DeviceAuthErrorResponse",
},
},
},
},
500: {
description: "Failed to refresh access token.",
headers: {
"x-trace-id": {
schema: { type: "string" },
},
},
content: {
"application/json": {
schema: {
$ref: "#/components/schemas/DeviceAuthErrorResponse",
},
},
},
},
},
},
},
} satisfies Record<string, unknown>;

const existingDescription = document.info?.description ?? "";
const notes = [
existingDescription,
"Device auth endpoints are included for CLI integrations (`/auth/device/start`, `/auth/device/token`).",
"Device auth endpoints are included for CLI integrations (`/auth/device/start`, `/auth/device/token`, `/auth/refresh`).",
]
.filter(Boolean)
.join(" ");
Expand Down
18 changes: 18 additions & 0 deletions apps/web/src/lib/orpc/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ export function createOrpcContext(
const orpc = os.$context<OrpcContext>();

type PublicErrorReason =
| "NOT_FOUND"
| "UNAUTHORIZED"
| "AI_NO_OUTPUT"
| "AI_PROVIDER_ERROR"
Expand All @@ -84,6 +85,10 @@ function classifyError(error: unknown): {
const name = error.name;
const lower = message.toLowerCase();

if (lower.includes("session not found")) {
return { reason: "NOT_FOUND", message, name };
}

if (lower.includes("no output generated")) {
return { reason: "AI_NO_OUTPUT", message, name };
}
Expand Down Expand Up @@ -154,6 +159,19 @@ function throwInternalError(params: {
});
}

if (reason === "NOT_FOUND") {
throw new ORPCError("NOT_FOUND", {
message: `${params.action} could not find the requested diagram session. traceId=${params.traceId}`,
data: {
traceId: params.traceId,
stage: params.stage,
action: params.action,
errorName: name,
errorMessage: message.slice(0, 600),
},
});
}

withScope((scope) => {
scope.setTag("traceId", params.traceId);
scope.setTag("orpc.route", params.action);
Expand Down
Loading
Loading