Enable registrations, require proof-of-work

This commit is contained in:
Alex Gleason 2023-09-10 15:07:31 -05:00
parent 35b91812fc
commit 052c00821d
No known key found for this signature in database
GPG Key ID: 7211D1F99744FBB7
6 changed files with 87 additions and 16 deletions

View File

@ -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);

View File

@ -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);

View File

@ -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) => {

View File

@ -21,6 +21,7 @@ export {
matchFilters,
nip04,
nip05,
nip13,
nip19,
nip21,
verifySignature,

View File

@ -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<void>) => Promise<void>,
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 };

View File

@ -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>) {