Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
32 changes: 32 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# DA Content

## Helix 6 compatibility

Configure `HLX6_MIGRATED_SITES` in the Cloudflare dashboard with the same
`org/site` entries used by da-admin. Arrays, JSON-encoded arrays, and
comma/newline-separated strings are accepted. Keep `HLX6_DUAL_WRITES` in sync
as well: a dual-writing source site still uses normal DA routing.
Malformed migration-variable JSON fails explicitly instead of using R2.

For migrated sites, requests use the `daadmin` service binding before any
direct-R2 allowlist or image opt-out. Deploy the da-admin read/save bridge
first; this worker does not forward directly to api.aem.live or substitute a
service credential.

Legacy content URLs retain lowercase/document/index normalization,
`auth_token` cookie, Authorization header, query-token handling, and the local
`.gimme_cookie` endpoint. GET/HEAD responses stream through the binding,
preserving ETag, Last-Modified, cache controls and upstream errors. Conditional
headers are forwarded. SVG download behavior and CORS remain on the DA host.

Unauthenticated requests can still fail: bypassing old public-R2 paths does
not grant permission to read HLX6 authoring content. A failure never retries
against R2. Source/config saves belong to da-admin; content-host mutations
remain unsupported.

Neither migration variable is declared in the Wrangler vars block;
`keep_vars = true` preserves dashboard values during deployment.

## Validation

Run `npm test` and `npm run lint`.
18 changes: 18 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { getCookie } from './cookie.js';
import { get404, daResp, getRobots } from './responses/index.js';
import getFromAdmin from './storage/admin.js';
import { isEmbeddableAsset } from './storage/utils.js';
import isHlx6Site from './utils/hlx6.js';

// https://www.aem.live/docs/security#backends-with-ip-filtering
const HELIX_ADMIN_IP = '3.227.118.73';
Expand Down Expand Up @@ -49,6 +50,12 @@ function shouldGetFromStorage(env, req, pathname, org) {
}

export default {
/**
* Routes migrated sites through admin before legacy R2 bypasses, keeping cookie endpoints local.
* @param {Request} req Incoming content request.
* @param {Object} env Worker bindings, storage settings and migration configuration.
* @returns {Promise<Response>} Content response or explicit routing/configuration error.
*/
async fetch(req, env) {
const url = new URL(req.url);
const { pathname } = url;
Expand All @@ -64,6 +71,17 @@ export default {

if (!org || !site) return get404();

try {
if (isHlx6Site(env, org, site)) return getFromAdmin(req, env);
} catch (e) {
// eslint-disable-next-line no-console
console.error('[hlx6] Migration routing configuration error', e.message);
const resp = daResp({ status: 503, body: e.message, contentType: 'text/plain' });
resp.headers.set('x-error', e.message);
resp.headers.set('cache-control', 'private, no-store');
return resp;
}

if (shouldGetFromStorage(env, req, pathname, org)) {
return getFromStorage(pathname, env);
}
Expand Down
6 changes: 3 additions & 3 deletions src/responses/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,13 @@ function isSvgContentType(contentType) {
export function daResp({ body, status, contentType }) {
const headers = new Headers();
headers.append('Access-Control-Allow-Origin', '*');
headers.append('Access-Control-Allow-Methods', 'GET, OPTIONS');
headers.append('Access-Control-Allow-Headers', 'authorization');
headers.append('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS');
headers.append('Access-Control-Allow-Headers', 'authorization, if-match, if-none-match');

if (contentType) headers.append('Content-Type', contentType);
if (isSvgContentType(contentType)) headers.append('Content-Disposition', 'attachment');

return new Response(body, { status, headers });
return new Response(status === 204 || status === 304 ? undefined : body, { status, headers });
}

export function get404() {
Expand Down
21 changes: 19 additions & 2 deletions src/storage/admin.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,12 +72,20 @@ function canonicalizePathname(pathname) {
return canonicalized;
}

/**
* Canonicalizes legacy content URLs and streams GET/HEAD through the daadmin service binding.
* Preserves caller cookie/header/query-token auth, conditions, metadata, errors and SVG handling.
* OPTIONS remains local; transport failures return 503 without falling back to R2.
* @param {Request} req Legacy content request.
* @param {{daadmin: {fetch: typeof fetch}}} env Admin service binding.
* @returns {Promise<Response>} Legacy-host content/metadata response or explicit error.
*/
export default async function getFromAdmin(req, env) {
if (req.method === 'OPTIONS') {
return daResp({ body: '', status: 200 });
}

if (req.method !== 'GET') {
if (req.method !== 'GET' && req.method !== 'HEAD') {
return new Response('', { status: 405 });
}

Expand All @@ -92,14 +100,23 @@ export default async function getFromAdmin(req, env) {
if (authHeader) {
reqHeaders.set('authorization', authHeader);
}
['if-match', 'if-none-match'].forEach((name) => {
if (req.headers.has(name)) reqHeaders.set(name, req.headers.get(name));
});

try {
const resp = await env.daadmin.fetch(url, {
method: req.method,
headers: reqHeaders,
});
const { status, headers } = resp;
const contentType = headers.get('content-type');
return daResp({ body: resp.body, status, contentType });
const result = daResp({ body: req.method === 'HEAD' ? undefined : resp.body, status, contentType });
['etag', 'last-modified', 'cache-control', 'content-length', 'x-error', 'x-error-code', 'retry-after'].forEach((name) => {
if (headers.has(name)) result.headers.set(name, headers.get(name));
});
result.headers.set('access-control-expose-headers', 'ETag, Last-Modified, x-error, x-error-code, Retry-After');
return result;
} catch (e) {
const msg = 'Failed to fetch from admin';
return new Response(
Expand Down
67 changes: 67 additions & 0 deletions src/utils/hlx6.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/*
* Copyright 2026 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
/**
* Parses dashboard arrays, JSON arrays or comma/newline-separated migration entries.
* @param {string[]|string|undefined} value Migration-variable value.
* @param {string} name Variable name used in configuration errors.
* @returns {unknown[]} Parsed entries, or an empty array for an unset variable.
* @throws {Error} If a provided value has an unsupported type or malformed JSON array.
*/
function entries(value, name) {
if (!value) return [];
if (Array.isArray(value)) return value;
if (typeof value !== 'string') {
throw new Error(`Invalid ${name}`);
}
if (!value.trim().startsWith('[')) return value.split(/[,\n]/);
try {
const parsed = JSON.parse(value);
if (Array.isArray(parsed)) return parsed;
} catch {
throw new Error(`Invalid JSON in ${name}`);
}
throw new Error(`Invalid ${name}`);
}

/**
* Normalizes a single org/site entry, ignoring values that do not identify exactly two segments.
* @param {unknown} value Candidate org/site entry.
* @returns {string|undefined} Lowercase org/site key, or undefined for an invalid entry.
*/
function orgSite(value) {
if (typeof value !== 'string') return undefined;
const parts = value.trim().toLowerCase().split('/').filter(Boolean);
return parts.length === 2 ? parts.join('/') : undefined;
}

/**
* Selects migrated sources for admin routing while excluding valid dual-write source entries.
* A mapped dual-write target does not exempt that target from migrated routing.
* @param {Object} env Worker migration configuration.
* @param {string[]|string} [env.HLX6_MIGRATED_SITES] Migrated org/site entries.
* @param {string[]|string} [env.HLX6_DUAL_WRITES] Source entries with optional target mappings.
* @param {string} org Content organization.
* @param {string} site Content site.
* @returns {boolean} Whether requests must use admin rather than direct R2.
* @throws {Error} If either configured migration list cannot be parsed.
*/
export default function isHlx6Site(env, org, site) {
const key = `${org}/${site}`.toLowerCase();
const migrated = entries(env.HLX6_MIGRATED_SITES, 'HLX6_MIGRATED_SITES')
.some((entry) => typeof entry === 'string' && !entry.includes('->') && orgSite(entry) === key);
const dualWrite = entries(env.HLX6_DUAL_WRITES, 'HLX6_DUAL_WRITES').some((entry) => {
if (typeof entry !== 'string') return false;
const [from, to, ...rest] = entry.split('->');
return !rest.length && orgSite(from) === key && (to === undefined || !!orgSite(to));
});
return migrated && !dualWrite;
}
49 changes: 49 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,55 @@ describe('Index Tests', () => {
});
});

describe('migrated sites', () => {
it('fails closed on malformed dashboard JSON before an allowlisted storage read', async () => {
const result = await worker.fetch(createRequest('https://example.com/org1/site/page', {
headers: { 'cf-connecting-ip': HELIX_ADMIN_IP },
}), createEnv({ HLX6_MIGRATED_SITES: '["org1/site"' }));
expect(result.status).to.equal(503);
expect(result.headers.get('x-error')).to.include('HLX6_MIGRATED_SITES');
});

it('uses admin before the IP allowlist and canonicalizes document URLs', async () => {
nock.admin().get('/source/org1/site/library/blocks/columns.html')
.matchHeader('authorization', 'Bearer caller')
.reply(200, 'HLX6 content', { 'content-type': 'text/html' });
const result = await worker.fetch(createRequest('https://example.com/ORG1/SITE/library/blocks/columns', {
headers: { 'cf-connecting-ip': HELIX_ADMIN_IP, authorization: 'Bearer caller' },
}), createEnv({ HLX6_MIGRATED_SITES: ['org1/site'] }));
expect(result.status).to.equal(200);
expect(await result.text()).to.equal('HLX6 content');
});

it('uses admin before image opt-out without falling back on denial', async () => {
nock.admin().get('/source/optout-org/site/logo.png').reply(401);
const result = await worker.fetch(createRequest('https://example.com/optout-org/site/logo.png'), createEnv({
ADMIN_IMAGES_OPTOUT_ORGS: 'optout-org', HLX6_MIGRATED_SITES: '["optout-org/site"]',
}));
expect(result.status).to.equal(401);
});

it('keeps a mapped dual-write source on existing storage routing', async () => {
nock.s3(S3_BUCKET_HOST).get(/\/.+/).reply(200, 'DA content', { 'content-type': 'text/html' });
const result = await worker.fetch(createRequest('https://example.com/org1/site/page', {
headers: { 'cf-connecting-ip': HELIX_ADMIN_IP },
}), createEnv({
HLX6_MIGRATED_SITES: 'org1/site', HLX6_DUAL_WRITES: 'org1/site -> target/other',
}));
expect(await result.text()).to.equal('DA content');
});

it('does not exempt a mapped dual-write target', async () => {
nock.admin().get('/source/org1/site/page.html').reply(200, 'HLX6 content');
const result = await worker.fetch(createRequest('https://example.com/org1/site/page', {
headers: { 'cf-connecting-ip': HELIX_ADMIN_IP },
}), createEnv({
HLX6_MIGRATED_SITES: 'org1/site', HLX6_DUAL_WRITES: ['source/site -> org1/site'],
}));
expect(await result.text()).to.equal('HLX6 content');
});
});

describe('S3 errors', () => {
it('returns 404 when S3 returns error', async () => {
nock.s3(S3_BUCKET_HOST)
Expand Down
4 changes: 2 additions & 2 deletions test/responses/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ describe('daResp', () => {
expect(response).to.be.instanceOf(Response);
expect(response.status).to.equal(200);
expect(response.headers.get('Access-Control-Allow-Origin')).to.equal('*');
expect(response.headers.get('Access-Control-Allow-Methods')).to.equal('GET, OPTIONS');
expect(response.headers.get('Access-Control-Allow-Headers')).to.equal('authorization');
expect(response.headers.get('Access-Control-Allow-Methods')).to.equal('GET, HEAD, OPTIONS');
expect(response.headers.get('Access-Control-Allow-Headers')).to.equal('authorization, if-match, if-none-match');
});

it('includes content type when provided', () => {
Expand Down
24 changes: 24 additions & 0 deletions test/storage/admin.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,30 @@ describe('getFromAdmin', () => {
});

describe('admin API integration', () => {
it('forwards conditional HEAD and exposes metadata without a body', async () => {
nock.admin().head('/source/org/site/page.html')
.matchHeader('if-none-match', '"revision"')
.reply(304, '', { etag: '"revision"', 'cache-control': 'private, no-store' });
const result = await getFromAdmin(createRequest('https://example.com/org/site/page', {
method: 'HEAD', headers: { 'if-none-match': '"revision"' },
}), createEnv());
expect(result.status).to.equal(304);
expect(await result.text()).to.equal('');
expect(result.headers.get('etag')).to.equal('"revision"');
expect(result.headers.get('cache-control')).to.equal('private, no-store');
expect(result.headers.get('access-control-expose-headers')).to.include('ETag');
});

it('preserves upstream error details', async () => {
nock.admin().get('/source/org/site/page.html')
.reply(429, 'limited', { 'x-error': 'receiver limit', 'retry-after': '30' });
const result = await getFromAdmin(createRequest('https://example.com/org/site/page'), createEnv());
expect(result.status).to.equal(429);
expect(await result.text()).to.equal('limited');
expect(result.headers.get('x-error')).to.equal('receiver limit');
expect(result.headers.get('retry-after')).to.equal('30');
});

it('constructs correct admin URL', async () => {
nock.admin()
.get('/source/org/site/page.html')
Expand Down
Loading