Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

2625 port chainmanager from poc #2649

Merged
merged 10 commits into from
Nov 25, 2024
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion 3rd-party/auth
Submodule auth updated 0 files
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## [unreleased]

### New features

* Adds basic sigchain functions ([#2649](https://github.com/TryQuiet/quiet/pull/2649))

### Fixes

* Fixed memory leak associated with autoUpdater ([#2606](https://github.com/TryQuiet/quiet/issues/2606))
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
"e2e:linux:run": "lerna run --scope e2e-tests test --",
"prepare": "husky",
"lint-staged": "lerna run lint-staged",
"build:auth": "cd ./3rd-party/auth && pnpm install && pnpm build"
"build:auth": "cd ./3rd-party/auth && pnpm install && pnpm build",
"bootstrap": "npm run build:auth && lerna bootstrap"
},
"engines": {
"node": "18.12.1",
Expand Down
81 changes: 68 additions & 13 deletions packages/backend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 5 additions & 2 deletions packages/backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,8 @@
"yargs": "^17.1.0"
},
"dependencies": {
"@localfirst/auth": "file:../../3rd-party/auth/packages/auth",
"@localfirst/auth": "file:../../3rd-party/auth/packages/auth/dist",
"@localfirst/crdx": "file:../../3rd-party/auth/packages/crdx/dist",
"@chainsafe/libp2p-gossipsub": "6.1.0",
"@chainsafe/libp2p-noise": "11.0.0",
"@nestjs/common": "^10.2.10",
Expand All @@ -111,6 +112,7 @@
"express": "^4.17.1",
"fastq": "^1.17.1",
"fetch-retry": "^6.0.0",
"getmac": "^6.6.0",
"get-port": "^5.1.1",
"go-ipfs": "npm:[email protected]",
"http-server": "^0.12.3",
Expand Down Expand Up @@ -142,7 +144,8 @@
"socks-proxy-agent": "^5.0.0",
"string-replace-loader": "3.1.0",
"ts-jest-resolver": "^2.0.0",
"validator": "^13.11.0"
"validator": "^13.11.0",
"utf-8-validate": "^5.0.2"
},
"overrides": {
"level": "$level",
Expand Down
14 changes: 14 additions & 0 deletions packages/backend/src/nest/auth/services/chainServiceBase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { SigChain } from '../sigchain'
import { createLogger } from '../../common/logger'

const logger = createLogger('auth:baseChainService')

class ChainServiceBase {
protected constructor(protected sigChain: SigChain) {}

public static init(sigChain: SigChain, ...params: any[]): ChainServiceBase {
throw new Error('init not implemented')
}
}

export { ChainServiceBase }
145 changes: 145 additions & 0 deletions packages/backend/src/nest/auth/services/crypto/crypto.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
/**
adrastaea marked this conversation as resolved.
Show resolved Hide resolved
* Handles invite-related chain operations
*/

import { EncryptedAndSignedPayload, EncryptedPayload, EncryptionScope, EncryptionScopeType } from './types'
import { ChainServiceBase } from '../chainServiceBase'
import { SigChain } from '../../sigchain'
import { Base58, Keyset, KeysetWithSecrets, LocalUserContext, Member, SignedEnvelope } from '@localfirst/auth'
import { DEFAULT_SEARCH_OPTIONS, MemberSearchOptions } from '../members/types'
import { ChannelService } from '../roles/channel.service'
import { createLogger } from '../../../common/logger'

const logger = createLogger('auth:cryptoService')

class CryptoService extends ChainServiceBase {
public static init(sigChain: SigChain): CryptoService {
return new CryptoService(sigChain)
}

// TODO: Can we get other members' keys by generation?
public getPublicKeysForMembersById(
memberIds: string[],
searchOptions: MemberSearchOptions = DEFAULT_SEARCH_OPTIONS
): Keyset[] {
const members = this.sigChain.users.getUsersById(memberIds, searchOptions)
return members.map((member: Member) => {
return member.keys
})
}

public getKeysForRole(roleName: string, generation?: number): KeysetWithSecrets {
return this.sigChain.team.roleKeys(roleName, generation)
}

public getKeysForChannel(channelName: string, generation?: number): KeysetWithSecrets {
return this.getKeysForRole(ChannelService.getPrivateChannelRoleName(channelName), generation)
}

public encryptAndSign(message: any, scope: EncryptionScope, context: LocalUserContext): EncryptedAndSignedPayload {
let recipientKey: Base58
let senderKey: Base58
let generation: number
if (scope.type === EncryptionScopeType.ROLE) {
if (scope.name == null) {
throw new Error(`Must provide a role name when encryption scope is set to ${scope.type}`)
}
const keys = this.getKeysForRole(scope.name)
recipientKey = keys.encryption.publicKey
senderKey = keys.encryption.secretKey
generation = keys.generation
} else if (scope.type === EncryptionScopeType.CHANNEL) {
if (scope.name == null) {
throw new Error(`Must provide a channel name when encryption scope is set to ${scope.type}`)
}
const keys = this.getKeysForChannel(scope.name)
recipientKey = keys.encryption.publicKey
senderKey = keys.encryption.secretKey
generation = keys.generation
} else if (scope.type === EncryptionScopeType.USER) {
if (scope.name == null) {
throw new Error(`Must provide a user ID when encryption scope is set to ${scope.type}`)
}
const recipientKeys = this.getPublicKeysForMembersById([scope.name])
recipientKey = recipientKeys[0].encryption
senderKey = context.user.keys.encryption.secretKey
generation = recipientKeys[0].generation
} else if (scope.type === EncryptionScopeType.TEAM) {
const keys = this.sigChain.team.teamKeys()
recipientKey = keys.encryption.publicKey
senderKey = keys.encryption.secretKey
generation = keys.generation
} else {
throw new Error(`Unknown encryption scope type ${scope.type}`)
}

const encryptedContents = SigChain.lfa.asymmetric.encrypt({
secret: message,
senderSecretKey: senderKey,
recipientPublicKey: recipientKey,
})

const signature = this.sigChain.team.sign(encryptedContents)

return {
encrypted: {
contents: encryptedContents,
scope: {
...scope,
generation,
},
},
signature,
ts: Date.now(),
username: context.user.userName,
}
}

public decryptAndVerify(encrypted: EncryptedPayload, signature: SignedEnvelope, context: LocalUserContext): any {
const isValid = this.sigChain.team.verify(signature)
if (!isValid) {
throw new Error(`Couldn't verify signature on message`)
}

let recipientKey: Base58
let senderKey: Base58
if (encrypted.scope.type === EncryptionScopeType.ROLE) {
if (encrypted.scope.name == null) {
throw new Error(`Must provide a role name when encryption scope is set to ${encrypted.scope.type}`)
}
const keys = this.getKeysForRole(encrypted.scope.name, encrypted.scope.generation)
recipientKey = keys.encryption.secretKey
senderKey = keys.encryption.publicKey
} else if (encrypted.scope.type === EncryptionScopeType.CHANNEL) {
if (encrypted.scope.name == null) {
throw new Error(`Must provide a channel name when encryption scope is set to ${encrypted.scope.type}`)
}
const keys = this.getKeysForChannel(encrypted.scope.name, encrypted.scope.generation)
recipientKey = keys.encryption.secretKey
senderKey = keys.encryption.publicKey
} else if (encrypted.scope.type === EncryptionScopeType.USER) {
if (encrypted.scope.name == null) {
throw new Error(`Must provide a user ID when encryption scope is set to ${encrypted.scope.type}`)
}
const senderKeys = this.sigChain.crypto.getPublicKeysForMembersById([signature.author.name])
recipientKey = context.user.keys.encryption.secretKey
senderKey = senderKeys[0].encryption
} else if (encrypted.scope.type === EncryptionScopeType.TEAM) {
const keys = this.sigChain.team.teamKeys(encrypted.scope.generation)
recipientKey = keys.encryption.publicKey
senderKey = keys.encryption.secretKey
} else {
throw new Error(`Unknown encryption scope type ${encrypted.scope.type}`)
}

const decrypted = SigChain.lfa.asymmetric.decrypt({
cipher: encrypted.contents,
senderPublicKey: senderKey,
recipientSecretKey: recipientKey,
})

return decrypted
}
}

export { CryptoService }
27 changes: 27 additions & 0 deletions packages/backend/src/nest/auth/services/crypto/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Base58, SignedEnvelope } from '@localfirst/auth'

export enum EncryptionScopeType {
ROLE = 'ROLE',
CHANNEL = 'CHANNEL',
USER = 'USER',
TEAM = 'TEAM',
}

export type EncryptionScope = {
type: EncryptionScopeType
name?: string
}

export type EncryptedPayload = {
contents: Base58
scope: EncryptionScope & {
generation: number
}
}

export type EncryptedAndSignedPayload = {
encrypted: EncryptedPayload
signature: SignedEnvelope
ts: number
username: string
}
Loading
Loading