@zkpassport/sdk 0.1.2 → 0.2.1

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 +80 -25
  2. package/dist/{encryption.d.ts → cjs/encryption.d.ts} +4 -4
  3. package/dist/cjs/encryption.js +79 -0
  4. package/dist/cjs/index.d.ts +191 -0
  5. package/dist/cjs/index.js +857 -0
  6. package/dist/{json-rpc.d.ts → cjs/json-rpc.d.ts} +1 -1
  7. package/dist/cjs/json-rpc.js +48 -0
  8. package/dist/{logger.js → cjs/logger.js} +5 -38
  9. package/dist/cjs/mobile.js +131 -0
  10. package/dist/{websocket.js → cjs/websocket.js} +2 -2
  11. package/dist/esm/encryption.d.ts +7 -0
  12. package/dist/esm/encryption.js +40 -0
  13. package/dist/esm/index.d.ts +191 -0
  14. package/dist/esm/index.js +846 -0
  15. package/dist/esm/json-rpc.d.ts +6 -0
  16. package/dist/esm/json-rpc.js +41 -0
  17. package/dist/esm/logger.d.ts +7 -0
  18. package/dist/esm/logger.js +37 -0
  19. package/dist/esm/mobile.d.ts +39 -0
  20. package/dist/esm/mobile.js +126 -0
  21. package/dist/esm/websocket.d.ts +2 -0
  22. package/dist/esm/websocket.js +15 -0
  23. package/package.json +16 -8
  24. package/src/index.ts +974 -63
  25. package/src/json-rpc.ts +6 -2
  26. package/src/mobile.ts +14 -5
  27. package/tsconfig.json +14 -9
  28. package/dist/constants/index.d.ts +0 -13
  29. package/dist/constants/index.js +0 -52
  30. package/dist/encryption.js +0 -126
  31. package/dist/index.d.ts +0 -79
  32. package/dist/index.js +0 -384
  33. package/dist/json-rpc.js +0 -105
  34. package/dist/mobile.js +0 -253
  35. package/dist/types/countries.d.ts +0 -1
  36. package/dist/types/countries.js +0 -2
  37. package/dist/types/credentials.d.ts +0 -17
  38. package/dist/types/credentials.js +0 -2
  39. package/dist/types/index.d.ts +0 -4
  40. package/dist/types/index.js +0 -2
  41. package/dist/types/json-rpc.d.ts +0 -12
  42. package/dist/types/json-rpc.js +0 -2
  43. package/dist/types/query-result.d.ts +0 -46
  44. package/dist/types/query-result.js +0 -2
  45. package/src/circuits/proof_age.json +0 -1
  46. package/src/constants/index.ts +0 -54
  47. package/src/types/countries.ts +0 -278
  48. package/src/types/credentials.ts +0 -40
  49. package/src/types/index.ts +0 -13
  50. package/src/types/json-rpc.ts +0 -13
  51. package/src/types/query-result.ts +0 -49
  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
package/README.md CHANGED
@@ -1,4 +1,10 @@
1
- # zkpassport-sdk
1
+ # ZKPassport SDK
2
+
3
+ Privacy-preserving identity verification using passports and ID cards.
4
+
5
+ _⚠️ Warning ⚠️_
6
+
7
+ _This version of the SDK is only compatible with the version 0.5 and above of ZKPassport mobile app._
2
8
 
3
9
  ## Installation
4
10
 
@@ -9,35 +15,52 @@ npm install @zkpassport/sdk
9
15
  ## How to use
10
16
 
11
17
  ```ts
12
- import { ZkPassport } from '@zkpassport/sdk'
18
+ import { ZKPassport, EU_COUNTRIES } from '@zkpassport/sdk'
13
19
 
14
20
  // Replace with your domain
15
- const zkPassport = new ZkPassport('demo.zkpassport.id')
21
+ const zkPassport = new ZKPassport('demo.zkpassport.id')
16
22
 
17
23
  // Specify your app name, logo and the purpose of the request
18
24
  // you'll send to your visitors or users
19
25
  const queryBuilder = await zkPassport.request({
20
- name: 'ZKpassport',
26
+ name: 'ZKPassport',
21
27
  logo: 'https://zkpassport.id/logo.png',
22
- purpose: 'Proof of country and first name',
28
+ purpose: 'Prove you are an adult from the EU but not from Scandinavia',
29
+ // The scope is optional and can be used to scope the unique identifier
30
+ // of the request to a specific use case
31
+ // By default, the request's unique identifier is scoped to your domain name only
32
+ scope: 'eu-adult-not-scandinavia',
23
33
  })
24
34
 
25
35
  // Specify the data you want to disclose
26
36
  // Then you can call the `done` method to get the url and the callbacks to follow the progress
27
37
  // and get back the result along with the proof
28
- const { url, requestId, onQRCodeScanned, onGeneratingProof, onProofGenerated, onReject, onError } = queryBuilder
29
- .disclose('nationality')
38
+ // The example below requests to disclose the firstname, prove the user is at least 18 years old,
39
+ // prove the user is from the EU but not from a Scandinavian country (note that Norway is not in the EU)
40
+ const {
41
+ url,
42
+ requestId,
43
+ onRequestReceived,
44
+ onGeneratingProof,
45
+ onProofGenerated,
46
+ onResult,
47
+ onReject,
48
+ onError,
49
+ } = queryBuilder
30
50
  .disclose('firstname')
51
+ .gte('age', 18)
52
+ .in('nationality', EU_COUNTRIES)
53
+ .out('nationality', ['Sweden', 'Denmark'])
31
54
  .done()
32
55
 
33
- // Generate a url with the url and let your user scan it
34
- // or transform it into a button if the user is on mobile
56
+ // Generate a QR Code with the url and let your user scan it
57
+ // or transform it into a button if the user is on their phone
35
58
 
36
- onQRCodeScanned(() => {
37
- // The user scanned the QR code or clicked the button
59
+ onRequestReceived(() => {
60
+ // The user scanned the QR code or clicked the link to the request
38
61
  // Essentially, this means the request popup is now opened
39
62
  // on the user phone
40
- console.log('QR code scanned')
63
+ console.log('Request received')
41
64
  })
42
65
 
43
66
  onGeneratingProof(() => {
@@ -45,17 +68,49 @@ onGeneratingProof(() => {
45
68
  console.log('Generating proof')
46
69
  })
47
70
 
48
- onProofGenerated((result: ProofResult) => {
49
- // The proof has been generated
50
- // You can retrieve the proof, the verification key and the result of your query
51
- // Note: the verify function will soon be added to the SDK so you can verify the proof
52
- // directly
53
- console.log('Proof', result.proof)
54
- console.log('Verification key', result.verificationKey)
55
- console.log('Query result', result.queryResult)
56
- console.log('firstname', result.queryResult.firstname.disclose.result)
57
- console.log('nationality', result.queryResult.nationality.disclose.result)
71
+ // You probably don't need to use this callback
72
+ // But if you want to get the proofs and verify them manually, it's here
73
+ onProofGenerated(({ proof, vkeyHash, version, name }: ProofResult) => {
74
+ // One of the proofs has been generated
75
+ // Here, you can retrieve the proof manually and verify it
76
+ // But note that the verification of the proofs is handled
77
+ // automatically by the SDK
78
+ console.log('Proof generated', proof)
79
+ console.log('Verification key hash', vkeyHash)
80
+ console.log('Version', version)
81
+ console.log('Name', name)
58
82
  })
83
+
84
+ // That's the callback you're looking for
85
+ onResult(
86
+ ({
87
+ uniqueIdentifier,
88
+ verified,
89
+ result,
90
+ }: {
91
+ uniqueIdentifier: string
92
+ verified: boolean
93
+ result: QueryResult
94
+ }) => {
95
+ // All the proofs have been generated and the final result is available
96
+ console.log('firstname', result.firstname.disclose.result)
97
+ console.log('age over 18', result.age.gte.result)
98
+ console.log('nationality in EU', result.nationality.in.result)
99
+ console.log('nationality not from Scandinavia', result.nationality.out.result)
100
+ // You can also retrieved what were the values originally requested
101
+ console.log('age over', result.age.gte.expected)
102
+ console.log('nationality in', result.nationality.in.expected)
103
+ console.log('nationality not in', result.nationality.out.expected)
104
+ // You can make sure the proof are valid by checking verified is set to true
105
+ console.log('proofs are valid', verified)
106
+ // You can also retrieve the unique identifier associated to this request
107
+ // The assumption is that the unique identifier will be the same if coming
108
+ // from the same ID for the same domain name and scope
109
+ // So you can use it to identify if the user has already provided the proof
110
+ // for this specific use case
111
+ console.log('unique identifier', uniqueIdentifier)
112
+ },
113
+ )
59
114
  ```
60
115
 
61
116
  ### Using with Next.js
@@ -68,12 +123,12 @@ You can integrate `@zkpassport/sdk` into a Next.js application by creating a bac
68
123
 
69
124
  ```typescript
70
125
  import { NextResponse } from 'next/server'
71
- import { ZkPassport } from '@zkpassport/sdk'
126
+ import { ZKPassport } from '@zkpassport/sdk'
72
127
 
73
128
  export async function GET() {
74
- const zkPassport = new ZkPassport('demo.zkpassport.id') // Replace with your domain
129
+ const zkPassport = new ZKPassport('demo.zkpassport.id') // Replace with your domain
75
130
  const queryBuilder = await zkPassport.request({
76
- name: 'ZKpassport Demo',
131
+ name: 'ZKPassport Demo',
77
132
  logo: 'https://via.placeholder.com/150',
78
133
  purpose: 'Verify user nationality and first name',
79
134
  })
@@ -1,7 +1,7 @@
1
1
  export declare function generateECDHKeyPair(): Promise<{
2
- privateKey: Uint8Array;
3
- publicKey: Uint8Array;
2
+ privateKey: import("@noble/secp256k1").Bytes;
3
+ publicKey: import("@noble/secp256k1").Bytes;
4
4
  }>;
5
- export declare function getSharedSecret(privateKey: string, publicKey: string): Promise<Uint8Array>;
6
- export declare function encrypt(message: string, sharedSecret: Uint8Array, topic: string): Promise<Uint8Array>;
5
+ export declare function getSharedSecret(privateKey: string, publicKey: string): Promise<Uint8Array<ArrayBuffer>>;
6
+ export declare function encrypt(message: string, sharedSecret: Uint8Array, topic: string): Promise<Uint8Array<ArrayBufferLike>>;
7
7
  export declare function decrypt(ciphertext: Uint8Array, sharedSecret: Uint8Array, topic: string): Promise<string>;
@@ -0,0 +1,79 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.generateECDHKeyPair = generateECDHKeyPair;
37
+ exports.getSharedSecret = getSharedSecret;
38
+ exports.encrypt = encrypt;
39
+ exports.decrypt = decrypt;
40
+ const aes_1 = require("@noble/ciphers/aes");
41
+ const utils_1 = require("@noble/ciphers/utils");
42
+ async function sha256Truncate(topic) {
43
+ const encoder = new TextEncoder();
44
+ const data = encoder.encode(topic);
45
+ const hashBuffer = await crypto.subtle.digest('SHA-256', data);
46
+ const fullHashArray = new Uint8Array(hashBuffer);
47
+ const truncatedHashArray = fullHashArray.slice(0, 12);
48
+ return truncatedHashArray;
49
+ }
50
+ async function generateECDHKeyPair() {
51
+ const secp256k1 = await Promise.resolve().then(() => __importStar(require('@noble/secp256k1')));
52
+ const privKey = secp256k1.utils.randomPrivateKey();
53
+ const pubKey = secp256k1.getPublicKey(privKey);
54
+ return {
55
+ privateKey: privKey,
56
+ publicKey: pubKey,
57
+ };
58
+ }
59
+ async function getSharedSecret(privateKey, publicKey) {
60
+ const secp256k1 = await Promise.resolve().then(() => __importStar(require('@noble/secp256k1')));
61
+ const sharedSecret = secp256k1.getSharedSecret(privateKey, publicKey);
62
+ return sharedSecret.slice(0, 32);
63
+ }
64
+ async function encrypt(message, sharedSecret, topic) {
65
+ // Nonce must be 12 bytes
66
+ const nonce = await sha256Truncate(topic);
67
+ const aes = (0, aes_1.gcm)(sharedSecret, nonce);
68
+ const data = (0, utils_1.utf8ToBytes)(message);
69
+ const ciphertext = aes.encrypt(data);
70
+ return ciphertext;
71
+ }
72
+ async function decrypt(ciphertext, sharedSecret, topic) {
73
+ // Nonce must be 12 bytes
74
+ const nonce = await sha256Truncate(topic);
75
+ const aes = (0, aes_1.gcm)(sharedSecret, nonce);
76
+ const data = aes.decrypt(ciphertext);
77
+ const dataString = new TextDecoder().decode(data);
78
+ return dataString;
79
+ }
@@ -0,0 +1,191 @@
1
+ import { type DisclosableIDCredential, type IDCredential, type IDCredentialValue, type NumericalIDCredential, type ProofResult, type QueryResult } from '@zkpassport/utils';
2
+ export type * from '@zkpassport/utils';
3
+ export { SANCTIONED_COUNTRIES, EU_COUNTRIES, EEA_COUNTRIES, SCHENGEN_COUNTRIES, ASEAN_COUNTRIES, MERCOSUR_COUNTRIES, } from '@zkpassport/utils';
4
+ export type QueryBuilderResult = {
5
+ /**
6
+ * The URL of the request.
7
+ *
8
+ * You can either encode the URL in a QR code or let the user click the link
9
+ * to this URL on your website if they're visiting your website on their phone.
10
+ */
11
+ url: string;
12
+ /**
13
+ * The id of the request.
14
+ */
15
+ requestId: string;
16
+ /**
17
+ * Called when the user has scanned the QR code or clicked the link to the request.
18
+ *
19
+ * This means the user is currently viewing the request popup with your website information
20
+ * and the information requested from them.
21
+ */
22
+ onRequestReceived: (callback: () => void) => void;
23
+ /**
24
+ * Called when the user has accepted the request and
25
+ * started to generate the proof on their phone.
26
+ */
27
+ onGeneratingProof: (callback: () => void) => void;
28
+ /**
29
+ * Called when the SDK successfully connects to the bridge with the mobile app.
30
+ */
31
+ onBridgeConnect: (callback: () => void) => void;
32
+ /**
33
+ * Called when the user has generated a proof.
34
+ *
35
+ * There is a minimum of 4 proofs, but there can be more depending
36
+ * on the type of information requested from the user.
37
+ */
38
+ onProofGenerated: (callback: (proof: ProofResult) => void) => void;
39
+ /**
40
+ * Called when the user has sent the query result.
41
+ *
42
+ * The response contains the unique identifier associated to the user,
43
+ * your domain name and chosen scope, along with the query result and whether
44
+ * the proofs were successfully verified.
45
+ */
46
+ onResult: (callback: (response: {
47
+ uniqueIdentifier: string | undefined;
48
+ verified: boolean;
49
+ result: QueryResult;
50
+ }) => void) => void;
51
+ /**
52
+ * Called when the user has rejected the request.
53
+ */
54
+ onReject: (callback: () => void) => void;
55
+ /**
56
+ * Called when an error occurs, such as one of the requirements not being met
57
+ * or a proof failing to be generated.
58
+ */
59
+ onError: (callback: (error: string) => void) => void;
60
+ /**
61
+ * @returns true if the bridge with the mobile app is connected
62
+ */
63
+ isBridgeConnected: () => boolean;
64
+ /**
65
+ * Get if the user has scanned the QR code or the link to this request
66
+ * @returns true if the request has been received by the user on their phone
67
+ */
68
+ requestReceived: () => boolean;
69
+ };
70
+ export type QueryBuilder = {
71
+ /**
72
+ * Requires this attribute to be equal to the provided value.
73
+ * @param key The attribute to compare.
74
+ * @param value The value of the attribute you require.
75
+ */
76
+ eq: <T extends IDCredential>(key: T, value: IDCredentialValue<T>) => QueryBuilder;
77
+ /**
78
+ * Requires this attribute to be greater than or equal to the provided value.
79
+ * @param key The attribute to compare.
80
+ * @param value The value of the attribute you require.
81
+ */
82
+ gte: <T extends NumericalIDCredential>(key: T, value: IDCredentialValue<T>) => QueryBuilder;
83
+ /**
84
+ * Requires this attribute to be less than or equal to the provided value.
85
+ * @param key The attribute to compare.
86
+ * @param value The value of the attribute you require.
87
+ */
88
+ lte: <T extends 'birthdate' | 'expiry_date'>(key: T, value: IDCredentialValue<T>) => QueryBuilder;
89
+ /**
90
+ * Requires this attribute to be less than the provided value.
91
+ * @param key The attribute to compare.
92
+ * @param value The value of the attribute you require.
93
+ */
94
+ lt: <T extends 'age'>(key: T, value: IDCredentialValue<T>) => QueryBuilder;
95
+ /**
96
+ * Requires this attribute to be included in the provided range.
97
+ * @param key The attribute to compare.
98
+ * @param start The start of the range.
99
+ * @param end The end of the range.
100
+ */
101
+ range: <T extends NumericalIDCredential>(key: T, start: IDCredentialValue<T>, end: IDCredentialValue<T>) => QueryBuilder;
102
+ /**
103
+ * Requires this attribute to be included in the provided list.
104
+ * @param key The attribute to compare.
105
+ * @param value The list of values to check inclusion against.
106
+ */
107
+ in: <T extends 'nationality'>(key: T, value: IDCredentialValue<T>[]) => QueryBuilder;
108
+ /**
109
+ * Requires this attribute to be excluded from the provided list.
110
+ * @param key The attribute to compare.
111
+ * @param value The list of values to check exclusion against.
112
+ */
113
+ out: <T extends 'nationality'>(key: T, value: IDCredentialValue<T>[]) => QueryBuilder;
114
+ /**
115
+ * Requires this attribute to be disclosed.
116
+ * @param key The attribute to disclose.
117
+ */
118
+ disclose: (key: DisclosableIDCredential) => QueryBuilder;
119
+ /**
120
+ * Builds the request.
121
+ *
122
+ * This will return the URL of the request, which you can either encode in a QR code
123
+ * or provide as a link to the user if they're visiting your website on their phone.
124
+ * It also returns all the callbacks you can use to handle the user's response.
125
+ */
126
+ done: () => QueryBuilderResult;
127
+ };
128
+ export declare class ZKPassport {
129
+ private domain;
130
+ private topicToConfig;
131
+ private topicToKeyPair;
132
+ private topicToWebSocketClient;
133
+ private topicToSharedSecret;
134
+ private topicToRequestReceived;
135
+ private topicToService;
136
+ private topicToProofs;
137
+ private onRequestReceivedCallbacks;
138
+ private onGeneratingProofCallbacks;
139
+ private onBridgeConnectCallbacks;
140
+ private onProofGeneratedCallbacks;
141
+ private onResultCallbacks;
142
+ private onRejectCallbacks;
143
+ private onErrorCallbacks;
144
+ constructor(_domain?: string);
145
+ /**
146
+ * @notice Handle an encrypted message.
147
+ * @param request The request.
148
+ * @param outerRequest The outer request.
149
+ */
150
+ private handleEncryptedMessage;
151
+ private getZkPassportRequest;
152
+ /**
153
+ * @notice Create a new request.
154
+ * @returns The query builder object.
155
+ */
156
+ request({ name, logo, purpose, scope, topicOverride, keyPairOverride, }: {
157
+ name: string;
158
+ logo: string;
159
+ purpose: string;
160
+ scope?: string;
161
+ topicOverride?: string;
162
+ keyPairOverride?: {
163
+ privateKey: Uint8Array;
164
+ publicKey: Uint8Array;
165
+ };
166
+ }): Promise<QueryBuilder>;
167
+ private checkPublicInputs;
168
+ /**
169
+ * @notice Verify the proofs received from the mobile app.
170
+ * @param requestId The request ID.
171
+ * @param proofs The proofs to verify.
172
+ * @param queryResult The query result to verify against
173
+ * @returns An object containing the unique identifier associated to the user
174
+ * and a boolean indicating whether the proofs were successfully verified.
175
+ */
176
+ verify(requestId: string, proofs?: Array<ProofResult>, queryResult?: QueryResult): Promise<{
177
+ uniqueIdentifier: string | undefined;
178
+ verified: boolean;
179
+ }>;
180
+ /**
181
+ * @notice Returns the URL of the request.
182
+ * @param requestId The request ID.
183
+ * @returns The URL of the request.
184
+ */
185
+ getUrl(requestId: string): string;
186
+ /**
187
+ * @notice Cancels a request by closing the WebSocket connection and deleting the associated data.
188
+ * @param requestId The request ID.
189
+ */
190
+ cancelRequest(requestId: string): void;
191
+ }