Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
143 changes: 143 additions & 0 deletions packages/javascript/src/api/account/__tests__/meAgentsApi.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
// Copyright 2026 The ThunderID Authors
// SPDX-License-Identifier: Apache-2.0

import {describe, expect, it, vi, type Mock} from 'vitest';
import ThunderIDAPIError from '../../../errors/ThunderIDAPIError';
import {ApiFetcher} from '../../../models/api';
import deleteMeAgent from '../deleteMeAgent';
import getMeAgent from '../getMeAgent';
import getMeAgents from '../getMeAgents';
import suspendAllMeAgents from '../suspendAllMeAgents';
import suspendMeAgent from '../suspendMeAgent';
import unsuspendMeAgent from '../unsuspendMeAgent';
import updateMeAgent from '../updateMeAgent';

type FetcherMock = Mock<ApiFetcher>;
type Run = (fetcher: ApiFetcher) => Promise<unknown>;

const baseUrl = 'https://localhost:8090';
const agentId = 'agent-1';
const payload = {
attributes: {name: 'Spending assistant'},
grantTypes: ['authorization_code'],
redirectUris: ['https://assistant.example.com/callback'],
};

const respond = (status: number, body: unknown = {}): FetcherMock =>
vi.fn<ApiFetcher>().mockResolvedValue({
json: () => Promise.resolve(body),
ok: status >= 200 && status < 300,
status,
statusText: '',
text: () => Promise.resolve(JSON.stringify(body)),
} as Response);

describe('personal agent self-service API', () => {
it.each<[string, Run, string, string, unknown]>([
[
'getMeAgents',
(fetcher: ApiFetcher) => getMeAgents({baseUrl, fetcher, kind: 'personal-assistant', limit: 5, offset: 10}),
'GET',
`${baseUrl}/users/me/agents?kind=personal-assistant&limit=5&offset=10`,
undefined,
],
[
'getMeAgent',
(fetcher: ApiFetcher) => getMeAgent({agentId, baseUrl, fetcher}),
'GET',
`${baseUrl}/users/me/agents/agent-1?include=display`,
undefined,
],
[
'updateMeAgent',
(fetcher: ApiFetcher) => updateMeAgent({agentId, baseUrl, fetcher, payload}),
'PUT',
`${baseUrl}/users/me/agents/agent-1`,
JSON.stringify(payload),
],
[
'deleteMeAgent',
(fetcher: ApiFetcher) => deleteMeAgent({agentId, baseUrl, fetcher}),
'DELETE',
`${baseUrl}/users/me/agents/agent-1`,
undefined,
],
[
'suspendMeAgent',
(fetcher: ApiFetcher) => suspendMeAgent({agentId, baseUrl, fetcher}),
'POST',
`${baseUrl}/users/me/agents/agent-1/suspend`,
undefined,
],
[
'unsuspendMeAgent',
(fetcher: ApiFetcher) => unsuspendMeAgent({agentId, baseUrl, fetcher}),
'POST',
`${baseUrl}/users/me/agents/agent-1/unsuspend`,
undefined,
],
[
'suspendAllMeAgents',
(fetcher: ApiFetcher) => suspendAllMeAgents({baseUrl, fetcher}),
'POST',
`${baseUrl}/users/me/agents/suspend`,
undefined,
],
])('%s sends %s to the self-service route', async (_name, run, method, url, body) => {
const fetcher: FetcherMock = respond(200);

await run(fetcher);

const [sentUrl, init] = fetcher.mock.calls[0];
expect(sentUrl).toBe(url);
expect(init.method).toBe(method);
expect(init.body).toBe(body);
});

it('lists every agent the user owns when no kind is given', async () => {
const fetcher: FetcherMock = respond(200, {agents: [], count: 0, startIndex: 1, totalResults: 0});

await getMeAgents({baseUrl, fetcher});

expect(fetcher.mock.calls[0][0]).toBe(`${baseUrl}/users/me/agents`);
});

it('honors the collection URL override, including for suspending every agent', async () => {
const url = 'https://rs.example.com/users/me/agents/';
const single: FetcherMock = respond(204);
const all: FetcherMock = respond(200, {suspendedCount: 2});

await suspendMeAgent({agentId, fetcher: single, url});
const result: unknown = await suspendAllMeAgents({fetcher: all, url});

expect(single.mock.calls[0][0]).toBe('https://rs.example.com/users/me/agents/agent-1/suspend');
expect(all.mock.calls[0][0]).toBe('https://rs.example.com/users/me/agents/suspend');
expect(result).toEqual({suspendedCount: 2});
});

it('resolves with nothing when the server answers 204', async () => {
await expect(unsuspendMeAgent({agentId, baseUrl, fetcher: respond(204)})).resolves.toBeUndefined();
});

it.each<[number, string]>([
[403, 'getMeAgent-ForbiddenError-001'],
[404, 'getMeAgent-NotFoundError-001'],
[500, 'getMeAgent-ResponseError-001'],
])('raises a distinct code for HTTP %i', async (status, code) => {
const error: unknown = await getMeAgent({agentId, baseUrl, fetcher: respond(status, {code: 'AGT-1004'})}).catch(
(caught: unknown) => caught,
);

expect(error).toBeInstanceOf(ThunderIDAPIError);
expect((error as ThunderIDAPIError).code).toBe(code);
});

it('refuses an empty agent ID before any request', async () => {
const fetcher: FetcherMock = respond(200);

await expect(deleteMeAgent({agentId: ' ', baseUrl, fetcher})).rejects.toMatchObject({
code: 'deleteMeAgent-ValidationError-002',
});
expect(fetcher).not.toHaveBeenCalled();
});
});
40 changes: 40 additions & 0 deletions packages/javascript/src/api/account/deleteMeAgent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// Copyright 2026 The ThunderID Authors
// SPDX-License-Identifier: Apache-2.0

import {ManagementRequestConfig} from '../../models/api';
import requestManagementResource from '../../utils/requestManagementResource';

/**
* Configuration for the deleteMeAgent request.
*/
export interface DeleteMeAgentConfig extends ManagementRequestConfig {
/**
* Identifier of the personal agent to delete.
*/
agentId: string;
}

/**
* Deletes one of the signed-in user's personal agents.
*
* @param config - Request configuration object.
* @returns A promise that resolves once the agent is deleted.
*
* @example
* ```typescript
* await deleteMeAgent({
* baseUrl: 'https://localhost:8090',
* agentId: '6f1e2d3c-4b5a-4978-8a6b-5c4d3e2f1a0b',
* });
* ```
*/
const deleteMeAgent = async ({agentId, ...config}: DeleteMeAgentConfig): Promise<void> =>
requestManagementResource<void>(config, {
collection: 'users/me/agents',
failureMessage: 'Failed to delete your agent',
id: agentId,
method: 'DELETE',
operation: 'deleteMeAgent',
});

export default deleteMeAgent;
43 changes: 43 additions & 0 deletions packages/javascript/src/api/account/getMeAgent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// Copyright 2026 The ThunderID Authors
// SPDX-License-Identifier: Apache-2.0

import {Agent} from '../../models/agent-resource';
import {ManagementRequestConfig} from '../../models/api';
import requestManagementResource from '../../utils/requestManagementResource';

/**
* Configuration for the getMeAgent request.
*/
export interface GetMeAgentConfig extends ManagementRequestConfig {
/**
* Identifier of the agent to retrieve.
*/
agentId: string;
}

/**
* Retrieves one of the agents the signed-in user owns. Another user's agent, or one outside the
* organization unit the access token names, is not found.
*
* @param config - Request configuration object.
* @returns A promise that resolves with the agent.
*
* @example
* ```typescript
* const agent = await getMeAgent({
* baseUrl: 'https://localhost:8090',
* agentId: '6f1e2d3c-4b5a-4978-8a6b-5c4d3e2f1a0b',
* });
* ```
*/
const getMeAgent = async ({agentId, ...config}: GetMeAgentConfig): Promise<Agent> =>
requestManagementResource<Agent>(config, {
collection: 'users/me/agents',
failureMessage: 'Failed to fetch your agent',
id: agentId,
method: 'GET',
operation: 'getMeAgent',
query: {include: 'display'},
});

export default getMeAgent;
44 changes: 44 additions & 0 deletions packages/javascript/src/api/account/getMeAgents.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Copyright 2026 The ThunderID Authors
// SPDX-License-Identifier: Apache-2.0

import {AgentKind, AgentListResponse} from '../../models/agent-resource';
import {ApiFilteringParams, ManagementRequestConfig} from '../../models/api';
import requestManagementResource from '../../utils/requestManagementResource';

/**
* Configuration for the getMeAgents request.
*/
export type GetMeAgentsConfig = ManagementRequestConfig &
Pick<ApiFilteringParams, 'limit' | 'offset'> & {
/**
* Lists only the agents of this kind. Without it, every agent the signed-in user owns is listed.
*/
kind?: AgentKind;
};

/**
* Retrieves a page of the agents the signed-in user owns, in the organization unit the access token names.
* The token must be the user's own: a delegated token, such as an agent's token for its owner, is refused.
*
* @param config - Request configuration object.
* @returns A promise that resolves with the page of agents.
*
* @example
* ```typescript
* const {agents, totalResults} = await getMeAgents({
* baseUrl: 'https://localhost:8090',
* kind: PERSONAL_AGENT_KIND,
* limit: 10,
* });
* ```
*/
const getMeAgents = async ({kind, limit, offset, ...config}: GetMeAgentsConfig): Promise<AgentListResponse> =>
requestManagementResource<AgentListResponse>(config, {
collection: 'users/me/agents',
failureMessage: 'Failed to fetch your agents',
method: 'GET',
operation: 'getMeAgents',
query: {kind, limit, offset},
});

export default getMeAgents;
37 changes: 37 additions & 0 deletions packages/javascript/src/api/account/suspendAllMeAgents.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Copyright 2026 The ThunderID Authors
// SPDX-License-Identifier: Apache-2.0

import {SuspendAllMeAgentsResponse} from '../../models/agent-resource';
import {ManagementRequestConfig} from '../../models/api';
import requestManagementResource from '../../utils/requestManagementResource';

/**
* Configuration for the suspendAllMeAgents request.
*/
export type SuspendAllMeAgentsConfig = ManagementRequestConfig;

/**
* Suspends every personal agent of the signed-in user that the user has not already suspended, in the
* organization unit the access token names, after the server revokes the tokens issued to each.
*
* @param config - Request configuration object. A `url` is the collection of the user's agents, as for
* {@link getMeAgents}.
* @returns A promise that resolves with how many agents the request suspended.
*
* @example
* ```typescript
* const {suspendedCount} = await suspendAllMeAgents({baseUrl: 'https://localhost:8090'});
* ```
*/
const suspendAllMeAgents = async ({url, ...config}: SuspendAllMeAgentsConfig): Promise<SuspendAllMeAgentsResponse> =>
requestManagementResource<SuspendAllMeAgentsResponse>(
{...config, url: url ? `${url.replace(/\/+$/, '')}/suspend` : undefined},
{
collection: 'users/me/agents/suspend',
failureMessage: 'Failed to suspend your agents',
method: 'POST',
operation: 'suspendAllMeAgents',
},
);

export default suspendAllMeAgents;
42 changes: 42 additions & 0 deletions packages/javascript/src/api/account/suspendMeAgent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Copyright 2026 The ThunderID Authors
// SPDX-License-Identifier: Apache-2.0

import {ManagementRequestConfig} from '../../models/api';
import requestManagementResource from '../../utils/requestManagementResource';

/**
* Configuration for the suspendMeAgent request.
*/
export interface SuspendMeAgentConfig extends ManagementRequestConfig {
/**
* Identifier of the personal agent to suspend.
*/
agentId: string;
}

/**
* Suspends one of the signed-in user's personal agents, after the server revokes the tokens issued to it.
* The owner's suspension is independent of the organization's, and suspending again changes nothing.
*
* @param config - Request configuration object.
* @returns A promise that resolves once the agent is suspended.
*
* @example
* ```typescript
* await suspendMeAgent({
* baseUrl: 'https://localhost:8090',
* agentId: '6f1e2d3c-4b5a-4978-8a6b-5c4d3e2f1a0b',
* });
* ```
*/
const suspendMeAgent = async ({agentId, ...config}: SuspendMeAgentConfig): Promise<void> =>
requestManagementResource<void>(config, {
collection: 'users/me/agents',
failureMessage: 'Failed to suspend your agent',
id: agentId,
method: 'POST',
operation: 'suspendMeAgent',
subPath: 'suspend',
});

export default suspendMeAgent;
42 changes: 42 additions & 0 deletions packages/javascript/src/api/account/unsuspendMeAgent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Copyright 2026 The ThunderID Authors
// SPDX-License-Identifier: Apache-2.0

import {ManagementRequestConfig} from '../../models/api';
import requestManagementResource from '../../utils/requestManagementResource';

/**
* Configuration for the unsuspendMeAgent request.
*/
export interface UnsuspendMeAgentConfig extends ManagementRequestConfig {
/**
* Identifier of the personal agent whose owner's suspension to lift.
*/
agentId: string;
}

/**
* Lifts the suspension the signed-in user placed on one of their personal agents. A suspension by the
* organization stays in force, so the agent stays suspended until an administrator lifts it.
*
* @param config - Request configuration object.
* @returns A promise that resolves once the owner's suspension is lifted.
*
* @example
* ```typescript
* await unsuspendMeAgent({
* baseUrl: 'https://localhost:8090',
* agentId: '6f1e2d3c-4b5a-4978-8a6b-5c4d3e2f1a0b',
* });
* ```
*/
const unsuspendMeAgent = async ({agentId, ...config}: UnsuspendMeAgentConfig): Promise<void> =>
requestManagementResource<void>(config, {
collection: 'users/me/agents',
failureMessage: 'Failed to unsuspend your agent',
id: agentId,
method: 'POST',
operation: 'unsuspendMeAgent',
subPath: 'unsuspend',
});

export default unsuspendMeAgent;
Loading
Loading