import { createHash, createHmac, pbkdf2Sync, randomBytes, timingSafeEqual } from 'node:crypto';
const url = process.env.LINK4SYNC_URL;
const username = process.env.LINK4SYNC_USERNAME;
const password = process.env.LINK4SYNC_PASSWORD;
const base64 = (text) => Buffer.from(text, 'utf8').toString('base64');
const fromBase64 = (text) => Buffer.from(text, 'base64').toString('utf8');
const scramAttributes = (text) =>
Object.fromEntries(text.split(',').map((part) => [part[0], part.slice(2)]));
const authParams = (header) =>
Object.fromEntries(
header
.replace(/^SCRAM-SHA-256\s+/i, '')
.split(',')
.map((part) => {
const index = part.indexOf('=');
return [
part.slice(0, index).trim(),
part
.slice(index + 1)
.trim()
.replace(/^"|"$/g, ''),
];
}),
);
export async function publish(event) {
const body = JSON.stringify(event);
const headers = { 'Content-Type': 'application/json' };
const nonce = randomBytes(18).toString('base64url');
const user = username.replaceAll('=', '=3D').replaceAll(',', '=2C');
const clientFirstBare = `n=${user},r=${nonce}`;
const first = await fetch(url, {
method: 'POST',
redirect: 'manual',
headers: { ...headers, Authorization: `SCRAM-SHA-256 data=${base64(`n,,${clientFirstBare}`)}` },
body,
});
if (first.status !== 401) throw new Error(`Expected a SCRAM challenge, got ${first.status}`);
const challenge = authParams(first.headers.get('www-authenticate') ?? '');
const serverFirst = fromBase64(challenge.data);
const { r, s, i } = scramAttributes(serverFirst);
if (!r?.startsWith(nonce) || r.length <= nonce.length) throw new Error('Bad server nonce');
const salted = pbkdf2Sync(password, Buffer.from(s, 'base64'), Number(i), 32, 'sha256');
const clientKey = createHmac('sha256', salted).update('Client Key').digest();
const storedKey = createHash('sha256').update(clientKey).digest();
const withoutProof = `c=biws,r=${r}`;
const authMessage = `${clientFirstBare},${serverFirst},${withoutProof}`;
const signature = createHmac('sha256', storedKey).update(authMessage).digest();
const proof = Buffer.from(clientKey.map((byte, index) => byte ^ signature[index]));
const final = await fetch(url, {
method: 'POST',
redirect: 'manual',
headers: {
...headers,
Authorization: `SCRAM-SHA-256 sid=${challenge.sid},data=${base64(`${withoutProof},p=${proof.toString('base64')}`)}`,
},
body,
});
if (final.status !== 202) throw new Error(`Publish rejected with ${final.status}`);
const serverKey = createHmac('sha256', salted).update('Server Key').digest();
const expected = createHmac('sha256', serverKey).update(authMessage).digest();
const info = authParams(final.headers.get('authentication-info') ?? '');
const received = Buffer.from(scramAttributes(fromBase64(info.data ?? '')).v ?? '', 'base64');
if (received.length !== expected.length || !timingSafeEqual(received, expected)) {
throw new Error('Server signature did not match');
}
}