fix(web): nonce JSON-LD scripts

This commit is contained in:
2026-10-16 00:21:33 +02:00
parent e6069248b0
commit 9119599e45
2 changed files with 52 additions and 1 deletions
+47
View File
@@ -0,0 +1,47 @@
import { Transform } from "node:stream";
import type { TransformCallback } from "node:stream";
const JSON_LD_OPENING_TAG = Buffer.from('<script type="application/ld+json">');
export function nonceJsonLdScripts(nonce: string): Transform {
const nonceOpeningTag = Buffer.from(
`<script nonce="${nonce}" type="application/ld+json">`,
);
const retainedBytes = JSON_LD_OPENING_TAG.length - 1;
let pending = Buffer.alloc(0);
return new Transform({
transform(chunk: Buffer, _encoding: BufferEncoding, callback: TransformCallback) {
const data = Buffer.concat([pending, chunk]);
const safeLimit = Math.max(0, data.length - retainedBytes);
let cursor = 0;
let match = data.indexOf(JSON_LD_OPENING_TAG, cursor);
while (match !== -1 && match < safeLimit) {
this.push(data.subarray(cursor, match));
this.push(nonceOpeningTag);
cursor = match + JSON_LD_OPENING_TAG.length;
match = data.indexOf(JSON_LD_OPENING_TAG, cursor);
}
const safeEnd = Math.max(cursor, safeLimit);
if (safeEnd > cursor) this.push(data.subarray(cursor, safeEnd));
pending = Buffer.from(data.subarray(safeEnd));
callback();
},
flush(callback: TransformCallback) {
let cursor = 0;
let match = pending.indexOf(JSON_LD_OPENING_TAG, cursor);
while (match !== -1) {
this.push(pending.subarray(cursor, match));
this.push(nonceOpeningTag);
cursor = match + JSON_LD_OPENING_TAG.length;
match = pending.indexOf(JSON_LD_OPENING_TAG, cursor);
}
this.push(pending.subarray(cursor));
callback();
},
});
}