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

DIrectives #297

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
4 changes: 2 additions & 2 deletions package-lock.json

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

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@0xpolygonid/js-sdk",
"version": "1.26.0",
"version": "1.27.0",
"description": "SDK to work with Polygon ID",
"main": "dist/node/cjs/index.js",
"module": "dist/node/esm/index.js",
Expand All @@ -18,7 +18,8 @@
"types": "dist/types/index.d.ts",
"source": "./src/index.ts",
"files": [
"dist"
"dist",
"src"
],
"scripts": {
"clean": "rimraf ./dist",
Expand Down
71 changes: 71 additions & 0 deletions src/iden3comm/directiveHelper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { BasicMessage, DirectiveAttachment, Iden3AttachmentType, Iden3Directive } from './types';

/**
* The `DirectiveManager` class provides methods to extract and propagate Iden3 directives
* within a basic message. It includes functionality to handle message attachments and
* manage directives of type `Iden3Directive`.
*/
export class DirectiveHelper {
/**
* Extracts Iden3 directives from a given message.
* @param message - The message object containing attachments.
* @returns An array of Iden3Directive objects extracted from the message.
*/
static extractDirectiveFromMessage(message: BasicMessage): Iden3Directive[] {
const attachments = message.attachments;
if (!attachments) {
return [];
}
return attachments.reduce((acc: Iden3Directive[], attachment: DirectiveAttachment) => {
if (!attachment.data) {
return acc;
}
if (attachment.data.type !== Iden3AttachmentType.Iden3Directive) {
return acc;
}
const directives = attachment.data.directives;
return directives?.length ? [...acc, ...directives] : acc;
}, []);
}

/**
* Propagates incoming directives into a basic message.
* @param message - The basic message to propagate directives into.
* @param incomingDirective - The incoming directives to add to the existing ones.
* @returns The updated basic message with the attached directives.
*/
static propagateDirectiveIntoMessage(
message: BasicMessage,
incomingDirective: Iden3Directive[]
): BasicMessage {
// add incoming directives to the existing ones
const attachedDirectives = (message.attachments ?? [])
.filter((att) => att.data.type === Iden3AttachmentType.Iden3Directive)
.reduce((acc: Iden3Directive[], att) => {
const dir = att.data.directives;
return [...acc, ...dir];
}, incomingDirective);

if (!attachedDirectives.length) {
return message;
}

// merge directives attachment with existing attachments
const resultedAttachments = [
...(message.attachments ?? []).filter(
(att) => att.data.type !== Iden3AttachmentType.Iden3Directive
),
{
data: {
type: Iden3AttachmentType.Iden3Directive,
directives: attachedDirectives
}
}
];

return {
...message,
attachments: resultedAttachments
};
}
}
6 changes: 5 additions & 1 deletion src/iden3comm/handlers/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ import {
IPackageManager,
JWSPackerParams,
ZeroKnowledgeProofRequest,
JSONObject
JSONObject,
DirectiveAttachment
} from '../types';
import { DID, getUnixTimestamp } from '@iden3/js-iden3-core';
import { proving } from '@iden3/js-jwz';
Expand All @@ -35,6 +36,7 @@ export type AuthorizationRequestCreateOptions = {
accept?: string[];
scope?: ZeroKnowledgeProofRequest[];
expires_time?: Date;
attachments?: DirectiveAttachment[];
};

/**
Expand Down Expand Up @@ -86,6 +88,8 @@ export function createAuthorizationRequestWithMessage(
created_time: getUnixTimestamp(new Date()),
expires_time: opts?.expires_time ? getUnixTimestamp(opts.expires_time) : undefined
};

opts?.attachments && (request.attachments = opts.attachments);
return request;
}

Expand Down
107 changes: 102 additions & 5 deletions src/iden3comm/handlers/credential-proposal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import {
CredentialOffer,
CredentialsOfferMessage,
DIDDocument,
Iden3Directive,
Iden3DirectiveType,
IPackageManager,
JsonDocumentObject,
PackerParams
Expand All @@ -19,7 +21,7 @@ import {
ProposalMessage
} from '../types/protocol/proposal-request';
import { IIdentityWallet } from '../../identity';
import { byteEncoder } from '../../utils';
import { byteDecoder, byteEncoder } from '../../utils';
import { W3CCredential } from '../../verifiable';
import {
AbstractMessageHandler,
Expand All @@ -31,8 +33,10 @@ import { verifyExpiresTime } from './common';
/** @beta ProposalRequestCreationOptions represents proposal-request creation options */
export type ProposalRequestCreationOptions = {
credentials: ProposalRequestCredential[];
metadata?: { type: string; data?: JsonDocumentObject };
metadata?: { type: string; data?: JsonDocumentObject | JsonDocumentObject[] };
did_doc?: DIDDocument;
mediaType?: MediaType;
thid?: string;
expires_time?: Date;
};

Expand Down Expand Up @@ -60,7 +64,7 @@ export function createProposalRequest(
thid: uuidv4,
from: sender.string(),
to: receiver.string(),
typ: MediaType.PlainMessage,
typ: opts?.mediaType ?? MediaType.PlainMessage,
type: PROTOCOL_MESSAGE_TYPE.PROPOSAL_REQUEST_MESSAGE_TYPE,
body: opts,
created_time: getUnixTimestamp(new Date()),
Expand Down Expand Up @@ -142,6 +146,21 @@ export interface ICredentialProposalHandler {
): Promise<{
proposal: ProposalMessage;
}>;

/**
* @beta
* creates proposal-request
* @param {ProposalRequestCreationOptions} params - creation options
* @returns `Promise<ProposalRequestMessage>`
*/
createProposalRequestPacked(
params: {
thid: string;
sender: DID;
receiver: DID;
directives?: Iden3Directive[];
} & ProposalRequestCreationOptions
): Promise<{ request: ProposalRequestMessage; token: string }>;
}

/** @beta ProposalRequestHandlerOptions represents proposal-request handler options */
Expand All @@ -155,7 +174,11 @@ export type ProposalHandlerOptions = BasicHandlerOptions & {
/** @beta CredentialProposalHandlerParams represents credential proposal handler params */
export type CredentialProposalHandlerParams = {
agentUrl: string;
proposalResolverFn: (context: string, type: string) => Promise<Proposal>;
proposalResolverFn: (
context: string,
type: string,
request?: ProposalRequestMessage
) => Promise<Proposal>;
packerParams: PackerParams;
};

Expand Down Expand Up @@ -283,7 +306,11 @@ export class CredentialProposalHandler
}

// credential not found in the wallet, prepare proposal protocol message
const proposal = await this._params.proposalResolverFn(cred.context, cred.type);
const proposal = await this._params.proposalResolverFn(
cred.context,
cred.type,
proposalRequest
);
if (!proposal) {
throw new Error(`can't resolve Proposal for type: ${cred.type}, context: ${cred.context}`);
}
Expand Down Expand Up @@ -361,4 +388,74 @@ export class CredentialProposalHandler
}
return { proposal };
}

/**
* @inheritdoc ICredentialProposalHandler#createProposalRequest
*/
async createProposalRequestPacked(
params: {
thid: string;
sender: DID;
receiver: DID;
directives?: Iden3Directive[];
} & ProposalRequestCreationOptions
): Promise<{ request: ProposalRequestMessage; token: string }> {
const thid = params.thid ?? uuid.v4();

const directives = (params.directives ?? []).filter(
(directive) => directive.purpose === PROTOCOL_MESSAGE_TYPE.PROPOSAL_REQUEST_MESSAGE_TYPE
);

const credentialsToRequest: ProposalRequestCredential[] = [...params.credentials];

const result = directives.reduce<{
metadata: {
type: string;
data: JsonDocumentObject[];
};
credentialsToRequest: ProposalRequestCredential[];
}>(
(acc, directive) => {
if (directive.type !== Iden3DirectiveType.TransparentPaymentDirective) {
return acc;
}
const directiveCredentials: ProposalRequestCredential[] = (directive.data ?? []).flatMap(
(p) => p.credential
);
acc.credentialsToRequest = [...acc.credentialsToRequest, ...directiveCredentials];
delete directive.purpose;
const meta = Array.isArray(acc.metadata.data) ? acc.metadata.data : [acc.metadata.data];
acc.metadata.data = [...meta, directive as JsonDocumentObject];
return acc;
},
{
metadata: {
type: 'Iden3Metadata',
data: []
},
credentialsToRequest
}
);

const msg = createProposalRequest(params.sender, params.receiver, {
credentials: [...new Set(result.credentialsToRequest.map((c) => JSON.stringify(c)))].map(
(c) => JSON.parse(c)
),
metadata: result.metadata,
mediaType: params.mediaType,
did_doc: params.did_doc,
thid
});

const msgBytes = byteEncoder.encode(JSON.stringify(msg));

const token = byteDecoder.decode(
await this._packerMgr.pack(msg.typ ?? MediaType.PlainMessage, msgBytes, {
senderDID: params.sender,
...this._params.packerParams
})
);

return { request: msg, token };
}
}
1 change: 1 addition & 0 deletions src/iden3comm/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export * from './types';
export * from './handlers';
export * from './utils/did';
export * from './utils/accept-profile';
export * from './directiveHelper';

import * as PROTOCOL_CONSTANTS from './constants';
export { PROTOCOL_CONSTANTS };
1 change: 1 addition & 0 deletions src/iden3comm/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export * from './protocol/proposal-request';
export * from './protocol/payment';
export * from './protocol/accept-profile';
export * from './protocol/discovery-protocol';
export * from './protocol/directives';

export * from './packer';
export * from './models';
Expand Down
8 changes: 7 additions & 1 deletion src/iden3comm/types/packer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { CircuitId } from '../../circuits';
import { MediaType, PROTOCOL_MESSAGE_TYPE } from '../constants';
import { DIDDocument, VerificationMethod } from 'did-resolver';
import { StateVerificationOpts } from './models';
import { DirectiveAttachment } from './protocol/directives';

/**
* Protocol message type
Expand Down Expand Up @@ -51,14 +52,19 @@ export type BasicMessage = {
to?: string;
created_time?: number;
expires_time?: number;
attachments?: DirectiveAttachment[];
};

/**
* Basic message with all possible fields required
*/
export type RequiredBasicMessage = Omit<Required<BasicMessage>, 'created_time' | 'expires_time'> & {
export type RequiredBasicMessage = Omit<
Required<BasicMessage>,
'created_time' | 'expires_time' | 'attachments'
> & {
created_time?: number;
expires_time?: number;
attachments?: DirectiveAttachment[];
};

/**
Expand Down
48 changes: 48 additions & 0 deletions src/iden3comm/types/protocol/directives.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { PROTOCOL_MESSAGE_TYPE } from '../../constants';

export enum Iden3DirectiveType {
TransparentPaymentDirective = 'TransparentPaymentDirective'
}

export type TransparentPaymentCredential = {
type: string;
context: string;
};

export type TransparentPaymentRequestData = {
recipient: string;
amount: string;
token?: string;
expiration: string;
nonce: string;
metadata: string;
};

export type TransparentPaymentDirectivePayload = {
credential: TransparentPaymentCredential;
paymentData: TransparentPaymentRequestData;
permitSignature: string;
description?: string;
};

export type TransparentPaymentDirective = {
type: Iden3DirectiveType.TransparentPaymentDirective;
purpose?: (typeof PROTOCOL_MESSAGE_TYPE)[keyof typeof PROTOCOL_MESSAGE_TYPE];
context?: string;
data: TransparentPaymentDirectivePayload[];
};

export enum Iden3AttachmentType {
Iden3Directive = 'Iden3Directive'
}

export type Iden3Directive = TransparentPaymentDirective; // Union type if more directive types are added later

export type Iden3Directives = {
type: Iden3AttachmentType;
directives: Iden3Directive[];
};

export type DirectiveAttachment = {
data: Iden3Directives;
};
2 changes: 1 addition & 1 deletion src/iden3comm/types/protocol/proposal-request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export type ProposalRequestMessage = BasicMessage & {
/** @beta ProposalRequestMessageBody is struct the represents body for proposal-request */
export type ProposalRequestMessageBody = {
credentials: ProposalRequestCredential[];
metadata?: { type: string; data?: JsonDocumentObject };
metadata?: { type: string; data?: JsonDocumentObject | JsonDocumentObject[] };
did_doc?: DIDDocument;
};

Expand Down
Loading
Loading