diff --git a/.github/workflows/vetkeys-password-manager-with-metadata.yml b/.github/workflows/vetkeys-password-manager-with-metadata.yml index 79beb304da..18c13e3440 100644 --- a/.github/workflows/vetkeys-password-manager-with-metadata.yml +++ b/.github/workflows/vetkeys-password-manager-with-metadata.yml @@ -6,6 +6,7 @@ on: - master pull_request: paths: + - motoko/vetkeys/password_manager_with_metadata/** - rust/vetkeys/password_manager_with_metadata/** - .github/workflows/vetkeys-password-manager-with-metadata.yml @@ -14,23 +15,28 @@ concurrency: cancel-in-progress: true jobs: - rust: + motoko: runs-on: ubuntu-24.04 - container: ghcr.io/dfinity/icp-dev-env-rust:1.0.1 + container: ghcr.io/dfinity/icp-dev-env-motoko:1.0.1 env: ICP_CLI_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} steps: - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 - - name: Deploy Password Manager With Metadata Rust - working-directory: rust/vetkeys/password_manager_with_metadata/rust - run: icp network start -d && icp deploy - motoko: + - name: Deploy + working-directory: motoko/vetkeys/password_manager_with_metadata + run: | + icp network start -d + icp deploy + + rust: runs-on: ubuntu-24.04 - container: ghcr.io/dfinity/icp-dev-env-motoko:1.0.1 + container: ghcr.io/dfinity/icp-dev-env-rust:1.0.1 env: ICP_CLI_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} steps: - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 - - name: Deploy Password Manager With Metadata Motoko - working-directory: rust/vetkeys/password_manager_with_metadata/motoko - run: icp network start -d && icp deploy + - name: Deploy + working-directory: rust/vetkeys/password_manager_with_metadata + run: | + icp network start -d + icp deploy diff --git a/motoko/vetkeys/password_manager_with_metadata/README.md b/motoko/vetkeys/password_manager_with_metadata/README.md new file mode 100644 index 0000000000..66497b738d --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/README.md @@ -0,0 +1,78 @@ +# VetKey Password Manager with Metadata (Motoko) + +[View this sample's code on GitHub](https://github.com/dfinity/examples/tree/master/motoko/vetkeys/password_manager_with_metadata) + +Also available in: [Rust](../../../rust/vetkeys/password_manager_with_metadata) + +The **VetKey Password Manager** is an example application demonstrating how to use **VetKeys** and **Encrypted Maps** to build a secure, decentralized password manager on the **Internet Computer (IC)**. This application allows users to create password vaults, store encrypted passwords, and share vaults with other users via their **Internet Identity Principal**. + +This version extends the basic password manager by supporting unencrypted metadata, such as URLs and tags, alongside encrypted passwords. The goal is to demonstrate how to make atomic updates to the Encrypted Maps canister, storing both encrypted and unencrypted data in a single update call. + +## Features + +- **Secure Password Storage**: Uses VetKey to encrypt passwords before storing them in Encrypted Maps. +- **Vault-Based Organization**: Users can create multiple vaults, each containing multiple passwords. +- **Access Control**: Vaults can be shared with other users via their **Internet Identity Principal**. +- **Atomic Updates**: Stores encrypted passwords along with unencrypted metadata in a single update call. + +## Build and deploy from the command line + +### Prerequisites + +- Install [Node.js](https://nodejs.org/en/download/) +- Install [icp-cli](https://cli.internetcomputer.org): `npm install -g @icp-sdk/icp-cli @icp-sdk/ic-wasm` +- Install [ic-mops](https://mops.one): `npm install -g ic-mops` + +### (Optionally) choose a different master key + +This example uses `test_key_1` by default. To use a different [available master key](https://docs.internetcomputer.org/concepts/vetkeys/#api-overview), change the `init_args` value in `icp.yaml` before deploying. + +### Install + +```bash +git clone https://github.com/dfinity/examples +cd examples/motoko/vetkeys/password_manager_with_metadata +``` + +### Deploy + +```bash +icp network start -d +icp deploy +``` + +Open the frontend URL printed by `icp deploy`. + +To run the frontend in development mode with hot reloading (after `icp deploy`): + +```bash +npm run dev +``` + +When done, stop the local network to free up the port for other projects: + +```bash +icp network stop +``` + +## Example components + +### Backend (`backend/`) + +An **Encrypted Maps**-enabled Motoko canister that stores encrypted passwords together with unencrypted metadata (URLs, tags) in atomic update calls. + +> **Note on naming.** The backend methods are snake_case (rather than the usual Motoko camelCase). The standard Encrypted Maps methods are called by these exact names by the `@icp-sdk/vetkeys` Encrypted Maps client, and the custom metadata methods follow the same convention — renaming them would break the frontend. An upstream Motoko actor mixin that generates the Encrypted Maps endpoint set automatically is in progress ([dfinity/vetkeys#405](https://github.com/dfinity/vetkeys/pull/405)). + +### Frontend (`frontend/`) + +A **Svelte** application for managing vaults and passwords. It uses the `@icp-sdk/vetkeys` Encrypted Maps client for the crypto operations and a canister actor (bindings generated from `backend/backend.did` by the `@icp-sdk/bindgen` Vite plugin) for the metadata methods. + +## Limitations + +This example app does not implement key rotation, which is strongly recommended in a production environment. Key rotation involves periodically changing encryption keys and re-encrypting data to enhance security. In a production app, key rotation would be useful to limit the impact of a potential key compromise, or to limit access when users are added to or removed from sharing. + +## Additional resources + +- **[Basic Password Manager](../../../rust/vetkeys/password_manager)** — a simpler example without metadata. +- **[What are VetKeys](https://docs.internetcomputer.org/concepts/vetkeys)** — more information about VetKeys and VetKD. +- [Security best practices](https://docs.internetcomputer.org/guides/security/overview/) diff --git a/rust/vetkeys/password_manager_with_metadata/motoko/backend/src/Main.mo b/motoko/vetkeys/password_manager_with_metadata/backend/app.mo similarity index 92% rename from rust/vetkeys/password_manager_with_metadata/motoko/backend/src/Main.mo rename to motoko/vetkeys/password_manager_with_metadata/backend/app.mo index b13b3f6a0f..938bf276dc 100644 --- a/rust/vetkeys/password_manager_with_metadata/motoko/backend/src/Main.mo +++ b/motoko/vetkeys/password_manager_with_metadata/backend/app.mo @@ -12,10 +12,18 @@ import Debug "mo:core/Debug"; import Runtime "mo:core/Runtime"; import VetKeys "mo:ic-vetkeys"; -persistent actor class (keyName : Text) { +// This canister combines the Encrypted Maps interface with extra metadata-aware +// methods. Its public methods are intentionally snake_case (not the usual Motoko +// camelCase): the standard Encrypted Maps methods are called by these exact names +// by the `@icp-sdk/vetkeys` Encrypted Maps client, and the custom metadata +// methods follow the same convention for a consistent interface — renaming to +// camelCase would break the frontend. An upstream Motoko actor mixin that +// generates the Encrypted Maps endpoint set automatically is in progress +// (https://github.com/dfinity/vetkeys/pull/405). +actor class (keyName : Text) { // Global state - let encryptedMapsState = VetKeys.EncryptedMaps.newEncryptedMapsState({ curve = #bls12_381_g2; name = keyName }, "password_manager_example_dapp"); + let encryptedMapsState = VetKeys.EncryptedMaps.newEncryptedMapsState({ curve = #bls12_381_g2; name = keyName }, "password_manager_example_app"); transient let encryptedMaps = VetKeys.EncryptedMaps.EncryptedMaps(encryptedMapsState, VetKeys.accessRightsOperations()); func compareMetadataKeys(a : MetadataKey, b : MetadataKey) : { diff --git a/motoko/vetkeys/password_manager_with_metadata/backend/backend.did b/motoko/vetkeys/password_manager_with_metadata/backend/backend.did new file mode 100644 index 0000000000..9371d69b44 --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/backend/backend.did @@ -0,0 +1,79 @@ +type _anon_class_15_1 = + service { + get_accessible_shared_map_names: () -> + (vec record { + principal; + ByteBuf; + }) query; + get_encrypted_values_for_map_with_metadata: (map_owner: principal, + map_name: ByteBuf) -> (Result_4) query; + get_encrypted_vetkey: (map_owner: principal, map_name: ByteBuf, + transport_key: ByteBuf) -> (Result_3); + get_owned_non_empty_map_names: () -> (vec ByteBuf) query; + get_shared_user_access_for_map: (map_owner: principal, map_name: + ByteBuf) -> (Result_2) query; + get_user_rights: (map_owner: principal, map_name: ByteBuf, user: + principal) -> (Result) query; + get_vetkey_verification_key: () -> (ByteBuf); + insert_encrypted_value_with_metadata: (map_owner: principal, map_name: + ByteBuf, map_key: ByteBuf, value: ByteBuf, tags: vec text, url: text) -> + (Result_1); + remove_encrypted_value_with_metadata: (map_owner: principal, map_name: + ByteBuf, map_key: ByteBuf) -> (Result_1); + remove_user: (map_owner: principal, map_name: ByteBuf, user: principal) -> + (Result); + set_user_rights: (map_owner: principal, map_name: ByteBuf, user: + principal, access_rights: AccessRights) -> (Result); + }; +type Result_4 = + variant { + Err: text; + Ok: vec record { + ByteBuf; + ByteBuf; + PasswordMetadata; + }; + }; +type Result_3 = + variant { + Err: text; + Ok: ByteBuf; + }; +type Result_2 = + variant { + Err: text; + Ok: vec record { + principal; + AccessRights; + }; + }; +type Result_1 = + variant { + Err: text; + Ok: opt record { + ByteBuf; + PasswordMetadata; + }; + }; +type Result = + variant { + Err: text; + Ok: opt AccessRights; + }; +type PasswordMetadata = + record { + creation_date: nat64; + last_modification_date: nat64; + last_modified_principal: principal; + number_of_modifications: nat64; + tags: vec text; + url: text; + }; +type ByteBuf = record {inner: blob;}; +type AccessRights = + variant { + Read; + ReadWrite; + ReadWriteManage; + }; +service : (keyName: text) -> _anon_class_15_1 diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/.gitignore b/motoko/vetkeys/password_manager_with_metadata/frontend/.gitignore new file mode 100644 index 0000000000..061e2e66e1 --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/.gitignore @@ -0,0 +1,3 @@ +node_modules/ +dist/ +src/bindings/ diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/index.html b/motoko/vetkeys/password_manager_with_metadata/frontend/index.html new file mode 100644 index 0000000000..d880f186ed --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/index.html @@ -0,0 +1,14 @@ + + + + + + + Password Manager with Metadata based on vetKeys + + +
+ + + + diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/jsconfig.json b/motoko/vetkeys/password_manager_with_metadata/frontend/jsconfig.json new file mode 100644 index 0000000000..cdcb3c8dbf --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/jsconfig.json @@ -0,0 +1,38 @@ +{ + "compilerOptions": { + "moduleResolution": "bundler", + "target": "ESNext", + "module": "ESNext", + /** + * svelte-preprocess cannot figure out whether you have + * a value or a type, so tell TypeScript to enforce using + * `import type` instead of `import` for Types. + */ + "verbatimModuleSyntax": true, + "isolatedModules": true, + "resolveJsonModule": true, + /** + * To have warnings / errors of the Svelte compiler at the + * correct position, enable source maps by default. + */ + "sourceMap": true, + "esModuleInterop": true, + "skipLibCheck": true, + /** + * Typecheck JS in `.svelte` and `.js` files by default. + * Disable this if you'd like to use dynamic types. + */ + "checkJs": true + }, + /** + * Use global.d.ts instead of compilerOptions.types + * to avoid limiting type declarations. + */ + "include": [ + "src/**/*.d.ts", + "src/**/*.js", + "src/**/*.svelte", + "src/main.ts", + "src/main.ts" + ] +} diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/package.json b/motoko/vetkeys/password_manager_with_metadata/frontend/package.json new file mode 100644 index 0000000000..adaf711ac4 --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/package.json @@ -0,0 +1,35 @@ +{ + "name": "frontend", + "private": true, + "type": "module", + "scripts": { + "prebuild": "npm i --include=dev", + "dev": "vite", + "build": "vite build", + "preview": "vite preview" + }, + "devDependencies": { + "@icp-sdk/bindgen": "~0.2.2", + "@rollup/plugin-typescript": "^12.1.2", + "@tailwindcss/postcss": "^4.0.6", + "@tailwindcss/vite": "^4.0.0", + "@tsconfig/svelte": "^5.0.4", + "@typewriter/delta": "^1.2.4", + "autoprefixer": "^10.4.20", + "rollup-plugin-css-only": "^4.5.2", + "tslib": "^2.8.1", + "vite": "^5.4.21" + }, + "dependencies": { + "@icp-sdk/auth": "^7.1.0", + "@icp-sdk/core": "^5.4.0", + "@icp-sdk/vetkeys": "^0.5.0-beta.0", + "@sveltejs/vite-plugin-svelte": "^3.0.2", + "daisyui": "^4.12.23", + "svelte": "^4.2.19", + "svelte-icons": "^2.1.0", + "svelte-spa-router": "^4.0.1", + "tailwindcss": "^3.0.17", + "typewriter-editor": "^0.9.4" + } +} diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/public/.ic-assets.json5 b/motoko/vetkeys/password_manager_with_metadata/frontend/public/.ic-assets.json5 new file mode 100644 index 0000000000..a57140a5e5 --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/public/.ic-assets.json5 @@ -0,0 +1,10 @@ +[ + { + match: "**/*", + security_policy: "hardened", + headers: { + "Content-Security-Policy": "default-src 'self';script-src 'self';connect-src 'self' http://localhost:* https://icp0.io https://*.icp0.io https://icp-api.io;img-src 'self' data:;style-src * 'unsafe-inline';object-src 'none';base-uri 'self';frame-ancestors 'none';form-action 'self';upgrade-insecure-requests;", + }, + allow_raw_access: false + }, +] diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/public/img/ic-badge-powered-by-crypto_label-stripe-dark-text.png b/motoko/vetkeys/password_manager_with_metadata/frontend/public/img/ic-badge-powered-by-crypto_label-stripe-dark-text.png new file mode 100644 index 0000000000..1a227a2b05 Binary files /dev/null and b/motoko/vetkeys/password_manager_with_metadata/frontend/public/img/ic-badge-powered-by-crypto_label-stripe-dark-text.png differ diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/public/img/ic-badge-powered-by-crypto_label-stripe-white-text.png b/motoko/vetkeys/password_manager_with_metadata/frontend/public/img/ic-badge-powered-by-crypto_label-stripe-white-text.png new file mode 100644 index 0000000000..e1da198555 Binary files /dev/null and b/motoko/vetkeys/password_manager_with_metadata/frontend/public/img/ic-badge-powered-by-crypto_label-stripe-white-text.png differ diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/public/img/ic-badge-powered-by-crypto_transparent-dark-text.png b/motoko/vetkeys/password_manager_with_metadata/frontend/public/img/ic-badge-powered-by-crypto_transparent-dark-text.png new file mode 100644 index 0000000000..90029c464b Binary files /dev/null and b/motoko/vetkeys/password_manager_with_metadata/frontend/public/img/ic-badge-powered-by-crypto_transparent-dark-text.png differ diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/public/img/ic-badge-powered-by-crypto_transparent-white-text.png b/motoko/vetkeys/password_manager_with_metadata/frontend/public/img/ic-badge-powered-by-crypto_transparent-white-text.png new file mode 100644 index 0000000000..f1a2d80812 Binary files /dev/null and b/motoko/vetkeys/password_manager_with_metadata/frontend/public/img/ic-badge-powered-by-crypto_transparent-white-text.png differ diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/public/vite.svg b/motoko/vetkeys/password_manager_with_metadata/frontend/public/vite.svg new file mode 100644 index 0000000000..e7b8dfb1b2 --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/public/vite.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/src/App.svelte b/motoko/vetkeys/password_manager_with_metadata/frontend/src/App.svelte new file mode 100644 index 0000000000..ed34e5e20d --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/src/App.svelte @@ -0,0 +1,13 @@ + + +{#if $auth.state === "initialized"} + +{:else} + +{/if} + diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/src/app.css b/motoko/vetkeys/password_manager_with_metadata/frontend/src/app.css new file mode 100644 index 0000000000..b5c61c9567 --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/src/app.css @@ -0,0 +1,3 @@ +@tailwind base; +@tailwind components; +@tailwind utilities; diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/src/assets/svelte.svg b/motoko/vetkeys/password_manager_with_metadata/frontend/src/assets/svelte.svg new file mode 100644 index 0000000000..c5e08481f8 --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/src/assets/svelte.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/Disclaimer.svelte b/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/Disclaimer.svelte new file mode 100644 index 0000000000..e4065d217b --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/Disclaimer.svelte @@ -0,0 +1,26 @@ + + +{#if !isDismissed} +
+

+ +

+ + +
+{/if} diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/DisclaimerCopy.svelte b/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/DisclaimerCopy.svelte new file mode 100644 index 0000000000..7cf5977604 --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/DisclaimerCopy.svelte @@ -0,0 +1,5 @@ + + +Disclaimer: This sample app is intended exclusively for experimental +purpose. You are advised not to use this app for storing your critical data such +as keys or passwords. diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/EditPassword.svelte b/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/EditPassword.svelte new file mode 100644 index 0000000000..2f250d92ea --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/EditPassword.svelte @@ -0,0 +1,356 @@ + + +{#if parentVaultName.length > 0} +
+ Edit password + +
+
+ {#if $vaultsStore.state === "loaded"} +
+ + + + + +
+ +
+ Created: {new Date( + Number(originalPassword.metadata.creation_date) / 1000000, + )} +
+
+ Last modified: {new Date( + Number(originalPassword.metadata.last_modification_date) / + 1000000, + )} +
+
+ Number of modifications: {originalPassword.metadata + .number_of_modifications} +
+
+ Last modification by: {originalPassword.metadata.last_modified_principal.toText()} +
+ + Back + + + +
+ {:else if $vaultsStore.state === "loading"} + Loading password... + {/if} +
+{:else} +
+ Edit password +
+
+ {#if $vaultsStore.state === "loading"} + + Loading password... + {:else if $vaultsStore.state === "loaded"} +
Could not find password.
+ {/if} +
+{/if} diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/EditVault.svelte b/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/EditVault.svelte new file mode 100644 index 0000000000..c671bb0fe9 --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/EditVault.svelte @@ -0,0 +1,92 @@ + + +{#if editedVault} +
+ Edit vault + +
+
+ {#if $vaultsStore.state === "loaded"} +
+ + {:else if $vaultsStore.state === "loading"} + Loading vaults... + {/if} +
+{:else} +
+ Edit vault +
+
+ {#if $vaultsStore.state === "loading"} + + Loading vault... + {:else if $vaultsStore.state === "loaded"} +
Could not find vault.
+ {/if} +
+{/if} diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/Header.svelte b/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/Header.svelte new file mode 100644 index 0000000000..77e83eb954 --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/Header.svelte @@ -0,0 +1,27 @@ + + + diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/Hero.svelte b/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/Hero.svelte new file mode 100644 index 0000000000..9b58a6ca3b --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/Hero.svelte @@ -0,0 +1,60 @@ + + +
+
+
+

+ Password Manager +

+

+ Your private passwords on the Internet Computer. +

+

+ A safe place to store your personal lists, thoughts, ideas or + passphrases and much more... +

+ + {#if auth.state === "initializing-auth"} +
+ + Initializing... +
+ {:else if auth.state === "anonymous"} + + {:else if auth.state === "error"} +
An error occurred.
+ {/if} + +
+ +
+
+
+
+ + Powered by the Internet Computer +
+
diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/LayoutAuthenticated.svelte b/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/LayoutAuthenticated.svelte new file mode 100644 index 0000000000..090735f212 --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/LayoutAuthenticated.svelte @@ -0,0 +1,29 @@ + + + + + diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/NewPassword.svelte b/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/NewPassword.svelte new file mode 100644 index 0000000000..4dc1a099e3 --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/NewPassword.svelte @@ -0,0 +1,146 @@ + + + + +
+ New password +
+ +
+ +
+ + + + + +
+ + +
diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/Notifications.svelte b/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/Notifications.svelte new file mode 100644 index 0000000000..800cc748fd --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/Notifications.svelte @@ -0,0 +1,22 @@ + + +
+ {#each $notifications as n (n.id)} +
+

{n.message}

+
+ {/each} +
diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/Password.svelte b/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/Password.svelte new file mode 100644 index 0000000000..0bfe573317 --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/Password.svelte @@ -0,0 +1,107 @@ + + +
+ + Password: {password.passwordName} + + + {#if $vaultsStore.state === "loaded" && $vaultsStore.list.length > 0} + New password + {/if} + +
+ +
+ {#if $vaultsStore.state === "loading"} + + Loading password... + {:else if $vaultsStore.state === "loaded"} + {#if password.parentVaultName === ""} +
+ There is no such password in this vault. +
+ + {:else} +
+
+

+ {password.passwordName}: "{password.content}" +

+
+
+ {/if} +
+ + {/if} +
diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/PasswordEditor.svelte b/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/PasswordEditor.svelte new file mode 100644 index 0000000000..e8fa33191c --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/PasswordEditor.svelte @@ -0,0 +1,73 @@ + + + +
+ + + + +
+
+ +
+ + diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/Passwords.svelte b/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/Passwords.svelte new file mode 100644 index 0000000000..f5355ea706 --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/Passwords.svelte @@ -0,0 +1,79 @@ + + +
+ Your passwords + + {#if $vaultsStore.state === "loaded" && $vaultsStore.list.length > 0} + New Password + {/if} + +
+
+ {#if $vaultsStore.state === "loading"} + + Loading passwords... + {:else if $vaultsStore.state === "loaded"} + {#if $vaultsStore.list.length > 0} +
+ +
+ +
+ {#each filteredVaults as vault (vault.name)} + {#each Array.from(vault.passwords.map((password) => password[1])) as password ((password.owner, password.parentVaultName, password.passwordName))} + + {/each} + {/each} +
+ {:else} +
You don't have any notes.
+ + {/if} + {:else if $vaultsStore.state === "error"} +
Could not load passwords.
+ {/if} +
diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/SharingEditor.svelte b/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/SharingEditor.svelte new file mode 100644 index 0000000000..f3fe7b5654 --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/SharingEditor.svelte @@ -0,0 +1,222 @@ + + +

Users

+{#if canManage} +

+ Add users by their principal to allow them viewing or editing the vault. +

+{:else} +

+ This vault is shared with you. It is + owned by + {editedVault.owner}. +

+

Users with whom the vault is shared:

+{/if} +
+ {#each editedVault.users as sharing (sharing[0].toText())} + + {/each} + + + +
diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/SidebarLayout.svelte b/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/SidebarLayout.svelte new file mode 100644 index 0000000000..94a1e1fe5a --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/SidebarLayout.svelte @@ -0,0 +1,84 @@ + + +
+ +
+
+ +
+ +
+
+
+
diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/Spinner.svelte b/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/Spinner.svelte new file mode 100644 index 0000000000..74904b535a --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/Spinner.svelte @@ -0,0 +1,5 @@ + + + diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/Vault.svelte b/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/Vault.svelte new file mode 100644 index 0000000000..3783517611 --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/Vault.svelte @@ -0,0 +1,150 @@ + + +
+ + + + + Vault: {vault.name} + + + {#if $vaultsStore.state === "loaded" && $vaultsStore.list.length > 0} + New password + {/if} + +
+ +
+ {#if $vaultsStore.state === "loading"} + + Loading vault... + {:else if $vaultsStore.state === "loaded"} +
+

+ {vaultSummary} +

+
+
+ + +
+ +
+

Passwords

+
+ {#if vault.passwords.length === 0} +
+ You don't have any passwords in this vault. +
+ + {:else} +
+ {#each vault.passwords as password ((password[1].owner, password[1].parentVaultName, password[1].passwordName))} + +
+

+ {password[1].passwordName}: "{password[1] + .content}" +

+
+
+ {/each} +
+ {/if} +
+ + {/if} +
diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/Vaults.svelte b/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/Vaults.svelte new file mode 100644 index 0000000000..f7f42947cb --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/src/components/Vaults.svelte @@ -0,0 +1,90 @@ + + +
+ Your vaults + + {#if $vaultsStore.state === "loaded" && $vaultsStore.list.length > 0} + New password + {/if} + +
+
+ {#if $vaultsStore.state === "loading"} + + Loading vaults... + {:else if $vaultsStore.state === "loaded"} + {#if $vaultsStore.list.length > 0} +
+ +
+ +
+ {#each filteredVaults as vault ([vault.owner, vault.name])} + +
+

+ "{vault.name}" owned by {vault.owner} +

+
+
+ {/each} +
+ {:else} +
+ You don't have any vaults. +
+ + {/if} + {:else if $vaultsStore.state === "error"} +
Could not load vaults.
+ {/if} +
diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/src/lib/encrypted_maps.ts b/motoko/vetkeys/password_manager_with_metadata/frontend/src/lib/encrypted_maps.ts new file mode 100644 index 0000000000..6fc0287456 --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/src/lib/encrypted_maps.ts @@ -0,0 +1,22 @@ +import { HttpAgent } from "@icp-sdk/core/agent"; +import { + DefaultEncryptedMapsClient, + EncryptedMaps, +} from "@icp-sdk/vetkeys/encrypted_maps"; +import { safeGetCanisterEnv } from "@icp-sdk/core/agent/canister-env"; + +const canisterEnv = safeGetCanisterEnv<{ + "PUBLIC_CANISTER_ID:backend": string; +}>(); + +export function createEncryptedMaps(agent: HttpAgent): EncryptedMaps { + const canisterId = + canisterEnv?.["PUBLIC_CANISTER_ID:backend"]; + if (!canisterId) { + throw new Error( + "Canister ID for backend is not set", + ); + } + + return new EncryptedMaps(new DefaultEncryptedMapsClient(agent, canisterId)); +} diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/src/lib/init.ts b/motoko/vetkeys/password_manager_with_metadata/frontend/src/lib/init.ts new file mode 100644 index 0000000000..e69de29bb2 diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/src/lib/password.ts b/motoko/vetkeys/password_manager_with_metadata/frontend/src/lib/password.ts new file mode 100644 index 0000000000..84ad07680c --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/src/lib/password.ts @@ -0,0 +1,31 @@ +import type { Principal } from "@icp-sdk/core/principal"; +import type { PasswordMetadata } from "../bindings/declarations/backend.did"; + +export interface PasswordModel { + owner: Principal; + parentVaultName: string; + passwordName: string; + content: string; + metadata: PasswordMetadata; +} + +export function passwordFromContent( + owner: Principal, + parentVaultName: string, + passwordName: string, + content: string, + metadata: PasswordMetadata, +): PasswordModel { + return { + owner, + parentVaultName, + passwordName, + content, + metadata, + }; +} + +export function summarize(password: PasswordModel, maxLength = 50) { + const text = password.content.replace(/<[^>]+>/, ""); + return text.slice(0, maxLength) + (text.length > maxLength ? "..." : ""); +} diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/src/lib/password_manager.ts b/motoko/vetkeys/password_manager_with_metadata/frontend/src/lib/password_manager.ts new file mode 100644 index 0000000000..131eacd51d --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/src/lib/password_manager.ts @@ -0,0 +1,182 @@ +import { Actor, HttpAgent, type ActorSubclass } from "@icp-sdk/core/agent"; +import { safeGetCanisterEnv } from "@icp-sdk/core/agent/canister-env"; +import type { Principal } from "@icp-sdk/core/principal"; +import { EncryptedMaps } from "@icp-sdk/vetkeys/encrypted_maps"; +import { + idlFactory, + type _SERVICE, +} from "../bindings/declarations/backend.did"; +import { createEncryptedMaps } from "./encrypted_maps"; +import { passwordFromContent, type PasswordModel } from "../lib/password"; +import { vaultFromContent, type VaultModel } from "../lib/vault"; + +const canisterEnv = safeGetCanisterEnv<{ + "PUBLIC_CANISTER_ID:backend": string; +}>(); + +export class PasswordManager { + /// The actor class representing the full interface of the canister. + private readonly canisterClient: ActorSubclass<_SERVICE>; + // TODO: inaccessible API are get, instert and remove + readonly encryptedMaps: EncryptedMaps; + + constructor( + canisterClient: ActorSubclass<_SERVICE>, + encryptedMaps: EncryptedMaps, + ) { + this.canisterClient = canisterClient; + this.encryptedMaps = encryptedMaps; + } + + async setPassword( + owner: Principal, + vault: string, + passwordName: string, + password: Uint8Array, + tags: string[], + url: string, + ): Promise<{ Ok: null } | { Err: string }> { + const encryptedPassword = await this.encryptedMaps.encryptFor( + owner, + new TextEncoder().encode(vault), + new TextEncoder().encode(passwordName), + password, + ); + const maybeError = + await this.canisterClient.insert_encrypted_value_with_metadata( + owner, + stringToBytebuf(vault), + stringToBytebuf(passwordName), + { inner: encryptedPassword }, + tags, + url, + ); + if ("Err" in maybeError) { + return maybeError; + } else { + return { Ok: null }; + } + } + + async getDecryptedVaults(owner: Principal): Promise { + const vaultsSharedWithMe = + await this.encryptedMaps.getAccessibleSharedMapNames(); + const vaultsOwnedByMeResult = + await this.encryptedMaps.getOwnedNonEmptyMapNames(); + + const vaultIds = new Array<[Principal, Uint8Array]>(); + for (const vaultName of vaultsOwnedByMeResult) { + vaultIds.push([owner, vaultName]); + } + for (const [otherOwner, vaultName] of vaultsSharedWithMe) { + vaultIds.push([otherOwner, vaultName]); + } + + const vaults = []; + + for (const [otherOwner, vaultName] of vaultIds) { + const result = + await this.canisterClient.get_encrypted_values_for_map_with_metadata( + otherOwner, + { inner: vaultName }, + ); + if ("Err" in result) { + throw new Error(result.Err); + } + + const passwords = new Array<[string, PasswordModel]>(); + const vaultNameString = new TextDecoder().decode(vaultName); + for (const [ + passwordNameBytebuf, + encryptedData, + passwordMetadata, + ] of result.Ok) { + const passwordNameBytes = Uint8Array.from( + passwordNameBytebuf.inner, + ); + const passwordNameString = new TextDecoder().decode( + passwordNameBytes, + ); + const data = await this.encryptedMaps.decryptFor( + otherOwner, + vaultName, + passwordNameBytes, + Uint8Array.from(encryptedData.inner), + ); + + const passwordContent = new TextDecoder().decode(data); + const password = passwordFromContent( + otherOwner, + vaultNameString, + passwordNameString, + passwordContent, + passwordMetadata, + ); + passwords.push([passwordNameString, password]); + } + + const usersResult = await this.encryptedMaps + .getSharedUserAccessForMap(otherOwner, vaultName) + .catch(() => []); + + vaults.push( + vaultFromContent( + otherOwner, + vaultNameString, + passwords, + usersResult, + ), + ); + } + + return vaults; + } + + async removePassword( + owner: Principal, + vault: string, + passwordName: string, + ): Promise<{ Ok: null } | { Err: string }> { + const maybeError = + await this.canisterClient.remove_encrypted_value_with_metadata( + owner, + stringToBytebuf(vault), + stringToBytebuf(passwordName), + ); + if ("Err" in maybeError) { + return maybeError; + } else { + return { Ok: null }; + } + } +} + +export async function createPasswordManager(agentOptions?: { + identity?: HttpAgent["config"]["identity"]; +}): Promise { + const canisterId = + canisterEnv?.["PUBLIC_CANISTER_ID:backend"]; + if (!canisterId) { + throw new Error( + "Canister ID for backend is not set", + ); + } + + const agent = await HttpAgent.create({ + ...agentOptions, + host: window.location.origin, + rootKey: canisterEnv?.IC_ROOT_KEY, + }); + + const encryptedMaps = createEncryptedMaps(agent); + const canisterClient = Actor.createActor<_SERVICE>(idlFactory, { + agent, + canisterId, + }); + + return new PasswordManager(canisterClient, encryptedMaps); +} + +function stringToBytebuf(str: string): { inner: Uint8Array } { + return { inner: new TextEncoder().encode(str) }; +} diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/src/lib/sleep.ts b/motoko/vetkeys/password_manager_with_metadata/frontend/src/lib/sleep.ts new file mode 100644 index 0000000000..38caca0c10 --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/src/lib/sleep.ts @@ -0,0 +1,3 @@ +export function sleep(ms: number) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/src/lib/vault.ts b/motoko/vetkeys/password_manager_with_metadata/frontend/src/lib/vault.ts new file mode 100644 index 0000000000..49d302a8d5 --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/src/lib/vault.ts @@ -0,0 +1,31 @@ +import type { Principal } from "@icp-sdk/core/principal"; +import type { PasswordModel } from "./password"; +import type { AccessRights } from "@icp-sdk/vetkeys/encrypted_maps"; + +export interface VaultModel { + owner: Principal; + name: string; + passwords: Array<[string, PasswordModel]>; + users: Array<[Principal, AccessRights]>; +} + +export function vaultFromContent( + owner: Principal, + name: string, + passwords: Array<[string, PasswordModel]>, + users: Array<[Principal, AccessRights]>, +): VaultModel { + return { owner, name, passwords, users }; +} + +export function summarize(vault: VaultModel, maxLength = 1500) { + let text = + "Owner: " + + vault.owner.toString() + + ", " + + vault.users.length + + " users"; + text += ", " + vault.passwords.length + " passwords.\n"; + + return text.slice(0, maxLength) + (text.length > maxLength ? "..." : ""); +} diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/src/main.ts b/motoko/vetkeys/password_manager_with_metadata/frontend/src/main.ts new file mode 100644 index 0000000000..336504f610 --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/src/main.ts @@ -0,0 +1,11 @@ +import "./app.css"; +import App from "./App.svelte"; + +const init = () => { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const app = new App({ + target: document.body, + }); +}; + +init(); diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/src/store/auth.ts b/motoko/vetkeys/password_manager_with_metadata/frontend/src/store/auth.ts new file mode 100644 index 0000000000..1f54fb574e --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/src/store/auth.ts @@ -0,0 +1,130 @@ +import { get, writable } from "svelte/store"; +import { AuthClient, LocalStorage } from "@icp-sdk/auth/client"; +import { DelegationIdentity } from "@icp-sdk/core/identity"; +import type { Principal } from "@icp-sdk/core/principal"; +import { replace } from "svelte-spa-router"; +import { + PasswordManager, + createPasswordManager, +} from "../lib/password_manager.js"; + +export type AuthState = + | { + state: "initializing-auth"; + } + | { + state: "anonymous"; + client: AuthClient; + } + | { + state: "initialized"; + passwordManager: PasswordManager; + client: AuthClient; + principal: Principal; + } + | { + state: "error"; + error: string; + }; + +export const auth = writable({ + state: "initializing-auth", +}); + +async function initAuth() { + const isLocalEnv = + window.location.hostname === "localhost" || + window.location.hostname.endsWith(".localhost"); + // Workaround for https://github.com/dfinity/icp-js-auth/issues/120 + // IdbStorage has a race condition on localhost dev servers. LocalStorage + // avoids IDB on local but uses plain string storage (less secure), so + // production deployments keep the default secure IdbStorage + ECDSA key. + const client = new AuthClient({ + identityProvider: isLocalEnv + ? "http://id.ai.localhost:8000/authorize" + : "https://id.ai/authorize", + ...(isLocalEnv + ? { storage: new LocalStorage(), keyType: "Ed25519" as const } + : {}), + }); + if (client.isAuthenticated()) { + await authenticate(client); + } else { + auth.update(() => ({ + state: "anonymous", + client, + })); + } +} + +void initAuth(); + +export function login() { + const currentAuth = get(auth); + + if (currentAuth.state === "anonymous") { + void (async () => { + try { + await currentAuth.client.signIn({ + maxTimeToLive: BigInt(1800) * BigInt(1_000_000_000), + }); + void authenticate(currentAuth.client); + } catch (error: unknown) { + console.error("Login failed:", error); + } + })(); + } +} + +export async function logout() { + const currentAuth = get(auth); + + if (currentAuth.state === "initialized") { + await currentAuth.client.signOut(); + auth.update(() => ({ + state: "anonymous", + client: currentAuth.client, + })); + await replace("/"); + } +} + +export async function authenticate(client: AuthClient) { + void handleSessionTimeout(client); + + try { + const identity = await client.getIdentity(); + const passwordManager = await createPasswordManager({ identity }); + + auth.update(() => ({ + state: "initialized", + passwordManager, + client, + principal: identity.getPrincipal(), + })); + } catch (e) { + auth.update(() => ({ + state: "error", + error: (e as Error).message || "An error occurred", + })); + } +} + +// set a timer when the II session will expire and log the user out +async function handleSessionTimeout(client: AuthClient) { + try { + const identity = await client.getIdentity(); + if (!(identity instanceof DelegationIdentity)) return; + + const chain = identity.getDelegation(); + // expiration is a BigInt of nanoseconds since epoch + const expirationMs = + Number(chain.delegations[0].delegation.expiration) / 1_000_000; + + setTimeout(() => { + void logout(); + }, expirationMs - Date.now()); + } catch { + console.error("Could not handle delegation expiry."); + } +} diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/src/store/draft.ts b/motoko/vetkeys/password_manager_with_metadata/frontend/src/store/draft.ts new file mode 100644 index 0000000000..85a8ec2e40 --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/src/store/draft.ts @@ -0,0 +1,36 @@ +import { writable } from "svelte/store"; +import { auth } from "./auth"; + +interface DraftModel { + content: string; +} + +let initialDraft: DraftModel = { + content: "", +}; + +try { + const getDraft = localStorage.getItem("draft"); + if (getDraft) { + const savedDraft = JSON.parse(getDraft) as DraftModel; + if ("content" in savedDraft && "tags" in savedDraft) { + initialDraft = savedDraft; + } + } else { + throw new Error("Draft not found"); + } +} catch { + // ignore error +} + +export const draft = writable(initialDraft); + +draft.subscribe((draft) => { + localStorage.setItem("draft", JSON.stringify(draft)); +}); + +auth.subscribe(($auth) => { + if ($auth.state === "anonymous") { + draft.set(initialDraft); + } +}); diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/src/store/notifications.ts b/motoko/vetkeys/password_manager_with_metadata/frontend/src/store/notifications.ts new file mode 100644 index 0000000000..d876301531 --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/src/store/notifications.ts @@ -0,0 +1,30 @@ +import { writable } from "svelte/store"; + +export interface Notification { + type: "error" | "info" | "success"; + message: string; + id: number; +} + +export type NewNotification = Omit; + +let nextId = 0; + +export const notifications = writable([]); + +export function addNotification(notification: NewNotification, timeout = 2000) { + const id = nextId++; + + notifications.update(($n) => [...$n, { ...notification, id }]); + + setTimeout(() => { + notifications.update(($n) => $n.filter((n) => n.id != id)); + }, timeout); +} + +export function showError(e: Error, message: string): never { + addNotification({ type: "error", message }); + console.error(e); + console.error(e.stack); + throw e; +} diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/src/store/vaults.ts b/motoko/vetkeys/password_manager_with_metadata/frontend/src/store/vaults.ts new file mode 100644 index 0000000000..f56f5dcb8d --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/src/store/vaults.ts @@ -0,0 +1,147 @@ +import { writable } from "svelte/store"; +import { type PasswordModel } from "../lib/password"; +import { type VaultModel } from "../lib/vault"; +import { auth } from "./auth"; +import { showError } from "./notifications"; +import { type AccessRights } from "@icp-sdk/vetkeys/encrypted_maps"; +import type { Principal } from "@icp-sdk/core/principal"; +import type { PasswordManager } from "../lib/password_manager"; + +export const vaultsStore = writable< + | { + state: "uninitialized"; + } + | { + state: "loading"; + } + | { + state: "loaded"; + list: VaultModel[]; + } + | { + state: "error"; + } +>({ state: "uninitialized" }); + +let vaultPollerHandle: ReturnType | null; + +function updateVaults(vaults: VaultModel[]) { + vaultsStore.set({ + state: "loaded", + list: vaults, + }); +} + +export async function refreshVaults( + owner: Principal, + passwordManager: PasswordManager, +) { + updateVaults(await passwordManager.getDecryptedVaults(owner)); +} + +export async function setPassword( + parentVaultOwner: Principal, + parentVaultName: string, + passwordName: string, + password: string, + url: string, + tags: string[], + passwordManager: PasswordManager, +) { + const result = await passwordManager.setPassword( + parentVaultOwner, + parentVaultName, + passwordName, + new TextEncoder().encode(password), + tags, + url, + ); + if ("Err" in result) { + throw new Error(result.Err); + } +} + +export async function removePassword( + password: PasswordModel, + passwordManager: PasswordManager, +) { + const result = await passwordManager.removePassword( + password.owner, + password.parentVaultName, + password.passwordName, + ); + if ("Err" in result) { + throw new Error(result.Err); + } +} + +export async function addUser( + owner: Principal, + vaultName: string, + user: Principal, + userRights: AccessRights, + passwordManager: PasswordManager, +) { + await passwordManager.encryptedMaps.setUserRights( + owner, + new TextEncoder().encode(vaultName), + user, + userRights, + ); +} + +export async function removeUser( + owner: Principal, + vaultName: string, + user: Principal, + passwordManager: PasswordManager, +) { + await passwordManager.encryptedMaps.removeUser( + owner, + new TextEncoder().encode(vaultName), + user, + ); +} + +auth.subscribe((auth) => { + if (!auth) { + throw Error("$auth is undefined"); + } + if (auth.state === "initialized") { + if (vaultPollerHandle !== null) { + clearInterval(vaultPollerHandle); + vaultPollerHandle = null; + } + + vaultsStore.set({ + state: "loading", + }); + + void (async () => { + try { + await refreshVaults(auth.principal, auth.passwordManager).catch( + (e) => showError(e as Error, "Could not poll vaults."), + ); + + vaultPollerHandle = setInterval(() => { + void refreshVaults( + auth.principal, + auth.passwordManager, + ).catch((e) => + showError(e as Error, "Could not poll vaults."), + ); + }, 3000); + } catch { + vaultsStore.set({ + state: "error", + }); + } + })(); + } else if (auth.state === "anonymous" && vaultPollerHandle !== null) { + clearInterval(vaultPollerHandle); + vaultPollerHandle = null; + vaultsStore.set({ + state: "uninitialized", + }); + } +}); diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/src/vite-env.d.ts b/motoko/vetkeys/password_manager_with_metadata/frontend/src/vite-env.d.ts new file mode 100644 index 0000000000..4078e7476a --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/src/vite-env.d.ts @@ -0,0 +1,2 @@ +/// +/// diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/svelte.config.js b/motoko/vetkeys/password_manager_with_metadata/frontend/svelte.config.js new file mode 100644 index 0000000000..9a3adfbed9 --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/svelte.config.js @@ -0,0 +1,7 @@ +import { vitePreprocess } from "@sveltejs/vite-plugin-svelte"; + +export default { + // Consult https://svelte.dev/docs#compile-time-svelte-preprocess + // for more information about preprocessors + preprocess: vitePreprocess(), +}; diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/tailwind.config.mjs b/motoko/vetkeys/password_manager_with_metadata/frontend/tailwind.config.mjs new file mode 100644 index 0000000000..18a39dbc2f --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/tailwind.config.mjs @@ -0,0 +1,9 @@ +import daisyui from "daisyui"; + +export default { + content: ["./index.html", "./src/**/*.{svelte,js,ts,jsx,tsx}"], + theme: { + extend: {}, + }, + plugins: [daisyui], +}; diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/tsconfig.json b/motoko/vetkeys/password_manager_with_metadata/frontend/tsconfig.json new file mode 100644 index 0000000000..ba869ee473 --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/tsconfig.json @@ -0,0 +1,24 @@ +{ + "extends": "@tsconfig/svelte/tsconfig.json", + "compilerOptions": { + "target": "ES2022", + "useDefineForClassFields": true, + "module": "ES2022", + "lib": [ + "ES2022", + "DOM", + "DOM.Iterable" + ], + "skipLibCheck": true, + /* Bundler mode */ + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "isolatedModules": true, + "moduleDetection": "force", + "noEmit": true, + "noUncheckedSideEffectImports": true + }, + "include": [ + "src" + ] +} diff --git a/motoko/vetkeys/password_manager_with_metadata/frontend/vite.config.js b/motoko/vetkeys/password_manager_with_metadata/frontend/vite.config.js new file mode 100644 index 0000000000..169539f3bb --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/frontend/vite.config.js @@ -0,0 +1,67 @@ +import { defineConfig } from "vite"; +import { svelte } from "@sveltejs/vite-plugin-svelte"; +import tailwindcss from "tailwindcss"; +import autoprefixer from "autoprefixer"; +import css from "rollup-plugin-css-only"; +import { icpBindgen } from "@icp-sdk/bindgen/plugins/vite"; +import { execSync } from "child_process"; + +function getDevServerConfig() { + try { + const canisterId = execSync("icp canister status backend -e local -i", { + encoding: "utf-8", + stdio: "pipe", + }).trim(); + const networkStatus = JSON.parse( + execSync("icp network status --json", { + encoding: "utf-8", + stdio: "pipe", + }) + ); + return { + headers: { + "Set-Cookie": `ic_env=${encodeURIComponent( + `ic_root_key=${networkStatus.root_key}&PUBLIC_CANISTER_ID:backend=${canisterId}` + )}; SameSite=Lax;`, + }, + proxy: { + "/api": { target: "http://127.0.0.1:8000", changeOrigin: true }, + }, + }; + } catch {} + + throw new Error( + "No local network running. Start with:\n icp network start -d && icp deploy" + ); +} + +export default defineConfig(({ command }) => ({ + base: "./", + plugins: [ + svelte(), + css({ output: "bundle.css" }), + icpBindgen({ + didFile: "../backend/backend.did", + outDir: "./src/bindings", + }), + ], + css: { + postcss: { + plugins: [autoprefixer(), tailwindcss()], + }, + }, + build: { + sourcemap: true, + rollupOptions: { + output: { + inlineDynamicImports: true, + }, + }, + }, + resolve: { + alias: { + "@dfinity/vetkeys": "@icp-sdk/vetkeys", + }, + }, + server: command === "serve" ? getDevServerConfig() : undefined, +})); diff --git a/rust/vetkeys/password_manager_with_metadata/motoko/icp.yaml b/motoko/vetkeys/password_manager_with_metadata/icp.yaml similarity index 60% rename from rust/vetkeys/password_manager_with_metadata/motoko/icp.yaml rename to motoko/vetkeys/password_manager_with_metadata/icp.yaml index 09bb4252c5..ba5979ac3f 100644 --- a/rust/vetkeys/password_manager_with_metadata/motoko/icp.yaml +++ b/motoko/vetkeys/password_manager_with_metadata/icp.yaml @@ -1,18 +1,19 @@ canisters: - - name: password_manager_with_metadata + - name: backend recipe: type: "@dfinity/motoko@v5.0.0" init_args: type: text value: "(\"test_key_1\")" - - name: www + - name: frontend recipe: type: "@dfinity/asset-canister@v2.2.1" configuration: - dir: dist + dir: frontend/dist build: - - cd frontend && npm i --include=dev && npm run build && cd - && rm -rf dist; mv frontend/dist ./ + - npm install --prefix frontend + - npm run build --prefix frontend networks: - name: local diff --git a/motoko/vetkeys/password_manager_with_metadata/mops.toml b/motoko/vetkeys/password_manager_with_metadata/mops.toml new file mode 100644 index 0000000000..5dae136934 --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/mops.toml @@ -0,0 +1,16 @@ +[toolchain] +moc = "1.11.0" + +[dependencies] +core = "2.5.0" +ic-vetkeys = "0.5.0" + +[moc] +# M0236: use context dot notation +# M0237: redundant explicit implicit arguments +# M0223: redundant type instantiation +args = ["--default-persistent-actors", "-W=M0236,M0237,M0223"] + +[canisters.backend] +main = "backend/app.mo" +candid = "backend/backend.did" diff --git a/motoko/vetkeys/password_manager_with_metadata/package.json b/motoko/vetkeys/password_manager_with_metadata/package.json new file mode 100644 index 0000000000..a874aee1a8 --- /dev/null +++ b/motoko/vetkeys/password_manager_with_metadata/package.json @@ -0,0 +1,13 @@ +{ + "name": "password_manager_with_metadata", + "private": true, + "type": "module", + "scripts": { + "build": "npm run build --workspaces --if-present", + "prebuild": "npm run prebuild --workspaces --if-present", + "dev": "npm run dev --workspaces --if-present" + }, + "workspaces": [ + "frontend" + ] +} diff --git a/rust/vetkeys/password_manager_with_metadata/rust/Cargo.toml b/rust/vetkeys/password_manager_with_metadata/Cargo.toml similarity index 100% rename from rust/vetkeys/password_manager_with_metadata/rust/Cargo.toml rename to rust/vetkeys/password_manager_with_metadata/Cargo.toml diff --git a/rust/vetkeys/password_manager_with_metadata/README.md b/rust/vetkeys/password_manager_with_metadata/README.md index 719685c3a1..cd06c10aa5 100644 --- a/rust/vetkeys/password_manager_with_metadata/README.md +++ b/rust/vetkeys/password_manager_with_metadata/README.md @@ -1,14 +1,12 @@ -# VetKey Password Manager with Metadata +# VetKey Password Manager with Metadata (Rust) - +[View this sample's code on GitHub](https://github.com/dfinity/examples/tree/master/rust/vetkeys/password_manager_with_metadata) + +Also available in: [Motoko](../../../motoko/vetkeys/password_manager_with_metadata) The **VetKey Password Manager** is an example application demonstrating how to use **VetKeys** and **Encrypted Maps** to build a secure, decentralized password manager on the **Internet Computer (IC)**. This application allows users to create password vaults, store encrypted passwords, and share vaults with other users via their **Internet Identity Principal**. -This version of the application extends the basic password manager by supporting unencrypted metadata, such as URLs and tags, alongside encrypted passwords. The goal is to demonstrate how to make atomic updates to the Encrypted Maps canister, storing both encrypted and unencrypted data in a single update call. +This version extends the basic password manager by supporting unencrypted metadata, such as URLs and tags, alongside encrypted passwords. The goal is to demonstrate how to make atomic updates to the Encrypted Maps canister, storing both encrypted and unencrypted data in a single update call. ## Features @@ -17,71 +15,72 @@ This version of the application extends the basic password manager by supporting - **Access Control**: Vaults can be shared with other users via their **Internet Identity Principal**. - **Atomic Updates**: Stores encrypted passwords along with unencrypted metadata in a single update call. -## Setup +## Build and deploy from the command line ### Prerequisites -- [ICP CLI](https://cli.internetcomputer.org) -- [npm](https://www.npmjs.com/package/npm) - -### (Optionally) Choose a Different Master Key +- Install [Node.js](https://nodejs.org/en/download/) +- Install [icp-cli](https://cli.internetcomputer.org): `npm install -g @icp-sdk/icp-cli @icp-sdk/ic-wasm` +- Install the [Rust toolchain](https://www.rust-lang.org/tools/install), then add the WASM target: `rustup target add wasm32-unknown-unknown` -This example uses `test_key_1` by default. To use a different [available master key](https://docs.internetcomputer.org/concepts/vetkeys/#api-overview), change the `init_args` value in `icp.yaml` to the desired key before running `icp deploy` in the next step. +### (Optionally) choose a different master key -### Folder Structure +This example uses `test_key_1` by default. To use a different [available master key](https://docs.internetcomputer.org/concepts/vetkeys/#api-overview), change the `init_args` value in `icp.yaml` before deploying. -This example provides both a **Rust** and a **Motoko** backend, sharing a common `frontend/`: +### Install -``` -password_manager_with_metadata/ -├── frontend/ ← shared frontend (symlinked into rust/ and motoko/) -├── motoko/ ← Motoko backend + icp.yaml -└── rust/ ← Rust backend + icp.yaml +```bash +git clone https://github.com/dfinity/examples +cd examples/rust/vetkeys/password_manager_with_metadata ``` -### Deploy the Canisters Locally +### Deploy -Deploy with the **Motoko** backend: ```bash -cd motoko -icp network start -d && icp deploy +icp network start -d +icp deploy ``` -Or deploy with the **Rust** backend: -```bash -cd rust -icp network start -d && icp deploy -``` +Open the frontend URL printed by `icp deploy`. + +To run the frontend in development mode with hot reloading (after `icp deploy`): -To run the frontend in development mode with hot reloading (after running `icp deploy`): ```bash -cd frontend -npm run dev:motoko # if you deployed the Motoko backend -# or -npm run dev:rust # if you deployed the Rust backend +npm run dev ``` -When you are done testing, stop the local network to free up resources and unblock the default port for other projects: +When done, stop the local network to free up the port for other projects: + ```bash icp network stop ``` -## Example Components +## Example components + +### Backend (`backend/`) + +An **Encrypted Maps**-enabled Rust canister that stores encrypted passwords together with unencrypted metadata (URLs, tags) in atomic update calls. + +> **Note.** A plain Encrypted Maps canister can be generated by an upstream Rust macro — `ic_vetkeys::export_encrypted_maps_canister!(...)` — that is in progress ([dfinity/vetkeys#404](https://github.com/dfinity/vetkeys/pull/404)). This example instead hand-writes a custom canister so it can add the metadata-aware methods on top of the Encrypted Maps interface. -### Backend +### Frontend (`frontend/`) -The backend consists of an **Encrypted Maps**-enabled canister that securely stores passwords. +A **Svelte** application for managing vaults and passwords. It uses the `@icp-sdk/vetkeys` Encrypted Maps client for the crypto operations and a canister actor (bindings generated from `backend/backend.did` by the `@icp-sdk/bindgen` Vite plugin) for the metadata methods. -### Frontend +## Updating the Candid interface -The frontend is a **Svelte** application providing a user-friendly interface for managing vaults and passwords. +`backend/backend.did` defines the backend's public interface; the frontend bindings are generated from it during the build. If you change the backend's public API, regenerate it: + +```bash +icp build backend && candid-extractor target/wasm32-unknown-unknown/release/backend.wasm > backend/backend.did +``` ## Limitations -This example dapp does not implement key rotation, which is strongly recommended in a production environment. -Key rotation involves periodically changing encryption keys and re-encrypting data to enhance security. -In a production dapp, key rotation would be useful to limit the impact of potential key compromise if a malicious party gains access to a key, or to limit access when users are added or removed from note sharing. +This example app does not implement key rotation, which is strongly recommended in a production environment. Key rotation involves periodically changing encryption keys and re-encrypting data to enhance security. In a production app, key rotation would be useful to limit the impact of a potential key compromise, or to limit access when users are added to or removed from sharing. -## Additional Resources +## Additional resources -- **[Basic Password Manager](../password_manager/)** - If you want a simpler example without metadata. +- **[Basic Password Manager](../password_manager)** — a simpler example without metadata. +- **[What are VetKeys](https://docs.internetcomputer.org/concepts/vetkeys)** — more information about VetKeys and VetKD. +- [Security best practices](https://docs.internetcomputer.org/guides/security/overview/) diff --git a/rust/vetkeys/password_manager_with_metadata/rust/backend/Cargo.toml b/rust/vetkeys/password_manager_with_metadata/backend/Cargo.toml similarity index 88% rename from rust/vetkeys/password_manager_with_metadata/rust/backend/Cargo.toml rename to rust/vetkeys/password_manager_with_metadata/backend/Cargo.toml index 964961938e..3480734795 100644 --- a/rust/vetkeys/password_manager_with_metadata/rust/backend/Cargo.toml +++ b/rust/vetkeys/password_manager_with_metadata/backend/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "ic-vetkd-example-password-manager-with-metadata-backend" +name = "backend" authors = ["DFINITY Stiftung"] version = "0.1.0" edition = "2021" diff --git a/rust/vetkeys/password_manager_with_metadata/rust/backend/backend.did b/rust/vetkeys/password_manager_with_metadata/backend/backend.did similarity index 100% rename from rust/vetkeys/password_manager_with_metadata/rust/backend/backend.did rename to rust/vetkeys/password_manager_with_metadata/backend/backend.did diff --git a/rust/vetkeys/password_manager_with_metadata/rust/backend/src/lib.rs b/rust/vetkeys/password_manager_with_metadata/backend/src/lib.rs similarity index 100% rename from rust/vetkeys/password_manager_with_metadata/rust/backend/src/lib.rs rename to rust/vetkeys/password_manager_with_metadata/backend/src/lib.rs diff --git a/rust/vetkeys/password_manager_with_metadata/frontend/.gitignore b/rust/vetkeys/password_manager_with_metadata/frontend/.gitignore new file mode 100644 index 0000000000..061e2e66e1 --- /dev/null +++ b/rust/vetkeys/password_manager_with_metadata/frontend/.gitignore @@ -0,0 +1,3 @@ +node_modules/ +dist/ +src/bindings/ diff --git a/rust/vetkeys/password_manager_with_metadata/frontend/.prettierignore b/rust/vetkeys/password_manager_with_metadata/frontend/.prettierignore deleted file mode 100644 index 187eec9533..0000000000 --- a/rust/vetkeys/password_manager_with_metadata/frontend/.prettierignore +++ /dev/null @@ -1,6 +0,0 @@ -# Ignore artifacts: -build -coverage -dist -README.md -**/declarations/ diff --git a/rust/vetkeys/password_manager_with_metadata/frontend/.prettierrc b/rust/vetkeys/password_manager_with_metadata/frontend/.prettierrc deleted file mode 100644 index 2b9bd83ee0..0000000000 --- a/rust/vetkeys/password_manager_with_metadata/frontend/.prettierrc +++ /dev/null @@ -1,5 +0,0 @@ -{ - "plugins": ["prettier-plugin-svelte"], - "tabWidth": 4, - "overrides": [{ "files": ["*.svelte"], "options": { "parser": "svelte" } }] -} diff --git a/rust/vetkeys/password_manager_with_metadata/frontend/eslint.config.mjs b/rust/vetkeys/password_manager_with_metadata/frontend/eslint.config.mjs deleted file mode 100644 index 1606408854..0000000000 --- a/rust/vetkeys/password_manager_with_metadata/frontend/eslint.config.mjs +++ /dev/null @@ -1,55 +0,0 @@ -// @ts-check - -import eslint from "@eslint/js"; -import eslintPluginPrettierRecommended from "eslint-plugin-prettier/recommended"; -import globals from "globals"; -import tseslint from "typescript-eslint"; -import svelteConfig from "./svelte.config.js"; -import svelte from "eslint-plugin-svelte"; - -export default tseslint.config( - eslint.configs.recommended, - tseslint.configs.recommendedTypeChecked, - ...svelte.configs.recommended, - eslintPluginPrettierRecommended, - { - languageOptions: { - parserOptions: { - projectService: { - defaultProject: "./tsconfig.json", - }, - tsconfigRootDir: import.meta.dirname, - }, - globals: { - ...globals.browser, - ...globals.es2020, - }, - }, - }, - { - files: ["**/*.svelte", "**/*.svelte.ts", "**/*.svelte.js"], - languageOptions: { - parserOptions: { - projectService: true, - extraFileExtensions: [".svelte"], - parser: tseslint.parser, - svelteConfig, - }, - }, - }, - { - ignores: [ - "dist/", - "src/declarations", - "*.config.js", - "*.config.cjs", - "*.config.mjs", - ], - }, - { - rules: { - "@typescript-eslint/no-unsafe-argument": "off", - "@typescript-eslint/no-unsafe-member-access": "off", - }, - }, -); diff --git a/rust/vetkeys/password_manager_with_metadata/frontend/package.json b/rust/vetkeys/password_manager_with_metadata/frontend/package.json index a50afea070..adaf711ac4 100644 --- a/rust/vetkeys/password_manager_with_metadata/frontend/package.json +++ b/rust/vetkeys/password_manager_with_metadata/frontend/package.json @@ -1,52 +1,35 @@ { - "name": "password-manager-with-metadata-frontend", - "version": "0.1.0", - "license": "Apache-2.0", - "type": "module", - "scripts": { - "build": "npm run build:bindings && vite build", - "dev": "printf '\\nNo backend specified. Use one of:\\n\\n npm run dev:motoko\\n npm run dev:rust\\n\\n' && exit 1", - "dev:motoko": "npm run build:bindings && BACKEND=motoko vite", - "dev:rust": "npm run build:bindings && BACKEND=rust vite", - "build:bindings": "cd scripts && ./gen_bindings.sh", - "lint": "eslint", - "prettier": "prettier --write .", - "prettier-check": "prettier --check .", - "preview": "vite preview" - }, - "devDependencies": { - "@eslint/js": "^9.22.0", - "@rollup/plugin-typescript": "^12.1.2", - "@tailwindcss/postcss": "^4.0.6", - "@tailwindcss/vite": "^4.0.0", - "@tsconfig/svelte": "^5.0.4", - "@typewriter/delta": "^1.2.4", - "autoprefixer": "^10.4.20", - "eslint": "^9.22.0", - "eslint-config-prettier": "^10.1.5", - "eslint-plugin-prettier": "^5.2.5", - "eslint-plugin-svelte": "^3.3.3", - "globals": "^16.0.0", - "prettier": "3.5.3", - "prettier-plugin-svelte": "^3.3.3", - "rollup-plugin-css-only": "^4.5.2", - "tslib": "^2.8.1", - "typescript-eslint": "^8.26.1", - "vite": "^5.4.21", - "vite-plugin-compression": "^0.5.1", - "vite-plugin-eslint": "^1.8.1" - }, - "dependencies": { - "@icp-sdk/auth": "^7.1.0", - "@icp-sdk/core": "^5.4.0", - "@icp-sdk/vetkeys": "^0.5.0-beta.0", - "@sveltejs/vite-plugin-svelte": "^3.0.2", - "daisyui": "^4.12.23", - "save": "^2.9.0", - "svelte": "^4.2.19", - "svelte-icons": "^2.1.0", - "svelte-spa-router": "^4.0.1", - "tailwindcss": "^3.0.17", - "typewriter-editor": "^0.9.4" - } + "name": "frontend", + "private": true, + "type": "module", + "scripts": { + "prebuild": "npm i --include=dev", + "dev": "vite", + "build": "vite build", + "preview": "vite preview" + }, + "devDependencies": { + "@icp-sdk/bindgen": "~0.2.2", + "@rollup/plugin-typescript": "^12.1.2", + "@tailwindcss/postcss": "^4.0.6", + "@tailwindcss/vite": "^4.0.0", + "@tsconfig/svelte": "^5.0.4", + "@typewriter/delta": "^1.2.4", + "autoprefixer": "^10.4.20", + "rollup-plugin-css-only": "^4.5.2", + "tslib": "^2.8.1", + "vite": "^5.4.21" + }, + "dependencies": { + "@icp-sdk/auth": "^7.1.0", + "@icp-sdk/core": "^5.4.0", + "@icp-sdk/vetkeys": "^0.5.0-beta.0", + "@sveltejs/vite-plugin-svelte": "^3.0.2", + "daisyui": "^4.12.23", + "svelte": "^4.2.19", + "svelte-icons": "^2.1.0", + "svelte-spa-router": "^4.0.1", + "tailwindcss": "^3.0.17", + "typewriter-editor": "^0.9.4" + } } diff --git a/rust/vetkeys/password_manager_with_metadata/frontend/scripts/gen_bindings.sh b/rust/vetkeys/password_manager_with_metadata/frontend/scripts/gen_bindings.sh deleted file mode 100755 index 624b678351..0000000000 --- a/rust/vetkeys/password_manager_with_metadata/frontend/scripts/gen_bindings.sh +++ /dev/null @@ -1,17 +0,0 @@ -#!/bin/bash -# Bindings are always generated from the Rust backend since both backends -# expose the same Candid interface. - -# Resolve the physical path of this script so that navigating up works -# correctly even when frontend/ is reached via a symlink (e.g. motoko/frontend). -SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd -P) -if command -v candid-extractor >/dev/null 2>&1; then - cd "$SCRIPT_DIR/../../rust/backend" && make extract-candid -fi - -cd "$SCRIPT_DIR/../.." -rm -rf frontend/src/declarations/password_manager_with_metadata -mkdir -p frontend/src/declarations/password_manager_with_metadata -npx --yes @icp-sdk/bindgen --did-file rust/backend/backend.did \ - --out-dir frontend/src/declarations/password_manager_with_metadata \ - --declarations-flat --force diff --git a/rust/vetkeys/password_manager_with_metadata/frontend/src/lib/encrypted_maps.ts b/rust/vetkeys/password_manager_with_metadata/frontend/src/lib/encrypted_maps.ts index e464c683c8..6fc0287456 100644 --- a/rust/vetkeys/password_manager_with_metadata/frontend/src/lib/encrypted_maps.ts +++ b/rust/vetkeys/password_manager_with_metadata/frontend/src/lib/encrypted_maps.ts @@ -6,15 +6,15 @@ import { import { safeGetCanisterEnv } from "@icp-sdk/core/agent/canister-env"; const canisterEnv = safeGetCanisterEnv<{ - "PUBLIC_CANISTER_ID:password_manager_with_metadata": string; + "PUBLIC_CANISTER_ID:backend": string; }>(); export function createEncryptedMaps(agent: HttpAgent): EncryptedMaps { const canisterId = - canisterEnv?.["PUBLIC_CANISTER_ID:password_manager_with_metadata"]; + canisterEnv?.["PUBLIC_CANISTER_ID:backend"]; if (!canisterId) { throw new Error( - "Canister ID for password_manager_with_metadata is not set", + "Canister ID for backend is not set", ); } diff --git a/rust/vetkeys/password_manager_with_metadata/frontend/src/lib/password.ts b/rust/vetkeys/password_manager_with_metadata/frontend/src/lib/password.ts index ff7d78287a..84ad07680c 100644 --- a/rust/vetkeys/password_manager_with_metadata/frontend/src/lib/password.ts +++ b/rust/vetkeys/password_manager_with_metadata/frontend/src/lib/password.ts @@ -1,5 +1,5 @@ import type { Principal } from "@icp-sdk/core/principal"; -import type { PasswordMetadata } from "../declarations/password_manager_with_metadata/backend.did"; +import type { PasswordMetadata } from "../bindings/declarations/backend.did"; export interface PasswordModel { owner: Principal; diff --git a/rust/vetkeys/password_manager_with_metadata/frontend/src/lib/password_manager.ts b/rust/vetkeys/password_manager_with_metadata/frontend/src/lib/password_manager.ts index fe216a6383..131eacd51d 100644 --- a/rust/vetkeys/password_manager_with_metadata/frontend/src/lib/password_manager.ts +++ b/rust/vetkeys/password_manager_with_metadata/frontend/src/lib/password_manager.ts @@ -5,13 +5,13 @@ import { EncryptedMaps } from "@icp-sdk/vetkeys/encrypted_maps"; import { idlFactory, type _SERVICE, -} from "../declarations/password_manager_with_metadata/backend.did"; +} from "../bindings/declarations/backend.did"; import { createEncryptedMaps } from "./encrypted_maps"; import { passwordFromContent, type PasswordModel } from "../lib/password"; import { vaultFromContent, type VaultModel } from "../lib/vault"; const canisterEnv = safeGetCanisterEnv<{ - "PUBLIC_CANISTER_ID:password_manager_with_metadata": string; + "PUBLIC_CANISTER_ID:backend": string; }>(); export class PasswordManager { @@ -155,10 +155,10 @@ export async function createPasswordManager(agentOptions?: { identity?: HttpAgent["config"]["identity"]; }): Promise { const canisterId = - canisterEnv?.["PUBLIC_CANISTER_ID:password_manager_with_metadata"]; + canisterEnv?.["PUBLIC_CANISTER_ID:backend"]; if (!canisterId) { throw new Error( - "Canister ID for password_manager_with_metadata is not defined", + "Canister ID for backend is not set", ); } diff --git a/rust/vetkeys/password_manager_with_metadata/frontend/vite.config.js b/rust/vetkeys/password_manager_with_metadata/frontend/vite.config.js index ca53dc054a..169539f3bb 100644 --- a/rust/vetkeys/password_manager_with_metadata/frontend/vite.config.js +++ b/rust/vetkeys/password_manager_with_metadata/frontend/vite.config.js @@ -1,56 +1,49 @@ import { defineConfig } from "vite"; import { svelte } from "@sveltejs/vite-plugin-svelte"; -import eslint from "vite-plugin-eslint"; import tailwindcss from "tailwindcss"; import autoprefixer from "autoprefixer"; import css from "rollup-plugin-css-only"; -import viteCompression from "vite-plugin-compression"; +import { icpBindgen } from "@icp-sdk/bindgen/plugins/vite"; import { execSync } from "child_process"; -const environment = process.env.ICP_ENVIRONMENT || "local"; -const CANISTER_NAMES = ["password_manager_with_metadata"]; - function getDevServerConfig() { - const backend = process.env.BACKEND; - if (!backend) { - throw new Error( - "BACKEND env var is required. Use `npm run dev:motoko` or `npm run dev:rust`.", + try { + const canisterId = execSync("icp canister status backend -e local -i", { + encoding: "utf-8", + stdio: "pipe", + }).trim(); + const networkStatus = JSON.parse( + execSync("icp network status --json", { + encoding: "utf-8", + stdio: "pipe", + }) ); - } + return { + headers: { + "Set-Cookie": `ic_env=${encodeURIComponent( + `ic_root_key=${networkStatus.root_key}&PUBLIC_CANISTER_ID:backend=${canisterId}` + )}; SameSite=Lax;`, + }, + proxy: { + "/api": { target: "http://127.0.0.1:8000", changeOrigin: true }, + }, + }; + } catch {} - const networkStatus = JSON.parse( - execSync( - `icp network status -e ${environment} --json --project-root-override ../${backend}`, - { encoding: "utf-8" }, - ), + throw new Error( + "No local network running. Start with:\n icp network start -d && icp deploy" ); - const canisterParams = CANISTER_NAMES.map((name) => { - const id = execSync( - `icp canister status ${name} -e ${environment} --id-only --project-root-override ../${backend}`, - { encoding: "utf-8", stdio: "pipe" }, - ).trim(); - return `PUBLIC_CANISTER_ID:${name}=${id}`; - }).join("&"); - return { - headers: { - "Set-Cookie": `ic_env=${encodeURIComponent( - `${canisterParams}&ic_root_key=${networkStatus.root_key}`, - )}; SameSite=Lax;`, - }, - proxy: { - "/api": { target: networkStatus.api_url, changeOrigin: true }, - }, - hmr: false, - }; } -// https://vite.dev/config/ export default defineConfig(({ command }) => ({ + base: "./", plugins: [ svelte(), css({ output: "bundle.css" }), - eslint(), - viteCompression(), + icpBindgen({ + didFile: "../backend/backend.did", + outDir: "./src/bindings", + }), ], css: { postcss: { @@ -58,18 +51,17 @@ export default defineConfig(({ command }) => ({ }, }, build: { + sourcemap: true, rollupOptions: { output: { inlineDynamicImports: true, }, }, - sourcemap: true, }, - root: "./", resolve: { alias: { "@dfinity/vetkeys": "@icp-sdk/vetkeys", }, }, - ...(command === "serve" ? { server: getDevServerConfig() } : {}), + server: command === "serve" ? getDevServerConfig() : undefined, })); diff --git a/rust/vetkeys/password_manager_with_metadata/rust/icp.yaml b/rust/vetkeys/password_manager_with_metadata/icp.yaml similarity index 50% rename from rust/vetkeys/password_manager_with_metadata/rust/icp.yaml rename to rust/vetkeys/password_manager_with_metadata/icp.yaml index 332199d440..3b7759d854 100644 --- a/rust/vetkeys/password_manager_with_metadata/rust/icp.yaml +++ b/rust/vetkeys/password_manager_with_metadata/icp.yaml @@ -1,21 +1,21 @@ canisters: - - name: password_manager_with_metadata + - name: backend recipe: - type: "@dfinity/rust@v3.2.0" + type: "@dfinity/rust@v3.3.0" configuration: - package: ic-vetkd-example-password-manager-with-metadata-backend candid: backend/backend.did init_args: type: text value: "(\"test_key_1\")" - - name: www + - name: frontend recipe: type: "@dfinity/asset-canister@v2.2.1" configuration: - dir: dist + dir: frontend/dist build: - - cd frontend && npm i --include=dev && npm run build && cd - && rm -rf dist; mv frontend/dist ./ + - npm install --prefix frontend + - npm run build --prefix frontend networks: - name: local diff --git a/rust/vetkeys/password_manager_with_metadata/motoko/frontend b/rust/vetkeys/password_manager_with_metadata/motoko/frontend deleted file mode 120000 index af288785f3..0000000000 --- a/rust/vetkeys/password_manager_with_metadata/motoko/frontend +++ /dev/null @@ -1 +0,0 @@ -../frontend \ No newline at end of file diff --git a/rust/vetkeys/password_manager_with_metadata/motoko/mops.toml b/rust/vetkeys/password_manager_with_metadata/motoko/mops.toml deleted file mode 100644 index dff61c8753..0000000000 --- a/rust/vetkeys/password_manager_with_metadata/motoko/mops.toml +++ /dev/null @@ -1,8 +0,0 @@ -[toolchain] -moc = "1.9.0" - -[dependencies] -core = "2.5.0" -ic-vetkeys = "0.5.0" -[canisters.password_manager_with_metadata] -main = "backend/src/Main.mo" diff --git a/rust/vetkeys/password_manager_with_metadata/package.json b/rust/vetkeys/password_manager_with_metadata/package.json new file mode 100644 index 0000000000..a874aee1a8 --- /dev/null +++ b/rust/vetkeys/password_manager_with_metadata/package.json @@ -0,0 +1,13 @@ +{ + "name": "password_manager_with_metadata", + "private": true, + "type": "module", + "scripts": { + "build": "npm run build --workspaces --if-present", + "prebuild": "npm run prebuild --workspaces --if-present", + "dev": "npm run dev --workspaces --if-present" + }, + "workspaces": [ + "frontend" + ] +} diff --git a/rust/vetkeys/password_manager_with_metadata/rust/rust-toolchain.toml b/rust/vetkeys/password_manager_with_metadata/rust-toolchain.toml similarity index 100% rename from rust/vetkeys/password_manager_with_metadata/rust/rust-toolchain.toml rename to rust/vetkeys/password_manager_with_metadata/rust-toolchain.toml diff --git a/rust/vetkeys/password_manager_with_metadata/rust/backend/Makefile b/rust/vetkeys/password_manager_with_metadata/rust/backend/Makefile deleted file mode 100644 index fadd943554..0000000000 --- a/rust/vetkeys/password_manager_with_metadata/rust/backend/Makefile +++ /dev/null @@ -1,15 +0,0 @@ -.PHONY: compile-wasm -.SILENT: compile-wasm -compile-wasm: - cargo build --release --target wasm32-unknown-unknown - -.PHONY: extract-candid -.SILENT: extract-candid -extract-candid: compile-wasm - candid-extractor ../target/wasm32-unknown-unknown/release/ic_vetkd_example_password_manager_with_metadata_backend.wasm > backend.did - -.PHONY: clean -.SILENT: clean -clean: - cargo clean - rm -rf ../.icp \ No newline at end of file diff --git a/rust/vetkeys/password_manager_with_metadata/rust/frontend b/rust/vetkeys/password_manager_with_metadata/rust/frontend deleted file mode 120000 index af288785f3..0000000000 --- a/rust/vetkeys/password_manager_with_metadata/rust/frontend +++ /dev/null @@ -1 +0,0 @@ -../frontend \ No newline at end of file