fix: improve CORS proxy handling and update documentation for certificate fetching

This commit is contained in:
alam00000
2026-02-20 16:07:21 +05:30
parent 832e28aaca
commit e6c8eaf23c
4 changed files with 732 additions and 516 deletions

View File

@@ -824,7 +824,7 @@ For detailed security configuration, see [SECURITY.md](SECURITY.md).
### Digital Signature CORS Proxy (Required)
The **Digital Signature** tool uses a signing library that may need to fetch certificate chain data from certificate authority provider. Since many certificate servers don't include CORS headers, a proxy is required for this feature to work in the browser.
The **Digital Signature** tool uses a signing library that may need to fetch certificate chain data from certificate authority providers. Since many certificate servers don't include CORS headers (and often serve over HTTP, which is blocked by browsers on HTTPS sites), a proxy is required for this feature to work.
**When is the proxy needed?**
@@ -846,30 +846,48 @@ The **Digital Signature** tool uses a signing library that may need to fetch cer
npx wrangler login
```
3. **Deploy the worker:**
3. **Update allowed origins** — open `cors-proxy-worker.js` and change `ALLOWED_ORIGINS` to your domain:
```js
const ALLOWED_ORIGINS = [
'https://your-domain.com',
'https://www.your-domain.com',
];
```
> [!IMPORTANT]
> Without this step, the proxy will reject all requests from your site with a 403 error. The default only allows `bentopdf.com`.
4. **Deploy the worker:**
```bash
npx wrangler deploy
```
4. **Note your worker URL** (e.g., `https://bentopdf-cors-proxy.your-subdomain.workers.dev`)
5. **Note your worker URL** (e.g., `https://bentopdf-cors-proxy.your-subdomain.workers.dev`)
5. **Set the environment variable when building:**
6. **Set the environment variable when building:**
```bash
VITE_CORS_PROXY_URL=https://your-worker-url.workers.dev npm run build
```
Or with Docker:
```bash
docker build --build-arg VITE_CORS_PROXY_URL="https://your-worker-url.workers.dev" -t your-bentopdf .
```
#### Production Security Features
The CORS proxy includes several security measures:
| Feature | Description |
| ----------------------- | ------------------------------------------------------------------------- |
| **URL Restrictions** | Only allows certificate URLs (`.crt`, `.cer`, `.pem`, `/certs/`, `/ocsp`) |
| **Private IP Blocking** | Blocks requests to localhost, 10.x, 192.168.x, 172.16-31.x |
| **File Size Limit** | Rejects files larger than 10MB |
| ----------------------- | -------------------------------------------------------------------------------------- |
| **Origin Validation** | Only allows requests from domains listed in `ALLOWED_ORIGINS` |
| **URL Restrictions** | Only allows certificate URLs (`.crt`, `.cer`, `.pem`, `/certs/`, `/ocsp`, `/crl`) |
| **Private IP Blocking** | Blocks IPv4/IPv6 private ranges, link-local, loopback, decimal IPs, and cloud metadata |
| **Content-Type Safety** | Only returns safe certificate MIME types, blocks upstream content-type injection |
| **File Size Limit** | Streams response with 10MB limit, aborts mid-download if exceeded |
| **Rate Limiting** | 60 requests per IP per minute (requires KV) |
| **HMAC Signatures** | Optional client-side signing (limited protection) |
| **HMAC Signatures** | Optional client-side signing (deters casual abuse) |
#### Enabling Rate Limiting (Recommended)

View File

@@ -12,7 +12,7 @@
* - PROXY_SECRET: Shared secret for HMAC signature verification
*/
const ALLOWED_PATTERNS = [
const ALLOWED_PATH_PATTERNS = [
/\.crt$/i,
/\.cer$/i,
/\.pem$/i,
@@ -22,18 +22,17 @@ const ALLOWED_PATTERNS = [
/caIssuers/i,
];
const ALLOWED_ORIGINS = [
'https://www.bentopdf.com',
'https://bentopdf.com',
];
const ALLOWED_ORIGINS = ['https://www.bentopdf.com', 'https://bentopdf.com'];
const BLOCKED_DOMAINS = [
'localhost',
'127.0.0.1',
'0.0.0.0',
const SAFE_CONTENT_TYPES = [
'application/x-x509-ca-cert',
'application/pkix-cert',
'application/x-pem-file',
'application/pkcs7-mime',
'application/octet-stream',
'text/plain',
];
const MAX_TIMESTAMP_AGE_MS = 5 * 60 * 1000;
const RATE_LIMIT_MAX_REQUESTS = 60;
@@ -53,7 +52,7 @@ async function verifySignature(message, signature, secret) {
);
const signatureBytes = new Uint8Array(
signature.match(/.{1,2}/g).map(byte => parseInt(byte, 16))
signature.match(/.{1,2}/g).map((byte) => parseInt(byte, 16))
);
return await crypto.subtle.verify(
@@ -68,30 +67,51 @@ async function verifySignature(message, signature, secret) {
}
}
async function generateSignature(message, secret) {
const encoder = new TextEncoder();
const key = await crypto.subtle.importKey(
'raw',
encoder.encode(secret),
{ name: 'HMAC', hash: 'SHA-256' },
false,
['sign']
);
const signature = await crypto.subtle.sign(
'HMAC',
key,
encoder.encode(message)
);
return Array.from(new Uint8Array(signature))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
}
function isAllowedOrigin(origin) {
if (!origin) return false;
return ALLOWED_ORIGINS.some(allowed => origin.startsWith(allowed.replace(/\/$/, '')));
return ALLOWED_ORIGINS.includes(origin);
}
function isPrivateOrReservedHost(hostname) {
if (
/^10\./.test(hostname) ||
/^172\.(1[6-9]|2[0-9]|3[0-1])\./.test(hostname) ||
/^192\.168\./.test(hostname) ||
/^169\.254\./.test(hostname) || // link-local (cloud metadata)
/^100\.(6[4-9]|[7-9]\d|1[0-1]\d|12[0-7])\./.test(hostname) || // CGNAT
/^127\./.test(hostname) ||
/^0\./.test(hostname)
) {
return true;
}
if (/^\d+$/.test(hostname)) {
return true;
}
const lower = hostname.toLowerCase().replace(/^\[|\]$/g, '');
if (
lower === '::1' ||
lower.startsWith('::ffff:') ||
lower.startsWith('fe80') ||
lower.startsWith('fc') ||
lower.startsWith('fd') ||
lower.startsWith('ff')
) {
return true;
}
const blockedNames = [
'localhost',
'localhost.localdomain',
'0.0.0.0',
'[::1]',
];
if (blockedNames.includes(hostname.toLowerCase())) {
return true;
}
return false;
}
function isValidCertificateUrl(urlString) {
@@ -102,26 +122,27 @@ function isValidCertificateUrl(urlString) {
return false;
}
if (BLOCKED_DOMAINS.some(domain => url.hostname.includes(domain))) {
if (isPrivateOrReservedHost(url.hostname)) {
return false;
}
const hostname = url.hostname;
if (/^10\./.test(hostname) ||
/^172\.(1[6-9]|2[0-9]|3[0-1])\./.test(hostname) ||
/^192\.168\./.test(hostname)) {
return false;
}
return ALLOWED_PATTERNS.some(pattern => pattern.test(urlString));
return ALLOWED_PATH_PATTERNS.some((pattern) => pattern.test(url.pathname));
} catch {
return false;
}
}
function getSafeContentType(upstreamContentType) {
if (!upstreamContentType) return 'application/octet-stream';
const match = SAFE_CONTENT_TYPES.find((ct) =>
upstreamContentType.startsWith(ct)
);
return match || 'application/octet-stream';
}
function corsHeaders(origin) {
return {
'Access-Control-Allow-Origin': origin || '*',
'Access-Control-Allow-Origin': origin,
'Access-Control-Allow-Methods': 'GET, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Max-Age': '86400',
@@ -130,6 +151,9 @@ function corsHeaders(origin) {
function handleOptions(request) {
const origin = request.headers.get('Origin');
if (!isAllowedOrigin(origin)) {
return new Response(null, { status: 403 });
}
return new Response(null, {
status: 204,
headers: corsHeaders(origin),
@@ -147,15 +171,18 @@ export default {
// NOTE: If you are selfhosting this proxy, you can remove this check, or can set it to only accept requests from your own domain
if (!isAllowedOrigin(origin)) {
return new Response(JSON.stringify({
return new Response(
JSON.stringify({
error: 'Forbidden',
message: 'This proxy only accepts requests from bentopdf.com',
}), {
message: 'This proxy only accepts requests from allowed origins',
}),
{
status: 403,
headers: {
'Content-Type': 'application/json',
},
});
}
);
}
if (request.method !== 'GET') {
@@ -166,79 +193,104 @@ export default {
}
const targetUrl = url.searchParams.get('url');
const timestamp = url.searchParams.get('t');
const signature = url.searchParams.get('sig');
if (env.PROXY_SECRET) {
if (!timestamp || !signature) {
return new Response(JSON.stringify({
error: 'Missing authentication parameters',
message: 'Request must include timestamp (t) and signature (sig) parameters',
}), {
status: 401,
headers: {
...corsHeaders(origin),
'Content-Type': 'application/json',
},
});
}
const requestTime = parseInt(timestamp, 10);
const now = Date.now();
if (isNaN(requestTime) || Math.abs(now - requestTime) > MAX_TIMESTAMP_AGE_MS) {
return new Response(JSON.stringify({
error: 'Request expired or invalid timestamp',
message: 'Timestamp must be within 5 minutes of current time',
}), {
status: 401,
headers: {
...corsHeaders(origin),
'Content-Type': 'application/json',
},
});
}
const message = `${targetUrl}${timestamp}`;
const isValid = await verifySignature(message, signature, env.PROXY_SECRET);
if (!isValid) {
return new Response(JSON.stringify({
error: 'Invalid signature',
message: 'Request signature verification failed',
}), {
status: 401,
headers: {
...corsHeaders(origin),
'Content-Type': 'application/json',
},
});
}
}
if (!targetUrl) {
return new Response(JSON.stringify({
return new Response(
JSON.stringify({
error: 'Missing url parameter',
usage: 'GET /?url=<certificate_url>',
}), {
}),
{
status: 400,
headers: {
...corsHeaders(origin),
'Content-Type': 'application/json',
},
});
}
);
}
if (!isValidCertificateUrl(targetUrl)) {
return new Response(JSON.stringify({
return new Response(
JSON.stringify({
error: 'Invalid or disallowed URL',
message: 'Only certificate-related URLs are allowed (*.crt, *.cer, *.pem, /certs/, /ocsp, /crl)',
}), {
message:
'Only certificate-related URLs are allowed (*.crt, *.cer, *.pem, /certs/, /ocsp, /crl)',
}),
{
status: 403,
headers: {
...corsHeaders(origin),
'Content-Type': 'application/json',
},
});
}
);
}
if (env.PROXY_SECRET) {
const timestamp = url.searchParams.get('t');
const signature = url.searchParams.get('sig');
if (!timestamp || !signature) {
return new Response(
JSON.stringify({
error: 'Missing authentication parameters',
message:
'Request must include timestamp (t) and signature (sig) parameters',
}),
{
status: 401,
headers: {
...corsHeaders(origin),
'Content-Type': 'application/json',
},
}
);
}
const requestTime = parseInt(timestamp, 10);
const now = Date.now();
if (
isNaN(requestTime) ||
Math.abs(now - requestTime) > MAX_TIMESTAMP_AGE_MS
) {
return new Response(
JSON.stringify({
error: 'Request expired or invalid timestamp',
message: 'Timestamp must be within 5 minutes of current time',
}),
{
status: 401,
headers: {
...corsHeaders(origin),
'Content-Type': 'application/json',
},
}
);
}
const message = `${targetUrl}${timestamp}`;
const isValid = await verifySignature(
message,
signature,
env.PROXY_SECRET
);
if (!isValid) {
return new Response(
JSON.stringify({
error: 'Invalid signature',
message: 'Request signature verification failed',
}),
{
status: 401,
headers: {
...corsHeaders(origin),
'Content-Type': 'application/json',
},
}
);
}
}
const clientIP = request.headers.get('CF-Connecting-IP') || 'unknown';
@@ -246,30 +298,49 @@ export default {
const now = Date.now();
if (env.RATE_LIMIT_KV) {
const rateLimitData = await env.RATE_LIMIT_KV.get(rateLimitKey, { type: 'json' });
const rateLimitData = await env.RATE_LIMIT_KV.get(rateLimitKey, {
type: 'json',
});
const requests = rateLimitData?.requests || [];
const recentRequests = requests.filter(t => now - t < RATE_LIMIT_WINDOW_MS);
const recentRequests = requests.filter(
(t) => now - t < RATE_LIMIT_WINDOW_MS
);
if (recentRequests.length >= RATE_LIMIT_MAX_REQUESTS) {
return new Response(JSON.stringify({
return new Response(
JSON.stringify({
error: 'Rate limit exceeded',
message: `Maximum ${RATE_LIMIT_MAX_REQUESTS} requests per minute. Please try again later.`,
retryAfter: Math.ceil((recentRequests[0] + RATE_LIMIT_WINDOW_MS - now) / 1000),
}), {
retryAfter: Math.ceil(
(recentRequests[0] + RATE_LIMIT_WINDOW_MS - now) / 1000
),
}),
{
status: 429,
headers: {
...corsHeaders(origin),
'Content-Type': 'application/json',
'Retry-After': Math.ceil((recentRequests[0] + RATE_LIMIT_WINDOW_MS - now) / 1000).toString(),
'Retry-After': Math.ceil(
(recentRequests[0] + RATE_LIMIT_WINDOW_MS - now) / 1000
).toString(),
},
});
}
);
}
recentRequests.push(now);
await env.RATE_LIMIT_KV.put(rateLimitKey, JSON.stringify({ requests: recentRequests }), {
await env.RATE_LIMIT_KV.put(
rateLimitKey,
JSON.stringify({ requests: recentRequests }),
{
expirationTtl: 120,
});
}
);
} else {
console.warn(
'[CORS Proxy] RATE_LIMIT_KV not configured — rate limiting is disabled'
);
}
try {
@@ -280,72 +351,105 @@ export default {
});
if (!response.ok) {
return new Response(JSON.stringify({
return new Response(
JSON.stringify({
error: 'Failed to fetch certificate',
status: response.status,
statusText: response.statusText,
}), {
}),
{
status: response.status,
headers: {
...corsHeaders(origin),
'Content-Type': 'application/json',
},
});
}
);
}
const contentLength = parseInt(response.headers.get('Content-Length') || '0', 10);
// Check Content-Length header first (fast reject for known-large responses)
const contentLength = parseInt(
response.headers.get('Content-Length') || '0',
10
);
if (contentLength > MAX_FILE_SIZE_BYTES) {
return new Response(JSON.stringify({
return new Response(
JSON.stringify({
error: 'File too large',
message: `Certificate file exceeds maximum size of ${MAX_FILE_SIZE_BYTES / 1024}KB`,
size: contentLength,
maxSize: MAX_FILE_SIZE_BYTES,
}), {
}),
{
status: 413,
headers: {
...corsHeaders(origin),
'Content-Type': 'application/json',
},
});
}
);
}
const certData = await response.arrayBuffer();
const reader = response.body.getReader();
const chunks = [];
let totalSize = 0;
if (certData.byteLength > MAX_FILE_SIZE_BYTES) {
return new Response(JSON.stringify({
while (true) {
const { done, value } = await reader.read();
if (done) break;
totalSize += value.byteLength;
if (totalSize > MAX_FILE_SIZE_BYTES) {
reader.cancel();
return new Response(
JSON.stringify({
error: 'File too large',
message: `Certificate file exceeds maximum size of ${MAX_FILE_SIZE_BYTES / 1024}KB`,
size: certData.byteLength,
maxSize: MAX_FILE_SIZE_BYTES,
}), {
}),
{
status: 413,
headers: {
...corsHeaders(origin),
'Content-Type': 'application/json',
},
});
}
);
}
chunks.push(value);
}
const certData = new Uint8Array(totalSize);
let offset = 0;
for (const chunk of chunks) {
certData.set(chunk, offset);
offset += chunk.byteLength;
}
return new Response(certData, {
status: 200,
headers: {
...corsHeaders(origin),
'Content-Type': response.headers.get('Content-Type') || 'application/x-x509-ca-cert',
'Content-Length': certData.byteLength.toString(),
'Content-Type': getSafeContentType(
response.headers.get('Content-Type')
),
'Content-Length': totalSize.toString(),
'Cache-Control': 'public, max-age=86400',
'X-Content-Type-Options': 'nosniff',
},
});
} catch (error) {
return new Response(JSON.stringify({
console.error('Proxy fetch error:', error);
return new Response(
JSON.stringify({
error: 'Proxy error',
message: error.message,
}), {
message: 'Failed to fetch the requested certificate',
}),
{
status: 500,
headers: {
...corsHeaders(origin),
'Content-Type': 'application/json',
},
});
}
);
}
},
};

View File

@@ -2,6 +2,8 @@
The digital signature tool uses a CORS proxy to fetch issuer certificates from external Certificate Authorities (CAs). This is necessary because many CA servers don't include CORS headers in their responses, which prevents direct browser-based fetching.
Additionally, many CA servers serve certificates over plain HTTP. When your BentoPDF instance is hosted over HTTPS, browsers block these HTTP requests (mixed content policy). The CORS proxy resolves both issues by routing requests through an HTTPS endpoint with proper headers.
## How It Works
When signing a PDF with a certificate:
@@ -13,35 +15,64 @@ When signing a PDF with a certificate:
## Self-Hosting the CORS Proxy
If you're self-hosting BentoPDF, you'll need to deploy your own CORS proxy.
If you're self-hosting BentoPDF, you'll need to deploy your own CORS proxy for digital signatures to work with certificates that require chain fetching.
### Option 1: Cloudflare Workers (Recommended)
1. **Install Wrangler CLI**:
```bash
npm install -g wrangler
```
2. **Login to Cloudflare**:
```bash
wrangler login
```
3. **Deploy the proxy**:
3. **Clone BentoPDF and update allowed origins**:
```bash
git clone https://github.com/alam00000/bentopdf.git
cd bentopdf/cloudflare
```
Open `cors-proxy-worker.js` and change the `ALLOWED_ORIGINS` array to your domain:
```js
const ALLOWED_ORIGINS = [
'https://your-domain.com',
'https://www.your-domain.com',
];
```
::: warning Important
Without this change, the proxy will reject all requests from your site with a **403 Forbidden** error. The default only allows requests from `bentopdf.com`.
:::
4. **Deploy the proxy**:
```bash
cd cloudflare
wrangler deploy
```
4. **Update your environment**:
Create a `.env` or set in your hosting platform:
```
VITE_CORS_PROXY_URL=https://your-worker-name.your-subdomain.workers.dev
Note your worker URL (e.g., `https://bentopdf-cors-proxy.your-subdomain.workers.dev`).
5. **Rebuild BentoPDF with the proxy URL**:
If using Docker:
```bash
docker build \
--build-arg VITE_CORS_PROXY_URL="https://your-worker.workers.dev" \
-t your-bentopdf .
```
5. **Rebuild BentoPDF**:
If building from source:
```bash
npm run build
VITE_CORS_PROXY_URL=https://your-worker.workers.dev npm run build
```
### Option 2: Custom Backend Proxy
@@ -51,9 +82,9 @@ You can also create your own proxy endpoint. The requirements are:
1. Accept GET requests with a `url` query parameter
2. Fetch the URL from your server (no CORS restrictions server-side)
3. Return the response with these headers:
- `Access-Control-Allow-Origin: *` (or your specific origin)
- `Access-Control-Allow-Origin: https://your-domain.com`
- `Access-Control-Allow-Methods: GET, OPTIONS`
- `Content-Type: application/x-x509-ca-cert`
- `X-Content-Type-Options: nosniff`
Example Express.js implementation:
@@ -70,8 +101,9 @@ app.get('/api/cert-proxy', async (req, res) => {
const response = await fetch(targetUrl);
const data = await response.arrayBuffer();
res.set('Access-Control-Allow-Origin', '*');
res.set('Content-Type', 'application/x-x509-ca-cert');
res.set('Access-Control-Allow-Origin', 'https://your-domain.com');
res.set('Content-Type', 'application/octet-stream');
res.set('X-Content-Type-Options', 'nosniff');
res.send(Buffer.from(data));
} catch (error) {
res.status(500).json({ error: 'Proxy error' });
@@ -83,9 +115,15 @@ app.get('/api/cert-proxy', async (req, res) => {
The included Cloudflare Worker has several security measures:
- **URL Validation**: Only allows certificate-related URLs (`.crt`, `.cer`, `.pem`, `/certs/`, `/ocsp`, `/crl`)
- **Blocked Domains**: Prevents access to localhost and private IP ranges
- **HTTP Methods**: Only allows GET requests
| Feature | Description |
| ----------------------- | -------------------------------------------------------------------------------------- |
| **Origin Validation** | Only allows requests from domains listed in `ALLOWED_ORIGINS` |
| **URL Restrictions** | Only allows certificate URLs (`.crt`, `.cer`, `.pem`, `/certs/`, `/ocsp`, `/crl`) |
| **Private IP Blocking** | Blocks IPv4/IPv6 private ranges, link-local, loopback, decimal IPs, and cloud metadata |
| **Content-Type Safety** | Only returns safe certificate MIME types, blocks upstream content-type injection |
| **File Size Limit** | Streams response with 10MB limit, aborts mid-download if exceeded |
| **Rate Limiting** | 60 requests per IP per minute (requires KV) |
| **HMAC Signatures** | Optional client-side signing (deters casual abuse) |
## Disabling the Proxy
@@ -95,22 +133,39 @@ If you don't want to use a CORS proxy, set the environment variable to an empty
VITE_CORS_PROXY_URL=
```
**Note**: Without the proxy, signing with certificates that require external chain fetching (like FNMT or some corporate CAs) will fail.
**Note**: Without the proxy, signing with certificates that require external chain fetching (like FNMT or some corporate CAs) will fail with a "Failed to fetch" error.
## Troubleshooting
### "Failed to fetch certificate chain" Error
### "Signing error: TypeError: Failed to fetch"
1. Check that your CORS proxy is deployed and accessible
2. Verify the `VITE_CORS_PROXY_URL` is correctly set
3. Test the proxy directly:
```bash
curl "https://your-proxy.workers.dev?url=https://www.cert.fnmt.es/certs/ACUSU.crt"
```
This usually means either:
1. **No CORS proxy configured** — Set `VITE_CORS_PROXY_URL` and rebuild
2. **Mixed content blocked** — Your site is HTTPS but the certificate's issuer URL is HTTP. The CORS proxy resolves this.
3. **CORS proxy rejecting your origin** — Check that your domain is in the `ALLOWED_ORIGINS` array in `cors-proxy-worker.js`
### "403 Forbidden" from the proxy
Your domain is not in the `ALLOWED_ORIGINS` list. Edit `cors-proxy-worker.js`:
```js
const ALLOWED_ORIGINS = ['https://your-domain.com'];
```
Then redeploy: `npx wrangler deploy`
### Testing the proxy
```bash
curl -H "Origin: https://your-domain.com" \
"https://your-proxy.workers.dev?url=http://www.cert.fnmt.es/certs/ACUSU.crt"
```
### Certificates That Work Without Proxy
Some certificates include the full chain in the P12/PFX file and don't require external fetching:
- Self-signed certificates
- Some commercial CAs that bundle intermediate certificates
- Certificates you've manually assembled with the full chain

View File

@@ -2,8 +2,13 @@ import { PdfSigner, type SignOption } from 'zgapdfsigner';
import forge from 'node-forge';
import { CertificateData, SignPdfOptions } from '@/types';
export function parsePfxFile(pfxBytes: ArrayBuffer, password: string): CertificateData {
const pfxAsn1 = forge.asn1.fromDer(forge.util.createBuffer(new Uint8Array(pfxBytes)));
export function parsePfxFile(
pfxBytes: ArrayBuffer,
password: string
): CertificateData {
const pfxAsn1 = forge.asn1.fromDer(
forge.util.createBuffer(new Uint8Array(pfxBytes))
);
const pfx = forge.pkcs12.pkcs12FromAsn1(pfxAsn1, password);
const certBags = pfx.getBags({ bagType: forge.pki.oids.certBag });
@@ -49,7 +54,7 @@ export function parsePemFiles(
privateKey = forge.pki.privateKeyFromPem(keyPem);
}
const p12Password = keyPassword || 'temp-password';
const p12Password = keyPassword || crypto.randomUUID();
const p12Asn1 = forge.pkcs12.toPkcs12Asn1(
privateKey,
[certificate],
@@ -65,9 +70,16 @@ export function parsePemFiles(
return { p12Buffer: p12Buffer.buffer, password: p12Password, certificate };
}
export function parseCombinedPem(pemContent: string, password?: string): CertificateData {
const certMatch = pemContent.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/);
const keyMatch = pemContent.match(/-----BEGIN (RSA |EC |ENCRYPTED )?PRIVATE KEY-----[\s\S]*?-----END (RSA |EC |ENCRYPTED )?PRIVATE KEY-----/);
export function parseCombinedPem(
pemContent: string,
password?: string
): CertificateData {
const certMatch = pemContent.match(
/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/
);
const keyMatch = pemContent.match(
/-----BEGIN (RSA |EC |ENCRYPTED )?PRIVATE KEY-----[\s\S]*?-----END (RSA |EC |ENCRYPTED )?PRIVATE KEY-----/
);
if (!certMatch) {
throw new Error('No certificate found in PEM file');
@@ -116,7 +128,10 @@ const CORS_PROXY_URL = import.meta.env.VITE_CORS_PROXY_URL || '';
*/
const CORS_PROXY_SECRET = import.meta.env.VITE_CORS_PROXY_SECRET || '';
async function generateProxySignature(url: string, timestamp: number): Promise<string> {
async function generateProxySignature(
url: string,
timestamp: number
): Promise<string> {
const encoder = new TextEncoder();
const key = await crypto.subtle.importKey(
'raw',
@@ -134,7 +149,7 @@ async function generateProxySignature(url: string, timestamp: number): Promise<s
);
return Array.from(new Uint8Array(signature))
.map(b => b.toString(16).padStart(2, '0'))
.map((b) => b.toString(16).padStart(2, '0'))
.join('');
}
@@ -145,25 +160,37 @@ async function generateProxySignature(url: string, timestamp: number): Promise<s
* the fetch fails. This wrapper routes such requests through our CORS proxy.
*
* If VITE_CORS_PROXY_SECRET is configured, requests include HMAC signatures for anti-spoofing.
*
*/
let fetchWrapRefCount = 0;
let savedOriginalFetch: typeof fetch | null = null;
function createCorsAwareFetch(): {
wrappedFetch: typeof fetch;
restore: () => void;
} {
const originalFetch = window.fetch.bind(window);
if (fetchWrapRefCount === 0) {
savedOriginalFetch = window.fetch.bind(window);
const wrappedFetch: typeof fetch = async (input, init) => {
const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;
const originalFetch = savedOriginalFetch;
const isExternalCertificateUrl = (
url.includes('.crt') ||
window.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const url =
typeof input === 'string'
? input
: input instanceof URL
? input.toString()
: input.url;
const isExternalCertificateUrl =
(url.includes('.crt') ||
url.includes('.cer') ||
url.includes('.pem') ||
url.includes('/certs/') ||
url.includes('/ocsp') ||
url.includes('/crl') ||
url.includes('caIssuers')
) && !url.startsWith(window.location.origin);
url.includes('caIssuers')) &&
!url.startsWith(window.location.origin);
if (isExternalCertificateUrl && CORS_PROXY_URL) {
let proxyUrl = `${CORS_PROXY_URL}?url=${encodeURIComponent(url)}`;
@@ -172,28 +199,36 @@ function createCorsAwareFetch(): {
const timestamp = Date.now();
const signature = await generateProxySignature(url, timestamp);
proxyUrl += `&t=${timestamp}&sig=${signature}`;
console.log(`[CORS Proxy] Routing signed certificate request through proxy: ${url}`);
console.log(
`[CORS Proxy] Routing signed certificate request through proxy: ${url}`
);
} else {
console.log(`[CORS Proxy] Routing certificate request through proxy: ${url}`);
console.log(
`[CORS Proxy] Routing certificate request through proxy: ${url}`
);
}
return originalFetch(proxyUrl, init);
}
return originalFetch(input, init);
};
}) as typeof fetch;
}
window.fetch = wrappedFetch;
fetchWrapRefCount++;
return {
wrappedFetch,
wrappedFetch: window.fetch,
restore: () => {
window.fetch = originalFetch;
fetchWrapRefCount--;
if (fetchWrapRefCount === 0 && savedOriginalFetch) {
window.fetch = savedOriginalFetch;
savedOriginalFetch = null;
}
},
};
}
export async function signPdf(
pdfBytes: Uint8Array,
certificateData: CertificateData,
@@ -229,8 +264,12 @@ export async function signPdf(
h: vs.height,
},
pageidx: vs.page,
imgInfo: undefined as { imgData: ArrayBuffer; imgType: string } | undefined,
textInfo: undefined as { text: string; size: number; color: string } | undefined,
imgInfo: undefined as
| { imgData: ArrayBuffer; imgType: string }
| undefined,
textInfo: undefined as
| { text: string; size: number; color: string }
| undefined,
};
if (vs.imageData && vs.imageType) {
@@ -274,8 +313,8 @@ export function getCertificateInfo(certificate: forge.pki.Certificate): {
const issuerCN = certificate.issuer.getField('CN');
return {
subject: subjectCN?.value as string ?? 'Unknown',
issuer: issuerCN?.value as string ?? 'Unknown',
subject: (subjectCN?.value as string) ?? 'Unknown',
issuer: (issuerCN?.value as string) ?? 'Unknown',
validFrom: certificate.validity.notBefore,
validTo: certificate.validity.notAfter,
serialNumber: certificate.serialNumber,