import { createReconciliation } from './reconciliation.mjs'; import { timingSafeEqual } from 'node:crypto'; import { planIssueImport } from '../core/planner.mjs'; import { newCheckpoint, validateRuntimeCheckpoint } from '../core/executor.mjs'; import { resolveConfiguration, oauthScope } from './configuration.mjs'; import { exportGithubIssues } from './github.mjs'; import { createStateStore, projectKey } from './storage.mjs'; import { LocalFailure, failureResponse } from './errors.mjs'; const responseHeaders = { 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'no-referrer' }; const json = (value, status = 200) => Response.json(value, { status, headers: responseHeaders }); const initialState = () => ({ version: 1, configuration: null, plan: null, checkpoint: null, verification: null, lastError: null }); const equal = (a, b) => typeof a === 'string' && Buffer.byteLength(a) === Buffer.byteLength(b) && timingSafeEqual(Buffer.from(a), Buffer.from(b)); const hasProgress = checkpoint => Object.keys(checkpoint?.entries ?? {}).length > 0 || Object.keys(checkpoint?.inFlight ?? {}).length > 0 || Object.keys(checkpoint?.attachments ?? {}).length > 0; async function body(request, maximum = 64 * 1024 * 1024) { const length = Number(request.headers.get('content-length')); if (Number.isFinite(length) && length > maximum) throw new LocalFailure('REQUEST_TOO_LARGE', 413); const reader = request.body?.getReader(); if (!reader) return {}; const chunks = []; let bytes = 0; try { while (true) { const { value, done } = await reader.read(); if (done) break; bytes += value.byteLength; if (bytes > maximum) { await reader.cancel(); throw new LocalFailure('REQUEST_TOO_LARGE', 413); } chunks.push(value); } } finally { reader.releaseLock(); } if (!bytes) return {}; const buffer = new Uint8Array(bytes); let offset = 0; for (const chunk of chunks) { buffer.set(chunk, offset); offset += chunk.byteLength; } try { return JSON.parse(new TextDecoder().decode(buffer)); } catch { throw new LocalFailure('INVALID_JSON'); } } function download(value, name) { return new Response(JSON.stringify(value, null, 2), { headers: { ...responseHeaders, 'Content-Type': 'application/json', 'Content-Disposition': `attachment; filename="${name}"` } }); } /** * @param {{stateDirectory: string, origin: string, nonce: string, fetcher?: typeof fetch, exportIssues?: Function, planner?: Function, resolve?: Function, validateCheckpoint?: Function, scanRecords?: Function, readRecord?: Function, dependencyScan?: Function, now?: Function}} options */ export function createMigratorHandler({ stateDirectory, origin, nonce, fetcher = fetch, exportIssues = exportGithubIssues, planner = planIssueImport, resolve = resolveConfiguration, validateCheckpoint = validateRuntimeCheckpoint, scanRecords, readRecord, dependencyScan, now }) { const localOrigin = new URL(origin); if (localOrigin.protocol !== 'http:' || localOrigin.hostname !== '127.0.0.1' || !nonce || typeof nonce !== 'string') throw new Error('A loopback origin and per-launch nonce are required'); const store = createStateStore(stateDirectory); let state = store.load() ?? initialState(); // Required permission changes alter the OAuth client ID. Refresh only this // derived metadata; an existing import plan and its receipts remain intact. if (state.configuration && state.configuration.scope !== oauthScope(state.configuration.repoDid)) { state.configuration = { ...state.configuration, scope: oauthScope(state.configuration.repoDid) }; store.save(state); } const reconciliation = createReconciliation({ getState: () => state, commitState: next => { store.save(next); state = next; }, resolve, fetcher, ...(scanRecords ? { scan: scanRecords } : {}), ...(readRecord ? { readRecord } : {}), ...(dependencyScan ? { dependencyScan } : {}), ...(now ? { now } : {}) }); let planning = false; const persist = () => { if (state.configuration) store.save(state); }; const configured = () => { if (!state.configuration) throw new LocalFailure('CONFIGURATION_REQUIRED', 409); }; return async request => { const url = new URL(request.url); if (!url.pathname.startsWith('/api/')) return null; try { if (url.origin !== localOrigin.origin || request.headers.get('host') !== localOrigin.host) throw new LocalFailure('WRONG_HOST', 403); const requestOrigin = request.headers.get('origin'); if (requestOrigin && requestOrigin !== localOrigin.origin) throw new LocalFailure('WRONG_ORIGIN', 403); if (!equal(request.headers.get('x-local-nonce'), nonce)) throw new LocalFailure('LOCAL_AUTHENTICATION_REQUIRED', 403); if (!['GET', 'HEAD'].includes(request.method) && requestOrigin !== localOrigin.origin) throw new LocalFailure('ORIGIN_REQUIRED', 403); if (request.method === 'POST' && ['/api/reconciliation/check', '/api/reconciliation/retry', '/api/reconciliation/delete/prepare', '/api/reconciliation/delete/finish'].includes(url.pathname)) { configured(); const input = await body(request, 16384); const result = url.pathname.endsWith('/prepare') ? await reconciliation.prepareDelete(input) : url.pathname.endsWith('/finish') ? await reconciliation.finishDelete(input) : url.pathname.endsWith('/check') ? await reconciliation.check(input) : await reconciliation.retry(input); persist(); return json(result); } if (request.method === 'GET' && url.pathname === '/api/state') return json(state); if (request.method === 'GET' && url.pathname === '/api/config') { configured(); const fresh = await resolve(state.configuration, { fetcher }); if (fresh.repoDid !== state.configuration.repoDid || fresh.actorDid !== state.configuration.actorDid || fresh.ownerDid !== state.configuration.ownerDid || fresh.knot !== state.configuration.knot || fresh.serviceAudience !== state.configuration.serviceAudience) throw new LocalFailure('CONFIGURATION_IDENTITY_CHANGED', 409); return json(fresh); } if (request.method === 'POST' && url.pathname === '/api/configure') { if (planning) throw new LocalFailure('PLAN_IN_PROGRESS', 409); const configuration = await resolve(await body(request, 16 * 1024), { fetcher }); const saved = store.forConfiguration(configuration); state = saved ? { ...saved, configuration, lastError: null } : { ...initialState(), configuration }; store.save(state, true); return json(state); } if (request.method === 'POST' && url.pathname === '/api/plan') { configured(); if (planning) throw new LocalFailure('PLAN_IN_PROGRESS', 409); const input = await body(request); const configuration = state.configuration, selected = projectKey(configuration); planning = true; try { const issues = input.issues ?? await exportIssues(configuration.sourceRepository); const plan = planner(issues, { repository: configuration.sourceRepository, repoDid: configuration.repoDid }); if (selected !== projectKey(state.configuration)) throw new LocalFailure('CONFIGURATION_CHANGED', 409); if (hasProgress(state.checkpoint) && state.plan?.planHash !== plan.planHash) throw new LocalFailure('PLAN_CHANGED_AFTER_WRITES', 409); if (state.plan?.planHash !== plan.planHash) { state.plan = plan; state.checkpoint = newCheckpoint(plan); state.verification = null; } state.lastError = null; persist(); return json(state); } finally { planning = false; } } if (request.method === 'GET' && ['/api/plan', '/api/plan/download'].includes(url.pathname)) { if (!state.plan) throw new LocalFailure('PLAN_REQUIRED', 409); return url.pathname.endsWith('/download') ? download(state.plan, 'tangled-migration-plan.json') : json(state.plan); } if (request.method === 'GET' && url.pathname === '/api/checkpoint') return json(state.checkpoint); if (request.method === 'PUT' && url.pathname === '/api/checkpoint') { if (!state.plan) throw new LocalFailure('PLAN_REQUIRED', 409); const { checkpoint } = await body(request); const selectedProject = projectKey(state.configuration), selectedPlan = state.plan.planHash; try { await validateCheckpoint(state.plan, checkpoint); } catch { throw new LocalFailure('CHECKPOINT_INVALID', 409); } // Validation hashes asynchronously. A different tab may select another // project or replace the plan while that work is in flight. if (!state.configuration || projectKey(state.configuration) !== selectedProject || state.plan?.planHash !== selectedPlan) throw new LocalFailure('CONFIGURATION_CHANGED', 409); if (JSON.stringify(checkpoint.retryGenerations ?? {}) !== JSON.stringify(state.checkpoint?.retryGenerations ?? {})) throw new LocalFailure('CHECKPOINT_REGRESSION', 409); if (hasProgress(state.checkpoint) && checkpoint.startedAt !== state.checkpoint.startedAt) throw new LocalFailure('CHECKPOINT_REGRESSION', 409); const attachmentStages = ['BlobVerified', 'ArtifactAttempted', 'ArtifactWritten', 'ArtifactAttested']; for (const [id, next] of Object.entries(checkpoint.attachments ?? {})) { const previous = state.checkpoint?.attachments?.[id]; const before = previous ? attachmentStages.indexOf(previous.stage) : -1; const after = attachmentStages.indexOf(next.stage); if (after < 0 || after < before || after > before + 1) throw new LocalFailure('CHECKPOINT_REGRESSION', 409); if (previous) { const immutable = ['sha256', 'size', 'mimeType', 'fileName', 'blob', 'downloadUrl', 'subjectOid', 'record', 'attestationRkey', 'attestationCreatedAt']; if (immutable.some(key => JSON.stringify(previous[key]) !== JSON.stringify(next[key]))) throw new LocalFailure('CHECKPOINT_REGRESSION', 409); if (before >= 2 && ['uri', 'cid', 'change'].some(key => JSON.stringify(previous[key]) !== JSON.stringify(next[key]))) throw new LocalFailure('CHECKPOINT_REGRESSION', 409); } } if (Object.keys(state.checkpoint?.attachments ?? {}).some(id => !checkpoint.attachments?.[id])) throw new LocalFailure('CHECKPOINT_REGRESSION', 409); for (const [id, previous] of Object.entries(state.checkpoint?.entries ?? {})) { const next = checkpoint.entries[id]; const stages = previous.protocol === 'server-minted' ? { written: ['written', 'attested', 'attested-open'], 'attested-open': ['attested-open', 'state-written'], 'state-written': ['state-written', 'attested'], attested: ['attested'] } : { written: ['written', 'attested'], attested: ['attested'] }; // A finalized ticket is a guarded revision of the same record. Only // that durable stage boundary can replace its CID/change receipt. const revision = previous.protocol === 'server-minted' && previous.stage === 'attested-open' && next?.stage === 'state-written'; const immutable = ['uri', 'protocol', 'writtenRecordHash', 'recordHash', 'sourceHash', 'subjectCid', 'attestationRkey', 'attestationCreatedAt', 'desiredRecord', 'initialCid', 'initialChange', 'finalAttestationRkey', 'finalAttestationCreatedAt']; if (!next || !stages[previous.stage]?.includes(next.stage) || immutable.some(key => JSON.stringify(next[key]) !== JSON.stringify(previous[key])) || (!revision && (next.cid !== previous.cid || JSON.stringify(next.change) !== JSON.stringify(previous.change) || JSON.stringify(next.actualRecord) !== JSON.stringify(previous.actualRecord)))) throw new LocalFailure('CHECKPOINT_REGRESSION', 409); } for (const [id, previous] of Object.entries(state.checkpoint?.inFlight ?? {})) { const next = checkpoint.inFlight[id] ?? checkpoint.entries[id]; if (!next || (previous.createAttempted && (!next.createAttempted && !checkpoint.entries[id] || next.protocol !== previous.protocol)) || next.attestationRkey !== previous.attestationRkey || next.attestationCreatedAt !== previous.attestationCreatedAt) throw new LocalFailure('CHECKPOINT_REGRESSION', 409); } const nextState = { ...state, checkpoint, verification: null, lastError: null }; store.save(nextState); state = nextState; return json({ checkpoint }); } if (request.method === 'POST' && url.pathname === '/api/verification') { if (!state.plan || !state.checkpoint) throw new LocalFailure('PLAN_REQUIRED', 409); const { verification } = await body(request, 1024 * 1024); if (!verification || typeof verification !== 'object' || verification.planHash !== state.plan.planHash) throw new LocalFailure('VERIFICATION_INVALID', 409); if (verification.complete === true && !state.plan.operations.every(op => state.checkpoint.entries[op.id]?.stage === 'attested')) throw new LocalFailure('VERIFICATION_INCOMPLETE', 409); state.verification = verification; persist(); return json({ verification }); } if (request.method === 'GET' && url.pathname === '/api/receipt') { if (!state.plan) throw new LocalFailure('PLAN_REQUIRED', 409); return download({ version: 1, configuration: state.configuration, planHash: state.plan.planHash, counts: state.plan.counts, mapping: state.plan.mapping.map(item => ({ ...item, uri: state.checkpoint?.entries[item.operationId]?.uri ?? item.uri })), checkpoint: state.checkpoint, verification: state.verification, reconciliations: state.reconciliations ?? [] }, 'tangled-migration-receipt.json'); } return json({ error: { code: 'NOT_FOUND' } }, 404); } catch (error) { const failure = failureResponse(error); if (failure.status !== 403 && state.configuration) { state.lastError = { code: failure.code }; try { persist(); } catch { return json({ error: { code: 'STATE_PERSISTENCE_FAILED' } }, 500); } } return json({ error: { code: failure.code } }, failure.status); } }; }