@ibgib/web-gib 0.0.10 → 0.0.12

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.
Files changed (55) hide show
  1. package/dist/keystone/keystone-config-builder.d.mts +77 -0
  2. package/dist/keystone/keystone-config-builder.d.mts.map +1 -0
  3. package/dist/keystone/keystone-config-builder.mjs +156 -0
  4. package/dist/keystone/keystone-config-builder.mjs.map +1 -0
  5. package/dist/keystone/keystone-constants.d.mts +15 -0
  6. package/dist/keystone/keystone-constants.d.mts.map +1 -0
  7. package/dist/keystone/keystone-constants.mjs +15 -0
  8. package/dist/keystone/keystone-constants.mjs.map +1 -0
  9. package/dist/keystone/keystone-helpers.d.mts +54 -0
  10. package/dist/keystone/keystone-helpers.d.mts.map +1 -0
  11. package/dist/keystone/keystone-helpers.mjs +155 -0
  12. package/dist/keystone/keystone-helpers.mjs.map +1 -0
  13. package/dist/keystone/keystone-service-v1.d.mts +81 -0
  14. package/dist/keystone/keystone-service-v1.d.mts.map +1 -0
  15. package/dist/keystone/keystone-service-v1.mjs +606 -0
  16. package/dist/keystone/keystone-service-v1.mjs.map +1 -0
  17. package/dist/keystone/keystone-service-v1.respec.d.mts +2 -0
  18. package/dist/keystone/keystone-service-v1.respec.d.mts.map +1 -0
  19. package/dist/keystone/keystone-service-v1.respec.mjs +443 -0
  20. package/dist/keystone/keystone-service-v1.respec.mjs.map +1 -0
  21. package/dist/keystone/keystone-types.d.mts +231 -0
  22. package/dist/keystone/keystone-types.d.mts.map +1 -0
  23. package/dist/keystone/keystone-types.mjs +50 -0
  24. package/dist/keystone/keystone-types.mjs.map +1 -0
  25. package/dist/keystone/strategy/hash-reveal-v1/hash-reveal-v1.d.mts +35 -0
  26. package/dist/keystone/strategy/hash-reveal-v1/hash-reveal-v1.d.mts.map +1 -0
  27. package/dist/keystone/strategy/hash-reveal-v1/hash-reveal-v1.mjs +106 -0
  28. package/dist/keystone/strategy/hash-reveal-v1/hash-reveal-v1.mjs.map +1 -0
  29. package/dist/keystone/strategy/keystone-strategy-factory.d.mts +15 -0
  30. package/dist/keystone/strategy/keystone-strategy-factory.d.mts.map +1 -0
  31. package/dist/keystone/strategy/keystone-strategy-factory.mjs +26 -0
  32. package/dist/keystone/strategy/keystone-strategy-factory.mjs.map +1 -0
  33. package/dist/keystone/strategy/keystone-strategy.d.mts +48 -0
  34. package/dist/keystone/strategy/keystone-strategy.d.mts.map +1 -0
  35. package/dist/keystone/strategy/keystone-strategy.mjs +14 -0
  36. package/dist/keystone/strategy/keystone-strategy.mjs.map +1 -0
  37. package/dist/witness/agent/agent-types.d.mts.map +1 -1
  38. package/dist/witness/agent/agent-types.mjs +2 -3
  39. package/dist/witness/agent/agent-types.mjs.map +1 -1
  40. package/dist/witness/agent/gemini/gemini-constants.d.mts +1 -0
  41. package/dist/witness/agent/gemini/gemini-constants.d.mts.map +1 -1
  42. package/dist/witness/agent/gemini/gemini-constants.mjs +1 -0
  43. package/dist/witness/agent/gemini/gemini-constants.mjs.map +1 -1
  44. package/package.json +1 -1
  45. package/src/keystone/keystone-config-builder.mts +186 -0
  46. package/src/keystone/keystone-constants.mts +16 -0
  47. package/src/keystone/keystone-helpers.mts +207 -0
  48. package/src/keystone/keystone-service-v1.mts +725 -0
  49. package/src/keystone/keystone-service-v1.respec.mts +540 -0
  50. package/src/keystone/keystone-types.mts +295 -0
  51. package/src/keystone/strategy/hash-reveal-v1/hash-reveal-v1.mts +145 -0
  52. package/src/keystone/strategy/keystone-strategy-factory.mts +35 -0
  53. package/src/keystone/strategy/keystone-strategy.mts +71 -0
  54. package/src/witness/agent/agent-types.mts +2 -3
  55. package/src/witness/agent/gemini/gemini-constants.mts +1 -0
@@ -0,0 +1,725 @@
1
+ import { extractErrorMsg, hash, pretty } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';
2
+ import { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs';
3
+ import { mut8 } from '@ibgib/ts-gib/dist/V1/transforms/mut8.mjs';
4
+ import { Factory_V1 } from '@ibgib/ts-gib/dist/V1/factory.mjs';
5
+ import { getGib } from '@ibgib/ts-gib/dist/V1/transforms/transform-helper.mjs';
6
+ import { TransformResult } from '@ibgib/ts-gib/dist/types.mjs';
7
+ import { validateIbGibIntrinsically } from '@ibgib/ts-gib/dist/V1/validate-helper.mjs';
8
+ import { IbGibSpaceAny } from '@ibgib/core-gib/dist/witness/space/space-base-v1.mjs';
9
+ import { MetaspaceService } from '@ibgib/core-gib/dist/witness/space/metaspace/metaspace-types.mjs';
10
+
11
+ import { GLOBAL_LOG_A_LOT } from '../constants.mjs';
12
+ import {
13
+ KeystoneData_V1,
14
+ KeystoneIbGib_V1,
15
+ KeystonePoolConfig,
16
+ KeystoneClaim,
17
+ KeystoneProof,
18
+ KeystoneChallengePool,
19
+ KeystoneSolution,
20
+ KeystoneReplenishStrategy,
21
+ KeystoneRevocationInfo,
22
+ KEYSTONE_REPLENISH_STRATEGY_VALID_VALUES,
23
+ } from './keystone-types.mjs';
24
+ import { KeystoneStrategyFactory } from './strategy/keystone-strategy-factory.mjs';
25
+ import { KEYSTONE_ATOM, POOL_ID_REVOKE, VERB_REVOKE } from './keystone-constants.mjs';
26
+ import {
27
+ addToBindingMap, getDeterministicRequirements, getKeystoneIb,
28
+ removeFromBindingMap,
29
+ } from './keystone-helpers.mjs';
30
+ import { getDependencyGraph } from '@ibgib/core-gib/dist/common/other/graph-helper.mjs';
31
+
32
+ const logalot = GLOBAL_LOG_A_LOT;
33
+
34
+ /**
35
+ * Facade for managing Keystone Identities.
36
+ *
37
+ * Handles Genesis, Authorized Evolution (Signing), and Validation.
38
+ */
39
+ export class KeystoneService_V1 {
40
+ protected lc: string = `[${KeystoneService_V1.name}]`;
41
+
42
+ /**
43
+ * Creates a brand new Keystone Identity Timeline.
44
+ */
45
+ async genesis({
46
+ masterSecret,
47
+ configs,
48
+ metaspace,
49
+ space,
50
+ }: {
51
+ masterSecret: string;
52
+ configs: KeystonePoolConfig[];
53
+ metaspace: MetaspaceService;
54
+ space: IbGibSpaceAny;
55
+ }): Promise<KeystoneIbGib_V1> {
56
+ const lc = `${this.lc}[${this.genesis.name}]`;
57
+ try {
58
+ if (logalot) { console.log(`${lc} starting... (I: c98ae8adbc5888dbf84c5aced7610b25)`); }
59
+
60
+ const challengePools: KeystoneChallengePool[] = [];
61
+
62
+ for (const config of configs) {
63
+ const strategy = KeystoneStrategyFactory.create({ config });
64
+ const poolSecret = await strategy.derivePoolSecret({ masterSecret });
65
+ const challenges: { [id: string]: any } = {};
66
+ const bindingMap: { [char: string]: string[] } = {}; // <--- New
67
+
68
+ const targetSize = config.behavior.size;
69
+ const timestamp = Date.now().toString();
70
+
71
+ for (let i = 0; i < targetSize; i++) {
72
+ const challengeId = await this.generateOpaqueChallengeId({
73
+ salt: config.salt, timestamp, index: i
74
+ });
75
+
76
+ const solution = await strategy.generateSolution({
77
+ poolSecret, poolId: config.salt, challengeId,
78
+ });
79
+ const challenge = await strategy.generateChallenge({ solution });
80
+ challenges[challengeId] = challenge;
81
+
82
+ // Populate Binding Map
83
+ addToBindingMap(bindingMap, challengeId);
84
+ }
85
+
86
+ // TODO: Check for empty buckets in bindingMap if config.targetBindingChars > 0?
87
+ // For V1, we assume statistical probability of SHA256 is sufficient for size > 50.
88
+
89
+ challengePools.push({
90
+ id: config.salt,
91
+ config,
92
+ challenges,
93
+ bindingMap
94
+ });
95
+ }
96
+
97
+ const data: KeystoneData_V1 = { challengePools, proofs: [] };
98
+ const keystoneIbGib = await this.createKeystoneIbGibImpl({ data, metaspace, space });
99
+ return keystoneIbGib;
100
+ } catch (error) {
101
+ console.error(`${lc} ${extractErrorMsg(error)}`);
102
+ throw error;
103
+ } finally {
104
+ if (logalot) { console.log(`${lc} complete.`); }
105
+ }
106
+ }
107
+
108
+ /**
109
+ * Signs a claim using a hybrid selection strategy.
110
+ * Supports: Mandatory IDs (Alice) + Sequential (FIFO) + Random (Stochastic).
111
+ */
112
+ async sign({
113
+ latestKeystone,
114
+ masterSecret,
115
+ claim,
116
+ poolId,
117
+ requiredChallengeIds = [],
118
+ frameDetails,
119
+ metaspace,
120
+ space,
121
+ }: {
122
+ latestKeystone: KeystoneIbGib_V1;
123
+ masterSecret: string;
124
+ claim: Partial<KeystoneClaim>;
125
+ poolId?: string;
126
+ requiredChallengeIds?: string[];
127
+ frameDetails?: any;
128
+ metaspace: MetaspaceService;
129
+ space: IbGibSpaceAny;
130
+ }): Promise<KeystoneIbGib_V1> {
131
+ const lc = `${this.lc}[${this.sign.name}]`;
132
+ try {
133
+ if (logalot) { console.log(`${lc} starting... (I: 519e0810cce8647ce83bdb3b5019a825)`); }
134
+
135
+ const prevData = latestKeystone.data!;
136
+
137
+ if (prevData.revocationInfo) { throw new Error(`keystone has been revoked (latestKeystone.data.revocationInfo is truthy). (E: 4f2198c39116d15c48ba191940316825)`); }
138
+
139
+ let pool: KeystoneChallengePool | undefined;
140
+
141
+ // ---------------------------------------------------------------
142
+ // 0. POOL RESOLUTION (Deterministic Mapping)
143
+ // ---------------------------------------------------------------
144
+ if (poolId) {
145
+ // Explicit selection
146
+ pool = prevData.challengePools.find(p => p.id === poolId);
147
+ if (!pool) { throw new Error(`Pool not found: ${poolId} (E: genuuid)`); }
148
+
149
+ // Enforce Policy on Explicit Selection
150
+ // FIX: Check length > 0. If empty, it's a default pool (allow all).
151
+ if (pool.config.allowedVerbs && pool.config.allowedVerbs.length > 0 && claim.verb) {
152
+ if (!pool.config.allowedVerbs.includes(claim.verb)) {
153
+ throw new Error(`Pool ${poolId} is not authorized for verb: ${claim.verb} (E: genuuid)`);
154
+ }
155
+ }
156
+ } else {
157
+ // Automatic Resolution based on Verb
158
+ if (!claim.verb) { throw new Error(`Cannot auto-resolve pool without a verb in the claim. (E: genuuid)`); }
159
+
160
+ // 1. Look for Specific Match
161
+ pool = prevData.challengePools.find(p =>
162
+ p.config.allowedVerbs && p.config.allowedVerbs.includes(claim.verb!)
163
+ );
164
+
165
+ // 2. Look for General/Default (No restrictions)
166
+ if (!pool) {
167
+ pool = prevData.challengePools.find(p =>
168
+ !p.config.allowedVerbs || p.config.allowedVerbs.length === 0
169
+ );
170
+ }
171
+
172
+ if (!pool) { throw new Error(`No suitable pool found for verb: ${claim.verb} (E: genuuid)`); }
173
+ }
174
+
175
+
176
+ // 1. Get Deterministic Requirements (Demands -> Binding -> FIFO)
177
+ const { mandatoryIds, availableIds } = getDeterministicRequirements({
178
+ pool,
179
+ requiredChallengeIds,
180
+ targetAddr: claim.target
181
+ });
182
+
183
+ // 2. Stochastic Selection
184
+ const randomCount = pool.config.behavior.selectRandomly;
185
+ const randomIds: string[] = [];
186
+
187
+ if (randomCount > 0) {
188
+ if (availableIds.length < randomCount) {
189
+ throw new Error(`Insufficient challenges for random requirement. Need ${randomCount}, have ${availableIds.length}`);
190
+ }
191
+ // Shuffle & Pick
192
+ const shuffled = availableIds.sort(() => 0.5 - Math.random());
193
+ randomIds.push(...shuffled.slice(0, randomCount));
194
+ }
195
+
196
+ // 3. Combine & Solve
197
+ const finalSelectedIds = [...mandatoryIds, ...randomIds];
198
+
199
+ const strategy = KeystoneStrategyFactory.create({ config: pool.config });
200
+ const poolSecret = await strategy.derivePoolSecret({ masterSecret });
201
+ const solutions: KeystoneSolution[] = [];
202
+
203
+ for (const id of finalSelectedIds) {
204
+ const solution = await strategy.generateSolution({
205
+ poolSecret, poolId: pool.id, challengeId: id,
206
+ });
207
+ solutions.push(solution);
208
+ }
209
+
210
+ // 4. Replenish
211
+ const nextPools = await this.applyReplenishmentStrategy({
212
+ prevPools: prevData.challengePools,
213
+ targetPoolId: pool.id,
214
+ consumedIds: finalSelectedIds,
215
+ masterSecret,
216
+ strategy,
217
+ config: pool.config
218
+ });
219
+
220
+ // 5. Build Proof (Include requiredChallengeIds!)
221
+ const proof: KeystoneProof = {
222
+ claim,
223
+ solutions,
224
+ requiredChallengeIds: requiredChallengeIds.length > 0 ? requiredChallengeIds : undefined
225
+ };
226
+
227
+ const newData: KeystoneData_V1 = {
228
+ challengePools: nextPools,
229
+ proofs: [proof],
230
+ frameDetails,
231
+ // isTjp: false,
232
+ };
233
+
234
+ const newIbGib = await this.evolveKeystoneIbGibImpl({ prevIbGib: latestKeystone, newData, metaspace, space });
235
+ return newIbGib;
236
+
237
+ } catch (error) {
238
+ console.error(`${lc} ${extractErrorMsg(error)}`);
239
+ throw error;
240
+ } finally {
241
+ if (logalot) { console.log(`${lc} complete.`); }
242
+ }
243
+ }
244
+
245
+ /**
246
+ * Validates the transition from Prev -> Curr.
247
+ * Enforces Cryptography AND Behavioral Policy.
248
+ *
249
+ * @returns Array of validation error strings. Empty array means Valid.
250
+ */
251
+ async validate({
252
+ currentIbGib,
253
+ prevIbGib,
254
+ }: {
255
+ currentIbGib: KeystoneIbGib_V1;
256
+ prevIbGib: KeystoneIbGib_V1;
257
+ metaspace: MetaspaceService;
258
+ space: IbGibSpaceAny;
259
+ }): Promise<string[]> {
260
+ const lc = `${this.lc}[${this.validate.name}]`;
261
+ const errors: string[] = [];
262
+ try {
263
+ if (!currentIbGib) { throw new Error(`(UNEXPECTED) currentIbGib falsy? (E: 3c0f02655fa8279e386a079ebb604b25)`); }
264
+ if (!prevIbGib) { throw new Error(`(UNEXPECTED) prevIbGib falsy? (E: 0d07c812634d839c784f31b8848ba825)`); }
265
+
266
+ validateIbGibIntrinsically
267
+ getDependencyGraph
268
+
269
+ const currData = currentIbGib.data!;
270
+ const prevData = prevIbGib.data!;
271
+
272
+ for (const proof of currData.proofs) {
273
+ if (proof.solutions.length === 0) {
274
+ errors.push(`Proof ${proof.id || 'unknown'} has no solutions.`);
275
+ continue;
276
+ }
277
+
278
+ const poolId = proof.solutions[0].poolId;
279
+ const pool = prevData.challengePools.find(p => p.id === poolId);
280
+ if (!pool) {
281
+ errors.push(`Proof references unknown pool: ${poolId}`);
282
+ continue;
283
+ }
284
+
285
+ // -----------------------------------------------------------
286
+ // 0. VALIDATE VERB AUTHORIZATION
287
+ // -----------------------------------------------------------
288
+ if (pool.config.allowedVerbs && pool.config.allowedVerbs.length > 0) {
289
+ if (!proof.claim.verb || !pool.config.allowedVerbs.includes(proof.claim.verb)) {
290
+ errors.push(`Policy Violation: Pool ${poolId} used for unauthorized verb ${proof.claim.verb}`);
291
+ }
292
+ }
293
+
294
+ // 1. Reconstruct Deterministic Requirements
295
+ const { mandatoryIds, availableIds } = getDeterministicRequirements({
296
+ pool,
297
+ requiredChallengeIds: proof.requiredChallengeIds,
298
+ targetAddr: proof.claim.target
299
+ });
300
+
301
+ const proofIds = new Set(proof.solutions.map(s => s.challengeId));
302
+
303
+ // 2. Verify Mandatory Compliance
304
+ for (const id of mandatoryIds) {
305
+ if (!proofIds.has(id)) {
306
+ errors.push(`Policy Violation: Missing mandatory challenge ${id}`);
307
+ }
308
+ }
309
+
310
+ // 3. Verify Stochastic Compliance
311
+ const randomCandidates = [...proofIds].filter(id => !mandatoryIds.has(id));
312
+ const requiredRandomCount = pool.config.behavior.selectRandomly;
313
+
314
+ if (randomCandidates.length < requiredRandomCount) {
315
+ errors.push(`Policy Violation: Insufficient random count. Need ${requiredRandomCount}, got ${randomCandidates.length}`);
316
+ }
317
+
318
+ // 4. Verify Validity (Existence & Double-Dip Check)
319
+ for (const id of randomCandidates) {
320
+ if (!availableIds.includes(id)) {
321
+ errors.push(`Policy Violation: ID ${id} is invalid or double-dipped.`);
322
+ }
323
+ }
324
+
325
+ // 5. Verify Crypto
326
+ const strategy = KeystoneStrategyFactory.create({ config: pool.config });
327
+ for (const solution of proof.solutions) {
328
+ const challenge = pool.challenges[solution.challengeId];
329
+ if (!challenge) {
330
+ errors.push(`Crypto Violation: Challenge ${solution.challengeId} not found in pool.`);
331
+ } else {
332
+ const isValid = await strategy.validateSolution({ solution, challenge });
333
+ if (!isValid) {
334
+ errors.push(`Crypto Violation: Solution for ${solution.challengeId} is invalid.`);
335
+ }
336
+ }
337
+ }
338
+ }
339
+
340
+ // Revocation Logic
341
+ if (currData.revocationInfo) {
342
+ const target = currData.revocationInfo.proof.claim.target;
343
+ const expectedTarget = getIbGibAddr({ ibGib: prevIbGib });
344
+ if (target !== expectedTarget) {
345
+ errors.push(`Revocation target mismatch. Expected ${expectedTarget}, got ${target}`);
346
+ }
347
+ }
348
+
349
+ return errors;
350
+ } catch (error) {
351
+ console.error(`${lc} ${extractErrorMsg(error)}`);
352
+ throw error; // System errors still throw
353
+ } finally {
354
+ if (logalot) { console.log(`${lc} complete.`); }
355
+ }
356
+ }
357
+
358
+ /**
359
+ * Permanently revokes the Identity.
360
+ *
361
+ * Logic:
362
+ * 1. Locates the 'revoke' pool.
363
+ * 2. Consumes ALL available challenges in that pool (Scorched Earth).
364
+ * 3. Sets the revocationInfo on the new frame.
365
+ */
366
+ async revoke({
367
+ latestKeystone,
368
+ masterSecret,
369
+ reason = "User initiated revocation",
370
+ frameDetails,
371
+ metaspace,
372
+ space,
373
+ }: {
374
+ latestKeystone: KeystoneIbGib_V1;
375
+ masterSecret: string;
376
+ reason?: string;
377
+ frameDetails?: any;
378
+ metaspace: MetaspaceService;
379
+ space?: IbGibSpaceAny;
380
+ }): Promise<KeystoneIbGib_V1> {
381
+ const lc = `${this.lc}[${this.revoke.name}]`;
382
+ try {
383
+ const prevData = latestKeystone.data!;
384
+ space ??= await metaspace.getLocalUserSpace({ lock: false });
385
+ if (!space) { throw new Error(`(UNEXPECTED) space falsy and couldn't get default local user space from the metaspace? (E: 73c8bfc0e7383a540ea1d6b14b020125)`); }
386
+
387
+ // 1. Find Revocation Pool
388
+ const pool = prevData.challengePools.find(p => p.id === POOL_ID_REVOKE);
389
+ if (!pool) { throw new Error(`Revocation pool not found (E: 8c4f18c5461c1d601283108878c79825)`); }
390
+
391
+ // 2. Select Challenges (Standard Policy, NOT ALL)
392
+ // We want to satisfy the security policy (e.g. 10 sequential + 10 random)
393
+ // without revealing the all of the keys in the pool.
394
+ const claim: Partial<KeystoneClaim> = {
395
+ verb: VERB_REVOKE,
396
+ target: getIbGibAddr({ ibGib: latestKeystone })
397
+ };
398
+
399
+ const { mandatoryIds, availableIds } = getDeterministicRequirements({
400
+ pool,
401
+ requiredChallengeIds: [], // Revocation usually doesn't have external demands
402
+ targetAddr: claim.target
403
+ });
404
+
405
+ // Stochastic Selection
406
+ const randomCount = pool.config.behavior.selectRandomly;
407
+ const randomIds: string[] = [];
408
+ if (randomCount > 0) {
409
+ if (availableIds.length < randomCount) { throw new Error(`Insufficient challenges. availableIds.length (${availableIds.length}) is less than required random count (${randomCount}) (E: b2e3570ab998dfdbab5fbdda1e43d825)`); }
410
+ const shuffled = availableIds.sort(() => 0.5 - Math.random());
411
+ randomIds.push(...shuffled.slice(0, randomCount));
412
+ }
413
+
414
+ const selectedIds = [...mandatoryIds, ...randomIds];
415
+ if (selectedIds.length === 0) { throw new Error(`Revocation policy selected 0 challenges? Check config for pool. id: ${pool.id}. pool.config: ${pretty(pool.config)} (E: 97e5a8356d241ae7b882db791cb1f825)`); }
416
+
417
+ // 3. Solve Selected
418
+ const strategy = KeystoneStrategyFactory.create({ config: pool.config });
419
+ const poolSecret = await strategy.derivePoolSecret({ masterSecret });
420
+ const solutions: KeystoneSolution[] = [];
421
+
422
+ for (const id of selectedIds) {
423
+ const solution = await strategy.generateSolution({
424
+ poolSecret, poolId: pool.id, challengeId: id,
425
+ });
426
+ solutions.push(solution);
427
+ }
428
+
429
+ // 4. The default revocation behavior is to delete all of the
430
+ // challenges so that the challenge pool is empty.
431
+ // see KeystoneReplenishStrategy.scorchedEarth
432
+ const nextPools = await this.applyReplenishmentStrategy({
433
+ prevPools: prevData.challengePools,
434
+ targetPoolId: pool.id,
435
+ consumedIds: selectedIds,
436
+ masterSecret,
437
+ strategy,
438
+ config: pool.config
439
+ });
440
+
441
+ // 5. Construct Proof
442
+ const proof: KeystoneProof = {
443
+ claim,
444
+ solutions,
445
+ };
446
+
447
+ const revocationInfo: KeystoneRevocationInfo = { reason, proof };
448
+
449
+ const newData: KeystoneData_V1 = {
450
+ challengePools: nextPools,
451
+ proofs: [proof],
452
+ revocationInfo,
453
+ frameDetails
454
+ };
455
+
456
+ return await this.evolveKeystoneIbGibImpl({
457
+ prevIbGib: latestKeystone,
458
+ newData,
459
+ metaspace,
460
+ space,
461
+ });
462
+
463
+ } catch (error) {
464
+ console.error(`${lc} ${extractErrorMsg(error)}`);
465
+ throw error;
466
+ } finally {
467
+ if (logalot) { console.log(`${lc} complete.`); }
468
+ }
469
+ }
470
+
471
+ /**
472
+ * Generates an opaque, collision-resistant ID for a challenge.
473
+ * Hash(Salt + Timestamp + Index)
474
+ */
475
+ private async generateOpaqueChallengeId({
476
+ salt,
477
+ timestamp,
478
+ index
479
+ }: {
480
+ salt: string,
481
+ timestamp: string,
482
+ index: number
483
+ }): Promise<string> {
484
+ // Use full SHA-256 hash, or slice it?
485
+ // User suggested substring is fine for pool uniqueness.
486
+ // Let's use first 16 chars of hex (64 bits) for brevity + safety.
487
+ const raw = await hash({ s: `${salt}${timestamp}${index}` });
488
+ return raw.substring(0, 16);
489
+ }
490
+
491
+ private async applyReplenishmentStrategy({
492
+ prevPools,
493
+ targetPoolId,
494
+ consumedIds,
495
+ masterSecret,
496
+ strategy,
497
+ config
498
+ }: {
499
+ prevPools: KeystoneChallengePool[];
500
+ targetPoolId: string;
501
+ consumedIds: string[];
502
+ masterSecret: string;
503
+ strategy: any;
504
+ config: KeystonePoolConfig;
505
+ }): Promise<KeystoneChallengePool[]> {
506
+ const newPools = JSON.parse(JSON.stringify(prevPools));
507
+ const pool = newPools.find((p: any) => p.id === targetPoolId);
508
+ const poolSecret = await strategy.derivePoolSecret({ masterSecret });
509
+ const timestamp = Date.now().toString();
510
+
511
+ const strategyType = config.behavior.replenish;
512
+
513
+ // Clean up Binding Map for consumed IDs
514
+ consumedIds.forEach(id => {
515
+ if (pool.bindingMap) { removeFromBindingMap(pool.bindingMap, id); }
516
+ });
517
+
518
+ if (strategyType === KeystoneReplenishStrategy.topUp) {
519
+ // Remove consumed
520
+ consumedIds.forEach(id => delete pool.challenges[id]);
521
+
522
+ // Add New
523
+ for (let i = 0; i < consumedIds.length; i++) {
524
+ const newId = await this.generateOpaqueChallengeId({
525
+ salt: config.salt, timestamp, index: i
526
+ });
527
+
528
+ // Collision Check? No. Better than this is the configuration
529
+ // that requires multiple challenges. So we should assume that a
530
+ // very small number of repeats is going to happen, but that the
531
+ // overall security remains intact due to multiple layers of
532
+ // challenges (multiple FIFO, Stochastic, Binding, etc.).
533
+
534
+ const solution = await strategy.generateSolution({
535
+ poolSecret, poolId: pool.id, challengeId: newId
536
+ });
537
+ pool.challenges[newId] = await strategy.generateChallenge({ solution });
538
+
539
+ // Update Binding Map
540
+ if (!pool.bindingMap) { pool.bindingMap = {}; }
541
+ addToBindingMap(pool.bindingMap, newId);
542
+ }
543
+ } else if (strategyType === KeystoneReplenishStrategy.replaceAll) {
544
+ pool.challenges = {};
545
+ pool.bindingMap = {};
546
+
547
+ for (let i = 0; i < config.behavior.size; i++) {
548
+ const newId = await this.generateOpaqueChallengeId({
549
+ salt: config.salt, timestamp, index: i
550
+ });
551
+ const solution = await strategy.generateSolution({
552
+ poolSecret, poolId: pool.id, challengeId: newId
553
+ });
554
+ pool.challenges[newId] = await strategy.generateChallenge({ solution });
555
+ addToBindingMap(pool.bindingMap, newId);
556
+ }
557
+ } else if (strategyType === KeystoneReplenishStrategy.consume) {
558
+ consumedIds.forEach(id => delete pool.challenges[id]);
559
+ } else if (strategyType === KeystoneReplenishStrategy.scorchedEarth) {
560
+ // SCORCHED EARTH: Delete EVERYTHING.
561
+ pool.challenges = {};
562
+ pool.bindingMap = {};
563
+ } else {
564
+ throw new Error(`Unknown replenish strategy: ${strategyType}. Valid list: ${pretty(KEYSTONE_REPLENISH_STRATEGY_VALID_VALUES)} (E: 0acf56f1e1486240080e11e8046d0825)`);
565
+ }
566
+
567
+ return newPools;
568
+ }
569
+
570
+ /**
571
+ * Creates a new keystone ibgib that has no dna and no past.
572
+ */
573
+ private async createKeystoneIbGibImpl({
574
+ data,
575
+ metaspace,
576
+ space,
577
+ }: {
578
+ data: KeystoneData_V1,
579
+ metaspace: MetaspaceService,
580
+ space?: IbGibSpaceAny,
581
+ }): Promise<KeystoneIbGib_V1> {
582
+ const lc = `${this.lc}[${this.createKeystoneIbGibImpl.name}]`;
583
+ try {
584
+ if (logalot) { console.log(`${lc} starting... (I: 5e32389700e9899e788cbefacef7c825)`); }
585
+
586
+ space ??= await metaspace.getLocalUserSpace({ lock: false });
587
+ if (!space) { throw new Error(`(UNEXPECTED) space was falsy and we couldn't get default local user space from metaspace? (E: 9a6498cf16a8801f19ec376749742225)`); }
588
+
589
+ // create the actual keystoneIbGib
590
+ const resFirstGen = await Factory_V1.firstGen({
591
+ parentIbGib: Factory_V1.primitive({ ib: KEYSTONE_ATOM }),
592
+ ib: await getKeystoneIb({ keystoneData: data }),
593
+ data,
594
+ // just showing rel8ns for completeness. in the future when we have
595
+ // composite keystones, this will probably change to a truthy value
596
+ // rel8ns: undefined,
597
+ dna: false,
598
+ nCounter: true,
599
+ tjp: {
600
+ timestamp: true,
601
+ uuid: true,
602
+ },
603
+ }) as TransformResult<KeystoneIbGib_V1>;
604
+ const keystoneIbGib = resFirstGen.newIbGib;
605
+
606
+ // at this point, the first gen result has an interstitial ibgib and
607
+ // its past is not empty. We need to change this so that the past is
608
+ // indeed empty. We then will drop the interstitial and re-calculate
609
+ // the gib (hash).
610
+ // console.error(`${lc} PART 1 - NOT AN ERROR. JUST A TEMP LOG MSG TO BE REMOVED. I WANT TO SEE WHAT THIS LOOKS LIKE IN DEBUGGING. specifically, I am looking at n & isTjp and whether we need to manually adjust them.\nkeystoneIbGib... (I: 2ce3b821ba739cd3e821625811315525)`);
611
+ // console.dir(keystoneIbGib);
612
+ // console.log(pretty(keystoneIbGib)); // uncomment this to see the actual full object (it's big though)
613
+ if (!keystoneIbGib.data) { throw new Error(`(UNEXPECTED) keystoneIbGib.data falsy? We expect the data to be populated with real keystone data. (E: 38a358facdb89d16d81d48c8520d3d25)`); }
614
+ if (!keystoneIbGib.rel8ns) { throw new Error(`(UNEXPECTED) keystoneIbGib.rel8ns falsy? we expect the rel8ns to have ancestor and past. (E: 20cb7723dc33ae1ef808fe76d1bf4b25)`); }
615
+ if (!keystoneIbGib.rel8ns.past || keystoneIbGib.rel8ns.past.length === 0) {
616
+ throw new Error(`(UNEXPECTED) keystoneIbGib.rel8ns.past falsy or empty? we expect the firstGen call to generate an interstitial ibgib that we will splice out. (E: 0fd8388d045ab9f37834c27d67e78825)`);
617
+ }
618
+
619
+ // reset n
620
+ keystoneIbGib.data.n = 0;
621
+ // reset tjp
622
+ keystoneIbGib.data.isTjp = true;
623
+ delete keystoneIbGib.rel8ns.tjp;
624
+ // reset past
625
+ delete keystoneIbGib.rel8ns.past;
626
+
627
+ // recalculate gib
628
+ keystoneIbGib.gib = await getGib({ ibGib: keystoneIbGib });
629
+
630
+ // console.error(`${lc} PART 2 - NOT AN ERROR. JUST A TEMP LOG MSG TO BE REMOVED. I WANT TO SEE WHAT THIS LOOKS LIKE IN DEBUGGING. specifically, I am looking at n & isTjp and whether we need to manually adjust them.\nkeystoneIbGib... (I: db9f181938184d9d9832fac8fa25a325)`);
631
+ // console.dir(keystoneIbGib);
632
+ // console.log(pretty(keystoneIbGib)); // uncomment this to see the actual full object (it's big though)
633
+
634
+ // save and register
635
+ await metaspace.put({ ibGib: keystoneIbGib, space, });
636
+ await metaspace.registerNewIbGib({ ibGib: keystoneIbGib, space, });
637
+
638
+ return keystoneIbGib;
639
+ } catch (error) {
640
+ console.error(`${lc} ${extractErrorMsg(error)}`);
641
+ throw error;
642
+ } finally {
643
+ if (logalot) { console.log(`${lc} complete.`); }
644
+ }
645
+ }
646
+
647
+ /**
648
+ * for signing/revoking, the newData is entirely new per frame, i.e., we
649
+ * replace all relevant keystone information. IOW we are not just patching
650
+ * the data by adding or replacing keys, we are providing all pools, claim,
651
+ * solutions, required, and frameDetails. So this implementation is required
652
+ * to remove each of the old keys in the call to {@link mut8}.
653
+ */
654
+ private async evolveKeystoneIbGibImpl({
655
+ prevIbGib,
656
+ newData,
657
+ metaspace,
658
+ space,
659
+ }: {
660
+ prevIbGib: KeystoneIbGib_V1,
661
+ newData: KeystoneData_V1
662
+ metaspace: MetaspaceService,
663
+ space: IbGibSpaceAny,
664
+ }): Promise<KeystoneIbGib_V1> {
665
+ const lc = `${this.lc}[${this.evolveKeystoneIbGibImpl.name}]`;
666
+ try {
667
+ if (logalot) { console.log(`${lc} starting... (I: 8b10e8920f08b7842803665834cf8925)`); }
668
+
669
+ if (!prevIbGib.data) { throw new Error(`(UNEXPECTED) prevIbGib.data falsy? (E: 5e84875bf992c585b979e6c8ed5bf225)`); }
670
+ if (prevIbGib.data.revocationInfo) { throw new Error(`Keystone has already been revoked (prevIbGib.data.revocationInfo truthy), so we cannot evolve the keystone. Keystone addr: ${getIbGibAddr({ ibGib: prevIbGib })} (E: 45d7f846556829de6b2a701838c3f825)`); }
671
+
672
+ const prevData = prevIbGib.data;
673
+ /**
674
+ * we want to completely replace these keys, so we will remove them
675
+ * from the data. This occurs first in the underlying mut8
676
+ * transform.
677
+ * @see {@link mut8}
678
+ */
679
+ let dataToRemove: Partial<KeystoneData_V1> | undefined = {}
680
+ if (prevData.proofs) { dataToRemove.proofs = []; }
681
+ if (prevData.challengePools) { dataToRemove.challengePools = []; }
682
+ if (prevData.frameDetails) { dataToRemove.frameDetails = {}; }
683
+ if (Object.keys(dataToRemove).length === 0) { dataToRemove = undefined; }
684
+
685
+ const resMut8 = await mut8({
686
+ src: prevIbGib,
687
+ dataToRemove,
688
+ dataToAddOrPatch: newData,
689
+ // dna: false, // explicitly set to false just to show
690
+ nCounter: true,
691
+ });
692
+
693
+ if (!!resMut8.intermediateIbGibs) { throw new Error(`(UNEXPECTED) resMut8.intermediateIbGibs truthy? I'm not sure if we expect there to be intermediateIbGibs, but I feel like we shouldn't. Pretty sure we shouldn't, definitely don't *want* them. (E: ba40d55d7c2d36d438c413886f148625)`); }
694
+ if (!!resMut8.dnas) { throw new Error(`(UNEXPECTED) resMut8.dnas truthy? We do not want dnas with keystones. (E: 49470513d018f97d28024f4e82da3b25)`); }
695
+
696
+
697
+ const newKeystoneIbGib = resMut8.newIbGib as KeystoneIbGib_V1;
698
+
699
+ // run validation here? I think we should probably at least for awhile
700
+ // --- VALIDATION UPDATE ---
701
+ const errors = await this.validate({
702
+ currentIbGib: newKeystoneIbGib,
703
+ prevIbGib,
704
+ metaspace,
705
+ space,
706
+ });
707
+ if (errors.length > 0) {
708
+ // console.error(`${lc} invalid keystone immediately after evolution. newKeystoneIbGib:\n${pretty(newKeystoneIbGib)} (E: 466a52230e7ece724fd119f39fbce825)`)
709
+ console.error(`${lc} Validation Failed:\n${errors.join('\n')}`);
710
+ throw new Error(`(UNEXPECTED) invalid keystone after we just evolved it? Errors: ${errors.join('; ')} (E: ae2c58406c1db7687879dfb89fc1f825)`);
711
+ }
712
+
713
+ // save and register
714
+ await metaspace.put({ ibGib: newKeystoneIbGib, space, });
715
+ await metaspace.registerNewIbGib({ ibGib: newKeystoneIbGib, space, });
716
+
717
+ return newKeystoneIbGib;
718
+ } catch (error) {
719
+ console.error(`${lc} ${extractErrorMsg(error)}`);
720
+ throw error;
721
+ } finally {
722
+ if (logalot) { console.log(`${lc} complete.`); }
723
+ }
724
+ }
725
+ }