@eulab/connect 0.8.0 → 0.10.0

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.
@@ -0,0 +1,406 @@
1
+ import { createHash, randomBytes, createCipheriv, createDecipheriv, timingSafeEqual } from 'node:crypto';
2
+ import { createRemoteJWKSet, jwtVerify } from 'jose';
3
+ import { ConnectOnboardingSource, ConnectOnboardingError, ConnectServer } from './server.js';
4
+ export * from './application-store.js';
5
+ export const connectConsentVersion = '2026-10-21-mandatory-v1';
6
+ export class ConnectApplicationError extends Error {
7
+ code;
8
+ callbackStage;
9
+ authorizationDetail;
10
+ constructor(code) {
11
+ super(code);
12
+ this.code = code;
13
+ this.name = 'ConnectApplicationError';
14
+ }
15
+ }
16
+ const opaque = () => randomBytes(32).toString('base64url');
17
+ const digest = (v) => createHash('sha256').update(v).digest('base64url');
18
+ const same = (a, b) => { const x = Buffer.from(a), y = Buffer.from(b); return x.length === y.length && timingSafeEqual(x, y); };
19
+ function fail(code) { throw new ConnectApplicationError(code); }
20
+ /** Server-only application facade. No provider token appears in a public result. */
21
+ export class ConnectApplication {
22
+ config;
23
+ /** Read-only entry point usable even when construction would reject invalid configuration. */
24
+ static async diagnose(config, email) {
25
+ try {
26
+ return await new ConnectApplication(config).diagnose(email);
27
+ }
28
+ catch {
29
+ return { checks: [{ code: 'configuration', status: 'failed' }, { code: 'discovery', status: 'not_checked' }, { code: 'source', status: 'not_checked' }, { code: 'authorization', status: 'not_checked' }] };
30
+ }
31
+ }
32
+ source;
33
+ get catalog() { return { ...this.config.catalog, appId: this.settings?.appId || this.plannedAppId || this.config.appId }; }
34
+ key;
35
+ jwks;
36
+ settings;
37
+ plannedAppId;
38
+ prefix;
39
+ ttl;
40
+ constructor(config) {
41
+ this.config = config;
42
+ try {
43
+ for (const value of [config.apiUrl, config.appOrigin, ...(config.oidcTransportOrigin ? [config.oidcTransportOrigin] : []), ...(config.issuer ? [config.issuer] : []), ...(config.redirectUri ? [config.redirectUri] : [])]) {
44
+ const u = new URL(value);
45
+ if (u.username || u.password || u.hash || !(u.protocol === 'https:' || (config.allowLoopbackHttp && u.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(u.hostname))))
46
+ fail('invalid_configuration');
47
+ }
48
+ if ((config.redirectUri && new URL(config.redirectUri).origin !== config.appOrigin) || !(config.sourceSecret || config.presenter?.secret) || ((config.issuer || config.clientId || config.redirectUri) && !(config.issuer && config.clientId && config.redirectUri)) || !config.sourceId || config.catalog.appId !== config.appId || !/^([a-f0-9]{64})$/i.test(config.encryptionKey))
49
+ fail('invalid_configuration');
50
+ if (config.oidcTransportOrigin) {
51
+ const transport = new URL(config.oidcTransportOrigin);
52
+ if (transport.pathname !== '/' || transport.search)
53
+ fail('invalid_configuration');
54
+ }
55
+ this.ttl = config.sessionTtlSeconds ?? 28800;
56
+ if (this.ttl < 60 || this.ttl > 604800)
57
+ fail('invalid_configuration');
58
+ }
59
+ catch {
60
+ fail('invalid_configuration');
61
+ }
62
+ this.key = Buffer.from(config.encryptionKey, 'hex');
63
+ this.prefix = (new URL(config.appOrigin).protocol === 'https:' ? '__Host-' : '') + 'connect_' + digest(config.sourceId + ':' + config.appId).slice(0, 12);
64
+ this.source = new ConnectOnboardingSource({ apiUrl: config.apiUrl, sourceId: config.sourceId, appId: config.appId, secret: config.presenter?.secret || config.sourceSecret, presenterId: config.presenter?.id, deployment: config.presenter?.deployment });
65
+ if (config.issuer && config.clientId && config.redirectUri)
66
+ this.settings = { sourceId: config.sourceId, appId: config.appId, issuer: config.issuer, clientId: config.clientId, redirectUri: config.redirectUri, clientSecret: config.clientSecret };
67
+ }
68
+ validateConfiguration(c) {
69
+ try {
70
+ if (c.sourceId !== this.config.sourceId || !c.clientId || !/^[a-z][a-z0-9_.:-]{0,79}$/.test(c.appId) || new URL(c.redirectUri).origin !== this.config.appOrigin)
71
+ fail('invalid_configuration');
72
+ for (const value of [c.issuer, c.redirectUri]) {
73
+ const u = new URL(value);
74
+ if (u.username || u.password || u.hash || !(u.protocol === 'https:' || (this.config.allowLoopbackHttp && u.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(u.hostname))))
75
+ fail('invalid_configuration');
76
+ }
77
+ }
78
+ catch {
79
+ fail('invalid_configuration');
80
+ }
81
+ }
82
+ async loadSettings() {
83
+ if (!this.settings) {
84
+ const stored = await this.transaction('configuration', tx => this.read(tx, 'configuration'));
85
+ if (stored) {
86
+ this.validateConfiguration(stored);
87
+ this.settings = stored;
88
+ }
89
+ }
90
+ return this.settings;
91
+ }
92
+ async oidc() { const settings = await this.loadSettings(); if (!settings)
93
+ fail('invalid_configuration'); return settings; }
94
+ configuration = { sync: async () => {
95
+ const result = await this.onboarding(() => this.source.configuration());
96
+ if (result.status !== 'ready') {
97
+ this.plannedAppId = undefined;
98
+ if (result.plannedAppId) {
99
+ if (!/^[a-z][a-z0-9_.:-]{0,79}$/.test(result.plannedAppId))
100
+ fail('invalid_configuration');
101
+ this.plannedAppId = result.plannedAppId;
102
+ }
103
+ return { status: result.status, ...(result.plannedAppId ? { plannedAppId: result.plannedAppId } : {}) };
104
+ }
105
+ this.validateConfiguration(result.configuration);
106
+ await this.transaction('configuration', tx => this.put(tx, 'configuration', result.configuration, 365 * 86400));
107
+ this.settings = result.configuration;
108
+ this.jwks = undefined;
109
+ return { status: 'ready', appId: result.configuration.appId };
110
+ } };
111
+ async transaction(key, fn) { try {
112
+ return await this.config.store.transaction(key, fn);
113
+ }
114
+ catch (e) {
115
+ if (e instanceof ConnectApplicationError)
116
+ throw e;
117
+ return fail('provider_unavailable');
118
+ } }
119
+ cookie(name, value, maxAge) { return { name: this.prefix + '_' + name, value, httpOnly: true, secure: new URL(this.config.appOrigin).protocol === 'https:', sameSite: 'lax', path: '/', maxAge }; }
120
+ browser(ctx) { if (ctx.origin !== this.config.appOrigin)
121
+ fail('invalid_context'); }
122
+ seal(id, value) { const iv = randomBytes(12), cipher = createCipheriv('aes-256-gcm', this.key, iv); cipher.setAAD(Buffer.from(this.config.sourceId + ':' + this.config.appId + ':' + id)); const bytes = Buffer.concat([cipher.update(JSON.stringify(value)), cipher.final()]); return Buffer.concat([iv, cipher.getAuthTag(), bytes]).toString('base64url'); }
123
+ open(id, value) { try {
124
+ const bytes = Buffer.from(value, 'base64url'), dec = createDecipheriv('aes-256-gcm', this.key, bytes.subarray(0, 12));
125
+ dec.setAAD(Buffer.from(this.config.sourceId + ':' + this.config.appId + ':' + id));
126
+ dec.setAuthTag(bytes.subarray(12, 28));
127
+ return JSON.parse(Buffer.concat([dec.update(bytes.subarray(28)), dec.final()]).toString());
128
+ }
129
+ catch {
130
+ return fail('invalid_flow');
131
+ } }
132
+ async put(tx, id, value, ttlSeconds) { await tx.put(id, this.seal(id, value), Date.now() + ttlSeconds * 1000); }
133
+ async read(tx, id) { const cipher = await tx.get(id); return cipher ? this.open(id, cipher) : null; }
134
+ async take(id) { return this.transaction(id, async (tx) => { const value = await this.read(tx, id); await tx.remove(id); return value; }); }
135
+ client(context) { return new ConnectServer({ apiUrl: this.config.apiUrl, installationId: context.binding.installationId, secret: context.binding.secret, requestTimeoutMs: 10000 }); }
136
+ async onboarding(operation) { try {
137
+ return await operation();
138
+ }
139
+ catch (e) {
140
+ if (e instanceof ConnectOnboardingError)
141
+ fail(e.status === 409 ? 'invalid_context' : e.status >= 500 || e.status === 0 ? 'provider_unavailable' : 'access_denied');
142
+ return fail('provider_unavailable');
143
+ } }
144
+ async current(email, expected) {
145
+ const found = await this.onboarding(() => this.source.loginContext(email));
146
+ if (found.status !== 'connect' && found.status !== 'configuration_required')
147
+ return fail('access_denied');
148
+ const a = found.context, b = expected;
149
+ if (a.user.subject !== b.user.subject || a.user.id !== b.user.id || a.tenant.id !== b.tenant.id || a.binding.installationId !== b.binding.installationId || a.binding.customerId !== b.binding.customerId)
150
+ fail('invalid_context');
151
+ return a;
152
+ }
153
+ async verifyAccess(context, token) {
154
+ let a;
155
+ try {
156
+ a = await this.client(context).permissions(token);
157
+ }
158
+ catch (cause) {
159
+ const error = new ConnectApplicationError('access_denied');
160
+ const status = cause instanceof Error ? cause.message.match(/^Connect (\d{3}):/)?.[1] : undefined;
161
+ error.authorizationDetail = status === '401' ? 'http_401' : status === '403' ? 'http_403' : status ? 'http_other' : 'transport';
162
+ throw error;
163
+ }
164
+ const detail = a.canLogin !== true ? 'login_denied' : a.appId !== (this.settings?.appId || this.config.appId) ? 'app_mismatch' : a.installationId !== context.binding.installationId ? 'installation_mismatch' : a.subject !== context.user.subject ? 'subject_mismatch' : a.localUserId !== context.user.id ? 'local_user_mismatch' : undefined;
165
+ if (detail) {
166
+ const error = new ConnectApplicationError('access_denied');
167
+ error.authorizationDetail = detail;
168
+ throw error;
169
+ }
170
+ return a;
171
+ }
172
+ providerUrl(issuer, path) {
173
+ const canonical = new URL(issuer + path);
174
+ return this.config.oidcTransportOrigin ? new URL(canonical.pathname + canonical.search, this.config.oidcTransportOrigin).href : canonical.href;
175
+ }
176
+ async grant(params) {
177
+ try {
178
+ const sso = await this.oidc();
179
+ const r = await fetch(this.providerUrl(sso.issuer, '/protocol/openid-connect/token'), { method: 'POST', redirect: 'error', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ ...params, client_id: sso.clientId, ...(sso.clientSecret ? { client_secret: sso.clientSecret } : {}) }), signal: AbortSignal.timeout(10000) });
180
+ if (!r.ok)
181
+ fail(r.status >= 500 ? 'provider_unavailable' : 'access_denied');
182
+ const t = await r.json();
183
+ if (typeof t.access_token !== 'string' || !t.access_token || typeof t.refresh_token !== 'string' || !t.refresh_token || !Number.isFinite(t.expires_in) || t.expires_in <= 0)
184
+ fail('access_denied');
185
+ return { ...t, expiresAt: Date.now() + t.expires_in * 1000 };
186
+ }
187
+ catch (e) {
188
+ if (e instanceof ConnectApplicationError)
189
+ throw e;
190
+ return fail('provider_unavailable');
191
+ }
192
+ }
193
+ next(request) { return request.nextAction ?? (['pending', 'approved', 'migrating'].includes(request.state) ? 'wait' : request.state === 'completed' ? 'sign_in' : 'contact_admin'); }
194
+ async begin(context, email) {
195
+ const sso = await this.oidc();
196
+ const state = opaque(), browser = opaque(), nonce = opaque(), verifier = opaque();
197
+ await this.transaction('flow:' + digest(state), tx => this.put(tx, 'flow:' + digest(state), { context, email, verifier, nonce, browserHash: digest(browser) }, 600));
198
+ const u = new URL(sso.issuer + '/protocol/openid-connect/auth');
199
+ for (const [k, v] of Object.entries({ client_id: sso.clientId, redirect_uri: sso.redirectUri, response_type: 'code', scope: 'openid profile email', state, nonce, code_challenge: digest(verifier), code_challenge_method: 'S256', login_hint: email }))
200
+ u.searchParams.set(k, v);
201
+ return { status: 'redirect', url: u.href, cookies: [this.cookie('flow', browser, 600)] };
202
+ }
203
+ auth = {
204
+ signIn: async (input, ctx) => {
205
+ this.browser(ctx);
206
+ let found;
207
+ try {
208
+ found = await this.onboarding(() => this.source.loginContext(input.email));
209
+ }
210
+ catch (e) {
211
+ if (e instanceof ConnectApplicationError && e.code === 'invalid_context')
212
+ return { status: 'administrative_required', reason: 'source_conflict' };
213
+ throw e;
214
+ }
215
+ if (found.status === 'connect' || found.status === 'configuration_required') {
216
+ if (!await this.loadSettings())
217
+ return { status: 'configuration_required', appId: found.status === 'configuration_required' ? found.appId : this.config.appId };
218
+ return this.begin(found.context, input.email);
219
+ }
220
+ const next = found.request ? this.next(found.request) : undefined;
221
+ if (found.request && next !== 'resubmit' && next !== 'choose_connect_password')
222
+ return { status: 'pending', request: found.request, nextAction: next };
223
+ if (!input.password)
224
+ fail('invalid_credentials');
225
+ const legacy = await this.config.accounts.verifyLegacy({ email: input.email, password: input.password });
226
+ if (!legacy)
227
+ fail('invalid_credentials');
228
+ const challenge = opaque();
229
+ await this.transaction('challenge:' + digest(challenge), tx => this.put(tx, 'challenge:' + digest(challenge), { legacy, email: input.email, request: found.request, browserHash: digest(challenge) }, 120));
230
+ return { status: 'migration_required', challenge, consentVersion: connectConsentVersion, cookies: [this.cookie('challenge', challenge, 120)], ...(found.request ? { request: found.request } : {}) };
231
+ },
232
+ callback: async (input, ctx) => {
233
+ let stage = 'flow';
234
+ try {
235
+ this.browser(ctx);
236
+ const sso = await this.oidc();
237
+ const id = 'flow:' + digest(input.state), flow = await this.take(id);
238
+ if (!flow || !same(flow.browserHash, digest(ctx.cookies[this.prefix + '_flow'] ?? '')) || input.error || !input.code || (input.iss && input.iss !== sso.issuer))
239
+ return fail('invalid_flow');
240
+ stage = 'token_exchange';
241
+ const tokens = await this.grant({ grant_type: 'authorization_code', code: input.code, redirect_uri: sso.redirectUri, code_verifier: flow.verifier });
242
+ stage = 'id_token';
243
+ try {
244
+ if (!tokens.id_token)
245
+ fail('access_denied');
246
+ const { payload } = await jwtVerify(tokens.id_token, this.jwks ??= createRemoteJWKSet(new URL(this.providerUrl(sso.issuer, '/protocol/openid-connect/certs')), { timeoutDuration: 10000 }), { issuer: sso.issuer, audience: sso.clientId, algorithms: ['RS256', 'ES256'], requiredClaims: ['sub', 'iat', 'exp', 'nonce'] });
247
+ if (payload.sub !== flow.context.user.subject || payload.nonce !== flow.nonce || (payload.azp && payload.azp !== sso.clientId))
248
+ fail('invalid_context');
249
+ }
250
+ catch {
251
+ return fail('access_denied');
252
+ }
253
+ stage = 'context';
254
+ const context = await this.current(flow.email, flow.context);
255
+ stage = 'authorization';
256
+ await this.verifyAccess(context, tokens.access_token);
257
+ stage = 'handoff';
258
+ const handoff = opaque(), browser = opaque();
259
+ await this.transaction('handoff:' + digest(handoff), tx => this.put(tx, 'handoff:' + digest(handoff), { context, email: flow.email, tokens, browserHash: digest(browser) }, 60));
260
+ return { status: 'handoff', handoff, cookies: [this.cookie('flow', '', 0), this.cookie('handoff', browser, 60)] };
261
+ }
262
+ catch (error) {
263
+ if (error instanceof ConnectApplicationError)
264
+ error.callbackStage = stage;
265
+ throw error;
266
+ }
267
+ },
268
+ exchange: async (handoff, ctx) => {
269
+ this.browser(ctx);
270
+ const id = 'handoff:' + digest(handoff);
271
+ return this.transaction(id, async (tx) => {
272
+ const flow = await this.read(tx, id);
273
+ if (!flow || !same(flow.browserHash, digest(ctx.cookies[this.prefix + '_handoff'] ?? '')))
274
+ return fail('invalid_flow');
275
+ const context = await this.current(flow.email, flow.context);
276
+ await this.verifyAccess(context, flow.tokens.access_token);
277
+ const profile = await this.config.accounts.provision(context, { operationId: id, transaction: tx });
278
+ if (profile.localUserId !== context.user.id || profile.localTenantId !== context.tenant.id)
279
+ fail('provision_conflict');
280
+ const sessionId = opaque(), expiry = Date.now() + this.ttl * 1000;
281
+ await this.put(tx, 'session:' + digest(sessionId), { context, email: flow.email, tokens: flow.tokens, profile, expiresAt: expiry, refreshedAt: 0, generation: opaque() }, this.ttl);
282
+ await tx.remove(id);
283
+ return { status: 'authenticated', session: { sessionId, profile, subject: context.user.subject, expiresAt: expiry }, cookies: [this.cookie('handoff', '', 0), this.cookie('session', sessionId, this.ttl)] };
284
+ });
285
+ },
286
+ resolve: async (sessionId) => this.resolve(sessionId, false),
287
+ refresh: async (sessionId) => this.resolve(sessionId, true),
288
+ fromCookies: (ctx) => { this.browser(ctx); return ctx.cookies[this.prefix + '_session'] ?? ''; },
289
+ logout: async (sessionId, ctx) => {
290
+ this.browser(ctx);
291
+ const id = 'session:' + digest(sessionId);
292
+ const session = await this.take(id);
293
+ let providerRevoked = null;
294
+ if (session) {
295
+ try {
296
+ const sso = await this.oidc();
297
+ const r = await fetch(this.providerUrl(sso.issuer, '/protocol/openid-connect/logout'), { method: 'POST', redirect: 'error', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ client_id: sso.clientId, refresh_token: session.tokens.refresh_token, ...(sso.clientSecret ? { client_secret: sso.clientSecret } : {}) }), signal: AbortSignal.timeout(10000) });
298
+ providerRevoked = r.ok;
299
+ }
300
+ catch {
301
+ providerRevoked = false;
302
+ }
303
+ }
304
+ return { revoked: true, providerRevoked, cookies: [this.cookie('session', '', 0)] };
305
+ }
306
+ };
307
+ async resolve(sessionId, force) {
308
+ const result = await this.withSession(sessionId, force, async (s) => ({ sessionId, profile: s.profile, subject: s.context.user.subject, expiresAt: s.expiresAt }));
309
+ return result;
310
+ }
311
+ async withSession(sessionId, force, fn) {
312
+ const id = 'session:' + digest(sessionId);
313
+ const result = await this.transaction(id, async (tx) => {
314
+ const s = await this.read(tx, id);
315
+ if (!s || s.expiresAt <= Date.now())
316
+ return { error: 'session_expired' };
317
+ try {
318
+ const intentId = 'refresh:' + digest(sessionId + ':' + s.generation);
319
+ const interrupted = await tx.get(intentId);
320
+ if (interrupted)
321
+ fail('session_expired');
322
+ s.context = await this.current(s.email, s.context);
323
+ // A shared persisted timestamp also deduplicates callers queued on another process.
324
+ if (s.tokens.expiresAt <= Date.now() + 30000 || (force && s.refreshedAt < Date.now() - 5000)) {
325
+ // Commit a tombstone BEFORE a rotating grant: on an ambiguous response/crash the old token is never replayed.
326
+ // The intent survives a crash/rollback and is checked on every session use.
327
+ await this.put(tx, intentId, { pending: true }, this.ttl);
328
+ await tx.checkpoint();
329
+ s.tokens = await this.grant({ grant_type: 'refresh_token', refresh_token: s.tokens.refresh_token });
330
+ s.refreshedAt = Date.now();
331
+ s.generation = opaque();
332
+ // The new generation supersedes the durable intent only on commit.
333
+ }
334
+ await this.verifyAccess(s.context, s.tokens.access_token);
335
+ const value = await fn(s);
336
+ await tx.put(id, this.seal(id, s), s.expiresAt);
337
+ return { value };
338
+ }
339
+ catch (e) {
340
+ await tx.remove(id);
341
+ return { error: e instanceof ConnectApplicationError ? e.code : 'access_denied' };
342
+ }
343
+ });
344
+ if ('error' in result)
345
+ return fail(result.error);
346
+ // Old intents expire with their session; no unsafe cleanup race between processes.
347
+ return result.value;
348
+ }
349
+ migration = {
350
+ submit: async (input, ctx) => {
351
+ this.browser(ctx);
352
+ if (input.consentVersion !== connectConsentVersion)
353
+ fail('invalid_consent');
354
+ const proof = await this.take('challenge:' + digest(input.challenge));
355
+ if (!proof || !same(proof.browserHash, digest(ctx.cookies[this.prefix + '_challenge'] ?? '')))
356
+ fail('invalid_flow');
357
+ const verified = await this.config.accounts.verifyLegacy({ email: proof.email, password: input.legacyPassword });
358
+ if (!verified || JSON.stringify(verified) !== JSON.stringify(proof.legacy))
359
+ fail('invalid_credentials');
360
+ if (proof.request && this.next(proof.request) === 'choose_connect_password') {
361
+ if (!input.newConnectPassword || same(input.newConnectPassword, input.legacyPassword))
362
+ fail('invalid_password');
363
+ return this.onboarding(() => this.source.recoverPassword({ requestId: proof.request.requestId, email: proof.email, localTenantId: verified.localTenant.id, localUserId: verified.localUser.id, consentVersion: input.consentVersion, newPassword: input.newConnectPassword }, input.idempotencyKey));
364
+ }
365
+ return this.onboarding(() => this.source.submit({ kind: 'migration', consentVersion: input.consentVersion, ...verified, initialPassword: input.legacyPassword }, input.idempotencyKey));
366
+ }
367
+ };
368
+ activation = { submit: async (input, ctx) => {
369
+ this.browser(ctx);
370
+ if (input.consentVersion !== connectConsentVersion)
371
+ fail('invalid_consent');
372
+ const { idempotencyKey, consentVersion, ...request } = input;
373
+ return this.onboarding(() => this.source.submit(request, idempotencyKey));
374
+ } };
375
+ access = { authorize: async (sessionId, functionKey, resource = null) => this.withSession(sessionId, false, async (s) => {
376
+ if (!this.catalog.functions.some(f => f.key === functionKey))
377
+ return { allowed: false, reason: 'unknown_function' };
378
+ const central = await this.client(s.context).authorize(s.tokens.access_token, functionKey);
379
+ return central.allowed ? { allowed: await this.config.accounts.restrict(s.profile, functionKey, resource), reason: 'local_policy' } : central;
380
+ }) };
381
+ /** All existing Connect services share this authenticated server session. No callback is retried. */
382
+ async services(sessionId, operation) { return this.withSession(sessionId, false, s => operation(this.client(s.context), s.tokens.access_token)); }
383
+ async diagnose(email) {
384
+ const checks = [{ code: 'configuration', status: 'ok' }];
385
+ const sso = await this.loadSettings();
386
+ if (!sso)
387
+ checks.push({ code: 'discovery', status: 'not_checked' });
388
+ else
389
+ try {
390
+ const r = await fetch(this.providerUrl(sso.issuer, '/.well-known/openid-configuration'), { redirect: 'error', signal: AbortSignal.timeout(10000) });
391
+ const d = await r.json();
392
+ checks.push({ code: 'discovery', status: r.ok && d.issuer === sso.issuer ? 'ok' : 'failed' });
393
+ }
394
+ catch {
395
+ checks.push({ code: 'discovery', status: 'failed' });
396
+ }
397
+ try {
398
+ const context = await this.source.loginContext(email ?? 'connect-diagnostic@example.invalid');
399
+ checks.push({ code: 'source', status: 'ok' }, { code: 'authorization', status: 'not_checked' });
400
+ }
401
+ catch (e) {
402
+ checks.push({ code: 'source', status: e instanceof ConnectOnboardingError && e.status === 403 ? 'ok' : 'failed' }, { code: 'authorization', status: 'not_checked' });
403
+ }
404
+ return { checks };
405
+ }
406
+ }
package/dist/browser.d.ts CHANGED
@@ -3,8 +3,8 @@ export type { IVRInput, IVRPrompt, IVRChannel, VoiceIVRSession } from './bot.js'
3
3
  export type { WhatsAppRealtimeEvent, WhatsAppSnapshot, WhatsAppRealtimeStatus, WhatsAppSubscribeOptions, WhatsAppSubscription } from './realtime.js';
4
4
  export type { WhatsAppBotDefinition, WhatsAppBotNode, WhatsAppBotState, WhatsAppBotTurn, WhatsAppBot } from './bot.js';
5
5
  export { defineFunctions, functionsResponse, functionCatalogPath } from './functions.js';
6
- export type { AppFunction, FunctionMatrix, AccessResult, ConnectUser } from './functions.js';
7
- import type { AccessResult, ConnectUser } from './functions.js';
6
+ export type { AppFunction, FunctionMatrix, AccessResult, ConnectUser, TeamFunction, TeamRole, TeamUser, TeamOverview, TeamRoleInput, TeamUserAssignment, TeamRevocation, TeamRestore } from './functions.js';
7
+ import type { AccessResult, ConnectUser, TeamFunction, TeamOverview, TeamRole, TeamRoleInput, TeamUser, TeamUserAssignment, TeamRevocation, TeamRestore } from './functions.js';
8
8
  export type { WhatsAppSession, WhatsAppArchive, Conversation, WhatsAppMessage, WhatsAppPayload } from './whatsapp.js';
9
9
  export interface BrowserConfig {
10
10
  apiUrl: string;
@@ -84,6 +84,18 @@ export declare class ConnectBrowser {
84
84
  can(functionKey: string): boolean;
85
85
  permissions(): Promise<AccessResult>;
86
86
  users(): Promise<ConnectUser[]>;
87
+ teamOverview(): Promise<TeamOverview>;
88
+ teamUsers(): Promise<TeamUser[]>;
89
+ teamRoles(): Promise<TeamRole[]>;
90
+ teamFunctions(): Promise<TeamFunction[]>;
91
+ createTeamRole(role: TeamRoleInput): Promise<TeamRole>;
92
+ updateTeamRole(id: string, role: TeamRoleInput): Promise<TeamRole>;
93
+ deleteTeamRole(id: string): Promise<{
94
+ removed: boolean;
95
+ }>;
96
+ setTeamUserRoles(subject: string, roleIds: string[]): Promise<TeamUserAssignment>;
97
+ revokeTeamUser(subject: string): Promise<TeamRevocation>;
98
+ restoreTeamUser(subject: string): Promise<TeamRestore>;
87
99
  watchAccess(onChange: (access: AccessResult | null) => void, intervalMs?: number): () => void;
88
100
  watchSession(onChange: (valid: boolean | null) => void, intervalMs?: number): () => void;
89
101
  get authenticated(): boolean;
package/dist/browser.js CHANGED
@@ -111,6 +111,16 @@ export class ConnectBrowser {
111
111
  can(functionKey) { return !!this.accessState?.canLogin && this.accessState.functions.some(f => f.key === functionKey); }
112
112
  async permissions() { const result = await this.request('/v1/access'); this.accessState = result; return result; }
113
113
  users() { return this.request('/v1/users'); }
114
+ teamOverview() { return this.request('/v1/team'); }
115
+ teamUsers() { return this.request('/v1/team/users'); }
116
+ teamRoles() { return this.request('/v1/team/roles'); }
117
+ teamFunctions() { return this.request('/v1/team/functions'); }
118
+ createTeamRole(role) { return this.request('/v1/team/roles', 'POST', role); }
119
+ updateTeamRole(id, role) { return this.request('/v1/team/roles/' + encodeURIComponent(id), 'PUT', role); }
120
+ deleteTeamRole(id) { return this.request('/v1/team/roles/' + encodeURIComponent(id), 'DELETE'); }
121
+ setTeamUserRoles(subject, roleIds) { return this.request('/v1/team/users/' + encodeURIComponent(subject) + '/roles', 'PUT', { roleIds }); }
122
+ revokeTeamUser(subject) { return this.request('/v1/team/users/' + encodeURIComponent(subject), 'DELETE'); }
123
+ restoreTeamUser(subject) { return this.request('/v1/team/users/' + encodeURIComponent(subject) + '/restore', 'POST'); }
114
124
  watchAccess(onChange, intervalMs = 30000) { const refresh = async () => { try {
115
125
  if (!await this.checkSession()) {
116
126
  this.accessState = null;
@@ -30,5 +30,63 @@ export interface ConnectUser {
30
30
  name: string;
31
31
  }[];
32
32
  }
33
+ export interface TeamFunction {
34
+ key: string;
35
+ name: string;
36
+ delegable: boolean;
37
+ }
38
+ export interface TeamRole {
39
+ id: string;
40
+ name: string;
41
+ permissions: string[];
42
+ }
43
+ export interface TeamUser {
44
+ subject: string;
45
+ localUserId: string;
46
+ displayName: string;
47
+ identityEnabled: boolean;
48
+ membershipEnabled: boolean;
49
+ accessRevoked: boolean;
50
+ roles: {
51
+ id: string;
52
+ name: string;
53
+ }[];
54
+ }
55
+ export interface TeamOverview {
56
+ installationId: string;
57
+ customerId: string;
58
+ appId: string;
59
+ canManage: boolean;
60
+ functions: TeamFunction[];
61
+ delegation: {
62
+ key: string;
63
+ name: string;
64
+ }[];
65
+ roles: TeamRole[];
66
+ users: TeamUser[];
67
+ }
68
+ export interface TeamRoleInput {
69
+ name: string;
70
+ permissions: string[];
71
+ }
72
+ export interface TeamUserAssignment {
73
+ subject: string;
74
+ localUserId: string;
75
+ roleIds: string[];
76
+ accessRestored: boolean;
77
+ }
78
+ export interface TeamRevocation {
79
+ revoked: boolean;
80
+ subject: string;
81
+ localUserId: string;
82
+ identityPreserved: boolean;
83
+ membershipPreserved: boolean;
84
+ otherApplicationsPreserved: boolean;
85
+ }
86
+ export interface TeamRestore {
87
+ restored: boolean;
88
+ subject: string;
89
+ localUserId: string;
90
+ }
33
91
  export declare function defineFunctions(input: Omit<FunctionMatrix, 'schemaVersion'>): FunctionMatrix;
34
92
  export declare function functionsResponse(matrix: FunctionMatrix): Response;