UNPKG

@welshare/react

Version:

React library for integrating with Welshare's sovereign data sharing platform

169 lines (122 loc) 7.98 kB
# @welshare/react ### Disclaimer, notes on maturity This library is in Alpha / demo state at this moment. We're using it to review the security aspects while data is in transfer and in rest. There's absolutely no guarantee or warrant that at this point any data is safe. All data can be lost at any time - even though we're using resources that puts decentralization and resilience values to the front. Be **very** careful if you're integrating this into user facing code. Welshare Health wallets are controlled by cryptographic material which _can_ be stored in non custodial / MPC environments (Privy). While that's considered very safe, we can't guarantee at this point that we've already got each aspect of inter application communication or key derivation features right, so don't connect wallets that store significant value with the welshare wallet yet. ## Purpose This is a React library that helps integrating with Welshare's sovereign data sharing platform. This package provides React hooks and components to connect applications with Welshare's wallet for secure data submission. ## Installation ```bash npm install @welshare/react # or yarn add @welshare/react # or pnpm add @welshare/react ``` ## Peer Dependencies This package requires React 19+ as a peer dependency. ## Prerequisites You need to register an app identifier using the Welshare Wallet frontend first: https://wallet.welshare.app/application. We're referring to this as `your-application-id` from here on. If you want to submit questionnaire data, your application must first register a new questionnaire definition. You can also reuse an existing questionnaire id to let users contribute responses to another app's questionaire, but that's not highly encouraged at this point. ## Data Submissions At the moment there are only two supported submission types: Fhir compatible QuestionnaireResponses and our custom "Reflex" app submissions. Both types are identified by schema uids that are accessible on the `Schemas` export. ``` export const Schemas = { QuestionnaireResponse: "b14b538f-7de3-4767-ad77-464d755d78bd" }; ``` To submit questionnaires using custom frontends, you'll use the `useWelshare` hook to open a wallet dialog that lets your application talk to the user's connected wallets (using derived storage keys). All communication with the Welshare infrastructure happens inside that browser window. ## Code Sample ```tsx import { ConnectWelshareButton, Schemas, useWelshare } from "@welshare/react"; export function QuestionnaireForm() { const { isConnected, openWallet, submitData } = useWelshare({ applicationId: <your-application-id>, environment: "development", //optional, at the moment the environment is always development callbacks: { onUploaded: (payload) => console.log('Data uploaded:', payload), onError: (error) => console.error('Error:', error), onSessionReady: (storageKey) => console.log('Session ready:', storageKey), } }); const handleSubmit = () => { //response is a QuestionnaireResponse compatible object submitData(Schemas.QuestionnaireResponse, response); }; // using the `ConnectWelshareButton` is not mandatory. Use your own buttons if you feel like it. return ( <div> {!isConnected ? ( <ConnectWelshareButton openWallet={openWallet}> Connect to Welshare </ConnectWelshareButton> ) : ( <form> {/* ... some form that collects your response data ... */} <button onClick={() => handleSubmit(response)} disabled={isSubmitting}> {isSubmitting ? 'Submitting...' : 'Submit Data'} </button> </form> )} </div> ); } ``` ### Binary file uploads (e.g. images) binary file uploads require a lot of back and forth with the wallet dialog that we wrapped into one convenient upload API. If you want to include binary uploads into your questionnaires, you would typically hook into your own form, upload the file using the `uploadFile` function exposed by the `useWelshare` hook and use the response information to in the respective questionnaire form answer item. Each download should contain a reference to the resource that initiated its upload. As Welshare right now is mostly about questionnaires, you should use a combination of the resource type (questionnaire), the questionnaire id and the answer item's id ```ts const reference = `questionnaire/${questionnaireId}/${answerItemId}`; ``` Binary files are addressed as items of type `valueAttachment` in Fhir. See https://www.hl7.org/fhir/questionnaireresponse.html Before uploading, welshare encrypts all files with a new random symmetric AES (GCM / 256 bits) key. Users request a presigned upload url and post the encrypted file to an S3 compatible API of ours. Finally, they encrypt the encryption key on a user controlled Nillion *owned* collection for binary data and grant respective access rights for the application. The application a user used to upload the file is by default able to download the file again (Technically, that application is always welshare right now. This will change to the "builder" address of the respective app and the hpmp enclave keys, which allow AI access to the files) Here's an example how to use it: ```ts const { isConnected, openWallet, uploadFile, submitData } = useWelshare({ applicationId: process.env.NEXT_PUBLIC_WELSHARE_APP_ID || "" }) //... let users select a file on their box const { url: uploadedFileUrl, binaryFileUid } = await uploadFile( userFile, reference: `questionnaire/${questionnaireId}/<linkId>` ); const responseItem = { answer = [ { valueAttachment: { id: binaryFileUid, contentType: userFile.type, size: userFile.size, title: userFile.name, url: uploadedFileUrl, }, }, ]; } // insert the responseItem into your QuestionnaireResponse ``` ## API ### supported callbacks those are configured in the `useWelshare` options parameter and called back during interactions with the wallet dialog ```tsx callbacks: { onUploaded?: (payload: SubmissionPayload<unknown>) => void; onError?: (error: string) => void; onSessionReady?: (sessionPubKey: string) => void; onDialogClosing?: () => void; onDialogReady?: () => void; onFileUploaded?: (insertedUid: string, url: string) => void } ``` ## Security Notes No part of this application deals with a "blockchain" directly (Nillion nodes are validated by a custom chain but that's not a fact relevant for end users' security in this scope). The EVM addresses that control a user profile are (supposedly) never leaked to a third party. The key derivation mechanism that creates new storage keys that users use to sign messages is not guaranteed to be 100% sound. At this moment it's used as a cryptographic authenticator, but the derivation mechanism will change in the future, rendering already existing keys obsolete. We're not guaranteeing that your key material stays trivially derivable. Data is stored on [nilDB (by Nillion)](https://docs.nillion.com/build/private-storage/quickstart), a system that can enforces access control, encryption at rest and storage redundancy. While technically possible, the current library does not MPC-encrypt any information. The data is sent to nilDB by a _user client_ that's controlled by the user's own key material. Welshare only delegates NUCs (access rights) to the users. Right now the welshare builder _can_ read any data users upload. This concept will eventually change - welshare's goal is to only make user originated information available inside trusted execution environments. ## Development This package is built using: - TypeScript - Tshy for build management - Vitest for testing ## License MIT. See the [LICENSE](LICENSE) file for details. ## Contact Get in touch on Telegram. Check https://welshare.health