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
2 changes: 1 addition & 1 deletion .github/copilot-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@
- Always use `getAuthUserId(ctx)` to check authentication:

```typescript
import { getAuthUserId } from "@convex-dev/auth/server";
import { getAuthUserId } from "../_utils/auth";

export const myFunction = query({
args: {},
Expand Down
85 changes: 56 additions & 29 deletions bun.lock

Large diffs are not rendered by default.

15 changes: 14 additions & 1 deletion convex/_generated/api.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ import type * as _ai_tools_executors from "../_ai/tools/executors.js";
import type * as _ai_utils from "../_ai/utils.js";
import type * as _ai_workflow from "../_ai/workflow.js";
import type * as _utils_accessControl from "../_utils/accessControl.js";
import type * as _utils_auth from "../_utils/auth.js";
import type * as _utils_authRedirect from "../_utils/authRedirect.js";
import type * as _utils_environment from "../_utils/environment.js";
import type * as _utils_gitdogFormat from "../_utils/gitdogFormat.js";
Expand Down Expand Up @@ -171,10 +172,14 @@ import type * as tokenUsage_quota from "../tokenUsage/quota.js";
import type * as tokenUsage_totals from "../tokenUsage/totals.js";
import type * as tokenUsage_usageSummary from "../tokenUsage/usageSummary.js";
import type * as users_action from "../users/action.js";
import type * as users_githubAccount from "../users/githubAccount.js";
import type * as users_internalMutation from "../users/internalMutation.js";
import type * as users_internalQuery from "../users/internalQuery.js";
import type * as users_legal from "../users/legal.js";
import type * as users_migrations from "../users/migrations.js";
import type * as users_mutation from "../users/mutation.js";
import type * as users_query from "../users/query.js";
import type * as users_tables from "../users/tables.js";

import type {
ApiFromModules,
Expand Down Expand Up @@ -216,6 +221,7 @@ declare const fullApi: ApiFromModules<{
"_ai/utils": typeof _ai_utils;
"_ai/workflow": typeof _ai_workflow;
"_utils/accessControl": typeof _utils_accessControl;
"_utils/auth": typeof _utils_auth;
"_utils/authRedirect": typeof _utils_authRedirect;
"_utils/environment": typeof _utils_environment;
"_utils/gitdogFormat": typeof _utils_gitdogFormat;
Expand Down Expand Up @@ -346,10 +352,14 @@ declare const fullApi: ApiFromModules<{
"tokenUsage/totals": typeof tokenUsage_totals;
"tokenUsage/usageSummary": typeof tokenUsage_usageSummary;
"users/action": typeof users_action;
"users/githubAccount": typeof users_githubAccount;
"users/internalMutation": typeof users_internalMutation;
"users/internalQuery": typeof users_internalQuery;
"users/legal": typeof users_legal;
"users/migrations": typeof users_migrations;
"users/mutation": typeof users_mutation;
"users/query": typeof users_query;
"users/tables": typeof users_tables;
}>;

/**
Expand Down Expand Up @@ -378,4 +388,7 @@ export declare const internal: FilterApi<
FunctionReference<any, "internal">
>;

export declare const components: {};
export declare const components: {
auth: import("@convex-dev/auth/_generated/component.js").ComponentApi<"auth">;
authGithub: import("@convex-dev/auth/components/github/_generated/component.js").ComponentApi<"authGithub">;
};
2 changes: 2 additions & 0 deletions convex/_generated/server.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ import type { DataModel } from "./dataModel.js";
type Env = {
readonly CONVEX_CLOUD_URL: string;
readonly CONVEX_SITE_URL: string;
readonly GITHUB_APP_CLIENT_ID: string;
readonly GITHUB_APP_CLIENT_SECRET: string;
};

/**
Expand Down
17 changes: 17 additions & 0 deletions convex/_utils/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { getAuthUserId as getSessionUserId } from "@convex-dev/auth/server";
import type { Auth } from "convex/server";
import type { Id } from "../_generated/dataModel";

type SessionLookupCtx = Parameters<typeof getSessionUserId>[0];

/**
* The signed-in user, from the caller's session in the auth component, or
* null. Works in queries, mutations and actions: @convex-dev/auth types its
* context after a query's runQuery, which an action's does not match.
*/
export async function getAuthUserId(ctx: {
auth: Auth;
runQuery: unknown;
}): Promise<Id<"users"> | null> {
return await getSessionUserId<"users">(ctx as SessionLookupCtx);
}
40 changes: 12 additions & 28 deletions convex/_utils/authRedirect.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,14 @@
/** Keep web redirects same-origin and allow the CLI's exact loopback URL. */
export function resolveAuthRedirect(
redirectTo: string,
siteUrl: string,
): string {
const loopback =
/^http:\/\/127\.0\.0\.1:([1-9]\d{3,4})\/gitdog\/callback\?state=[a-f0-9]{64}$/.exec(
redirectTo,
);
if (
loopback &&
loopback[0] === redirectTo &&
Number(loopback[1]) >= 1024 &&
Number(loopback[1]) <= 65535
) {
return redirectTo;
}
/**
* Local ports the CLI listens on for its sign-in callback, tried in order.
* @convex-dev/auth 2.0 returns only to exact origins, so the CLI cannot pick
* a random port. packages/cli/src/auth.ts lists the same ports.
*/
export const CLI_LOGIN_PORTS = [41721, 41722, 41723, 41724, 41725] as const;

const base = new URL(siteUrl);
const target = new URL(redirectTo, base);
if (
(base.protocol === "https:" || base.protocol === "http:") &&
target.origin === base.origin &&
target.username === "" &&
target.password === ""
) {
return target.toString();
}
throw new Error("Invalid authentication redirect destination");
/** Where a sign-in may return: Gitdog's site or the CLI's loopback listener. */
export function allowedSignInOrigins(siteUrl: string): string[] {
return [
new URL(siteUrl).origin,
...CLI_LOGIN_PORTS.map((port) => `http://127.0.0.1:${port}`),
];
}
2 changes: 1 addition & 1 deletion convex/admin/mutation.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { mutation, type MutationCtx } from "../_generated/server";
import { getAuthUserId } from "@convex-dev/auth/server";
import { getAuthUserId } from "../_utils/auth";
import { v } from "convex/values";
import type { Id } from "../_generated/dataModel";

Expand Down
2 changes: 1 addition & 1 deletion convex/admin/query.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { query, type QueryCtx } from "../_generated/server";
import { getAuthUserId } from "@convex-dev/auth/server";
import { getAuthUserId } from "../_utils/auth";
import { v } from "convex/values";
import type { Id } from "../_generated/dataModel";

Expand Down
2 changes: 1 addition & 1 deletion convex/admin/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getAuthUserId } from "@convex-dev/auth/server";
import { getAuthUserId } from "../_utils/auth";
import type { Id } from "../_generated/dataModel";
import type { MutationCtx, QueryCtx } from "../_generated/server";

Expand Down
2 changes: 1 addition & 1 deletion convex/apiKeys/action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { randomBytes } from "node:crypto";
import { action } from "../_generated/server";
import { internal } from "../_generated/api";
import type { Id } from "../_generated/dataModel";
import { getAuthUserId } from "@convex-dev/auth/server";
import { getAuthUserId } from "../_utils/auth";
import { v } from "convex/values";
import { apiError, hashApiKey } from "./security";

Expand Down
2 changes: 1 addition & 1 deletion convex/apiKeys/internalMutation.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { internalMutation } from "../_generated/server";
import { getAuthUserId } from "@convex-dev/auth/server";
import { getAuthUserId } from "../_utils/auth";
import { v } from "convex/values";
import {
apiError,
Expand Down
2 changes: 1 addition & 1 deletion convex/apiKeys/mutation.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { mutation } from "../_generated/server";
import { getAuthUserId } from "@convex-dev/auth/server";
import { getAuthUserId } from "../_utils/auth";
import { v } from "convex/values";
import { apiError, ownedRepository } from "./security";

Expand Down
2 changes: 1 addition & 1 deletion convex/apiKeys/query.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { query } from "../_generated/server";
import { getAuthUserId } from "@convex-dev/auth/server";
import { getAuthUserId } from "../_utils/auth";
import { paginationOptsValidator } from "convex/server";
import { v } from "convex/values";
import { apiError, ownedRepository, publicKey } from "./security";
Expand Down
9 changes: 3 additions & 6 deletions convex/auth.config.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
import { convexAuthProvider } from "@convex-dev/auth/server";

export default {
providers: [
{
domain: process.env.CONVEX_SITE_URL,
applicationID: "convex",
},
],
providers: [convexAuthProvider()],
};
67 changes: 27 additions & 40 deletions convex/auth.ts
Original file line number Diff line number Diff line change
@@ -1,43 +1,30 @@
import { convexAuth } from "@convex-dev/auth/server";
import GitHub from "@auth/core/providers/github";
import type { MutationCtx } from "./_generated/server";
import { resolveAuthRedirect } from "./_utils/authRedirect";
import {
fetchAccessibleGitHubInstallationIds,
persistGitHubInstallationAttestation,
} from "./github/oauthInstallationAttestation";
import { setupConvexAuth } from "@convex-dev/auth/server";
import { setupGithub } from "@convex-dev/auth/methods/github/server";
import { components, internal } from "./_generated/api";
import { allowedSignInOrigins } from "./_utils/authRedirect";

export const { auth, signIn, signOut, store } = convexAuth({
providers: [
GitHub({
clientId: process.env.GITHUB_APP_CLIENT_ID,
clientSecret: process.env.GITHUB_APP_CLIENT_SECRET,
async profile(profile, tokens) {
const githubAccountId = profile.id.toString();
const accessToken = tokens.access_token;
if (typeof accessToken !== "string" || accessToken.trim() === "") {
throw new Error("GitHub user authorization is unavailable");
}
const githubInstallationIds =
await fetchAccessibleGitHubInstallationIds(accessToken);
return {
id: githubAccountId,
name: profile.login, // Use login (username) instead of display name
email: typeof profile.email === "string" ? profile.email : undefined,
image: profile.avatar_url,
githubAccountId,
githubInstallationIds,
};
},
}),
],
callbacks: {
redirect: async ({ redirectTo }) => {
const siteUrl = process.env.SITE_URL;
if (!siteUrl) throw new Error("SITE_URL is not configured");
return resolveAuthRedirect(redirectTo, siteUrl);
},
createOrUpdateUser: async (ctx, args) =>
await persistGitHubInstallationAttestation(ctx as MutationCtx, args),
const siteUrl = process.env.SITE_URL;
if (!siteUrl) throw new Error("SITE_URL is not configured");

// One-hour access tokens, as before 2.0: GITDOG_TOKEN automation sends one
// without refreshing it.
const core = setupConvexAuth({
component: components.auth,
accessTokenTtlSeconds: 60 * 60,
});

export const { signOut, refreshSession, isAuthenticated } = core;

// Sign-in never sees the GitHub user token in 2.0, so it records no
// installation access. "Verify GitHub access" (github/accessVerification.ts)
// does, whenever installation recovery reports reauth_required.
export const { startSignInWithGithub, completeSignInWithGithub } = setupGithub(
core,
{
component: components.authGithub,
allowedRedirectOrigins: allowedSignInOrigins(siteUrl),
},
).attachUserCallbacks({
createUser: internal.users.internalMutation.createUserFromGithub,
Comment thread
hyochan marked this conversation as resolved.
Resolved
onSignIn: internal.users.internalMutation.updateUserFromGithub,
});
21 changes: 20 additions & 1 deletion convex/convex.config.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,24 @@
import { defineApp } from "convex/server";
import { v } from "convex/values";
import auth from "@convex-dev/auth/convex.config";
import authGithub from "@convex-dev/auth/components/github/convex.config";

const app = defineApp();
const app = defineApp({
env: {
GITHUB_APP_CLIENT_ID: v.string(),
GITHUB_APP_CLIENT_SECRET: v.string(),
},
});

// Sessions and tokens live in the core; GitHub accounts in authGithub, whose
// OAuth callback is served at <site>/oauth/github/callback.
app.use(auth);
app.use(authGithub, {
httpPrefix: "/oauth/github",
env: {
CLIENT_ID: app.env.GITHUB_APP_CLIENT_ID,
CLIENT_SECRET: app.env.GITHUB_APP_CLIENT_SECRET,
},
});

export default app;
2 changes: 1 addition & 1 deletion convex/github/action.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { action, internalAction, type ActionCtx } from "../_generated/server";
import { getAuthUserId } from "@convex-dev/auth/server";
import { getAuthUserId } from "../_utils/auth";
import { api, internal } from "../_generated/api";
import { v } from "convex/values";
import {
Expand Down
6 changes: 2 additions & 4 deletions convex/github/internalMutation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@ import { internalMutation, type MutationCtx } from "../_generated/server";
import { v } from "convex/values";
import { internal } from "../_generated/api";
import { getExactGitHubInstallation } from "./installationAccess";
import {
readLinkedGitHubAccountId,
saveInstallationAttestation,
} from "./oauthInstallationAttestation";
import { saveInstallationAttestation } from "./oauthInstallationAttestation";
import { readLinkedGitHubAccountId } from "../users/githubAccount";
import {
getInstallationWebhookStateRetryDelayMs,
INSTALLATION_WEBHOOK_STATE_ATTEMPT_LEASE_MS,
Expand Down
Loading