From 052c00821dc98965f31c65c15e211a70485a6f55 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 10 Sep 2023 15:07:31 -0500 Subject: [PATCH 01/17] 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>) { From b725550fc4ce422285d862e38cb33293b634f962 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 10 Sep 2023 15:14:01 -0500 Subject: [PATCH 02/17] ci: remove `check` job, since `test` already does it --- .gitlab-ci.yml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index a80d993..69fbb6a 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -14,10 +14,6 @@ lint: stage: test script: deno lint -check: - stage: test - script: deno task check - test: stage: test script: deno task test \ No newline at end of file From 607ef4b9803c7b1f62fe16ff2863a89935820b7d Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 10 Sep 2023 15:37:32 -0500 Subject: [PATCH 03/17] Make POW configurable, expose over the API --- src/app.ts | 3 ++- src/config.ts | 6 ++++++ src/controllers/api/instance.ts | 3 +++ 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/app.ts b/src/app.ts index c30579a..2e3fc70 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1,3 +1,4 @@ +import { Conf } from '@/config.ts'; import '@/cron.ts'; import { type Context, @@ -103,7 +104,7 @@ app.post('/oauth/revoke', emptyObjectController); app.post('/oauth/authorize', oauthAuthorizeController); app.get('/oauth/authorize', oauthController); -app.post('/api/v1/acccounts', requireProof({ pow: 20 }), createAccountController); +app.post('/api/v1/acccounts', requireProof({ pow: Conf.pow.registrations }), 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 4f60580..440cd26 100644 --- a/src/config.ts +++ b/src/config.ts @@ -126,6 +126,12 @@ const Conf = { 'system', ]; }, + /** Proof-of-work configuration. */ + pow: { + get registrations() { + return Number(Deno.env.get('DITTO_POW_REGISTRATIONS') ?? 20); + }, + }, /** 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/instance.ts b/src/controllers/api/instance.ts index b30c753..8ef38a7 100644 --- a/src/controllers/api/instance.ts +++ b/src/controllers/api/instance.ts @@ -53,6 +53,9 @@ const instanceController: AppController = (c) => { nostr: { pubkey: Conf.pubkey, relay: `${wsProtocol}//${host}/relay`, + pow: { + registrations: Conf.pow.registrations, + }, }, rules: [], }); From 2d7398e9d10ad6e6ebb994fa56666269109bcb8c Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 10 Sep 2023 17:11:13 -0500 Subject: [PATCH 04/17] nip98: fix pow check --- src/utils/nip98.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/nip98.ts b/src/utils/nip98.ts index 0445fbd..facc9af 100644 --- a/src/utils/nip98.ts +++ b/src/utils/nip98.ts @@ -36,7 +36,7 @@ function validateAuthEvent(req: Request, event: Event, opts: ParseAuthRequestOpt .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((event) => pow ? nip13.getPow(event.id) >= pow : true, 'Insufficient proof of work') .refine(validateBody, 'Event payload does not match request body'); function validateBody(event: Event<27235>) { From e3f11545b7f5749dc82770c1809c4764d7755756 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 10 Sep 2023 19:23:50 -0500 Subject: [PATCH 05/17] /api/v1/acccounts --> /api/v1/accounts --- src/app.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app.ts b/src/app.ts index 2e3fc70..a9d3585 100644 --- a/src/app.ts +++ b/src/app.ts @@ -104,7 +104,7 @@ app.post('/oauth/revoke', emptyObjectController); app.post('/oauth/authorize', oauthAuthorizeController); app.get('/oauth/authorize', oauthController); -app.post('/api/v1/acccounts', requireProof({ pow: Conf.pow.registrations }), createAccountController); +app.post('/api/v1/accounts', requireProof({ pow: Conf.pow.registrations }), 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); From 75dd2652d2da500b9a447a46b976521cbc65c68c Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 10 Sep 2023 19:42:41 -0500 Subject: [PATCH 06/17] app: remove unused account search fallback endpoint --- src/app.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/app.ts b/src/app.ts index a9d3585..129b302 100644 --- a/src/app.ts +++ b/src/app.ts @@ -147,7 +147,6 @@ app.post('/api/v1/pleroma/admin/config', requireRole('admin'), updateConfigContr // Not (yet) implemented. app.get('/api/v1/bookmarks', emptyArrayController); app.get('/api/v1/custom_emojis', emptyArrayController); -app.get('/api/v1/accounts/search', emptyArrayController); app.get('/api/v1/filters', emptyArrayController); app.get('/api/v1/blocks', emptyArrayController); app.get('/api/v1/mutes', emptyArrayController); From 0adb6f5eba8c73c253fd4ba79e626ebd9e74e547 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 10 Sep 2023 19:43:07 -0500 Subject: [PATCH 07/17] Add messages to HTTPException's --- src/middleware/auth19.ts | 2 +- src/middleware/auth98.ts | 2 +- src/sign.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/middleware/auth19.ts b/src/middleware/auth19.ts index f92f678..fec79ad 100644 --- a/src/middleware/auth19.ts +++ b/src/middleware/auth19.ts @@ -38,7 +38,7 @@ const auth19: AppMiddleware = async (c, next) => { /** Throw a 401 if the pubkey isn't set. */ const requirePubkey: AppMiddleware = async (c, next) => { if (!c.get('pubkey')) { - throw new HTTPException(401); + throw new HTTPException(401, { message: 'No pubkey provided' }); } await next(); diff --git a/src/middleware/auth98.ts b/src/middleware/auth98.ts index 8a2272b..20787fe 100644 --- a/src/middleware/auth98.ts +++ b/src/middleware/auth98.ts @@ -81,7 +81,7 @@ function withProof( c.set('proof', proof); await handler(c, proof, next); } else { - throw new HTTPException(401); + throw new HTTPException(401, { message: 'No proof' }); } }; } diff --git a/src/sign.ts b/src/sign.ts index a97478a..14c192f 100644 --- a/src/sign.ts +++ b/src/sign.ts @@ -36,7 +36,7 @@ async function signNostrConnect(event: EventTemplate< const pubkey = c.get('pubkey'); if (!pubkey) { - throw new HTTPException(401); + throw new HTTPException(401, { message: 'Missing pubkey' }); } const messageId = crypto.randomUUID(); From 82c4f0827ef265006deb8557a2db46e057ccda83 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 10 Sep 2023 23:43:06 -0500 Subject: [PATCH 08/17] Make registrations configurable by env --- src/config.ts | 4 ++++ src/controllers/api/accounts.ts | 4 ++++ src/controllers/api/instance.ts | 2 +- 3 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/config.ts b/src/config.ts index 440cd26..ba36898 100644 --- a/src/config.ts +++ b/src/config.ts @@ -126,6 +126,10 @@ const Conf = { 'system', ]; }, + /** Whether registrations are open or closed. */ + get registrations() { + return optionalBooleanSchema.parse(Deno.env.get('DITTO_REGISTRATIONS')) ?? false; + }, /** Proof-of-work configuration. */ pow: { get registrations() { diff --git a/src/controllers/api/accounts.ts b/src/controllers/api/accounts.ts index 7ac74a0..1d37f70 100644 --- a/src/controllers/api/accounts.ts +++ b/src/controllers/api/accounts.ts @@ -22,6 +22,10 @@ const createAccountSchema = z.object({ }); const createAccountController: AppController = async (c) => { + if (!Conf.registrations) { + return c.json({ error: 'Registrations are disabled.' }, 403); + } + const pubkey = c.get('pubkey')!; const result = createAccountSchema.safeParse(await c.req.json()); diff --git a/src/controllers/api/instance.ts b/src/controllers/api/instance.ts index 8ef38a7..10b359b 100644 --- a/src/controllers/api/instance.ts +++ b/src/controllers/api/instance.ts @@ -12,7 +12,7 @@ const instanceController: AppController = (c) => { title: 'Ditto', description: 'An efficient and flexible social media server.', short_description: 'An efficient and flexible social media server.', - registrations: false, + registrations: Conf.registrations, max_toot_chars: Conf.postCharLimit, configuration: { media_attachments: { From 8a9f8454bf348f0dfb451d7cb1066d6a7c068e52 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 11 Sep 2023 00:19:56 -0500 Subject: [PATCH 09/17] Serve a frontend through Ditto --- public/.gitignore | 2 ++ src/app.ts | 5 +++++ src/deps.ts | 2 +- 3 files changed, 8 insertions(+), 1 deletion(-) create mode 100644 public/.gitignore diff --git a/public/.gitignore b/public/.gitignore new file mode 100644 index 0000000..c96a04f --- /dev/null +++ b/public/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore \ No newline at end of file diff --git a/src/app.ts b/src/app.ts index 129b302..33592e3 100644 --- a/src/app.ts +++ b/src/app.ts @@ -9,6 +9,7 @@ import { type HonoEnv, logger, type MiddlewareHandler, + serveStatic, } from '@/deps.ts'; import '@/firehose.ts'; @@ -155,6 +156,10 @@ app.get('/api/v1/markers', emptyObjectController); app.get('/api/v1/conversations', emptyArrayController); app.get('/api/v1/lists', emptyArrayController); +app.get('/packs/*', serveStatic({ root: './public/' })); +app.get('/instance/*', serveStatic({ root: './public/' })); +app.get('*', serveStatic({ path: './public/index.html' })); + app.get('/', indexController); export default app; diff --git a/src/deps.ts b/src/deps.ts index 99e8c4f..a31d988 100644 --- a/src/deps.ts +++ b/src/deps.ts @@ -7,7 +7,7 @@ export { HTTPException, type MiddlewareHandler, } from 'https://deno.land/x/hono@v3.3.4/mod.ts'; -export { cors, logger } from 'https://deno.land/x/hono@v3.3.4/middleware.ts'; +export { cors, logger, serveStatic } from 'https://deno.land/x/hono@v3.3.4/middleware.ts'; export { z } from 'https://deno.land/x/zod@v3.21.4/mod.ts'; export { Author, RelayPool } from 'https://dev.jspm.io/nostr-relaypool@0.6.28'; export { From 4310bb7157059f180095999a475c59dc50282f60 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 11 Sep 2023 04:04:55 -0500 Subject: [PATCH 10/17] Add a CSP --- src/app.ts | 3 ++- src/middleware/csp.ts | 30 ++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 src/middleware/csp.ts diff --git a/src/app.ts b/src/app.ts index 33592e3..d46cb91 100644 --- a/src/app.ts +++ b/src/app.ts @@ -60,6 +60,7 @@ 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, requireProof, requireRole } from './middleware/auth98.ts'; +import { csp } from './middleware/csp.ts'; interface AppEnv extends HonoEnv { Variables: { @@ -84,7 +85,7 @@ app.get('/api/v1/streaming', streamingController); app.get('/api/v1/streaming/', streamingController); app.get('/relay', relayController); -app.use('*', cors({ origin: '*', exposeHeaders: ['link'] }), auth19, auth98()); +app.use('*', csp(), cors({ origin: '*', exposeHeaders: ['link'] }), auth19, auth98()); app.get('/.well-known/webfinger', webfingerController); app.get('/.well-known/host-meta', hostMetaController); diff --git a/src/middleware/csp.ts b/src/middleware/csp.ts new file mode 100644 index 0000000..6f5c3a8 --- /dev/null +++ b/src/middleware/csp.ts @@ -0,0 +1,30 @@ +import { AppMiddleware } from '@/app.ts'; +import { Conf } from '@/config.ts'; + +const csp = (): AppMiddleware => { + return async (c, next) => { + const { host, protocol } = Conf.url; + const wsProtocol = protocol === 'http:' ? 'ws:' : 'wss:'; + + const policies = [ + 'upgrade-insecure-requests', + 'script-src \'self\'', + `connect-src 'self' blob: ${Conf.localDomain} ${wsProtocol}//${host}`, + `media-src 'self' ${Conf.mediaDomain}`, + `img-src 'self' data: blob: ${Conf.mediaDomain}`, + 'default-src \'none\'', + 'base-uri \'self\'', + 'frame-ancestors \'none\'', + 'style-src \'self\' \'unsafe-inline\'', + 'font-src \'self\'', + 'manifest-src \'self\'', + 'frame-src \'self\' https:', + ]; + + c.res.headers.set('content-security-policy', policies.join('; ')); + + await next(); + }; +}; + +export { csp }; From 9cda8e3000e1b5520ca3fcf459c83ff3dc312c1f Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 11 Sep 2023 04:07:54 -0500 Subject: [PATCH 11/17] csp: use template literals to avoid escaping single quotes --- src/middleware/csp.ts | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/middleware/csp.ts b/src/middleware/csp.ts index 6f5c3a8..f97fc9a 100644 --- a/src/middleware/csp.ts +++ b/src/middleware/csp.ts @@ -8,17 +8,17 @@ const csp = (): AppMiddleware => { const policies = [ 'upgrade-insecure-requests', - 'script-src \'self\'', + `script-src 'self'`, `connect-src 'self' blob: ${Conf.localDomain} ${wsProtocol}//${host}`, `media-src 'self' ${Conf.mediaDomain}`, `img-src 'self' data: blob: ${Conf.mediaDomain}`, - 'default-src \'none\'', - 'base-uri \'self\'', - 'frame-ancestors \'none\'', - 'style-src \'self\' \'unsafe-inline\'', - 'font-src \'self\'', - 'manifest-src \'self\'', - 'frame-src \'self\' https:', + `default-src 'none'`, + `base-uri 'self'`, + `frame-ancestors 'none'`, + `style-src 'self' 'unsafe-inline'`, + `font-src 'self'`, + `manifest-src 'self'`, + `frame-src 'self' https:`, ]; c.res.headers.set('content-security-policy', policies.join('; ')); From a5bf09ed2b1f245f29c008f7bc9c7d0190e9c9de Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 11 Sep 2023 04:14:08 -0500 Subject: [PATCH 12/17] Resolve any file in public/ --- src/app.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/app.ts b/src/app.ts index d46cb91..ff57ec0 100644 --- a/src/app.ts +++ b/src/app.ts @@ -157,8 +157,7 @@ app.get('/api/v1/markers', emptyObjectController); app.get('/api/v1/conversations', emptyArrayController); app.get('/api/v1/lists', emptyArrayController); -app.get('/packs/*', serveStatic({ root: './public/' })); -app.get('/instance/*', serveStatic({ root: './public/' })); +app.get('*', serveStatic({ root: './public/' })); app.get('*', serveStatic({ path: './public/index.html' })); app.get('/', indexController); From bacb872a18bc41dc79a38bc6163ec1736505bc07 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 11 Sep 2023 04:55:15 -0500 Subject: [PATCH 13/17] Add /api not implemented controller --- src/app.ts | 4 +++- src/controllers/api/fallback.ts | 3 ++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/app.ts b/src/app.ts index ff57ec0..ef59c8f 100644 --- a/src/app.ts +++ b/src/app.ts @@ -29,7 +29,7 @@ import { verifyCredentialsController, } from './controllers/api/accounts.ts'; import { appCredentialsController, createAppController } from './controllers/api/apps.ts'; -import { emptyArrayController, emptyObjectController } from './controllers/api/fallback.ts'; +import { emptyArrayController, emptyObjectController, notImplementedController } from './controllers/api/fallback.ts'; import { instanceController } from './controllers/api/instance.ts'; import { mediaController } from './controllers/api/media.ts'; import { notificationsController } from './controllers/api/notifications.ts'; @@ -157,6 +157,8 @@ app.get('/api/v1/markers', emptyObjectController); app.get('/api/v1/conversations', emptyArrayController); app.get('/api/v1/lists', emptyArrayController); +app.use('/api/*', notImplementedController); + app.get('*', serveStatic({ root: './public/' })); app.get('*', serveStatic({ path: './public/index.html' })); diff --git a/src/controllers/api/fallback.ts b/src/controllers/api/fallback.ts index c57de7a..b46460e 100644 --- a/src/controllers/api/fallback.ts +++ b/src/controllers/api/fallback.ts @@ -2,5 +2,6 @@ import type { Context } from '@/deps.ts'; const emptyArrayController = (c: Context) => c.json([]); const emptyObjectController = (c: Context) => c.json({}); +const notImplementedController = (c: Context) => Promise.resolve(c.json({ error: 'Not implemented' }, 404)); -export { emptyArrayController, emptyObjectController }; +export { emptyArrayController, emptyObjectController, notImplementedController }; From 10a804b60ee541541dc54c0b3cf240d310468fc0 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 11 Sep 2023 05:57:50 -0500 Subject: [PATCH 14/17] Remove POW requirement for now --- src/app.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/app.ts b/src/app.ts index ef59c8f..d78c259 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1,4 +1,3 @@ -import { Conf } from '@/config.ts'; import '@/cron.ts'; import { type Context, @@ -106,7 +105,7 @@ app.post('/oauth/revoke', emptyObjectController); app.post('/oauth/authorize', oauthAuthorizeController); app.get('/oauth/authorize', oauthController); -app.post('/api/v1/accounts', requireProof({ pow: Conf.pow.registrations }), createAccountController); +app.post('/api/v1/accounts', requireProof(), 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); From 1b2f4d9a54a5768a0ee733a085a80881da246455 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 11 Sep 2023 07:17:00 -0500 Subject: [PATCH 15/17] accounts: return token after registering account --- src/controllers/api/accounts.ts | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/controllers/api/accounts.ts b/src/controllers/api/accounts.ts index 1d37f70..d1bc244 100644 --- a/src/controllers/api/accounts.ts +++ b/src/controllers/api/accounts.ts @@ -1,12 +1,12 @@ import { type AppController } from '@/app.ts'; import { Conf } from '@/config.ts'; -import { type Filter, findReplyTag, z } from '@/deps.ts'; +import { type Filter, findReplyTag, nip19, z } from '@/deps.ts'; import * as mixer from '@/mixer.ts'; import { getAuthor, getFollowedPubkeys, getFollows, syncUser } from '@/queries.ts'; import { booleanParamSchema, fileSchema } from '@/schema.ts'; import { jsonMetaContentSchema } from '@/schemas/nostr.ts'; import { toAccount, toRelationship, toStatus } from '@/transformers/nostr-to-mastoapi.ts'; -import { isFollowing, lookupAccount, Time } from '@/utils.ts'; +import { isFollowing, lookupAccount, nostrNow, Time } from '@/utils.ts'; import { paginated, paginationSchema, parseBody } from '@/utils/web.ts'; import { createEvent } from '@/utils/web.ts'; import { renderEventAccounts } from '@/views.ts'; @@ -41,7 +41,12 @@ const createAccountController: AppController = async (c) => { admin: 0, }); - return new Response(); + return c.json({ + access_token: nip19.npubEncode(pubkey), + token_type: 'Bearer', + scope: 'read write follow push', + created_at: nostrNow(), + }); } catch (_e) { return c.json({ error: 'Username already taken.' }, 422); } From 31114b6094dbe335f9cedd39fdd99f0b00f12095 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 11 Sep 2023 09:08:15 -0500 Subject: [PATCH 16/17] accounts: return a blank account for verify_credentials if it isn't resolved --- src/controllers/api/accounts.ts | 6 +++--- src/deps.ts | 1 + src/transformers/nostr-to-mastoapi.ts | 22 +++++++++++++++++----- 3 files changed, 21 insertions(+), 8 deletions(-) diff --git a/src/controllers/api/accounts.ts b/src/controllers/api/accounts.ts index d1bc244..211eb77 100644 --- a/src/controllers/api/accounts.ts +++ b/src/controllers/api/accounts.ts @@ -5,7 +5,7 @@ import * as mixer from '@/mixer.ts'; import { getAuthor, getFollowedPubkeys, getFollows, syncUser } from '@/queries.ts'; import { booleanParamSchema, fileSchema } from '@/schema.ts'; import { jsonMetaContentSchema } from '@/schemas/nostr.ts'; -import { toAccount, toRelationship, toStatus } from '@/transformers/nostr-to-mastoapi.ts'; +import { accountFromPubkey, toAccount, toRelationship, toStatus } from '@/transformers/nostr-to-mastoapi.ts'; import { isFollowing, lookupAccount, nostrNow, Time } from '@/utils.ts'; import { paginated, paginationSchema, parseBody } from '@/utils/web.ts'; import { createEvent } from '@/utils/web.ts'; @@ -60,9 +60,9 @@ const verifyCredentialsController: AppController = async (c) => { const event = await getAuthor(pubkey); if (event) { return c.json(await toAccount(event, { withSource: true })); + } else { + return c.json(await accountFromPubkey(pubkey, { withSource: true })); } - - return c.json({ error: 'Could not find user.' }, 404); }; const accountController: AppController = async (c) => { diff --git a/src/deps.ts b/src/deps.ts index a31d988..35b4763 100644 --- a/src/deps.ts +++ b/src/deps.ts @@ -24,6 +24,7 @@ export { nip13, nip19, nip21, + type UnsignedEvent, verifySignature, } from 'npm:nostr-tools@^1.14.0'; export { findReplyTag } from 'https://gitlab.com/soapbox-pub/mostr/-/raw/c67064aee5ade5e01597c6d23e22e53c628ef0e2/src/nostr/tags.ts'; diff --git a/src/transformers/nostr-to-mastoapi.ts b/src/transformers/nostr-to-mastoapi.ts index 5fc02a8..0bf09f3 100644 --- a/src/transformers/nostr-to-mastoapi.ts +++ b/src/transformers/nostr-to-mastoapi.ts @@ -2,12 +2,12 @@ import { isCWTag } from 'https://gitlab.com/soapbox-pub/mostr/-/raw/c67064aee5ad import { Conf } from '@/config.ts'; import * as eventsDB from '@/db/events.ts'; -import { type Event, findReplyTag, lodash, nip19, sanitizeHtml, TTLCache, unfurl } from '@/deps.ts'; +import { type Event, findReplyTag, lodash, nip19, sanitizeHtml, TTLCache, unfurl, type UnsignedEvent } from '@/deps.ts'; import { getMediaLinks, parseNoteContent } from '@/note.ts'; import { getAuthor, getFollowedPubkeys, getFollows } from '@/queries.ts'; import { emojiTagSchema, filteredArray } from '@/schema.ts'; import { jsonMediaDataSchema, jsonMetaContentSchema } from '@/schemas/nostr.ts'; -import { isFollowing, type Nip05, nostrDate, parseNip05, Time } from '@/utils.ts'; +import { isFollowing, type Nip05, nostrDate, nostrNow, parseNip05, Time } from '@/utils.ts'; import { verifyNip05Cached } from '@/utils/nip05.ts'; import { findUser } from '@/db/users.ts'; import { DittoAttachment, renderAttachment } from '@/views/attachment.ts'; @@ -19,7 +19,7 @@ interface ToAccountOpts { withSource?: boolean; } -async function toAccount(event: Event<0>, opts: ToAccountOpts = {}) { +async function toAccount(event: UnsignedEvent<0>, opts: ToAccountOpts = {}) { const { withSource = false } = opts; const { pubkey } = event; @@ -75,6 +75,18 @@ async function toAccount(event: Event<0>, opts: ToAccountOpts = {}) { }; } +function accountFromPubkey(pubkey: string, opts: ToAccountOpts = {}) { + const event: UnsignedEvent<0> = { + kind: 0, + pubkey, + content: '', + tags: [], + created_at: nostrNow(), + }; + + return toAccount(event, opts); +} + async function parseAndVerifyNip05(nip05: string | undefined, pubkey: string): Promise { if (nip05 && await verifyNip05Cached(nip05, pubkey)) { return parseNip05(nip05); @@ -257,7 +269,7 @@ function unfurlCardCached(url: string): Promise { return card; } -function toEmojis(event: Event) { +function toEmojis(event: UnsignedEvent) { const emojiTags = event.tags.filter((tag) => tag[0] === 'emoji'); return filteredArray(emojiTagSchema).parse(emojiTags) @@ -310,4 +322,4 @@ async function toNotificationMention(event: Event<1>, viewerPubkey?: string) { }; } -export { toAccount, toNotification, toRelationship, toStatus }; +export { accountFromPubkey, toAccount, toNotification, toRelationship, toStatus }; From ef96fa539ae2a0e8fa018d839bb379305b805527 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 11 Sep 2023 09:46:41 -0500 Subject: [PATCH 17/17] Render status account from pubkey --- src/transformers/nostr-to-mastoapi.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/transformers/nostr-to-mastoapi.ts b/src/transformers/nostr-to-mastoapi.ts index 0bf09f3..b827df3 100644 --- a/src/transformers/nostr-to-mastoapi.ts +++ b/src/transformers/nostr-to-mastoapi.ts @@ -117,8 +117,7 @@ async function toMention(pubkey: string) { async function toStatus(event: Event<1>, viewerPubkey?: string) { const profile = await getAuthor(event.pubkey); - const account = profile ? await toAccount(profile) : undefined; - if (!account) return; + const account = profile ? await toAccount(profile) : await accountFromPubkey(event.pubkey); const replyTag = findReplyTag(event);