@ibgib/space-gib 0.0.6 → 0.0.8

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 (38) hide show
  1. package/README.md +20 -0
  2. package/dist/client/bootstrap.mjs +31 -31
  3. package/dist/client/bootstrap.mjs.map +3 -3
  4. package/dist/client/chunk-DBHMHCGD.mjs +2341 -0
  5. package/dist/client/{chunk-SMOZ2D5E.mjs.map → chunk-DBHMHCGD.mjs.map} +4 -4
  6. package/dist/client/chunk-SUQ5QJH4.mjs +42 -0
  7. package/dist/client/chunk-SUQ5QJH4.mjs.map +7 -0
  8. package/dist/client/index.mjs +1 -1
  9. package/dist/client/script.mjs +1 -1
  10. package/dist/server/server.mjs +1561 -179
  11. package/dist/server/server.mjs.map +4 -4
  12. package/package.json +5 -5
  13. package/space-gib.localhost-1783713259760.log +45 -0
  14. package/src/client/AUTO-GENERATED-version.mts +1 -1
  15. package/src/client/api/space-gib-api-bridge.mts +7 -2
  16. package/src/client/bootstrap.mts +9 -0
  17. package/src/client/components/identity-header/identity-header.mts +43 -26
  18. package/src/client/components/identity-manager/identity-manager.css +57 -392
  19. package/src/client/components/identity-manager/identity-manager.html +0 -114
  20. package/src/client/components/identity-manager/identity-manager.mts +356 -543
  21. package/src/client/components/keystone-creator/keystone-creator.mts +4 -3
  22. package/src/client/components/keystone-details/keystone-details.css +569 -0
  23. package/src/client/components/keystone-details/keystone-details.html +127 -0
  24. package/src/client/components/keystone-details/keystone-details.mts +1013 -0
  25. package/src/client/components/keystone-scrubber/SCRUBBER_IMPLEMENTATION.md +33 -0
  26. package/src/client/components/keystone-scrubber/keystone-scrubber.css +46 -0
  27. package/src/client/components/keystone-scrubber/keystone-scrubber.html +15 -0
  28. package/src/client/components/keystone-scrubber/keystone-scrubber.mts +356 -0
  29. package/src/client/ui/shell/space-gib-shell-service.mts +4 -0
  30. package/src/server/path-constants.mts +12 -0
  31. package/src/server/serve-gib/handlers/api/keystone/keystone-evolve.handler.mts +33 -0
  32. package/src/server/serve-gib/handlers/api/keystone/sso-config.handler.mts +66 -0
  33. package/src/server/serve-gib/handlers/api/keystone/sso-link.handler.mts +140 -0
  34. package/src/server/serve-gib/handlers/api/keystone/sso-login.handler.mts +190 -0
  35. package/src/server/server.mts +6 -0
  36. package/dist/client/chunk-734MMI4C.mjs +0 -42
  37. package/dist/client/chunk-734MMI4C.mjs.map +0 -7
  38. package/dist/client/chunk-SMOZ2D5E.mjs +0 -2049
@@ -0,0 +1,140 @@
1
+ import { extractErrorMsg } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';
2
+ import { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs';
3
+ import { loadSsoServerConfig } from '@ibgib/web-gib/dist/identity/sso/sso-config-helper.mjs';
4
+ import { SsoCustodianService } from '@ibgib/web-gib/dist/identity/sso/sso-custodian-service.mjs';
5
+ import { SsoProviderId } from '@ibgib/web-gib/dist/identity/sso/sso-types.mjs';
6
+ import { isSsoProviderLinked } from '@ibgib/web-gib/dist/identity/sso/sso-helpers.mjs';
7
+ import { KeystoneService_V1 } from '@ibgib/core-gib/dist/keystone/keystone-service-v1.mjs';
8
+
9
+ import { GLOBAL_LOG_A_LOT } from '../../../constants.mjs';
10
+ import { ServeGibHandlerWithMetaspaceBase } from '../../handler-base.mjs';
11
+ import { API_PATH_REGEXES } from '../../../../path-constants.mjs';
12
+ import { ParamsWithDomain, RequestContext, ResponseResult, ServeGibHttpMethod } from '../../../types.mjs';
13
+
14
+ const logalot = GLOBAL_LOG_A_LOT || true;
15
+
16
+ let custodian: SsoCustodianService | undefined;
17
+ function getCustodian(): SsoCustodianService {
18
+ if (!custodian) {
19
+ const config = loadSsoServerConfig();
20
+ custodian = new SsoCustodianService(config);
21
+ }
22
+ return custodian;
23
+ }
24
+
25
+ interface LinkParams extends ParamsWithDomain {
26
+ parentTjpAddr: string;
27
+ }
28
+
29
+ interface LinkBody {
30
+ code: string;
31
+ providerId: SsoProviderId;
32
+ parentTjpAddr: string;
33
+ userNonce: string;
34
+ redirectUri: string;
35
+ }
36
+
37
+ /**
38
+ * POST /api/identity/sso/link
39
+ *
40
+ * Links an identity provider (Google, GitHub) to the user's sovereign parent identity.
41
+ * Generates the deterministic server-delegate keystone and registers it in the domain metaspace.
42
+ */
43
+ export class SsoLinkHandler extends ServeGibHandlerWithMetaspaceBase<LinkParams, any> {
44
+ protected override lc: string = `[${SsoLinkHandler.name}]`;
45
+ protected override method: ServeGibHttpMethod = 'POST';
46
+ protected override regex = API_PATH_REGEXES.IDENTITY_SSO_LINK;
47
+
48
+ protected override async parseParamsImpl(reqCtx: RequestContext<LinkParams, any>): Promise<LinkParams | undefined> {
49
+ let parsed: any;
50
+ try {
51
+ parsed = JSON.parse(reqCtx.body);
52
+ } catch {
53
+ return undefined;
54
+ }
55
+ const parentTjpAddr = parsed?.parentTjpAddr;
56
+ if (!parentTjpAddr) { return undefined; }
57
+ return {
58
+ parentTjpAddr,
59
+ domainInfo: this.getDomainInfo({ domainAddr: parentTjpAddr })
60
+ };
61
+ }
62
+
63
+ protected override async validateQueryParams({ queryParams }: { queryParams: any }): Promise<string[]> {
64
+ return [];
65
+ }
66
+
67
+ protected async handleRouteImpl(reqCtx: RequestContext<LinkParams>): Promise<ResponseResult | undefined> {
68
+ const lc = `${this.lc}[${this.handleRouteImpl.name}]`;
69
+ try {
70
+ if (logalot) { console.log(`${lc} starting...`); }
71
+
72
+ if (!reqCtx.params) {
73
+ return this.error(400, 'Invalid parameters: parentTjpAddr missing');
74
+ }
75
+ if (!reqCtx.metaspace) {
76
+ return this.error(500, 'Metaspace not initialized');
77
+ }
78
+
79
+ let parsed: LinkBody;
80
+ try {
81
+ parsed = JSON.parse(reqCtx.body);
82
+ } catch {
83
+ return this.error(400, 'Request body must be valid JSON');
84
+ }
85
+
86
+ const { code, providerId, parentTjpAddr, userNonce, redirectUri } = parsed;
87
+ if (!code || !providerId || !parentTjpAddr || !userNonce || !redirectUri) {
88
+ return this.error(400, 'Body missing required parameters (code, providerId, parentTjpAddr, userNonce, redirectUri)');
89
+ }
90
+
91
+ const space = await reqCtx.metaspace.getLocalUserSpace({ lock: false });
92
+ if (!space) {
93
+ return this.error(500, 'No local user space found in domain metaspace');
94
+ }
95
+
96
+ // 0. Fetch target keystone and verify if already linked
97
+ const keystoneService = new KeystoneService_V1();
98
+ const targetKeystone = await keystoneService.getLatestKeystone({
99
+ addr: parentTjpAddr,
100
+ metaspace: reqCtx.metaspace,
101
+ space
102
+ });
103
+ if (!targetKeystone) {
104
+ return this.error(400, `Keystone not found for address: ${parentTjpAddr}`);
105
+ }
106
+
107
+ if (isSsoProviderLinked({ keystone: targetKeystone, providerId })) {
108
+ return this.error(400, `SSO provider "${providerId}" is already linked to this keystone.`);
109
+ }
110
+
111
+ // 1. Authenticate with provider and retrieve user info
112
+ const service = getCustodian();
113
+ const userInfo = await service.getOAuthUserInfo(providerId, code, redirectUri);
114
+
115
+ // 2. Generate the custodian foreign challenge pool
116
+ const custodianPool = await service.createCustodianChallengePool({
117
+ providerId,
118
+ providerKey: userInfo.providerKey,
119
+ userNonce,
120
+ keystoneAddr: parentTjpAddr,
121
+ metaspace: reqCtx.metaspace,
122
+ space
123
+ });
124
+
125
+ console.log(`${lc} created custodian pool for: ${userInfo.providerKey}`);
126
+
127
+ return this.ok({
128
+ success: true,
129
+ custodianPool
130
+ }, 200);
131
+
132
+ } catch (error) {
133
+ const emsg = extractErrorMsg(error);
134
+ console.error(`${lc} Link failed: ${emsg}`);
135
+ return this.error(500, `Link failed: ${emsg}`);
136
+ } finally {
137
+ if (logalot) { console.log(`${lc} complete.`); }
138
+ }
139
+ }
140
+ }
@@ -0,0 +1,190 @@
1
+ import { createHmac } from 'node:crypto';
2
+ import { extractErrorMsg } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';
3
+ import { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs';
4
+ import { loadSsoServerConfig } from '@ibgib/web-gib/dist/identity/sso/sso-config-helper.mjs';
5
+ import { SsoCustodianService } from '@ibgib/web-gib/dist/identity/sso/sso-custodian-service.mjs';
6
+ import { SsoProviderId } from '@ibgib/web-gib/dist/identity/sso/sso-types.mjs';
7
+ import { POOL_ID_CUSTODIAN_MANAGE, KEYSTONE_VERB_MANAGE } from '@ibgib/core-gib/dist/keystone/keystone-constants.mjs';
8
+ import { KeystoneStrategyFactory } from '@ibgib/core-gib/dist/keystone/strategy/keystone-strategy-factory.mjs';
9
+
10
+ import { GLOBAL_LOG_A_LOT } from '../../../constants.mjs';
11
+ import { ServeGibHandlerWithMetaspaceBase } from '../../handler-base.mjs';
12
+ import { API_PATH_REGEXES } from '../../../../path-constants.mjs';
13
+ import { ParamsWithDomain, RequestContext, ResponseResult, ServeGibHttpMethod } from '../../../types.mjs';
14
+
15
+ const logalot = GLOBAL_LOG_A_LOT || true;
16
+
17
+ let custodian: SsoCustodianService | undefined;
18
+ function getCustodian(): SsoCustodianService {
19
+ if (!custodian) {
20
+ const config = loadSsoServerConfig();
21
+ custodian = new SsoCustodianService(config);
22
+ }
23
+ return custodian;
24
+ }
25
+
26
+ function signSessionToken(payload: any, secret: string): string {
27
+ const header = { alg: 'HS256', typ: 'JWT' };
28
+ const headerB64 = Buffer.from(JSON.stringify(header)).toString('base64url');
29
+ const payloadB64 = Buffer.from(JSON.stringify(payload)).toString('base64url');
30
+ const data = `${headerB64}.${payloadB64}`;
31
+ const signature = createHmac('sha256', secret).update(data).digest('base64url');
32
+ return `${data}.${signature}`;
33
+ }
34
+
35
+ interface LoginParams extends ParamsWithDomain {
36
+ parentTjpAddr: string;
37
+ }
38
+
39
+ interface LoginBody {
40
+ code: string;
41
+ providerId: SsoProviderId;
42
+ parentTjpAddr: string;
43
+ userNonce: string;
44
+ redirectUri: string;
45
+ }
46
+
47
+ /**
48
+ * POST /api/identity/sso/login
49
+ *
50
+ * Exposes login endpoint for SSO authentication. Verifies provider identity, asserts
51
+ * that the deterministic server-delegate keystone is registered in the parent keystone,
52
+ * and yields a secure HttpOnly session token.
53
+ */
54
+ export class SsoLoginHandler extends ServeGibHandlerWithMetaspaceBase<LoginParams, any> {
55
+ protected override lc: string = `[${SsoLoginHandler.name}]`;
56
+ protected override method: ServeGibHttpMethod = 'POST';
57
+ protected override regex = API_PATH_REGEXES.IDENTITY_SSO_LOGIN;
58
+
59
+ protected override async parseParamsImpl(reqCtx: RequestContext<LoginParams, any>): Promise<LoginParams | undefined> {
60
+ let parsed: any;
61
+ try {
62
+ parsed = JSON.parse(reqCtx.body);
63
+ } catch {
64
+ return undefined;
65
+ }
66
+ const parentTjpAddr = parsed?.parentTjpAddr;
67
+ if (!parentTjpAddr) { return undefined; }
68
+ return {
69
+ parentTjpAddr,
70
+ domainInfo: this.getDomainInfo({ domainAddr: parentTjpAddr })
71
+ };
72
+ }
73
+
74
+ protected override async validateQueryParams({ queryParams }: { queryParams: any }): Promise<string[]> {
75
+ return [];
76
+ }
77
+
78
+ protected async handleRouteImpl(reqCtx: RequestContext<LoginParams>): Promise<ResponseResult | undefined> {
79
+ const lc = `${this.lc}[${this.handleRouteImpl.name}]`;
80
+ try {
81
+ if (logalot) { console.log(`${lc} starting...`); }
82
+
83
+ if (!reqCtx.params) {
84
+ return this.error(400, 'Invalid parameters: parentTjpAddr missing');
85
+ }
86
+ if (!reqCtx.metaspace) {
87
+ return this.error(500, 'Metaspace not initialized');
88
+ }
89
+
90
+ let parsed: LoginBody;
91
+ try {
92
+ parsed = JSON.parse(reqCtx.body);
93
+ } catch {
94
+ return this.error(400, 'Request body must be valid JSON');
95
+ }
96
+
97
+ const { code, providerId, parentTjpAddr, userNonce, redirectUri } = parsed;
98
+ if (!code || !providerId || !parentTjpAddr || !userNonce || !redirectUri) {
99
+ return this.error(400, 'Body missing required parameters (code, providerId, parentTjpAddr, userNonce, redirectUri)');
100
+ }
101
+
102
+ const space = await reqCtx.metaspace.getLocalUserSpace({ lock: false });
103
+ if (!space) {
104
+ return this.error(500, 'No local user space found in domain metaspace');
105
+ }
106
+
107
+ // 1. Authenticate with provider and retrieve user info
108
+ const service = getCustodian();
109
+ const userInfo = await service.getOAuthUserInfo(providerId, code, redirectUri);
110
+
111
+ // 2. Derive custodian secret using providerKey and userNonce
112
+ const custodianSecret = await service.deriveServerDelegateSecret(userInfo.providerKey, userNonce);
113
+
114
+ // 3. Fetch latest parent keystone from metaspace
115
+ const latestParentAddr = await reqCtx.metaspace.getLatestAddr({ addr: parentTjpAddr, space });
116
+ if (!latestParentAddr) {
117
+ return this.error(404, `Parent identity keystone not found for address: ${parentTjpAddr}`);
118
+ }
119
+
120
+ const resGet = await reqCtx.metaspace.get({ addr: latestParentAddr, space });
121
+ const parentKeystone = resGet.ibGibs?.[0];
122
+ if (!parentKeystone) {
123
+ return this.error(404, `Parent identity keystone not found in space for address: ${latestParentAddr}`);
124
+ }
125
+
126
+ // 4. Resolve the custodian pool from the parent keystone using dynamic poolId
127
+ const targetPoolId = `custodian-manage-${providerId}`;
128
+ const custodianPool = parentKeystone.data?.challengePools?.find((p: any) => p.id === targetPoolId);
129
+ if (!custodianPool) {
130
+ return this.error(401, `Unauthorized: Custodian pool '${targetPoolId}' is not registered in the parent identity keystone.`);
131
+ }
132
+
133
+ // 5. Assert allowed verbs contain KEYSTONE_VERB_MANAGE
134
+ const allowedVerbs = custodianPool.config.allowedVerbs || [];
135
+ if (!allowedVerbs.includes(KEYSTONE_VERB_MANAGE)) {
136
+ return this.error(401, `Unauthorized: Custodian pool does not have the required manage permission.`);
137
+ }
138
+
139
+ // 6. Cryptographically verify the custodian secret against the pool's challenges
140
+ const strategy = KeystoneStrategyFactory.create({ config: custodianPool.config });
141
+ const poolSecret = await strategy.derivePoolSecret({ masterSecret: custodianSecret });
142
+
143
+ for (const [id, challenge] of Object.entries(custodianPool.challenges)) {
144
+ const solution = await strategy.generateSolution({
145
+ poolSecret,
146
+ poolId: custodianPool.id,
147
+ challengeId: id
148
+ });
149
+ const hashValue = await strategy.generateChallenge({ solution });
150
+ if (hashValue.hash !== (challenge as any).hash) {
151
+ return this.error(401, 'Unauthorized: Cryptographic verification of custodian pool challenges failed.');
152
+ }
153
+ }
154
+
155
+ // 7. Issue secure HttpOnly session cookie
156
+ const sessionPayload = {
157
+ parentTjpAddr,
158
+ providerKey: userInfo.providerKey,
159
+ exp: Math.floor(Date.now() / 1000) + 24 * 3600 // 24-hour expiration
160
+ };
161
+
162
+ const config = loadSsoServerConfig();
163
+ const sessionToken = signSessionToken(sessionPayload, config.sessionSecret);
164
+
165
+ const headers = {
166
+ 'Set-Cookie': `space_gib_session=${sessionToken}; Path=/; HttpOnly; SameSite=Strict; Max-Age=86400`
167
+ };
168
+
169
+ console.log(`${lc} login successful for parent: ${parentTjpAddr}, custodian providerKey: ${userInfo.providerKey}`);
170
+
171
+ return {
172
+ status: 200,
173
+ headers,
174
+ body: {
175
+ success: true,
176
+ parentTjpAddr,
177
+ custodianPoolId: custodianPool.id
178
+ },
179
+ isJson: true
180
+ };
181
+
182
+ } catch (error) {
183
+ const emsg = extractErrorMsg(error);
184
+ console.error(`${lc} Login failed: ${emsg}`);
185
+ return this.error(500, `Login failed: ${emsg}`);
186
+ } finally {
187
+ if (logalot) { console.log(`${lc} complete.`); }
188
+ }
189
+ }
190
+ }
@@ -21,6 +21,9 @@ import { StaticFileHandler } from './serve-gib/handlers/static-handler.mjs';
21
21
  import { ErrorHandler } from './serve-gib/handlers/error-handler.mjs';
22
22
  import { canHandleWsUpgrade, handleWsEchoUpgrade } from './serve-gib/handlers/api/debug/ws-echo.handler.mjs';
23
23
  import { SyncUpgradeHandler } from './serve-gib/handlers/ws/sync-upgrade.handler.mjs';
24
+ import { SsoLinkHandler } from './serve-gib/handlers/api/keystone/sso-link.handler.mjs';
25
+ import { SsoLoginHandler } from './serve-gib/handlers/api/keystone/sso-login.handler.mjs';
26
+ import { SsoConfigHandler } from './serve-gib/handlers/api/keystone/sso-config.handler.mjs';
24
27
 
25
28
  const __dirname = dirname(fileURLToPath(import.meta.url));
26
29
 
@@ -56,6 +59,9 @@ async function main(): Promise<void> {
56
59
  new KeystoneEvolveHandler(),
57
60
  new KeystonePostHandler(),
58
61
  new KeystoneGetHandler(),
62
+ new SsoLinkHandler(),
63
+ new SsoLoginHandler(),
64
+ new SsoConfigHandler(),
59
65
  new StaticFileHandler(CLIENT_DIR),
60
66
  ],
61
67
  errorHandler: new ErrorHandler()