Skip to content

SRI for SSR Content

This content is not available in your language yet.

By default, Astro-Shield does not enable SRI for SSR (Server-Side-Rendered) content, but you can easily enable it by setting the sri.enableMiddleware option to true in your Astro config file.

import { resolve } from 'node:path'
import { defineConfig } from 'astro/config'
import { shield } from '@kindspells/astro-shield'
const rootDir = new URL('.', import.meta.url).pathname
const modulePath = resolve(rootDir, 'src', 'generated', 'sriHashes.mjs')
export default defineConfig({
integrations: [
shield({
sri: {
hashesModule: modulePath,
enableMiddleware: true,
},
}),
],
})

Reinforcing security for dynamic content

Allow Lists

Astro-Shield will block any cross-origin resource that it isn’t explicitly allowed. This is because doing otherwise could open the door to a variety of security vulnerabilities caused by loading untrusted content and marking it as safe.

We can define a list of allowed resource URLs like in the example below:

import { resolve } from 'node:path'
import { defineConfig } from 'astro/config'
import { shield } from '@kindspells/astro-shield'
const rootDir = new URL('.', import.meta.url).pathname
const modulePath = resolve(rootDir, 'src', 'generated', 'sriHashes.mjs')
export default defineConfig({
integrations: [
shield({
sri: {
hashesModule: modulePath,
enableMiddleware: true,
scriptsAllowListUrls: [
'https://code.jquery.com/jquery-3.7.1.slim.min.js',
],
stylesAllowListUrls: [
'https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css',
],
},
}),
],
})

Blocking Inline Resources

Although Astro-Shield does not block inline resources by default, it might be a good idea to block them in certain cases to prevent XSS attacks. You can do this by setting the options sri.allowInlineScripts and sri.allowInlineStyles to false or 'static' (this one allows inline resources only in static content).

import { resolve } from 'node:path'
import { defineConfig } from 'astro/config'
import { shield } from '@kindspells/astro-shield'
const rootDir = new URL('.', import.meta.url).pathname
const modulePath = resolve(rootDir, 'src', 'generated', 'sriHashes.mjs')
export default defineConfig({
integrations: [
shield({
sri: {
hashesModule: modulePath,
enableMiddleware: true,
allowInlineScripts: false,
allowInlineStyles: 'static',
},
}),
],
})