@ibgib/space-gib 0.0.6 → 0.0.7

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 (37) 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-RXFIBFRK.mjs +42 -0
  5. package/dist/client/chunk-RXFIBFRK.mjs.map +7 -0
  6. package/dist/client/chunk-ULFNE26Y.mjs +2216 -0
  7. package/dist/client/chunk-ULFNE26Y.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 +1346 -245
  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/bootstrap.mts +9 -0
  16. package/src/client/components/identity-header/identity-header.mts +43 -26
  17. package/src/client/components/identity-manager/identity-manager.css +57 -392
  18. package/src/client/components/identity-manager/identity-manager.html +0 -114
  19. package/src/client/components/identity-manager/identity-manager.mts +356 -543
  20. package/src/client/components/keystone-creator/keystone-creator.mts +4 -3
  21. package/src/client/components/keystone-details/keystone-details.css +472 -0
  22. package/src/client/components/keystone-details/keystone-details.html +99 -0
  23. package/src/client/components/keystone-details/keystone-details.mts +821 -0
  24. package/src/client/components/keystone-scrubber/SCRUBBER_IMPLEMENTATION.md +33 -0
  25. package/src/client/components/keystone-scrubber/keystone-scrubber.css +46 -0
  26. package/src/client/components/keystone-scrubber/keystone-scrubber.html +15 -0
  27. package/src/client/components/keystone-scrubber/keystone-scrubber.mts +356 -0
  28. package/src/client/ui/shell/space-gib-shell-service.mts +4 -0
  29. package/src/server/path-constants.mts +12 -0
  30. package/src/server/serve-gib/handlers/api/keystone/sso-config.handler.mts +66 -0
  31. package/src/server/serve-gib/handlers/api/keystone/sso-link.handler.mts +119 -0
  32. package/src/server/serve-gib/handlers/api/keystone/sso-login.handler.mts +189 -0
  33. package/src/server/server.mts +6 -0
  34. package/dist/client/chunk-734MMI4C.mjs +0 -42
  35. package/dist/client/chunk-734MMI4C.mjs.map +0 -7
  36. package/dist/client/chunk-SMOZ2D5E.mjs +0 -2049
  37. package/dist/client/chunk-SMOZ2D5E.mjs.map +0 -7
@@ -0,0 +1,189 @@
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 POOL_ID_CUSTODIAN_MANAGE pool from the parent keystone
127
+ const custodianPool = parentKeystone.data?.challengePools?.find((p: any) => p.id === POOL_ID_CUSTODIAN_MANAGE);
128
+ if (!custodianPool) {
129
+ return this.error(401, `Unauthorized: Custodian pool '${POOL_ID_CUSTODIAN_MANAGE}' is not registered in the parent identity keystone.`);
130
+ }
131
+
132
+ // 5. Assert allowed verbs contain KEYSTONE_VERB_MANAGE
133
+ const allowedVerbs = custodianPool.config.allowedVerbs || [];
134
+ if (!allowedVerbs.includes(KEYSTONE_VERB_MANAGE)) {
135
+ return this.error(401, `Unauthorized: Custodian pool does not have the required manage permission.`);
136
+ }
137
+
138
+ // 6. Cryptographically verify the custodian secret against the pool's challenges
139
+ const strategy = KeystoneStrategyFactory.create({ config: custodianPool.config });
140
+ const poolSecret = await strategy.derivePoolSecret({ masterSecret: custodianSecret });
141
+
142
+ for (const [id, challenge] of Object.entries(custodianPool.challenges)) {
143
+ const solution = await strategy.generateSolution({
144
+ poolSecret,
145
+ poolId: custodianPool.id,
146
+ challengeId: id
147
+ });
148
+ const hashValue = await strategy.generateChallenge({ solution });
149
+ if (hashValue.hash !== (challenge as any).hash) {
150
+ return this.error(401, 'Unauthorized: Cryptographic verification of custodian pool challenges failed.');
151
+ }
152
+ }
153
+
154
+ // 7. Issue secure HttpOnly session cookie
155
+ const sessionPayload = {
156
+ parentTjpAddr,
157
+ providerKey: userInfo.providerKey,
158
+ exp: Math.floor(Date.now() / 1000) + 24 * 3600 // 24-hour expiration
159
+ };
160
+
161
+ const config = loadSsoServerConfig();
162
+ const sessionToken = signSessionToken(sessionPayload, config.sessionSecret);
163
+
164
+ const headers = {
165
+ 'Set-Cookie': `space_gib_session=${sessionToken}; Path=/; HttpOnly; SameSite=Strict; Max-Age=86400`
166
+ };
167
+
168
+ console.log(`${lc} login successful for parent: ${parentTjpAddr}, custodian providerKey: ${userInfo.providerKey}`);
169
+
170
+ return {
171
+ status: 200,
172
+ headers,
173
+ body: {
174
+ success: true,
175
+ parentTjpAddr,
176
+ custodianPoolId: custodianPool.id
177
+ },
178
+ isJson: true
179
+ };
180
+
181
+ } catch (error) {
182
+ const emsg = extractErrorMsg(error);
183
+ console.error(`${lc} Login failed: ${emsg}`);
184
+ return this.error(500, `Login failed: ${emsg}`);
185
+ } finally {
186
+ if (logalot) { console.log(`${lc} complete.`); }
187
+ }
188
+ }
189
+ }
@@ -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()