-
Notifications
You must be signed in to change notification settings - Fork 234
feat(admin): accept NIP-98 auth on admin API routes #730
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Anshumancanrock
wants to merge
1
commit into
cameri:main
Choose a base branch
from
Anshumancanrock:feat/nip98-admin-auth
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| "nostream": minor | ||
| --- | ||
|
|
||
| feat(admin): accept NIP-98 Authorization on protected admin API routes |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,19 +1,187 @@ | ||
| import { NextFunction, Request, Response } from 'express' | ||
| import { NextFunction, Response } from 'express' | ||
|
|
||
| import { IAdminAuthProvider } from '../../@types/admin' | ||
| import { createAdminAuthProvider } from '../../factories/admin-auth-provider-factory' | ||
| import { createLogger } from '../../factories/logger-factory' | ||
| import { createSettings } from '../../factories/settings-factory' | ||
| import { getAbsoluteHttpRequestUrl } from '../../utils/http' | ||
| import { | ||
| DEFAULT_NIP98_MAX_AUTHORIZATION_HEADER_LENGTH, | ||
| verifyNip98Auth, | ||
| } from '../../utils/nip98' | ||
| import { claimNip98AuthEventId, resolveNip98ReplayTtlSeconds } from '../../utils/nip98-replay' | ||
| import { AdminRequest } from './admin-json-body-middleware' | ||
|
|
||
| const adminAuthProvider = createAdminAuthProvider() | ||
| const logger = createLogger('admin-auth-middleware') | ||
|
|
||
| export const adminAuthMiddleware = (request: Request, response: Response, next: NextFunction) => { | ||
| const adminAuthProvider: IAdminAuthProvider = createAdminAuthProvider() | ||
|
|
||
| const METHODS_WITH_BODY = new Set(['POST', 'PUT', 'PATCH', 'DELETE']) | ||
|
|
||
| export const isNostrAuthorizationHeader = (authorizationHeader: string | undefined): boolean => { | ||
| if (typeof authorizationHeader !== 'string') { | ||
| return false | ||
| } | ||
|
|
||
| return /^Nostr\s+/i.test(authorizationHeader.trim()) | ||
| } | ||
|
|
||
| const isAllowedNip98Pubkey = (pubkey: string, allowedPubkeys: string[] | undefined): boolean => { | ||
| if (!Array.isArray(allowedPubkeys) || allowedPubkeys.length === 0) { | ||
| return false | ||
| } | ||
|
|
||
| const normalized = pubkey.toLowerCase() | ||
| return allowedPubkeys.some((allowed) => typeof allowed === 'string' && allowed.toLowerCase() === normalized) | ||
| } | ||
|
|
||
| const resolveBodyForNip98 = (request: AdminRequest): Buffer | undefined | 'missing-raw-body' => { | ||
| if (request.rawBody !== undefined) { | ||
| return request.rawBody | ||
| } | ||
|
|
||
| if (!METHODS_WITH_BODY.has(request.method.toUpperCase())) { | ||
| return undefined | ||
| } | ||
|
|
||
| const contentLength = Number(request.headers['content-length'] ?? '0') | ||
| const transferEncodingHeader = request.headers['transfer-encoding'] | ||
| const transferEncoding = Array.isArray(transferEncodingHeader) | ||
| ? transferEncodingHeader.join(',') | ||
| : (transferEncodingHeader ?? '') | ||
| const hasChunkedBody = transferEncoding.toLowerCase().includes('chunked') | ||
|
|
||
| if ((Number.isFinite(contentLength) && contentLength > 0) || hasChunkedBody) { | ||
| return 'missing-raw-body' | ||
| } | ||
|
|
||
| return Buffer.alloc(0) | ||
| } | ||
|
|
||
| const sendUnauthorized = (response: Response): void => { | ||
| response.status(401).setHeader('content-type', 'application/json').send({ error: 'Unauthorized' }) | ||
| } | ||
|
|
||
| export const adminAuthGateMiddleware = async (request: AdminRequest, response: Response, next: NextFunction) => { | ||
| try { | ||
| if (!adminAuthProvider.isRequestAuthenticated(request)) { | ||
| response.status(401).setHeader('content-type', 'application/json').send({ error: 'Unauthorized' }) | ||
| if (adminAuthProvider.isRequestAuthenticated(request)) { | ||
| next() | ||
| return | ||
| } | ||
|
|
||
| const settings = createSettings() | ||
| const nip98Settings = settings.admin?.nip98 | ||
| const authorizationHeader = request.headers.authorization | ||
|
|
||
| if (nip98Settings?.enabled !== true || !isNostrAuthorizationHeader(authorizationHeader)) { | ||
| sendUnauthorized(response) | ||
| return | ||
| } | ||
|
|
||
| if (authorizationHeader.length > DEFAULT_NIP98_MAX_AUTHORIZATION_HEADER_LENGTH) { | ||
| logger('rejecting NIP-98 auth gate: authorization header too large') | ||
| sendUnauthorized(response) | ||
| return | ||
| } | ||
|
|
||
| const absoluteUrl = getAbsoluteHttpRequestUrl(request, settings) | ||
| if (!absoluteUrl) { | ||
| logger('rejecting NIP-98 auth gate: unable to build absolute request URL') | ||
| sendUnauthorized(response) | ||
| return | ||
| } | ||
|
|
||
| const result = await verifyNip98Auth({ | ||
| authorizationHeader, | ||
| url: absoluteUrl, | ||
| method: request.method.toUpperCase(), | ||
| maxSkewSeconds: nip98Settings.maxSkewSeconds, | ||
| }) | ||
|
|
||
| if (result.ok === false) { | ||
| logger('rejecting NIP-98 auth gate: %s', result.reason) | ||
| sendUnauthorized(response) | ||
| return | ||
| } | ||
|
|
||
| if (!isAllowedNip98Pubkey(result.pubkey, nip98Settings.allowedPubkeys)) { | ||
| logger('rejecting NIP-98 auth gate: pubkey %s is not allowlisted', result.pubkey) | ||
| sendUnauthorized(response) | ||
| return | ||
| } | ||
| } catch { | ||
|
|
||
| next() | ||
| } catch (error) { | ||
| logger('admin auth gate error: %o', error) | ||
| response.status(500).setHeader('content-type', 'application/json').send({ error: 'Internal Server Error' }) | ||
| return | ||
| } | ||
| } | ||
|
|
||
| next() | ||
| export const adminAuthMiddleware = async (request: AdminRequest, response: Response, next: NextFunction) => { | ||
| try { | ||
| if (adminAuthProvider.isRequestAuthenticated(request)) { | ||
| next() | ||
| return | ||
| } | ||
|
|
||
| const settings = createSettings() | ||
| const nip98Settings = settings.admin?.nip98 | ||
| const authorizationHeader = request.headers.authorization | ||
|
|
||
| if (!nip98Settings?.enabled || !isNostrAuthorizationHeader(authorizationHeader)) { | ||
| sendUnauthorized(response) | ||
| return | ||
| } | ||
|
|
||
| const absoluteUrl = getAbsoluteHttpRequestUrl(request, settings) | ||
| if (!absoluteUrl) { | ||
| logger('rejecting NIP-98 auth: unable to build absolute request URL') | ||
| sendUnauthorized(response) | ||
| return | ||
| } | ||
|
|
||
| const body = resolveBodyForNip98(request) | ||
| if (body === 'missing-raw-body') { | ||
| logger('rejecting NIP-98 auth: request body present but rawBody was not captured') | ||
| sendUnauthorized(response) | ||
| return | ||
| } | ||
|
|
||
| const result = await verifyNip98Auth({ | ||
| authorizationHeader, | ||
| url: absoluteUrl, | ||
| method: request.method.toUpperCase(), | ||
| body, | ||
| maxSkewSeconds: nip98Settings.maxSkewSeconds, | ||
| payloadPolicy: 'require-when-body', | ||
| }) | ||
|
|
||
| if (result.ok === false) { | ||
| logger('rejecting NIP-98 auth: %s', result.reason) | ||
| sendUnauthorized(response) | ||
| return | ||
| } | ||
|
|
||
| if (!isAllowedNip98Pubkey(result.pubkey, nip98Settings.allowedPubkeys)) { | ||
| logger('rejecting NIP-98 auth: pubkey %s is not allowlisted', result.pubkey) | ||
| sendUnauthorized(response) | ||
| return | ||
| } | ||
|
|
||
| const claim = await claimNip98AuthEventId( | ||
| result.event.id, | ||
| resolveNip98ReplayTtlSeconds(result.event.created_at, nip98Settings.maxSkewSeconds), | ||
| ) | ||
| if (claim !== 'claimed') { | ||
| logger('rejecting NIP-98 auth: event %s replay protection result=%s', result.event.id, claim) | ||
| sendUnauthorized(response) | ||
| return | ||
| } | ||
|
|
||
| request.nip98Pubkey = result.pubkey | ||
| next() | ||
| } catch (error) { | ||
| logger('admin auth middleware error: %o', error) | ||
| response.status(500).setHeader('content-type', 'application/json').send({ error: 'Internal Server Error' }) | ||
| } | ||
| } |
15 changes: 15 additions & 0 deletions
15
src/handlers/request-handlers/admin-json-body-middleware.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| import { json, Request, RequestHandler } from 'express' | ||
|
|
||
| export type AdminRequest = Request & { | ||
| rawBody?: Buffer | ||
| nip98Pubkey?: string | ||
| } | ||
|
|
||
| const ADMIN_JSON_BODY_LIMIT = '1mb' | ||
|
|
||
| export const adminJsonBodyMiddleware: RequestHandler = json({ | ||
| limit: ADMIN_JSON_BODY_LIMIT, | ||
| verify: (request: AdminRequest, _response, buffer) => { | ||
| request.rawBody = Buffer.from(buffer) | ||
| }, | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.