Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ma/dbconnections #13

Merged
merged 8 commits into from
Dec 16, 2024
Merged
Show file tree
Hide file tree
Changes from 6 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 .husky/pre-commit
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
pnpm interfaces build
pnpm kysely build
pnpm kysely authhero
pnpm authhero build
9 changes: 9 additions & 0 deletions apps/demo/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
# @authhero/demo

## 0.5.4

### Patch Changes

- Updated dependencies
- Updated dependencies
- [email protected]
- @authhero/[email protected]

## 0.5.3

### Patch Changes
Expand Down
6 changes: 3 additions & 3 deletions apps/demo/package.json
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
{
"name": "@authhero/demo",
"private": true,
"version": "0.5.3",
"version": "0.5.4",
"scripts": {
"dev": "bun --watch src/bun.ts"
},
"dependencies": {
"@authhero/kysely-adapter": "^0.25.1",
"@authhero/kysely-adapter": "^0.25.3",
"@hono/swagger-ui": "^0.5.0",
"@hono/zod-openapi": "^0.18.3",
"@peculiar/x509": "^1.12.3",
"authhero": "^0.25.0",
"authhero": "^0.26.0",
"hono": "^4.6.13",
"hono-openapi-middlewares": "^1.0.11",
"kysely-bun-sqlite": "^0.3.2",
Expand Down
13 changes: 13 additions & 0 deletions packages/adapter-interfaces/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
# @authhero/adapter-interfaces

## 0.33.0

### Minor Changes

- add sendgrid and postmark mail services
- migrate dbconnections and setup email providers

## 0.32.1

### Patch Changes

- update all build packages

## 0.32.0

### Minor Changes
Expand Down
2 changes: 1 addition & 1 deletion packages/adapter-interfaces/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"type": "git",
"url": "https://github.com/markusahlstrand/authhero"
},
"version": "0.32.0",
"version": "0.33.0",
"files": [
"dist"
],
Expand Down
4 changes: 1 addition & 3 deletions packages/adapter-interfaces/src/types/Client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@ const ClientDomainSchema = z.object({
dkim_private_key: z.string().optional(),
dkim_public_key: z.string().optional(),
email_api_key: z.string().optional(),
email_service: z
.union([z.literal("mailgun"), z.literal("mailchannels")])
.optional(),
email_service: z.string().optional(),
});

const ClientSchema = z.object({
Expand Down
2 changes: 1 addition & 1 deletion packages/adapter-interfaces/src/types/Domain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export const domainInsertSchema = z.object({
dkim_private_key: z.string().optional(),
dkim_public_key: z.string().optional(),
email_api_key: z.string().optional(),
email_service: z.enum(["mailgun", "mailchannels"]),
email_service: z.string().optional(),
});
export type DomainInsert = z.infer<typeof domainInsertSchema>;

Expand Down
27 changes: 27 additions & 0 deletions packages/authhero/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,32 @@
# authhero

## 0.26.0

### Minor Changes

- add id-token support to hook
- migrate dbconnections and setup email providers

### Patch Changes

- Updated dependencies
- Updated dependencies
- @authhero/[email protected]

## 0.25.2

### Patch Changes

- update all build packages
- Updated dependencies
- @authhero/[email protected]

## 0.25.1

### Patch Changes

- update the build

## 0.25.0

### Minor Changes
Expand Down
2 changes: 1 addition & 1 deletion packages/authhero/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "authhero",
"version": "0.25.0",
"version": "0.26.0",
"files": [
"dist"
],
Expand Down
4 changes: 3 additions & 1 deletion packages/authhero/src/auth-app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
tokenRoutes,
wellKnownRoutes,
userinfoRoutes,
dbConnectionRoutes,
} from "./routes/auth-api";

export interface CreateAuthParams {
Expand All @@ -26,7 +27,8 @@ export default function create() {
.route("/v2/logout", logoutRoutes)
.route("/userinfo", userinfoRoutes)
.route("/.well-known", wellKnownRoutes)
.route("/oauth/token", tokenRoutes);
.route("/oauth/token", tokenRoutes)
.route("/dbconnections", dbConnectionRoutes);

oauthApp.doc("/spec", {
openapi: "3.0.0",
Expand Down
92 changes: 48 additions & 44 deletions packages/authhero/src/authentication-flows/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ export interface CreateAuthTokensParams {
sid?: string;
}

const RESERVED_CLAIMS = ["sub", "iss", "aud", "exp", "nbf", "iat", "jti"];

export async function createAuthTokens(
ctx: Context<{ Bindings: Bindings; Variables: Variables }>,
params: CreateAuthTokensParams,
Expand All @@ -31,7 +33,7 @@ export async function createAuthTokens(

const keyBuffer = pemToBuffer(signingKey.pkcs7);

const payload = {
const accessTokenPayload = {
// TODO: consider if the dafault should be removed
aud: authParams.audience || "default",
scope: authParams.scope || "",
Expand All @@ -41,6 +43,26 @@ export async function createAuthTokens(
sid,
};

const idTokenPayload =
user && authParams.scope?.split(" ").includes("openid")
? {
// The audience for an id token is the client id
aud: authParams.client_id,
sub: user.user_id,
iss: ctx.env.ISSUER,
sid,
nonce: authParams.nonce,
given_name: user.given_name,
family_name: user.family_name,
nickname: user.nickname,
picture: user.picture,
locale: user.locale,
name: user.name,
email: user.email,
email_verified: user.email_verified,
}
: undefined;

if (ctx.env.hooks?.onExecuteCredentialsExchange) {
await ctx.env.hooks.onExecuteCredentialsExchange(
{
Expand All @@ -52,19 +74,21 @@ export async function createAuthTokens(
{
accessToken: {
setCustomClaim: (claim, value) => {
const reservedClaims = [
"sub",
"iss",
"aud",
"exp",
"nbf",
"iat",
"jti",
];
if (reservedClaims.includes(claim)) {
if (RESERVED_CLAIMS.includes(claim)) {
throw new Error(`Cannot overwrite reserved claim '${claim}'`);
}
accessTokenPayload[claim] = value;
},
},
idToken: {
setCustomClaim: (claim, value) => {
if (RESERVED_CLAIMS.includes(claim)) {
throw new Error(`Cannot overwrite reserved claim '${claim}'`);
}
payload[claim] = value;

if (idTokenPayload) {
idTokenPayload[claim] = value;
}
},
},
access: {
Expand All @@ -78,44 +102,24 @@ export async function createAuthTokens(
);
}

const access_token = await createJWT("RS256", keyBuffer, payload, {
const header = {
includeIssuedTimestamp: true,
expiresIn: new TimeSpan(1, "d"),
headers: {
kid: signingKey.kid,
},
});
};

const id_token =
user && authParams.scope?.split(" ").includes("openid")
? await createJWT(
"RS256",
keyBuffer,
{
// The audience for an id token is the client id
aud: authParams.client_id,
sub: user.user_id,
iss: ctx.env.ISSUER,
sid,
nonce: authParams.nonce,
given_name: user.given_name,
family_name: user.family_name,
nickname: user.nickname,
picture: user.picture,
locale: user.locale,
name: user.name,
email: user.email,
email_verified: user.email_verified,
},
{
includeIssuedTimestamp: true,
expiresIn: new TimeSpan(1, "d"),
headers: {
kid: signingKey.kid,
},
},
)
: undefined;
const access_token = await createJWT(
"RS256",
keyBuffer,
accessTokenPayload,
header,
);

const id_token = idTokenPayload
? await createJWT("RS256", keyBuffer, idTokenPayload, header)
: undefined;

return {
access_token,
Expand Down
1 change: 1 addition & 0 deletions packages/authhero/src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export const JWKS_CACHE_TIMEOUT_IN_SECONDS = 60 * 5; // 5 minutes
export const SILENT_AUTH_MAX_AGE = 30 * 24 * 60 * 60; // 30 days
export const UNIVERSAL_AUTH_SESSION_EXPIRES_IN_SECONDS = 24 * 60 * 60; // 1 day
export const SILENT_COOKIE_NAME = "auth-token";
61 changes: 61 additions & 0 deletions packages/authhero/src/emails/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { Context } from "hono";
import { Bindings, Variables } from "../types";
import { User } from "@authhero/adapter-interfaces";
import { HTTPException } from "hono/http-exception";

export async function sendEmail(
ctx: Context<{ Bindings: Bindings; Variables: Variables }>,
tenant_id: string,
to: string,
subject: string,
html: string,
) {
const emailProvider = await ctx.env.data.emailProviders.get(tenant_id);

if (!emailProvider) {
throw new HTTPException(500, { message: "Email provider not found" });
}

const emailService = ctx.env.emailProviders?.[emailProvider.name];
if (!emailService) {
throw new HTTPException(500, { message: "Email provider not found" });
markusahlstrand marked this conversation as resolved.
Show resolved Hide resolved
}

emailService({
to,
from: emailProvider.default_from_address || `login@${ctx.env.ISSUER}`,
markusahlstrand marked this conversation as resolved.
Show resolved Hide resolved
subject,
html,
});
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add await to email service call.

The email service call might be asynchronous but lacks the await keyword, which could lead to unhandled promises.

-  emailService({
+  await emailService({
     to,
     from: emailProvider.default_from_address || `login@${ctx.env.ISSUER}`,
     subject,
     html,
   });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
emailService({
to,
from: emailProvider.default_from_address || `login@${ctx.env.ISSUER}`,
subject,
html,
});
await emailService({
to,
from: emailProvider.default_from_address || `login@${ctx.env.ISSUER}`,
subject,
html,
});

}

export async function sendResetPassword(
ctx: Context<{ Bindings: Bindings; Variables: Variables }>,
tenant_id: string,
to: string,
// auth0 just has a ticket, but we have a code and a state
code: string,
state?: string,
) {
markusahlstrand marked this conversation as resolved.
Show resolved Hide resolved
await sendEmail(
ctx,
tenant_id,
to,
`Reset your password`,
`Click here to reset your password: ${ctx.env.ISSUER}u/reset-password?state=${state}&code=${code}`,
markusahlstrand marked this conversation as resolved.
Show resolved Hide resolved
);
}

export async function sendValidateEmailAddress(
ctx: Context<{ Bindings: Bindings; Variables: Variables }>,
tenant_id: string,
user: User,
) {
markusahlstrand marked this conversation as resolved.
Show resolved Hide resolved
await sendEmail(
ctx,
tenant_id,
user.email,
`Validate your email address`,
`Click here to validate your email: ${ctx.env.ISSUER}u/validate-email`,
markusahlstrand marked this conversation as resolved.
Show resolved Hide resolved
);
}
Loading