Skip to content

Commit

Permalink
Feature: Replace JSONObject type with JsonDocumentObject (#258)
Browse files Browse the repository at this point in the history
* Replace json object type with json document object

* 1.17.5
  • Loading branch information
amonsosanz authored Aug 22, 2024
1 parent 737264d commit 1e015ef
Show file tree
Hide file tree
Showing 19 changed files with 90 additions and 64 deletions.
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.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@0xpolygonid/js-sdk",
"version": "1.17.4",
"version": "1.17.5",
"description": "SDK to work with Polygon ID",
"main": "dist/node/cjs/index.js",
"module": "dist/node/esm/index.js",
Expand Down
3 changes: 2 additions & 1 deletion src/credentials/models.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { JsonDocumentObject } from '../iden3comm';
import {
CredentialStatusType,
MerklizedRootPosition,
Expand Down Expand Up @@ -32,7 +33,7 @@ export interface CredentialRequest {
/**
* Credential subject, usually contains claims and identifier
*/
credentialSubject: { [key: string]: string | object | number | boolean };
credentialSubject: JsonDocumentObject;
/**
* expiration time
*/
Expand Down
4 changes: 2 additions & 2 deletions src/credentials/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ export const getKMSIdByAuthCredential = (credential: W3CCredential): KmsKeyId =>
if (!credential.type.includes('AuthBJJCredential')) {
throw new Error("can't sign with not AuthBJJCredential credential");
}
const x = credential.credentialSubject['x'] as unknown as string;
const y = credential.credentialSubject['y'] as unknown as string;
const x = credential.credentialSubject['x'] as string;
const y = credential.credentialSubject['y'] as string;

const pb: PublicKey = new PublicKey([BigInt(x), BigInt(y)]);
const kp = keyPath(KmsKeyType.BabyJubJub, pb.hex());
Expand Down
14 changes: 7 additions & 7 deletions src/iden3comm/handlers/common.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { getRandomBytes } from '@iden3/js-crypto';
import {
JSONObject,
JsonDocumentObject,
JWSPackerParams,
ZeroKnowledgeProofRequest,
ZeroKnowledgeProofResponse
Expand All @@ -18,11 +18,11 @@ import { Signer } from 'ethers';
* Returns a Map where the key is the groupId and the value is an object containing the query and linkNonce.
*
* @param requestScope - An array of ZeroKnowledgeProofRequest objects.
* @returns A Map<number, { query: JSONObject; linkNonce: number }> representing the grouped queries.
* @returns A Map<number, { query: JsonDocumentObject; linkNonce: number }> representing the grouped queries.
*/
const getGroupedQueries = (
requestScope: ZeroKnowledgeProofRequest[]
): Map<number, { query: JSONObject; linkNonce: number }> =>
): Map<number, { query: JsonDocumentObject; linkNonce: number }> =>
requestScope.reduce((acc, proofReq) => {
const groupId = proofReq.query.groupId as number | undefined;
if (!groupId) {
Expand All @@ -39,22 +39,22 @@ const getGroupedQueries = (
}

const credentialSubject = mergeObjects(
existedData.query.credentialSubject as JSONObject,
proofReq.query.credentialSubject as JSONObject
existedData.query.credentialSubject as JsonDocumentObject,
proofReq.query.credentialSubject as JsonDocumentObject
);

acc.set(groupId, {
...existedData,
query: {
skipClaimRevocationCheck:
existedData.query.skipClaimRevocationCheck || proofReq.query.skipClaimRevocationCheck,
...(existedData.query as JSONObject),
...existedData.query,
credentialSubject
}
});

return acc;
}, new Map<number, { query: JSONObject; linkNonce: number }>());
}, new Map<number, { query: JsonDocumentObject; linkNonce: number }>());

/**
* Processes zero knowledge proof requests.
Expand Down
6 changes: 3 additions & 3 deletions src/iden3comm/handlers/credential-proposal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
CredentialOffer,
CredentialsOfferMessage,
IPackageManager,
JSONObject,
JsonDocumentObject,
PackerParams
} from '../types';

Expand All @@ -25,8 +25,8 @@ import { AbstractMessageHandler, IProtocolMessageHandler } from './message-handl
/** @beta ProposalRequestCreationOptions represents proposal-request creation options */
export type ProposalRequestCreationOptions = {
credentials: ProposalRequestCredential[];
metadata?: { type: string; data?: JSONObject };
did_doc?: JSONObject;
metadata?: { type: string; data?: JsonDocumentObject };
did_doc?: JsonDocumentObject;
};

/**
Expand Down
15 changes: 15 additions & 0 deletions src/iden3comm/types/packer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,21 @@ export type JSONObject = {
[x: string]: JSONValue;
};

/**
* JSON document object
*/
export type JsonDocumentObject = { [key: string]: JsonDocumentObjectValue };

/**
* JSON document object allowed values
*/
export type JsonDocumentObjectValue =
| string
| number
| boolean
| JsonDocumentObject
| JsonDocumentObjectValue[];

export type BasicMessage = {
id: string;
typ?: MediaType;
Expand Down
8 changes: 4 additions & 4 deletions src/iden3comm/types/protocol/auth.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ZKProof } from '@iden3/js-jwz';
import { BasicMessage, JSONObject } from '../packer';
import { BasicMessage, JsonDocumentObject } from '../packer';
import { PROTOCOL_MESSAGE_TYPE } from '../../constants';

/** AuthorizationResponseMessage is struct the represents iden3message authorization response */
Expand All @@ -12,7 +12,7 @@ export type AuthorizationResponseMessage = BasicMessage & {

/** AuthorizationMessageResponseBody is struct the represents authorization response data */
export type AuthorizationMessageResponseBody = {
did_doc?: JSONObject;
did_doc?: JsonDocumentObject;
message?: string;
scope: Array<ZeroKnowledgeProofResponse>;
};
Expand All @@ -29,7 +29,7 @@ export type AuthorizationRequestMessageBody = {
callbackUrl: string;
reason?: string;
message?: string;
did_doc?: JSONObject;
did_doc?: JsonDocumentObject;
scope: Array<ZeroKnowledgeProofRequest>;
};

Expand All @@ -38,7 +38,7 @@ export type ZeroKnowledgeProofRequest = {
id: number;
circuitId: string;
optional?: boolean;
query: JSONObject;
query: JsonDocumentObject;
params?: {
nullifierSessionId?: string | number;
};
Expand Down
4 changes: 2 additions & 2 deletions src/iden3comm/types/protocol/credentials.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { W3CCredential } from '../../../verifiable';
import { PROTOCOL_MESSAGE_TYPE } from '../../constants';
import { BasicMessage, JSONObject } from '../packer';
import { BasicMessage, JsonDocumentObject } from '../packer';
import { ContractInvokeTransactionData } from './contract-request';

/** CredentialIssuanceRequestMessageBody represents data for credential issuance request */
export type CredentialIssuanceRequestMessageBody = {
schema: Schema;
data: JSONObject;
data: JsonDocumentObject;
expiration: number;
};

Expand Down
6 changes: 3 additions & 3 deletions src/iden3comm/types/protocol/proposal-request.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { BasicMessage, JSONObject } from '../';
import { BasicMessage, JsonDocumentObject } from '../';
import { PROTOCOL_MESSAGE_TYPE } from '../../constants';

/** @beta ProposalRequestMessage is struct the represents proposal-request message */
Expand All @@ -10,8 +10,8 @@ export type ProposalRequestMessage = BasicMessage & {
/** @beta ProposalRequestMessageBody is struct the represents body for proposal-request */
export type ProposalRequestMessageBody = {
credentials: ProposalRequestCredential[];
metadata?: { type: string; data?: JSONObject };
did_doc?: JSONObject;
metadata?: { type: string; data?: JsonDocumentObject };
did_doc?: JsonDocumentObject;
};

/** @beta ProposalMessage is struct the represents proposal message */
Expand Down
1 change: 1 addition & 0 deletions src/identity/identity-wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1518,6 +1518,7 @@ export class IdentityWallet implements IIdentityWallet {
txId = await this.transitState(did, oldTreeState, isOldStateGenesis, ethSigner, prover);
break;
} catch (err) {
// eslint-disable-next-line no-console
console.warn(
`Error while transiting state, retrying state transition, attempt: ${attempt}`,
err
Expand Down
6 changes: 3 additions & 3 deletions src/proof/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import {
} from '../verifiable';
import { Merklizer, Options, Path } from '@iden3/js-jsonld-merklization';
import { byteEncoder } from '../utils';
import { JSONObject } from '../iden3comm';
import { JsonDocumentObject } from '../iden3comm';
import { Claim } from '@iden3/js-iden3-core';
import { poseidon } from '@iden3/js-crypto';

Expand Down Expand Up @@ -112,7 +112,7 @@ export type QueryMetadata = PropertyQuery & {
merklizedSchema: boolean;
};

export const parseCredentialSubject = (credentialSubject?: JSONObject): PropertyQuery[] => {
export const parseCredentialSubject = (credentialSubject?: JsonDocumentObject): PropertyQuery[] => {
// credentialSubject is empty
if (!credentialSubject) {
return [{ operator: QueryOperators.$noop, fieldName: '' }];
Expand Down Expand Up @@ -240,7 +240,7 @@ export const parseQueryMetadata = async (
export const parseQueriesMetadata = async (
credentialType: string,
ldContextJSON: string,
credentialSubject: JSONObject,
credentialSubject: JsonDocumentObject,
options: Options
): Promise<QueryMetadata[]> => {
const queriesMetadata = parseCredentialSubject(credentialSubject);
Expand Down
7 changes: 4 additions & 3 deletions src/proof/proof-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ import {
JSONObject,
ZeroKnowledgeProofRequest,
ZeroKnowledgeProofResponse,
PROTOCOL_CONSTANTS
PROTOCOL_CONSTANTS,
JsonDocumentObject
} from '../iden3comm';
import { cacheLoader } from '../schema-processor';
import { ICircuitStorage, IStateStorage } from '../storage';
Expand Down Expand Up @@ -286,7 +287,7 @@ export class ProofService implements IProofService {
}

const propertiesMetadata = parseCredentialSubject(
proofReq.query.credentialSubject as JSONObject
proofReq.query.credentialSubject as JsonDocumentObject
);
if (!propertiesMetadata.length) {
throw new Error('no queries in zkp request');
Expand Down Expand Up @@ -428,7 +429,7 @@ export class ProofService implements IProofService {
const [first, ...rest] = queryMetadata.fieldName.split('.');
let v = credential.credentialSubject[first];
for (const part of rest) {
v = (v as JSONObject)[part];
v = (v as JsonDocumentObject)[part];
}
if (typeof v === 'undefined') {
throw new Error(`credential doesn't contain value for field ${queryMetadata.fieldName}`);
Expand Down
12 changes: 6 additions & 6 deletions src/proof/verifiers/pub-signals-verifier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ import { parseQueriesMetadata, QueryMetadata } from '../common';
import { Operators } from '../../circuits';
import { calculateQueryHashV3 } from './query-hash';
import { JsonLd } from 'jsonld/jsonld-spec';
import { PROTOCOL_CONSTANTS, JSONObject } from '../../iden3comm';
import { PROTOCOL_CONSTANTS, JSONObject, JsonDocumentObject } from '../../iden3comm';

/**
* Verify Context - params for pub signal verification
Expand Down Expand Up @@ -257,7 +257,7 @@ export class PubSignalsVerifier {
const queriesMetadata = await parseQueriesMetadata(
query.type,
JSON.stringify(context),
query.credentialSubject as JSONObject,
query.credentialSubject as JsonDocumentObject,
{
documentLoader: loader
}
Expand Down Expand Up @@ -423,15 +423,15 @@ export class PubSignalsVerifier {
);

// verify query
let schema: JSONObject;
let schema: JsonDocumentObject;
const ldOpts = { documentLoader: this._documentLoader };
try {
schema = (await ldOpts.documentLoader(query.context || '')).document as JSONObject;
schema = (await ldOpts.documentLoader(query.context || '')).document as JsonDocumentObject;
} catch (e) {
throw new Error(`can't load schema for request query`);
}
const ldContextJSON = JSON.stringify(schema);
const credentialSubject = query.credentialSubject as JSONObject;
const credentialSubject = query.credentialSubject as JsonDocumentObject;
const schemaId: string = await Path.getTypeIDFromContext(
ldContextJSON,
query.type || '',
Expand Down Expand Up @@ -540,7 +540,7 @@ export class PubSignalsVerifier {
const queriesMetadata = await parseQueriesMetadata(
query.type,
JSON.stringify(context),
query.credentialSubject as JSONObject,
query.credentialSubject as JsonDocumentObject,
{
documentLoader: loader
}
Expand Down
22 changes: 13 additions & 9 deletions src/utils/object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,32 @@
* @param otherCredSubject - The second object to merge.
* @returns A new object with the merged properties.
*/
type obj = { [k: string]: unknown };

export function mergeObjects(credSubject: obj, otherCredSubject: obj) {
let result = {} as obj;
import { JsonDocumentObject } from '../iden3comm';

export function mergeObjects(
credSubject: JsonDocumentObject,
otherCredSubject: JsonDocumentObject
) {
let result = {} as JsonDocumentObject;
const credSubjectKeys = Object.keys(credSubject);

for (const key of credSubjectKeys) {
if (typeof otherCredSubject[key] !== 'undefined') {
if (typeof credSubject[key] !== 'object' && typeof otherCredSubject[key] !== 'object') {
throw new Error('Invalid query');
}
const subjectProperty = credSubject[key] as obj;
const otherSubjectProperty = otherCredSubject[key] as obj;
const subjectProperty = credSubject[key] as JsonDocumentObject;
const otherSubjectProperty = otherCredSubject[key] as JsonDocumentObject;
const propertyOperators = Object.keys(subjectProperty);
const subjectPropertyResult: obj = {};
const subjectPropertyResult: JsonDocumentObject = {};
for (const operatorKey of propertyOperators) {
if (typeof otherSubjectProperty[operatorKey] !== 'undefined') {
const operatorValue1 = subjectProperty[operatorKey] as obj;
const operatorValue1 = subjectProperty[operatorKey] as JsonDocumentObject;
const operatorValue2 = otherSubjectProperty[operatorKey];
subjectPropertyResult[operatorKey] = [
...new Set([
...((subjectPropertyResult[operatorKey] as Array<obj>) ?? []),
...((subjectPropertyResult[operatorKey] as Array<JsonDocumentObject>) ?? []),
operatorValue1,
...(Array.isArray(operatorValue2) ? operatorValue2 : [operatorValue2])
])
Expand All @@ -36,7 +40,7 @@ export function mergeObjects(credSubject: obj, otherCredSubject: obj) {
}
}
result[key] = {
...(otherCredSubject[key] as obj),
...(otherCredSubject[key] as JsonDocumentObject),
...subjectPropertyResult
};
}
Expand Down
3 changes: 2 additions & 1 deletion src/verifiable/credential.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import {

import * as jsonld from 'jsonld/lib';
import * as ldcontext from 'jsonld/lib/context';
import { JsonDocumentObject } from '../iden3comm';

/**
* W3C Verifiable credential
Expand All @@ -45,7 +46,7 @@ export class W3CCredential {
refreshService?: RefreshService;
displayMethod?: DisplayMethod;
issuanceDate?: string;
credentialSubject: { [key: string]: object | string | number | boolean } = {};
credentialSubject: JsonDocumentObject = {};
credentialStatus!: CredentialStatus;
issuer = '';
credentialSchema!: CredentialSchema;
Expand Down
Loading

0 comments on commit 1e015ef

Please sign in to comment.