Remove Conf from middleware

This commit is contained in:
Alex Gleason 2025-02-15 18:43:59 -06:00
parent 8d2c83bb09
commit d0d37f5948
No known key found for this signature in database
GPG key ID: 7211D1F99744FBB7
6 changed files with 26 additions and 20 deletions

View file

@ -11,7 +11,6 @@ import {
type ParseAuthRequestOpts, type ParseAuthRequestOpts,
validateAuthEvent, validateAuthEvent,
} from '@/utils/nip98.ts'; } from '@/utils/nip98.ts';
import { Conf } from '@/config.ts';
/** /**
* NIP-98 auth. * NIP-98 auth.
@ -35,12 +34,13 @@ 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 withProof(async (_c, proof, next) => { return withProof(async (c, proof, next) => {
const { conf } = c.var;
const store = await Storages.db(); const store = await Storages.db();
const [user] = await store.query([{ const [user] = await store.query([{
kinds: [30382], kinds: [30382],
authors: [Conf.pubkey], authors: [conf.pubkey],
'#d': [proof.pubkey], '#d': [proof.pubkey],
limit: 1, limit: 1,
}]); }]);

View file

@ -1,5 +1,4 @@
import { AppMiddleware } from '@/app.ts'; import { AppMiddleware } from '@/app.ts';
import { Conf } from '@/config.ts';
import { PleromaConfigDB } from '@/utils/PleromaConfigDB.ts'; import { PleromaConfigDB } from '@/utils/PleromaConfigDB.ts';
import { Storages } from '@/storages.ts'; import { Storages } from '@/storages.ts';
import { getPleromaConfigs } from '@/utils/pleroma.ts'; import { getPleromaConfigs } from '@/utils/pleroma.ts';
@ -8,13 +7,14 @@ let configDBCache: Promise<PleromaConfigDB> | undefined;
export const cspMiddleware = (): AppMiddleware => { export const cspMiddleware = (): AppMiddleware => {
return async (c, next) => { return async (c, next) => {
const { conf } = c.var;
const store = await Storages.db(); const store = await Storages.db();
if (!configDBCache) { if (!configDBCache) {
configDBCache = getPleromaConfigs(store); configDBCache = getPleromaConfigs(store);
} }
const { host, protocol, origin } = Conf.url; const { host, protocol, origin } = conf.url;
const wsProtocol = protocol === 'http:' ? 'ws:' : 'wss:'; const wsProtocol = protocol === 'http:' ? 'ws:' : 'wss:';
const configDB = await configDBCache; const configDB = await configDBCache;
const sentryDsn = configDB.getIn(':pleroma', ':frontend_configurations', ':soapbox_fe', 'sentryDsn'); const sentryDsn = configDB.getIn(':pleroma', ':frontend_configurations', ':soapbox_fe', 'sentryDsn');

View file

@ -1,14 +1,13 @@
import { type DittoConf } from '@ditto/conf';
import { MiddlewareHandler } from '@hono/hono'; import { MiddlewareHandler } from '@hono/hono';
import { rateLimiter } from 'hono-rate-limiter'; import { rateLimiter } from 'hono-rate-limiter';
import { Conf } from '@/config.ts';
/** /**
* Rate limit middleware for Hono, based on [`hono-rate-limiter`](https://github.com/rhinobase/hono-rate-limiter). * Rate limit middleware for Hono, based on [`hono-rate-limiter`](https://github.com/rhinobase/hono-rate-limiter).
*/ */
export function rateLimitMiddleware(limit: number, windowMs: number, includeHeaders?: boolean): MiddlewareHandler { export function rateLimitMiddleware(limit: number, windowMs: number, includeHeaders?: boolean): MiddlewareHandler {
// @ts-ignore Mismatched hono versions. // @ts-ignore Mismatched hono versions.
return rateLimiter({ return rateLimiter<{ Variables: { conf: DittoConf } }>({
limit, limit,
windowMs, windowMs,
standardHeaders: includeHeaders, standardHeaders: includeHeaders,
@ -17,8 +16,9 @@ export function rateLimitMiddleware(limit: number, windowMs: number, includeHead
return c.text('Too many requests, please try again later.', 429); return c.text('Too many requests, please try again later.', 429);
}, },
skip: (c) => { skip: (c) => {
const { conf } = c.var;
const ip = c.req.header('x-real-ip'); const ip = c.req.header('x-real-ip');
return !ip || Conf.ipWhitelist.includes(ip); return !ip || conf.ipWhitelist.includes(ip);
}, },
keyGenerator: (c) => c.req.header('x-real-ip')!, keyGenerator: (c) => c.req.header('x-real-ip')!,
}); });

View file

@ -1,9 +1,9 @@
import { type DittoConf } from '@ditto/conf';
import { MiddlewareHandler } from '@hono/hono'; import { MiddlewareHandler } from '@hono/hono';
import { HTTPException } from '@hono/hono/http-exception'; import { HTTPException } from '@hono/hono/http-exception';
import { NostrSigner, NSecSigner } from '@nostrify/nostrify'; import { NostrSigner, NSecSigner } from '@nostrify/nostrify';
import { nip19 } from 'nostr-tools'; import { nip19 } from 'nostr-tools';
import { Conf } from '@/config.ts';
import { ConnectSigner } from '@/signers/ConnectSigner.ts'; import { ConnectSigner } from '@/signers/ConnectSigner.ts';
import { ReadOnlySigner } from '@/signers/ReadOnlySigner.ts'; import { ReadOnlySigner } from '@/signers/ReadOnlySigner.ts';
import { Storages } from '@/storages.ts'; import { Storages } from '@/storages.ts';
@ -14,7 +14,11 @@ import { getTokenHash } from '@/utils/auth.ts';
const BEARER_REGEX = new RegExp(`^Bearer (${nip19.BECH32_REGEX.source})$`); const BEARER_REGEX = new RegExp(`^Bearer (${nip19.BECH32_REGEX.source})$`);
/** Make a `signer` object available to all controllers, or unset if the user isn't logged in. */ /** Make a `signer` object available to all controllers, or unset if the user isn't logged in. */
export const signerMiddleware: MiddlewareHandler<{ Variables: { signer: NostrSigner } }> = async (c, next) => { export const signerMiddleware: MiddlewareHandler<{ Variables: { signer: NostrSigner; conf: DittoConf } }> = async (
c,
next,
) => {
const { conf } = c.var;
const header = c.req.header('authorization'); const header = c.req.header('authorization');
const match = header?.match(BEARER_REGEX); const match = header?.match(BEARER_REGEX);
@ -32,7 +36,7 @@ export const signerMiddleware: MiddlewareHandler<{ Variables: { signer: NostrSig
.where('token_hash', '=', tokenHash) .where('token_hash', '=', tokenHash)
.executeTakeFirstOrThrow(); .executeTakeFirstOrThrow();
const nep46Seckey = await aesDecrypt(Conf.seckey, nip46_sk_enc); const nep46Seckey = await aesDecrypt(conf.seckey, nip46_sk_enc);
c.set( c.set(
'signer', 'signer',

View file

@ -1,4 +1,5 @@
import { CashuMint, CashuWallet, getEncodedToken, type Proof } from '@cashu/cashu-ts'; import { CashuMint, CashuWallet, getEncodedToken, type Proof } from '@cashu/cashu-ts';
import { type DittoConf } from '@ditto/conf';
import { MiddlewareHandler } from '@hono/hono'; import { MiddlewareHandler } from '@hono/hono';
import { HTTPException } from '@hono/hono/http-exception'; import { HTTPException } from '@hono/hono/http-exception';
import { getPublicKey } from 'nostr-tools'; import { getPublicKey } from 'nostr-tools';
@ -9,7 +10,6 @@ import { logi } from '@soapbox/logi';
import { isNostrId } from '@/utils.ts'; import { isNostrId } from '@/utils.ts';
import { errorJson } from '@/utils/log.ts'; import { errorJson } from '@/utils/log.ts';
import { Conf } from '@/config.ts';
import { createEvent } from '@/utils/api.ts'; import { createEvent } from '@/utils/api.ts';
import { z } from 'zod'; import { z } from 'zod';
@ -18,8 +18,9 @@ import { z } from 'zod';
* Errors are only thrown if 'signer' and 'store' middlewares are not set. * Errors are only thrown if 'signer' and 'store' middlewares are not set.
*/ */
export const swapNutzapsMiddleware: MiddlewareHandler< export const swapNutzapsMiddleware: MiddlewareHandler<
{ Variables: { signer: SetRequired<NostrSigner, 'nip44'>; store: NStore } } { Variables: { signer: SetRequired<NostrSigner, 'nip44'>; store: NStore; conf: DittoConf } }
> = async (c, next) => { > = async (c, next) => {
const { conf } = c.var;
const signer = c.get('signer'); const signer = c.get('signer');
const store = c.get('store'); const store = c.get('store');
@ -133,7 +134,7 @@ export const swapNutzapsMiddleware: MiddlewareHandler<
[ [
'e', // nutzap event that has been redeemed 'e', // nutzap event that has been redeemed
event.id, event.id,
Conf.relay, conf.relay,
'redeemed', 'redeemed',
], ],
['p', event.pubkey], // pubkey of the author of the 9321 event (nutzap sender) ['p', event.pubkey], // pubkey of the author of the 9321 event (nutzap sender)
@ -173,7 +174,7 @@ export const swapNutzapsMiddleware: MiddlewareHandler<
JSON.stringify([ JSON.stringify([
['direction', 'in'], ['direction', 'in'],
['amount', amount], ['amount', amount],
['e', unspentProofs.id, Conf.relay, 'created'], ['e', unspentProofs.id, conf.relay, 'created'],
]), ]),
), ),
tags: mintsToProofs[mint].redeemed, tags: mintsToProofs[mint].redeemed,

View file

@ -1,15 +1,16 @@
import { safeFetch } from '@soapbox/safe-fetch'; import { safeFetch } from '@soapbox/safe-fetch';
import { AppMiddleware } from '@/app.ts'; import { AppMiddleware } from '@/app.ts';
import { Conf } from '@/config.ts';
import { DeepLTranslator } from '@/translators/DeepLTranslator.ts'; import { DeepLTranslator } from '@/translators/DeepLTranslator.ts';
import { LibreTranslateTranslator } from '@/translators/LibreTranslateTranslator.ts'; import { LibreTranslateTranslator } from '@/translators/LibreTranslateTranslator.ts';
/** Set the translator used for translating posts. */ /** Set the translator used for translating posts. */
export const translatorMiddleware: AppMiddleware = async (c, next) => { export const translatorMiddleware: AppMiddleware = async (c, next) => {
switch (Conf.translationProvider) { const { conf } = c.var;
switch (conf.translationProvider) {
case 'deepl': { case 'deepl': {
const { deeplApiKey: apiKey, deeplBaseUrl: baseUrl } = Conf; const { deeplApiKey: apiKey, deeplBaseUrl: baseUrl } = conf;
if (apiKey) { if (apiKey) {
c.set('translator', new DeepLTranslator({ baseUrl, apiKey, fetch: safeFetch })); c.set('translator', new DeepLTranslator({ baseUrl, apiKey, fetch: safeFetch }));
} }
@ -17,7 +18,7 @@ export const translatorMiddleware: AppMiddleware = async (c, next) => {
} }
case 'libretranslate': { case 'libretranslate': {
const { libretranslateApiKey: apiKey, libretranslateBaseUrl: baseUrl } = Conf; const { libretranslateApiKey: apiKey, libretranslateBaseUrl: baseUrl } = conf;
if (apiKey) { if (apiKey) {
c.set('translator', new LibreTranslateTranslator({ baseUrl, apiKey, fetch: safeFetch })); c.set('translator', new LibreTranslateTranslator({ baseUrl, apiKey, fetch: safeFetch }));
} }