@ibgib/web-gib 0.0.52 → 0.0.56

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 (150) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/AUTO-GENERATED-version.d.mts +1 -1
  3. package/dist/AUTO-GENERATED-version.mjs +1 -1
  4. package/dist/api/commands/chat/hello-world.mjs.map +1 -1
  5. package/dist/api/commands/command-constants.d.mts +4 -4
  6. package/dist/api/commands/command-constants.d.mts.map +1 -1
  7. package/dist/api/commands/command-service-v1.d.mts.map +1 -1
  8. package/dist/api/commands/command-service-v1.mjs.map +1 -1
  9. package/dist/api/commands/ibgib/get-ibgibs.d.mts.map +1 -1
  10. package/dist/api/commands/ibgib/get-ibgibs.mjs.map +1 -1
  11. package/dist/api/ibgib-api-bridge.d.mts +81 -0
  12. package/dist/api/ibgib-api-bridge.d.mts.map +1 -0
  13. package/dist/api/ibgib-api-bridge.mjs +259 -0
  14. package/dist/api/ibgib-api-bridge.mjs.map +1 -0
  15. package/dist/app-bootstrap/init-orchestration.d.mts +1 -1
  16. package/dist/app-bootstrap/init-orchestration.d.mts.map +1 -1
  17. package/dist/app-bootstrap/init-orchestration.mjs +17 -3
  18. package/dist/app-bootstrap/init-orchestration.mjs.map +1 -1
  19. package/dist/assets/fullscreen-dialog.html +18 -0
  20. package/dist/assumptions.respec.mjs.map +1 -1
  21. package/dist/common/settings/settings-constants.d.mts.map +1 -1
  22. package/dist/helpers.d.mts.map +1 -1
  23. package/dist/helpers.mjs.map +1 -1
  24. package/dist/helpers.web.d.mts.map +1 -1
  25. package/dist/helpers.web.mjs.map +1 -1
  26. package/dist/helpers.web.respec.mjs.map +1 -1
  27. package/dist/identity/keystone-sync-service.d.mts +37 -0
  28. package/dist/identity/keystone-sync-service.d.mts.map +1 -0
  29. package/dist/identity/keystone-sync-service.mjs +211 -0
  30. package/dist/identity/keystone-sync-service.mjs.map +1 -0
  31. package/dist/identity/sso/sso-custodian-service.d.mts.map +1 -1
  32. package/dist/identity/sso/sso-custodian-service.mjs.map +1 -1
  33. package/dist/identity/sso/sso-custodian-service.respec.mjs.map +1 -1
  34. package/dist/index.d.mts +17 -1
  35. package/dist/index.d.mts.map +1 -1
  36. package/dist/index.mjs +21 -26
  37. package/dist/index.mjs.map +1 -1
  38. package/dist/storage/storage-helpers.web.mjs.map +1 -1
  39. package/dist/ui/component/common-component-styles.css +270 -0
  40. package/dist/ui/component/ibgib-component-service.d.mts.map +1 -1
  41. package/dist/ui/component/ibgib-dynamic-component-bases.d.mts.map +1 -1
  42. package/dist/ui/component/ibgib-dynamic-component-bases.mjs.map +1 -1
  43. package/dist/ui/component/identity/add-device/add-device.css +133 -0
  44. package/dist/ui/component/identity/add-device/add-device.d.mts +49 -0
  45. package/dist/ui/component/identity/add-device/add-device.d.mts.map +1 -0
  46. package/dist/ui/component/identity/add-device/add-device.html +52 -0
  47. package/dist/ui/component/identity/add-device/add-device.mjs +321 -0
  48. package/dist/ui/component/identity/add-device/add-device.mjs.map +1 -0
  49. package/dist/ui/component/identity/identity-header/identity-header.css +317 -0
  50. package/dist/ui/component/identity/identity-header/identity-header.d.mts +85 -0
  51. package/dist/ui/component/identity/identity-header/identity-header.d.mts.map +1 -0
  52. package/dist/ui/component/identity/identity-header/identity-header.html +72 -0
  53. package/dist/ui/component/identity/identity-header/identity-header.mjs +546 -0
  54. package/dist/ui/component/identity/identity-header/identity-header.mjs.map +1 -0
  55. package/dist/ui/component/identity/identity-manager/identity-manager.css +178 -0
  56. package/dist/ui/component/identity/identity-manager/identity-manager.d.mts +76 -0
  57. package/dist/ui/component/identity/identity-manager/identity-manager.d.mts.map +1 -0
  58. package/dist/ui/component/identity/identity-manager/identity-manager.html +19 -0
  59. package/dist/ui/component/identity/identity-manager/identity-manager.mjs +591 -0
  60. package/dist/ui/component/identity/identity-manager/identity-manager.mjs.map +1 -0
  61. package/dist/ui/component/identity/index.d.mts +17 -0
  62. package/dist/ui/component/identity/index.d.mts.map +1 -0
  63. package/dist/ui/component/identity/index.mjs +34 -0
  64. package/dist/ui/component/identity/index.mjs.map +1 -0
  65. package/dist/ui/component/identity/keystone-creator/keystone-creator.css +97 -0
  66. package/dist/ui/component/identity/keystone-creator/keystone-creator.d.mts +58 -0
  67. package/dist/ui/component/identity/keystone-creator/keystone-creator.d.mts.map +1 -0
  68. package/dist/ui/component/identity/keystone-creator/keystone-creator.html +51 -0
  69. package/dist/ui/component/identity/keystone-creator/keystone-creator.mjs +410 -0
  70. package/dist/ui/component/identity/keystone-creator/keystone-creator.mjs.map +1 -0
  71. package/dist/ui/component/identity/keystone-details/keystone-details.css +621 -0
  72. package/dist/ui/component/identity/keystone-details/keystone-details.d.mts +98 -0
  73. package/dist/ui/component/identity/keystone-details/keystone-details.d.mts.map +1 -0
  74. package/dist/ui/component/identity/keystone-details/keystone-details.html +154 -0
  75. package/dist/ui/component/identity/keystone-details/keystone-details.mjs +1377 -0
  76. package/dist/ui/component/identity/keystone-details/keystone-details.mjs.map +1 -0
  77. package/dist/ui/component/identity/keystone-scrubber/keystone-scrubber.css +46 -0
  78. package/dist/ui/component/identity/keystone-scrubber/keystone-scrubber.d.mts +64 -0
  79. package/dist/ui/component/identity/keystone-scrubber/keystone-scrubber.d.mts.map +1 -0
  80. package/dist/ui/component/identity/keystone-scrubber/keystone-scrubber.html +15 -0
  81. package/dist/ui/component/identity/keystone-scrubber/keystone-scrubber.mjs +300 -0
  82. package/dist/ui/component/identity/keystone-scrubber/keystone-scrubber.mjs.map +1 -0
  83. package/dist/ui/component/identity/remove-device/remove-device.css +118 -0
  84. package/dist/ui/component/identity/remove-device/remove-device.d.mts +50 -0
  85. package/dist/ui/component/identity/remove-device/remove-device.d.mts.map +1 -0
  86. package/dist/ui/component/identity/remove-device/remove-device.html +31 -0
  87. package/dist/ui/component/identity/remove-device/remove-device.mjs +188 -0
  88. package/dist/ui/component/identity/remove-device/remove-device.mjs.map +1 -0
  89. package/dist/ui/ui-constants.d.mts +1 -0
  90. package/dist/ui/ui-constants.d.mts.map +1 -1
  91. package/dist/ui/ui-constants.mjs +1 -0
  92. package/dist/ui/ui-constants.mjs.map +1 -1
  93. package/dist/ui/ui-types.d.mts +7 -0
  94. package/dist/ui/ui-types.d.mts.map +1 -1
  95. package/dist/witness/agent/agent-constants.d.mts.map +1 -1
  96. package/dist/witness/agent/agent-helpers.mjs.map +1 -1
  97. package/dist/witness/agent/agent-one-file.d.mts.map +1 -1
  98. package/dist/witness/agent/agent-one-file.mjs.map +1 -1
  99. package/dist/witness/agent/agents-service-v1.d.mts.map +1 -1
  100. package/dist/witness/agent/agents-service-v1.mjs.map +1 -1
  101. package/dist/witness/agent/gemini/agent-witness-gemini-v1.d.mts.map +1 -1
  102. package/dist/witness/agent/gemini/gemini-agent-factory.d.mts.map +1 -1
  103. package/dist/witness/live-proxy-ibgib/live-proxy-ibgib-one-file.d.mts.map +1 -1
  104. package/dist/witness/live-proxy-ibgib/live-proxy-ibgib-one-file.mjs.map +1 -1
  105. package/dist/witness/space/metaspace/metaspace-webspace/metaspace-webspace-helper.mjs.map +1 -1
  106. package/dist/witness/space/metaspace/metaspace-webspace/metaspace-webspace.d.mts +4 -0
  107. package/dist/witness/space/metaspace/metaspace-webspace/metaspace-webspace.d.mts.map +1 -1
  108. package/dist/witness/space/metaspace/metaspace-webspace/metaspace-webspace.mjs +40 -1
  109. package/dist/witness/space/metaspace/metaspace-webspace/metaspace-webspace.mjs.map +1 -1
  110. package/dist/witness/space/web-filesystem-space/web-filesystem-space-types.d.mts.map +1 -1
  111. package/dist/witness/space/web-filesystem-space/web-filesystem-space-v1.d.mts.map +1 -1
  112. package/package.json +2 -2
  113. package/src/AUTO-GENERATED-version.mts +1 -1
  114. package/src/api/ibgib-api-bridge.mts +292 -0
  115. package/src/app-bootstrap/init-orchestration.mts +17 -6
  116. package/src/custom.d.ts +11 -0
  117. package/src/identity/keystone-sync-service.mts +257 -0
  118. package/src/index.mts +24 -25
  119. package/src/ui/component/README.md +82 -5
  120. package/src/ui/component/common-component-styles.css +270 -0
  121. package/src/ui/component/identity/add-device/add-device.css +133 -0
  122. package/src/ui/component/identity/add-device/add-device.html +52 -0
  123. package/src/ui/component/identity/add-device/add-device.mts +397 -0
  124. package/src/ui/component/identity/identity-header/IMPLEMENTATION.md +45 -0
  125. package/src/ui/component/identity/identity-header/identity-header.css +317 -0
  126. package/src/ui/component/identity/identity-header/identity-header.html +72 -0
  127. package/src/ui/component/identity/identity-header/identity-header.mts +651 -0
  128. package/src/ui/component/identity/identity-manager/IMPLEMENTATION.md +100 -0
  129. package/src/ui/component/identity/identity-manager/identity-manager.css +178 -0
  130. package/src/ui/component/identity/identity-manager/identity-manager.html +19 -0
  131. package/src/ui/component/identity/identity-manager/identity-manager.mts +675 -0
  132. package/src/ui/component/identity/index.mts +36 -0
  133. package/src/ui/component/identity/keystone-creator/keystone-creator.css +97 -0
  134. package/src/ui/component/identity/keystone-creator/keystone-creator.html +51 -0
  135. package/src/ui/component/identity/keystone-creator/keystone-creator.mts +497 -0
  136. package/src/ui/component/identity/keystone-details/keystone-details.css +621 -0
  137. package/src/ui/component/identity/keystone-details/keystone-details.html +154 -0
  138. package/src/ui/component/identity/keystone-details/keystone-details.mts +1506 -0
  139. package/src/ui/component/identity/keystone-scrubber/SCRUBBER_IMPLEMENTATION.md +33 -0
  140. package/src/ui/component/identity/keystone-scrubber/keystone-scrubber.css +46 -0
  141. package/src/ui/component/identity/keystone-scrubber/keystone-scrubber.html +15 -0
  142. package/src/ui/component/identity/keystone-scrubber/keystone-scrubber.mts +355 -0
  143. package/src/ui/component/identity/remove-device/remove-device.css +118 -0
  144. package/src/ui/component/identity/remove-device/remove-device.html +31 -0
  145. package/src/ui/component/identity/remove-device/remove-device.mts +247 -0
  146. package/src/ui/ui-constants.mts +1 -0
  147. package/src/ui/ui-types.mts +8 -0
  148. package/src/witness/space/metaspace/metaspace-webspace/metaspace-webspace.mts +42 -1
  149. package/tools/auto-generated-agent-skills/skills/ibgib-dependency-graph/SKILL.md +209 -0
  150. package/tools/auto-generated-agent-skills/skills/ibgib-implementation-plan/SKILL.md +102 -0
@@ -0,0 +1,1506 @@
1
+ import thisCss from "./keystone-details.css";
2
+ import thisHtml from "./keystone-details.html";
3
+ import commonComponentStylesCss from "../../common-component-styles.css";
4
+
5
+ import { extractErrorMsg, pretty } from "@ibgib/helper-gib/dist/helpers/utils-helper.mjs";
6
+ import { IbGibAddr } from "@ibgib/ts-gib/dist/types.mjs";
7
+ import { IbGib_V1 } from "@ibgib/ts-gib/dist/V1/types.mjs";
8
+ import { getIbAndGib, getIbGibAddr } from "@ibgib/ts-gib/dist/helper.mjs";
9
+ import { getGibInfo } from "@ibgib/ts-gib/dist/V1/transforms/transform-helper.mjs";
10
+ import { KeystoneService_V1 } from "@ibgib/core-gib/dist/keystone/keystone-service-v1.mjs";
11
+ import { KeystoneIbGib_V1 } from "@ibgib/core-gib/dist/keystone/keystone-types.mjs";
12
+ import {
13
+ IbGibDynamicComponentMetaBase, IbGibDynamicComponentInstanceBase,
14
+ } from "../../ibgib-dynamic-component-bases.mjs";
15
+ import {
16
+ ElementsBase, IbGibDynamicComponentInstance,
17
+ IbGibDynamicComponentInstanceInitOpts,
18
+ } from "../../component-types.mjs";
19
+ import { EVENT_IBGIB_IDENTITY_REQUEST_CHANGE, EVENT_IBGIB_IDENTITY_CHANGED } from "../../../ui-constants.mjs";
20
+ import { getApiBridge } from "../../../../api/ibgib-api-bridge.mjs";
21
+ import { getKeystoneSyncService } from "../../../../identity/keystone-sync-service.mjs";
22
+ import { updateSpecialIndex } from "@ibgib/core-gib/dist/timeline/timeline-api.mjs";
23
+ import { getTjpAddr, toDto } from "@ibgib/core-gib/dist/common/other/ibgib-helper.mjs";
24
+ import { parseSpaceIb } from "@ibgib/core-gib/dist/witness/space/space-helper.mjs";
25
+
26
+ import { getComponentCtorArg } from "../../../../app-bootstrap/init-orchestration.mjs";
27
+ import { promptForSecret } from "../../../../helpers.web.mjs";
28
+ import { isSsoProviderLinked } from "../../../../identity/sso/sso-helpers.mjs";
29
+ import { getGlobalMetaspace_waitIfNeeded } from "../../../../helpers.mjs";
30
+
31
+ const logalot = false;
32
+
33
+ export const KEYSTONE_DETAILS_COMPONENT_NAME = 'ibgib-keystone-details';
34
+
35
+ export class KeystoneDetailsComponentMeta extends IbGibDynamicComponentMetaBase {
36
+ protected override lc: string = `[KeystoneDetailsComponentMeta]`;
37
+
38
+ routeRegExp?: RegExp = new RegExp(`^${KEYSTONE_DETAILS_COMPONENT_NAME}$`);
39
+ componentName = KEYSTONE_DETAILS_COMPONENT_NAME;
40
+
41
+ constructor() {
42
+ super(getComponentCtorArg());
43
+ if (!customElements.get(this.componentName)) {
44
+ customElements.define(this.componentName, KeystoneDetailsComponentInstance);
45
+ }
46
+ }
47
+
48
+ async createInstance({
49
+ path,
50
+ ibGibAddr
51
+ }: {
52
+ path: string;
53
+ ibGibAddr: IbGibAddr;
54
+ }): Promise<IbGibDynamicComponentInstance> {
55
+ const lc = `${this.lc}[${this.createInstance.name}]`;
56
+ const component = document.createElement(this.componentName) as KeystoneDetailsComponentInstance;
57
+ await component.initialize({
58
+ ibGibAddr,
59
+ meta: this,
60
+ html: thisHtml,
61
+ css: [commonComponentStylesCss, thisCss],
62
+ });
63
+ return component;
64
+ }
65
+ }
66
+
67
+ interface KeystoneDetailsElements extends ElementsBase {
68
+ identityDetailsViewEl: HTMLDivElement;
69
+ identityAddrEl: HTMLElement;
70
+ identityGenEl: HTMLElement;
71
+ identityTimestampEl: HTMLElement;
72
+ identityUuidEl: HTMLElement;
73
+ identityNameEl: HTMLElement;
74
+ identityDescriptionEl: HTMLElement;
75
+ identityFrameDetailsEl: HTMLPreElement;
76
+ identityAggrDetailsEl: HTMLPreElement;
77
+
78
+ poolsContainerEl: HTMLDivElement;
79
+ btnVerifyChainEl: HTMLButtonElement;
80
+ btnSetActiveEl: HTMLButtonElement;
81
+ btnCheckUpdatesEl: HTMLButtonElement;
82
+ btnUpdateIdentityEl: HTMLButtonElement;
83
+ syncStatusMsgEl: HTMLDivElement;
84
+ verificationStatusEl: HTMLDivElement;
85
+ rawAccordionHeaderEl: HTMLDivElement;
86
+ rawAccordionContentEl: HTMLDivElement;
87
+ rawKeystoneJsonEl: HTMLPreElement;
88
+ delegatesCardEl: HTMLDivElement;
89
+ delegatesListEl: HTMLTableSectionElement;
90
+ historicalWarningBannerEl: HTMLDivElement;
91
+ containerEl: HTMLDivElement;
92
+ ssoLinkCardEl: HTMLDivElement;
93
+ btnLinkGoogleEl: HTMLDivElement;
94
+ btnLinkGithubEl: HTMLDivElement;
95
+ ssoStatusMsgEl: HTMLDivElement;
96
+ inputCurrentPassphraseEl: HTMLInputElement;
97
+ inputNewPassphraseEl: HTMLInputElement;
98
+ inputConfirmPassphraseEl: HTMLInputElement;
99
+ btnChangePassphraseEl: HTMLButtonElement;
100
+ changePassphraseStatusEl: HTMLDivElement;
101
+ changePassphraseCardEl: HTMLDivElement;
102
+ }
103
+
104
+ export class KeystoneDetailsComponentInstance
105
+ extends IbGibDynamicComponentInstanceBase<KeystoneIbGib_V1, KeystoneDetailsElements>
106
+ implements IbGibDynamicComponentInstance<KeystoneIbGib_V1, KeystoneDetailsElements> {
107
+
108
+ protected override lc: string = `[KeystoneDetailsComponentInstance]`;
109
+
110
+ private staticIbGib: KeystoneIbGib_V1 | undefined;
111
+
112
+ override get ibGib(): KeystoneIbGib_V1 | undefined {
113
+ return this.staticIbGib;
114
+ }
115
+
116
+ private globalActiveAddr: string | null = null;
117
+ private isHistoricalFrame: boolean = false;
118
+ private _onIdentityChanged: ((e: any) => void) | null = null;
119
+ private keystoneCache: Map<string, { username: string, description: string, isPrimary: boolean, n: number }> = new Map();
120
+
121
+ constructor() {
122
+ super();
123
+ }
124
+
125
+ override async initialize(opts: IbGibDynamicComponentInstanceInitOpts): Promise<void> {
126
+ const lc = `${this.lc}[${this.initialize.name}]`;
127
+ try {
128
+ if (logalot) { console.log(`${lc} starting... (I: 4c9328643a18e56b56e57292c87bd226)`); }
129
+
130
+ await super.initialize(opts);
131
+ // await this.loadIbGib({ getLatest: false });
132
+ await this.loadIbGib({ getLatest: false });
133
+
134
+ } catch (error) {
135
+ console.error(`${lc} ${extractErrorMsg(error)}`);
136
+ throw error;
137
+ } finally {
138
+ if (logalot) { console.log(`${lc} complete.`); }
139
+ }
140
+ }
141
+
142
+ private async getKeystoneDetails(addr: string): Promise<{ username: string, description: string, isPrimary: boolean, n: number }> {
143
+ const cached = this.keystoneCache.get(addr);
144
+ if (cached) return cached;
145
+
146
+ const metaspace = await getGlobalMetaspace_waitIfNeeded();
147
+ if (!metaspace) return { username: '', description: '', isPrimary: false, n: 0 };
148
+ const space = await metaspace.getLocalUserSpace({ lock: false });
149
+ if (!space) return { username: '', description: '', isPrimary: false, n: 0 };
150
+
151
+ try {
152
+ const keystoneSvc = new KeystoneService_V1();
153
+ const info = await keystoneSvc.getKeystoneCommonInfo({
154
+ addr,
155
+ metaspace,
156
+ space
157
+ });
158
+
159
+ if (info) {
160
+ const details = {
161
+ username: info.name,
162
+ description: info.description,
163
+ isPrimary: info.isPrimary,
164
+ n: info.n
165
+ };
166
+ this.keystoneCache.set(addr, details);
167
+ return details;
168
+ } else {
169
+ console.warn(`[getKeystoneDetails] Keystone common info not found in local space for addr: ${addr}`);
170
+ }
171
+ } catch (err) {
172
+ console.warn(`Error getting details for keystone ${addr}: ${extractErrorMsg(err)}`);
173
+ }
174
+
175
+ return { username: '', description: '', isPrimary: false, n: 0 };
176
+ }
177
+
178
+ override async created(): Promise<void> {
179
+ const lc = `${this.lc}[${this.created.name}]`;
180
+ try {
181
+ if (logalot) { console.log(`${lc} starting... (I: 0b2c6debcdac9db9b7928aa8695ed826)`); }
182
+
183
+ this.elements = {} as KeystoneDetailsElements;
184
+
185
+ const shadow = this.shadowRoot!;
186
+ this.elements.identityDetailsViewEl = shadow.getElementById('identity-details-view') as HTMLDivElement;
187
+ this.elements.identityAddrEl = shadow.getElementById('identity-addr') as HTMLElement;
188
+ this.elements.identityGenEl = shadow.getElementById('identity-gen') as HTMLSpanElement;
189
+ this.elements.identityTimestampEl = shadow.getElementById('identity-timestamp') as HTMLSpanElement;
190
+ this.elements.identityUuidEl = shadow.getElementById('identity-uuid') as HTMLSpanElement;
191
+ this.elements.identityNameEl = shadow.getElementById('identity-name') as HTMLElement;
192
+ this.elements.identityDescriptionEl = shadow.getElementById('identity-description') as HTMLElement;
193
+ this.elements.identityFrameDetailsEl = shadow.getElementById('identity-frame-details') as HTMLPreElement;
194
+ this.elements.identityAggrDetailsEl = shadow.getElementById('identity-aggr-details') as HTMLPreElement;
195
+
196
+ this.elements.poolsContainerEl = shadow.getElementById('pools-container') as HTMLDivElement;
197
+ this.elements.btnVerifyChainEl = shadow.getElementById('btn-verify-chain') as HTMLButtonElement;
198
+ this.elements.btnSetActiveEl = shadow.getElementById('btn-set-active') as HTMLButtonElement;
199
+ this.elements.btnCheckUpdatesEl = shadow.getElementById('btn-check-updates') as HTMLButtonElement;
200
+ this.elements.btnUpdateIdentityEl = shadow.getElementById('btn-update-identity') as HTMLButtonElement;
201
+ this.elements.syncStatusMsgEl = shadow.getElementById('sync-status-msg') as HTMLDivElement;
202
+ this.elements.verificationStatusEl = shadow.getElementById('verification-status') as HTMLDivElement;
203
+ this.elements.rawAccordionHeaderEl = shadow.getElementById('raw-accordion-header') as HTMLDivElement;
204
+ this.elements.rawAccordionContentEl = shadow.getElementById('raw-accordion-content') as HTMLDivElement;
205
+ this.elements.rawKeystoneJsonEl = shadow.getElementById('raw-keystone-json') as HTMLPreElement;
206
+ this.elements.delegatesCardEl = shadow.getElementById('delegates-card') as HTMLDivElement;
207
+ this.elements.delegatesListEl = shadow.getElementById('delegates-list') as HTMLTableSectionElement;
208
+ this.elements.containerEl = shadow.getElementById('container') as HTMLDivElement;
209
+ this.elements.historicalWarningBannerEl = shadow.getElementById('historical-warning-banner') as HTMLDivElement;
210
+ this.elements.ssoLinkCardEl = shadow.getElementById('sso-link-card') as HTMLDivElement;
211
+ this.elements.btnLinkGoogleEl = shadow.getElementById('btn-link-google') as HTMLDivElement;
212
+ this.elements.btnLinkGithubEl = shadow.getElementById('btn-link-github') as HTMLDivElement;
213
+ this.elements.ssoStatusMsgEl = shadow.getElementById('sso-status-msg') as HTMLDivElement;
214
+ this.elements.inputCurrentPassphraseEl = shadow.getElementById('input-current-passphrase') as HTMLInputElement;
215
+ this.elements.inputNewPassphraseEl = shadow.getElementById('input-new-passphrase') as HTMLInputElement;
216
+ this.elements.inputConfirmPassphraseEl = shadow.getElementById('input-confirm-passphrase') as HTMLInputElement;
217
+ this.elements.btnChangePassphraseEl = shadow.getElementById('btn-change-passphrase') as HTMLButtonElement;
218
+ this.elements.changePassphraseStatusEl = shadow.getElementById('change-passphrase-status') as HTMLDivElement;
219
+ this.elements.changePassphraseCardEl = shadow.getElementById('change-passphrase-card') as HTMLDivElement;
220
+
221
+ // ElementBase requires contentEl
222
+ this.elements.contentEl = shadow.getElementById('identity-details-view') as HTMLDivElement;
223
+
224
+ this.initHandlers();
225
+
226
+ // Subscribe to global active identity changes
227
+ this._onIdentityChanged = async (e: any) => {
228
+ this.globalActiveAddr = e.detail?.activeIdentityAddr || null;
229
+ this.keystoneCache.clear();
230
+ await this.updateFrameDetailsView();
231
+ this.updateActiveButtonState();
232
+ };
233
+ window.addEventListener(EVENT_IBGIB_IDENTITY_CHANGED, this._onIdentityChanged);
234
+
235
+ await this.resolveActiveIdentity();
236
+ await this.loadIbGib({ getLatest: false });
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
+ override async disconnected(): Promise<void> {
246
+ if (this._onIdentityChanged) {
247
+ window.removeEventListener(EVENT_IBGIB_IDENTITY_CHANGED, this._onIdentityChanged);
248
+ }
249
+ }
250
+
251
+ private initHandlers() {
252
+ // Setup raw JSON accordion toggle
253
+ this.elements!.rawAccordionHeaderEl.addEventListener('click', () => this.toggleAccordion());
254
+
255
+ // Buttons
256
+ this.elements!.btnVerifyChainEl.addEventListener('click', () => this.handleVerifyIdentityChain());
257
+ this.elements!.btnSetActiveEl.addEventListener('click', () => this.handleSetActiveIdentity());
258
+ this.elements!.btnCheckUpdatesEl.addEventListener('click', () => this.handleCheckForUpdates());
259
+ this.elements!.btnUpdateIdentityEl.addEventListener('click', () => this.handleUpdateIdentity());
260
+ this.elements!.btnLinkGoogleEl.addEventListener('click', () => this.handleSSOClick('google'));
261
+ this.elements!.btnLinkGithubEl.addEventListener('click', () => this.handleSSOClick('github'));
262
+ this.elements!.btnChangePassphraseEl.addEventListener('click', () => this.handleChangePassphrase());
263
+ }
264
+
265
+ private toggleAccordion() {
266
+ const header = this.elements!.rawAccordionHeaderEl;
267
+ const content = this.elements!.rawAccordionContentEl;
268
+ header.classList.toggle('expanded');
269
+ content.classList.toggle('expanded');
270
+ }
271
+
272
+ private setSyncStatus(msg: string, type: 'info' | 'success' | 'error') {
273
+ const statusEl = this.elements!.syncStatusMsgEl;
274
+ statusEl.textContent = msg;
275
+ statusEl.className = `status-msg ${type}`;
276
+ statusEl.classList.remove('hidden');
277
+ }
278
+
279
+ protected async handleCheckForUpdates(): Promise<void> {
280
+ const lc = `${this.lc}[${this.handleCheckForUpdates.name}]`;
281
+ if (!this.ibGibAddr) { return; }
282
+ this.setSyncStatus("Checking server for keystone updates...", "info");
283
+ try {
284
+ const metaspace = await getGlobalMetaspace_waitIfNeeded();
285
+ const space = metaspace ? await metaspace.getLocalUserSpace({ lock: false }) : undefined;
286
+ const syncSvc = getKeystoneSyncService();
287
+ const res = await syncSvc.checkForKeystoneUpdate({
288
+ activePrimaryAddr: this.ibGibAddr,
289
+ metaspace,
290
+ space
291
+ });
292
+ if (res.hasUpdate) {
293
+ this.setSyncStatus(`Update Available (Server n=${res.serverN}, Local n=${res.localN})`, "info");
294
+ } else {
295
+ this.setSyncStatus(`Up to Date (n=${res.localN})`, "success");
296
+ }
297
+ } catch (error) {
298
+ console.error(`${lc} ${extractErrorMsg(error)}`);
299
+ this.setSyncStatus(`Check failed: ${extractErrorMsg(error)}`, "error");
300
+ }
301
+ }
302
+
303
+ protected async handleUpdateIdentity(): Promise<void> {
304
+ const lc = `${this.lc}[${this.handleUpdateIdentity.name}]`;
305
+ if (!this.ibGibAddr) { return; }
306
+ this.setSyncStatus("Updating identity keystone from server...", "info");
307
+ try {
308
+ const metaspace = await getGlobalMetaspace_waitIfNeeded();
309
+ const space = metaspace ? await metaspace.getLocalUserSpace({ lock: false }) : undefined;
310
+ const syncSvc = getKeystoneSyncService();
311
+ const updatedFrame = await syncSvc.updateActiveKeystone({
312
+ activePrimaryAddr: this.ibGibAddr,
313
+ metaspace,
314
+ space
315
+ });
316
+ if (updatedFrame) {
317
+ const newAddr = getIbGibAddr({ ibGib: updatedFrame });
318
+ this.ibGibAddr = newAddr;
319
+ this.staticIbGib = updatedFrame;
320
+ this.setSyncStatus(`Identity updated successfully to n=${updatedFrame.data?.n ?? 0}`, "success");
321
+ await this.loadIbGib({ getLatest: true });
322
+ } else {
323
+ this.setSyncStatus("Identity is already up to date.", "info");
324
+ }
325
+ } catch (error) {
326
+ console.error(`${lc} ${extractErrorMsg(error)}`);
327
+ this.setSyncStatus(`Update failed: ${extractErrorMsg(error)}`, "error");
328
+ }
329
+ }
330
+
331
+ protected async handleVerifyIdentityChain() {
332
+ const lc = `${this.lc}[${this.handleVerifyIdentityChain.name}]`;
333
+ console.log(`${lc} Verifying identity keystone timeline...`);
334
+ this.setVerificationStatus("Verification request sent...", "info");
335
+ try {
336
+ this.setVerificationStatus("Verification complete. Root Keystone is verified (Genesis phase 1).", "success");
337
+ } catch (error) {
338
+ this.setVerificationStatus(`Verification failed: ${extractErrorMsg(error)}`, "error");
339
+ }
340
+ }
341
+
342
+ protected async handleSetActiveIdentity() {
343
+ if (!this.ibGibAddr) { return; }
344
+ window.dispatchEvent(new CustomEvent(EVENT_IBGIB_IDENTITY_REQUEST_CHANGE, {
345
+ detail: { activeIdentityAddr: this.ibGibAddr },
346
+ bubbles: true,
347
+ composed: true
348
+ }));
349
+ }
350
+
351
+ private setVerificationStatus(msg: string, type: 'info' | 'success' | 'error') {
352
+ const statusEl = this.elements!.verificationStatusEl;
353
+ statusEl.textContent = msg;
354
+ statusEl.className = `status-msg ${type}`;
355
+ statusEl.classList.remove('hidden');
356
+ }
357
+
358
+ private async resolveActiveIdentity() {
359
+ const lc = `${this.lc}[resolveActiveIdentity]`;
360
+ try {
361
+ const domainIdentity = (globalThis as any).ibgib?.identity?.domainIdentity;
362
+ this.globalActiveAddr = domainIdentity ? getIbGibAddr({ ibGib: domainIdentity }) : null;
363
+ } catch (error) {
364
+ console.error(`${lc} ${extractErrorMsg(error)}`);
365
+ this.globalActiveAddr = null;
366
+ }
367
+ }
368
+
369
+ override async loadIbGib(opts?: { getLatest?: boolean }): Promise<void> {
370
+ const lc = `${this.lc}[${this.loadIbGib.name}]`;
371
+ try {
372
+ if (logalot) { console.log(`${lc} starting... (I: f0f7e8d52cbdc37bec844b2875996e26)`); }
373
+
374
+ if (!this.ibGibAddr) { return; }
375
+
376
+ const metaspace = await getGlobalMetaspace_waitIfNeeded();
377
+ if (!metaspace) {
378
+ throw new Error(`(UNEXPECTED) metaspace falsy? (E: a9864dbbaefc1082ce7bd228ebd67c26)`);
379
+ }
380
+ let space = await metaspace.getLocalUserSpace({ lock: false });
381
+ if (!space) {
382
+ throw new Error(`(UNEXPECTED) space falsy and we couldn't get default local user space from metaspace? (E: fa298edcecbda889cfd7b228fbd57c26)`);
383
+ }
384
+
385
+ let loadAddr = this.ibGibAddr;
386
+ if (opts?.getLatest) {
387
+ const latest = await metaspace.getLatestAddr({ addr: this.ibGibAddr, space });
388
+ if (latest) {
389
+ loadAddr = latest;
390
+ this.ibGibAddr = latest;
391
+ }
392
+ }
393
+
394
+ const resGet = await metaspace.get({ addrs: [loadAddr], space });
395
+
396
+ if (resGet.success && resGet.ibGibs && resGet.ibGibs.length === 1) {
397
+ this.staticIbGib = resGet.ibGibs[0] as KeystoneIbGib_V1;
398
+ } else {
399
+ const resIbGib = resGet.rawResultIbGib as any;
400
+ const addrsNotFound = resIbGib?.data?.addrsNotFound ?? 'unknown';
401
+ throw new Error(`couldn't find address ${loadAddr}. addrsNotFound: ${addrsNotFound}? resGet.errorMsg: ${resGet.errorMsg} (E: e0e5c9b7de2837bc902fa88390cd9f26)`);
402
+ }
403
+
404
+ await this.updateFrameDetailsView();
405
+ } catch (error) {
406
+ console.error(`${lc} ${extractErrorMsg(error)}`);
407
+ throw error;
408
+ } finally {
409
+ if (logalot) { console.log(`${lc} complete.`); }
410
+ }
411
+ }
412
+ protected override async renderUI(): Promise<void> {
413
+ const lc = `${this.lc}[${this.renderUI.name}]`;
414
+ try {
415
+ if (logalot) { console.log(`${lc} starting... (I: c8aa086352d8079708e00f78b6ac0826)`); }
416
+ await super.renderUI();
417
+ // await this.updateFrameDetailsView();
418
+ } catch (error) {
419
+ console.error(`${lc} ${extractErrorMsg(error)}`);
420
+ throw error;
421
+ } finally {
422
+ if (logalot) { console.log(`${lc} complete.`); }
423
+ }
424
+ }
425
+
426
+ private updateActiveButtonState() {
427
+ if (!this.elements) { return; }
428
+
429
+ const tjpGib = getGibInfo({ ibGibAddr: this.ibGibAddr }).tjpGib ?? getIbAndGib({ ibGibAddr: this.ibGibAddr }).gib;
430
+ const activeTjpGib = this.globalActiveAddr
431
+ ? (getGibInfo({ ibGibAddr: this.globalActiveAddr }).tjpGib ?? getIbAndGib({ ibGibAddr: this.globalActiveAddr }).gib)
432
+ : null;
433
+
434
+ const isTimelineActive = !!(this.globalActiveAddr && tjpGib === activeTjpGib);
435
+
436
+ if (isTimelineActive) {
437
+ this.elements.btnSetActiveEl.textContent = "Active Identity";
438
+ this.elements.btnSetActiveEl.classList.add('active-primary');
439
+ } else {
440
+ this.elements.btnSetActiveEl.textContent = "Set as Active Identity";
441
+ this.elements.btnSetActiveEl.classList.remove('active-primary');
442
+ }
443
+
444
+ // Disable buttons if historical
445
+ if (this.isHistoricalFrame) {
446
+ this.elements.btnSetActiveEl.disabled = true;
447
+ this.elements.btnVerifyChainEl.disabled = true;
448
+ this.elements.btnLinkGoogleEl.classList.add('disabled');
449
+ this.elements.btnLinkGithubEl.classList.add('disabled');
450
+ } else {
451
+ this.elements.btnVerifyChainEl.disabled = false;
452
+ this.elements.btnSetActiveEl.disabled = isTimelineActive;
453
+ this.elements.btnLinkGoogleEl.classList.remove('disabled');
454
+ this.elements.btnLinkGithubEl.classList.remove('disabled');
455
+
456
+ // Check if already linked
457
+ const isGoogleLinked = isSsoProviderLinked({ keystone: this.ibGib, providerId: 'google' });
458
+ const isGithubLinked = isSsoProviderLinked({ keystone: this.ibGib, providerId: 'github' });
459
+
460
+ // Google Card States
461
+ const googleCard = this.elements.btnLinkGoogleEl;
462
+ const googleLabel = googleCard.querySelector('.toggle-state-text')!;
463
+ if (isGoogleLinked) {
464
+ googleCard.classList.remove('unlinked');
465
+ googleCard.classList.add('linked');
466
+ googleLabel.textContent = "Google Linked ✅";
467
+ } else {
468
+ googleCard.classList.remove('linked');
469
+ googleCard.classList.add('unlinked');
470
+ googleLabel.textContent = "Unlinked";
471
+ }
472
+
473
+ // GitHub Card States
474
+ const githubCard = this.elements.btnLinkGithubEl;
475
+ const githubLabel = githubCard.querySelector('.toggle-state-text')!;
476
+ if (isGithubLinked) {
477
+ githubCard.classList.remove('unlinked');
478
+ githubCard.classList.add('linked');
479
+ githubLabel.textContent = "GitHub Linked ✅";
480
+ } else {
481
+ githubCard.classList.remove('linked');
482
+ githubCard.classList.add('unlinked');
483
+ githubLabel.textContent = "Unlinked";
484
+ }
485
+ }
486
+ }
487
+
488
+ private async updateFrameDetailsView(): Promise<void> {
489
+ const lc = `${this.lc}[${this.updateFrameDetailsView.name}]`;
490
+ try {
491
+ if (logalot) { console.log(`${lc} starting... (I: 1fa9e66d2e78fb100874573e2db71d26)`); }
492
+
493
+ if (!this.elements) { return; }
494
+
495
+ const keystone = this.ibGib;
496
+ if (!keystone) {
497
+ this.clearActiveDetails();
498
+ return;
499
+ }
500
+ const keystoneAddr = this.ibGibAddr;
501
+
502
+ // Update Verifiable Address
503
+ this.elements.identityAddrEl.textContent = keystoneAddr;
504
+
505
+ // Update Generation
506
+ this.elements.identityGenEl.textContent = keystone.data?.n !== undefined ? String(keystone.data.n) : '0 (Genesis)';
507
+
508
+ // Update Timestamp
509
+ const timestampStr = keystone.data?.timestamp;
510
+ let formattedTimestamp = 'N/A';
511
+ if (timestampStr) {
512
+ const parsed = parseInt(timestampStr);
513
+ if (!isNaN(parsed)) {
514
+ formattedTimestamp = new Date(parsed).toLocaleString();
515
+ } else {
516
+ formattedTimestamp = new Date(timestampStr).toLocaleString();
517
+ }
518
+ }
519
+ this.elements.identityTimestampEl.textContent = formattedTimestamp;
520
+
521
+ // Update UUID
522
+ this.elements.identityUuidEl.textContent = keystone.data?.uuid || 'N/A';
523
+
524
+ // Show Frame Details
525
+ const frameDetails = keystone.data?.frameDetails;
526
+ this.elements.identityFrameDetailsEl.textContent = frameDetails ? pretty(frameDetails) : '{}';
527
+
528
+ // Get and Show Aggregated details up to the scrolled-to frame
529
+ let isHistorical = false;
530
+ const metaspace = await getGlobalMetaspace_waitIfNeeded();
531
+ if (metaspace) {
532
+ const space = await metaspace.getLocalUserSpace({ lock: false });
533
+ if (space) {
534
+ try {
535
+ const latestAddr = await metaspace.getLatestAddr({ addr: this.ibGibAddr, space });
536
+ if (latestAddr && latestAddr !== this.ibGibAddr) {
537
+ isHistorical = true;
538
+ }
539
+ } catch (err) {
540
+ console.warn(`${lc} Error checking latest address: ${extractErrorMsg(err)}`);
541
+ }
542
+
543
+ try {
544
+ const keystoneSvc = new KeystoneService_V1();
545
+ const aggregated = await keystoneSvc.getAggregateDetails({
546
+ latestKeystone: keystone,
547
+ metaspace,
548
+ space
549
+ });
550
+
551
+ this.elements.identityAggrDetailsEl.textContent = aggregated ? pretty(aggregated) : '{}';
552
+
553
+ // Update Username and Description fields
554
+ this.elements.identityNameEl.textContent = aggregated?.username || aggregated?.profile?.name || aggregated?.name || '-';
555
+ this.elements.identityDescriptionEl.textContent = aggregated?.description || aggregated?.profile?.description || '-';
556
+ } catch (err) {
557
+ console.warn(`${lc} Error aggregating details: ${extractErrorMsg(err)}`);
558
+ this.elements.identityAggrDetailsEl.textContent = '{}';
559
+ this.elements.identityNameEl.textContent = '-';
560
+ this.elements.identityDescriptionEl.textContent = '-';
561
+ }
562
+ } else {
563
+ this.elements.identityAggrDetailsEl.textContent = '{}';
564
+ this.elements.identityNameEl.textContent = '-';
565
+ this.elements.identityDescriptionEl.textContent = '-';
566
+ }
567
+ } else {
568
+ this.elements.identityAggrDetailsEl.textContent = '{}';
569
+ this.elements.identityNameEl.textContent = '-';
570
+ this.elements.identityDescriptionEl.textContent = '-';
571
+ }
572
+
573
+ // Update historical warning state
574
+ this.isHistoricalFrame = isHistorical;
575
+ const banner = this.elements.historicalWarningBannerEl;
576
+ const container = this.elements.containerEl;
577
+ if (banner && container) {
578
+ if (isHistorical) {
579
+ banner.classList.remove('hidden');
580
+ container.classList.add('is-historical');
581
+ } else {
582
+ banner.classList.add('hidden');
583
+ container.classList.remove('is-historical');
584
+ }
585
+ }
586
+
587
+ // Render Raw Timeline JSON
588
+ this.elements.rawKeystoneJsonEl.textContent = pretty(keystone);
589
+
590
+ // Render Challenge Pools
591
+ this.renderChallengePools(keystone.data?.challengePools || []);
592
+
593
+ // Render Delegates, SSO link, and Passphrase Change cards (only if this is a primary keystone, hide them for delegate/session keystones)
594
+ const details = await this.getKeystoneDetails(this.ibGibAddr);
595
+ if (details.isPrimary) {
596
+ this.elements.delegatesCardEl.classList.remove('hidden');
597
+ await this.renderDelegates(keystone.data?.delegates);
598
+ this.elements.ssoLinkCardEl.classList.remove('hidden');
599
+ this.elements.changePassphraseCardEl.classList.remove('hidden');
600
+ } else {
601
+ this.elements.delegatesCardEl.classList.add('hidden');
602
+ this.elements.ssoLinkCardEl.classList.add('hidden');
603
+ this.elements.changePassphraseCardEl.classList.add('hidden');
604
+ }
605
+
606
+ this.updateActiveButtonState();
607
+ } catch (error) {
608
+ console.error(`${lc} ${extractErrorMsg(error)}`);
609
+ throw error;
610
+ } finally {
611
+ if (logalot) { console.log(`${lc} complete.`); }
612
+ }
613
+ }
614
+
615
+ private clearActiveDetails() {
616
+ if (!this.elements) { return; }
617
+ this.isHistoricalFrame = false;
618
+ if (this.elements.historicalWarningBannerEl) {
619
+ this.elements.historicalWarningBannerEl.classList.add('hidden');
620
+ }
621
+ if (this.elements.containerEl) {
622
+ this.elements.containerEl.classList.remove('is-historical');
623
+ }
624
+ this.elements.identityGenEl.textContent = '-';
625
+ this.elements.identityTimestampEl.textContent = '-';
626
+ this.elements.identityUuidEl.textContent = '-';
627
+ this.elements.identityNameEl.textContent = '-';
628
+ this.elements.identityDescriptionEl.textContent = '-';
629
+ this.elements.identityFrameDetailsEl.textContent = '{}';
630
+ this.elements.identityAggrDetailsEl.textContent = '{}';
631
+ this.elements.poolsContainerEl.innerHTML = '';
632
+ if (this.elements.delegatesListEl) {
633
+ this.elements.delegatesListEl.innerHTML = '';
634
+ }
635
+ }
636
+
637
+ private renderChallengePools(pools: any[]) {
638
+ if (!this.elements) { return; }
639
+ const container = this.elements.poolsContainerEl;
640
+ container.innerHTML = '';
641
+
642
+ if (!pools || pools.length === 0) {
643
+ container.innerHTML = `<p class="description">No challenge pools found in this keystone.</p>`;
644
+ return;
645
+ }
646
+
647
+ for (const pool of pools) {
648
+ const card = document.createElement('div');
649
+ card.className = 'pool-card';
650
+
651
+ const config = pool.config || {};
652
+ const behavior = config.behavior || {};
653
+ const allowedVerbs = config.allowedVerbs || [];
654
+ const activeCount = pool.challenges ? Object.keys(pool.challenges).length : 0;
655
+ const isForeign = !!pool.isForeign;
656
+
657
+ // Generate HTML for the challenges list
658
+ const challenges = pool.challenges || {};
659
+ const challengeListHtml = Object.entries(challenges).map(([id, challenge]: [string, any]) => {
660
+ const truncatedHash = challenge.hash && challenge.hash.length > 20
661
+ ? challenge.hash.substring(0, 10) + '...' + challenge.hash.substring(challenge.hash.length - 8)
662
+ : challenge.hash || 'N/A';
663
+ return `
664
+ <div class="pool-challenge-item">
665
+ <span class="challenge-id">${id}</span>
666
+ <span class="challenge-hash" title="${challenge.hash || ''}">${truncatedHash}</span>
667
+ </div>
668
+ `;
669
+ }).join('');
670
+
671
+ card.innerHTML = `
672
+ <div class="pool-header">
673
+ <span class="pool-title">${pool.id || 'Unnamed Pool'}</span>
674
+ <span class="pool-tag ${isForeign ? 'foreign' : 'native'}">${isForeign ? 'Foreign' : 'Native'}</span>
675
+ </div>
676
+ <div class="pool-grid">
677
+ <div class="pool-field">
678
+ <label>Verbs Allowed</label>
679
+ <span>${allowedVerbs.length > 0 ? allowedVerbs.join(', ') : 'Any'}</span>
680
+ </div>
681
+ <div class="pool-field">
682
+ <label>FIFO / Random cost</label>
683
+ <span>FIFO: ${behavior.selectSequentially ?? 0}, Rand: ${behavior.selectRandomly ?? 0}</span>
684
+ </div>
685
+ </div>
686
+
687
+ <!-- Collapsible Challenges List -->
688
+ <details class="pool-details">
689
+ <summary class="pool-details-summary">Challenges (${activeCount})</summary>
690
+ <div class="pool-challenges-list">
691
+ ${challengeListHtml || '<p class="placeholder-text" style="padding: 0.5rem; text-align: center;">No challenges active.</p>'}
692
+ </div>
693
+ </details>
694
+ `;
695
+ container.appendChild(card);
696
+ }
697
+ }
698
+
699
+ private showRemoteDelegateModal(info: any) {
700
+ const shadow = this.shadowRoot!;
701
+ let modalOverlay = shadow.getElementById('remote-delegate-modal-overlay');
702
+ if (modalOverlay) {
703
+ modalOverlay.remove();
704
+ }
705
+
706
+ modalOverlay = document.createElement('div');
707
+ modalOverlay.id = 'remote-delegate-modal-overlay';
708
+ modalOverlay.className = 'modal-overlay';
709
+ modalOverlay.style.cssText = `
710
+ position: fixed;
711
+ top: 0;
712
+ left: 0;
713
+ width: 100%;
714
+ height: 100%;
715
+ background: rgba(0, 0, 0, 0.7);
716
+ display: flex;
717
+ align-items: center;
718
+ justify-content: center;
719
+ z-index: 9999;
720
+ `;
721
+
722
+ const modalContent = document.createElement('div');
723
+ modalContent.className = 'modal-card card';
724
+ modalContent.style.cssText = `
725
+ background: var(--clr-bg-card, #1e1e1e);
726
+ color: var(--clr-text-primary, #ffffff);
727
+ padding: 1.5rem;
728
+ border-radius: 8px;
729
+ max-width: 550px;
730
+ width: 90%;
731
+ box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
732
+ font-family: inherit;
733
+ `;
734
+
735
+ const deviceNameText = info.deviceName || info.details?.deviceTag || info.details?.name || 'Device Delegate';
736
+ const nameText = info.username || info.name || info.details?.name || info.details?.username || 'Remote Delegate';
737
+ const descText = info.description || info.details?.description || 'N/A';
738
+ const spaceIdText = info.spaceId || info.details?.spaceId || 'N/A';
739
+ const allowedVerbsText = info.allowedVerbs ? info.allowedVerbs.join(', ') : 'None';
740
+ const tjpAddrText = info.delegateTjpAddr || 'N/A';
741
+
742
+ modalContent.innerHTML = `
743
+ <h3 style="margin-top: 0; display: flex; align-items: center; justify-content: space-between; gap: 0.5rem;">
744
+ <span>Remote Delegate Metadata</span>
745
+ <span class="badge badge-remote-device" style="background-color: #0d47a1; color: #90caf9; font-size: 0.75rem; padding: 0.2rem 0.5rem; border-radius: 4px; font-weight: bold;">Remote Device</span>
746
+ </h3>
747
+ <p style="color: var(--clr-text-secondary, #b3b3b3); font-size: 0.875rem; margin-bottom: 1rem;">
748
+ This delegate origin is a remote device. Full timeline history stays isolated on the origin device unless explicitly synced.
749
+ </p>
750
+ <div class="kv-grid" style="display: grid; grid-template-columns: 120px 1fr; gap: 0.5rem 1rem; margin-bottom: 1.5rem; font-size: 0.9rem;">
751
+ <div style="font-weight: bold; color: var(--clr-text-secondary, #b3b3b3);">Device Name</div>
752
+ <div>💻 ${deviceNameText}</div>
753
+
754
+ <div style="font-weight: bold; color: var(--clr-text-secondary, #b3b3b3);">Name</div>
755
+ <div>${nameText}</div>
756
+
757
+ <div style="font-weight: bold; color: var(--clr-text-secondary, #b3b3b3);">Description</div>
758
+ <div>${descText}</div>
759
+
760
+ <div style="font-weight: bold; color: var(--clr-text-secondary, #b3b3b3);">Space ID</div>
761
+ <code style="word-break: break-all; background: rgba(255,255,255,0.05); padding: 2px 6px; border-radius: 4px;">${spaceIdText}</code>
762
+
763
+ <div style="font-weight: bold; color: var(--clr-text-secondary, #b3b3b3);">Allowed Verbs</div>
764
+ <div>${allowedVerbsText}</div>
765
+
766
+ <div style="font-weight: bold; color: var(--clr-text-secondary, #b3b3b3);">TJP Address</div>
767
+ <code style="word-break: break-all; background: rgba(255,255,255,0.05); padding: 2px 6px; border-radius: 4px;">${tjpAddrText}</code>
768
+ </div>
769
+ <div style="display: flex; justify-content: flex-end;">
770
+ <button id="close-remote-modal-btn" class="action-btn secondary">Close</button>
771
+ </div>
772
+ `;
773
+
774
+ modalOverlay.appendChild(modalContent);
775
+ shadow.appendChild(modalOverlay);
776
+
777
+ const closeBtn = modalContent.querySelector('#close-remote-modal-btn');
778
+ closeBtn?.addEventListener('click', () => {
779
+ modalOverlay?.remove();
780
+ });
781
+
782
+ modalOverlay.addEventListener('click', (e) => {
783
+ if (e.target === modalOverlay) {
784
+ modalOverlay?.remove();
785
+ }
786
+ });
787
+ }
788
+
789
+ private async renderDelegates(delegates: Record<string, any> | undefined) {
790
+ if (!this.elements) { return; }
791
+ const listEl = this.elements.delegatesListEl;
792
+ listEl.innerHTML = '';
793
+
794
+ if (!delegates || Object.keys(delegates).length === 0) {
795
+ listEl.innerHTML = `
796
+ <tr>
797
+ <td colspan="4" style="text-align: center; color: var(--clr-text-secondary, #b3b3b3);">
798
+ No registered delegates.
799
+ </td>
800
+ </tr>
801
+ `;
802
+ return;
803
+ }
804
+
805
+ const metaspace = await getGlobalMetaspace_waitIfNeeded();
806
+ let localSpaceId: string | undefined;
807
+ if (metaspace) {
808
+ const space = await metaspace.getLocalUserSpace({ lock: false });
809
+ if (space?.ib) {
810
+ localSpaceId = parseSpaceIb({ spaceIb: space.ib }).spaceId;
811
+ }
812
+ }
813
+
814
+ for (const [delegateTjpAddr, info] of Object.entries(delegates)) {
815
+ const tr = document.createElement('tr');
816
+
817
+ const deviceName = info.deviceName || info.details?.deviceTag || info.details?.name || 'Device Delegate';
818
+ const tdName = document.createElement('td');
819
+
820
+ const delegateSpaceId = info.spaceId || info.details?.spaceId;
821
+ let badgeEl: HTMLSpanElement | null = null;
822
+
823
+ if (delegateSpaceId) {
824
+ badgeEl = document.createElement('span');
825
+ badgeEl.style.marginLeft = '0.5rem';
826
+ badgeEl.style.padding = '0.15rem 0.4rem';
827
+ badgeEl.style.borderRadius = '4px';
828
+ badgeEl.style.fontSize = '0.75rem';
829
+ badgeEl.style.fontWeight = 'bold';
830
+ if (localSpaceId && delegateSpaceId === localSpaceId) {
831
+ badgeEl.textContent = 'This Device';
832
+ badgeEl.className = 'badge badge-this-device';
833
+ badgeEl.style.backgroundColor = '#1b5e20';
834
+ badgeEl.style.color = '#a5d6a7';
835
+ } else {
836
+ badgeEl.textContent = 'Remote Device';
837
+ badgeEl.className = 'badge badge-remote-device';
838
+ badgeEl.style.backgroundColor = '#0d47a1';
839
+ badgeEl.style.color = '#90caf9';
840
+ }
841
+ }
842
+
843
+ const applyNameAndBadge = (displayName: string, hoverText?: string) => {
844
+ tdName.innerHTML = '';
845
+ const textSpan = document.createElement('span');
846
+ textSpan.textContent = displayName;
847
+ tdName.appendChild(textSpan);
848
+ if (badgeEl) {
849
+ tdName.appendChild(badgeEl);
850
+ }
851
+ tdName.title = hoverText || displayName;
852
+ };
853
+
854
+ const displayName = `💻 ${deviceName}`;
855
+ applyNameAndBadge(displayName, `TJP: ${delegateTjpAddr}\nDevice: ${deviceName}`);
856
+
857
+ const tdTjp = document.createElement('td');
858
+ tdTjp.textContent = delegateTjpAddr;
859
+ tdTjp.title = delegateTjpAddr;
860
+
861
+ const tdVerbs = document.createElement('td');
862
+ tdVerbs.textContent = info.allowedVerbs ? info.allowedVerbs.join(', ') : '-';
863
+ tdVerbs.title = tdVerbs.textContent;
864
+
865
+ const isRemote = !!(delegateSpaceId && localSpaceId && delegateSpaceId !== localSpaceId);
866
+
867
+ const tdActions = document.createElement('td');
868
+ const btnView = document.createElement('button');
869
+ btnView.className = 'action-btn secondary small';
870
+ btnView.textContent = 'View Details';
871
+ btnView.addEventListener('click', async () => {
872
+ const lc = `${this.lc}[renderDelegates.click]`;
873
+ if (isRemote) {
874
+ this.showRemoteDelegateModal(info);
875
+ } else {
876
+ if (info.delegateAddr) {
877
+ let addrToLoad = info.delegateAddr;
878
+ if (metaspace) {
879
+ const space = await metaspace.getLocalUserSpace({ lock: false });
880
+ if (space) {
881
+ try {
882
+ const latest = await metaspace.getLatestAddr({ addr: delegateTjpAddr, space });
883
+ if (latest) {
884
+ addrToLoad = latest;
885
+ }
886
+ } catch (err) {
887
+ console.warn(`${lc} Error resolving latest delegate address: ${extractErrorMsg(err)}`);
888
+ }
889
+ }
890
+ }
891
+ this.dispatchEvent(new CustomEvent('ibgib-view-keystone-details', {
892
+ detail: { addr: addrToLoad },
893
+ bubbles: true,
894
+ composed: true
895
+ }));
896
+ } else {
897
+ this.showRemoteDelegateModal(info);
898
+ }
899
+ }
900
+ });
901
+ tdActions.appendChild(btnView);
902
+
903
+ const btnRevoke = document.createElement('button');
904
+ btnRevoke.className = 'action-btn danger small';
905
+ btnRevoke.style.marginLeft = '0.4rem';
906
+ btnRevoke.textContent = 'Revoke';
907
+ btnRevoke.addEventListener('click', async () => {
908
+ await this.handleRevokeDelegate(delegateTjpAddr, deviceName);
909
+ });
910
+ tdActions.appendChild(btnRevoke);
911
+
912
+ tr.appendChild(tdName);
913
+ tr.appendChild(tdTjp);
914
+ tr.appendChild(tdVerbs);
915
+ tr.appendChild(tdActions);
916
+ listEl.appendChild(tr);
917
+ }
918
+ }
919
+
920
+ protected async handleRevokeDelegate(delegateTjpAddr: string, deviceName: string): Promise<void> {
921
+ const lc = `${this.lc}[${this.handleRevokeDelegate.name}]`;
922
+ try {
923
+ let masterSecret: string;
924
+ try {
925
+ masterSecret = await promptForSecret({
926
+ msg: `Enter Master Passphrase to revoke delegate '${deviceName}':`,
927
+ confirm: false
928
+ });
929
+ } catch (err) {
930
+ // User cancelled prompt
931
+ return;
932
+ }
933
+ if (!masterSecret) { return; }
934
+
935
+ this.setSyncStatus("Revoking delegate device...", "info");
936
+
937
+ const metaspace = await getGlobalMetaspace_waitIfNeeded();
938
+ if (!metaspace) throw new Error("Metaspace not found");
939
+ const space = await metaspace.getLocalUserSpace({ lock: false });
940
+ if (!space) { throw new Error("Local space not found"); }
941
+
942
+ const keystoneSvc = new KeystoneService_V1();
943
+
944
+ // Unregister delegate from parent keystone
945
+ const evolvedParent = await keystoneSvc.unregisterDelegate({
946
+ parentKeystone: this.ibGib!,
947
+ delegateTjpAddr,
948
+ masterSecret,
949
+ metaspace,
950
+ space
951
+ });
952
+
953
+ // Put evolved parent keystone to server via putEvolveKeystone
954
+ const parentTjp = getTjpAddr({ ibGib: this.ibGib! }) || getIbGibAddr({ ibGib: this.ibGib! });
955
+ const syncRes = await getApiBridge().putEvolveKeystone({
956
+ domainAddr: parentTjp,
957
+ keystoneIbGib: evolvedParent,
958
+ relatedKeystoneIbGibs: []
959
+ });
960
+
961
+ if (!syncRes.success) {
962
+ throw new Error(`Server rejected delegate revocation: ${syncRes.message}`);
963
+ }
964
+
965
+ // Save evolved parent to space and update local index
966
+ await metaspace.put({ ibGibs: [evolvedParent], space });
967
+ await metaspace.registerNewIbGib({ ibGib: evolvedParent, space });
968
+ await updateSpecialIndex({
969
+ type: "keystones",
970
+ rel8nInfos: [
971
+ {
972
+ rel8nName: "keystone",
973
+ ibGibs: [toDto({ ibGib: evolvedParent })]
974
+ }
975
+ ],
976
+ metaspace,
977
+ space
978
+ });
979
+
980
+ const evolvedAddr = getIbGibAddr({ ibGib: evolvedParent });
981
+
982
+ // Dispatch EVENT_IBGIB_IDENTITY_CHANGED
983
+ window.dispatchEvent(new CustomEvent(EVENT_IBGIB_IDENTITY_CHANGED, {
984
+ detail: { activeIdentityAddr: evolvedAddr },
985
+ bubbles: true,
986
+ composed: true
987
+ }));
988
+
989
+ this.setSyncStatus(`Successfully revoked device '${deviceName}'!`, "success");
990
+
991
+ // Refresh the view
992
+ this.ibGibAddr = evolvedAddr;
993
+ this.staticIbGib = evolvedParent;
994
+ await this.loadIbGib({ getLatest: true });
995
+
996
+ } catch (error) {
997
+ console.error(`${lc} Delegate revocation failed: ${extractErrorMsg(error)}`);
998
+ this.setSyncStatus(`Revocation failed: ${extractErrorMsg(error)}`, "error");
999
+ }
1000
+ }
1001
+
1002
+ override async handleContextUpdated(): Promise<void> {
1003
+ const lc = `${this.lc}[${this.handleContextUpdated.name}]`;
1004
+ try {
1005
+ if (logalot) { console.log(`${lc} starting... (I: 243a88c1d4689c779bbbf2a4abd5da26)`); }
1006
+
1007
+ // don't do anything when the context is updated?
1008
+
1009
+ // is this hit? no. leave this as a no-op
1010
+ console.warn(`${lc} this component currently designed expecting that this does not hit (W: 95dc018b87027287e860de0826146826)`);
1011
+
1012
+ await super.handleContextUpdated();
1013
+ } catch (error) {
1014
+ console.error(`${lc} ${extractErrorMsg(error)}`);
1015
+ throw error;
1016
+ } finally {
1017
+ if (logalot) { console.log(`${lc} complete.`); }
1018
+ }
1019
+ }
1020
+
1021
+ protected override async handleNewContextChild({ childIbGib }: { childIbGib: IbGib_V1; }): Promise<void> {
1022
+ const lc = `${this.lc}[${this.handleNewContextChild.name}]`;
1023
+ try {
1024
+ if (logalot) { console.log(`${lc} starting... (I: b04dc63842f871658840233485659726)`); }
1025
+ // is this hit? no
1026
+ await super.handleNewContextChild({ childIbGib });
1027
+
1028
+ console.warn(`${lc} this component currently designed expecting that this does not hit (W: 95dc018b87027287e860de0826146826)`);
1029
+ } catch (error) {
1030
+ console.error(`${lc} ${extractErrorMsg(error)}`);
1031
+ throw error;
1032
+ } finally {
1033
+ if (logalot) { console.log(`${lc} complete.`); }
1034
+ }
1035
+ }
1036
+
1037
+ protected async handleSSOLink(providerId: 'google' | 'github') {
1038
+ const lc = `${this.lc}[${this.handleSSOLink.name}]`;
1039
+ this.setSSOStatus(`Linking ${providerId}...`, "info");
1040
+
1041
+ try {
1042
+ // 1. Fetch public SSO configs from server
1043
+ const res = await fetch('/api/identity/sso/config');
1044
+ if (!res.ok) {
1045
+ throw new Error(`Failed to fetch SSO config from server: ${res.statusText}`);
1046
+ }
1047
+ const data = await res.json();
1048
+ if (!data.success || !data.providers) {
1049
+ throw new Error(`SSO configuration fetch failed: ${data.message || 'unknown error'}`);
1050
+ }
1051
+
1052
+ const providerConfig = data.providers.find((p: any) => p.providerId === providerId);
1053
+ if (!providerConfig) {
1054
+ throw new Error(`SSO provider '${providerId}' is not configured on the server.`);
1055
+ }
1056
+
1057
+ // 2. Generate a secure, high-entropy user nonce
1058
+ const userNonce = (Math.random().toString(36).substring(2) + Math.random().toString(36).substring(2)).substring(0, 32);
1059
+
1060
+ // 3. Construct state payload
1061
+ const stateObj = {
1062
+ providerId,
1063
+ parentTjpAddr: this.ibGibAddr,
1064
+ userNonce
1065
+ };
1066
+ const state = btoa(JSON.stringify(stateObj));
1067
+
1068
+ // 4. Construct Auth URL
1069
+ const authUrl = `${providerConfig.authUrl}?client_id=${providerConfig.clientId}&redirect_uri=${encodeURIComponent(providerConfig.redirectUri)}&response_type=code&scope=${encodeURIComponent(providerConfig.scope)}&state=${encodeURIComponent(state)}`;
1070
+
1071
+ // 5. Open popup window
1072
+ const popup = window.open(
1073
+ authUrl,
1074
+ 'sso-oauth-popup',
1075
+ 'width=600,height=700,status=yes,toolbar=no,menubar=no,location=yes'
1076
+ );
1077
+ if (!popup) {
1078
+ throw new Error("Popup blocked by browser. Please enable popups for this site.");
1079
+ }
1080
+
1081
+ // 6. Listen for callback from pop-up
1082
+ let checkClosedInterval: any;
1083
+ const messageListener = async (event: MessageEvent) => {
1084
+ if (event.origin !== window.location.origin) return;
1085
+ const callbackData = event.data;
1086
+ if (callbackData && callbackData.type === 'sso-oauth-callback') {
1087
+ window.removeEventListener('message', messageListener);
1088
+ clearInterval(checkClosedInterval);
1089
+ await this.handleSSOLinkCallback(callbackData.code, stateObj, providerConfig.redirectUri);
1090
+ }
1091
+ };
1092
+ window.addEventListener('message', messageListener);
1093
+
1094
+ // 7. Poll for manual closure of the popup window
1095
+ checkClosedInterval = setInterval(() => {
1096
+ if (popup.closed) {
1097
+ clearInterval(checkClosedInterval);
1098
+ window.removeEventListener('message', messageListener);
1099
+ const statusEl = this.elements!.ssoStatusMsgEl;
1100
+ if (statusEl.textContent && statusEl.textContent.startsWith('Linking')) {
1101
+ this.setSSOStatus('Linking cancelled (window closed).', 'error');
1102
+ }
1103
+ }
1104
+ }, 500);
1105
+
1106
+ } catch (error) {
1107
+ console.error(`${lc} SSO link initiation failed: ${extractErrorMsg(error)}`);
1108
+ this.setSSOStatus(`Link failed: ${extractErrorMsg(error)}`, "error");
1109
+ }
1110
+ }
1111
+
1112
+ private setSSOStatus(msg: string, type: 'info' | 'success' | 'error') {
1113
+ const statusEl = this.elements!.ssoStatusMsgEl;
1114
+ statusEl.textContent = msg;
1115
+ statusEl.className = `status-msg ${type}`;
1116
+ statusEl.classList.remove('hidden');
1117
+ }
1118
+
1119
+ protected async handleSSOLinkCallback(code: string, stateObj: any, redirectUri: string) {
1120
+ const lc = `${this.lc}[${this.handleSSOLinkCallback.name}]`;
1121
+ this.setSSOStatus("Retrieving challenge pool configuration from server...", "info");
1122
+
1123
+ try {
1124
+ // 1. Exchange OAuth code for custodian public pool config
1125
+ const res = await fetch('/api/identity/sso/link', {
1126
+ method: 'POST',
1127
+ headers: { 'Content-Type': 'application/json' },
1128
+ body: JSON.stringify({
1129
+ code,
1130
+ providerId: stateObj.providerId,
1131
+ parentTjpAddr: stateObj.parentTjpAddr,
1132
+ userNonce: stateObj.userNonce,
1133
+ redirectUri
1134
+ })
1135
+ });
1136
+ if (!res.ok) {
1137
+ const errBody = await res.json().catch(() => ({}));
1138
+ throw new Error(`Server link exchange failed: ${errBody.message || res.statusText}`);
1139
+ }
1140
+
1141
+ const linkData = await res.json();
1142
+ if (!linkData.success || !linkData.custodianPool) {
1143
+ throw new Error(`Failed to retrieve custodian challenge pool: ${linkData.message || 'unknown error'}`);
1144
+ }
1145
+
1146
+ const custodianPool = linkData.custodianPool;
1147
+
1148
+ // 2. Prompt user for master secret and verify it
1149
+ const keystoneService = new KeystoneService_V1();
1150
+ let masterSecret: string | undefined;
1151
+ let isCorrect = false;
1152
+ let tries = 0;
1153
+ const maxTries = 8;
1154
+
1155
+ while (tries < maxTries && !isCorrect) {
1156
+ try {
1157
+ const promptMsg = tries === 0
1158
+ ? "Link successful! Enter your local Master Secret (Passphrase) to sign and register the custodian pool"
1159
+ : `Incorrect passphrase. Please try again (${maxTries - tries} tries remaining):`;
1160
+ masterSecret = await promptForSecret({
1161
+ msg: promptMsg,
1162
+ confirm: false
1163
+ });
1164
+ } catch (error) {
1165
+ // cancelled
1166
+ if (logalot) { console.log(`${lc}[promptForSecret] user cancelled (I: 911ff1fb0234949228481968e9087626)`); }
1167
+ masterSecret = undefined;
1168
+ break;
1169
+ }
1170
+
1171
+ if (!masterSecret) {
1172
+ break;
1173
+ }
1174
+
1175
+ // Verify secret using verifySigningSecret (requires manage poolId)
1176
+ isCorrect = await keystoneService.verifySigningSecret({
1177
+ keystoneIbGib: this.ibGib!,
1178
+ signingSecret: masterSecret,
1179
+ poolId: 'manage'
1180
+ });
1181
+
1182
+ if (!isCorrect) {
1183
+ tries++;
1184
+ }
1185
+ }
1186
+
1187
+ if (!isCorrect) {
1188
+ this.setSSOStatus("Link cancelled or failed (incorrect passphrase).", "error");
1189
+ return;
1190
+ }
1191
+
1192
+ this.setSSOStatus("Evolving identity locally and generating cryptographic signatures...", "info");
1193
+
1194
+ const metaspace = await getGlobalMetaspace_waitIfNeeded();
1195
+ if (!metaspace) throw new Error("Metaspace not found");
1196
+ const space = await metaspace.getLocalUserSpace({ lock: false });
1197
+ if (!space) { throw new Error("Local space not found"); }
1198
+
1199
+ // 3. Evolve parent keystone to include the custodian pool
1200
+ const evolvedParent = await keystoneService.addPools({
1201
+ latestKeystone: this.ibGib!,
1202
+ masterSecret: masterSecret!,
1203
+ newPools: [custodianPool],
1204
+ metaspace,
1205
+ space
1206
+ });
1207
+
1208
+ // 4. Sync evolved parent keystone back to server
1209
+ this.setSSOStatus("Publishing evolved identity keystone to server...", "info");
1210
+ const syncRes = await getApiBridge().putEvolveKeystone({
1211
+ domainAddr: stateObj.parentTjpAddr,
1212
+ keystoneIbGib: evolvedParent,
1213
+ relatedKeystoneIbGibs: [] // No outward delegate timelines
1214
+ });
1215
+ if (!syncRes.success) {
1216
+ throw new Error(`Server synchronization rejected: ${syncRes.message}`);
1217
+ }
1218
+
1219
+ // 5. Update index locally
1220
+ await updateSpecialIndex({
1221
+ type: "keystones",
1222
+ rel8nInfos: [
1223
+ {
1224
+ rel8nName: "keystone",
1225
+ ibGibs: [toDto({ ibGib: evolvedParent })]
1226
+ }
1227
+ ],
1228
+ metaspace,
1229
+ space
1230
+ });
1231
+
1232
+ this.setSSOStatus(`Successfully linked with ${stateObj.providerId}!`, "success");
1233
+ await this.loadIbGib({ getLatest: false });
1234
+
1235
+ } catch (error) {
1236
+ console.error(`${lc} SSO callback processing failed: ${extractErrorMsg(error)}`);
1237
+ this.setSSOStatus(`Link failed: ${extractErrorMsg(error)}`, "error");
1238
+ }
1239
+ }
1240
+
1241
+ protected async handleSSOClick(providerId: 'google' | 'github') {
1242
+ const isLinked = isSsoProviderLinked({ keystone: this.ibGib, providerId });
1243
+ if (isLinked) {
1244
+ await this.handleSSOUnlink(providerId);
1245
+ } else {
1246
+ await this.handleSSOLink(providerId);
1247
+ }
1248
+ }
1249
+
1250
+ protected async handleSSOUnlink(providerId: 'google' | 'github') {
1251
+ const lc = `${this.lc}[${this.handleSSOUnlink.name}]`;
1252
+ this.setSSOStatus(`Unlinking ${providerId}...`, "info");
1253
+
1254
+ try {
1255
+ // 1. Prompt user for passphrase
1256
+ const keystoneService = new KeystoneService_V1();
1257
+ let masterSecret: string | undefined;
1258
+ let isCorrect = false;
1259
+ let tries = 0;
1260
+ const maxTries = 8;
1261
+
1262
+ while (tries < maxTries && !isCorrect) {
1263
+ try {
1264
+ const promptMsg = tries === 0
1265
+ ? `Are you sure you want to unlink your ${providerId} account? If so, enter your local Master Secret (Passphrase) to authorize. Otherwise, click Cancel.`
1266
+ : `Incorrect passphrase. Please try again (${maxTries - tries} tries remaining):`;
1267
+ masterSecret = await promptForSecret({
1268
+ msg: promptMsg,
1269
+ confirm: false
1270
+ });
1271
+ } catch (error) {
1272
+ masterSecret = undefined;
1273
+ break;
1274
+ }
1275
+
1276
+ if (!masterSecret) {
1277
+ break;
1278
+ }
1279
+
1280
+ // Verify secret using verifySigningSecret (requires manage poolId)
1281
+ isCorrect = await keystoneService.verifySigningSecret({
1282
+ keystoneIbGib: this.ibGib!,
1283
+ signingSecret: masterSecret,
1284
+ poolId: 'manage'
1285
+ });
1286
+
1287
+ if (!isCorrect) {
1288
+ tries++;
1289
+ }
1290
+ }
1291
+
1292
+ if (!isCorrect) {
1293
+ this.setSSOStatus("Unlink cancelled or failed (incorrect passphrase).", "error");
1294
+ return;
1295
+ }
1296
+
1297
+ this.setSSOStatus("Evolving identity locally and removing custodian pool...", "info");
1298
+
1299
+ const metaspace = await getGlobalMetaspace_waitIfNeeded();
1300
+ if (!metaspace) throw new Error("Metaspace not found");
1301
+ const space = await metaspace.getLocalUserSpace({ lock: false });
1302
+ if (!space) { throw new Error("Local space not found"); }
1303
+
1304
+ // 2. Evolve parent keystone to remove the custodian pool
1305
+ const targetPoolId = `custodian-manage-${providerId}`;
1306
+ const evolvedParent = await keystoneService.removePools({
1307
+ latestKeystone: this.ibGib!,
1308
+ masterSecret: masterSecret!,
1309
+ poolIds: [targetPoolId],
1310
+ metaspace,
1311
+ space
1312
+ });
1313
+
1314
+ // 3. Sync evolved parent keystone back to server
1315
+ this.setSSOStatus("Publishing evolved identity keystone to server...", "info");
1316
+ const syncRes = await getApiBridge().putEvolveKeystone({
1317
+ domainAddr: getIbGibAddr({ ibGib: this.ibGib! }),
1318
+ keystoneIbGib: evolvedParent,
1319
+ relatedKeystoneIbGibs: [] // No outward delegate timelines
1320
+ });
1321
+ if (!syncRes.success) {
1322
+ throw new Error(`Server synchronization rejected: ${syncRes.message}`);
1323
+ }
1324
+
1325
+ // 4. Update index locally
1326
+ await updateSpecialIndex({
1327
+ type: "keystones",
1328
+ rel8nInfos: [
1329
+ {
1330
+ rel8nName: "keystone",
1331
+ ibGibs: [toDto({ ibGib: evolvedParent })]
1332
+ }
1333
+ ],
1334
+ metaspace,
1335
+ space
1336
+ });
1337
+
1338
+ this.setSSOStatus(`Successfully unlinked ${providerId}!`, "success");
1339
+ await this.loadIbGib({ getLatest: true });
1340
+
1341
+ } catch (error) {
1342
+ console.error(`${lc} SSO unlink failed: ${extractErrorMsg(error)}`);
1343
+ this.setSSOStatus(`Unlink failed: ${extractErrorMsg(error)}`, "error");
1344
+ }
1345
+ }
1346
+
1347
+ private setChangePassphraseStatus(msg: string, type: 'info' | 'success' | 'error') {
1348
+ const el = this.elements!.changePassphraseStatusEl;
1349
+ el.textContent = msg;
1350
+ el.className = `status-msg ${type}`;
1351
+ el.classList.remove('hidden');
1352
+ }
1353
+
1354
+ protected async handleChangePassphrase(): Promise<void> {
1355
+ const lc = `${this.lc}[${this.handleChangePassphrase.name}]`;
1356
+ this.setChangePassphraseStatus("Validating entries...", "info");
1357
+
1358
+ try {
1359
+ const currentPassphrase = this.elements!.inputCurrentPassphraseEl.value;
1360
+ const newPassphrase = this.elements!.inputNewPassphraseEl.value;
1361
+ const confirmPassphrase = this.elements!.inputConfirmPassphraseEl.value;
1362
+
1363
+ if (!currentPassphrase) {
1364
+ this.setChangePassphraseStatus("Current passphrase is required.", "error");
1365
+ return;
1366
+ }
1367
+ if (!newPassphrase) {
1368
+ this.setChangePassphraseStatus("New passphrase is required.", "error");
1369
+ return;
1370
+ }
1371
+ if (newPassphrase !== confirmPassphrase) {
1372
+ this.setChangePassphraseStatus("New passphrase and confirmation do not match.", "error");
1373
+ return;
1374
+ }
1375
+
1376
+ const keystoneService = new KeystoneService_V1();
1377
+
1378
+ // 1. Verify current passphrase against parent manage pool
1379
+ const isMatch = await keystoneService.verifySigningSecret({
1380
+ keystoneIbGib: this.ibGib!,
1381
+ signingSecret: currentPassphrase,
1382
+ poolId: 'manage'
1383
+ });
1384
+ if (!isMatch) {
1385
+ this.setChangePassphraseStatus("Incorrect current passphrase.", "error");
1386
+ return;
1387
+ }
1388
+
1389
+ this.setChangePassphraseStatus("Evolving primary identity keystone...", "info");
1390
+
1391
+ const metaspace = await getGlobalMetaspace_waitIfNeeded();
1392
+ if (!metaspace) throw new Error("Metaspace not found");
1393
+ const space = await metaspace.getLocalUserSpace({ lock: false });
1394
+ if (!space) { throw new Error("Local space not found"); }
1395
+
1396
+ // 2. Rotate parent identity
1397
+ debugger; // walk through this...looking for delegate failure
1398
+ const { newKeystone: evolvedParent, newDelegates: evolvedDelegates } = await keystoneService.changePassword({
1399
+ keystoneIbGib: this.ibGib!,
1400
+ newMasterSecret: newPassphrase,
1401
+ signingSecret: currentPassphrase,
1402
+ signingPoolId: 'manage',
1403
+ metaspace,
1404
+ space
1405
+ });
1406
+ debugger; // look at evolvedDelegates
1407
+
1408
+ this.setChangePassphraseStatus("Resolving and rotating delegate keystones...", "info");
1409
+
1410
+ // // 3. Evolve registered delegate keystones (preserving custodian/foreign delegate secrets)
1411
+ // const delegates = this.ibGib!.data?.delegates || {};
1412
+ // const evolvedDelegates: KeystoneIbGib_V1[] = [];
1413
+
1414
+ // for (const delegateInfo of Object.values(delegates)) {
1415
+ // const delegateAddr = delegateInfo.delegateAddr;
1416
+ // const delegateKeystone = await keystoneService.getLatestKeystone({
1417
+ // addr: delegateAddr,
1418
+ // metaspace,
1419
+ // space,
1420
+ // });
1421
+
1422
+ // // Identify user-owned challenge pools in the delegate that match the old passphrase
1423
+ // const poolsToRotate: string[] = [];
1424
+ // for (const pool of delegateKeystone.data?.challengePools ?? []) {
1425
+ // if (!pool.isForeign) {
1426
+ // /**
1427
+ // * WARNING: There is an extreme edge case that if two pools
1428
+ // * happen to be owned by different parties but share the
1429
+ // * same secret, this will change the wrong pool's secret
1430
+ // * also. For V1, this shouldn't matter. But we need a
1431
+ // * better way of tracking pool ownership for V2 (or even
1432
+ // * V1 if we have multi-party support). (DO NOT REMOVE
1433
+ // * THIS COMMENT UNTIL THIS IS ADDRESSED)
1434
+ // */
1435
+ // const isPoolMatch = await keystoneService.verifySigningSecret({
1436
+ // keystoneIbGib: delegateKeystone,
1437
+ // signingSecret: currentPassphrase,
1438
+ // poolId: pool.id
1439
+ // });
1440
+ // if (isPoolMatch) { poolsToRotate.push(pool.id); }
1441
+ // }
1442
+ // }
1443
+
1444
+ // if (poolsToRotate.length > 0) {
1445
+ // console.log(`${lc} Rotating pools in delegate ${delegateInfo.delegateTjpAddr}: ${poolsToRotate.join(', ')}`);
1446
+ // const {newKeystone: evolvedDelegate} = await keystoneService.changePassword({
1447
+ // keystoneIbGib: delegateKeystone,
1448
+ // newMasterSecret: newPassphrase,
1449
+ // signingSecret: currentPassphrase,
1450
+ // signingPoolId: 'manage',
1451
+ // poolIds: poolsToRotate,
1452
+ // metaspace,
1453
+ // space
1454
+ // });
1455
+ // evolvedDelegates.push(evolvedDelegate);
1456
+ // }
1457
+ // }
1458
+
1459
+ // 4. Sync evolved parent and all evolved delegate keystones atomically
1460
+ this.setChangePassphraseStatus("Syncing evolved keystones to server...", "info");
1461
+ const parentTjp = getIbGibAddr({ ibGib: this.ibGib! }); // is this.ibGib the tjp always? or is it the latest in the keystone line? Does it matter?
1462
+
1463
+ const syncRes = await getApiBridge().putEvolveKeystone({
1464
+ domainAddr: parentTjp,
1465
+ keystoneIbGib: evolvedParent,
1466
+ relatedKeystoneIbGibs: evolvedDelegates,
1467
+ });
1468
+ if (!syncRes.success) {
1469
+ throw new Error(`Server synchronization rejected: ${syncRes.message}`);
1470
+ }
1471
+
1472
+ // 5. Update index locally
1473
+ this.setChangePassphraseStatus("Updating local indexes...", "info");
1474
+ const newKeystoneIbGibs = [toDto({ ibGib: evolvedParent })];
1475
+ if (evolvedDelegates) {
1476
+ evolvedDelegates.forEach(d => {
1477
+ newKeystoneIbGibs.push(toDto({ ibGib: d }));
1478
+ });
1479
+ }
1480
+ const rel8nInfos = [
1481
+ {
1482
+ rel8nName: "keystone",
1483
+ ibGibs: newKeystoneIbGibs,
1484
+ }
1485
+ ];
1486
+ await updateSpecialIndex({
1487
+ type: "keystones",
1488
+ rel8nInfos,
1489
+ metaspace,
1490
+ space
1491
+ });
1492
+
1493
+ // Clear inputs
1494
+ this.elements!.inputCurrentPassphraseEl.value = "";
1495
+ this.elements!.inputNewPassphraseEl.value = "";
1496
+ this.elements!.inputConfirmPassphraseEl.value = "";
1497
+
1498
+ this.setChangePassphraseStatus("Passphrase updated successfully!", "success");
1499
+ await this.loadIbGib({ getLatest: true });
1500
+
1501
+ } catch (error) {
1502
+ console.error(`${lc} Passphrase rotation failed: ${extractErrorMsg(error)}`);
1503
+ this.setChangePassphraseStatus(`Update failed: ${extractErrorMsg(error)}`, "error");
1504
+ }
1505
+ }
1506
+ }