@zkpassport/sdk 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +97 -40
  2. package/dist/cjs/encryption.js +69 -0
  3. package/dist/cjs/index.d.ts +191 -0
  4. package/dist/cjs/index.js +857 -0
  5. package/dist/{json-rpc.d.ts → cjs/json-rpc.d.ts} +2 -2
  6. package/dist/cjs/json-rpc.js +48 -0
  7. package/dist/{logger.js → cjs/logger.js} +5 -38
  8. package/dist/cjs/mobile.js +131 -0
  9. package/dist/{websocket.js → cjs/websocket.js} +2 -2
  10. package/dist/esm/encryption.d.ts +7 -0
  11. package/dist/esm/encryption.js +40 -0
  12. package/dist/esm/index.d.ts +191 -0
  13. package/dist/esm/index.js +846 -0
  14. package/dist/esm/json-rpc.d.ts +6 -0
  15. package/dist/esm/json-rpc.js +41 -0
  16. package/dist/esm/logger.d.ts +7 -0
  17. package/dist/esm/logger.js +37 -0
  18. package/dist/esm/mobile.d.ts +39 -0
  19. package/dist/esm/mobile.js +126 -0
  20. package/dist/esm/websocket.d.ts +2 -0
  21. package/dist/esm/websocket.js +15 -0
  22. package/package.json +15 -7
  23. package/src/index.ts +978 -67
  24. package/src/json-rpc.ts +9 -5
  25. package/src/mobile.ts +18 -9
  26. package/tsconfig.json +14 -9
  27. package/dist/constants/index.d.ts +0 -13
  28. package/dist/constants/index.js +0 -52
  29. package/dist/encryption.js +0 -126
  30. package/dist/index.d.ts +0 -79
  31. package/dist/index.js +0 -384
  32. package/dist/json-rpc.js +0 -105
  33. package/dist/mobile.js +0 -253
  34. package/dist/types/countries.d.ts +0 -1
  35. package/dist/types/countries.js +0 -2
  36. package/dist/types/credentials.d.ts +0 -17
  37. package/dist/types/credentials.js +0 -2
  38. package/dist/types/index.d.ts +0 -4
  39. package/dist/types/index.js +0 -2
  40. package/dist/types/json-rpc.d.ts +0 -12
  41. package/dist/types/json-rpc.js +0 -2
  42. package/dist/types/query-result.d.ts +0 -46
  43. package/dist/types/query-result.js +0 -2
  44. package/src/circuits/proof_age.json +0 -1
  45. package/src/constants/index.ts +0 -54
  46. package/src/types/countries.ts +0 -278
  47. package/src/types/credentials.ts +0 -40
  48. package/src/types/index.ts +0 -13
  49. package/src/types/json-rpc.ts +0 -13
  50. package/src/types/query-result.ts +0 -49
  51. /package/dist/{encryption.d.ts → cjs/encryption.d.ts} +0 -0
  52. /package/dist/{logger.d.ts → cjs/logger.d.ts} +0 -0
  53. /package/dist/{mobile.d.ts → cjs/mobile.d.ts} +0 -0
  54. /package/dist/{websocket.d.ts → cjs/websocket.d.ts} +0 -0
@@ -0,0 +1,6 @@
1
+ import type { JsonRpcRequest, JsonRpcResponse } from '@zkpassport/utils';
2
+ import { WebSocketClient } from './websocket';
3
+ export declare function createJsonRpcRequest(method: string, params: any): JsonRpcRequest;
4
+ export declare function createEncryptedJsonRpcRequest(method: string, params: any, sharedSecret: Uint8Array, topic: string): Promise<JsonRpcRequest>;
5
+ export declare function sendEncryptedJsonRpcRequest(method: string, params: any, sharedSecret: Uint8Array, topic: string, wsClient: WebSocketClient): Promise<boolean>;
6
+ export declare function createJsonRpcResponse(id: string, result: any): JsonRpcResponse;
@@ -0,0 +1,41 @@
1
+ import { randomBytes } from 'crypto';
2
+ import { encrypt } from './encryption';
3
+ import logger from './logger';
4
+ export function createJsonRpcRequest(method, params) {
5
+ return {
6
+ jsonrpc: '2.0',
7
+ id: randomBytes(16).toString('hex'),
8
+ method,
9
+ params,
10
+ };
11
+ }
12
+ export async function createEncryptedJsonRpcRequest(method, params, sharedSecret, topic) {
13
+ const encryptedMessage = await encrypt(JSON.stringify({ method, params: params || {} }), sharedSecret, topic);
14
+ return createJsonRpcRequest('encryptedMessage', {
15
+ payload: Buffer.from(encryptedMessage).toString('base64'),
16
+ });
17
+ }
18
+ export async function sendEncryptedJsonRpcRequest(method, params, sharedSecret, topic, wsClient) {
19
+ try {
20
+ const message = { method, params: params || {} };
21
+ const encryptedMessage = await encrypt(JSON.stringify(message), sharedSecret, topic);
22
+ const request = createJsonRpcRequest('encryptedMessage', {
23
+ payload: Buffer.from(encryptedMessage).toString('base64'),
24
+ });
25
+ logger.debug('Sending encrypted message (original):', message);
26
+ logger.debug('Sending encrypted message (encrypted):', request);
27
+ wsClient.send(JSON.stringify(request));
28
+ return true;
29
+ }
30
+ catch (error) {
31
+ logger.error('Error sending encrypted message:', error);
32
+ return false;
33
+ }
34
+ }
35
+ export function createJsonRpcResponse(id, result) {
36
+ return {
37
+ jsonrpc: '2.0',
38
+ id,
39
+ result,
40
+ };
41
+ }
@@ -0,0 +1,7 @@
1
+ declare const customLogger: {
2
+ debug: (message: string, ...args: any[]) => void;
3
+ info: (message: string, ...args: any[]) => void;
4
+ warn: (message: string, ...args: any[]) => void;
5
+ error: (message: string, ...args: any[]) => void;
6
+ };
7
+ export default customLogger;
@@ -0,0 +1,37 @@
1
+ // import { createLogger, transports, format } from 'winston'
2
+ // import colors from 'colors/safe'
3
+ // import util from 'util'
4
+ // const logger = createLogger({
5
+ // level: 'debug',
6
+ // format: format.combine(
7
+ // format.timestamp({ format: 'HH:mm' }),
8
+ // format.printf(({ timestamp, level, message, additionalInfo }) => {
9
+ // const colorMap = {
10
+ // debug: colors.cyan,
11
+ // info: colors.green,
12
+ // warn: colors.yellow,
13
+ // error: colors.red,
14
+ // } as const
15
+ // const coloredLevel = (colorMap[level as keyof typeof colorMap] || colors.white)(level.toUpperCase())
16
+ // let logMessage = `${timestamp} [${coloredLevel}] ${message}`
17
+ // if (additionalInfo && additionalInfo.length > 0) {
18
+ // logMessage += ' ' + util.inspect(additionalInfo, { depth: null, colors: true })
19
+ // }
20
+ // return logMessage
21
+ // }),
22
+ // ),
23
+ // transports: [new transports.Console()],
24
+ // })
25
+ // const customLogger = {
26
+ // debug: (message: string, ...args: any[]) => logger.debug(message, { additionalInfo: args }),
27
+ // info: (message: string, ...args: any[]) => logger.info(message, { additionalInfo: args }),
28
+ // warn: (message: string, ...args: any[]) => logger.warn(message, { additionalInfo: args }),
29
+ // error: (message: string, ...args: any[]) => logger.error(message, { additionalInfo: args }),
30
+ // }
31
+ const customLogger = {
32
+ debug: (message, ...args) => console.debug(message, ...args),
33
+ info: (message, ...args) => console.info(message, ...args),
34
+ warn: (message, ...args) => console.warn(message, ...args),
35
+ error: (message, ...args) => console.error(message, ...args),
36
+ };
37
+ export default customLogger;
@@ -0,0 +1,39 @@
1
+ export declare class ZkPassportProver {
2
+ private domain?;
3
+ private topicToKeyPair;
4
+ private topicToWebSocketClient;
5
+ private topicToRemoteDomainVerified;
6
+ private topicToSharedSecret;
7
+ private topicToRemotePublicKey;
8
+ private onDomainVerifiedCallbacks;
9
+ private onBridgeConnectCallbacks;
10
+ private onWebsiteDomainVerifyFailureCallbacks;
11
+ constructor();
12
+ /**
13
+ * @notice Handle an encrypted message.
14
+ * @param request The request.
15
+ * @param outerRequest The outer request.
16
+ */
17
+ private handleEncryptedMessage;
18
+ /**
19
+ * @notice Scan a credentirequest QR code.
20
+ * @returns
21
+ */
22
+ scan(url: string, { keyPairOverride, }?: {
23
+ keyPairOverride?: {
24
+ privateKey: Uint8Array;
25
+ publicKey: Uint8Array;
26
+ };
27
+ }): Promise<{
28
+ domain: string;
29
+ requestId: string;
30
+ isBridgeConnected: () => boolean;
31
+ isDomainVerified: () => boolean;
32
+ onDomainVerified: (callback: () => void) => number;
33
+ onBridgeConnect: (callback: () => void) => number;
34
+ notifyReject: () => Promise<void>;
35
+ notifyAccept: () => Promise<void>;
36
+ notifyDone: (proof: any) => Promise<void>;
37
+ notifyError: (error: string) => Promise<void>;
38
+ }>;
39
+ }
@@ -0,0 +1,126 @@
1
+ import { bytesToHex } from '@noble/ciphers/utils';
2
+ import { getWebSocketClient } from './websocket';
3
+ import { sendEncryptedJsonRpcRequest } from './json-rpc';
4
+ import { decrypt, generateECDHKeyPair, getSharedSecret } from './encryption';
5
+ import logger from './logger';
6
+ export class ZkPassportProver {
7
+ constructor() {
8
+ this.topicToKeyPair = {};
9
+ this.topicToWebSocketClient = {};
10
+ this.topicToRemoteDomainVerified = {};
11
+ this.topicToSharedSecret = {};
12
+ this.topicToRemotePublicKey = {};
13
+ this.onDomainVerifiedCallbacks = {};
14
+ this.onBridgeConnectCallbacks = {};
15
+ this.onWebsiteDomainVerifyFailureCallbacks = {};
16
+ }
17
+ /**
18
+ * @notice Handle an encrypted message.
19
+ * @param request The request.
20
+ * @param outerRequest The outer request.
21
+ */
22
+ async handleEncryptedMessage(topic, request, outerRequest) {
23
+ logger.debug('Received encrypted message:', request);
24
+ if (request.method === 'hello') {
25
+ logger.info(`Successfully verified origin domain name: ${outerRequest.origin}`);
26
+ this.topicToRemoteDomainVerified[topic] = true;
27
+ await Promise.all(this.onDomainVerifiedCallbacks[topic].map((callback) => callback()));
28
+ }
29
+ else if (request.method === 'closed_page') {
30
+ // TODO: Implement
31
+ }
32
+ }
33
+ /**
34
+ * @notice Scan a credentirequest QR code.
35
+ * @returns
36
+ */
37
+ async scan(url, { keyPairOverride, } = {}) {
38
+ const parsedUrl = new URL(url);
39
+ const domain = parsedUrl.searchParams.get('d');
40
+ const topic = parsedUrl.searchParams.get('t');
41
+ const pubkeyHex = parsedUrl.searchParams.get('p');
42
+ if (!domain || !topic || !pubkeyHex) {
43
+ throw new Error('Invalid URL: missing required parameters');
44
+ }
45
+ const pubkey = new Uint8Array(Buffer.from(pubkeyHex, 'hex'));
46
+ this.domain = domain;
47
+ const keyPair = keyPairOverride || (await generateECDHKeyPair());
48
+ this.topicToKeyPair[topic] = {
49
+ privateKey: keyPair.privateKey,
50
+ publicKey: keyPair.publicKey,
51
+ };
52
+ this.topicToRemotePublicKey[topic] = pubkey;
53
+ this.topicToSharedSecret[topic] = await getSharedSecret(bytesToHex(keyPair.privateKey), bytesToHex(pubkey));
54
+ this.topicToRemoteDomainVerified[topic] = false;
55
+ this.onDomainVerifiedCallbacks[topic] = [];
56
+ this.onBridgeConnectCallbacks[topic] = [];
57
+ // Set up WebSocket connection
58
+ const wsClient = getWebSocketClient(`wss://bridge.zkpassport.id?topic=${topic}&pubkey=${bytesToHex(keyPair.publicKey)}`);
59
+ this.topicToWebSocketClient[topic] = wsClient;
60
+ wsClient.onopen = async () => {
61
+ logger.info('[mobile] WebSocket connection established');
62
+ await Promise.all(this.onBridgeConnectCallbacks[topic].map((callback) => callback()));
63
+ // Server sends handshake automatically (when it sees a pubkey in websocket URI)
64
+ // wsClient.send(
65
+ // JSON.stringify(
66
+ // createJsonRpcRequest('handshake', {
67
+ // pubkey: bytesToHex(keyPair.publicKey),
68
+ // }),
69
+ // ),
70
+ // )
71
+ };
72
+ wsClient.addEventListener('message', async (event) => {
73
+ logger.info('[mobile] Received message:', event.data);
74
+ try {
75
+ const data = JSON.parse(event.data);
76
+ const originDomain = data.origin ? new URL(data.origin).hostname : undefined;
77
+ // Origin domain must match domain in QR code
78
+ if (originDomain !== this.domain) {
79
+ logger.warn(`[mobile] Origin does not match domain in QR code. Expected ${this.domain} but got ${originDomain}`);
80
+ return;
81
+ }
82
+ if (data.method === 'encryptedMessage') {
83
+ // Decode the payload from base64 to Uint8Array
84
+ const payload = new Uint8Array(atob(data.params.payload)
85
+ .split('')
86
+ .map((c) => c.charCodeAt(0)));
87
+ try {
88
+ // Decrypt the payload using the shared secret
89
+ const decrypted = await decrypt(payload, this.topicToSharedSecret[topic], topic);
90
+ const decryptedJson = JSON.parse(decrypted);
91
+ await this.handleEncryptedMessage(topic, decryptedJson, data);
92
+ }
93
+ catch (error) {
94
+ logger.error('[mobile] Error decrypting message:', error);
95
+ }
96
+ }
97
+ }
98
+ catch (error) {
99
+ logger.error('[mobile] Error:', error);
100
+ }
101
+ });
102
+ wsClient.onerror = (error) => {
103
+ logger.error('[mobile] WebSocket error:', error);
104
+ };
105
+ return {
106
+ domain: this.domain,
107
+ requestId: topic,
108
+ isBridgeConnected: () => this.topicToWebSocketClient[topic].readyState === WebSocket.OPEN,
109
+ isDomainVerified: () => this.topicToRemoteDomainVerified[topic] === true,
110
+ onDomainVerified: (callback) => this.onDomainVerifiedCallbacks[topic].push(callback),
111
+ onBridgeConnect: (callback) => this.onBridgeConnectCallbacks[topic].push(callback),
112
+ notifyReject: async () => {
113
+ await sendEncryptedJsonRpcRequest('reject', null, this.topicToSharedSecret[topic], topic, this.topicToWebSocketClient[topic]);
114
+ },
115
+ notifyAccept: async () => {
116
+ await sendEncryptedJsonRpcRequest('accept', null, this.topicToSharedSecret[topic], topic, this.topicToWebSocketClient[topic]);
117
+ },
118
+ notifyDone: async (proof) => {
119
+ await sendEncryptedJsonRpcRequest('done', { proof }, this.topicToSharedSecret[topic], topic, this.topicToWebSocketClient[topic]);
120
+ },
121
+ notifyError: async (error) => {
122
+ await sendEncryptedJsonRpcRequest('error', { error }, this.topicToSharedSecret[topic], topic, this.topicToWebSocketClient[topic]);
123
+ },
124
+ };
125
+ }
126
+ }
@@ -0,0 +1,2 @@
1
+ export declare function getWebSocketClient(url: string, origin?: string): WebSocket | import("ws").WebSocket;
2
+ export type WebSocketClient = ReturnType<typeof getWebSocketClient>;
@@ -0,0 +1,15 @@
1
+ export function getWebSocketClient(url, origin) {
2
+ if (typeof window !== 'undefined' && window.WebSocket) {
3
+ // Browser environment
4
+ return new WebSocket(url);
5
+ }
6
+ else {
7
+ // Node.js environment
8
+ const WebSocket = require('ws');
9
+ return new WebSocket(url, {
10
+ headers: {
11
+ Origin: origin || 'nodejs',
12
+ },
13
+ });
14
+ }
15
+ }
package/package.json CHANGED
@@ -1,31 +1,39 @@
1
1
  {
2
2
  "name": "@zkpassport/sdk",
3
- "version": "0.1.1",
4
- "description": "",
5
- "main": "./dist/index.js",
6
- "types": "./dist/index.d.ts",
3
+ "version": "0.2.0",
4
+ "description": "ZKPassport SDK",
5
+ "main": "./dist/cjs/index.js",
6
+ "module": "./dist/esm/index.js",
7
+ "types": "./dist/esm/index.d.ts",
7
8
  "files": [
8
9
  "src/",
9
- "dist/",
10
+ "dist/**",
10
11
  "tsconfig.json",
11
12
  "README.md"
12
13
  ],
13
14
  "scripts": {
14
15
  "prepare": "npm i --save-dev @types/node && npm run build",
15
- "build": "tsc"
16
+ "build": "npm run build:esm && npm run build:cjs",
17
+ "build:esm": "tsc -p tsconfig.json",
18
+ "build:cjs": "tsc -p tsconfig.cjs.json"
16
19
  },
17
20
  "keywords": [],
18
21
  "author": "",
19
22
  "license": "Apache-2.0",
20
23
  "devDependencies": {
21
- "@types/node": "^22.10.5",
24
+ "@types/node": "^22.10.9",
25
+ "@types/node-gzip": "^1.1.3",
22
26
  "@types/ws": "^8.5.12",
23
27
  "typescript": "^5.6.2"
24
28
  },
25
29
  "dependencies": {
30
+ "@aztec/bb.js": "^0.67.0",
26
31
  "@noble/ciphers": "^1.0.0",
27
32
  "@noble/secp256k1": "^2.1.0",
33
+ "@zkpassport/utils": "^0.2.12",
28
34
  "i18n-iso-countries": "^7.12.0",
35
+ "node-gzip": "^1.1.2",
36
+ "tslib": "^2.8.1",
29
37
  "ws": "^8.18.0"
30
38
  }
31
39
  }