@eulab/connect 0.8.1 → 0.12.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,218 @@
1
+ import { ConnectOnboardingSource, ConnectServer } from './server.js';
2
+ import type { ApplicationTeamUserInput, ApplicationTeamUserResult } from './server.js';
3
+ export { ConnectApiError } from './server.js';
4
+ export type { ApplicationTeamUserInput, ApplicationTeamUserResult } from './server.js';
5
+ import type { AuthorizedConnectContext, OnboardingRequestStatus, AppOnboardingActivationRequest, OnboardingNextAction, DeploymentMetadata } from './server.js';
6
+ import type { FunctionMatrix } from './functions.js';
7
+ import type { ConnectApplicationStore, ConnectStoreTransaction } from './application-store.js';
8
+ export * from './application-store.js';
9
+ export declare const connectConsentVersion = "2026-10-21-mandatory-v1";
10
+ export type ConnectApplicationErrorCode = 'invalid_configuration' | 'invalid_credentials' | 'invalid_context' | 'invalid_flow' | 'invalid_consent' | 'invalid_password' | 'access_denied' | 'session_expired' | 'provider_unavailable' | 'provision_conflict';
11
+ export type ConnectCallbackStage = 'flow' | 'token_exchange' | 'id_token' | 'context' | 'authorization' | 'handoff';
12
+ export declare class ConnectApplicationError extends Error {
13
+ readonly code: ConnectApplicationErrorCode;
14
+ callbackStage?: ConnectCallbackStage;
15
+ authorizationDetail?: 'http_401' | 'http_403' | 'http_other' | 'transport' | 'login_denied' | 'app_mismatch' | 'installation_mismatch' | 'subject_mismatch' | 'local_user_mismatch';
16
+ constructor(code: ConnectApplicationErrorCode);
17
+ }
18
+ export interface BrowserContext {
19
+ origin: string;
20
+ cookies: Record<string, string | undefined>;
21
+ }
22
+ export interface CookieDirective {
23
+ name: string;
24
+ value: string;
25
+ httpOnly: true;
26
+ secure: boolean;
27
+ sameSite: 'lax';
28
+ path: '/';
29
+ maxAge: number;
30
+ }
31
+ export interface LegacyAccount {
32
+ localTenant: {
33
+ id: string;
34
+ name: string;
35
+ slug: string;
36
+ };
37
+ localUser: Omit<AuthorizedConnectContext['user'], 'subject'>;
38
+ }
39
+ export interface LocalProfile {
40
+ localUserId: string;
41
+ localTenantId: string;
42
+ }
43
+ export interface ConnectAccountAdapter {
44
+ verifyLegacy(input: {
45
+ email: string;
46
+ password: string;
47
+ }): Promise<LegacyAccount | null>;
48
+ /** Must be idempotent on operationId and reject conflicting existing IDs/subjects. Never join by email. */
49
+ provision(context: AuthorizedConnectContext, operation: {
50
+ operationId: string;
51
+ transaction: ConnectStoreTransaction;
52
+ }): Promise<LocalProfile>;
53
+ restrict(profile: LocalProfile, functionKey: string, resource: unknown): Promise<boolean>;
54
+ }
55
+ export interface ConnectApplicationConfig {
56
+ apiUrl: string;
57
+ sourceId: string;
58
+ appId: string;
59
+ sourceSecret?: string;
60
+ presenter?: {
61
+ id: string;
62
+ secret: string;
63
+ deployment: DeploymentMetadata;
64
+ };
65
+ issuer?: string;
66
+ clientId?: string;
67
+ clientSecret?: string;
68
+ redirectUri?: string;
69
+ appOrigin: string;
70
+ /** Server-only origin for provider HTTP calls; canonical issuer/token validation and browser redirects stay unchanged. */
71
+ oidcTransportOrigin?: string;
72
+ encryptionKey: string;
73
+ store: ConnectApplicationStore;
74
+ accounts: ConnectAccountAdapter;
75
+ catalog: FunctionMatrix;
76
+ /** Explicit opt-in restricted to loopback HTTP. */ allowLoopbackHttp?: boolean;
77
+ sessionTtlSeconds?: number;
78
+ }
79
+ export type SignInResult = {
80
+ status: 'administrative_required';
81
+ reason: 'source_conflict';
82
+ } | {
83
+ status: 'configuration_required';
84
+ appId: string;
85
+ } | {
86
+ status: 'redirect';
87
+ url: string;
88
+ cookies: CookieDirective[];
89
+ } | {
90
+ status: 'migration_required';
91
+ challenge: string;
92
+ consentVersion: string;
93
+ request?: OnboardingRequestStatus;
94
+ cookies: CookieDirective[];
95
+ } | {
96
+ status: 'pending';
97
+ request: OnboardingRequestStatus;
98
+ nextAction: OnboardingNextAction;
99
+ };
100
+ export interface ConnectDiagnosticReport {
101
+ checks: {
102
+ code: 'configuration' | 'discovery' | 'source' | 'authorization';
103
+ status: 'ok' | 'failed' | 'not_checked';
104
+ }[];
105
+ }
106
+ export interface ApplicationSession {
107
+ sessionId: string;
108
+ profile: LocalProfile;
109
+ subject: string;
110
+ expiresAt: number;
111
+ }
112
+ /** Server-only application facade. No provider token appears in a public result. */
113
+ export declare class ConnectApplication {
114
+ private readonly config;
115
+ /** Read-only entry point usable even when construction would reject invalid configuration. */
116
+ static diagnose(config: ConnectApplicationConfig, email?: string): Promise<ConnectDiagnosticReport>;
117
+ readonly source: ConnectOnboardingSource;
118
+ get catalog(): FunctionMatrix;
119
+ private readonly key;
120
+ private jwks?;
121
+ private settings?;
122
+ private plannedAppId?;
123
+ private readonly prefix;
124
+ private readonly ttl;
125
+ constructor(config: ConnectApplicationConfig);
126
+ private validateConfiguration;
127
+ private loadSettings;
128
+ private oidc;
129
+ readonly configuration: {
130
+ sync: () => Promise<{
131
+ plannedAppId?: string | undefined;
132
+ status: "pending" | "configuration_required";
133
+ appId?: undefined;
134
+ } | {
135
+ status: "ready";
136
+ appId: string;
137
+ }>;
138
+ };
139
+ private transaction;
140
+ private cookie;
141
+ private browser;
142
+ private seal;
143
+ private open;
144
+ private put;
145
+ private read;
146
+ private take;
147
+ private client;
148
+ private onboarding;
149
+ private current;
150
+ private verifyAccess;
151
+ private providerUrl;
152
+ private grant;
153
+ private next;
154
+ private begin;
155
+ readonly auth: {
156
+ signIn: (input: {
157
+ email: string;
158
+ password?: string;
159
+ }, ctx: BrowserContext) => Promise<SignInResult>;
160
+ callback: (input: {
161
+ state: string;
162
+ code?: string;
163
+ error?: string;
164
+ iss?: string;
165
+ }, ctx: BrowserContext) => Promise<{
166
+ status: "handoff";
167
+ handoff: string;
168
+ cookies: CookieDirective[];
169
+ }>;
170
+ exchange: (handoff: string, ctx: BrowserContext) => Promise<{
171
+ status: "authenticated";
172
+ session: {
173
+ sessionId: string;
174
+ profile: LocalProfile;
175
+ subject: string;
176
+ expiresAt: number;
177
+ };
178
+ cookies: CookieDirective[];
179
+ }>;
180
+ resolve: (sessionId: string) => Promise<ApplicationSession>;
181
+ refresh: (sessionId: string) => Promise<ApplicationSession>;
182
+ fromCookies: (ctx: BrowserContext) => string;
183
+ logout: (sessionId: string, ctx: BrowserContext) => Promise<{
184
+ revoked: boolean;
185
+ providerRevoked: boolean | null;
186
+ cookies: CookieDirective[];
187
+ }>;
188
+ };
189
+ private resolve;
190
+ private withSession;
191
+ readonly migration: {
192
+ submit: (input: {
193
+ challenge: string;
194
+ legacyPassword: string;
195
+ consentVersion: string;
196
+ idempotencyKey: string;
197
+ newConnectPassword?: string;
198
+ }, ctx: BrowserContext) => Promise<OnboardingRequestStatus>;
199
+ };
200
+ readonly activation: {
201
+ submit: (input: AppOnboardingActivationRequest & {
202
+ consentVersion: string;
203
+ idempotencyKey: string;
204
+ }, ctx: BrowserContext) => Promise<OnboardingRequestStatus>;
205
+ };
206
+ readonly access: {
207
+ authorize: (sessionId: string, functionKey: string, resource?: unknown) => Promise<{
208
+ allowed: boolean;
209
+ reason: string;
210
+ }>;
211
+ };
212
+ /** All existing Connect services share this authenticated server session. No callback is retried. */
213
+ services<T>(sessionId: string, operation: (client: ConnectServer, accessToken: string) => Promise<T>): Promise<T>;
214
+ readonly team: {
215
+ createUser: (sessionId: string, input: ApplicationTeamUserInput) => Promise<ApplicationTeamUserResult>;
216
+ };
217
+ diagnose(email?: string): Promise<ConnectDiagnosticReport>;
218
+ }
@@ -0,0 +1,432 @@
1
+ import { createHash, randomBytes, createCipheriv, createDecipheriv, timingSafeEqual } from 'node:crypto';
2
+ import { createRemoteJWKSet, jwtVerify } from 'jose';
3
+ import { ConnectOnboardingSource, ConnectOnboardingError, ConnectServer, ConnectApiError } from './server.js';
4
+ export { ConnectApiError } from './server.js';
5
+ export * from './application-store.js';
6
+ export const connectConsentVersion = '2026-10-21-mandatory-v1';
7
+ export class ConnectApplicationError extends Error {
8
+ code;
9
+ callbackStage;
10
+ authorizationDetail;
11
+ constructor(code) {
12
+ super(code);
13
+ this.code = code;
14
+ this.name = 'ConnectApplicationError';
15
+ }
16
+ }
17
+ const opaque = () => randomBytes(32).toString('base64url');
18
+ const digest = (v) => createHash('sha256').update(v).digest('base64url');
19
+ const same = (a, b) => { const x = Buffer.from(a), y = Buffer.from(b); return x.length === y.length && timingSafeEqual(x, y); };
20
+ function fail(code) { throw new ConnectApplicationError(code); }
21
+ /** Server-only application facade. No provider token appears in a public result. */
22
+ export class ConnectApplication {
23
+ config;
24
+ /** Read-only entry point usable even when construction would reject invalid configuration. */
25
+ static async diagnose(config, email) {
26
+ try {
27
+ return await new ConnectApplication(config).diagnose(email);
28
+ }
29
+ catch {
30
+ return { checks: [{ code: 'configuration', status: 'failed' }, { code: 'discovery', status: 'not_checked' }, { code: 'source', status: 'not_checked' }, { code: 'authorization', status: 'not_checked' }] };
31
+ }
32
+ }
33
+ source;
34
+ get catalog() { return { ...this.config.catalog, appId: this.settings?.appId || this.plannedAppId || this.config.appId }; }
35
+ key;
36
+ jwks;
37
+ settings;
38
+ plannedAppId;
39
+ prefix;
40
+ ttl;
41
+ constructor(config) {
42
+ this.config = config;
43
+ try {
44
+ for (const value of [config.apiUrl, config.appOrigin, ...(config.oidcTransportOrigin ? [config.oidcTransportOrigin] : []), ...(config.issuer ? [config.issuer] : []), ...(config.redirectUri ? [config.redirectUri] : [])]) {
45
+ const u = new URL(value);
46
+ if (u.username || u.password || u.hash || !(u.protocol === 'https:' || (config.allowLoopbackHttp && u.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(u.hostname))))
47
+ fail('invalid_configuration');
48
+ }
49
+ 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))
50
+ fail('invalid_configuration');
51
+ if (config.oidcTransportOrigin) {
52
+ const transport = new URL(config.oidcTransportOrigin);
53
+ if (transport.pathname !== '/' || transport.search)
54
+ fail('invalid_configuration');
55
+ }
56
+ this.ttl = config.sessionTtlSeconds ?? 28800;
57
+ if (this.ttl < 60 || this.ttl > 604800)
58
+ fail('invalid_configuration');
59
+ }
60
+ catch {
61
+ fail('invalid_configuration');
62
+ }
63
+ this.key = Buffer.from(config.encryptionKey, 'hex');
64
+ this.prefix = (new URL(config.appOrigin).protocol === 'https:' ? '__Host-' : '') + 'connect_' + digest(config.sourceId + ':' + config.appId).slice(0, 12);
65
+ 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 });
66
+ if (config.issuer && config.clientId && config.redirectUri)
67
+ this.settings = { sourceId: config.sourceId, appId: config.appId, issuer: config.issuer, clientId: config.clientId, redirectUri: config.redirectUri, clientSecret: config.clientSecret };
68
+ }
69
+ validateConfiguration(c) {
70
+ try {
71
+ 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)
72
+ fail('invalid_configuration');
73
+ for (const value of [c.issuer, c.redirectUri]) {
74
+ const u = new URL(value);
75
+ 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))))
76
+ fail('invalid_configuration');
77
+ }
78
+ }
79
+ catch {
80
+ fail('invalid_configuration');
81
+ }
82
+ }
83
+ async loadSettings() {
84
+ if (!this.settings) {
85
+ const stored = await this.transaction('configuration', tx => this.read(tx, 'configuration'));
86
+ if (stored) {
87
+ this.validateConfiguration(stored);
88
+ this.settings = stored;
89
+ }
90
+ }
91
+ return this.settings;
92
+ }
93
+ async oidc() { const settings = await this.loadSettings(); if (!settings)
94
+ fail('invalid_configuration'); return settings; }
95
+ configuration = { sync: async () => {
96
+ const result = await this.onboarding(() => this.source.configuration());
97
+ if (result.status !== 'ready') {
98
+ this.plannedAppId = undefined;
99
+ if (result.plannedAppId) {
100
+ if (!/^[a-z][a-z0-9_.:-]{0,79}$/.test(result.plannedAppId))
101
+ fail('invalid_configuration');
102
+ this.plannedAppId = result.plannedAppId;
103
+ }
104
+ return { status: result.status, ...(result.plannedAppId ? { plannedAppId: result.plannedAppId } : {}) };
105
+ }
106
+ this.validateConfiguration(result.configuration);
107
+ await this.transaction('configuration', tx => this.put(tx, 'configuration', result.configuration, 365 * 86400));
108
+ this.settings = result.configuration;
109
+ this.jwks = undefined;
110
+ return { status: 'ready', appId: result.configuration.appId };
111
+ } };
112
+ async transaction(key, fn) { try {
113
+ return await this.config.store.transaction(key, fn);
114
+ }
115
+ catch (e) {
116
+ if (e instanceof ConnectApplicationError)
117
+ throw e;
118
+ return fail('provider_unavailable');
119
+ } }
120
+ cookie(name, value, maxAge) { return { name: this.prefix + '_' + name, value, httpOnly: true, secure: new URL(this.config.appOrigin).protocol === 'https:', sameSite: 'lax', path: '/', maxAge }; }
121
+ browser(ctx) { if (ctx.origin !== this.config.appOrigin)
122
+ fail('invalid_context'); }
123
+ 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'); }
124
+ open(id, value) { try {
125
+ const bytes = Buffer.from(value, 'base64url'), dec = createDecipheriv('aes-256-gcm', this.key, bytes.subarray(0, 12));
126
+ dec.setAAD(Buffer.from(this.config.sourceId + ':' + this.config.appId + ':' + id));
127
+ dec.setAuthTag(bytes.subarray(12, 28));
128
+ return JSON.parse(Buffer.concat([dec.update(bytes.subarray(28)), dec.final()]).toString());
129
+ }
130
+ catch {
131
+ return fail('invalid_flow');
132
+ } }
133
+ async put(tx, id, value, ttlSeconds) { await tx.put(id, this.seal(id, value), Date.now() + ttlSeconds * 1000); }
134
+ async read(tx, id) { const cipher = await tx.get(id); return cipher ? this.open(id, cipher) : null; }
135
+ async take(id) { return this.transaction(id, async (tx) => { const value = await this.read(tx, id); await tx.remove(id); return value; }); }
136
+ client(context) { return new ConnectServer({ apiUrl: this.config.apiUrl, installationId: context.binding.installationId, secret: context.binding.secret, requestTimeoutMs: 10000 }); }
137
+ async onboarding(operation) { try {
138
+ return await operation();
139
+ }
140
+ catch (e) {
141
+ if (e instanceof ConnectOnboardingError)
142
+ fail(e.status === 409 ? 'invalid_context' : e.status >= 500 || e.status === 429 || e.status === 0 ? 'provider_unavailable' : 'access_denied');
143
+ return fail('provider_unavailable');
144
+ } }
145
+ async current(email, expected) {
146
+ const found = await this.onboarding(() => this.source.loginContext(email));
147
+ if (found.status !== 'connect' && found.status !== 'configuration_required')
148
+ return fail('access_denied');
149
+ const a = found.context, b = expected;
150
+ 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)
151
+ fail('invalid_context');
152
+ return a;
153
+ }
154
+ async verifyAccess(context, token) {
155
+ let a;
156
+ try {
157
+ a = await this.client(context).permissions(token);
158
+ }
159
+ catch (cause) {
160
+ const status = cause instanceof ConnectApiError ? String(cause.status) : cause instanceof Error ? cause.message.match(/^Connect (\d{3}):/)?.[1] : undefined;
161
+ const error = new ConnectApplicationError(!status || status === '429' || Number(status) >= 500 ? 'provider_unavailable' : 'access_denied');
162
+ error.authorizationDetail = status === '401' ? 'http_401' : status === '403' ? 'http_403' : status ? 'http_other' : 'transport';
163
+ throw error;
164
+ }
165
+ 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;
166
+ if (detail) {
167
+ const error = new ConnectApplicationError('access_denied');
168
+ error.authorizationDetail = detail;
169
+ throw error;
170
+ }
171
+ return a;
172
+ }
173
+ providerUrl(issuer, path) {
174
+ const canonical = new URL(issuer + path);
175
+ return this.config.oidcTransportOrigin ? new URL(canonical.pathname + canonical.search, this.config.oidcTransportOrigin).href : canonical.href;
176
+ }
177
+ async grant(params) {
178
+ try {
179
+ const sso = await this.oidc();
180
+ 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) });
181
+ if (!r.ok)
182
+ fail(r.status >= 500 ? 'provider_unavailable' : 'access_denied');
183
+ const t = await r.json();
184
+ 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)
185
+ fail('access_denied');
186
+ return { ...t, expiresAt: Date.now() + t.expires_in * 1000 };
187
+ }
188
+ catch (e) {
189
+ if (e instanceof ConnectApplicationError)
190
+ throw e;
191
+ return fail('provider_unavailable');
192
+ }
193
+ }
194
+ next(request) { return request.nextAction ?? (['pending', 'approved', 'migrating'].includes(request.state) ? 'wait' : request.state === 'completed' ? 'sign_in' : 'contact_admin'); }
195
+ async begin(context, email) {
196
+ const sso = await this.oidc();
197
+ const state = opaque(), browser = opaque(), nonce = opaque(), verifier = opaque();
198
+ await this.transaction('flow:' + digest(state), tx => this.put(tx, 'flow:' + digest(state), { context, email, verifier, nonce, browserHash: digest(browser) }, 600));
199
+ const u = new URL(sso.issuer + '/protocol/openid-connect/auth');
200
+ 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 }))
201
+ u.searchParams.set(k, v);
202
+ return { status: 'redirect', url: u.href, cookies: [this.cookie('flow', browser, 600)] };
203
+ }
204
+ auth = {
205
+ signIn: async (input, ctx) => {
206
+ this.browser(ctx);
207
+ let found;
208
+ try {
209
+ found = await this.onboarding(() => this.source.loginContext(input.email));
210
+ }
211
+ catch (e) {
212
+ if (e instanceof ConnectApplicationError && e.code === 'invalid_context')
213
+ return { status: 'administrative_required', reason: 'source_conflict' };
214
+ throw e;
215
+ }
216
+ if (found.status === 'connect' || found.status === 'configuration_required') {
217
+ if (!await this.loadSettings())
218
+ return { status: 'configuration_required', appId: found.status === 'configuration_required' ? found.appId : this.config.appId };
219
+ return this.begin(found.context, input.email);
220
+ }
221
+ const next = found.request ? this.next(found.request) : undefined;
222
+ if (found.request && next !== 'resubmit' && next !== 'choose_connect_password')
223
+ return { status: 'pending', request: found.request, nextAction: next };
224
+ if (!input.password)
225
+ fail('invalid_credentials');
226
+ const legacy = await this.config.accounts.verifyLegacy({ email: input.email, password: input.password });
227
+ if (!legacy)
228
+ fail('invalid_credentials');
229
+ const challenge = opaque();
230
+ await this.transaction('challenge:' + digest(challenge), tx => this.put(tx, 'challenge:' + digest(challenge), { legacy, email: input.email, request: found.request, browserHash: digest(challenge) }, 120));
231
+ return { status: 'migration_required', challenge, consentVersion: connectConsentVersion, cookies: [this.cookie('challenge', challenge, 120)], ...(found.request ? { request: found.request } : {}) };
232
+ },
233
+ callback: async (input, ctx) => {
234
+ let stage = 'flow';
235
+ try {
236
+ this.browser(ctx);
237
+ const sso = await this.oidc();
238
+ const id = 'flow:' + digest(input.state), flow = await this.take(id);
239
+ if (!flow || !same(flow.browserHash, digest(ctx.cookies[this.prefix + '_flow'] ?? '')) || input.error || !input.code || (input.iss && input.iss !== sso.issuer))
240
+ return fail('invalid_flow');
241
+ stage = 'token_exchange';
242
+ const tokens = await this.grant({ grant_type: 'authorization_code', code: input.code, redirect_uri: sso.redirectUri, code_verifier: flow.verifier });
243
+ stage = 'id_token';
244
+ try {
245
+ if (!tokens.id_token)
246
+ fail('access_denied');
247
+ 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'] });
248
+ if (payload.sub !== flow.context.user.subject || payload.nonce !== flow.nonce || (payload.azp && payload.azp !== sso.clientId))
249
+ fail('invalid_context');
250
+ }
251
+ catch {
252
+ return fail('access_denied');
253
+ }
254
+ stage = 'context';
255
+ const context = await this.current(flow.email, flow.context);
256
+ stage = 'authorization';
257
+ await this.verifyAccess(context, tokens.access_token);
258
+ stage = 'handoff';
259
+ const handoff = opaque(), browser = opaque();
260
+ await this.transaction('handoff:' + digest(handoff), tx => this.put(tx, 'handoff:' + digest(handoff), { context, email: flow.email, tokens, browserHash: digest(browser) }, 60));
261
+ return { status: 'handoff', handoff, cookies: [this.cookie('flow', '', 0), this.cookie('handoff', browser, 60)] };
262
+ }
263
+ catch (error) {
264
+ if (error instanceof ConnectApplicationError)
265
+ error.callbackStage = stage;
266
+ throw error;
267
+ }
268
+ },
269
+ exchange: async (handoff, ctx) => {
270
+ this.browser(ctx);
271
+ const id = 'handoff:' + digest(handoff);
272
+ return this.transaction(id, async (tx) => {
273
+ const flow = await this.read(tx, id);
274
+ if (!flow || !same(flow.browserHash, digest(ctx.cookies[this.prefix + '_handoff'] ?? '')))
275
+ return fail('invalid_flow');
276
+ const context = await this.current(flow.email, flow.context);
277
+ await this.verifyAccess(context, flow.tokens.access_token);
278
+ const profile = await this.config.accounts.provision(context, { operationId: id, transaction: tx });
279
+ if (profile.localUserId !== context.user.id || profile.localTenantId !== context.tenant.id)
280
+ fail('provision_conflict');
281
+ const sessionId = opaque(), expiry = Date.now() + this.ttl * 1000;
282
+ await this.put(tx, 'session:' + digest(sessionId), { context, email: flow.email, tokens: flow.tokens, profile, expiresAt: expiry, refreshedAt: 0, generation: opaque() }, this.ttl);
283
+ await tx.remove(id);
284
+ return { status: 'authenticated', session: { sessionId, profile, subject: context.user.subject, expiresAt: expiry }, cookies: [this.cookie('handoff', '', 0), this.cookie('session', sessionId, this.ttl)] };
285
+ });
286
+ },
287
+ resolve: async (sessionId) => this.resolve(sessionId, false),
288
+ refresh: async (sessionId) => this.resolve(sessionId, true),
289
+ fromCookies: (ctx) => { this.browser(ctx); return ctx.cookies[this.prefix + '_session'] ?? ''; },
290
+ logout: async (sessionId, ctx) => {
291
+ this.browser(ctx);
292
+ const id = 'session:' + digest(sessionId);
293
+ const session = await this.take(id);
294
+ let providerRevoked = null;
295
+ if (session) {
296
+ try {
297
+ const sso = await this.oidc();
298
+ 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) });
299
+ providerRevoked = r.ok;
300
+ }
301
+ catch {
302
+ providerRevoked = false;
303
+ }
304
+ }
305
+ return { revoked: true, providerRevoked, cookies: [this.cookie('session', '', 0)] };
306
+ }
307
+ };
308
+ async resolve(sessionId, force) {
309
+ const result = await this.withSession(sessionId, force, async (s) => ({ sessionId, profile: s.profile, subject: s.context.user.subject, expiresAt: s.expiresAt }));
310
+ return result;
311
+ }
312
+ async withSession(sessionId, force, fn) {
313
+ const id = 'session:' + digest(sessionId);
314
+ const result = await this.transaction(id, async (tx) => {
315
+ const s = await this.read(tx, id);
316
+ if (!s || s.expiresAt <= Date.now())
317
+ return { error: 'session_expired' };
318
+ let rotatingGrantStarted = false;
319
+ try {
320
+ const intentId = 'refresh:' + digest(sessionId + ':' + s.generation);
321
+ const interrupted = await tx.get(intentId);
322
+ if (interrupted)
323
+ fail('session_expired');
324
+ s.context = await this.current(s.email, s.context);
325
+ // A shared persisted timestamp also deduplicates callers queued on another process.
326
+ if (s.tokens.expiresAt <= Date.now() + 30000 || (force && s.refreshedAt < Date.now() - 5000)) {
327
+ // Commit a tombstone BEFORE a rotating grant: on an ambiguous response/crash the old token is never replayed.
328
+ // The intent survives a crash/rollback and is checked on every session use.
329
+ await this.put(tx, intentId, { pending: true }, this.ttl);
330
+ await tx.checkpoint();
331
+ rotatingGrantStarted = true;
332
+ s.tokens = await this.grant({ grant_type: 'refresh_token', refresh_token: s.tokens.refresh_token });
333
+ s.refreshedAt = Date.now();
334
+ s.generation = opaque();
335
+ // The new generation supersedes the durable intent only on commit.
336
+ }
337
+ await this.verifyAccess(s.context, s.tokens.access_token);
338
+ }
339
+ catch (e) {
340
+ // Deny this request without destroying a valid session for a transient read failure.
341
+ // After a rotating grant starts, retain the existing fail-closed invalidation.
342
+ if (!(e instanceof ConnectApplicationError && e.code === 'provider_unavailable' && !rotatingGrantStarted))
343
+ await tx.remove(id);
344
+ return { error: e instanceof ConnectApplicationError ? e.code : 'access_denied' };
345
+ }
346
+ try {
347
+ const value = await fn(s);
348
+ await tx.put(id, this.seal(id, s), s.expiresAt);
349
+ return { value };
350
+ }
351
+ catch (error) {
352
+ if (error instanceof ConnectApiError && error.status === 401) {
353
+ await tx.remove(id);
354
+ return { error: 'session_expired' };
355
+ }
356
+ await tx.put(id, this.seal(id, s), s.expiresAt);
357
+ return { operationError: error };
358
+ }
359
+ });
360
+ if ('error' in result)
361
+ return fail(result.error);
362
+ if ('operationError' in result)
363
+ throw result.operationError;
364
+ // Old intents expire with their session; no unsafe cleanup race between processes.
365
+ return result.value;
366
+ }
367
+ migration = {
368
+ submit: async (input, ctx) => {
369
+ this.browser(ctx);
370
+ if (input.consentVersion !== connectConsentVersion)
371
+ fail('invalid_consent');
372
+ const proof = await this.take('challenge:' + digest(input.challenge));
373
+ if (!proof || !same(proof.browserHash, digest(ctx.cookies[this.prefix + '_challenge'] ?? '')))
374
+ fail('invalid_flow');
375
+ const verified = await this.config.accounts.verifyLegacy({ email: proof.email, password: input.legacyPassword });
376
+ if (!verified || JSON.stringify(verified) !== JSON.stringify(proof.legacy))
377
+ fail('invalid_credentials');
378
+ if (proof.request && this.next(proof.request) === 'choose_connect_password') {
379
+ if (!input.newConnectPassword || same(input.newConnectPassword, input.legacyPassword))
380
+ fail('invalid_password');
381
+ 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));
382
+ }
383
+ return this.onboarding(() => this.source.submit({ kind: 'migration', consentVersion: input.consentVersion, ...verified, initialPassword: input.legacyPassword }, input.idempotencyKey));
384
+ }
385
+ };
386
+ activation = { submit: async (input, ctx) => {
387
+ this.browser(ctx);
388
+ if (input.consentVersion !== connectConsentVersion)
389
+ fail('invalid_consent');
390
+ const { idempotencyKey, consentVersion, ...request } = input;
391
+ return this.onboarding(() => this.source.submit(request, idempotencyKey));
392
+ } };
393
+ access = { authorize: async (sessionId, functionKey, resource = null) => this.withSession(sessionId, false, async (s) => {
394
+ if (!this.catalog.functions.some(f => f.key === functionKey))
395
+ return { allowed: false, reason: 'unknown_function' };
396
+ const central = await this.client(s.context).authorize(s.tokens.access_token, functionKey);
397
+ return central.allowed ? { allowed: await this.config.accounts.restrict(s.profile, functionKey, resource), reason: 'local_policy' } : central;
398
+ }) };
399
+ /** All existing Connect services share this authenticated server session. No callback is retried. */
400
+ async services(sessionId, operation) { return this.withSession(sessionId, false, s => operation(this.client(s.context), s.tokens.access_token)); }
401
+ team = { createUser: async (sessionId, input) => this.withSession(sessionId, false, s => {
402
+ const u = input.localUser;
403
+ return this.client(s.context).mirrorApplicationUser(s.tokens.access_token, {
404
+ localUserId: u.localUserId, username: u.username || 'app-' + digest(JSON.stringify([this.config.sourceId, s.context.binding.installationId, u.localUserId])).slice(0, 40), email: u.email, displayName: [u.firstName, u.lastName].join(' '),
405
+ ...(input.initialPassword === undefined ? {} : { initialPassword: input.initialPassword, ...(input.initialPasswordTemporary === undefined ? {} : { initialPasswordTemporary: input.initialPasswordTemporary }) }),
406
+ application: { sourceId: this.config.sourceId, localTenantId: s.context.tenant.id, firstName: u.firstName, lastName: u.lastName, role: u.role, permissions: u.permissions, roleIds: input.roleIds }
407
+ });
408
+ }) };
409
+ async diagnose(email) {
410
+ const checks = [{ code: 'configuration', status: 'ok' }];
411
+ const sso = await this.loadSettings();
412
+ if (!sso)
413
+ checks.push({ code: 'discovery', status: 'not_checked' });
414
+ else
415
+ try {
416
+ const r = await fetch(this.providerUrl(sso.issuer, '/.well-known/openid-configuration'), { redirect: 'error', signal: AbortSignal.timeout(10000) });
417
+ const d = await r.json();
418
+ checks.push({ code: 'discovery', status: r.ok && d.issuer === sso.issuer ? 'ok' : 'failed' });
419
+ }
420
+ catch {
421
+ checks.push({ code: 'discovery', status: 'failed' });
422
+ }
423
+ try {
424
+ const context = await this.source.loginContext(email ?? 'connect-diagnostic@example.invalid');
425
+ checks.push({ code: 'source', status: 'ok' }, { code: 'authorization', status: 'not_checked' });
426
+ }
427
+ catch (e) {
428
+ checks.push({ code: 'source', status: e instanceof ConnectOnboardingError && e.status === 403 ? 'ok' : 'failed' }, { code: 'authorization', status: 'not_checked' });
429
+ }
430
+ return { checks };
431
+ }
432
+ }