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 Label Generator showing incorrect asset ID #319

Closed
wants to merge 1 commit into from

Conversation

katosdev
Copy link
Contributor

@katosdev katosdev commented Nov 3, 2024

What type of PR is this?

  • Bug fix

What this PR does / why we need it:

Fixes Label Generator showing incorrect asset ID due to ordering mismatch.

Which issue(s) this PR fixes:

Fixes #289

Summary by CodeRabbit

  • New Features

    • Enhanced user interface for the label generator, improving layout and usability.
    • Repositioned button for generating labels for easier access.
  • Bug Fixes

    • Improved error handling for page size validation against card dimensions.
  • Documentation

    • Updated text and formatting for clarity throughout the interface.

Copy link
Contributor

coderabbitai bot commented Nov 3, 2024

Walkthrough

The pull request involves a comprehensive reorganization of the label-generator.vue file, focusing on the script and template sections. Key modifications include enhanced readability of the calculateGridData and calcPages functions, while maintaining existing functionality. Type definitions for various entities have been added, and the layout of the template has been improved for better usability. Minor text and formatting adjustments were made to enhance clarity, but the core logic and data handling remain unchanged.

Changes

File Change Summary
frontend/pages/reports/label-generator.vue Complete reorganization of script and template sections, improved readability of functions, added type definitions, and enhanced layout and styling.

Assessment against linked issues

Objective Addressed Explanation
Ensure correct asset IDs are displayed in labels (#289)

Possibly related PRs

Security Recommendations

  • Ensure that any user input in the label generator is properly validated and sanitized to prevent potential injection attacks.
  • Review access controls to ensure that only authorized users can generate or view labels, particularly if sensitive information is included.

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7228c64 and 429de96.

📒 Files selected for processing (1)
  • frontend/pages/reports/label-generator.vue (2 hunks)

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.

@katosdev katosdev self-assigned this Nov 3, 2024
@katosdev katosdev added 🕷️ bug Something isn't working review needed A review is needed on this PR or Issue labels Nov 3, 2024
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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 5

🛑 Comments failed to post (5)
frontend/pages/reports/label-generator.vue (5)

332-334: ⚠️ Potential issue

Secure template rendering against XSS

The template directly renders user-provided data (name and location) without sanitization, potentially allowing XSS attacks.

Recommended security measures:

  1. Install and use a sanitization library:
npm install xss
  1. Apply sanitization:
 function getItem(n: number, item: { name: string; location: { name: string } } | null): LabelData {
+  const sanitize = require('xss');
   const assetID = fmtAssetID(n);
   return {
     url: getQRCodeUrl(assetID),
     assetID,
-    name: item?.name ?? "_______________",
-    location: item?.location?.name ?? "_______________",
+    name: sanitize(item?.name ?? "_______________"),
+    location: sanitize(item?.location?.name ?? "_______________"),
   };
 }

157-163: 🛠️ Refactor suggestion

Enhance error handling for API failures

The current error handling silently fails by returning an empty array. This could lead to confusion when labels are generated without data.

Suggested improvement:

 const { data: allFields } = await useAsyncData(async () => {
   const { data, error } = await api.items.getAll();
   if (error) {
+    notifier.error(`Failed to fetch items: ${error.message}`);
     return { items: [] };
   }
   return data;
 });

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


166-173: 🛠️ Refactor suggestion

Strengthen input validation for asset range

The current validation allows negative numbers and has a high upper limit that could lead to performance issues.

Recommended improvements:

 const items = computed(() => {
+  // Ensure positive numbers
+  if (displayProperties.assetRange < 0 || displayProperties.assetRangeMax < 0) {
+    notifier.error('Asset range cannot be negative');
+    return [];
+  }
+
   if (displayProperties.assetRange > displayProperties.assetRangeMax) {
+    notifier.error('Start range cannot be greater than end range');
     return [];
   }

   const diff = displayProperties.assetRangeMax - displayProperties.assetRange;
   if (diff > 999) {
+    notifier.error('Range cannot exceed 999 items');
     return [];
   }
📝 Committable suggestion

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

  // Ensure positive numbers
  if (displayProperties.assetRange < 0 || displayProperties.assetRangeMax < 0) {
    notifier.error('Asset range cannot be negative');
    return [];
  }

  if (displayProperties.assetRange > displayProperties.assetRangeMax) {
    notifier.error('Start range cannot be greater than end range');
    return [];
  }

  const diff = displayProperties.assetRangeMax - displayProperties.assetRange;
  if (diff > 999) {
    notifier.error('Range cannot exceed 999 items');
    return [];
  }

138-145: ⚠️ Potential issue

Address potential XSS vulnerability in QR code URL generation

The current implementation has security concerns:

  1. The base URL is directly used without validation
  2. The asset ID is included in the URL without proper sanitization

Recommended security improvements:

 function getQRCodeUrl(assetID: string): string {
+  // Validate base URL format
+  const urlPattern = /^https?:\/\/[^\s/$.?#].[^\s]*$/i;
+  if (!urlPattern.test(displayProperties.baseURL.trim())) {
+    throw new Error('Invalid base URL format');
+  }
+
   let origin = displayProperties.baseURL.trim();
   if (origin.endsWith("/")) {
     origin = origin.slice(0, -1);
   }
+  
+  // Sanitize asset ID
+  if (!/^\d{3}-\d{3}$/.test(assetID)) {
+    throw new Error('Invalid asset ID format');
+  }
+
   const data = `${origin}/a/${assetID}`;
   return route(`/qrcode`, { data: encodeURIComponent(data) });
 }

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


175-179: ⚠️ Potential issue

Fix asset ID ordering issue

The current implementation may contribute to the incorrect asset ID display issue mentioned in PR #289. The items array is being populated based on the index i, but there's no guarantee that the items in allFields.value.items maintain the same order as the asset IDs.

Suggested fix:

- const item = allFields?.value?.items?.[i];
+ const item = allFields?.value?.items?.find(item => item.id === i.toString());
  items.push(getItem(i, item?.location ? item : null));

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

Copy link
Collaborator

@tonyaellie tonyaellie left a comment

Choose a reason for hiding this comment

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

image

Seems like its not working properly and the inputs seem to not follow the same styles.


const api = useUserApi();

const bordered = ref(false);
Copy link
Collaborator

Choose a reason for hiding this comment

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

This doesn't seem to be used any more.

@@ -319,135 +257,91 @@
<h1>Homebox Label Generator</h1>
Copy link
Collaborator

Choose a reason for hiding this comment

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

Translation keys need to be added for all the text on this page but I think thats should be sorted in a seperate PR?

const items: LabelData[] = [];
for (let i = displayProperties.assetRange; i < displayProperties.assetRangeMax; i++) {
const item = allFields?.value?.items?.[i];
items.push(getItem(i, item?.location ? item : null));

Choose a reason for hiding this comment

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

This is where the asset ID mismatch happens. api.items.getAll() which is used to fill allFields appears to return the items in alphabetical order based on name (seems like the entire database, which may be inefficient if you have a large number of items and only want to print a few labels). Loop index "i" is not associated with the actual assetID of allFields?.value?.items?.[i], it's just whatever order the array happened to get filled in. This loop index i is what is used to create the QR code and assetID label in "getItem". Even if the array did happen to get filled in the same order of assetID, this wouldn't handle a case where there was a gap in assetIDs.

Unfortunately it doesn't look like api.items.getAll() returns an assetID. Probably the right fix is changing that so it does, or you can look up the assetID based on the id property which is what I did in my comment on issue #289 but that seems more like a band-aid.

@tankerkiller125
Copy link
Contributor

Closing in favor of #351

@katosdev katosdev deleted the katos/fix-asset-ids branch December 26, 2024 19:16
@katosdev katosdev restored the katos/fix-asset-ids branch December 26, 2024 19:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🕷️ bug Something isn't working review needed A review is needed on this PR or Issue
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Label Generator showing incorrect asset ID
4 participants