| 1 | import { type Database, schema } from '@ghost/db'; |
| 2 | import { Inject, Injectable |
| 3 | import { and, eq |
| 4 | import { nanoid } |
| 5 | |
| 6 | import { DATABASE } |
| 7 | import { isoTimestamp } |
| 8 | import { readPublicKey } |
| 9 | import { |
| 10 | GpgKeyAlreadyExistsError, |
| 11 | GpgKeyEmailNotVerifiedError, |
| 12 | GpgKeyNotFoundError, |
| 13 | InvalidGpgKeyError, |
| 14 | } from '../../lib/gpg-keys/gpg-keys.errors.js'; |
| 15 | import { UsersService } |
| 16 | import type { GpgKeyDTO, |
| 17 | |
| 18 | /** A key is only accepted once one of its user ids is an address the account has verified; otherwise anyone could upload a key naming someone else's address. */ |
| 19 | const keyColumns = { |
| 20 | id: schema.userGpgKey |
| 21 | keyId: schema.userGpgKey |
| 22 | fingerprint: schema.userGpgKey |
| 23 | publicKey: schema.userGpgKey |
| 24 | createdAt: isoTimestamp(schema |
| 25 | }; |
| 26 | |
| 27 | @Injectable() |
| 28 | export class GpgKeysService |
| 29 | constructor( |
| 30 | @Inject(DATABASE) |
| 31 | private readonly users |
| 32 | ) {} |
| 33 | |
| 34 | async list(userId |
| 35 | const rows = |
| 36 | .select(keyColumns) |
| 37 | .from(schema.userGpgKey |
| 38 | .where(eq(schema |
| 39 | .orderBy(schema.userGpgKey |
| 40 | |
| 41 | return { |
| 42 | keys: await Promise |
| 43 | rows.map(async |
| 44 | ...key, |
| 45 | // Read back from the armor rather than stored twice: a key's user ids are only ever as current as the armor that was uploaded. |
| 46 | emails: await readPublicKey |
| 47 | .then((parsed) |
| 48 | .catch((): string |
| 49 | })), |
| 50 | ), |
| 51 | }; |
| 52 | } |
| 53 | |
| 54 | async add(userId |
| 55 | const key = |
| 56 | throw new InvalidGpgKeyError( |
| 57 | }); |
| 58 | |
| 59 | if (key.revoked |
| 60 | if (key.expired |
| 61 | |
| 62 | const user = |
| 63 | const owned = |
| 64 | if (!key.emails |
| 65 | throw new GpgKeyEmailNotVerifiedError( |
| 66 | } |
| 67 | |
| 68 | const [row] |
| 69 | .insert(schema.userGpgKey |
| 70 | .values({ |
| 71 | id: `gpg_${nanoid |
| 72 | userId, |
| 73 | keyId: key.keyId |
| 74 | fingerprint: key.fingerprint |
| 75 | publicKey: armoredKey.trim |
| 76 | }) |
| 77 | .onConflictDoNothing() |
| 78 | .returning({ |
| 79 | id: schema.userGpgKey |
| 80 | keyId: schema.userGpgKey |
| 81 | fingerprint: schema.userGpgKey |
| 82 | createdAt: isoTimestamp(schema |
| 83 | }); |
| 84 | |
| 85 | // A key id belongs to one account, so a clash is someone else's key - or this account adding the same one twice. |
| 86 | if (!row) |
| 87 | |
| 88 | return { ...row |
| 89 | } |
| 90 | |
| 91 | async remove(userId |
| 92 | // Ownership is part of the match, so another account's key id deletes nothing rather than deleting theirs. |
| 93 | const [row] |
| 94 | .delete(schema.userGpgKey |
| 95 | .where( |
| 96 | and(eq(schema |
| 97 | ) |
| 98 | .returning({ id: |
| 99 | |
| 100 | if (!row) |
| 101 | } |
| 102 | } |