Skip to content

refactor(portal-framework-auth, portal-plugin-dashboard): add event emitter to auth provider#462

Merged
pcfreak30 merged 1 commit intodevelopfrom
libs/portal-plugin-dashboard
Aug 23, 2025
Merged

refactor(portal-framework-auth, portal-plugin-dashboard): add event emitter to auth provider#462
pcfreak30 merged 1 commit intodevelopfrom
libs/portal-plugin-dashboard

Conversation

@pcfreak30
Copy link
Copy Markdown
Member

@pcfreak30 pcfreak30 commented Aug 23, 2025

  • Added nanoevents dependency for event handling
  • Implemented AuthEvents interface with auth check and registration events
  • Extended AuthProvider to include event emitter functionality
  • Updated dashboard plugin to listen for auth success events

Summary by CodeRabbit

  • New Features

    • Authentication provider now emits events and supports subscriptions.
    • Dashboard listens for successful sign-in/OTP events and auto-syncs the API token to avoid re-auth prompts.
    • Registration attempts and auth success/failure are observable for integrations.
  • Chores

    • Added a dependency to enable the event system.

@changeset-bot
Copy link
Copy Markdown

changeset-bot bot commented Aug 23, 2025

⚠️ No Changeset found

Latest commit: 7afc796

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Aug 23, 2025

Walkthrough

Adds nanoevents and a typed nanoevents-based emitter to the auth data provider (new public event types and an on(...) API). The dashboard now subscribes to authCheckSuccess from the provider to update the REST token; no listener deregistration or destroy changes were added.

Changes

Cohort / File(s) Summary of changes
Dependencies
libs/portal-framework-auth/package.json
Added dependency nanoevents ^9.1.0.
Auth provider events API
libs/portal-framework-auth/src/dataProviders/auth.ts
Added event payload interfaces (AuthCheckFailedEvent, AuthCheckSuccessEvent, RegisterAttemptEvent), AuthEvents mapping, AuthProviderWithEmitter (adds on<E extends keyof AuthEvents>(event, callback): () => void), switched createAuthProvider to return the emitter-enabled provider, imported createNanoEvents, and emit authCheckFailed, authCheckSuccess, and registerAttempt at relevant flows.
Dashboard token sync integration
libs/portal-plugin-dashboard/src/capabilities/refineConfig.ts
Imported AuthProviderWithEmitter type and, when present, subscribed to the provider's authCheckSuccess event to update the REST data provider token (acctProvider.token = params.token). No listener deregistration or destroy logic was added in this diff.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant Auth as AuthProvider (with emitter)
  participant Emitter as Nanoevents Emitter
  participant Dashboard as Dashboard (refineConfig)
  participant REST as REST Data Provider

  User->>Auth: initiate login / auth check
  Auth->>Emitter: emit authCheckSuccess(token) or authCheckFailed(error)
  Dashboard->>Auth: on('authCheckSuccess', handler)  %% subscribe
  Emitter-->>Dashboard: authCheckSuccess(token)
  Dashboard->>REST: set acctProvider.token = token
  note right of REST: REST provider token updated for subsequent requests
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

I nibble on a tiny thread of news,
Events hop out — a token and some clues.
Dashboard perks up, ears all a-flutter,
REST waits ready — no more stutter.
🥕🐇

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 2625c7c and 7afc796.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (3)
  • libs/portal-framework-auth/package.json (1 hunks)
  • libs/portal-framework-auth/src/dataProviders/auth.ts (6 hunks)
  • libs/portal-plugin-dashboard/src/capabilities/refineConfig.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • libs/portal-framework-auth/package.json
  • libs/portal-framework-auth/src/dataProviders/auth.ts
  • libs/portal-plugin-dashboard/src/capabilities/refineConfig.ts
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch libs/portal-plugin-dashboard

🪧 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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
Copy Markdown

@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: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
libs/portal-framework-auth/src/dataProviders/auth.ts (1)

259-279: Bug: normal (non-OTP) login does not emit authCheckSuccess.

You set the SDK token but do not emit the event here. Downstream (dashboard) relies on this event to sync the REST data provider token, so post-login requests may use a stale token until a later check() runs.

Apply this diff:

         if (response.data.token) {
           sdk.setAuthToken(response.data.token);
+          emitter.emit("authCheckSuccess", { token: response.data.token });
           const baseUrl = getApiBaseUrl();
           if (baseUrl) {
🧹 Nitpick comments (3)
libs/portal-framework-auth/src/dataProviders/auth.ts (2)

68-80: Solid event contracts; consider rounding out event surface (optional).

The event names/readability are good. For completeness and downstream ergonomics, consider also emitting a logout-related event and/or a generic tokenRevoked event so subscribers can clear state when sessions end or checks fail.


326-329: PII event payload: be intentional about handling and logging.

registerAttempt includes email and firstName. If this is for metrics/telemetry, ensure subscribers avoid logging raw PII or scrub appropriately. Consider documenting the intended consumers and data handling expectations in code comments or README.

Would you like me to add a short JSDoc above RegisterAttemptEvent clarifying PII handling expectations?

libs/portal-plugin-dashboard/src/capabilities/refineConfig.ts (1)

36-38: Optional: clear token on authCheckFailed to reduce 401s after expiry.

Subscribing to authCheckFailed to clear acctProvider’s token (or trigger a redirect) can reduce transient unauthorized calls after session expiry.

Proposed snippet inside the guarded block:

this.#offAuthFailed?.();
const offFailed = authProvider.on("authCheckFailed", () => {
  acctProvider.setAuthToken("");
});
this.#offAuthFailed = offFailed;

And mirror a corresponding teardown in destroy().

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 7994d5a and 4e2a973.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (3)
  • libs/portal-framework-auth/package.json (1 hunks)
  • libs/portal-framework-auth/src/dataProviders/auth.ts (6 hunks)
  • libs/portal-plugin-dashboard/src/capabilities/refineConfig.ts (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
libs/portal-framework-auth/src/dataProviders/auth.ts (2)
libs/portal-sdk/src/account/generated/accountAPI.schemas.ts (1)
  • Error (74-78)
libs/portal-sdk/src/sdk.ts (1)
  • Sdk (3-18)
libs/portal-plugin-dashboard/src/capabilities/refineConfig.ts (1)
libs/portal-framework-auth/src/dataProviders/auth.ts (1)
  • AuthProviderWithEmitter (82-84)
🔇 Additional comments (6)
libs/portal-framework-auth/package.json (1)

23-25: Dependency addition looks appropriate.

nanoevents is a tiny, treeshakeable emitter well-suited for this use-case. Keeping it in dependencies (not devDependencies) is correct since it’s used at runtime.

libs/portal-framework-auth/src/dataProviders/auth.ts (3)

105-117: Good: emitting authCheckFailed/authCheckSuccess during check.

This will keep subscribers in sync after initial bootstrapping or token refresh. No issues spotted here.


210-214: Good: OTP login path emits authCheckSuccess.

This ensures immediate token propagation to subscribers after 2FA validation.


91-93: Verified: widened createAuthProvider return type does not break downstream typings

  • The only direct call to createAuthProvider is in libs/portal-framework-auth/src/capabilities/refineConfig.ts (line 44), assigning its result to a field typed AuthProvider. Extra emitter methods are structurally compatible with the AuthProvider interface.
  • The wrapper createPortalAuthProvider in libs/portal-shared/src/dataProviders/authProvider.ts explicitly returns AuthProvider (lines 124+), and does not delegate to createAuthProvider.
  • Other consumers (e.g. useCheckAuth(authProvider?: AuthProvider) in libs/portal-shared/src/hooks/useCheckAuth.ts and the authProvider constant in libs/portal-plugin-abuse-report/src/providers/auth-provider.ts) all expect AuthProvider and will accept the widened type without issue.

No further action required.

libs/portal-plugin-dashboard/src/capabilities/refineConfig.ts (2)

4-7: Import changes look good.

Using the extended AuthProviderWithEmitter type here is appropriate and keeps the dashboard decoupled from emitter implementation details.


55-76: Initialization ordering is already enforced by the framework manager

  • The core CapabilityManager (libs/portal-framework-core/src/capabilities/manager.ts) strictly awaits each capability’s initialize(this.#framework) before marking it initialized and resolving its deferred promise (lines 172–174).
  • In the UI, AppComponent (libs/portal-framework-ui/src/components/app/AppComponent.tsx:135) only iterates over and invokes cap.getConfig() on capabilities after they’ve all been initialized.

Since initialize() is guaranteed to run before getConfig(), no additional runtime guard or lazy‐initialization logic is needed here.

@pcfreak30 pcfreak30 force-pushed the libs/portal-plugin-dashboard branch from 4e2a973 to 2625c7c Compare August 23, 2025 11:30
…mitter to auth provider

- Added nanoevents dependency for event handling
- Implemented AuthEvents interface with auth check and registration events
- Extended AuthProvider to include event emitter functionality
- Updated dashboard plugin to listen for auth success events
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