From fcb5780ef9831dea3101b01d7c816ca5e1a49832 Mon Sep 17 00:00:00 2001 From: Sergo Date: Sat, 5 Aug 2023 11:48:46 +0300 Subject: [PATCH 1/4] store express sessions in redis --- config/default.json | 3 + config/prod.js | 3 + deployment.yaml | 12 ++ package-lock.json | 205 ++++++++++++++++++++++++++ package.json | 3 + src/app.ts | 12 +- src/services/aliases/aliases.class.ts | 10 +- 7 files changed, 242 insertions(+), 6 deletions(-) diff --git a/config/default.json b/config/default.json index 62b451a..61c41f9 100644 --- a/config/default.json +++ b/config/default.json @@ -14,5 +14,8 @@ "token": "aaaaa", "domain": "test-codemowers.eu", "preferredDomain": "k-space.ee" + }, + "redis": { + "url": "redis://localhost:6379" } } \ No newline at end of file diff --git a/config/prod.js b/config/prod.js index 2d79fca..d1551f0 100644 --- a/config/prod.js +++ b/config/prod.js @@ -10,5 +10,8 @@ module.exports = { url: process.env.WILDDUCK_URL, token: process.env.WILDDUCK_TOKEN, domain: process.env.WILDDUCK_DOMAIN + }, + redis: { + url: process.env.REDIS_URL } }; \ No newline at end of file diff --git a/deployment.yaml b/deployment.yaml index 1c5ec76..d54729f 100644 --- a/deployment.yaml +++ b/deployment.yaml @@ -98,6 +98,18 @@ spec: secretKeyRef: name: walias-secrets key: WILDDUCK_DOMAIN + - name: REDIS_URL + value: walias-cache envFrom: - secretRef: name: oidc-client-walias-owner-secrets + +--- +apiVersion: codemowers.cloud/v1beta1 +kind: RedisClaim +metadata: + name: walias-cache + namespace: msergo-bwybg +spec: + capacity: 100Mi + class: cache diff --git a/package-lock.json b/package-lock.json index b16f1d1..51e9bc6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -22,8 +22,10 @@ "axios": "^1.4.0", "compression": "^1.7.4", "config": "^3.3.9", + "connect-redis": "^7.1.0", "cookie-parser": "^1.4.6", "express-session": "^1.17.3", + "ioredis": "^5.3.2", "openid-client": "^5.4.3", "winston": "^3.10.0" }, @@ -34,6 +36,7 @@ "@types/express-session": "^1.17.7", "@types/mocha": "^10.0.1", "@types/node": "^20.4.5", + "@types/redis": "^4.0.11", "cross-env": "^7.0.3", "mocha": "^10.2.0", "nodemon": "^3.0.1", @@ -411,6 +414,11 @@ "url": "https://github.com/sponsors/daffl" } }, + "node_modules/@ioredis/commands": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@ioredis/commands/-/commands-1.2.0.tgz", + "integrity": "sha512-Sx1pU8EM64o2BrqNpEO1CNLtKQwyhuXuqyfH7oGKCk+1a33d2r5saW8zNwm3j6BTExtjrv2BxTgzzkMwts6vGg==" + }, "node_modules/@jridgewell/resolve-uri": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.1.tgz", @@ -436,6 +444,65 @@ "@jridgewell/sourcemap-codec": "^1.4.10" } }, + "node_modules/@redis/bloom": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@redis/bloom/-/bloom-1.2.0.tgz", + "integrity": "sha512-HG2DFjYKbpNmVXsa0keLHp/3leGJz1mjh09f2RLGGLQZzSHpkmZWuwJbAvo3QcRY8p80m5+ZdXZdYOSBLlp7Cg==", + "dev": true, + "peerDependencies": { + "@redis/client": "^1.0.0" + } + }, + "node_modules/@redis/client": { + "version": "1.5.8", + "resolved": "https://registry.npmjs.org/@redis/client/-/client-1.5.8.tgz", + "integrity": "sha512-xzElwHIO6rBAqzPeVnCzgvrnBEcFL1P0w8P65VNLRkdVW8rOE58f52hdj0BDgmsdOm4f1EoXPZtH4Fh7M/qUpw==", + "dev": true, + "dependencies": { + "cluster-key-slot": "1.1.2", + "generic-pool": "3.9.0", + "yallist": "4.0.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@redis/graph": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@redis/graph/-/graph-1.1.0.tgz", + "integrity": "sha512-16yZWngxyXPd+MJxeSr0dqh2AIOi8j9yXKcKCwVaKDbH3HTuETpDVPcLujhFYVPtYrngSco31BUcSa9TH31Gqg==", + "dev": true, + "peerDependencies": { + "@redis/client": "^1.0.0" + } + }, + "node_modules/@redis/json": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@redis/json/-/json-1.0.4.tgz", + "integrity": "sha512-LUZE2Gdrhg0Rx7AN+cZkb1e6HjoSKaeeW8rYnt89Tly13GBI5eP4CwDVr+MY8BAYfCg4/N15OUrtLoona9uSgw==", + "dev": true, + "peerDependencies": { + "@redis/client": "^1.0.0" + } + }, + "node_modules/@redis/search": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@redis/search/-/search-1.1.3.tgz", + "integrity": "sha512-4Dg1JjvCevdiCBTZqjhKkGoC5/BcB7k9j99kdMnaXFXg8x4eyOIVg9487CMv7/BUVkFLZCaIh8ead9mU15DNng==", + "dev": true, + "peerDependencies": { + "@redis/client": "^1.0.0" + } + }, + "node_modules/@redis/time-series": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@redis/time-series/-/time-series-1.0.4.tgz", + "integrity": "sha512-ThUIgo2U/g7cCuZavucQTQzA9g9JbDDY2f64u3AbAoz/8vE2lt2U37LamDUVChhaDA3IRT9R6VvJwqnUfTJzng==", + "dev": true, + "peerDependencies": { + "@redis/client": "^1.0.0" + } + }, "node_modules/@socket.io/component-emitter": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.0.tgz", @@ -608,6 +675,16 @@ "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.4.tgz", "integrity": "sha512-EEhsLsD6UsDM1yFhAvy0Cjr6VwmpMWqFBCb9w07wVugF7w9nfajxLuVmngTIpgS6svCnm6Vaw+MZhoDCKnOfsw==" }, + "node_modules/@types/redis": { + "version": "4.0.11", + "resolved": "https://registry.npmjs.org/@types/redis/-/redis-4.0.11.tgz", + "integrity": "sha512-bI+gth8La8Wg/QCR1+V1fhrL9+LZUSWfcqpOj2Kc80ZQ4ffbdL173vQd5wovmoV9i071FU9oP2g6etLuEwb6Rg==", + "deprecated": "This is a stub types definition. redis provides its own type definitions, so you do not need this installed.", + "dev": true, + "dependencies": { + "redis": "*" + } + }, "node_modules/@types/send": { "version": "0.17.1", "resolved": "https://registry.npmjs.org/@types/send/-/send-0.17.1.tgz", @@ -1130,6 +1207,14 @@ "node": ">=0.8" } }, + "node_modules/cluster-key-slot": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/cluster-key-slot/-/cluster-key-slot-1.1.2.tgz", + "integrity": "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA==", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/color": { "version": "3.2.1", "resolved": "https://registry.npmjs.org/color/-/color-3.2.1.tgz", @@ -1235,6 +1320,17 @@ "node": ">= 10.0.0" } }, + "node_modules/connect-redis": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/connect-redis/-/connect-redis-7.1.0.tgz", + "integrity": "sha512-UaqO1EirWjON2ENsyau7N5lbkrdYBpS6mYlXSeff/OYXsd6EGZ+SXSmNPoljL2PSua8fgjAEaldSA73PMZQ9Eg==", + "engines": { + "node": ">=16" + }, + "peerDependencies": { + "express-session": ">=1" + } + }, "node_modules/content-disposition": { "version": "0.5.4", "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", @@ -1396,6 +1492,14 @@ "node": ">=0.4.0" } }, + "node_modules/denque": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/denque/-/denque-2.1.0.tgz", + "integrity": "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==", + "engines": { + "node": ">=0.10" + } + }, "node_modules/depd": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", @@ -1826,6 +1930,15 @@ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==" }, + "node_modules/generic-pool": { + "version": "3.9.0", + "resolved": "https://registry.npmjs.org/generic-pool/-/generic-pool-3.9.0.tgz", + "integrity": "sha512-hymDOu5B53XvN4QT9dBmZxPX4CWhBPPLguTZ9MMFeFa/Kg0xWVfylOVNlJji/E7yTZWFd/q9GO5TxDLq156D7g==", + "dev": true, + "engines": { + "node": ">= 4" + } + }, "node_modules/get-caller-file": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", @@ -2056,6 +2169,50 @@ "node": ">= 0.10" } }, + "node_modules/ioredis": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ioredis/-/ioredis-5.3.2.tgz", + "integrity": "sha512-1DKMMzlIHM02eBBVOFQ1+AolGjs6+xEcM4PDL7NqOS6szq7H9jSaEkIUH6/a5Hl241LzW6JLSiAbNvTQjUupUA==", + "dependencies": { + "@ioredis/commands": "^1.1.1", + "cluster-key-slot": "^1.1.0", + "debug": "^4.3.4", + "denque": "^2.1.0", + "lodash.defaults": "^4.2.0", + "lodash.isarguments": "^3.1.0", + "redis-errors": "^1.2.0", + "redis-parser": "^3.0.0", + "standard-as-callback": "^2.1.0" + }, + "engines": { + "node": ">=12.22.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/ioredis" + } + }, + "node_modules/ioredis/node_modules/debug": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/ioredis/node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, "node_modules/ipaddr.js": { "version": "1.9.1", "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", @@ -2292,6 +2449,16 @@ "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" }, + "node_modules/lodash.defaults": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/lodash.defaults/-/lodash.defaults-4.2.0.tgz", + "integrity": "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ==" + }, + "node_modules/lodash.isarguments": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/lodash.isarguments/-/lodash.isarguments-3.1.0.tgz", + "integrity": "sha512-chi4NHZlZqZD18a0imDHnZPrDeBbTtVN7GXMwuGdRH9qotxAjYs3aVLKc7zNOG9eddR5Ksd8rvFEBc9SsggPpg==" + }, "node_modules/log-symbols": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.1.0.tgz", @@ -3056,6 +3223,39 @@ "node": ">= 0.10" } }, + "node_modules/redis": { + "version": "4.6.7", + "resolved": "https://registry.npmjs.org/redis/-/redis-4.6.7.tgz", + "integrity": "sha512-KrkuNJNpCwRm5vFJh0tteMxW8SaUzkm5fBH7eL5hd/D0fAkzvapxbfGPP/r+4JAXdQuX7nebsBkBqA2RHB7Usw==", + "dev": true, + "dependencies": { + "@redis/bloom": "1.2.0", + "@redis/client": "1.5.8", + "@redis/graph": "1.1.0", + "@redis/json": "1.0.4", + "@redis/search": "1.1.3", + "@redis/time-series": "1.0.4" + } + }, + "node_modules/redis-errors": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/redis-errors/-/redis-errors-1.2.0.tgz", + "integrity": "sha512-1qny3OExCf0UvUV/5wpYKf2YwPcOqXzkwKKSmKHiE6ZMQs5heeE/c8eXK+PNllPvmjgAbfnsbpkGZWy8cBpn9w==", + "engines": { + "node": ">=4" + } + }, + "node_modules/redis-parser": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/redis-parser/-/redis-parser-3.0.0.tgz", + "integrity": "sha512-DJnGAeenTdpMEH6uAJRK/uiyEIH9WVsUmoLwzudwGJUwZPp80PDBWPHXSAGNPwNvIXAbe7MSUB1zQFugFml66A==", + "dependencies": { + "redis-errors": "^1.0.0" + }, + "engines": { + "node": ">=4" + } + }, "node_modules/regenerator-runtime": { "version": "0.13.11", "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz", @@ -3394,6 +3594,11 @@ "node": "*" } }, + "node_modules/standard-as-callback": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/standard-as-callback/-/standard-as-callback-2.1.0.tgz", + "integrity": "sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==" + }, "node_modules/statuses": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", diff --git a/package.json b/package.json index 45f0a14..82f397f 100644 --- a/package.json +++ b/package.json @@ -55,8 +55,10 @@ "axios": "^1.4.0", "compression": "^1.7.4", "config": "^3.3.9", + "connect-redis": "^7.1.0", "cookie-parser": "^1.4.6", "express-session": "^1.17.3", + "ioredis": "^5.3.2", "openid-client": "^5.4.3", "winston": "^3.10.0" }, @@ -67,6 +69,7 @@ "@types/express-session": "^1.17.7", "@types/mocha": "^10.0.1", "@types/node": "^20.4.5", + "@types/redis": "^4.0.11", "cross-env": "^7.0.3", "mocha": "^10.2.0", "nodemon": "^3.0.1", diff --git a/src/app.ts b/src/app.ts index f0a24a4..0030c77 100644 --- a/src/app.ts +++ b/src/app.ts @@ -12,7 +12,9 @@ import configuration from "@feathersjs/configuration"; import socketio from "@feathersjs/socketio"; import session from "express-session"; import cookieParser from "cookie-parser"; - +import RedisStore from "connect-redis"; +import { createClient } from "redis"; +import config from "config"; import type { Application } from "./declarations"; import { logger } from "./logger"; @@ -35,9 +37,15 @@ app.use( app.use(cookieParser()); app.use( session({ + store: new RedisStore({ + prefix: "walias:", + client: createClient({ + url: config.get("redis.url"), + }), + }), secret: randomUUID(), resave: false, - saveUninitialized: true, + saveUninitialized: false, cookie: { secure: false }, }), ); diff --git a/src/services/aliases/aliases.class.ts b/src/services/aliases/aliases.class.ts index 928ec99..7260b27 100644 --- a/src/services/aliases/aliases.class.ts +++ b/src/services/aliases/aliases.class.ts @@ -94,10 +94,12 @@ export class AliasesService const addressInfoResponse = await Promise.any( emails - .filter((email: string) => email.endsWith(config.get("wildDuck.preferredDomain"))) - .map((email: string) => - wildDuckClient.get(`addresses/resolve/${email}`), - ), + .filter((email: string) => + email.endsWith(config.get("wildDuck.preferredDomain")), + ) + .map((email: string) => + wildDuckClient.get(`addresses/resolve/${email}`), + ), ); return addressInfoResponse.data.user; From cc453e23377af595555c9141ef84ad8dff699793 Mon Sep 17 00:00:00 2001 From: Sergo Date: Sat, 5 Aug 2023 15:01:37 +0300 Subject: [PATCH 2/4] sanitize aliases response, hide delete button for non-prefereable domain aliases --- deployment.yaml | 10 --- public/index.js | 44 +++++++----- src/app.ts | 22 +++--- src/helpers/get-env.ts | 16 +++++ src/services/aliases/aliases.class.ts | 96 ++++++++++++++++++++------- 5 files changed, 130 insertions(+), 58 deletions(-) create mode 100644 src/helpers/get-env.ts diff --git a/deployment.yaml b/deployment.yaml index d54729f..7ef2aea 100644 --- a/deployment.yaml +++ b/deployment.yaml @@ -103,13 +103,3 @@ spec: envFrom: - secretRef: name: oidc-client-walias-owner-secrets - ---- -apiVersion: codemowers.cloud/v1beta1 -kind: RedisClaim -metadata: - name: walias-cache - namespace: msergo-bwybg -spec: - capacity: 100Mi - class: cache diff --git a/public/index.js b/public/index.js index 86770f0..fe1c00a 100644 --- a/public/index.js +++ b/public/index.js @@ -31,29 +31,17 @@ function renderAliases(aliases) { const tdCreated = document.createElement('td') tdCreated.innerText = alias.created const tdActions = document.createElement('td') - const aDelete = document.createElement('a') - aDelete.addEventListener('click', async () => { - const res = await fetch(`/aliases/${alias.id}`, { - method: 'DELETE' - }) + const deleteButton = createDeleteButton(alias) - if (res.ok) { - const data = await res.json() - renderAliases(data) - return - } - }) - - aDelete.classList.add('btn', 'btn-danger') - aDelete.innerText = 'Delete' - tdActions.appendChild(aDelete) + tdActions.appendChild(deleteButton) tr.appendChild(tdAddress) tr.appendChild(tdCreated) tr.appendChild(tdActions) tbody.appendChild(tr) }) + table.appendChild(tbody) dataContainer.innerHTML = '' @@ -62,6 +50,32 @@ function renderAliases(aliases) { renderCreateButton(); } +function createDeleteButton(alias) { + const deleteButton = document.createElement('a') + deleteButton.classList.add('btn', 'btn-danger') + + if (!alias.id) { + deleteButton.classList.add('disabled') + } else { + + deleteButton.addEventListener('click', async () => { + const res = await fetch(`/aliases/${alias.id}`, { + method: 'DELETE' + }) + + if (res.ok) { + const data = await res.json() + renderAliases(data) + return + } + }) + } + + deleteButton.innerText = 'Delete' + + return deleteButton +} + function renderCreateButton() { const dataContainer = document.getElementById('container') const button = document.createElement('a') diff --git a/src/app.ts b/src/app.ts index 0030c77..65bb717 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1,3 +1,4 @@ +import { randomUUID } from "crypto"; import { feathers } from "@feathersjs/feathers"; import express, { rest, @@ -16,12 +17,11 @@ import RedisStore from "connect-redis"; import { createClient } from "redis"; import config from "config"; import type { Application } from "./declarations"; - import { logger } from "./logger"; import { logError } from "./hooks/log-error"; import { services } from "./services/index"; import { channels } from "./channels"; -import { randomUUID } from "crypto"; +import { Env, getEnv } from "./helpers/get-env"; const app: Application = express(feathers()); @@ -35,14 +35,20 @@ app.use( ); app.use(cookieParser()); + +const sessionStore = + getEnv() === Env.prod + ? new RedisStore({ + prefix: "walias:", + client: createClient({ + url: config.get("redis.url"), + }), + }) + : undefined; + app.use( session({ - store: new RedisStore({ - prefix: "walias:", - client: createClient({ - url: config.get("redis.url"), - }), - }), + store: sessionStore, secret: randomUUID(), resave: false, saveUninitialized: false, diff --git a/src/helpers/get-env.ts b/src/helpers/get-env.ts new file mode 100644 index 0000000..4198918 --- /dev/null +++ b/src/helpers/get-env.ts @@ -0,0 +1,16 @@ +export enum Env { + dev = "dev", + prod = "prod", + test = "test", +} + +export const getEnv = (): Env => { + const env = process.env.NODE_ENV; + if (env === "prod") { + return Env.prod; + } else if (env === "test") { + return Env.test; + } else { + return Env.dev; + } +}; diff --git a/src/services/aliases/aliases.class.ts b/src/services/aliases/aliases.class.ts index 7260b27..a089feb 100644 --- a/src/services/aliases/aliases.class.ts +++ b/src/services/aliases/aliases.class.ts @@ -6,11 +6,11 @@ import type { import type { Application } from "../../declarations"; import wildDuckClient from "../../clients/wildduck.client"; -import { faker } from "@faker-js/faker"; +import { faker, th } from "@faker-js/faker"; import { BadRequest } from "@feathersjs/errors"; import config from "config"; -interface Alias { +interface WildDuckAddress { success: boolean; id: string; address: string; @@ -20,12 +20,19 @@ interface Alias { created: string; } -interface GetAddressInfoResponse { +interface GetWildDuckAddressInfoResponse { success: boolean; - results: Alias[]; + results: WildDuckAddress[]; } -interface CreateAddressResponse { +interface AliasApiResponse { + id: string | null; + address: string; + tags: string[]; + created: string; +} + +interface CreateWildDuckAddressResponse { success: boolean; id: string; } @@ -34,7 +41,12 @@ type AliasesData = any; type AliasesPatch = any; type AliasesQuery = any; -export type { Alias as Aliases, AliasesData, AliasesPatch, AliasesQuery }; +export type { + WildDuckAddress as Aliases, + AliasesData, + AliasesPatch, + AliasesQuery, +}; export interface AliasesServiceOptions { app: Application; @@ -45,21 +57,30 @@ export interface AliasesParams extends Params { } export class AliasesService - implements ServiceInterface + implements + ServiceInterface< + AliasApiResponse, + AliasesData, + ServiceParams, + AliasesPatch + > { constructor(public options: AliasesServiceOptions) {} - async find(params: ServiceParams): Promise { + async find(params: ServiceParams): Promise { const userId = await this.getUserIdByEmailAddress(params); return this.getUserAddresses(userId); } - async create(data: AliasesData, params: ServiceParams): Promise; async create( data: AliasesData, params: ServiceParams, - ): Promise { + ): Promise; + async create( + data: AliasesData, + params: ServiceParams, + ): Promise { const userId = await this.getUserIdByEmailAddress(params); const randomString = faker.git.commitSha({ length: 4 }); @@ -73,12 +94,13 @@ export class AliasesService const emailDomain = config.get("wildDuck.domain"); - const createResult = await wildDuckClient.post( - `/users/${userId}/addresses`, - { - address: `${alias}@${emailDomain}`, - }, - ); + const createResult = + await wildDuckClient.post( + `/users/${userId}/addresses`, + { + address: `${alias}@${emailDomain}`, + }, + ); if (!createResult.data.success) { throw new BadRequest("Failed to create alias"); @@ -92,32 +114,40 @@ export class AliasesService ): Promise { const emails = params.session?.user?.emails; + const preferredDomain = config.get("wildDuck.preferredDomain"); + + if (!emails.length || !preferredDomain) { + throw new BadRequest("Unable to find user"); + } + const addressInfoResponse = await Promise.any( emails .filter((email: string) => email.endsWith(config.get("wildDuck.preferredDomain")), ) .map((email: string) => - wildDuckClient.get(`addresses/resolve/${email}`), + wildDuckClient.get(`addresses/resolve/${email}`), ), ); return addressInfoResponse.data.user; } - private async getUserAddresses(userId: string): Promise { + private async getUserAddresses(userId: string): Promise { const { data: userAddressesResponse } = - await wildDuckClient.get( + await wildDuckClient.get( `/users/${userId}/addresses`, ); - return userAddressesResponse.results; + return userAddressesResponse.results.map(this.sanitizeAliasResponse); } - async remove(id: NullableId, params: ServiceParams): Promise { - const { data: addressInfoResponse } = await wildDuckClient.get( - `addresses/resolve/${id}`, - ); + async remove( + id: NullableId, + params: ServiceParams, + ): Promise { + const { data: addressInfoResponse } = + await wildDuckClient.get(`addresses/resolve/${id}`); const allowedDomain: string = config.get("wildDuck.domain"); // If address does not match the allowed domain, throw an error @@ -129,10 +159,26 @@ export class AliasesService } const userId = await this.getUserIdByEmailAddress(params); - await wildDuckClient.delete(`users/${userId}/addresses/${id}`); + await wildDuckClient.delete( + `users/${userId}/addresses/${id}`, + ); return this.getUserAddresses(userId); } + + sanitizeAliasResponse(alias: WildDuckAddress): AliasApiResponse { + // Hide the id if the alias is not removable + const isRemovable = + alias.main || + !alias.address.endsWith(config.get("wildDuck.preferredDomain")); + + return { + id: isRemovable ? null : alias.id, + address: alias.address, + tags: alias.tags, + created: alias.created, + }; + } } export const getOptions = (app: Application) => { From feb5e5b4cad8da611d37b9cd4a637d3abb0d3dc0 Mon Sep 17 00:00:00 2001 From: Sergo Date: Sun, 6 Aug 2023 09:21:17 +0300 Subject: [PATCH 3/4] add prettier --- .prettierrc.json | 9 + index.ts | 40 +-- logger.ts | 10 +- src/app.ts | 114 ++++----- src/channels.ts | 61 +++-- src/clients/wildduck.client.ts | 14 +- src/declarations.ts | 7 +- src/helpers/get-env.ts | 22 +- src/hooks/log-error.ts | 24 +- src/hooks/validate-auth.ts | 10 +- src/index.ts | 14 +- src/logger.ts | 10 +- src/services/aliases/aliases.class.ts | 230 +++++++----------- src/services/aliases/aliases.ts | 60 ++--- src/services/auth-oidc/auth-oidc.class.ts | 61 +++-- src/services/auth-oidc/auth-oidc.ts | 74 +++--- .../callback/auth-oidc-callback.class.ts | 78 +++--- .../auth-oidc/callback/auth-oidc-callback.ts | 79 +++--- src/services/index.ts | 14 +- src/validators.ts | 40 +-- test/app.test.ts | 62 ++--- test/services/aliases/aliases.test.ts | 14 +- test/services/auth-oidc/auth-oidc.test.ts | 14 +- .../auth-oidc/callback/callback.test.ts | 14 +- validators.ts | 40 +-- 25 files changed, 524 insertions(+), 591 deletions(-) create mode 100644 .prettierrc.json diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 0000000..db68f23 --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1,9 @@ +{ + "trailingComma": "es5", + "tabWidth": 4, + "semi": true, + "singleQuote": true, + "printWidth": 120, + "quoteProps": "as-needed", + "arrowParens": "avoid" +} \ No newline at end of file diff --git a/index.ts b/index.ts index 1a1c7eb..ae7aa25 100644 --- a/index.ts +++ b/index.ts @@ -1,33 +1,33 @@ -import { app } from "./app"; -import { logger } from "./logger"; +import { app } from './app'; +import { logger } from './logger'; -const port = app.get("port"); -const host = app.get("host"); +const port = app.get('port'); +const host = app.get('host'); const server = app.listen(port); app.listen(port).then(() => { - logger.info(`Walias app listening on http://${host}:${port}`); + logger.info(`Walias app listening on http://${host}:${port}`); }); -process.on("SIGINT", () => { - logger.info("Received SIGINT signal. Shutting down gracefully."); +process.on('SIGINT', () => { + logger.info('Received SIGINT signal. Shutting down gracefully.'); - server.close(() => { - logger.info("HTTP server closed."); - process.exit(0); - }); + server.close(() => { + logger.info('HTTP server closed.'); + process.exit(0); + }); }); -process.on("SIGTERM", () => { - logger.info("Received SIGTERM signal. Shutting down gracefully."); +process.on('SIGTERM', () => { + logger.info('Received SIGTERM signal. Shutting down gracefully.'); - server.close(() => { - logger.info("HTTP server closed."); - process.exit(0); - }); + server.close(() => { + logger.info('HTTP server closed.'); + process.exit(0); + }); }); -process.on("unhandledRejection", (reason) => { - logger.error("Unhandled rejection", reason); - process.exit(1); +process.on('unhandledRejection', reason => { + logger.error('Unhandled rejection', reason); + process.exit(1); }); diff --git a/logger.ts b/logger.ts index 57edc25..99097e3 100644 --- a/logger.ts +++ b/logger.ts @@ -1,10 +1,10 @@ // For more information about this file see https://dove.feathersjs.com/guides/cli/logging.html -import { createLogger, format, transports } from "winston"; +import { createLogger, format, transports } from 'winston'; // Configure the Winston logger. For the complete documentation see https://github.com/winstonjs/winston export const logger = createLogger({ - // To see more detailed errors, change this to 'debug' - level: "info", - format: format.combine(format.splat(), format.simple()), - transports: [new transports.Console()], + // To see more detailed errors, change this to 'debug' + level: 'info', + format: format.combine(format.splat(), format.simple()), + transports: [new transports.Console()], }); diff --git a/src/app.ts b/src/app.ts index 65bb717..123a78c 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1,27 +1,19 @@ -import { randomUUID } from "crypto"; -import { feathers } from "@feathersjs/feathers"; -import express, { - rest, - json, - urlencoded, - cors, - serveStatic, - notFound, - errorHandler, -} from "@feathersjs/express"; -import configuration from "@feathersjs/configuration"; -import socketio from "@feathersjs/socketio"; -import session from "express-session"; -import cookieParser from "cookie-parser"; -import RedisStore from "connect-redis"; -import { createClient } from "redis"; -import config from "config"; -import type { Application } from "./declarations"; -import { logger } from "./logger"; -import { logError } from "./hooks/log-error"; -import { services } from "./services/index"; -import { channels } from "./channels"; -import { Env, getEnv } from "./helpers/get-env"; +import { randomUUID } from 'crypto'; +import { feathers } from '@feathersjs/feathers'; +import express, { rest, json, urlencoded, cors, serveStatic, notFound, errorHandler } from '@feathersjs/express'; +import configuration from '@feathersjs/configuration'; +import socketio from '@feathersjs/socketio'; +import session from 'express-session'; +import cookieParser from 'cookie-parser'; +import RedisStore from 'connect-redis'; +import { createClient } from 'redis'; +import config from 'config'; +import type { Application } from './declarations'; +import { logger } from './logger'; +import { logError } from './hooks/log-error'; +import { services } from './services/index'; +import { channels } from './channels'; +import { Env, getEnv } from './helpers/get-env'; const app: Application = express(feathers()); @@ -29,54 +21,54 @@ const app: Application = express(feathers()); app.configure(configuration()); app.use(cors()); app.use( - json({ - limit: "20mb", - }), + json({ + limit: '20mb', + }) ); app.use(cookieParser()); const sessionStore = - getEnv() === Env.prod - ? new RedisStore({ - prefix: "walias:", - client: createClient({ - url: config.get("redis.url"), - }), - }) - : undefined; + getEnv() === Env.prod + ? new RedisStore({ + prefix: 'walias:', + client: createClient({ + url: config.get('redis.url'), + }), + }) + : undefined; app.use( - session({ - store: sessionStore, - secret: randomUUID(), - resave: false, - saveUninitialized: false, - cookie: { secure: false }, - }), + session({ + store: sessionStore, + secret: randomUUID(), + resave: false, + saveUninitialized: false, + cookie: { secure: false }, + }) ); // Propagate session to request.params in feathers services app.use(function (req, _res, next) { - req.feathers = { - ...req.feathers, - session: req.session, - }; - next(); + req.feathers = { + ...req.feathers, + session: req.session, + }; + next(); }); app.use(urlencoded({ extended: true })); // Host the public folder -app.use("/", serveStatic(app.get("public"))); +app.use('/', serveStatic(app.get('public'))); // Configure services and real-time functionality app.configure(rest()); app.configure( - socketio({ - cors: { - origin: app.get("origins"), - }, - }), + socketio({ + cors: { + origin: app.get('origins'), + }, + }) ); app.configure(services); app.configure(channels); @@ -87,17 +79,17 @@ app.use(errorHandler({ logger })); // Register hooks that run on all service methods app.hooks({ - around: { - all: [logError], - }, - before: {}, - after: {}, - error: {}, + around: { + all: [logError], + }, + before: {}, + after: {}, + error: {}, }); // Register application setup and teardown hooks here app.hooks({ - setup: [], - teardown: [], + setup: [], + teardown: [], }); export { app }; diff --git a/src/channels.ts b/src/channels.ts index 53d5203..6f0fcb9 100644 --- a/src/channels.ts +++ b/src/channels.ts @@ -1,41 +1,38 @@ // For more information about this file see https://dove.feathersjs.com/guides/cli/channels.html -import type { RealTimeConnection, Params } from "@feathersjs/feathers"; -import type { AuthenticationResult } from "@feathersjs/authentication"; -import "@feathersjs/transport-commons"; -import type { Application, HookContext } from "./declarations"; -import { logger } from "./logger"; +import type { RealTimeConnection, Params } from '@feathersjs/feathers'; +import type { AuthenticationResult } from '@feathersjs/authentication'; +import '@feathersjs/transport-commons'; +import type { Application, HookContext } from './declarations'; +import { logger } from './logger'; export const channels = (app: Application) => { - logger.warn( - "Publishing all events to all authenticated users. See `channels.ts` and https://dove.feathersjs.com/api/channels.html for more information.", - ); + logger.warn( + 'Publishing all events to all authenticated users. See `channels.ts` and https://dove.feathersjs.com/api/channels.html for more information.' + ); - app.on("connection", (connection: RealTimeConnection) => { - // On a new real-time connection, add it to the anonymous channel - app.channel("anonymous").join(connection); - }); + app.on('connection', (connection: RealTimeConnection) => { + // On a new real-time connection, add it to the anonymous channel + app.channel('anonymous').join(connection); + }); - app.on( - "login", - (authResult: AuthenticationResult, { connection }: Params) => { - // connection can be undefined if there is no - // real-time connection, e.g. when logging in via REST - if (connection) { - // The connection is no longer anonymous, remove it - app.channel("anonymous").leave(connection); + app.on('login', (authResult: AuthenticationResult, { connection }: Params) => { + // connection can be undefined if there is no + // real-time connection, e.g. when logging in via REST + if (connection) { + // The connection is no longer anonymous, remove it + app.channel('anonymous').leave(connection); - // Add it to the authenticated user channel - app.channel("authenticated").join(connection); - } - }, - ); + // Add it to the authenticated user channel + app.channel('authenticated').join(connection); + } + }); - // eslint-disable-next-line no-unused-vars - app.publish((data: any, context: HookContext) => { - // Here you can add event publishers to channels set up in `channels.js` - // To publish only for a specific event use `app.publish(eventname, () => {})` + // eslint-disable-next-line no-unused-vars + app.publish((data: any, context: HookContext) => { + // Here you can add event publishers to channels set up in `channels.js` + // To publish only for a specific event use `app.publish(eventname, () => {})` - // e.g. to publish all service events to all authenticated users use - return app.channel("authenticated"); - }); + // e.g. to publish all service events to all authenticated users use + return app.channel('authenticated'); + }); }; diff --git a/src/clients/wildduck.client.ts b/src/clients/wildduck.client.ts index ef880a2..383740c 100644 --- a/src/clients/wildduck.client.ts +++ b/src/clients/wildduck.client.ts @@ -1,12 +1,12 @@ -import axios from "axios"; -import config from "config"; +import axios from 'axios'; +import config from 'config'; const wildDuckClient = axios.create({ - baseURL: config.get("wildDuck.url"), - headers: { - "X-Access-Token": config.get("wildDuck.token"), - }, - responseType: "json", + baseURL: config.get('wildDuck.url'), + headers: { + 'X-Access-Token': config.get('wildDuck.token'), + }, + responseType: 'json', }); export default wildDuckClient; diff --git a/src/declarations.ts b/src/declarations.ts index 2f7319d..2a65a3b 100644 --- a/src/declarations.ts +++ b/src/declarations.ts @@ -1,9 +1,6 @@ // For more information about this file see https://dove.feathersjs.com/guides/cli/typescript.html -import { - HookContext as FeathersHookContext, - NextFunction, -} from "@feathersjs/feathers"; -import { Application as FeathersApplication } from "@feathersjs/express"; +import { HookContext as FeathersHookContext, NextFunction } from '@feathersjs/feathers'; +import { Application as FeathersApplication } from '@feathersjs/express'; type ApplicationConfiguration = any; export { NextFunction }; diff --git a/src/helpers/get-env.ts b/src/helpers/get-env.ts index 4198918..0c40f6b 100644 --- a/src/helpers/get-env.ts +++ b/src/helpers/get-env.ts @@ -1,16 +1,16 @@ export enum Env { - dev = "dev", - prod = "prod", - test = "test", + dev = 'dev', + prod = 'prod', + test = 'test', } export const getEnv = (): Env => { - const env = process.env.NODE_ENV; - if (env === "prod") { - return Env.prod; - } else if (env === "test") { - return Env.test; - } else { - return Env.dev; - } + const env = process.env.NODE_ENV; + if (env === 'prod') { + return Env.prod; + } else if (env === 'test') { + return Env.test; + } else { + return Env.dev; + } }; diff --git a/src/hooks/log-error.ts b/src/hooks/log-error.ts index 787730f..14e0ad0 100644 --- a/src/hooks/log-error.ts +++ b/src/hooks/log-error.ts @@ -1,17 +1,17 @@ -import type { HookContext, NextFunction } from "../declarations"; -import { logger } from "../logger"; +import type { HookContext, NextFunction } from '../declarations'; +import { logger } from '../logger'; export const logError = async (context: HookContext, next: NextFunction) => { - try { - await next(); - } catch (error: any) { - logger.error(error.stack); + try { + await next(); + } catch (error: any) { + logger.error(error.stack); - // Log validation errors - if (error.data) { - logger.error("Data: %O", error.data); + // Log validation errors + if (error.data) { + logger.error('Data: %O', error.data); + } + + throw error; } - - throw error; - } }; diff --git a/src/hooks/validate-auth.ts b/src/hooks/validate-auth.ts index 3de2f11..a9ec365 100644 --- a/src/hooks/validate-auth.ts +++ b/src/hooks/validate-auth.ts @@ -1,9 +1,9 @@ -import { NotAuthenticated } from "@feathersjs/errors"; -import type { HookContext, NextFunction } from "../declarations"; +import { NotAuthenticated } from '@feathersjs/errors'; +import type { HookContext, NextFunction } from '../declarations'; // Check if user is stored in session export const validateAuth = async (context: HookContext) => { - if (!context.params.session?.user) { - throw new NotAuthenticated("Not authenticated"); - } + if (!context.params.session?.user) { + throw new NotAuthenticated('Not authenticated'); + } }; diff --git a/src/index.ts b/src/index.ts index a203c16..f8fffc5 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,13 +1,11 @@ -import { app } from "./app"; -import { logger } from "./logger"; +import { app } from './app'; +import { logger } from './logger'; -const port = app.get("port"); -const host = app.get("host"); +const port = app.get('port'); +const host = app.get('host'); -process.on("unhandledRejection", (reason) => - logger.error("Unhandled Rejection %O", reason), -); +process.on('unhandledRejection', reason => logger.error('Unhandled Rejection %O', reason)); app.listen(port).then(() => { - logger.info(`Feathers app listening on http://${host}:${port}`); + logger.info(`Feathers app listening on http://${host}:${port}`); }); diff --git a/src/logger.ts b/src/logger.ts index 57edc25..99097e3 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -1,10 +1,10 @@ // For more information about this file see https://dove.feathersjs.com/guides/cli/logging.html -import { createLogger, format, transports } from "winston"; +import { createLogger, format, transports } from 'winston'; // Configure the Winston logger. For the complete documentation see https://github.com/winstonjs/winston export const logger = createLogger({ - // To see more detailed errors, change this to 'debug' - level: "info", - format: format.combine(format.splat(), format.simple()), - transports: [new transports.Console()], + // To see more detailed errors, change this to 'debug' + level: 'info', + format: format.combine(format.splat(), format.simple()), + transports: [new transports.Console()], }); diff --git a/src/services/aliases/aliases.class.ts b/src/services/aliases/aliases.class.ts index a089feb..7f427d6 100644 --- a/src/services/aliases/aliases.class.ts +++ b/src/services/aliases/aliases.class.ts @@ -1,186 +1,142 @@ -import type { - NullableId, - Params, - ServiceInterface, -} from "@feathersjs/feathers"; +import type { NullableId, Params, ServiceInterface } from '@feathersjs/feathers'; -import type { Application } from "../../declarations"; -import wildDuckClient from "../../clients/wildduck.client"; -import { faker, th } from "@faker-js/faker"; -import { BadRequest } from "@feathersjs/errors"; -import config from "config"; +import type { Application } from '../../declarations'; +import wildDuckClient from '../../clients/wildduck.client'; +import { faker, th } from '@faker-js/faker'; +import { BadRequest } from '@feathersjs/errors'; +import config from 'config'; interface WildDuckAddress { - success: boolean; - id: string; - address: string; - main: boolean; - user: string; - tags: string[]; - created: string; + success: boolean; + id: string; + address: string; + main: boolean; + user: string; + tags: string[]; + created: string; } interface GetWildDuckAddressInfoResponse { - success: boolean; - results: WildDuckAddress[]; + success: boolean; + results: WildDuckAddress[]; } interface AliasApiResponse { - id: string | null; - address: string; - tags: string[]; - created: string; + id: string | null; + address: string; + tags: string[]; + created: string; } interface CreateWildDuckAddressResponse { - success: boolean; - id: string; + success: boolean; + id: string; } type AliasesData = any; type AliasesPatch = any; type AliasesQuery = any; -export type { - WildDuckAddress as Aliases, - AliasesData, - AliasesPatch, - AliasesQuery, -}; +export type { WildDuckAddress as Aliases, AliasesData, AliasesPatch, AliasesQuery }; export interface AliasesServiceOptions { - app: Application; + app: Application; } export interface AliasesParams extends Params { - session?: any; + session?: any; } export class AliasesService - implements - ServiceInterface< - AliasApiResponse, - AliasesData, - ServiceParams, - AliasesPatch - > + implements ServiceInterface { - constructor(public options: AliasesServiceOptions) {} + constructor(public options: AliasesServiceOptions) {} - async find(params: ServiceParams): Promise { - const userId = await this.getUserIdByEmailAddress(params); + async find(params: ServiceParams): Promise { + const userId = await this.getUserIdByEmailAddress(params); - return this.getUserAddresses(userId); - } - - async create( - data: AliasesData, - params: ServiceParams, - ): Promise; - async create( - data: AliasesData, - params: ServiceParams, - ): Promise { - const userId = await this.getUserIdByEmailAddress(params); - - const randomString = faker.git.commitSha({ length: 4 }); - - // Replace all non-alphanumeric characters with nothing and spaces with dashes - const alias = - `${faker.color.human()}-${faker.animal.snake()}-${randomString}` - .replace(/\s+/g, "-") - .replace(/[^a-zA-Z0-9-]/g, "") - .toLowerCase(); - - const emailDomain = config.get("wildDuck.domain"); - - const createResult = - await wildDuckClient.post( - `/users/${userId}/addresses`, - { - address: `${alias}@${emailDomain}`, - }, - ); - - if (!createResult.data.success) { - throw new BadRequest("Failed to create alias"); + return this.getUserAddresses(userId); } - return this.getUserAddresses(userId); - } + async create(data: AliasesData, params: ServiceParams): Promise; + async create(data: AliasesData, params: ServiceParams): Promise { + const userId = await this.getUserIdByEmailAddress(params); - private async getUserIdByEmailAddress( - params: ServiceParams, - ): Promise { - const emails = params.session?.user?.emails; + const randomString = faker.git.commitSha({ length: 4 }); - const preferredDomain = config.get("wildDuck.preferredDomain"); + // Replace all non-alphanumeric characters with nothing and spaces with dashes + const alias = `${faker.color.human()}-${faker.animal.snake()}-${randomString}` + .replace(/\s+/g, '-') + .replace(/[^a-zA-Z0-9-]/g, '') + .toLowerCase(); - if (!emails.length || !preferredDomain) { - throw new BadRequest("Unable to find user"); + const emailDomain = config.get('wildDuck.domain'); + + const createResult = await wildDuckClient.post(`/users/${userId}/addresses`, { + address: `${alias}@${emailDomain}`, + }); + + if (!createResult.data.success) { + throw new BadRequest('Failed to create alias'); + } + + return this.getUserAddresses(userId); } - const addressInfoResponse = await Promise.any( - emails - .filter((email: string) => - email.endsWith(config.get("wildDuck.preferredDomain")), - ) - .map((email: string) => - wildDuckClient.get(`addresses/resolve/${email}`), - ), - ); + private async getUserIdByEmailAddress(params: ServiceParams): Promise { + const emails = params.session?.user?.emails; - return addressInfoResponse.data.user; - } + const preferredDomain = config.get('wildDuck.preferredDomain'); - private async getUserAddresses(userId: string): Promise { - const { data: userAddressesResponse } = - await wildDuckClient.get( - `/users/${userId}/addresses`, - ); + if (!emails.length || !preferredDomain) { + throw new BadRequest('Unable to find user'); + } - return userAddressesResponse.results.map(this.sanitizeAliasResponse); - } + const addressInfoResponse = await Promise.any( + emails + .filter((email: string) => email.endsWith(config.get('wildDuck.preferredDomain'))) + .map((email: string) => wildDuckClient.get(`addresses/resolve/${email}`)) + ); - async remove( - id: NullableId, - params: ServiceParams, - ): Promise { - const { data: addressInfoResponse } = - await wildDuckClient.get(`addresses/resolve/${id}`); - const allowedDomain: string = config.get("wildDuck.domain"); - - // If address does not match the allowed domain, throw an error - if ( - !allowedDomain || - !addressInfoResponse.address.endsWith(allowedDomain) - ) { - throw new BadRequest("Unable to delete address"); + return addressInfoResponse.data.user; } - const userId = await this.getUserIdByEmailAddress(params); - await wildDuckClient.delete( - `users/${userId}/addresses/${id}`, - ); + private async getUserAddresses(userId: string): Promise { + const { data: userAddressesResponse } = await wildDuckClient.get( + `/users/${userId}/addresses` + ); - return this.getUserAddresses(userId); - } + return userAddressesResponse.results.map(this.sanitizeAliasResponse); + } - sanitizeAliasResponse(alias: WildDuckAddress): AliasApiResponse { - // Hide the id if the alias is not removable - const isRemovable = - alias.main || - !alias.address.endsWith(config.get("wildDuck.preferredDomain")); + async remove(id: NullableId, params: ServiceParams): Promise { + const { data: addressInfoResponse } = await wildDuckClient.get(`addresses/resolve/${id}`); + const allowedDomain: string = config.get('wildDuck.domain'); - return { - id: isRemovable ? null : alias.id, - address: alias.address, - tags: alias.tags, - created: alias.created, - }; - } + // If address does not match the allowed domain, throw an error + if (!allowedDomain || !addressInfoResponse.address.endsWith(allowedDomain)) { + throw new BadRequest('Unable to delete address'); + } + const userId = await this.getUserIdByEmailAddress(params); + + await wildDuckClient.delete(`users/${userId}/addresses/${id}`); + + return this.getUserAddresses(userId); + } + + sanitizeAliasResponse(alias: WildDuckAddress): AliasApiResponse { + // Hide the id if the alias is not removable + const isRemovable = alias.main || !alias.address.endsWith(config.get('wildDuck.preferredDomain')); + + return { + id: isRemovable ? null : alias.id, + address: alias.address, + tags: alias.tags, + created: alias.created, + }; + } } export const getOptions = (app: Application) => { - return { app }; + return { app }; }; diff --git a/src/services/aliases/aliases.ts b/src/services/aliases/aliases.ts index 97ba226..afc3f87 100644 --- a/src/services/aliases/aliases.ts +++ b/src/services/aliases/aliases.ts @@ -1,39 +1,39 @@ -import type { Application } from "../../declarations"; -import { validateAuth } from "../../hooks/validate-auth"; -import { AliasesService, getOptions } from "./aliases.class"; +import type { Application } from '../../declarations'; +import { validateAuth } from '../../hooks/validate-auth'; +import { AliasesService, getOptions } from './aliases.class'; -export const aliasesPath = "aliases"; -export const aliasesMethods = ["find", "create", "remove"] as const; +export const aliasesPath = 'aliases'; +export const aliasesMethods = ['find', 'create', 'remove'] as const; -export * from "./aliases.class"; +export * from './aliases.class'; export const aliases = (app: Application) => { - app.use(aliasesPath, new AliasesService(getOptions(app)), { - methods: aliasesMethods, - events: [], - }); + app.use(aliasesPath, new AliasesService(getOptions(app)), { + methods: aliasesMethods, + events: [], + }); - app.service(aliasesPath).hooks({ - around: { - all: [], - }, - before: { - all: [validateAuth], - find: [], - create: [], - }, - after: { - all: [], - }, - error: { - all: [], - }, - }); + app.service(aliasesPath).hooks({ + around: { + all: [], + }, + before: { + all: [validateAuth], + find: [], + create: [], + }, + after: { + all: [], + }, + error: { + all: [], + }, + }); }; // Add this service to the service type index -declare module "../../declarations" { - interface ServiceTypes { - [aliasesPath]: AliasesService; - } +declare module '../../declarations' { + interface ServiceTypes { + [aliasesPath]: AliasesService; + } } diff --git a/src/services/auth-oidc/auth-oidc.class.ts b/src/services/auth-oidc/auth-oidc.class.ts index 4a5797f..c0cc4d3 100644 --- a/src/services/auth-oidc/auth-oidc.class.ts +++ b/src/services/auth-oidc/auth-oidc.class.ts @@ -1,9 +1,9 @@ -import type { Params, ServiceInterface } from "@feathersjs/feathers"; +import type { Params, ServiceInterface } from '@feathersjs/feathers'; -import type { Application } from "../../declarations"; +import type { Application } from '../../declarations'; -import { Issuer, generators } from "openid-client"; -import config from "config"; +import { Issuer, generators } from 'openid-client'; +import config from 'config'; type AuthOidcResponse = string; type AuthOidcQuery = any; @@ -11,43 +11,42 @@ type AuthOidcQuery = any; export type { AuthOidcResponse as AuthOidc, AuthOidcQuery }; export interface AuthOidcServiceOptions { - app: Application; + app: Application; } export interface AuthOidcParams extends Params { - session?: any; + session?: any; } -export class AuthOidcService< - ServiceParams extends AuthOidcParams = AuthOidcParams, -> implements ServiceInterface +export class AuthOidcService + implements ServiceInterface { - constructor(public options: AuthOidcServiceOptions) {} + constructor(public options: AuthOidcServiceOptions) {} - async find(params: ServiceParams): Promise { - const issuer = await Issuer.discover(config.get("oidc.gatewayUri")); - const client = new issuer.Client({ - client_id: config.get("oidc.clientId"), - client_secret: config.get("oidc.clientSecret"), - redirect_uris: [config.get("oidc.redirectUris")], - response_types: ["code"], - }); - const codeVerifier = generators.codeVerifier(); - const codeChallenge = generators.codeChallenge(codeVerifier); + async find(params: ServiceParams): Promise { + const issuer = await Issuer.discover(config.get('oidc.gatewayUri')); + const client = new issuer.Client({ + client_id: config.get('oidc.clientId'), + client_secret: config.get('oidc.clientSecret'), + redirect_uris: [config.get('oidc.redirectUris')], + response_types: ['code'], + }); + const codeVerifier = generators.codeVerifier(); + const codeChallenge = generators.codeChallenge(codeVerifier); - const url = client.authorizationUrl({ - redirect_uri: config.get("clientUrl") + "/auth-oidc/callback", - scope: "openid profile offline_access", - response_type: "code", - code_challenge: codeChallenge, - code_challenge_method: "S256", - }); + const url = client.authorizationUrl({ + redirect_uri: config.get('clientUrl') + '/auth-oidc/callback', + scope: 'openid profile offline_access', + response_type: 'code', + code_challenge: codeChallenge, + code_challenge_method: 'S256', + }); - params.session.codeVerifier = codeVerifier; - return url; - } + params.session.codeVerifier = codeVerifier; + return url; + } } export const getOptions = (app: Application) => { - return { app }; + return { app }; }; diff --git a/src/services/auth-oidc/auth-oidc.ts b/src/services/auth-oidc/auth-oidc.ts index fc4c484..ce6e76d 100644 --- a/src/services/auth-oidc/auth-oidc.ts +++ b/src/services/auth-oidc/auth-oidc.ts @@ -1,45 +1,45 @@ -import type { Application } from "../../declarations"; -import { AuthOidcService, getOptions } from "./auth-oidc.class"; +import type { Application } from '../../declarations'; +import { AuthOidcService, getOptions } from './auth-oidc.class'; -export const authOidcPath = "auth-oidc"; -export const authOidcMethods = ["find"] as const; +export const authOidcPath = 'auth-oidc'; +export const authOidcMethods = ['find'] as const; -export * from "./auth-oidc.class"; +export * from './auth-oidc.class'; export const authOidc = (app: Application) => { - // TODO: fix this to use the correct type - // @ts-ignore - app.use( - authOidcPath, - new AuthOidcService(getOptions(app)), - { - methods: authOidcMethods, - events: [], - }, - (req: any, res: any) => { - return res.redirect(res.data); - }, - ); + // TODO: fix this to use the correct type + // @ts-ignore + app.use( + authOidcPath, + new AuthOidcService(getOptions(app)), + { + methods: authOidcMethods, + events: [], + }, + (req: any, res: any) => { + return res.redirect(res.data); + } + ); - app.service(authOidcPath).hooks({ - around: { - all: [], - }, - before: { - all: [], - find: [], - }, - after: { - all: [], - }, - error: { - all: [], - }, - }); + app.service(authOidcPath).hooks({ + around: { + all: [], + }, + before: { + all: [], + find: [], + }, + after: { + all: [], + }, + error: { + all: [], + }, + }); }; -declare module "../../declarations" { - interface ServiceTypes { - [authOidcPath]: AuthOidcService; - } +declare module '../../declarations' { + interface ServiceTypes { + [authOidcPath]: AuthOidcService; + } } diff --git a/src/services/auth-oidc/callback/auth-oidc-callback.class.ts b/src/services/auth-oidc/callback/auth-oidc-callback.class.ts index cd4e3db..c4c9234 100644 --- a/src/services/auth-oidc/callback/auth-oidc-callback.class.ts +++ b/src/services/auth-oidc/callback/auth-oidc-callback.class.ts @@ -1,68 +1,56 @@ -import type { Params, ServiceInterface } from "@feathersjs/feathers"; -import type { Application } from "../../../declarations"; -import { Issuer } from "openid-client"; +import type { Params, ServiceInterface } from '@feathersjs/feathers'; +import type { Application } from '../../../declarations'; +import { Issuer } from 'openid-client'; -import config from "config"; +import config from 'config'; type AuthOidcCallback = string; type AuthOidcCallbackData = any; type AuthOidcCallbackPatch = any; type AuthOidcCallbackQuery = any; -export type { - AuthOidcCallback, - AuthOidcCallbackData, - AuthOidcCallbackPatch, - AuthOidcCallbackQuery, -}; +export type { AuthOidcCallback, AuthOidcCallbackData, AuthOidcCallbackPatch, AuthOidcCallbackQuery }; export interface AuthOidcCallbackServiceOptions { - app: Application; + app: Application; } export interface AuthOidcCallbackParams extends Params { - session?: any; - query: { - iss: string; - code: string; - }; + session?: any; + query: { + iss: string; + code: string; + }; } -export class AuthOidcCallbackService< - ServiceParams extends AuthOidcCallbackParams = AuthOidcCallbackParams, -> implements - ServiceInterface< - AuthOidcCallback, - AuthOidcCallbackData, - ServiceParams, - AuthOidcCallbackPatch - > +export class AuthOidcCallbackService + implements ServiceInterface { - constructor(public options: AuthOidcCallbackServiceOptions) {} + constructor(public options: AuthOidcCallbackServiceOptions) {} - async find(params: ServiceParams): Promise { - const issuer = await Issuer.discover(config.get("oidc.gatewayUri")); - const client = new issuer.Client({ - client_id: config.get("oidc.clientId"), - client_secret: config.get("oidc.clientSecret"), - redirect_uris: [config.get("oidc.redirectUris")], - response_types: ["code"], - }); + async find(params: ServiceParams): Promise { + const issuer = await Issuer.discover(config.get('oidc.gatewayUri')); + const client = new issuer.Client({ + client_id: config.get('oidc.clientId'), + client_secret: config.get('oidc.clientSecret'), + redirect_uris: [config.get('oidc.redirectUris')], + response_types: ['code'], + }); - const codeVerifier = params.session.codeVerifier; - const tokenSet = await client.callback( - config.get("clientUrl") + "/auth-oidc/callback", - { code: params.query.code, iss: params.query.iss }, - { code_verifier: codeVerifier }, - ); - const userinfo = await client.userinfo(tokenSet.access_token as string); + const codeVerifier = params.session.codeVerifier; + const tokenSet = await client.callback( + config.get('clientUrl') + '/auth-oidc/callback', + { code: params.query.code, iss: params.query.iss }, + { code_verifier: codeVerifier } + ); + const userinfo = await client.userinfo(tokenSet.access_token as string); - params.session.user = userinfo; + params.session.user = userinfo; - return "/"; - } + return '/'; + } } export const getOptions = (app: Application) => { - return { app }; + return { app }; }; diff --git a/src/services/auth-oidc/callback/auth-oidc-callback.ts b/src/services/auth-oidc/callback/auth-oidc-callback.ts index 5131b2e..9024d2c 100644 --- a/src/services/auth-oidc/callback/auth-oidc-callback.ts +++ b/src/services/auth-oidc/callback/auth-oidc-callback.ts @@ -1,49 +1,46 @@ -import { http } from "@feathersjs/transport-commons"; -import type { Application } from "../../../declarations"; -import { - AuthOidcCallbackService, - getOptions, -} from "./auth-oidc-callback.class"; +import { http } from '@feathersjs/transport-commons'; +import type { Application } from '../../../declarations'; +import { AuthOidcCallbackService, getOptions } from './auth-oidc-callback.class'; -export const authOidcCallbackPath = "auth-oidc/callback"; -export const authOidcCallbackMethods = ["find"] as const; +export const authOidcCallbackPath = 'auth-oidc/callback'; +export const authOidcCallbackMethods = ['find'] as const; -export * from "./auth-oidc-callback.class"; +export * from './auth-oidc-callback.class'; export const authOidcCallback = (app: Application) => { - // TODO: fix this to use the correct type - // @ts-ignore - app.use( - authOidcCallbackPath, - new AuthOidcCallbackService(getOptions(app)), - { - methods: authOidcCallbackMethods, - events: [], - }, - (req: any, res: any) => { - return res.redirect(res.data); - }, - ); + // TODO: fix this to use the correct type + // @ts-ignore + app.use( + authOidcCallbackPath, + new AuthOidcCallbackService(getOptions(app)), + { + methods: authOidcCallbackMethods, + events: [], + }, + (req: any, res: any) => { + return res.redirect(res.data); + } + ); - app.service(authOidcCallbackPath).hooks({ - around: { - all: [], - }, - before: { - all: [], - find: [], - }, - after: { - all: [], - }, - error: { - all: [], - }, - }); + app.service(authOidcCallbackPath).hooks({ + around: { + all: [], + }, + before: { + all: [], + find: [], + }, + after: { + all: [], + }, + error: { + all: [], + }, + }); }; -declare module "../../../declarations" { - interface ServiceTypes { - [authOidcCallbackPath]: AuthOidcCallbackService; - } +declare module '../../../declarations' { + interface ServiceTypes { + [authOidcCallbackPath]: AuthOidcCallbackService; + } } diff --git a/src/services/index.ts b/src/services/index.ts index b5e6904..9a84b7a 100644 --- a/src/services/index.ts +++ b/src/services/index.ts @@ -1,10 +1,10 @@ -import { authOidcCallback } from "./auth-oidc/callback/auth-oidc-callback"; -import { authOidc } from "./auth-oidc/auth-oidc"; -import { aliases } from "./aliases/aliases"; -import type { Application } from "../declarations"; +import { authOidcCallback } from './auth-oidc/callback/auth-oidc-callback'; +import { authOidc } from './auth-oidc/auth-oidc'; +import { aliases } from './aliases/aliases'; +import type { Application } from '../declarations'; export const services = (app: Application) => { - app.configure(authOidcCallback); - app.configure(authOidc); - app.configure(aliases); + app.configure(authOidcCallback); + app.configure(authOidc); + app.configure(aliases); }; diff --git a/src/validators.ts b/src/validators.ts index a540fc9..2a69f14 100644 --- a/src/validators.ts +++ b/src/validators.ts @@ -1,29 +1,29 @@ // For more information about this file see https://dove.feathersjs.com/guides/cli/validators.html -import { Ajv, addFormats } from "@feathersjs/schema"; -import type { FormatsPluginOptions } from "@feathersjs/schema"; +import { Ajv, addFormats } from '@feathersjs/schema'; +import type { FormatsPluginOptions } from '@feathersjs/schema'; const formats: FormatsPluginOptions = [ - "date-time", - "time", - "date", - "email", - "hostname", - "ipv4", - "ipv6", - "uri", - "uri-reference", - "uuid", - "uri-template", - "json-pointer", - "relative-json-pointer", - "regex", + 'date-time', + 'time', + 'date', + 'email', + 'hostname', + 'ipv4', + 'ipv6', + 'uri', + 'uri-reference', + 'uuid', + 'uri-template', + 'json-pointer', + 'relative-json-pointer', + 'regex', ]; export const dataValidator: Ajv = addFormats(new Ajv({}), formats); export const queryValidator: Ajv = addFormats( - new Ajv({ - coerceTypes: true, - }), - formats, + new Ajv({ + coerceTypes: true, + }), + formats ); diff --git a/test/app.test.ts b/test/app.test.ts index fb37c1b..1ca0133 100644 --- a/test/app.test.ts +++ b/test/app.test.ts @@ -1,40 +1,40 @@ // For more information about this file see https://dove.feathersjs.com/guides/cli/app.test.html -import assert from "assert"; -import axios from "axios"; -import type { Server } from "http"; -import { app } from "../src/app"; +import assert from 'assert'; +import axios from 'axios'; +import type { Server } from 'http'; +import { app } from '../src/app'; -const port = app.get("port"); -const appUrl = `http://${app.get("host")}:${port}`; +const port = app.get('port'); +const appUrl = `http://${app.get('host')}:${port}`; -describe("Feathers application tests", () => { - let server: Server; +describe('Feathers application tests', () => { + let server: Server; - before(async () => { - server = await app.listen(port); - }); + before(async () => { + server = await app.listen(port); + }); - after(async () => { - await app.teardown(); - }); + after(async () => { + await app.teardown(); + }); - it("starts and shows the index page", async () => { - const { data } = await axios.get(appUrl); + it('starts and shows the index page', async () => { + const { data } = await axios.get(appUrl); - assert.ok(data.indexOf('') !== -1); - }); + assert.ok(data.indexOf('') !== -1); + }); - it("shows a 404 JSON error", async () => { - try { - await axios.get(`${appUrl}/path/to/nowhere`, { - responseType: "json", - }); - assert.fail("should never get here"); - } catch (error: any) { - const { response } = error; - assert.strictEqual(response?.status, 404); - assert.strictEqual(response?.data?.code, 404); - assert.strictEqual(response?.data?.name, "NotFound"); - } - }); + it('shows a 404 JSON error', async () => { + try { + await axios.get(`${appUrl}/path/to/nowhere`, { + responseType: 'json', + }); + assert.fail('should never get here'); + } catch (error: any) { + const { response } = error; + assert.strictEqual(response?.status, 404); + assert.strictEqual(response?.data?.code, 404); + assert.strictEqual(response?.data?.name, 'NotFound'); + } + }); }); diff --git a/test/services/aliases/aliases.test.ts b/test/services/aliases/aliases.test.ts index db9f5e2..ba8cba8 100644 --- a/test/services/aliases/aliases.test.ts +++ b/test/services/aliases/aliases.test.ts @@ -1,11 +1,11 @@ // For more information about this file see https://dove.feathersjs.com/guides/cli/service.test.html -import assert from "assert"; -import { app } from "../../../src/app"; +import assert from 'assert'; +import { app } from '../../../src/app'; -describe("aliases service", () => { - it("registered the service", () => { - const service = app.service("aliases"); +describe('aliases service', () => { + it('registered the service', () => { + const service = app.service('aliases'); - assert.ok(service, "Registered the service"); - }); + assert.ok(service, 'Registered the service'); + }); }); diff --git a/test/services/auth-oidc/auth-oidc.test.ts b/test/services/auth-oidc/auth-oidc.test.ts index e877a96..68dfe26 100644 --- a/test/services/auth-oidc/auth-oidc.test.ts +++ b/test/services/auth-oidc/auth-oidc.test.ts @@ -1,11 +1,11 @@ // For more information about this file see https://dove.feathersjs.com/guides/cli/service.test.html -import assert from "assert"; -import { app } from "../../../src/app"; +import assert from 'assert'; +import { app } from '../../../src/app'; -describe("auth-oidc service", () => { - it("registered the service", () => { - const service = app.service("auth-oidc"); +describe('auth-oidc service', () => { + it('registered the service', () => { + const service = app.service('auth-oidc'); - assert.ok(service, "Registered the service"); - }); + assert.ok(service, 'Registered the service'); + }); }); diff --git a/test/services/auth-oidc/callback/callback.test.ts b/test/services/auth-oidc/callback/callback.test.ts index 2e53041..1c8e272 100644 --- a/test/services/auth-oidc/callback/callback.test.ts +++ b/test/services/auth-oidc/callback/callback.test.ts @@ -1,11 +1,11 @@ // For more information about this file see https://dove.feathersjs.com/guides/cli/service.test.html -import assert from "assert"; -import { app } from "../../../../src/app"; +import assert from 'assert'; +import { app } from '../../../../src/app'; -describe("auth-oidc/callback service", () => { - it("registered the service", () => { - const service = app.service("auth-oidc/callback"); +describe('auth-oidc/callback service', () => { + it('registered the service', () => { + const service = app.service('auth-oidc/callback'); - assert.ok(service, "Registered the service"); - }); + assert.ok(service, 'Registered the service'); + }); }); diff --git a/validators.ts b/validators.ts index a540fc9..2a69f14 100644 --- a/validators.ts +++ b/validators.ts @@ -1,29 +1,29 @@ // For more information about this file see https://dove.feathersjs.com/guides/cli/validators.html -import { Ajv, addFormats } from "@feathersjs/schema"; -import type { FormatsPluginOptions } from "@feathersjs/schema"; +import { Ajv, addFormats } from '@feathersjs/schema'; +import type { FormatsPluginOptions } from '@feathersjs/schema'; const formats: FormatsPluginOptions = [ - "date-time", - "time", - "date", - "email", - "hostname", - "ipv4", - "ipv6", - "uri", - "uri-reference", - "uuid", - "uri-template", - "json-pointer", - "relative-json-pointer", - "regex", + 'date-time', + 'time', + 'date', + 'email', + 'hostname', + 'ipv4', + 'ipv6', + 'uri', + 'uri-reference', + 'uuid', + 'uri-template', + 'json-pointer', + 'relative-json-pointer', + 'regex', ]; export const dataValidator: Ajv = addFormats(new Ajv({}), formats); export const queryValidator: Ajv = addFormats( - new Ajv({ - coerceTypes: true, - }), - formats, + new Ajv({ + coerceTypes: true, + }), + formats ); From c0a310b5ff0138c9b659025627c8209cba1599c9 Mon Sep 17 00:00:00 2001 From: Sergo Date: Sun, 6 Aug 2023 09:34:26 +0300 Subject: [PATCH 4/4] update TODO --- readme.md | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/readme.md b/readme.md index d9b8b3a..55fd6eb 100644 --- a/readme.md +++ b/readme.md @@ -7,12 +7,13 @@ This project was build for [K-Space Hackathon2023](https://wiki.k-space.ee/en/hackathon/2023) ## Features - * auth with oidc - * headless only, no DB - * develop/debug with skaffold on k8s cluster + +- auth with oidc +- headless only, no DB +- develop/debug with skaffold on k8s cluster ## TODO - * remove TS-related hacks - * add tests - * make nicer UI - * implement persistent sessions for multi-docker deployment (redis, db, etc) \ No newline at end of file + +- remove TS-related hacks +- add tests +- make nicer UI