From 052c00821dc98965f31c65c15e211a70485a6f55 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 10 Sep 2023 15:07:31 -0500 Subject: [PATCH] Enable registrations, require proof-of-work --- src/app.ts | 4 +-- src/config.ts | 11 ++++++++ src/controllers/api/accounts.ts | 33 +++++++++++++++++++++-- src/deps.ts | 1 + src/middleware/auth98.ts | 47 ++++++++++++++++++++++++++------- src/utils/nip98.ts | 7 +++-- 6 files changed, 87 insertions(+), 16 deletions(-) diff --git a/src/app.ts b/src/app.ts index 7d9750a..c30579a 100644 --- a/src/app.ts +++ b/src/app.ts @@ -57,7 +57,7 @@ import { nodeInfoController, nodeInfoSchemaController } from './controllers/well import { nostrController } from './controllers/well-known/nostr.ts'; import { webfingerController } from './controllers/well-known/webfinger.ts'; import { auth19, requirePubkey } from './middleware/auth19.ts'; -import { auth98, requireRole } from './middleware/auth98.ts'; +import { auth98, requireProof, requireRole } from './middleware/auth98.ts'; interface AppEnv extends HonoEnv { Variables: { @@ -103,7 +103,7 @@ app.post('/oauth/revoke', emptyObjectController); app.post('/oauth/authorize', oauthAuthorizeController); app.get('/oauth/authorize', oauthController); -app.post('/api/v1/acccounts', createAccountController); +app.post('/api/v1/acccounts', requireProof({ pow: 20 }), createAccountController); app.get('/api/v1/accounts/verify_credentials', requirePubkey, verifyCredentialsController); app.patch('/api/v1/accounts/update_credentials', requirePubkey, updateCredentialsController); app.get('/api/v1/accounts/search', accountSearchController); diff --git a/src/config.ts b/src/config.ts index c92ad05..4f60580 100644 --- a/src/config.ts +++ b/src/config.ts @@ -115,6 +115,17 @@ const Conf = { get maxUploadSize() { return Number(Deno.env.get('MAX_UPLOAD_SIZE') || 100 * 1024 * 1024); }, + /** Usernames that regular users cannot sign up with. */ + get forbiddenUsernames() { + return Deno.env.get('FORBIDDEN_USERNAMES')?.split(',') || [ + '_', + 'admin', + 'administrator', + 'root', + 'sysadmin', + 'system', + ]; + }, /** Domain of the Ditto server as a `URL` object, for easily grabbing the `hostname`, etc. */ get url() { return new URL(Conf.localDomain); diff --git a/src/controllers/api/accounts.ts b/src/controllers/api/accounts.ts index 1147c6c..7ac74a0 100644 --- a/src/controllers/api/accounts.ts +++ b/src/controllers/api/accounts.ts @@ -1,4 +1,5 @@ import { type AppController } from '@/app.ts'; +import { Conf } from '@/config.ts'; import { type Filter, findReplyTag, z } from '@/deps.ts'; import * as mixer from '@/mixer.ts'; import { getAuthor, getFollowedPubkeys, getFollows, syncUser } from '@/queries.ts'; @@ -9,9 +10,37 @@ import { isFollowing, lookupAccount, Time } from '@/utils.ts'; import { paginated, paginationSchema, parseBody } from '@/utils/web.ts'; import { createEvent } from '@/utils/web.ts'; import { renderEventAccounts } from '@/views.ts'; +import { insertUser } from '@/db/users.ts'; -const createAccountController: AppController = (c) => { - return c.json({ error: 'Please log in with Nostr.' }, 405); +const usernameSchema = z + .string().min(1).max(30) + .regex(/^[a-z0-9_]+$/i) + .refine((username) => !Conf.forbiddenUsernames.includes(username), 'Username is reserved.'); + +const createAccountSchema = z.object({ + username: usernameSchema, +}); + +const createAccountController: AppController = async (c) => { + const pubkey = c.get('pubkey')!; + const result = createAccountSchema.safeParse(await c.req.json()); + + if (!result.success) { + return c.json({ error: 'Bad request', schema: result.error }, 400); + } + + try { + await insertUser({ + pubkey, + username: result.data.username, + inserted_at: new Date(), + admin: 0, + }); + + return new Response(); + } catch (_e) { + return c.json({ error: 'Username already taken.' }, 422); + } }; const verifyCredentialsController: AppController = async (c) => { diff --git a/src/deps.ts b/src/deps.ts index 727bba1..99e8c4f 100644 --- a/src/deps.ts +++ b/src/deps.ts @@ -21,6 +21,7 @@ export { matchFilters, nip04, nip05, + nip13, nip19, nip21, verifySignature, diff --git a/src/middleware/auth98.ts b/src/middleware/auth98.ts index be97320..8a2272b 100644 --- a/src/middleware/auth98.ts +++ b/src/middleware/auth98.ts @@ -1,5 +1,5 @@ import { type AppContext, type AppMiddleware } from '@/app.ts'; -import { HTTPException } from '@/deps.ts'; +import { type Event, HTTPException } from '@/deps.ts'; import { buildAuthEventTemplate, parseAuthRequest, @@ -32,19 +32,22 @@ type UserRole = 'user' | 'admin'; /** Require the user to prove their role before invoking the controller. */ function requireRole(role: UserRole, opts?: ParseAuthRequestOpts): AppMiddleware { - return async (c, next) => { - const header = c.req.headers.get('x-nostr-sign'); - const proof = c.get('proof') || header ? await obtainProof(c, opts) : undefined; - const user = proof ? await findUser({ pubkey: proof.pubkey }) : undefined; + return withProof(async (_c, proof, next) => { + const user = await findUser({ pubkey: proof.pubkey }); - if (proof && user && matchesRole(user, role)) { - c.set('pubkey', proof.pubkey); - c.set('proof', proof); + if (user && matchesRole(user, role)) { await next(); } else { throw new HTTPException(401); } - }; + }, opts); +} + +/** Require the user to demonstrate they own the pubkey by signing an event. */ +function requireProof(opts?: ParseAuthRequestOpts): AppMiddleware { + return withProof(async (_c, _proof, next) => { + await next(); + }, opts); } /** Check whether the user fulfills the role. */ @@ -59,6 +62,30 @@ function matchesRole(user: User, role: UserRole): boolean { } } +/** HOC to obtain proof in middleware. */ +function withProof( + handler: (c: AppContext, proof: Event<27235>, next: () => Promise) => Promise, + opts?: ParseAuthRequestOpts, +): AppMiddleware { + return async (c, next) => { + const pubkey = c.get('pubkey'); + const proof = c.get('proof') || await obtainProof(c, opts); + + // Prevent people from accidentally using the wrong account. This has no other security implications. + if (proof && pubkey && pubkey !== proof.pubkey) { + throw new HTTPException(401, { message: 'Pubkey mismatch' }); + } + + if (proof) { + c.set('pubkey', proof.pubkey); + c.set('proof', proof); + await handler(c, proof, next); + } else { + throw new HTTPException(401); + } + }; +} + /** Get the proof over Nostr Connect. */ async function obtainProof(c: AppContext, opts?: ParseAuthRequestOpts) { const req = localRequest(c); @@ -71,4 +98,4 @@ async function obtainProof(c: AppContext, opts?: ParseAuthRequestOpts) { } } -export { auth98, requireRole }; +export { auth98, requireProof, requireRole }; diff --git a/src/utils/nip98.ts b/src/utils/nip98.ts index 5606d8b..0445fbd 100644 --- a/src/utils/nip98.ts +++ b/src/utils/nip98.ts @@ -1,4 +1,4 @@ -import { type Event, type EventTemplate } from '@/deps.ts'; +import { type Event, type EventTemplate, nip13 } from '@/deps.ts'; import { decode64Schema, jsonSchema } from '@/schema.ts'; import { signedEventSchema } from '@/schemas/nostr.ts'; import { eventAge, findTag, nostrNow, sha256 } from '@/utils.ts'; @@ -12,6 +12,8 @@ interface ParseAuthRequestOpts { maxAge?: number; /** Whether to validate the request body of the request with the payload of the auth event. (default: `true`) */ validatePayload?: boolean; + /** Difficulty of the proof of work. (default: `0`) */ + pow?: number; } /** Parse the auth event from a Request, returning a zod SafeParse type. */ @@ -27,13 +29,14 @@ async function parseAuthRequest(req: Request, opts: ParseAuthRequestOpts = {}) { /** Compare the auth event with the request, returning a zod SafeParse type. */ function validateAuthEvent(req: Request, event: Event, opts: ParseAuthRequestOpts = {}) { - const { maxAge = Time.minutes(1), validatePayload = true } = opts; + const { maxAge = Time.minutes(1), validatePayload = true, pow = 0 } = opts; const schema = signedEventSchema .refine((event): event is Event<27235> => event.kind === 27235, 'Event must be kind 27235') .refine((event) => eventAge(event) < maxAge, 'Event expired') .refine((event) => tagValue(event, 'method') === req.method, 'Event method does not match HTTP request method') .refine((event) => tagValue(event, 'u') === req.url, 'Event URL does not match request URL') + .refine((event) => pow > 0 && nip13.getPow(event.id) >= pow, 'Insufficient proof of work') .refine(validateBody, 'Event payload does not match request body'); function validateBody(event: Event<27235>) {