Update relay to current MacClient implementation

This commit is contained in:
Maddin committed 2026-10-28 00:23:32 +01:00
1 parent 9e49118e8e
commit a571721d4c
8 files changed
+1062 -33

No files matched your search

+117 -2
View File
@@ -82,6 +82,24 @@ test('relay persists opaque chunks, acknowledges and revokes pairings', async t
assert.equal(claimResponse.status, 200);
const claim = await claimResponse.json();
assert.ok(claim.relayToken);
const secondSecretHash = crypto.createHash('sha256').update('second-pairing-secret').digest('hex');
const secondOfferResponse = await postJSON(`${base}/api/v1/pairing/offers`, {
protocolVersion: 2,
secretHash: secondSecretHash,
publicKey: 'mac-key-two',
identityKey: 'mac-identity-two'
}, owner.accessToken);
assert.equal(secondOfferResponse.status, 201);
const secondOffer = await secondOfferResponse.json();
const secondClaimResponse = await postJSON(`${base}/api/v1/pairing/offers/${secondOffer.id}/claim`, {
protocolVersion: 2,
secretHash: secondSecretHash,
publicKey: 'phone-key-two',
identityKey: 'phone-identity-two'
});
assert.equal(secondClaimResponse.status, 200);
const secondClaim = await secondClaimResponse.json();
assert.ok(secondClaim.relayToken);
const persistedPairing = JSON.parse(await readFile(path.join(dataDir, 'state.json'), 'utf8')).pairingSessions[0];
assert.equal(persistedPairing.sessionToken, undefined);
assert.equal(persistedPairing.relayToken, undefined);
@@ -203,6 +221,47 @@ test('relay persists opaque chunks, acknowledges and revokes pairings', async t
const attachmentAck = await postJSON(`${attachmentPath}/${attachmentID}/ack`, {}, claim.relayToken);
assert.equal(attachmentAck.status, 200);
// Exercise the supported maximum audio size as bounded opaque chunks. Keep
// only one chunk buffer in memory while the relay stages the full payload.
const maximumAudioBytes = 500 * 1024 * 1024;
const audioChunkSize = 3 * 1024 * 1024;
const audioChunkCount = Math.ceil(maximumAudioBytes / audioChunkSize);
const largeAudioID = crypto.randomUUID();
const largeAudioManifest = await postJSON(messagePath, {
id: largeAudioID,
direction: 'attachment',
size: maximumAudioBytes,
chunkCount: audioChunkCount
}, claim.relayToken);
assert.equal(largeAudioManifest.status, 201);
let remainingAudioBytes = maximumAudioBytes;
let lastEncryptedChunk;
const reusableEncryptedChunk = Buffer.alloc(audioChunkSize + 16);
for (let index = 0; index < audioChunkCount; index++) {
const plaintextLength = Math.min(audioChunkSize, remainingAudioBytes);
const encryptedLength = plaintextLength + 16;
reusableEncryptedChunk.fill(index & 0xff, 0, encryptedLength);
const encryptedChunk = reusableEncryptedChunk.subarray(0, encryptedLength);
const response = await fetch(`${messagePath}/${largeAudioID}/chunks/${index}`, {
method: 'PUT',
headers: { authorization: `Bearer ${claim.relayToken}`, 'content-type': 'application/octet-stream' },
body: encryptedChunk
});
assert.equal(response.status, 200);
if (index === audioChunkCount - 1) lastEncryptedChunk = Buffer.from(encryptedChunk);
remainingAudioBytes -= plaintextLength;
}
assert.equal(remainingAudioBytes, 0);
const largeAudioStatus = await fetch(`${messagePath}/${largeAudioID}`, { headers: { authorization: `Bearer ${claim.relayToken}` } });
assert.equal(largeAudioStatus.status, 200);
assert.equal((await largeAudioStatus.json()).chunkCount, audioChunkCount);
const lastAudioChunkResponse = await fetch(`${messagePath}/${largeAudioID}/chunks?index=${audioChunkCount - 1}`, {
headers: { authorization: `Bearer ${claim.relayToken}` }
});
assert.deepEqual(Buffer.from(await lastAudioChunkResponse.arrayBuffer()), lastEncryptedChunk);
const largeAudioAck = await postJSON(`${messagePath}/${largeAudioID}/ack`, {}, claim.relayToken);
assert.equal(largeAudioAck.status, 200);
let listing = await fetch(relayPath, { headers: { authorization: `Bearer ${claim.relayToken}` } });
assert.deepEqual((await listing.json()).uploads.map(upload => upload.id), [id]);
const chunk = await fetch(`${relayPath}/uploads/${id}/chunks?index=0`, { headers: { authorization: `Bearer ${claim.relayToken}` } });
@@ -215,11 +274,67 @@ test('relay persists opaque chunks, acknowledges and revokes pairings', async t
assert.equal(revoke.status, 200);
const unauthorized = await fetch(relayPath, { headers: { authorization: `Bearer ${claim.relayToken}` } });
assert.equal(unauthorized.status, 401);
// Exhaust the general-purpose IP bucket and verify it cannot block the
// paired session heartbeat, which has its own pairing budget.
let defaultLimitReached = false;
let defaultLimitResponse;
for (let attempt = 0; attempt < 610; attempt++) {
const response = await fetch(`${base}/health`);
if (response.status === 429) {
defaultLimitReached = true;
defaultLimitResponse = response;
break;
}
assert.equal(response.status, 200);
}
assert.equal(defaultLimitReached, true);
assert.equal(defaultLimitResponse.headers.get('retry-after'), '60');
assert.deepEqual(await defaultLimitResponse.json(), { error: 'rate_limited', retryAfterSeconds: 60 });
const heartbeatAfterDefaultLimit = await postJSON(
`${sessionPath}/heartbeat`,
{ protocolVersion: 2, side: 'client' },
claim.sessionToken
);
assert.equal(heartbeatAfterDefaultLimit.status, 200);
// Flood one authenticated pairing while another pairing continues to poll
// concurrently from the same simulated public IP. The session-scoped limit
// must reject only the busy pairing and keep the other inbox responsive.
const sessionScopedRelayPath = `${base}/api/v1/relay/sessions/${offer.id}/messages?direction=request`;
const sameNATHeaders = { authorization: `Bearer ${claim.relayToken}`, 'x-forwarded-for': '203.0.113.19' };
const secondSessionRelayPath = `${base}/api/v1/relay/sessions/${secondOffer.id}/messages?direction=request`;
const secondSessionHeaders = { authorization: `Bearer ${secondClaim.relayToken}`, 'x-forwarded-for': '203.0.113.19' };
let sessionLimitReached = false;
for (let batch = 0; batch < 19 && !sessionLimitReached; batch++) {
const [responses, independentResponses] = await Promise.all([
Promise.all(Array.from({ length: 100 }, () => fetch(sessionScopedRelayPath, { headers: sameNATHeaders }))),
Promise.all(Array.from({ length: 50 }, () => fetch(secondSessionRelayPath, { headers: secondSessionHeaders })))
]);
assert.ok(independentResponses.every(response => response.status === 200), 'The independent pairing must remain responsive during the concurrent flood.');
sessionLimitReached = responses.some(response => response.status === 429);
}
assert.equal(sessionLimitReached, true);
const otherSessionPoll = await fetch(secondSessionRelayPath, { headers: secondSessionHeaders });
assert.equal(otherSessionPoll.status, 200);
// The Mac's long poll uses the session root. Keep that high-frequency
// endpoint in its own budget so a stuck poll cannot throttle iPhone RPCs.
const macQueuePollPath = `${base}/api/v1/relay/sessions/${secondOffer.id}?queue=mac&wait=0`;
const macQueuePolls = await Promise.all(Array.from({ length: 190 }, () => fetch(macQueuePollPath, { headers: secondSessionHeaders })));
assert.ok(macQueuePolls.some(response => response.status === 429), 'The Mac queue poll must remain bounded.');
const rpcAfterQueueFlood = await fetch(secondSessionRelayPath, { headers: secondSessionHeaders });
assert.equal(rpcAfterQueueFlood.status, 200, 'A Mac queue poll flood must not block iPhone relay RPCs.');
const revokePairing = await fetch(sessionPath, { method: 'DELETE', headers: { authorization: `Bearer ${claim.sessionToken}` } });
assert.equal(revokePairing.status, 200);
const revokeSecondPairing = await fetch(`${base}/api/v1/pairing/sessions/${secondOffer.id}`, {
method: 'DELETE', headers: { authorization: `Bearer ${secondClaim.sessionToken}` }
});
assert.equal(revokeSecondPairing.status, 200);
const afterUnpair = JSON.parse(await readFile(path.join(dataDir, 'state.json'), 'utf8'));
assert.equal(afterUnpair.pushDevices, undefined);
assert.equal(afterUnpair.pushEvents, undefined);
assert.equal(afterUnpair.pushDevices[offer.id], undefined);
assert.equal(afterUnpair.pushEvents[offer.id], undefined);
const revokedStatus = await fetch(`${sessionPath}/status`, { headers: { authorization: `Bearer ${claim.sessionToken}` } });
assert.equal(revokedStatus.status, 404);
});