Skip to content
2 changes: 1 addition & 1 deletion packages/seal/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ export class SealClient {
/**
* Fetch keys from the key servers and update the cache.
*
* It is recommended to call this function once for all ids of all encrypted obejcts if
* It is recommended to call this function once for all ids of all encrypted objects if
* there are multiple, then call decrypt for each object. This avoids calling fetchKey
* individually for each decrypt.
*
Expand Down
20 changes: 16 additions & 4 deletions packages/seal/src/key-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,12 @@ export async function retrieveKeyServers({
objectIds: string[];
client: SealCompatibleClient;
}): Promise<KeyServer[]> {
// todo: do not fetch the same object ID if this is fetched before.
return await Promise.all(
objectIds.map(async (objectId) => {
const uniqueIds = Array.from(new Set(objectIds));
const fetchedServers: Record<string, KeyServer> = {};

// Only fetch key server information for each unique objectId.
await Promise.all(
uniqueIds.map(async (objectId) => {
let res;
try {
res = await client.core.getObject({
Expand All @@ -74,7 +77,7 @@ export async function retrieveKeyServers({
throw new UnsupportedFeatureError(`Unsupported key type ${ks.keyType}`);
}

return {
fetchedServers[objectId] = {
objectId,
name: ks.name,
url: ks.url,
Expand All @@ -83,6 +86,15 @@ export async function retrieveKeyServers({
};
}),
);

return objectIds.map((objectId) => {
if (!fetchedServers[objectId]) {
console.error(`KeyServer ${objectId} not found in fetched servers`);
throw new InvalidGetObjectError(`KeyServer ${objectId} not found`);
}

return fetchedServers[objectId];
});
}

/**
Expand Down