@yourself_id/siwys-api-js 0.0.15-sapp-118-documentation.0 → 0.0.15

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 (2) hide show
  1. package/package.json +2 -2
  2. package/README.md +0 -522
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yourself_id/siwys-api-js",
3
- "version": "0.0.15-sapp-118-documentation.0+c67697f",
3
+ "version": "0.0.15",
4
4
  "description": "A React component library",
5
5
  "repository": "https://github.com/selfidhq/siwys-js",
6
6
  "main": "dist/index.js",
@@ -35,5 +35,5 @@
35
35
  "tsup": "^8.3.0",
36
36
  "typescript": "4.9.4"
37
37
  },
38
- "gitHead": "c67697fc65379095623304473e512803079cb7ee"
38
+ "gitHead": "cacce959c0608638911c00d3b72d8cd305e8a519"
39
39
  }
package/README.md DELETED
@@ -1,522 +0,0 @@
1
- # Sign in with your SELF API SDK
2
-
3
- Sign in with your SELF (SIWYS) is a SELF product that allows users to authenticate with partner apps/dapps using their own private keys and credentials and the MDIP protocol.
4
-
5
- This SDK is designed to facilitate the ability to integrate Keymaster functionality into an existing NodeJS web service or to communicate with an existing external Keymaster service.
6
-
7
- Please refer to the partner integration guide for more information regarding SIWYS.
8
-
9
- # Install
10
-
11
- ```
12
- npm install @yourself_id/siwys-api-js
13
- ```
14
- or
15
- ```
16
- yarn add @yourself_id/siwys-api-js
17
- ```
18
-
19
- # Initialize Keymaster
20
-
21
- Initializing the Keymaster client depends on your use case, Integrated vs External Keymaster.
22
-
23
- ## Integrated Keymaster
24
-
25
- Integrated Keymaster requires integrating Keymaster functionality into your existing server. To acheive this you will need to communicate to an existing Gatekeeper service and provide the necessary configuration for managing your digital Wallet.
26
-
27
- Initializing a Keymaster client is as easy as creating a class instance of `Keymaster`
28
-
29
- ```js
30
- import { Keymaster } from "@yourself_id/siwys-api-js";
31
-
32
-
33
- new Keymaster({
34
- gatekeeperConfig: {
35
- url: "https://gatekeeper-url",
36
- chatty: true,
37
- waitUntilReady: true,
38
- intervalSeconds: 5
39
- },
40
- walletConfig: {
41
- id: "my-wallet",
42
- mnemonic: "red orange yellow green blue indigo violet pink white black brown grey",
43
- registry: "TFTC"
44
- },
45
- walletDb: {
46
- loadWallet,
47
- saveWallet
48
- },
49
- })
50
- ```
51
-
52
- The following are the configuration options for the `Keymaster` client:
53
-
54
- |Parameter|Type|Description|Required|Default|
55
- |--|-|-|-|-|
56
- |gatekeeperConfig.url|string|URL of the external Gatekeeper service|Yes||
57
- |gatekeeperConfig.chatty|boolean|Control the log "noisyness"|No|false|
58
- |gatekeeperConfig.waitUntilReady|boolean|Whether or not to wait for the Gatekeeper service to become operational|No|false|
59
- |gatekeeperConfig.intervalSeconds|number|How often to poll for readyness|No|5|
60
- |walletConfig.id|string|Human-friendly alias for the digital wallet|Yes||
61
- |walletConfig.mnemonic|string|User-supplied mnemonic device used during wallet creation|No|Auto-generated|
62
- |walletConfig.registry|string|Registry to use for transactions, one of "hyperswarm", "TBTC", or "TFTC"|No|TFTC|
63
- |walletDb.loadWallet|func|Callback for loading the wallet.<br/><br/>Must return a `Promise<Wallet \| null>`|Yes||
64
- |walletDb.saveWallet|func|Callback for saving the wallet.<br/><br/>Accepts two parameters:<br/>1. The Wallet payload as an object<br/>2. Boolean flag indicating whether to overwrite the exsiting wallet<br/><br/>Must return a `Promise<boolean>`|Yes||
65
-
66
- ### Wallet DB Callbacks
67
-
68
- A necessary part of running your server as an Integrate Keymaster is that you will be responsible for managing your digital Wallet. Consequently,
69
- you must provide the methods for loading and saving the wallet.
70
-
71
- The following are minimal examples for achieving this:
72
-
73
- Save to the file system
74
- ```js
75
- import fs from "fs";
76
-
77
- import type { Wallet } from "@yourself_id/siwys-api-js";
78
-
79
- const dataFolder = "data"
80
- const walletName = `${dataFolder}/wallet.json`
81
-
82
- async function loadWallet(): Promise<Wallet | null> {
83
- if (fs.existsSync(walletName)) {
84
- const walletJson = fs.readFileSync(walletName);
85
- return JSON.parse(walletJson.toString());
86
- }
87
-
88
- return null;
89
- }
90
-
91
- async function saveWallet(wallet: Wallet, overwrite: booelan = false): Promise<boolean> {
92
- try {
93
- if (fs.existsSync(walletName) && !overwrite) {
94
- return true;
95
- }
96
-
97
- if (!fs.existsSync(dataFolder)) {
98
- fs.mkdirSync(dataFolder, { recursive: true });
99
- }
100
-
101
- fs.writeFileSync(walletName, JSON.stringify(wallet, null, 4));
102
- return true;
103
- } catch (e) {
104
- return false;
105
- }
106
- }
107
- ```
108
-
109
- Save to Firestore
110
- ```js
111
- import fs from "fs";
112
-
113
- import { collection, doc, getDoc, getFirestore, setDoc } from "firebase/firestore";
114
-
115
- import type { Wallet } from "@yourself_id/siwys-api-js";
116
-
117
- const walletCollection = "wallet"
118
- const walletName = "server-wallet"
119
-
120
- async function loadWallet(): Promise<Wallet | null> {
121
- const walletDoc = await getDoc(doc(db, walletCollection, walletName));
122
-
123
- if (walletDoc.exists()) {
124
- return walletDoc.data() as Wallet;
125
- }
126
-
127
- return null;
128
- }
129
-
130
- async function saveWallet(wallet: Wallet, overwrite: booelan = false): Promise<boolean> {
131
- try {
132
- const walletDoc = await getDoc(doc(db, walletCollection, walletName));
133
-
134
- const walletExists = walletDoc.exists();
135
- if (walletExists && !overwrite) {
136
- return true
137
- }
138
-
139
- await setDoc(doc(collection(db, walletCollection), walletName), wallet);
140
- return true;
141
- } catch (e) {
142
- // handle error
143
- return false;
144
- }
145
- }
146
- ```
147
-
148
- > [!IMPORTANT]
149
- > The `seed` key of the wallet contains sensitive data regarding your Wallet. Please consider this when deciding on the appropriate wallet storage mechanism. The following is an updated example of omitting the seed data when persisting to Firestore.
150
-
151
- ```js
152
- import fs from "fs";
153
-
154
- import { collection, doc, getDoc, getFirestore, setDoc } from "firebase/firestore";
155
-
156
- import type { Wallet, WalletSeed } from "@yourself_id/siwys-api-js";
157
-
158
- const walletCollection = "wallet"
159
- const walletName = "server-wallet"
160
-
161
- async function getSeedFromSecretManager(): Promise<WalletSeed> {
162
- // implement your Secret Manager fetching logic
163
- }
164
-
165
- async function saveSeedToSecretManager(seed: WalletSeed): Promise<void> {
166
- const existingSeed = await getSeedFromSecretManager();
167
- if (existingSeed) {
168
- return existingSeed;
169
- } else {
170
- // implement your Secret Manager saving logic
171
- }
172
- return;
173
- }
174
-
175
- async function loadWallet(): Promise<Wallet | null> {
176
- const walletDoc = await getDoc(doc(db, walletCollection, walletName));
177
-
178
- if (walletDoc.exists()) {
179
- const walletData = walletDoc.data() as Wallet;
180
- const seedData = await getSeedFromSecretManager();
181
- const wallet: Wallet = {
182
- ...walletData,
183
- ...seedData
184
- };
185
- return wallet;
186
- }
187
-
188
- return null;
189
- }
190
-
191
- async function saveWallet(wallet: Wallet, overwrite: booelan = false): Promise<boolean> {
192
- try {
193
- const walletDoc = await getDoc(doc(db, walletCollection, walletName));
194
-
195
- const walletExists = walletDoc.exists();
196
- if (walletExists && !overwrite) {
197
- return true
198
- }
199
-
200
- const { seed, ...rest } = wallet;
201
-
202
- // save the seed in Secret Manager
203
- await saveSeedToSecretManager(seed);
204
- // save the rest of the Wallet in Firestore
205
- await setDoc(doc(collection(db, walletCollection), walletName), rest);
206
- return true;
207
- } catch (e) {
208
- // handle error
209
- return false;
210
- }
211
- }
212
- ```
213
-
214
-
215
- ## External Keymaster
216
-
217
- If you want your server to simply communicate with an existing, external Keymaster you just need to provide the Keymaster config.
218
-
219
- ```js
220
- import { Keymaster } from "@yourself_id/siwys-api-js";
221
-
222
-
223
- new Keymaster({
224
- keymasterConfig: {
225
- url: "https://keymaster-url",
226
- chatty: true,
227
- waitUntilReady: true,
228
- intervalSeconds: 5
229
- },
230
- })
231
- ```
232
-
233
- The following are the configuration options for the `Keymaster` client:
234
-
235
-
236
- |Parameter|Type|Description|Required|Default|
237
- |--|-|-|-|-|
238
- |keymasterConfig.url|string|URL of the external Keymaster service|Yes||
239
- |keymasterConfig.chatty|boolean|Control the log "noisyness"|No|false|
240
- |keymasterConfig.waitUntilReady|boolean|Whether or not to wait for the Keymaster service to become operational|No|false|
241
- |keymasterConfig.intervalSeconds|number|How often to poll for readyness|No|5|
242
-
243
-
244
- # Starting Keymaster
245
-
246
- The Keymaster client must be manually started once it has been configured.
247
-
248
- The easiest way to do this is to start it when your server starts up.
249
-
250
- ```js
251
-
252
- import express from "express";
253
- import { Keymaster, KeymasterConfig } from "@yourself_id/siwys-api-js";
254
-
255
- const app = express();
256
-
257
- app.listen(8080, () => {
258
- const config: KeymasterConfig = {}
259
- const keymaster = new Keymaster(config).start()
260
- });
261
- ```
262
-
263
- You can keep a global reference for easy use where you need it
264
- ```js
265
- import { Keymaster, KeymasterConfig } from "@yourself_id/siwys-api-js";
266
-
267
- let keymaster: Keymaster;
268
- async startKeymaster () => {
269
- const config: KeymasterConfig = {}
270
- keymaster = new Keymaster(config)
271
- await keymaster.start()
272
- return keymaster
273
- }
274
- startKeymaster()
275
- ```
276
-
277
- # Add SIWYS API Endpoints
278
-
279
- The SIWYS workflow is as follows:
280
- 1. User clicks the SIWYS button and a challenge is rendered via a QR code
281
- 2. The user completes the challenge via scanning the QR code in their SELF mobile app
282
- 3. The mobile app executes the specified callback function for the challenge on a successful scan
283
- 4. Optionally, the UI can poll for challenge completion and perform the appropriate steps once complete
284
-
285
- You need to add the following endpoints to help facilitate this workflow
286
-
287
- ### Create Challenge
288
-
289
- Endpoint to create and return a Challenge
290
-
291
- ```js
292
- app.post("/challenges", async (_, res) => {
293
- // callbackUrl should be the endpoint defined in Step 3 (above)
294
-
295
- const callbackUrl = "http://your-server-url/auth";
296
- // use the keymaster service you started earlier
297
- const challenge = await keymaster.createChallenge({
298
- callback: callbackUrl,
299
- });
300
-
301
- res.json(challenge);
302
- });
303
- ```
304
-
305
- ### Accept Challenge Callback
306
- The endpoint the SELF app will hit to signify a completed Challenge
307
-
308
- > [!IMPORTANT]
309
- > This endpoint **MUST** be publicly accessbile as the callback will be executed from the SELF mobile app on the user's device.
310
-
311
- ```js
312
- import { collection, doc, setDoc } from "firebase/firestore";
313
- import { VerifyResponseResponse } from "@yourself_id/siwys-api-js"
314
-
315
- app.post("/auth", async (req, res) => {
316
- // parse the response from the request body
317
- const { response } = req.body;
318
-
319
- // verify the response
320
- const verified: VerifyResponseResponse = await keymaster.verifyResponse(response);
321
-
322
- if (verified.match) {
323
- /**
324
- * match = authentication is successful
325
- *
326
- * You should implement the necessary DB logic here for caching this
327
- * "user login session". A "user login session" can be represented by the
328
- * challenge DID that was generated paired with the responding user's agent DID
329
- * who completed the challenge.
330
- *
331
- * The `verified` response contains a "responder" field that
332
- * represents the user's agent DID. This is the uniquely
333
- * identifying ID for the user.
334
- *
335
- * A minimal example has been included below that will
336
- * cache the challenge and create the user in Firestore.
337
- */
338
- const challengeId = verified.challenge
339
- const userId = verified.responder
340
-
341
- // cache challenge
342
- await setDoc(doc(collection(db, "challenges"), challengeId), verified);
343
- console.log("Created challenge document with ID", userId);
344
-
345
- // create user
346
- await setDoc(doc(collection(db, "users"), userId), verified);
347
- console.log("Created user document with ID", userId);
348
- }
349
-
350
- res.sendStatus(204);
351
- });
352
- ```
353
-
354
- ### Poll for Challenge Complete
355
-
356
- Optionally, you can configure the SIWYS React component to poll for a completed challenge by specifying the polling URL.
357
-
358
- If you omit this, you will need to implement the challenge completion logic yourself. For example, you could push a message via WebSocket to the front-end when the challenge has been completed during the callback (above).
359
-
360
- > [!IMPORTANT]
361
- > The polling logic in the React component will pass the Challenge DID via a query parameter.
362
-
363
- ```js
364
- import { collection, doc, getDoc } from "firebase/firestore";
365
-
366
- app.get("/auth", async (req, res) => {
367
- // parse the challenge from the query string
368
- const challengeId = req.query.challenge;
369
- if (!challengeId || typeof challengeId !== "string") {
370
- return res.sendStatus(400);
371
- }
372
-
373
- /**
374
- * You should implement the necessary DB logic here for looking up
375
- * an active "user login session". You can refernce the cached challenge
376
- * created in the callback endpoint from above.
377
- *
378
- * A minimal example has been included below that will fetch the challenge
379
- * and user from Firestore.
380
- */
381
-
382
- const challengeDoc = await getDoc(doc(db, "challenges", challengeId));
383
- if (challengeDoc.exists()) {
384
- console.log("Found challenge document with ID", challengeId)
385
- const docData = challengeDoc.data()
386
- const userId = docData.responder
387
- const userDoc = await getDoc(doc(db, "users", userId));
388
-
389
- if (userDoc.exists()) {
390
- console.log("Found user document with ID", userId)
391
- const userData = userDoc.data()
392
- // you add any authentication logic here
393
- // eg create a cookie and return in result
394
- res.json(userData);
395
- }
396
- }
397
-
398
- res.sendStatus(404);
399
- });
400
-
401
- ```
402
-
403
- # Complete Example
404
-
405
- Below is a complete, minimal example using Express and Firestore.
406
- ```js
407
- import express from "express"
408
- import { collection, doc, getDoc, getFirestore, setDoc } from "firebase/firestore";
409
- import { Keymaster, Wallet } from "@yourself_id/siwys-api-js";
410
-
411
-
412
- const app = express();
413
- const db = getFirestore() // firestore init logic
414
-
415
- const walletCollection = "wallet"
416
- const walletName = "server-wallet"
417
-
418
- async function loadWallet(): Promise<Wallet | null> {
419
- const walletDoc = await getDoc(doc(db, walletCollection, walletName));
420
-
421
- if (walletDoc.exists()) {
422
- return walletDoc.data() as Wallet;
423
- }
424
-
425
- return null;
426
- }
427
-
428
- async function saveWallet(wallet: Wallet, overwrite: booelan = false): Promise<boolean> {
429
- try {
430
- const walletDoc = await getDoc(doc(db, walletCollection, walletName));
431
-
432
- const walletExists = walletDoc.exists();
433
- if (walletExists && !overwrite) {
434
- return true
435
- }
436
-
437
- await setDoc(doc(collection(db, walletCollection), walletName), wallet);
438
- return true;
439
- } catch (e) {
440
- // handle error
441
- return false;
442
- }
443
- }
444
-
445
- let keymaster: Keymaster; // global ref
446
- async () => {
447
- keymaster = new Keymaster({
448
- gatekeeperConfig: {
449
- url: "https://gatekeeper-url",
450
- waitUntilReady: true,
451
- },
452
- walletConfig: {
453
- id: "my-wallet"
454
- },
455
- walletDb: {
456
- loadWallet,
457
- saveWallet
458
- }
459
- });
460
- await keymaster.start();
461
- return keymaster;
462
- }
463
-
464
-
465
-
466
- app.post("/challenges", async (_, res) => {
467
- const callbackUrl = "http://your-server-url/auth";
468
- const challenge = await keymaster.createChallenge({
469
- callback: callbackUrl,
470
- });
471
-
472
- res.json(challenge);
473
- });
474
-
475
- app.get("/auth", async (req, res) => {
476
- const challengeId = req.query.challenge;
477
- if (!challengeId || typeof challengeId !== "string") {
478
- return res.sendStatus(400);
479
- }
480
-
481
- const challengeDoc = await getDoc(doc(db, "challenges", challengeId));
482
- if (challengeDoc.exists()) {
483
- console.log("Found challenge document with ID", challengeId)
484
- const docData = challengeDoc.data()
485
- const userId = docData.responder
486
- const userDoc = await getDoc(doc(db, "users", userId));
487
-
488
- if (userDoc.exists()) {
489
- console.log("Found user document with ID", userId)
490
- const userData = userDoc.data()
491
- // authenticate session and return
492
- res.json(userData);
493
- }
494
- }
495
-
496
- res.sendStatus(404);
497
- });
498
-
499
- app.post("/auth", async (req, res) => {
500
- const { response } = req.body;
501
- const verified = await keymaster.verifyResponse(response);
502
-
503
- if (verified.match) {
504
- const challengeId = verified.challenge
505
- const userId = verified.responder
506
-
507
- // cache challenge
508
- await setDoc(doc(collection(db, "challenges"), challengeId), verified);
509
- console.log("Created challenge document with ID", userId);
510
-
511
- // create user
512
- await setDoc(doc(collection(db, "users"), userId), verified);
513
- console.log("Created user document with ID", userId);
514
- }
515
-
516
- res.sendStatus(204);
517
- });
518
-
519
- app.listen(8080, async () => {
520
- console.log(`Server listening on port ${8080}`);
521
- });
522
- ```