Skip to content

Commit

Permalink
fix: throw error when no granteeAddress passed
Browse files Browse the repository at this point in the history
  • Loading branch information
Mohammed-Mamoun98 committed Dec 19, 2024
2 parents 1bcc70b + cbf6903 commit 0af89b5
Show file tree
Hide file tree
Showing 42 changed files with 428 additions and 389 deletions.
9 changes: 4 additions & 5 deletions apps/dashboard-for-dapps/src/routes/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ const useFetchGrants = () => {
queryKey: ["grants"],
queryFn: () =>
idOS.grants.list({
grantee: address,
granteeAddress: address,
}),
select: (data) =>
data.map((grant) => ({
Expand Down Expand Up @@ -211,7 +211,7 @@ function CredentialDetails({

if (!credential.data || !secretKey) return null;

const result = decrypt(credential.data.content, credential.data.encryption_public_key, secretKey);
const result = decrypt(credential.data.content, credential.data.encryptor_public_key, secretKey);
const content = JSON.parse(result);

const subject = Object.entries(content.credentialSubject).filter(
Expand Down Expand Up @@ -331,7 +331,6 @@ function CredentialDetails({
<List.Item
flexShrink="0"
key={key}
role="button"
transition="transform 0.2s"
cursor="pointer"
_hover={{ transform: "scale(1.02)" }}
Expand Down Expand Up @@ -424,7 +423,7 @@ function SearchResults({ results }: { results: GrantsWithFormattedLockedUntil })
pt="4"
grow
label="Owner"
value={grant.owner}
value={grant.ownerAddress}
truncate
/>
<DataListItem
Expand All @@ -439,7 +438,7 @@ function SearchResults({ results }: { results: GrantsWithFormattedLockedUntil })
pt="4"
grow
label="Grantee"
value={grant.grantee}
value={grant.granteeAddress}
truncate
/>
<DataListItem
Expand Down
2 changes: 1 addition & 1 deletion apps/idos-data-dashboard/src/core/idos/idos-provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export const Provider = ({ children }: PropsWithChildren) => {
if (profile) {
// @ts-ignore
await _sdk.setSigner(signer.type, signer.value);
const _pk = _sdk.auth.currentUser.publicKey;
const _pk = _sdk.auth.currentUser.currentUserPublicKey;

setPublicKey(_pk);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ export const DeleteCredential = ({ isOpen, credential, onClose }: DeleteCredenti
if (!credential) return null;

const [currentToRevoke] = state;
const { grantee } = currentToRevoke ?? {};
const { granteeAddress } = currentToRevoke ?? {};

const meta = JSON.parse(credential.public_notes);

Expand Down Expand Up @@ -172,7 +172,7 @@ export const DeleteCredential = ({ isOpen, credential, onClose }: DeleteCredenti
<>
<Text mb={1}>Revoking grant for grantee:</Text>
<Code px={2} py={1} rounded="md" fontSize="sm" bg="neutral.800">
{grantee}
{granteeAddress}
</Code>
</>
) : deleteCredential.isPending ? (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ type GrantsCenterProps = {
};

function generateGrantId(grant: idOSGrant): string {
const { dataId, grantee, owner, lockedUntil } = grant;
return [dataId, grantee, owner, lockedUntil].join("-");
const { dataId, granteeAddress, ownerAddress, lockedUntil } = grant;
return [dataId, granteeAddress, ownerAddress, lockedUntil].join("-");
}

function timelockToMs(timelock: number): number {
Expand Down Expand Up @@ -96,7 +96,7 @@ const Shares = ({ credentialId, grants }: { credentialId: string; grants: idOSGr
data-grant={JSON.stringify(grant)}
>
<Td maxW={140}>
<Text isTruncated>{grant.grantee}</Text>
<Text isTruncated>{grant.granteeAddress}</Text>
</Td>
<Td>
<Text>{grant.lockedUntil ? timelockToDate(grant.lockedUntil) : "-"}</Text>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ export const useFetchGrants = ({ credentialId }: { credentialId: string }) => {
const queryClient = useQueryClient();
const credentials = queryClient.getQueryData<idOSCredentialWithShares[]>(["credentials"]);

const owner = address?.includes("0x") ? address : publicKey;
const ownerAddress = address?.includes("0x") ? address : publicKey;

return useQuery({
queryKey: ["grants", credentialId],
queryFn: () => sdk.grants.list({ owner }),
queryFn: () => sdk.grants.list({ ownerAddress }),
retry: 1,
select(grants) {
if (!credentials || !grants) return [];
Expand All @@ -34,8 +34,8 @@ export const useRevokeGrant = () => {
const queryClient = useQueryClient();

return useMutation<{ transactionId: string }, DefaultError, idOSGrant, Ctx>({
mutationFn: ({ grantee, dataId, lockedUntil }: idOSGrant) =>
sdk.grants.revoke("credentials", dataId, grantee, dataId, lockedUntil),
mutationFn: ({ granteeAddress, dataId, lockedUntil }: idOSGrant) =>
sdk.grants.revoke("credentials", dataId, granteeAddress, dataId, lockedUntil),
mutationKey: ["revokeGrant"],
async onMutate(grant) {
const previousCredentials =
Expand Down
29 changes: 13 additions & 16 deletions apps/idos-enclave/src/lib/enclave.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ export class Enclave {
});
}

storage(humanId, signerAddress, signerPublicKey, expectedUserEncryptionPublicKey) {
humanId && this.store.set("human-id", humanId);
storage(userId, signerAddress, signerPublicKey, expectedUserEncryptionPublicKey) {
userId && this.store.set("user-id", userId);
signerAddress && this.store.set("signer-address", signerAddress);
signerPublicKey && this.store.set("signer-public-key", signerPublicKey);

Expand All @@ -59,19 +59,20 @@ export class Enclave {
const storeWithCodec = this.store.pipeCodec(Base64Codec);

this.expectedUserEncryptionPublicKey = expectedUserEncryptionPublicKey;
this.humanId = humanId;
this.userId = userId;

if (!this.isAuthorizedOrigin) {
return {
humanId: "",
userId: "",
encryptionPublicKey: "",
signerAddress: "",
signerPublicKey: "",
};
}

return {
humanId: this.humanId ?? this.store.get("human-id"),
// TODO Remove human-user migration code.
userId: this.userId ?? this.store.get("user-id") ?? this.store.get("human-id"),
encryptionPublicKey: storeWithCodec.get("encryption-public-key"),
signerAddress: this.store.get("signer-address"),
signerPublicKey: this.store.get("signer-public-key"),
Expand Down Expand Up @@ -157,7 +158,7 @@ export class Enclave {

async ensureKeyPair() {
const password = this.store.get("password");
const salt = this.humanId;
const salt = this.userId;

const storeWithCodec = this.store.pipeCodec(Base64Codec);

Expand Down Expand Up @@ -250,18 +251,14 @@ export class Enclave {
}
}

messageParent(message) {
window.parent.postMessage(message, this.parentOrigin);
}

async filterCredentialsByCountries(credentials, countries) {
const decrypted = await Promise.all(
credentials.map(async (credential) => ({
...credential,
content: Utf8Codec.decode(
await this.decrypt(
Base64Codec.decode(credential.content),
Base64Codec.decode(credential.encryption_public_key),
Base64Codec.decode(credential.encryptor_public_key),
),
),
})),
Expand All @@ -287,7 +284,7 @@ export class Enclave {
content: Utf8Codec.decode(
await this.decrypt(
Base64Codec.decode(credential.content),
Base64Codec.decode(credential.encryption_public_key),
Base64Codec.decode(credential.encryptor_public_key),
),
),
})),
Expand Down Expand Up @@ -326,7 +323,7 @@ export class Enclave {
const [requestName, requestData] = Object.entries(event.data).flat();
const {
fullMessage,
humanId,
userId,
message,
receiverPublicKey,
senderPublicKey,
Expand All @@ -352,7 +349,7 @@ export class Enclave {
reset: () => [],
configure: () => [mode, theme],
storage: () => [
humanId,
userId,
signerAddress,
signerPublicKey,
expectedUserEncryptionPublicKey,
Expand Down Expand Up @@ -401,7 +398,7 @@ export class Enclave {
}

async #openDialog(intent, message) {
if (!this.humanId) throw new Error("Can't open dialog without humanId");
if (!this.userId) throw new Error("Can't open dialog without userId");
const width = 600;
const height =
this.configuration?.mode === "new" ? 600 : intent === "backupPasswordOrSecret" ? 520 : 400;
Expand All @@ -417,7 +414,7 @@ export class Enclave {
.map((feat) => feat.join("="))
.join(",");

const dialogURL = new URL(`/dialog.html?humanId=${this.humanId}`, window.location.origin);
const dialogURL = new URL(`/dialog.html?userId=${this.userId}`, window.location.origin);
this.dialog = window.open(dialogURL, "idos-dialog", popupConfig);

await new Promise((resolve) => this.dialog.addEventListener("ready", resolve, { once: true }));
Expand Down
2 changes: 1 addition & 1 deletion apps/idos-enclave/src/lib/idOSKeyDerivation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { scrypt } from "scrypt-js";
* Unicode normalization of input strigs
* NFKC: compatibility decomposition followed by canonical composition
* validateSalt
* UUID v4 format (idOS human IDs)
* UUID v4 format (idOS user IDs)
* n, r, p
* CPU/RAM cost (higher = costlier)
* n: iteration count
Expand Down
8 changes: 2 additions & 6 deletions apps/idos-enclave/src/pages/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ export function App({ store, enclave }: AppProps) {
const [origin, setOrigin] = useState<string | null>(null);
const [message, setMessage] = useState<string | null>(null);
const [encryptionPublicKey, setEncryptionUserPublicKey] = useState<string>("");
const [humanId] = useState<string | null>(
const [userId] = useState<string | null>(
new URLSearchParams(window.location.search).get("humanId"),
);

Expand Down Expand Up @@ -197,11 +197,7 @@ export function App({ store, enclave }: AppProps) {
if (method === "password") {
return (
<Layout onHeaderClick={resetMethod}>
<PasswordForm
{...methodProps}
encryptionPublicKey={encryptionPublicKey}
humanId={humanId}
/>
<PasswordForm {...methodProps} encryptionPublicKey={encryptionPublicKey} userId={userId} />
</Layout>
);
}
Expand Down
7 changes: 4 additions & 3 deletions apps/idos-enclave/src/pages/methods/Password.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -82,10 +82,10 @@ export function PasswordForm({
onSuccess,
store,
encryptionPublicKey,
humanId,
userId,
}: MethodProps<{ password: string; duration: number }> & {
encryptionPublicKey?: string;
humanId: string | null;
userId: string | null;
}) {
const password = useSignal("");
const duration = useSignal(7);
Expand All @@ -96,7 +96,8 @@ export function PasswordForm({
const litCipher = store.get("lit-cipher-text");

async function derivePublicKeyFromPassword(password: string) {
const salt = store.get("human-id") || humanId;
// TODO Remove human-user migration code.
const salt = store.get("user-id") || store.get("human-id") || userId;
const secretKey = await idOSKeyDerivation({ password, salt });
const keyPair = nacl.box.keyPair.fromSecretKey(secretKey);
return encode(keyPair.publicKey);
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
Expand Up @@ -19,7 +19,7 @@ const evmGranteeSigner = new ethers.Wallet(
const idosGrantee = await idOSGrantee.init({
chainType: "EVM",
granteeSigner: evmGranteeSigner,
encryptionSecret: ENCRYPTION_SECRET_KEY,
recipientEncryptionPrivateKey: ENCRYPTION_SECRET_KEY,
});

const encryptionPublicKey = idosGrantee.encryptionPublicKey;
Expand Down
4 changes: 2 additions & 2 deletions examples/idos-example-dapp/api/NEAR.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const nearGranteeSigner = KeyPair.fromString(NEAR_GRANTEE_PRIVATE_KEY);
const idosGrantee = await idOSGrantee.init({
chainType: "NEAR",
granteeSigner: nearGranteeSigner,
encryptionSecret: ENCRYPTION_SECRET_KEY,
recipientEncryptionPrivateKey: ENCRYPTION_SECRET_KEY,
});

const encryptionPublicKey = idosGrantee.encryptionPublicKey;
Expand All @@ -38,7 +38,7 @@ export default async function (request: VercelRequest, response: VercelResponse)
}

const rawBody = request.read();
let body;
let body: ReturnType<typeof JSON.parse>;
try {
body = JSON.parse(rawBody);
} catch (e) {
Expand Down
20 changes: 10 additions & 10 deletions examples/idos-example-dapp/src/creds2.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ const makePublicNotes = (plaintextW3cVc: ReturnType<typeof makeW3cCredential>):

export const issuer_makeUserCredential = (
idvData: IdvDataResult,
humanId: string,
userId: string,
receiverEncryptionPublicKey: Uint8Array,
issuerAttestationSecretKey: Uint8Array,
) => {
Expand All @@ -74,7 +74,7 @@ export const issuer_makeUserCredential = (
const publicNotes = makePublicNotes(plaintextContent);

return {
humanId,
userId,
publicNotes: JSON.stringify(publicNotes),
plaintextContent: toBytes(plaintextContent),
receiverEncryptionPublicKey,
Expand All @@ -83,7 +83,7 @@ export const issuer_makeUserCredential = (

export const issuer_makeUserCredentialForSharing = (
idvData: IdvDataResult,
humanId: string,
userId: string,
receiverEncryptionPublicKey: Uint8Array,
issuerAttestationSecretKey: Uint8Array,
originalCredentialId: string,
Expand All @@ -93,7 +93,7 @@ export const issuer_makeUserCredentialForSharing = (
const plaintextContent = makeW3cCredential(idvData, issuerAttestationSecretKey);

return {
humanId,
userId,
publicNotes: "",
plaintextContent: toBytes(plaintextContent),
receiverEncryptionPublicKey,
Expand All @@ -115,7 +115,7 @@ import {
shareCredentialByGrant,
} from "@idos-network/issuer-sdk-js/credentials";

const humanId = "bf8709ce-9dfc-11ef-a188-047c16570806";
const userId = "bf8709ce-9dfc-11ef-a188-047c16570806";
const userEncryptionSecretKey = Base64Codec.decode("nIvx0jPbA8d83rL+I7Vs1B/Fp6pndGtXOX4GDmlEkSQ=");
const userEncryptionPublicKey = nacl.box.keyPair.fromSecretKey(userEncryptionSecretKey).publicKey;
const _thirdPartyEncryptionSecretKey = Base64Codec.decode(
Expand Down Expand Up @@ -173,7 +173,7 @@ await (async () => {
const issuerConfig = await issuerConfigBuild();
const credential = issuer_makeUserCredential(
getIdvData(),
humanId,
userId,
userEncryptionPublicKey,
issuerAttestationSecretKey,
);
Expand All @@ -189,7 +189,7 @@ await (async () => {
const issuerConfig = await issuerConfigBuild();
const credential = issuer_makeUserCredential(
getIdvData(),
humanId,
userId,
userEncryptionPublicKey,
issuerAttestationSecretKey,
);
Expand All @@ -207,14 +207,14 @@ await (async () => {
issuerConfig,
issuer_makeUserCredential(
getIdvData(),
humanId,
userId,
userEncryptionPublicKey,
issuerAttestationSecretKey,
),
);
const sharedCredential = issuer_makeUserCredentialForSharing(
getIdvData(),
humanId,
userId,
thirdPartyEncryptionPublicKey,
issuerAttestationSecretKey,
insertedCredential.id,
Expand All @@ -233,7 +233,7 @@ await (async () => {
const issuerConfig = await issuerConfigBuild();
const credential = issuer_makeUserCredential(
getIdvData(),
humanId,
userId,
userEncryptionPublicKey,
issuerAttestationSecretKey,
);
Expand Down
Loading

0 comments on commit 0af89b5

Please sign in to comment.