Enable registrations, require proof-of-work
This commit is contained in:
parent
35b91812fc
commit
052c00821d
|
@ -57,7 +57,7 @@ import { nodeInfoController, nodeInfoSchemaController } from './controllers/well
|
||||||
import { nostrController } from './controllers/well-known/nostr.ts';
|
import { nostrController } from './controllers/well-known/nostr.ts';
|
||||||
import { webfingerController } from './controllers/well-known/webfinger.ts';
|
import { webfingerController } from './controllers/well-known/webfinger.ts';
|
||||||
import { auth19, requirePubkey } from './middleware/auth19.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 {
|
interface AppEnv extends HonoEnv {
|
||||||
Variables: {
|
Variables: {
|
||||||
|
@ -103,7 +103,7 @@ app.post('/oauth/revoke', emptyObjectController);
|
||||||
app.post('/oauth/authorize', oauthAuthorizeController);
|
app.post('/oauth/authorize', oauthAuthorizeController);
|
||||||
app.get('/oauth/authorize', oauthController);
|
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.get('/api/v1/accounts/verify_credentials', requirePubkey, verifyCredentialsController);
|
||||||
app.patch('/api/v1/accounts/update_credentials', requirePubkey, updateCredentialsController);
|
app.patch('/api/v1/accounts/update_credentials', requirePubkey, updateCredentialsController);
|
||||||
app.get('/api/v1/accounts/search', accountSearchController);
|
app.get('/api/v1/accounts/search', accountSearchController);
|
||||||
|
|
|
@ -115,6 +115,17 @@ const Conf = {
|
||||||
get maxUploadSize() {
|
get maxUploadSize() {
|
||||||
return Number(Deno.env.get('MAX_UPLOAD_SIZE') || 100 * 1024 * 1024);
|
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. */
|
/** Domain of the Ditto server as a `URL` object, for easily grabbing the `hostname`, etc. */
|
||||||
get url() {
|
get url() {
|
||||||
return new URL(Conf.localDomain);
|
return new URL(Conf.localDomain);
|
||||||
|
|
|
@ -1,4 +1,5 @@
|
||||||
import { type AppController } from '@/app.ts';
|
import { type AppController } from '@/app.ts';
|
||||||
|
import { Conf } from '@/config.ts';
|
||||||
import { type Filter, findReplyTag, z } from '@/deps.ts';
|
import { type Filter, findReplyTag, z } from '@/deps.ts';
|
||||||
import * as mixer from '@/mixer.ts';
|
import * as mixer from '@/mixer.ts';
|
||||||
import { getAuthor, getFollowedPubkeys, getFollows, syncUser } from '@/queries.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 { paginated, paginationSchema, parseBody } from '@/utils/web.ts';
|
||||||
import { createEvent } from '@/utils/web.ts';
|
import { createEvent } from '@/utils/web.ts';
|
||||||
import { renderEventAccounts } from '@/views.ts';
|
import { renderEventAccounts } from '@/views.ts';
|
||||||
|
import { insertUser } from '@/db/users.ts';
|
||||||
|
|
||||||
const createAccountController: AppController = (c) => {
|
const usernameSchema = z
|
||||||
return c.json({ error: 'Please log in with Nostr.' }, 405);
|
.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) => {
|
const verifyCredentialsController: AppController = async (c) => {
|
||||||
|
|
|
@ -21,6 +21,7 @@ export {
|
||||||
matchFilters,
|
matchFilters,
|
||||||
nip04,
|
nip04,
|
||||||
nip05,
|
nip05,
|
||||||
|
nip13,
|
||||||
nip19,
|
nip19,
|
||||||
nip21,
|
nip21,
|
||||||
verifySignature,
|
verifySignature,
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
import { type AppContext, type AppMiddleware } from '@/app.ts';
|
import { type AppContext, type AppMiddleware } from '@/app.ts';
|
||||||
import { HTTPException } from '@/deps.ts';
|
import { type Event, HTTPException } from '@/deps.ts';
|
||||||
import {
|
import {
|
||||||
buildAuthEventTemplate,
|
buildAuthEventTemplate,
|
||||||
parseAuthRequest,
|
parseAuthRequest,
|
||||||
|
@ -32,19 +32,22 @@ type UserRole = 'user' | 'admin';
|
||||||
|
|
||||||
/** Require the user to prove their role before invoking the controller. */
|
/** Require the user to prove their role before invoking the controller. */
|
||||||
function requireRole(role: UserRole, opts?: ParseAuthRequestOpts): AppMiddleware {
|
function requireRole(role: UserRole, opts?: ParseAuthRequestOpts): AppMiddleware {
|
||||||
return async (c, next) => {
|
return withProof(async (_c, proof, next) => {
|
||||||
const header = c.req.headers.get('x-nostr-sign');
|
const user = await findUser({ pubkey: proof.pubkey });
|
||||||
const proof = c.get('proof') || header ? await obtainProof(c, opts) : undefined;
|
|
||||||
const user = proof ? await findUser({ pubkey: proof.pubkey }) : undefined;
|
|
||||||
|
|
||||||
if (proof && user && matchesRole(user, role)) {
|
if (user && matchesRole(user, role)) {
|
||||||
c.set('pubkey', proof.pubkey);
|
|
||||||
c.set('proof', proof);
|
|
||||||
await next();
|
await next();
|
||||||
} else {
|
} else {
|
||||||
throw new HTTPException(401);
|
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. */
|
/** 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. */
|
/** Get the proof over Nostr Connect. */
|
||||||
async function obtainProof(c: AppContext, opts?: ParseAuthRequestOpts) {
|
async function obtainProof(c: AppContext, opts?: ParseAuthRequestOpts) {
|
||||||
const req = localRequest(c);
|
const req = localRequest(c);
|
||||||
|
@ -71,4 +98,4 @@ async function obtainProof(c: AppContext, opts?: ParseAuthRequestOpts) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export { auth98, requireRole };
|
export { auth98, requireProof, requireRole };
|
||||||
|
|
|
@ -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 { decode64Schema, jsonSchema } from '@/schema.ts';
|
||||||
import { signedEventSchema } from '@/schemas/nostr.ts';
|
import { signedEventSchema } from '@/schemas/nostr.ts';
|
||||||
import { eventAge, findTag, nostrNow, sha256 } from '@/utils.ts';
|
import { eventAge, findTag, nostrNow, sha256 } from '@/utils.ts';
|
||||||
|
@ -12,6 +12,8 @@ interface ParseAuthRequestOpts {
|
||||||
maxAge?: number;
|
maxAge?: number;
|
||||||
/** Whether to validate the request body of the request with the payload of the auth event. (default: `true`) */
|
/** Whether to validate the request body of the request with the payload of the auth event. (default: `true`) */
|
||||||
validatePayload?: boolean;
|
validatePayload?: boolean;
|
||||||
|
/** Difficulty of the proof of work. (default: `0`) */
|
||||||
|
pow?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Parse the auth event from a Request, returning a zod SafeParse type. */
|
/** 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. */
|
/** Compare the auth event with the request, returning a zod SafeParse type. */
|
||||||
function validateAuthEvent(req: Request, event: Event, opts: ParseAuthRequestOpts = {}) {
|
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
|
const schema = signedEventSchema
|
||||||
.refine((event): event is Event<27235> => event.kind === 27235, 'Event must be kind 27235')
|
.refine((event): event is Event<27235> => event.kind === 27235, 'Event must be kind 27235')
|
||||||
.refine((event) => eventAge(event) < maxAge, 'Event expired')
|
.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, '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) => 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');
|
.refine(validateBody, 'Event payload does not match request body');
|
||||||
|
|
||||||
function validateBody(event: Event<27235>) {
|
function validateBody(event: Event<27235>) {
|
||||||
|
|
Loading…
Reference in New Issue