Add whitelistPolicy

This commit is contained in:
Alex Gleason 2023-03-26 15:58:37 -05:00
parent 817519c132
commit 254b0f1f11
No known key found for this signature in database
GPG Key ID: 7211D1F99744FBB7
2 changed files with 47 additions and 0 deletions

View File

@ -0,0 +1,15 @@
import { assert } from '../deps.ts';
import { buildEvent, buildInputMessage } from '../test.ts';
import whitelistPolicy from './whitelist-policy.ts';
Deno.test('allows only whitelisted pubkeys', async () => {
const msgA = buildInputMessage({ event: buildEvent({ pubkey: 'A' }) });
const msgB = buildInputMessage({ event: buildEvent({ pubkey: 'B' }) });
const msgC = buildInputMessage({ event: buildEvent({ pubkey: 'C' }) });
assert((await whitelistPolicy(msgA, [])).action === 'reject');
assert((await whitelistPolicy(msgA, ['A'])).action === 'accept');
assert((await whitelistPolicy(msgC, ['B', 'A'])).action === 'reject');
assert((await whitelistPolicy(msgB, ['B', 'A'])).action === 'accept');
});

View File

@ -0,0 +1,32 @@
import type { Policy } from '../types.ts';
/**
* Allows only the listed pubkeys to post to the relay. All other events are rejected.
* Pass an array of pubkeys or an iterable, making it efficient to load pubkeys from a large file.
*/
const whitelistPolicy: Policy<Iterable<string>> = ({ event: { id, pubkey } }, pubkeys = []) => {
let isMatch = false;
for (const p of pubkeys) {
if (p === pubkey) {
isMatch = true;
break;
}
}
if (isMatch) {
return {
id,
action: 'accept',
msg: '',
};
}
return {
id,
action: 'reject',
msg: 'Only certain pubkeys are allowed.',
};
};
export default whitelistPolicy;