@ibgib/space-gib 0.0.8 → 0.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) 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-GCWH3SH4.mjs +21 -0
  6. package/dist/client/chunk-GCWH3SH4.mjs.map +7 -0
  7. package/dist/client/chunk-I7KNBFG3.mjs +2329 -0
  8. package/dist/client/chunk-I7KNBFG3.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 +18815 -17778
  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 -195
  19. package/src/client/dev-tools/common.mts +4 -4
  20. package/src/client/ui/shell/space-gib-shell-service.mts +68 -18
  21. package/src/common/keystone-policies.mts +1 -1
  22. package/src/server/README.md +3 -2
  23. package/src/server/server.mts +13 -32
  24. package/src/server/test.json +0 -0
  25. package/dist/client/chunk-DBHMHCGD.mjs +0 -2341
  26. package/dist/client/chunk-DBHMHCGD.mjs.map +0 -7
  27. package/dist/client/chunk-SUQ5QJH4.mjs +0 -42
  28. package/dist/client/chunk-SUQ5QJH4.mjs.map +0 -7
  29. package/space-gib.localhost-1783713259760.log +0 -45
  30. package/src/client/components/identity-header/IMPLEMENTATION.md +0 -45
  31. package/src/client/components/identity-header/identity-header.css +0 -112
  32. package/src/client/components/identity-header/identity-header.html +0 -11
  33. package/src/client/components/identity-header/identity-header.mts +0 -439
  34. package/src/client/components/identity-manager/IMPLEMENTATION.md +0 -100
  35. package/src/client/components/identity-manager/identity-manager.css +0 -171
  36. package/src/client/components/identity-manager/identity-manager.html +0 -19
  37. package/src/client/components/identity-manager/identity-manager.mts +0 -639
  38. package/src/client/components/keystone-creator/keystone-creator.css +0 -65
  39. package/src/client/components/keystone-creator/keystone-creator.html +0 -41
  40. package/src/client/components/keystone-creator/keystone-creator.mts +0 -443
  41. package/src/client/components/keystone-details/keystone-details.css +0 -569
  42. package/src/client/components/keystone-details/keystone-details.html +0 -127
  43. package/src/client/components/keystone-details/keystone-details.mts +0 -1013
  44. package/src/client/components/keystone-scrubber/SCRUBBER_IMPLEMENTATION.md +0 -33
  45. package/src/client/components/keystone-scrubber/keystone-scrubber.css +0 -46
  46. package/src/client/components/keystone-scrubber/keystone-scrubber.html +0 -15
  47. package/src/client/components/keystone-scrubber/keystone-scrubber.mts +0 -356
  48. package/src/server/bootstrap-helper.mts +0 -141
  49. package/src/server/bootstrap-helper.respec.mts +0 -100
  50. package/src/server/metaspace-nodeindexedspace/metaspace-nodeindexedspace.mts +0 -85
  51. package/src/server/path-constants.mts +0 -101
  52. package/src/server/path-helper.mts +0 -101
  53. package/src/server/path-helper.respec.mts +0 -99
  54. package/src/server/serve-gib/CHANGELOG.md +0 -29
  55. package/src/server/serve-gib/README.md +0 -43
  56. package/src/server/serve-gib/constants.mts +0 -1
  57. package/src/server/serve-gib/handlers/api/debug/ws-echo.handler.mts +0 -105
  58. package/src/server/serve-gib/handlers/api/health.handler.mts +0 -23
  59. package/src/server/serve-gib/handlers/api/health.respec.mts +0 -51
  60. package/src/server/serve-gib/handlers/api/ibgib/ibgib-handler-types.mts +0 -49
  61. package/src/server/serve-gib/handlers/api/ibgib/ibgib.handler.mts +0 -176
  62. package/src/server/serve-gib/handlers/api/keystone/keystone-evolve.handler.mts +0 -141
  63. package/src/server/serve-gib/handlers/api/keystone/keystone-genesis.handler.mts +0 -146
  64. package/src/server/serve-gib/handlers/api/keystone/keystone-get.handler.mts +0 -198
  65. package/src/server/serve-gib/handlers/api/keystone/keystone-get.respec.mts +0 -107
  66. package/src/server/serve-gib/handlers/api/keystone/keystone-handler-types.mts +0 -29
  67. package/src/server/serve-gib/handlers/api/keystone/keystone-post.handler.mts +0 -55
  68. package/src/server/serve-gib/handlers/api/keystone/keystone-post.respec.mts +0 -130
  69. package/src/server/serve-gib/handlers/api/keystone/sso-config.handler.mts +0 -66
  70. package/src/server/serve-gib/handlers/api/keystone/sso-link.handler.mts +0 -140
  71. package/src/server/serve-gib/handlers/api/keystone/sso-login.handler.mts +0 -190
  72. package/src/server/serve-gib/handlers/error-handler.mts +0 -36
  73. package/src/server/serve-gib/handlers/handler-base.mts +0 -383
  74. package/src/server/serve-gib/handlers/static-handler.mts +0 -82
  75. package/src/server/serve-gib/handlers/ws/sync-upgrade-handler-base.mts +0 -233
  76. package/src/server/serve-gib/handlers/ws/sync-upgrade.handler.mts +0 -24
  77. package/src/server/serve-gib/handlers/ws/ws-helper.mts +0 -216
  78. package/src/server/serve-gib/handlers/ws/ws-types.mts +0 -53
  79. package/src/server/serve-gib/serve-gib-helpers.mts +0 -32
  80. package/src/server/serve-gib/serve-gib-v1.mts +0 -172
  81. package/src/server/serve-gib/serve-gib.respec.mts +0 -90
  82. package/src/server/serve-gib/types.mts +0 -102
  83. 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,141 +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
- interface EvolveBody {
33
- keystoneIbGib: KeystoneIbGib_V1;
34
- relatedIbGibs?: IbGib_V1[];
35
- revokeTokens?: Record<string, string>;
36
- }
37
-
38
- export class KeystoneEvolveHandler extends ServeGibHandlerWithMetaspaceBase<EvolveParams, EvolveBody> {
39
- protected override lc: string = `[${KeystoneEvolveHandler.name}]`;
40
- protected override method: 'PUT' = 'PUT';
41
- protected override regex = API_PATH_REGEXES.KEYSTONE_EVOLVE;
42
-
43
- protected override async parseParamsImpl(reqCtx: RequestContext<EvolveParams, any>): Promise<EvolveParams | undefined> {
44
- const match = reqCtx.pathname.match(this.regex);
45
- if (match && match.length >= 3) {
46
- const domainIb = decodeURIComponent(match[1]);
47
- const domainGib = decodeURIComponent(match[2]);
48
- const domainAddr = getIbGibAddr({ ib: domainIb, gib: domainGib });
49
- return {
50
- domainAddr,
51
- domainInfo: this.getDomainInfo({ domainAddr })
52
- };
53
- } else {
54
- return undefined;
55
- }
56
- }
57
-
58
- protected override async validateQueryParams({ queryParams }: { queryParams: any; }): Promise<string[]> {
59
- return []; // We don't expect any query parameters for evolution
60
- }
61
-
62
- protected override async handleRouteImpl(reqCtx: RequestContext<EvolveParams>): Promise<ResponseResult> {
63
- const lc = `${this.lc}[handleRouteImpl]`;
64
- try {
65
- if (logalot) { console.log(`${lc} starting...`); }
66
-
67
- if (!reqCtx.params) { return this.error(400, 'Invalid parameters'); }
68
- if (!reqCtx.metaspace) { return this.error(500, 'Metaspace not initialized'); }
69
-
70
- const { domainAddr } = reqCtx.params;
71
- const bodyStr = reqCtx.body;
72
- if (!bodyStr) { return this.error(400, 'Empty body'); }
73
-
74
- let parsed: EvolveBody;
75
- try {
76
- parsed = JSON.parse(bodyStr);
77
- } catch (err) {
78
- return this.error(400, 'Invalid request JSON body: bodyStr does NOT parse. (E: 2f81c8c80a6884ff32b877671e92f326)');
79
- }
80
-
81
- const { keystoneIbGib, relatedIbGibs = [] } = parsed;
82
- if (!keystoneIbGib) {
83
- return this.error(400, 'Invalid request. Body must contain keystoneIbGib (E: e234647f79282982c8012fe8015f5826)');
84
- }
85
-
86
- const space = await reqCtx.metaspace.getLocalUserSpace({ lock: false });
87
- if (!space) {
88
- return this.error(500, 'No local user space found (E: a1144e5d6cd9641fb82d6b359f131126)');
89
- }
90
-
91
- // Delegate all intrinsic checks, transition rules, pool restrictions, and registration/persistence to core-gib helper
92
- await validateAndRegisterEvolveKeystone({
93
- domainAddr,
94
- keystoneIbGib,
95
- relatedIbGibs,
96
- metaspace: reqCtx.metaspace,
97
- space
98
- });
99
-
100
- // Post-Evolution Hook: Handle SSO provider unlinking
101
- const claim = keystoneIbGib.data?.proofs?.[0]?.claim;
102
- if (claim?.details?.type === 'remove-pool') {
103
- const removeInfo = claim.details.info;
104
- if (removeInfo && Array.isArray(removeInfo.remove)) {
105
- // Lazy-load custodian service config
106
- const config = loadSsoServerConfig();
107
- const custodian = new SsoCustodianService(config);
108
-
109
- for (const poolId of removeInfo.remove) {
110
- if (poolId.startsWith('custodian-manage-')) {
111
- const providerId = poolId.replace('custodian-manage-', '');
112
- console.log(`${lc} Evolved keystone removed custodian pool: ${poolId}. Performing unlink cleanup for provider: ${providerId}`);
113
-
114
- // Revoke token if supplied by the client
115
- const token = parsed.revokeTokens?.[providerId];
116
- if (token) {
117
- try {
118
- await custodian.revokeToken(providerId as any, token);
119
- } catch (e) {
120
- console.warn(`${lc} Failed to revoke token for provider ${providerId}: ${extractErrorMsg(e)}`);
121
- }
122
- } else {
123
- console.log(`${lc} No OAuth token supplied by client for revocation of provider: ${providerId}`);
124
- }
125
- }
126
- }
127
- }
128
- }
129
-
130
- return this.ok({
131
- message: `Successfully evolved domain keystone with session keystone`,
132
- });
133
-
134
- } catch (error) {
135
- console.error(`${lc} ${extractErrorMsg(error)}`);
136
- return this.error(422, `Evolve validation/persistence failed: ${extractErrorMsg(error)}`);
137
- } finally {
138
- if (logalot) { console.log(`${lc} complete.`); }
139
- }
140
- }
141
- }
@@ -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
- }