diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index af6ff07bb..5198fef4d 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -25,7 +25,6 @@ services: - db - dm3-storage environment: - REDIS_URL: redis://db:6379 SIGNING_PUBLIC_KEY: ${SIGNING_PUBLIC_KEY} SIGNING_PRIVATE_KEY: ${SIGNING_PRIVATE_KEY} ENCRYPTION_PUBLIC_KEY: ${ENCRYPTION_PUBLIC_KEY} @@ -36,12 +35,6 @@ services: LOG_LEVEL: 'debug' DATABASE_URL: ${DATABASE_URL} - db: - image: redis - restart: always - volumes: - - ${PERSISTENCE_DIRECTORY}/db/redis:/data - dm3-storage: image: postgres:13 restart: always diff --git a/packages/backend/docker-compose.test.yml b/packages/backend/docker-compose.test.yml index bd4d42e37..1606c248d 100644 --- a/packages/backend/docker-compose.test.yml +++ b/packages/backend/docker-compose.test.yml @@ -2,12 +2,6 @@ version: '3.6' # The containers that compose the project services: - db: - image: redis - restart: always - container_name: redis-backend - ports: - - '6380:6379' # map to host port 6380 postgres: image: postgres:13 restart: always diff --git a/packages/backend/docker-compose.yml b/packages/backend/docker-compose.yml index 695e0c083..89485ee60 100644 --- a/packages/backend/docker-compose.yml +++ b/packages/backend/docker-compose.yml @@ -2,12 +2,6 @@ version: '3.6' # The containers that compose the project services: - db: - image: redis - restart: always - container_name: redis - ports: - - '6380:6379' # map to host port 6380 dm3-storage: image: postgres:13 restart: always diff --git a/packages/backend/manual_data_migration/insertWithinDocker.sh b/packages/backend/manual_data_migration/insertWithinDocker.sh deleted file mode 100755 index c99c7cf57..000000000 --- a/packages/backend/manual_data_migration/insertWithinDocker.sh +++ /dev/null @@ -1,27 +0,0 @@ -#!/bin/bash - -# Input file -input_file="dump.txt" - -DB_NAME="dm3" -DB_USER="prisma" - - -# Read the input file line by line -while IFS= read -r line -do - # Extract the ID (first part of the line) and timestamp (after "createdAt") - id=$(echo "$line" | cut -d ':' -f 2) - timestamp=$(echo "$line" | grep -oP '(?<="createdAt":)[0-9]+') - - # Convert the timestamp from milliseconds to seconds - timestamp_seconds=$(echo $timestamp | sed 's/...$//') - - # Insert the extracted values into the PostgreSQL table - psql -U $DB_USER -d $DB_NAME -c "INSERT INTO \"Account\" (id, \"createdAt\") \ - VALUES ('$id', to_timestamp($timestamp_seconds))\ - ON CONFLICT (id) \ - DO UPDATE SET \"createdAt\" = excluded.\"createdAt\";" - -done < "$input_file" - diff --git a/packages/backend/manual_data_migration/notes.md b/packages/backend/manual_data_migration/notes.md deleted file mode 100644 index f7ab24c2c..000000000 --- a/packages/backend/manual_data_migration/notes.md +++ /dev/null @@ -1,37 +0,0 @@ -Process: - -check data -`docker exec -it dm3-db-1 redis-cli --scan --pattern 'session*addr.dm3.eth'` - -`docker exec -it dm3-storage psql -U prisma -d dm3 -c 'SELECT * FROM "Account";'` - -go into the redis container -docker exec -it dm3-db-1 bash - -dump all relevant sessions -for key in `redis-cli --scan --pattern 'session*addr.dm3.eth'`; do echo $key: `redis-cli GET $key` >> dump.txt; echo $key; done - -copy the dump to the host -docker cp dm3-db-1:/data/dump.txt . - -copy the dump to the postgres container -docker cp dump.txt dm3-storage:/ - -paste script onto server -vi insertWithinDocker.sh --> paste, close - -copy the script to the postgres container -docker cp insertWithinDocker.sh dm3-storage:/ - -go into the postgres container -docker exec -it dm3-storage bash - -make script executable -chmod a+x insertWithinDocker.sh - -run the script -./insertWithinDocker.sh - -check the data from outside the container -docker exec -it dm3-storage psql -U prisma -d dm3 -c 'SELECT \* FROM "Account";' diff --git a/packages/backend/package.json b/packages/backend/package.json index 5b6cbbea7..fa2779811 100644 --- a/packages/backend/package.json +++ b/packages/backend/package.json @@ -20,7 +20,7 @@ "dotenv": "^16.0.1", "ethers": "5.7.2", "express": "^4.18.1", - "redis": "^4.1.0", + "prisma": "^5.10.1", "web-push": "^3.6.7", "yaml": "^2.1.3" }, @@ -43,7 +43,6 @@ "@types/cors": "^2.8.17", "@types/express": "^4.17.13", "@types/node": "^20.3.1", - "@types/redis": "^4.0.11", "@types/supertest": "^2.0.12", "babel-cli": "^6.26.0", "babel-jest": "^29.2.2", diff --git a/packages/backend/src/index.ts b/packages/backend/src/index.ts index 20fe2d05b..46ae634ef 100644 --- a/packages/backend/src/index.ts +++ b/packages/backend/src/index.ts @@ -1,5 +1,5 @@ import { - Auth, + Authenticate, errorHandler, getCachedWebProvider, getServerSecret, @@ -39,7 +39,7 @@ app.use(bodyParser.json()); }); app.use('/profile', Profile(db, web3Provider, serverSecret)); app.use('/storage', Storage(db, web3Provider, serverSecret)); - app.use('/auth', Auth(db, serverSecret, web3Provider)); + app.use('/auth', Authenticate(db, serverSecret, web3Provider)); app.use(logError); app.use(errorHandler); })(); diff --git a/packages/backend/src/persistence/account/getAccount.ts b/packages/backend/src/persistence/account/getAccount.ts deleted file mode 100644 index d83694907..000000000 --- a/packages/backend/src/persistence/account/getAccount.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { Redis, RedisPrefix } from '../getDatabase'; -import { Session, spamFilter } from '@dm3-org/dm3-lib-delivery'; -import { getIdEnsName } from '../getIdEnsName'; - -export function getAccount(redis: Redis) { - return async (ensName: string) => { - let session = await redis.get( - RedisPrefix.Account + (await getIdEnsName(redis)(ensName)), - ); - - console.debug('get account ', ensName, session); - - return session - ? (JSON.parse(session) as Session & { - spamFilterRules: spamFilter.SpamFilterRules; - }) - : null; - }; -} diff --git a/packages/backend/src/persistence/account/index.ts b/packages/backend/src/persistence/account/index.ts deleted file mode 100644 index 37cd75311..000000000 --- a/packages/backend/src/persistence/account/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { setAccount } from './setAccount'; -import { getAccount } from './getAccount'; -import { getIdEnsName } from '../getIdEnsName'; -export default { setAccount, getAccount, getIdEnsName }; diff --git a/packages/backend/src/persistence/account/setAccount.ts b/packages/backend/src/persistence/account/setAccount.ts deleted file mode 100644 index 2308bcdf9..000000000 --- a/packages/backend/src/persistence/account/setAccount.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { Redis, RedisPrefix } from '../getDatabase'; -import { Session, schema } from '@dm3-org/dm3-lib-delivery'; -import { validateSchema, stringify } from '@dm3-org/dm3-lib-shared'; -import { getIdEnsName } from '../getIdEnsName'; - -export function setAccount(redis: Redis) { - return async (ensName: string, session: Session) => { - const isValid = validateSchema(schema.Session, session); - - if (!isValid) { - throw Error('Invalid session'); - } - console.debug('set account ', ensName, session); - await redis.set( - RedisPrefix.Account + (await getIdEnsName(redis)(ensName)), - stringify(session), - ); - }; -} diff --git a/packages/backend/src/persistence/getDatabase.ts b/packages/backend/src/persistence/getDatabase.ts index 6c16b1db8..93e508696 100644 --- a/packages/backend/src/persistence/getDatabase.ts +++ b/packages/backend/src/persistence/getDatabase.ts @@ -1,51 +1,9 @@ import { Account, PrismaClient } from '@prisma/client'; -import { createClient } from 'redis'; import Storage from './storage'; import { ConversationRecord } from './storage/postgres/dto/ConversationRecord'; import { MessageRecord } from './storage/postgres/dto/MessageRecord'; import { IAccountDatabase } from '@dm3-org/dm3-lib-server-side'; -export enum RedisPrefix { - Conversation = 'conversation:', - IncomingConversations = 'incoming.conversations:', - Sync = 'sync:', - // Account used to be called Session. The prefix still resolves to "session:" for now. - Account = 'session:', - NotificationChannel = 'notificationChannel:', - GlobalNotification = 'globalNotification:', - Otp = 'otp:', - UserStorageMigrated = 'user.storage.migrated:', -} - -export async function getRedisClient() { - const url = process.env.REDIS_URL || 'redis://127.0.0.1:6380'; - const socketConf = { - socket: { - tls: true, - rejectUnauthorized: false, - }, - }; - const client = createClient( - process.env.NODE_ENV === 'production' - ? { - url, - ...socketConf, - } - : { url }, - ); - - client.on('error', (err) => { - console.error('Redis error: ' + (err as Error).message); - }); - - client.on('reconnecting', () => console.info('Redis reconnection')); - client.on('ready', () => console.info('Redis ready')); - - await client.connect(); - - return client; -} - export async function getPrismaClient() { return new PrismaClient(); } @@ -56,28 +14,28 @@ export async function getDatabase( const prisma = _prisma ?? (await getPrismaClient()); return { - //Session + //Account setAccount: Storage.setAccount(prisma), getAccount: Storage.getAccount(prisma), hasAccount: Storage.hasAccount(prisma), - //Storage AddConversation + //AddConversation addConversation: Storage.addConversation(prisma), getConversationList: Storage.getConversationList(prisma), - //Storage Add Messages + //Add Messages addMessageBatch: Storage.addMessageBatch(prisma), - //Storage Get Messages + //Get Messages getMessagesFromStorage: Storage.getMessages(prisma), - //Storage Edit Message Batch + //Edit Message Batch editMessageBatch: Storage.editMessageBatch(prisma), - //Storage Get Number Of Messages + //Get Number Of Messages getNumberOfMessages: Storage.getNumberOfMessages(prisma), - //Storage Get Number Of Converations + //Get Number Of Converations getNumberOfConverations: Storage.getNumberOfConversations(prisma), - //Storage Toggle Hide Conversation + //Toggle Hide Conversation toggleHideConversation: Storage.toggleHideConversation(prisma), - //Storage Get Halted Messages + //Get Halted Messages getHaltedMessages: Storage.getHaltedMessages(prisma), - //Storage Delete Halted Message + //Delete Halted Message clearHaltedMessage: Storage.clearHaltedMessage(prisma), }; } @@ -130,5 +88,3 @@ export interface IBackendDatabase extends IAccountDatabase { messageId: string, ) => Promise; } - -export type Redis = Awaited>; diff --git a/packages/backend/src/persistence/getIdEnsName.ts b/packages/backend/src/persistence/getIdEnsName.ts deleted file mode 100644 index 533df28ba..000000000 --- a/packages/backend/src/persistence/getIdEnsName.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { Redis, RedisPrefix } from './getDatabase'; -import { normalizeEnsName } from '@dm3-org/dm3-lib-profile'; - -export function getIdEnsName(redis: Redis) { - const resolveAlias = async (ensName: string): Promise => { - const lowerEnsName = normalizeEnsName( - (await redis.get( - RedisPrefix.Account + 'alias:' + normalizeEnsName(ensName), - )) ?? ensName, - ); - - return lowerEnsName === ensName ? ensName : resolveAlias(lowerEnsName); - }; - return resolveAlias; -} diff --git a/packages/backend/src/persistence/account/setAccount.test.ts b/packages/backend/src/persistence/storage/postgres/setAccount.test.ts similarity index 77% rename from packages/backend/src/persistence/account/setAccount.test.ts rename to packages/backend/src/persistence/storage/postgres/setAccount.test.ts index f82ab6d57..69272b0c1 100644 --- a/packages/backend/src/persistence/account/setAccount.test.ts +++ b/packages/backend/src/persistence/storage/postgres/setAccount.test.ts @@ -1,6 +1,10 @@ import { UserProfile } from '@dm3-org/dm3-lib-profile'; import { PrismaClient } from '@prisma/client'; -import { IBackendDatabase, getDatabase, getPrismaClient } from '../getDatabase'; +import { + IBackendDatabase, + getDatabase, + getPrismaClient, +} from '../../getDatabase'; const USER_NAME = '0x25A643B6e52864d0eD816F1E43c0CF49C83B8292.dm3.eth'; @@ -14,12 +18,6 @@ describe('Set Account', () => { }); it('Creates a new Account ', async () => { - const profile: UserProfile = { - publicEncryptionKey: '', - publicSigningKey: '', - deliveryServices: [], - }; - const priorSetAccount = await db.getAccount(USER_NAME); //User has no account yet diff --git a/packages/backend/src/profile/getUserProfile.ts b/packages/backend/src/profile/getUserProfile.ts deleted file mode 100644 index 337a5a666..000000000 --- a/packages/backend/src/profile/getUserProfile.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { Session } from '@dm3-org/dm3-lib-delivery'; -import { SignedUserProfile, normalizeEnsName } from '@dm3-org/dm3-lib-profile'; - -export async function getUserProfile( - getAccount: (accountAddress: string) => Promise, - ensName: string, -): Promise { - const account = normalizeEnsName(ensName); - const session = await getAccount(account); - return session?.signedUserProfile; -} diff --git a/packages/backend/src/profile/profile.test.ts b/packages/backend/src/profile/profile.test.ts index 673869ee0..e5bfac450 100644 --- a/packages/backend/src/profile/profile.test.ts +++ b/packages/backend/src/profile/profile.test.ts @@ -43,7 +43,6 @@ const createDbMock = async () => { const dbMock = { getAccount: async (ensName: string) => Promise.resolve(accountMocked), setAccount: async (id: string) => {}, - getIdEnsName: async (ensName: string) => ensName, }; return dbMock as any; @@ -113,7 +112,6 @@ describe('Profile', () => { setAccount: async (_: string, __: any) => { return (_: any, __: any, ___: any) => {}; }, - getIdEnsName: async (ensName: string) => ensName, }; const app = express(); diff --git a/packages/backend/src/profile/profile.ts b/packages/backend/src/profile/profile.ts index 6b64090c4..9a6f83711 100644 --- a/packages/backend/src/profile/profile.ts +++ b/packages/backend/src/profile/profile.ts @@ -54,8 +54,6 @@ export default ( method: 'POST', url: req.url, ensName, - disableSessionCheck: - process.env.DISABLE_SESSION_CHECK === 'true', }); // check if profile and signature are valid diff --git a/packages/backend/src/storage.ts b/packages/backend/src/storage.ts index 736df4555..2131d63d1 100644 --- a/packages/backend/src/storage.ts +++ b/packages/backend/src/storage.ts @@ -1,5 +1,5 @@ import { normalizeEnsName } from '@dm3-org/dm3-lib-profile'; -import { authorize } from '@dm3-org/dm3-lib-server-side'; +import { authorizationMiddleware } from '@dm3-org/dm3-lib-server-side'; import { sha256, validateSchema } from '@dm3-org/dm3-lib-shared'; import cors from 'cors'; import { ethers } from 'ethers'; @@ -32,7 +32,7 @@ export default ( next: NextFunction, ensName: string, ) => { - authorize( + authorizationMiddleware( req, res, next, diff --git a/packages/delivery-service/src/delivery.ts b/packages/delivery-service/src/delivery.ts index 19b07799d..15ad08db0 100644 --- a/packages/delivery-service/src/delivery.ts +++ b/packages/delivery-service/src/delivery.ts @@ -4,7 +4,7 @@ import { schema, } from '@dm3-org/dm3-lib-delivery'; import { normalizeEnsName } from '@dm3-org/dm3-lib-profile'; -import { authorize } from '@dm3-org/dm3-lib-server-side'; +import { authorizationMiddleware } from '@dm3-org/dm3-lib-server-side'; import { validateSchema } from '@dm3-org/dm3-lib-shared'; import cors from 'cors'; import { ethers } from 'ethers'; @@ -40,7 +40,7 @@ export default ( //TODO remove router.use(cors()); router.param('ensName', async (req, res, next, ensName: string) => { - authorize( + authorizationMiddleware( req, res, next, diff --git a/packages/delivery-service/src/index.ts b/packages/delivery-service/src/index.ts index 1abcc46fa..ea7ad42c0 100644 --- a/packages/delivery-service/src/index.ts +++ b/packages/delivery-service/src/index.ts @@ -1,6 +1,6 @@ -import { Session } from '@dm3-org/dm3-lib-delivery'; +import { Account } from '@dm3-org/dm3-lib-delivery'; import { - Auth, + Authenticate, errorHandler, getCachedWebProvider, getServerSecret, @@ -46,7 +46,7 @@ const getDbWithAddressResolvedGetAccount = ( ): IDatabase => { const getAccountForEnsName = ( web3Provider: ethers.providers.JsonRpcProvider, - getAccount: (ensName: string) => Promise, + getAccount: (ensName: string) => Promise, ) => { return async (ensName: string) => { const address = await web3Provider.resolveName(ensName); @@ -141,7 +141,7 @@ app.use(bodyParser.json()); }); app.use('/metrics', Metrics(db, deliveryServiceProperties)); - app.use('/auth', Auth(db, serverSecret, web3Provider)); + app.use('/auth', Authenticate(db, serverSecret, web3Provider)); app.use('/profile', Profile(db, web3Provider, serverSecret)); app.use('/delivery', Delivery(web3Provider, db, serverSecret)); app.use( diff --git a/packages/delivery-service/src/message/MessageProcessor.test.ts b/packages/delivery-service/src/message/MessageProcessor.test.ts index 466022d0c..09bd7eab2 100644 --- a/packages/delivery-service/src/message/MessageProcessor.test.ts +++ b/packages/delivery-service/src/message/MessageProcessor.test.ts @@ -12,7 +12,7 @@ import { MessageProcessor } from './MessageProcessor'; import { checkSignature, decryptAsymmetric } from '@dm3-org/dm3-lib-crypto'; import { DeliveryServiceProperties, - Session, + Account, spamFilter, } from '@dm3-org/dm3-lib-delivery'; import { UserProfile, normalizeEnsName } from '@dm3-org/dm3-lib-profile'; @@ -66,7 +66,7 @@ describe('MessageProcessor', () => { ensName: string, socketId?: string, ): Promise< - (Session & { spamFilterRules: spamFilter.SpamFilterRules }) | null + (Account & { spamFilterRules: spamFilter.SpamFilterRules }) | null > => { const emptyProfile: UserProfile = { publicSigningKey: '', @@ -76,11 +76,11 @@ describe('MessageProcessor', () => { const isSender = getAddress(ensName) === sender.address; const isReceiver = getAddress(ensName) === receiver.address; - const session = ( + const account = ( account: string, token: string, profile: UserProfile, - ): Session => ({ + ): Account => ({ account, signedUserProfile: { profile, @@ -97,14 +97,14 @@ describe('MessageProcessor', () => { if (isSender) { return { - ...session(sender.address, '123', emptyProfile), + ...account(sender.address, '123', emptyProfile), spamFilterRules: {}, }; } if (isReceiver) { return { - ...session(getAddress(receiver.address), 'abc', { + ...account(getAddress(receiver.address), 'abc', { ...emptyProfile, publicEncryptionKey: receiver.profileKeys.encryptionKeyPair.publicKey, @@ -256,7 +256,7 @@ describe('MessageProcessor', () => { await expect(() => messageProcessor.processEnvelop(incomingEnvelop), - ).rejects.toEqual(Error('unknown session')); + ).rejects.toEqual(Error('unknown account')); }); // //TODO remove skip once spam-filter is implemented // //TODO remove skip once spam-filter is implemented @@ -265,7 +265,7 @@ describe('MessageProcessor', () => { ({ ...(await getAccount(address)), spamFilterRules: { minNonce: 2 }, - } as Session & { spamFilterRules: spamFilter.SpamFilterRules }); + } as Account & { spamFilterRules: spamFilter.SpamFilterRules }); const db = { createMessage: async () => {}, @@ -322,7 +322,7 @@ describe('MessageProcessor', () => { ({ ...(await getAccount(address)), spamFilterRules: { minBalance: '0xa' }, - } as Session & { spamFilterRules: spamFilter.SpamFilterRules }); + } as Account & { spamFilterRules: spamFilter.SpamFilterRules }); const db = { createMessage: async () => {}, @@ -384,7 +384,7 @@ describe('MessageProcessor', () => { amount: '0xa', }, }, - } as Session & { spamFilterRules: spamFilter.SpamFilterRules }); + } as Account & { spamFilterRules: spamFilter.SpamFilterRules }); const db = { createMessage: async () => {}, diff --git a/packages/delivery-service/src/message/MessageProcessor.ts b/packages/delivery-service/src/message/MessageProcessor.ts index 504462bc2..7fb59de58 100644 --- a/packages/delivery-service/src/message/MessageProcessor.ts +++ b/packages/delivery-service/src/message/MessageProcessor.ts @@ -50,7 +50,7 @@ export class MessageProcessor { * In order to be considered valid a incoming message has to meet the following criterias * 1. The message size must be lower than the sizeLimit specified by the deliveryService {@see messageIsToLarge} * 2. The DeliveryServiceToken used by the sender has to be valid - * 3. The receiver has to have a session at the deliveryService + * 3. The receiver has to have a account at the deliveryService * 4. The message must pass every {@see SpamFilterRule} the receiver declared */ public async processEnvelop(envelop: EncryptionEnvelop): Promise { @@ -107,18 +107,18 @@ export class MessageProcessor { ); console.debug(conversationId, deliveryInformation); - //Retrieves the session of the receiver - const receiverSession = await this.db.getAccount(receiverAddress); - if (!receiverSession) { + //Retrieves the account of the receiver + const receiverAccount = await this.db.getAccount(receiverAddress); + if (!receiverAccount) { console.debug('unknown user ', deliveryInformation.to); - throw Error('unknown session'); + throw Error('unknown account'); } //Checks if the message is spam if ( await spamFilter.isSpam( this.provider, - receiverSession, + receiverAccount, deliveryInformation, ) ) { @@ -129,7 +129,7 @@ export class MessageProcessor { } const receiverEncryptionKey = - receiverSession.signedUserProfile.profile.publicEncryptionKey; + receiverAccount.signedUserProfile.profile.publicEncryptionKey; const envelopWithPostmark: EncryptionEnvelop = { ...envelop, @@ -158,11 +158,11 @@ export class MessageProcessor { //Client is already connect to the delivery service and the message can be dispatched //TODO MOVE send method to the WebSocketManager this.onSubmitMessage( - receiverSession.socketId!, + receiverAccount.socketId!, envelopWithPostmark, ); - console.debug('WS send to socketId ', receiverSession.socketId); + console.debug('WS send to socketId ', receiverAccount.socketId); //If not we're notifing the user that there is a new message waiting for them } else { try { diff --git a/packages/delivery-service/src/messaging.test.ts b/packages/delivery-service/src/messaging.test.ts index cb458edba..1856c4c2e 100644 --- a/packages/delivery-service/src/messaging.test.ts +++ b/packages/delivery-service/src/messaging.test.ts @@ -1,4 +1,4 @@ -import { Session } from '@dm3-org/dm3-lib-delivery'; +import { Account } from '@dm3-org/dm3-lib-delivery'; import { EncryptionEnvelop } from '@dm3-org/dm3-lib-messaging'; import { UserProfile } from '@dm3-org/dm3-lib-profile'; import { IWebSocketManager, ethersHelper } from '@dm3-org/dm3-lib-shared'; @@ -50,7 +50,7 @@ describe('Messaging', () => { const isReceiver = ethersHelper.formatAddress(address) === receiver.address; - const session = ( + const account = ( account: string, token: string, profile: UserProfile, @@ -64,11 +64,11 @@ describe('Messaging', () => { }); if (isSender) { - return session(sender.address, '123', emptyProfile); + return account(sender.address, '123', emptyProfile); } if (isReceiver) { - return session(receiver.address, 'abc', { + return account(receiver.address, 'abc', { ...emptyProfile, publicEncryptionKey: receiver.profileKeys.encryptionKeyPair.publicKey, @@ -198,14 +198,14 @@ describe('Messaging', () => { done(); }); - const session = async (addr: string) => { + const account = async (addr: string) => { return { ...(await getAccount(addr)), spamFilterRules: { minNonce: 2 }, - } as Session; + } as Account; }; const db = { - getAccount: session, + getAccount: account, createMessage: () => {}, getIdEnsName: async (ensName: string) => ensName, getUsersNotificationChannels: () => Promise.resolve([]), diff --git a/packages/delivery-service/src/messaging.ts b/packages/delivery-service/src/messaging.ts index 5b523cca7..82f68ab2e 100644 --- a/packages/delivery-service/src/messaging.ts +++ b/packages/delivery-service/src/messaging.ts @@ -32,7 +32,7 @@ export function onConnection( socket.on('connection_error', (err) => { console.log(err.req); // the request object console.log(err.code); // the error code, for example 1 - console.log(err.message); // the error message, for example "Session ID unknown" + console.log(err.message); // the error message, for example "Account ID unknown" console.log(err.context); // some additional error context }); diff --git a/packages/delivery-service/src/notifications.ts b/packages/delivery-service/src/notifications.ts index 9a993cf01..6890d988d 100644 --- a/packages/delivery-service/src/notifications.ts +++ b/packages/delivery-service/src/notifications.ts @@ -2,7 +2,7 @@ import cors from 'cors'; import { normalizeEnsName } from '@dm3-org/dm3-lib-profile'; import express from 'express'; -import { authorize } from '@dm3-org/dm3-lib-server-side'; +import { authorizationMiddleware } from '@dm3-org/dm3-lib-server-side'; import { ethers } from 'ethers'; import { validateNewNotificationChannelData, @@ -35,7 +35,7 @@ export default ( // Adding a route parameter middleware named 'ensName' router.param('ensName', (req, res, next, ensName: string) => { - authorize( + authorizationMiddleware( req, res, next, diff --git a/packages/delivery-service/src/persistence/account/getAccount.ts b/packages/delivery-service/src/persistence/account/getAccount.ts index 35d76769c..623eda6ab 100644 --- a/packages/delivery-service/src/persistence/account/getAccount.ts +++ b/packages/delivery-service/src/persistence/account/getAccount.ts @@ -1,18 +1,18 @@ -import { Session } from '@dm3-org/dm3-lib-delivery'; +import { Account } from '@dm3-org/dm3-lib-delivery'; import { ethers } from 'ethers'; import { Redis, RedisPrefix } from '../getDatabase'; export function getAccount(redis: Redis) { return async (address: string) => { - const session = await redis.get( + const account = await redis.get( RedisPrefix.Account + ethers.utils.getAddress(address), ); - if (!session) { + if (!account) { console.debug('there is no account for this address: ', address); return null; } - return JSON.parse(session) as Session; + return JSON.parse(account) as Account; }; } diff --git a/packages/delivery-service/src/persistence/account/setAccount.test.ts b/packages/delivery-service/src/persistence/account/setAccount.test.ts index b5099c65b..974448551 100644 --- a/packages/delivery-service/src/persistence/account/setAccount.test.ts +++ b/packages/delivery-service/src/persistence/account/setAccount.test.ts @@ -1,10 +1,10 @@ import { Redis, IDatabase, getRedisClient, getDatabase } from '../getDatabase'; import { UserProfile } from '@dm3-org/dm3-lib-profile'; -import { Session } from '@dm3-org/dm3-lib-delivery'; +import { Account } from '@dm3-org/dm3-lib-delivery'; const USER_ADDRESS = '0x25A643B6e52864d0eD816F1E43c0CF49C83B8292'; -describe('Set Session', () => { +describe('Set Account', () => { let redisClient: Redis; let db: IDatabase; @@ -19,13 +19,13 @@ describe('Set Session', () => { await redisClient.disconnect(); }); - it('Creates a new Session ', async () => { + it('Creates a new Account ', async () => { const profile: UserProfile = { publicEncryptionKey: '', publicSigningKey: '', deliveryServices: [], }; - const session: Session = { + const account: Account = { account: USER_ADDRESS, signedUserProfile: { profile, signature: 'foo' }, token: '', @@ -35,25 +35,25 @@ describe('Set Session', () => { }, }; - const priorSetSession = await db.getAccount(USER_ADDRESS); - //User has no session yet - expect(priorSetSession).toBe(null); - await db.setAccount(USER_ADDRESS, session); + const priorSetAccount = await db.getAccount(USER_ADDRESS); + //User has no account yet + expect(priorSetAccount).toBe(null); + await db.setAccount(USER_ADDRESS, account); - const afterSetSession = await db.getAccount(USER_ADDRESS); - //User has no session yet - expect(afterSetSession?.signedUserProfile).toEqual({ + const afterSetAccount = await db.getAccount(USER_ADDRESS); + //User has no account yet + expect(afterSetAccount?.signedUserProfile).toEqual({ profile, signature: 'foo', }); }); - it('Creates a new Session and uses normalized address', async () => { + it('Creates a new Account and uses normalized address', async () => { const profile: UserProfile = { publicEncryptionKey: '', publicSigningKey: '', deliveryServices: [], }; - const session: Session = { + const account: Account = { // Address is not normalized account: USER_ADDRESS.toUpperCase(), signedUserProfile: { profile, signature: 'foo' }, @@ -64,26 +64,26 @@ describe('Set Session', () => { }, }; - const priorSetSession = await db.getAccount(USER_ADDRESS); - //User has no session yet - expect(priorSetSession).toBe(null); - await db.setAccount(USER_ADDRESS, session); + const priorSetAccount = await db.getAccount(USER_ADDRESS); + //User has no account yet + expect(priorSetAccount).toBe(null); + await db.setAccount(USER_ADDRESS, account); - const afterSetSession = await db.getAccount(USER_ADDRESS); - //User has no session yet - expect(afterSetSession?.signedUserProfile).toEqual({ + const afterSetAccount = await db.getAccount(USER_ADDRESS); + //User has no account yet + expect(afterSetAccount?.signedUserProfile).toEqual({ profile, signature: 'foo', }); }); - it('Rejects session with an invalid address', async () => { + it('Rejects account with an invalid address', async () => { const profile: UserProfile = { publicEncryptionKey: '', publicSigningKey: '', deliveryServices: [], }; - const session: Session = { + const account: Account = { account: USER_ADDRESS, signedUserProfile: { profile, @@ -96,20 +96,20 @@ describe('Set Session', () => { }, }; try { - await db.setAccount('foo', session); + await db.setAccount('foo', account); fail(); } catch (e) { expect(e).toStrictEqual(Error('Invalid address')); } }); - it('Rejects session with an invalid schema', async () => { - const invalidSession = {} as Session; + it('Rejects account with an invalid schema', async () => { + const invalidAccount = {} as Account; try { - await db.setAccount('foo', invalidSession); + await db.setAccount('foo', invalidAccount); fail(); } catch (e) { - expect(e).toStrictEqual(Error('Invalid session')); + expect(e).toStrictEqual(Error('Invalid account')); } }); }); diff --git a/packages/delivery-service/src/persistence/account/setAccount.ts b/packages/delivery-service/src/persistence/account/setAccount.ts index b380c6987..3aad4f3af 100644 --- a/packages/delivery-service/src/persistence/account/setAccount.ts +++ b/packages/delivery-service/src/persistence/account/setAccount.ts @@ -1,16 +1,16 @@ -import { Session, schema } from '@dm3-org/dm3-lib-delivery'; +import { Account, schema } from '@dm3-org/dm3-lib-delivery'; import { stringify, validateSchema } from '@dm3-org/dm3-lib-shared'; import { ethers } from 'ethers'; import { Redis, RedisPrefix } from '../getDatabase'; export function setAccount(redis: Redis) { - return async (address: string, session: Session) => { - const isValid = validateSchema(schema.Session, session); + return async (address: string, Account: Account) => { + const isValid = validateSchema(schema.Account, Account); const isAddess = ethers.utils.isAddress(address); if (!isValid) { - console.debug('Invalid session: ', session); - throw Error('Invalid session'); + console.debug('Invalid account: ', Account); + throw Error('Invalid account'); } if (!isAddess) { @@ -18,11 +18,11 @@ export function setAccount(redis: Redis) { throw Error('Invalid address'); } - console.debug('set account ', address, session); + console.debug('set account ', address, Account); await redis.set( RedisPrefix.Account + ethers.utils.getAddress(address), - stringify(session), + stringify(Account), ); }; } diff --git a/packages/delivery-service/src/persistence/getDatabase.ts b/packages/delivery-service/src/persistence/getDatabase.ts index 24c23a738..2ad44acbd 100644 --- a/packages/delivery-service/src/persistence/getDatabase.ts +++ b/packages/delivery-service/src/persistence/getDatabase.ts @@ -2,7 +2,7 @@ import { DeliveryServiceProperties, IGlobalNotification, IOtp, - Session, + type Account as AccountType, } from '@dm3-org/dm3-lib-delivery'; import { EncryptionEnvelop } from '@dm3-org/dm3-lib-messaging'; import { IAccountDatabase } from '@dm3-org/dm3-lib-server-side'; @@ -104,8 +104,8 @@ export async function getDatabase(_redis?: Redis): Promise { } export interface IDatabase extends IAccountDatabase { - setAccount: (address: string, session: Session) => Promise; - getAccount: (address: string) => Promise; + setAccount: (address: string, account: AccountType) => Promise; + getAccount: (address: string) => Promise; //TODO use address getIncomingMessages: ( address: string, diff --git a/packages/delivery-service/src/persistence/notification/addUsersNotificationChannel.test.ts b/packages/delivery-service/src/persistence/notification/addUsersNotificationChannel.test.ts index 0160e3904..2c1cfdde6 100644 --- a/packages/delivery-service/src/persistence/notification/addUsersNotificationChannel.test.ts +++ b/packages/delivery-service/src/persistence/notification/addUsersNotificationChannel.test.ts @@ -32,14 +32,14 @@ describe('Set Users NotificationChannel', () => { const priorSetUsersNotificationChannel = await db.getUsersNotificationChannels(USER_ADDRESS); - //User has no session yet + //User has no account yet expect(priorSetUsersNotificationChannel).toEqual([]); await db.addUsersNotificationChannel(USER_ADDRESS, notificationChannel); - const afterSetSession = await db.getUsersNotificationChannels( + const afterSetAccount = await db.getUsersNotificationChannels( USER_ADDRESS, ); - expect(afterSetSession).toEqual([notificationChannel]); + expect(afterSetAccount).toEqual([notificationChannel]); }); it('Rejects Notification Channel with an invalid schema', async () => { @@ -116,14 +116,14 @@ describe('Set Users NotificationChannel', () => { const priorSetUsersNotificationChannel = await db.getUsersNotificationChannels(USER_ADDRESS); - //User has no session yet + //User has no account yet expect(priorSetUsersNotificationChannel).toEqual([]); await db.addUsersNotificationChannel(USER_ADDRESS, notificationChannel); - const afterSetSession = await db.getUsersNotificationChannels( + const afterSetAccount = await db.getUsersNotificationChannels( USER_ADDRESS, ); - expect(afterSetSession).toEqual([notificationChannel]); + expect(afterSetAccount).toEqual([notificationChannel]); }); it('Rejects Push Notification Channel with an invalid schema', async () => { diff --git a/packages/delivery-service/src/profile/profile.test.ts b/packages/delivery-service/src/profile/profile.test.ts index 1b679d6ca..eb15d709c 100644 --- a/packages/delivery-service/src/profile/profile.test.ts +++ b/packages/delivery-service/src/profile/profile.test.ts @@ -1,4 +1,4 @@ -import { Session } from '@dm3-org/dm3-lib-delivery'; +import { Account } from '@dm3-org/dm3-lib-delivery'; import { generateAuthJWT } from '@dm3-org/dm3-lib-server-side'; import { UserProfile, @@ -27,16 +27,16 @@ const setUpApp = async ( }; const createDbMock = async () => { - const sessionMocked = { + const accountMocked = { challenge: '123', token: 'deprecated token that is not used anymore', signedUserProfile: {}, - } as Session; + } as Account; const dbMock = { getAccount: async (ensName: string) => - Promise.resolve(sessionMocked), // returns some valid session - setAccount: async (_: string, __: Session) => {}, + Promise.resolve(accountMocked), // returns some valid account + setAccount: async (_: string, __: Account) => {}, getIdEnsName: async (ensName: string) => ensName, }; diff --git a/packages/delivery-service/src/rpc/methods/handleResolveProfileExtension.ts b/packages/delivery-service/src/rpc/methods/handleResolveProfileExtension.ts index cf9be3ab8..25d59f8ef 100644 --- a/packages/delivery-service/src/rpc/methods/handleResolveProfileExtension.ts +++ b/packages/delivery-service/src/rpc/methods/handleResolveProfileExtension.ts @@ -10,10 +10,10 @@ export function handleResolveProfileExtension(axios: Axios, db: IDatabase) { } = req.body; const idEnsName = await db.getIdEnsName(ensName); - //Get the Session to retrieve profileExtension - const session = await db.getAccount(idEnsName); + //Get the Account to retrieve profileExtension + const account = await db.getAccount(idEnsName); - if (!session) { + if (!account) { //The requested ens-name is not known to the delivery service const error = 'unknown user'; console.warn({ @@ -23,7 +23,7 @@ export function handleResolveProfileExtension(axios: Axios, db: IDatabase) { return res.status(400).send({ error }); } - const { profileExtension } = session; + const { profileExtension } = account; return res.status(200).send({ jsonrpc: '2.0', diff --git a/packages/delivery-service/src/rpc/rpc-proxy.test.ts b/packages/delivery-service/src/rpc/rpc-proxy.test.ts index ac7e09ba5..4bfd5a897 100644 --- a/packages/delivery-service/src/rpc/rpc-proxy.test.ts +++ b/packages/delivery-service/src/rpc/rpc-proxy.test.ts @@ -61,7 +61,7 @@ describe('rpc-Proxy', () => { const isReceiver = ethersHelper.formatAddress(address) === receiver.address; - const session = ( + const account = ( account: string, token: string, profile: UserProfile, @@ -75,11 +75,11 @@ describe('rpc-Proxy', () => { }); if (isSender) { - return session(sender.address, '123', emptyProfile); + return account(sender.address, '123', emptyProfile); } if (isReceiver) { - return session(RECEIVER_NAME, 'abc', { + return account(RECEIVER_NAME, 'abc', { ...emptyProfile, publicEncryptionKey: receiver.profileKeys.encryptionKeyPair.publicKey, diff --git a/packages/delivery-service/src/socketAuth.ts b/packages/delivery-service/src/socketAuth.ts index 51d2cd8c5..e478e4ab0 100644 --- a/packages/delivery-service/src/socketAuth.ts +++ b/packages/delivery-service/src/socketAuth.ts @@ -33,15 +33,15 @@ export function socketAuth( console.log('check token has failed for WS '); return next(new Error('check token has failed for WS')); } - const session = await db.getAccount(ensName); - if (!session) { - throw Error('Could not get session'); + const account = await db.getAccount(ensName); + if (!account) { + throw Error('Could not get account'); } - //we use session.account here as a key for setAccount here. - //We can do this because the address is used as account when the Session has been created. + //we use account.account here as a key for setAccount here. + //We can do this because the address is used as account when the Account has been created. //That saves a address lookup via ENS - await db.setAccount(session.account, { - ...session, + await db.setAccount(account.account, { + ...account, socketId: socket.id, }); } catch (e) { diff --git a/packages/delivery-service/src/ws/WebSocketManager.test.ts b/packages/delivery-service/src/ws/WebSocketManager.test.ts index bf65316f8..a075cea41 100644 --- a/packages/delivery-service/src/ws/WebSocketManager.test.ts +++ b/packages/delivery-service/src/ws/WebSocketManager.test.ts @@ -94,7 +94,7 @@ describe('WebSocketManager', () => { expect(socket0IsConnected).toBe(false); }); - it('reject socket without session', async () => { + it('reject socket without account', async () => { const mockedWeb3Provider = { resolveName: (_: string) => Promise.resolve('0x'), } as any; @@ -173,7 +173,7 @@ describe('WebSocketManager', () => { }); }); describe('isConnected', () => { - it('returns true if name has one session', async () => { + it('returns true if name has one account', async () => { const mockedWeb3Provider = { resolveName: (_: string) => Promise.resolve(receiver.address), } as any; @@ -222,7 +222,7 @@ describe('WebSocketManager', () => { const isConnected = await wsManager.isConnected(receiver.address); expect(isConnected).toBe(true); }); - it('returns true if name has at least one session', async () => { + it('returns true if name has at least one account', async () => { const mockedWeb3Provider = { resolveName: (_: string) => Promise.resolve(receiver.address), } as any; @@ -345,7 +345,7 @@ describe('WebSocketManager', () => { const isConnected = await wsManager.isConnected(rando.address); expect(isConnected).toBe(false); }); - it('keeps track of different independent sessions', async () => { + it('keeps track of different independent accounts', async () => { const mockedWeb3Provider = { resolveName: (_: string) => { if (_ === receiver.account.ensName) { diff --git a/packages/delivery-service/src/ws/WebSocketManager.ts b/packages/delivery-service/src/ws/WebSocketManager.ts index 3b86d6638..b3e1bbc36 100644 --- a/packages/delivery-service/src/ws/WebSocketManager.ts +++ b/packages/delivery-service/src/ws/WebSocketManager.ts @@ -54,38 +54,38 @@ export class WebSocketManager implements IWebSocketManager { */ private async addConnection(connection: Socket) { try { - const { account, token } = connection.handshake.auth; + const { account: accountInfo, token } = connection.handshake.auth; - const ensName = normalizeEnsName(account.ensName); + const ensName = normalizeEnsName(accountInfo.ensName); //Use the already existing function checkToken to check whether the token matches the provided ensName - const hasSession = await checkToken( + const hasAccount = await checkToken( this.web3Provider, this.db.hasAccount, ensName, token, this.serverSecret, ); - //retrieve the session from the db - const session = await this.db.getAccount(ensName); - //If the ensName has not a valid session we disconnect the socket - if (!hasSession || !session) { + //retrieve the account from the db + const account = await this.db.getAccount(ensName); + //If the ensName has not a valid account we disconnect the socket + if (!hasAccount || !account) { console.log('connection refused for ', ensName); connection.emit(UNAUTHORIZED); connection.disconnect(); return; } //Get the old connections and add the new one - const oldConnections = this.connections.get(session.account) || []; - this.connections.set(session.account, [ + const oldConnections = this.connections.get(account.account) || []; + this.connections.set(account.account, [ ...oldConnections, connection, ]); //Send the authorized event connection.emit(AUTHORIZED); - console.log('connection established for ', session.account); + console.log('connection established for ', account.account); //When the socket disconnects we want them no longer in our connections List connection.on('disconnect', () => { - console.log('connection closed for ', session.account); + console.log('connection closed for ', account.account); this.removeConnection(connection); }); } catch (e) { diff --git a/packages/lib/delivery/schemas.sh b/packages/lib/delivery/schemas.sh index 5a7aa09d4..6e76b7c52 100644 --- a/packages/lib/delivery/schemas.sh +++ b/packages/lib/delivery/schemas.sh @@ -1,4 +1,4 @@ yarn ts-json-schema-generator -f tsconfig.json --path Delivery.ts --type DeliveryServiceProperties -o ./src/schema/DeliveryServiceProperties.schema.json --no-type-check \ && yarn ts-json-schema-generator -f tsconfig.json --path Messages.ts --type Acknowledgement -o ./src/schema/Acknowledgement.schema.json --no-type-check \ -&& yarn ts-json-schema-generator -f tsconfig.json --path Session.ts --type Session -o ./src/schema/Session.schema.json --no-type-check \ +&& yarn ts-json-schema-generator -f tsconfig.json --path Account.ts --type Account -o ./src/schema/Account.schema.json --no-type-check \ && yarn ts-json-schema-generator -f tsconfig.json --path notifications/types.ts --type NotificationChannel -o ./src/schema/NotificationChannel.schema.json --no-type-check \ diff --git a/packages/lib/delivery/src/Session.test.ts b/packages/lib/delivery/src/Account.test.ts similarity index 99% rename from packages/lib/delivery/src/Session.test.ts rename to packages/lib/delivery/src/Account.test.ts index 562cfe4db..ec5edadb3 100644 --- a/packages/lib/delivery/src/Session.test.ts +++ b/packages/lib/delivery/src/Account.test.ts @@ -5,7 +5,7 @@ const serverSecret = 'veryImportantSecretToGenerateAndValidateJSONWebTokens'; // create valid jwt const token = generateAuthJWT('alice.eth', serverSecret); -describe('Session', () => { +describe('Account', () => { describe('checkToken with state', () => { it('Should return true if the jwt is valid', async () => { const hasAccount = (_: string) => Promise.resolve(true); @@ -24,7 +24,7 @@ describe('Session', () => { expect(isValid).toBe(true); }); - it('Should return false if no session exists for the account ', async () => { + it('Should return false if no account exists for the account ', async () => { const hasAccount = (_: string) => Promise.resolve(false); const isValid = await checkToken( @@ -59,7 +59,7 @@ describe('Session', () => { expect(isValid).toBe(false); }); - it('Should return false if a session exists but the token is expired ', async () => { + it('Should return false if a account exists but the token is expired ', async () => { const hasAccount = (_: string) => Promise.resolve(true); const oneMinuteAgo = new Date().getTime() / 1000 - 60; diff --git a/packages/lib/delivery/src/Session.ts b/packages/lib/delivery/src/Account.ts similarity index 94% rename from packages/lib/delivery/src/Session.ts rename to packages/lib/delivery/src/Account.ts index c0b5fb63e..b5e42a2bb 100644 --- a/packages/lib/delivery/src/Session.ts +++ b/packages/lib/delivery/src/Account.ts @@ -4,7 +4,7 @@ import { SpamFilterRules } from './spam-filter'; //1Year const TTL = 31536000000; -export interface Session { +export interface Account { account: string; signedUserProfile: SignedUserProfile; token: string; diff --git a/packages/lib/delivery/src/UserProfile.test.ts b/packages/lib/delivery/src/UserProfile.test.ts index 33617d077..6ea821683 100644 --- a/packages/lib/delivery/src/UserProfile.test.ts +++ b/packages/lib/delivery/src/UserProfile.test.ts @@ -4,7 +4,7 @@ import { UserProfile, } from '@dm3-org/dm3-lib-profile'; import { stringify } from '@dm3-org/dm3-lib-shared'; -import { Session } from './Session'; +import { Account } from './Account'; import { getUserProfile, submitUserProfile } from './UserProfile'; const SENDER_NAME = 'alice.eth'; @@ -62,11 +62,11 @@ describe('UserProfile', () => { it('override a userProfile that already exists but with other nonce', async () => { const setAccount = () => Promise.resolve(); const getAccount = async (address: string) => { - const session = async ( + const account = async ( account: string, token: string, profile: UserProfile, - ): Promise => { + ): Promise => { const signedUserProfile = await signProfile(profile); return { account, @@ -80,7 +80,7 @@ describe('UserProfile', () => { }; }; - return session(SENDER_ADDRESS, '123', emptyProfile); + return account(SENDER_ADDRESS, '123', emptyProfile); }; const singedUserProfile = await signProfile(emptyProfile); @@ -122,16 +122,16 @@ describe('UserProfile', () => { }); }); describe('GetUserProfile', () => { - it('Returns undefined if address has no session', async () => { + it('Returns undefined if address has no account', async () => { const getAccount = () => Promise.resolve(null); const profile = await getUserProfile(getAccount, RANDO_NAME); expect(profile).toBeUndefined(); }); - it('Returns the signedUserProfile if a session was created', async () => { + it('Returns the signedUserProfile if a account was created', async () => { const getAccount = () => - Promise.resolve({ signedUserProfile: {} } as Session); + Promise.resolve({ signedUserProfile: {} } as Account); const profile = await getUserProfile(getAccount, RANDO_NAME); diff --git a/packages/lib/delivery/src/UserProfile.ts b/packages/lib/delivery/src/UserProfile.ts index 6b4944c12..9bf7ebef6 100644 --- a/packages/lib/delivery/src/UserProfile.ts +++ b/packages/lib/delivery/src/UserProfile.ts @@ -7,11 +7,11 @@ import { import { logDebug } from '@dm3-org/dm3-lib-shared'; import { ethers } from 'ethers'; import { generateAuthJWT } from '@dm3-org/dm3-lib-server-side'; -import { Session } from './Session'; +import { Account } from './Account'; export async function submitUserProfile( - getAccount: (accountAddress: string) => Promise, - setAccount: (accountAddress: string, session: Session) => Promise, + getAccount: (accountAddress: string) => Promise, + setAccount: (accountAddress: string, account: Account) => Promise, address: string, signedUserProfile: SignedUserProfile, serverSecret: string, @@ -27,25 +27,25 @@ export async function submitUserProfile( logDebug('submitUserProfile - Signature invalid'); throw Error('Signature invalid.'); } - const session: Session = { + const account: Account = { account: _address, signedUserProfile, token: generateAuthJWT(_address, serverSecret), createdAt: new Date().getTime(), profileExtension: getDefaultProfileExtension(), }; - logDebug({ text: 'submitUserProfile', session }); - await setAccount(_address, session); + logDebug({ text: 'submitUserProfile', account }); + await setAccount(_address, account); - return session.token; + return account.token; } // todo: remove this function (profiles should be loaded from chain and possibly cached) export async function getUserProfile( - getAccount: (accountAddress: string) => Promise, + getAccount: (accountAddress: string) => Promise, ensName: string, ): Promise { - const account = normalizeEnsName(ensName); - const session = await getAccount(account); - return session?.signedUserProfile; + const accountName = normalizeEnsName(ensName); + const account = await getAccount(accountName); + return account?.signedUserProfile; } diff --git a/packages/lib/delivery/src/index.ts b/packages/lib/delivery/src/index.ts index 9826ba909..4f1168996 100644 --- a/packages/lib/delivery/src/index.ts +++ b/packages/lib/delivery/src/index.ts @@ -9,7 +9,7 @@ export { getConversationId } from './Messages'; export type {} from './PublicMessages'; export * as schema from './schema'; export * as spamFilter from './spam-filter/'; -export type { Session } from './Session'; +export type { Account } from './Account'; export type { DeliveryServiceProperties } from './Delivery'; export * from './notifications'; export { diff --git a/packages/lib/delivery/src/schema/index.ts b/packages/lib/delivery/src/schema/index.ts index 2da911ccc..d54f7c5d8 100644 --- a/packages/lib/delivery/src/schema/index.ts +++ b/packages/lib/delivery/src/schema/index.ts @@ -1,10 +1,10 @@ import AcknowledgementSchema from './Acknowledgement.schema.json'; import DeliveryServicePropertiesSchema from './DeliveryServiceProperties.schema.json'; -import SessionSchema from './Session.schema.json'; +import AccountSchema from './Account.schema.json'; import NotificationChannelSchema from './NotificationChannel.schema.json'; export const Acknowledgement = AcknowledgementSchema.definitions.Acknowledgement; export const DeliveryServiceProperties = DeliveryServicePropertiesSchema; -export const Session = SessionSchema; +export const Account = AccountSchema; export const NotificationChannel = NotificationChannelSchema; diff --git a/packages/lib/delivery/src/spam-filter/index.ts b/packages/lib/delivery/src/spam-filter/index.ts index 32f890fe1..d7999808f 100644 --- a/packages/lib/delivery/src/spam-filter/index.ts +++ b/packages/lib/delivery/src/spam-filter/index.ts @@ -5,7 +5,7 @@ import { nonceFilterFactory } from './filter/nonceFilter/NonceFilter'; import { SpamFilter, SpamFilterFactory } from './filter/SpamFilter'; import { tokenBalanceFilterFactory } from './filter/tokenBalanceFilter/TokenBalanceFilter'; import { SpamFilterRules } from './SpamFilterRules'; -import { Session } from '../Session'; +import { Account } from '../Account'; export type { SpamFilterRules }; @@ -35,11 +35,11 @@ function compileSpamFilter(filter: SpamFilter[]) { }; } /** - * Maps the {@see SpamFilterRules} a user has specified in they session to an array of filters + * Maps the {@see SpamFilterRules} a user has specified in they account to an array of filters */ function getUsersSpamFilters( provider: ethers.providers.BaseProvider, - { spamFilterRules }: Session, + { spamFilterRules }: Account, ) { //User has not defined any rules if (!spamFilterRules) { @@ -55,10 +55,10 @@ function getUsersSpamFilters( */ export async function isSpam( provider: ethers.providers.BaseProvider, - session: Session, + account: Account, deliveryInformation: DeliveryInformation, ) { - const usersSpamFilters = getUsersSpamFilters(provider, session); + const usersSpamFilters = getUsersSpamFilters(provider, account); const filter = compileSpamFilter(usersSpamFilters); //The predicate of a filter returns true if the message is valid. diff --git a/packages/lib/delivery/src/spam-filter/spamfilter.test.ts b/packages/lib/delivery/src/spam-filter/spamfilter.test.ts index bc1cb7afe..f0c8bfad6 100644 --- a/packages/lib/delivery/src/spam-filter/spamfilter.test.ts +++ b/packages/lib/delivery/src/spam-filter/spamfilter.test.ts @@ -4,7 +4,7 @@ import { isSpam } from '.'; import { testData } from '../../../../../test-data/encrypted-envelops.test'; import { SpamFilterRules } from './SpamFilterRules'; -import { Session } from '@dm3-org/dm3-lib-delivery'; +import { Account } from '@dm3-org/dm3-lib-delivery'; const keysA = { encryptionKeyPair: { @@ -48,13 +48,13 @@ const connection = { describe('SpamFilter', () => { describe('isSpam ', () => { it('Should filter correctly with one filter criteria', async () => { - const session = { + const account = { spamFilterRules: { minBalance: '1' }, - } as Session & { spamFilterRules: SpamFilterRules }; + } as Account & { spamFilterRules: SpamFilterRules }; const envelopAIsSpam = await isSpam( connection.provider, - session, + account, JSON.parse( await decryptAsymmetric( keysA.encryptionKeyPair, @@ -66,7 +66,7 @@ describe('SpamFilter', () => { ); const envelopBIsSpam = await isSpam( connection.provider, - session, + account, JSON.parse( await decryptAsymmetric( keysA.encryptionKeyPair, @@ -81,13 +81,13 @@ describe('SpamFilter', () => { await expect(envelopBIsSpam).toBe(false); }); it('Should use filter correctly with two filter criteria', async () => { - const session = { + const account = { spamFilterRules: { minBalance: '1', minNonce: 2 }, - } as Session & { spamFilterRules: SpamFilterRules }; + } as Account & { spamFilterRules: SpamFilterRules }; const envelopAIsSpam = await isSpam( connection.provider, - session, + account, JSON.parse( await decryptAsymmetric( keysA.encryptionKeyPair, @@ -99,7 +99,7 @@ describe('SpamFilter', () => { ); const envelopBIsSpam = await isSpam( connection.provider, - session, + account, JSON.parse( await decryptAsymmetric( keysA.encryptionKeyPair, @@ -114,13 +114,13 @@ describe('SpamFilter', () => { await expect(envelopBIsSpam).toBe(true); }); it('Should not consider a message as spam if no SpamFilterRules are provided', async () => { - const session = {} as Session & { + const account = {} as Account & { spamFilterRules: SpamFilterRules; }; const envelopAIsSpam = await isSpam( connection.provider, - session, + account, JSON.parse( await decryptAsymmetric( keysA.encryptionKeyPair, diff --git a/packages/lib/server-side/src/auth.test.ts b/packages/lib/server-side/src/authenticate.test.ts similarity index 89% rename from packages/lib/server-side/src/auth.test.ts rename to packages/lib/server-side/src/authenticate.test.ts index b0e29db8e..2f4e9ebc5 100644 --- a/packages/lib/server-side/src/auth.test.ts +++ b/packages/lib/server-side/src/authenticate.test.ts @@ -5,7 +5,7 @@ import { ethers } from 'ethers'; import express from 'express'; import { verify } from 'jsonwebtoken'; import request from 'supertest'; -import { Auth } from './auth'; +import { Authenticate } from './authenticate'; import { IAccountDatabase } from './iAccountDatabase'; import { createChallenge } from './Keys'; import { sign } from '@dm3-org/dm3-lib-crypto'; @@ -70,7 +70,11 @@ describe('Auth', () => { const app = express(); app.use(bodyParser.json()); app.use( - Auth(mockDbWithAccount, serverSecret, mockWeb3Provider), + Authenticate( + mockDbWithAccount, + serverSecret, + mockWeb3Provider, + ), ); const response = await request(app) @@ -136,14 +140,18 @@ describe('Auth', () => { }); }); - describe('createNewSessionToken', () => { + describe('createNewAccountToken', () => { describe('schema', () => { it('Returns 400 if signature is invalid', async () => { const app = express(); app.use(bodyParser.json()); app.use( - Auth(mockDbWithAccount, serverSecret, mockWeb3Provider), + Authenticate( + mockDbWithAccount, + serverSecret, + mockWeb3Provider, + ), ); // create the challenge jwt @@ -172,7 +180,11 @@ describe('Auth', () => { app.use(bodyParser.json()); app.use( - Auth(mockDbWithAccount, serverSecret, mockWeb3Provider), + Authenticate( + mockDbWithAccount, + serverSecret, + mockWeb3Provider, + ), ); // create the challenge jwt @@ -207,7 +219,11 @@ describe('Auth', () => { app.use(bodyParser.json()); app.use( - Auth(mockDbWithAccount, serverSecret, mockWeb3Provider), + Authenticate( + mockDbWithAccount, + serverSecret, + mockWeb3Provider, + ), ); const { status } = await request(app).post(`/somename`).send({ @@ -221,7 +237,11 @@ describe('Auth', () => { app.use(bodyParser.json()); app.use( - Auth(mockDbWithAccount, serverSecret, mockWeb3Provider), + Authenticate( + mockDbWithAccount, + serverSecret, + mockWeb3Provider, + ), ); // create the challenge jwt diff --git a/packages/lib/server-side/src/auth.ts b/packages/lib/server-side/src/authenticate.ts similarity index 99% rename from packages/lib/server-side/src/auth.ts rename to packages/lib/server-side/src/authenticate.ts index 0901ec384..0c4bae56b 100644 --- a/packages/lib/server-side/src/auth.ts +++ b/packages/lib/server-side/src/authenticate.ts @@ -34,7 +34,7 @@ const createNewSessionTokenBodySchema = { additionalProperties: false, }; -export const Auth = ( +export const Authenticate = ( db: IAccountDatabase, serverSecret: string, web3Provider: ethers.providers.JsonRpcProvider, diff --git a/packages/lib/server-side/src/authorize.test.ts b/packages/lib/server-side/src/authorizationMiddleware.test.ts similarity index 97% rename from packages/lib/server-side/src/authorize.test.ts rename to packages/lib/server-side/src/authorizationMiddleware.test.ts index d8841b2b0..d8eb88968 100644 --- a/packages/lib/server-side/src/authorize.test.ts +++ b/packages/lib/server-side/src/authorizationMiddleware.test.ts @@ -2,8 +2,7 @@ import bodyParser from 'body-parser'; import express, { NextFunction, Request, Response } from 'express'; import { sign, verify } from 'jsonwebtoken'; import request from 'supertest'; - -import { authorize } from './authorize'; +import { authorizationMiddleware } from './authorizationMiddleware'; const serverSecret = 'testSecret'; @@ -34,7 +33,7 @@ describe('Utils', () => { next: NextFunction, ensName: string, ) => { - authorize( + authorizationMiddleware( req, res, next, @@ -83,7 +82,7 @@ describe('Utils', () => { next: NextFunction, ensName: string, ) => { - authorize( + authorizationMiddleware( req, res, next, @@ -131,7 +130,7 @@ describe('Utils', () => { next: NextFunction, ensName: string, ) => { - authorize( + authorizationMiddleware( req, res, next, @@ -188,7 +187,7 @@ describe('Utils', () => { next: NextFunction, ensName: string, ) => { - authorize( + authorizationMiddleware( req, res, next, @@ -257,7 +256,7 @@ describe('Utils', () => { next: NextFunction, ensName: string, ) => { - authorize( + authorizationMiddleware( req, res, next, @@ -346,7 +345,7 @@ describe('Utils', () => { next: NextFunction, ensName: string, ) => { - authorize( + authorizationMiddleware( req, res, next, diff --git a/packages/lib/server-side/src/authorize.ts b/packages/lib/server-side/src/authorizationMiddleware.ts similarity index 98% rename from packages/lib/server-side/src/authorize.ts rename to packages/lib/server-side/src/authorizationMiddleware.ts index b3c18e382..74a673952 100644 --- a/packages/lib/server-side/src/authorize.ts +++ b/packages/lib/server-side/src/authorizationMiddleware.ts @@ -16,7 +16,7 @@ const authJwtPayloadSchema = { additionalProperties: false, }; -export async function authorize( +export async function authorizationMiddleware( req: Request, res: Response, next: NextFunction, diff --git a/packages/lib/server-side/src/index.ts b/packages/lib/server-side/src/index.ts index 2106f0f28..89eb29253 100644 --- a/packages/lib/server-side/src/index.ts +++ b/packages/lib/server-side/src/index.ts @@ -1,5 +1,5 @@ -export { Auth } from './auth'; -export * from './authorize'; +export { Authenticate } from './authenticate'; +export * from './authorizationMiddleware'; export { getCachedWebProvider } from './web3Provider/getCachedWebProvider'; export type { IAccountDatabase } from './iAccountDatabase'; export * from './utils'; diff --git a/packages/messenger-widget/src/context/testHelper/getMockedAuthContext.ts b/packages/messenger-widget/src/context/testHelper/getMockedAuthContext.ts index b34523d42..b99fbcaa7 100644 --- a/packages/messenger-widget/src/context/testHelper/getMockedAuthContext.ts +++ b/packages/messenger-widget/src/context/testHelper/getMockedAuthContext.ts @@ -1,6 +1,6 @@ import { AuthContextType } from '../AuthContext'; -//Provide a mocked Auth context +//Provide a mocked Authenticate context //Override the default values with the provided values export const getMockedAuthContext = (override?: Partial) => { const defaultValues = { diff --git a/packages/messenger-widget/src/context/testHelper/getMockedConversationContext.ts b/packages/messenger-widget/src/context/testHelper/getMockedConversationContext.ts index 24412867d..02e3dc3f4 100644 --- a/packages/messenger-widget/src/context/testHelper/getMockedConversationContext.ts +++ b/packages/messenger-widget/src/context/testHelper/getMockedConversationContext.ts @@ -1,7 +1,7 @@ import { ContactPreview } from '../../interfaces/utils'; import { ConversationContextType } from '../ConversationContext'; -//Provide a mocked Auth context +//Provide a mocked Authenticate context //Override the default values with the provided values export const getMockedConversationContext = ( override?: Partial, diff --git a/yarn.lock b/yarn.lock index 5c6e7daa6..415f08321 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2071,7 +2071,6 @@ __metadata: "@types/cors": ^2.8.17 "@types/express": ^4.17.13 "@types/node": ^20.3.1 - "@types/redis": ^4.0.11 "@types/supertest": ^2.0.12 axios: ^0.27.2 babel-cli: ^6.26.0 @@ -2086,7 +2085,6 @@ __metadata: jest-mock-extended: 2.0.4 prettier: ^2.6.2 prisma: ^5.19.1 - redis: ^4.1.0 superagent: ^8.0.3 supertest: ^6.3.1 ts-json-schema-generator: ^0.98.0