From 23bedd82a068dbbfedab4f7dedd40b4d90ccc10a Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 2 Oct 2024 13:35:34 -0500 Subject: [PATCH 1/6] utils: remove unused sha256 text function --- src/utils.ts | 16 +--------------- 1 file changed, 1 insertion(+), 15 deletions(-) diff --git a/src/utils.ts b/src/utils.ts index e361109d..ae257374 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -64,20 +64,6 @@ function findTag(tags: string[][], name: string): string[] | undefined { return tags.find((tag) => tag[0] === name); } -/** - * Get sha256 hash (hex) of some text. - * https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest#converting_a_digest_to_a_hex_string - */ -async function sha256(message: string): Promise { - const msgUint8 = new TextEncoder().encode(message); - const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8); - const hashArray = Array.from(new Uint8Array(hashBuffer)); - const hashHex = hashArray - .map((b) => b.toString(16).padStart(2, '0')) - .join(''); - return hashHex; -} - /** Test whether the value is a Nostr ID. */ function isNostrId(value: unknown): boolean { return n.id().safeParse(value).success; @@ -88,6 +74,6 @@ function isURL(value: unknown): boolean { return z.string().url().safeParse(value).success; } -export { bech32ToPubkey, eventAge, findTag, isNostrId, isURL, type Nip05, nostrDate, nostrNow, parseNip05, sha256 }; +export { bech32ToPubkey, eventAge, findTag, isNostrId, isURL, type Nip05, nostrDate, nostrNow, parseNip05 }; export { Time } from '@/utils/time.ts'; From 1d2bf07460290b587240415492f21a3b182e14da Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 2 Oct 2024 13:44:50 -0500 Subject: [PATCH 2/6] Remove unused nostr-relaypool library --- deno.json | 30 +++++++++++++++++++++++------- deno.lock | 35 ----------------------------------- 2 files changed, 23 insertions(+), 42 deletions(-) diff --git a/deno.json b/deno.json index 00ab104f..b081f323 100644 --- a/deno.json +++ b/deno.json @@ -22,8 +22,15 @@ "clean:deps": "deno cache --reload src/app.ts", "db:populate-search": "deno run -A scripts/db-populate-search.ts" }, - "unstable": ["cron", "ffi", "kv", "worker-options"], - "exclude": ["./public"], + "unstable": [ + "cron", + "ffi", + "kv", + "worker-options" + ], + "exclude": [ + "./public" + ], "imports": { "@/": "./src/", "@b-fuze/deno-dom": "jsr:@b-fuze/deno-dom@^0.1.47", @@ -68,7 +75,6 @@ "linkify-string": "npm:linkify-string@^4.1.1", "linkifyjs": "npm:linkifyjs@^4.1.1", "lru-cache": "npm:lru-cache@^10.2.2", - "nostr-relaypool": "npm:nostr-relaypool2@0.6.34", "nostr-tools": "npm:nostr-tools@2.5.1", "nostr-wasm": "npm:nostr-wasm@^0.1.0", "path-to-regexp": "npm:path-to-regexp@^7.1.0", @@ -84,14 +90,24 @@ "~/fixtures/": "./fixtures/" }, "lint": { - "include": ["src/", "scripts/"], + "include": [ + "src/", + "scripts/" + ], "rules": { - "tags": ["recommended"], - "exclude": ["no-explicit-any"] + "tags": [ + "recommended" + ], + "exclude": [ + "no-explicit-any" + ] } }, "fmt": { - "include": ["src/", "scripts/"], + "include": [ + "src/", + "scripts/" + ], "useTabs": false, "lineWidth": 120, "indentWidth": 2, diff --git a/deno.lock b/deno.lock index b64f2f95..7b7e7d1c 100644 --- a/deno.lock +++ b/deno.lock @@ -97,7 +97,6 @@ "npm:lint-staged": "npm:lint-staged@15.2.2", "npm:lru-cache@^10.2.0": "npm:lru-cache@10.2.2", "npm:lru-cache@^10.2.2": "npm:lru-cache@10.2.2", - "npm:nostr-relaypool2@0.6.34": "npm:nostr-relaypool2@0.6.34", "npm:nostr-tools@2.5.1": "npm:nostr-tools@2.5.1", "npm:nostr-tools@^2.5.0": "npm:nostr-tools@2.5.1", "npm:nostr-tools@^2.7.0": "npm:nostr-tools@2.7.0", @@ -583,10 +582,6 @@ "integrity": "sha512-RQgQ4uQ+pLbqXfOmieB91ejmLwvSgv9nLx6sT6sD83s7umBypgg+OIBOBbEUiJXrfpnp9j0mRhYYdzp9uqq3lA==", "dependencies": {} }, - "@noble/ciphers@0.2.0": { - "integrity": "sha512-6YBxJDAapHSdd3bLDv6x2wRPwq4QFMUaB3HvljNBUTThDd12eSm7/3F+2lnfzx2jvM+S6Nsy0jEt9QbPqSwqRw==", - "dependencies": {} - }, "@noble/ciphers@0.5.3": { "integrity": "sha512-B0+6IIHiqEs3BPMT0hcRmHvEj2QHOLu+uwt+tqDDeVd0oyVzh7BPrDcPjRnV1PV/5LaknXJJQvOuRGR0zQJz+w==", "dependencies": {} @@ -988,12 +983,6 @@ "jsdom": "jsdom@24.0.0" } }, - "isomorphic-ws@5.0.0_ws@8.17.0": { - "integrity": "sha512-muId7Zzn9ywDsyXgTIafTry2sV3nySZeUDe6YedVd1Hvuuep5AsIlqK+XefWpYTyJG5e503F2xIuT2lcU6rCSw==", - "dependencies": { - "ws": "ws@8.17.0" - } - }, "jsdom@24.0.0": { "integrity": "sha512-UDS2NayCvmXSXVP6mpTj+73JnNQadZlr9N68189xib2tx5Mls7swlTNao26IoHv46BZJFvXygyRtyXd1feAk1A==", "dependencies": { @@ -1154,25 +1143,6 @@ "whatwg-url": "whatwg-url@5.0.0" } }, - "nostr-relaypool2@0.6.34": { - "integrity": "sha512-e3FDh9w/wQkY513mvoJps1Hc/Y5wiWXeBM6MD+YKSyAg+px+/8uHSSHAuHhlavw7oOEOvEsIGlMDMc57DG3MOA==", - "dependencies": { - "isomorphic-ws": "isomorphic-ws@5.0.0_ws@8.17.0", - "nostr-tools": "nostr-tools@1.17.0", - "safe-stable-stringify": "safe-stable-stringify@2.4.3" - } - }, - "nostr-tools@1.17.0": { - "integrity": "sha512-LZmR8GEWKZeElbFV5Xte75dOeE9EFUW/QLI1Ncn3JKn0kFddDKEfBbFN8Mu4TMs+L4HR/WTPha2l+PPuRnJcMw==", - "dependencies": { - "@noble/ciphers": "@noble/ciphers@0.2.0", - "@noble/curves": "@noble/curves@1.1.0", - "@noble/hashes": "@noble/hashes@1.3.1", - "@scure/base": "@scure/base@1.1.1", - "@scure/bip32": "@scure/bip32@1.3.1", - "@scure/bip39": "@scure/bip39@1.2.1" - } - }, "nostr-tools@2.5.1": { "integrity": "sha512-bpkhGGAhdiCN0irfV+xoH3YP5CQeOXyXzUq7SYeM6D56xwTXZCPEmBlUGqFVfQidvRsoVeVxeAiOXW2c2HxoRQ==", "dependencies": { @@ -1303,10 +1273,6 @@ "integrity": "sha512-APM0Gt1KoXBz0iIkkdB/kfvGOwC4UuJFeG/c+yV7wSc7q96cG/kJ0HiYCnzivD9SB53cLV1MlHFNfOuPaadYSw==", "dependencies": {} }, - "safe-stable-stringify@2.4.3": { - "integrity": "sha512-e2bDA2WJT0wxseVd4lsDP4+3ONX6HpMXQa1ZhFQ7SU+GjvORCmShbCMltrtIDfkYhVHrOcPtj+KhmDBdPdZD1g==", - "dependencies": {} - }, "safer-buffer@2.1.2": { "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", "dependencies": {} @@ -2183,7 +2149,6 @@ "npm:linkify-string@^4.1.1", "npm:linkifyjs@^4.1.1", "npm:lru-cache@^10.2.2", - "npm:nostr-relaypool2@0.6.34", "npm:nostr-tools@2.5.1", "npm:nostr-wasm@^0.1.0", "npm:path-to-regexp@^7.1.0", From 70f56af281c40013283a05f693e03f936c4a27e5 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 2 Oct 2024 15:05:37 -0500 Subject: [PATCH 3/6] Add auth utils for generating/hashing/encoding/decoding tokens --- src/utils/auth.bench.ts | 11 +++++++++++ src/utils/auth.test.ts | 18 ++++++++++++++++++ src/utils/auth.ts | 30 ++++++++++++++++++++++++++++++ 3 files changed, 59 insertions(+) create mode 100644 src/utils/auth.bench.ts create mode 100644 src/utils/auth.test.ts create mode 100644 src/utils/auth.ts diff --git a/src/utils/auth.bench.ts b/src/utils/auth.bench.ts new file mode 100644 index 00000000..fbffc857 --- /dev/null +++ b/src/utils/auth.bench.ts @@ -0,0 +1,11 @@ +import { generateToken, getTokenHash } from '@/utils/auth.ts'; + +Deno.bench('generateToken', async () => { + await generateToken(); +}); + +Deno.bench('getTokenHash', async (b) => { + const { token } = await generateToken(); + b.start(); + await getTokenHash(token); +}); diff --git a/src/utils/auth.test.ts b/src/utils/auth.test.ts new file mode 100644 index 00000000..a0256b5d --- /dev/null +++ b/src/utils/auth.test.ts @@ -0,0 +1,18 @@ +import { assertEquals } from '@std/assert'; +import { decodeHex } from '@std/encoding/hex'; + +import { generateToken, getTokenHash } from '@/utils/auth.ts'; + +Deno.test('generateToken', async () => { + const sk = decodeHex('a0968751df8fd42f362213f08751911672f2a037113b392403bbb7dd31b71c95'); + + const { token, hash } = await generateToken(sk); + + assertEquals(token, 'token15ztgw5wl3l2z7d3zz0cgw5v3zee09gphzyanjfqrhwma6vdhrj2sauwknd'); + assertEquals(hash, decodeHex('ab4c4ead4d1c72a38fffd45b999937b7e3f25f867b19aaf252df858e77b66a8a')); +}); + +Deno.test('getTokenHash', async () => { + const hash = await getTokenHash('token15ztgw5wl3l2z7d3zz0cgw5v3zee09gphzyanjfqrhwma6vdhrj2sauwknd'); + assertEquals(hash, decodeHex('ab4c4ead4d1c72a38fffd45b999937b7e3f25f867b19aaf252df858e77b66a8a')); +}); diff --git a/src/utils/auth.ts b/src/utils/auth.ts new file mode 100644 index 00000000..8d71ed6f --- /dev/null +++ b/src/utils/auth.ts @@ -0,0 +1,30 @@ +import { bech32 } from '@scure/base'; +import { generateSecretKey } from 'nostr-tools'; + +/** + * Generate an auth token for the API. + * + * Returns a bech32 encoded API token and the SHA-256 hash of the bytes. + * The token should be presented to the user, but only the hash should be stored in the database. + */ +export async function generateToken(sk = generateSecretKey()): Promise<{ token: `token1${string}`; hash: Uint8Array }> { + const words = bech32.toWords(sk); + const token = bech32.encode('token', words); + + const buffer = await crypto.subtle.digest('SHA-256', sk); + const hash = new Uint8Array(buffer); + + return { token, hash }; +} + +/** + * Get the SHA-256 hash of an API token. + * First decodes from bech32 then hashes the bytes. + * Used to identify the user in the database by the hash of their token. + */ +export async function getTokenHash(token: `token1${string}`): Promise { + const { bytes: sk } = bech32.decodeToBytes(token); + const buffer = await crypto.subtle.digest('SHA-256', sk); + + return new Uint8Array(buffer); +} From e73a8d71dc33cb7160b35fc9673e5d428c24dd58 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 2 Oct 2024 17:56:30 -0500 Subject: [PATCH 4/6] auth: add encryptSecretKey & decryptSecretKey functions --- src/utils/auth.bench.ts | 19 ++++++++++++++++++- src/utils/auth.test.ts | 19 +++++++++++++++---- src/utils/auth.ts | 24 ++++++++++++++++++++++++ 3 files changed, 57 insertions(+), 5 deletions(-) diff --git a/src/utils/auth.bench.ts b/src/utils/auth.bench.ts index fbffc857..8c3da7cf 100644 --- a/src/utils/auth.bench.ts +++ b/src/utils/auth.bench.ts @@ -1,4 +1,6 @@ -import { generateToken, getTokenHash } from '@/utils/auth.ts'; +import { generateSecretKey } from 'nostr-tools'; + +import { decryptSecretKey, encryptSecretKey, generateToken, getTokenHash } from '@/utils/auth.ts'; Deno.bench('generateToken', async () => { await generateToken(); @@ -9,3 +11,18 @@ Deno.bench('getTokenHash', async (b) => { b.start(); await getTokenHash(token); }); + +Deno.bench('encryptSecretKey', async (b) => { + const sk = generateSecretKey(); + const decrypted = generateSecretKey(); + b.start(); + await encryptSecretKey(sk, decrypted); +}); + +Deno.bench('decryptSecretKey', async (b) => { + const sk = generateSecretKey(); + const decrypted = generateSecretKey(); + const encrypted = await encryptSecretKey(sk, decrypted); + b.start(); + await decryptSecretKey(sk, encrypted); +}); diff --git a/src/utils/auth.test.ts b/src/utils/auth.test.ts index a0256b5d..e9e610c1 100644 --- a/src/utils/auth.test.ts +++ b/src/utils/auth.test.ts @@ -1,7 +1,8 @@ import { assertEquals } from '@std/assert'; -import { decodeHex } from '@std/encoding/hex'; +import { decodeHex, encodeHex } from '@std/encoding/hex'; +import { generateSecretKey } from 'nostr-tools'; -import { generateToken, getTokenHash } from '@/utils/auth.ts'; +import { decryptSecretKey, encryptSecretKey, generateToken, getTokenHash } from '@/utils/auth.ts'; Deno.test('generateToken', async () => { const sk = decodeHex('a0968751df8fd42f362213f08751911672f2a037113b392403bbb7dd31b71c95'); @@ -9,10 +10,20 @@ Deno.test('generateToken', async () => { const { token, hash } = await generateToken(sk); assertEquals(token, 'token15ztgw5wl3l2z7d3zz0cgw5v3zee09gphzyanjfqrhwma6vdhrj2sauwknd'); - assertEquals(hash, decodeHex('ab4c4ead4d1c72a38fffd45b999937b7e3f25f867b19aaf252df858e77b66a8a')); + assertEquals(encodeHex(hash), 'ab4c4ead4d1c72a38fffd45b999937b7e3f25f867b19aaf252df858e77b66a8a'); }); Deno.test('getTokenHash', async () => { const hash = await getTokenHash('token15ztgw5wl3l2z7d3zz0cgw5v3zee09gphzyanjfqrhwma6vdhrj2sauwknd'); - assertEquals(hash, decodeHex('ab4c4ead4d1c72a38fffd45b999937b7e3f25f867b19aaf252df858e77b66a8a')); + assertEquals(encodeHex(hash), 'ab4c4ead4d1c72a38fffd45b999937b7e3f25f867b19aaf252df858e77b66a8a'); +}); + +Deno.test('encryptSecretKey & decryptSecretKey', async () => { + const sk = generateSecretKey(); + const data = generateSecretKey(); + + const encrypted = await encryptSecretKey(sk, data); + const decrypted = await decryptSecretKey(sk, encrypted); + + assertEquals(encodeHex(decrypted), encodeHex(data)); }); diff --git a/src/utils/auth.ts b/src/utils/auth.ts index 8d71ed6f..05e838a9 100644 --- a/src/utils/auth.ts +++ b/src/utils/auth.ts @@ -28,3 +28,27 @@ export async function getTokenHash(token: `token1${string}`): Promise { + const secretKey = await crypto.subtle.importKey('raw', sk, { name: 'AES-GCM' }, false, ['encrypt']); + const iv = crypto.getRandomValues(new Uint8Array(12)); + const buffer = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, secretKey, decrypted); + + return new Uint8Array([...iv, ...new Uint8Array(buffer)]); +} + +/** + * Decrypt a secret key with AES-GCM. + * This function is used to retrieve the secret key from the database. + */ +export async function decryptSecretKey(sk: Uint8Array, encrypted: Uint8Array): Promise { + const secretKey = await crypto.subtle.importKey('raw', sk, { name: 'AES-GCM' }, false, ['decrypt']); + const iv = encrypted.slice(0, 12); + const buffer = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, secretKey, encrypted.slice(12)); + + return new Uint8Array(buffer); +} From 432857c2ff593630cfec99f54eaf4223c75a833e Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 2 Oct 2024 18:28:24 -0500 Subject: [PATCH 5/6] Rework auth tokens table to use hashed/encrypted data --- src/controllers/api/oauth.ts | 32 +++++++---------- src/controllers/api/streaming.ts | 12 ++++--- src/db/DittoTables.ts | 15 ++++---- src/db/migrations/037_auth_tokens.ts | 52 ++++++++++++++++++++++++++++ src/middleware/signerMiddleware.ts | 15 +++++--- src/utils/nip98.ts | 20 +++++++---- 6 files changed, 102 insertions(+), 44 deletions(-) create mode 100644 src/db/migrations/037_auth_tokens.ts diff --git a/src/controllers/api/oauth.ts b/src/controllers/api/oauth.ts index 94aaeecd..c4c3eca4 100644 --- a/src/controllers/api/oauth.ts +++ b/src/controllers/api/oauth.ts @@ -1,14 +1,14 @@ import { NConnectSigner, NSchema as n, NSecSigner } from '@nostrify/nostrify'; -import { bech32 } from '@scure/base'; import { escape } from 'entities'; -import { generateSecretKey, getPublicKey } from 'nostr-tools'; +import { generateSecretKey } from 'nostr-tools'; import { z } from 'zod'; import { AppController } from '@/app.ts'; import { Conf } from '@/config.ts'; +import { Storages } from '@/storages.ts'; import { nostrNow } from '@/utils.ts'; import { parseBody } from '@/utils/api.ts'; -import { Storages } from '@/storages.ts'; +import { encryptSecretKey, generateToken } from '@/utils/auth.ts'; const passwordGrantSchema = z.object({ grant_type: z.literal('password'), @@ -82,38 +82,30 @@ async function getToken( { pubkey, secret, relays = [] }: { pubkey: string; secret?: string; relays?: string[] }, ): Promise<`token1${string}`> { const kysely = await Storages.kysely(); - const token = generateToken(); + const { token, hash } = await generateToken(); - const serverSeckey = generateSecretKey(); - const serverPubkey = getPublicKey(serverSeckey); + const nip46Seckey = generateSecretKey(); const signer = new NConnectSigner({ pubkey, - signer: new NSecSigner(serverSeckey), + signer: new NSecSigner(nip46Seckey), relay: await Storages.pubsub(), // TODO: Use the relays from the request. timeout: 60_000, }); await signer.connect(secret); - await kysely.insertInto('nip46_tokens').values({ - api_token: token, - user_pubkey: pubkey, - server_seckey: serverSeckey, - server_pubkey: serverPubkey, - relays: JSON.stringify(relays), - connected_at: new Date(), + await kysely.insertInto('auth_tokens').values({ + token_hash: hash, + pubkey, + nip46_sk_enc: await encryptSecretKey(Conf.seckey, nip46Seckey), + nip46_relays: relays, + created_at: new Date(), }).execute(); return token; } -/** Generate a bech32 token for the API. */ -function generateToken(): `token1${string}` { - const words = bech32.toWords(generateSecretKey()); - return bech32.encode('token', words); -} - /** Display the OAuth form. */ const oauthController: AppController = (c) => { const encodedUri = c.req.query('redirect_uri'); diff --git a/src/controllers/api/streaming.ts b/src/controllers/api/streaming.ts index cee7c57e..9693a16c 100644 --- a/src/controllers/api/streaming.ts +++ b/src/controllers/api/streaming.ts @@ -14,6 +14,7 @@ import { MuteListPolicy } from '@/policies/MuteListPolicy.ts'; import { getFeedPubkeys } from '@/queries.ts'; import { hydrateEvents } from '@/storages/hydrate.ts'; import { Storages } from '@/storages.ts'; +import { getTokenHash } from '@/utils/auth.ts'; import { bech32ToPubkey, Time } from '@/utils.ts'; import { renderReblog, renderStatus } from '@/views/mastodon/statuses.ts'; import { renderNotification } from '@/views/mastodon/notifications.ts'; @@ -233,14 +234,15 @@ async function topicToFilter( async function getTokenPubkey(token: string): Promise { if (token.startsWith('token1')) { const kysely = await Storages.kysely(); + const tokenHash = await getTokenHash(token as `token1${string}`); - const { user_pubkey } = await kysely - .selectFrom('nip46_tokens') - .select(['user_pubkey', 'server_seckey', 'relays']) - .where('api_token', '=', token) + const { pubkey } = await kysely + .selectFrom('auth_tokens') + .select('pubkey') + .where('token_hash', '=', tokenHash) .executeTakeFirstOrThrow(); - return user_pubkey; + return pubkey; } else { return bech32ToPubkey(token); } diff --git a/src/db/DittoTables.ts b/src/db/DittoTables.ts index c05ffe66..b6fa93f4 100644 --- a/src/db/DittoTables.ts +++ b/src/db/DittoTables.ts @@ -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 { diff --git a/src/db/migrations/037_auth_tokens.ts b/src/db/migrations/037_auth_tokens.ts new file mode 100644 index 00000000..9df133f5 --- /dev/null +++ b/src/db/migrations/037_auth_tokens.ts @@ -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): Promise { + 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): Promise { + await db.schema.dropTable('auth_tokens').execute(); +} diff --git a/src/middleware/signerMiddleware.ts b/src/middleware/signerMiddleware.ts index 344e14ef..8200ae1d 100644 --- a/src/middleware/signerMiddleware.ts +++ b/src/middleware/signerMiddleware.ts @@ -3,9 +3,11 @@ import { NSecSigner } from '@nostrify/nostrify'; import { nip19 } from 'nostr-tools'; import { AppMiddleware } from '@/app.ts'; +import { Conf } from '@/config.ts'; import { ConnectSigner } from '@/signers/ConnectSigner.ts'; import { ReadOnlySigner } from '@/signers/ReadOnlySigner.ts'; import { Storages } from '@/storages.ts'; +import { decryptSecretKey, getTokenHash } from '@/utils/auth.ts'; /** We only accept "Bearer" type. */ const BEARER_REGEX = new RegExp(`^Bearer (${nip19.BECH32_REGEX.source})$`); @@ -21,14 +23,17 @@ export const signerMiddleware: AppMiddleware = async (c, next) => { if (bech32.startsWith('token1')) { try { const kysely = await Storages.kysely(); + const tokenHash = await getTokenHash(bech32 as `token1${string}`); - const { user_pubkey, server_seckey, relays } = await kysely - .selectFrom('nip46_tokens') - .select(['user_pubkey', 'server_seckey', 'relays']) - .where('api_token', '=', bech32) + const { pubkey, nip46_sk_enc, nip46_relays } = await kysely + .selectFrom('auth_tokens') + .select(['pubkey', 'nip46_sk_enc', 'nip46_relays']) + .where('token_hash', '=', tokenHash) .executeTakeFirstOrThrow(); - c.set('signer', new ConnectSigner(user_pubkey, new NSecSigner(server_seckey), JSON.parse(relays))); + const nep46Seckey = await decryptSecretKey(Conf.seckey, nip46_sk_enc); + + c.set('signer', new ConnectSigner(pubkey, new NSecSigner(nep46Seckey), nip46_relays)); } catch { throw new HTTPException(401); } diff --git a/src/utils/nip98.ts b/src/utils/nip98.ts index c33da877..f83fcddb 100644 --- a/src/utils/nip98.ts +++ b/src/utils/nip98.ts @@ -1,9 +1,10 @@ import { NostrEvent, NSchema as n } from '@nostrify/nostrify'; +import { encodeHex } from '@std/encoding/hex'; import { EventTemplate, nip13 } from 'nostr-tools'; import { decode64Schema } from '@/schema.ts'; import { signedEventSchema } from '@/schemas/nostr.ts'; -import { eventAge, findTag, nostrNow, sha256 } from '@/utils.ts'; +import { eventAge, findTag, nostrNow } from '@/utils.ts'; import { Time } from '@/utils/time.ts'; /** Decode a Nostr event from a base64 encoded string. */ @@ -41,11 +42,10 @@ function validateAuthEvent(req: Request, event: NostrEvent, opts: ParseAuthReque .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: NostrEvent) { + async function validateBody(event: NostrEvent): Promise { if (!validatePayload) return true; - return req.clone().text() - .then(sha256) - .then((hash) => hash === tagValue(event, 'payload')); + const payload = await getPayload(req); + return payload === tagValue(event, 'payload'); } return schema.safeParseAsync(event); @@ -62,7 +62,7 @@ async function buildAuthEventTemplate(req: Request, opts: ParseAuthRequestOpts = ]; if (validatePayload) { - const payload = await req.clone().text().then(sha256); + const payload = await getPayload(req); tags.push(['payload', payload]); } @@ -74,6 +74,14 @@ async function buildAuthEventTemplate(req: Request, opts: ParseAuthRequestOpts = }; } +/** Get a SHA-256 hash of the request body encoded as a hex string. */ +async function getPayload(req: Request): Promise { + const text = await req.clone().text(); + const bytes = new TextEncoder().encode(text); + const buffer = await crypto.subtle.digest('SHA-256', bytes); + return encodeHex(buffer); +} + /** Get the value for the first matching tag name in the event. */ function tagValue(event: NostrEvent, tagName: string): string | undefined { return findTag(event.tags, tagName)?.[1]; From ff361a410662ae11993e915493d3a60a698d0378 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 2 Oct 2024 18:34:19 -0500 Subject: [PATCH 6/6] Recreate nip46_tokens in down migration --- src/db/migrations/037_auth_tokens.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/db/migrations/037_auth_tokens.ts b/src/db/migrations/037_auth_tokens.ts index 9df133f5..71e971d3 100644 --- a/src/db/migrations/037_auth_tokens.ts +++ b/src/db/migrations/037_auth_tokens.ts @@ -49,4 +49,14 @@ export async function up(db: Kysely): Promise { export async function down(db: Kysely): Promise { await db.schema.dropTable('auth_tokens').execute(); + + await db.schema + .createTable('nip46_tokens') + .addColumn('api_token', 'text', (col) => col.primaryKey().unique().notNull()) + .addColumn('user_pubkey', 'text', (col) => col.notNull()) + .addColumn('server_seckey', 'bytea', (col) => col.notNull()) + .addColumn('server_pubkey', 'text', (col) => col.notNull()) + .addColumn('relays', 'text', (col) => col.defaultTo('[]')) + .addColumn('connected_at', 'timestamp', (col) => col.defaultTo(sql`CURRENT_TIMESTAMP`)) + .execute(); }