Skip to content

Commit

Permalink
feat: csp support
Browse files Browse the repository at this point in the history
  • Loading branch information
Julien-R44 committed Feb 29, 2024
1 parent a08281a commit 0bd9bc0
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 5 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
"@adonisjs/core": "6.3.1",
"@adonisjs/eslint-config": "^1.2.1",
"@adonisjs/prettier-config": "^1.2.1",
"@adonisjs/session": "^7.1.1",
"@adonisjs/shield": "^8.1.1",
"@adonisjs/tsconfig": "^1.2.1",
"@japa/assert": "2.1.0",
Expand Down
30 changes: 30 additions & 0 deletions providers/vite_provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
*/

import type { ApplicationService } from '@adonisjs/core/types'
import type { cspKeywords as ShieldCSPKeywords } from '@adonisjs/shield'

import { Vite } from '../src/vite.js'
import type { ViteOptions } from '../src/types.js'
Expand Down Expand Up @@ -42,6 +43,35 @@ export default class ViteProvider {
}
}

/**
* Registers CSP keywords when @adonisjs/shield is installed
*/
protected async registerShieldKeywords() {
let cspKeywords: typeof ShieldCSPKeywords | null = null
try {
const shieldExports = await import('@adonisjs/shield')
cspKeywords = shieldExports.cspKeywords
} catch {}

if (!cspKeywords) return

const vite = await this.app.container.make('vite')

/**
* Registering the @viteUrl keyword for CSP directives.
* Returns http URL to the dev or the CDN server, otherwise
* an empty string
*/
cspKeywords.register('@viteUrl', function () {
const assetsURL = vite.assetsUrl()
if (!assetsURL || !assetsURL.startsWith('http://') || assetsURL.startsWith('https://')) {
return ''
}

return assetsURL
})
}

/**
* Register Vite bindings
*/
Expand Down
6 changes: 1 addition & 5 deletions src/vite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -209,13 +209,9 @@ export class Vite {
}

/**
* Returns the dev server URL when running in hot
* mode, otherwise returns the explicitly configured
* "assets" URL
* Returns the explicitly configured assetsUrl
*/
assetsUrl() {
if (this.isViteRunning) return this.#devServer!.config.server.host

return this.#options.assetsUrl
}

Expand Down

0 comments on commit 0bd9bc0

Please sign in to comment.