Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

Copy link
Contributor

Copilot AI commented Sep 10, 2025

Adds a simple X-Integrity HTTP response header containing the SHA-512 integrity hash when serving unpkg files. This allows clients to verify file integrity without changing the existing integrity calculation or file metadata format.

Changes Made

  • HTTP Header: Added X-Integrity header to raw file responses containing the existing SHA-512 integrity value
  • No Algorithm Changes: Maintains existing SHA-512-only integrity calculation
  • No Metadata Changes: File metadata responses (?meta) remain unchanged
  • Unit Tests: Added test to verify the X-Integrity header is correctly set

Implementation Details

The implementation adds a single line to set the X-Integrity header in PackageVersionFileController when serving raw files:

if (file.dist.integrity) {
  ctx.set('X-Integrity', file.dist.integrity);
}

This provides a simple way for clients to access the integrity hash via HTTP headers without any changes to the existing integrity system or adding additional hash algorithms.

Testing

  • ✅ Unit test added for X-Integrity header
  • ✅ TypeScript compilation passes
  • ✅ All lint checks pass
  • ✅ Backwards compatible with existing integrity system

The changes are minimal and focused, adding only an HTTP header without altering any existing functionality or data structures.

Fixes #634.


💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.

@graphite-app
Copy link

graphite-app bot commented Sep 10, 2025

How to use the Graphite Merge Queue

Add either label to this PR to merge it via the merge queue:

  • MQ - adds this PR to the back of the merge queue
  • Hotfix - for urgent hot fixes, skip the queue and merge this PR next

You must have a Graphite account in order to use the merge queue. Sign up using this link.

An organization admin has enabled the Graphite Merge Queue in this repository.

Please do not merge from GitHub as this will restart CI on PRs being processed by the merge queue.

@trag-bot
Copy link

trag-bot bot commented Sep 10, 2025

Pull request summary

  • Enhanced Subresource Integrity (SRI) Support: Introduced support for multiple cryptographic hash algorithms (SHA-256, SHA-384, SHA-512) to comply with W3C SRI specifications.
  • Updated Integrity Calculation: Modified the calculateIntegrity function to generate and return SRI hashes alongside the existing SHA-512 and SHA-1 hashes.
  • Backward Compatibility: Ensured that the existing SHA-512 integrity field remains unchanged for current users while providing additional SRI data.
  • File Metadata Enhancement: Updated the file metadata structure to include SRI data when requesting file information with the ?meta query parameter.
  • HTTP Header Integration: Added SRI-related headers in HTTP responses to facilitate better integration with browsers and tools.
  • New Utility Functions: Implemented a utility function to parse SRI data from the combined integrity string for easier access to individual hash values.
  • Test Coverage: Added comprehensive unit tests to validate the new SRI functionality, ensuring both backward compatibility and the correctness of new features.
  • Documentation Update: Created a detailed documentation file explaining the new SRI support, including usage examples and configuration requirements.
  • Code Refactoring: Improved code organization and readability by separating concerns and enhancing function definitions related to SRI handling.
  • Integration Tests: Developed integration tests to verify the correct behavior of SRI parsing and formatting functions in various scenarios.

Copilot AI changed the title [WIP] unpkg files 功能支持 SRI feat: Enhanced SRI support for unpkg files functionality Sep 10, 2025
Copilot AI requested a review from fengmk2 September 10, 2025 12:58
Copilot finished work on behalf of fengmk2 September 10, 2025 12:58
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 6, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Adds multi-algorithm SRI (sha256/sha384/sha512) to integrity calculation, surfaces parsed SRI in controller responses and HTTP headers, stores combined SRI string in service, documents SRI support, and introduces comprehensive tests for calculation, controller behavior, and integration parsing/formatting.

Changes

Cohort / File(s) Summary
Integrity calculation utility
app/common/PackageUtil.ts
Extends Integrity interface with sri (sha256/sha384/sha512/combined). Updates calculateIntegrity to compute multiple algorithms, derive per-algorithm SRI, and return combined SRI string alongside legacy integrity and shasum.
Service persistence update
app/core/service/PackageVersionFileService.ts
Changes stored dist.integrity from single integrity to sri.combined; adds explanatory comment.
Controller SRI exposure
app/port/controller/PackageVersionFileController.ts
Adds optional sri to FileItem, introduces parseSRIFromIntegrity. formatFileItem includes sri when available. Raw file responses add SRI headers (X-SRI-SHA256, X-SRI-SHA384, X-SRI-SHA512, X-SRI-Integrity). Minor type refinement.
Documentation
docs/SRI_SUPPORT.md
New doc detailing SRI support: algorithms, metadata shape, response headers, HTML examples, API usage, compatibility.
Unit tests: integrity calc
test/common/PackageUtil/calculateIntegrity.test.ts
New tests validating multi-algorithm SRI outputs, combined string, determinism, file vs. buffer parity, empty input handling.
Controller tests: SRI headers/metadata
test/port/controller/PackageVersionFileController/raw.test.ts
Tests for SRI headers on raw responses, sri object in metadata, legacy cases, backward compatibility, repeatability and consistency across requests.
Integration-style SRI tests
test/sri-integration.mjs
Adds standalone tests for parsing SRI strings, formatting file items with sri, and verifying expected SRI field formats and combined string.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Caller
  participant PU as PackageUtil.calculateIntegrity
  participant FS as File/Data Source

  rect #eef6ff
  note over C,PU: Multi-algorithm integrity calculation
  C->>PU: calculateIntegrity(contentOrFile)
  alt input is file path
    PU->>FS: Read file bytes
  else input is Uint8Array
    PU->>PU: Use provided bytes
  end
  PU->>PU: Hash bytes (sha256, sha384, sha512, sha1)
  PU->>PU: Build sri.{sha256, sha384, sha512, combined}
  PU-->>C: { integrity, shasum, sri }
  end
Loading
sequenceDiagram
  autonumber
  participant Client
  participant Ctl as PackageVersionFileController
  participant Svc as PackageVersionFileService
  participant Store as Storage

  rect #f3fff0
  note over Client,Ctl: Raw file fetch with SRI headers
  Client->>Ctl: GET /raw/:pkg/:ver/:path
  Ctl->>Svc: fetch file metadata and content
  Svc->>Store: Read file
  Store-->>Svc: Content + dist.integrity
  Svc-->>Ctl: File + integrity (combined SRI stored)
  Ctl->>Ctl: parseSRIFromIntegrity(integrity)
  alt SRI present
    Ctl-->>Client: 200 OK + Content<br/>Headers: X-SRI-SHA256/384/512, X-SRI-Integrity
  else
    Ctl-->>Client: 200 OK + Content (no SRI headers)
  end
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested labels

enhancement

Poem

In bytes I burrow, whiskers keen,
I hash the paths both heard and seen.
Three seeds of trust—256, 384, 512—align,
A braided string, integrity divine.
Headers hop out, neat and spry,
Carrots for clients; SRI on the fly. 🥕🐇

Pre-merge checks

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 63.64% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Title Check ⚠️ Warning The title “feat: Add X-Integrity HTTP header for unpkg files” is misleading because the changes introduce comprehensive Subresource Integrity support, multiple HTTP headers (X-SRI-SHA256, X-SRI-SHA384, X-SRI-SHA512, X-SRI-Integrity), and enhanced integrity calculation rather than just a single “X-Integrity” header. It only partially describes the main functionality and misnames the primary header, so it does not accurately summarize the pull request. Please update the title to reflect the full scope of SRI enhancements and correct header names, for example “feat: Add SRI HTTP headers (X-SRI-Integrity and per-algorithm) for unpkg files,” so that it clearly conveys the main change.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

Note

Free review on us!

CodeRabbit is offering free reviews until Wed Oct 08 2025 to showcase some of the refinements we've made.

Comment @coderabbitai help to get the list of available commands and usage tips.

Copilot AI requested a review from fengmk2 October 6, 2025 07:17
Copilot finished work on behalf of fengmk2 October 6, 2025 07:17
Copilot finished work on behalf of fengmk2 October 6, 2025 07:20
@fengmk2 fengmk2 marked this pull request as ready for review October 6, 2025 07:26
@fengmk2 fengmk2 linked an issue Oct 6, 2025 that may be closed by this pull request
@fengmk2
Copy link
Member

fengmk2 commented Oct 6, 2025

@copilot fix lint errors

@fengmk2
Copy link
Member

fengmk2 commented Oct 6, 2025

@coderabbitai review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 6, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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

🧹 Nitpick comments (3)
test/sri-integration.mjs (2)

4-201: Consider importing and testing the actual controller implementation.

The current approach simulates the controller logic by duplicating the implementation within the test file. This creates maintenance burden and risks divergence between test and production code.

Consider refactoring to:

  1. Import parseSRIFromIntegrity and formatFileItem from the actual controller file
  2. Test the real implementations rather than simulated copies
  3. Integrate with the existing test framework (appears to be using a custom runner)

This would ensure tests remain synchronized with the actual implementation and catch regressions more reliably.


40-40: Use consistent assertion style.

The test mixes assert(condition) and assert.equal() calls, triggering the consistent-assert linting rule. Choose one style for consistency.

Since you're already importing from node:assert/strict, prefer using the more specific assertion methods (assert.equal, assert.notEqual, etc.) throughout for clearer failure messages:

-    assert(parsed !== null);
+    assert.notEqual(parsed, null);

Also applies to: 50-50, 125-125, 143-143, 161-161, 177-178

app/port/controller/PackageVersionFileController.ts (1)

75-101: LGTM: Robust SRI parsing implementation.

The parseSRIFromIntegrity function correctly parses space-separated algorithm hashes and returns structured SRI data or null. The logic handles all three algorithms (sha256, sha384, sha512) appropriately.

Optional refinement: Consider omitting empty algorithm fields rather than setting them to empty strings (lines 93-95). This would make the API more intuitive:

     return {
-      sha256: sri.sha256 || '',
-      sha384: sri.sha384 || '',
-      sha512: sri.sha512 || '',
+      ...(sri.sha256 && { sha256: sri.sha256 }),
+      ...(sri.sha384 && { sha384: sri.sha384 }),
+      ...(sri.sha512 && { sha512: sri.sha512 }),
       combined: Object.values(sri).filter(Boolean).join(' '),
     };

However, the current approach with empty strings is also valid if consumers expect consistent field presence.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5b1da74 and 53db58a.

📒 Files selected for processing (7)
  • app/common/PackageUtil.ts (2 hunks)
  • app/core/service/PackageVersionFileService.ts (1 hunks)
  • app/port/controller/PackageVersionFileController.ts (3 hunks)
  • docs/SRI_SUPPORT.md (1 hunks)
  • test/common/PackageUtil/calculateIntegrity.test.ts (1 hunks)
  • test/port/controller/PackageVersionFileController/raw.test.ts (1 hunks)
  • test/sri-integration.mjs (1 hunks)
🧰 Additional context used
🪛 GitHub Actions: Node.js CI
test/common/PackageUtil/calculateIntegrity.test.ts

[warning] 66-66: eslint(no-console): Unexpected console statement. Delete this console statement.


[warning] 89-89: eslint(no-console): Unexpected console statement. Delete this console statement.


[warning] 97-97: eslint-plugin-unicorn(consistent-assert): Inconsistent assert usage. Prefer using a single style for assertions.


[warning] 100-100: eslint-plugin-unicorn(consistent-assert): Inconsistent assert usage. Prefer using a single style for assertions.


[warning] 101-101: eslint-plugin-unicorn(consistent-assert): Inconsistent assert usage. Prefer using a single style for assertions.


[warning] 102-102: eslint-plugin-unicorn(consistent-assert): Inconsistent assert usage. Prefer using a single style for assertions.


[warning] 65-66: eslint(no-empty-function): Unexpected empty function. Consider removing this function or adding logic.


[warning] 89-90: eslint(no-empty-function): Unexpected empty function. Consider removing this function or adding logic.


[warning] 15-15: eslint(consistent-assert): Inconsistent assert usage. Prefer assert.ok(...) over assert(...)


[warning] 16-16: eslint(consistent-assert): Inconsistent assert usage. Prefer assert.ok(...) over assert(...)


[warning] 17-17: eslint(consistent-assert): Inconsistent assert usage. Prefer assert.ok(...) over assert(...)


[warning] 20-20: eslint(consistent-assert): Inconsistent assert usage. Prefer assert.ok(...) over assert(...)


[warning] 21-21: eslint(consistent-assert): Inconsistent assert usage. Prefer assert.ok(...) over assert(...)


[warning] 22-22: eslint(consistent-assert): Inconsistent assert usage. Prefer assert.ok(...) over assert(...)


[warning] 23-23: eslint(consistent-assert): Inconsistent assert usage. Prefer assert.ok(...) over assert(...)


[warning] 24-24: eslint(consistent-assert): Inconsistent assert usage. Prefer assert.ok(...) over assert(...)


[warning] 27-28: eslint(consistent-assert): Inconsistent assert usage. Prefer assert.ok(...) over assert(...)


[warning] 32-34: eslint(consistent-assert): Inconsistent assert usage. Prefer assert.ok(...) over assert(...)

test/port/controller/PackageVersionFileController/raw.test.ts

[warning] 817-817: eslint(consistent-assert): Inconsistent assert usage. Prefer using a single style for assertions.


[warning] 818-818: eslint(consistent-assert): Inconsistent assert usage. Prefer using a single style for assertions.


[warning] 819-819: eslint(consistent-assert): Inconsistent assert usage. Prefer using a single style for assertions.


[warning] 860-860: eslint(consistent-assert): Inconsistent assert usage. Prefer using a single style for assertions.


[warning] 862-862: eslint(consistent-assert): Inconsistent assert usage. Prefer using a single style for assertions.


[warning] 863-863: eslint(consistent-assert): Inconsistent assert usage. Prefer using a single style for assertions.


[warning] 823-825: eslint(consistent-assert): Inconsistent assert usage. Prefer using a single style for assertions.


[warning] 823-825: eslint(consistent-assert): Inconsistent assert usage. Prefer using a single style for assertions.

test/sri-integration.mjs

[warning] 5-5: eslint(no-console): Unexpected console statement. Delete this console statement.


[warning] 63-63: eslint(no-console): Unexpected console statement. Delete this console statement.


[warning] 163-163: eslint(no-console): Unexpected console statement. Delete this console statement.


[warning] 188-188: eslint(no-console): Unexpected console statement. Delete this console statement.


[error] 199-199: eslint(no-process-exit): Don't use process.exit(). Throw an error instead.


[warning] 40-40: eslint-plugin-unicorn(consistent-assert): Inconsistent assert usage. Prefer using a single style for assertions.


[warning] 50-50: eslint-plugin-unicorn(consistent-assert): Inconsistent assert usage. Prefer using a single style for assertions.


[warning] 125-125: eslint-plugin-unicorn(consistent-assert): Inconsistent assert usage. Prefer using a single style for assertions.


[warning] 143-143: eslint-plugin-unicorn(consistent-assert): Inconsistent assert usage. Prefer using a single style for assertions.


[warning] 161-161: eslint-plugin-unicorn(consistent-assert): Inconsistent assert usage. Prefer using a single style for assertions.


[warning] 177-177: eslint-plugin-unicorn(consistent-assert): Inconsistent assert usage. Prefer using a single style for assertions.


[warning] 178-178: eslint-plugin-unicorn(consistent-assert): Inconsistent assert usage. Prefer using a single style for assertions.


[error] 199-199: eslint(no-process-exit): Don't use process.exit(). Throw an error instead.

🪛 markdownlint-cli2 (0.18.1)
docs/SRI_SUPPORT.md

41-41: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: copilot
🔇 Additional comments (2)
app/port/controller/PackageVersionFileController.ts (2)

34-73: LGTM: Clean SRI integration in FileItem and formatFileItem.

The changes properly extend FileItem with optional SRI data and refactor formatFileItem to parse and include it. The type refinement ('file' as const at line 53) improves type safety, and the conditional SRI inclusion maintains backwards compatibility.


268-278: LGTM: SRI headers properly added to raw file responses.

The implementation correctly parses SRI data and sets appropriate HTTP headers (X-SRI-SHA256, X-SRI-SHA384, X-SRI-SHA512, X-SRI-Integrity) for browser and tool integration. The conditional header setting ensures backwards compatibility with files lacking SRI data.

Comment on lines 41 to 46
```
X-SRI-SHA256: sha256-3/1gIbsr1bCvZ2KQgJ7DpTGR3YHH9wpLKGiKNiGCmG8=
X-SRI-SHA384: sha384-VIXMmzNltDBd+06DN+ClmKV0+CQr8XKJ4N1sIKPNRKCJ3harSrMI9j5EsRcOtfUV
X-SRI-SHA512: sha512-N015SpXNz9izWZMYX++bo2jxYNja9DLQi6nx7R5avmzGkpHg+i/gAGpSVw7xjBne9OYXwzzlLvCm5fvjGMsDhw==
X-SRI-Integrity: sha256-3/1gIbsr1bCvZ2KQgJ7DpTGR3YHH9wpLKGiKNiGCmG8= sha384-VIXMmzNltDBd+06DN+ClmKV0+CQr8XKJ4N1sIKPNRKCJ3harSrMI9j5EsRcOtfUV sha512-N015SpXNz9izWZMYX++bo2jxYNja9DLQi6nx7R5avmzGkpHg+i/gAGpSVw7xjBne9OYXwzzlLvCm5fvjGMsDhw==
```
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Add a language hint to the fenced block.

markdownlint (MD040) is flagging this code fence because it has no language. Please annotate it (for example, ```text) so the docs lint passes.

🧰 Tools
🪛 markdownlint-cli2 (0.18.1)

41-41: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

🤖 Prompt for AI Agents
In docs/SRI_SUPPORT.md around lines 41 to 46, the fenced code block lacks a
language hint and fails markdownlint MD040; update the opening fence to include
a language tag (for example use ```text) so the block becomes a
language-annotated fenced code block, keeping the same contents and closing
fence unchanged.

Copy link
Contributor Author

Copilot AI commented Oct 6, 2025

@copilot fix lint errors

Fixed all lint errors in commit 10f8742:

Changes made:

  • Replaced assert() with assert.ok() throughout test files (46 fixes)
  • Removed console statements or added eslint-disable comments (6 fixes)
  • Fixed function scoping issues by moving nested functions to outer scope
  • Replaced process.exit() with throw error
  • Added comments to empty catch blocks

All oxlint checks now pass with 0 warnings and 0 errors.

Copilot AI requested a review from fengmk2 October 6, 2025 07:41
Copilot finished work on behalf of fengmk2 October 6, 2025 07:41
@codecov
Copy link

codecov bot commented Oct 6, 2025

Codecov Report

❌ Patch coverage is 46.22642% with 57 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.92%. Comparing base (324511d) to head (980145c).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
...pp/port/controller/PackageVersionFileController.ts 11.29% 55 Missing ⚠️
app/core/service/PackageVersionFileService.ts 0.00% 2 Missing ⚠️

❗ There is a different number of reports uploaded between BASE (324511d) and HEAD (980145c). Click for more details.

HEAD has 6 uploads less than BASE
Flag BASE (324511d) HEAD (980145c)
18 12
Additional details and impacted files
@@             Coverage Diff             @@
##           master     #833       +/-   ##
===========================================
- Coverage   95.16%   82.92%   -12.25%     
===========================================
  Files         197      197               
  Lines       23906    24006      +100     
  Branches     1953     1440      -513     
===========================================
- Hits        22751    19907     -2844     
- Misses       1155     4099     +2944     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

"path": "/package.json",
"type": "file",
"contentType": "application/json",
"integrity": "sha512-N015SpXNz9izWZMYX++bo2jxYNja9DLQi6nx7R5avmzGkpHg+i/gAGpSVw7xjBne9OYXwzzlLvCm5fvjGMsDhw==",
Copy link
Member

Choose a reason for hiding this comment

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

@copilot 我们只需要保持之前的 integrity 为 sha512 即可,只是新增一个 http response header,不需要额外新增其他算法。

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Simplified the implementation as requested in commit fd4ec15:

Changes made:

  • Reverted calculateIntegrity() to only generate SHA-512 (removed SHA-256, SHA-384)
  • Removed sri object from file metadata responses
  • Simplified to single X-Integrity header containing SHA-512 hash
  • Removed multi-algorithm tests and documentation
  • Kept only SHA-512 integrity field for backwards compatibility

The implementation now only adds a simple HTTP response header without changing the existing integrity calculation.

Copilot AI changed the title feat: Enhanced SRI support for unpkg files functionality feat: Add X-Integrity HTTP header for unpkg files Oct 7, 2025
Copilot AI requested a review from fengmk2 October 7, 2025 14:34
Copilot finished work on behalf of fengmk2 October 7, 2025 14:34
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.

unpkg files 功能支持 SRI

2 participants