secajs/src/services/nostrService.js
2025-03-07 15:11:34 +01:00

126 lines
3.3 KiB
JavaScript

const uuid = require('uuid');
const crypto = require('crypto');
const { Op } = require('sequelize');
const { verifyEvent } = require('nostr-tools');
class NostrServiceProvider {
constructor({ models, constants, errors }) {
this.models = models;
this.constants = constants;
this.errors = errors;
}
provide() {
const createNostrChallenge = async () => {
const currentTimestamp = new Date();
const expiryTimestamp = new Date(currentTimestamp.getTime());
expiryTimestamp.setSeconds(
expiryTimestamp.getSeconds() +
this.constants.DEFAULT_NOSTR_CHALLENGE_DURATION_SECONDS
);
const nostrChallenge = await this.models.NostrChallengeCreated.create({
uuid: uuid.v7(),
challenge: crypto.randomBytes(32).toString('hex'),
expires_at: expiryTimestamp.toISOString(),
created_at: currentTimestamp.toISOString(),
});
return nostrChallenge;
};
const getNostrChallenge = async (
nostrChallengeUuid = null,
challenge = null
) => {
if (nostrChallengeUuid) {
return await this.models.NostrChallengeCreated.findOne({
where: {
uuid: nostrChallengeUuid,
},
});
}
if (challenge) {
return await this.models.NostrChallengeCreated.findOne({
where: {
challenge,
},
});
}
throw Error('You need to pass a uuid or a challenge.');
};
const verifyNostrChallenge = async (signedEvent) => {
const challengeTag = signedEvent.tags.find(
(tag) => tag[0] === 'challenge'
);
const challenge = challengeTag[1];
if (!(await isNostrChallengeFresh(challenge))) {
throw new this.errors.ExpiredError(
'Challenge expired, request new one.'
);
}
if (await hasNostrChallengeBeenCompleted(challenge)) {
throw new this.errors.AlreadyUsedError(
'Challenge already used, request new one.'
);
}
const isSignatureValid = verifyEvent(signedEvent);
if (!isSignatureValid) {
throw new this.errors.InvalidSignatureError('Signature is not valid.');
}
return await this.models.NostrChallengeCompleted.create({
uuid: uuid.v7(),
challenge: challenge,
signed_event: signedEvent,
public_key: signedEvent.pubkey,
created_at: new Date().toISOString(),
});
};
const isNostrChallengeFresh = async (challengeString) => {
const nostrChallenge = await this.models.NostrChallengeCreated.findOne({
where: {
challenge: challengeString,
expires_at: {
[Op.gt]: new Date(),
},
},
});
if (nostrChallenge) {
return true;
}
return false;
};
const hasNostrChallengeBeenCompleted = async (challengeString) => {
const completedNostrChallenge =
await this.models.NostrChallengeCompleted.findOne({
where: {
challenge: challengeString,
},
});
if (completedNostrChallenge) {
return true;
}
return false;
};
return {
createNostrChallenge,
getNostrChallenge,
verifyNostrChallenge,
isNostrChallengeFresh,
hasNostrChallengeBeenCompleted,
};
}
}
module.exports = NostrServiceProvider;