Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

fix: fix device auth route validation and bearer handling

Tin505e1ff93617
diff --git a/apps/api/drizzle/0024_device_code_timestamps.sql b/apps/api/drizzle/0024_device_code_timestamps.sql
new file mode 100644
index 000000000..49efdae4e
--- /dev/null
+++ b/apps/api/drizzle/0024_device_code_timestamps.sql
@@ -0,0 +1,3 @@
+ALTER TABLE "device_code" ADD COLUMN "created_at" timestamp DEFAULT now() NOT NULL;
+--> statement-breakpoint
+ALTER TABLE "device_code" ADD COLUMN "updated_at" timestamp DEFAULT now() NOT NULL;
diff --git a/apps/api/drizzle/meta/_journal.json b/apps/api/drizzle/meta/_journal.json
index e91bde4b7..f6f40341e 100644
--- a/apps/api/drizzle/meta/_journal.json
+++ b/apps/api/drizzle/meta/_journal.json
@@ -169,6 +169,13 @@
"when": 1775215568801,
"tag": "0023_cold_omega_red",
"breakpoints": true
+ },
+ {
+ "idx": 24,
+ "version": "7",
+ "when": 1775215568802,
+ "tag": "0024_device_code_timestamps",
+ "breakpoints": true
}
]
}
diff --git a/apps/api/src/database/schema.ts b/apps/api/src/database/schema.ts
index b226cddb4..b41dfbeb0 100644
--- a/apps/api/src/database/schema.ts
+++ b/apps/api/src/database/schema.ts
@@ -669,6 +669,11 @@ export const deviceCodeTable = pgTable(
onDelete: "cascade",
onUpdate: "cascade",
}),
+ createdAt: timestamp("created_at", { mode: "date" }).defaultNow().notNull(),
+ updatedAt: timestamp("updated_at", { mode: "date" })
+ .defaultNow()
+ .$onUpdate(() => new Date())
+ .notNull(),
expiresAt: timestamp("expires_at", { mode: "date" }).notNull(),
status: text("status").notNull(),
lastPolledAt: timestamp("last_polled_at", { mode: "date" }),
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index d57a7f2f3..ceb958e60 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -317,24 +317,72 @@ export function createApp() {
// Better Auth serves GET /auth/device as JSON. Browsers that open the API URL
// directly expect a page — redirect full document navigations to the web app.
- api.get("/auth/device", async (c) => {
- const userCode = c.req.query("user_code");
- const secFetchDest = c.req.header("Sec-Fetch-Dest");
- const forceUiRedirect = c.req.query("ui") === "1";
- // Top-level browser tab / address bar (not `fetch()` / XHR from the SPA).
- // Optional `ui=1` forces redirect when Sec-Fetch-* headers are missing (e.g. some clients).
- if (userCode && (forceUiRedirect || secFetchDest === "document")) {
- const clientUrl = (
- process.env.KANEO_CLIENT_URL || "http://localhost:5173"
- ).replace(/\/$/, "");
- return c.redirect(
- `${clientUrl}/device?user_code=${encodeURIComponent(userCode)}`,
- 302,
- );
- }
- return auth.handler(c.req.raw);
+ const authDeviceQuerySchema = v.object({
+ user_code: v.string(),
+ ui: v.optional(v.picklist(["1"])),
});
+ api.get(
+ "/auth/device",
+ describeRoute({
+ operationId: "getDeviceAuthorizationPage",
+ tags: ["Authentication"],
+ description:
+ "Redirect browser-based device authorization requests to the web UI",
+ security: [],
+ parameters: [
+ {
+ name: "user_code",
+ in: "query",
+ required: true,
+ schema: {
+ type: "string",
+ },
+ description: "The device authorization user code.",
+ },
+ {
+ name: "ui",
+ in: "query",
+ required: false,
+ schema: {
+ type: "string",
+ enum: ["1"],
+ },
+ description: "Force a redirect to the web UI.",
+ },
+ ],
+ responses: {
+ 302: {
+ description: "Redirects the browser to the web app device screen",
+ },
+ 200: {
+ description: "Device authorization payload from Better Auth",
+ content: {
+ "application/json": { schema: resolver(v.any()) },
+ },
+ },
+ },
+ }),
+ validator("query", authDeviceQuerySchema),
+ async (c) => {
+ const { user_code: userCode, ui } = c.req.valid("query");
+ const secFetchDest = c.req.header("Sec-Fetch-Dest");
+ const forceUiRedirect = ui === "1";
+ // Top-level browser tab / address bar (not `fetch()` / XHR from the SPA).
+ // Optional `ui=1` forces redirect when Sec-Fetch-* headers are missing (e.g. some clients).
+ if (forceUiRedirect || secFetchDest === "document") {
+ const clientUrl = (
+ process.env.KANEO_CLIENT_URL || "http://localhost:5173"
+ ).replace(/\/$/, "");
+ return c.redirect(
+ `${clientUrl}/device?user_code=${encodeURIComponent(userCode)}`,
+ 302,
+ );
+ }
+ return auth.handler(c.req.raw);
+ },
+ );
+
api.on(["POST", "GET", "PUT", "DELETE"], "/auth/*", (c) => {
const authHeader = c.req.header("Authorization");
diff --git a/apps/api/src/utils/authenticate-api-request.ts b/apps/api/src/utils/authenticate-api-request.ts
index 34ee2b437..74ba860f2 100644
--- a/apps/api/src/utils/authenticate-api-request.ts
+++ b/apps/api/src/utils/authenticate-api-request.ts
@@ -10,10 +10,22 @@ async function getSessionFromBearerOnlyHeaders(c: Context) {
return auth.api.getSession({ headers });
}
+function parseBearerToken(authHeader: string | undefined) {
+ if (!authHeader) {
+ return null;
+ }
+
+ const match = authHeader.match(/^Bearer\s+(.+)$/i);
+ if (!match) {
+ return null;
+ }
+
+ return match[1].replace(/\s+/g, "").trim();
+}
+
export async function authenticateApiRequest(c: Context): Promise<void> {
- const authHeader = c.req.header("Authorization");
- if (authHeader?.startsWith("Bearer ")) {
- const token = authHeader.substring(7).replace(/\s+/g, "").trim();
+ const token = parseBearerToken(c.req.header("Authorization"));
+ if (token) {
const apiKeyResult = await verifyApiKey(token);
if (apiKeyResult?.valid && apiKeyResult.key) {
const key = apiKeyResult.key;
@@ -55,9 +67,8 @@ export async function resolveAssetBearerOrCookie(c: Context): Promise<{
userId: string;
apiKeyId?: string;
}> {
- const authHeader = c.req.header("Authorization");
- if (authHeader?.startsWith("Bearer ")) {
- const token = authHeader.substring(7).replace(/\s+/g, "").trim();
+ const token = parseBearerToken(c.req.header("Authorization"));
+ if (token) {
const apiKeyResult = await verifyApiKey(token);
if (apiKeyResult?.valid && apiKeyResult.key) {
return {
diff --git a/apps/docs/core/installation/environment-variables.mdx b/apps/docs/core/installation/environment-variables.mdx
index 91595b5fa..88ddb986e 100644
--- a/apps/docs/core/installation/environment-variables.mdx
+++ b/apps/docs/core/installation/environment-variables.mdx
@@ -50,7 +50,7 @@ This section will cover all the variables related to the authentication.
Name | Description |
--- | --- |
| `AUTH_SECRET` | The secret key for the JWT token. **Must be at least 32 characters long**, use a long, random value in production. Example: use `openssl rand -base64 32` to generate a secure key in Linux/macOS.
-| `DEVICE_AUTH_CLIENT_IDS` | Comma-separated list of allowed device authorization client IDs. Use this to permit trusted CLI or external app identifiers such as `kaneo-cli,my-desktop-app`. |
+| `DEVICE_AUTH_CLIENT_IDS` | Comma-separated list of allowed device authorization client IDs. When unset, `kaneo-cli` is allowed by default, so no extra configuration is required for the CLI. Use this to permit trusted external app identifiers such as `kaneo-cli,my-desktop-app`. |
## Optional variables
diff --git a/apps/web/src/routes/auth/verify-otp.tsx b/apps/web/src/routes/auth/verify-otp.tsx
index 67836b374..e3d9e5e56 100644
--- a/apps/web/src/routes/auth/verify-otp.tsx
+++ b/apps/web/src/routes/auth/verify-otp.tsx
@@ -65,6 +65,14 @@ function VerifyOtp() {
return undefined;
}, [redirect]);
+ const signInPath = useMemo(() => {
+ if (!redirect) {
+ return "/auth/sign-in";
+ }
+
+ return `/auth/sign-in?redirect=${encodeURIComponent(redirect)}`;
+ }, [redirect]);
+
const onSubmit = useCallback(
async (data: VerifyOtpFormValues) => {
setIsPending(true);
@@ -199,7 +207,7 @@ function VerifyOtp() {
<Button
type="button"
variant="outline"
- onClick={() => history.push("/auth/sign-in")}
+ onClick={() => history.push(signInPath)}
className="w-full"
>
<ArrowLeft className="size-4" />
diff --git a/tests/api-integration/device-authorization.test.ts b/tests/api-integration/device-authorization.test.ts
index 666cc4538..978016d1f 100644
--- a/tests/api-integration/device-authorization.test.ts
+++ b/tests/api-integration/device-authorization.test.ts
@@ -334,5 +334,18 @@ describe("API integration: device authorization (RFC 8628)", () => {
);
expect(res.status).toBe(401);
+
+ const lowercaseSchemeRes = await app.request(
+ `/api/project?workspaceId=${encodeURIComponent(workspaceId)}`,
+ {
+ headers: {
+ authorization: "bearer definitely-not-a-real-token",
+ Cookie: cookieJar,
+ Origin: origin,
+ },
+ },
+ );
+
+ expect(lowercaseSchemeRes.status).toBe(401);
});
});