@idos-network/enclave 1.2.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,10 +1,13 @@
1
1
  {
2
2
  "name": "@idos-network/enclave",
3
- "version": "1.2.0",
3
+ "version": "2.2.0",
4
4
  "description": "idOS Enclave JavaScript SDK",
5
5
  "homepage": "https://idos.network",
6
6
  "license": "MIT",
7
- "repository": "github:idos-network/idos-sdk-js",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "github:idos-network/idos-sdk-js"
10
+ },
8
11
  "files": [
9
12
  "dist/**/*",
10
13
  "src/**/*"
@@ -31,26 +34,27 @@
31
34
  "access": "public"
32
35
  },
33
36
  "dependencies": {
37
+ "@idos-network/credentials": "2.2.0",
38
+ "@idos-network/kwil-infra": "2.2.0",
39
+ "@idos-network/utils": "2.2.0",
34
40
  "scrypt-js": "^3.0.1",
35
41
  "tiny-invariant": "^1.3.3",
36
42
  "tweetnacl": "^1.0.3",
37
- "zod": "4.4.3",
38
- "@idos-network/credentials": "1.2.0",
39
- "@idos-network/kwil-infra": "1.2.0",
40
- "@idos-network/utils": "1.2.0"
43
+ "zod": "4.5.4"
41
44
  },
42
45
  "devDependencies": {
43
- "@types/chrome": "^0.1.0",
44
- "@types/node": "25.6.2",
46
+ "@types/chrome": "^0.2.5",
47
+ "@types/node": "25.9.5",
48
+ "@vitest/coverage-v8": "4.1.11",
45
49
  "jsdom": "^22.1.0",
46
- "tsdown": "^0.22.0",
47
- "typescript": "^5.8.3",
48
- "vitest": "4.1.5"
50
+ "tsdown": "^0.23.0",
51
+ "typescript": "^5.9.3",
52
+ "vitest": "4.1.11"
49
53
  },
50
54
  "peerDependencies": {
51
- "@partisiablockchain/abi-client": "^5.207.0",
52
- "@partisiablockchain/blockchain-api-transaction-client": "^5.149.0",
53
- "ethers": "^6.14.0"
55
+ "@partisiablockchain/abi-client": "^5.310.0",
56
+ "@partisiablockchain/blockchain-api-transaction-client": "^5.214.0",
57
+ "ethers": "^6.17.0"
54
58
  },
55
59
  "peerDependenciesMeta": {
56
60
  "@partisiablockchain/blockchain-api-transaction-client": {
@@ -71,6 +75,7 @@
71
75
  "dev": "tsdown --watch",
72
76
  "publint": "pnpx publint --strict",
73
77
  "test": "vitest",
78
+ "coverage": "vitest run --coverage",
74
79
  "typecheck": "tsc --noEmit"
75
80
  }
76
81
  }
package/src/base.test.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { idOSCredential } from "@idos-network/credentials/types";
1
+ import type { idOSCredentialRecord as idOSCredential } from "@idos-network/credentials/types";
2
2
 
3
3
  import { base64Encode, utf8Encode } from "@idos-network/utils/codecs";
4
4
  import { describe, expect, it, vi } from "vitest";
package/src/base.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { idOSCredential } from "@idos-network/credentials/types";
1
+ import type { idOSCredentialRecord as idOSCredential } from "@idos-network/credentials/types";
2
2
 
3
3
  import { recordFilter } from "@idos-network/credentials/utils";
4
4
  import { base64Decode, fromBytesToJson, hexEncode } from "@idos-network/utils/codecs";
@@ -238,6 +238,10 @@ export abstract class BaseProvider<K extends EnclaveOptions = EnclaveOptions> {
238
238
 
239
239
  const decrypted = await Promise.all(
240
240
  credentials.map(async (credential: idOSCredential) => {
241
+ if (!credential.content) {
242
+ throw new Error(`Credential ${credential.id} has no inline content`);
243
+ }
244
+
241
245
  const content = await this.decrypt(
242
246
  base64Decode(credential.content),
243
247
  base64Decode(credential.encryptor_public_key),
package/src/local.test.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { idOSCredential } from "@idos-network/credentials/types";
1
+ import type { idOSCredentialRecord as idOSCredential } from "@idos-network/credentials/types";
2
2
 
3
3
  import { base64Decode, base64Encode, utf8Encode } from "@idos-network/utils/codecs";
4
4
  import { encryptContent } from "@idos-network/utils/cryptography";
@@ -6,10 +6,49 @@ import { MemoryStore } from "@idos-network/utils/store";
6
6
  import tweetnacl from "tweetnacl";
7
7
  import { describe, expect, it, vi } from "vitest";
8
8
 
9
+ import { STORAGE_KEYS } from "./keys.js";
9
10
  import { LocalEnclave, type LocalEnclaveOptions } from "./local.js";
10
11
 
12
+ // ponytail: real scrypt (N=16384) runs on every obfuscated store read/write, which is
13
+ // several hundred ms per test and times out on CI. The codec only needs a deterministic
14
+ // key of the right length, not a real KDF.
15
+ vi.mock("scrypt-js", () => ({
16
+ syncScrypt: (
17
+ _password: Uint8Array,
18
+ salt: Uint8Array,
19
+ _n: number,
20
+ _r: number,
21
+ _p: number,
22
+ dkLen: number,
23
+ ) =>
24
+ new Uint8Array(Array.from({ length: dkLen }, (_, index) => salt[index % salt.length] ^ index)),
25
+ }));
26
+
27
+ vi.mock("@idos-network/utils/encryption", async (importOriginal) => {
28
+ const actual = await importOriginal<typeof import("@idos-network/utils/encryption")>();
29
+
30
+ return {
31
+ ...actual,
32
+ keyDerivation: vi.fn(
33
+ async () => new Uint8Array(Array.from({ length: 32 }, (_, index) => index)),
34
+ ),
35
+ };
36
+ });
37
+
38
+ // Obfuscated store uses syncScrypt(N=16384); keep tests under vitest's default 5s timeout on CI.
39
+ vi.mock("scrypt-js", () => ({
40
+ syncScrypt: vi.fn(
41
+ (_password: Uint8Array, _salt: Uint8Array, _N: number, _r: number, _p: number, dkLen: number) =>
42
+ new Uint8Array(dkLen).fill(7),
43
+ ),
44
+ }));
45
+
11
46
  class TestEnclave extends LocalEnclave {
47
+ userIdPresentOnPrompt: boolean[] = [];
48
+
12
49
  async getPasswordContext() {
50
+ this.userIdPresentOnPrompt.push((await this.store.get(STORAGE_KEYS.USER_ID)) !== undefined);
51
+
13
52
  return {
14
53
  encryptionPasswordStore: "user",
15
54
  password: "super-secret",
@@ -18,9 +57,116 @@ class TestEnclave extends LocalEnclave {
18
57
  }
19
58
  }
20
59
 
60
+ class MPCTestEnclave extends LocalEnclave {
61
+ mpcPassword = "super-secret";
62
+
63
+ async getPasswordContext() {
64
+ return {
65
+ encryptionPasswordStore: "mpc",
66
+ } as const;
67
+ }
68
+
69
+ protected async ensureMPCPassword() {
70
+ return this.mpcPassword;
71
+ }
72
+ }
73
+
21
74
  describe("LocalEnclave", () => {
22
75
  const userId = "9f51b3b2-4cbe-4c2b-8ea3-0b0c1b2f1a11";
23
76
 
77
+ it("rejects passwords whose derived public key does not match expectedUserEncryptionPublicKey", async () => {
78
+ const store = new MemoryStore();
79
+ const enclave = new TestEnclave({
80
+ userId,
81
+ store,
82
+ expectedUserEncryptionPublicKey: base64Encode(new Uint8Array(32).fill(1)),
83
+ } as LocalEnclaveOptions);
84
+
85
+ await expect(
86
+ enclave.createEncryptionProfileFromPassword("super-secret", userId, "user"),
87
+ ).rejects.toThrow(
88
+ "Derived encryption public key does not match expectedUserEncryptionPublicKey",
89
+ );
90
+ });
91
+
92
+ it("accepts passwords whose derived public key matches expectedUserEncryptionPublicKey", async () => {
93
+ const store = new MemoryStore();
94
+ const enclave = new TestEnclave({ userId, store } as LocalEnclaveOptions);
95
+ const { keyPair } = await enclave.createEncryptionProfileFromPassword(
96
+ "super-secret",
97
+ userId,
98
+ "user",
99
+ );
100
+
101
+ const matchingEnclave = new TestEnclave({
102
+ userId,
103
+ store: new MemoryStore(),
104
+ expectedUserEncryptionPublicKey: base64Encode(keyPair.publicKey),
105
+ } as LocalEnclaveOptions);
106
+
107
+ await expect(
108
+ matchingEnclave.createEncryptionProfileFromPassword("super-secret", userId, "user"),
109
+ ).resolves.toMatchObject({ userId, encryptionPasswordStore: "user" });
110
+ });
111
+
112
+ it("rejects MPC unlock when the downloaded password derives a mismatched public key", async () => {
113
+ const store = new MemoryStore();
114
+ const enclave = new MPCTestEnclave({
115
+ userId,
116
+ store,
117
+ mode: "existing",
118
+ expectedUserEncryptionPublicKey: base64Encode(new Uint8Array(32).fill(1)),
119
+ } as LocalEnclaveOptions);
120
+
121
+ await expect(enclave.getPrivateEncryptionProfile()).rejects.toThrow(
122
+ "Derived encryption public key does not match expectedUserEncryptionPublicKey",
123
+ );
124
+ });
125
+
126
+ it("requires origin authorization after deriving a key and keeps the profile if denied", async () => {
127
+ const store = new MemoryStore();
128
+ const enclave = new TestEnclave({ userId, store } as LocalEnclaveOptions);
129
+ let allowed = false;
130
+ const guard = vi.spyOn(enclave, "guardKeys").mockImplementation(async () => allowed);
131
+ const passwordContextSpy = vi.spyOn(enclave, "getPasswordContext");
132
+
133
+ await expect(enclave.getPrivateEncryptionProfile()).rejects.toThrow(
134
+ "Origin is not authorized to use the keys",
135
+ );
136
+ expect(passwordContextSpy).toHaveBeenCalledTimes(1);
137
+ expect(guard).toHaveBeenCalledTimes(1);
138
+
139
+ allowed = true;
140
+ const profile = await enclave.getPrivateEncryptionProfile();
141
+
142
+ expect(profile.userId).toBe(userId);
143
+ expect(passwordContextSpy).toHaveBeenCalledTimes(1);
144
+ expect(guard).toHaveBeenCalledTimes(2);
145
+ });
146
+
147
+ it("does not check origin authorization when the guard is skipped", async () => {
148
+ const enclave = new TestEnclave({ userId, store: new MemoryStore() } as LocalEnclaveOptions);
149
+ const guard = vi.spyOn(enclave, "guardKeys");
150
+
151
+ await enclave.getPrivateEncryptionProfile(true);
152
+
153
+ expect(guard).not.toHaveBeenCalled();
154
+ });
155
+
156
+ it("does not request a password context for an MM profile without a stored key", async () => {
157
+ const enclave = new TestEnclave({
158
+ userId,
159
+ store: new MemoryStore(),
160
+ encryptionPasswordStore: "mm",
161
+ });
162
+ const passwordContextSpy = vi.spyOn(enclave, "getPasswordContext");
163
+
164
+ await expect(enclave.getPrivateEncryptionProfile()).rejects.toThrow(
165
+ "MM encryption profiles require an externally supplied encryption private key",
166
+ );
167
+ expect(passwordContextSpy).not.toHaveBeenCalled();
168
+ });
169
+
24
170
  it("creates and exposes a public encryption profile", async () => {
25
171
  const store = new MemoryStore();
26
172
  const enclave = new TestEnclave({ userId, store } as LocalEnclaveOptions);
@@ -110,4 +256,28 @@ describe("LocalEnclave", () => {
110
256
  expect(filtered[0]?.content).toBe("");
111
257
  expect(passwordContextSpy).toHaveBeenCalledTimes(1);
112
258
  });
259
+
260
+ it("forgets a cached profile after the remember duration elapses", async () => {
261
+ vi.useFakeTimers({ toFake: ["Date"] });
262
+
263
+ try {
264
+ vi.setSystemTime(new Date("2026-01-01T00:00:00Z"));
265
+
266
+ const store = new MemoryStore();
267
+ const enclave = new TestEnclave({ userId, store } as LocalEnclaveOptions);
268
+ const first = await enclave.getPrivateEncryptionProfile();
269
+
270
+ expect(await enclave.getPrivateEncryptionProfile()).toBe(first);
271
+
272
+ vi.setSystemTime(new Date("2026-01-03T00:00:00Z"));
273
+ const after = await enclave.getPrivateEncryptionProfile();
274
+
275
+ expect(after).not.toBe(first);
276
+ expect(after.userId).toBe(userId);
277
+ // First prompt finds an empty store. The second must too: expiry resets before re-entry.
278
+ expect(enclave.userIdPresentOnPrompt).toEqual([false, false]);
279
+ } finally {
280
+ vi.useRealTimers();
281
+ }
282
+ });
113
283
  });
package/src/local.ts CHANGED
@@ -96,7 +96,7 @@ export class LocalEnclave<
96
96
  async reset(): Promise<void> {
97
97
  await super.reset();
98
98
  this.storedEncryptionProfile = undefined;
99
- this.store.reset();
99
+ await this.store.reset();
100
100
  }
101
101
 
102
102
  /** @override parent method to reconfigure the enclave */
@@ -266,26 +266,32 @@ export class LocalEnclave<
266
266
  * @see BaseProvider#getPrivateEncryptionProfile
267
267
  */
268
268
  async getPrivateEncryptionProfile(skipGuard = false): Promise<PrivateEncryptionProfile> {
269
- // In case there is a no key pair, which matches we don't need a new one.
270
- if (this.storedEncryptionProfile) {
271
- let canBeUsed = this.storedEncryptionProfile.userId === this.userId;
269
+ // Remember duration is a key-use check. A long-lived iframe keeps this profile
270
+ // in memory, so construction-time store expiry is not enough.
271
+ if (this.storedEncryptionProfile && (await this.store.hasRememberDurationElapsed())) {
272
+ await this.reset();
273
+ }
272
274
 
273
- if (canBeUsed && !skipGuard) {
274
- // When users matches, we also need to check
275
- // if origin is authorized to use the keys.
276
- canBeUsed = await this.guardKeys();
275
+ if (this.storedEncryptionProfile?.userId === this.userId) {
276
+ // A matching cached profile still needs origin authorization before key use.
277
+ // Denying it must keep the profile and the allowlist; only a different user resets.
278
+ if (!skipGuard && !(await this.guardKeys())) {
279
+ throw new Error("Origin is not authorized to use the keys");
277
280
  }
278
281
 
279
- if (canBeUsed) {
280
- return this.storedEncryptionProfile;
281
- }
282
+ return this.storedEncryptionProfile;
283
+ }
282
284
 
283
- // Something did not match, we need to create a new key pair
284
- // and reset the enclave.
285
+ if (this.storedEncryptionProfile) {
285
286
  await this.reset();
286
287
  }
287
288
 
288
- // The stored profile can't be used, or we have to create a new one.
289
+ if (this.options.encryptionPasswordStore === "mm") {
290
+ throw new Error(
291
+ "MM encryption profiles require an externally supplied encryption private key",
292
+ );
293
+ }
294
+
289
295
  let password: string | undefined;
290
296
  let encryptionPasswordStore: EncryptionPasswordStore | undefined;
291
297
 
@@ -310,7 +316,18 @@ export class LocalEnclave<
310
316
  throw new Error("Password or encryption password store is not found");
311
317
  }
312
318
 
313
- return this.createEncryptionProfileFromPassword(password, this.userId, encryptionPasswordStore);
319
+ const profile = await this.createEncryptionProfileFromPassword(
320
+ password,
321
+ this.userId,
322
+ encryptionPasswordStore,
323
+ );
324
+
325
+ // Same origin check as the cached path. Password or MPC success is not authorization.
326
+ if (!skipGuard && !(await this.guardKeys())) {
327
+ throw new Error("Origin is not authorized to use the keys");
328
+ }
329
+
330
+ return profile;
314
331
  }
315
332
 
316
333
  /** @see BaseProvider#ensureUserEncryptionProfile */
@@ -351,6 +368,13 @@ export class LocalEnclave<
351
368
 
352
369
  const keyPair = nacl.box.keyPair.fromSecretKey(secretKey);
353
370
 
371
+ const expectedPublicKey = this.options.expectedUserEncryptionPublicKey;
372
+ if (expectedPublicKey && base64Encode(keyPair.publicKey) !== expectedPublicKey) {
373
+ throw new Error(
374
+ "Derived encryption public key does not match expectedUserEncryptionPublicKey",
375
+ );
376
+ }
377
+
354
378
  await this.store.set(STORAGE_KEYS.USER_ID, userId);
355
379
  await this.storeObfuscated.set(STORAGE_KEYS.OBFUSCATED_PASSWORD, password);
356
380
  await this.store.delete(STORAGE_KEYS.DEPRECATED___PASSWORD);
@@ -1 +0,0 @@
1
- {"version":3,"file":"base-0xSNl4rW.d.mts","names":[],"sources":["../src/types.ts","../src/base.ts"],"mappings":";;;;;KAIY,uBAAA;EACV,MAAA;EACA,uBAAA;EACA,uBAAA,EAAyB,yBAAA;AAAA;AAAA,KAGf,wBAAA;EACV,MAAA;EACA,QAAA;EACA,OAAA,EAAS,IAAA,CAAK,UAAA;EACd,uBAAA,EAAyB,yBAAA;AAAA;AAAA,KAGf,cAAA;EACV,KAAA;EACA,IAAA;EACA,MAAA;EACA,+BAAA;EACA,aAAA;EACA,eAAA;EACA,UAAA,GAAa,UAAA;EACb,uBAAA,GAA0B,yBAAA;AAAA;AAAA,KAGhB,eAAA;EACV,uBAAA;EACA,QAAA;EACA,QAAA;AAAA;AAAA,KAGU,kBAAA;EACV,uBAAA;AAAA;;;uBCtBoB,YAAA,WAAuB,cAAA,GAAiB,cAAA;EAAA,SACnD,OAAA,EAAS,CAAA;EAAA,UAGR,WAAA,IAAe,MAAA,OAAa,KAAA,OAAY,KAAA,UAAe,OAAA;EAAA,QACzD,eAAA;EAER,WAAA,CAAY,OAAA,EAAS,CAAA;EDbI;;;;;ECsBzB,SAAA,CAAU,MAAA;IACR,aAAA,IAAiB,MAAA,UAAgB,KAAA,YAAiB,KAAA,aAAkB,OAAA;IAEpE,WAAA,IAAe,OAAA,aAAoB,OAAA;IAEnC,MAAA,IAAU,OAAA,aAAoB,OAAA;EAAA;EA4BhC,aAAA,CAAoB,MAAA,OAAa,KAAA,OAAY,KAAA,QAAa,OAAA;;;;;;MAkDtD,MAAA,CAAA;;;;EAUJ,KAAA,CAAA,GAAe,OAAA;EDzGL;;;;;ECkHV,WAAA,CAAkB,OAAA,GAAS,OAAA,CAAQ,CAAA,IAAU,OAAA;;;;EAO7C,IAAA,CAAA,GAAc,OAAA;;;;;;AD9GhB;;;;EC2HE,OAAA,CACE,QA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