aboutsummaryrefslogtreecommitdiffstats
path: root/lib
diff options
context:
space:
mode:
authorAdam Soltys <[email protected]>2023-12-01 11:36:35 -0800
committerAdam Soltys <[email protected]>2023-12-01 11:36:35 -0800
commit7709c1efde9a1f3078171ee56985cd25511d6f7b (patch)
treecd996eaaa860cdb3d7da688e0ad4c5ec7bae1a0c /lib
parent826c7b361c93905c4725755038d398221530051d (diff)
downloadcoinos-server-7709c1efde9a1f3078171ee56985cd25511d6f7b.tar.gz
coinos-server-7709c1efde9a1f3078171ee56985cd25511d6f7b.zip
biome formatter
Diffstat (limited to 'lib')
-rw-r--r--lib/app.js5
-rw-r--r--lib/auth.js4
-rw-r--r--lib/db.js11
-rw-r--r--lib/locations.js2
-rw-r--r--lib/nostr.js16
-rw-r--r--lib/payments.js8
-rw-r--r--lib/rates.js6
-rw-r--r--lib/register.js4
-rw-r--r--lib/rpc.js38
-rw-r--r--lib/sockets.js12
-rw-r--r--lib/upload.js14
-rw-r--r--lib/utils.js12
-rw-r--r--lib/whitelist.js2
13 files changed, 62 insertions, 72 deletions
diff --git a/lib/app.js b/lib/app.js
index f2542780..00a45bf1 100644
--- a/lib/app.js
+++ b/lib/app.js
@@ -57,10 +57,7 @@ app.setErrorHandler((error, request, reply) => {
});
app.setNotFoundHandler((request, reply) => {
- reply
- .code(404)
- .type("text/html")
- .send("Not Found");
+ reply.code(404).type("text/html").send("Not Found");
});
export default app;
diff --git a/lib/auth.js b/lib/auth.js
index 55de6df0..0e96218a 100644
--- a/lib/auth.js
+++ b/lib/auth.js
@@ -7,7 +7,7 @@ export const optional = {
preValidation: fastifyPassport.authenticate(
"jwt",
{ session: false },
- function(req, res, err, user, info) {
+ function (req, res, err, user, info) {
req.user = user;
}
)
@@ -29,7 +29,7 @@ export const jwtStrategy = new jwt.Strategy(
{
jwtFromRequest: jwt.ExtractJwt.fromExtractors([
jwt.ExtractJwt.fromAuthHeaderAsBearerToken(),
- req => (req.cookies ? req.cookies.token : null)
+ (req) => (req.cookies ? req.cookies.token : null)
]),
secretOrKey: config.jwt
},
diff --git a/lib/db.js b/lib/db.js
index b790917e..31464b19 100644
--- a/lib/db.js
+++ b/lib/db.js
@@ -30,30 +30,29 @@ return {ok = 'ok'}
let debit = defineScript({
NUMBER_OF_KEYS: 2,
SCRIPT,
- transformArguments: (...args) => args.map(a => a.toString())
+ transformArguments: (...args) => args.map((a) => a.toString())
});
export let db = createClient({
url: config.db,
scripts: { debit },
socket: {
- reconnectStrategy: retries => Math.min(retries * 50, 5000)
+ reconnectStrategy: (retries) => Math.min(retries * 50, 5000)
}
});
-
async function connectWithRetry() {
try {
await db.connect();
} catch (err) {
- console.error('Failed to connect to Redis, retrying...', err);
+ console.error("Failed to connect to Redis, retrying...", err);
setTimeout(connectWithRetry, 5000); // Retry after 5 seconds
}
}
connectWithRetry();
-db.on("error", e => {
+db.on("error", (e) => {
if (e.message.startsWith("getaddr")) return;
err("Redis error", e.message);
});
@@ -64,7 +63,7 @@ db.on("end", () => {
export default db;
-export let g = async k => {
+export let g = async (k) => {
let v = await db.get(k);
try {
return JSON.parse(v);
diff --git a/lib/locations.js b/lib/locations.js
index 5cf43733..dc2c9d54 100644
--- a/lib/locations.js
+++ b/lib/locations.js
@@ -11,7 +11,7 @@ export let getLocations = async () => {
).json();
locations = locations.filter(
- l =>
+ (l) =>
l["osm_json"].tags &&
l["osm_json"].tags["payment:coinos"] === "yes" &&
l["osm_json"]["type"] === "node"
diff --git a/lib/nostr.js b/lib/nostr.js
index f352c020..f75da37c 100644
--- a/lib/nostr.js
+++ b/lib/nostr.js
@@ -11,7 +11,7 @@ export let pool;
export let fillPool = () => {
pool = RelayPool(config.relays);
- pool.on("open", relay => {
+ pool.on("open", (relay) => {
if (relay.url.includes(config.nostr)) coinos = relay;
relay.subscribe("live", { limit: 1 });
});
@@ -113,7 +113,7 @@ export let q = async (
let done = { [sub]: [] };
- let check = s => {
+ let check = (s) => {
let elapsed = Date.now() - start;
if (rejected) return true;
if (
@@ -168,7 +168,7 @@ export let q = async (
let seen = [];
-let getUser = async pubkey => {
+let getUser = async (pubkey) => {
let id = await g(`user:${pubkey}`);
let user = await g(`user:${id}`);
return (
@@ -218,7 +218,7 @@ export async function handleZap(invoice) {
}
let ptags = zapreq.tags.filter(
- t => t && t.length && t.length >= 2 && t[0] === "p"
+ (t) => t && t.length && t.length >= 2 && t[0] === "p"
);
if (ptags.length !== 1) {
@@ -226,7 +226,7 @@ export async function handleZap(invoice) {
}
let etags = zapreq.tags.filter(
- t => t && t.length && t.length >= 2 && t[0] === "e"
+ (t) => t && t.length && t.length >= 2 && t[0] === "e"
);
if (!(etags.length === 0 || etags.length === 1)) {
@@ -234,14 +234,14 @@ export async function handleZap(invoice) {
}
let relays_tag = zapreq.tags.find(
- t => t && t.length && t.length >= 2 && t[0] === "relays"
+ (t) => t && t.length && t.length >= 2 && t[0] === "relays"
);
if (!relays_tag) {
fail(`No relays tag found`);
}
- let relays = relays_tag.slice(1).filter(r => r && r.startsWith("ws"));
+ let relays = relays_tag.slice(1).filter((r) => r && r.startsWith("ws"));
let etag = etags.length > 0 && etags[0];
let ptag = ptags[0];
@@ -260,5 +260,5 @@ export async function handleZap(invoice) {
ev.id = await calculateId(ev);
ev.sig = await signId(privkey, ev.id);
- await Promise.all(relays.map(r => send(ev, r)));
+ await Promise.all(relays.map((r) => send(ev, r)));
}
diff --git a/lib/payments.js b/lib/payments.js
index f2fab1ba..5152806a 100644
--- a/lib/payments.js
+++ b/lib/payments.js
@@ -118,7 +118,7 @@ export let credit = async (hash, amount, memo, ref, type = types.internal) => {
return;
}
- let { tip } = invoice;
+ let { tip } = invoice;
tip = parseInt(tip) || 0;
if (!memo) ({ memo } = invoice);
@@ -243,10 +243,10 @@ export let payLightning = async (user, payreq, amount, maxfee, memo) => {
let r;
let { pays } = await ln.listpays(payreq);
- if (pays.find(p => p.status === "complete"))
+ if (pays.find((p) => p.status === "complete"))
fail("Invoice has already been paid");
- if (pays.find(p => p.status === "pending"))
+ if (pays.find((p) => p.status === "pending"))
fail("Payment is already underway");
p = await debit(payreq, total, maxfee, memo, user, types.lightning);
@@ -257,7 +257,7 @@ export let payLightning = async (user, payreq, amount, maxfee, memo) => {
let recordExists = !!(await g(`payment:${p.id}`));
let paymentFailed =
- !pays.length || pays.every(p => p.status === "failed");
+ !pays.length || pays.every((p) => p.status === "failed");
l("checking", payreq, recordExists, paymentFailed);
diff --git a/lib/rates.js b/lib/rates.js
index bbb5418f..2fce4f42 100644
--- a/lib/rates.js
+++ b/lib/rates.js
@@ -15,11 +15,11 @@ let connect = async () => {
ws = new WebSocket("wss://stream.binance.com:9443/ws/btcusdt@ticker");
- ws.onmessage = async function(event) {
+ ws.onmessage = async function (event) {
try {
let msg = JSON.parse(event.data);
- Object.keys(store.fx).map(symbol => {
+ Object.keys(store.fx).map((symbol) => {
store.rates[symbol] = msg.c * store.fx[symbol];
});
@@ -31,7 +31,7 @@ let connect = async () => {
}
};
- ws.onerror = async function(error) {
+ ws.onerror = async function (error) {
err("binance socket error", error.message);
};
diff --git a/lib/register.js b/lib/register.js
index c52dad03..2459d3a8 100644
--- a/lib/register.js
+++ b/lib/register.js
@@ -28,9 +28,7 @@ export default async (user, ip, requireChallenge) => {
if (config.ipregistry) {
try {
let {
- location: {
- country: { code }
- }
+ location: { country: { code } }
} = await got(
`https://api.ipregistry.co/${ip}?key=${config.ipregistry}&fields=location.country.code`
).json();
diff --git a/lib/rpc.js b/lib/rpc.js
index b8a2d0dd..ec2ff879 100644
--- a/lib/rpc.js
+++ b/lib/rpc.js
@@ -4,23 +4,25 @@ export default ({ host, port, wallet, username, password }) =>
new Proxy(
{},
{
- get: (target, prop) => (...params) =>
- ((method, ...params) => {
- let url = `http://${host}:${port}/wallet/${wallet}`;
- return got
- .post(url, {
- json: {
- method,
- params
- },
- headers: {
- authorization: `Basic ${Buffer.from(
- `${username}:${password}`
- ).toString("base64")}`
- }
- })
- .json()
- .then(({ result }) => result);
- })(prop.toLowerCase(), ...params)
+ get:
+ (target, prop) =>
+ (...params) =>
+ ((method, ...params) => {
+ let url = `http://${host}:${port}/wallet/${wallet}`;
+ return got
+ .post(url, {
+ json: {
+ method,
+ params
+ },
+ headers: {
+ authorization: `Basic ${Buffer.from(
+ `${username}:${password}`
+ ).toString("base64")}`
+ }
+ })
+ .json()
+ .then(({ result }) => result);
+ })(prop.toLowerCase(), ...params)
}
);
diff --git a/lib/sockets.js b/lib/sockets.js
index 03ad6752..46fda67c 100644
--- a/lib/sockets.js
+++ b/lib/sockets.js
@@ -41,7 +41,7 @@ export const broadcast = (type, data) => {
}
}
- Object.values(all).map(ws => {
+ Object.values(all).map((ws) => {
if (!sent.includes(ws.id)) ws.send(JSON.stringify({ type, data }));
});
};
@@ -58,7 +58,7 @@ let track = async (ws, token) => {
const existing = Object.keys(store.sockets[uid]);
if (existing.length > 4) {
- const p = existing.find(sid => sid !== uid);
+ const p = existing.find((sid) => sid !== uid);
store.sockets[uid][p].close(code, "too many sockets");
}
@@ -72,7 +72,7 @@ export async function socketServer(app) {
app.get("/ws", { websocket: true }, (connection, req) => {
let { socket: ws } = connection;
- connection.on("error", e => err(e.message));
+ connection.on("error", (e) => err(e.message));
const id = v4();
ws.id = id;
@@ -80,7 +80,7 @@ export async function socketServer(app) {
ws.send(JSON.stringify({ type: "connected", data: id }));
all[id] = ws;
- ws.on("message", async message => {
+ ws.on("message", async (message) => {
let type, data;
try {
@@ -126,9 +126,9 @@ export async function socketServer(app) {
}
});
- ws.on("error", e => {});
+ ws.on("error", (e) => {});
- ws.on("close", function(code, reason) {
+ ws.on("close", function (code, reason) {
try {
const uid = users[id];
if (store.sockets[uid] && store.sockets[uid][id]) {
diff --git a/lib/upload.js b/lib/upload.js
index e07b9b1a..39c4a07f 100644
--- a/lib/upload.js
+++ b/lib/upload.js
@@ -14,7 +14,7 @@ async function getSha256Hash(stream) {
stream.pipe(hash);
let hashValue;
- hash.on("data", data => {
+ hash.on("data", (data) => {
hashValue = data.toString("hex");
});
@@ -42,16 +42,10 @@ export default async (req, res) => {
if (format !== "image" && !["jpg", "jpeg", "png"].includes(ext))
throw new Error("unsupported file type");
- let t = sharp()
- .rotate()
- .resize(width)
- .webp();
+ let t = sharp().rotate().resize(width).webp();
let processedBuffer = await streamToBuffer(s2.pipe(t));
- let hash = crypto
- .createHash("sha256")
- .update(processedBuffer)
- .digest("hex");
+ let hash = crypto.createHash("sha256").update(processedBuffer).digest("hex");
let filePath = `/app/data/uploads/${hash}.webp`;
fs.writeFileSync(filePath, processedBuffer);
@@ -62,7 +56,7 @@ export default async (req, res) => {
function streamToBuffer(stream) {
return new Promise((resolve, reject) => {
const chunks = [];
- stream.on("data", chunk => chunks.push(chunk));
+ stream.on("data", (chunk) => chunks.push(chunk));
stream.on("end", () => resolve(Buffer.concat(chunks)));
stream.on("error", reject);
});
diff --git a/lib/utils.js b/lib/utils.js
index 2eac0054..a1612483 100644
--- a/lib/utils.js
+++ b/lib/utils.js
@@ -4,7 +4,7 @@ import config from "$config";
export const nada = () => {};
-export const sleep = n => new Promise(r => setTimeout(r, n));
+export const sleep = (n) => new Promise((r) => setTimeout(r, n));
export const wait = async (f, s = 300, n = 50) => {
let i = 0;
while (!(await f()) && i < s) (await sleep(n)) && i++;
@@ -13,17 +13,17 @@ export const wait = async (f, s = 300, n = 50) => {
};
export const prod = process.env.NODE_ENV === "production";
-export const fail = msg => {
+export const fail = (msg) => {
throw new Error(msg);
};
export const bail = (res, msg) => res.code(500).send(msg);
export const SATS = 100000000;
-export const sats = n => Math.round(n * SATS);
-export const btc = n => parseFloat((n / SATS).toFixed(8));
+export const sats = (n) => Math.round(n * SATS);
+export const btc = (n) => parseFloat((n / SATS).toFixed(8));
-export const uniq = (a, k) => [...new Map(a.map(x => [k(x), x])).values()];
+export const uniq = (a, k) => [...new Map(a.map((x) => [k(x), x])).values()];
export const pick = (O, K) =>
K.reduce((o, k) => (typeof O[k] !== "undefined" && (o[k] = O[k]), o), {});
@@ -56,7 +56,7 @@ export const fields = [
"banner"
];
-export const getUser = async username => {
+export const getUser = async (username) => {
username = username.replace(/\s/g, "").toLowerCase();
let uid = await g(`user:${username}`);
return g(`user:${uid}`);
diff --git a/lib/whitelist.js b/lib/whitelist.js
index 1d722683..8c988ab5 100644
--- a/lib/whitelist.js
+++ b/lib/whitelist.js
@@ -32,5 +32,5 @@ export default [
"username",
"verified",
"shopifyStore",
- "shopifyToken",
+ "shopifyToken"
];