Rework auth tokens table to use hashed/encrypted data

This commit is contained in:
Alex Gleason
2024-10-02 18:28:24 -05:00
parent e73a8d71dc
commit 432857c2ff
6 changed files with 102 additions and 44 deletions

View File

@@ -4,7 +4,7 @@ import { NPostgresSchema } from '@nostrify/db';
export interface DittoTables extends NPostgresSchema {
nostr_events: NostrEventsRow;
nip46_tokens: NIP46TokenRow;
auth_tokens: AuthTokenRow;
author_stats: AuthorStatsRow;
event_stats: EventStatsRow;
pubkey_domains: PubkeyDomainRow;
@@ -33,13 +33,12 @@ interface EventStatsRow {
zaps_amount: number;
}
interface NIP46TokenRow {
api_token: string;
user_pubkey: string;
server_seckey: Uint8Array;
server_pubkey: string;
relays: string;
connected_at: Date;
interface AuthTokenRow {
token_hash: Uint8Array;
pubkey: string;
nip46_sk_enc: Uint8Array;
nip46_relays: string[];
created_at: Date;
}
interface PubkeyDomainRow {

View File

@@ -0,0 +1,52 @@
import { Kysely, sql } from 'kysely';
import { encryptSecretKey, getTokenHash } from '@/utils/auth.ts';
import { Conf } from '@/config.ts';
interface DB {
nip46_tokens: {
api_token: `token1${string}`;
user_pubkey: string;
server_seckey: Uint8Array;
server_pubkey: string;
relays: string;
connected_at: Date;
};
auth_tokens: {
token_hash: Uint8Array;
pubkey: string;
nip46_sk_enc: Uint8Array;
nip46_relays: string[];
created_at: Date;
};
}
export async function up(db: Kysely<DB>): Promise<void> {
await db.schema
.createTable('auth_tokens')
.addColumn('token_hash', 'bytea', (col) => col.primaryKey())
.addColumn('pubkey', 'char(64)', (col) => col.notNull())
.addColumn('nip46_sk_enc', 'bytea', (col) => col.notNull())
.addColumn('nip46_relays', 'jsonb', (col) => col.defaultTo('[]'))
.addColumn('created_at', 'timestamp', (col) => col.defaultTo(sql`CURRENT_TIMESTAMP`))
.execute();
// There are probably not that many tokens in the database yet, so this should be fine.
const tokens = await db.selectFrom('nip46_tokens').selectAll().execute();
for (const token of tokens) {
await db.insertInto('auth_tokens').values({
token_hash: await getTokenHash(token.api_token),
pubkey: token.user_pubkey,
nip46_sk_enc: await encryptSecretKey(Conf.seckey, token.server_seckey),
nip46_relays: JSON.parse(token.relays),
created_at: token.connected_at,
}).execute();
}
await db.schema.dropTable('nip46_tokens').execute();
}
export async function down(db: Kysely<DB>): Promise<void> {
await db.schema.dropTable('auth_tokens').execute();
}