@ibgib/space-gib 0.0.9 → 0.0.13

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 (82) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +1 -0
  3. package/dist/client/bootstrap.mjs +33 -33
  4. package/dist/client/bootstrap.mjs.map +3 -3
  5. package/dist/client/chunk-ROJZUPPE.mjs +19 -0
  6. package/dist/client/chunk-ROJZUPPE.mjs.map +7 -0
  7. package/dist/client/chunk-WJHRARK6.mjs +2329 -0
  8. package/dist/client/chunk-WJHRARK6.mjs.map +7 -0
  9. package/dist/client/index.mjs +22 -1
  10. package/dist/client/index.mjs.map +4 -4
  11. package/dist/client/script.mjs +1 -1
  12. package/dist/server/server.mjs +19147 -18210
  13. package/dist/server/server.mjs.map +4 -4
  14. package/package.json +4 -4
  15. package/space-gib.localhost-1785337158142.log +75 -0
  16. package/src/client/AUTO-GENERATED-version.mts +1 -1
  17. package/src/client/README.md +1 -1
  18. package/src/client/api/space-gib-api-bridge.mts +8 -224
  19. package/src/client/ui/shell/space-gib-shell-service.mts +68 -18
  20. package/src/common/keystone-policies.mts +1 -1
  21. package/src/server/README.md +3 -2
  22. package/src/server/server.mts +13 -32
  23. package/src/server/test.json +0 -0
  24. package/dist/client/chunk-ACIGPCQW.mjs +0 -2407
  25. package/dist/client/chunk-ACIGPCQW.mjs.map +0 -7
  26. package/dist/client/chunk-QRMTJE6M.mjs +0 -42
  27. package/dist/client/chunk-QRMTJE6M.mjs.map +0 -7
  28. package/space-gib.localhost-1783713259760.log +0 -45
  29. package/src/client/components/identity-header/IMPLEMENTATION.md +0 -45
  30. package/src/client/components/identity-header/identity-header.css +0 -112
  31. package/src/client/components/identity-header/identity-header.html +0 -11
  32. package/src/client/components/identity-header/identity-header.mts +0 -439
  33. package/src/client/components/identity-manager/IMPLEMENTATION.md +0 -100
  34. package/src/client/components/identity-manager/identity-manager.css +0 -171
  35. package/src/client/components/identity-manager/identity-manager.html +0 -19
  36. package/src/client/components/identity-manager/identity-manager.mts +0 -639
  37. package/src/client/components/keystone-creator/keystone-creator.css +0 -65
  38. package/src/client/components/keystone-creator/keystone-creator.html +0 -41
  39. package/src/client/components/keystone-creator/keystone-creator.mts +0 -443
  40. package/src/client/components/keystone-details/keystone-details.css +0 -611
  41. package/src/client/components/keystone-details/keystone-details.html +0 -151
  42. package/src/client/components/keystone-details/keystone-details.mts +0 -1213
  43. package/src/client/components/keystone-scrubber/SCRUBBER_IMPLEMENTATION.md +0 -33
  44. package/src/client/components/keystone-scrubber/keystone-scrubber.css +0 -46
  45. package/src/client/components/keystone-scrubber/keystone-scrubber.html +0 -15
  46. package/src/client/components/keystone-scrubber/keystone-scrubber.mts +0 -356
  47. package/src/server/bootstrap-helper.mts +0 -141
  48. package/src/server/bootstrap-helper.respec.mts +0 -100
  49. package/src/server/metaspace-nodeindexedspace/metaspace-nodeindexedspace.mts +0 -85
  50. package/src/server/path-constants.mts +0 -101
  51. package/src/server/path-helper.mts +0 -101
  52. package/src/server/path-helper.respec.mts +0 -99
  53. package/src/server/serve-gib/CHANGELOG.md +0 -29
  54. package/src/server/serve-gib/README.md +0 -43
  55. package/src/server/serve-gib/constants.mts +0 -1
  56. package/src/server/serve-gib/handlers/api/debug/ws-echo.handler.mts +0 -105
  57. package/src/server/serve-gib/handlers/api/health.handler.mts +0 -23
  58. package/src/server/serve-gib/handlers/api/health.respec.mts +0 -51
  59. package/src/server/serve-gib/handlers/api/ibgib/ibgib-handler-types.mts +0 -49
  60. package/src/server/serve-gib/handlers/api/ibgib/ibgib.handler.mts +0 -176
  61. package/src/server/serve-gib/handlers/api/keystone/keystone-evolve.handler.mts +0 -150
  62. package/src/server/serve-gib/handlers/api/keystone/keystone-genesis.handler.mts +0 -146
  63. package/src/server/serve-gib/handlers/api/keystone/keystone-get.handler.mts +0 -198
  64. package/src/server/serve-gib/handlers/api/keystone/keystone-get.respec.mts +0 -107
  65. package/src/server/serve-gib/handlers/api/keystone/keystone-handler-types.mts +0 -29
  66. package/src/server/serve-gib/handlers/api/keystone/keystone-post.handler.mts +0 -55
  67. package/src/server/serve-gib/handlers/api/keystone/keystone-post.respec.mts +0 -130
  68. package/src/server/serve-gib/handlers/api/keystone/sso-config.handler.mts +0 -66
  69. package/src/server/serve-gib/handlers/api/keystone/sso-link.handler.mts +0 -140
  70. package/src/server/serve-gib/handlers/api/keystone/sso-login.handler.mts +0 -190
  71. package/src/server/serve-gib/handlers/error-handler.mts +0 -36
  72. package/src/server/serve-gib/handlers/handler-base.mts +0 -383
  73. package/src/server/serve-gib/handlers/static-handler.mts +0 -82
  74. package/src/server/serve-gib/handlers/ws/sync-upgrade-handler-base.mts +0 -233
  75. package/src/server/serve-gib/handlers/ws/sync-upgrade.handler.mts +0 -24
  76. package/src/server/serve-gib/handlers/ws/ws-helper.mts +0 -216
  77. package/src/server/serve-gib/handlers/ws/ws-types.mts +0 -53
  78. package/src/server/serve-gib/serve-gib-helpers.mts +0 -32
  79. package/src/server/serve-gib/serve-gib-v1.mts +0 -172
  80. package/src/server/serve-gib/serve-gib.respec.mts +0 -90
  81. package/src/server/serve-gib/types.mts +0 -102
  82. package/src/server/server-constants.mts +0 -2
@@ -1,23 +0,0 @@
1
- /**
2
- * @module serve-gib/handlers/api/health
3
- */
4
-
5
- import { ServeGibHandlerBase } from '../handler-base.mjs';
6
- import { RequestContext, ResponseResult, ServeGibHttpMethod } from '../../types.mjs';
7
- import { API_PATH_REGEXES } from '../../../path-constants.mjs';
8
-
9
- /**
10
- * GET /api/health
11
- */
12
- export class HealthHandler extends ServeGibHandlerBase {
13
- protected override method: ServeGibHttpMethod = 'ALL';
14
- protected override regex = API_PATH_REGEXES.HEALTH;
15
-
16
- protected async handleRouteImpl(reqCtx: RequestContext): Promise<ResponseResult | undefined> {
17
- if (reqCtx.method === 'GET') {
18
- return this.ok({ status: 'ok', timestamp: new Date().toISOString() });
19
- } else {
20
- throw new Error(`info.method !== 'GET' in ${HealthHandler.name} (E: bfff3c547b5827ca7845277804057f26)`);
21
- }
22
- }
23
- }
@@ -1,51 +0,0 @@
1
- import { respecfully, iReckon, ifWe, ifWeMight } from '@ibgib/helper-gib/dist/respec-gib/respec-gib.mjs';
2
- import { ServeGib_V1 } from '../../serve-gib-v1.mjs';
3
- import { HealthHandler } from './health.handler.mjs';
4
- import { ErrorHandler } from '../error-handler.mjs';
5
-
6
- const sir = `[${import.meta.url}]`;
7
-
8
- await respecfully(sir, 'Health Handler Integration', async () => {
9
- const testDataDir = './test-data-health';
10
- const port = 3002;
11
-
12
- await ifWe(sir, 'get a 200 OK from /api/health', async () => {
13
- // 1. Setup ServeGib_V1
14
- const serveGib = new ServeGib_V1({
15
- port,
16
- dataDir: testDataDir,
17
- handlers: [new HealthHandler()],
18
- errorHandler: new ErrorHandler()
19
- });
20
-
21
- // 2. Mock GET Request
22
- const req: any = {
23
- url: '/api/health',
24
- method: 'GET',
25
- headers: {},
26
- on: (event: string, cb: any) => {
27
- if (event === 'end') { cb(); }
28
- }
29
- };
30
-
31
- let capturedStatus: number = 0;
32
- let capturedBody: any = null;
33
- const res: any = {
34
- writeHead: (status: number) => {
35
- capturedStatus = status;
36
- },
37
- end: (body: string) => {
38
- capturedBody = JSON.parse(body);
39
- },
40
- statusCode: 0
41
- };
42
-
43
- // 3. Handle
44
- await serveGib.handleRequest(req, res);
45
-
46
- // 4. Verify
47
- iReckon(sir, capturedStatus).asTo('captured status code').isGonnaBe(200);
48
- iReckon(sir, capturedBody.status).asTo('captured body status').isGonnaBe('ok');
49
- iReckon(sir, capturedBody.timestamp).asTo('captured body timestamp').isGonnaBe(capturedBody.timestamp);
50
- });
51
- });
@@ -1,49 +0,0 @@
1
- import { IbGibAddr } from "@ibgib/ts-gib/dist/types.mjs";
2
-
3
- import { DomainInfo } from "../../../types.mjs";
4
-
5
- export interface IbGibParams {
6
- domainInfo: DomainInfo;
7
- ibGibIb: string;
8
- ibGibGib: string;
9
- ibGibAddr: IbGibAddr;
10
- }
11
-
12
- // #region IbGibGetQueryParams
13
- export const DEFAULT_QUERY_PARAMS_GET_IBGIB = {
14
- /**
15
- * If true, will get the latest ibgib.
16
- */
17
- getLatest: false, // Default to false for regular ibgibs
18
- /**
19
- * If true, will get the ibgib's entire dependency graph
20
- */
21
- getGraph: false, // Default to false for regular ibgibs
22
- /**
23
- * If true, returns only the resolved address (addr) rather than the full
24
- * ibgib or graph body. Useful for a lightweight "tip check" before initiating
25
- * a full sync: client compares `latestAddr` with its locally known addr.
26
- *
27
- * ## notes
28
- *
29
- * Typically combined with `getLatest: true` to ask "what is the server's
30
- * current tip for this timeline?" without paying the cost of fetching the
31
- * full ibgib body or graph.
32
- *
33
- * When `getLatest: false` and `addrOnly: true`, returns the addr as-is
34
- * (i.e., confirms the given addr exists on the server).
35
- */
36
- addrOnly: false,
37
- };
38
- /**
39
- * @see {@link DEFAULT_QUERY_PARAMS_GET_IBGIB} key/values for jsdocs
40
- */
41
- export type IbGibGetQueryParams = Partial<typeof DEFAULT_QUERY_PARAMS_GET_IBGIB>;
42
- export type KNOWN_QUERY_PARAMS_IBGIB_GET = keyof IbGibGetQueryParams;
43
- export const KNOWN_QUERY_PARAMS_IBGIB_GET = Object.keys(DEFAULT_QUERY_PARAMS_GET_IBGIB) as KNOWN_QUERY_PARAMS_IBGIB_GET[];
44
- export function isKnownQueryParamsKey_IbGibGet(key: any): key is KNOWN_QUERY_PARAMS_IBGIB_GET {
45
- return !!key && typeof key === 'string' ?
46
- KNOWN_QUERY_PARAMS_IBGIB_GET.includes(key as any) :
47
- false;
48
- }
49
- // #endregion IbGibGetQueryParams
@@ -1,176 +0,0 @@
1
- /**
2
- * @module serve-gib/handlers/api/ibgib
3
- */
4
-
5
- import { extractErrorMsg } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';
6
- import { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs';
7
- import { IbGib_V1 } from '@ibgib/ts-gib/dist/V1/types.mjs';
8
-
9
- import { GLOBAL_LOG_A_LOT } from '../../../constants.mjs';
10
- import { ServeGibHandlerWithMetaspaceBase } from '../../handler-base.mjs';
11
- import { RequestContext, ResponseResult, ServeGibHttpMethod } from '../../../types.mjs';
12
- import { validateAddressSegment } from '../../../../path-helper.mjs';
13
- import { API_PATH_REGEXES } from '../../../../path-constants.mjs';
14
- import {
15
- DEFAULT_QUERY_PARAMS_GET_IBGIB, IbGibGetQueryParams, IbGibParams,
16
- isKnownQueryParamsKey_IbGibGet, KNOWN_QUERY_PARAMS_IBGIB_GET
17
- } from './ibgib-handler-types.mjs';
18
- import { validateAndCoerceBooleanQueryParam } from '../../../serve-gib-helpers.mjs';
19
-
20
- export interface IbGibGraphResponseBody {
21
- addr: string;
22
- count: number;
23
- graph: Record<string, IbGib_V1>;
24
- }
25
-
26
- const logalot = GLOBAL_LOG_A_LOT;
27
-
28
- /**
29
- * GET /api/ibgib/:domainAddr/:ibGibAddr
30
- */
31
- export class IbGibHandler extends ServeGibHandlerWithMetaspaceBase<IbGibParams, IbGibGetQueryParams> {
32
- protected override lc: string = `[${IbGibHandler.name}]`;
33
- protected override method: ServeGibHttpMethod = 'GET';
34
- protected override regex = API_PATH_REGEXES.IBGIB_ADDR;
35
-
36
- protected override async parseParamsImpl(reqCtx: RequestContext<IbGibParams, IbGibGetQueryParams>): Promise<IbGibParams | undefined> {
37
- const lc = `${this.lc}[${this.parseParamsImpl.name}]`;
38
- try {
39
- if (logalot) { console.log(`${lc} starting...`); }
40
- const match = reqCtx.pathname.match(this.regex);
41
- if (!match) { throw new Error(`(UNEXPECTED) match falsy for regex? at this point, we have passed canHandleRoute, so this should parse correctly. (E: 8ce0810a3a88f420639bf8286df1d826)`); }
42
- const domainIb = decodeURIComponent(match[1]);
43
- const domainGib = decodeURIComponent(match[2]);
44
- const domainAddr = getIbGibAddr({ ib: domainIb, gib: domainGib });
45
- const ibGibIb = decodeURIComponent(match[3]);
46
- const ibGibGib = decodeURIComponent(match[4]);
47
- const ibGibAddr = getIbGibAddr({ ib: ibGibIb, gib: ibGibGib });
48
- return {
49
- ibGibIb, ibGibGib, ibGibAddr,
50
- domainInfo: this.getDomainInfo({ domainAddr }),
51
- };
52
- } catch (error) {
53
- console.error(`${lc} ${extractErrorMsg(error)}`);
54
- throw error;
55
- } finally {
56
- if (logalot) { console.log(`${lc} complete.`); }
57
- }
58
- }
59
-
60
- protected override async validateQueryParams({ queryParams }: { queryParams: any; }): Promise<string[]> {
61
- const lc = `${this.lc}[${this.validateQueryParams.name}]`;
62
- try {
63
- if (logalot) { console.log(`${lc} starting...`); }
64
-
65
- const errors: string[] = [];
66
-
67
- // strict checking
68
- const queryParamsKeys = Object.keys(queryParams);
69
- const invalidKeys: string[] = queryParamsKeys.filter(x => !isKnownQueryParamsKey_IbGibGet(x));
70
- if (invalidKeys.length > 0) {
71
- throw new Error(`invalid query params keys: ${invalidKeys.join(', ')}. valid query params keys: ${KNOWN_QUERY_PARAMS_IBGIB_GET.join(', ')} (E: b7e8a9f2c1d34e56b89a01d4f2e7c326)`);
72
- }
73
-
74
- // Enforce that EVERY key must have a validation function mapping
75
- type ValidationFn = () => Promise<void>;
76
- const ValidationFns: Record<KNOWN_QUERY_PARAMS_IBGIB_GET, ValidationFn> = {
77
- getLatest: async () => validateAndCoerceBooleanQueryParam(queryParams, 'getLatest', errors),
78
- getGraph: async () => validateAndCoerceBooleanQueryParam(queryParams, 'getGraph', errors),
79
- addrOnly: async () => validateAndCoerceBooleanQueryParam(queryParams, 'addrOnly', errors),
80
- };
81
-
82
- // execute all validation functions
83
- for (const fn of Object.values(ValidationFns)) {
84
- await fn();
85
- }
86
-
87
- return errors;
88
-
89
- } catch (error) {
90
- console.error(`${lc} ${extractErrorMsg(error)}`);
91
- throw error;
92
- } finally {
93
- if (logalot) { console.log(`${lc} complete.`); }
94
- }
95
- }
96
-
97
- protected async handleRouteImpl(reqCtx: RequestContext<IbGibParams, IbGibGetQueryParams>): Promise<ResponseResult | undefined> {
98
- const lc = `${this.lc}[${this.handleRouteImpl.name}]`;
99
- try {
100
- if (logalot) { console.log(`${lc} starting... (I: 03d6a889b1f8af879c0f7158a3b3de26)`); }
101
-
102
- if (logalot) { console.log(`${lc} starting... (I: 03d6a889b1f8af879c0f7158a3b3de26)`); }
103
- if (!reqCtx.metaspace) { throw new Error(`(UNEXPECTED) metaspace falsy? we should have initialized it by now since this is a domain-dependent handler (E: 864661c668d2aa1918b7ee677a7d9c26)`); }
104
-
105
- const { ibGibIb, ibGibGib } = reqCtx.params as IbGibParams;
106
- if (!ibGibIb || !ibGibGib) { return undefined; }
107
-
108
- // Reconstruct addr from params
109
- const rawAddr = `${ibGibIb}^${ibGibGib}`;
110
- if (!validateAddressSegment(rawAddr)) return this.error(400, 'Invalid address format');
111
- const addr = rawAddr;
112
-
113
- const queryParams = {
114
- ...DEFAULT_QUERY_PARAMS_GET_IBGIB,
115
- ...(reqCtx.queryParams ?? {}),
116
- };
117
-
118
- const { getLatest, getGraph, addrOnly } = queryParams;
119
-
120
- const space = await reqCtx.metaspace.getLocalUserSpace({ lock: false });
121
- if (!space) { throw new Error(`(UNEXPECTED) couldn't get default local user space? (E: ec6161ea3a08892ad8bfd1b7b0d79826)`); }
122
-
123
- let addr_latest: string = addr;
124
- if (getLatest) {
125
- const latestAddr = await reqCtx.metaspace.getLatestAddr({ addr, space });
126
- if (latestAddr) { addr_latest = latestAddr; }
127
- }
128
-
129
- // Lightweight tip-check: return only the resolved address.
130
- // Client uses this to decide whether a full sync is necessary
131
- // without incurring the cost of fetching the full ibgib or graph.
132
- if (addrOnly && !getGraph) {
133
- return this.ok({ addr: addr_latest, clientAddr: addr });
134
- } /* <<<<< returns early */
135
-
136
- if (getGraph) {
137
- const resGraph = await reqCtx.metaspace.getDependencyGraph({
138
- ibGibAddr: addr_latest,
139
- space,
140
- live: getLatest,
141
- });
142
- const addrs = Object.keys(resGraph);
143
- if (addrs.length > 0) {
144
- if (addrOnly) {
145
- // Return only the address list for delta negotiation (smart diff):
146
- // client compares these against what it already has to determine
147
- // the minimal set it needs to fetch.
148
- return this.ok({ addr: addr_latest, clientAddr: addr, addrs });
149
- } else {
150
- const responseBody: IbGibGraphResponseBody = {
151
- addr: addr_latest,
152
- count: addrs.length,
153
- graph: resGraph
154
- };
155
- return this.ok(responseBody);
156
- }
157
- } else {
158
- return this.notFound(`Graph not found for ${addr_latest} (E: 89b259f13ae5e4f0d8287f6c0475a826)`);
159
- }
160
- } else {
161
- const resGet = await reqCtx.metaspace.get({ space, addr: addr_latest });
162
- if (resGet.success && resGet.ibGibs?.length === 1) {
163
- const ibGib = resGet.ibGibs[0];
164
- return this.ok(ibGib);
165
- } else {
166
- return this.notFound(`IbGib not found for ${addr_latest} (E: 017621e0a8086832ff06cfc884b8c426)`);
167
- }
168
- }
169
- } catch (error) {
170
- if (logalot) { console.error(extractErrorMsg(error)) }
171
- return this.error(500, extractErrorMsg(error));
172
- } finally {
173
- if (logalot) { console.log(`${lc} complete.`); }
174
- }
175
- }
176
- }
@@ -1,150 +0,0 @@
1
- /**
2
- * @module serve-gib/handlers/api/keystone/keystone-evolve.handler
3
- *
4
- * PUT /api/keystone/evolve/:domainAddr
5
- *
6
- * Receives an evolved domain keystone (`I^I1.Itjp`) and any related
7
- * ibgibs (e.g., the `S^Stjp` session keystone).
8
- *
9
- * Validates the evolution, verifies the `S` session keystone, and persists
10
- * them to the domain metaspace to authorize the sync session.
11
- */
12
-
13
- import { extractErrorMsg } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';
14
- import { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs';
15
- import { IbGib_V1 } from '@ibgib/ts-gib/dist/V1/types.mjs';
16
- import { validateAndRegisterEvolveKeystone } from '@ibgib/core-gib/dist/sync/sync-peer/sync-peer-websocket/sync-peer-websocket-receiver/sync-websocket-peer-helpers.mjs';
17
- import { KeystoneIbGib_V1 } from '@ibgib/core-gib/dist/keystone/keystone-types.mjs';
18
- import { loadSsoServerConfig } from '@ibgib/web-gib/dist/identity/sso/sso-config-helper.mjs';
19
- import { SsoCustodianService } from '@ibgib/web-gib/dist/identity/sso/sso-custodian-service.mjs';
20
-
21
- import { GLOBAL_LOG_A_LOT } from '../../../constants.mjs';
22
- import { ServeGibHandlerWithMetaspaceBase } from '../../handler-base.mjs';
23
- import { API_PATH_REGEXES } from '../../../../path-constants.mjs';
24
- import { ParamsWithDomain, RequestContext, ResponseResult } from '../../../types.mjs';
25
-
26
- const logalot = GLOBAL_LOG_A_LOT || true;
27
-
28
- interface EvolveParams extends ParamsWithDomain {
29
- domainAddr: string;
30
- }
31
-
32
- /**
33
- * Body payload for the Keystone Evolve REST API request.
34
- */
35
- interface EvolveBody {
36
- /** The main evolved keystone frame. */
37
- keystoneIbGib: KeystoneIbGib_V1;
38
- /**
39
- * Array of other keystone frames related to this evolution.
40
- * Ephemeral session keystones for sync, or persistent delegate keystones for manage.
41
- */
42
- relatedKeystoneIbGibs?: IbGib_V1[];
43
- /** Optional map of providerId to token to revoke during unlinking. */
44
- revokeTokens?: Record<string, string>;
45
- }
46
-
47
- export class KeystoneEvolveHandler extends ServeGibHandlerWithMetaspaceBase<EvolveParams, EvolveBody> {
48
- protected override lc: string = `[${KeystoneEvolveHandler.name}]`;
49
- protected override method: 'PUT' = 'PUT';
50
- protected override regex = API_PATH_REGEXES.KEYSTONE_EVOLVE;
51
-
52
- protected override async parseParamsImpl(reqCtx: RequestContext<EvolveParams, any>): Promise<EvolveParams | undefined> {
53
- const match = reqCtx.pathname.match(this.regex);
54
- if (match && match.length >= 3) {
55
- const domainIb = decodeURIComponent(match[1]);
56
- const domainGib = decodeURIComponent(match[2]);
57
- const domainAddr = getIbGibAddr({ ib: domainIb, gib: domainGib });
58
- return {
59
- domainAddr,
60
- domainInfo: this.getDomainInfo({ domainAddr })
61
- };
62
- } else {
63
- return undefined;
64
- }
65
- }
66
-
67
- protected override async validateQueryParams({ queryParams }: { queryParams: any; }): Promise<string[]> {
68
- return []; // We don't expect any query parameters for evolution
69
- }
70
-
71
- protected override async handleRouteImpl(reqCtx: RequestContext<EvolveParams>): Promise<ResponseResult> {
72
- const lc = `${this.lc}[handleRouteImpl]`;
73
- try {
74
- if (logalot) { console.log(`${lc} starting...`); }
75
-
76
- if (!reqCtx.params) { return this.error(400, 'Invalid parameters'); }
77
- if (!reqCtx.metaspace) { return this.error(500, 'Metaspace not initialized'); }
78
-
79
- const { domainAddr } = reqCtx.params;
80
- const bodyStr = reqCtx.body;
81
- if (!bodyStr) { return this.error(400, 'Empty body'); }
82
-
83
- let parsed: EvolveBody;
84
- try {
85
- parsed = JSON.parse(bodyStr);
86
- } catch (err) {
87
- return this.error(400, 'Invalid request JSON body: bodyStr does NOT parse. (E: 2f81c8c80a6884ff32b877671e92f326)');
88
- }
89
-
90
- const { keystoneIbGib, relatedKeystoneIbGibs = [] } = parsed;
91
- if (!keystoneIbGib) {
92
- return this.error(400, 'Invalid request. Body must contain keystoneIbGib (E: e234647f79282982c8012fe8015f5826)');
93
- }
94
-
95
- const space = await reqCtx.metaspace.getLocalUserSpace({ lock: false });
96
- if (!space) {
97
- return this.error(500, 'No local user space found (E: a1144e5d6cd9641fb82d6b359f131126)');
98
- }
99
-
100
- // Delegate all intrinsic checks, transition rules, pool restrictions, and registration/persistence to core-gib helper
101
- await validateAndRegisterEvolveKeystone({
102
- domainAddr,
103
- keystoneIbGib,
104
- relatedKeystoneIbGibs,
105
- metaspace: reqCtx.metaspace,
106
- space
107
- });
108
-
109
- // Post-Evolution Hook: Handle SSO provider unlinking
110
- const claim = keystoneIbGib.data?.proofs?.[0]?.claim;
111
- if (claim?.details?.type === 'remove-pool') {
112
- const removeInfo = claim.details.info;
113
- if (removeInfo && Array.isArray(removeInfo.remove)) {
114
- // Lazy-load custodian service config
115
- const config = loadSsoServerConfig();
116
- const custodian = new SsoCustodianService(config);
117
-
118
- for (const poolId of removeInfo.remove) {
119
- if (poolId.startsWith('custodian-manage-')) {
120
- const providerId = poolId.replace('custodian-manage-', '');
121
- console.log(`${lc} Evolved keystone removed custodian pool: ${poolId}. Performing unlink cleanup for provider: ${providerId}`);
122
-
123
- // Revoke token if supplied by the client
124
- const token = parsed.revokeTokens?.[providerId];
125
- if (token) {
126
- try {
127
- await custodian.revokeToken(providerId as any, token);
128
- } catch (e) {
129
- console.warn(`${lc} Failed to revoke token for provider ${providerId}: ${extractErrorMsg(e)}`);
130
- }
131
- } else {
132
- console.log(`${lc} No OAuth token supplied by client for revocation of provider: ${providerId}`);
133
- }
134
- }
135
- }
136
- }
137
- }
138
-
139
- return this.ok({
140
- message: `Successfully evolved domain keystone with session keystone`,
141
- });
142
-
143
- } catch (error) {
144
- console.error(`${lc} ${extractErrorMsg(error)}`);
145
- return this.error(422, `Evolve validation/persistence failed: ${extractErrorMsg(error)}`);
146
- } finally {
147
- if (logalot) { console.log(`${lc} complete.`); }
148
- }
149
- }
150
- }
@@ -1,146 +0,0 @@
1
- /**
2
- * @module serve-gib/handlers/api/keystone/keystone-genesis.handler
3
- *
4
- * POST /api/keystone/genesis
5
- *
6
- * Accepts a single genesis-frame keystone ibgib from the client and
7
- * bootstraps a new domain-isolated metaspace for it.
8
- *
9
- * ## request body
10
- *
11
- * ```json
12
- * { "keystoneIbGib": <KeystoneIbGib_V1> }
13
- * ```
14
- *
15
- * ## validation steps
16
- *
17
- * 1. Body contains `keystoneIbGib` (single ibgib, not an array).
18
- * 2. Intrinsic hash validation passes (`validateIbGibIntrinsically`).
19
- * 3. Structural keystone check: `ib` starts with `"keystone"`, no `past` in
20
- * `rel8ns` (genesis = TJP frame, no prior timeline).
21
- * 4. Domain uniqueness: the path derived from the keystone's tjpGib must not
22
- * already exist on disk — if it does, return 409 Conflict.
23
- * 5. Bootstrap: call `bootstrapDomainMetaspace` to create folders + metaspace.
24
- * 6. Persist the keystone ibgib into the newly created domain space.
25
- *
26
- * ## notes
27
- *
28
- * Unlike domain-scoped handlers, this handler does NOT rely on
29
- * `reqCtx.metaspace` (which is undefined when no domain exists yet). It
30
- * creates the metaspace itself using `bootstrapDomainMetaspace`.
31
- */
32
-
33
- import { existsSync } from 'node:fs';
34
-
35
- import { extractErrorMsg, pretty } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';
36
- import { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs';
37
- import { validateIbGibIntrinsically } from '@ibgib/ts-gib/dist/V1/validate-helper.mjs';
38
- import { getGibInfo } from '@ibgib/ts-gib/dist/V1/transforms/transform-helper.mjs';
39
- import { KeystoneService_V1 } from '@ibgib/core-gib/dist/keystone/keystone-service-v1.mjs';
40
-
41
- import { GLOBAL_LOG_A_LOT } from '../../../constants.mjs';
42
- import { ServeGibHandlerBase } from '../../handler-base.mjs';
43
- import { RequestContext, ResponseResult, ServeGibHttpMethod } from '../../../types.mjs';
44
- import { API_PATH_REGEXES } from '../../../../path-constants.mjs';
45
- import { getDomainRootPath } from '../../../../bootstrap-helper.mjs';
46
- import { bootstrapDomainMetaspace } from '../../../../bootstrap-helper.mjs';
47
-
48
- const logalot = GLOBAL_LOG_A_LOT || true;
49
-
50
-
51
-
52
-
53
- /**
54
- * POST /api/keystone/genesis
55
- *
56
- * No path params — the domain is derived from the incoming keystone ibgib.
57
- */
58
- export class KeystoneGenesisHandler extends ServeGibHandlerBase<undefined, undefined> {
59
- protected override lc: string = `[${KeystoneGenesisHandler.name}]`;
60
- protected override method: ServeGibHttpMethod = 'POST';
61
- protected override regex = API_PATH_REGEXES.KEYSTONE_GENESIS;
62
-
63
- protected async handleRouteImpl(
64
- reqCtx: RequestContext<undefined, undefined>
65
- ): Promise<ResponseResult | undefined> {
66
- const lc = `${this.lc}[${this.handleRouteImpl.name}]`;
67
- try {
68
- if (logalot) { console.log(`${lc} starting... (I: a1b2c3d4e5f6a7b8c9d0e1f2a3b4c526)`); }
69
-
70
- // ----------------------------------------------------------------
71
- // 1. Parse body — expect { keystoneIbGib }
72
- // ----------------------------------------------------------------
73
- let parsed: any;
74
- try {
75
- parsed = JSON.parse(reqCtx.body);
76
- } catch {
77
- return this.error(400, 'Request body must be valid JSON (E: dd8618857568f8fc5e9c62b8ed135826)');
78
- }
79
-
80
- const { keystoneIbGib } = parsed;
81
- if (!keystoneIbGib) {
82
- return this.error(400, 'Body must contain keystoneIbGib (E: 9c8c5d979d7842cd716ba64f69349c26)');
83
- }
84
-
85
- // ----------------------------------------------------------------
86
- // 2. Intrinsic hash validation
87
- // ----------------------------------------------------------------
88
- const intrinsicErrors = await validateIbGibIntrinsically({ ibGib: keystoneIbGib });
89
- if (intrinsicErrors) {
90
- return this.error(422, 'Intrinsic keystone validation failed (E: 76d388e198f23a87dd6596f59c36e826)', { errors: intrinsicErrors });
91
- }
92
-
93
- // ----------------------------------------------------------------
94
- // 3. Structural keystone + genesis-frame checks
95
- // ----------------------------------------------------------------
96
- const keystoneService = new KeystoneService_V1();
97
- const keystoneErrors = await keystoneService.validateGenesisKeystone({
98
- keystoneIbGib
99
- });
100
- if (keystoneErrors && keystoneErrors.length > 0) {
101
- return this.error(422, `Keystone genesis validation failed. Errors: ${keystoneErrors} (E: 8384285be7a8ab0d41cfd1df2e2aa826)`, { errors: keystoneErrors });
102
- }
103
-
104
- // ----------------------------------------------------------------
105
- // 4. Domain uniqueness check — 409 if the domain already exists
106
- // ----------------------------------------------------------------
107
- const addr = getIbGibAddr({ ibGib: keystoneIbGib });
108
- const { tjpGib, punctiliarHash } = getGibInfo({ ibGibAddr: addr });
109
- const domainGib = tjpGib || punctiliarHash;
110
- if (!domainGib) {
111
- return this.error(422, `Could not extract domain identifier from keystone address: ${addr} (E: 2758588a6d7cc77f078e97989feed326)`);
112
- }
113
-
114
- const domainRootPath = getDomainRootPath(domainGib, reqCtx.dataDir);
115
- if (existsSync(domainRootPath)) {
116
- return this.error(409, `Domain already exists for this keystone (tjpGib: ${domainGib}). Use PUT /api/keystone/evolve/:domainAddr to evolve. (E: 1c56c8885781c86df89cbdfc1b310626)`);
117
- }
118
-
119
- // ----------------------------------------------------------------
120
- // 5. Bootstrap the new domain metaspace (creates folders)
121
- // ----------------------------------------------------------------
122
- const metaspace = await bootstrapDomainMetaspace(addr, reqCtx.dataDir);
123
-
124
- // ----------------------------------------------------------------
125
- // 6. Persist the genesis keystone into the new domain space
126
- // ----------------------------------------------------------------
127
- const space = await metaspace.getLocalUserSpace({ lock: false });
128
- if (!space) {
129
- throw new Error(`(UNEXPECTED) Could not get local user space after bootstrapping domain for ${addr} (E: b1c2d3e4f5a6b7c8d9e0f1a2b3c4d526)`);
130
- }
131
-
132
- await metaspace.put({ ibGibs: [keystoneIbGib], space });
133
- await metaspace.registerNewIbGib({ ibGib: keystoneIbGib, space });
134
-
135
- console.log(`${lc} domain created and keystone persisted: ${addr}`);
136
- // if (logalot) { console.log(`${lc} keystoneIbGib: ${pretty(keystoneIbGib)} (I: d598c6ff7a48997d585b84c19c464826)`); }
137
- return this.ok({ success: true, addr }, 201);
138
- } catch (error) {
139
- const emsg = extractErrorMsg(error);
140
- console.error(`${lc} ${emsg}`);
141
- return this.error(500, emsg);
142
- } finally {
143
- if (logalot) { console.log(`${lc} complete.`); }
144
- }
145
- }
146
- }