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

Update demo #8

Merged
merged 4 commits into from
Dec 9, 2024
Merged

Update demo #8

merged 4 commits into from
Dec 9, 2024

Conversation

markusahlstrand
Copy link
Owner

@markusahlstrand markusahlstrand commented Dec 9, 2024

Added init for demo

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new OAuth application with dedicated routes for token management.
    • Added a test endpoint that returns a greeting message.
    • Enhanced functionality for creating and managing X.509 certificates.
  • Updates

    • Updated version to 0.3.0 for the @authhero/demo package and to 0.18.0 for the authhero package.
    • Added new dependencies to the @authhero/demo package.
  • Bug Fixes

    • Improved clarity in changelogs for both @authhero/demo and authhero packages.
  • Refactor

    • Reorganized API initialization and routing logic for better integration of OAuth functionality.
    • Removed unnecessary parameters from the management application creation process.

Copy link

vercel bot commented Dec 9, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
authhero-react-admin ❌ Failed (Inspect) Dec 9, 2024 10:50am

Copy link

coderabbitai bot commented Dec 9, 2024

Warning

Rate limit exceeded

@markusahlstrand has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 17 minutes and 44 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 38cf420 and d9021c5.

📒 Files selected for processing (4)
  • apps/demo/package.json (1 hunks)
  • apps/demo/src/app.ts (2 hunks)
  • apps/demo/src/helpers/encryption.ts (1 hunks)
  • packages/authhero/src/oauth-app.ts (1 hunks)

Walkthrough

The pull request includes updates to the @authhero/demo and authhero packages, featuring version increments, dependency updates, and new functionalities. The changelog for both packages has been revised to reflect these changes. Notably, the @authhero/demo package introduces a new route and modifies the initialization of hooks, while the authhero package adds OAuth capabilities and restructures its API. Additionally, new methods and interfaces related to X.509 certificate management have been introduced.

Changes

File Change Summary
apps/demo/CHANGELOG.md Updated to version 0.3.0, reflecting changes in hook initialization and dependency updates.
apps/demo/package.json Version updated to 0.3.0; authhero dependency updated to ^0.18.0; added @peculiar/x509 and oslo dependencies.
apps/demo/src/app.ts Updated init function to return oauthApp; added /test route; established routing for oauthApp.
apps/demo/src/bun.ts Updated import for createAdapters, added database migration call, and enhanced key management logic.
apps/demo/src/helpers/encryption.ts Introduced X.509 certificate management functions and interface for certificate parameters.
apps/demo/src/types/Bindings.ts Added data: DataAdapters property to Bindings type.
packages/authhero/CHANGELOG.md Updated to version 0.18.0, reflecting changes in hook initialization and minor updates.
packages/authhero/package.json Version updated to 0.18.0.
packages/authhero/src/authentication-flows/common.ts Modified import path for pemToBuffer; no functional changes.
packages/authhero/src/index.ts Removed tokenRoutes and wellKnownRoutes imports; added createOauthApi; modified init parameter types.
packages/authhero/src/management-app.ts Changed create function to remove params parameter; adjusted internal logic accordingly.
packages/authhero/src/oauth-app.ts Introduced new OAuth application with routes and documentation; defined CreateAuthParams interface.

Possibly related PRs

  • Ma/email providers #4: The changes in this PR involve updates to the changelog and dependencies for the @authhero/demo package, which are relevant to the main PR's updates on dependency versions.
  • add ip to logins table #5: This PR also updates the changelog and dependencies for the @authhero/demo package, specifically mentioning updates to the authhero dependency, which aligns with the main PR's focus on dependency updates.
  • add silent auth for the code flow #7: This PR introduces silent authentication for the code flow, which relates to the changes in the main PR that involve updates to the authhero package, including dependency updates that may support this new functionality.

🐰 "In the garden of code, we hop with glee,
New routes and hooks, as fresh as can be!
Dependencies updated, our path now is bright,
With certificates shining, we leap into the night!
So let’s celebrate changes, both big and small,
A joyful new version, let’s share it with all!" 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 7

🧹 Outside diff range and nitpick comments (7)
apps/demo/src/helpers/encryption.ts (2)

59-77: Rename convertPKCS7ToPem to accurately reflect functionality

The function convertPKCS7ToPem converts keys to PEM format but does not handle PKCS#7 structures. This may cause confusion, as PKCS#7 is associated with cryptographic message syntax rather than key encoding.

Rename the function for clarity:

-export function convertPKCS7ToPem(
+export function convertKeyToPem(
  keyType: "PRIVATE" | "PUBLIC",
  binaryData: ArrayBuffer,
) {
  // ...
}

Update references to the function:

- const pkcs7 = convertPKCS7ToPem("PRIVATE", privateKey);
+ const pemPrivateKey = convertKeyToPem("PRIVATE", privateKey);

69-71: Replace deprecated substr with slice

The substr method is deprecated. Use slice for better compatibility and to avoid potential issues.

Update the code as follows:

- pemCert += base64Cert.substr(nextIndex, 64) + "\r\n";
+ pemCert += base64Cert.slice(nextIndex, nextIndex + 64) + "\r\n";

- pemCert += base64Cert.substr(nextIndex) + "\r\n";
+ pemCert += base64Cert.slice(nextIndex) + "\r\n";
apps/demo/src/bun.ts (1)

23-39: Enhance initialization logging and validation

The initialization block could benefit from improved logging and validation:

  1. No validation of the certificate creation result
  2. Basic console.log for initialization status
  3. No logging for existing database state

Consider enhancing the initialization block:

 const keys = await dataAdapter.keys.list();
 if (keys.length === 0) {
+  console.log('No signing keys found, initializing database...');
   const signingKey = await createX509Certificate({
     name: `CN=demo`,
   });
+  if (!signingKey) {
+    throw new Error('Failed to create X509 certificate');
+  }
   await dataAdapter.keys.create(signingKey);

   await dataAdapter.tenants.create({
     id: "default",
     name: "Default Tenant",
     audience: "https://example.com",
     sender_email: "[email protected]",
     sender_name: "SenderName",
   });

-  console.log("Initiated database");
+  console.log("Successfully initialized database with default tenant and signing key");
+} else {
+  console.log(`Database already initialized with ${keys.length} signing keys`);
 }
apps/demo/src/app.ts (1)

37-39: Validate init response

The destructuring of init() response assumes both managementApp and oauthApp will be present.

Add validation:

-  const { managementApp, oauthApp } = init({
+  const result = init({
     dataAdapter,
   });
+  if (!result.managementApp || !result.oauthApp) {
+    throw new Error('Failed to initialize apps');
+  }
+  const { managementApp, oauthApp } = result;
packages/authhero/src/management-app.ts (1)

Line range hint 16-19: Clean up unused code

The following items appear to be unused after the refactoring:

  • CreateAuthParams interface
  • DataAdapters import

Apply this diff to clean up unused code:

-import { DataAdapters } from "@authhero/adapter-interfaces";
 import { createAuthMiddleware } from "./middlewares/authentication";
 import { emailProviderRoutes } from "./routes/management-api/emails";
 
-export interface CreateAuthParams {
-  dataAdapter: DataAdapters;
-}

Also applies to: 1-1

apps/demo/CHANGELOG.md (1)

3-12: Enhance changelog entry clarity

The changelog entry could be more descriptive to help users understand the impact of these changes:

  • Where were the hooks moved to?
  • Is this a breaking change for existing implementations?

Consider expanding the changelog entry like this:

 ## 0.3.0
 
 ### Minor Changes
 
-- moved the init of the hooks
+- Moved hook initialization from management-app to [new location]
+  - This change may require updates to existing implementations
 
 ### Patch Changes
 
 - Updated dependencies
   - [email protected]
packages/authhero/CHANGELOG.md (1)

3-8: Enhance changelog entry with migration details

The changelog entry should provide more context about this architectural change:

  • Where were the hooks moved to?
  • How should users migrate their code?
  • What's the relationship with changes in the demo package?

Consider expanding the changelog entry like this:

 ## 0.18.0
 
 ### Minor Changes
 
-- moved the init of the hooks
+- Architectural Change: Moved hook initialization
+  - Relocated from management-app to [new location]
+  - Breaking: Removed dataAdapter parameter from management-app create()
+  - Migration: Update your initialization code to use [new approach]
+  - Related: This change is coordinated with @authhero/[email protected]
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 294ed22 and e6e0660.

⛔ Files ignored due to path filters (2)
  • apps/.DS_Store is excluded by !**/.DS_Store
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (12)
  • apps/demo/CHANGELOG.md (1 hunks)
  • apps/demo/package.json (1 hunks)
  • apps/demo/src/app.ts (2 hunks)
  • apps/demo/src/bun.ts (2 hunks)
  • apps/demo/src/helpers/encryption.ts (1 hunks)
  • apps/demo/src/types/Bindings.ts (1 hunks)
  • packages/authhero/CHANGELOG.md (1 hunks)
  • packages/authhero/package.json (1 hunks)
  • packages/authhero/src/authentication-flows/common.ts (1 hunks)
  • packages/authhero/src/index.ts (1 hunks)
  • packages/authhero/src/management-app.ts (1 hunks)
  • packages/authhero/src/oauth-app.ts (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • packages/authhero/package.json
  • packages/authhero/src/authentication-flows/common.ts
🔇 Additional comments (6)
apps/demo/src/types/Bindings.ts (1)

1-9: Addition of data property to Bindings is appropriate

The inclusion of data: DataAdapters in Bindings correctly extends the bindings to include data adapters, which are essential for data management within the application.

packages/authhero/src/index.ts (2)

12-17: Middleware correctly integrates data hooks

The middleware function adds data hooks to the context environment using addDataHooks, ensuring that ctx.env.data is properly initialized with the provided dataAdapter. This setup is appropriate for extending the application's capabilities.


25-28: Integration of OAuth routes appears correct

The application now routes OAuth endpoints through createOauthApi(), replacing previous configurations. This update should modularize and streamline OAuth functionalities.

apps/demo/src/bun.ts (1)

44-45: LGTM: DataAdapter integration

The integration of dataAdapter into the server's fetch context is clean and follows the pattern established in the Bindings type.

packages/authhero/src/oauth-app.ts (1)

9-11: ⚠️ Potential issue

Unused interface parameter

The CreateAuthParams interface is defined but the create function doesn't accept any parameters.

Update the function signature to use the interface:

-export default function create() {
+export default function create(params: CreateAuthParams) {
   const app = new OpenAPIHono<{
     Bindings: Bindings;
     Variables: Variables;
   }>();

Likely invalid or redundant comment.

apps/demo/src/app.ts (1)

60-61: Verify route precedence

The order of route registration might affect request handling. The OAuth routes at root ("/") might intercept requests intended for other endpoints.

Let's verify the route definitions:

✅ Verification successful

Let me check the implementation of oauthApp and managementApp to understand their route definitions.


Let me try a different approach to find the route definitions by searching for files that might contain these apps.


Let me try one final search to find the actual implementations of these apps to understand their route structures.


Route precedence appears to be correctly configured

Based on the route definitions found, the order is appropriate:

  • /api/v2/* routes are registered first, ensuring they take precedence for their specific path
  • The root route / is registered last, which is correct as it should only handle requests not matched by more specific routes

The current order prevents any unintended interception of API requests by the OAuth routes.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for potential route conflicts
rg -A 2 "\.route\(|\.get\(|\.post\(|\.put\(|\.delete\(" apps/demo/src/

Length of output: 875


Script:

#!/bin/bash
# Check oauth and management app route definitions
rg -A 5 "const oauthApp|const managementApp" apps/demo/src/

Length of output: 61


Script:

#!/bin/bash
# Find relevant files and their route definitions
fd -e ts -e js . apps/demo/src/ --exec grep -l "oauthApp\|managementApp" {} \;

# Then examine their content
echo "=== Route Definitions ==="
rg "app\.(get|post|put|delete|route)\(" $(fd -e ts -e js . apps/demo/src/ --exec grep -l "oauthApp\|managementApp" {} \;)

Length of output: 449


Script:

#!/bin/bash
# Search for the oauth and management app implementations
echo "=== OAuth App Implementation ==="
rg -B 2 -A 5 "export (const|function) oauthApp" apps/demo/src/

echo "=== Management App Implementation ==="
rg -B 2 -A 5 "export (const|function) managementApp" apps/demo/src/

Length of output: 294

apps/demo/src/helpers/encryption.ts Outdated Show resolved Hide resolved
apps/demo/src/helpers/encryption.ts Outdated Show resolved Hide resolved
apps/demo/package.json Outdated Show resolved Hide resolved
apps/demo/src/bun.ts Show resolved Hide resolved
packages/authhero/src/oauth-app.ts Outdated Show resolved Hide resolved
apps/demo/src/app.ts Outdated Show resolved Hide resolved
packages/authhero/src/management-app.ts Show resolved Hide resolved
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (1)
packages/authhero/src/index.ts (1)

5-5: Ensure consistent naming for default exports

In oauth-app.ts, the default exported function is named create, but in index.ts, it is imported as createOauthApi. For clarity and maintainability, consider renaming the function in oauth-app.ts to match the import name.

Suggested change in oauth-app.ts:

- export default function create() {
+ export default function createOauthApi() {

This will align the function name with its usage throughout the codebase.

Also applies to: 12-12

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e6e0660 and 38cf420.

📒 Files selected for processing (2)
  • packages/authhero/src/index.ts (1 hunks)
  • packages/authhero/src/oauth-app.ts (1 hunks)
🔇 Additional comments (1)
packages/authhero/src/oauth-app.ts (1)

27-33: Remove duplicate OpenAPI documentation

As previously noted, the oauthApp.doc("/spec", {...}) method is called twice with different titles but on the same path /spec. This can cause conflicts or overwrite documentation definitions.

Please consolidate the OpenAPI documentation into a single doc call, merging the information as needed.

Also applies to: 37-43

Comment on lines +12 to +17
export default function create() {
const app = new OpenAPIHono<{
Bindings: Bindings;
Variables: Variables;
}>();

Copy link

@coderabbitai coderabbitai bot Dec 9, 2024

Choose a reason for hiding this comment

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

⚠️ Potential issue

Unused app instance after middleware application

The app instance is created and middleware is applied using app.use(createAuthMiddleware(app));, but app is not used afterward. Instead, a new oauthApp instance is created and returned.

Consider either integrating the routes into app and returning it, or removing app if it's unnecessary.

Option 1: Integrate routes into app and return app:

export default function create() {
  const app = new OpenAPIHono<{
    Bindings: Bindings;
    Variables: Variables;
  }>();

  app.use(createAuthMiddleware(app));

- const oauthApp = new OpenAPIHono<{
-   Bindings: Bindings;
-   Variables: Variables;
- }>()
-   .route("/.well-known", wellKnownRoutes)
-   .route("/oauth/token", tokenRoutes);

+ app.route("/.well-known", wellKnownRoutes)
+    .route("/oauth/token", tokenRoutes);

  app.doc("/spec", {
    openapi: "3.0.0",
    info: {
      version: "1.0.0",
      title: "OAuth endpoints",
    },
  });

  registerComponent(app);

  return app;
}

Option 2: Remove app if it's not needed and apply middleware to oauthApp:

export default function create() {
- const app = new OpenAPIHono<{
-   Bindings: Bindings;
-   Variables: Variables;
- }>();

- app.use(createAuthMiddleware(app));

  const oauthApp = new OpenAPIHono<{
    Bindings: Bindings;
    Variables: Variables;
  }>()
+   .use(createAuthMiddleware)
    .route("/.well-known", wellKnownRoutes)
    .route("/oauth/token", tokenRoutes);

  oauthApp.doc("/spec", {
    openapi: "3.0.0",
    info: {
      version: "1.0.0",
      title: "OAuth endpoints",
    },
  });

  registerComponent(oauthApp);

  return oauthApp;
}

Committable suggestion skipped: line range outside the PR's diff.

Copy link
Owner Author

Choose a reason for hiding this comment

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

The issues is getting the types right. The middleware will return a normal hono router and not the openapi-version

Copy link

Choose a reason for hiding this comment

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

@markusahlstrand, thank you for the clarification. I understand that the issue is with the types—since the middleware returns a normal Hono router and not the OpenAPIHono version, integrating it directly affects type compatibility. That makes sense.


✏️ Learnings added
Learnt from: markusahlstrand
PR: markusahlstrand/authhero#8
File: packages/authhero/src/oauth-app.ts:12-17
Timestamp: 2024-12-09T10:49:39.560Z
Learning: In `packages/authhero/src/oauth-app.ts`, the middleware returns a normal Hono router instead of an `OpenAPIHono` instance, which can lead to type compatibility issues when integrating with `OpenAPIHono`.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

packages/authhero/src/index.ts Show resolved Hide resolved
@markusahlstrand markusahlstrand merged commit 63a3e17 into main Dec 9, 2024
2 of 3 checks passed
@markusahlstrand markusahlstrand deleted the update-demo branch December 9, 2024 10:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant