Conversation
|
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
WalkthroughThis change introduces a suite of new helper modules and documentation for base64url encoding, cookie management, encryption, and signing in the server package. It adds corresponding tests, updates package exports and dependencies, and enhances documentation to reference and demonstrate these helpers, including integration tips for plugin usage. Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant ServerHelpers (index)
participant Base64Url
participant Cookie
participant Encryption
participant Signing
User->>ServerHelpers: import { encodeBase64url, setCookie, encrypt, sign }
ServerHelpers->>Base64Url: encodeBase64url(data)
ServerHelpers->>Cookie: setCookie(headers, name, value, options)
ServerHelpers->>Encryption: encrypt(value, secret)
ServerHelpers->>Signing: sign(value, secret)
Note over ServerHelpers: All helpers are accessible via a unified entry point.
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Suggested labels
Poem
Note ⚡️ Unit Test Generation is now available in beta!Learn more here, or try it out under "Finishing Touches" below. 📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (4)
✅ Files skipped from review due to trivial changes (1)
🚧 Files skipped from review as they are similar to previous changes (3)
⏰ 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). (3)
✨ Finishing Touches
🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Summary of Changes
Hello @unnoq, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!
This pull request significantly enhances the @orpc/server library by introducing a dedicated helpers module. This module centralizes common utility functions for web development, including robust solutions for URL-safe base64 operations, streamlined HTTP cookie management, and essential cryptographic primitives for data signing and encryption. The changes aim to provide developers with a more complete and secure toolkit for building server-side applications, backed by thorough documentation and unit tests.
Highlights
- New Helper Module: Introduced a new
helpersmodule within the@orpc/serverpackage, providing a collection of reusable utility functions. - Base64Url Utilities: Added
encodeBase64urlanddecodeBase64urlfunctions for URL-safe base64 encoding and decoding, crucial for handling web tokens and data serialization. - HTTP Cookie Management: Implemented
setCookieandgetCookiehelpers to simplify setting and retrieving HTTP cookies, including options for security attributes. - Cryptographic Helpers: Provided
signandunsignfunctions for data integrity using HMAC-SHA256, andencryptanddecryptfunctions for sensitive data confidentiality using AES-GCM with PBKDF2. - Documentation and Examples: Comprehensive documentation pages have been added for all new helpers, complete with usage examples and security considerations. Existing plugin documentation has been updated to reference the new cookie helpers.
- Dependency and Export Updates: The
package.jsonfor@orpc/serverhas been updated to expose the newhelpersentry point and include thecookiepackage as a dependency.
Using Gemini Code Assist
The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.
Invoking Gemini
You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.
| Feature | Command | Description |
|---|---|---|
| Code Review | /gemini review |
Performs a code review for the current pull request in its current state. |
| Pull Request Summary | /gemini summary |
Provides a summary of the current pull request in its current state. |
| Comment | @gemini-code-assist | Responds in comments when explicitly tagged, both in issue comments and review comments. |
| Help | /gemini help |
Displays a list of available commands. |
Customization
To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.
Limitations & Feedback
Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments or fill out our survey to provide feedback.
You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.
Footnotes
-
Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩
More templates
@orpc/arktype
@orpc/client
@orpc/contract
@orpc/experimental-durable-event-iterator
@orpc/hey-api
@orpc/json-schema
@orpc/nest
@orpc/openapi
@orpc/openapi-client
@orpc/react
@orpc/react-query
@orpc/server
@orpc/shared
@orpc/solid-query
@orpc/standard-server
@orpc/standard-server-aws-lambda
@orpc/standard-server-fetch
@orpc/standard-server-node
@orpc/standard-server-peer
@orpc/svelte-query
@orpc/tanstack-query
@orpc/trpc
@orpc/valibot
@orpc/vue-colada
@orpc/vue-query
@orpc/zod
commit: |
There was a problem hiding this comment.
Code Review
This pull request introduces a new helpers module to the @orpc/server package, providing utilities for base64url encoding, cookie management, encryption, and signing. The implementations are well-tested and follow modern security practices using the Web Crypto API.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (7)
packages/server/src/helpers/index.ts (1)
1-4: Consider explicit re-exports for better tree-shaking
export *is convenient but may bloat consumer bundles because all symbols are re-exported even when unused.
A light optimisation is to perform named re-exports – still one-liner and keeps IDE autocomplete intact:-export * from './base64url' -export * from './cookie' -export * from './encryption' -export * from './signing' +export { encodeBase64Url, decodeBase64Url } from './base64url' +export { setCookie, getCookie } from './cookie' +export { encrypt, decrypt } from './encryption' +export { sign, unsign } from './signing'Not critical, just worth considering.
apps/content/docs/plugins/request-headers.md (1)
20-30: Minor: handle possibly undefined return
getCookiecan returnundefinedwhen the cookie is missing, yet the example stores it straight intosessionIdwithout showing a guard. For clarity:- const sessionId = getCookie(context.reqHeaders, 'session_id') + const sessionId = getCookie(context.reqHeaders, 'session_id') + if (!sessionId) { + // handle unauthenticated request… + }Purely illustrative, but avoids implying the value is always present.
apps/content/docs/plugins/response-headers.md (1)
15-32: Docs example looks good – small formatting tweakTrailing comma after the options object is fine in TS, but some users copy-paste into JS where it may not be desired. Consider removing the trailing comma for wider compatibility.
apps/content/docs/helpers/cookie.md (1)
31-45: Clarify async example
sign/unsignare async, so wrapping the example in an async IIFE (or noting that it runs inside an async function) would prevent newcomers from wondering where theawaitis permitted.;(async () => { const secret = 'your-secret-key' const headers = new Headers() setCookie(headers, 'sessionId', await sign('abc123', secret), { httpOnly: true, secure: true, maxAge: 3600, }) const signedSessionId = await unsign(getCookie(headers, 'sessionId'), secret) })()packages/server/src/helpers/cookie.ts (1)
62-78: Consider input validation for cookie names.The
getCookiefunction handles edge cases well (undefined headers, missing cookie header). However, consider adding validation for cookie names to prevent potential issues with malformed or suspicious cookie names.export function getCookie( headers: Headers | undefined, name: string, options: GetCookieOptions = {}, ): string | undefined { + // Validate cookie name to prevent potential issues + if (!name || typeof name !== 'string') { + return undefined + } + if (headers === undefined) { return undefined }packages/server/src/helpers/signing.test.ts (2)
162-175: Consider adding more specific error scenario tests.While the malformed input tests are good, consider adding tests for specific crypto-related edge cases that might occur in production environments.
it('should return undefined for malformed input that throws errors', async () => { // Test various malformed inputs that might cause crypto operations to throw const malformedInputs = [ 'value.', '.signature', 'value.invalid-signature-length', 'value.!@#$%^&*()', + // Add more specific crypto edge cases + 'value.' + 'a'.repeat(1000), // Very long signature + 'value.YWJj', // Valid base64 but wrong length for signature + 'value.====', // Invalid base64url padding ]
217-232: Consider performance implications of repetitive operations.While the consistency test is valuable, running 10 identical operations might be overkill for a unit test. Consider reducing to 3-5 iterations unless there's a specific reason to test for non-deterministic behavior.
- for (let i = 0; i < 10; i++) { + for (let i = 0; i < 5; i++) {
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (17)
apps/content/.vitepress/config.ts(1 hunks)apps/content/docs/helpers/base64url.md(1 hunks)apps/content/docs/helpers/cookie.md(1 hunks)apps/content/docs/helpers/encryption.md(1 hunks)apps/content/docs/helpers/signing.md(1 hunks)apps/content/docs/plugins/request-headers.md(3 hunks)apps/content/docs/plugins/response-headers.md(3 hunks)packages/server/package.json(3 hunks)packages/server/src/helpers/base64url.test.ts(1 hunks)packages/server/src/helpers/base64url.ts(1 hunks)packages/server/src/helpers/cookie.test.ts(1 hunks)packages/server/src/helpers/cookie.ts(1 hunks)packages/server/src/helpers/encryption.test.ts(1 hunks)packages/server/src/helpers/encryption.ts(1 hunks)packages/server/src/helpers/index.ts(1 hunks)packages/server/src/helpers/signing.test.ts(1 hunks)packages/server/src/helpers/signing.ts(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
apps/content/docs/plugins/response-headers.md (1)
packages/server/src/plugins/response-headers.ts (3)
ResponseHeadersPlugin(14-56)ResponseHeadersPluginContext(4-6)init(15-55)
⏰ 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). (3)
- GitHub Check: publish-commit
- GitHub Check: lint
- GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (24)
apps/content/.vitepress/config.ts (1)
145-154: Sidebar entry LGTM – verify paths existThe new “Helpers” group is correctly inserted after “Plugins” and before “Client”.
Double-check that each markdown file (/docs/helpers/{base64url,cookie,encryption,signing}) is committed and the route slugs match exactly (case-sensitive on some hosts) to avoid dead sidebar links.apps/content/docs/helpers/encryption.md (1)
1-30: Documentation looks comprehensive and well-structured.The encryption helper documentation effectively explains the functionality, performance trade-offs, and provides clear usage examples. The cross-reference to signing helpers and the note about graceful null/undefined handling are valuable for users.
apps/content/docs/helpers/signing.md (1)
1-30: Excellent documentation with clear security trade-offs.The signing helper documentation effectively communicates the performance benefits and security considerations. The example clearly shows how the original data remains visible in the signed output, which is crucial for users to understand.
packages/server/src/helpers/encryption.test.ts (1)
1-72: Comprehensive test coverage with excellent edge case handling.The test suite thoroughly covers all critical aspects of the encryption functionality including correctness, security properties, output format validation, and graceful error handling. The base64url encoding verification and Unicode support testing are particularly valuable.
packages/server/src/helpers/cookie.test.ts (1)
1-115: Thorough test coverage for cookie helper functions.The test suite comprehensively covers both
setCookieandgetCookiefunctionality with proper edge case handling, including undefined inputs, special characters, multiple cookies, and all serialization/parsing options. The use of Web APIHeadersobject testing ensures compatibility.apps/content/docs/helpers/base64url.md (1)
1-23: Clear and practical documentation for base64url helpers.The documentation effectively explains the URL-safe base64 encoding concept and provides a practical example showing proper byte array handling with
TextEncoder/TextDecoder. The use case explanation helps users understand when to use these helpers.packages/server/src/helpers/base64url.test.ts (1)
1-56: Comprehensive test coverage with good edge case handling.The test suite effectively covers the critical scenarios for base64url encoding/decoding:
- Round-trip encoding/decoding verification
- URL-safe output validation (no +/= characters)
- Empty data handling
- Large data processing without stack overflow
- Graceful handling of invalid inputs
The tests are well-structured and provide good confidence in the implementation.
packages/server/package.json (3)
23-27: Properly configured helper exports.The new "./helpers" export path is correctly configured with appropriate TypeScript definitions and build outputs.
92-92: Development export path correctly configured.The helpers export for development properly points to the source TypeScript file.
135-136: Appropriate dependencies added for cookie helpers.The cookie package and its TypeScript definitions are correctly added to support the cookie helper functionality.
packages/server/src/helpers/base64url.ts (2)
13-27: Well-implemented base64url encoding with proper chunking strategy.The implementation correctly handles large data by chunking to avoid call stack limits and properly converts standard base64 to base64url format. The approach is sound and secure.
41-65: Robust decoding with proper error handling.The decoding function handles edge cases well:
- Type checking for non-string inputs
- Proper padding restoration for base64url
- Graceful error handling with try-catch
- Returns undefined for invalid inputs
packages/server/src/helpers/signing.ts (2)
19-37: Secure HMAC-SHA256 signing implementation.The signing function correctly uses the Web Crypto API with HMAC-SHA256, which provides strong cryptographic security. The signature format (value.signature) is clear and the base64url encoding ensures URL safety.
54-90: Robust signature verification with proper security checks.The unsign function properly:
- Validates input types and format
- Splits the signed value correctly using lastIndexOf (handles dots in original value)
- Uses constant-time verification via Web Crypto API
- Returns undefined for any validation failures
packages/server/src/helpers/encryption.ts (2)
14-54: Secure AES-GCM encryption with proper key derivation.The encryption implementation follows cryptographic best practices:
- AES-GCM provides authenticated encryption (confidentiality + integrity)
- PBKDF2 with 100,000 iterations provides strong key derivation
- Random salt (16 bytes) and IV (12 bytes) for each encryption
- Proper data layout combining salt, IV, and ciphertext
67-115: Robust decryption with comprehensive error handling.The decryption function properly:
- Validates input and returns undefined for invalid data
- Correctly extracts salt, IV, and encrypted data
- Uses the same key derivation parameters as encryption
- Handles all decryption failures gracefully by returning undefined
packages/server/src/helpers/cookie.ts (3)
4-11: Well-designed interface with sensible defaults.The
SetCookieOptionsinterface properly extends the underlying cookie package's options while providing a sensible default path of "/". The JSDoc documentation clearly explains the path attribute and its default behavior.
28-44: Robust implementation with proper error handling.The
setCookiefunction correctly handles the undefined headers case and uses the cookie package's serialize function with appropriate defaults. The use ofheaders.append()is correct for Set-Cookie headers since multiple cookies can be set.
71-71: No changes needed: Headers API matches names case-insensitively
Verified in the Cloudflare Worker typedefs thatHeaders.get()matches header names by a case-insensitive byte sequence, so usingheaders.get('cookie')is safe as-is.packages/server/src/helpers/signing.test.ts (5)
7-18: Excellent foundational test structure.The basic signing test properly validates the expected output format (value.signature) and verifies the signature component exists. Good use of string operations to validate the structure.
20-39: Comprehensive deterministic behavior validation.These tests properly verify that signatures are deterministic (same inputs produce same outputs) and that different inputs produce different outputs. This is crucial for cryptographic functions.
41-70: Thorough edge case coverage for various input types.Excellent coverage of edge cases including empty strings, values with dots, special characters, and unicode. These tests ensure the signing function handles real-world data correctly.
81-128: Robust security and error handling validation.The unsign tests comprehensively cover security scenarios including tampering detection, invalid signatures, and malformed inputs. The coverage of base64url decoding errors is particularly important for security.
178-233: Excellent integration testing with comprehensive scenarios.The integration tests are particularly well-designed, testing consistency across multiple operations and proper secret isolation. The loop-based testing approach efficiently validates behavior across different scenarios.
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
There was a problem hiding this comment.
Pull Request Overview
This PR introduces a comprehensive suite of helper utilities for server-side operations, including base64url encoding/decoding, cookie management, encryption, and data signing/verification. The helpers provide cryptographic security functions and web application utilities to streamline common server tasks.
- Adds four helper modules: base64url, cookie, encryption, and signing with full TypeScript support
- Implements secure cryptographic operations using Web Crypto API with HMAC-SHA256 and AES-GCM
- Provides comprehensive test coverage and documentation for all helper functions
Reviewed Changes
Copilot reviewed 17 out of 18 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| packages/server/src/helpers/signing.ts | Implements HMAC-SHA256 signing and verification functions |
| packages/server/src/helpers/signing.test.ts | Comprehensive test suite for signing functionality |
| packages/server/src/helpers/encryption.ts | AES-GCM encryption/decryption with PBKDF2 key derivation |
| packages/server/src/helpers/encryption.test.ts | Test coverage for encryption operations |
| packages/server/src/helpers/cookie.ts | HTTP cookie management utilities |
| packages/server/src/helpers/cookie.test.ts | Cookie helper test suite |
| packages/server/src/helpers/base64url.ts | URL-safe base64 encoding/decoding functions |
| packages/server/src/helpers/base64url.test.ts | Base64url functionality tests |
| packages/server/src/helpers/index.ts | Main export file for all helpers |
| packages/server/package.json | Package configuration with new exports and cookie dependency |
| apps/content/docs/helpers/*.md | Documentation pages for each helper module |
| apps/content/.vitepress/config.ts | Navigation configuration for helpers documentation |
| apps/content/docs/plugins/*.md | Updated plugin documentation with helper integration examples |
Files not reviewed (1)
- pnpm-lock.yaml: Language not supported
b6463f1 to
0d98757
Compare
Summary by CodeRabbit
New Features
Documentation
Tests