Skip to content

Commit e6df9b3

Browse files
authored
refactor: Simplify import statements and streamline function calls across multiple files
1 parent 0298f5c commit e6df9b3

15 files changed

Lines changed: 47 additions & 108 deletions

‎packages/trueforge/src/apis/modelProviders.ts‎

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -69,9 +69,7 @@ function toWireProvider(record: ModelProviderRecord): ConfiguredModelProvider {
6969
export function createModelProvidersRouter<TTransaction>(deps: ModelProvidersRouterDeps<TTransaction>) {
7070
const listHandler: RouteHandler<typeof listModelProvidersRoute> = async c => {
7171
const requestContext = deps.resolveRequestContext(c);
72-
const records = await deps
73-
.resolveModelProviderStore(c)
74-
.listProviders({ tenant_id: requestContext.tenant_id });
72+
const records = await deps.resolveModelProviderStore(c).listProviders({ tenant_id: requestContext.tenant_id });
7573
return c.json({ data: records.map(toWireProvider) }, 200);
7674
};
7775

@@ -110,18 +108,12 @@ export function createModelProvidersRouter<TTransaction>(deps: ModelProvidersRou
110108
// Lock → resolve secret from that snapshot → upsert, all in one txn so concurrent keep
111109
// cannot re-write a secret over a rotate that committed in between.
112110
const record = await deps.withTransaction(async transaction => {
113-
const existing = await store.getProviderForUpdate(
114-
{ tenant_id: requestContext.tenant_id, name },
115-
transaction,
116-
);
111+
const existing = await store.getProviderForUpdate({ tenant_id: requestContext.tenant_id, name }, transaction);
117112
const manifest = resolveModelProviderManifestForWrite({
118113
incoming: provider,
119114
existing: existing?.manifest,
120115
});
121-
return store.upsertProvider(
122-
{ tenant_id: requestContext.tenant_id, name, manifest },
123-
transaction,
124-
);
116+
return store.upsertProvider({ tenant_id: requestContext.tenant_id, name, manifest }, transaction);
125117
});
126118
return c.json({ data: toWireProvider(record) }, 200);
127119
} catch (error) {

‎packages/trueforge/src/apis/schedules.ts‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
*/
44
import { OpenAPIHono, type RouteHandler } from '@hono/zod-openapi';
55
import { InvalidPageTokenError, type Sessions } from '@truefoundry/trueforge-core/agent-session';
6-
import type { ResolveRequestContext, RequestContext } from '../auth/identity';
6+
import type { RequestContext, ResolveRequestContext } from '../auth/identity';
77
import { ScheduleAgentNotFoundError, startScheduleRun } from '../controller/scheduleDispatch';
88
import type { IAgentStore } from '../db/agentStore';
99
import {
@@ -107,10 +107,7 @@ const FORBIDDEN_SCHEDULE_ACCESS = 'Only the schedule creator can access this sch
107107
* Standalone auth stamps `is_admin: true` on the sole identity, which already
108108
* owns everything it created — so admin bypass is a no-op there.
109109
*/
110-
function canAccessSchedule(
111-
requestContext: Pick<RequestContext, 'is_admin' | 'subject'>,
112-
createdBy: string,
113-
): boolean {
110+
function canAccessSchedule(requestContext: Pick<RequestContext, 'is_admin' | 'subject'>, createdBy: string): boolean {
114111
return requestContext.is_admin || requestContext.subject.id === createdBy;
115112
}
116113

‎packages/trueforge/src/apis/sessions.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -275,7 +275,10 @@ function createGetOrCreateSessionByExternalIdHandler(
275275
created_by: requestContext.subject.id,
276276
agent,
277277
});
278-
if (!created && !checkSessionAccess({ subject_id: requestContext.subject.id, createdBy: session.record.created_by })) {
278+
if (
279+
!created &&
280+
!checkSessionAccess({ subject_id: requestContext.subject.id, createdBy: session.record.created_by })
281+
) {
279282
return c.json({ error: { message: FORBIDDEN_SESSION_ACCESS } }, 403);
280283
}
281284
return c.json({ data: toWireSession(session.record) }, created ? 201 : 200);

‎packages/trueforge/src/apis/turns.ts‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -789,9 +789,7 @@ export function createTurnsRouter(deps: TurnsRouterDeps) {
789789
return c.json({ error: { message: `Turn not found: ${turnId}` } }, 404);
790790
}
791791

792-
const turnEventStream = deps.eventSubscriptions.get(
793-
turnStreamId(requestContext.tenant_id, sessionId, turnId),
794-
);
792+
const turnEventStream = deps.eventSubscriptions.get(turnStreamId(requestContext.tenant_id, sessionId, turnId));
795793

796794
// Admission check before SSE headers are sent, so it can still map to HTTP 412.
797795
try {

‎packages/trueforge/src/app.ts‎

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,7 @@ import { createInternalSessionsRouter, createSessionsRouter } from './apis/sessi
2323
import { createSettingsRouter } from './apis/settings';
2424
import { createAvailableSkillsRouter } from './apis/skills';
2525
import { createTurnsRouter } from './apis/turns';
26-
import {
27-
createAdminAuthMiddleware,
28-
createAuthMiddleware,
29-
type Authenticator,
30-
} from './auth/authenticator';
26+
import { createAdminAuthMiddleware, createAuthMiddleware, type Authenticator } from './auth/authenticator';
3127
import { resolveRequestContext } from './auth/identity';
3228
import { StandaloneAuthenticator } from './auth/standaloneAuthenticator';
3329
import type { McpCatalog } from './catalog/McpCatalog';

‎packages/trueforge/src/auth/claims.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -64,8 +64,7 @@ export function toRequestContext(params: {
6464
assertEmailAllowed(claims, config);
6565
const subjectId = resolveUserRef(claims, config);
6666
const role = resolveRole(claims, config);
67-
const displayName =
68-
resolveOptionalStringClaim(claims, config.OIDC_USER_DISPLAY_NAME_CLAIM) ?? subjectId;
67+
const displayName = resolveOptionalStringClaim(claims, config.OIDC_USER_DISPLAY_NAME_CLAIM) ?? subjectId;
6968
return {
7069
tenant_id: 'default',
7170
subject: {
@@ -89,14 +88,15 @@ export interface AuthorizationRequestParams {
8988
* from configured claim names and {@link OIDCConfig.OIDC_SCOPES}.
9089
* `essential: true` on identity claims makes the IdP reject the
9190
* login outright if it can't actually produce that claim.
91+
* Display name is requested via scopes/claims mapping but is not essential —
92+
* {@link toRequestContext} falls back to the subject id when it is absent.
9293
* When an email allowlist is configured, `email` is also marked essential so
9394
* the IdP cannot complete login without a usable address to check.
9495
*/
9596
export function buildAuthorizationRequestParams(config: OIDCConfig): AuthorizationRequestParams {
9697
const idTokenClaims: Record<string, { essential: true }> = {
9798
[config.OIDC_USER_REFERENCE_CLAIM]: { essential: true },
9899
[config.OIDC_USER_ROLE_CLAIM]: { essential: true },
99-
[config.OIDC_USER_DISPLAY_NAME_CLAIM]: { essential: true },
100100
};
101101
if (config.OIDC_ALLOWED_EMAILS.length > 0) {
102102
idTokenClaims['email'] = { essential: true };

‎packages/trueforge/src/auth/oidcAuthenticator.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@ import type { Context } from 'hono';
22
import { HTTPException } from 'hono/http-exception';
33
import { jwtVerify } from 'jose';
44

5-
import { toRequestContext, type IdTokenClaims } from './claims';
65
import type { Authenticator } from './authenticator';
6+
import { toRequestContext, type IdTokenClaims } from './claims';
77
import type { RequestContext } from './identity';
88
import { getOidcVerify } from './oidc';
99
import { extractRequestToken, toBearerAuthorization } from './token';

‎packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.ts‎

Lines changed: 3 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@ const GetSessionResponseSchema = z.object({
3434

3535
export type GetSessionResponse = z.infer<typeof GetSessionResponseSchema>;
3636

37-
3837
const ListResponseSchema = z.union([
3938
z.array(z.unknown()),
4039
z.object({
@@ -162,62 +161,13 @@ export class TrueFoundryServiceFoundryServerClient {
162161

163162
/**
164163
* `GET v1/session` for RequestContext mapping.
165-
* 401/403 propagate; transport / non-auth upstream / parse failures → 502 with `{ cause }`.
164+
* Transport / auth failures follow {@link #getJson}; schema mismatch → 502 with `{ cause }`.
166165
*/
167166
async getSession(accessToken: string): Promise<GetSessionResponse> {
168-
const url = this.#url(SESSION_PATH);
169-
const startedAt = Date.now();
170-
let response: Awaited<ReturnType<typeof undiciFetch>>;
171-
try {
172-
response = await undiciFetch(url, {
173-
method: 'GET',
174-
headers: {
175-
accept: 'application/json',
176-
authorization: `Bearer ${accessToken}`,
177-
},
178-
...(this.#dispatcher ? { dispatcher: this.#dispatcher } : {}),
179-
});
180-
} catch (error) {
181-
this.#logger?.warn('TrueFoundry ServiceFoundry session request failed', {
182-
url: url.href,
183-
durationMs: Date.now() - startedAt,
184-
...extractErrorLogFields(error),
185-
});
186-
throw new HTTPException(502, {
187-
message: 'TrueFoundry ServiceFoundry server request failed',
188-
cause: error,
189-
});
190-
}
191-
this.#logger?.info('TrueFoundry ServiceFoundry session request completed', {
192-
url: url.href,
193-
status: response.status,
194-
durationMs: Date.now() - startedAt,
195-
});
196-
if (response.status === 401 || response.status === 403) {
197-
throw new HTTPException(response.status, {
198-
message: 'TrueFoundry ServiceFoundry server rejected the request',
199-
});
200-
}
201-
if (!response.ok) {
202-
const detail = await readServiceFoundryErrorMessage(response);
203-
throw new HTTPException(502, {
204-
message: `TrueFoundry ServiceFoundry server request failed: ${detail ?? `HTTP ${String(response.status)}`}`,
205-
});
206-
}
207-
208-
let payload: unknown;
209-
try {
210-
payload = await response.json();
211-
} catch (error) {
212-
throw new HTTPException(502, {
213-
message: 'TrueFoundry ServiceFoundry session response was not valid JSON',
214-
cause: error,
215-
});
216-
}
217-
167+
const payload = await this.#getJson(this.#url(SESSION_PATH), accessToken);
218168
const parsed = GetSessionResponseSchema.safeParse(payload);
219169
if (!parsed.success) {
220-
throw new HTTPException(502, {
170+
throw new HTTPException(500, {
221171
message: 'TrueFoundry ServiceFoundry session response was malformed',
222172
cause: parsed.error,
223173
});

‎packages/trueforge/tests/unit/apis/agents.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { createAgentsRouter } from '../../../src/apis/agents';
2+
import { STANDALONE_REQUEST_CONTEXT } from '../../../src/auth/identity';
23
import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';
34
import { SqliteAgentStore } from '../../../src/db/sqlite/agent-store/SqliteAgentStore';
45
import { createSqliteDb } from '../../../src/db/sqlite/client';
@@ -84,6 +85,7 @@ describe('agents router', () => {
8485
skillStore: new SqliteSkillStore(db),
8586
sandboxProviderStore: new SqliteSandboxProviderStore(db),
8687
withTransaction: callback => db.transaction().execute(callback),
88+
resolveRequestContext: () => STANDALONE_REQUEST_CONTEXT,
8789
});
8890
});
8991

‎packages/trueforge/tests/unit/apis/auth.test.ts‎

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ import winston from 'winston';
55
import { createAuthRouter } from '../../../src/apis/auth';
66
import { createAuthMiddleware } from '../../../src/auth/authenticator';
77
import { STANDALONE_REQUEST_CONTEXT } from '../../../src/auth/identity';
8-
import { OidcAuthenticator } from '../../../src/auth/oidcAuthenticator';
98
import { disableOidcAuth, initOidc } from '../../../src/auth/oidc';
9+
import { OidcAuthenticator } from '../../../src/auth/oidcAuthenticator';
1010
import { StandaloneAuthenticator } from '../../../src/auth/standaloneAuthenticator';
1111
import configuration from '../../../src/config';
1212

@@ -230,7 +230,7 @@ describe('auth router (auth enabled)', () => {
230230
expect.arrayContaining(['openid', 'profile', 'email', 'groups']),
231231
);
232232
expect(JSON.parse(authUrl.searchParams.get('claims') ?? '{}')).toEqual({
233-
id_token: { sub: { essential: true }, groups: { essential: true }, name: { essential: true } },
233+
id_token: { sub: { essential: true }, groups: { essential: true } },
234234
});
235235
expect(cookieValue(setCookies(res), STATE_COOKIE)).toBeTruthy();
236236
});
@@ -256,7 +256,7 @@ describe('auth router (auth enabled)', () => {
256256
);
257257
expect(authUrl.searchParams.get('scope')?.split(' ')).not.toContain('groups');
258258
expect(JSON.parse(authUrl.searchParams.get('claims') ?? '{}')).toEqual({
259-
id_token: { sub: { essential: true }, roles: { essential: true }, name: { essential: true } },
259+
id_token: { sub: { essential: true }, roles: { essential: true } },
260260
});
261261
});
262262

@@ -297,7 +297,6 @@ describe('auth router (auth enabled)', () => {
297297
id_token: {
298298
sub: { essential: true },
299299
groups: { essential: true },
300-
name: { essential: true },
301300
email: { essential: true },
302301
},
303302
});
@@ -342,10 +341,9 @@ describe('auth router (auth enabled)', () => {
342341
// No `error` code → this is our own validation failure, so the attacker-supplied
343342
// description must not be reflected; the reason stays generic.
344343
const crafted = 'Your%20account%20is%20compromised%2C%20call%201-800-EVIL';
345-
const res = await createTestAuthRouter({ oidcClient }).request(
346-
`/callback?state=any&error_description=${crafted}`,
347-
{ redirect: 'manual' },
348-
);
344+
const res = await createTestAuthRouter({ oidcClient }).request(`/callback?state=any&error_description=${crafted}`, {
345+
redirect: 'manual',
346+
});
349347
expect(res.status).toBe(302);
350348
expect(res.headers.get('location')).toBe('/?error=login_failed');
351349
});
@@ -380,13 +378,10 @@ describe('auth router (auth enabled)', () => {
380378
}
381379

382380
const token = await createIdToken();
383-
const res = await createTestAuthRouter({ oidcClient: restrictedClient }).request(
384-
'/callback?code=abc&state=spent',
385-
{
386-
redirect: 'manual',
387-
headers: { Cookie: `${ID_TOKEN_COOKIE}=${token}` },
388-
},
389-
);
381+
const res = await createTestAuthRouter({ oidcClient: restrictedClient }).request('/callback?code=abc&state=spent', {
382+
redirect: 'manual',
383+
headers: { Cookie: `${ID_TOKEN_COOKIE}=${token}` },
384+
});
390385
expect(res.status).toBe(302);
391386
expect(res.headers.get('location')).toBe('/?error=login_failed');
392387
expect(

0 commit comments

Comments
 (0)