Skip to content

feat(browser): support for nonce in some loadScript calls #1302

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/old-cameras-unite.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@segment/analytics-next': patch
---

Added support for nonce attribute in injected load script
6 changes: 1 addition & 5 deletions packages/browser/src/browser/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,11 +214,7 @@ async function registerPlugins(
await import(
/* webpackChunkName: "remoteMiddleware" */ '../plugins/remote-middleware'
).then(async ({ remoteMiddlewares }) => {
const middleware = await remoteMiddlewares(
ctx,
cdnSettings,
options.obfuscate
)
const middleware = await remoteMiddlewares(ctx, cdnSettings, options)
const promises = middleware.map((mdw) =>
analytics.addSourceMiddleware(mdw)
)
Expand Down
4 changes: 4 additions & 0 deletions packages/browser/src/browser/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,10 @@ export interface InitOptions {
plan?: Plan
retryQueue?: boolean
obfuscate?: boolean
/**
* Nonce to be used by the injected segment script
*/
nonce?: string
/**
* This callback allows you to update/mutate CDN Settings.
* This is called directly after settings are fetched from the CDN.
Expand Down
2 changes: 1 addition & 1 deletion packages/browser/src/browser/standalone.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ import { setGlobalAnalyticsKey } from '../lib/global-analytics-helper'
let ajsIdentifiedCSP = false

const sendErrorMetrics = (tags: string[]) => {
// this should not be instantied at the root, or it will break ie11.
// this should not be instantiated at the root, or it will break ie11.
const metrics = new RemoteMetrics()
metrics.increment('analytics_js.invoke.error', [
...tags,
Expand Down
7 changes: 1 addition & 6 deletions packages/browser/src/plugins/ajs-destination/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,12 +136,7 @@ export class LegacyDestination implements InternalPluginWithAddMiddleware {

const integrationSource =
this.integrationSource ??
(await loadIntegration(
ctx,
this.name,
this.version,
this.options.obfuscate
))
(await loadIntegration(ctx, this.name, this.version, this.options))

this.integration = buildIntegration(
integrationSource,
Expand Down
11 changes: 7 additions & 4 deletions packages/browser/src/plugins/ajs-destination/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,18 +71,19 @@ export async function loadIntegration(
ctx: Context,
name: string,
version: string,
obfuscate?: boolean
options?: { obfuscate?: boolean; nonce?: string }
): Promise<ClassicIntegrationSource> {
const nonceAttr = options?.nonce ? { nonce: options.nonce } : undefined
const pathName = normalizeName(name)
const obfuscatedPathName = obfuscatePathName(pathName, obfuscate)
const obfuscatedPathName = obfuscatePathName(pathName, options?.obfuscate)
const path = getNextIntegrationsURL()

const fullPath = `${path}/integrations/${
obfuscatedPathName ?? pathName
}/${version}/${obfuscatedPathName ?? pathName}.dynamic.js.gz`

try {
await loadScript(fullPath)
await loadScript(fullPath, nonceAttr)
recordLoadMetrics(fullPath, ctx, name)
} catch (err) {
ctx.stats.gauge('legacy_destination_time', -1, [`plugin:${name}`, `failed`])
Expand All @@ -91,7 +92,9 @@ export async function loadIntegration(

// @ts-ignore
const deps: string[] = window[`${pathName}Deps`]
await Promise.all(deps.map((dep) => loadScript(path + dep + '.gz')))
await Promise.all(
deps.map((dep) => loadScript(path + dep + '.gz', nonceAttr))
)

// @ts-ignore
window[`${pathName}Loader`]()
Expand Down
39 changes: 36 additions & 3 deletions packages/browser/src/plugins/remote-loader/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,10 @@ describe('Remote Loader', () => {
{}
)

expect(loader.loadScript).toHaveBeenCalledWith('cdn/path/to/file.js')
expect(loader.loadScript).toHaveBeenCalledWith(
'cdn/path/to/file.js',
undefined
)
})

it('should attempt to load a script from the obfuscated url of each remotePlugin', async () => {
Expand All @@ -69,6 +72,30 @@ describe('Remote Loader', () => {
)
})

it('should pass the nonce attribute for each remotePlugin load', async () => {
await remoteLoader(
{
...cdnSettingsMinimal,
remotePlugins: [
{
name: 'remote plugin',
creationName: 'remote plugin',
url: 'cdn/path/to/file.js',
libraryName: 'testPlugin',
settings: {},
},
],
},
{},
{},
{ nonce: 'my-foo-nonce' }
)

expect(loader.loadScript).toHaveBeenCalledWith('cdn/path/to/file.js', {
nonce: 'my-foo-nonce',
})
})

it('should attempt to load a script from a custom CDN', async () => {
window.analytics = {}
window.analytics._cdn = 'foo.com'
Expand All @@ -89,7 +116,10 @@ describe('Remote Loader', () => {
{}
)

expect(loader.loadScript).toHaveBeenCalledWith('foo.com/actions/file.js')
expect(loader.loadScript).toHaveBeenCalledWith(
'foo.com/actions/file.js',
undefined
)
})

it('should work if the cdn is staging', async () => {
Expand All @@ -114,7 +144,10 @@ describe('Remote Loader', () => {
{}
)

expect(loader.loadScript).toHaveBeenCalledWith('foo.com/actions/foo.js')
expect(loader.loadScript).toHaveBeenCalledWith(
'foo.com/actions/foo.js',
undefined
)
})

it('should attempt calling the library', async () => {
Expand Down
11 changes: 6 additions & 5 deletions packages/browser/src/plugins/remote-loader/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,13 +223,14 @@ function isPluginDisabled(

async function loadPluginFactory(
remotePlugin: RemotePlugin,
obfuscate?: boolean
options?: { obfuscate?: boolean; nonce?: string }
): Promise<void | PluginFactory> {
try {
const defaultCdn = new RegExp('https://cdn.segment.(com|build)')
const cdn = getCDN()
const nonceAttr = options?.nonce ? { nonce: options.nonce } : undefined

if (obfuscate) {
if (options?.obfuscate) {
const urlSplit = remotePlugin.url.split('/')
const name = urlSplit[urlSplit.length - 2]
const obfuscatedURL = remotePlugin.url.replace(
Expand All @@ -241,10 +242,10 @@ async function loadPluginFactory(
} catch (error) {
// Due to syncing concerns it is possible that the obfuscated action destination (or requested version) might not exist.
// We should use the unobfuscated version as a fallback.
await loadScript(remotePlugin.url.replace(defaultCdn, cdn))
await loadScript(remotePlugin.url.replace(defaultCdn, cdn), nonceAttr)
}
} else {
await loadScript(remotePlugin.url.replace(defaultCdn, cdn))
await loadScript(remotePlugin.url.replace(defaultCdn, cdn), nonceAttr)
}

// @ts-expect-error
Expand Down Expand Up @@ -278,7 +279,7 @@ export async function remoteLoader(
const pluginFactory =
pluginSources?.find(
({ pluginName }) => pluginName === remotePlugin.name
) || (await loadPluginFactory(remotePlugin, options?.obfuscate))
) || (await loadPluginFactory(remotePlugin, options))

if (pluginFactory) {
const intg = mergedIntegrations[remotePlugin.name]
Expand Down
7 changes: 4 additions & 3 deletions packages/browser/src/plugins/remote-middleware/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { MiddlewareFunction } from '../middleware'
export async function remoteMiddlewares(
ctx: Context,
settings: CDNSettings,
obfuscate?: boolean
options?: { obfuscate?: boolean; nonce?: string }
): Promise<MiddlewareFunction[]> {
if (isServer()) {
return []
Expand All @@ -22,13 +22,14 @@ export async function remoteMiddlewares(
const scripts = names.map(async (name) => {
const nonNamespaced = name.replace('@segment/', '')
let bundleName = nonNamespaced
if (obfuscate) {
if (options?.obfuscate) {
bundleName = btoa(nonNamespaced).replace(/=/g, '')
}
const fullPath = `${path}/middleware/${bundleName}/latest/${bundleName}.js.gz`

try {
await loadScript(fullPath)
const nonceAttr = options?.nonce ? { nonce: options.nonce } : undefined
await loadScript(fullPath, nonceAttr)
// @ts-ignore
return window[`${nonNamespaced}Middleware`] as MiddlewareFunction
} catch (error: any) {
Expand Down