dfinity / agent-js

A collection of libraries and tools for building software around the Internet Computer, in JavaScript.
https://agent-js.icp.xyz
Apache License 2.0
155 stars 96 forks source link

feat: allow option set agent replica time #923

Closed krpeacock closed 2 months ago

krpeacock commented 2 months ago

Description

Adds a new feature to set and read a specified replicaTime on the HttpAgent. This is useful in situations where the device clock may not be accurate, such as in an airgapped device, since the agent needs to agree with the replica when creating an Expiry or validating certificates.

Also improves the error handling for replica time errors, throwing a new ReplicaTimeError, containing a reference back to the agent that threw it, as well as a parsed replicaTime Date object from the error message.

This replaces the offset strategy previously used.

examples

// set replica time
const agent = HttpAgent.createSync();
agent.replicaTime = new Date('2021-01-01T00:00:00Z');
// read replica time
const agent = HttpAgent.createSync();
console.log(agent.replicaTime);
// catch time error
try {
  // should throw an error
  await actor.whoami();
} catch (err) {
  // handle the replica time error. "name" will be 'ReplicaTimeError'
  if (err.name === 'ReplicaTimeError') {
    console.log(err.agent);
    console.log(err.replicaTime);
    handleErr(err);
  }
}

Important: the error response cannot be certified. Using it directly could subject users to replay attacks

Fixes SDK-1812

How Has This Been Tested?

New e2e tests

Checklist:

github-actions[bot] commented 2 months ago

size-limit report 📦

Path Size
@dfinity/agent 86.33 KB (+0.43% 🔺)
@dfinity/candid 13.58 KB (0%)
@dfinity/principal 4.97 KB (0%)
@dfinity/auth-client 60.42 KB (+0.1% 🔺)
@dfinity/assets 81.14 KB (+0.19% 🔺)
@dfinity/identity 57.65 KB (+0.16% 🔺)
@dfinity/identity-secp256k1 131.89 KB (+0.57% 🔺)