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

fix: Stop whitespace in prefixes and fixes validation on bytes #2893

Merged
merged 6 commits into from
Feb 13, 2025

Conversation

perkinsjr
Copy link
Collaborator

@perkinsjr perkinsjr commented Feb 13, 2025

What does this PR do?

Fixes #2297

If there is not an issue for this, please create one first. This is used to tracking purposes and also helps use understand why this PR exists

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • Chore (refactoring code, technical debt, workflow improvements)
  • Enhancement (small improvements)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

How should this be tested?

Try updating your prefix with spaces in the middle or end. This should error before submission.

Checklist

Required

  • Filled out the "How to test" section in this PR
  • Read Contributing Guide
  • Self-reviewed my own code
  • Commented on my code in hard-to-understand areas
  • Ran pnpm build
  • Ran pnpm fmt
  • Checked for warnings, there are none
  • Removed all console.logs
  • Merged the latest changes from main onto my branch with git pull origin main
  • My changes don't cause any responsiveness issues

Appreciated

  • If a UI change was made: Added a screen recording or screenshots to this PR
  • Updated the Unkey Docs if changes were necessary

Summary by CodeRabbit

  • New Features
    • Enhanced prefix field validation across API and dashboard settings to enforce an 8-character limit and disallow spaces.
    • Updated error messages provide clearer, more intuitive feedback on invalid inputs.
    • Redesigned form structures improve how validation messages are displayed for a smoother, more efficient user experience.

Prefix allowed for whitespaces

- Refined them
- Fixed errors
- Removed redudant errors
- Made all the errors the same
Copy link

changeset-bot bot commented Feb 13, 2025

⚠️ No Changeset found

Latest commit: 8f152c5

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

Copy link

vercel bot commented Feb 13, 2025

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

Name Status Preview Comments Updated (UTC)
dashboard ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 13, 2025 2:45pm
engineering ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 13, 2025 2:45pm
play ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 13, 2025 2:45pm
www ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 13, 2025 2:45pm

Copy link
Contributor

coderabbitai bot commented Feb 13, 2025

📝 Walkthrough

Walkthrough

This pull request updates the validation logic and form handling in several components. The changes enhance the enforcement of constraints on the prefix and defaultPrefix fields by updating error messages, enforcing maximum lengths, and introducing additional checks to disallow spaces. In parallel, form components have been refactored to leverage a new set of UI components and an asynchronous resolver for improved structure and validation integration.

Changes

File(s) Change Summaries
apps/dashboard/.../keys/[keyAuthId]/new/validation.ts Updated prefix schema: removed .trim(), modified max-length error message, and added a space-check refinement.
apps/dashboard/.../settings/default-bytes.tsx,
apps/dashboard/.../settings/default-prefix.tsx
Refactored form structure with new Form, FormControl, FormItem, and FormMessage components; updated resolver to an asynchronous wrapper around zodResolver with additional configuration options; enhanced field validation.
apps/dashboard/.../routers/api/setDefaultPrefix.ts,
apps/dashboard/.../routers/key/create.ts
Updated API procedures’ input validation schemas to enforce a maximum length (with a new error message) and to disallow spaces using a refinement on the prefix/defaultPrefix fields.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant F as Form Component
    participant V as Validation (Zod)
    participant A as API Procedure

    U->>F: Submit form data
    F->>V: Validate input (prefix/defaultPrefix)
    alt Validation passes
        F->>A: Invoke API procedure
    else Validation fails
        V->>F: Return error messages
        F->>U: Display error messages
    end
Loading

Possibly related PRs

  • fix: create key toggle issue #2711 – The changes in the main PR regarding the validation of the prefix field are directly related to the modifications in the retrieved PR, which also updates the validation for the prefix field in the createKey procedure, enforcing similar constraints.
  • feat: Add default bytes and prefix #2146 – The changes in the main PR regarding the validation of the prefix field are directly related to the modifications in the retrieved PR, which also involves the defaultPrefix field's validation logic, ensuring both adhere to similar constraints.
  • fix: UI for update and create key #2795 – The changes in the main PR regarding the validation of the prefix field are directly related to the modifications in the retrieved PR, which also involve validation for the defaultPrefix and prefix fields, ensuring they do not exceed a maximum length and do not contain spaces.

Suggested labels

Feature, Needs Approval

Suggested reviewers

  • mcstepp
  • chronark
  • ogzhanolguncu
  • MichaelUnkey

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 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.

@github-actions github-actions bot added the Bug Something isn't working label Feb 13, 2025
Copy link
Contributor

github-actions bot commented Feb 13, 2025

Thank you for following the naming conventions for pull request titles! 🙏

Form validation never worked on our default pages.

This fixes that and also fixes white spaces anywhere with an error
Copy link
Contributor

@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

🧹 Nitpick comments (2)
apps/dashboard/app/(app)/apis/[apiId]/settings/default-prefix.tsx (1)

93-97: Remove unnecessary empty onBlur handler.

The onBlur handler doesn't perform any action and can be removed.

Apply this diff:

 <Input
   className="max-w-sm"
   {...field}
-  onBlur={(e) => {
-    if (e.target.value === "") {
-      return;
-    }
-  }}
 />
apps/dashboard/lib/trpc/routers/key/create.ts (1)

13-19: LGTM! Consider additional edge case validation.

The validation changes effectively prevent spaces in prefixes and provide clear error messages. However, consider adding validation to prevent empty strings or strings containing only spaces.

Here's a suggested enhancement:

      prefix: z
        .string()
        .max(8, { message: "Prefixes cannot be longer than 8 characters" })
+       .transform((val) => val.trim())
+       .refine((val) => val.length > 0, {
+         message: "Prefix cannot be empty or contain only spaces",
+       })
        .refine((prefix) => !prefix.includes(" "), {
          message: "Prefixes cannot contain spaces.",
        })
        .optional(),
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a85027f and 4cbe284.

📒 Files selected for processing (5)
  • apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/new/validation.ts (1 hunks)
  • apps/dashboard/app/(app)/apis/[apiId]/settings/default-bytes.tsx (3 hunks)
  • apps/dashboard/app/(app)/apis/[apiId]/settings/default-prefix.tsx (4 hunks)
  • apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts (1 hunks)
  • apps/dashboard/lib/trpc/routers/key/create.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts (1)
Learnt from: chronark
PR: unkeyed/unkey#2146
File: apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts:80-80
Timestamp: 2024-11-10T16:45:16.994Z
Learning: Ensure that audit log descriptions accurately reflect the action being performed, such as updating the `defaultPrefix`, and avoid incorrect references like 'name' when not applicable.
🪛 Biome (1.9.4)
apps/dashboard/app/(app)/apis/[apiId]/settings/default-bytes.tsx

[error] 85-85: A form label must be associated with an input.

Consider adding a for or htmlFor attribute to the label element or moving the input element to inside the label element.

(lint/a11y/noLabelWithoutControl)

apps/dashboard/app/(app)/apis/[apiId]/settings/default-prefix.tsx

[error] 83-83: A form label must be associated with an input.

Consider adding a for or htmlFor attribute to the label element or moving the input element to inside the label element.

(lint/a11y/noLabelWithoutControl)

⏰ Context from checks skipped due to timeout of 90000ms (13)
  • GitHub Check: Test Packages / Test ./packages/rbac
  • GitHub Check: Test Packages / Test ./packages/nextjs
  • GitHub Check: Test Packages / Test ./packages/hono
  • GitHub Check: Test Packages / Test ./packages/cache
  • GitHub Check: Test Packages / Test ./packages/api
  • GitHub Check: Test Packages / Test ./internal/clickhouse
  • GitHub Check: Test Packages / Test ./internal/keys
  • GitHub Check: Test Packages / Test ./internal/hash
  • GitHub Check: Test Packages / Test ./internal/encryption
  • GitHub Check: Test API / API Test Local
  • GitHub Check: Test Agent Local / test_agent_local
  • GitHub Check: Build / Build
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (6)
apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts (1)

12-17: LGTM! Validation prevents whitespace in prefixes.

The validation logic effectively prevents spaces in prefixes and provides clear error messages.

apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/new/validation.ts (1)

15-20: LGTM! Consistent prefix validation.

The validation rules and error messages are consistent with the changes in setDefaultPrefix.ts.

apps/dashboard/app/(app)/apis/[apiId]/settings/default-bytes.tsx (1)

71-116: LGTM! Improved form structure.

The form structure has been enhanced with proper form components and validation handling.

🧰 Tools
🪛 Biome (1.9.4)

[error] 85-85: A form label must be associated with an input.

Consider adding a for or htmlFor attribute to the label element or moving the input element to inside the label element.

(lint/a11y/noLabelWithoutControl)

apps/dashboard/app/(app)/apis/[apiId]/settings/default-prefix.tsx (1)

22-27: LGTM! Robust prefix validation.

The validation rules effectively prevent spaces and enforce length limits with clear error messages.

apps/dashboard/lib/trpc/routers/key/create.ts (2)

69-72: LGTM! Integration with newKey function is correct.

The validated prefix is properly passed to the newKey function, maintaining consistency with the updated validation rules.


13-19: Implementation aligns perfectly with PR objectives.

The validation changes successfully prevent whitespace in prefixes and catch the issue before submission, exactly as specified in the PR objectives.

Copy link
Contributor

@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)
apps/dashboard/app/(app)/apis/[apiId]/settings/default-bytes.tsx (1)

78-129: Enhance error handling for empty defaultBytes.

The form structure looks good, but there's a potential edge case in the validation.

Consider adding a clear error message when the user submits without entering a value:

 async function onSubmit(values: z.infer<typeof formSchema>) {
-  if (values.defaultBytes === keyAuth.defaultBytes || !values.defaultBytes) {
+  if (!values.defaultBytes) {
+    return toast.error("Please provide a default byte size");
+  }
+  if (values.defaultBytes === keyAuth.defaultBytes) {
     return toast.error(
       "Please provide a different byte-size than already existing one as default"
     );
   }
   await setDefaultBytes.mutateAsync(values);
 }
apps/dashboard/app/(app)/apis/[apiId]/settings/default-prefix.tsx (2)

107-111: Remove empty onBlur handler.

The onBlur handler is empty and can be removed.

-                        onBlur={(e) => {
-                          if (e.target.value === "") {
-                            return;
-                          }
-                        }}

124-126: Consolidate loading states.

The button has both disabled based on isSubmitting and a separate loading prop.

 <Button
   variant="primary"
-  disabled={!form.formState.isValid || form.formState.isSubmitting}
+  disabled={!form.formState.isValid}
   type="submit"
   loading={form.formState.isSubmitting}
 >
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4cbe284 and 2c2726f.

📒 Files selected for processing (2)
  • apps/dashboard/app/(app)/apis/[apiId]/settings/default-bytes.tsx (3 hunks)
  • apps/dashboard/app/(app)/apis/[apiId]/settings/default-prefix.tsx (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (16)
  • GitHub Check: Test Packages / Test ./packages/nextjs
  • GitHub Check: Test Packages / Test ./packages/hono
  • GitHub Check: Test Packages / Test ./packages/cache
  • GitHub Check: Test Packages / Test ./packages/api
  • GitHub Check: Test Packages / Test ./internal/clickhouse
  • GitHub Check: Test Packages / Test ./internal/resend
  • GitHub Check: Test Packages / Test ./internal/keys
  • GitHub Check: Test Packages / Test ./internal/id
  • GitHub Check: Test Packages / Test ./internal/hash
  • GitHub Check: Test Packages / Test ./internal/encryption
  • GitHub Check: Test Packages / Test ./internal/billing
  • GitHub Check: Test API / API Test Local
  • GitHub Check: Test Agent Local / test_agent_local
  • GitHub Check: autofix
  • GitHub Check: Build / Build
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (2)
apps/dashboard/app/(app)/apis/[apiId]/settings/default-bytes.tsx (1)

44-55: LGTM: Form configuration enhances validation and user experience.

The form configuration improvements with async resolver, immediate validation (mode: "all"), and focus management enhance the user experience.

apps/dashboard/app/(app)/apis/[apiId]/settings/default-prefix.tsx (1)

31-36: LGTM: Robust prefix validation prevents whitespace.

The validation logic effectively prevents spaces in prefixes and enforces the 8-character limit, which aligns with the PR objective.

Copy link
Contributor

@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)
apps/dashboard/app/(app)/apis/[apiId]/settings/default-bytes.tsx (1)

38-49: Simplify the resolver configuration.

The async wrapper around zodResolver is unnecessary as it already returns a Promise.

Apply this diff to simplify the resolver:

   const form = useForm<z.infer<typeof formSchema>>({
-    resolver: async (data, context, options) => {
-      return zodResolver(formSchema)(data, context, options);
-    },
+    resolver: zodResolver(formSchema),
     mode: "all",
     shouldFocusError: true,
     delayError: 100,
apps/dashboard/app/(app)/apis/[apiId]/settings/default-prefix.tsx (1)

96-100: Remove empty onBlur handler.

The onBlur handler is empty and serves no purpose.

Apply this diff to remove the empty handler:

   <Input
     id="defaultPrefix"
     className="max-w-sm"
     {...field}
-    onBlur={(e) => {
-      if (e.target.value === "") {
-        return;
-      }
-    }}
   />
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2c2726f and 8f152c5.

📒 Files selected for processing (5)
  • apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/new/validation.ts (1 hunks)
  • apps/dashboard/app/(app)/apis/[apiId]/settings/default-bytes.tsx (3 hunks)
  • apps/dashboard/app/(app)/apis/[apiId]/settings/default-prefix.tsx (4 hunks)
  • apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts (1 hunks)
  • apps/dashboard/lib/trpc/routers/key/create.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/new/validation.ts
  • apps/dashboard/lib/trpc/routers/key/create.ts
  • apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts
⏰ Context from checks skipped due to timeout of 90000ms (17)
  • GitHub Check: Test Packages / Test ./packages/rbac
  • GitHub Check: Test Packages / Test ./packages/nextjs
  • GitHub Check: Test Packages / Test ./packages/hono
  • GitHub Check: Test Packages / Test ./packages/cache
  • GitHub Check: Test Packages / Test ./packages/api
  • GitHub Check: Test Packages / Test ./internal/clickhouse
  • GitHub Check: Test Packages / Test ./internal/resend
  • GitHub Check: Test Packages / Test ./internal/keys
  • GitHub Check: Test Packages / Test ./internal/id
  • GitHub Check: Test Packages / Test ./internal/hash
  • GitHub Check: Test API / API Test Local
  • GitHub Check: Test Packages / Test ./internal/encryption
  • GitHub Check: Test Agent Local / test_agent_local
  • GitHub Check: Test Packages / Test ./internal/billing
  • GitHub Check: Build / Build
  • GitHub Check: autofix
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (5)
apps/dashboard/app/(app)/apis/[apiId]/settings/default-bytes.tsx (2)

11-11: LGTM!

The form schema validation is well-defined with appropriate constraints and clear error messages.

Also applies to: 20-27


72-119: LGTM!

The form structure is well-organized with:

  • Proper accessibility through label-input association
  • Correct input validation for numeric values
  • Clear error message placement
  • Appropriate loading states
apps/dashboard/app/(app)/apis/[apiId]/settings/default-prefix.tsx (3)

22-27: LGTM!

The schema validation effectively addresses the PR objective by:

  • Enforcing max length of 8 characters
  • Preventing spaces in prefixes
  • Providing clear error messages

39-50: Simplify the resolver configuration.

The async wrapper around zodResolver is unnecessary as it already returns a Promise.

Apply this diff to simplify the resolver:

   const form = useForm<z.infer<typeof formSchema>>({
-    resolver: async (data, context, options) => {
-      return zodResolver(formSchema)(data, context, options);
-    },
+    resolver: zodResolver(formSchema),
     mode: "all",
     shouldFocusError: true,
     delayError: 100,

70-95: LGTM!

The form structure is well-organized with:

  • Proper accessibility through label-input association
  • Clear error message placement
  • Appropriate loading states

Also applies to: 101-121

Copy link
Contributor

@ogzhanolguncu ogzhanolguncu left a comment

Choose a reason for hiding this comment

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

lgtm

@perkinsjr perkinsjr added this pull request to the merge queue Feb 13, 2025
Merged via the queue into main with commit a9e894d Feb 13, 2025
27 of 28 checks passed
@perkinsjr perkinsjr deleted the fix-prefix branch February 13, 2025 15:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Something isn't working
Projects
None yet
Development

Successfully merging this pull request may close these issues.

API Setting : "Default Prefix" Field Should Not Allow Only Whitespace Values
3 participants