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

Third party developers #23

Merged
merged 1 commit into from
Feb 20, 2025
Merged

Third party developers #23

merged 1 commit into from
Feb 20, 2025

Conversation

AnthonyRonning
Copy link
Contributor

@AnthonyRonning AnthonyRonning commented Feb 10, 2025

Summary by CodeRabbit

  • Documentation

    • Updated integration guidelines to require a unique Client ID alongside the API URL for proper configuration.
  • New Features

    • Introduced the Client ID requirement across authentication and account management flows to enhance security and consistency.
  • Chores

    • Added scripts for automated code formatting to ensure consistent styling.
  • Refactor / Style

    • Standardized formatting and parameter structures throughout the codebase for improved clarity and maintainability.
  • Bug Fixes

    • Enhanced error handling during test setup to ensure all required credentials are present.

Copy link

coderabbitai bot commented Feb 10, 2025

Walkthrough

This pull request updates the SDK to require an additional client identifier (clientId) across documentation, API functions, and tests. The OpenSecretProvider component and its usage examples now expect both an apiUrl and a clientId. API endpoint functions have been revised to include a new parameter (client_id) in their request payloads, and associated test files now ensure the corresponding environment variable is set. Additionally, the PR includes several formatting and minor refactoring updates, as well as the introduction of a fake attestation schema for local development.

Changes

Files Change Summary
README.md, src/main.tsx (instantiation) Updated documentation & component instantiation to require and pass both apiUrl and clientId.
src/lib/main.tsx Enhanced context: Added clientId property and updated authentication methods to include the new parameter in API calls.
src/lib/api.ts Revised API functions (login, signup, password reset, account conversion) to include an additional client_id parameter in their payloads.
src/lib/ai.test.ts, src/lib/api.test.ts, src/lib/signing.test.ts Updated tests to introduce TEST_CLIENT_ID and enforce its presence along with other credentials with improved error handling.
src/lib/attestation.ts Introduced FakeAttestationDocumentSchema and added conditional logic in verifyAttestation for handling fake attestations in local development.
package.json, src/global.d.ts, src/lib/attestationForView.ts, src/lib/getAttestation.ts, src/lib/pcr.ts, src/lib/test/api-url-loader.ts, src/lib/test/utils.ts Applied formatting improvements and code style updates, including new Prettier scripts and minor refactoring (indentation, quotes, newlines).

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant OSP as OpenSecretProvider
    participant API as API Service

    U->>OSP: Provide apiUrl & clientId
    OSP->>OSP: Validate clientId presence
    OSP->>API: signIn(email, password, clientId)
    API-->>OSP: Return login response
    OSP-->>U: Deliver authenticated session
Loading
sequenceDiagram
    participant Client
    participant Verifier as verifyAttestation
    participant Fake as fakeAuthenticate
    participant Real as authenticate

    Client->>Verifier: Submit attestation document
    Verifier->>Verifier: Check if running in local environment
    alt Local environment
        Verifier->>Fake: Process attestation
        Fake-->>Verifier: Return fake attestation result
    else Production
        Verifier->>Real: Process attestation
        Real-->>Verifier: Return attestation result
    end
    Verifier-->>Client: Return verification outcome
Loading

Possibly related PRs

  • Fix local attestations #20: Involves modifications to API parameter handling (apiUrl and clientId), closely related to the parameter enhancements made in this PR.

Poem

I'm a rabbit in the codeyard, hopping with delight,
New clientId fields now shine so bright.
With tests and docs all updated today,
I nibble on bugs that scurry away.
Format, refactor, and schema unfold—
A tiny tale of code in a world of gold! 🥕
Hoppy coding to all, in every byte and bit!

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

🪧 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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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: 0

🧹 Nitpick comments (5)
src/lib/api.test.ts (1)

85-127: Consider re-enabling guest conversion tests.

The guest conversion tests are commented out due to email sending. Consider mocking the email service to enable these tests.

Would you like me to help implement a mock email service to re-enable these tests?

src/lib/attestation.ts (1)

268-273: Consider using environment variable for development mode.

Instead of hardcoding development URLs, consider using an environment variable to determine the development mode.

-    if (
-      apiUrl &&
-      (apiUrl === "http://127.0.0.1:3000" ||
-        apiUrl === "http://localhost:3000" ||
-        apiUrl === "http://0.0.0.0:3000")
-    ) {
+    if (apiUrl && process.env.NODE_ENV === 'development') {
src/lib/signing.test.ts (2)

15-32: Consider addressing potential race condition.

While the delay helps ensure tokens are set, it might indicate an underlying race condition. Consider implementing a more robust solution, such as using events or promises to track token setup completion.

-    // Add a small delay to ensure tokens are properly set
-    await new Promise((resolve) => setTimeout(resolve, 100));
+    // Wait for token to be available
+    let attempts = 0;
+    const maxAttempts = 10;
+    while (!window.localStorage.getItem("access_token") && attempts < maxAttempts) {
+      await new Promise((resolve) => setTimeout(resolve, 50));
+      attempts++;
+    }
🧰 Tools
🪛 ESLint

[error] 29-29: Unexpected any. Specify a different type.

(@typescript-eslint/no-explicit-any)


132-248: Consider optimizing test execution.

The test includes delays between API calls, suggesting possible rate limiting. Consider:

  1. Documenting the rate limits in comments
  2. Using test doubles for rate-limited endpoints
  3. Implementing parallel test execution where possible
src/lib/getAttestation.ts (1)

28-31: Parameter Formatting & Unused Parameter Notice

The reformatting of the function signature for getAttestation improves readability. However, note that the new apiUrl parameter is defined but not used within the function body. If the parameter is intended for future enhancements or external configurations, consider adding an inline comment (or TODO) to clarify its purpose. Otherwise, it might be prudent to remove it to avoid confusion.

🧰 Tools
🪛 ESLint

[error] 30-30: 'apiUrl' is defined but never used.

(@typescript-eslint/no-unused-vars)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0923fbe and 1a6a7bc.

📒 Files selected for processing (15)
  • README.md (2 hunks)
  • package.json (1 hunks)
  • src/global.d.ts (1 hunks)
  • src/lib/ai.test.ts (4 hunks)
  • src/lib/api.test.ts (6 hunks)
  • src/lib/api.ts (9 hunks)
  • src/lib/attestation.ts (2 hunks)
  • src/lib/attestationForView.ts (3 hunks)
  • src/lib/getAttestation.ts (1 hunks)
  • src/lib/main.tsx (16 hunks)
  • src/lib/pcr.ts (2 hunks)
  • src/lib/signing.test.ts (11 hunks)
  • src/lib/test/api-url-loader.ts (1 hunks)
  • src/lib/test/utils.ts (1 hunks)
  • src/main.tsx (1 hunks)
✅ Files skipped from review due to trivial changes (5)
  • src/lib/test/utils.ts
  • src/lib/test/api-url-loader.ts
  • src/lib/attestationForView.ts
  • src/global.d.ts
  • src/lib/pcr.ts
🧰 Additional context used
🪛 GitHub Check: test
src/lib/api.test.ts

[failure] 20-20: error: Test credentials must be set in .env.local

  at /home/runner/work/OpenSecret-SDK/OpenSecret-SDK/src/lib/api.test.ts:20:9
src/lib/signing.test.ts

[failure] 12-12: error: Test credentials must be set in .env.local

  at /home/runner/work/OpenSecret-SDK/OpenSecret-SDK/src/lib/signing.test.ts:12:9
src/lib/ai.test.ts

[failure] 12-12: error: Test credentials must be set in .env.local

  at /home/runner/work/OpenSecret-SDK/OpenSecret-SDK/src/lib/ai.test.ts:12:9
🪛 GitHub Actions: Library Tests
src/lib/api.test.ts

[error] 1-1: Unhandled error between tests.

🪛 ESLint
src/lib/signing.test.ts

[error] 29-29: Unexpected any. Specify a different type.

(@typescript-eslint/no-explicit-any)

src/lib/getAttestation.ts

[error] 30-30: 'apiUrl' is defined but never used.

(@typescript-eslint/no-unused-vars)

🔇 Additional comments (19)
src/main.tsx (1)

9-12: Verify environment variable setup.

The VITE_CLIENT_ID environment variable is now required. Ensure it's properly configured in your deployment environments.

Run this script to check environment variable setup:

❌ Verification inconclusive

🏁 Script executed:

#!/bin/bash
# Description: Check if VITE_CLIENT_ID is set in environment files.

# Test: Search for VITE_CLIENT_ID in environment files. Expect: At least one occurrence.
fd -t f '\.env' -x grep -l 'VITE_CLIENT_ID'

Length of output: 43


ENV Variable Setup Requires Manual Verification

The automated search did not locate any occurrence of VITE_CLIENT_ID in repository environment files. This could mean one of two things:

  • The variable is configured externally in your deployment/CI environment rather than in version-controlled .env files.
  • The variable setup is missing and needs to be added.

Please manually confirm that VITE_CLIENT_ID is correctly configured in the intended deployment environment.

src/lib/ai.test.ts (2)

8-13: LGTM! Environment variable check is comprehensive.

The check for required test credentials is thorough and includes the new TEST_CLIENT_ID.

🧰 Tools
🪛 GitHub Check: test

[failure] 12-12: error: Test credentials must be set in .env.local

  at /home/runner/work/OpenSecret-SDK/OpenSecret-SDK/src/lib/ai.test.ts:12:9

21-25: LGTM! Authentication flow updated correctly.

The fetchLogin call has been properly updated to include the required TEST_CLIENT_ID parameter.

src/lib/api.test.ts (1)

19-21: LGTM! Environment variable check is comprehensive.

The check for required test credentials is thorough and includes the new TEST_CLIENT_ID.

🧰 Tools
🪛 GitHub Check: test

[failure] 20-20: error: Test credentials must be set in .env.local

  at /home/runner/work/OpenSecret-SDK/OpenSecret-SDK/src/lib/api.test.ts:20:9
src/lib/attestation.ts (1)

243-245: LGTM! Schema definition is clear and focused.

The FakeAttestationDocumentSchema is well-defined and appropriately scoped for local development.

src/lib/signing.test.ts (3)

9-13: LGTM! Good validation of test credentials.

Early validation of required test credentials with a clear error message improves the developer experience.

🧰 Tools
🪛 GitHub Check: test

[failure] 12-12: error: Test credentials must be set in .env.local

  at /home/runner/work/OpenSecret-SDK/OpenSecret-SDK/src/lib/signing.test.ts:12:9

64-96: LGTM! Comprehensive test coverage.

The test thoroughly validates the signature format, hash matching, and cryptographic verification using noble/curves.


250-289: LGTM! Good test coverage for edge cases.

The tests effectively cover authentication failures, signature uniqueness, and public key consistency.

src/lib/api.ts (3)

550-569: LGTM! Clean implementation of optional parameters.

Good use of the spread operator for optional parameters and clean type definitions.


236-276: Breaking change: Added client_id to password reset functions.

The addition of the required client_id parameter to password reset functions is a breaking change. The error handling is well-structured with clear error messages.

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Check for existing usages that need to be updated
rg -A 2 "requestPasswordReset|confirmPasswordReset" --type ts

Length of output: 1192


Breaking Change Confirmed: New client_id Parameter

  • Both requestPasswordReset and confirmPasswordReset now require the client_id parameter.
  • This change is breaking as it forces all callers (e.g., in src/lib/main.tsx) to provide this additional argument.
  • The error messages remain clear and well-structured.

45-107: Breaking change: Added required client_id parameter.

The addition of the required client_id parameter to authentication functions is a breaking change. Ensure this is documented in the changelog and migration guide.

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Check for existing usages that need to be updated
rg -A 2 "fetchLogin|fetchGuestLogin|fetchSignUp|fetchGuestSignUp" --type ts

Length of output: 4476


Breaking Change Detected: client_id as a Required Parameter

The grep results confirm that all usages of the authentication functions in the tests (and in the main code) have been updated to include the new required client_id parameter. This breaking change is correctly propagated across the codebase.
Please ensure that the changelog and migration guide are updated accordingly to reflect this breaking change.

src/lib/main.tsx (3)

21-385: LGTM! Well-documented context type definitions.

The addition of clientId to the context is well-documented with clear JSDoc comments explaining its purpose and usage.


413-478: LGTM! Good input validation.

The provider properly validates both apiUrl and clientId with clear error messages.


483-552: LGTM! Consistent error handling.

The authentication methods consistently handle errors and include helpful logging.

package.json (1)

23-24: LGTM! Good addition of formatting scripts.

The addition of Prettier formatting scripts with comprehensive file patterns will help maintain consistent code style.

README.md (4)

15-17: Documentation Clarity Improved for Usage Instructions

The added lines now clearly list both the backend URL and the project’s client ID as required props. This helps users understand the new requirements for the provider.


24-27: Correct JSX Provider Instantiation Update

The updated code snippet now correctly passes both apiUrl and clientId to the <OpenSecretProvider>. This aligns the usage example with the new prop requirements.


60-62: Enhanced API Reference Description

The updated text in the API Reference section now accurately describes the two essential props: apiUrl and clientId. This reinforces the configuration requirements presented in the usage section.


65-68: Consistent Example in API Reference

The updated code snippet example in the API Reference correctly demonstrates the updated component usage with both apiUrl and clientId. The consistency between usage and reference is maintained.

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: 0

🧹 Nitpick comments (3)
src/lib/ai.test.ts (3)

11-13: Enhance error message with specific missing variables.

The error message could be more helpful by indicating which specific environment variables are missing.

-  throw new Error("Test credentials must be set in .env.local");
+  const missingVars = [
+    !TEST_EMAIL && "VITE_TEST_EMAIL",
+    !TEST_PASSWORD && "VITE_TEST_PASSWORD",
+    !TEST_CLIENT_ID && "VITE_TEST_CLIENT_ID",
+    !API_URL && "VITE_OPEN_SECRET_API_URL"
+  ].filter(Boolean);
+  throw new Error(`Missing required environment variables: ${missingVars.join(", ")}`);
🧰 Tools
🪛 GitHub Check: test

[failure] 12-12: error: Test credentials must be set in .env.local

  at /home/runner/work/OpenSecret-SDK/OpenSecret-SDK/src/lib/ai.test.ts:12:9

43-46: Consider making the model name configurable.

The model name is hardcoded, which could make the tests brittle if the model changes.

+const TEST_MODEL = process.env.VITE_TEST_MODEL || "ibnzterrell/Meta-Llama-3.3-70B-Instruct-AWQ-INT4";
-  const model = "ibnzterrell/Meta-Llama-3.3-70B-Instruct-AWQ-INT4";
+  const model = TEST_MODEL;

77-78: Remove model name duplication.

The model name is duplicated from the test case. Consider extracting it to a shared constant.

+const TEST_MODEL = process.env.VITE_TEST_MODEL || "ibnzterrell/Meta-Llama-3.3-70B-Instruct-AWQ-INT4";
...
-      model: "ibnzterrell/Meta-Llama-3.3-70B-Instruct-AWQ-INT4",
+      model: TEST_MODEL,
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7c69cbf and e027bb9.

📒 Files selected for processing (1)
  • src/lib/ai.test.ts (4 hunks)
🧰 Additional context used
🪛 GitHub Check: test
src/lib/ai.test.ts

[failure] 12-12: error: Test credentials must be set in .env.local

  at /home/runner/work/OpenSecret-SDK/OpenSecret-SDK/src/lib/ai.test.ts:12:9
🔇 Additional comments (3)
src/lib/ai.test.ts (3)

15-18: LGTM!

The ChatMessage type definition is clear and well-structured.


109-116: LGTM!

The test case is well-structured and properly validates the streaming functionality.


20-28:

✅ Verification successful

LGTM! Verify token storage.

The function correctly handles the new client ID parameter and token storage.


🏁 Script executed:

#!/bin/bash
# Description: Verify that the tokens are properly used in other test files.

# Search for localStorage.setItem usage with tokens
rg -A 2 'localStorage\.setItem.*token'

Length of output: 3271


LGTM – Token Storage Confirmed

The setupTestUser function now correctly integrates the TEST_CLIENT_ID parameter and reliably stores tokens. A repository-wide search confirms that all instances (in files like src/lib/ai.test.ts, src/lib/main.tsx, and src/lib/api.test.ts) correctly use localStorage.setItem for token storage. No further changes are required.

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: 0

🧹 Nitpick comments (2)
README.md (2)

60-62: API Reference Enhancements:
The API reference now explicitly states that the OpenSecretProvider requires two props—apiUrl and clientId. The description for clientId clearly mentions that it is a UUID that identifies the project, which is very helpful. You might consider emphasizing that the clientId must be a valid UUID for added clarity.


80-82: Authentication Methods Documentation Update:
The modifications to the authentication method descriptions (for signInGuest, signUpGuest, and convertGuestToUserAccount) now indicate that guest account operations are scoped based on clientId. This detail is both informative and necessary given the current SDK changes. As a minor nitpick, please review and ensure consistent punctuation (for example, that each descriptive sentence ends with a period) for uniformity.

🧰 Tools
🪛 LanguageTool

[uncategorized] ~80-~80: Loose punctuation mark.
Context: ...tring, password: string): Promise`: Signs in a guest user with their ID and...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~81-~81: Loose punctuation mark.
Context: ...teCode: string): Promise`: Creates a new guest account with just a...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~82-~82: Loose punctuation mark.
Context: ...: string, name?: string): Promise`: Converts current guest account to a reg...

(UNLIKELY_OPENING_PUNCTUATION)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e027bb9 and 910b57f.

📒 Files selected for processing (3)
  • README.md (3 hunks)
  • src/lib/api.ts (11 hunks)
  • src/lib/main.tsx (20 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/lib/api.ts
  • src/lib/main.tsx
🧰 Additional context used
🪛 LanguageTool
README.md

[uncategorized] ~80-~80: Loose punctuation mark.
Context: ...tring, password: string): Promise`: Signs in a guest user with their ID and...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~81-~81: Loose punctuation mark.
Context: ...teCode: string): Promise`: Creates a new guest account with just a...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~82-~82: Loose punctuation mark.
Context: ...: string, name?: string): Promise`: Converts current guest account to a reg...

(UNLIKELY_OPENING_PUNCTUATION)

🔇 Additional comments (2)
README.md (2)

15-17: Usage Instructions Update:
The updated instructions clearly list the required props—apiUrl and clientId—for wrapping your application in the OpenSecretProvider component. This added detail improves clarity for developers setting up the SDK.


24-27: Updated Provider Usage Example:
The usage example now correctly demonstrates how to pass both the apiUrl and the new clientId prop. This aligns perfectly with the SDK’s new requirements. Consider adding a brief note that these are placeholder values meant to be replaced in real configurations.

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: 0

🧹 Nitpick comments (6)
src/lib/signing.test.ts (1)

29-29: Improve type safety by replacing 'any' with a specific error type.

Consider using a more specific type for error handling instead of 'any'.

-  } catch (error: any) {
+  } catch (error: Error | unknown) {
🧰 Tools
🪛 ESLint

[error] 29-29: Unexpected any. Specify a different type.

(@typescript-eslint/no-explicit-any)

src/lib/api.ts (1)

236-253: Consider enhancing error messages for password reset functions.

While the client_id integration is correct, the error messages could be more specific to help with debugging.

-    "Failed to request password reset"
+    "Failed to request password reset. Please verify your email and client ID."
-    "Failed to confirm password reset"
+    "Failed to confirm password reset. Please verify your credentials and client ID."

Also applies to: 255-276

src/lib/main.tsx (3)

24-28: Consider enhancing clientId validation.

While the provider validates that clientId is non-empty, it should also validate the UUID format.

+  const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
   if (!clientId || clientId.trim() === "") {
     throw new Error(
       "OpenSecretProvider requires a non-empty clientId. Please provide a valid project UUID."
     );
   }
+  if (!UUID_REGEX.test(clientId)) {
+    throw new Error(
+      "OpenSecretProvider requires a valid UUID for clientId. Please provide a valid UUID v4."
+    );
+  }

Also applies to: 435-447


488-499: Consider enhancing error handling for authentication methods.

While the implementation correctly uses clientId, the error handling could be more specific about client ID related issues.

   } catch (error) {
     console.error(error);
+    if (error instanceof Error && error.message.includes("client_id")) {
+      throw new Error("Authentication failed: Invalid or unauthorized client ID.");
+    }
     throw error;
   }

Also applies to: 501-517, 519-530, 532-547


495-498: Consider implementing structured error handling.

The current error handling could be improved by implementing structured error types for better error management and user feedback.

type AuthError = {
  code: 'INVALID_CLIENT_ID' | 'UNAUTHORIZED' | 'NETWORK_ERROR';
  message: string;
  details?: unknown;
};

function handleAuthError(error: unknown): AuthError {
  if (error instanceof Error) {
    if (error.message.includes("client_id")) {
      return { code: 'INVALID_CLIENT_ID', message: 'Invalid or unauthorized client ID.' };
    }
    // Add more error type checks
  }
  return { code: 'NETWORK_ERROR', message: 'An unexpected error occurred.', details: error };
}

Also applies to: 513-516, 526-529, 543-546

README.md (1)

15-18: Consider adding security best practices for client ID handling.

While the documentation clearly explains the client ID requirement, it would be helpful to add security best practices.

Add the following security notes:

### Security Best Practices
- Store your client ID securely and never expose it in client-side source code
- Use environment variables to inject the client ID during build/runtime
- Regularly audit client ID usage and rotate if compromised

Also applies to: 60-63

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 910b57f and 96eeddc.

📒 Files selected for processing (20)
  • README.md (3 hunks)
  • package.json (1 hunks)
  • src/AI.tsx (5 hunks)
  • src/App.css (1 hunks)
  • src/App.tsx (10 hunks)
  • src/global.d.ts (1 hunks)
  • src/lib/ai.test.ts (4 hunks)
  • src/lib/ai.ts (1 hunks)
  • src/lib/api.test.ts (6 hunks)
  • src/lib/api.ts (11 hunks)
  • src/lib/attestation.ts (2 hunks)
  • src/lib/attestationForView.ts (3 hunks)
  • src/lib/getAttestation.ts (1 hunks)
  • src/lib/main.tsx (20 hunks)
  • src/lib/pcr.ts (2 hunks)
  • src/lib/signing.test.ts (11 hunks)
  • src/lib/test/api-url-loader.ts (1 hunks)
  • src/lib/test/der-loader.ts (1 hunks)
  • src/lib/test/utils.ts (1 hunks)
  • src/main.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (13)
  • src/lib/test/utils.ts
  • src/lib/test/der-loader.ts
  • package.json
  • src/lib/test/api-url-loader.ts
  • src/global.d.ts
  • src/lib/ai.ts
  • src/main.tsx
  • src/AI.tsx
  • src/lib/attestationForView.ts
  • src/App.css
  • src/lib/attestation.ts
  • src/lib/pcr.ts
  • src/App.tsx
🧰 Additional context used
🪛 GitHub Check: test
src/lib/api.test.ts

[failure] 20-20: error: Test credentials must be set in .env.local

  at /home/runner/work/OpenSecret-SDK/OpenSecret-SDK/src/lib/api.test.ts:20:9
src/lib/signing.test.ts

[failure] 12-12: error: Test credentials must be set in .env.local

  at /home/runner/work/OpenSecret-SDK/OpenSecret-SDK/src/lib/signing.test.ts:12:9
src/lib/ai.test.ts

[failure] 12-12: error: Test credentials must be set in .env.local

  at /home/runner/work/OpenSecret-SDK/OpenSecret-SDK/src/lib/ai.test.ts:12:9
🪛 GitHub Actions: Library Tests
src/lib/api.test.ts

[error] 1-1: Unhandled error between tests

🪛 ESLint
src/lib/signing.test.ts

[error] 29-29: Unexpected any. Specify a different type.

(@typescript-eslint/no-explicit-any)

src/lib/getAttestation.ts

[error] 30-30: 'apiUrl' is defined but never used.

(@typescript-eslint/no-unused-vars)

🪛 LanguageTool
README.md

[uncategorized] ~80-~80: Loose punctuation mark.
Context: ...tring, password: string): Promise`: Signs in a guest user with their ID and...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~81-~81: Loose punctuation mark.
Context: ...teCode: string): Promise`: Creates a new guest account with just a...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~82-~82: Loose punctuation mark.
Context: ...: string, name?: string): Promise`: Converts current guest account to a reg...

(UNLIKELY_OPENING_PUNCTUATION)

🔇 Additional comments (12)
src/lib/getAttestation.ts (2)

28-31: Address unused parameter.

The apiUrl parameter is defined but never used in the function implementation.

Do you want me to help implement the apiUrl parameter usage or should it be removed?

🧰 Tools
🪛 ESLint

[error] 30-30: 'apiUrl' is defined but never used.

(@typescript-eslint/no-unused-vars)


20-20: LGTM!

The formatting change improves readability without affecting functionality.

src/lib/ai.test.ts (2)

8-13: LGTM!

The credential validation ensures all required test credentials are present.

🧰 Tools
🪛 GitHub Check: test

[failure] 12-12: error: Test credentials must be set in .env.local

  at /home/runner/work/OpenSecret-SDK/OpenSecret-SDK/src/lib/ai.test.ts:12:9

21-25: LGTM!

The login function is correctly updated to include the new client ID parameter.

src/lib/api.test.ts (3)

17-21: LGTM!

The credential validation ensures all required test credentials are present.

🧰 Tools
🪛 GitHub Check: test

[failure] 20-20: error: Test credentials must be set in .env.local

  at /home/runner/work/OpenSecret-SDK/OpenSecret-SDK/src/lib/api.test.ts:20:9

23-32: LGTM!

The email login and signup functions are correctly updated to include the client ID parameter.


63-84: LGTM!

The guest signup and login flow correctly integrates the client ID parameter.

src/lib/signing.test.ts (1)

15-31: LGTM!

The enhanced error handling in setupTestUser provides better debugging information.

🧰 Tools
🪛 ESLint

[error] 29-29: Unexpected any. Specify a different type.

(@typescript-eslint/no-explicit-any)

src/lib/api.ts (3)

45-54: LGTM! Authentication functions properly updated to include client_id.

The changes consistently add the client_id parameter across all authentication functions, with proper type definitions and request payload updates.

Also applies to: 57-66, 69-92, 94-106


291-311: LGTM! OAuth functions properly handle client_id with comprehensive error handling.

The implementation correctly:

  • Adds client_id to both GitHub and Google OAuth initiation
  • Maintains detailed error handling with specific error messages

Also applies to: 361-381


133-182: LGTM! Unmodified functions maintain their functionality.

The key-value storage and user management functions correctly maintain their existing implementation, as they don't require client identification.

README.md (1)

80-83: LGTM! Clear documentation of guest account scoping.

The documentation clearly explains how guest accounts are scoped to specific projects using clientId.

🧰 Tools
🪛 LanguageTool

[uncategorized] ~80-~80: Loose punctuation mark.
Context: ...tring, password: string): Promise`: Signs in a guest user with their ID and...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~81-~81: Loose punctuation mark.
Context: ...teCode: string): Promise`: Creates a new guest account with just a...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~82-~82: Loose punctuation mark.
Context: ...: string, name?: string): Promise`: Converts current guest account to a reg...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~83-~83: Loose punctuation mark.
Context: ...ated under. - signOut(): Promise<void>: Signs out the current user. #### Key-V...

(UNLIKELY_OPENING_PUNCTUATION)

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: 0

🧹 Nitpick comments (4)
src/lib/signing.test.ts (1)

29-31: Improve type safety by replacing any with a specific error type.

Consider using a more specific type for error handling instead of any.

-  } catch (error: any) {
+  } catch (error: unknown) {
+    const errorMessage = error instanceof Error ? error.message : String(error);
-    throw new Error("Failed to set up test user: " + error.message);
+    throw new Error("Failed to set up test user: " + errorMessage);
🧰 Tools
🪛 ESLint

[error] 29-29: Unexpected any. Specify a different type.

(@typescript-eslint/no-explicit-any)

src/lib/api.ts (2)

69-92: Consider reordering parameters to maintain consistency.

The client_id parameter is placed before the optional name parameter. While this works, it would be more consistent with TypeScript conventions to group required parameters first, followed by optional parameters.

-export async function fetchSignUp(
-  email: string,
-  password: string,
-  inviteCode: string,
-  client_id: string,
-  name?: string | null
-): Promise<LoginResponse> {
+export async function fetchSignUp(
+  email: string,
+  password: string,
+  inviteCode: string,
+  name?: string | null,
+  client_id: string
+): Promise<LoginResponse> {

236-252: Consider using a type for the reset data payload.

The reset data structure could be reused across functions. Consider extracting it to a type definition.

+type PasswordResetRequestData = {
+  email: string;
+  hashed_secret: string;
+  client_id: string;
+};

 export async function requestPasswordReset(
   email: string,
   hashedSecret: string,
   client_id: string
 ): Promise<void> {
-  const resetData = {
-    email,
-    hashed_secret: hashedSecret,
-    client_id
-  };
+  const resetData: PasswordResetRequestData = {
+    email,
+    hashed_secret: hashedSecret,
+    client_id
+  };
src/lib/main.tsx (1)

663-670: Consider extracting password reset function types.

The password reset function types could be extracted to improve readability and reusability.

+type PasswordResetRequest = (email: string, hashedSecret: string) => Promise<void>;
+type PasswordResetConfirmation = (
+  email: string,
+  alphanumericCode: string,
+  plaintextSecret: string,
+  newPassword: string
+) => Promise<void>;

-    requestPasswordReset: (email: string, hashedSecret: string) =>
-      api.requestPasswordReset(email, hashedSecret, clientId),
-    confirmPasswordReset: (
-      email: string,
-      alphanumericCode: string,
-      plaintextSecret: string,
-      newPassword: string
-    ) => api.confirmPasswordReset(email, alphanumericCode, plaintextSecret, newPassword, clientId),
+    requestPasswordReset: ((email, hashedSecret) =>
+      api.requestPasswordReset(email, hashedSecret, clientId)) as PasswordResetRequest,
+    confirmPasswordReset: ((email, alphanumericCode, plaintextSecret, newPassword) =>
+      api.confirmPasswordReset(
+        email,
+        alphanumericCode,
+        plaintextSecret,
+        newPassword,
+        clientId
+      )) as PasswordResetConfirmation,
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 96eeddc and 1fcc7a6.

📒 Files selected for processing (21)
  • .github/workflows/test.yml (1 hunks)
  • README.md (3 hunks)
  • package.json (1 hunks)
  • src/AI.tsx (5 hunks)
  • src/App.css (1 hunks)
  • src/App.tsx (10 hunks)
  • src/global.d.ts (1 hunks)
  • src/lib/ai.test.ts (4 hunks)
  • src/lib/ai.ts (1 hunks)
  • src/lib/api.test.ts (6 hunks)
  • src/lib/api.ts (11 hunks)
  • src/lib/attestation.ts (2 hunks)
  • src/lib/attestationForView.ts (3 hunks)
  • src/lib/getAttestation.ts (1 hunks)
  • src/lib/main.tsx (20 hunks)
  • src/lib/pcr.ts (2 hunks)
  • src/lib/signing.test.ts (11 hunks)
  • src/lib/test/api-url-loader.ts (1 hunks)
  • src/lib/test/der-loader.ts (1 hunks)
  • src/lib/test/utils.ts (1 hunks)
  • src/main.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (13)
  • src/lib/test/api-url-loader.ts
  • src/lib/test/der-loader.ts
  • src/lib/attestationForView.ts
  • src/global.d.ts
  • src/lib/test/utils.ts
  • src/lib/ai.ts
  • src/main.tsx
  • src/lib/attestation.ts
  • package.json
  • src/AI.tsx
  • src/App.css
  • src/App.tsx
  • src/lib/pcr.ts
🧰 Additional context used
🪛 LanguageTool
README.md

[uncategorized] ~80-~80: Loose punctuation mark.
Context: ...tring, password: string): Promise`: Signs in a guest user with their ID and...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~81-~81: Loose punctuation mark.
Context: ...teCode: string): Promise`: Creates a new guest account with just a...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~82-~82: Loose punctuation mark.
Context: ...: string, name?: string): Promise`: Converts current guest account to a reg...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~82-~82: The preposition “for” seems more likely in this position.
Context: ...ed with the same project it was created under. - signOut(): Promise<void>: Signs ou...

(AI_EN_LECTOR_REPLACEMENT_PREPOSITION)

🪛 ESLint
src/lib/getAttestation.ts

[error] 30-30: 'apiUrl' is defined but never used.

(@typescript-eslint/no-unused-vars)

src/lib/signing.test.ts

[error] 29-29: Unexpected any. Specify a different type.

(@typescript-eslint/no-explicit-any)

🔇 Additional comments (12)
src/lib/getAttestation.ts (1)

28-31: Use the apiUrl parameter or remove it.

The apiUrl parameter is defined but never used in the function. If this parameter is intended to be used for making API calls, please implement its usage. Otherwise, consider removing it.

🧰 Tools
🪛 ESLint

[error] 30-30: 'apiUrl' is defined but never used.

(@typescript-eslint/no-unused-vars)

src/lib/ai.test.ts (1)

8-13: LGTM!

Good addition of TEST_CLIENT_ID validation and proper error handling for missing environment variables.

src/lib/api.test.ts (1)

17-21: LGTM!

Good integration of TEST_CLIENT_ID across all authentication flows, including email and guest user scenarios.

src/lib/signing.test.ts (1)

9-13: LGTM!

Good addition of TEST_CLIENT_ID validation and proper error handling for missing environment variables.

src/lib/api.ts (4)

45-54: LGTM! The client_id parameter is correctly added to fetchLogin.

The function signature and payload are properly updated to include the new client_id parameter.


57-66: LGTM! The client_id parameter is correctly added to fetchGuestLogin.

The function signature and payload are properly updated to include the new client_id parameter.


361-380:

❓ Verification inconclusive

Verify Google OAuth integration with client_id parameter.

The Google OAuth flow has been updated to include client_id. Ensure this change is coordinated with the Google OAuth application settings.


🏁 Script executed:

#!/bin/bash
# Description: Check if Google OAuth callback endpoint handles client_id parameter

# Search for Google OAuth callback handler implementation
rg -A 10 "google/callback"

Length of output: 495


Google OAuth Integration: Confirm Coordination on the client_id Update

The updated initiateGoogleAuth function now correctly includes the client_id in its POST payload to ${apiUrl}/auth/google. A search also confirms that the corresponding callback endpoint (${apiUrl}/auth/google/callback) exists and is invoked with callbackData. Please verify that:

  • The server-side logic for the Google OAuth callback is updated as needed to handle (or safely ignore) the client_id—if its management is required on this endpoint.
  • The Google OAuth application settings (in the Google API Console) are coordinated with this change to ensure consistency across the OAuth flow.

291-310:

❓ Verification inconclusive

Verify GitHub OAuth integration with client_id parameter.

The GitHub OAuth flow has been updated to include client_id. Ensure this change is coordinated with the GitHub OAuth application settings.


🏁 Script executed:

#!/bin/bash
# Description: Check if GitHub OAuth callback endpoint handles client_id parameter

# Search for GitHub OAuth callback handler implementation
rg -A 10 "github/callback"

Length of output: 495


Action: Confirm GitHub OAuth Integration with Updated client_id Parameter

  • The updated initiateGitHubAuth function now explicitly passes the client_id (along with an optional invite code) when calling the GitHub auth endpoint.
  • Our search confirms that the GitHub callback endpoint is implemented (as seen in src/lib/api.ts), though it doesn’t directly reference the client_id parameter—consistent with the expected flow.
  • Please ensure that the GitHub OAuth application settings are adjusted to accommodate this change and that any backend handling (especially around the callback) remains in sync with these client_id updates.
src/lib/main.tsx (2)

24-28: LGTM! The clientId property is well documented.

The JSDoc comments clearly explain the purpose and type of the clientId property.


435-447: LGTM! Proper validation of required props.

The useEffect hook correctly validates both apiUrl and clientId, throwing descriptive errors if either is missing or empty.

.github/workflows/test.yml (1)

31-31: LGTM! Test environment properly configured.

The VITE_TEST_CLIENT_ID secret is correctly added to the test environment.

README.md (1)

15-17: LGTM! Documentation is clear and comprehensive.

The README updates clearly explain:

  • The requirement for both apiUrl and clientId
  • The purpose of the clientId (project/tenant identification)
  • Updated usage examples with both props

Also applies to: 24-27, 60-62

@AnthonyRonning AnthonyRonning merged commit b44de62 into master Feb 20, 2025
2 checks passed
@AnthonyRonning AnthonyRonning deleted the add-client-id branch February 20, 2025 03:19
@coderabbitai coderabbitai bot mentioned this pull request Feb 25, 2025
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