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

refactor: messaging #18

Merged
merged 39 commits into from
Oct 5, 2023
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
39 commits
Select commit Hold shift + click to select a range
40301e9
copy all types
Ad96el Aug 4, 2023
e6d2f3d
integrated messaging
Ad96el Aug 4, 2023
f442317
with messaging
Ad96el Aug 4, 2023
0ab879c
with quote
Ad96el Aug 4, 2023
7008be2
fix: make exportable
Ad96el Aug 7, 2023
5bb1159
fix: test against latest not develop
Ad96el Aug 7, 2023
819d315
fix: test against latest not develop
Ad96el Aug 7, 2023
dcc28a7
refactor: reduce types
Ad96el Aug 8, 2023
0ce054a
refactor: remove jest setup
Ad96el Aug 8, 2023
844cdbf
refactor: restructure
Ad96el Aug 9, 2023
b5042c7
chore: copyright
Ad96el Aug 9, 2023
f66bca6
remove terms
Ad96el Aug 9, 2023
e026d9c
remove newline
Ad96el Aug 9, 2023
d4fb2a0
update imports
Ad96el Aug 9, 2023
3f3aa01
add comments
Ad96el Aug 9, 2023
92f433e
docs docs docs
Ad96el Aug 9, 2023
e7dc7cc
docs docs docs
Ad96el Aug 9, 2023
d1c69c7
feat: type guards
Ad96el Aug 9, 2023
a493e93
feat: generics for message
Ad96el Aug 10, 2023
13b7dcf
feat: type guards
Ad96el Aug 10, 2023
7cc83fa
fmt
Ad96el Aug 10, 2023
7670f94
feat: errors
Ad96el Aug 10, 2023
0c97d2b
feat: catch
Ad96el Aug 10, 2023
6bfd5d8
refactor: errors
Ad96el Aug 10, 2023
878fe28
feat: default type
Ad96el Aug 10, 2023
1aa812a
newline
Ad96el Aug 11, 2023
792dc5d
refactor: change return type
Ad96el Aug 11, 2023
1b23e4c
fmt
Ad96el Aug 14, 2023
b0bb518
fix tests
Ad96el Aug 14, 2023
c76cc9b
change response
Ad96el Aug 21, 2023
dfaafcd
fix tests
Ad96el Aug 22, 2023
22073b2
namespace
Ad96el Aug 22, 2023
e06c1ec
do not export verifyMessageEnvelope
Ad96el Aug 23, 2023
0a2ffb9
reduce interface
Ad96el Aug 23, 2023
3969f72
change body type
Ad96el Aug 23, 2023
b5316c5
remove comments
Ad96el Aug 23, 2023
64f5d52
message body
Ad96el Aug 23, 2023
7d348a0
from body generic
Ad96el Aug 24, 2023
a93d110
refactor types
Ad96el Aug 29, 2023
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
3 changes: 2 additions & 1 deletion src/messaging/CredentialApiMessageType.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,9 @@ export function ensureOwnerIsSender(message: IMessage): void {
*
* @param decryptedMessage The decrypted message to check.
*/
export function verify(decryptedMessage: IMessage): void {
export function assertKnownMessage(decryptedMessage: IMessage): IMessage['body'] {
rflechtner marked this conversation as resolved.
Show resolved Hide resolved
verifyMessageBody(decryptedMessage)
verifyMessageEnvelope(decryptedMessage)
ensureOwnerIsSender(decryptedMessage)
return decryptedMessage.body
}
6 changes: 5 additions & 1 deletion src/messaging/Error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,18 @@
*/

export declare class MessageError extends Error {}

export declare class HashMalformedError extends MessageError {
constructor(hash?: string, type?: string)
}

export declare class SignatureMalformedError extends MessageError {}
export declare class UnknownMessageBodyTypeError extends MessageError {}
export declare class DecodingMessageError extends MessageError {}
export declare class CTypeUnknownPropertiesError extends MessageError {}
export declare class InvalidDidFormatError extends MessageError {}
export declare class DidError extends MessageError {
constructor(context?: string, type?: string)
}
export declare class IdentityMismatchError extends MessageError {
constructor(context?: string, type?: string)
}
12 changes: 6 additions & 6 deletions src/messaging/Message.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import { u8aToHex } from '@polkadot/util'
import { Attestation, CType, Claim, Credential, Quote } from '@kiltprotocol/core'
import * as Did from '@kiltprotocol/did'
import { SDKErrors, init } from '@kiltprotocol/sdk-js'
import { init } from '@kiltprotocol/sdk-js'
import * as MessageError from './Error'
import { Crypto } from '@kiltprotocol/utils'
import type {
Expand All @@ -36,7 +36,7 @@ import {
} from '../tests'
import { fromBody, verifyRequiredCTypeProperties } from './utils'
import { decrypt, encrypt, verifyMessageEnvelope } from './MessageEnvelope'
import { ensureOwnerIsSender, verify, verifyMessageBody } from './CredentialApiMessageType'
import { ensureOwnerIsSender, assertKnownMessage, verifyMessageBody } from './CredentialApiMessageType'
import type {
IEncryptedMessage,
IMessage,
Expand Down Expand Up @@ -133,7 +133,7 @@ describe('Messaging', () => {
const decryptedMessage = await decrypt(encryptedMessage, bobEncKey.decrypt, { resolveKey })
expect(JSON.stringify(message.body)).toEqual(JSON.stringify(decryptedMessage.body))

expect(() => verify(decryptedMessage)).not.toThrow()
expect(() => assertKnownMessage(decryptedMessage)).not.toThrow()

const encryptedMessageWrongContent = JSON.parse(
JSON.stringify(encryptedMessage)
Expand Down Expand Up @@ -666,11 +666,11 @@ describe('Error checking / Verification', () => {

it('Checking required properties for given CType', () => {
expect(() => verifyRequiredCTypeProperties(['id', 'name'], testCType)).toThrowError(
SDKErrors.CTypeUnknownPropertiesError
MessageError.CTypeUnknownPropertiesError
)

expect(() => verifyRequiredCTypeProperties(['id', 'name'], testCTypeWithMultipleProperties)).not.toThrowError(
SDKErrors.CTypeUnknownPropertiesError
MessageError.CTypeUnknownPropertiesError
)

expect(() => verifyRequiredCTypeProperties(['id', 'name'], testCTypeWithMultipleProperties)).not.toThrowError()
Expand Down Expand Up @@ -707,7 +707,7 @@ describe('Error checking / Verification', () => {
it('message envelope verifier should throw errors on faulty envelopes', () => {
// @ts-ignore
messageSubmitTerms.sender = 'this is not a sender did'
expect(() => verifyMessageEnvelope(messageSubmitTerms)).toThrowError(SDKErrors.InvalidDidFormatError)
expect(() => verifyMessageEnvelope(messageSubmitTerms)).toThrowError(MessageError.InvalidDidFormatError)
// @ts-ignore
messageRequestAttestationForClaim.messageId = 12
expect(() => verifyMessageEnvelope(messageRequestAttestationForClaim)).toThrowError(TypeError)
Expand Down
3 changes: 1 addition & 2 deletions src/messaging/MessageEnvelope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@

import { DecryptCallback, DidResolveKey, DidResourceUri, EncryptCallback } from '@kiltprotocol/types'
import * as Did from '@kiltprotocol/did'
import { SDKErrors } from '@kiltprotocol/sdk-js'
import * as MessageError from './Error'
import { hexToU8a, stringToU8a, u8aToHex, u8aToString } from '@polkadot/util'

Expand Down Expand Up @@ -60,7 +59,7 @@ export async function decrypt(

const { fragment } = Did.parse(receiverKeyUri)
if (!fragment) {
throw new SDKErrors.DidError(`No fragment for the receiver key ID "${receiverKeyUri}"`)
throw new MessageError.DidError(`No fragment for the receiver key ID "${receiverKeyUri}"`)
}

let data: Uint8Array
Expand Down
5 changes: 3 additions & 2 deletions src/messaging/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@

import { ICType } from '@kiltprotocol/types'
import { IMessage, MessageBody } from '../types'
import { CType, SDKErrors } from '@kiltprotocol/sdk-js'
import * as MessageError from './Error'
import { CType } from '@kiltprotocol/sdk-js'
import { UUID } from '@kiltprotocol/utils'

/**
Expand Down Expand Up @@ -40,6 +41,6 @@ export function verifyRequiredCTypeProperties(requiredProperties: string[], cTyp

const unknownProperties = requiredProperties.find((property) => !(property in cType.properties))
if (unknownProperties) {
throw new SDKErrors.CTypeUnknownPropertiesError()
throw new MessageError.CTypeUnknownPropertiesError()
}
}
2 changes: 2 additions & 0 deletions src/quote/Error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,5 @@ export declare class HashMalformedError extends QuoteError {
}

export declare class QuoteUnverifiableError extends QuoteError {}
export declare class SignatureUnverifiableError extends QuoteError {}
export declare class DidSubjectMismatchError extends QuoteError {}
12 changes: 7 additions & 5 deletions src/quote/Quote.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/* eslint-disable @typescript-eslint/no-non-null-assertion */
/* eslint-disable @typescript-eslint/ban-ts-comment */

/**
* Copyright (c) 2018-2023, BOTLabs GmbH.
*
Expand All @@ -20,12 +21,13 @@ import type {
IQuoteAttesterSigned,
ResolvedDidKey,
} from '@kiltprotocol/types'
import { Crypto, SDKErrors } from '@kiltprotocol/utils'
import { Crypto } from '@kiltprotocol/utils'
import { Credential, CType } from '@kiltprotocol/sdk-js'

import { createLocalDemoFullDidFromKeypair, makeSigningKeyTool } from '../tests'
import * as Quote from './Quote'
import { QuoteSchema } from './QuoteSchema'
import * as QuoteError from './Error'

describe('Quote', () => {
let claimerIdentity: DidDocument
Expand Down Expand Up @@ -193,7 +195,7 @@ describe('Quote', () => {
Quote.verifyAttesterSignedQuote(messedWithCurrency, {
didResolveKey: mockResolveKey,
})
).rejects.toThrow(SDKErrors.SignatureUnverifiableError)
).rejects.toThrow(QuoteError.SignatureUnverifiableError)
const messedWithRootHash: IQuoteAgreement = {
...quoteBothAgreed,
rootHash: '0x1234',
Expand All @@ -202,7 +204,7 @@ describe('Quote', () => {
Quote.verifyQuoteAgreement(messedWithRootHash, {
didResolveKey: mockResolveKey,
})
).rejects.toThrow(SDKErrors.SignatureUnverifiableError)
).rejects.toThrow(QuoteError.SignatureUnverifiableError)
})

it('complains if attesterDid does not match attester signature', async () => {
Expand All @@ -224,7 +226,7 @@ describe('Quote', () => {
Quote.verifyAttesterSignedQuote(wrongSignerAttester, {
didResolveKey: mockResolveKey,
})
).rejects.toThrow(SDKErrors.DidSubjectMismatchError)
).rejects.toThrow(QuoteError.DidSubjectMismatchError)
})

it('complains if claimerDid does not match claimer signature', async () => {
Expand All @@ -246,6 +248,6 @@ describe('Quote', () => {
Quote.verifyQuoteAgreement(wrongSignerClaimer, {
didResolveKey: mockResolveKey,
})
).rejects.toThrow(SDKErrors.DidSubjectMismatchError)
).rejects.toThrow(QuoteError.DidSubjectMismatchError)
})
})
7 changes: 7 additions & 0 deletions src/tests/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,9 @@
/**
* Copyright (c) 2018-2023, BOTLabs GmbH.
*
* This source code is licensed under the BSD 4-Clause "Original" license
* found in the LICENSE file in the root directory of this source tree.
*/

export * from './messageUtils'
export * from './utils'
6 changes: 1 addition & 5 deletions src/types/Imported.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,7 @@
* found in the LICENSE file in the root directory of this source tree.
*/

export type {
ISubmittableResult,
AnyNumber,
AnyJson,
} from '@polkadot/types/types'
export type { ISubmittableResult, AnyNumber, AnyJson } from '@polkadot/types/types'
export type { BN } from '@polkadot/util'
export type { HexString } from '@polkadot/util/types'
export type { Prefix } from '@polkadot/util-crypto/address/types'
Expand Down
43 changes: 24 additions & 19 deletions src/types/Message.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,14 @@
import type { ICredential, ICredentialPresentation, IAttestation, CTypeHash, DidResourceUri, DidUri, IDelegationNode, PartialClaim, ICType } from '@kiltprotocol/types'
import type {
ICredential,
ICredentialPresentation,
IAttestation,
CTypeHash,
DidResourceUri,
DidUri,
IDelegationNode,
PartialClaim,
ICType,
} from '@kiltprotocol/types'
import type { IQuoteAgreement, IQuoteAttesterSigned } from './Quote'

/**
Expand Down Expand Up @@ -30,12 +40,11 @@ export type MessageBodyType =
| 'submit-credential'
| 'reject-terms'

export interface IMessageBodyBase<Type extends string = string, Content = unknown> {
export interface IMessageBodyBase<Type extends string = string, Content = unknown> {
content: Content
type: Type
}


/**
* - `body` - The body of the message, see [[MessageBody]].
* - `createdAt` - The timestamp of the message construction.
Expand All @@ -46,7 +55,7 @@ export interface IMessageBodyBase<Type extends string = string, Content = unknow
* - `inReplyTo` - The id of the parent-message.
* - `references` - The references or the in-reply-to of the parent-message followed by the message-id of the parent-message.
*/
export interface IMessage<Body extends IMessageBodyBase = {type: string, content: unknown}> {
export interface IMessage<Body extends IMessageBodyBase = { type: string; content: unknown }> {
body: Body
createdAt: number
sender: DidUri
Expand All @@ -61,19 +70,18 @@ export interface IMessage<Body extends IMessageBodyBase = {type: string, content
* Error messages signal unintentional programming errors which happened during
* the processing of the incoming messages or when constructing a response message.
*/
export type IError = IMessageBodyBase<'error', {name? : string, message?: string}>;
export type IError = IMessageBodyBase<'error', { name?: string; message?: string }>

/**
* Rejection messages signal the intentional cancelling of an individual step in the flow.
*/
export type IReject = IMessageBodyBase<'reject', {name? : string, message?: string}>;
export type IReject = IMessageBodyBase<'reject', { name?: string; message?: string }>

/**
* An attester utilizes the message to propose a claim. The purpose of the extension is to enable
* the user to authorize and endorse the claims prepared by the attester.
*/
export type ISubmitTerms = IMessageBodyBase<'submit-terms', ITerms>;

export type ISubmitTerms = IMessageBodyBase<'submit-terms', ITerms>

/**
* The content of the [IRequestAttestation] message.
Expand All @@ -90,7 +98,6 @@ export interface IRequestAttestationContent {
*/
export type IRequestAttestation = IMessageBodyBase<'request-attestation', IRequestAttestationContent>


/**
* The content of the [IRequestPayment] message.
*/
Expand All @@ -104,7 +111,6 @@ export interface IRequestPaymentContent {
*/
export type IRequestPayment = IMessageBodyBase<'request-payment', IRequestPaymentContent>


/**
* The content of the [ISubmitAttestation] message.
*/
Expand All @@ -117,15 +123,11 @@ export interface ISubmitAttestationContent {
*/
export type ISubmitAttestation = IMessageBodyBase<'submit-attestation', ISubmitAttestationContent>


/**
* If the attester does not approve the attestation request, the extension receives the [IRejectAttestation] message.
*/
export type IRejectAttestation = IMessageBodyBase<'reject-attestation', ICredential['rootHash']>




/**
* The content of the [ISubmitTerms] message.
*/
Expand All @@ -141,7 +143,6 @@ export interface ITerms {
cTypes?: ICType[]
}


/** Message to submit credentials from the extension or dapp.*/
export type ISubmitCredential = IMessageBodyBase<'submit-credential', ICredentialPresentation[]>

Expand All @@ -159,7 +160,6 @@ export interface IRequestCredentialContent {

export type IRequestCredential = IMessageBodyBase<'request-credential', IRequestCredentialContent>


/**
* The content of the [IConfirmPayment] message.
*/
Expand All @@ -172,7 +172,6 @@ export interface IConfirmPaymentContent {
blockHash: string
}


/**
* After the user has authorized the payment and it has been transferred,
* the extension confirms the transfer to the attester by sending the [IConfirmPayment] message.
Expand All @@ -182,7 +181,10 @@ export type IConfirmPayment = IMessageBodyBase<'confirm-payment', IConfirmPaymen
/**
* Everything which is part of the encrypted and protected part of the [[IMessage]].
*/
export type IEncryptedMessageContents<Body extends IMessageBodyBase = {type: string, content: unknown}> = Omit<IMessage<Body>, 'receivedAt'>
export type IEncryptedMessageContents<Body extends IMessageBodyBase = { type: string; content: unknown }> = Omit<
IMessage<Body>,
'receivedAt'
>

/**
* Removes the plaintext [[IEncryptedMessageContents]] from an [[IMessage]] and instead includes them in encrypted form.
Expand All @@ -192,7 +194,10 @@ export type IEncryptedMessageContents<Body extends IMessageBodyBase = {type: str
* - `receiverKeyUri` - The URI of the receiver's encryption key.
* - `senderKeyUri` - The URI of the sender's encryption key.
*/
export type IEncryptedMessage<Body extends IMessageBodyBase = {type: string, content: unknown}> = Pick<IMessage<Body>, 'receivedAt'> & {
export type IEncryptedMessage<Body extends IMessageBodyBase = { type: string; content: unknown }> = Pick<
IMessage<Body>,
'receivedAt'
> & {
receiverKeyUri: DidResourceUri
senderKeyUri: DidResourceUri
ciphertext: string
Expand Down
3 changes: 1 addition & 2 deletions src/types/Quote.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export interface IQuote {
* Signed quote from attester
*/
export interface IQuoteAttesterSigned extends IQuote {
// Signature of the attester
// Signature of the attester
attesterSignature: DidSignature
}

Expand All @@ -42,4 +42,3 @@ export interface IQuoteAgreement extends IQuoteAttesterSigned {
// The signature of the claimer.
claimerSignature: DidSignature
}

Loading