Skip to content

Commit

Permalink
Merge branch 'main' of github.com:idos-network/idos-sdk-js into refac…
Browse files Browse the repository at this point in the history
…tor/kwill-calls-renamings
  • Loading branch information
pkoch committed Dec 17, 2024
2 parents 1231fb7 + e28b231 commit 776c575
Show file tree
Hide file tree
Showing 46 changed files with 752 additions and 868 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/pkg.pr.new.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ jobs:
run: pnpm install

- name: Build
run: pnpm build --filter=@idos-network/issuer-sdk-js --filter=@idos-network/idos-sdk --filter=@idos-network/idos-sdk-server-dapp
run: pnpm build --filter=@idos-network/issuer-sdk-js --filter=@idos-network/idos-sdk --filter=@idos-network/grantee-sdk-js

- name: Release
run: pnpx pkg-pr-new publish --pnpm './packages/issuer-sdk-js' './packages/idos-sdk-js' './packages/idos-sdk-server-dapp'
run: pnpx pkg-pr-new publish --pnpm './packages/issuer-sdk-js' './packages/idos-sdk-js' './packages/grantee-sdk-js'

20 changes: 12 additions & 8 deletions apps/idos-enclave/src/lib/enclave.js
Original file line number Diff line number Diff line change
Expand Up @@ -125,12 +125,13 @@ export class Enclave {
try {
if (storedCredentialId) {
({ password, credentialId } = await getWebAuthnCredential(storedCredentialId));
} else if (preferredAuthMethod) {
({ password, duration } = await this.#openDialog(preferredAuthMethod));
} else {
({ password, duration, credentialId } = await this.#openDialog("auth", {
expectedUserEncryptionPublicKey: this.expectedUserEncryptionPublicKey,
}));
({ password, duration, credentialId } = await this.#openDialog(
preferredAuthMethod || "auth",
{
expectedUserEncryptionPublicKey: this.expectedUserEncryptionPublicKey,
},
));
}
} catch (e) {
return reject(e);
Expand Down Expand Up @@ -171,7 +172,8 @@ export class Enclave {

encrypt(message, receiverPublicKey = this.keyPair.publicKey) {
const nonce = nacl.randomBytes(nacl.box.nonceLength);
const encrypted = nacl.box(message, nonce, receiverPublicKey, this.keyPair.secretKey);
const ephemeralKeyPair = nacl.box.keyPair();
const encrypted = nacl.box(message, nonce, receiverPublicKey, ephemeralKeyPair.secretKey);

if (encrypted === null)
throw Error(
Expand All @@ -191,7 +193,7 @@ export class Enclave {
fullMessage.set(nonce, 0);
fullMessage.set(encrypted, nonce.length);

return fullMessage;
return { content: fullMessage, encryptorPublicKey: ephemeralKeyPair.publicKey };
}

async decrypt(fullMessage, senderPublicKey) {
Expand Down Expand Up @@ -364,7 +366,7 @@ export class Enclave {
const response = await this[requestName](...paramBuilder());
event.ports[0].postMessage({ result: response });
} catch (error) {
console.warn("catch", error);
console.error("catch", error);
event.ports[0].postMessage({ error });
} finally {
this.unlockButton.style.display = "none";
Expand Down Expand Up @@ -423,6 +425,8 @@ export class Enclave {
this.unlockButton.disabled = false;
this.confirmButton.disabled = false;
this.backupButton.disabled = false;
port1.close();
this.dialog.close();
return reject(error);
}

Expand Down
14 changes: 12 additions & 2 deletions apps/idos-enclave/src/pages/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export function App({ store, enclave }: AppProps) {
// Confirm options.
const [origin, setOrigin] = useState<string | null>(null);
const [message, setMessage] = useState<string | null>(null);
const [encryptionPublicKey, setEncryptionUserPublicKey] = useState<string | undefined>();
const [encryptionPublicKey, setEncryptionUserPublicKey] = useState<string>("");
const [humanId] = useState<string | null>(
new URLSearchParams(window.location.search).get("humanId"),
);
Expand All @@ -88,6 +88,11 @@ export function App({ store, enclave }: AppProps) {
}
}, [theme]);

useEffect(() => {
if (mode === "new" || !responsePort.current) return;
if (!encryptionPublicKey) onError("Can’t find a public encryption key for this user");
}, [mode, encryptionPublicKey, responsePort.current]);

const resetMethod = useCallback(() => setMethod(null), []);

/**
Expand All @@ -102,11 +107,11 @@ export function App({ store, enclave }: AppProps) {
throw new Error(`Unexpected request from parent: ${requestData.intent}`);

responsePort.current = ports[0];
setEncryptionUserPublicKey(requestData.message?.expectedUserEncryptionPublicKey);

switch (requestData.intent) {
case "auth":
setMethod(null);
setEncryptionUserPublicKey(event.data.message.expectedUserEncryptionPublicKey);
break;

case "passkey":
Expand Down Expand Up @@ -176,6 +181,11 @@ export function App({ store, enclave }: AppProps) {
mode,
};

useEffect(() => {
if (mode === "new" || !responsePort.current) return; // encryptionPublicKey is only set after responsePort is set
if (!encryptionPublicKey) onError("can't find a public encryption key for this user");
}, [mode, encryptionPublicKey, responsePort.current]);

if (confirm && message) {
return (
<Layout onHeaderClick={resetMethod}>
Expand Down
2 changes: 1 addition & 1 deletion examples/idos-backend-demo-app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
},
"dependencies": {
"@hono/node-server": "^1.12.0",
"@idos-network/idos-sdk-server-dapp": "workspace:*",
"@idos-network/grantee-sdk-js": "workspace:*",
"@idos-network/idos-sdk": "workspace:*",
"@idos-network/issuer-sdk-js": "workspace:*",
"ethers": "^6.13.4",
Expand Down
2 changes: 1 addition & 1 deletion examples/idos-backend-demo-app/src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { serve } from "@hono/node-server";
import { idOS } from "@idos-network/grantee-sdk-js";
import type { Grant } from "@idos-network/idos-sdk";
import { idOS } from "@idos-network/idos-sdk-server-dapp";
import { Hono } from "hono";
import type { FC } from "hono/jsx";
const app = new Hono();
Expand Down
2 changes: 1 addition & 1 deletion examples/idos-example-dapp/api/EVM.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { idOSGrantee } from "@idos-network/idos-sdk-server-dapp";
import { idOSGrantee } from "@idos-network/grantee-sdk-js";
import { ethers } from "ethers";

/* global crypto */
Expand Down
2 changes: 1 addition & 1 deletion examples/idos-example-dapp/api/NEAR.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { idOSGrantee } from "@idos-network/idos-sdk-server-dapp";
import { idOSGrantee } from "@idos-network/grantee-sdk-js";
import { KeyPair } from "near-api-js";

/* global crypto */
Expand Down
2 changes: 1 addition & 1 deletion examples/idos-example-dapp/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
},
"dependencies": {
"@idos-network/idos-sdk": "workspace:*",
"@idos-network/idos-sdk-server-dapp": "workspace:*",
"@idos-network/grantee-sdk-js": "workspace:*",
"@idos-network/idos-sdk-types": "workspace:*",
"@idos-network/issuer-sdk-js": "workspace:*",
"@kwilteam/kwil-js": "0.7.1",
Expand Down
121 changes: 66 additions & 55 deletions examples/idos-example-dapp/src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -204,64 +204,75 @@ const connectWallet = {

cache.set("credentials", credentials);

terminal.table(credentials, ["id", ...Object.keys(credentials[0].public_notes)], {
id: async (id) => {
const credential = await terminal
.detail()
.h1("inspect", `Credential # ${id}`)
.wait(
"awaiting signature",
cache.get(`credential_${id}`) || idos.data.get("credentials", id),
);
cache.set(`credential_${id}`, credential);

await terminal
.wait("verifying credential...", idOS.verifiableCredentials.verify(credential.content))
.then((_) => terminal.status("done", "Verified"))
.catch(terminal.error.bind(terminal));

terminal.h1("eyes", "Content").json(JSON.parse(credential.content));
terminal.br();

const buttonId = `acquire-access-grant-${id}`;
terminal.button(buttonId, "🔏 Acquire access grant", async () => {
terminal.removeButton(buttonId);

let timelock =
window.prompt(
"Please enter the grant timelock in seconds",
granteeInfo.lockTimeSpanSeconds,
) || granteeInfo.lockTimeSpanSeconds;

timelock = Number.isInteger(+timelock) ? +timelock : granteeInfo.lockTimeSpanSeconds;

const grantPromise = idos.grants.create(
"credentials",
id,
granteeInfo.grantee,
Math.floor(Date.now() / 1000) + timelock,
granteeInfo.encryptionPublicKey,
);

try {
const result = await terminal.wait("creating access grant...", grantPromise);
terminal.status("done", `Created access grant with dataId ${result.grant.dataId}`);
} catch (e) {
terminal.error(e);
return;
}

cache.set("grants", null);
terminal.br();
terminal.log("Press Restart to see the newly created access grant.");
const { id, ...fields } = JSON.parse(credentials[0].public_notes);

terminal.table(
credentials.map((credential) => {
return {
...credential,
...fields,
};
}),
["id", ...Object.keys(fields)],
{
id: async (id) => {
const credential = await terminal
.detail()
.h1("inspect", `Credential # ${id}`)
.wait(
"awaiting signature",
cache.get(`credential_${id}`) || idos.data.get("credentials", id),
);
cache.set(`credential_${id}`, credential);

await terminal
.wait("verifying credential...", idOS.verifiableCredentials.verify(credential.content))
.then((_) => terminal.status("done", "Verified"))
.catch(terminal.error.bind(terminal));

terminal.h1("eyes", "Content").json(JSON.parse(credential.content));
terminal.br();

chosenFlow.grants = true;
window.localStorage.setItem("chosen-flow", JSON.stringify(chosenFlow));
terminal.button(`restart-${id}`, "Restart", terminal.reloadPage);
});
const buttonId = `acquire-access-grant-${id}`;
terminal.button(buttonId, "🔏 Acquire access grant", async () => {
terminal.removeButton(buttonId);

let timelock =
window.prompt(
"Please enter the grant timelock in seconds",
granteeInfo.lockTimeSpanSeconds,
) || granteeInfo.lockTimeSpanSeconds;

timelock = Number.isInteger(+timelock) ? +timelock : granteeInfo.lockTimeSpanSeconds;

const grantPromise = idos.grants.create(
"credentials",
id,
granteeInfo.grantee,
Math.floor(Date.now() / 1000) + timelock,
granteeInfo.encryptionPublicKey,
);

try {
const result = await terminal.wait("creating access grant...", grantPromise);
terminal.status("done", `Created access grant with dataId ${result.grant.dataId}`);
} catch (e) {
terminal.error(e);
return;
}

cache.set("grants", null);
terminal.br();
terminal.log("Press Restart to see the newly created access grant.");
terminal.br();

chosenFlow.grants = true;
window.localStorage.setItem("chosen-flow", JSON.stringify(chosenFlow));
terminal.button(`restart-${id}`, "Restart", terminal.reloadPage);
});
},
},
});
);
}

if (chosenFlow.grants) {
Expand Down
2 changes: 1 addition & 1 deletion examples/issuer-sdk-demo/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
"lokijs": "^1.5.12",
"pino-pretty": "^10.3.1",
"postcss": "^8.4.47",
"supports-color": "^9.4.0",
"supports-color": "^8.1.1",
"tailwindcss": "^3.4.14",
"typescript": "^5.4.5",
"utf-8-validate": "^5.0.2"
Expand Down
1 change: 0 additions & 1 deletion examples/issuer-sdk-demo/src/issuer.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ export async function getIssuerConfig(): Promise<IssuerConfig> {

cachedIssuer = await createIssuerConfig({
nodeUrl: NODE_URL,
encryptionKeyPair: nacl.box.keyPair.fromSecretKey(decode(ENCRYPTION_SECRET_KEY)),
signingKeyPair: nacl.sign.keyPair.fromSecretKey(decode(SIGNING_SECRET_KEY)),
});

Expand Down
File renamed without changes.
3 changes: 3 additions & 0 deletions packages/codecs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# idOS codecs

A collection of codecs used by the idOS SDK.
10 changes: 10 additions & 0 deletions packages/codecs/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
export { decode as base64Decode } from "@stablelib/base64";
export { encode as base64Encode } from "@stablelib/base64";
export { writeUint16BE as binaryWriteUint16BE } from "@stablelib/binary";
export { concat as bytesConcat } from "@stablelib/bytes";
export { decode as hexDecode } from "@stablelib/hex";
export { encode as hexEncode } from "@stablelib/hex";
export { hash as sha256Hash } from "@stablelib/sha256";
export { decode as utf8Decode } from "@stablelib/utf8";
export { encode as utf8Encode } from "@stablelib/utf8";
export { serialize as borshSerialize } from "borsh";
19 changes: 19 additions & 0 deletions packages/codecs/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"name": "@idos-network/codecs",
"version": "0.0.1",
"description": "A collection of codecs used by the idOS SDK.",
"homepage": "https://idos.network",
"repository": "https://github.com/idos-network/idos-sdk-js",
"license": "MIT",
"type": "module",
"main": "index.ts",
"dependencies": {
"@stablelib/base64": "^1.0.1",
"@stablelib/binary": "^1.0.1",
"@stablelib/bytes": "^1.0.1",
"@stablelib/hex": "^2.0.0",
"@stablelib/sha256": "^1.0.1",
"@stablelib/utf8": "^1.0.1",
"borsh": "^1.0.0"
}
}
20 changes: 20 additions & 0 deletions packages/codecs/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"target": "ESNext",
"composite": true,
"lib": ["ESNext"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"baseUrl": "."
},
"include": ["./src/**/*.ts"]
}
File renamed without changes.
File renamed without changes.
21 changes: 21 additions & 0 deletions packages/grantee-sdk-js/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 idOS Network

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# idOS JavaScript SDK for server dApps.
# idOS Grantee JavaScript SDK.

[![NPM](https://img.shields.io/npm/v/@idos-network/idos-sdk?logo=npm)](https://www.npmjs.com/package/@idos-network/idos-sdk) ![License](https://img.shields.io/badge/license-MIT-blue?&logo=data:image/svg%2bxml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI2NHB4IiBoZWlnaHQ9IjY0cHgiIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjRkZGRkZGIiBzdHJva2Utd2lkdGg9IjIiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCI+PGcgaWQ9IlNWR1JlcG9fYmdDYXJyaWVyIiBzdHJva2Utd2lkdGg9IjAiPjwvZz48ZyBpZD0iU1ZHUmVwb190cmFjZXJDYXJyaWVyIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiPjwvZz48ZyBpZD0iU1ZHUmVwb19pY29uQ2FycmllciI+IDxwYXRoIGQ9Ik0xNiAxNmwzLTggMy4wMDEgOEE1LjAwMiA1LjAwMiAwIDAxMTYgMTZ6Ij48L3BhdGg+IDxwYXRoIGQ9Ik0yIDE2bDMtOCAzLjAwMSA4QTUuMDAyIDUuMDAyIDAgMDEyIDE2eiI+PC9wYXRoPiA8cGF0aCBkPSJNNyAyMWgxMCI+PC9wYXRoPiA8cGF0aCBkPSJNMTIgM3YxOCI+PC9wYXRoPiA8cGF0aCBkPSJNMyA3aDJjMiAwIDUtMSA3LTIgMiAxIDUgMiA3IDJoMiI+PC9wYXRoPiA8L2c+PC9zdmc+Cg==)

Expand All @@ -14,7 +14,7 @@ pnpm add @idos-network/idos-sdk-server-dapp ethers near-api-js
Import the SDK and initialize it:

```js
import { idOS } from "@idos-network/idos-sdk-server-dapp";
import { idOS } from "@idos-network/grantee-sdk-js";

export const sdk = await idOS.init(...options);
```
Expand Down
Loading

0 comments on commit 776c575

Please sign in to comment.