A Passport.js authentication strategy for Nostr, using signed events for secure authentication.
- Uses Nostr events for authentication.
- Ensures valid signatures using
nostr-tools
. - Validates timestamp, kind, method, and URL.
- Supports
passReqToCallback
for additional flexibility.
Install the package and its dependencies:
npm install passport-nostr
import passport from "passport";
import { NostrStrategy } from "passport-nostr";
passport.use(
new NostrStrategy({}, (pubkey, done) => {
// Find or create user by pubkey
const user = { pubkey };
return done(null, user);
})
);
import express from "express";
const app = express();
app.use(passport.initialize());
app.post("/protected", passport.authenticate("nostr", { session: false }), (req, res) => {
res.json({ message: "Authenticated!", user: req.user });
});
npm install @nestjs/passport
import { Injectable, ExecutionContext } from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";
@Injectable()
export class NostrAuthGuard extends AuthGuard("nostr") {
canActivate(context: ExecutionContext) {
return super.canActivate(context);
}
}
import { Controller, Get, UseGuards, Request } from "@nestjs/common";
import { NostrAuthGuard } from "./nostr-auth.guard";
@Controller("protected")
export class ProtectedController {
@Get()
@UseGuards(NostrAuthGuard)
getProtected(@Request() req) {
return { message: "Authenticated!", user: req.user };
}
}
A client must send a signed Nostr event in the Authorization
header.
POST /protected HTTP/1.1
Authorization: Nostr eyJwdWJrZXkiOiAicHVibGljS2V5IiwgImNyZWF0ZWRfYXQiOiAxNzAwMDAwMDAwLCAiZ2V0cyI6IFtbInVybCIsICJodHRwOi8vbG9jYWxob3N0L3Byb3RlY3RlZCJdLCBbIm1ldGhvZCIsICJQT1NUIl1dfQ==
- Extracts the
Authorization
header. - Decodes the Nostr event.
- Validates:
- Signature using
nostr-tools.verifyEvent()
- Kind (must be
27235
) - Timestamp (must be within ±5 minutes)
- Method & URL tags
- Signature using
- Calls the verify callback with the
pubkey
.
Option | Type | Default | Description |
---|---|---|---|
passReqToCallback |
boolean | false |
If true , passes req to the verify function |
timeToleranceMs |
number | 300000 (5 min) |
Adjusts the allowed timestamp difference |
Apache