@dfinity/vetkeys
Version:
JavaScript and TypeScript library to use Internet Computer vetKeys
286 lines (285 loc) • 8.15 kB
JavaScript
import { T as l, D as h, E as g } from "./index-DeK1G2V9.mjs";
import { H as d, A as p } from "./actor-DZk8-pAg.mjs";
const f = ({ IDL: e }) => {
const t = e.Record({ inner: e.Vec(e.Nat8) }), r = e.Variant({ Ok: t, Err: e.Text }), i = e.Variant({
Read: e.Null,
ReadWrite: e.Null,
ReadWriteManage: e.Null
}), s = e.Variant({
Ok: e.Vec(e.Tuple(e.Principal, i)),
Err: e.Text
}), n = e.Variant({
Ok: e.Opt(i),
Err: e.Text
});
return e.Service({
get_accessible_shared_key_ids: e.Func(
[],
[e.Vec(e.Tuple(e.Principal, t))],
["query"]
),
get_encrypted_vetkey: e.Func(
[e.Principal, t, t],
[r],
[]
),
get_shared_user_access_for_key: e.Func(
[e.Principal, t],
[s],
["query"]
),
get_user_rights: e.Func(
[e.Principal, t, e.Principal],
[n],
["query"]
),
get_vetkey_verification_key: e.Func([], [t], []),
remove_user: e.Func(
[e.Principal, t, e.Principal],
[n],
[]
),
set_user_rights: e.Func(
[e.Principal, t, e.Principal, i],
[n],
[]
)
});
}, o = process.env.CANISTER_ID_IC_VETKEYS_MANAGER_CANISTER, y = (e, t = {}) => {
const r = t.agent || new d({ ...t.agentOptions });
return t.agent && t.agentOptions && console.warn(
"Detected both agent and agentOptions passed to createActor. Ignoring agentOptions and proceeding with the provided agent."
), process.env.DFX_NETWORK !== "ic" && r.fetchRootKey().catch((i) => {
console.warn(
"Unable to fetch root key. Check to ensure that your local replica is running"
), console.error(i);
}), p.createActor(f, {
agent: r,
canisterId: e,
...t.actorOptions
});
};
o && y(o);
class R {
canisterId;
actor;
verificationKey = void 0;
constructor(t, r) {
this.canisterId = r, this.actor = y(r, { agent: t });
}
get_accessible_shared_key_ids() {
return this.actor.get_accessible_shared_key_ids();
}
set_user_rights(t, r, i, s) {
return this.actor.set_user_rights(t, r, i, s);
}
get_user_rights(t, r, i) {
return this.actor.get_user_rights(t, r, i);
}
remove_user(t, r, i) {
return this.actor.remove_user(t, r, i);
}
async get_encrypted_vetkey(t, r, i) {
return await this.actor.get_encrypted_vetkey(
t,
r,
i
);
}
async get_vetkey_verification_key() {
return this.verificationKey ? this.verificationKey : (this.verificationKey = await this.actor.get_vetkey_verification_key(), this.verificationKey);
}
}
class K {
/**
* The client instance for interacting with the KeyManager canister.
*/
canisterClient;
/**
* Creates a new instance of the KeyManager.
*
* @example
* ```ts
* import { KeyManager } from "@dfinity/vetkeys/key_manager";
*
* const keyManager = new KeyManager(keyManagerClientInstance);
* ```
*/
constructor(t) {
this.canisterClient = t;
}
/**
* Retrieves a list of keys that were shared with the user and the user still has access to.
*
* @example
* ```ts
* const sharedKeys = await keyManager.getAccessibleSharedKeyIds();
* console.log("Shared Keys:", sharedKeys);
* ```
*
* @returns Promise resolving to an array of `[Principal, Uint8Array]` pairs representing accessible key identifiers.
*/
async getAccessibleSharedKeyIds() {
return (await this.canisterClient.get_accessible_shared_key_ids()).map(
([t, r]) => [t, Uint8Array.from(r.inner)]
);
}
/**
* Fetches and decrypts an encrypted VetKey.
*
* @example
* ```ts
* const keyOwner = Principal.fromText("aaaaa-aa");
* const vetkeyName = "my_secure_key";
*
* const vetkey = await keyManager.getVetkey(
* keyOwner,
* vetkeyName,
* );
* console.log("Decrypted VetKey:", vetkey);
* ```
*
* @param keyOwner - The principal of the key owner
* @param vetkeyName - The name/identifier of the VetKey
* @returns Promise resolving to the decrypted VetKey bytes
* @throws Error if the key retrieval or decryption fails
*/
async getVetkey(t, r) {
const i = l.random(), s = await this.canisterClient.get_encrypted_vetkey(
t,
c(r),
c(i.publicKeyBytes())
);
if ("Err" in s)
throw Error(s.Err);
{
const n = Uint8Array.from(s.Ok.inner), a = await this.getVetkeyVerificationKey(), u = h.deserialize(
Uint8Array.from(a)
), _ = new Uint8Array([
t.toUint8Array().length,
...t.toUint8Array(),
...r
]);
return g.deserialize(n).decryptAndVerify(
i,
u,
_
).signatureBytes();
}
}
/**
* Retrieves the public verification key for validating encrypted VetKeys.
* The vetkeys obtained via `getVetkey` are verified using this key,
* and, therefore, this method is not needed for using `getVetkey`.
*
* @example
* ```ts
* const verificationKey = await keyManager.getVetkeyVerificationKey();
* console.log("Verification Key:", verificationKey);
* ```
*
* @returns Promise resolving to the verification key bytes
*/
async getVetkeyVerificationKey() {
return Uint8Array.from(
(await this.canisterClient.get_vetkey_verification_key()).inner
);
}
/**
* Grants or modifies access rights for a user.
*
* @example
* ```ts
* const owner = Principal.fromText("aaaaa-aa");
* const keyName = "my_secure_key";
* const user = Principal.fromText("bbbbbb-bb");
* const accessRights = { ReadWrite: null };
*
* const result = await keyManager.setUserRights(
* owner,
* keyName,
* user,
* accessRights,
* );
* console.log("Replaced Access Rights:", result);
* ```
*
* @param owner - The principal of the key owner
* @param vetkeyName - The name/identifier of the VetKey
* @param user - The principal of the user to grant/modify rights for
* @param userRights - The access rights to grant
* @returns Promise resolving to the previous access rights if they existed
* @throws Error if the operation fails
*/
async setUserRights(t, r, i, s) {
const n = await this.canisterClient.set_user_rights(
t,
c(r),
i,
s
);
if ("Err" in n) throw Error(n.Err);
if (n.Ok.length > 1)
throw Error("Unexpected result from set_user_rights");
return n.Ok.length === 0 ? void 0 : n.Ok[0];
}
/**
* Checks a user's access rights.
*
* @example
* ```ts
* const userRights = await keyManager.get_user_rights(owner, keyName, user);
* console.log("User Access Rights:", userRights);
* ```
*
* @param owner - The principal of the key owner
* @param vetkeyName - The name/identifier of the VetKey
* @param user - The principal of the user to check rights for
* @returns Promise resolving to the user's access rights if they exist
* @throws Error if the operation fails
*/
async getUserRights(t, r, i) {
const s = await this.canisterClient.get_user_rights(
t,
c(r),
i
);
if ("Err" in s) throw Error(s.Err);
if (s.Ok.length > 1)
throw Error("Unexpected result from set_user_rights");
return s.Ok.length === 0 ? void 0 : s.Ok[0];
}
/**
* Revokes a user's access.
*
* @example
* ```ts
* const removalResult = await keyManager.removeUser(owner, keyName, user);
* console.log("User Removed:", removalResult);
* ```
*
* @param owner - The principal of the key owner
* @param vetkeyName - The name/identifier of the VetKey
* @param user - The principal of the user to remove
* @returns Promise resolving to the previous access rights if they existed
* @throws Error if the operation fails
*/
async removeUser(t, r, i) {
const s = await this.canisterClient.remove_user(
t,
c(r),
i
);
if ("Err" in s) throw Error(s.Err);
if (s.Ok.length > 1)
throw Error("Unexpected result from set_user_rights");
return s.Ok.length === 0 ? void 0 : s.Ok[0];
}
}
function c(e) {
return { inner: Array.from(e) };
}
export {
R as DefaultKeyManagerClient,
K as KeyManager
};