|
| 1 | +import { Injectable, UnauthorizedException } from '@nestjs/common'; |
| 2 | +import { PassportStrategy } from '@nestjs/passport'; |
| 3 | +import { Event, verifyEvent } from 'nostr-tools'; |
| 4 | +import { Request } from 'express'; |
| 5 | +import { Strategy } from 'passport-strategy'; |
| 6 | + |
| 7 | +@Injectable() |
| 8 | +export class Nip98Strategy extends PassportStrategy(Strategy, 'nip98') { |
| 9 | + public Scheme = 'Nostr'; |
| 10 | + |
| 11 | + constructor() { |
| 12 | + super(); |
| 13 | + } |
| 14 | + |
| 15 | + authenticate(req: unknown) { |
| 16 | + const request = req as Request |
| 17 | + const authHeader = request.headers['authorization']; |
| 18 | + |
| 19 | + if (!authHeader) { |
| 20 | + return this.fail(new UnauthorizedException('Missing Authorization header'), 401); |
| 21 | + } |
| 22 | + |
| 23 | + if (authHeader.slice(0, 5) !== this.Scheme) { |
| 24 | + return this.fail(new UnauthorizedException('Invalid auth scheme'), 401); |
| 25 | + } |
| 26 | + |
| 27 | + const token = authHeader.slice(6); |
| 28 | + |
| 29 | + const bToken = Buffer.from(token, 'base64').toString('utf-8'); |
| 30 | + |
| 31 | + if (!bToken || bToken.length === 0 || bToken[0] != '{') { |
| 32 | + return this.fail(new UnauthorizedException('Invalid token'), 401); |
| 33 | + } |
| 34 | + |
| 35 | + const ev = JSON.parse(bToken) as Event; |
| 36 | + |
| 37 | + const isValidEvent = verifyEvent(ev); |
| 38 | + if (!isValidEvent) { |
| 39 | + return this.fail(new UnauthorizedException('Invalid event'), 401); |
| 40 | + } |
| 41 | + |
| 42 | + if (ev.kind != 27_235) { |
| 43 | + return this.fail(new UnauthorizedException('Invalid nostr event, wrong kind'), 401); |
| 44 | + } |
| 45 | + |
| 46 | + const now = Date.now(); |
| 47 | + const diffTime = Math.abs(ev.created_at * 1000 - now); |
| 48 | + |
| 49 | + // if (diffTime < 1 * 60 * 1000) { // 1 min |
| 50 | + // return this.fail(new UnauthorizedException('Invalid nostr event, timestamp out of range'), 401); |
| 51 | + // } |
| 52 | + |
| 53 | + const urlTag = ev.tags[0]?.[1]; |
| 54 | + const methodTag = ev.tags[1]?.[1]; |
| 55 | + const a = new URL(urlTag!).pathname; |
| 56 | + console.log(new URL(urlTag!).pathname == request.path); |
| 57 | + if (!urlTag || new URL(urlTag).pathname !== request.path) { |
| 58 | + return this.fail(new UnauthorizedException('Invalid nostr event, URL tag invalid'), 401); |
| 59 | + } |
| 60 | + |
| 61 | + if (!methodTag || methodTag.toLowerCase() !== request.method.toLowerCase()) { |
| 62 | + return { success: false, message: 'Invalid nostr event, method tag invalid' }; |
| 63 | + } |
| 64 | + |
| 65 | + this.success({ pubkey: ev.pubkey }); |
| 66 | + } |
| 67 | +} |
0 commit comments