Skip to content
Merged
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
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,17 @@ are transmitted.

## Resolve local Git conflicts with Sweetiebot

For **Resolve and sync with Lindsey**, Sweetiebot discovers this server from
the Lindsey App's HTTPS `/webhook` URL. It signs a short-lived request for the
publishing repository using the key saved in Magic Settings. The server
verifies the proof and checks the repository's App installation in GitHub.
The server trusts the public key derived from `GITHUB_PRIVATE_KEY` by default.
If Magic Settings uses a different key for the same App, set
`LINDSEY_RESOLVE_PUBLIC_KEY` on the server to that key's public PEM.

The standalone preview CLI and older Sweetiebot releases use the shared-secret
flow below. Leave `LINDSEY_RESOLVE_SECRET` unset to disable that legacy flow.

The companion Sweetiebot conflict-recovery action looks for this repository in a
sibling `lindsey-sync` directory, any open VS Code workspace folder, or the
directory named by `LINDSEY_SYNC_REPO`. Both repositories must be checked out
Expand Down
36 changes: 23 additions & 13 deletions scripts/resolve-conflicts.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,29 +90,39 @@ export async function main(args = process.argv.slice(2), env = process.env, fetc
const secret = env.LINDSEY_RESOLVE_SECRET?.trim();
if (!secret) throw new Error('Set LINDSEY_RESOLVE_SECRET in Sweetiebot’s local environment');
const endpoint = validateEndpoint(env.LINDSEY_RESOLVE_URL || '');
const manifest = await prepareConflictPreview(repo, output, async request => {
const response = await fetchImpl(endpoint, {
method: 'POST', redirect: 'error',
headers: { Authorization: 'Bearer ' + secret, 'Content-Type': 'application/json' },
body: JSON.stringify(request),
signal: AbortSignal.timeout(120000)
});
const reply = await response.json();
if (!response.ok || !reply.ok) {
throw new Error(reply.error || 'Lindsey resolve endpoint HTTP ' + response.status);
}
return reply;
});
process.stdout.write(JSON.stringify(manifest) + '\n');
return manifest;
}

export async function prepareConflictPreview(repo, output, requestResolution) {
if (!path.isAbsolute(repo) || !path.isAbsolute(output) || repo === output || output.startsWith(repo + path.sep)) {
throw new Error('Provide a repository and a separate output directory outside its worktree');
}
const { request, originals } = await collectConflictRequest(repo);
await mkdir(output, { recursive: true });
if (!(await lstat(output)).isDirectory()) throw new Error('Output is not a directory');
const response = await fetchImpl(endpoint, {
method: 'POST',
headers: { Authorization: 'Bearer ' + secret, 'Content-Type': 'application/json' },
body: JSON.stringify(request),
signal: AbortSignal.timeout(120000)
});
const reply = await response.json();
if (!response.ok || !reply.ok) {
throw new Error(reply.error || 'Lindsey resolve endpoint HTTP ' + response.status);
}
const reply = await requestResolution(request);
const validated = validateResolutionOutput(reply, request.files);
const files = [];
for (const [i, result] of validated.resolutions.entries()) {
const filename = 'candidate-' + i + '.txt';
await writeFile(path.join(output, filename), result.contents, { flag: 'wx', mode: 0o600 });
files.push({ path: result.path, candidate: filename, originalSha: originals.get(result.path) });
}
const manifest = { version: 1, branch: request.branch, head: request.head, files };
process.stdout.write(JSON.stringify(manifest) + '\n');
return manifest;
return { version: 1, branch: request.branch, head: request.head, files };
}

if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
Expand Down
40 changes: 40 additions & 0 deletions src/resolve-auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { createHash, createPublicKey, verify } from 'node:crypto';
import { createAppJwt, githubRequest, GitHubHttpError } from './bot.js';

const proofLifetime = 60;

export function createResolverAuthorizer(config, { request = githubRequest, now = Date.now } = {}) {
const normalize = value => value.replace(/\\n/g, '\n');
const keys = [createPublicKey(normalize(config.privateKey))];
if (config.resolvePublicKey) keys.push(createPublicKey(normalize(config.resolvePublicKey)));
const used = new Map();

return async (method, headers, body) => {
const app = headers['x-lindsey-app'];
const repository = headers['x-lindsey-repository'];
const time = headers['x-lindsey-time'];
const nonce = headers['x-lindsey-nonce'];
const proof = headers['x-lindsey-proof'];
const seconds = Math.floor(now() / 1000);
if (app !== config.appId || !/^[\w.-]+\/[\w.-]+$/.test(repository || '') ||
repository.split('/').some(part => part === '.' || part === '..') ||
!/^\d{10}$/.test(time || '') || Math.abs(seconds - Number(time)) > proofLifetime ||
!/^[a-f0-9-]{36}$/.test(nonce || '') || !/^[\w-]{100,1024}$/.test(proof || '')) return false;

const digest = createHash('sha256').update(body).digest('hex');
const signed = Buffer.from(['lindsey-resolver-v1', method, app, repository, time, nonce, digest].join('\n'));
if (!keys.some(key => verify('RSA-SHA256', signed, key, Buffer.from(proof, 'base64url')))) return false;

for (const [id, expires] of used) if (expires < seconds) used.delete(id);
if (used.has(nonce) || used.size >= 4096) return false;
used.set(nonce, Number(time) + proofLifetime);
try {
const { data } = await request(`/repos/${repository}/installation`,
createAppJwt(config.appId, config.privateKey), { redirect: 'error', signal: AbortSignal.timeout(15000) });
return Number.isSafeInteger(data?.id) && String(data.app_id) === config.appId && !data.suspended_at;
} catch (error) {
if (error instanceof GitHubHttpError && error.status === 404) return false;
throw new Error('GitHub could not verify the Lindsey repository installation.');
}
};
}
23 changes: 20 additions & 3 deletions src/server.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { createServer } from 'node:http';
import { authorizeCommit, commitAsLindsey, CommitValidationError } from './commit.js';
import { resolveConflicts, ResolutionValidationError } from './resolve.js';
import { createResolverAuthorizer } from './resolve-auth.js';

import {
handleReviewRequested,
Expand Down Expand Up @@ -32,6 +33,7 @@ function configFromEnv() {
return {
commitSecret,
resolveSecret: process.env.LINDSEY_RESOLVE_SECRET?.trim() || '',
resolvePublicKey: process.env.LINDSEY_RESOLVE_PUBLIC_KEY?.trim() || '',
commitInstallationId,
commitRepositories,
appId: requiredEnv('GITHUB_APP_ID'),
Expand Down Expand Up @@ -70,6 +72,7 @@ function sendJson(res, status, value) {
}

const config = configFromEnv();
const authorizeResolver = createResolverAuthorizer(config);
const host = process.env.HOST?.trim() || '0.0.0.0';
const port = Number(process.env.PORT || 8788);

Expand Down Expand Up @@ -104,13 +107,27 @@ const server = createServer(async (req, res) => {
}


if (req.method === 'POST' && url.pathname === '/resolve-conflicts') {
if (!authorizeCommit(req.headers.authorization, config.resolveSecret)) {
if (['GET', 'POST'].includes(req.method) && url.pathname === '/resolve-conflicts') {
const signed = req.headers['x-lindsey-proof'] !== undefined;
const legacy = req.method === 'POST' && !signed && authorizeCommit(req.headers.authorization, config.resolveSecret);
if (!signed && !legacy) {
res.writeHead(401).end('Unauthorized');
return;
}
try {
const rawBody = await readBody(req, 1024 * 1024);
const rawBody = req.method === 'POST' ? await readBody(req, 1024 * 1024) : Buffer.alloc(0);
if (signed && !await authorizeResolver(req.method, req.headers, rawBody)) {
res.writeHead(401).end('Unauthorized');
return;
}
if (req.method === 'GET') {
if (!config.openaiApiKey) {
sendJson(res, 503, { ok: false, error: 'The Lindsey resolver model is not configured.' });
return;
}
sendJson(res, 200, { ok: true, authentication: 'lindsey-app-v1' });
return;
}
const payload = JSON.parse(rawBody.toString('utf8'));
const resolution = await resolveConflicts(payload, config);
sendJson(res, 200, { ok: true, ...resolution });
Expand Down
34 changes: 34 additions & 0 deletions test/resolve-auth.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import assert from 'node:assert/strict';
import { createHash, generateKeyPairSync, randomUUID, sign } from 'node:crypto';
import test from 'node:test';
import { createResolverAuthorizer } from '../src/resolve-auth.js';

test('resolver verifies signed request bytes and the named installation', async () => {
const { privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
const now = 1782000000000;
let checks = 0;
const authorize = createResolverAuthorizer({ appId: '42', privateKey: privateKey.export({ type: 'pkcs8', format: 'pem' }) }, {
now: () => now,
request: async path => {
checks++;
assert.equal(path, '/repos/owner/repo/installation');
return { data: { id: 1, app_id: 42, suspended_at: checks > 1 ? '2026-06-01' : null } };
}
});
const body = Buffer.from('{"files":[]}');
const headers = (time = String(now / 1000)) => {
const nonce = randomUUID(), digest = createHash('sha256').update(body).digest('hex');
const input = ['lindsey-resolver-v1', 'POST', '42', 'owner/repo', time, nonce, digest].join('\n');
return { 'x-lindsey-app': '42', 'x-lindsey-repository': 'owner/repo', 'x-lindsey-time': time,
'x-lindsey-nonce': nonce, 'x-lindsey-proof': sign('RSA-SHA256', Buffer.from(input), privateKey).toString('base64url') };
};
const proof = headers();
assert.equal(await authorize('GET', proof, body), false);
assert.equal(await authorize('POST', proof, Buffer.from('modified')), false);
assert.equal(await authorize('POST', { ...proof, 'x-lindsey-repository': 'owner/other' }, body), false);
assert.equal(await authorize('POST', headers(String(now / 1000 - 61)), body), false);
assert.equal(await authorize('POST', proof, body), true);
assert.equal(await authorize('POST', proof, body), false);
assert.equal(checks, 1);
assert.equal(await authorize('POST', headers(), body), false, 'The signed repo installation is suspended');
});
Loading