Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
22 changes: 22 additions & 0 deletions app/tests/utils/proving/actorMock.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// SPDX-License-Identifier: BUSL-1.1; Copyright (c) 2025 Social Connect Labs, Inc.; Licensed under BUSL-1.1 (see LICENSE); Apache-2.0 from 2029-06-11

import { jest } from '@jest/globals';

// Minimal actor stub used to observe send calls and emit state transitions

export const actorMock = {
start: jest.fn(),
stop: jest.fn(),
send: jest.fn(),
subscribe: jest.fn((cb: (state: any) => void) => {
(actorMock as any)._callback = cb;
return { unsubscribe: jest.fn() };
}),
};

export function emitState(stateValue: string) {
const cb = (actorMock as any)._callback;
if (cb) {
cb({ value: stateValue, matches: (v: string) => v === stateValue });
}
}
166 changes: 166 additions & 0 deletions app/tests/utils/proving/provingMachine.generatePayload.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
// SPDX-License-Identifier: BUSL-1.1; Copyright (c) 2025 Social Connect Labs, Inc.; Licensed under BUSL-1.1 (see LICENSE); Apache-2.0 from 2029-06-11

import { jest } from '@jest/globals';

import { useProtocolStore } from '../../../src/stores/protocolStore';
import { useSelfAppStore } from '../../../src/stores/selfAppStore';
import { useProvingStore } from '../../../src/utils/proving/provingMachine';

jest.mock('xstate', () => {
const actual = jest.requireActual('xstate') as any;
const { actorMock } = require('./actorMock');
return { ...actual, createActor: jest.fn(() => actorMock) };
});

jest.mock('../../../src/utils/analytics', () => () => ({
trackEvent: jest.fn(),
}));

jest.mock('@selfxyz/common', () => {
const actual = jest.requireActual('@selfxyz/common') as any;
return {
...actual,
getSolidityPackedUserContextData: jest.fn(() => '0x1234'),
};
});

jest.mock('../../../src/utils/proving/provingInputs', () => ({
generateTEEInputsRegister: jest.fn(() => ({
inputs: { r: 1 },
circuitName: 'reg',
endpointType: 'celo',
endpoint: 'https://reg',
})),
generateTEEInputsDSC: jest.fn(() => ({
inputs: { d: 1 },
circuitName: 'dsc',
endpointType: 'celo',
endpoint: 'https://dsc',
})),
generateTEEInputsDisclose: jest.fn(() => ({
inputs: { s: 1 },
circuitName: 'vc_and_disclose',
endpointType: 'https',
endpoint: 'https://dis',
})),
}));

jest.mock('../../../src/utils/proving/provingUtils', () => {
const actual = jest.requireActual(
'../../../src/utils/proving/provingUtils',
) as any;
return {
...actual,
getPayload: jest.fn(() => ({ mocked: true })),
encryptAES256GCM: jest.fn(() => ({
nonce: [0],
cipher_text: [1],
auth_tag: [2],
})),
};
});

const {
getPayload,
encryptAES256GCM,
} = require('../../../src/utils/proving/provingUtils');
const {
generateTEEInputsRegister,
generateTEEInputsDSC,
generateTEEInputsDisclose,
} = require('../../../src/utils/proving/provingInputs');

describe('_generatePayload', () => {
beforeEach(() => {
jest.clearAllMocks();
useProvingStore.setState({
circuitType: 'register',
passportData: { documentCategory: 'passport', mock: false },
secret: 'sec',
uuid: '123',
sharedKey: Buffer.alloc(32, 1),
env: 'prod',
});
useSelfAppStore.setState({
selfApp: {
chainID: 42220,
userId: 'u',
userDefinedData: '0x0',
endpointType: 'https',
endpoint: 'https://e',
scope: 's',
sessionId: '',
appName: '',
logoBase64: '',
header: '',
userIdType: 'uuid',
devMode: false,
disclosures: {},
version: 1,
},
});
useProtocolStore.setState({
passport: {
dsc_tree: 'tree',
csca_tree: [['a']],
commitment_tree: null,
deployed_circuits: null,
circuits_dns_mapping: null,
alternative_csca: {},
fetch_deployed_circuits: jest.fn(),
fetch_circuits_dns_mapping: jest.fn(),
fetch_csca_tree: jest.fn(),
fetch_dsc_tree: jest.fn(),
fetch_identity_tree: jest.fn(),
fetch_alternative_csca: jest.fn(),
fetch_all: jest.fn(),
},
id_card: {
commitment_tree: null,
dsc_tree: null,
csca_tree: null,
deployed_circuits: null,
circuits_dns_mapping: null,
alternative_csca: {},
fetch_deployed_circuits: jest.fn(),
fetch_circuits_dns_mapping: jest.fn(),
fetch_csca_tree: jest.fn(),
fetch_dsc_tree: jest.fn(),
fetch_identity_tree: jest.fn(),
fetch_alternative_csca: jest.fn(),
fetch_all: jest.fn(),
},
} as any);
});

it('register circuit', async () => {
useProvingStore.setState({ circuitType: 'register' });
const payload = await useProvingStore.getState()._generatePayload();
expect(generateTEEInputsRegister).toHaveBeenCalled();
expect(getPayload).toHaveBeenCalled();
expect(encryptAES256GCM).toHaveBeenCalled();
expect(useProvingStore.getState().endpointType).toBe('celo');
expect(payload.params).toEqual({
uuid: '123',
nonce: [0],
cipher_text: [1],
auth_tag: [2],
});
});

it('dsc circuit', async () => {
useProvingStore.setState({ circuitType: 'dsc' });
const payload = await useProvingStore.getState()._generatePayload();
expect(generateTEEInputsDSC).toHaveBeenCalled();
expect(useProvingStore.getState().endpointType).toBe('celo');
expect(payload.params.uuid).toBe('123');
});

it('disclose circuit', async () => {
useProvingStore.setState({ circuitType: 'disclose' });
const payload = await useProvingStore.getState()._generatePayload();
expect(generateTEEInputsDisclose).toHaveBeenCalled();
expect(useProvingStore.getState().endpointType).toBe('https');
expect(payload.params.uuid).toBe('123');
});
});
64 changes: 64 additions & 0 deletions app/tests/utils/proving/provingMachine.init.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// SPDX-License-Identifier: BUSL-1.1; Copyright (c) 2025 Social Connect Labs, Inc.; Licensed under BUSL-1.1 (see LICENSE); Apache-2.0 from 2029-06-11

import { jest } from '@jest/globals';

import { useProvingStore } from '../../../src/utils/proving/provingMachine';
import { emitState } from './actorMock';

jest.mock('xstate', () => {
const actual = jest.requireActual('xstate') as any;
const { actorMock } = require('./actorMock');
return { ...actual, createActor: jest.fn(() => actorMock) };
});

jest.mock('../../../src/providers/passportDataProvider', () => ({
loadSelectedDocument: jest.fn(),
}));

jest.mock('../../../src/providers/authProvider', () => ({
unsafe_getPrivateKey: jest.fn(),
}));

jest.mock('../../../src/utils/analytics', () => () => ({
trackEvent: jest.fn(),
}));

const {
loadSelectedDocument,
} = require('../../../src/providers/passportDataProvider');
const { unsafe_getPrivateKey } = require('../../../src/providers/authProvider');
const { actorMock } = require('./actorMock');

describe('provingMachine init', () => {
beforeEach(() => {
jest.clearAllMocks();
useProvingStore.setState({});
});

it('handles missing document', async () => {
loadSelectedDocument.mockResolvedValue(null);
await useProvingStore.getState().init('register');
expect(actorMock.send).toHaveBeenCalledWith({
type: 'PASSPORT_DATA_NOT_FOUND',
});
emitState('passport_data_not_found');
expect(useProvingStore.getState().currentState).toBe(
'passport_data_not_found',
);
});

it('initializes state with document and secret', async () => {
loadSelectedDocument.mockResolvedValue({
data: { documentCategory: 'passport', mock: false },
});
unsafe_getPrivateKey.mockResolvedValue('mysecret');
await useProvingStore.getState().init('register');
expect(useProvingStore.getState().passportData).toEqual({
documentCategory: 'passport',
mock: false,
});
expect(useProvingStore.getState().secret).toBe('mysecret');
expect(useProvingStore.getState().env).toBe('prod');
expect(useProvingStore.getState().circuitType).toBe('register');
});
});
102 changes: 102 additions & 0 deletions app/tests/utils/proving/provingMachine.websocket.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
// SPDX-License-Identifier: BUSL-1.1; Copyright (c) 2025 Social Connect Labs, Inc.; Licensed under BUSL-1.1 (see LICENSE); Apache-2.0 from 2029-06-11

import { jest } from '@jest/globals';

import { useProvingStore } from '../../../src/utils/proving/provingMachine';

jest.mock('xstate', () => {
const actual = jest.requireActual('xstate') as any;
const { actorMock } = require('./actorMock');
return { ...actual, createActor: jest.fn(() => actorMock) };
});

jest.mock('../../../src/utils/analytics', () => () => ({
trackEvent: jest.fn(),
}));
jest.mock('uuid', () => ({ v4: jest.fn(() => 'uuid') }));

jest.mock('../../../src/utils/proving/attest', () => ({
getPublicKey: jest.fn(() => '04' + 'a'.repeat(128)),
verifyAttestation: jest.fn(() => Promise.resolve(true)),
}));
jest.mock('../../../src/utils/proving/provingUtils', () => ({
ec: { keyFromPublic: jest.fn(() => ({ getPublic: jest.fn() })) },
clientKey: { derive: jest.fn(() => ({ toArray: () => Array(32).fill(1) })) },
clientPublicKeyHex: '00',
}));

jest.mock('../../../src/providers/passportDataProvider', () => ({
loadSelectedDocument: jest.fn(() =>
Promise.resolve({ data: { documentCategory: 'passport', mock: false } }),
),
}));

jest.mock('../../../src/providers/authProvider', () => ({
unsafe_getPrivateKey: jest.fn(() => Promise.resolve('sec')),
}));

const { actorMock } = require('./actorMock');

const { verifyAttestation } = require('../../../src/utils/proving/attest');

describe('websocket handlers', () => {
beforeEach(async () => {
jest.clearAllMocks();
useProvingStore.setState({
wsConnection: {
send: jest.fn(),
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
close: jest.fn(),
} as any,
});
await useProvingStore.getState().init('register');
useProvingStore.setState({
wsConnection: {
send: jest.fn(),
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
close: jest.fn(),
} as any,
});
});

it('_handleWsOpen sends hello', () => {
useProvingStore.getState()._handleWsOpen();
const ws = useProvingStore.getState().wsConnection as any;
expect(ws.send).toHaveBeenCalled();
const sent = JSON.parse(ws.send.mock.calls[0][0]);
expect(sent.params.uuid).toBe('uuid');
expect(useProvingStore.getState().uuid).toBe('uuid');
});

it('_handleWebSocketMessage processes attestation', async () => {
const message = new MessageEvent('message', {
data: JSON.stringify({ result: { attestation: 'a' } }),
});
await useProvingStore.getState()._handleWebSocketMessage(message);
expect(verifyAttestation).toHaveBeenCalled();
expect(
actorMock.send.mock.calls.some(
(c: any) => c[0].type === 'CONNECT_SUCCESS',
),
).toBe(true);
});

it('_handleWebSocketMessage handles error', async () => {
const message = new MessageEvent('message', {
data: JSON.stringify({ error: 'oops' }),
});
await useProvingStore.getState()._handleWebSocketMessage(message);
const lastCall = actorMock.send.mock.calls.pop();
expect(lastCall[0]).toEqual({ type: 'PROVE_ERROR' });
});

it('_handleWsClose triggers failure during proving', () => {
useProvingStore.setState({ currentState: 'proving' });
const event: any = { code: 1000, reason: '', type: 'close' };
useProvingStore.getState()._handleWsClose(event);
const last = actorMock.send.mock.calls.pop();
expect(last[0]).toEqual({ type: 'PROVE_ERROR' });
});
Comment on lines +95 to +101
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add more WebSocket close event scenarios.

The current test only covers close during proving state. Add tests for:

  1. Close events during different states
  2. Different close codes (1000, 1001, 1006, etc.)
  3. Close with custom reason messages
+  it('_handleWsClose handles different close codes', () => {
+    const closeCodes = [1000, 1001, 1006, 1011];
+    closeCodes.forEach(code => {
+      jest.clearAllMocks();
+      useProvingStore.setState({ currentState: 'proving' });
+      const event: any = { code, reason: `Close code ${code}`, type: 'close' };
+      useProvingStore.getState()._handleWsClose(event);
+      expect(actorMock.send).toHaveBeenCalledWith({ type: 'PROVE_ERROR' });
+    });
+  });
+
+  it('_handleWsClose ignores close during non-proving states', () => {
+    ['idle', 'connected', 'completed'].forEach(state => {
+      jest.clearAllMocks();
+      useProvingStore.setState({ currentState: state });
+      const event: any = { code: 1000, reason: '', type: 'close' };
+      useProvingStore.getState()._handleWsClose(event);
+      expect(actorMock.send).not.toHaveBeenCalled();
+    });
+  });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
it('_handleWsClose triggers failure during proving', () => {
useProvingStore.setState({ currentState: 'proving' });
const event: any = { code: 1000, reason: '', type: 'close' };
useProvingStore.getState()._handleWsClose(event);
const last = actorMock.send.mock.calls.pop();
expect(last[0]).toEqual({ type: 'PROVE_ERROR' });
});
it('_handleWsClose triggers failure during proving', () => {
useProvingStore.setState({ currentState: 'proving' });
const event: any = { code: 1000, reason: '', type: 'close' };
useProvingStore.getState()._handleWsClose(event);
const last = actorMock.send.mock.calls.pop();
expect(last[0]).toEqual({ type: 'PROVE_ERROR' });
});
it('_handleWsClose handles different close codes', () => {
const closeCodes = [1000, 1001, 1006, 1011];
closeCodes.forEach(code => {
jest.clearAllMocks();
useProvingStore.setState({ currentState: 'proving' });
const event: any = { code, reason: `Close code ${code}`, type: 'close' };
useProvingStore.getState()._handleWsClose(event);
expect(actorMock.send).toHaveBeenCalledWith({ type: 'PROVE_ERROR' });
});
});
it('_handleWsClose ignores close during non-proving states', () => {
['idle', 'connected', 'completed'].forEach(state => {
jest.clearAllMocks();
useProvingStore.setState({ currentState: state });
const event: any = { code: 1000, reason: '', type: 'close' };
useProvingStore.getState()._handleWsClose(event);
expect(actorMock.send).not.toHaveBeenCalled();
});
});
🤖 Prompt for AI Agents
In app/tests/utils/proving/provingMachine.websocket.test.ts around lines 95 to
101, the test only covers the WebSocket close event during the 'proving' state
with a single close code and empty reason. Add additional test cases to cover
close events occurring in different states of the proving store, use various
close codes such as 1000, 1001, 1006, and include cases with custom reason
messages. This will ensure comprehensive coverage of the _handleWsClose behavior
under different scenarios.

});
Loading
Loading