diff options
| author | Adam Soltys <[email protected]> | 2026-02-28 15:16:20 -0800 |
|---|---|---|
| committer | Adam Soltys <[email protected]> | 2026-02-28 15:16:20 -0800 |
| commit | 32f01e3e328db0006a55c6324625b49d60244b66 (patch) | |
| tree | b97866549b919964957365e1e05681e85af7021a /lib | |
| parent | a1632ae402d11fdd7ffc360de97c55e0b4fad677 (diff) | |
| download | coinos-server-32f01e3e328db0006a55c6324625b49d60244b66.tar.gz coinos-server-32f01e3e328db0006a55c6324625b49d60244b66.zip | |
fix typescript issues
Diffstat (limited to 'lib')
| -rw-r--r-- | lib/app.ts | 8 | ||||
| -rw-r--r-- | lib/ark.ts | 4 | ||||
| -rw-r--r-- | lib/db.ts | 10 | ||||
| -rw-r--r-- | lib/esplora.ts | 6 | ||||
| -rw-r--r-- | lib/health.ts | 4 | ||||
| -rw-r--r-- | lib/ln.ts | 2 | ||||
| -rw-r--r-- | lib/locales/index.ts | 2 | ||||
| -rw-r--r-- | lib/locations.ts | 2 | ||||
| -rw-r--r-- | lib/mail.ts | 3 | ||||
| -rw-r--r-- | lib/migrate.ts | 26 | ||||
| -rw-r--r-- | lib/nostr.ts | 15 | ||||
| -rw-r--r-- | lib/notifications.ts | 10 | ||||
| -rw-r--r-- | lib/nwc.ts | 6 | ||||
| -rw-r--r-- | lib/passkey.ts | 13 | ||||
| -rw-r--r-- | lib/payments.ts | 15 | ||||
| -rw-r--r-- | lib/register.ts | 2 | ||||
| -rw-r--r-- | lib/tb.ts | 7 | ||||
| -rw-r--r-- | lib/upload.ts | 6 | ||||
| -rw-r--r-- | lib/webhooks.ts | 1 | ||||
| -rw-r--r-- | lib/zmq.ts | 4 |
20 files changed, 73 insertions, 73 deletions
@@ -30,7 +30,7 @@ app.use("*", async (c, next) => { // Skip rate limiting for public assets if (url.includes("public")) return next(); - const ip = (c.req.header("cf-connecting-ip") as string) || c.env?.ip || "unknown"; + const ip = (c.req.header("cf-connecting-ip") as string) || (c.env as any)?.ip || "unknown"; const ua = c.req.header("user-agent") || "unknown-ua"; const rateLimitBy = c.req.header("rate-limit-by"); const key = rateLimitBy === "ua" ? ua : ip; @@ -103,7 +103,7 @@ app.use("*", async (c, next) => { if (shouldLog) { const xff = c.req.header("x-forwarded-for"); const forwardedIp = xff?.split(",")[0]?.trim(); - const ip = c.req.header("cf-connecting-ip") || forwardedIp || c.env?.ip || "unknown"; + const ip = c.req.header("cf-connecting-ip") || forwardedIp || (c.env as any)?.ip || "unknown"; let body; // Only parse body for non-GET requests @@ -119,7 +119,7 @@ app.use("*", async (c, next) => { ip, query: c.req.query(), body, - user: c.get("user")?.username, + user: (c.get("user" as never) as any)?.username, }); } @@ -141,7 +141,7 @@ app.use("*", async (c, next) => { }); // Error handler -app.onError((err, c) => { +app.onError((_err, c) => { return c.json({ ok: false }, 500); }); @@ -1,5 +1,5 @@ import { EventSource } from "eventsource"; -if (!globalThis.EventSource) globalThis.EventSource = EventSource; +if (!globalThis.EventSource) globalThis.EventSource = EventSource as any; import config from "$config"; import { SingleKey, Wallet, Ramps, RestArkProvider, VtxoManager } from "@arkade-os/sdk"; @@ -149,6 +149,6 @@ export const verifyArkVtxo = async (hash: string) => { const r = await fetch( `${config.ark.arkServerUrl}/v1/indexer/vtxos?scripts=5120${vtxoHex}&spendable_only=true`, ); - const { vtxos } = await r.json(); + const { vtxos } = await r.json() as any; return vtxos?.some((v: any) => v.outpoint?.txid === hash) ?? false; }; @@ -59,7 +59,7 @@ export default db; export const g = async (k) => { const v = await db.get(k); try { - return JSON.parse(v); + return JSON.parse(v as string); } catch (e) { return v; } @@ -79,7 +79,7 @@ export async function* scan(pattern: string) { export const ga = async (k) => { const v = await archive.get(k); try { - return JSON.parse(v); + return JSON.parse(v as string); } catch (e) { return v; } @@ -98,7 +98,7 @@ export const gf = async (k) => { let v = await db.get(k); if (v === null) v = await archive.get(k); try { - return JSON.parse(v); + return JSON.parse(v as string); } catch (e) { return v; } @@ -116,13 +116,13 @@ export const getWithArchive = async (prefix, id) => { if (v === null) v = await archive.get(`${prefix}:${id}`); if (v === null) return null; try { - const parsed = JSON.parse(v); + const parsed = JSON.parse(v as string); // If it's a reference to another key, follow it if (typeof parsed === "string") { let ref = await db.get(`${prefix}:${parsed}`); if (ref === null) ref = await archive.get(`${prefix}:${parsed}`); if (ref === null) return null; - return JSON.parse(ref); + return JSON.parse(ref as string); } return parsed; } catch (e) { diff --git a/lib/esplora.ts b/lib/esplora.ts index d92fad0c..a2db8100 100644 --- a/lib/esplora.ts +++ b/lib/esplora.ts @@ -37,7 +37,7 @@ export const getAddressUtxos = async (addresses: string[]) => { const results = []; for (const address of addresses) { const utxos = await getUtxos(address); - for (const u of utxos) { + for (const u of utxos as any) { u.address = address; results.push(u); } @@ -98,7 +98,7 @@ const hdVersionsForKey = (pubkey: string) => { export const deriveAddress = ( pubkey: string, - fingerprint: string, + _fingerprint: string, index: number, internal = false, ) => { @@ -140,7 +140,7 @@ export const findLastUsedIndex = async (pubkey: string, fingerprint: string, max for (let i = 0; i < maxScan; i++) { const { address } = deriveAddress(pubkey, fingerprint, i, false); const txs = await getAddressTxs(address); - if (txs.length > 0) lastUsed = i; + if ((txs as any).length > 0) lastUsed = i; } return lastUsed + 1; }; diff --git a/lib/health.ts b/lib/health.ts index fbefa8fa..0502748f 100644 --- a/lib/health.ts +++ b/lib/health.ts @@ -41,7 +41,7 @@ async function checkLightningHealth(): Promise<boolean> { try { l("health check: testing lightning connection..."); - const info = await withTimeout(ln.getinfo(), RPC_TIMEOUT, "getinfo"); + const info = await withTimeout(ln.getinfo(), RPC_TIMEOUT, "getinfo") as any; if (!info?.id) { throw new Error("getinfo returned invalid response (no node id)"); @@ -57,7 +57,7 @@ async function checkLightningHealth(): Promise<boolean> { }), RPC_TIMEOUT, "invoice", - ); + ) as any; if (!invoice?.bolt11) { throw new Error("invoice creation returned invalid response"); @@ -21,7 +21,7 @@ function isSocketDied(e: any) { return code === "EPIPE" || code === "ECONNRESET" || code === "ENOENT" || code === 2; } -function lightningProxy(rpcPath: string) { +function lightningProxy(rpcPath: string): any { let client: any = null; let nextTryAt = 0; diff --git a/lib/locales/index.ts b/lib/locales/index.ts index c902a8d2..3a9ce465 100644 --- a/lib/locales/index.ts +++ b/lib/locales/index.ts @@ -2,6 +2,6 @@ import fs from "fs"; export default "ar,bn,de,el,en,es,fa,fr,hi,it,ja,ko,nl,pl,pt,ru,th,tr,zh" .split(",") .reduce((a, l) => { - a[l] = JSON.parse(fs.readFileSync(`lib/locales/${l}.json`)); + a[l] = JSON.parse(fs.readFileSync(`lib/locales/${l}.json`) as any); return a; }, {}); diff --git a/lib/locations.ts b/lib/locations.ts index 734cd027..ff9eb158 100644 --- a/lib/locations.ts +++ b/lib/locations.ts @@ -53,7 +53,7 @@ export const getLocations = async () => { await s("locations", dedupedLocations); await s("locations:since", `${new Date().toISOString().split(".")[0]}Z`); - for (const loc of dedupedLocations) { + for (const loc of dedupedLocations as any) { if (loc.deleted_at) continue; const { lat, lon } = loc.osm_json; if (!(lat && lon)) continue; diff --git a/lib/mail.ts b/lib/mail.ts index 033902aa..77280390 100644 --- a/lib/mail.ts +++ b/lib/mail.ts @@ -1,10 +1,9 @@ -import { l, err, warn } from "$lib/logging"; +import { l, err } from "$lib/logging"; import config from "$config"; import { SESClient } from "@aws-sdk/client-ses"; import { SendEmailCommand } from "@aws-sdk/client-ses"; import handlebars from "handlebars"; import fs from "fs"; -import path from "path"; const Charset = "UTF-8"; diff --git a/lib/migrate.ts b/lib/migrate.ts index e3cfa9bc..8ea37a06 100644 --- a/lib/migrate.ts +++ b/lib/migrate.ts @@ -25,7 +25,7 @@ export const migrateAccounts = async () => { for (const key of keys) { try { - if (key.endsWith(":invoices")) continue; + if ((key as string).endsWith(":invoices")) continue; const keyType = await db.type(key); if (keyType !== "string") continue; @@ -65,8 +65,8 @@ export const migrateBalancesToTB = async () => { // Migrate balance:* keys for await (const k of scan("balance:*")) { try { - const id = k.split(":")[1]; - const balance = Number.parseInt((await db.get(k)) || "0"); + const id = (k as string).split(":")[1]; + const balance = Number.parseInt(((await db.get(k)) as string) || "0"); await createBalanceAccount(id); if (balance > 0) await tbSetBalance(id, balance); count++; @@ -78,8 +78,8 @@ export const migrateBalancesToTB = async () => { // Migrate pending:* keys for await (const k of scan("pending:*")) { try { - const id = k.split(":")[1]; - const pending = Number.parseInt((await db.get(k)) || "0"); + const id = (k as string).split(":")[1]; + const pending = Number.parseInt(((await db.get(k)) as string) || "0"); if (pending > 0) await tbSetPending(id, pending); } catch (e) { warn("failed to migrate pending", k, e.message); @@ -89,10 +89,10 @@ export const migrateBalancesToTB = async () => { // Migrate credit:*:* keys for await (const k of scan("credit:*:*")) { try { - const parts = k.split(":"); + const parts = (k as string).split(":"); const type = parts[1]; const uid = parts[2]; - const amount = Number.parseInt((await db.get(k)) || "0"); + const amount = Number.parseInt(((await db.get(k)) as string) || "0"); await createCreditAccounts(uid); if (amount > 0) await tbSetCredit(uid, type, amount); } catch (e) { @@ -118,9 +118,9 @@ export const migrateToMicrosats = async () => { if (!raw) continue; // Skip user alias keys (they just contain another key reference) - if (!raw.startsWith("{")) continue; + if (!(raw as string).startsWith("{")) continue; - const user = JSON.parse(raw); + const user = JSON.parse(raw as string); if (!user.id) continue; const multiplied = await tbMultiplyForMicrosats(user.id); @@ -144,9 +144,9 @@ export const migrateAutowithdraw = async () => { for await (const k of scan("user:*")) { try { const raw = await db.get(k); - if (!raw || !raw.startsWith("{")) continue; + if (!raw || !(raw as string).startsWith("{")) continue; - const user = JSON.parse(raw); + const user = JSON.parse(raw as string); if (!user.id || !user.autowithdraw) continue; const accountIds = await db.lRange(`${user.id}:accounts`, 0, -1); @@ -184,7 +184,7 @@ export const migrateFundsToTB = async () => { for await (const k of scan("fund:*")) { try { // Skip sub-keys like fund:name:payments, fund:name:managers, fund:limit - const parts = k.split(":"); + const parts = (k as string).split(":"); if (parts.length !== 2) continue; const name = parts[1]; if (name === "limit") continue; @@ -192,7 +192,7 @@ export const migrateFundsToTB = async () => { const keyType = await db.type(k); if (keyType !== "string") continue; - const balance = Number.parseInt((await db.get(k)) || "0"); + const balance = Number.parseInt(((await db.get(k)) as string) || "0"); await createFundAccount(name); if (balance > 0) await tbFundCredit(name, balance); count++; diff --git a/lib/nostr.ts b/lib/nostr.ts index bcb20ea1..7ed41f36 100644 --- a/lib/nostr.ts +++ b/lib/nostr.ts @@ -1,5 +1,5 @@ import config from "$config"; -import { db, g, s } from "$lib/db"; +import { db, g } from "$lib/db"; import { l, warn } from "$lib/logging"; import { scan } from "$lib/strfry"; import { fail, fields, getUser, pick } from "$lib/utils"; @@ -23,8 +23,7 @@ const alwaysTrue: any = (t: Event) => { t[Symbol("verified")] = true; return true; }; -export const pool = new AbstractSimplePool({ verifyEvent: alwaysTrue }); -const opts = { maxWait: 2000 }; +export const pool = new (AbstractSimplePool as any)({ verifyEvent: alwaysTrue }); export const anon = (pubkey) => ({ username: pubkey.substr(0, 6), @@ -124,9 +123,10 @@ export const getRelays = async (pubkey): Promise<any> => { if (!r[2] || r[2] === "read") read.push(r[1]); } } else - pool + (pool as any) .get(relays, filter) - .then(send) + // @ts-ignore + .then(send as any) .catch(() => {}); return { read, write }; @@ -163,7 +163,8 @@ export const getCount = async (pubkey) => { let followers = await g(k); if (followers === null) { - [followers] = await count({ + // @ts-ignore + [followers] = await (count as any)({ "#p": [pubkey], kinds: [3], }); @@ -220,7 +221,7 @@ export const q = async (f) => { const p = new Promise((resolve) => { const r = []; - pool.subscribeMany(["wss://relay.primal.net"], [f], { + (pool as any).subscribeMany(["wss://relay.primal.net"], [f], { onevent(e) { r.push(e); coinos.publish(e); diff --git a/lib/notifications.ts b/lib/notifications.ts index 261ad4bb..da6eae92 100644 --- a/lib/notifications.ts +++ b/lib/notifications.ts @@ -57,8 +57,8 @@ export const notify = async (p, user, withdrawal) => { url: `/payment/${p.id}`, }; - for (const s of subscriptions) { - webpush.sendNotification(JSON.parse(s), JSON.stringify(payload)).catch((e) => { + for (const s of subscriptions as any) { + webpush.sendNotification(JSON.parse(s as string), JSON.stringify(payload)).catch((e) => { warn("sub failed", e.message); db.sRem(`${user.id}:subscriptions`, s); }); @@ -77,7 +77,7 @@ export const nwcNotify = async (p) => { try { const user = await getUser(p.uid); const pubkeys = await db.sMembers(`${user.id}:apps`); - if (pubkeys.length) { + if ((pubkeys as any).length) { let payment_hash = ""; if (p.type === "lightning") ({ payment_hash } = await ln.decode(p.hash)); for (const pubkey of pubkeys) { @@ -102,7 +102,7 @@ export const nwcNotify = async (p) => { notification, }); - const content = await nip04.encrypt(serverSecret2, pubkey, payload); + const content = await nip04.encrypt(serverSecret2 as any, pubkey as string, payload); const unsigned = { content, @@ -111,7 +111,7 @@ export const nwcNotify = async (p) => { created_at: Math.floor(Date.now() / 1000), }; - const event = finalizeEvent(unsigned, hexToBytes(serverSecret2)); + const event = finalizeEvent(unsigned as any, hexToBytes(serverSecret2)); publish(event).catch(nada); } @@ -2,7 +2,7 @@ import config from "$config"; import { archive, db, g, gf } from "$lib/db"; import { generate } from "$lib/invoices"; import ln from "$lib/ln"; -import { err, l, warn } from "$lib/logging"; +import { l, warn } from "$lib/logging"; import { handleZap, serverPubkey, serverPubkey2, serverSecret, serverSecret2 } from "$lib/nostr"; import { sendInternal, sendKeysend, sendLightning } from "$lib/payments"; import { getBalance } from "$lib/tb"; @@ -92,8 +92,8 @@ export default () => { db.zAdd(handledKey, { score: now, value: ev.id }); db.zRemRangeByScore(handledKey, 0, now - nwcEventMaxAgeSeconds); const size = await db.zCard(handledKey); - if (size > handledMaxSize) { - await db.zRemRangeByRank(handledKey, 0, size - handledMaxSize - 1); + if (Number(size) > handledMaxSize) { + await db.zRemRangeByRank(handledKey, 0, Number(size) - handledMaxSize - 1); } let { content, pubkey } = ev; const pk = ev.tags.find((t) => t[0] === "p")[1]; diff --git a/lib/passkey.ts b/lib/passkey.ts index 29b9b095..ff38b37b 100644 --- a/lib/passkey.ts +++ b/lib/passkey.ts @@ -4,9 +4,10 @@ import { generateAuthenticationOptions, verifyAuthenticationResponse, } from "@simplewebauthn/server"; +// @ts-ignore import type { AuthenticatorTransportFuture } from "@simplewebauthn/types"; import { db, g, s } from "$lib/db"; -import { fail, getUser } from "$lib/utils"; +import { fail } from "$lib/utils"; import { v4 } from "uuid"; const rpName = "coinos"; @@ -27,7 +28,7 @@ export async function generatePasskeyRegistration(user: any, origin: string) { rpName, rpID, userName: user.username, - userID: new TextEncoder().encode(user.id), + userID: new TextEncoder().encode(user.id) as any, attestationType: "none", excludeCredentials: passkeys.map((p: any) => ({ id: p.credentialID, @@ -51,7 +52,7 @@ export async function verifyPasskeyRegistration(user: any, response: any, origin const verification = await verifyRegistrationResponse({ response, - expectedChallenge, + expectedChallenge: expectedChallenge as string, expectedOrigin: origin, expectedRPID: rpID, }); @@ -108,15 +109,15 @@ export async function verifyPasskeyLogin(response: any, challengeId: string, ori const verification = await verifyAuthenticationResponse({ response, - expectedChallenge, + expectedChallenge: expectedChallenge as string, expectedOrigin: origin, expectedRPID: rpID, credential: { id: passkey.credentialID, - publicKey: Buffer.from(passkey.credentialPublicKey, "base64url"), + publicKey: Buffer.from(passkey.credentialPublicKey, "base64url") as any, counter: passkey.counter, transports: passkey.transports as AuthenticatorTransportFuture[], - }, + } as any, }); if (!verification.verified) fail("Passkey authentication failed"); diff --git a/lib/payments.ts b/lib/payments.ts index 08fa8665..52319c8d 100644 --- a/lib/payments.ts +++ b/lib/payments.ts @@ -1,6 +1,6 @@ import config from "$config"; import api from "$lib/api"; -import { db, g, ga, gf, s } from "$lib/db"; +import { db, g, gf, s } from "$lib/db"; import { broadcastTx, btcNetwork, @@ -922,7 +922,7 @@ const getAddressType = async (a) => { } }; -const buildNonCustodial = async ({ aid, amount, address, feeRate, subtract, user }) => { +const buildNonCustodial = async ({ aid, amount, address, feeRate, subtract, user: _user }) => { const account = await g(`account:${aid}`); if (!account?.pubkey) fail("account missing pubkey"); @@ -1146,10 +1146,10 @@ export const catchUp = async () => { try { // Check watched addresses for any missed bitcoin transactions const watched = await db.sMembers("watching"); - for (const address of watched) { + for (const address of watched as any) { try { - const txs = await getAddressTxs(address); - for (const tx of txs) { + const txs = await getAddressTxs(address as string); + for (const tx of txs as any) { await processWatchedTx(tx); } } catch (e) { @@ -1160,7 +1160,6 @@ export const catchUp = async () => { // Non-custodial accounts: check pending outgoing payments const inflightAccounts = await db.keys("inflight:*"); for (const key of inflightAccounts) { - const aid = key.replace("inflight:", ""); const keyType = await db.type(key); if (keyType !== "set") continue; const paymentIds = await db.sMembers(key); @@ -1171,7 +1170,7 @@ export const catchUp = async () => { await db.sRem(key, pid); continue; } - const status = await getTxStatus(p.hash); + const status = await getTxStatus(p.hash) as any; if (status.confirmed) { p.confirmed = true; await s(`payment:${p.id}`, p); @@ -1258,7 +1257,7 @@ export const importAccountHistory = async (account) => { const txsById = new Map(); for (const address of allAddrs) { const txs = await getAddressTxs(address); - for (const tx of txs) { + for (const tx of txs as any) { txsById.set(tx.txid, tx); } } diff --git a/lib/register.ts b/lib/register.ts index 928d560f..b26acd6d 100644 --- a/lib/register.ts +++ b/lib/register.ts @@ -13,7 +13,7 @@ import { v4 } from "uuid"; const valid = /^[\p{L}\p{N}]{2,24}$/u; export default async (user, ip) => { - let { password, pubkey, username, authPubkey } = user; + let { password, pubkey, username } = user; l("registering", username); const reserved = ["ecash"]; @@ -63,6 +63,7 @@ function u128(n: bigint): bigint { } async function resolveAddresses(addresses: string[]): Promise<string[]> { + // @ts-ignore const { lookup } = await import("node:dns/promises"); const resolved: string[] = []; for (const addr of addresses) { @@ -181,12 +182,12 @@ async function getAccount(id: bigint) { // Raw microsats balance for internal use function accountBalanceMicro(account: any): bigint { if (!account) return 0n; - return account.credits_posted - account.debits_posted; + return BigInt(account.credits_posted) - BigInt(account.debits_posted); } function accountBalance(account: any): number { if (!account) return 0; - const micro = account.credits_posted - account.debits_posted; + const micro = BigInt(account.credits_posted) - BigInt(account.debits_posted); return Number(micro / MSATS); // Floor division to sats } @@ -685,7 +686,7 @@ export async function tbMultiplyForMicrosats(uid: string): Promise<number> { const multiplyAccount = async (accountId: bigint, ledger: number, houseId: bigint) => { const acct = await client.lookupAccounts([u128(accountId)]); if (!acct.length) return; - const current = acct[0].credits_posted - acct[0].debits_posted; + const current = BigInt(acct[0].credits_posted) - BigInt(acct[0].debits_posted); if (current <= 0n) return; const results = await client.createTransfers([ diff --git a/lib/upload.ts b/lib/upload.ts index 900d49dd..3eb31250 100644 --- a/lib/upload.ts +++ b/lib/upload.ts @@ -15,17 +15,17 @@ export default async (c) => { let buf = Buffer.from(await (file as File).arrayBuffer()); - const [format, ext] = (await fileTypeFromBuffer(buf)).mime.split("/"); + const [format, ext] = (await fileTypeFromBuffer(buf as any)).mime.split("/"); if (format !== "image" && !["jpg", "jpeg", "png"].includes(ext)) fail("unsupported file type"); const w = type === "banner" ? 1920 : 240; buf = await sharp(buf, { failOnError: false }).rotate().resize(w).webp().toBuffer(); - const hash = createHash("sha256").update(buf).digest("hex"); + const hash = createHash("sha256").update(buf as any).digest("hex"); const filePath = `/home/bun/app/data/uploads/${hash}.webp`; - writeFileSync(filePath, buf); + writeFileSync(filePath, buf as any); return c.json({ hash }); } catch (e) { diff --git a/lib/webhooks.ts b/lib/webhooks.ts index 2a888991..8b0ab919 100644 --- a/lib/webhooks.ts +++ b/lib/webhooks.ts @@ -1,4 +1,3 @@ -import config from "$config"; import got from "got"; import { l, err } from "$lib/logging"; @@ -221,8 +221,8 @@ const startSub = (url: string, topic: string, onMessage: (b: Uint8Array) => void }; socket.on("connect", () => socket.write(greeting())); - socket.on("data", (d: Uint8Array) => { - buffer = concatBytes(buffer, d); + socket.on("data", (d: any) => { + buffer = concatBytes(buffer, d as Uint8Array) as any; processBuffer().catch((e) => err("zmq parse error", e.message)); }); socket.on("error", (e) => { |
