Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
14 changes: 14 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Contributor instructions

## HLX6 compatibility

Every new feature or API endpoint must explicitly handle requests for projects
(`org/site`) backed by HLX6. Use the existing
[site-backend resolver](./src/utils/hlx6.js) and preserve authentication and authorization.

- Forward supported operations through the `daadmin` service binding and its
HLX6 compatibility bridge.
- Return HTTP `410 Gone` when the operation is unsupported on HLX6.
- Never fall back to legacy DA/R2 storage or direct-R2 bypasses for an unsupported
HLX6 operation or after forwarding fails.
- Add focused tests for the chosen HLX6 behavior and preserve legacy DA behavior.
59 changes: 51 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,37 @@

## 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 closed with `503` across the worker
instead of risking fallback reads from R2.
Both workers bind the same KV namespace as `DA_SITE_BACKENDS`: production uses
`DA_SITE_BACKENDS` (`90c6a793da054676b11134d647f0aeaf`) and staging uses
`DA_SITE_BACKENDS_STAGE` (`624b26551dcf4fe3bd31a08e70cda86f`).
Keys are lowercase `org/site`, with string values `da` or `hlx6`
(case and surrounding whitespace are normalized when reading).
Local development uses emulated KV.

Cache hits do not ping. Missing entries trigger an unauthenticated GET to
`https://admin.hlx.page/ping/{org}/{site}` with a 3s timeout. Set `HLX_ADMIN`
to override the probe base URL per environment (for example in `.dev.vars` or
the Cloudflare dashboard). The presence of `x-api-upgrade-available` selects
HLX6; this is a source-bus configuration heuristic, including overlays, **not
proof of completed cutover**. Explicit registry entries override it.
Successful responses without the header and 404s select DA. Successful probe
results are stored without expiration; 404 results expire after **300 seconds**,
allowing later-created sites to be detected. Concurrent cold requests own their
I/O independently, so multiple probes may occur across requests and KV locations.
Later requests read KV again.

Content routing depends only on the registry. This worker does not read
`HLX6_DUAL_WRITES`; dual-write configuration belongs exclusively to da-admin.
Before starting dual write, explicitly set the site's registry entry to `da`
so a cold ping cannot switch content reads to HLX6 during migration.
Invalid registry values, KV read failures, and probe failures fail closed with
`503` instead of risking fallback reads from R2. Failed KV writes are logged
without discarding a known probe result.
Preflight and `.gimme_cookie` requests do not consult the registry.

The 404 expiry limits entry retention, not traffic: unauthenticated requests
can still generate cold probes for arbitrary names. The registry is not a
rate limiter or an org-existence check.

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
Expand All @@ -25,8 +50,26 @@ 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.
`HLX6_MIGRATED_SITES` is no longer read. Before rollout, preload **all sites
still served by DA** (including dual-write sites) as `da`, and copy existing
migrated entries as `hlx6`. Do not blindly overwrite authoritative entries;
resolve conflicting inventory first. This avoids rollout dependence on cold
pings and prevents an overlay header from triggering premature cutover.
Manual entries have no expiration. Deploy da-admin first.

To migrate a site, pause its traffic and drain in-flight requests/probes,
update `org/site` to `hlx6` in the shared KV, and remove any dual-write source
entry in da-admin. KV changes (including cached misses) can take 60 seconds
or more to propagate: keep traffic paused until both workers' routing is
verified. A probe already in flight can overwrite a manual update, so draining
is necessary. Setting the value to `da` explicitly selects legacy storage;
deleting the entry makes the next request probe again.

## Development requirements

Every new feature or API endpoint must follow the
[HLX6 compatibility requirements](./AGENTS.md#hlx6-compatibility): forward
supported calls for HLX6-backed projects or return `410 Gone` when unsupported.

## Validation

Expand Down
7 changes: 4 additions & 3 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,14 +80,15 @@ export default {
}

if (!org || !site) return get404();
if (req.method === 'OPTIONS') return getFromAdmin(req, env);

let migrated;
try {
migrated = isHlx6Site(env, org, site);
migrated = await isHlx6Site(env, org, site);
} catch (e) {
// eslint-disable-next-line no-console
console.error('[hlx6] Migration routing configuration error', e.message);
const msg = 'Migration routing configuration error';
console.error('[hlx6] Site backend resolution failed', e.message);
const msg = 'Site backend resolution failed';
const resp = daResp({
status: 503,
body: req.method === 'HEAD' ? undefined : msg,
Expand Down
119 changes: 35 additions & 84 deletions src/utils/hlx6.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,98 +9,49 @@
* 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}`);
}
const trimmed = value.trim();
if (trimmed.startsWith('{')) {
throw new Error(`Invalid ${name}`);
}
if (!trimmed.startsWith('[')) return value.split(/[,\n]/);
try {
return JSON.parse(trimmed);
} catch {
throw new Error(`Invalid JSON in ${name}`);
}
function parseBackend(value, key) {
if (value === null) return undefined;
const backend = value.trim().toLowerCase();
if (backend === 'hlx6' || backend === 'da') return backend;
throw new Error(`Invalid site backend for ${key}`);
}

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

let migratedCache = { raw: undefined, sites: new Set() };
let dualWriteCache = { raw: undefined, sources: new Set() };

/**
* Parses and caches migrated org/site entries keyed by the raw configuration value.
* @param {string[]|string|undefined} raw Raw HLX6_MIGRATED_SITES configuration.
* @returns {Set<string>} Normalized migrated org/site keys.
* @throws {Error} If HLX6_MIGRATED_SITES cannot be parsed.
*/
function getMigratedSites(raw) {
if (migratedCache.raw === raw) return migratedCache.sites;
const sites = new Set();
entries(raw, 'HLX6_MIGRATED_SITES').forEach((entry) => {
if (typeof entry === 'string' && !entry.includes('->')) {
const parsed = orgSite(entry);
if (parsed) sites.add(parsed);
}
});
migratedCache = { raw, sites };
return sites;
}

/**
* Parses and caches valid dual-write source entries keyed by the raw configuration value.
* @param {string[]|string|undefined} raw Raw HLX6_DUAL_WRITES configuration.
* @returns {Set<string>} Normalized dual-write source org/site keys.
* @throws {Error} If HLX6_DUAL_WRITES cannot be parsed.
*/
function getDualWriteSources(raw) {
if (dualWriteCache.raw === raw) return dualWriteCache.sources;
const sources = new Set();
entries(raw, 'HLX6_DUAL_WRITES').forEach((entry) => {
if (typeof entry !== 'string') return;
const [from, to, ...rest] = entry.split('->');
const source = orgSite(from);
if (!rest.length && source && (to === undefined || !!orgSite(to))) {
sources.add(source);
}
async function detectHlx6Site(namespace, key, hlxAdmin) {
const cached = parseBackend(await namespace.get(key), key);
if (cached !== undefined) return cached === 'hlx6';
const base = (hlxAdmin || 'https://admin.hlx.page').replace(/\/+$/, '');
const path = key.split('/').map(encodeURIComponent).join('/');
const resp = await fetch(`${base}/ping/${path}`, {
method: 'GET', redirect: 'manual', signal: AbortSignal.timeout(3000),
});
dualWriteCache = { raw, sources };
return sources;
await resp.body?.cancel();
// Unregistered sites may be created later, so their DA result is short-lived.
if (!resp.ok && resp.status !== 404) {
throw new Error(`Site backend probe failed for ${key}: ${resp.status}`);
}
const migrated = resp.headers.has('x-api-upgrade-available');
try {
await namespace.put(key, migrated ? 'hlx6' : 'da', resp.status === 404 ? { expirationTtl: 300 } : undefined);
} catch (e) {
// eslint-disable-next-line no-console
console.error('[hlx6] Failed to cache site backend', key, e.message);
}
return migrated;
}

/**
* 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.
* Resolves the shared site registry, probing missing entries.
* Request-scoped I/O is never shared between Worker requests.
* @param {Object} env Worker bindings.
* @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.
* @returns {Promise<boolean>} Whether requests must use admin rather than direct R2.
* @throws {Error} If registry access or the ping fails.
*/
export default function isHlx6Site(env, org, site) {
export default async function isHlx6Site(env, org, site) {
if (!org || !site) return false;
const key = `${org}/${site}`.toLowerCase();
const migrated = getMigratedSites(env.HLX6_MIGRATED_SITES);
const dualWrite = getDualWriteSources(env.HLX6_DUAL_WRITES);
return migrated.has(key) && !dualWrite.has(key);
const namespace = env.DA_SITE_BACKENDS;
if (!namespace) throw new Error('Missing DA_SITE_BACKENDS binding');
return detectHlx6Site(namespace, key, env.HLX_ADMIN);
}
50 changes: 24 additions & 26 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ function createEnv(overrides = {}) {
S3_ACCESS_KEY_ID: 'test-key',
S3_SECRET_ACCESS_KEY: 'test-secret',
daadmin: { fetch: globalThis.fetch },
DA_SITE_BACKENDS: { get: async () => 'da' },
...overrides,
};
}
Expand Down Expand Up @@ -247,35 +248,41 @@ describe('Index Tests', () => {
});

describe('migrated sites', () => {
it('fails closed on malformed dashboard JSON before an allowlisted storage read without leaking var names', async () => {
it('fails closed on invalid registry entries 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"' }));
}), createEnv({ DA_SITE_BACKENDS: { get: async () => 'invalid' } }));
expect(result.status).to.equal(503);
expect(result.headers.get('x-error')).to.equal('Migration routing configuration error');
expect(result.headers.get('x-error')).to.equal('Site backend resolution failed');
expect(result.headers.get('access-control-expose-headers')).to.equal('x-error');
expect(await result.text()).to.equal('Migration routing configuration error');
expect(await result.text()).to.equal('Site backend resolution failed');
});

it('omits body on HEAD when migration configuration is malformed', async () => {
it('omits body on HEAD when the registry read fails', async () => {
const result = await worker.fetch(createRequest('https://example.com/org1/site/page', {
method: 'HEAD',
headers: { 'cf-connecting-ip': HELIX_ADMIN_IP },
}), createEnv({ HLX6_DUAL_WRITES: '["org1/site"' }));
}), createEnv({
DA_SITE_BACKENDS: {
get: async () => {
throw new Error('KV unavailable');
},
},
}));
expect(result.status).to.equal(503);
expect(result.headers.get('x-error')).to.equal('Migration routing configuration error');
expect(result.headers.get('x-error')).to.equal('Site backend resolution failed');
expect(await result.text()).to.equal('');
});

it('normalizes percent-encoded, dot, and empty path segments before migration checks and rejects traversal', async () => {
nock.admin().get('/source/optout-org/site/logo.png').reply(401);
const encoded = await worker.fetch(createRequest('https://example.com//optout-org/./%73ite/logo.png'), createEnv({
ADMIN_IMAGES_OPTOUT_ORGS: 'optout-org', HLX6_MIGRATED_SITES: '["optout-org/site"]',
ADMIN_IMAGES_OPTOUT_ORGS: 'optout-org', DA_SITE_BACKENDS: { get: async () => 'hlx6' },
}));
expect(encoded.status).to.equal(401);

const traversal = await worker.fetch(createRequest('https://example.com/optout-org/other/..%2Fsite/logo.png'), createEnv({
ADMIN_IMAGES_OPTOUT_ORGS: 'optout-org', HLX6_MIGRATED_SITES: '["optout-org/site"]',
ADMIN_IMAGES_OPTOUT_ORGS: 'optout-org', DA_SITE_BACKENDS: { get: async () => 'hlx6' },
}));
expect(traversal.status).to.equal(404);

Expand All @@ -286,13 +293,13 @@ describe('Index Tests', () => {
it('preserves OPTIONS and .gimme_cookie locally on migrated sites', async () => {
const optionsRes = await worker.fetch(
createRequest('https://example.com/org1/site/page', { method: 'OPTIONS' }),
createEnv({ HLX6_MIGRATED_SITES: ['org1/site'] }),
createEnv({ DA_SITE_BACKENDS: { get: async () => { throw new Error('Must not read KV'); } } }),
);
expect(optionsRes.status).to.equal(200);

const cookieRes = await worker.fetch(
createRequest('https://example.com/org1/site/.gimme_cookie', { headers: { Origin: 'https://da.live' } }),
createEnv({ HLX6_MIGRATED_SITES: ['org1/site'] }),
createEnv({ DA_SITE_BACKENDS: { get: async () => { throw new Error('Must not read KV'); } } }),
);
expect(cookieRes.status).to.equal(401);
});
Expand All @@ -312,36 +319,27 @@ describe('Index Tests', () => {
.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'] }));
}), createEnv({ DA_SITE_BACKENDS: { get: async () => 'hlx6' } }));
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"]',
ADMIN_IMAGES_OPTOUT_ORGS: 'optout-org', DA_SITE_BACKENDS: { get: async () => 'hlx6' },
}));
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' });
it('follows the HLX6 registry entry despite a legacy dual-write source flag', async () => {
nock.admin().get('/source/org1/site/page.html').reply(200, 'HLX6 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'],
DA_SITE_BACKENDS: { get: async () => 'hlx6' }, HLX6_DUAL_WRITES: 'org1/site -> target/other',
}));
expect(result.status).to.equal(200);
expect(await result.text()).to.equal('HLX6 content');
});
});
Expand Down
Loading
Loading