signerMiddleware: accept token1 bech32's

This commit is contained in:
Alex Gleason
2024-05-26 20:18:49 -05:00
parent 0141a732c3
commit b1a497b127
4 changed files with 63 additions and 26 deletions

View File

@@ -1,11 +1,11 @@
import { NSecSigner } from '@nostrify/nostrify';
import { Stickynotes } from '@soapbox/stickynotes';
import { nip19 } from 'nostr-tools';
import { AppMiddleware } from '@/app.ts';
import { ConnectSigner } from '@/signers/ConnectSigner.ts';
const console = new Stickynotes('ditto:signerMiddleware');
import { ReadOnlySigner } from '@/signers/ReadOnlySigner.ts';
import { HTTPException } from 'hono';
import { DittoDB } from '@/db/DittoDB.ts';
/** We only accept "Bearer" type. */
const BEARER_REGEX = new RegExp(`^Bearer (${nip19.BECH32_REGEX.source})$`);
@@ -18,22 +18,38 @@ export const signerMiddleware: AppMiddleware = async (c, next) => {
if (match) {
const [_, bech32] = match;
try {
const decoded = nip19.decode(bech32!);
if (bech32.startsWith('token1')) {
try {
const kysely = await DittoDB.getInstance();
switch (decoded.type) {
case 'npub':
c.set('signer', new ConnectSigner(decoded.data));
break;
case 'nprofile':
c.set('signer', new ConnectSigner(decoded.data.pubkey, decoded.data.relays));
break;
case 'nsec':
c.set('signer', new NSecSigner(decoded.data));
break;
const { user_pubkey, server_seckey, relays } = await kysely
.selectFrom('connections')
.select(['user_pubkey', 'server_seckey', 'relays'])
.where('api_token', '=', bech32)
.executeTakeFirstOrThrow();
c.set('signer', new ConnectSigner(user_pubkey, new NSecSigner(server_seckey), JSON.parse(relays)));
} catch {
throw new HTTPException(401);
}
} else {
try {
const decoded = nip19.decode(bech32!);
switch (decoded.type) {
case 'npub':
c.set('signer', new ReadOnlySigner(decoded.data));
break;
case 'nprofile':
c.set('signer', new ReadOnlySigner(decoded.data.pubkey));
break;
case 'nsec':
c.set('signer', new NSecSigner(decoded.data));
break;
}
} catch {
throw new HTTPException(401);
}
} catch {
console.debug('The user is not logged in');
}
}