Skip to content

Commit

Permalink
refactor: cleanup
Browse files Browse the repository at this point in the history
- remove deprecated options
- less aggressive minification, to avoid warning messages on userland
  during build stage.
- better tree-shaking.
- upgraded dependencies
- pass noCheck option to .d.ts files generation step (faster)
- remove outdated comments

Signed-off-by: Andres Correa Casablanca <[email protected]>
  • Loading branch information
castarco committed Sep 19, 2024
1 parent 3cf8655 commit 69e61c1
Show file tree
Hide file tree
Showing 17 changed files with 226 additions and 259 deletions.
2 changes: 1 addition & 1 deletion @kindspells/astro-shield/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@
"@types/node": "^22.5.5",
"astro": "^4.15.7",
"get-tsconfig": "^4.8.1",
"rollup": "^4.21.3",
"rollup": "^4.22.0",
"rollup-plugin-dts": "^6.1.1",
"rollup-plugin-esbuild": "^6.1.1",
"typescript": "^5.6.2",
Expand Down
35 changes: 23 additions & 12 deletions @kindspells/astro-shield/rollup.config.mjs
Original file line number Diff line number Diff line change
@@ -1,47 +1,58 @@
import { dirname } from 'node:path'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'

import { getTsconfig } from 'get-tsconfig'
import { defineConfig } from 'rollup'
import dts from 'rollup-plugin-dts'
import { dts } from 'rollup-plugin-dts'
import esbuild from 'rollup-plugin-esbuild'

const projectDir = dirname(fileURLToPath(import.meta.url))
const tsconfig = getTsconfig(projectDir)
const target = tsconfig?.config.compilerOptions?.target ?? 'es2020'
const target = tsconfig?.config.compilerOptions?.target ?? 'es2022'

const outputBaseConfig = {
const baseConfig = {
plugins: [
esbuild({
target: ['node18', 'node20', 'node22', target],
loaders: { '.mts': 'ts' },
minify: true,
keepNames: true,
minifyIdentifiers: true,
minifySyntax: true,
minifyWhitespace: false,
treeShaking: true,
}),
],
external: ['node:crypto', 'node:fs/promises', 'node:path', 'node:url'],
}

const outputConfig = /** @type {import('rollup').OutputOptions} */ ({
format: 'esm',
indent: '\t', // With any luck, some day esbuild will support this option
sourcemap: true,
})

export default defineConfig([
{
input: 'src/core.mts',
output: [{ format: 'esm', file: 'dist/core.mjs', sourcemap: true }],
...outputBaseConfig,
output: [{ ...outputConfig, file: 'dist/core.mjs' }],
...baseConfig,
},
{
input: 'src/main.mts',
output: [{ format: 'esm', file: 'dist/main.mjs', sourcemap: true }],
output: [{ ...outputConfig, file: 'dist/main.mjs' }],
external: ['#as/core'],
...outputBaseConfig,
...baseConfig,
},
{
input: 'src/state.mts',
output: [{ format: 'esm', file: 'dist/state.mjs', sourcemap: true }],
...outputBaseConfig,
output: [{ ...outputConfig, file: 'dist/state.mjs' }],
...baseConfig,
},
{
input: 'src/main.mts',
output: [{ format: 'esm', file: 'dist/main.d.mts' }],
external: ['#as/core'],
plugins: [dts()],
// TODO: When possible, pass `noCheck: true` instead of loading an entire tsconfig file
plugins: [dts({ tsconfig: resolve(projectDir, 'tsconfig.dts.json') })],
},
])
36 changes: 14 additions & 22 deletions @kindspells/astro-shield/src/core.mts
Original file line number Diff line number Diff line change
Expand Up @@ -725,21 +725,23 @@ export async function generateSRIHashesModule(
}
}

const newHashesCollection = (): HashesCollection => ({
inlineScriptHashes: new Set(),
inlineStyleHashes: new Set(),
extScriptHashes: new Set(),
extStyleHashes: new Set(),
perPageSriHashes: new Map(),
perResourceSriHashes: {
scripts: new Map(),
styles: new Map(),
},
})

export const processStaticFiles = async (
logger: Logger,
{ distDir, sri, securityHeaders }: StrictShieldOptions,
): Promise<void> => {
const h = {
inlineScriptHashes: new Set(),
inlineStyleHashes: new Set(),
extScriptHashes: new Set(),
extStyleHashes: new Set(),
perPageSriHashes: new Map(),
perResourceSriHashes: {
scripts: new Map(),
styles: new Map(),
},
} satisfies HashesCollection
const h = newHashesCollection()

await scanAllowLists(sri, h)
await scanForNestedResources(logger, distDir, h)
Expand Down Expand Up @@ -884,17 +886,7 @@ const loadVirtualMiddlewareModule = async (
}

if (shouldRegenerateHashesModule) {
const h = {
inlineScriptHashes: new Set(),
inlineStyleHashes: new Set(),
extScriptHashes: new Set(),
extStyleHashes: new Set(),
perPageSriHashes: new Map(),
perResourceSriHashes: {
scripts: new Map(),
styles: new Map(),
},
} satisfies HashesCollection
const h = newHashesCollection()

// We generate a provisional hashes module. It won't contain the hashes for
// resources created by Astro, but it can be useful nonetheless.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,17 @@ import node from '@astrojs/node'
import { shield } from '@kindspells/astro-shield'
import { defineConfig } from 'astro/config'

/**
* @typedef {{ -readonly [key in keyof T]: T[key] }} Mutable<T>
* @template {any} T
*/

// https://astro.build/config
export default defineConfig({
output: 'server',
trailingSlash: 'always',
adapter: node({ mode: 'standalone' }),
integrations: [
shield({
enableStatic_SRI: false,
enableMiddleware_SRI: true,
sri: {
enableStatic: false,
enableMiddleware: true,
},
}),
],
})
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,8 @@ import node from '@astrojs/node'
import { shield } from '@kindspells/astro-shield'
import { defineConfig } from 'astro/config'

/**
* @typedef {{ -readonly [key in keyof T]: T[key] }} Mutable<T>
* @template {any} T
*/

const rootDir = new URL('.', import.meta.url).pathname
const sriHashesModule = resolve(rootDir, 'src', 'generated', 'sri.mjs')
const hashesModule = resolve(rootDir, 'src', 'generated', 'sri.mjs')

// https://astro.build/config
export default defineConfig({
Expand All @@ -24,9 +19,11 @@ export default defineConfig({
adapter: node({ mode: 'standalone' }),
integrations: [
shield({
enableStatic_SRI: true,
enableMiddleware_SRI: true,
sriHashesModule,
sri: {
enableStatic: true,
enableMiddleware: true,
hashesModule,
},
}),
],
})
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,8 @@ import node from '@astrojs/node'
import { shield } from '@kindspells/astro-shield'
import { defineConfig } from 'astro/config'

/**
* @typedef {{ -readonly [key in keyof T]: T[key] }} Mutable<T>
* @template {any} T
*/

const rootDir = new URL('.', import.meta.url).pathname
const sriHashesModule = resolve(rootDir, 'src', 'generated', 'sri.mjs')
const hashesModule = resolve(rootDir, 'src', 'generated', 'sri.mjs')

// https://astro.build/config
export default defineConfig({
Expand All @@ -24,9 +19,11 @@ export default defineConfig({
adapter: node({ mode: 'standalone' }),
integrations: [
shield({
enableStatic_SRI: true,
enableMiddleware_SRI: true,
sriHashesModule,
sri: {
enableStatic: true,
enableMiddleware: true,
hashesModule,
},
}),
],
vite: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,6 @@ import node from '@astrojs/node'
import { shield } from '@kindspells/astro-shield'
import { defineConfig } from 'astro/config'

/**
* @typedef {{ -readonly [key in keyof T]: T[key] }} Mutable<T>
* @template {any} T
*/

const rootDir = new URL('.', import.meta.url).pathname
const sriHashesModule = resolve(rootDir, 'src', 'generated', 'sri.mjs')

Expand Down
21 changes: 9 additions & 12 deletions @kindspells/astro-shield/src/e2e/fixtures/static/astro.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,26 +9,23 @@ import { env } from 'node:process'
import { shield } from '@kindspells/astro-shield'
import { defineConfig } from 'astro/config'

/**
* @typedef {{ -readonly [key in keyof T]: T[key] }} Mutable<T>
* @template {any} T
*/

const rootDir = new URL('.', import.meta.url).pathname
const sriHashesModule = resolve(rootDir, 'src', 'generated', 'sri.mjs')
const hashesModule = resolve(rootDir, 'src', 'generated', 'sri.mjs')

// https://astro.build/config
export default defineConfig({
output: 'static',
trailingSlash: 'always',
integrations: [
shield({
...((env.ENABLE_SRI_MODULE ?? 'true') === 'true'
? { sriHashesModule }
: undefined),
...(env.ENABLE_STATIC_SRI
? { enableStatic_SRI: env.ENABLE_STATIC_SRI === 'true' }
: undefined),
sri: {
...((env.ENABLE_SRI_MODULE ?? 'true') === 'true'
? { hashesModule }
: undefined),
...(env.ENABLE_STATIC_SRI
? { enableStatic: env.ENABLE_STATIC_SRI === 'true' }
: undefined),
},
}),
],
})
10 changes: 5 additions & 5 deletions @kindspells/astro-shield/src/headers.mts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { PerPageHashes } from './types.mts'
import type { CSPDirectiveNames, PerPageHashes } from './types.mts'
import type {
CSPDirectives,
CSPOptions,
Expand Down Expand Up @@ -51,10 +51,10 @@ export const parseCspDirectives = (cspHeader: string): CSPDirectives => {
const parts = directive
.replace(spacesRegex, '||||||')
.split('||||||')
return /** @type {[CSPDirectiveNames, string]} */ ([
parts[0],
parts[1] ?? '',
])
return [parts[0] as CSPDirectiveNames, parts[1] ?? ''] satisfies [
CSPDirectiveNames,
string,
]
}) ?? [],
)
: {}
Expand Down
26 changes: 5 additions & 21 deletions @kindspells/astro-shield/src/main.mts
Original file line number Diff line number Diff line change
Expand Up @@ -34,37 +34,21 @@ const logWarn = (msg: string): void =>
// Integration
// -----------------------------------------------------------------------------
export const shield = ({
enableMiddleware_SRI,
enableStatic_SRI,
sriHashesModule,
securityHeaders,
sri,
}: ShieldOptions): AstroIntegration => {
// TODO: Remove deprecated options in a future release
if (enableMiddleware_SRI !== undefined) {
logWarn(
'`enableMiddleware_SRI` is deprecated, use `sri.enableMiddleware` instead',
)
}
if (enableStatic_SRI !== undefined) {
logWarn('`enableStatic_SRI` is deprecated, use `sri.enableStatic` instead')
}
if (sriHashesModule !== undefined) {
logWarn('`sriHashesModule` is deprecated, use `sri.hashesModule` instead')
}

// We need to merge the deprecated options into the new object
const _sri = /** @satisfies {Required<SRIOptions>} */ {
enableMiddleware: sri?.enableMiddleware ?? enableMiddleware_SRI ?? false,
enableStatic: sri?.enableStatic ?? enableStatic_SRI ?? true,
hashesModule: sri?.hashesModule ?? sriHashesModule,
const _sri = {
enableMiddleware: sri?.enableMiddleware ?? false,
enableStatic: sri?.enableStatic ?? true,
hashesModule: sri?.hashesModule,

allowInlineScripts: sri?.allowInlineScripts ?? 'all',
allowInlineStyles: sri?.allowInlineStyles ?? 'all',

scriptsAllowListUrls: sri?.scriptsAllowListUrls ?? [],
stylesAllowListUrls: sri?.stylesAllowListUrls ?? [],
}
} satisfies Required<SRIOptions>

if (_sri.hashesModule && _sri.enableStatic === false) {
logWarn('`sriHashesModule` is ignored when `enableStatic_SRI` is `false`')
Expand Down
4 changes: 2 additions & 2 deletions @kindspells/astro-shield/src/tests/core.test.mts
Original file line number Diff line number Diff line change
Expand Up @@ -623,7 +623,7 @@ describe('updateStaticPageSriHashes', () => {
<title>My Test Page</title>
</head>
<body>
<script type="module" src="/state.mjs" integrity="sha256-GnAS2y0U5qIXDOpQOY7sE+D1/ncp19EQxwySQzSR/bQ="></script>
<script type="module" src="/state.mjs" integrity="sha256-c2maJMv9xUmyw/qVU3BqJdJxvlXslBMh6bElfvFXXTQ="></script>
</body>
</html>`

Expand All @@ -641,7 +641,7 @@ describe('updateStaticPageSriHashes', () => {

expect(
h.extScriptHashes.has(
'sha256-GnAS2y0U5qIXDOpQOY7sE+D1/ncp19EQxwySQzSR/bQ=',
'sha256-c2maJMv9xUmyw/qVU3BqJdJxvlXslBMh6bElfvFXXTQ=',
),
).toBe(true)
expect(h.inlineScriptHashes.size).toBe(0)
Expand Down
6 changes: 4 additions & 2 deletions @kindspells/astro-shield/src/tests/main.test.mts
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,10 @@ describe('sriCSP', () => {

it('returns hooks only for dynamic content when we enable middleware and disable static sri', () => {
const integration = shield({
enableStatic_SRI: false,
enableMiddleware_SRI: true,
sri: {
enableStatic: false,
enableMiddleware: true,
},
})
checkIntegration(integration, ['astro:config:setup'])
})
Expand Down
9 changes: 0 additions & 9 deletions @kindspells/astro-shield/src/types.mts
Original file line number Diff line number Diff line change
Expand Up @@ -161,15 +161,6 @@ export type ShieldOptions = {
* Defaults to `undefined`.
*/
securityHeaders?: SecurityHeadersOptions | undefined

/** @deprecated Use `sri.enableStatic` instead. */
enableStatic_SRI?: boolean | undefined

/** @deprecated Use `sri.enableMiddleware` instead. */
enableMiddleware_SRI?: boolean | undefined

/** @deprecated Use `sri.hashesModule` instead. */
sriHashesModule?: string | undefined
}

export type StrictShieldOptions = ShieldOptions & {
Expand Down
9 changes: 9 additions & 0 deletions @kindspells/astro-shield/tsconfig.dts.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"noEmit": false,
"declaration": true,
"emitDeclarationOnly": true,
"noCheck": true
}
}
Loading

0 comments on commit 69e61c1

Please sign in to comment.