Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add enclave controller #607

Merged
merged 1 commit into from
Mar 6, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion packages/@controllers/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
},
"exports": {
".": "./src/index.ts",
"./isle": "./src/isle/index.ts"
"./isle": "./src/isle/index.ts",
"./secure-enclave": "./src/secure-enclave/index.ts"
},
"license": "MIT",
"peerDependencies": {
Expand Down
1 change: 1 addition & 0 deletions packages/@controllers/src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from "./isle";
export * from "./secure-enclave";
259 changes: 259 additions & 0 deletions packages/@controllers/src/secure-enclave/iframe-enclave.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,259 @@
import { base64Encode, type idOSCredential } from "@idos-network/core";

import type {
BackupPasswordInfo,
DiscoverUserEncryptionPublicKeyResponse,
EnclaveOptions,
EnclaveProvider,
StoredData,
} from "./types";

export class IframeEnclave implements EnclaveProvider {
options: Omit<EnclaveOptions, "container" | "url">;
container: string;
iframe: HTMLIFrameElement;
hostUrl: URL;

constructor(options: EnclaveOptions) {
const { container, ...other } = options;
this.container = container;
this.options = other;
this.hostUrl = new URL(other.url ?? "https://enclave.idos.network");
this.iframe = document.createElement("iframe");
this.iframe.id = "idos-enclave-iframe";
}

async load(): Promise<StoredData> {
await this.#loadEnclave();

await this.#requestToEnclave({ configure: this.options });

return (await this.#requestToEnclave({ storage: {} })) as StoredData;
}

async ready(
userId?: string,
signerAddress?: string,
signerPublicKey?: string,
expectedUserEncryptionPublicKey?: string,
): Promise<Uint8Array> {
let { encryptionPublicKey: userEncryptionPublicKey } = (await this.#requestToEnclave({
storage: {
userId,
signerAddress,
signerPublicKey,
expectedUserEncryptionPublicKey,
},
})) as StoredData;

while (!userEncryptionPublicKey) {
this.#showEnclave();
try {
userEncryptionPublicKey = (await this.#requestToEnclave({
keys: {},
})) as Uint8Array;
} catch (e) {
if (this.options.throwOnUserCancelUnlock) throw e;
} finally {
this.#hideEnclave();
}
}

return userEncryptionPublicKey;
}

async store(key: string, value: string): Promise<string> {
return this.#requestToEnclave({ storage: { [key]: value } }) as Promise<string>;
}

async reset(): Promise<void> {
this.#requestToEnclave({ reset: {} });
}

async updateStore(key: string, value: unknown): Promise<void> {
await this.#requestToEnclave({ updateStore: { key, value } });
}

async confirm(message: string): Promise<boolean> {
this.#showEnclave();

return this.#requestToEnclave({ confirm: { message } }).then((response) => {
this.#hideEnclave();
return response as boolean;
});
}

async encrypt(
message: Uint8Array,
receiverPublicKey: Uint8Array,
): Promise<{ content: Uint8Array; encryptorPublicKey: Uint8Array }> {
return this.#requestToEnclave({
encrypt: { message, receiverPublicKey },
}) as Promise<{ content: Uint8Array; encryptorPublicKey: Uint8Array }>;
}

async decrypt(message: Uint8Array, senderPublicKey: Uint8Array): Promise<Uint8Array> {
return this.#requestToEnclave({
decrypt: { fullMessage: message, senderPublicKey },
}) as Promise<Uint8Array>;
}

async filterCredentialsByCountries(credentials: Record<string, string>[], countries: string[]) {
return this.#requestToEnclave({
filterCredentialsByCountries: { credentials, countries },
}) as Promise<string[]>;
}

filterCredentials(
credentials: Record<string, string>[],
privateFieldFilters: { pick: Record<string, string>; omit: Record<string, string> },
): Promise<idOSCredential[]> {
return this.#requestToEnclave({
filterCredentials: { credentials, privateFieldFilters },
}) as Promise<idOSCredential[]>;
}

async #loadEnclave(): Promise<void> {
const container =
document.querySelector(this.container) ||
throwNew(Error, `Can't find container with selector ${this.container}`);

// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Permissions-Policy#directives
const permissionsPolicies = ["publickey-credentials-get", "storage-access"];

// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#sandbox
const liftedSandboxRestrictions = [
"forms",
"modals",
"popups",
"popups-to-escape-sandbox",
"same-origin",
"scripts",
].map((toLift) => `allow-${toLift}`);

// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#referrerpolicy
const referrerPolicy = "origin";

const styles = {
"aspect-ratio": "4/1",
"background-color": "transparent",
border: "none",
display: "block",
width: "100%",
};

this.iframe.allow = permissionsPolicies.join("; ");
this.iframe.referrerPolicy = referrerPolicy;
this.iframe.sandbox.add(...liftedSandboxRestrictions);
this.iframe.src = this.hostUrl.toString();
for (const [k, v] of Object.entries(styles)) {
this.iframe.style.setProperty(k, v);
}

let el: HTMLElement | null;
// biome-ignore lint/suspicious/noAssignInExpressions: it's on purpose
while ((el = document.getElementById(this.iframe.id))) {
console.log("reinstalling idOS iframe...");
container.removeChild(el);
}
container.appendChild(this.iframe);

return new Promise((resolve) =>
this.iframe.addEventListener(
"load",
() => {
resolve();
},
{ once: true },
),
);
}

#showEnclave() {
// biome-ignore lint/style/noNonNullAssertion: Make the explosion visible.
this.iframe.parentElement!.classList.add("visible");
}

#hideEnclave() {
// biome-ignore lint/style/noNonNullAssertion: Make the explosion visible.
this.iframe.parentElement!.classList.remove("visible");
}

// biome-ignore lint/suspicious/noExplicitAny: `any` is fine here. We will type it properly later.
async #requestToEnclave(request: any) {
return new Promise((resolve, reject) => {
const { port1, port2 } = new MessageChannel();

port1.onmessage = ({ data }) => {
port1.close();
data.error ? reject(data.error) : resolve(data.result);
};

// biome-ignore lint/style/noNonNullAssertion: Make the explosion visible.
this.iframe.contentWindow!.postMessage(request, this.hostUrl.origin, [port2]);
});
}

async backupPasswordOrSecret(
backupFn: (data: BackupPasswordInfo) => Promise<void>,
): Promise<void> {
const abortController = new AbortController();
this.#showEnclave();

window.addEventListener(
"message",
async (event) => {
if (event.data.type !== "idOS:store" || event.origin !== this.hostUrl.origin) return;

let status = "";

try {
status = "success";
await backupFn(event);
this.#hideEnclave();
} catch (error) {
status = "failure";
this.#hideEnclave();
}

event.ports[0].postMessage({
result: {
type: "idOS:store",
status,
},
});
event.ports[0].close();
abortController.abort();
},
{ signal: abortController.signal },
);

try {
await this.#requestToEnclave({
backupPasswordOrSecret: {},
});
} catch (error) {
console.error(error);
} finally {
this.#hideEnclave();
}
}

async discoverUserEncryptionPublicKey(
userId: string,
): Promise<DiscoverUserEncryptionPublicKeyResponse> {
if (this.options.mode !== "new")
throw new Error("You can only call `discoverUserEncryptionPublicKey` when mode is `new`.");

const userEncryptionPublicKey = await this.ready(userId);

return {
userId,
userEncryptionPublicKey: base64Encode(userEncryptionPublicKey),
};
}
}

function throwNew(ErrorClass: ErrorConstructor, ...args: Parameters<ErrorConstructor>): never {
throw new ErrorClass(...args);
}
2 changes: 2 additions & 0 deletions packages/@controllers/src/secure-enclave/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { IframeEnclave } from "./iframe-enclave";
export { MetaMaskSnapEnclave } from "./metamask-snap-enclave";
114 changes: 114 additions & 0 deletions packages/@controllers/src/secure-enclave/metamask-snap-enclave.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import type { idOSCredential } from "@idos-network/core";
import type {
DiscoverUserEncryptionPublicKeyResponse,
EnclaveProvider,
StoredData,
} from "./src/types";

export class MetaMaskSnapEnclave implements EnclaveProvider {
// biome-ignore lint/suspicious/noExplicitAny: Types will be added later
enclaveHost: any;
snapId: string;

constructor(_?: Record<string, unknown>) {
// biome-ignore lint/suspicious/noExplicitAny: Types will be added later
this.enclaveHost = (window as any).ethereum;
this.snapId = "npm:@idos-network/metamask-snap-enclave";
}
filterCredentials(
credentials: Record<string, string>[],
privateFieldFilters: { pick: Record<string, string>; omit: Record<string, string> },
): Promise<idOSCredential[]> {
console.log(credentials, privateFieldFilters);
throw new Error("Method not implemented.");
}

async discoverUserEncryptionPublicKey(): Promise<DiscoverUserEncryptionPublicKeyResponse> {
throw new Error("Method not implemented.");
}

filterCredentialsByCountries(
credentials: Record<string, string>[],
countries: string[],
): Promise<string[]> {
console.log(credentials, countries);

throw new Error("Method not implemented.");
}
async load(): Promise<StoredData> {
const snaps = await this.enclaveHost.request({ method: "wallet_getSnaps" });
// biome-ignore lint/suspicious/noExplicitAny: Types will be added later
const connected = Object.values(snaps).find((snap: any) => snap.id === this.snapId);

if (!connected)
await this.enclaveHost.request({
method: "wallet_requestSnaps",
params: { [this.snapId]: {} },
});

const storage = JSON.parse((await this.invokeSnap("storage")) || {});
storage.encryptionPublicKey &&= Uint8Array.from(Object.values(storage.encryptionPublicKey));

return storage;
}

async ready(
userId?: string,
signerAddress?: string,
signerPublicKey?: string,
): Promise<Uint8Array> {
let { encryptionPublicKey } = JSON.parse(
await this.invokeSnap("storage", { userId, signerAddress, signerPublicKey }),
);

encryptionPublicKey ||= await this.invokeSnap("init");
encryptionPublicKey &&= Uint8Array.from(Object.values(encryptionPublicKey));

return encryptionPublicKey;
}

invokeSnap(method: string, params: unknown = {}) {
return this.enclaveHost.request({
method: "wallet_invokeSnap",
params: {
snapId: this.snapId,
request: { method, params },
},
});
}

async store(key: string, value: string): Promise<string> {
return this.invokeSnap("storage", { [key]: value });
}

async reset(): Promise<void> {
return this.invokeSnap("reset");
}

updateStore(key: string, value: unknown): Promise<void> {
return this.invokeSnap("updateStore", { key, value });
}

async confirm(message: string): Promise<boolean> {
return this.invokeSnap("confirm", { message });
}

async encrypt(
message: Uint8Array,
receiverPublicKey: Uint8Array,
): Promise<{ content: Uint8Array; encryptorPublicKey: Uint8Array }> {
await this.invokeSnap("encrypt", { message, receiverPublicKey });

throw new Error("The Metamask Enclave needs to be updated");
}

async decrypt(message: Uint8Array, senderPublicKey: Uint8Array): Promise<Uint8Array> {
const decrypted = await this.invokeSnap("decrypt", { message, senderPublicKey });

return Uint8Array.from(Object.values(decrypted));
}

async backupPasswordOrSecret(): Promise<void> {
throw new Error("Method not implemented.");
}
}
Loading